text:
Q: Differences between synchronized(this) and synchronized(objectReference) I'd like to better understand the mechanics of what actually happens when thread enters the synchronized(this) block vs synchronized(someObjectReference) block.
    synchronized (this) {
        // Statement 1
        // Statement 2
    }

    synchronized (someObjectReference) {
        // Statement 1
        // Statement 2
    }

As i understand it: (am i missing something? am i wrong?)

*

*In both cases, only 1 thread can access synchronized block at a time

*When we're synchronizing on someObjectReference :

*

*Only 1 thread at a time may access/modify it in this block

*Only 1 thread at a time may enter this block

What other mechanics are there please?
    synchronized (objectReference) {
        // Statement 1 dealing with someObjectReference
        // Statement 2 not dealing with someObjectReference
    }

In the example above, does it make any sense adding statements not dealing with mutex into the synchronized block?

A: There's only a difference when you mix the two together.
The single, basic rule of synchronized(foo) is that only one thread can be in a synchronized(foo) block for the same foo at any given time.  That's it.  (The only caveat maybe worth mentioning is that a thread can be inside several nested synchronized(foo) blocks for the same foo.)
If some code is inside a synchronized(foo) block, and some code is inside a synchronized(bar) block, then those pieces of code can run simultaneously -- but you can't have two threads running code in synchronized(foo) blocks simultaneously.

A:
In both cases, only 1 thread can access synchronized block at a time

Not really. For exemple, when synchronizing on "this", 2 threads can access to the same block if they have 2 different instances of the same class. But yes, for one instance, there will be only one access to the block. And there will also have only one acess to any synchronized block on this
"Synchronized" means that only 1 thread can have access to any synchronized block on the same instance. So if you have 2 synchronized block in 2 different source files, but on the same instance, if one thread is inside one of those blocks, another thread cannot access to both synchronized block
About "what to do within a synchronized block" : do only things dealing with the synchronized object. Any other instruction that doesn't need synchronization will lock the ressource for nothing, an potentially create a bottleneck

A: Synchronize basically means program request to take a lock on the specified object...If a Thread is not able to enter any synchronized block then that means any other thread has already taken lock on the specified object..BLock of code specify that inside this region a thread can enter if lock is successfully acquired..
 In both cases, only 1 thread can access synchronized block at a time

--Depend on the object to be locked availability

A: One important thing to note about synchronizing on this deals with visibility. Lets say you have a class A and it synchronizes on this. Any code that uses A has a reference to the object A is using to lock on. This means it is possible for a user of A to create a deadlock if they also lock on the A instance.
public class A implements Runnable {
  public void run() {
    synchronized (this) {
      // something that blocks waiting for a signal
    }
    //other code
  }
}

public class DeadLock {
  public void deadLock() {
    A a = new A();
    Thread t = new Thread(a);
    t.start();

    Thread.sleep(5000); //make sure other thread starts and enters synchronized block
    synchronized (a) {
      // THIS CODE BLOCK NEVER EXECUTES
      // signal a
    }
  }
}

Where as, if you always synchronize on a private member variable, you know that you are the only one using that reference as a lock.


text:
Q: Simplification with letsimp in Maxima, what is going on? Here is a simple session with maxima, in which im trying to make the simplification (r-r0)=h
(%i1) ax: G*M*m*(r-r0)/r0^2 - G*M*m/r0 ;
                            G M m (r - r0)   G M m
(%o1)                       -------------- - -----
                                   2          r0
                                 r0
(%i2) let(r-r0,h);
(%o2)                            r - r0 --> h
(%i3) expand(scanmap(letsimp,ax));
                               G M m r   2 G M m
(%o3)                          ------- - -------
                                   2       r0
                                 r0

I was expecting this in the last part:
                               G M m h   2 G M m
                              ------- - -------
                                   2       r0
                                 r0

Why did maxima replace (r-r0) with  r rather than with h?
Iv attempted letsimp and letrat as instructed in this other question: common subexpressions

A: r - r0 is not a form supported by let. From the documentation:

-- Function: let
            let (, , , , ..., )
            let ([, , , , ..., ],
            )
 Defines a substitution rule for 'letsimp' such that <prod> is
 replaced by <repl>.  <prod> is a product of positive or negative
 powers of the following terms:

    * Atoms which 'letsimp' will search for literally unless
      previous to calling 'letsimp' the 'matchdeclare' function is
      used to associate a predicate with the atom.  In this case
      'letsimp' will match the atom to any term of a product
      satisfying the predicate.
    * Kernels such as 'sin(x)', 'n!', 'f(x,y)', etc.  As with atoms
      above 'letsimp' will look for a literal match unless
      'matchdeclare' is used to associate a predicate with the
      argument of the kernel.

In this case one can start with a syntactic substitution:
    (%i1) ax: G*M*m*(r-r0)/r0^2 - G*M*m/r0 $

    (%i2) subst(h, r - r0, ax);
                                    G M h m   G M m
    (%o2)                           ------- - -----
                                        2      r0
                                      r0

redpajama_set_name: RedPajamaStackExchange


text:
Q: I want to add 12 pictures in one page without entering the writing between pictures
\begin{figure}[!htb]
\minipage{0.32\textwidth}
\includegraphics[width=\linewidth]{0000.png}
\caption*{(a)}
\endminipage\hfill
\minipage{0.32\textwidth}
\includegraphics[width=\linewidth]{11.png}
\caption*{(b)}
\endminipage\hfill
\minipage{0.32\textwidth}%
\includegraphics[width=\linewidth]{22.png}
\caption*{(c)}
\endminipage
\end{figure}
\begin{figure}[!htb]
\minipage{0.32\textwidth}
\includegraphics[width=\linewidth]{33.png}
\caption*{(d)}
\endminipage\hfill
\minipage{0.32\textwidth}
\includegraphics[width=\linewidth]{44.png}
\caption*{(e)}
\endminipage\hfill
\minipage{0.32\textwidth}%
\includegraphics[width=\linewidth]{55.png}
\caption*{(f)}
\endminipage
\end{figure}
\begin{figure}[!htb]
\minipage{0.32\textwidth}
\includegraphics[width=\linewidth]{66.png}
\caption*{(g)}
\endminipage\hfill
 \minipage{0.32\textwidth}
 \includegraphics[width=\linewidth]{77.png}
\caption*{(h)}
 \endminipage\hfill
