text:
Q: How to write a mixed datatype datatable into an EXCEL using OLEDB in c# I have a datatable(obtained from a sql query) with columns of mixed data types that needs to be written into an excel without changing the datatype, here is the code that I have written I took a sample datatable for reference:
    DataTable dtA = new DataTable();

    dtA.Columns.Add("col1", typeof(string));

    dtA.Columns.Add("col2", typeof(decimal));

    dtA.Columns.Add("col3", typeof(DateTime));

    dtA.Columns.Add("col4");

    dtA.Rows.Add("VALUE1", 23.3, "12-06-2021", "VALUE4");

    // Now I am trying to push this datatable into an excel with the same multiple datatypes format:

   OleDbConnection objConn;

   OleDbCommand objCmd;

   OleDbDataAdapter objDatAdap = new OleDbDataAdapter();

   string excelConnectString;

   string reportspath =@"C:\Users\Report.xlsx";

   excelConnectString = (@"Provider=Microsoft.ACE.OLEDB.12.0; Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=NO;IMEX=1""").Replace("{0}", reportspath);

   objConn = new OleDbConnection(excelConnectString);

                try

                {

                    objConn.Open();
                    using (objCmd = new OleDbCommand())
                    {
                        objCmd.Connection = objConn;

                        List<KeyValuePair<string, string>> columnNamesFordtitems = new List<KeyValuePair<string, string>>();
                        foreach (DataColumn dataColumn in dtA.Columns)
                        {
                            columnNamesFordtitems.Add(new KeyValuePair<string, string>(dataColumn.ColumnName, dataColumn.DataType.ToString()));
                        }

                        string table = "test";

                        DataTable dtSheets = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                        bool existsTable = dtSheets.Select().ToList().Exists(sheet => sheet["TABLE_NAME"].ToString() == table);
                        if (existsTable)
                        {
                            objCmd.CommandText = $"DROP TABLE [{table}];";
                            objCmd.ExecuteNonQuery();
                        }

         //this is the original query in case of common datatype

// objCmd.CommandText = $"CREATE TABLE [{table}] ({String.Join(",", columnNamesFor11A.Select(c => $"[{c}] string").ToArray())});";

   //how to do it in case of multiple datatype

   objCmd.CommandText = $"CREATE TABLE [{table}] ({String.Join(",", columnNamesFordtitems.Select(c => $"[{c.Key, (c.Value)}]").ToArray())});";

   objCmd.ExecuteNonQuery();

                        foreach (DataRow row in dtA.Rows)

                        {

                            List<String> rowValues = new List<string>();

                            foreach (DataColumn column in dt.Columns)

                            {

                                rowValues.Add((row[column] != null && row[column] != DBNull.Value) ? row[column].ToString() : String.Empty);

                            }

                            objCmd.CommandText = $"INSERT INTO [{table}]({String.Join(",", columnNamesFordt.Select(c => $"[{c}]"))}) VALUES ({String.Join(",", rowValues.Select(r => $"'{r}'").ToArray())});";

                            objCmd.ExecuteNonQuery();

                        }

Any suggestions or solution would be really helpful for me.
Thanks in advance


text:
Q: If statements with list with python I'm trying to make a simple "note card" if you can even call it that in Python. I've looked around for hours, I just don't see the problem with my code. I'm trying to randomly choose a word from the string, and if the word is chosen, print the definition. The problem is that the phrase "to be" is going with everything in the list, and not only the [0], which is "ser". Here is my code:
import random

word = ["ser","haber","estar","tener", 'hacer']

print(random.choice(word))

for item in word :
    if item == word[0]:
        print("To be")

FIXED CODE
import random

word = ["ser","haber","estar","tener", 'hacer']

choice_word = random.choice(word)
print(choice_word)

if choice_word == word[0]:
        print("To be")

A: Not sure if this is what you want
import random

word = ["ser","haber","estar","tener", 'hacer']

print(random.choice(word))

for item in word :
    print("To be {}".format(item))

A: I'm not sure that I fully understand your question. But from what I understand is that you want to print To Be when the word[0] "ser" comes up. The issue then, is that you're looping through the list every time your check if item == word[0], so every time it'll print To Be because every time you're loop through the 1st item "ser". Try this instead:
import random

word = ["ser","haber","estar","tener", 'hacer']

choice_word = random.choice(word)
print(choice_word)

if choice_word == word[0]:
        print("To be")

A: based on what I understood from question, you don't need to iterate over loop before the if statement. Assign the output of random.choice to a variable and then compare it directly
In [123]: x=random.choice(word)

In [124]: if x== word[0]:
     ...:     print("to be")
     ...:

A: Is this what you are looking for:
import random
word = ["ser","haber","estar","tener", 'hacer']
item = random.choice(word);
print(item)
if item == word[0]:
print("To be")

A: Try this.
import random

word = ["ser","haber","estar","tener", 'hacer']
item = random.choice(word)
if item == word[0]:
    print(item)
    print("To be")

your are not considering your random word

A: It seems that from you description above, you would like to check the randomly chosen word from the list and check it with the current index in the loop. This is how that'd be done.
import random

word = ["ser","haber","estar","tener", 'hacer']

for item in word :
  choice = random.choice(word)
  print(item, choice)
  if item == choice:
      print("To be")

A: Your code prints a randomly selected word from the list and then ignores it for the remainder of the code.
Your for loop does the same thing every time you run the program, which is to print "To be". Why? It checks every word in the list against "ser". The first one will always match, and it will print "To be". In other words, you never used the randomly selected word after you printed it.
At some point, you will wish to print the translation of the randomly chosen word, and you'll learn about dictionaries. Then you can use:
import random
words = {"ser": "To be", "tener": "To have", "saber": "To know"}
spanish_word = random.choice(list(words.keys()))
print(f'En inglés, {spanish_word} is {words[spanish_word]}')

redpajama_set_name: RedPajamaStackExchange


text:
Q: Other Elementary Row Operations? The three elementary row operations are:

*

*Row switching

*Row multiplication

*Row addition

Each of these actions is a, in a sense, a 'do nothing' action on a linear system of equations. They can be applied without affecting the solution to the equation. It follows too, that if each of these actions 'does nothing', repeated application of them also doesn't affect the solution, so all compositions of elementary row operations also 'do nothing'. My question is, can all possible 'do nothing' actions be written as a composition of these elementary row operations?
Furthermore, my understanding is that row switching can be expressed using only Row multiplication (2) and Row addition (3). What would be the smallest list of 'atoms' (i.e. matrices which can't be composed from simpler matricies) to create all do nothing actions? Is Row addition sufficient to create all 'do nothing' matrices, and how could one show that no other 'do nothing' matrices exist?

A: Yes, all "do nothing" operations are compositions of elementary row operations. If two systems are equivalent, then you can use elementary row operations to bring the first system to reduced row-echelon form, and then use more elementary row operations on that reduced row-echelon form to get to the second system, since the inverse of an elementary row operation is also an elementary row operation.


text:
Q: Can't load a 'Mobile' CSS? i currently have this code working on my website:
<script>
if (window.top!=window.self) {
    loadCSSFile("http://www.website.com/css/iframe.css");
} else {
    loadCSSFile("http://www.website.com/css/style.css");
}
</script>

I am looking to fix this as i want to load three files but only if required? hoping you use php or add to the script above, currently this loads normal Css and CSS for Iframe (Facebook Apps) and now i want to style the mobile css, but with one file mobile.css i need to add a file to the above or a php code that handles this?
Cheers!

A: <link rel="stylesheet" media="(max-width: 800px)" href="mobile.css" />

Please don't use JS for this.

A: If you to load a CSS to style for mobile devices you can use the following code. This will detect that the device is a mobile by looking at the screen size and if it matches then it will load the css.
<link media="handheld, only screen and (max-width: 480px), only screen and (max-device-width: 480px)" href="mobile.css" type="text/css" rel="stylesheet" />


text:
Q: Does it mean what I am trying to make it mean? "He asked me why I did it and was dumbstruck for a second."
What I am trying to say is that he was dumbstruck for a second after asking me why I did this. But I see that there is a possibility of people interpreting this sentence as saying that why I did this and was dumbstruck for a second was the question he asked. So, is this a correct sentence and contains the meaning I am intending to have, or is it somehow just inevitably interpreted as the second meaning?
P.S.
Searching around, I found a possible solution to this. Putting a comma seemed to be a good idea.
"He asked me why I did it, and was dumbstruck for a second."
Now, does it mean what I make it mean?

A: The sentence might mean what you intended, but the usage is very strange. Ordinarily, a person is dumbstruck by a specific event, such as a revelation of information, and the reason for being dumbstruck is considered important enough to be mentioned immediately - probably in the same sentence.
Having asked you a question, one would expect that he would not speak until you answered his question, so silence on his part is expected. He might be dumbstruck by your answer, but not before you gave it. So I don't think that "dumbstruck" is an appropriate word under the circumstances.


text:
Q: Queue.Dequeue returns null I have a scenario where

*

*multiple threads are pushing data on a Queue

*only ONE thread is processing data using code below
code -
  while ( Continue )
  {
        while ( queue.Count > 0 )
        {
             MyObj o = queue.Dequeue();
             someProcess(o);
        }
        myAutoResetEvent.WaitOne();
  }

But sometimes, queue.Dequeue() returns null in the scenario above
What gives ?

A: You need to synchronise the access to the queue. Put lock statements around all code sections that access the queue (both reading and writing). If you access the queue simultaneously from multiple threads the internal structures may be corrupted and just about anything can happen.

A: You say:

multiple threads are pushing data on a Queue

The Queue<T>.Enqueue method is not thread-safe. This means that work gets done within the Enqueue method that needs to be synchronized if multiple threads are calling it. A simple example would be updating the Count property. It's a safe bet that somewhere in the Enqueue method there's a line that looks something like this:
++count;

But as we all know, this isn't an atomic operation. It's really more like this (in terms of what's actually happening):
int newCount = count + 1;
count = newCount;

So say the count is currently 5, and Thread 1 gets past int newCount = count + 1... then Thread 1 thinks, "OK, the count is now 5, so I'll make it 6." But the very next operation that gets executed is where Thread 2 gets to int newCount = count + 1 and thinks the same thing as Thread 1 ("the count is now 6"). So two items have just been added to the queue, but the count only went from 5 to 6.
This is just a very basic example of how a non thread-safe method like Queue<T>.Enqueue can get messed up when access is not synchronized. It doesn't specifically explain what's happening in your question; my intention is simply to point out that what you're doing is not thread-safe and will cause unexpected behavior.

A: Guffa is correct, having multiple threads reading and writing to the queue will cause problems, because Queue<T> is not thread safe.
If you're on .NET 4, use the ConcurrentQueue<T> class, which is thread safe. If you're not on .NET 3 or earlier, you can either do your own locking, as Guffa pointed out, or use a 3rd party library.

A: Make sure nothing's pushing null values into the queue.  nulls are allowed as queued values.  Also, according to this document, only Queue<T>'s static members are thread-safe, so beware of doing reading and writing across threads.

A: You need to read this blog post.
Also, here's a very minimal skeleton of a "channel" for communication between threads:
public class Channel<T>
{
    private readonly Queue<T> _queue = new Queue<T>();

    public void Enqueue(T item)
    {
        lock (_queue)
        {
            _queue.Enqueue(item);
            if (_queue.Count == 1)
                Monitor.PulseAll(_queue);
        }
    }

    public T Dequeue()
    {
        lock (_queue)
        {
            while (_queue.Count == 0)
                Monitor.Wait(_queue);

            return _queue.Dequeue();
        }
    }
}

A: Why don't you solve the problem that way?
while (IsRunning)
{
    do
    {
        MyObj myObj = queue.Dequeue();
        if (myObj != null)
        {
            DoSomethingWith(myObj);
        }
    } while (myObj != null);

    myAutoResetEvent.WaitOne();
}

Update
Ok, after reading Earwickers comment and all the other answers, you are all right and i'm just false. So please don't use the code above in multithreaded contexts .

A: If you happen to be using non-generic Queue (not that I advise to use it), you can use Queue.Synchronized method to get a thread-safe wrapper:
Queue queue = Queue.Synchronized(new Queue());

Otherwise you should take care of locking yourself, as others suggest.


text:
Q: Finding different lines between 2 HTML files I want to find the difference between 2 txt files that contain HTML code, tried the difflib module but delta stays 0 no matter what I try.
I need to find how many lines are different from the total HTML code
thanks!
import difflib
count = 0
count2 = 0
delta = 0
f = open('C\html1.txt', 'r')
f2 = open('C\html2.txt', 'r')
for i in f2:
    count2 += 1
for i in f:
    count += 1
diff = difflib.udiff = difflib.unified_diff(
            f.readlines(),
           f2.readlines(),
           fromfile='C\html1.txt',
            tofile='C\html2.txt',
       )
for line in diff:
    delta +=1
print delta

print count
per = (delta * 100) / count

A: The problem is as @wondercricket pointed out that the file pointers are already at EOF.
One way to solve this would be to call
f.seek(0) and f2.seek(0) to move the file pointer to the beginning of file before calculating the diff


text:
Q: Cardinal Inequality without using Choice Let $k$ be an infinite cardinal (i.e. not in bijection with any natural number), show that
$\mathbb{N} \leq 2^{2^k}$
This is very easy with choice, without it I don't even know where to start.

A: HINT:

*

*If $k$ is infinite, then $k$ contains subsets of every finite size.

*Of course, there will be many subsets of $k$ of each finite size.

*Do you see how to identify a given natural number $n$ with a certain family of subsets of $k$?


text:
Q: Check if a local HTML file exists and redirect to it if it does Goal: Check for the existence of a local file with a filename that changes each day (file:///C:/Directory/example-YYYYMMDD.html). If today's file does not yet exist, display a message. If today's file does exist, redirect to it.
Where I'm at so far: What I have below will check for the existence of the file and display a message if it doesn't exist, thanks to an example I found here. But in the event the file does exist, I haven't figured out how to make it redirect.
<!DOCTYPE html>

A: you can use fetch and window.location.href:
if available :

fetch('https://api.github.com ')//redirect url = https://api.github.com
.then(d=>{console.log('redirecting');
  window.location.href = 'https://api.github.com'})
.catch(e=>console.log('do other thing'))

if not available :

fetch('https://notavailable.com ')//redirect url = https://notavailable.com
.then(d=>{console.log('redirecting');
  window.location.href = 'https://notavailable.com'})
.catch(e=>console.log('do other thing'))

A: I read up on resource loading and determined it's an onload that I need to add:
el.onload = function redirect(){window.location = redirectURL;};

Bringing the end result to something like this:

<!DOCTYPE html>


text:
Q: sum on exsl:node-set is bringing back an incorrect value I have written some xsl to create some xml code which is then summed. Here is the code:
              <xsl:variable name ="tmpTotal">
                <root>
                  <xsl:for-each select="key('idxid',$id)//parent::*/transaction/transaction-date[substring(@iso-date,1,4) = $newyear  ]">
                      <xsl:if test="../transaction-type[@code='E']">
                        <item>
                          <xsl:value-of select="number(../value)"/>
                        </item>
                      </xsl:if>

                    </xsl:for-each>
               </root>
            </xsl:variable>

              <xsl:variable name="value" select="sum(exsl:node-set($tmpTotal)/root/item)" />

                All: <xsl:value-of select="exsl:node-set($tmpTotal)/*"/>

                Year: <xsl:value-of select="$newyear"/>

                Value:<xsl:value-of select="$value"/>

The result is as follows:
All: 96363464029561
 Year: 2005
 Value:73837
The list of numbers (From the All: output) are as follows:
9636
3460
29561
The total should be 42657. However, the total from the sum(exsl:node-set($tmpTotal)/root/item) is 73837. If the numbers are correct in the xml, why am I getting an incorrect total?
Thanks in advance for your help.

A: Your calculations are wrong. 9636 + 34640 + 29561 = 73837


text:
Q: Can't fix: 'og:image' error from Sharing Debugger I want share buttons on my webpage, using og meta tags. But Facebook doesn't use any of my og meta tags. So I tried the debugger, which fetched the latest version. But I can't see what's wrong.
these are my tags

<meta property="og:title" content="Vriendinnendag, het gezelligste dagje Sauna"/>
<meta property="og:site_name" content="A-Style beautyfarm, Nieuwegein"/>
<meta property="og:url" content="https://astyle.home.xs4all.nl/beautyfarm/index.html"/>
<meta property="og:description" content="Dagje BEAUTYFARM met je vriendin? A-Style Spa - Nieuwegein (Utrecht) De gezelligste verwendag. De vriendinnendag is een all-in beautyarrangement voor lage prijs. Top Dagje sauna doe je bij A-Style in Nieuwegein"/>
<meta property="og:image" content="https://astyle.home.xs4all.nl/beautyfarm/images/Ingang-A-Style-beautyfarm-sneeuw.jpg"/>
<meta property="fb:app_id" content="166407543414563" />
<meta property="og:type" content="website" />
<meta property="og:locale" content="nl-NL" />

this is the page where I test this all right now
and this is my sharebutton

and this is the warning from the sharing debugger

Inferred Property The 'og:image' property should be explicitly
  provided, even if a value can be inferred from other tags.

A: I found out the issue.
I had to set og:url "to my main page, and that's the spot where it looks for the 'og' elements.
og:url should point to a webpage what contain the OG element


text:
Q: Finding three elements in an array whose sum is closest to a given number Given an array of integers, A1, A2, ..., An, including negatives and positives, and another integer S. Now we need to find three different integers in the array, whose sum is closest to the given integer S. If there exists more than one solution, any of them is ok.
You can assume all the integers are within int32_t range, and no arithmetic overflow will occur with calculating the sum. S is nothing special but a randomly picked number.
Is there any efficient algorithm other than brute force search to find the three integers?

A: John Feminella's solution has a bug.
At the line
if (A[i] + A[j] + A[k] == 0) return (A[i], A[j], A[k])

We need to check if i,j,k are all distinct. Otherwise, if my target element is 6 and if my input array contains {3,2,1,7,9,0,-4,6} . If i print out the tuples that sum to 6, then I would also get 0,0,6 as output . To avoid this, we need to modify the condition in this way.
if ((A[i] + A[j] + A[k] == 0) && (i!=j) && (i!=k) && (j!=k)) return (A[i], A[j], A[k])

A: How about something like this, which is O(n^2)
for(each ele in the sorted array)
{
    ele = arr[i] - YOUR_NUMBER;
    let front be the pointer to the front of the array;
    let rear be the pointer to the rear element of the array.;

    // till front is not greater than rear.
    while(front <= rear)
    {
        if(*front + *rear == ele)
        {
            print "Found triplet "<<*front<<","<<*rear<<","<<ele<<endl;
            break;
        }
        else
        {
            // sum is > ele, so we need to decrease the sum by decrementing rear pointer.
            if((*front + *rear) > ele)
                decrement rear pointer.
            // sum is < ele, so we need to increase the sum by incrementing the front pointer.
            else
                increment front pointer.
        }
    }

This finds if sum of 3 elements is exactly equal to your number. If you want closest, you can modify it to remember the smallest delta(difference between your number of current triplet) and at the end print the triplet corresponding to smallest delta.

A: Note that we have a sorted array. This solution is similar to John's solution only that it looks for the sum and does not repeat the same element.
#include <stdio.h>;

int checkForSum (int arr[], int len, int sum) { //arr is sorted
    int i;
    for (i = 0; i < len ; i++) {
        int left = i + 1;
        int right = len - 1;
        while (right > left) {
            printf ("values are %d %d %d\n", arr[i], arr[left], arr[right]);
            if (arr[right] + arr[left] + arr[i] - sum == 0) {
                printf ("final values are %d %d %d\n", arr[i], arr[left], arr[right]);
                return 1;
            }
            if (arr[right] + arr[left] + arr[i] - sum > 0)
                right--;
            else
                left++;
        }
    }
    return -1;
}
int main (int argc, char **argv) {
    int arr[] = {-99, -45, -6, -5, 0, 9, 12, 16, 21, 29};
    int sum = 4;
    printf ("check for sum %d in arr is %d\n", sum, checkForSum(arr, 10, sum));
}

A: Here is the C++ code:
bool FindSumZero(int a[], int n, int& x, int& y, int& z)
{
    if (n < 3)
        return false;

    sort(a, a+n);

    for (int i = 0; i < n-2; ++i)
    {
        int j = i+1;
        int k = n-1;

        while (k >= j)
        {
            int s = a[i]+a[j]+a[k];

            if (s == 0 && i != j && j != k && k != i)
            {
                x = a[i], y = a[j], z = a[k];
                return true;
            }

            if (s > 0)
                --k;
            else
                ++j;
        }
    }

    return false;
}

A: certainly this is a better solution because it's easier to read and therefore less prone to errors. The only problem is, we need to add a few lines of code to avoid multiple selection of one element.
Another O(n^2) solution (by using a hashset).
// K is the sum that we are looking for
for i 1..n
    int s1 = K - A[i]
    for j 1..i
        int s2 = s1 - A[j]
        if (set.contains(s2))
            print the numbers
    set.add(A[i])

A: Very simple N^2*logN solution: sort the input array, then go through all pairs Ai, Aj (N^2 time), and for each pair check whether (S - Ai - Aj) is in array (logN time).
Another O(S*N) solution uses classical dynamic programming approach.
In short:
Create an 2-d array V[4][S + 1]. Fill it in such a way, that:
V[0][0] = 1, V[0][x] = 0;
V1[Ai]= 1 for any i, V1[x] = 0 for all other x
V[2][Ai + Aj]= 1, for any i, j. V[2][x] = 0 for all other x
V[3][sum of any 3 elements] = 1.
To fill it, iterate through Ai, for each Ai iterate through the array from right to left.

A:
Is there any efficient algorithm other than brute force search to find the three integers?

Yep; we can solve this in O(n2) time! First, consider that your problem P can be phrased equivalently in a slightly different way that eliminates the need for a "target value":

original problem P: Given an array A of n integers and a target value S, does there exist a 3-tuple from A that sums to S?
modified problem P': Given an array A of n integers, does there exist a 3-tuple from A that sums to zero?

Notice that you can go from this version of the problem P' from P by subtracting your S/3 from each element in A, but now you don't need the target value anymore.
Clearly, if we simply test all possible 3-tuples, we'd solve the problem in O(n3) -- that's the brute-force baseline. Is it possible to do better? What if we pick the tuples in a somewhat smarter way?
First, we invest some time to sort the array, which costs us an initial penalty of O(n log n). Now we execute this algorithm:
for (i in 1..n-2) {
  j = i+1  // Start right after i.
  k = n    // Start at the end of the array.

  while (k >= j) {
    // We got a match! All done.
    if (A[i] + A[j] + A[k] == 0) return (A[i], A[j], A[k])

    // We didn't match. Let's try to get a little closer:
    //   If the sum was too big, decrement k.
    //   If the sum was too small, increment j.
    (A[i] + A[j] + A[k] > 0) ? k-- : j++
  }
  // When the while-loop finishes, j and k have passed each other and there's
  // no more useful combinations that we can try with this i.
}

This algorithm works by placing three pointers, i, j, and k at various points in the array. i starts off at the beginning and slowly works its way to the end. k points to the very last element. j points to where i has started at. We iteratively try to sum the elements at their respective indices, and each time one of the following happens:

*

*The sum is exactly right! We've found the answer.

*The sum was too small. Move j closer to the end to select the next biggest number.

*The sum was too big. Move k closer to the beginning to select the next smallest number.

For each i, the pointers of j and k will gradually get closer to each other. Eventually they will pass each other, and at that point we don't need to try anything else for that i, since we'd be summing the same elements, just in a different order. After that point, we try the next i and repeat.
Eventually, we'll either exhaust the useful possibilities, or we'll find the solution. You can see that this is O(n2) since we execute the outer loop O(n) times and we execute the inner loop O(n) times. It's possible to do this sub-quadratically if you get really fancy, by representing each integer as a bit vector and performing a fast Fourier transform, but that's beyond the scope of this answer.

Note: Because this is an interview question, I've cheated a little bit here: this algorithm allows the selection of the same element multiple times. That is, (-1, -1, 2) would be a valid solution, as would (0, 0, 0). It also finds only the exact answers, not the closest answer, as the title mentions. As an exercise to the reader, I'll let you figure out how to make it work with distinct elements only (but it's a very simple change) and exact answers (which is also a simple change).

A: This can be solved efficiently in O(n log (n)) as following.
I am giving solution which tells if sum  of any three numbers equal a given number.
import java.util.*;
public class MainClass {
        public static void main(String[] args) {
        int[] a = {-1, 0, 1, 2, 3, 5, -4, 6};
        System.out.println(((Object) isThreeSumEqualsTarget(a, 11)).toString());
}

public static boolean isThreeSumEqualsTarget(int[] array, int targetNumber) {

    //O(n log (n))
    Arrays.sort(array);
    System.out.println(Arrays.toString(array));

    int leftIndex = 0;
    int rightIndex = array.length - 1;

    //O(n)
    while (leftIndex + 1 < rightIndex - 1) {
        //take sum of two corners
        int sum = array[leftIndex] + array[rightIndex];
        //find if the number matches exactly. Or get the closest match.
        //here i am not storing closest matches. You can do it for yourself.
        //O(log (n)) complexity
        int binarySearchClosestIndex = binarySearch(leftIndex + 1, rightIndex - 1, targetNumber - sum, array);
        //if exact match is found, we already got the answer
        if (-1 == binarySearchClosestIndex) {
            System.out.println(("combo is " + array[leftIndex] + ", " + array[rightIndex] + ", " + (targetNumber - sum)));
            return true;
        }
        //if exact match is not found, we have to decide which pointer, left or right to move inwards
        //we are here means , either we are on left end or on right end
        else {

            //we ended up searching towards start of array,i.e. we need a lesser sum , lets move inwards from right
            //we need to have a lower sum, lets decrease right index
            if (binarySearchClosestIndex == leftIndex + 1) {
                rightIndex--;
            } else if (binarySearchClosestIndex == rightIndex - 1) {
                //we need to have a higher sum, lets decrease right index
                leftIndex++;
            }
        }
    }
    return false;
}

public static int binarySearch(int start, int end, int elem, int[] array) {
    int mid = 0;
    while (start <= end) {
        mid = (start + end) >>> 1;
        if (elem < array[mid]) {
            end = mid - 1;
        } else if (elem > array[mid]) {
            start = mid + 1;
        } else {
            //exact match case
            //Suits more for this particular case to return -1
            return -1;
        }
    }
    return mid;
}
}

A: Reduction : I think @John Feminella solution O(n2) is most elegant. We can still reduce the A[n] in which to search for tuple. By observing A[k] such that all elements would be in A[0] - A[k], when our search array is huge and SUM (s) really small.
A[0] is minimum :- Ascending sorted array.
s = 2A[0] + A[k] : Given s and A[] we can find A[k] using binary search in log(n) time.

A: Here is the program in java which is O(N^2)
import java.util.Stack;

public class GetTripletPair {

    /** Set a value for target sum */
    public static final int TARGET_SUM = 32;

    private Stack<Integer> stack = new Stack<Integer>();

    /** Store the sum of current elements stored in stack */
    private int sumInStack = 0;
    private int count =0 ;

    public void populateSubset(int[] data, int fromIndex, int endIndex) {

        /*
        * Check if sum of elements stored in Stack is equal to the expected
        * target sum.
        *
        * If so, call print method to print the candidate satisfied result.
        */
        if (sumInStack == TARGET_SUM) {
            print(stack);
        }

        for (int currentIndex = fromIndex; currentIndex < endIndex; currentIndex++) {

            if (sumInStack + data[currentIndex] <= TARGET_SUM) {
                ++count;
                stack.push(data[currentIndex]);
                sumInStack += data[currentIndex];

                /*
                * Make the currentIndex +1, and then use recursion to proceed
                * further.
                */
                populateSubset(data, currentIndex + 1, endIndex);
                --count;
                sumInStack -= (Integer) stack.pop();
            }else{
            return;
        }
        }
    }

    /**
    * Print satisfied result. i.e. 15 = 4+6+5
    */

    private void print(Stack<Integer> stack) {
        StringBuilder sb = new StringBuilder();
        sb.append(TARGET_SUM).append(" = ");
        for (Integer i : stack) {
            sb.append(i).append("+");
        }
        System.out.println(sb.deleteCharAt(sb.length() - 1).toString());
    }

    private static final int[] DATA = {4,13,14,15,17};

    public static void main(String[] args) {
        GetAllSubsetByStack get = new GetAllSubsetByStack();
        get.populateSubset(DATA, 0, DATA.length);
    }
}

A: The problem can be solved in O(n^2) by extending the 2-sum problem with minor modifications.A is the vector containing elements and B is the required sum.
int Solution::threeSumClosest(vector &A, int B) {
sort(A.begin(),A.end());

int k=0,i,j,closest,val;int diff=INT_MAX;

while(k<A.size()-2)
{
    i=k+1;
    j=A.size()-1;

    while(i<j)
    {
        val=A[i]+A[j]+A[k];
        if(val==B) return B;
        if(abs(B-val)<diff)
        {
            diff=abs(B-val);
            closest=val;
        }
        if(B>val)
        ++i;
        if(B<val)
        --j;
    }
    ++k;

}
return closest;

A: Here is the Python3 code
class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        result = set()
        nums.sort()
        L = len(nums)
        for i in range(L):
            if i > 0 and nums[i] == nums[i-1]:
                continue
            for j in range(i+1,L):
                if j > i + 1 and nums[j] == nums[j-1]:
                    continue
                l = j+1
                r = L -1
                while l <= r:
                    sum = nums[i] + nums[j] + nums[l]
                    result.add(sum)
                    l = l + 1
                    while l<=r and nums[l] == nums[l-1]:
                        l = l + 1
        result = list(result)
        min = result[0]
        for i in range(1,len(result)):
            if abs(target - result[i]) < abs(target - min):
                min = result[i]
        return min

A: I did this in n^3, my pseudocode is below;
//Create a hashMap with key as Integer and value as ArrayList
//iterate through list using a for loop, for each value in list iterate again starting from next value;
for (int i=0; i<=arr.length-1 ; i++){
    for (int j=i+1; j<=arr.length-1;j++){

//if the sum of arr[i] and arr[j] is less than desired sum then there is potential to find a third digit so do another for loop
      if (arr[i]+arr[j] < sum){
        for (int k= j+1; k<=arr.length-1;k++)

//in this case we are now looking for the third value; if the sum of
arr[i] and arr[j] and arr[k] is the desired sum then add these to the HashMap by making the arr[i] the key and then adding arr[j] and arr[k] into the ArrayList in the value of that key
          if (arr[i]+arr[j]+arr[k] ==  sum){
              map.put(arr[i],new ArrayList<Integer>());
              map.get(arr[i]).add(arr[j]);
              map.get(arr[i]).add(arr[k]);}

after this you now have a dictionary that has all the entries representing the three values adding to the desired sum. Extract all these entries using HashMap functions. This worked perfectly.

A: Another solution that checks and fails early:
public boolean solution(int[] input) {
        int length = input.length;

        if (length < 3) {
            return false;
        }

        // x + y + z = 0  => -z = x + y
        final Set<Integer> z = new HashSet<>(length);
        int zeroCounter = 0, sum; // if they're more than 3 zeros we're done

        for (int element : input) {
            if (element < 0) {
                z.add(element);
            }

            if (element == 0) {
                ++zeroCounter;
                if (zeroCounter >= 3) {
                    return true;
                }
            }
        }

        if (z.isEmpty() || z.size() == length || (z.size() + zeroCounter == length)) {
            return false;
        } else {
            for (int x = 0; x < length; ++x) {
                for (int y = x + 1; y < length; ++y) {
                    sum = input[x] + input[y]; // will use it as inverse addition
                    if (sum < 0) {
                        continue;
                    }
                    if (z.contains(sum * -1)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

I added some unit tests here: GivenArrayReturnTrueIfThreeElementsSumZeroTest.
If the set is using too much space I can easily use a java.util.BitSet that will use O(n/w) space.

A: Program to get those three elements. I have just sorted the array/list first and them updated minCloseness based upon each triplet.
public int[] threeSumClosest(ArrayList<Integer> A, int B) {
    Collections.sort(A);
    int ansSum = 0;
    int ans[] = new int[3];
    int minCloseness = Integer.MAX_VALUE;
    for (int i = 0; i < A.size()-2; i++){
        int j = i+1;
        int k = A.size()-1;
        while (j < k){
            int sum = A.get(i) + A.get(j) + A.get(k);
            if (sum < B){
                j++;
            }else{
                k--;
            }
            if (minCloseness >  Math.abs(sum - B)){
                minCloseness = Math.abs(sum - B);
                ans[0] = A.get(i); ans[1] = A.get(j); ans[2] = A.get(k);
            }
        }
    }
    return ans;
}


text:
Q: Is it possible to find the position of a given element in a list without writing a jumble of code? I am trying to find out the position of a certain element in a list.  In concept, I input an item in the list, and it should return the position of that item.  I have written this:
alphabet = ["a", "b", "c", "d", "e"]

letter = "d" #Want the position in the list of this letter.

for i in range(0, len(alphabet)):
    if alphabet[i] == letter:
        position = i
        break

which works, but I feel like there is a more elegant/efficient way of doing it.
Any suggestions would be appreciated!

A: you can use:
alphabet = ["a", "b", "c", "d", "e"]
print(alphabet.index('d'))

It will return the index of the first 'd' into the list


text:
Q: watch a subdirectory with incron I use incron for watch a direcory and run a script if a file is added.
In /etc/incron.d/ I have a file with:
/home/pat0/downloads IN_CLOSE_WRITE /var/www/owncloud/scanOC.sh pat0

It's ok when I add a file in /home/pat0/downloads
but, if I create a subdirectory and I add in a file no thing run.
For exemple /home/pat0/downloads/test/myfile.txt is not seen.
How can I watch /home/pat0/download and all its future subdirectories and files?

A: According to the man page:
... Also, there is the symbol recursive=false. This symbol limits the observation on the specified directory and does not include subdirectories.

This rather implies that in the absence of such a flag incrond will check sub-directories. However my experience is that it does not. Sadly, specifying recursive=true also does not work.

A: No, I don't think this is possible with incron. Please check with Watcher.
Watcher is a daemon that watches specified files/folders for changes and fires commands in response to those changes. It is similar to incron, however, configuration uses a simpler to read yaml file instead of a plain text file. It's also written in Python, making it easier to hack.

A: Recursive directory watching in incron is a new feature added in version 0.5.12 (see https://github.com/ar-/incron/blob/master/CHANGELOG):

0.5.12   2015-02-01

*

*added recursive directory watching

*added configuration parameters: recursive, dotdirs and loopable

*added upstart script

*extended manpages and readme


text:
Q: WPF PasswordBox Password is "{DependencyProperty.UnsetValue}" I'm making a chating program.
I designed chat room list using XAML.
                                        <GridViewColumn x:Name="gridViewColumn_IsNeedPassword">
                                            <GridViewColumn.CellTemplate>
                                                <DataTemplate>
                                                    <PasswordBox x:Name="passwordBox_PW" MinWidth="100" IsEnabled="{Binding Path=IsNeedPassword}"/>
                                                </DataTemplate>
                                            </GridViewColumn.CellTemplate>
                                        </GridViewColumn>
                                        <GridViewColumn x:Name="gridViewColumn_EntryButton">
                                            <GridViewColumn.CellTemplate>
                                                <DataTemplate>
                                                    <Button Background="Aqua" Click="button_Entry_Click">
                                                        <StackPanel Orientation="Horizontal">
                                                            <Image Height="Auto" Width="Auto" Source="Resources/login.png"/>
                                                            <TextBlock Text="{Binding Converter={StaticResource EntryButtonConverter}}" VerticalAlignment="Center"/>
                                                        </StackPanel>
                                                        <Button.Tag>
                                                            <MultiBinding Converter="{StaticResource EntryButtonTagConverter}">
                                                                <Binding Path="ID"/>
                                                                <Binding Path="IsNeedPassword"/>
                                                                <Binding ElementName="passwordBox_PW" Path="Password"/>
                                                            </MultiBinding>
                                                        </Button.Tag>
                                                    </Button>
                                                </DataTemplate>
                                            </GridViewColumn.CellTemplate>
                                        </GridViewColumn>
                                        <GridViewColumn x:Name="gridViewColumn_DeleteButton">
                                            <GridViewColumn.CellTemplate>
                                                <DataTemplate>
                                                    <Button Background="Orange" Click="button_Delete_Click" IsEnabled="{Binding Path=Master, Converter={StaticResource DeleteButtonVisibilityConverter}}">
                                                        <StackPanel Orientation="Horizontal">
                                                            <Image Height="Auto" Width="Auto" Source="Resources/login.png"/>
                                                            <TextBlock Text="{Binding Converter={StaticResource DeleteButtonConverter}}" VerticalAlignment="Center"/>
                                                        </StackPanel>
                                                        <Button.Tag>
                                                            <Binding Path="ID"/>
                                                        </Button.Tag>
                                                    </Button>
                                                </DataTemplate>
                                            </GridViewColumn.CellTemplate>
                                        </GridViewColumn>
                                    </GridView.Columns>

Something like this.
Now, in the gridViewColumn_EntryButton I need some infos such as RoomID + IsNeedPassword + PasswordText
So i used MultiBinding.
and the EntryButtonTagConverter.Convert is like that.
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        string[] result = Array.ConvertAll<object, string>(values, obj =>
        {
            return (obj == null) ? string.Empty : obj.ToString();
        });
        // RoomID + IsNeedPassword + PasswordText
        return result[0] + '\n' + result[1] + '\n' + result[2];
    }

and When i debugging, the result[2], PasswordText is "{DependencyProperty.UnsetValue}"
But i inputed into the PasswordBox asdftest1234.
I don't know why PasswordBox.Password property is not accessable.
Any one some ideas?
Thanks.

A: It´s not possible to bind directly to the PasswordProperty for security reasons.
Take a look here!

A: Using PasswordBoxAssistant you can bind password.
public static class PasswordBoxAssistant
{
    public static readonly DependencyProperty BoundPasswordProperty =
        DependencyProperty.RegisterAttached("BoundPassword", typeof(string)
        , typeof(PasswordBoxAssistant), new FrameworkPropertyMetadata(string.Empty, OnBoundPasswordChanged));

    public static readonly DependencyProperty BindPasswordProperty = DependencyProperty.RegisterAttached(
        "BindPassword", typeof(bool), typeof(PasswordBoxAssistant), new PropertyMetadata(false, OnBindPasswordChanged));

    private static readonly DependencyProperty UpdatingPasswordProperty =
        DependencyProperty.RegisterAttached("UpdatingPassword", typeof(bool), typeof(PasswordBoxAssistant));

    private static void OnBoundPasswordChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        PasswordBox box = d as PasswordBox;

        // only handle this event when the property is attached to a PasswordBox
        // and when the BindPassword attached property has been set to true
        var ignoreBindProperty = false;
        if (box != null && box.Parent != null)
        {// TODO: Bind property change not set in case of hosting password box under Telerik datafield. That why I am ignoring the bind propery here - Morshed
            ignoreBindProperty = (box.Parent is Telerik.Windows.Controls.DataFormDataField);
        }

        if (d == null || !(GetBindPassword(d) || ignoreBindProperty))
        {
            return;
        }

        // avoid recursive updating by ignoring the box's changed event
        box.PasswordChanged -= HandlePasswordChanged;

        string newPassword = (string)e.NewValue;

        if (!GetUpdatingPassword(box))
        {
            box.Password = newPassword;
        }

        box.PasswordChanged += HandlePasswordChanged;
    }

    private static void OnBindPasswordChanged(DependencyObject dp, DependencyPropertyChangedEventArgs e)
    {
        // when the BindPassword attached property is set on a PasswordBox,
        // start listening to its PasswordChanged event

        PasswordBox box = dp as PasswordBox;

        if (box == null)
        {
            return;
        }

        bool wasBound = (bool)(e.OldValue);
        bool needToBind = (bool)(e.NewValue);

        if (wasBound)
        {
            box.PasswordChanged -= HandlePasswordChanged;
        }

        if (needToBind)
        {
            box.PasswordChanged += HandlePasswordChanged;
        }
    }

    private static void HandlePasswordChanged(object sender, RoutedEventArgs e)
    {
        PasswordBox box = sender as PasswordBox;

        // set a flag to indicate that we're updating the password
        SetUpdatingPassword(box, true);
        // push the new password into the BoundPassword property
        SetBoundPassword(box, box.Password);
        SetUpdatingPassword(box, false);
    }

    public static void SetBindPassword(DependencyObject dp, bool value)
    {
        dp.SetValue(BindPasswordProperty, value);
    }

    public static bool GetBindPassword(DependencyObject dp)
    {
        return (bool)dp.GetValue(BindPasswordProperty);
    }

    public static string GetBoundPassword(DependencyObject dp)
    {
        return (string)dp.GetValue(BoundPasswordProperty);
    }

    public static void SetBoundPassword(DependencyObject dp, string value)
    {
        dp.SetValue(BoundPasswordProperty, value);
    }

    private static bool GetUpdatingPassword(DependencyObject dp)
    {
        return (bool)dp.GetValue(UpdatingPasswordProperty);
    }

    private static void SetUpdatingPassword(DependencyObject dp, bool value)
    {
        dp.SetValue(UpdatingPasswordProperty, value);
    }
}

and change in xaml
<PasswordBox helpers:PasswordBoxAssistant.BindPassword="true"
              helpers:PasswordBoxAssistant.BoundPassword="{Binding Path=Password, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=true}"/>


text:
Q: angularjs compare two arrays How I can compare two arrays in AngularJS, and return the matching values?
Here is the first array:
[{
    "id":2,
    "student_name":"LiSa",
    "alien":"A",
    "world":"Sun",
    "justification":"i like sent this one",
    "submit_time":null
},{
    "id":1,
    "student_name":"Liz",
    "alien":"B",
    "world":"Earth",
    "justification":null,
    "submit_time":"2014-09-25T08:37:34.526-05:00"
}]

Here is the second one:
[{
    "id":1,
    "alien":"A",
    "world":"Sun",
    "color":"red"
},{
    "id":2,
    "alien":"A",
    "world":"Mercury",
    "color":"red"
},{
    "id":3,
    "alien":"B",
    "world":"Earth",
    "color":"red"
},{
    "id":4,
    "alien":"B",
    "world":"Moon",
    "color":"red"
}]

I want to check if the values for alien and world are matching in these two arrays. Then I can get the color value from the second array.
Here is the code I put in the controller:
angular.forEach(arr1, function(value1, key1) {
    angular.forEach(arr2, function(value2, key2){
        if(value1.alien === value2.alien && value1.world === value2.world){
            console.log(value2.color);

        }
    });
});

Shall I use angular.forEach? How can I do that? And where do I store the color value?

A: And if you are using ES6 then:
array1.forEach((elem1, index) => {elem1;
  array2.forEach((elem2, index) => {elem2;
    if(elem1.someProp=== elem2.someProp)
    {
     //--If elem1 equal elem2
    }
  });
});

A: Like duncan said, these are both arrays of objects and not multi-dimensional arrays. Here I use angulars .forEach method to loop through both arrays then compare the object properties.
I've added a comment where you would get your matching color.
angular.forEach(arr1, function(value1, key1) {
    angular.forEach(arr2, function(value2, key2) {
        if (value1.alien === value2.alien && value1.world === value2.world) {
            // here is where you grab the value2.color
        }
    });
});

Here's a fiddle


text:
Q: User env variable not working when PowerShell script started through Visual Studio I have a VB.NET form which starts a PowerShell script. One of the parameters passed to this script is a password, which I don't want to be written to the Windows PowerShell log. That's why I use a user environment variable to temporarily store this password. This works fine, as long as I run the script outside of Visual Studio. When I start the same script through my VB application, the variable is empty. So it looks like the script started through my application somehow runs as a different user, but I don't understand why...
Even weirder: when I start my applications exe file from the debug directory, the user environment variable does work!
Does anybody have an idea where to look? Thanks for any help in advance!
Kind regards,
Eric van Loon
Update 22-02-2023:
Here's an example of the VB code I use:
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Environment.SetEnvironmentVariable("TESTVAR", "Test Value", EnvironmentVariableTarget.User)
        Process.Start("Powershell.exe", "-noexit -ExecutionPolicy Bypass c:\test\test.ps1")
    End Sub
End Class

And the code for c:\test\test.ps1:
Write-Output $env:TESTVAR
read-host "Press ENTER to continue..."

You will see that when you start the VB application for the very first time, the script will not show the value of TESTVAR:
Press ENTER to continue...:

If you close VS, restart it and rerun the same VB application, the script will now properly pick up the value of TESTVAR:
Test Value
Press ENTER to continue...:

So the environment variable set by SetEnvironmentVariable() is only available after a restart of VS. Same thing for the compiled executable by the way.
Thanks for any help!


text:
Q: Is it possible to have url reference of an image in xaml like html? I am working on RichTextBox in WPF and i would like to know if i can have url references something like we have in html
<img src="http://AnyWebsite.com/example.png" />

in xaml ( which i will be converting to rtf and storing it into the DB )
Thank you for your help!

A: It's possible.
Based on your comment I am editing my earlier answer. This link will help you achieve what you want, you will need to create a custom converter class.
http://blog.davidsandor.com/post/2010/05/12/How-To-WPF-Databind-a-URL-URI-to-an-Image-control.aspx

A: I would recommend using FlowDocument instead of RichTextBox in this case as you want to display images and text togather.
For details you may refer to the article in msdn


text:
Q: Find mp4 files with certain file naming in subfolders and extract frames from it every second with ffmpeg I have a folder with several subfolders that contain mp4 files.
I want to extract frames of those mp4 files every second, but only of mp4 files that contain "abc" in the file name.
Those frames should be saved in a separated "images" folder with a naming that has frame count of the corresponding video.
The file structure with folder and subfolders and how I imagine the file naming of the frames:
|main_folder
|
├── folder1
|   ├── abc123.mp4
|   └── xyz123.mp4
├── folder2
|   ├── abc456.mp4
|   └── xyz456.mp4
|       ├── folder2.1
|          └──abc183.mp4
|          └──xyz183.mp4
├── folder3
|   ├── abc789.mp4
|   └── xyz789.mp4
├── images
    ├── video1-frame1.jpg
    ├── video1-frame30.jpg
    ├── video1-frame60.jpg
     ...
    ├── video2-frame1.jpg
    ├── video2-frame30.jpg
    ├── video2-frame60.jpg

So far I only have this and can't get any further :(
for file in *.mp4; do ffmpeg -i "$file" -vf fps=1 -q:v 3 "images/${i%.*}_frames%d.jpg"; done

I am missing the search in the subdirectories and the search for mp4s that only have "abc" in their file name.

A: try with find:
find /home/phillip -type f -iname '*abc*.mp4' | xargs -I %% ffmpeg -i %% -vf fps=1 -q:v 3 "images/${i%.*}_frames%d.jpg"


text:
Q: Boolean function within an range? I am trying to code a boolean function in which I can see if a modal score lives within the range of a real score.
 df['match'] = np.where(df['real_score'] + 0.5 >= df['modal_score']>= df['real_score'] - 0.5 , 'yes', 'no')

and
 df['match'] = np.where(df['modal_score']>= df['real_score']-0.5 and df['modal_score']<= df['real_score']+0.5, 'yes', 'no')

However this is not working. This is the error message I get : ''The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().''

A: I was staring at your code and didn't see anything wrong so I went and tried it out step by step.
The problem lies in the chaining of the comparison. Apparently, this doesn't work for pandas DataFrames.
So you'll have to write your check either as a single comparison (e.g. using abs(df['real_score'] - df['model_score']) <= 0.5 )
Ore you use two comparison and combine them with a logical and. But the and keyword doesn't work here either because that wants to just directly compare two booleans. Instead of the and you can use the & operator; make sure to use correct parentheses in this case:
df['match'] = np.where( (df['modal_score']>= df['real_score']-0.5) & (df['modal_score']<= df['real_score']+0.5), 'yes', 'no')


text:
Q: Why can I not change the Sprite attribute directly? I accidentally cross posted when I tried to switch the site I was posting to.  Oops!
https://gamedev.stackexchange.com/questions/120309/why-can-i-not-change-a-sprite-directly/120311#120311

I am changing the Sprites on an array of Images.  I could think of two ways to go about it.  The first way being:
var images = GetComponentsInChildren<Image>();
foreach(var image in images)
{
    if (!image.sprite)
    {
        image.sprite = GetMySprite();
    }
}

This way works perfectly.  But if I try to grab the sprite itself like so:
var images = GetComponentsInChildren<Image>();
foreach(var image in images)
{
    var sprite = image.sprite;
    if (!sprite)
    {
        sprite = GetMySprite();
    }
}

It does not work.  The Sprite gets assigned, but it is not the original Sprite.  The Sprite attached to the Image remains null.
At first I thought, maybe Sprite is a struct? But it is not - it is a sealed class extending Object.  (And I don't think that would necessarily explain it anyways).
So why must I retain the reference to the Image when changing its Sprite attribute?

A: In both instances the sprite field is a reference to a sprite object. In your second example you create a local variable which is also a reference to a sprite object - that you initialise by copying the value from image.sprite. Note that "var sprite" is not a reference to "image.sprite" itself.
In the second example, you only modify the value of the local variable, leaving the original unchanged.


text:
Q: How can I use the ValueError function correctly? This is my code:
from time import sleep

def Kontostand_Berechnen():
    if float(Kontostand_Nachfragen) >= float(Preis_Nachfragen):
        sleep(1)
        print("")
        print("Du hast genug Geld!")
        print("")
        sleep(1)
    else:
        sleep(1)
        print("")
        print("Du hast nicht genug Geld!")
        print("")
        sleep(1)

sleep(1)
print("")
Kontostand_Nachfragen = input("Wie viel Geld hast du?: ")
sleep(2)
print("")
Preis_Nachfragen = input("Wie viel kostet das Produkt?: ")
if ValueError:
    print("")
    sleep(1)
    print("Bitte nur Zahlen eingeben! Kein Text!")
    print("")
    sleep(1)
else:
    Kontostand_Berechnen()

I wrote this code just for practice and for fun. The print text is german. But I don't think that's hindering. I would like that if the user writes text and not a number, an error message is received. But that doesn't work as hoped. With this code, I ALWAYS get the error message, even when I write numbers.
(I'm sure the code is not very understandable. I also only started using Python recently)

A: If you want to take advantage of the ValueError you need to use try/except. You will deal with the error in the except block. A simplified example might look like:
while True:
    try:
        Preis_Nachfragen = float(input("Wie viel kostet das Produkt?: "))
        break
    except ValueError:
        print("Bitte nur Zahlen eingeben! Kein Text!")

print(Preis_Nachfragen)

A: You are receiving the error because if else clauses aren't for checking for errors. That why python have try except clauses.
Following on my answer here Check if String can be Converted to Float, you might want to take a look into to take a look into try except clause and check if the user put a number as input. Then, you will be able to treat input's that aren't numbers, like:
try:
    your_input = float(input("")) # fill in with input text
except Exception as e:
    raise ValueError("") # here you fill in the message you want to give to users

However you might be able to check that when you do float(input("message")) you are already receiving a ValueError with a standard message, so with the code above you can just edit that message (putting it in german, for example).


text:
Q: trait for something generic, but errors could be specific for trait implementation Let's say I have a trait for a Decoder, and I have specific decoders that implement this trait:
pub trait Decoder {
    fn do_something(&self) -> Result<(), DoSomethingError>;
}

pub enum DoSomethingError {}

pub struct SpecificDecoder1 {}

impl Decoder for SpecificDecoder1 {
    fn do_something(&self) -> Result<(), DoSomethingError> {
        todo!()
    }
}

pub struct SpecificDecoder2 {}

impl Decoder for SpecificDecoder2 {
    fn do_something(&self) -> Result<(), DoSomethingError> {
        todo!()
    }
}

each decoder could return specific errors. However, I don't want to include these specific errors in the DoSomethingError trait as some decoders could not even be available on some devices, so I don't want the mess of #cfg(feature="...") on the enum.
I thought about
pub trait DoSomethingError {}
fn do_something(&self) -> Result<(), Box<dyn DoSomethingError>> {
    Ok(self.do_another_something()?)
}

this way I can downcast the Box<dyn DoSomethingError> to a specific error if needed. However, Ok(self.do_another_something()?) wouldn't work. Remember that I don't want to store a string, I want to be able to match the error somehow, or try to match it, so I cannot create a UserDefined(String) variant on the string and convert every error to it.

A: If you want to have a different Error for each implementation, you can define the trait with an associated error type, just like in TryFrom:
pub trait Decoder {
    type Error;
    fn do_something(&self) -> Result<(), Self::Error>;
}

pub enum SpecificDecoder1Error {}
pub struct SpecificDecoder1 {}
impl Decoder for SpecificDecoder1 {
    type Error = SpecificDecoder1Error;
    fn do_something(&self) -> Result<(), Self::Error> {
        todo!()
    }
}

pub enum SpecificDecoder2Error {}
pub struct SpecificDecoder2 {}
impl Decoder for SpecificDecoder2 {
    type Error = SpecificDecoder2Error;
    fn do_something(&self) -> Result<(), Self::Error> {
        todo!()
    }
}

But if you want the trait to return a generic type, you can return a dyn std::any::Any value, and downcast if necessary:
pub trait Decoder {
    fn do_something(&self) -> Result<(), Box<dyn std::any::Any>>;
}

pub struct SpecificDecoder1Error(u16);
pub struct SpecificDecoder1 {}
impl Decoder for SpecificDecoder1 {
    fn do_something(&self) -> Result<(), Box<dyn std::any::Any>> {
        Err(Box::new(SpecificDecoder1Error(13)))
    }
}

pub struct SpecificDecoder2Error(String);
pub struct SpecificDecoder2 {}
impl Decoder for SpecificDecoder2 {
    fn do_something(&self) -> Result<(), Box<dyn std::any::Any>> {
        Err(Box::new(SpecificDecoder2Error(
            "Specific Error 2".to_string(),
        )))
    }
}

fn main() {
    let dec1 = SpecificDecoder1 {};
    let dec2 = SpecificDecoder2 {};
    let decs: [&dyn Decoder; 2] = [&dec1, &dec2];
    for dec in decs {
        let error = dec.do_something().err().unwrap();
        if let Some(error1) = error.downcast_ref::<SpecificDecoder1Error>() {
            println!("Error from SpecificDecoder1Error: {}", error1.0)
        } else if let Some(error2) =
            error.downcast_ref::<SpecificDecoder2Error>()
        {
            println!("Error from SpecificDecoder2Error: {}", error2.0)
        } else {
            unreachable!()
        }
    }
}


text:
Q: Default value of function parameter in Vim script How to specify default value (e.g. 0, None) for a parameter in Vim script?

A: Since Vim 8.1.1310 Vim also supports real optional function arguments.
However, that means that most vim installation don't support this yet. Neovim has that feature since version 0.7.0.
Example from :help optional-function-argument:
  function Something(key, value = 10)
     echo a:key .. ": " .. a:value
  endfunction
  call Something('empty')   "empfty: 10"
  call Something('key', 20) "key: 20"

A: From the docs, it seems that arguments can't have default values in Vim script. However, you can emulate this by defining a function with variable number of arguments, and using a:0 to determine the number of extra arguments and a:1 through a:n to access them:
function Foo(bar, ...)
  if a:0 > 0
    let xyzzy = a:1
  else
    let xyzzy = 0
  end
endfunction

A: You can use get to select an argument in the specific position or a default value if it's not present.
function! Foo(bar, ...)
    let baz = get(a:, 1, 0)
endfunction


text:
Q: Mute htlm5 video player with jQuery after seconds I have html5 video player:
    <video width="185" height="104" autoplay="autoplay" loop>
    <source src="comm.mp4" type="video/mp4" />
    </video>

It is a 5 seconds video. I want loop, but I want to mute this video once it has played for the first time.
jQuery masters... I'm looking for your help.

A: As written in the comment - one way would be setting the video to mute via a timeout after n seconds. I would prefer something like this:
// use all videos with a loop attribute
// remove the attribute and replay on end event
$('video[loop]').bind('ended', function(){
  // prop or attr depends on your jquery version
  $(this).attr('muted', true);
  this.play();
}).removeAttr('loop');


text:
Q: Extract value from an ID tag in a extracted Html data I hope my topic finds you well.
I want to extract a specific number from an ID value,
here is the line:
TAG POS=1 TYPE=INPUT ATTR=CLASS:markAll<SP>check EXTRACT=HTM

and here is the result I get after I run the previous line:
<input style="outline: 1px solid blue;" id="raidListMarkAll1518" class="markAll check" onclick="Game.RaidList.markAllSlotsOfAListForRaid(1518, this.checked); "type="checkbox">

For example, I want only to extract this number (1518) from this (id="raidListMarkAll1518").
I don't know how to make the EVAL command to achieve the result I want.
I hope to get help from you guys, I really appreciate it
Thank you so much.


text:
Q: How can the taint spread? I spawned near a huge section of taint, and I'm fairly sure it's spreading.  My panicking in the Minecraft chat room turned up the suggestion of turning off the spreading in the config file, so I dug out Thaumcraft.cfg, and found this:
# The chance per block update (1 in n) of the Taint biome spreading.
# Setting it to 0 prevents the spread of Taint biomes.
I:biome_taint_spread=0

So...it seems like it's not spreading?  Now, either I'm going crazy or there's something else causing it to spread.  Could Tainticles and the like (tainted spiders, creepers, etc) cause it to be spreading?
In what ways can the taint spread?

A: If there are any blocks marked to be infected they will turn to taint even after you disabled it in .cfg,but they won't spread afterwards.So make sure you give it enough time to really stop spreading before you declare yourself crazy.
Check your .cfg for "aura.Taintspawn" some people say you need to disable this but to me it looks like it is only a different name used for same setting,probably from older version.
Bodies of water (rivers,lakes,sea...) can't become tainted,but the taint as the infection can spread through them ; meaning,if you have 2 islands where only one of them is tainted,after enough time both of them will end up tainted.The taint will grow as it usually does through the water blocks,you just can't see it until it emerges on the surface somewhere else.In shallow waters sometimes you can see it spread on the seabed.
Even if you manage to completely stop the spreading of taint you can still infect the land by yourself using vials with taint,magic cauldron...or any similar pollutants.
If Tainted Creeper explodes outside tainted area,it will make even large crater and will also corrupt some blocks.
Tainted Testificates release gas that can make some tainted areas grow even more.
Tainted Sheep can vomit taint.


text:
Q: JQuery UI Tabs Switching - Dialog will not open I'm trying to use the JQuery UI tabs by pointing one of the tabs to another jsp in my app.  The link is in 1st tab and the button will show the dialog for the first time it is render.  If I click on any other tab and go back to the 1st tab the dialog will not open.
The example is based on JQuery UI tab examples but added a link to the Dialog box
http://jqueryui.com/demos/tabs/#default
Did I construct the tabs incorrectly?  Or is there a way to reset the JQuery state back to an initial state like a refresh?
Here's the code for page with all the tabs:
    <%@include file="/WEB-INF/jsp/taglibs.jsp"%>

<title>Recon Blotter Results</title>
<link rel="stylesheet" type="text/css" media="screen"
    href="resources/css/jquery-ui-1.8.15/redmond/jquery-ui-1.8.15.custom.css" />

Nunc tincidunt

Proin dolor

Aenean lacinia

Morbi tincidunt, dui sit amet facilisis feugiat, odio metus gravida ante, ut pharetra massa metus id nunc. Duis scelerisque molestie turpis. Sed fringilla, massa eget luctus malesuada, metus eros molestie lectus, ut tempus eros massa ut dolor. Aenean aliquet fringilla sem. Suspendisse sed ligula in ligula suscipit aliquam. Praesent in eros vestibulum mi adipiscing adipiscing. Morbi facilisis. Curabitur ornare consequat nunc. Aenean vel metus. Ut posuere viverra nulla. Aliquam erat volutpat. Pellentesque convallis. Maecenas feugiat, tellus pellentesque pretium posuere, felis lorem euismod felis, eu ornare leo nisi vel felis. Mauris consectetur tortor et purus.

Mauris eleifend est et turpis. Duis id erat. Suspendisse potenti. Aliquam vulputate, pede vel vehicula accumsan, mi neque rutrum erat, eu congue orci lorem eget lorem. Vestibulum non ante. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Fusce sodales. Quisque eu urna vel enim commodo pellentesque. Praesent eu risus hendrerit ligula tempus pretium. Curabitur lorem enim, pretium nec, feugiat nec, luctus a, lacus.

Duis cursus. Maecenas ligula eros, blandit nec, pharetra at, semper at, magna. Nullam ac lacus. Nulla facilisi. Praesent viverra justo vitae neque. Praesent blandit adipiscing velit. Suspendisse potenti. Donec mattis, pede vel pharetra blandit, magna ligula faucibus eros, id euismod lacus dolor eget odio. Nam scelerisque. Donec non libero sed nulla mattis commodo. Ut sagittis. Donec nisi lectus, feugiat porttitor, tempor ac, tempor vitae, pede. Aenean vehicula velit eu tellus interdum rutrum. Maecenas commodo. Pellentesque nec elit. Fusce in lacus. Vivamus a libero vitae lectus hendrerit hendrerit.

Here's the page that contains the dialog for the 1st tab.
<%@include file="/WEB-INF/jsp/taglibs.jsp"%>

<title>Recon Blotter Results</title>
<link rel="stylesheet" type="text/css" media="screen"
    href="resources/css/jquery-ui-1.8.15/redmond/jquery-ui-1.8.15.custom.css" />

Proin elit arcu, rutrum commodo, vehicula tempus, commodo a, risus. Curabitur nec arcu. Donec sollicitudin mi sit amet mauris. Nam elementum quam ullamcorper ante. Etiam aliquet massa et lorem. Mauris dapibus lacus auctor risus. Aenean tempor ullamcorper leo. Vivamus sed magna quis ligula eleifend adipiscing. Duis orci. Aliquam sodales tortor vitae ipsum. Aliquam nulla. Duis aliquam molestie erat. Ut et mauris vel pede varius sollicitudin. Sed ut dolor nec orci tincidunt interdum. Phasellus ipsum. Nunc tristique tempus lectus.

        <button id="testButton">Hello</button>

 Testing Dialog Control

A: The page loaded via AJAX should only contain the content; i.e. it shouldn't be a full HTML page. Try to cut down your tab1 page to the following:

Proin elit arcu, rutrum commodo, vehicula tempus, commodo a, risus. Curabitur nec arcu. Donec sollicitudin mi sit amet mauris. Nam elementum quam ullamcorper ante. Etiam aliquet massa et lorem. Mauris dapibus lacus auctor risus. Aenean tempor ullamcorper leo. Vivamus sed magna quis ligula eleifend adipiscing. Duis orci. Aliquam sodales tortor vitae ipsum. Aliquam nulla. Duis aliquam molestie erat. Ut et mauris vel pede varius sollicitudin. Sed ut dolor nec orci tincidunt interdum. Phasellus ipsum. Nunc tristique tempus lectus.

<button id="testButton">Hello</button>

 Testing Dialog Control


text:
Q: Trapezoidal rule or similar for integration over sphere (spherical triangle). I would like to calculate numerically the integral of the function defined on the sphere. Moreover, the sphere is completely covered by non-overlapping spherical triangles, I need the integral to be calculated as sum of integrals over triangles. For simplicity assume, that sphere has radius $1$.
So, if $S$ is a sphere, $T$ is the set of non-overlapping spherical triangles covering this sphere and $t\in T$ is triangle from this set then:
$\int\limits_{\mathbf{x}\in S}f(\mathbf{x})ds=\sum\limits_{t\in T}\int\limits_{\mathbf{x}\in t}f(\mathbf{x})ds$
What I need is the means to numerically calculate integral over spherical triangle $t$.
The simplest way is to use analogues of 'rectangular rule' here, that is
$\int\limits_{\mathbf{x}\in t}f(\mathbf{x})ds\approx f(\mathbf{x}_c)A(t)$
where $\mathbf{x}_c$ is the center of the spherical triangle (whatever point you think is the center of spherical triangle, as long as it is inside this triangle) and $A(t)$ is the spherical triangle's area.
But is it possible to use some more accurate formula which would take, for example, values of $f$ at 3 vertices of the triangle?
Assume, that triangles are of decent shape.

A: Here is a link to a paper which I believe might interest you
http://homepage.math.uiowa.edu/~atkinson/papers/SphereQuad1982.pdf
It is not certainly not new, but it is free and there is good basic information on centroid rule as well as an isoparametric method which has a higher order of convergence. There are some error bounds as well. I expect that they are pessimistic.
Regardless of how you proceed you will also need a reliable way of estimating the error. Here I recommend that you investigate the existence of an asymptotic error expansion of the form
\begin{equation}
I - A_h = \alpha h^p + \beta h^q + O(h^r).
\end{equation}
Here $I$ is your integral, $A_h$ is your approximation of the integral, $h$ is a measure of the size of your spherical triangles, say, the largest arc length used, $\alpha$, $\beta$ are constants independent of $h$, and $0<p<q<r$ are real numbers. Proving the existence of such an expansion is typically hard, but it is easy to verify numerically that it exists, in which case you can use it compute accurate error estimates. If the expansion exists, then you can show that
\begin{equation}
F_h = \frac{A_{2h} - A_{4h}}{A_h - A_{2h}} \rightarrow 2^p, \quad h \rightarrow 0
\end{equation}
and the convergence will be monotone. Here you should view $A_{4h}$ as your initial estimate based on a coarse triangulation, $A_{2h}$ and $A_h$ are improved estimates obtained by recursively cutting each triangle into 4 parts by halving each arc. Observing how $F_h$ behaves as $h$ tends to zero, will allow you to identify $p$, which is not necessarily an integer. Moreover, you will be able to show that the dominance error term $\alpha h^p$ satisfies
\begin{equation}
\alpha h^p = \frac{A_h - A_{2h}}{2^p - 1} + O(h^q).
\end{equation}
This will allow you to estimate the error. The error estimates are good, when the fractions are close to $2^p$. There are some numerical issues involving catastrophic cancellation when $h$ becomes small, but this is a minor matter. As long as the computed values of the above mentioned fractions are converging monotonically, then you are in good shape.
The entire technique is known as Richardson extrapolation.
If you functions are nice and smooth, then I expect that you will discover that $p$ is an integer.


text:
Q: Finding the solution of $u_x + y u_y = 0$ using $u(0, y) = y^3$ I am currently studying the textbook Partial Differential Equations – An introduction, second edition, by Walter A. Strauss. The section The Variable Coefficient Equation of chapter 1 says the following:

The equation
$$u_x + y u_y = 0 \label{4}\tag{4}$$
is linear and homogeneous but has a variable coefficient ($y$). We shall illustrate for equation \eqref{4} how to use the geometric method somewhat like Example 1. The PDE \eqref{4}  itself asserts that the directional derivative in the direction of the vector $(1, y)$ is zero. The curves in the $xy$ plane with $(1, y)$ as tangent vectors have slopes $y$ (see Figure 3). Their equations are
$$\dfrac{dy}{dx} = \dfrac{y}{1} \label{5}\tag{5}$$
This ODE has the solutions
$$y = Ce^x \label{6}\tag{6}$$
These curves are called the characteristic curves of the PDE \eqref{4} . As $C$ is changed, the curves fill out the $xy$ plane perfectly without intersecting. On each of the curves $u(x, y)$ is a constant because
$$\dfrac{d}{dx}u(x, Ce^x) = \dfrac{\partial{u}}{\partial{x}} + Ce^x \dfrac{\partial{u}}{\partial{y}} = u_x + yu_y = 0.$$
Thus $u(x, Ce^x) = u(0, Ce^0) = u(0, C)$ is independent of $x$. Putting $y = Ce^x$ and $C = e^{−x}y$, we have
$$u(x, y) = u(0, e^{-x}y).$$
It follows that
$$u(x, y) = f(e^{-x}y) \label{7}\tag{7}$$
is the general solution of this PDE, where again $f$ is an arbitrary function of only a single variable. This is easily checked by differentiation using the chain rule (see Exercise 4). Geometrically, the "picture" of the solution $u(x, y)$ is that it is constant on each characteristic curve in Figure 3.

I am now trying to do the following exercise:

Find the solution of \eqref{4}  that satisfies the auxiliary equation $u(0, y) = y^3$.

I used \eqref{6}  to get that $u(0, y) = y = C$, which means that $y = C = y^3$. However, I think that this is an incorrect conclusion. But is this not the reasoning that the author applied above to get \eqref{7}? So I don't understand why this reasoning was incorrect in this case.
I would greatly appreciate it if people would please take the time to carefully explain this.

A: You seem to make some confusion due to the use of the variables $x,y$ for multiple (and different) purposes. The auxiliary (initial value) equation you write as $u(0,y)=y^3$ but you could equally well write it as  $u(0,t)=t^3$ for any real value of $t$ (better not use $y$ here).
For a given point $(x,y)$ in the plane you have from the result just before (7):  $u(x,y) = u(0,ye^{-x})$. Setting $t=y e^{-x}$ and using the previous we get:
$$ u(x,y)=u(0,ye^{-x}) = u(0,t) = t^3 = (y e^{-x})^3 = y^3 e^{-3x}.$$
Hope this brings you some peace of mind.

A: Let us verify the solution, using the Cauchy method.
Trying to find the solution in the form of
$$u(x,y) = X(x)Y(y),\tag1$$
one can get
$$X'(x)Y(y) + yX(x)Y'(y) = 0,$$
$$\frac{X'(x)}{X(x)} + y\frac{Y'(y)}{Y(y)} = 0.\tag2$$
Since the first term of $LHS(2)$ does not depend of $y$ and the second term does not depend of $x,$ then solutions of $(2)$ exists only if these terms are the opposite constants.
Assume the second term as $\lambda,$ then
$$\frac{X'(x)}{X(x)} = -\lambda,\quad \frac{Y'(y)}{Y(y)} = \frac\lambda y,\tag3$$
$$
\begin{cases}
\ln C_1^{-1}X = - \lambda x\\[4pt]
\ln C_2^{-1}Y = \lambda \ln y
\end{cases}\Rightarrow
\begin{cases}
X = C_1e^{-\lambda x}\\[4pt]
Y = C_2y^\lambda,
\end{cases}
$$
$$u(x,y,\lambda) = C_\lambda(y e^{-x})^\lambda.\tag4$$
The general solution can be defined as the arbitrary linear combination of such solutions  over the domain $D(\lambda)$ in the form of
$$u(x,y) = \int\limits_{D(\lambda)} w(\lambda)\ y^\lambda\ e^{-\lambda x}\text{ d}\lambda
= f(e^{-x}y).\tag5$$
If $u(0,y) = y^3,$ then

*

*from $(4)$ should $\lambda = 3, C_\lambda = 1,u(x,y,3) = y^3e^{-3x};$

*from $(5)$ should $w(\lambda) = \delta(\lambda-3),\quad u(x,y)= y^3e^{-3x}.$
Also, some details by the paper.

*

*The directional derivative is
$$u^\,_{\{1,y\}}= \text{ grad }u\cdot \{1,y\}= \{u_x,u_y\}\cdot \{1,y\} = u_x+yu_y;$$

*Since characteristic lines are defined by the equation $u(x,y) = C,$ then the full differential
$$\text{ d}u = u_x \text{ d}x + u_y \text{ d}y = 0$$
on this lines is zero, and
$$\frac{\text{ d}y}{\text{ d}x} = -\dfrac{u_x}{u_y}.$$
Taking in account PDE $(OP.4),$ this leads to the ODE $(OP.5).$

*To get the solution from $(OP.7),$ Maclaurin series can be used. However, the kernel of the representation $(5)$ continuously depends of $\lambda$ and looks more suitable if $\lambda$ is not integer.

A: $u_x+yu_y=0\\ u_{xx}+yu_{xy}=0\\ a=\ln{y}+x\\ b=y\\ u_{ab}=0\\ u=f(a)+g(b)=f(\ln{y}-x)+g(y)\\ u_x+yu_y=0\Longrightarrow g(y)=C=\text{cost.}\\ f(\ln{y})=y^3\Longrightarrow f(t)=e^{3t}-C\Longrightarrow u=y^3e^{-3x}$


text:
Q: SQLite data should be displayed on view after clicking on tab (view) in tabbedNavigatorApplication (Flex mobile/Flash Builder) I had created an android app (Employee Directory) in flash builder with SQLite database connection and having 4 tabs (view). I Just want that when I click on the Admin tab the Employee details from the database should be loaded. Below is my code.
EmployeeDirectory.mxml
<s:TabbedViewNavigatorApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
                              xmlns:s="library://ns.adobe.com/flex/spark">
    <fx:Style>

    s|ActionBar
    {
        chromeColor: #D3D3D3;

    }

    s|ActionBar #titleDisplay
    {
        color: #161616;
        fontSize: 20;
        fontWeight: normal;
        fontFamily: "Microsoft Sans Serif";
    }

    s|TabbedViewNavigator #tabBar
    {
        chromeColor: #D3D3D3;
        color: #161616;
        fontFamily: "Microsoft Sans Serif";
        iconPlacement:top;

    }

</fx:Style>
<fx:Script>
    <![CDATA[

        import mx.events.FlexEvent;
        protected function button1_clickHandler(event:MouseEvent):void {
            // Switch to the first section in the application.
            tabbedNavigator.selectedIndex = 0;
            // Switch to the first view in the section.
        ViewNavigator(tabbedNavigator.selectedNavigator).popToFirstView();
        }
        protected function BackBtn_clickHandler(event:MouseEvent):void {

            // Switch to the first view in the section.
            ViewNavigator(tabbedNavigator.selectedNavigator).popView();
        }

        ]]>
</fx:Script>
<s:navigators>

    <s:ViewNavigator label="Home" width="100%" height="100%"
firstView="views.HomeView" icon="@Embed('assets/Home1.png')">

    </s:ViewNavigator>
    <s:ViewNavigator label="Admin" width="100%" height="100%"
firstView="views.AdminView" icon="@Embed('assets/admin.png')">
        <s:navigationContent>
            <s:Button icon="@Embed('assets/home.png')"
                      click="button1_clickHandler(event)"/>
            <s:Button icon="@Embed('assets/back2.png')"
                      click="BackBtn_clickHandler(event)"/>

        </s:navigationContent>
    </s:ViewNavigator>
    <s:ViewNavigator label="Consultants" width="100%" height="100%"
firstView="views.ConsultantsView" icon="@Embed('assets/doctor.jpg')">
        <s:navigationContent>
            <s:Button icon="@Embed('assets/home.png')"
                      click="button1_clickHandler(event)"/>
        </s:navigationContent>
    </s:ViewNavigator>
    <s:ViewNavigator label="Extn." width="100%" height="100%"
firstView="views.ExtnView" icon="@Embed('assets/ext.png')">
        <s:navigationContent>
            <s:Button icon="@Embed('assets/home.png')"
                      click="button1_clickHandler(event)"/>
            <s:Button label="Back"
                      click="BackBtn_clickHandler(event)"/>
        </s:navigationContent>
    </s:ViewNavigator>
</s:navigators>

<fx:Declarations>
</fx:Declarations>
</s:TabbedViewNavigatorApplication>

AdminView
<?xml version="1.0" encoding="utf-8"?>
<s:View xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark" title="Admin" xmlns:dao="dao.*">
<fx:Declarations>
    <dao:EmployeeDAO id="srv"/>
</fx:Declarations>
<s:titleContent>
    <s:TextInput id="key" width="100%"/>
</s:titleContent>
<s:actionContent>
    <s:Button icon="@Embed('assets/search.png')"
              click="data=srv.findByName(key.text)"/>
</s:actionContent>
<s:List id="list" top="0" bottom="0" left="0" right="0"
        dataProvider="{data}"
        change="navigator.pushView(Employeedetails, list.selectedItem)">
<s:itemRenderer>
<fx:Component>
            <s:IconItemRenderer
                label="{data.firstName} {data.lastName}"
                messageField="title"/>
        </fx:Component>
    </s:itemRenderer>
</s:List>
</s:View>

EmployeeDAO
package dao
{
import flash.data.SQLConnection;
import flash.data.SQLStatement;
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import mx.collections.ArrayCollection;

public class EmployeeDAO
{
    public function getItem(id:int):Employee
    {
        var sql:String = "SELECT id, firstName, lastName, title, department,
city, email, officePhone, cellPhone, managerId, picture FROM employee WHERE
id=?";
        var stmt:SQLStatement = new SQLStatement();
        stmt.sqlConnection = sqlConnection;
        stmt.text = sql;
        stmt.parameters[0] = id;
        stmt.execute();
        var result:Array = stmt.getResult().data;
        if (result && result.length == 1)
            return processRow(result[0]);
        else
            return null;

    }

    public function findByManager(managerId:int):ArrayCollection
    {
        var sql:String = "SELECT * FROM employee WHERE managerId=? ORDER BY
lastName, firstName";
        var stmt:SQLStatement = new SQLStatement();
        stmt.sqlConnection = sqlConnection;
        stmt.text = sql;
        stmt.parameters[0] = managerId;
        stmt.execute();
        var result:Array = stmt.getResult().data;
        if (result)
        {
            var list:ArrayCollection = new ArrayCollection();
            for (var i:int=0; i<result.length; i++)
            {
                list.addItem(processRow(result[i]));
            }
            return list;
        }
        else
        {
            return null;
        }
    }

    public function findByName(searchKey:String):ArrayCollection
    {

         var sql:String = "SELECT * FROM employee WHERE firstName || ' ' ||
lastName || ' ' || department LIKE ? and managerId in ('1','2') ORDER BY id,
managerId, firstName, lastName";
         var stmt:SQLStatement = new SQLStatement();
         stmt.sqlConnection = sqlConnection;
         stmt.text = sql;
         stmt.parameters[0] = "%" + searchKey + "%";
         stmt.execute();
         var result:Array = stmt.getResult().data;
         if (result)
         {
             var list:ArrayCollection = new ArrayCollection();
             for (var i:int=0; i<result.length; i++)
             {
                 list.addItem(processRow(result[i]));
             }
             return list;
         }
         else
         {
             return null;
         }
    }

    public function create(employee:Employee):void
    {
        trace(employee.firstName);
        if (employee.manager) trace(employee.manager.id);
        var sql:String =
            "INSERT INTO employee (id, firstName, lastName, title,
department, managerId, city, officePhone, cellPhone, email, picture) " +
            "VALUES (?,?,?,?,?,?,?,?,?,?,?)";
        var stmt:SQLStatement = new SQLStatement();
        stmt.sqlConnection = sqlConnection;
        stmt.text = sql;
        stmt.parameters[0] = employee.id;
        stmt.parameters[1] = employee.firstName;
        stmt.parameters[2] = employee.lastName;
        stmt.parameters[3] = employee.title;
        stmt.parameters[4] = employee.department;
        stmt.parameters[5] = employee.manager ? employee.manager.id : null;
        stmt.parameters[6] = employee.city;
        stmt.parameters[7] = employee.officePhone;
        stmt.parameters[8] = employee.cellPhone;
        stmt.parameters[9] = employee.email;
        stmt.parameters[10] = employee.picture;
        stmt.execute();
        employee.loaded = true;
    }

    protected function processRow(o:Object):Employee
    {
        var employee:Employee = new Employee();
        employee.id = o.id;
        employee.firstName = o.firstName == null ? "" : o.firstName;
        employee.lastName = o.lastName == null ? "" : o.lastName;
        employee.title = o.title == null ? "" : o.title;
        employee.department = o.department == null ? "" : o.department;
        employee.city = o.city == null ? "" : o.city;
        employee.email = o.email == null ? "" : o.email;
        employee.officePhone = o.officePhone == null ? "" : o.officePhone;
        employee.cellPhone = o.cellPhone == null ? "" : o.cellPhone;
        employee.picture = o.picture;

        if (o.managerId != null)
        {
            var manager:Employee = new Employee();
            manager.id = o.managerId;
            employee.manager = manager;
        }

        employee.loaded = true;
        return employee;
    }
    public static var _sqlConnection:SQLConnection;

    public function get sqlConnection():SQLConnection
    {
        if (_sqlConnection) return _sqlConnection;
        var file:File =
File.applicationDirectory.resolvePath("assets/Employee.db");
        var fileExists:Boolean = file.exists;
        _sqlConnection = new SQLConnection();
        _sqlConnection.open(file);
        if (!fileExists)
        {
            createDatabase();
            populateDatabase();
        }
        return _sqlConnection;
    }

    protected function createDatabase():void
    {
        var sql:String =
            "CREATE TABLE IF NOT EXISTS employee ( "+
            "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
            "firstName VARCHAR(50), " +
            "lastName VARCHAR(50), " +
            "title VARCHAR(50), " +
            "department VARCHAR(50), " +
            "managerId INTEGER, " +
            "city VARCHAR(50), " +
            "officePhone VARCHAR(30), " +
            "cellPhone VARCHAR(30), " +
            "email VARCHAR(30), " +
            "picture VARCHAR(200))";
        var stmt:SQLStatement = new SQLStatement();
        stmt.sqlConnection = sqlConnection;
        stmt.text = sql;
        stmt.execute();
    }

    protected function populateDatabase():void
    {
        var file:File =
File.applicationDirectory.resolvePath("assets/employees.xml");
        var stream:FileStream = new FileStream();
        stream.open(file, FileMode.READ);
        var xml:XML = XML(stream.readUTFBytes(stream.bytesAvailable));
        stream.close();
        var employeeDAO:EmployeeDAO = new EmployeeDAO();
        for each (var emp:XML in xml.employee)
        {
            var employee:Employee = new Employee();
            employee.id = emp.id;
            employee.firstName = emp.firstName;
            employee.lastName = emp.lastName;
            employee.title = emp.title;
            employee.department = emp.department;
            employee.city = emp.city;
            employee.officePhone = emp.officePhone;
            employee.cellPhone = emp.cellPhone;
            employee.email = emp.email;
            employee.picture = emp.picture;
            if (emp.managerId>0)
            {
                employee.manager = new Employee();
                employee.manager.id = emp.managerId;
            }
            employeeDAO.create(employee);
        }
    }

}
}

The below is my screen
this is the home screen and after clicking on admin tab the data should be
   displayed. Currently the data is displayed after clicking on search button in
   admin view
[After clicking on admin tab from home screen][2]
The data should be displayed like this


text:
Q: How to set fallback value if validation fails (NestJS, class-validator) I have a Person class similar to the one described below.
languages is an optional property. It may be missing or invalid.
I don't want the post call to fail if languages is missing or invalid. Instead, I want to set languages to a fallback value, say ["en"].
How would I do that?
I've looked into custom validators, but that doesn't seem to fit, since I want to both run all the validations and also change the object if it fails validation.
// interface
import { IsString, MinLength, IsNotEmpty } from 'class-validator';

class Person {
  @IsNotEmpty()
  public readonly name: string;

  @IsArray()
  @IsString({ each: true })
  @MinLength(1)
  public languages: string[];  // <-- how would I specify a fallback value?
}

// controller
import { Body, Controller, Post } from "@nestjs/common";

@Controller("signup")
export class SignupController {
   @Post()
   public async submit(@Body() formData: Person) {
      // create the user object and save it to the db
   }

}

A: I ended up using @Transform like this
import { Transform } from "class-transformer";
import { IsOptional } from 'class-validator';

class Person {
    @IsOptional()
    @Transform(({ value }) => {
        if (/* test for value validity */) {
            return value as string[];
        }
        return fallbackLanguages;
    })
    public languages: string[];
}


text:
Q: Google Sheets: Copying cells and sorting it in another tab i have a big document list ("MDR") from multiple projects and im trying to sort them as in progress/ done. It looks somethink like this:

Project
Document
Status

1
Doc11
Done

1
Doc12
In progress

1
Doc13
Done

2
Doc21
In progress

2
Doc22
Done

2
Doc23
In progress

I select the status from a data validation dropdown list.
And i want a second tab ("GPO") to filter this first MDR tab for projects that are In progress, so it would be like this:

Project
Document
Status

1
Doc12
In progress

2
Doc21
In progress

2
Doc23
In progress

Plus, i would like in case i got a revision on Doc13 to it be added on the second tab in his place:

Project
Document
Status

1
Doc12
In progress

1
Doc13
In progress

2
Doc21
In progress

2
Doc23
In progress

I tried using query and filter, but it doesnt work since i also need to assign information in the "GPO" tab, then information would get misplaced when adding/deleting rows.
Also tried making a macro for it, but got no luck, wasn't able to set it to trigger when i change the status of the project, neither i found a way to sort it in the right row.
I can't add filters in the MDR tab and write there since it's also used for other activities.
Can it be done via macros?
Or it would be easier with scripts? If so, what i should look into to find my answer?
I appreciate any kind of help!

A: function myfunc101() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName('Sheet1');
  const sh2 = ss.getSheetByName('Sheet2');
  sh2.clearContents();
  const sh3 = ss.getSheetByName('Sheet3');
  sh3.clearContents();
  const [hA,...vs] = sh.getDataRange().getValues();
  let inProg = vs.map(r=>{if(r[2]=='In progress'){return r}}).filter(e=>e);
  let done = vs.map(r=>{if(r[2]=='Done'){return r}}).filter(e=>e);
  inProg.unshift(hA);//add headers
  sh2.getRange(1,1,inProg.length,inProg[0].length).setValues(inProg);
  done.unshift(hA);//add headers
  sh3.getRange(1,1,done.length,done[0].length).setValues(done);
}

Sheet 1:

Project
Document
Status

1
Doc11
Done

1
Doc12
In progress

1
Doc13
Done

2
Doc21
In progress

2
Doc22
Done

2
Doc23
In progress

Sheet 2:

Project
Document
Status

1
Doc12
In progress

2
Doc21
In progress

2
Doc23
In progress

Sheet 3:

Project
Document
Status

1
Doc11
Done

1
Doc13
Done

2
Doc22
Done

A: Sounds like you could achieve that using a pivot table,
As you want an auto refreshing filtered table external to your data one.
If you're unfamiliar with pivot tables, read here:
https://support.google.com/docs/answer/1272900?co=GENIE.Platform%3DDesktop&hl=en#:~:text=Pivot%20table.,%2C%22%20choose%20a%20pivot%20table
or here:
https://coefficient.io/guide-to-using-pivot-tables-in-google-sheets?ref=quuu


text:
Q: Grouping Instances/ Symbols Together so I am working on a game where if you touch one side of a box, you'll be propelled in that direction.
* For example: Let's say I hit the left side of the box, I should be propelled to the left.
One way I could do this, is split the box into 4 instances where each instance is on the left, right, top & bottom sides.
Is there a way for me to embed instances/ access parts of an instance, etc.
OR if there is a better way to do this can you tell me how?

A: I guess the answer to your question is yes; what you want to do is have a single container MovieClip with 4 internal MovieClips that will be your hit targets.
I would go for the following setup; i.e. use triangles.
------------
|\   top  /|
| \      / |
|  \    /  |
|   \  /  r|
|left\/   i|
|    /\   g|
|   /  \  h|
|  /    \ t|
| /      \ |
|/ bottom \|
------------

if you were to do it based on coordinates, as Adam Harte mentioned, handle it like a 9-slice grid. if you imagine the centre box oversized, that will give you maximum hit areas.
-----------------
|   |       |   |
|   |   T   |   |
-----------------
|   |       |   |
| L |       | R |
|   |       |   |
-----------------
|   |   B   |   |
|   |       |   |
-----------------

A: You could just test the x and y position of the touch inside the the box when they touch it. Something like this pseudocode:
function onTouchDown(){
    if(touchX < halfBoxWidth)
    {
        // We touched the left side, so go left.
    }
    else
    {
        // We touched the right side, so go right.
    }
}


text:
Q: How to validate formulas easily in Excel 2003? When reviewing Excel spreadsheets done by others, I have to do the work of validating all formulas contained in the workbook.
It's a frustrating, time-consuming process to trace the quoted cells, sometimes even in different sheets. I know Ctrl-[ will only get back to one of the cells, if the formula contains several cells, i.e. =A1*sheet1!B6.
Is there a way to trace quickly back to all of them?


text:
Q: If $\dim V = n$, why does any set of $n$ linearly independent vectors span $V$? I am currently learning about vector spaces, spaning and dimensions for the first time and am reading old posts on here. I came across this one: If $\dim(V) = n$, is every spaning set $\{v_1,v_2,\ldots,v_n\}$ a basis for $V$?
In it, it is mentioned that "If $\dim V = n$, then any set of $n$  linearly independent vectors will span $V$". I understand that any spanning set of $n$ vectors must consist of linearly independent vectors due to $\dim V = n$ but I don't quite get the other direction.
Could someone help me understand this better?

A: Every linear independent family can be extended to a basis. By definition of $\dim$, this basis still has $n$ members, i.e., we did not really extend our family and already had a basis.

A: The dimension is defined as the cardinality of a maximal linearly independent set, or the minimal generating set. These two are shown to be the same in any textbook. We say basis to refer to these sets; being both maximal linearly independent and minimal generating sets.
So a set of $\dim V$ linearly independent vectors is a basis basically by definition

A: Let $\{v_1,\ldots,v_r\}\subset V$ be a set of $r$ linearly independent vectors, and let $\{w_1,\ldots,w_n\}$ be a basis for $V$. Then there exist $\alpha_{ij}$ with $i\in\{1,\ldots,r\}$ and $j\in\{1,\ldots,n\}$ such that $v_i=\sum_{j=1}^n \alpha_{ij}w_j$. Consider the system of equations: $$\sum_{i=1}^r \alpha_{ij} x_i=0, \ j\in\{1,\ldots,n\}$$
Let $(x_1,\ldots,x_n)$ be a solution. Then $$\sum_{i=1}^r x_i v_i=\sum_{i=1}^r\sum_{j=1}^n\alpha_{ij}x_i w_j=\sum_{j=1}^n\left(\sum_{i=1}^r\alpha_{ij}x_i\right)w_j=\sum_{j=1}^n 0\cdot w_j=0$$
$\{v_1,\ldots,v_r\}$ is linearly independent, so it must be $(x_1,\ldots,x_n)=0$. Hence, the previous system of equations either has unique solution or hasn't solution at all. Anyways, this means that it must have at least as many equations as variables, i.e. $r\leq n$.
Then, any linearly independent set must have, at most, $n$ vectors. Let now $\{v_1,\ldots,v_n\}$ be a linearly independent set and let's prove it must span $V$. Assume it doesn't, and take $v\in V\setminus\operatorname{Span}(v_1,\ldots,v_n)$. Then $\{v,v_1,\ldots,v_n\}$ is a linearly independent set with $n+1$ elements; a contradiction. Hence $\{v_1,\ldots,v_n\}$ spans $V$ so it's a basis.

A: Assume that V is a vector space and that you have n linearly independent vectors from it. The dimension of the sub space spanned by the n vectors is n. However since dim V =n, this must be V itself.