text:
Q: Click image to launch HTML5 Video in a next window I have some html5 video that I want to use on my website. However I want to launch or start the video in a new window after you click an image link, of course I want the video to have controls and such in the new window. How can this be done? The code I am currently using is below.
<video id=0 controls width=640 height=360>
<source src="Kingz Of Da City.ogv" type='video/ogg; codecs="theora, vorbis"'/>
<source src="Kingz Of Da City.webm" type='video/webm' >
<source src="Kingz Of Da City.mp4" type='video/mp4'>

Video is not visible, most likely your browser does not support HTML5 video

</video>

A: What you need is Sandwich page markup method
To strat with you need to create some php pages, such as head.php, player.php, body.php and those landing page for an example page1.php, page2.php  e.t.c
inside your head.php write this:
<?php if(isset($_REQUEST['v'])){
$video=$_REQUEST['v'];}
?>

inside your player.php write this:
<video id=0 controls width=640 height=360>
<source src="mediaFolder/<?php echo $video ?>.ogv" type='video/ogg; codecs="theora, vorbis"'/>
<source src="mediaFolder/<?php echo $video ?>.webm" type='video/webm' >
<source src="mediaFolder/<?php echo $video ?>.mp4" type='video/mp4'>

Video is not visible, most likely your browser does not support HTML5 video

</video>

inside your body.php or any where you want to use your link-out write this:

Save all created pages in your root directory.
Next>>>>>>>>
This is your sandwich  template (with the burger) this will go into each blank page such as that of home page, page1, page2 and page3

  <?php include('head.php'); ?>

    <?php include('player.php'); ?>

  <?php include('body.php'); ?>

  <?php include('footer.php'); ?>