\minipage{0.32\textwidth}%
\includegraphics[width=\linewidth]{88.png}
\caption*{(i)}
\endminipage
\end{figure}
\begin{figure}[!htb]
\minipage{0.32\textwidth}
\includegraphics[width=\linewidth]{99.png}
\caption*{(j)}
\endminipage\hfill
\minipage{0.32\textwidth}
\includegraphics[width=\linewidth]{100.png}
\caption*{(k)}
\endminipage\hfill
\minipage{0.32\textwidth}%
\includegraphics[width=\linewidth]{110.png}
\caption*{(l)}
\endminipage
\captionsetup{justification=centering}
\caption{Zoom de image 2.3.a de Munich (a)Image Optique (b)Image Span (c)Robert (d)Prewitt (e)Sobel (f)moyenneur(3$ \times $3) (g)moyenneur( (h)Canny (i)Emboss  (j)DOG (k)Laplacien (l)Résultat.}
\end{figure}

A: \begin{figure}[p]
    \minipage{0.32\textwidth}
    \includegraphics[width=\linewidth]{0000.png}
    \caption*{(a)}
    \endminipage\hfill
    \minipage{0.32\textwidth}
    \includegraphics[width=\linewidth]{11.png}
    \caption*{(b)}
    \endminipage\hfill
    \minipage{0.32\textwidth}%
    \includegraphics[width=\linewidth]{22.png}
    \caption*{(c)}
    \endminipage

    \minipage{0.32\textwidth}
    \includegraphics[width=\linewidth]{33.png}
    \caption*{(d)}
    \endminipage\hfill
    \minipage{0.32\textwidth}
    \includegraphics[width=\linewidth]{44.png}
    \caption*{(e)}
    \endminipage\hfill
    \minipage{0.32\textwidth}%
    \includegraphics[width=\linewidth]{55.png}
    \caption*{(f)}
    \endminipage

    \minipage{0.32\textwidth}
    \includegraphics[width=\linewidth]{66.png}
    \caption*{(g)}
    \endminipage\hfill
    \minipage{0.32\textwidth}
    \includegraphics[width=\linewidth]{77.png}
    \caption*{(h)}
    \endminipage\hfill
    \minipage{0.32\textwidth}%
    \includegraphics[width=\linewidth]{88.png}
    \caption*{(i)}
    \endminipage

    \minipage{0.32\textwidth}
    \includegraphics[width=\linewidth]{99.png}
    \caption*{(j)}
    \endminipage\hfill
    \minipage{0.32\textwidth}
    \includegraphics[width=\linewidth]{100.png}
    \caption*{(k)}
    \endminipage\hfill
    \minipage{0.32\textwidth}%
    \includegraphics[width=\linewidth]{110.png}
    \caption*{(l)}
    \endminipage
    \captionsetup{justification=centering}
    \caption{Zoom de image 2.3.a de Munich (a)Image Optique (b)Image Span (c)Robert (d)Prewitt (e)Sobel
    (f)moyenneur(3$ \times $3) (g)moyenneur( (h)Canny (i)Emboss  (j)DOG (k)Laplacien (l)Résultat.}
\end{figure}

However, using package subcaption and macro \subfigure would make more sense.
\begin{figure}[p]
\subcaptionbox{}{\includegraphics[width=0.32\linewidth]{0000.png}}
\hfill
\subcaptionbox{}{\includegraphics[width=0.32\linewidth]{11.png}}
\hfill
\subcaptionbox{}{\includegraphics[width=0.32\linewidth]{22.png}}

\subcaptionbox{}{\includegraphics[width=0.32\linewidth]{33.png}}
\hfill
\subcaptionbox{}{\includegraphics[width=0.32\linewidth]{44.png}}
\hfill
\subcaptionbox{}{\includegraphics[width=0.32\linewidth]{55.png}}

\subcaptionbox{}{\includegraphics[width=0.32\linewidth]{66.png}}
\hfill
\subcaptionbox{}{\includegraphics[width=0.32\linewidth]{77.png}}
\hfill
\subcaptionbox{}{\includegraphics[width=0.32\linewidth]{88.png}}

\subcaptionbox{}{\includegraphics[width=0.32\linewidth]{99.png}}
\hfill
\subcaptionbox{}{\includegraphics[width=0.32\linewidth]{100.png}}
\hfill
\subcaptionbox{}{\includegraphics[width=0.32\linewidth]{110.png}}

\captionsetup{justification=centering}
\caption{Zoom de image 2.3.a de Munich (a)Image Optique (b)Image Span (c)Robert (d)Prewitt (e)Sobel
        (f)moyenneur(3$ \times $3) (g)moyenneur( (h)Canny (i)Emboss  (j)DOG (k)Laplacien (l)Résultat.}
\end{figure}

A:
with subfloat environments and Gin key:
 \documentclass{article}
\usepackage[demo]{graphicx}
\usepackage{subfig}

\begin{document}
\begin{figure}[p]
   \setkeys{Gin}{width=0.32\linewidth}
\subfloat[]{\includegraphics{0000.png}}
\hfill
\subfloat[]{\includegraphics{11.png}}
\hfill
\subfloat[]{\includegraphics{22.png}}

\subfloat[]{\includegraphics{33.png}}
\hfill
\subfloat[]{\includegraphics{44.png}}
\hfill
\subfloat[]{\includegraphics{55.png}}

\subfloat[]{\includegraphics{66.png}}
\hfill
\subfloat[]{\includegraphics{77.png}}
\hfill
\subfloat[]{\includegraphics{88.png}}

\subfloat[]{\includegraphics{99.png}}
\hfill
\subfloat[]{\includegraphics{100.png}}
\hfill
\subfloat[]{\includegraphics{110.png}}
%
\caption{Zoom de image 2.3.a de Munich (a)Image Optique (b)Image Span (c)Robert (d)Prewitt (e)Sobel
    (f)moyenneur(3$ \times $3) (g)moyenneur( (h)Canny (i)Emboss  (j)DOG (k)Laplacien (l)Résultat.}
\end{figure}
\end{document}

caption set up i left to you.


text:
Q: Why isn't the splitting field always Galois? My question stems from the proof of the fundamental theorem of algebra in Dummit and Foote. There they claim that for any real polynomial $f(x)$ with roots $\alpha_1, \dots, \alpha_n$, $\Bbb R(\alpha_1, \dots, \alpha_n, i) / \Bbb R$ is Galois. I was under the impression that $f$ had to be separable in order to guarantee that the extension was Galois, but it seems that the Dummit and Foote claim ignores this requirement.
If we let $\alpha_{n+1} = i$, $f(x) \mapsto f(x) (x ^2 + 1)$, and replace $\Bbb R$ with any perfect field $F$ then we can assume that $\alpha_i$ are just roots of a polynomial $f(x) \in F[x]$. I can then rephrase my question as follows:
If $\alpha_i$ are the roots of a polynomial $f(x) \in F[x]$ for $F$ a perfect field, is $F(\alpha_1, \dots, \alpha_N)/ F$ Galois?
My attempt is as follows. Each $\alpha_i$ has a minimal polynomial $m_i(x)$ that divides $f(x)$ because they share a root (and thus all roots of $m_i$ are roots of $f$). Each of these is separable by virtue of being irreducible with coefficients in a perfect field, so letting $g$ be the square free product of the $m_i$'s, we have that $g$ is separable. Indeed, if $m_i$ and $m_j$ shared a root $\alpha$, then any extension $K /F$ splitting $m_i$ would be Galois because $m_i$ is separable, and $m_j$ having a root in $K$ implies all of its roots are in $K$. Since the roots of $m_i$ and $m_j$ are Galois conjugates of $\alpha$, we would have that $m_i = m_j$. In other words, we have that $g$ is a separable polynomial with the same roots as $f$ with splitting field $F(\alpha_1, \dots, \alpha_N)$.
Does this mean that the extension is indeed Galois or have I missed something, am I not proving that the splitting field of any polynomial (over a perfect field) is Galois?


text:
Q: Redirection rule WordPress I need to create a redirection rule in WordPress .htaccess that will do this.
http://www.domain.com/blog/2017/article-slug -->
http://blog.domain.com/article-slug
So basically removing the year and going from sub-directory to sub-domain.
I need to do that for more than 500 articles. So the option of doing this one by one is not very viable.
Thanks so much


text:
Q: Вывод строки "заборчиком" в python Необходимо вывести строку таким образом, чтобы  каждая вторая буква была заглавной. Пробовал использование среза и метода upper(), но получилось вывести только заглавные буквы.
text = input()
print(text[0:len(text):2].upper())

A: import re

text = input('Введите текст: ')
zabor = re.sub(r'(\b|\w)(\w)', lambda x: x.group(1).lower()+x.group(2).upper(), text)
print(zabor)

A: Например, так:
text = input()
count = [i for i in range(len(text))]
print(''.join(text[i].upper() if (i % 2 != 0) else text[i] for i in count))

A: Дело в том, что командой print(text[0:len(text):2].upper()) вы пытаетесь вывести срез строки, состоящий из каждого второго символа исходной строки, к которому применён метод upper(). Поэтому и выводится только каждый второй символ (заглавный из-за upper()).
Можно пойти несколькими путями:
Во-первых, самый банальный, при помощи цикла for:
text = input()

for i in range(len(text)):
    if i % 2 == 0:
        print(text[i].upper(), end="")
    else:
        print(text[i], end="")

Во-вторых чуть более хитрый при помощи генератора-списка, в котором стоит условие, что i-й символ объекта, возвращаемого генератором (то бишь i-й символ исходной строки text) либо остаётся неизменным, либо его регистр становится верхним.
text = input()

new_text = "".join([text[i].upper() if i % 2 == 0 else text[i] for i in range(len(text))])

print(text)

Заметьте, что тут исправлен тот недостаток, что вы в своём примере "пробегали" на каждый символ исходной строки, а лишь каждый второй, и исходная строка text проходится полностью.


text:
Q: How can I match the id of two different columns using left outer join in mysql select
    pe.fk_id_produto,
    pe.qt_unitaria,
    er.FK_produto,
    IFNULL(er.quantidade_recebida,0) AS quantidade_recebida
from tblprodutoencomendado as pe
left outer join tblencomendarecebida er on er.FK_encomenda = pe.FK_num_encomenda
where fk_id_produto IN(SELECT FK_produto FROM tblencomendarecebida WHERE fk_encomenda = 13) or fk_num_encomenda = 13
group by fk_id_produto asc;

----------------------------------------------------------------
RESULT OF THIS QUERY

FK_id_produto qt_unitaria FK_produto quantidade_recebida
------------- ----------- ---------- -------------------
13            17          NULL       NULL
16            44          13         32
15            15          NULL       NULL
20            10          20         10

What I desire:
FK_id_produto qt_unitaria FK_produto quantidade_recebida
------------- ----------- ---------- -------------------
13            17          13         32
15            15          NULL       NULL
16            44          NULL       NULL
20            10          20         10

I have tried almost everything... can any one help please? thanks in advance

A: it looks that your join not on the right field
select
    pe.fk_id_produto,
    pe.qt_unitaria,
    er.FK_produto,
    IFNULL(er.FK_produto,0) AS quantidade_recebida
from tblprodutoencomendado as pe
left outer join tblencomendarecebida er on er.FK_produto = pe.fk_id_produto
group by fk_id_produto asc;


text: Q: BigQuery API limit on DELETE DML with WHERE clause I have a BQ table with ~60k rows. A portion of these rows have a field called 'Temporary' that takes a Boolean value. Every morning, I send a query to BQ via the Python pandas_gbq package. The query is simple: DELETE FROM table WHERE Temporary = 'True'. However, lately I have been getting a 400 error from the API: 400 GET ... API limit exceeded: Unable to return a row that exceeds the API limits. To retrieve the row, export the table. I'm not sure how any 'row' exceeds the API limit since this should only delete some rows, not return any. Is there a better way to programmatically delete portions of data from a BQ table?


text:
Q: JQuery Change function not work with ajax content my html code

                <input id="selectUser_07c4ab10-4ad0-44d1-9d65-aeee70be20a6" class="ms-ChoiceField-input dataListField ng-valid ng-dirty ng-valid-parse ng-touched" type="checkbox" ng-model="item.isChecked" ng-change="UpdatedSelectedUsers(item)" tabindex="0" aria-checked="false" aria-invalid="false">

My jQuery Code
  $(":checkbox").change(function() {
 $(this).closest('[ng-repeat*="item"]').nextAll('[ng-repeat*="item"]:lt(3)').find('[type="checkbox"]').prop('checked', this.checked);
  });

so it not working when content is loaded via ajax , any idea how to make it working when content is loaded via ajax on page load and also more checkboxes entries are loaded when user scroll down .
working jsfiddle with static checkboxes list :: https://jsfiddle.net/mmzth076/7/
but not work with ajax

A: Try adding the change function in the success handler of the ajax:
$.ajax {
  method: 'GET',
  success: function() {
    load_grid(); //Code that builds the grid with the checkboxes
    $(":checkbox").change(function() {
      $(this).closest('[ng-repeat*="item"]')
        .nextAll('[ng-repeat*="item"]:lt(3)')
        .find('[type="checkbox"]')
        .prop('checked', this.checked);
    });
  }
}

You can also use any known parent of the grid that is available in the DOM at the time of binding the click event handler.
$('body').on('change', ":checkbox", function () {
    $(this).closest('[ng-repeat*="item"]')
        .nextAll('[ng-repeat*="item"]:lt(3)')
        .find('[type="checkbox"]')
        .prop('checked', this.checked);
});

Replace body with any known predecessor at the time of binding.

A: When you load contain via ajax, it's it's not going to trigger the the changed event.  If you want to trigger, just use jquery and trigger the event manually.
$('checkboxyouwanttotrigger').trigger('change')


text:
Q: Proper organization for a mixture of templated and non-templated functions not accessible to the end-user In a project I am working on, I am currently implementing an algorithm which is templated. I had some problems organizing my function declarations and definitions, because templates are involved (I asked a question here about how to deal with non-templated functions "grouped" together with the templated ones). This, however, made me wonder about a general proper organization of such files.
I wanted to separate all the definitions from all the declarations (just for readability purposes, even if I had to include templated definitions back into declarations).
The answers I got suggested organization such as this:

*

*The declarations file algo.h for all the function declarations

*The templated definitions file algo.tpp which will be included in algo.h (templates need declarations at compile time)

*The (non-templated) definitions file algo.cpp not included anywhere.

This works well if all the defined functions are supposed to be visible to the end-user (i.e. all the declarations are in the algo.h file). However, sometimes I like to break my big functions into smaller functionalities, but I would like the end-user to be able to access only the "big function" and not their sub-parts. In a non-templated set-up, I would do this in this way:

*

*The declarations file algo.h would contain only the declarations meant for the end-user (which will become accessible through the include)

*The definitions of those functions would go to algo.cpp

*The definitions (and declarations) of the sub-functionalities would only be present in the algo.cpp, allowing my big function in algo.cpp (the one declared in algo.h) to use them, but not making them accessible to the end-user.

This does not work any more if those sub-functionalities are not themselves templated, but are used by the templated function. The templated sub-functionalities can go into the .tpp file, get used by the templated "big function", and everything is good.
However, if those functionalities are non-templated, they would cause a multiple definitions error (which is what my previous question was about) if placed in the .tpp file. On the other hand, if they are in the separate .cpp file, they either become accessible to the end-user (if I put the declarations in the .h file), or become inaccessible to the big function meant to use them (if I do not put the declarations outside the .cpp file).
What is the proper way of organizing functions, some templated and some not, some of which are supposed to be accessible to the end-user, and some not, into multiple files?
Ideally, (for completeness), the answer I'm looking for would address the placement of the following (in the .h, .tpp, .cpp, or other appropriate files):

*

*templated client functions

*non-templated client functions

*templated client functions

*non-templated client functions

*declarations of all of the above (when declarations are used)

Short almost-pseudo-code example of the functionality I want to have (without the file-separation)
    // Templated sub-functionality, used by bigFunctionality,
    // but ideally not accessible to the end-user
    // This might not be possible since it is templated,
    // so I am content with putting it in the .tpp file
    template <typename Compare>
    void subFunctionality(Compare order, .. args ..){ /* impl */ }

    // Non-templated sub-functionality, used by
    // bigFunctionality, but NOT accessible to the end-user
    void moreSubFunctionality(.. args ..) { /* impl */ }

    // the main functionality, meant to be
    // accessible to everybody across all files:
    template <typename Compare>
    void bigFunctionality( .. non-templated args ..., Compare order){
         subFunctionality(order, .. args ..);
         moreSubFun(.. args ..);
         // more stuff
    }

Once again, I am looking how to separate this in to multiple files (even if they are included in each other, as it has to be done with templates), partially for readability purposes and partially for accessibility.
Just for clarifications, these are algorithms --> functions, and not classes. (I know that putting templated and non-templated functions in to the same templated class would solve my problems).
PS: I know the title of the question is very big and long, so if somebody has an idea about shortening it, I would be more than happy for the suggestions/edits

A: This is an unfortunate side-effect of the absence of modules in C++: what is declared is necessarily visible.
In general, the guideline is to simply use a "private" namespace (nested within the user-visible namespace(s)):

*

*use a clear name (such as internal)

*and declare those helper functions only in that namespace in your .tpp file

Then, you document that this namespace is internal and non-suitable for client callers. If possible, you also annotate the namespace/functions so that no documentation is generated for them.
At this point, those functions are clearly private and hidden.
If you wish to go one step further, you may simply declare them private in a class (*), and then have only your functions be friend of this class. Then, any attempt to use them will result in the compiler emitting an error: they are visible, but not accessible. However, most people (starting with Boost developers) just do not bother, and I certainly do not either.
(*) The class essentially replaces the private namespace.


text:
Q: Converting NSSet to NSMutableArray Currently I have a subclass of NSManaged object called Folder with property called item that is of type NSSet.
class Folder: NSManagedObject {

@NSManaged var title: String
@NSManaged var date: NSDate
@NSManaged var item: NSSet

func itemMutableArray() -> NSMutableArray {

    var mutableArray: NSMutableArray!

    mutableArray = [item.allObjects]

    return mutableArray

}

Item class:
class Item: NSManagedObject {

@NSManaged var title: String
@NSManaged var date: NSDate
@NSManaged var completed: Bool

Does anybody have any suggestions with where I am currently going wrong ?
Here is my previous function I was using which now I want to convert my NSSet to an NSMutableArray.
func itemArray() -> [Item] {
    let sortDescriptor = NSSortDescriptor(key: "date", ascending: true)
    return item.sortedArrayUsingDescriptors([sortDescriptor]) as! [Item]
}

A: func itemMutableArray() -> NSMutableArray {
    return NSMutableArray(array: (item.allObjects as! [Item]).sorted{ $0.date.compare($1.date) == NSComparisonResult.OrderedAscending } )
}

A: use Swift types, they are much more versatile
This puts the NSSet into an Array (var is mutable) and sorts it ascending by property date
@NSManaged var title: String
@NSManaged var date: NSDate
@NSManaged var item: NSSet

var sortedItemArray : Array<Item> {
  var array = item.allObjects as! [Item]
  return sorted(array) {$0.date < $1.date }
}


text:
Q: Python handling errors after handling an error inside try-except block try:
    print(1)
    assert 2 + 2 == 5
except AssertionError:
    print(3)
except:
    print(4)

In this code after handling that assertion error by except AssertionError: the except: print(4) doesn't work.
But if I create an error after the AssertionError like this:
try:
    print(1)
    assert 2 + 2 == 5
except AssertionError:
    print(3)
    print(2/0)
except:
    print(4)

it gives an error like this:
Traceback (most recent call last):
  File "<pyshell#14>", line 3, in <module>
    assert 2 + 2 == 5
AssertionError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<pyshell#14>", line 6, in <module>
    print(2/0)
ZeroDivisionError: division by zero

But why? It suppose to except that error too. Because that error happen inside the try except block.

A: In a try - except block, the only errors filtered are those that occurred under the try statement. For example, if you want to trigger the last except instead of the AssertionError then you can try:
try:
    print(1)
    raise(IOError) #To trigger the last except
    assert 2 + 2 == 5
except AssertionError:
    print(3)
except:
    print(4)

which should output:
1
4

Remember that any errors not under a try statement directly cannot be filtered by the except.

A: As the first answer correctly describes, the ZeroDivisionError does not occur inside the try block. If you need to catch that exception, from within the first except block, then you'll need to do something like:
try:
    print(1)
    assert 2 + 2 == 5
except AssertionError:
    try:
        print(3)
        print(2/0)
    except:
        print(4) # this except block will execute during print(2/0)
except:
    pass #this except block will never execute


text:
Q: Hibernate aggregates + Spring MVC I am using Hibernate with my Spring MVC project.
Lets say my model has 2 objects each linked to Oracle tables, respectively USERS (USERID, NAME) and USERMONEYDATA (CATEGORY, USERID, AMOUNT)
My users can add , edit and remove rows in USERMONEYDATA, that belongs to them of course.
Now, I want to have a view that aggregates those data.
Using oracle, I made a simple view  to get the total amount per user and category :
select  userid, category, sum(amount)
from USERS a inner join USERMONEYDATA b on a.USERID = b.USERID
group by userid, category

But what is the best way to use it? should I create a new MODEL object specifically for this view ?
Should I aggregate directly in Hibernate ? But if yes, how do I display the results if I dont have a specific POJO object to map it to ?
thanks

A: If User and UserMoneyData are mapped as Hibernate entities, it's a natural choice to run aggregate queries in Hibernate.
By default, HQL or JPQL SELECT clause with multiple paths produces tuples in the form of Object[]. Since this kind of data is read-only, you may display these arrays directly, without converting them to objects.
Another option is to create a POJO for representing results of the query and use a constructor syntax SELECT NEW MoneyReport(u.userId, d.category, SUM(d.amount)) .... These POJOs don't need to be entities.
See also:

*

*Chapter 15. HQL: The Hibernate Query Language


text:
Q: Can the below negative equation be converted to a positive equation? $$x+iy=\sqrt { \frac { a+ib }{ c+id }  }$$, prove that $$(x^{ 2 }+y^{ 2 })^{ 2 }=\frac { { a }^{ 2 }+{ b }^{ 2 } }{ { c }^{ 2 }+{ d }^{ 2 } } $$
Solving by myself, I have got this:
$$(x^{ 2 }-y^{ 2 })^{ 2 }=\frac { { a }^{ 2 }-{ b }^{ 2 } }{ { c }^{ 2 }-{ d }^{ 2 } } $$
Can this be changed to what is required or this approach is itself wrong?

A: hint: $(x+iy)^2(c+id) = a+ib \implies |x+iy|^2|c+id| = |a+ib|$, and square both sides with note that $|m+in| = \sqrt{m^2+n^2}$.


text:
Q: get city name from longitude and latitude using google geocoding api jquery I want to get city name from longitude and latitude.
I am using following code but it is returning the entire address with city name, postal code, province and country.
I just want only city name.
     $.ajax({ url:'http://maps.googleapis.com/maps/api/geocode/json?latlng='+position.coords.latitude+','+position.coords.longitude+'&sensor=true',
               success: function(data){
               alert(data.results[4].formatted_address);

               }
               });

Please see the result from geocoding
{
           "long_name" : "Vancouver",
           "short_name" : "Vancouver",
           "types" : [ "locality", "political" ]
        },

A: formatted_address is always going to return you a full address string, due to the nature of the datatype from the API.  You need to directly reference the locality type in the address_components array.
Google Maps Geocoding API
So for example, you need to search through the returned address_components array for the locality type:
for (var i = 0; i < data.results[4].address_components.length; i++) {
    for (var j = 0; j < data.results[4].address_components[i].types.length; j++) {
        if(data.results[4].address_components[i].types[j] == 'locality') {
            var city_name = data.results[4].address_components[i].long_name;
            alert(city_name);
        }
    }
}

A: I ran into an issue where not all localities are in results[4] so I looped through all.
url = "http://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+lng+"&sensor=true";
$.ajax(url).done(function(data) {
    for (var i = 0; i < data.results.length; i++) {
        for (var j = 0; j < data.results[i].address_components.length; j++) {
            for (var k = 0; k < data.results[i].address_components[j].types.length; k++) {
                if (data.results[i].address_components[j].types[k] === 'locality') {
                    var city_name = data.results[i].address_components[j].long_name;
                }
            }
        }
    }
}

NOTE: This is also using update jQuery AJAX syntax since the original post..

A: You need to check some variables to ensure that code will work for every positions, even if locality/city is not present:
var url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='+latitude+','+longitude+'&sensor=false'

$.ajax({
    dataType: "json",
    url: url,
    async: false,
    scriptCharset: "utf-8",
    contentType: "application/json; charset=utf-8",
    success: function(json)
    {
        var found_city = false;
        if (json && json.results.length > 0)
        {
            for (var k=0; k < json.results.length; k++ ) {
                if (json.results[k].address_components) {
                    for (var i = 0; i < json.results[k].address_components.length; i++) {
                        if (json.results[k].address_components[i]) {
                            for (var j = 0; j < json.results[k].address_components[i].types.length; j++) {
                                if(json.results[k].address_components[i].types[j] == 'locality') {
                                    var city_name = json.results[k].address_components[i].long_name;
                                    alert(city_name);
                                    found_city = true
                                }
                            }
                        }
                    }
                }
            }
         }
        if (!found_city) {
            alert("City not found!");
        }
    }
})
.fail(function( jqxhr, textStatus, error ) {
    var err = textStatus + ", " + error;
    alert("Request Failed: " + err );
});


text:
Q: Load Image From Api And Cache It I am getting the image from api which i created a Gson model for to get the items, now i try loading the image on glide but it's not showing, the image response looks like this
"image":"2017\/Oct\/1507106147_IMG-20171003-WA0003.jpg"

i just want to know how to cache the image so that it can be displayed and scroll smoothly on listview.

A: I don't think that's valid url/model to load your image.
If your image is on server, you must make sure you get the right url to access it like this one:
"image":"https://www.blog.google/static/blog/images/google-200x200.7714256da16f.png"

or maybe you get just a piece of it but you still need to make it become full link so it can be accessed, like this one:
"image":"/images/google-200x200.7714256da16f.png"

String base_url = "https://www.blog.google/static/blog/";
String full_url = base_url + image;


text:
Q: Create searcher to Dataview in Sencha Touch 2 In the dataview component i can insert a dataitem, but how i do insert a searcher?,  as in the list component

A: Dataviews and Lists are directly bound to Stores (Ext.data.Store). Therefore, anything that happens to that store will be reflected in the view.
So what you need to do is filter the store. You can do this by using the filter or filterBy methods on store.
More information: http://docs.sencha.com/touch/2-0/#!/api/Ext.data.Store-method-filter
Example
var store = Ext.create('Ext.data.Store', {
    fields: ['text'],
    data: [
        { text: 'one'},
        { text: 'two'},
        { text: 'three'}
    ]
});

store.filter('text', 'one'); // will only show the one record


text:
Q: Main method does not end in Eclipse I am developing tests in Eclipse (Indigo) using java (1.6) and WebDriver (2.16).
I have a fairly simple test that runs fine, but does not actually 'end'.  What I mean is that after all of the lines of code in the 'main' method have been executed, the Eclipse console still indicates that the code is running (red 'Terminate' button in the console is enabled).
This only started happening yesterday, after I extended the testing script with some new code.  Thinking that was the problem, I commented all new code.  Unfortunately, the problem persists.
How do I go about troubleshooting this?
Thanks for your input.
Edit
Below the relevant parts of a JStack thread dump. See here for the full dump

2012-01-07 10:56:40 Full thread dump Java HotSpot(TM) 64-Bit Server VM
  (20.4-b02 mixed mode):
"Thread-7" daemon prio=6 tid=0x0000000008c08800 nid=0x12f4 runnable
  [0x000000000 921f000]    java.lang.Thread.State: RUNNABLE
          at java.io.FileInputStream.readBytes(Native Method)
          at java.io.FileInputStream.read(Unknown Source)
          at org.apache.commons.exec.StreamPumper.run(StreamPumper.java:105)
          at java.lang.Thread.run(Unknown Source)
"Thread-6" daemon prio=6 tid=0x0000000008d7b800 nid=0xb98 runnable
  [0x0000000009 11f000]    java.lang.Thread.State: RUNNABLE
          at java.io.FileInputStream.readBytes(Native Method)
          at java.io.FileInputStream.read(Unknown Source)
          at java.io.BufferedInputStream.fill(Unknown Source)
          at java.io.BufferedInputStream.read1(Unknown Source)
          at java.io.BufferedInputStream.read(Unknown Source)
          - locked <0x00000007d5a00888> (a java.io.BufferedInputStream)
          at java.io.FilterInputStream.read(Unknown Source)
          at org.apache.commons.exec.StreamPumper.run(StreamPumper.java:105)
          at java.lang.Thread.run(Unknown Source)
"Thread-5" prio=6 tid=0x000000000678b000 nid=0x10e4 runnable
  [0x000000000901f000 ]    java.lang.Thread.State: RUNNABLE
          at java.lang.ProcessImpl.waitFor(Native Method)
          at org.apache.commons.exec.DefaultExecutor.executeInternal(DefaultExecut
  or.java:347)
          at org.apache.commons.exec.DefaultExecutor.access$200(DefaultExecutor.ja
  va:46)
          at org.apache.commons.exec.DefaultExecutor$1.run(DefaultExecutor.java:18
  8) "main" prio=6 tid=0x000000000062e000 nid=0x450 runnable
  [0x000000000261f000]    java.lang.Thread.State: RUNNABLE
          at java.lang.Thread.exit(Unknown Source)

EDIT
Here's my Excel code (using java IO and Apache's POI classes)
public HashMap<String, String> getTestData()
{
    InputStream myxls = null;

    try {
        // Create a connection to the Excel file
        myxls = new FileInputStream(fileName);
        System.out.println("Excel Input was opened");
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        //e.printStackTrace();
    }

    // Define a workbook object
    HSSFWorkbook wb = null;

    try {
        // Instantiate the workbook object
        wb = new HSSFWorkbook(myxls);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // Create a worksheet object
    HSSFSheet sheet = wb.getSheet(sheetName);
    // Read the first row (it always contains the headers (variable names)
    HSSFRow headerRow = sheet.getRow(0);
    // Read the row requested
    HSSFRow row = sheet.getRow(dataRow);

    //System.out.println("Creating a new HashMap from row " + dataRow + " in sheet " + sheetName);

    // Define a collection of value/value pairs
    HashMap<String,String> testData = new HashMap<String,String>();

    // Get count of columns != empty
    int columnCount = row.getPhysicalNumberOfCells();
    //System.out.println(Integer.toString(columnCount));

    String textHeader;
    String textData;

    // Loop through the columns
    for(int colcount=0; colcount < columnCount; colcount++)
    {
        // Read the column header and the cell value
        HSSFCell cell = row.getCell(colcount);
        HSSFCell headerCell = headerRow.getCell(colcount);

        switch (headerCell.getCellType ())
        {
            case HSSFCell.CELL_TYPE_NUMERIC :
            {
                // cell type numeric.
                textHeader = Double.toString(headerCell.getNumericCellValue());
                //System.out.println(textHeader);
                break;
            }
            case HSSFCell.CELL_TYPE_STRING :
            {
                // cell type string.
                HSSFRichTextString richTextString = headerCell.getRichStringCellValue();
                textHeader = richTextString.getString();
                break;
            }
            default :
            {
                // types other than String and Numeric.
                textHeader = "Type not supported";
                break;
            }

        }

        switch (cell.getCellType ())
        {
            case HSSFCell.CELL_TYPE_NUMERIC :
            {
                // cell type numeric.
                textData = Double.toString(cell.getNumericCellValue());
                break;
            }
            case HSSFCell.CELL_TYPE_STRING :
            {
                // cell type string.
                HSSFRichTextString richTextString = cell.getRichStringCellValue ();
                textData = richTextString.getString();
                break;
            }
            case HSSFCell.CELL_TYPE_BLANK :
            {
                // cell type string.
                textData = "";
                break;
            }
            default :
            {
                // types other than String and Numeric.
                textData = "Type not supported";
                break;
            }

        }

        // Add the value of each cell to the HashMap collection
        testData.put(textHeader,textData);
        //System.out.println(textHeader + " / " + textData);

    }

    try{
        // End the file object

        myxls.close();
        System.out.println("Excel Input was closed");
    }
    catch (IOException e){
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // Send the HashMap back to the calling code
    return testData;

}

A: For troubleshooting this you can take a thread dump, for example by using the jstack command (there is a whole SO question on this ). This allows you to see which threads are still running and which part of your code they are executing.
Edit
Based on the JStack output I would say you read some files on a separate Thread and the read method is still blocking, waiting for input as documented in the javadoc of FileInputStream#read.

A: After debugging my code, I believe I have found the culprit:
The Selenium WebDriver classes come with several 'drivers', one for each supported browser type (IE, Firefox, Chrome).  When I create a Firefox object, it tries to enable logging through log4j (which I have not configured since I don't use it).  I believe log4j causes the hung threads.


text:
Q: Carousel not visible when active state is removed? I am making carousel and inserting it in col-md-8 and remaining 4 grids are for side navigation. When I remove active class from wrapper class for slides then my carousel is not visible why does this happen why do we need to make it active.

If I change class="item active" to class="item" then my carousel is not visible why does this happen.

A: Because that indicates to the carousel component which slide is to be visible first. Read the Bootstrap docs..

Initial active element required
  The .active class needs to be added to one of the slides. Otherwise, the carousel will not be visible.

A: Active state means that is displaying one element from the list of images in your carousel, meaning if you don't have active state on any of the items will not display any slides, resulting in not displaying at all the carousel, since the height of the carousel is determined by the height of the active tab.


text:
Q: FindBugs RV_ABSOLUTE_VALUE_OF_RANDOM_INT warning I'm trying to do a code review for our project using FindBugs.
we have a method to generate unique id (randomly) :
 public static String generateUUID(int base){

    return String.valueOf(getCurrentTimeInNanos((long)base))  +

                     String.valueOf(Math.abs(random.nextInt()));
 }

and findBugs indicates RV_ABSOLUTE_VALUE_OF_RANDOM_INT warning (RV: Bad attempt to compute absolute value of signed 32-bit random integer ) , i guess the problem is in String.valueOf(Math.abs(random.nextInt()).
Does anyone have an explanation for why is this and how to fix it ?

A: Maybe it is because Math.abs can actually return negative results for integer inputs:
assertTrue( Math.abs(Integer.MIN_VALUE) < 0 );

It only does this for MIN_VALUE, though, because -MIN_VALUE cannot be represented. Kind of an overflow problem.
As for how to fix it:

*

*don't make your own UUID. Use java.util.UUID.

*cast the random number to long before calling Math.abs

*use random.nextInt(Integer.MAX_VALUE) to get a number from 0 to MAX_VALUE - 1


text:
Q: Getting different feeds from one URL i am trying to get some data(stats) from a specific YouTube channel. For this i am using following URL:
https://gdata.youtube.com/feeds/api/channels/rX3yH7nFEQq49lQGVk2Iqg?v=2
When i enter this URL directly into FireFox Addressbar i get the result i am looking for. BUT
if i open the exact same URL with:
$data = simplexml_load_file('https://gdata.youtube.com/feeds/api/channels/rX3yH7nFEQq49lQGVk2Iqg?v=2');

i get a completly different result(using print_r($data))!
Is there an explanation for this? Are i am doing something wrong? Is there something missing?
Thank you!

A: The most useful information about a channel will actually come from the /users/ service, not the /channels/.
You could also add in alt=json, unless you really like parsing XML instead of working with JSON.
Finally, the "correct" form for a channel id has a UC prefix, though v2 supports channel ids without the prefix as well.
Putting that all together gives you https://gdata.youtube.com/feeds/api/users/UCrX3yH7nFEQq49lQGVk2Iqg?v=2&alt=json
(leave out alt=json to work with simplexml_load_file())


text:
Q: TargetInvocationException - Object reference not set to an instance of an object. for Automapper I am Frequently seeing following error in Windows Event Viewer – Application Error Log. This is happening on Amazon Windows Server.
Web application is in the ASP.net MVC 5. I have recently updated NuGet package for solution just to overcome this error but error still exists.
Event code: 3005
Event message: An unhandled exception has occurred.
Event sequence: 22
Event occurrence: 9
Event detail code: 0

Application information:
    Trust level: Full
    Application Virtual Path: /
    Application Path: WebApPath
    Machine name: EC2AMAZ-TUK4T6L

Process information:
    Process ID: 9628
    Process name: w3wp.exe
    Account name: IIS APPPOOL\ AppPoolName

Exception information:
    Exception type: TargetInvocationException
    Exception message: Exception has been thrown by the target of an invocation.
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeConstructorInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.FastCreateInstance(Type implType, Object[] arguments, ConstructorCandidate constructor)
   at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.CreateInstanceCore(ConstructorCandidate constructor, Object[] arguments, Type implType)

Object reference not set to an instance of an object.
   at AutoMapper.TypeMapFactory.<>c__DisplayClass3_0.<MapDestinationPropertyToSource>b__0(IMemberConfiguration _)
   at System.Linq.Enumerable.Any[TSource](IEnumerable`1 source, Func`2 predicate)
   at AutoMapper.TypeMapFactory.CreateTypeMap(Type sourceType, Type destinationType, IProfileConfiguration options, MemberList memberList)
   at AutoMapper.ConfigurationStore.<>c__DisplayClass80_0.<CreateTypeMap>b__0(TypePair tp)
   at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
   at AutoMapper.ConfigurationStore.CreateMap[TSource,TDestination](String profileName, MemberList memberList)
   at AP.Web.Services.Services.CustInfoService..ctor(ICustInfoRepository repository)

Thread information:
    Thread ID: 22
    Thread account name: IIS APPPOOL\ AppPoolName
    Is impersonating: False
    Stack trace:    at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeConstructorInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.FastCreateInstance(Type implType, Object[] arguments, ConstructorCandidate constructor)
   at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.CreateInstanceCore(ConstructorCandidate constructor, Object[] arguments, Type implType)

Custom event details:

Not been able to determine why this error coming up. Your help will be greatly appreciated.
Thankyou,
Raj.


text:
Q: How do i make my function in my player class for game of hearts work without being a pointer? I was assigned to make a game of hearts where there is an array of 4 people and each people has a hand of 13 cards. Currently, when dealing trying to deal cards to each person deck, I am only able to accomplish this using pointers. However, this has posed problems in getting other functions like sort and such to work. I know that it's possible to do it without pointers I'm just not sure how and was wondering if anybody could assist.
In the psudocode, my teacher gave us, the hand[13] array which holds the cards is not a pointer, but I made it a pointer in order to points the cards to it.
  #include <iostream>
  #include <iomanip>
  #include "Card.h"
  #include "Player.h"
  #include <cstdlib>
  #include <random>
  using namespace std;

  //Prototype

   void shuffleDeck(Card deck1[])
      {

          int ranNum;
          Card temp;
          int count = 0;

    for(int i = 0; i < 52; i++)
    {
          count++;
          ranNum = (rand() % 52);
          temp = deck1[ranNum];
          deck1[ranNum] = deck1[i];
          deck1[i] = temp;

    }

     }

  int main()
  {

     //Declarations
      int nextPlayer;
      int firstPlayer;
      Card deck2[4][13];
      Suit temp;
      Card deck1[52];
      int count = 0;
      int check = 0;
      int round = 0;
      int points = 0;
      int numCards = 0;

 //Part 1: The set-up

//Create player array of [4] players
Player player[4] = {Player("Me"),
                    Player("Elton John"),
                    Player("Snoop Dog"),
                    Player("Lady Gaga")
                   };

//create and initialize deck;
    for (int r = 0; r < 4; r++)
    {

       for (int c = 0; c < 13; c++)
        {

        deck2[r][c].setNumber(c + 1);
        temp = ((Suit)r);
        deck2[r][c].setSuit(temp);

        deck2[r][c].setDescription();

        }

    }

  //Convert to one dimensional array
  for(int i = 0; i < 4; i++)
  {
      for(int j = 0; j < 13; j++)
      {
          deck1[count] = deck2[i][j];
          count++;

      }
  }
         shuffleDeck(deck1); //call shuffle deck function

//Deal deck to players // have add card in player class that sticks a card in players deck
/*
for(int i = 0; i < 52; i++)
{
    int playerIndex = i % 4;
    player[playerIndex].addCard(&deck1[i]); //HERE IS WHERE I CALL IT IN THE MAIN
}

//Sort each players hand
for (int i = 0; i < 4; i++)
{
    player[i].sort();
}
//Find player who goes first (the person holding the 2 of clubs) //firstPlayer

for(int j = 0; j < 4; j ++)
{
    for(int i = 0; i < 13; i++)
    {

        if(player[j].getCard(i) == 20)
        {
            firstPlayer = j;
        }
    }
}
*/

 Card openCard[4]; //keeps track of all played cards

//  //Part 2: The play
 for(int i = 0 ;  i < 13; i++) //gonna play 13 rounds, same thing 13 times
 {  numCards = 0;
     round++;

//     Print points of players
cout << "\nPlayer     Round " << round << "  Total\n";
cout << "-------    --------  -----\n";
cout << "\nMe ";
cout << "\nSnoop Dogg ";
cout << "\nLady Gaga  ";
cout << "\nElton John ";

//     Print hand
cout << "\n\nMy Hand: \n" << "-------------\n\n";

   for(int i = 0; i < 13; i++)
   {
//   cout << player[0].getCard(i) << "\n";
   numCards++;
   check++;
   cout << numCards << ".) " <<  deck1[i].getDescription() << "\n";

   }

     for (int j = 0; j < 3; j++)
     {
     nextPlayer = (firstPlayer + j) % 4;

     //Play a card
     //Compare card to other card

    //  openCard[nextPlayer] = player[nextPlayer].playCard(deck1[i], firstPlayer);

     //inside playCard() remove card from hand after it's played
    //  hand[cardPlayed] = null //null means played already// (I think this is another method of doing it)

      }
     //end for j

   //count points per player

   //firstPlayer = winner of round //implement this in
//   if(firstPlayer) //something like this
//   {
//       points++;
//   }
   //add points to first player

 }
//end for i

return 0;
}

//PLAYER CLASS

 #ifndef PLAYER_H
 #define PLAYER_H
 #include "Card.h"
 #include <iostream>
 #include <iomanip>
 using namespace std;

 class Player
 {
  //Member variables
private:
string name;

public:
static int count;
Card *hand[13]; //TRYING TO MAKE THIS NOT A POINTER
int number;
bool played;

//Constructors

Player()
{

    name = "";

}

Player(string n)
{
    name = n;

}

string getName()
{
    return name;
}

int getCard(int index)
{
    return hand[index]->getNumber();
}

void setName(string n)
{
    name = n;
}

 //     void addCard(Card *card) //THIS IS WHERE CARDS ARE DELT (HOW DO I
 MAKE IT NOT A POINTER?)
 //     {

 //          if (number < 13)
 //          {
//              hand[number] = card;
//              number++;
 //          }
 //     }

  //    void sort()
 //     {
 //         for (int i = 1; i < 13; i++)
 //         {

 //     Card *temp;
 //     bool swap = false;
 //     int size = 52;
 //     do
 //     {
 //         swap = false;
 //         for (int count = 0; count < (size - 1); count++)
//         {
//             if (hand[count + 1] < hand[count])
//             {
//                 temp = hand[count];
//                 hand[count] = hand[count + 1];
//                 hand[count + 1] = temp;
//                 swap = true;
//             }
//         }
//     }
//     while (swap == true);
//      }
//      }

//      Card playCard(Suit lead, bool leader)
//      {
//          int cardPlayed;

//      hand[cardPlayed] = -1; //null means played already// (I think this
is another method of doing it)
//      }

};

#endif


text:
Q: Updating an entry on MediaStore does not work on Android Q / API29 I am trying (without luck) to update entries for MediaStore for both audio tracks and images. I am using something like this:
ContentValues values = new ContentValues();
values.put(MediaStore.Audio.Media.TITLE, title);
values.put(MediaStore.Audio.Media.YEAR, year);

resolver.update(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values, MediaStore.Audio.Media._ID + "= ?", new String[] { String.valueOf(id) })

The above snippet works on API16->API28 without problems.
Though, on API29 it does not work. No errors are displayed on logs or messages. I am trying the above code on the API29 emulator. I am not sure if this issue is related to using an emulator or not.
I would really appreciate any information that points me in the right direction.

A: https://stackoverflow.com/a/60152702/786656 worked for me.
You need to call update once with the flag IS_PENDING set to 1. Then you call update again with the modified values you want and the flag IS_PENDING set to 0.


text:
Q: Python regular expression findall * I am not able to understand the following code behavior.
>>> import re
>>> text = 'been'
>>> r = re.compile(r'b(e)*')
>>> r.search(text).group()
'bee' #makes sense
>>> r.findall(text)
['e'] #makes no sense

I read some already existing question and answers about capturing groups and all. But still I am confused. Could someone please explain me.

A: When a pattern contains a capture group, findall returns only the content of the capture group and no more the whole match.
If this behaviour looks strange, it can be very useful to extract easily parts of a string in a particular context (substring before or after), especially since python re module doesn't support variable length lookbehinds.

A: The answer is simplified in the Regex Howto
As you can read here, group returns the string matched by the Regular Expression.

group() returns the substring that was matched by the RE.

But the action of findall is justified in the documentation

If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group

So you are getting the matched part of the capture group.
Some experiments include :
>>> r = re.compile(r'(b)(e)*')
>>> r.findall(text)
[('b', 'e')]

Here the regex has two capturing groups, so the returned values are a list of matched groups (in tuples)


text:
Q: How do I get Visual Studio to place the unit tests where I want them? In both VSTS 2008 and VS 2010 RC1 when I create a Unit Test (mstest), I am not asked where I would like the project to be placed.  It will always turn up at the Solution level.  I would like to place the test project inside the folder of the class(es) that are being tested.
I have tried unloading the unit test project and adding it to the class library, but that breaks the coupling with the class.
I am using Visual Studio 2010 Ultimate RC1 with ReSharper 5.0 and Visual Stuido 2008 with RS 4.5.
TIA,
Jim
Amended:  I was not at all clear about placing the unit tests.  I have a Solution with several Solution Folders.  One of these is a common library.  I would like to add unit tests for some classes in the library.  VS will place the TestProject at the base Solution level.  I would prefer
mySolution
mySolution\SolutionFolder
mySolution\SolutionFolder\ClassLibrary
mySolution\SolutionFolder\ClassLibrary\Class1.cs
mySolution\SolutionFolder\ClassLibrary\Class2.cs
mySolution\SolutionFolder\UnitTestForClass1
mySolution\SolutionFolder\UnitTestFOrClass2
Instead, VS will do:
mySolution
mySolution\SolutionFolder
mySolution\SolutionFolder\ClassLibrary
mySolution\SolutionFolder\ClassLibrary\Class1.cs
mySolution\SolutionFolder\ClassLibrary\Class2.cs
mySolution\UnitTestForClass1
mySolution\UnitTestFOrClass2
I hope this is clearer.  Thank you.
I do apologize for all the miss-edits I have posted.

A: The normal practice is to segregate byb source/source and source/test at the highest level.
In other words, suppose you have a "solution" with 3 projects, each of which builds a distinct assembly.  You might have a source tree like this:
soln\sourcesrc\proj1
soln\sourcesrc\proj2
soln\sourcesrc\proj3

The test code would normally be like this:
soln\testsrc\proj1
soln\testsrc\proj2
soln\testsrc\proj3

This is independent of Visual Studio or mstest.  This is just how I have seen it done, pretty much everywhere.

A: Projects don't go inside of other projects with Visual Studio. Is there any other project type you've seen go inside of another project?


text:
Q: Android WebView not redirecting to another page. SPA website I got a website and I want the website to become a mobile app since it is responsive. I decided to make it as a WebView since it is the easier to do because I am not a mobile dev. My website uses Laravel + Vuejs SPA (single page application). But after I log in when I click to the navbar, It does not redirect me to the next page. Can someone tell me what I missed? Does it concern my website or its just an android problem?
MainActivity.java
package com.example.carrental;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {

    WebView web;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        web = findViewById(R.id.webView);
        WebSettings webSettings = web.getSettings();
        webSettings.setJavaScriptEnabled(true);
        web.setWebViewClient(new Callback());
        web.loadUrl("http://52.74.70.6:90/");

    }

    private class Callback extends WebViewClient {
        @Override
        public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
            return false;
        }
    }
}

AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.carrental">

    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <application
        android:networkSecurityConfig="@xml/network_security_config"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

A: you can watch your url redirection when website open in web view by below code
 public class PaymentWebActivity extends Activity {

    private WebView webView;
    private String link = "";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_paymentview);
        webView = (WebView) findViewById(R.id.webview);
        if (getIntent().getExtras() != null) {
            link = getIntent().getExtras().getString("link");
        }
        initWebView();
    }

    private void initWebView() {
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        WebViewClientImpl webViewClient = new WebViewClientImpl(this);
        webView.setWebViewClient(webViewClient);
        webView.loadUrl(link);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && this.webView.canGoBack()) {
            this.webView.goBack();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    public class WebViewClientImpl extends WebViewClient {

        public WebViewClientImpl(Activity activity) {
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView webView, String url) {
            if (url.indexOf(link) > -1) return false;
            Log.e("Url :", url);
            checkUrl(webView, url);
            return false;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }

        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        public boolean shouldOverrideUrlLoading(WebView webView, WebResourceRequest webResourceRequest) {
            if (webResourceRequest.getUrl().toString().indexOf(link) > -1) return false;
            Log.e("Url :", webResourceRequest.getUrl().toString());
            checkUrl(webView, webResourceRequest.getUrl().toString());
            return false;
        }

    }

    private void checkUrl(WebView webView, String url) {
        if (checkSuccessUrl(url)) {
            webView.destroy();
            Intent returnIntent = new Intent();
            setResult(Activity.RESULT_OK,returnIntent);
            finish();
        } else if (checkErrorUrl(url)) {
            webView.destroy();
            Uri uri = Uri.parse(url);
            String errorMessage = uri.getQueryParameter("message");
            showConfirmDialog(errorMessage);
        }
    }

    private void showConfirmDialog(String errorMessage) {
        final Dialog dialog = new Dialog(PaymentWebActivity.this);
        Window w = dialog.getWindow();
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.dialog_error);

        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        lp.copyFrom(w.getAttributes());
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        w.setAttributes(lp);
        w.setBackgroundDrawableResource(android.R.color.transparent);

        TextView lbltitle = (TextView) w.findViewById(R.id.tvTitle);
        lbltitle.setText(CommonFunctions.getInstance().getArabicText(PaymentWebActivity.this, "APP Name"));
        lbltitle.setTypeface(CommonFunctions.getInstance().getRegular(PaymentWebActivity.this));

        TextView lblmessage = (TextView) w.findViewById(R.id.tvMessage);
        lblmessage.setText(CommonFunctions.getInstance().getArabicText(PaymentWebActivity.this, errorMessage));
        lblmessage.setTypeface(CommonFunctions.getInstance().getRegular(PaymentWebActivity.this));

        Button btnOk = (Button) w.findViewById(R.id.btnOk);
        btnOk.setText(CommonFunctions.getInstance().getArabicText(PaymentWebActivity.this, "OK"));
        btnOk.setTypeface(CommonFunctions.getInstance().getBold(PaymentWebActivity.this));
        btnOk.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                dialog.dismiss();
                finish();
            }
        });

        Button btnCancel = (Button) w.findViewById(R.id.btnCancel);
        btnCancel.setVisibility(View.GONE);
        /*btnCancel.setText(CommonFunctions.getInstance().getArabicText(PaymentWebActivity.this, "Cancel"));
        btnCancel.setTypeface(CommonFunctions.getInstance().getBold(PaymentWebActivity.this));
        btnCancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });*/

        dialog.setCancelable(false);
        dialog.show();
    }

    private boolean checkSuccessUrl(String url) {
        return url.contains("success.php");
    }

    private boolean checkErrorUrl(String url) {
        return url.contains("error.php");
    }
}

*

*success.php

*error.php

these two files are created on a server side so when checkUrl found this files we can execute our logic as per the url. you can also forward page as per the found.


text:
Q: jQuery UI Slider controller can replace other image? (can customize?) I have a simple question.

See. that's a basically slider .
But I want to change it.
Like this.

is it possible ???? ?
Thanks!!

A: I found it my self.
.ui-slider .ui-slider-handle{
    width:50px;
    height:50px;
    background:url(../images/slider_grabber.png) no-repeat; overflow: hidden;
    position:absolute;
    top: -10px;
    border-style:none;
}

here is stackoverflow's other question page :

How to change Jquery UI Slider handle


text:
Q: remove text in parentheses and the parentheses using .filter() or .slice() i have a table with code like this:

               5-17
               23.6 (22.0-24.0)
               18.0 (17-20.0)

               Total 0-17
               20.6 (8-15.6)
               16.1 (22.2-24.0)

i am using the following function to find the contents of the table cells and bring it into an array:
var l1 =   $('#datatable td:nth-child(2)').map(function() {
     return $(this).text();
    }).get();

the table fragment's id is "datatable".
this returns properly, however i am putting this array into jqPlot and it cant read the stuff between the parentheses or the parentheses themselves.
i need the data to remain in the table however because we are displaying both the table and the chart.
i cant reformat (add spans around the content i want to remove etc) because these tables are being generated by another piece of software.
i think what i need to do is either slice off after the space or use a regex to find and remove. not sure how to proceed with either of these. thanks!

A: You can use:
return $(this).text().match(/\S+/)[0];

This will take only everything up to the first space.
In a regular expression:
\S means a non-whitespace character.
\S+ means a sequence of one or more non-whitespace characters.
The regex will take as many non-whitespace characters as possible and return them.
The [0] at the end is needed because the match function returns an array, in this case consisting of only one element.
Edit: fixed bug in above code: it was missing the [0]


text:
Q: Is there an $\varepsilon >0$ such that if $xSuppose $l<y\in\mathbb{R}$ Is there a $0<\varepsilon$ such that $\varepsilon + l<y$?
This came across in my attempt to prove that if there is a sequence in the reals such that $x_n\in(0,1]$ for all $n$ and $\lim x_n = l\notin(0,1]$ then $\lim x_n = 0$. My proof was by contradiction:
By hypothesis we know the limit exists. Now suppose $\lim x_n \neq 0$. Notice that $\lim x_n \ngeq 1$ since $\lim x_n \notin(0,1]$ and because $x_n\leq 1$ for all $n$.
Consider that $\lim x_n = l< 0$. This means that for all $0<\varepsilon$ there is $N\in\mathbb{N}$ such that for all $n\in\mathbb{N}$ if $n>N$ then $-\varepsilon +l < x_n<\varepsilon +l$. I used the argument at the beginning to arrive to a contradiction (i am not sure if it is true). That is, there exists $0<\varepsilon$ such that $\varepsilon + l<0$. Hence $x_n<0$ but this is not possible since $x_n\in(0,1]$
So it must be that $l=0$
I'll appreciate any guidence. An other answer to the fact is welcomed, however I have more interest in the argument of the first line.

A: Yes this is correct. You can take any positive $\varepsilon$ less than $y-l$, which is positive. Your argument looks fine to me.


text:
Q: How to read FFMPEG with Go? How can you read UDP sent from ffmpeg?
I wrote a script to listen to UDP packets and write them into file, but the file is invalid and almost twice the size.
This is how I send the data:
ffmpeg -i video.mp4 -c:a aac -ar 48000 -ab 196k \
 -ac 2 -strict -2 -c:v libx264 -vb 500k -r 25 -s 320x240 \
 -ss 00.000 -f mp4 -movflags frag_keyframe+empty_moov \ udp://127.0.0.1:1936

This is the code in Go. It should simply write the video into a new video file:
package main

import (
  "net"
  "os"
)

func main(){
  var buf []byte = make([]byte, 512)
  addr, _ := net.ResolveUDPAddr("udp", ":1936")
  conn, _ := net.ListenUDP("udp", addr)
  defer conn.Close()

  os.Create("new_video.mp4")
  f, _ := os.OpenFile("new_video.mp4", syscall.O_WRONLY, 0644)
  defer f.Close()

  for {
    n, _ := conn.Read(buf)
    f.Write(buf[0:n])
    buf = make([]byte, 512)
  }
}

Thanks
Updated
I changed the format to mp4 but the file is still invalid.

A: The buffer size on the server was too small (512byte)


text:
Q: How to verify JSON request and response in Java? I have created selenium data driven frame work to register new users. I'll be creating the new user registration via UI, using selenium code. Once the user registration is complete, I access the REST API url, API request, and I need to verify the response.
How can I verify this? I have the API URL, REST API request and REST API response.
Please guide me.  I'm using Java as a programming language.

A: If you are using Python, use requests for GET or POST or whatever you need.
Below is the example you can follow :
    def get_Request(self, resourceURI):
        url = baseURL + resourceURI
        headers = "header value"
        r = requests.get(url,headers=headers)
        print r.status_code
        print r.text

that will give you status code and text which you can compare as you would like
For POST
    def post_Request(self, resourceURI, payload):
        url = baseURL + resourceURI
        headers = "Headers here"
        r = requests.post(url,'data',json,headers=headers)

Don't forget to import requests
Here is your guide for requests
http://docs.python-requests.org/en/master/
If you are using java , follow this :
http://unirest.io/java.html


text:
Q: MySQL Join on Same Table using WHERE I have a table that keeps track of pinball high scores. Tables/Columns as follows:
table: pinball_scores
columns: table_id (pinball table), initials, score

What I want to be able to do is get the high score for an individual pinball table (table_id, MAX(score)) and then compare it to a players highest score for that pinball table (table_id, initials, MAX(score)) and show the difference ( table_high_score - player_table_high_score = difference.
EDIT: Since apparently I didn't ask "right"
Given the following data:
#1
table_id: 1 (pinball table game id, ie. "Attack From Mars")
MAX(score): 810000 AS game_high_score WHERE table_id='1'
#2
table_id: 1
initials: AAA (player name)
MAX(score) WHERE table_id='1' AND initials='AAA' AS player_game_high_score
#3
table_id: 1
SUM(game_high_score - player_game_high_score) AS 'difference'
Desired output:
game_high_score | player_game_high_score | difference
I am aware this is basic SQL, and I am a beginner at SQL, which is why I'm here asking the question.

A: Here is how to get the maximum score per game:
select table_id, max(score) as high_score
from pinball_scores
group by table_id;

Here is how to get the maximum score per game and player:
select table_id, initials, max(score) as high_score
from pinball_scores
group by table_id, initials;

The two combined:
select
  table_id,
  p.initials,
  p.high_score as player_game_high_score,
  g.high_score as game_high_score,
  g.high_score - p.high_score as difference
from
(
  select table_id, max(score) as high_score
  from pinball_scores
  group by table_id
) g
join
(
  select table_id, initials, max(score) as high_score
  from pinball_scores
  group by table_id, initials;
) p using (table_id)
order by table_id, p.initials

You can add a WHERE clause to limit this to a single player of course.


text:
Q: Omit the minus "-" in Liferay friendly URL I've created a friendly URL file for my abc-portlet (the portlet uses the DefaultFriendlyURLMapper):
<routes>
    <route>
        <pattern>/{urlTitle}</pattern>
        <implicit-parameter name="p_p_lifecycle">0</implicit-parameter>
        <implicit-parameter name="struts_action">/view</implicit-parameter>
    </route>
</routes>

This works like a charm, but I would like to understand, if there's a way to omit the "-" in the friendly URL?
I.e.
http://.../page/-/abc/title

should be
http://.../page/abc/title

A: I found the solution.
You have to extend the DefaultFriendlyURLMapper and override the isCheckMappingWithPrefix method. (..and of course define this class as your FriendlyURLMapper.)
public class FriendlyUrlWithoutMinus extends DefaultFriendlyURLMapper {

    @Override
    public boolean isCheckMappingWithPrefix() {
        return false;
    }

}


text:
Q: Dividing images into patches i would like  to  practise with library of  patchify in order to learn how to  divide image  into  several patches, for this , i found  following  site  : image into patches
also i have download sample image  , which is given here :

dimension of this image is  612 X 408, so  on the  based of  site, i have applied code  and got  the following error :

raise ValueError("window_shape is incompatible with arr_in.shape")
ValueError: window_shape is incompatible with arr_in.shape

the code is given here :
`import numpy as np
from patchify import patchify
from PIL import Image
import cv2
#ocean =Image.open("ocean.jpg") #612 X 408
ocean =cv2.imread("ocean.jpg")
print(ocean.size)
ocean = np.asarray(ocean)
patches =patchify(ocean,(306,204),2)
print(patches.shape)
for i in range(patches.shape[0]):
    for j in range(patches.shape[1]):
        patch = patches[i, j]
        patch = Image.fromarray(patch)
        num = i * patches.shape[1] + j
        patch.save(f"patch_{num}.jpg")`

so my question is how  can determine window shape? i used   (306,204) because  it is  simple half of the original image's shape, is  there any  rule  of choosing  window shape?when i  searched about this  problem, i found following solution
possible solution
on this link there  was given such  suggestion :

**or the original image is not a stack of images (need to remove the first loop) **

if  i  will remove outer loop, then how can i go through  whole image? please help me

A: We have to follow the documentation.

*

*

image is a NumPy array ... or (image_height, image_width, N) for N-channels images (3 if RGB).

*

patch_shape is the shape of each patch, ... or (patch_height, patch_width, N)

*

step defines the distance between one patch... If step ≥ patch_height there is no overlap between patches in the same row...

Assuming we want to divide the image into 2x2 patches use:
patches = patchify(ocean, (204, 306, 3), 204)

Note:
Since the patches are not squares, there is an overlap in the horizontal axis.
It looks like patchify is intended to be used for patches with some ovelap.

Other issues:

*

*In OpenCV the order of the color channels is BGR and in PIL the order is RGB.
We should try not to load an image using OpenCV and save it with PIL.

*Use patch = patches[i, j, 0] as in the documentation instead of patch = patches[i, j].

Code sample:
import numpy as np
from patchify import patchify
from PIL import Image
import cv2
ocean = np.array(Image.open("ocean.jpg")) #612 X 408
#ocean =cv2.imread("ocean.jpg")
print(ocean.shape)
ocean = np.asarray(ocean)
patches = patchify(ocean, (204, 306, 3), 204)
print(patches.shape)
for i in range(patches.shape[0]):
    for j in range(patches.shape[1]):
        patch = patches[i, j, 0]
        patch = Image.fromarray(patch)
        num = i * patches.shape[1] + j
        patch.save(f"patch_{num}.jpg")


text:
Q: Why forward traverse for loop is not working properly in JavaScript This works properly:
for(var i = images1.length - 1; i >= 0; i--)
  document.getElementById("top").appendChild(images1[i]);

This is not working:
for(var i = 0; i < images1.length; i++)
  document.getElementById("top").appendChild(images1[i]);

Why above loop is not working properly.

A: The problem is that
 is placed underneath the pictures (guess based on testing). Because of that, when you move the pictures into #top, their position in the DOM changes with each iteration, and as the images in the array are ordered depending on the DOM position, the order of the array changes and that causes all the trouble.
For example, see this code (also available on this JSFiddle for testing purposes):

images1 = document.getElementsByTagName("img");

/*
//This works properly:
for(var i = images1.length - 1; i >= 0; i--)
  document.getElementById("top").appendChild(images1[i]);
*/

//This is not working:
for(var i = 0; i < images1.length; i++) {
    document.getElementById("top").appendChild(images1[i]);
}

If you inspect elements, you can see that the People's picture was not moved, and it remains outside of the #top div. But if you uncomment the first loop, and comment the second, it will work as expected.
This is because we would be moving the pictures in reversed order (from the last one to the first one), the relative position among them wouldn't change, and the images array doesn't change with it then (moving all the pictures successfully into #top).
As I mentioned above, the root cause for this behavior is that the images1 array changes in each iteration. When you call it first (line 0), its values are:
[ 0: Abstract, 1: People, 2: Sports]

But the order of the array changes with the order of the pictures on the page. Here are the values step by step (at the time of entering the iteration):
Iteration 1 (i = 0):

i = 0
images1 = [ 0: Abstract, 1: People, 2: Sports ]
images1[i] = Abstract

Result: Abstract is moved to the #top div, and also to the end of the array (as it's now the last positioned image in the DOM)

Iteration 2 (i = 1):

i = 1
images1 = [ 0: People, 1: Sports, 2: Abstract ]
images1[i] = Sports

Result: Sports is moved to the #top div, and to the end of the array. The People picture is ignored, because its index was 0, and we already skipped that one

Iteration 3 (i = 2):

i = 2
images1 = [ 0: People, 1: Abstract, 2: Sports ]
images1[i] = Sports

Result: Sports is again moved to the end of the #top div (remains in the same position), and the array stays the same.

One solution to this: place the pictures under the top div. That way, the order of the pictures will always be the same and both loops will work just fine: (see it also on this JSFiddle)

images1 = document.getElementsByTagName("img");

/*
//This works properly:
for(var i = images1.length - 1; i >= 0; i--)
  document.getElementById("top").appendChild(images1[i]);
*/

//This is not working:
for(var i = 0; i < images1.length; i++) {
    document.getElementById("top").appendChild(images1[i]);
}

If you cannot change the position of the elements, just the JavaScript, you could create a static copy of the images1 array, and use that one instead in the loops. Something like this:
// create a static duplicate that will not change with the DOM changes
for (var x = 0; x < images1.length; x++) {
    auximages1.push(images1[x]);
}

You can see working on this other JSFiddle.


text:
Q: Buffer Csv gets repeated when more than one feature is selected in mapcanvas in PYQGIS I have a function which will allow the user to select a feature or more features in map canvas and performs buffer for the selected feature(s) and writes the output to a csv file. I dont have any problem if a single feature is selected in map canvas. But when many features are selected, the name of the cities in the output csv gets repeated which is shown below and my code is also attached.
def mapselection(self):
    for layer in QgsMapLayerRegistry.instance().mapLayers().values():
        if layer.name() == "us_cities":
            lsNearCities = []
            filePath = self.dlg.fileNameEdit.text()
            if len(str(filePath)) ==0:
                QMessageBox.warning(self.dlg, "File Name","Give it a file name and try again")
                return
            if self.dlg.DistancelineEdit.text():
                dist = float(self.dlg.DistancelineEdit.text())*(1609.344)
                if dist != 0:
                    selfeature = layer.selectedFeatures()
                    for feature in selfeature:
                        mbuf = feature.geometry().buffer(dist, 2)
                        iterFeat = layer.getFeatures()
                        for f in iterFeat:
                            geom2 = f.geometry()
                            valTest = QgsGeometry.within(geom2, mbuf)
                            if valTest:
                                idx = layer.fieldNameIndex('name')  #name of the attribute column with the cities in it
                                idx1 = layer.fieldNameIndex('state')
                                nearCity = f.attributes()[idx]
                                state = f.attributes()[idx1]
                                state_and_cities = str(nearCity) + "," + str(state)
                                lsNearCities.append(state_and_cities)
                elif dist == 0:
                    selfeature = layer.selectedFeatures()
                    for feature in selfeature:
                        idx = layer.fieldNameIndex('name')  #name of the attribute column with the cities in it
                        idx1 = layer.fieldNameIndex('state')
                        nearCity = feature.attributes()[idx]
                        state = feature.attributes()[idx1]
                        state_and_cities = str(nearCity) + "," + str(state)
                        lsNearCities.append(state_and_cities)

            else:
                selfeature = layer.selectedFeatures()
                for feature in selfeature:
                    idx = layer.fieldNameIndex('name')  #name of the attribute column with the cities in it
                    idx1 = layer.fieldNameIndex('state')
                    nearCity = feature.attributes()[idx]
                    state = feature.attributes()[idx1]
                    state_and_cities = str(nearCity) + "," + str(state)
                    lsNearCities.append(state_and_cities)

    #call the function to write them into a file
    self.writeToFile(lsNearCities, filePath)


text:
Q: How to secure implemented url in my code android? I created an application on android. I use some Url to request on my server, but I do not know how to secure or hide those Urls in my app code. I have apk decompile so there code in displaying url so how to hide url. Can someone help me?

A: According to @marcinj The best way to Keep your secrets on some server on internet.
First request will go to with some identical token if server match token then response other all secret urls or data.


text:
Q: Certificate authority (CA) in Ubuntu 21.10 is installed but it does not work I've installed certificates before within Windows and Ubuntu [server] and it works normally, but today I tried to install certificates on Ubuntu Desktop 21.10 over RDP + AD user, and it does not work as expected:

*

*I installed the CA certificates via:
sudo mv euro-ca.crt euro-sub-ca.crt /usr/share/ca-certificates/
sudo update-ca-certificates

*I checked the certificate and it gives me this output, but it does not work in Chrome/Firefox; I cleared cache, cookies, rebooted Ubuntu, and logged in as another user [local admin]:
openssl s_client -connect firewall.euro.adroot:443 -CApath /etc/ssl/certs

  CONNECTED(00000003)
  depth=2 CN = euro-ca, C = FR, ST = *************  verify return:1
  depth=1 CN = euro-sub-ca, C = FR, *************  verify return:1
  depth=0 CN = firewall.euro.adroot, *************  verify return:1
  ---

  ---
  Post-Handshake New Session Ticket arrived:
  SSL-Session:
      Protocol  : TLSv1.3
      Cipher    : TLS_AES_256_GCM_SHA384
      Session-ID: ******************************
      Session-ID-ctx:
      Resumption PSK: *************************************
      PSK identity: None
      PSK identity hint: None
      SRP username: None
      TLS session ticket lifetime hint: 600 (seconds)
      TLS session ticket:
      0000 - 63 af b7 *************************23 **   c.. ..I*****..#.
      0010 - 37 cf ***********************8 42 4f **   7..#*******..BO.

      Start Time: 1640439082
      Timeout   : 7200 (sec)
      Verify return code: 0 (ok)
      Extended master secret: no
      Max Early Data: 0


text:
Q: Swipe to delete cell with strange behavior I have an application where the main root is a UIViewController with a similar behavior like the application of facebook or path, that is, swipe and show another view, on the left or right.

However, my problem is that sometimes the main UIViewController has UITableViewcells, which should be eliminated with swipe, yet this does not work correctly, sometimes it detects the gesture sometimes not.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
return YES;

}
    - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {

    [dataItems removeObjectAtIndex:indexPath.row];
    [self.tableView reloadData];

}

}
I am adopting this library
enter link description here
to make the controller of the UIViewController's
Any idea how to solve this?
Thanks in advance.

A: The problem is the gesture you're using. If both the table cells and view are trying to intercept swipe events you are guaranteed to not get the behavior you're looking for. The way that I usually solve this problem is to make a button that changes the table into editing mode. That way you don't have a conflict.
[tableView setEditing:YES animated:YES];

The problem isn't program design or language capabilities, it's having the EXACT SAME gesture do two DIFFERENT things. This isn't physically possible to implement and always get what you want. iOS devices can't read minds, although I heard about a new API in iOS 7...
You could try using multi-finger gestures.


text:
Q: Naming a variable based on user input Javascript So I am trying to have a program where a variables name is determined by user input, like:
<html>
<script>
var name = prompt("User input")
var hold = prompt("More stuff")
var (Test + (name)) = (hold)
</script>
</html>

But this doesn't work. What can I do?

A: You can't name variables by a string. You can name properties on an object however.
var name = prompt("User input")
var hold = prompt("More stuff")
var obj = {};
obj['Test' + name] = (hold)


text:
Q: Rewrite URL /blog/content/images/**/* to /content/images/**/* My front-end is hitting /blog/content/foo/bar.jpg when looking for static assets.How can I make NGINX redirect those requests to /content/foo/bar.jpg instead?
At first I tried this:
location ~ ^/blog/content/ {
    root /var/www/ghost/content/;
}

Apparently it didn't work – (btw, I'm testing each change in the .conf file with a sudo nginx -s reload + F5 in the browser.. is there a better way to test/debug NGINX behavior (and actually understand what's going on instead of this "worked / didn't work" feedback I get with each F5?)
Then, I tried this one I found in a cheatsheet – at the server level:
rewrite ^/blog/content/(.*)$ /$1 last;

Again, without luck. What bothers me is that I can't even see what the line above is doing and why it isn't working.
Someone, please, get me out of this "google for a solution -> try something that looks promising --> hit F5 hoping it works (it doesn't) -> google for a solution" loop.

A: The solution I found was to rewrite with:
rewrite ^/blog/(.*)$ /$1 last;

But it isn't ideal. I'd prefer to rewrite only when the URI contains "/blog/content/"..


text:
Q: Cambiar atributo selected según el resultado de la consulta (PHP, MySQL) Quiero desplegar una tabla con mysql y ajax con una etiqueta selected en una de sus celdas, y aquí la cuestión (ya lo tengo) ¿Cómo logro que el valor mostrado en el desplegable sea el que está en la base de datos?
Considero que no necesito copiar el código.

A: Primero, gracias.
Voy a tratar de explicarme: Tengo una tabla que sale de mysql usando php. Un campo llamado 'estado' es un <select> que quiero que al mostrarse la tabla la primera opción, la que tiene el atributo selected sea precisamente la que aparece en la base de datos. Ej: Si en la consulta aparece que el estado con id=1 es 'perdida' quiero que esa palabra sea la que tenga el atributo selected.
He hecho esto:
<?php

    require("conexion.php");

    $sql = "SELECT * FROM bicicletas";

    $result = $mysqli->query($sql);

    $opciones = array( 'activa', 'perdida', 'encontrada' );

    echo "

Estado

";

    while($registro = $result->fetch_array()){
        echo "

              <select>";
                  $valor = $registro['estado'];
                  $resultado = '';
                    for( $i=0; $i<count($opciones); $i++ ) {
                      $resultado .= '<option '.( $valor == $opciones[$i] ? 'selected="selected"' : '' ).'>'.$opciones[$i]
             . '</option>';}
              echo $resultado;
              echo "</select>

";
}
 ?>

Finalmente funciona. Espero que este código sirva de aporte al foro y de ayuda a quien lo necesite ;).


text:
Q: How to check React build folder I'm using create-react-app to build my project.
I'm trying to implement a health checker bash command to see if javascript bundle files are correctly built. Currently, I'm just testing if js files are there inside build/static/js by creating a JSON file that holds all js file names inside of it.
I'm still not sure if that's a good way or not.
Is there any way to check all files that are created inside the build folder are okay?


text:
Q: a large navigation menu in ios I have a large navigation menu, like a website header(Top logo, Bottom some menu buttons.) and this navigation menu must shown in every view of my application (like a masterpage, header(this navigation) will be static but content will change). What is the best way to represent this menu in my application?
I thought UINavigationBar may be appropriate but I am not sure about it. Can I customize it that much?

A: totally depends on how much is 'that much'.
you can use UIToolBar for more customization that what UINavigationBar allows, but you'll have to do some extra work in getting that functionality to match that of a nav bar,
or use a customViewController that has this largeNavigationMenu, and use it as a baseClass for all viewControllers you are using in your app.

A: You basically need to use some kind of container controller. Either a UINavigationController, a UITabBarController or maybe something custom like a drawer menu controller. Depends on the app design.


text:
Q: Trouble with adding percentages to stretch fully I'm trying to get a ul with different coloured inner elements to equally stretch 100%. It's fine until I test under 1280px. I have to minimize the window still to see it and also intermittent so tough to catch. Everything adds up. I really don't know what wrong here. Any help would be much appreciated. Thanks.
http://codepen.io/Compton/pen/xdGpm/

.orange {
    background-color:#f37028;
}

.red {
    background-color:#ed1b24;
}

.pink {
    background-color:#e54198;
}

.purple {
    background-color:#6b439c;
}

.blue {
    background-color:#0193cf;
}

.green {
    background-color:#91ff01;
}

.yellow {
    background-color:#fff300;
}

#colour-bar {
    top:0;
    left:0;
    width:100%;
    position:fixed;
    height:10px;
    background-color:#FFFFFF;
}

#colour-bar ul {
    width:100%;
    height:100%;
    padding:0;
    margin:0;
}

#colour-bar ul li {
    width:14.24%;
    height:100%;
    float:left;
    list-style:none;
}

#colour-bar ul li.spacer {
   width:0.05333%;
   height:100%;
   display:block;
   float:left;
}

A: The issue probably occurs due to some rounding inaccuracies that every browser introduces at some viewport widths, therefore sometimes the space between items disappear.
Furthermore, your spacer elements have a width of 0.0533% of the available width, so this means that the space is exactly 1px when the container is at least  1876px wide: below of this width is a choice of the browser how to round the value
Try this code: http://codepen.io/anon/pen/ioxtE
I first suggest to remove all the spacer elements (since it is empty markup, only for styling purpose, thus is a bad practice)

then give a space between list-items with
#colour-bar li + li {
  border-left: 1px #fff solid;
}

and assign this style
#colour-bar ul li {
   width:14.275%;   /*  ~(100/7)  */
   ...
   -webkit-box-sizing: border-box;
   -moz-box-sizing: border-box;
   box-sizing: border-box;
}

and the space between colours is always in its place

A: Try setting it's width to the viewport width, first add the viewport meta tag:
<meta name="viewport" content="width=device-width, initial-scale=1.0" />