What then happen is that whenever any of these images are clicked it send a signal to the head.php telling him the video name>> head received the signal and report>> to player.php (echo out the video name), HTML5 player triggers and play the video.
The sample  template above  is the basic of any CMS on the web . Such as that of YouTube (where you have something like: https://www.youtube.com/watch?v=xEsTd_a3WLQ ), WordPress, Twitter , Facebook name them.
I think we are done


text:
Q: position:fixed "hitboxes" move up in iOS 10 Safari on Plus-sized phones when tab bar is shown I have a div that acts as an overlay; I'm using position: fixed to accomplish this. In the overlay, I have a button. Normally, this works perfectly, but we've discovered a very strange bug that appears to be within Safari in iOS 10 on Plus-sized iPhones.

    <input type="button" value="Input Button" />
    <button>Button</button>

  This is the regular div. This is the regular div.

This is the regular div. This is the regular div.

This is the regular div. This is the regular div.

This is the regular div. This is the regular div.

This is the regular div. This is the regular div.

This is the regular div. This is the regular div.

This is the regular div. This is the regular div.

This is the regular div. This is the regular div.

This is the regular div. This is the regular div.

This is the regular div. This is the regular div.

This is the regular div. This is the regular div.

This is the regular div. This is the regular div.

This is the regular div. This is the regular div.

This is the regular div. This is the regular div.

This is the regular div. This is the regular div.

This is the regular div. This is the regular div.

This is the regular div. This is the regular div.

This is the regular div. This is the regular div.

This is the regular div. This is the regular div.

This is the regular div. This is the regular div.

This is the regular div. This is the regular div.

This is the regular div. This is the regular div.

This is the regular div. This is the regular div.

    <input type="button" value="Input Button" />
    <button class="pull-right">Button</button>

Steps to Reproduce

*

*Confirm that the Tab Bar in Safari is enabled.

*Open at least 2 tabs.

*In portrait mode, load the page in question, with the position: fixed div visible.

*Rotate the phone to the landscape orientation.

Safari should now show the Tab Bar at the top of the screen, under the Address Bar. But if you try to press the button, it will not do anything. Instead, you have to press above the button (more specifically, about the height of the button above the button) and Safari will act like you now pressed the button.
Clarification: The Tab Bar does not show when in portrait mode, even when the Tab Bar setting is enabled; it only shows after you rotate to landscape, which is where the DOM or some rendering of the page gets "unsynced" in Safari.
What is even more strange is that if you rotate the device back to portrait and again to landscape an additional time (after steps 1 through 4 above), the button's "hitbox" will be shifted vertically yet again, which means now you have to press above the button roughly twice the height of the button up.
This is happening on iOS 10.1.1 but I'm unsure about other versions. Confirmed on both an iPhone 7 Plus and a 6S Plus. I did find this webkit bug which appears to be closely related but possibly different.
Any ideas?

A: We had a similar issue and solved it by adding wrapper with transform:translate3d(0,0,0).
So, you'd end up with something like this:

        <input type="button" value="Input Button" />
        <button>Button</button>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Excel multiple arguments for AND function I need to check multiple cells and return TRUE if the value in all the cells is a number.
Example:
A2,A4, A5,A8,A12,A16 <p>

Currently I am writing the formula as below:
=IF(AND(ISNUMBER(A2),ISNUMBER(A4),ISNUMBER(A5),ISNUMBER(A8),ISNUMBER(A12),ISNUMBER(A16)),"All Numbers","Some not numbers")

Is there someway to write the formula with only one ISNUMBER function to which an array of cells are passed?

A: If the cells you want to check are in a contiguous array you can use an array formula with the isnumber function:
=ISNUMBER(A2:A5) and then press ctrl+shift+enter instead of just enter. When you then look at the cell the formula should be enclosed by curly braces like {=ISNUMBER(A2:A5)}
If the cells are not in a contiguous array this will not work, however

A: If the numbers will only ever be non-zero and positive:
=IF(INDEX(FREQUENCY((A2,A4,A5,A8,A12,A16),0),2)=COUNTA(A2,A4,A5,A8,A12,A16),"All Numbers","Some not numbers")

Otherwise:
=IF(SUM(COUNTIF(INDIRECT({"A2","A4","A5","A8","A12","A16"}),{">=0";"<0"}))=COUNTA(INDIRECT({"A2","A4","A5","A8","A12","A16"})),"All Numbers","Some not numbers")

If the range of cells over which you are performing this check is fixed, and not dynamic, then we can shorten these to:
=IF(INDEX(FREQUENCY((A2,A4,A5,A8,A12,A16),0),2)=6,"All Numbers","Some not numbers")

or:
=IF(SUM(COUNTIF(INDIRECT({"A2","A4","A5","A8","A12","A16"}),{">=0";"<0"}))=6,"All Numbers","Some not numbers")

Regards

A: well, to be frank.. since you want them to input number on those cells, why don't you just use data validation? (can be found on DATA tab > Data Validation). Choose decimal and you can even set the range of minimum to maximum value. I personally think that this is a sounder solution to your case, since the users will not be able to enter values besides number.

A: COUNT function only counts numbers (not text or error values or logical values or blanks), so this formula will give the same result as your current formula with multiple ISNUMBER functions
=IF(COUNT(A2,A4,A5,A8,A12,A16)=6,"All Numbers","Some not numbers")


text:
Q: Delete Matching Elements in two Arrays - Python def array_diff(a, b):
    b_index=0
    while b_index < len(b):
        for x in range(len(a)):
            if b[b_index]=a[x]:
                del a[x]
        b_index+=1
    print(a)

array_diff([1,2,3,4,5,6,6,7],[1,3,6])

causes a runtime error because i am mutating the container while still iterating over it
what exactly will be the best practice to delete the matching items and return the list without the items
Initial List [1,2,3,4,5,6,6,7]
Final List [2,4,5,7]

A: Here is how you can return the result in a new list:
elements = [1, 2, 3, 4, 5, 6, 6, 7]
exclude = [1, 3, 6]
result = [e for e in elements if e not in exclude]
# result == [2, 4, 5, 7]


text:
Q: Big O, how do you calculate/approximate it? Most people with a degree in CS will certainly know what Big O stands for.
It helps us to measure how well an algorithm scales.
But I'm curious, how do you calculate or approximate the complexity of your algorithms?

A: Less useful generally, I think, but for the sake of completeness there is also a Big Omega Ω, which defines a lower-bound on an algorithm's complexity, and a Big Theta Θ, which defines both an upper and lower bound.

A: Big O notation is useful because it's easy to work with and hides unnecessary complications and details (for some definition of unnecessary). One nice way of working out the complexity of divide and conquer algorithms is the tree method. Let's say you have a version of quicksort with the median procedure, so you split the array into perfectly balanced subarrays every time.
Now build a tree corresponding to all the arrays you work with. At the root you have the original array, the root has two children which are the subarrays. Repeat this until you have single element arrays at the bottom.
Since we can find the median in O(n) time and split the array in two parts in O(n) time, the work done at each node is O(k) where k is the size of the array. Each level of the tree contains (at most) the entire array so the work per level is O(n) (the sizes of the subarrays add up to n, and since we have O(k) per level we can add this up). There are only log(n) levels in the tree since each time we halve the input.
Therefore we can upper bound the amount of work by O(n*log(n)).
However, Big O hides some details which we sometimes can't ignore. Consider computing the Fibonacci sequence with
a=0;
b=1;
for (i = 0; i <n; i++) {
    tmp = b;
    b = a + b;
    a = tmp;
}

and lets just assume the a and b are BigIntegers in Java or something that can handle arbitrarily large numbers. Most people would say this is an O(n) algorithm without flinching. The reasoning is that you have n iterations in the for loop and O(1) work in side the loop.
But Fibonacci numbers are large, the n-th Fibonacci number is exponential in n so just storing it will take on the order of n bytes. Performing addition with big integers will take O(n) amount of work. So the total amount of work done in this procedure is
1 + 2 + 3 + ... + n = n(n-1)/2 = O(n^2)
So this algorithm runs in quadradic time!

A: Familiarity with the algorithms/data structures I use and/or quick glance analysis of iteration nesting.  The difficulty is when you call a library function, possibly multiple times - you can often be unsure of whether you are calling the function unnecessarily at times or what implementation they are using.  Maybe library functions should have a complexity/efficiency measure, whether that be Big O or some other metric, that is available in documentation or even IntelliSense.

A: Break down the algorithm into pieces you know the big O notation for, and combine through big O operators. That's the only way I know of.
For more information, check the Wikipedia page on the subject.

A: As to "how do you calculate" Big O, this is part of Computational complexity theory. For some (many) special cases you may be able to come with some simple heuristics (like multiplying loop counts for nested loops), esp. when all you want is any upper bound estimation, and you do not mind if it is too pessimistic - which I guess is probably what your question is about.
If you really want to answer your question for any algorithm the best you can do is to apply the theory. Besides of simplistic "worst case" analysis I have found Amortized analysis very useful in practice.

A: For the 1st case, the inner loop is executed n-i times, so the total number of executions is the sum for i going from 0 to n-1 (because lower than, not lower than or equal) of the n-i. You get finally n*(n + 1) / 2, so O(n²/2) = O(n²).
For the 2nd loop, i is between 0 and n included for the outer loop; then the inner loop is executed when j is strictly greater than n, which is then impossible.

A: I would like to explain the Big-O in a little bit different aspect.
Big-O is just to compare the complexity of the programs which means how fast are they growing when the inputs are increasing and not the exact time which is spend to do the action.
IMHO in the big-O formulas you better not to use more complex equations (you might just stick to the ones in the following graph.) However you still might use other more precise formula (like 3^n, n^3, ...) but more than that can be sometimes misleading! So better to keep it as simple as possible.

I would like to emphasize once again that here we don't want to get an exact formula for our algorithm. We only want to show how it grows when the inputs are growing and compare with the other algorithms in that sense. Otherwise you would better use different methods like bench-marking.

A: Small reminder: the big O notation is used to denote asymptotic complexity (that is, when the size of the problem grows to infinity), and it hides a constant.
This means that between an algorithm in O(n) and one in O(n2), the fastest is not always the first one (though there always exists a value of n such that for problems of size >n, the first algorithm is the fastest).
Note that the hidden constant very much depends on the implementation!
Also, in some cases, the runtime is not a deterministic function of the size n of the input. Take sorting using quick sort for example: the time needed to sort an array of n elements is not a constant but depends on the starting configuration of the array.
There are different time complexities:

*

*Worst case (usually the simplest to figure out, though not always very meaningful)

*Average case (usually much harder to figure out...)

*...
A good introduction is An Introduction to the Analysis of Algorithms by R. Sedgewick and P. Flajolet.
As you say, premature optimisation is the root of all evil, and (if possible) profiling really should always be used when optimising code. It can even help you determine the complexity of your algorithms.

A: In addition to using the master method (or one of its specializations), I test my algorithms experimentally.  This can't prove that any particular complexity class is achieved, but it can provide reassurance that the mathematical analysis is appropriate.  To help with this reassurance, I use code coverage tools in conjunction with my experiments, to ensure that I'm exercising all the cases.
As a very simple example say you wanted to do a sanity check on the speed of the .NET framework's list sort.  You could write something like the following, then analyze the results in Excel to make sure they did not exceed an n*log(n) curve.
In this example I measure the number of comparisons, but it's also prudent to examine the actual time required for each sample size.  However then you must be even more careful that you are just measuring the algorithm and not including artifacts from your test infrastructure.
int nCmp = 0;
System.Random rnd = new System.Random();

// measure the time required to sort a list of n integers
void DoTest(int n)
{
   List<int> lst = new List<int>(n);
   for( int i=0; i<n; i++ )
      lst[i] = rnd.Next(0,1000);

   // as we sort, keep track of the number of comparisons performed!
   nCmp = 0;
   lst.Sort( delegate( int a, int b ) { nCmp++; return (a<b)?-1:((a>b)?1:0)); }

   System.Console.Writeline( "{0},{1}", n, nCmp );
}

// Perform measurement for a variety of sample sizes.
// It would be prudent to check multiple random samples of each size, but this is OK for a quick sanity check
for( int n = 0; n<1000; n++ )
   DoTest(n);

A: Don't forget to also allow for space complexities that can also be a cause for concern if one has limited memory resources.  So for example you may hear someone wanting a constant space algorithm which is basically a way of saying that the amount of space taken by the algorithm doesn't depend on any factors inside the code.
Sometimes the complexity can come from how many times is something called, how often is a loop executed, how often is memory allocated, and so on is another part to answer this question.
Lastly, big O can be used for worst case, best case, and amortization cases where generally it is the worst case that is used for describing how bad an algorithm may be.

A: First of all, the accepted answer is trying to explain nice fancy stuff,
but I think, intentionally complicating Big-Oh is not the solution,
which programmers (or at least, people like me) search for.
Big Oh (in short)
function f(text) {
  var n = text.length;
  for (var i = 0; i < n; i++) {
    f(text.slice(0, n-1))
  }
  // ... other JS logic here, which we can ignore ...
}

Big Oh of above is f(n) = O(n!) where n represents number of items in input set,
and f represents operation done per item.

Big-Oh notation is the asymptotic upper-bound of the complexity of an algorithm.
In programming: The assumed worst-case time taken,
or assumed maximum repeat count of logic, for size of the input.
Calculation
Keep in mind (from above meaning) that; We just need worst-case time and/or maximum repeat count affected by N (size of input),
Then take another look at (accepted answer's) example:
for (i = 0; i < 2*n; i += 2) {  // line 123
    for (j=n; j > i; j--) {     // line 124
        foo();                  // line 125
    }
}

*

*Begin with this search-pattern:

*

*Find first line that N caused repeat behavior,

*Or caused increase of logic executed,

*But constant or not, ignore anything before that line.

*Seems line hundred-twenty-three is what we are searching ;-)

*

*On first sight, line seems to have 2*n max-looping.

*But looking again, we see i += 2 (and that half is skipped).

*So, max repeat is simply n, write it down, like f(n) = O( n  but don't close parenthesis yet.

*Repeat search till method's end, and find next line matching our search-pattern, here that's line 124

*

*Which is tricky, because strange condition, and reverse looping.

*But after remembering that we just need to consider maximum repeat count (or worst-case time taken).

*It's as easy as saying "Reverse-Loop j starts with j=n, am I right? yes, n seems to be maximum possible repeat count", so:

*

*Add n to previous write down's end,

*but like "( n "  instead of "+ n" (as this is inside previous loop),

*and close parenthesis only if we find something outside of previous loop.

Search Done! why? because line 125 (or any other line after) does not match our search-pattern.
We can now close any parenthesis (left-open in our write down), resulting in below:
f(n) = O( n( n ) )

Try to further shorten "n( n )" part, like:

*

*n( n ) = n * n

*= n2

*Finally, just wrap it with Big Oh notation, like O(n2) or O(n^2) without formatting.

A: Seeing the answers here I think we can conclude that most of us do indeed approximate the order of the algorithm by looking at it and use common sense instead of calculating it with, for example, the master method as we were thought at university.
With that said I must add that even the professor encouraged us (later on) to actually think about it instead of just calculating it.
Also I would like to add how it is done for recursive functions:
suppose we have a function like (scheme code):
(define (fac n)
    (if (= n 0)
        1
            (* n (fac (- n 1)))))

which recursively calculates the factorial of the given number.
The first step is to try and determine the performance characteristic for the body of the function only in this case, nothing special is done in the body, just a multiplication (or the return of the value 1).
So the performance for the body is: O(1) (constant).
Next try and determine this for the number of recursive calls. In this case we have n-1 recursive calls.
So the performance for the recursive calls is: O(n-1) (order is n, as we throw away the insignificant parts).
Then put those two together and you then have the performance for the whole recursive function:
1 * (n-1) = O(n)

Peter, to answer your raised issues; the method I describe here actually handles this quite well. But keep in mind that this is still an approximation and not a full mathematically correct answer. The method described here is also one of the methods we were taught at university, and if I remember correctly was used for far more advanced algorithms than the factorial I used in this example.
Of course it all depends on how well you can estimate the running time of the body of the function and the number of recursive calls, but that is just as true for the other methods.

A: What often gets overlooked is the expected behavior of your algorithms. It doesn't change the Big-O of your algorithm, but it does relate to the statement "premature optimization. . .."
Expected behavior of your algorithm is -- very dumbed down -- how fast you can expect your algorithm to work on data you're most likely to see.
For instance, if you're searching for a value in a list, it's O(n), but if you know that most lists you see have your value up front, typical behavior of your algorithm is faster.
To really nail it down, you need to be able to describe the probability distribution of your "input space" (if you need to sort a list, how often is that list already going to be sorted? how often is it totally reversed? how often is it mostly sorted?) It's not always feasible that you know that, but sometimes you do.

A: great question!
Disclaimer: this answer contains false statements see the comments below.
If you're using the Big O, you're talking about the worse case (more on what that means later). Additionally, there is capital theta for average case and a big omega for best case.
Check out this site for a lovely formal definition of Big O: https://xlinux.nist.gov/dads/HTML/bigOnotation.html

f(n) = O(g(n)) means there are positive constants c and k, such that 0 ≤ f(n) ≤ cg(n) for all n ≥ k. The values of c and k must be fixed for the function f and must not depend on n.

Ok, so now what do we mean by "best-case" and "worst-case" complexities?
This is probably most clearly illustrated through examples. For example if we are using linear search to find a number in a sorted array then the worst case is when we decide to search for the last element of the array as this would take as many steps as there are items in the array. The best case would be when we search for the first element since we would be done after the first check.
The point of all these adjective-case complexities is that we're looking for a way to graph the amount of time a hypothetical program runs to completion in terms of the size of particular variables. However for many algorithms you can argue that there is not a single time for a particular size of input. Notice that this contradicts with the fundamental requirement of a function, any input should have no more than one output. So we come up with multiple functions to describe an algorithm's complexity. Now, even though searching an array of size n may take varying amounts of time depending on what you're looking for in the array and depending proportionally to n, we can create an informative description of the algorithm using best-case, average-case, and worst-case classes.
Sorry this is so poorly written and lacks much technical information. But hopefully it'll make time complexity classes easier to think about. Once you become comfortable with these it becomes a simple matter of parsing through your program and looking for things like for-loops that depend on array sizes and reasoning based on your data structures what kind of input would result in trivial cases and what input would result in worst-cases.

A: If your cost is a polynomial, just keep the highest-order term, without its multiplier. E.g.:

O((n/2 + 1)*(n/2)) = O(n2/4 + n/2) = O(n2/4) = O(n2)

This doesn't work for infinite series, mind you. There is no single recipe for the general case, though for some common cases, the following inequalities apply:

O(log N) < O(N) < O(N log N) < O(N2) < O(Nk) < O(en) < O(n!)

A: I think about it in terms of information. Any problem consists of learning a certain number of bits.
Your basic tool is the concept of decision points and their entropy. The entropy of a decision point is the average information it will give you. For example, if a program contains a decision point with two branches, it's entropy is the sum of the probability of each branch times the log2 of the inverse probability of that branch. That's how much you learn by executing that decision.
For example, an if statement having two branches, both equally likely, has an entropy of 1/2 * log(2/1) + 1/2 * log(2/1) = 1/2 * 1 + 1/2 * 1 = 1. So its entropy is 1 bit.
Suppose you are searching a table of N items, like N=1024. That is a 10-bit problem because log(1024) = 10 bits. So if you can search it with IF statements that have equally likely outcomes, it should take 10 decisions.
That's what you get with binary search.
Suppose you are doing linear search. You look at the first element and ask if it's the one you want. The probabilities are 1/1024 that it is, and 1023/1024 that it isn't. The entropy of that decision is 1/1024*log(1024/1) + 1023/1024 * log(1024/1023) = 1/1024 * 10 + 1023/1024 * about 0 = about .01 bit. You've learned very little! The second decision isn't much better. That is why linear search is so slow. In fact it's exponential in the number of bits you need to learn.
Suppose you are doing indexing. Suppose the table is pre-sorted into a lot of bins, and you use some of all of the bits in the key to index directly to the table entry. If there are 1024 bins, the entropy is 1/1024 * log(1024) + 1/1024 * log(1024) + ... for all 1024 possible outcomes. This is 1/1024 * 10 times 1024 outcomes, or 10 bits of entropy for that one indexing operation. That is why indexing search is fast.
Now think about sorting.  You have N items, and you have a list. For each item, you have to search for where the item goes in the list, and then add it to the list. So sorting takes roughly N times the number of steps of the underlying search.
So sorts based on binary decisions having roughly equally likely outcomes all take about O(N log N) steps. An O(N) sort algorithm is possible if it is based on indexing search.
I've found that nearly all algorithmic performance issues can be looked at in this way.

A: Lets start from the beginning.
First of all, accept the principle that certain simple operations on data can be done in O(1) time, that is, in time that is independent of the size of the input. These primitive operations in C consist of

*

*Arithmetic operations (e.g. + or %).

*Logical operations (e.g., &&).

*Comparison operations (e.g., <=).

*Structure accessing operations (e.g. array-indexing like A[i], or pointer fol-
lowing with the -> operator).

*Simple assignment such as copying a value into a variable.

*Calls to library functions (e.g., scanf, printf).

The justification for this principle requires a detailed study of the machine instructions (primitive steps) of a typical computer. Each of the described operations can be done with some small number of machine instructions; often only one or two instructions are needed.
As a consequence, several kinds of statements in C can be executed in O(1) time, that is, in some constant amount of time independent of input. These simple include

*

*Assignment statements that do not involve function calls in their expressions.

*Read statements.

*Write statements that do not require function calls to evaluate arguments.

*The jump statements break, continue, goto, and return expression, where
expression does not contain a function call.

In C, many for-loops are formed by initializing an index variable to some value and
incrementing that variable by 1 each time around the loop. The for-loop ends when
the index reaches some limit. For instance, the for-loop
for (i = 0; i < n-1; i++)
{
    small = i;
    for (j = i+1; j < n; j++)
        if (A[j] < A[small])
            small = j;
    temp = A[small];
    A[small] = A[i];
    A[i] = temp;
}

uses index variable i. It increments i by 1 each time around the loop, and the iterations
stop when i reaches n − 1.
However, for the moment, focus on the simple form of for-loop, where the difference between the final and initial values, divided by the amount by which the index variable is incremented tells us how many times we go around the loop. That count is exact, unless there are ways to exit the loop via a jump statement; it is an upper bound on the number of iterations in any case.
For instance, the for-loop iterates ((n − 1) − 0)/1 = n − 1 times,
since 0 is the initial value of i, n − 1 is the highest value reached by i (i.e., when i
reaches n−1, the loop stops and no iteration occurs with i = n−1), and 1 is added
to i at each iteration of the loop.
In the simplest case, where the time spent in the loop body is the same for each
iteration, we can multiply the big-oh upper bound for the body by the number of
times around the loop. Strictly speaking, we must then add O(1) time to initialize
the loop index and O(1) time for the first comparison of the loop index with the
limit, because we test one more time than we go around the loop. However, unless
it is possible to execute the loop zero times, the time to initialize the loop and test
the limit once is a low-order term that can be dropped by the summation rule.

Now consider this example:
(1) for (j = 0; j < n; j++)
(2)   A[i][j] = 0;

We know that line (1) takes O(1) time. Clearly, we go around the loop n times, as
we can determine by subtracting the lower limit from the upper limit found on line
(1) and then adding 1. Since the body, line (2), takes O(1) time, we can neglect the
time to increment j and the time to compare j with n, both of which are also O(1).
Thus, the running time of lines (1) and (2) is the product of n and O(1), which is O(n).
Similarly, we can bound the running time of the outer loop consisting of lines
(2) through (4), which is
(2) for (i = 0; i < n; i++)
(3)     for (j = 0; j < n; j++)
(4)         A[i][j] = 0;

We have already established that the loop of lines (3) and (4) takes O(n) time.
Thus, we can neglect the O(1) time to increment i and to test whether i < n in
each iteration, concluding that each iteration of the outer loop takes O(n) time.
The initialization i = 0 of the outer loop and the (n + 1)st test of the condition
i < n likewise take O(1) time and can be neglected. Finally, we observe that we go
around the outer loop n times, taking O(n) time for each iteration, giving a total
O(n^2) running time.

A more practical example.

A: Big O gives the upper bound for time complexity of an algorithm.  It is usually used in conjunction with processing data sets (lists) but can be used elsewhere.
A few examples of how it's used in C code.
Say we have an array of n elements
int array[n];

If we wanted to access the first element of the array this would be O(1) since it doesn't matter how big the array is, it always takes the same constant time to get the first item.
x = array[0];

If we wanted to find a number in the list:
for(int i = 0; i < n; i++){
    if(array[i] == numToFind){ return i; }
}

This would be O(n) since at most we would have to look through the entire list to find our number.  The Big-O is still O(n) even though we might find our number the first try and run through the loop once because Big-O describes the upper bound for an algorithm (omega is for lower bound and theta is for tight bound).
When we get to nested loops:
for(int i = 0; i < n; i++){
    for(int j = i; j < n; j++){
        array[j] += 2;
    }
}

This is O(n^2) since for each pass of the outer loop ( O(n) ) we have to go through the entire list again so the n's multiply leaving us with n squared.
This is barely scratching the surface but when you get to analyzing more complex algorithms complex math involving proofs comes into play.  Hope this familiarizes you with the basics at least though.

A: For code A, the outer loop will execute for n+1 times, the '1' time means the process which checks the whether i still meets the requirement. And inner loop runs n times, n-2 times.... Thus,0+2+..+(n-2)+n= (0+n)(n+1)/2= O(n²).
For code B, though inner loop wouldn't step in and execute the foo(), the inner loop will be executed for n times depend on outer loop execution time, which is O(n)

A: I don't know how to programmatically solve this, but the first thing people do is that we sample the algorithm for certain patterns in the number of operations done, say 4n^2 + 2n + 1 we have 2 rules:

*

*If we have a sum of terms, the term with the largest growth rate is kept, with other terms omitted.

*If we have a product of several factors constant factors are omitted.

 If we simplify f(x), where f(x) is the formula for number of operations done, (4n^2 + 2n + 1 explained above), we obtain the big-O value [O(n^2) in this case]. But this would have to account for Lagrange interpolation in the program, which may be hard to implement. And what if the real big-O value was O(2^n), and we might have something like O(x^n), so this algorithm probably wouldn't be programmable. But if someone proves me wrong, give me the code . . . .

A: If you want to estimate the order of your code empirically rather than by analyzing the code, you could stick in a series of increasing values of n and time your code.  Plot your timings on a log scale.  If the code is O(x^n), the values should fall on a line of slope n.
This has several advantages over just studying the code.  For one thing, you can see whether you're in the range where the run time approaches its asymptotic order. Also, you may find that some code that you thought was order O(x) is really order O(x^2), for example, because of time spent in library calls.

A: I'll do my best to explain it here on simple terms, but be warned that this topic takes my students a couple of months to finally grasp. You can find more information on the Chapter 2 of the Data Structures and Algorithms in Java book.

There is no mechanical procedure that can be used to get the BigOh.
As a "cookbook", to obtain the BigOh from a piece of code you first need to realize that you are creating a math formula to count how many steps of computations get executed given an input of some size.
The purpose is simple: to compare algorithms from a theoretical point of view, without the need to execute the code. The lesser the number of steps, the faster the algorithm.
For example, let's say you have this piece of code:
int sum(int* data, int N) {
    int result = 0;               // 1

    for (int i = 0; i < N; i++) { // 2
        result += data[i];        // 3
    }

    return result;                // 4
}

This function returns the sum of all the elements of the array, and we want to create a formula to count the computational complexity of that function:
Number_Of_Steps = f(N)

So we have f(N), a function to count the number of computational steps. The input of the function is the size of the structure to process. It means that this function is called such as:
Number_Of_Steps = f(data.length)

The parameter N takes the data.length value. Now we need the actual definition of the function f(). This is done from the source code, in which each interesting line is numbered from 1 to 4.
There are many ways to calculate the BigOh. From this point forward we are going to assume that every sentence that doesn't depend on the size of the input data takes a constant C number computational steps.
We are going to add the individual number of steps of the function, and neither the local variable declaration nor the return statement depends on the size of the data array.
That means that lines 1 and 4 takes C amount of steps each, and the function is somewhat like this:
f(N) = C + ??? + C

The next part is to define the value of the for statement. Remember that we are counting the number of computational steps, meaning that the body of the for statement gets executed N times. That's the same as adding C, N times:
f(N) = C + (C + C + ... + C) + C = C + N * C + C

There is no mechanical rule to count how many times the body of the for gets executed, you need to count it by looking at what does the code do. To simplify the calculations, we are ignoring the variable initialization, condition and increment parts of the for statement.
To get the actual BigOh we need the Asymptotic analysis of the function. This is roughly done like this:

*

*Take away all the constants C.

*From f() get the polynomium in its standard form.

*Divide the terms of the polynomium and sort them by the rate of growth.

*Keep the one that grows bigger when N approaches infinity.

Our f() has two terms:
f(N) = 2 * C * N ^ 0 + 1 * C * N ^ 1

Taking away all the C constants and redundant parts:
f(N) = 1 + N ^ 1

Since the last term is the one which grows bigger when f() approaches infinity (think on limits) this is the BigOh argument, and the sum() function has a BigOh of:
O(N)

There are a few tricks to solve some tricky ones: use summations whenever you can.
As an example, this code can be easily solved using summations:
for (i = 0; i < 2*n; i += 2) {  // 1
    for (j=n; j > i; j--) {     // 2
        foo();                  // 3
    }
}

The first thing you needed to be asked is the order of execution of foo(). While the usual is to be O(1), you need to ask your professors about it. O(1) means (almost, mostly) constant C, independent of the size N.
The for statement on the sentence number one is tricky. While the index ends at 2 * N, the increment is done by two. That means that the first for gets executed only N steps, and we need to divide the count by two.
f(N) = Summation(i from 1 to 2 * N / 2)( ... ) =
     = Summation(i from 1 to N)( ... )

The sentence number two is even trickier since it depends on the value of i. Take a look: the index i takes the values: 0, 2, 4, 6, 8, ..., 2 * N, and the second for get executed: N times the first one, N - 2 the second, N - 4 the third... up to the N / 2 stage, on which the second for never gets executed.
On formula, that means:
f(N) = Summation(i from 1 to N)( Summation(j = ???)(  ) )

Again, we are counting the number of steps. And by definition, every summation should always start at one, and end at a number bigger-or-equal than one.
f(N) = Summation(i from 1 to N)( Summation(j = 1 to (N - (i - 1) * 2)( C ) )

(We are assuming that foo() is O(1) and takes C steps.)
We have a problem here: when i takes the value N / 2 + 1 upwards, the inner Summation ends at a negative number! That's impossible and wrong. We need to split the summation in two, being the pivotal point the moment i takes N / 2 + 1.
f(N) = Summation(i from 1 to N / 2)( Summation(j = 1 to (N - (i - 1) * 2)) * ( C ) ) + Summation(i from 1 to N / 2) * ( C )

Since the pivotal moment i > N / 2, the inner for won't get executed, and we are assuming a constant C execution complexity on its body.
Now the summations can be simplified using some identity rules:

*

*Summation(w from 1 to N)( C ) = N * C

*Summation(w from 1 to N)( A (+/-) B ) = Summation(w from 1 to N)( A ) (+/-) Summation(w from 1 to N)( B )

*Summation(w from 1 to N)( w * C ) = C * Summation(w from 1 to N)( w ) (C is a constant, independent of w)

*Summation(w from 1 to N)( w ) = (N * (N + 1)) / 2

Applying some algebra:
f(N) = Summation(i from 1 to N / 2)( (N - (i - 1) * 2) * ( C ) ) + (N / 2)( C )

f(N) = C * Summation(i from 1 to N / 2)( (N - (i - 1) * 2)) + (N / 2)( C )

f(N) = C * (Summation(i from 1 to N / 2)( N ) - Summation(i from 1 to N / 2)( (i - 1) * 2)) + (N / 2)( C )

f(N) = C * (( N ^ 2 / 2 ) - 2 * Summation(i from 1 to N / 2)( i - 1 )) + (N / 2)( C )

=> Summation(i from 1 to N / 2)( i - 1 ) = Summation(i from 1 to N / 2 - 1)( i )

f(N) = C * (( N ^ 2 / 2 ) - 2 * Summation(i from 1 to N / 2 - 1)( i )) + (N / 2)( C )

f(N) = C * (( N ^ 2 / 2 ) - 2 * ( (N / 2 - 1) * (N / 2 - 1 + 1) / 2) ) + (N / 2)( C )

=> (N / 2 - 1) * (N / 2 - 1 + 1) / 2 =

   (N / 2 - 1) * (N / 2) / 2 =

   ((N ^ 2 / 4) - (N / 2)) / 2 =

   (N ^ 2 / 8) - (N / 4)

f(N) = C * (( N ^ 2 / 2 ) - 2 * ( (N ^ 2 / 8) - (N / 4) )) + (N / 2)( C )

f(N) = C * (( N ^ 2 / 2 ) - ( (N ^ 2 / 4) - (N / 2) )) + (N / 2)( C )

f(N) = C * (( N ^ 2 / 2 ) - (N ^ 2 / 4) + (N / 2)) + (N / 2)( C )

f(N) = C * ( N ^ 2 / 4 ) + C * (N / 2) + C * (N / 2)

f(N) = C * ( N ^ 2 / 4 ) + 2 * C * (N / 2)

f(N) = C * ( N ^ 2 / 4 ) + C * N

f(N) = C * 1/4 * N ^ 2 + C * N

And the BigOh is:
O(N²)

A: Basically the thing that crops up 90% of the time is just analyzing loops.  Do you have single, double, triple nested loops?  The you have O(n), O(n^2), O(n^3) running time.
Very rarely (unless you are writing a platform with an extensive base library (like for instance, the .NET BCL, or C++'s STL) you will encounter anything that is more difficult than just looking at your loops (for statements, while, goto, etc...)

A: While knowing how to figure out the Big O time for your particular problem is useful, knowing some general cases can go a long way in helping you make decisions in your algorithm.
Here are some of the most common cases, lifted from http://en.wikipedia.org/wiki/Big_O_notation#Orders_of_common_functions:
O(1) - Determining if a number is even or odd; using a constant-size lookup table or hash table
O(logn) - Finding an item in a sorted array with a binary search
O(n) - Finding an item in an unsorted list; adding two n-digit numbers
O(n2) - Multiplying two n-digit numbers by a simple algorithm; adding two n×n matrices; bubble sort or insertion sort
O(n3) - Multiplying two n×n matrices by simple algorithm
O(cn) - Finding the (exact) solution to the traveling salesman problem using dynamic programming; determining if two logical statements are equivalent using brute force
O(n!) - Solving the traveling salesman problem via brute-force search
O(nn) - Often used instead of O(n!) to derive simpler formulas for asymptotic complexity


text:
Q: State of the art on: "If a dynamical system is Li-Yorke chaotic, does there exist a Cantor scrambled set?" The following problem is presented in the paper Recent development of chaos theory in topological dynamics - by Jian Li and Xiangdong Ye :
"If a dynamical system [$(X,f)$, $X$ metric space, $f$ continuous] is Li-Yorke chaotic, does there exist a Cantor scrambled set?"
I would like to know the current status of the problem. Some information is given in the paper, but it's a bit old (2015).
Thanks

A: This question was answered recently by Geschke, Grebík, and Miller:
S. Geschke, J. Grebík, and B. D. Miller, "Scrambled Cantor sets," Proceedings of the AMS 149 (link to the arxiv version)
They show that if $X$ is analytic (i.e., the continuous image of a Polish space), and if $(X,f)$ is a dynamical system with Li-Yorke chaos, then $(X,f)$ contains a scrambled Cantor set.
Let me point out that some assumption on $X$ (such as "analytic") is necessary here. For example, this is easiest to see if CH fails. Why? Let $(Y,f)$ be any dynamical system with Li-Yorke chaos. This means that it contains a scrambled set of size $\aleph_1$. Let $X$ denote the closure of this set under $f$, and observe that $(X,f)$ is then a dynamical system with Li-Yorke chaos, but its cardinality is smaller than that of the Cantor space! If CH holds, one can construct such things via transfinite recursion.


text:
Q: Django Admin upload image with foreign key I have a model Product with a User and ProductImages as foreign key.
models.py
class User(AbstractBaseUser):
    ...

class ProductImages(models.Model):
    image_type = models.CharField(max_length=33,default='image_type')
    image_file = models.ImageField(
        upload_to='images/',
        null=True,
        blank=True,
        default='magickhat-profile.jpg'
    )

class Product(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    productimages = models.ForeignKey(ProductImages, on_delete=models.CASCADE)
    product_title = models.CharField(max_length=255, default='product_title')
    product_description = models.CharField(max_length=255, default='product_description')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    is_active = models.BooleanField(default=True)
    product_view = models.IntegerField(default=0)

    def __str__(self):
        return self.product_title

    def get_absolute_url(self):
        return reverse('product_change', kwargs={'pk': self.pk})

forms.py
class ProductForm(ModelForm):

    productimages = forms.ImageField()

    CHOICES_STATUS = (('Pronto', 'Pronto'),('Em obras', 'Em obras'),('Lançamento', 'Lançamento'),)
    product_status = forms.ChoiceField(choices=CHOICES_STATUS)
    product_title = forms.CharField()
    product_description = forms.CharField()

    class Meta:
        model = Product
        fields = '__all__'

admin.py
class AdminProductModel(admin.ModelAdmin):

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        return qs.filter(user_id=request.user)

kadmin.register(User, UserAdmin)
kadmin.register(Product, AdminProductModel)

But in the admin Product model the field for image is redering as select field no ImageField
My purpose is add a upload image field on django model administration.
If i use ImageField direct on Product model the field is redering ok, but i need a external table to store that image becouse is a multimage upload, so i need a foreing key.
How is the right way to that purpose.
I see other questions about that, but the majority is old versions, and is not for custom AdminSite, like me.
Django 3.2 version Class View Based
As suggested in comments i change the relationship between models like:
uptade
models.py
class Product(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    product_title = models.CharField(max_length=255, default='product_title')
    product_description = models.CharField(max_length=255, default='product_description')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    is_active = models.BooleanField(default=True)
    product_view = models.IntegerField(default=0)

    def __str__(self):
        return self.product_title

    def get_absolute_url(self):
        return reverse('product_change', kwargs={'pk': self.pk})

class ProductImages(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    image_type = models.CharField(max_length=33,default='image_type')
    image_file = models.ImageField(
        upload_to='images/',
        null=True,
        blank=True,
        default='magickhat-profile.jpg'
    )

forms.py
class ProductForm(ModelForm):

    image_file = forms.ImageField()

    CHOICES_STATUS = (('Pronto', 'Pronto'),('Em obras', 'Em obras'),('Lançamento', 'Lançamento'),)
    product_status = forms.ChoiceField(choices=CHOICES_STATUS)
    product_title = forms.CharField()
    product_description = forms.CharField()

    class Meta:
        model = Product
        fields = '__all__'

My question now is, how bring that field image_file from ProducImages to ProductForm?

A: Am guessing you want to be able to post multiple images to your database in that case you should use StackedInline to merge the two models together then you can have multiple fields in the database to upload more images. You do that through the admin.py like so:
class ProductImagesAdmin(admin.StackedInline):
       model = ProductImages

class ProductAdmin(admin.ModelAdmin):
      # The field your want to display
      list_display  = ['','']
      # Here you link the models together
      inlines = [ ProductImagesAdmin]

To upload multiple images from the frontend you will need a form to handle
class ProductImagesForm(forms.ModelForm):
      class Meta:
        model = ProductImages
        fields = ['image_file']
        widget = forms.ClearableFileInput(attrs={'multiple':True})

View to handle multiple images
def upload_product_images(request):
    form = ProductImagesForm(request.POST, request.FILES)
    files = requests.FILES.getlist['image_file']
    title = request.POST['product_title']
    description = request.POST['descritpion']
    product = Product(product_title=title,product_description=description)
    product.save()
    # You would have to make some iterations through the list images in order topost
    # them to your database
    if form.is_valid:
       for file in files:
           prod_image_data = ProductImages(product=product, image=file)
           prod_image_data.save()
    return redirect(# redirect to anywhere you)


text:
Q: Keyring no longer prompts for password when SSH-ing I remember that I used to be able to do ssh blah@foo.com and have a prompt asks me for a password to unlock the keyring for the whole GNOME session so subsequent ssh wouldn't need to enter the keyring password any longer (not quite sure if this is in Ubuntu or other distro).
But nowadays doing ssh blah@foo.com would ask me, in the terminal, my keyring password every single time; which defeats the purpose of using SSH keys.
I checked
$ cat /etc/pam.d/lightdm | grep keyring
auth    optional        pam_gnome_keyring.so
session optional        pam_gnome_keyring.so auto_start

which looks fine, and
$ pgrep keyring
1784 gnome-keyring-d

so the keyring daemon is alive.
I finally found that SSH_AUTH_SOCK variable (and GNOME_KEYRING_CONTROL and GPG_AGENT_INFO and GNOME_KEYRING_PID) are not being set properly. What is the proper way to set this variable and why aren't they being set in my environment (i.e. shouldn't they be set in default install)?
I guess I can set it in .bashrc, but then the variables would only be defined in bash session, while that is fine for ssh, I believe the other environment variables are necessary for GUI apps to use keyring.

A: I found this on the Arch wiki: https://wiki.archlinux.org/index.php/GNOME_Keyring
Basically, you run gnome-keyring-daemon -s to get your specific keyring value, then to your .bashrc, add:
SSH_AUTH_SOCK=`netstat -xl | grep -o '/run/user/yourusername/keyring-xxxxxxx.*/ssh$'`
[ -z "$SSH_AUTH_SOCK" ] || export SSH_AUTH_SOCK

This should make ssh ask you for your password through the keyring GUI.

A: I use ssh a lot, mostly between my Ubuntu workstation and another Ubuntu web server with all the websites I work on.  I once came upon the same symptoms you are having, and it turned out to be something in the way I was running the terminal.  I had created a custom shortcut to run gnome-terminal because I wanted to pass a certain command line.  But I think I had the same problem running xterm.
When I ran the terminal from the built-in shortcut (Alt-Ctrl-T), or from the menu, it worked correctly and prompted me with a GUI dialog for the password, but when I ran it from my custom shortcut, it always asked from the terminal itself, and didn't remember it.

A: I had this problem too. Appeared suddenly. Apparently caused by a saved (maybe wrong) (SFTP) login password for the same domain.
Solution
Open Password and Keys (Gnome keyring) and delete the password (was beneath Ubuntu one)

Reboot and everything was fine.
export | grep SOCK

Now returned again:
SSH_AUTH_SOCK=/run/user/yourusername/keyring-xxxxxxx.*/ssh


text:
Q: In-app billing с вариативными ценами android Гугл сам представляет возможность продавать подписки и товары по фиксированной цене в мобильных приложениях. А можно ли через какие-нибудь сервисы или библиотеки предоставлять возможность покупать не статичный контент? Например, дать возможность оплачивать доставку еды, цена которой зависит от расстояния до ресторана? Чтобы пользователь мог заплатить, например, 304,64 руб. И если есть библиотеки/сервисы, то где проводить проверку всех покупок? Писать свой бэкэнд? Интересует конкретно андроид

A: К сожалению, Google не позволит Вам продавать что-то с динамической ценой.
А, если бы и мог позволить, то Вы бы быстро от этого отказались, т.к. Google берет комиссию в размере 30% (читать здесь RU / ENG).
В качестве альтернативы Вы можете воспользоваться платежной системой STRIPE для Android.
И я Вам настоятельно рекомендую еще раз прочесть правила Google Play, чтобы в будущем не остаться без лицензии разработчика - ЧИТАТЬ ЗДЕСЬ
Выкопировка специаально по Вашему вопросу - Монетизация и реклама | Раздел "Платежи"
Желаю Вам удачи в разработке продукта и интеграции платежной системы! ;-)


text:
Q: Is there a way to copy an Excel worksheet without copying all of the cell styles in the source workbook to the target workbook? The title pretty much says it. I have an Excel document with tons of randomly named styles that I didn't create but that I want to copy a worksheet from. When I do, it drags all of those styles into my target workbook, which I don't want. None of the styles themselves are used on the actual sheet I am copying.
If I can't prevent this, is there a way to delete a bunch of styles as a group, rather than selecting each and deleting it?
This other question of mine is similar, in that the problem I'm having is that I get garbage I don't want (and that I don't see that any user wants) when I copy a worksheet:
How do I copy a worksheet without creating local copies of workbook-scoped named formulas?
It earned a "tumbleweed" badge, but perhaps whoever answers this will have an answer for it as well...

A: You should be able to select all of the cells in the original worksheet, copy them, and then "paste special" (Edit > Paste Special) in the target workbook. From within the "paste special" dialog, you can specify only formulas, values, etc. and omit style information.
Disclaimer: I haven't tried this with Excel 2007 or higher. I'm stuck on the old version.


text:
Q: Unable to update multiple records with one single query (CASE/WHEN)) I am trying to update multiple records for few columns in a table in SQL with following query.
(I wish to update A with A1, B with B1, C with C1 and on..)
UPDATE Employee
SET CASE WHEN name ='A' then  'A1' END
    CASE WHEN name ='B' then  'A2' END
    CASE WHEN name ='C' then  'A3' END
    CASE WHEN name ='D' then  'A4' END
    CASE WHEN name ='E' then  'A5' END
    CASE WHEN name ='F' then  'A6' END
    CASE WHEN name ='G' then  'A7' END
    CASE WHEN name ='H' then  'A8' END
    CASE WHEN name ='J' then  'A9' END
    CASE WHEN name ='K' then  'B0' END
    CASE WHEN name ='L' then  'B1' END ,
    CASE WHEN Category = 'recrods' THEN 'records' END ,
    CASE WHEN featureID ='140' then 'CV5' END
    WHERE School = '5000'

Getting error : Incorrect syntax near the keyword 'CASE'. Sure I am missing something here.
Please help me. Thanks a lot in advance :)

A: You need a column as the first thing after the set.  Perhaps:
UPDATE Employee
    SET name = (CASE WHEN name ='A' then  'A1'
                     WHEN name ='B' then  'A2'
                     WHEN name ='C' then  'A3'
                     WHEN name ='D' then  'A4'
                     WHEN name ='E' then  'A5'
                     WHEN name ='F' then  'A6'
                     WHEN name ='G' then  'A7'
                     WHEN name ='H' then  'A8'
                     WHEN name ='J' then  'A9'
                     WHEN name ='K' then  'B0'
                     WHEN name ='L' then  'B1'
                     ELSE name
                 END),
        category = (CASE WHEN Category = 'recrods' THEN 'records' ELSE category END),
        featureID = (CASE WHEN featureID ='140' then 'CV5' else featureID END)
    WHERE School = '5000' ;


text:
Q: Email Notification on receiving empty file We currently have an pipeline in the receive port to decrypt the file and send the file in to the Send port. We are not processing anything with in the file. Not an new issue came up, sometimes the file that comes to us is empty and biztalk when it tries to decrypt it and send to destination errors out. Is there any way I can send an email notification if the file is empty. Can I don do it in admin console without developing any custom pipeline component.

A: If you want to catch and send errors in Receive Ports, You have to create and configure a SMTP Send Port and set the Filter to ErrorReport.FailureCode exists and also add ErrorReport.ReceivePortName with name of your ReceivePort. With these filter the Send Port will suscribe and get the errors in the Receive Port.
But if you are using the native File Adapter, when an empty file arrives to the Receive Location, the adapter discard this file and no error is generated.

A: Since you're using a PGP component, I'm going to presume it's a custom component based on one of the samples out there.
In that case, the correct way to handle this case is to modify the component to check the length of the incoming stream before attempting to decrypt.
If the steam is empty, 0 bytes, simply skip the actual decode.  You can then set a Context Property indicating an empty message which you can use to generate any alert later.
Now, make 200% sure you really need to send an email.  If empty files are a normal condition (you can verify with the sender) then generating a email is creating a superfluous alert which everyone will just ignore.

A: you can custom the code and send an email via an helper in case of empty file. have a look on this blog:
http://ninocrudele.com/biztalk-and-zero-byte-file


text:
Q: Drag file from desktop to IE and upload For a project I'm working on I would like the user to be able to drag a file from the desktop or windows explorer and drop it on a web page in IE and have it uploaded to the web server. I've read that its possible with ActiveX but have not found anything about it.
Anyone know how to do this and where I can get what I need?
Thanks!

A: Browser Plus from Yahoo.
Cross browser support, but needs an install.

A: I think that for drag-n-drop to work the user will have to install a plugin. That's how it's done in services like Projectplace at least.

A: If you want this to work cross-browser, you should consider a Java applet.
Otherwise, I believe you are right that a custom ActiveX component should solve it :)


text:
Q: KVO on adding/removing objects through NSArrayController How can I get a notification when an object has been added/removed through an NSArrayController ?
I tried something like
    [core addObserver:self forKeyPath:@"arrangedObjects" options:0 context:nil];

I do get a notification of something has been added or remove but I don't know which object and I don't know what has been done (removing or adding).
The change dictionary of  observeValueForKeyPath:ofObject:change:context: doesn't return any useful information.

A: I would bind a NSMutableArray to the NSArrayController's contentArray and observe that.
@property (retain) NSMutableArray *array;

[self addObserver:self forKeyPath:@"array" options:NSKeyValueObservingOptionNew context:NULL];

To get the changed index, you can use
[(NSIndexSet *)[[change allValues] lastObject] lastIndex];


text:
Q: How to Code categorical variables in LME for binary outcomes (R) I am struggling to work out how best to code my categorical variables in a LME model.
I am predicting RT on a task, and have several categorical variables used as predictors, including whether a participant searched additional info in a trial (Y|N), and what type of information was presented to them (a|b).
I initially opted for leaving additional search as 1,0 in the data set, and applying contrast codes as -0.5,0.5 for the type of information sought. I did this because i anticipated information type B increasing RT relative to type A.
overall, my model is:
Rt ~ confidence + information_searched + information_type + (1|Participant)

Do these contrasts make sense, and if i do nothing outside of specifying each variable as a factor, i.e
my_data$information_searched = as.factor(my_data$information_searched)
my_data$information_searched = as.factor(my_data$information_type)

would this provide acceptible results as an alternative?
thanks.


text:
Q: filtering post fields (using fieldsets?) I'm having trouble filtering my post's values. When I post it will give back an array like:
Array ( [db-table] => afdeling
        [box-2] => 2
        [box-3] => 3
        [db-fields] => array( random fields )
        [box-6] => 6
)

The form is build in 4 parts first some textboxes which are located inside a fieldset, then 4 checkboxes labeled 1 - 4 inside a 2nd fieldset, then some more textboxes inside a third fieldset and last, 4 more checkboxes labeled 5 - 8 inside a forth fieldset. the fieldsets are named:

*

*db-tabledata

*checkboxes-1

*db-fielddata

*chechboxes-2

I've also looked for things like "filtering similar named fields from a post" and tried it with some array functions like array_keys/filter with 2 for loops to get them piece by piece but I didn't get that to work.
In the end what I expect to do is filter the array in the $_POST to a structure like this:
Array (
  'db-data' =>    array( [db-table] => afdeling
                         [db-fields] => array( random fields )
                  ),
  'checkboxes' => array( [box-2] => 2
                         [box-3] => 3
                         [box-6] => 6
                  )
)

So can someone push me in the right direction on filtering the fields out of the array?
ADDITION:
At this moment I'm trying to order the array alphabetical so that the box-? fields will be in the beginning or the end of the array.
problem with this however is that the box-? fields can occur 1 to 8 times. So I need some kind of way to count every array key that looks like: box-?. To know how many of those there are.

A: You can name your fields using [], for example:
<input name="db-data[db-table]" ... />
<input name="db-data[db-fields][first-field]" ... />
<input name="db-data[db-fields][second-field]" ... />

<input name="checkboxes[box-1]" ... />
<input name="checkboxes[box-2]" ... />

In this case your $_POST array will already have the structure that you want.


text:
Q: Unity Add Item on click to Inventory Currently, I'm creating an RPG style game where the player has to click on certain "glowing" objects in order to obtain items that will be added to thier inventory in order to proceed to the next level. I've created the GUI inventory bar already and I can place items into the boxes, but I cannot figure out how I can import a GUI item on click to the inventory.
If anyone could give me some ideas or possible resources that I could look at to figure something out, that would be amazing.
Thank you.

A: Well I think your question is quite wide and lots depends on other thinks but let me put down some hints here, hope some of them will help you:

*

*To turn off an object use SetActive(false) on that object, this way it is still available for code but not clickable anymore

*For items (and this really depends on how you want to work with items in the game):

*

*either make these receivable items children of the glowing object and then just cjange its parent (item.transform.SetParent(bag.transfrom))or

*if you need just basic data about them create a MonoBehaviour script with the metadata and place it on the glowing object and after click copy them to your bag

If this didn't answer all what you wanted, please be more specific or put some example code here
EDIT:
I still think your question is too wide and you should specify it more but lets try second time:
let's assume that the glowing object has these images as Sprites and they are added in Editor or by some other script at runtime. Also the glowing object should have a reference to the bag object, again get it at runtime or in editor if possible. Then place this on click method into the gloving object component and that should do the trick:
public void OnClickOnGlowItem() {
  foreach(Sprite sprite in this.attachedItems)
    this.bagObjectInterface.AddNewItem(sprite);
}


text:
Q: How to add authentication to ssh dynamic port forwarding? I am using ssh client as a SOCKS server by running on the remote server this command:
ssh -f2qTnND *:1080 some-server-user@localhost

There is only one problem here: anyone can connect to the server and use it's internet connection.
Options:

*

*To use iptables to filter access to the remote server, but clients connect to the server from various non-statically allocated IP addresses so filters should be edited very frequently, which is awkward.

*To install a SOCKS server on the remote server (e.g. Dante). Ultimately this is the last option if there is no other simpler way to do it.

*Launching the command on clients instead of remote server. The problem here is that some clients don't run on Linux and it is awkward again to set up the tunnel (e.g. Windows + Putty). It is also more difficult for end users to set up their local SOCKS server (e.g. remembering the command, typing mistakes).

Is there a way to add authentication to a SOCKS server made using ssh client?
Bonus question: How to add encryption between the client and the server (made using ssh client)?

A: SSH is your authentication
If you only want the localhost to access bind it,
ssh -D localhost:port user@host
This ensures that only local programs can access the port.
vs
*:port
This is binding to both localhost and all your addresses.
If you want to reduce the login attempts on your ssh just change the default port and rate limit it with iptables,
I would also recommend setting up fail2ban http://www.fail2ban.org/wiki/index.php/Main_Page
Why add an extra level of auth on top?
If your too lazy just setup ssh key pair and a short cut to putty with the required settings.

A: You're saying that it's awkward to tunnel in Windows.  Try Bitvise Tunnelier, it's pretty easy to use.
There is no user authentication available in the OpenSSH client's socks server.

Bonus question: How to add encryption between the client and the server (made using SSH)?

SSH is encrypted already, and it's pointless for you since you're connecting to the localhost.  You're better off disabling the encryption for more speed.  There is no encryption for socks, if there is one, it's probably not going to work for most clients any ways.


text:
Q: How do I copy a OCaml closure? I want to store a OCaml closure for later use by an external C-library. I am able to do the following:
<TARGET> = caml_alloc(Wosize_val(<SOURCE>), Tag_val(<SOURCE>));
caml_register_global_root(<TARGET>);
Code_val(<TARGET>) = Code_val(<SOURCE>);

But as the name "closure" suggests, it does not suffice to copy just the code location.
How do I make a (garbage collector friendly) copy of <SOURCE>?

A: In our work on using OCaml in iOS, we often need to save OCaml closures and call them later (when interfacing to CocoaTouch libraries). So I have code that has been working for years. However, it's too complicated to make a good example (and it's written in Objective C). Here's some code I just wrote that captures the essence of what we're doing.
First some C code that saves some number of closures of type unit -> unit and lets you call them later by chronological index. (It's just an example.)
$ cat saveclo.c
#include "caml/mlvalues.h"
#include "caml/memory.h"
#include "caml/callback.h"

static value saved_closures[10];
static int saved_closure_count = 0;

value save_closure(value clo)
{
    CAMLparam1(clo);
    saved_closures[saved_closure_count] = clo;
    caml_register_global_root(&saved_closures[saved_closure_count]);
    saved_closure_count++;
    CAMLreturn(Val_unit);
}

value call_closure(value index)
{
    CAMLparam1(index);
    int ix = Int_val(index);
    // For simplicity assume closure : unit -> unit
    (void) caml_callback(saved_closures[ix], Val_unit);
    CAMLreturn(Val_unit);
}

Then some OCaml code that exercises these functions:
$ cat clo.ml
external save_closure : (unit -> unit) -> unit = "save_closure"
external call_closure : int -> unit = "call_closure"

let save alist =
    let howlong () =
        Printf.printf "list length %d\n" (List.length alist)
    in
    save_closure howlong

let call () =
    call_closure 1;
    call_closure 0

let () =
    save [1;2;3;4;5];
    save ['a'; 'b'; 'c'; 'd'; 'e'; 'f'];
    Gc.full_major();
    call ()

A test run looks like this:
$ cc -I /usr/local/lib/ocaml -c -o saveclo.o saveclo.c
$ ocamlopt -c clo.ml
$ ocamlopt -o clo clo.cmx saveclo.o
$ ./clo
list length 6
list length 5
$

I think the salient points are (a) the OCaml object representing a closure already contains what you need (a code reference of some kind, and the data). (b) You don't need to copy it, you just need to make sure it doesn't get garbage collected. (c) The call to caml_register_global_root creates a reference to the closure so the GC knows not to collect it.
I hope this is helpful. If anybody sees problems with this code, let me know and I'll be more than happy to correct errors. But I believe it's correct.


text:
Q: Oracle SQL - left join leading to duplicates Happy Friday to one and all!
I have three tables that I am working with and I am having a tough time with the joins.  Table 1 has fields name, id, state, sales.  Table 2 has state and stateID (among others).  Table 3 has stateID and region (among others).  What I need is the stateID and region fields in Table 1.
What I tried is
select name, id, state, stateID, region, sales
from table 1 taba
left join table 2 tabb
on taba.state = tabb.state
left join table 3 tabc
on tabb.stateid = tabc.stateid

This took table 1 from ~16k rows to ~100k rows
I tried just my first join by itself and got the correct number of rows.  How do I get rid of these duplicate rows when I do that third join?
Table 1
Name   ID    State        Sales
John   01    Texas       50,234
Steve  02    Washington  39,261
Amanda 03    Ohio        67,892

Table 2
State       StateID
Texas       TX
Washington  WA
Ohio        OH

Table 3
StateID    Region
TX         South
WA         Northwest
OH         Midwest

I need it to look like this:
Name   ID    State        StateID   Region   Sales
John   01    Texas        TX       South     50,234
Steve  02    Washington   WA       Northwest 39,261
Amanda 03    Ohio         OH       Midwest   67,892

A: I'm assuming each state has multiple regions, but there is nothing in table 1 that indicates a region. So when you join to table 3 and there is 100 regions in that state and the only thing you are joining on is a stateID, it will return all 100 regions.
You probably need region in your first table to indicate the region AND state the sale occurred in or you can throw a DISTINCT on the query.
select DISTINCT name, id, state, stateID, region, sales
from table 1 taba
left join table 2 tabb
on taba.state = tabb.state
left join table 3 tabc
on tabb.stateid = tabc.stateid

Based on your new provided tables and data, this should give you what you want:
select name, id, state, stateID, region, SUM(sales) AS sales
    from table1 taba
    left join table2 tabb
    on taba.state = tabb.state
    left join table3 tabc
    on tabb.stateid = tabc.stateid
GROUP BY name, id, state, stateID, region

A: I think using this query should do the job.
select name, id, state, stateID, region, sales
from table1 natural join table2 natural join table3

Because you tables are using the same names for attributes, you can use the natural join (It will only keep the common attributes, assuming that all states in table1 are in table2 and all stateID in table2 are in table3).
And if you need the sum of sales for each name (which is not clear from your question) :
select name, id, state, stateID, region, SUM(sales)
from table1 natural join table2 natural join table3
group by name, id, state, stateID, region


text:
Q: How to show data from another table with foreign key CakePHP? I have the following tables:

*

*users: id, name, ...

*courses: id, name, knowledge_area_id, educational_institution_id, ...

*users_courses: user_id, course_id, ...

*knowledge_areas: id, name

*educational_institutions: id, name, ...

I am currently trying to display on users' view some information about that user, including every course they are related to. Here is what I am currently doing:
On /Template/Users/view.ctp:
<?php foreach($user->courses as $courses): ?>
    <?= h($courses->name) ?>
    <?= h($courses->knowledge_area_id) ?>
    <?= h($courses->educational_institution_id ?>
    <?= h($courses->description) ?>
<?php endforeach; ?>

This shows every course the user is related to with it's name, the knowledge area ID, the educational institution ID and the course description. However, I would like to show the knowledge area's name and the educational institution's name instead of their ID. I have tried doing $courses->knowledge_area->name but it says I am trying get property name from a Non-Object.
When I try debug($courses) I get:
object(App\Model\Entity\Course) {

    'id' => (int) 2,
    'name' => 'course name',
    'knowledge_area_id' => (int) 1,
    'educational_institution_id' => (int) 1,
    'description' => 'course description',
    '_joinData' => object(Cake\ORM\Entity) {
    ...
}

When in reality I should be getting
object(App\Model\Entity\Course) {

    'id' => (int) 2,
    'name' => 'course name',
    'knowledge_area_id' => (int) 1,
    'educational_institution_id' => (int) 1,
    'description' => 'course description',
    'educational_institution' => object(App\Model\Entity\EducationalInstitution) {

        'id' => (int) 1,
        'address_id' => (int) 1,
        'name' => 'ed institution name',
        '[new]' => false,
        '[accessible]' => [
            'address_id' => true,
            'name' => true,
            'address' => true,
            'courses' => true,
            'users' => true
        ],
        '[dirty]' => [],
        '[original]' => [],
        '[virtual]' => [],
        '[errors]' => [],
        '[invalid]' => [],
        '[repository]' => 'EducationalInstitutions'

    },
    'knowledge_area' => object(App\Model\Entity\KnowledgeArea) {

        'id' => (int) 1,
        'name' => 'knowledge area name',
        '[new]' => false,
        '[accessible]' => [
            'name' => true,
            'courses' => true
        ],
        '[dirty]' => [],
        '[original]' => [],
        '[virtual]' => [],
        '[errors]' => [],
        '[invalid]' => [],
        '[repository]' => 'KnowledgeAreas'

    },
...
}

That way, I would be able to use $courses->knowledge_area->name, which is basically what happens on /Template/Courses/view.ctp, where for each course I am able to show which knowledge area it is related to.
Since I am following cake conventions and I double checked the files I am assuming everything on /Model/Table/.. and on the controllers is correct, any ideas on what I could do to fix this?

A: You can eager load associations as deep as you like using contain():
$query = $products->find()->contain([
    'Shops.Cities.Countries',
    'Shops.Managers'
]);

See here: https://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html#eager-loading-associations-via-contain

A: With the help of Mary's comment, I managed to find a slightly different solution that worked for me.
Since I was trying to edit the users view, I went into the view function on users controller and changed
$user = $this->Users->get($id, [
            'contain' => ['Addresses',
                          'AccessLevels',
                          'Courses',
                          'EducationalInstitutions'
            ]
        ]);
to
$user = $this->Users->get($id, [
            'contain' => ['Addresses',
                          'AccessLevels',
                          'Courses',
                          'EducationalInstitutions',
                          'Courses.KnowledgeAreas',
                          'Courses.EducationalInstitutions'
            ]
        ]);


text:
Q: Repeated application of parameters from a stream to a fluent builder method I'm writing a REST service client using the Jax-RS. For a request I'd like to add query parameters. The according method in Jax-RS is webTarget.queryParam(name, value) returning a new WebTarget instance (so webtarget is immutable).
Further, I have a stream of name-value-pairs: Stream<Tuple<String,String>> queryParams with a varying number of elements.
Now I'd like to repeatedly apply the parameters from the stream to the queryParam() method, using the result as invocation target on the next application:
As rolled out invocation it would look like this:
WebTarget original = ...
WebTaragt wt1 = original.queryParam(t1.name,t1.value);
WebTaragt wt2 = wt1.queryParam(t2.name,t2.value);
...
WebTarget wtFinal = wtNminus1.queryParam(tN.name,tN.value);

Is there a way to efficiently implement this as pure function?

A: I can not yet make a statement about the efficiency, but, you may want to look into Stream.reduce. The following solution assumes that you have at least one WebTarget which you can use to carry out the reduction. Moreover I this solution doesn't allow parallelization (for that an appropriate combiner would be needed and I do not know how the WebTargets need to be combined).
Stream<Tuple<String, String>> queryParamStream = ...
WebTarget wtFinal = queryParamStream.reduce(original,
                        (webtarget, tuple) -> webtarget.queryParam(tuple.name, tuple.value),
                        (webtarget1, webtarget2) -> /* what would be needed to combine those when you use a parallel stream? */ webtarget2);


text:
Q: Could a china ST-Link have bricked my STM32F4? I have built several boards with STM32F405 on them and I have been flashing them with a cheap china ST-Link knock-off from eBay which worked perfectly for many months now.
However, I now noticed, that my STM32F405 board is no longer accessible through the ST-Link (No Target Detected with ST-Link utility and STM32CubeIDE). However, the code runs fine on it! The LEDs are blinking and output is written to the SD-Card.
I am not able to do a chip erase on ST-Link Utility, because for that it needs to be connected. The issue exists on three of my boards, which have previously been flashed with the same cheap china ST-Link. I suspect that the boards have entered memory protection level 2 (RDP), thus no longer accessible via SWD, and thus bricked. ST-Utility does however not tell me that there is read out protection enabled (I don't know if it would..) it acts as if the SWD line is not connected, but I checked with a multimeter and they are... I enabled "connect under reset" and I see that the STM32 is resetting, but nothing else happens, still no connection established...
I also ordered a genuine ST-Link, and the issue appears the same.
Since I do not see any other common link between the three boards (2 have similar software, but the third has a really different software on it, the only thing in common is the drivers for the I2C and SPI sensors that are attached to the chip), I suspect that the problem could come from the cheap china ST-Link. Is that a known problem? Or do you have any other inputs? I am certain, that I did not set the memory protection flag when flashing the chip (I actually don't know how I would do that with STM32CubeIDE).
When I last flashed the board with the cheap china ST-Link I was using STM32CubeIDE on my macbook pro. ST utility was used on a virtual machine running windows 10.
All three custom STM32 Boards failed on the same day, two of them are physically the same, but running slightly different software, the third one has a much different schematic (but all use an STM32F405)
BOOT0 and BOOT1 are connected to ground through a 10k resistor, the board gets a solid 3.3v from the ST-Link. Crystal is connected with capacitors but not configured in the software. The SWD pins are not configured as anything else in software, I used the STM32CubeIDE graphical configuration tool and used them for debugging.
Thanks!
EDIT:
Conditions when it failed: High humidity (10 °C and up to 80-90% humidity) in a tent during one week (though other boards survived without any issues). Board has no conformal coating.
Schematic of one of the boards is attached.
EDIT 2:
The third board is not actually broken, it works with the genuine ST-Link but not with the replica one, however the first two boards do not work with either of them.. so there is definitely something wrong with the replica ST-Link..


text:
Q: Argument Error: Unknown key: :from I'm trying to create messages in rails. But when I run Message.new in the rails console I get:
ArgumentError: Unknown key: :from. Valid keys are: :class_name, :class, :foreign_key, :validate ... etc
My setup is as follows:
User Model
  has_many :messages
  has_many :message_recipients, :as => :recipient, :dependent => :destroy
  has_many :received_messages, :through => :message_recipients

Message Model
  belongs_to :user
  has_many :message_recipients, :dependent => :destroy
  has_many :recipients, :through => :message_recipients, :class_name => "User", :from => :recipient

Message_Recipient Model
  belongs_to :message
  belongs_to :recipient, :class_name => "User", :foreign_key => :recipient_id

Thanks for any advice or help.

A: It's telling you that :from is not a valid option in this line:
has_many :recipients, :through => :message_recipients, :class_name => "User", :from => :recipient

You should just be able to remove that part.
For valid options, see the documentation for has_many.
UPDATE
In the syntax of this line, the :from is a key in the options hash of the has_many macro/method. But the has_many method is checking the passed in options and warning you if anything you pass in is unknown. That's what :from would be -- an unknown option. I.e. Rails has no idea what to do with it. So it's not valid and just shouldn't be there.

A: In the Message model, while defining has_many association with recipients, you have passed :from option which is not a valid key for has_many method which is why you receive the error as
ArgumentError: Unknown key: :from. Valid keys are: :class_name, :class, :foreign_key, :validate ... etc

In Message model
has_many :recipients, :through => :message_recipients, :class_name => "User",
         :from => :recipient
         ## ^^
         ## Remove this

Here is a reference of all the valid options which you can pass to has_many association

A: :from is not a valid option in has_many relationship used in Message model. That's why you are receiving the problem of Argument Error.


text:
Q: How do I install a Ruby gem from GitHub and have it work in IRB? Seems like every Ruby tutorial I find centers around Rails.
Anyway, I simply want to install a gem from a GitHub repo and have that gem work in irb.
I want to install the exifr gem.  When I do a gem install exifr it doesn't get the newest version.
So I created a Gemfile and put:
gem 'exifr', :git => 'git://github.com/remvee/exifr.git'

Then bundle install.  Installs OK but now gem list doesn't find the gem.  So I can't require it in irb.
Any help for NON Rails applications?
Thanks

A: You need to kick off the bundler setup if you want to use the gems from a gemfile:
require 'bundler/setup'
require 'exifr'

or:
irb -rbundler/setup
> require 'exifr'

This is equivalent to running bundle exec irb, except it doesn't depend on a specific invocation to work, and instead presumes that a Gemfile is available and the gems were installed with Bundler.

A: Try...
bundle exec gem list

And..
bundle exec irb -rexifr

And see if that works.  That should help gem/irb find the installed gem.


text:
Q: Arduino C++ sprintf() print "?" void loop()
{

  float temperature = dht.readTemperature();
  char test[50];
  sprintf(test, "Temp: %f", temperature);

  Serial.println(temperature); // works fine
  Serial.println(test); // why it prints "?"

  delay(300);
}

// Output
24.10   <== Serial.println(temperature);
?       <== Serial.println(test);
24.10
?
24.10
?
24.10
?

Hi. I'm arduino/c newbie. Why print test is keep showing "?" Am I missing something? When I running the below code in c++ playground, it works fine.
float temperature = 23.19;
char test[50];
sprintf(test, "Temp: %f", temperature);
printf("%s", test);        <==== Works fine!


text:
Q: Apply CSS to  nested in  I want to apply CSS specific to <f:selectItem> in <h:selectOneMenu> to be displayed in a different style.
e.g. I want every option of coffee in the list below to be displayed in a different color.
<h:selectOneMenu value="#{user.favCoffee1}">
   <f:selectItem itemValue="Cream Latte"   itemLabel="Coffee3 - Cream Latte" />
   <f:selectItem itemValue="Extreme Mocha" itemLabel="Coffee3 - Extreme Mocha" />
   <f:selectItem itemValue="Buena Vista"   itemLabel="Coffee3 - Buena Vista" />
</h:selectOneMenu>`

Can anyone help me out here?

A: The <f:selectItem> renders a HTML <option> element. It has very limited CSS styling support. The color property is not among them. Even more, it works in MSIE only, not in other webbrowsers. There is however no way to give each <option> element its own style attribute by JSF, so closest what you can get is applying a CSS rule on all options and accepting that it works in MSIE only.
<h:selectOneMenu styleClass="mymenu">

with
.mymenu option {
    color: red;
}

Your best bet is to replace the dropdown by a <ul><li> with a good shot of CSS/JavaScript which mimics it to look like a dropdown. Some JSF component libraries has such a component, such as PrimeFaces' <p:selectOneMenu>. Check the Custom content example in its 3.0 showcase.

A: I'm not familar with JSF, but I assume the <f:selectItem> is not what gets sent to the browser.
You'll need to figure out what HTML is sent to the browser for that JSF tag, and apply your CSS to that.


text:
Q: flip a 2d array I'm trying to get a 2D array to a form, so I can work with it like I need. I just cant modify it correctly..
Say I have a 2D array:
0 1 0 1 0
0 0 1 1 1
0 0 0 3 0
0 0 0 0 1
0 0 0 0 0

How can I flip it to its symmetrical, so at the moment position 0,1 is 1 and therefore position 1,0 would be 1?
does this make seance?
I need to do this so I can work out Euler tour

A: You could just access it in a flipped way.
x = 3;
y = 5;

// Ask for x,y element
$normal = $myarray[$x][$y];

// Ask for x,y in the flipped array by asking for y,x
$flipped_access = $myarray[$y][$x];

A: Something like this (pseudo code)?
for x = 0 to width
  for y = 0 to x-1
     swap( array[x][y], array[y][x] )

Although depending on what your environment is, there might be special methods to do just that.

A: Isn't it same as transposing a square matrix?
(for i=0; i < order; i++) {
  for(j =i; j < order; j++) {
   temp = arr[i][j];
   arr[i][j] = arr[j][i];
   arr[j][i] = temp;
 }
}


text:
Q: Remove elements of an array in haskell I'm trying to remove the items of an array that coincide in both using map or filter, for example:
rmElements :: [Integer] -> [Integer] -> [Integer]

and by passing
rmElements [1,2] [1,2,3,4]

get [3,4]
Thanks

A: I guess this is some kind of homework?
Anyway the simplest thing I can think of is taking the union (easy with ++) and removing any element form the intersection:
rmElements xs ys = filter (\e -> not (e `elem` xs && e `elem` ys)) (xs ++ ys)

this is certainly not the most performant solution but it should work reasonably well (at least for your example) - it's a bit unclear of what to do with duplicates and if you need any order so I keep it with that.

A: Thanks, I've got it now in a simpler way for me:
rmElements x y = filter(\e -> notElem z x) y


text:
Q: Вывод значений на экран из нового потока JAVAFX Создаю новый поток и из него мне необходимо вывести значение t1 в Label
  public void Seconds(){
    new Thread(() -> {
        finish.set(true);
        while (finish.get()){
            a1++;
            t1 = Integer.toString(a1);
            Label.setText(t1);
            try {
                Thread.sleep(999);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    }).start();
}

Но вместо вывода значений получаю ошибку, что это не возможно. Как в таком случае вывести необходимое значение на экран? Через System.out.println(t1); все работает.

A:   public void Seconds(){
    new Thread(() -> {
        finish.set(true);
        while (finish.get()){
            a1++;
            t1 = Integer.toString(a1);
            Platform.runLater(new Runnable() {
            @Override public void run() {
               Label.setText(t1);
            }
            });
            try {
                Thread.sleep(999);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    }).start();
}

Plutform.runLater выполняет код в потоке пользовательского интерфейса. Любые изменения в интерфейсе необходимо проводить через него


text:
Q: int obj=new someMethod(); valid or not statement Is this statement valid or not?
int obj=new someMethod();

Also I want to know that what difference it creates when we create a object with different reference and constructor, like this:
Object obj=new otherObject();

I mean how it is different from
Object obj=new Object();

'someMethod' is constructor of another class 'someMethod' and 'otherObject' is also constructor of class 'otherObject'. Object is a class.

A: Taking the wild guess that someMethod is a method of a class, e.g.:
int someMethod() {
    // Code here
}

...and that otherObject is an instance of a class, then no, neither of those statements is valid.
In Java, the new keyword is use to create an instance of a class. Classes are not methods, and are not objects.
The statement:
Object obj = new Object();

is valid, and works, because Object is a class.
Now, of course, if otherObject is a class:
class otherObject {
    // Methods and such here
}

...then Object obj = new otherObject(); is a valid statement, because all classes derive from Object, so it's okay to assign an otherObject instance to a variable declared as Object. Note that in Java, the overwhelming convention is to use initially-capped CamelCase for class names (so, OtherObject rather than otherObject).
I recommend stepping back and reading some decent Java introductory tutorials, which will explain classes, instances, methods, and such.

A: int obj=new someMethod(); is not valid. int is a data type, not a class. You cannot inherit from int so someMethod could never be an int class/object.
If someMethod is a method (as the name suggests :) you can have
int intObj = someMethod();

if someMethod returns and int like so:
int someMethod()
{
    return 5;
}

baseObject obj=new otherObject(); means that the class 'otherObject' inherits from 'baseObject'. For instance, if you have an Animal class then a class such as Dog can inherit from it so you can have
Animal spot = new Dog();

But you cannot have
Dog spot = new Animal();

Here's a link explaining java inheritance: http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
Since all classes inherit from Object, Object obj = new OtherObject(); is valid

A: int obj=new someMethod();

is not valid because when you create an object of any class you can not assign it basic data type.
Object obj=new otherObject();

is valid because an object of a class can be assign to its own type or to its super class and Object class is super class of all.


text:
Q: AudioKit cannot record microphone I'm using the latest version of AudioKit, 4.8. I have set up a simple audio chain to record some audio from the microphone, and it works great on the simulator, but when I switch to a physical device, nothing is recorded and it keeps printing this is the console:
AKNodeRecorder.swift:process(buffer:time:):137:Write failed: error -> Cannot complete process.("com.apple.coreaudio.avfaudio"Error -50.)

So you see, nothing is recorded. -50 is the bad param error, but obviously I couldn't find what I'm missing. The audio session is set to playAndRecord and I DID request the microphone usage. If I don't use AKNodeRecorder but add my own tap instead, the same error still shows up when I try AKAudioFile.write(from:).
Here's my code:
    guard let file = try? AKAudioFile(forWriting: destinationURL, settings: [AVFormatIDKey: kAudioFormatMPEG4AAC, AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue]) else {
        return
    }

    microphone?.start()

    let recorder = try? AKNodeRecorder(node: microphone, file: file)
    try? recorder?.record()

What should I do?
P.S. before I upgraded to AudioKit 4.8, I was using 4.7, and instead of giving me error -50, it simply crashed when I began recording on a physical device, giving me this. All is fine on simulators.
Terminating app due to uncaught exception 'com.apple.coreaudio.avfaudio', reason: '[[busArray objectAtIndexedSubscript:(NSUInteger)element] setFormat:format error:&nsErr]: returned false, error Error Domain=NSOSStatusErrorDomain Code=-10865 "(null)"'


text:
Q: Plot asymptote in grotwth curve in R How can I plot the line asymptote off this curve above?
 # Create Data
    Conc <- c(0.03125, 0.06250, 0.12500, 0.25000, 0.50000, 1.00000, 0.03125, 0.06250, 0.12500, 0.25000, 0.50000, 1.00000, 0.03125, 0.06250, 0.12500, 0.25000, 0.50000, 1.00000, 0.03125, 0.06250, 0.12500, 0.25000, 0.50000, 1.00000, 0.03125, 0.06250, 0.12500, 0.25000, 0.50000, 1.00000, 0.03125, 0.06250, 0.12500, 0.25000, 0.50000, 1.00000)

    Response <- c(167.11246201, 53.96960486, 128.42857143, 43.67173252, 4.51975684, 0.34042553, 120.10334347, 101.14589666, 155.17629179, 35.31306991, 8.56534954, 1.71124620, 146.34954407, 108.50151976, 163.60182371, 64.70212766, 2.88145897, 0.50759878, 82.92401216, 109.80547112, 116.69300912, 26.85410334, 3.01519757, 0.37386018, 87.06990881, 84.82978723, 118.36474164, 27.52279635, 2.34650456, 0.10638298, 89.47720365, 109.47112462, 85.43161094, 17.69300912, 2.31306991, 0.07294833)

    df <- data.frame(Conc = Conc, Response = Response)

    #Make Modell
    library(drc)
    #adjust model
    drm <- drm(Response ~ Conc, data = df, fct = LL.4())
    #plot
    plot(drm)

This is an exemple of what I mean?
enter image description here

A: I am not sure what is the right way here, but I usually do it like this:
Logistic funtion
Still don't know how to use LL.4() for this purpose
flogis <- function(x, b, c, d, e){
  c + (d - c)/(1 + exp(b*(log(x) - log(e))))
}

Dataset
Make some example data:
dose <- rep(exp(seq(-5, 5, length.out = 10)), each = 3)
dat <- data.frame(
  dose = dose,
  response = flogis(dose, -1, 0, 1, .5) + rnorm(length(dose), 0, .05)
)

head(dat)
#  dose   response
#1 0.006737947 0.01310683
#2 0.006737947 0.08292573
#3 0.006737947 0.03263079
#4 0.020468076 0.02763111
#5 0.020468076 0.01934260
#6 0.020468076 0.01296994

Fitting 4-parameters log-logistic model
library(drc)

model <- drm(response ~ dose, data = dat, fct = LL.4())

summary(model)
#Model fitted: Log-logistic (ED50 as parameter) (4 parms)
#
#Parameter estimates:
#
#                Estimate Std. Error  t-value   p-value
#b:(Intercept) -1.0012680  0.0887792 -11.2782 1.637e-11 ***
#c:(Intercept)  0.0049506  0.0243151   0.2036    0.8402
#d:(Intercept)  0.9889417  0.0163848  60.3573 < 2.2e-16 ***
#e:(Intercept)  0.4054848  0.0419639   9.6627 4.310e-10 ***
#---
#Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#
#Residual standard error:
#
#0.04466107 (26 degrees of freedom)

Grab model parameters for use with ggplot
coefs <- setNames(coef(model), c("b", "c", "d", "e"))
y50 <- predict(model, newdata = data.frame(dose = coefs["e"]))

Plot data
(Sorry, have no time to play with text labels, and don't understand what phi2 + phi3 means on the example plot, but pretty sure that is something which is going on around EC50)
ggplot(dat, aes(x = dose, y = response)) +
  stat_function(fun = function(x, b, c, d, e){
    c + (d - c)/(1 + exp(b*(log(x) - log(e))))
  }, args = coefs, col = "skyblue", lwd = 1) +
  geom_point(pch = 21, fill = "white") +
  geom_hline(yintercept = coefs[c("c", "d")], lty = 2, colour = "gray50") +
  geom_segment(aes(x = coefs["e"], y = 0, xend = coefs["e"], yend = y50),
               lty = 2, colour = "gray50") +
  geom_segment(aes(x = coefs["e"], y = y50, xend = 0, yend = y50),
               lty = 2, colour = "gray50") +
  scale_x_log10(
    breaks = scales::trans_breaks("log10", function(x) 10^x),
    labels = scales::trans_format("log10", scales::math_format(10^.x))
  ) +
  annotation_logticks(sides = "b") +
  labs(x = "Dose",
       y = "Response"
  ) +
  expand_limits(y = 1) +
  ggthemes::theme_few()

A: try this :
library(drc)

#adjust model
drm <- drm(Response ~ Conc, data = df, fct = LL.4())

#plot
plot(drm)
abline(a=112.6868 , 0)

A: You can extract the value of the asymptote from the drm object:
asymptote <- coef(drm)[3]

This value can be used for plotting:
plot(drm)
abline(asymptote, 0)


text:
Q: Can't see achievement in google play games I'm working on a game which has been published to google play. Now we want to add achievement service to this game.
Following google play service samples, everything works fine. I can sign in and unlock the achievement successfully.
But the only thing trouble me is that I can't see the achievements in my device.
First I think it may be because the cache, but after two day, I still can't see it.
The game service's state is ready to test, but I heard from someone else, it is no mater.
So I don't know what I had missed.
Any suggestion is appreciate.

A: Is the user you are logged in as a "testing user"? If the achievement is not yet published, only testers will be able to see the achievement.


text:
Q: Getting ReferenceError: setInterval is not defined I'm trying to use setInterval() within an extension developed with the firefox add-on sdk.  Unfortunately, no matter how I call setInterval(), I keep getting the ReferenceError that setInterval is not defined.
I've simplified my code to illustrate the problem.  The below code results in this error:
var globalTimer = 0;

function setGlobalTimer() {
    globalTimer = setInterval(testFunction, 15000);
    //globalTimer = setInterval(function() { testFunction(); }, 15000);
}

function testFunction() {
    console.log("testFunction just called");
}

var { ToggleButton } = require("sdk/ui/button/toggle");
var button = ToggleButton({
    id: "my-button",
    label: "my button",
    icon: {
      "16": "./icon-16.png",
      "32": "./icon-32.png",
      "64": "./icon-64.png"
    },
    onClick: handleClick
});

function handleClick(state) {
    testFunction();
    setGlobalTimer();
}

Both ways of setting the global variable globalTimer in setGlobalTimer(), one way is commented out, result in the following error when I click on my toggle button in Firefox:
ReferenceError: setInterval is not defined
I've scanned the stackoverflow site for questions about setInterval() not working, and in other cases, using the calls I am using has worked.  But this code generates the above error for me.
If anyone can help me with this problem I would greatly appreciate it.
Thanks in advance.

A: setInterval is not a global with the add-on sdk at the moment.
you need to require it, like so var { setInterval } = require("sdk/timers")