and then give the div the viewport width instead of percentage:
#colour-bar {
top:0;
left:0;
width:100vw;
position:fixed;
height:10px;
background-color:#FFFFFF;
}

Hope this helps...


text:
Q: SetValue within reflected ProperyInfo I am using reflection to set a property from within a reflected property. I have to use reflection as I don't know what the type the child propery will be, but each time I get System.Target.TargetException (on the prop.SetValue) prop is pointing to the correct property
I can find lot of examples of the SetValue, the problem that I am having, is I expect related to the fact that selectSubProcess is a PropertyInfo rather than a actual class
PropertyInfo selectedSubProcess = process.GetProperty(e.ChangedItem.Parent.Label);
Type subType = selectedSubProcess.PropertyType;
PropertyInfo prop = subType.GetProperty(e.ChangedItem.Label + "Specified");
if (prop != null)
        {
            prop.SetValue(process, true, null);
        }

A: It looks like process is "Type", not an instance of an object.  in the line
prop.SetValue(process, true, null);

you need an instance of an object to set, not a Type.
Use "GetValue" to get an instance of the object you care about:
public void test()
{
  A originalProcess = new A();
  originalProcess.subProcess.someBoolean = false;

  Type originalProcessType = originalProcess.GetType();
  PropertyInfo selectedSubProcess = originalProcessType.GetProperty("subProcess");
  object subProcess = selectedSubProcess.GetValue(originalProcess, null);
  Type subType = selectedSubProcess.PropertyType;
  PropertyInfo prop = subType.GetProperty("someBoolean");
  if (prop != null)
  {
    prop.SetValue(subProcess, true, null);
  }

  MessageBox.Show(originalProcess.subProcess.someBoolean.ToString());
}

public class A
{
  private B pSubProcess = new B();
  public B subProcess
  {
    get
    {
      return pSubProcess;
    }
    set
    {
      pSubProcess = value;
    }
  }

}

public class B
{
  private bool pSomeBoolean = false;
  public bool someBoolean
  {
    get
    {
      return pSomeBoolean;
    }
    set
    {
      pSomeBoolean = true;
    }
  }
}