text:
Q: Play button to pause button What do I need to do with this CSS if I want the play button to change into this pause button: pause on click and play a sound. Then if I click on the pause button, change it back to a play button and set the specific sound in this box back to 0:00. If the sound ends, it should automatically switch to a play button and set the sound back to 0:00.
I want as well if I have for example 2 or more boxes like this every play/stop button will work only for the specific one and not for all of them.
Also can some designer look at that play button and update it to look better, but that isn't the main problem..

.box {
    text-align: center;
    width: 300px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
    background: linear-gradient(#ffffff, #f5f5f5);
    padding: 16px;
    margin: 0 0 10px 0;
    position: relative;

}

.box_title {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.2em;
    font-weight: bold;
    border-bottom:  1px solid rgb(170, 170, 170);
    cursor: pointer;
}
.box_title i {
    padding-right: 10px;
}

.box_content {
    margin: 0 0 18px 0;
    border-bottom:  1px solid rgb(170, 170, 170);
    text-align: justify;
}

.box_footer {
    position:absolute;
                bottom:-5px;
                left:20px;
    font-size: 14px;

}

.box_footer_right i {
    font-size: 14px;
    padding: 0 0.3em 0 0.3em;
    cursor: pointer;
}

.box_footer_right {
    display: flex;
    align-items: center;
    justify-content: center;
    position:absolute;
                bottom:-5px;
                right:20px;
}

.playbutton {
    cursor: pointer;
    object-fit: cover;
      border-radius: 50%;
      margin: 1em auto 20px auto;
      display: block;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
    background: linear-gradient(#ffffff, #f5f5f5);
    width: 125px;
    -webkit-transition: 0.5s;
    user-select: none;
}

.playbutton:hover {
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.4);
    -webkit-transition: 0.5s;
}

.playbutton:active {
    background: #f5f5f5;
    box-shadow: 0 5px #f5f5f5;
    -webkit-transition: 0s;
    transform: translateY(4px);
}

.playbutton i {
    font-size: 120px;
}
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;700&display=swap" rel="stylesheet">

graphic_eqTest song title

play_arrow

 Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text

 date | autor

 delete | edit | visibility

A: Change the code of the css stylesheet to this
        .box {
        text-align: center;
        width: 300px;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
        background: linear-gradient(#ffffff, #f5f5f5);
        padding: 16px;
        margin: 0 0 10px 0;
        position: relative;

    }

    .box_title {
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.2em;
        font-weight: bold;
        border-bottom: 1px solid rgb(170, 170, 170);
        cursor: pointer;
    }

    .box_title i {
        padding-right: 10px;
    }

    .box_content {
        margin: 0 0 18px 0;
        border-bottom: 1px solid rgb(170, 170, 170);
        text-align: justify;
    }

    .box_footer {
        position: absolute;
        bottom: -5px;
        left: 20px;
        font-size: 14px;

    }

    .box_footer_right i {
        font-size: 14px;
        padding: 0 0.3em 0 0.3em;
        cursor: pointer;
    }

    .box_footer_right {
        display: flex;
        align-items: center;
        justify-content: center;
        position: absolute;
        bottom: -5px;
        right: 20px;
    }

    .playbutton {
        cursor: pointer;
        object-fit: cover;
        border-radius: 50%;
        margin: 1em auto 20px auto;
        display: block;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
        background: linear-gradient(#ffffff, #f5f5f5);
        width: 125px;
        -webkit-transition: 0.5s;
        user-select: none;
        display: none
    }

    .playbutton.show {
        display: block;
    }

    .playbutton:hover {
        box-shadow: 0 0 20px rgba(0, 0, 0, 0.4);
        -webkit-transition: 0.5s;
    }

    .playbutton:active {
        background: #f5f5f5;
        box-shadow: 0 5px #f5f5f5;
        -webkit-transition: 0s;
        transform: translateY(4px);
    }

    .playbutton i {
        font-size: 120px;
    }

    .pausebutton {
        cursor: pointer;
        object-fit: cover;
        border-radius: 50%;
        margin: 1em auto 20px auto;
        display: block;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
        background: linear-gradient(#ffffff, #f5f5f5);
        width: 125px;
        display: none;
        -webkit-transition: 0.5s;
        user-select: none;
    }

    .pausebutton:hover {
        box-shadow: 0 0 20px rgba(0, 0, 0, 0.4);
        -webkit-transition: 0.5s;
    }

    .pausebutton:active {
        background: #f5f5f5;
        box-shadow: 0 5px #f5f5f5;
        -webkit-transition: 0s;
        transform: translateY(4px);
    }

    .pausebutton i {
        font-size: 120px;
    }

    .pausebutton.show {
        display: block
    }

Change the code of the HTML file to this:
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;700&display=swap" rel="stylesheet">

graphic_eqTest song title

play_arrow

pause

 Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text
            Text Text Text Text Text Text

 date | autor

 delete | edit | visibility

and just below the HTML File add this line of code of JavaScript:

A: With the Sound Version keep the css stylesheet code same:
    .box {
    text-align: center;
    width: 300px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
    background: linear-gradient(#ffffff, #f5f5f5);
    padding: 16px;
    margin: 0 0 10px 0;
    position: relative;

}

.box_title {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.2em;
    font-weight: bold;
    border-bottom: 1px solid rgb(170, 170, 170);
    cursor: pointer;
}

.box_title i {
    padding-right: 10px;
}

.box_content {
    margin: 0 0 18px 0;
    border-bottom: 1px solid rgb(170, 170, 170);
    text-align: justify;
}

.box_footer {
    position: absolute;
    bottom: -5px;
    left: 20px;
    font-size: 14px;

}

.box_footer_right i {
    font-size: 14px;
    padding: 0 0.3em 0 0.3em;
    cursor: pointer;
}

.box_footer_right {
    display: flex;
    align-items: center;
    justify-content: center;
    position: absolute;
    bottom: -5px;
    right: 20px;
}

.playbutton {
    cursor: pointer;
    object-fit: cover;
    border-radius: 50%;
    margin: 1em auto 20px auto;
    display: block;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
    background: linear-gradient(#ffffff, #f5f5f5);
    width: 125px;
    -webkit-transition: 0.5s;
    user-select: none;
    display: none
}

.playbutton.show {
    display: block;
}

.playbutton:hover {
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.4);
    -webkit-transition: 0.5s;
}

.playbutton:active {
    background: #f5f5f5;
    box-shadow: 0 5px #f5f5f5;
    -webkit-transition: 0s;
    transform: translateY(4px);
}

.playbutton i {
    font-size: 120px;
}

.pausebutton {
    cursor: pointer;
    object-fit: cover;
    border-radius: 50%;
    margin: 1em auto 20px auto;
    display: block;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
    background: linear-gradient(#ffffff, #f5f5f5);
    width: 125px;
    display: none;
    -webkit-transition: 0.5s;
    user-select: none;
}

.pausebutton:hover {
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.4);
    -webkit-transition: 0.5s;
}

.pausebutton:active {
    background: #f5f5f5;
    box-shadow: 0 5px #f5f5f5;
    -webkit-transition: 0s;
    transform: translateY(4px);
}

.pausebutton i {
    font-size: 120px;
}

.pausebutton.show {
    display: block
}

But in HTML change the code a little bit:
<link href="https://fonts.googleapis.com/icon?family=Material+Icons"                rel="stylesheet">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2? family=Nunito:wght@400;700&display=swap" rel="stylesheet">

<audio id="myAudio" src="your-sound-file-name" onended="showPlay()"></audio>

graphic_eqTest song title

play_arrow

pause

 Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text
        Text Text Text Text Text Text

 date | autor

 delete | edit | visibility

And Below it change the JavaScript Code:


text:
Q: The coefficient of a root in a root system must be 0 or at least 1 Let W be a Coxeter group (not necessarily finite), and let Π and Φ be the
corresponding root basis and root system. Suppose that x ∈ Φ
+ and a ∈ Π
such that the coefficient of a in x is not zero. Prove that this coefficient must
be greater than or equal to 1. You may assume that Π is linearly independent.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Tab spacing in align environment? How can I achieve this?
Example 1:        a = b         b = c

Example 2:        this equation is way longer than the others

Example 1:        c = d         e = f

All three lines are in a single align environment, but I can't manage to get it right, using && I always get
Example 1:        a = b                                             b = c

Example 2:        this equation is way longer than the others

Example 1:        c = d                                             e = f

because of the long second equation?
My code:
\begin{align*}

& Example 1: && a = b && b = c \\

& Example 2: && \text{this equation is way longer than the others} \\

& Example 1: && c = d && e = f

\end{align*}

A: Here are three possibilities, either with align*  or with alignat* (to have full control on the columns spacing. Also, I think, it would look better if the align environment started at the left margin, which can be done locally with the fleqn  environment from nccmath. Furthermore, the distance from the left margin where the environment starts can be set as an optional argument of fleqn:
\documentclass{article}

\usepackage{nccmath, mathtools}

\begin{document}

\noindent Some text. Some more text. Some more text. Some more text. Some more text. Some more text.
\begin{align*}
& \text{Example 1:} && a = b && b = c \\
&\text{Example 2:} && \mathrlap{this equation is way longer than the others} \\
& \text{Example 3:} && c = d && e = f
\end{align*}
\vskip 1cm
\begin{fleqn}
\begin{align*}
& \text{Example 1:} && a = b && b = c \\
&\text{Example 2:} && \mathrlap{this equation is way longer than the others} \\
& \text{Example 3:} && c = d && e = f
\end{align*}
\end{fleqn}
\vskip 1cm
\begin{fleqn}[1em]
\begin{alignat*}{3}
& \text{Example 1:} &\qquad& a = b &\hspace{5em}& b = c \\
&\text{Example 2:} && \mathrlap{this equation is way longer than the others} \\
& \text{Example 3:} && c = d && e = f
\end{alignat*}
\end{fleqn}
 Some more text. Some more text. Some more text. Some more text. Some more text.

\end{document}

A: Welcome to TeX.SX! The align* environment is best used for aligning equations, rather than text (in your case, the words "Example" will not be typeset as text, but rather as math symbols). Perhaps using the align (without *) environment is more suitable for referring to your equations later, as that numbers each line.
If you really want to put both together, I suggest using tabular and \multicolumn:
\begin{tabular}{r c c}
Example 1: & $a=b$ & $b=c$ \\
Example 2: & \multicolumn{2}{c}{this equation is way longer than the others}\\
Example 3: & $c=d$ & $e=f$
\end{tabular}

This is the result:

The \intertext command may also be useful, if you want to break an align environment but remember the alignment.


text:
Q: Refreshing flash memories. Does it work? We all know that the flash memories have data retention time of around 10..20 years.
But what if we need to design a device that has to work for 1000 years?
The obvious solution is to make a flash reprogramming once every 5..10 years, refreshing the charges in the memory cells. If the flash memory has 100K writing cycles life, it makes 500K..1M years retention time. Almost infinity.
But the obvious way is not always the right way.
So, is it possible to prolong the data retention time of the flash memories almost infinitely, by reflashing it every 5..10 years?

A: Rewriting flash is indeed a mechanism to extend flash retention when your device is running in a high-temperature environment (at lower temperatures, flash retention is not so much a problem).
Texas Instrument's application report MSP430 Flash Memory Characteristics (which should also apply to all other NOR flash-based MCUs) says in section 4.2 ("Enhancing Flash Data Retention Time With Flash Refresh"):

As explained in the previous section, data retention time is very much dependent on the ambient temperature of the MSP430 application. One possible solution to enhance flash data retention is refreshing the flash contents from time to time with software.
In an ideal scenario, the application has idle time frames, where no external events must be observed. During such an idle time, the software can copy one flash segment into RAM or any other flash segment. After erasing the original segment, the content is copied back into the original segment. After such a flash refresh cycle, the data retention time for this segment restarts.
  [...]
CAUTION
  The application must ensure that flash refresh of a flash segment is not interrupted by a power failure.

A: Probably the use of refresh IS a good way to extend lifetime.  Ferroelectric
nonvolatile memory is said to be more durable, and other nonvolatile forms
are in development.
Reflashing won't rejuvenate everything; some systems use dummy cells (which set the thresholds for multilevel discrimination), and aging dummy cells cannot be 'refreshed'. They aren't eraseable, they aren't even
addressable, but they might discharge with the years just like data cells.
Spare blocks have also been employed to extend FLASH lifetime in some chips CAT24C256 in combination with self-checking internal codes.


text:
Q: scrollTop on function call animate multiple I have this http://jsfiddle.net/Borisko/604rLvbc/38/
I want add animation (delay, what ever, make it nice) to scrolTop:
 $div.scrollTop(fixpos);

after adding animation, everything broke, and scrolling goes multiple times.
it there any way to make scrollTop animation run just once (like without animation)

A: Okay so I can't be sure about the reason behind this - if u add animation, the functionality stop, and code doesnt work - animation on one scroll goes multiple times to wrong element - but this is what I think is happening here : the scrollTop() value is still not updated when we assign value to pos
var pos = $div.scrollTop();

So instead before animating I have stored scrollTop value in a global variable valuePos and then set that value to pos on next scroll. I have initialized valuePos with scrollTop.
var valuePos = $("#target").scrollTop();

If you scroll fast the animation will work but with a slight delay as we are calling multiple animate here. I have used .stop() just before animate call so that animation won't lag too much.
Please refer this fiddle.


text:
Q: My uncommitted changes are carried and merged when I switch branches I made some changes in my master branch and without committing them, I checked out to development branch. I was expecting an error to be thrown but instead of that, my changes in master branch are merged with development branch.
$ git checkout development
Switched to branch 'development'
M       pom.xml
Your branch is up-to-date with 'origin/development'.

Instead of this I was expecting the below error, so that I could stash or commit my changes before checking out:
error: You have local changes ....; cannot switch branches.

Does anybody know why it happened or how can I prevent it to happen again?

A: As far as I know, this is now the default behavior of Git.  When switching branches, you carry your working directory with you.  I also seem to recall earlier versions where this was not the case.
You might not be able to avoid this from happening, but you can always make sure your working directory (and stage) is clean before switching branches.  Or, you could make a commit with your work, or stash.


text:
Q: Clean up installation after incomplete / interrupted setup The setup of an arbitrary application was interrupted, and the name of it does not appear in the "Add or Remove Program" list. I've tried to use the Windows Installer CleanUp Utility from Microsoft but the utility can't be used if the item doesn't appear in "Add or Remove Programs".
How can I remove the leftover items from the system?

A: It's impossible to answer accurately without knowing what program you're referring to, but one option would be to install the program again to completion, then uninstall it.
If the installer won't install the program because it thinks it's already installed (whew), you can try using the Windows Installer CleanUp Utility to mark the program as not installed.  After you do this, the installer might let you continue normally.

A: Revo Uninstaller The main feature of Revo Uninstaller is to remove unnecessary files and registry entries left behind by incomplete program uninstallation routines. But it is also as alternative Add/Remove programs in Windows

A: Try this tool from Microsoft: MicrosoftProgram_Install_and_Uninstall https://support.microsoft.com/en-us/help/17588/fix-problems-that-block-programs-from-being-installed-or-removed.
Select uninstall when asked which one you are facing a problem with, and then select your program from the list..


text:
Q: Not loading from the top I have a blog and while loading it doesn't show the top. but when finished loading it shows from the top.
while loading: http://prntscr.com/1dv2x9
after: http://prntscr.com/1dv2zm
Somebody please help me... I tried to change margin-top and add some load scripts..but I can't figure out what I should change from the template source.
I tried to edit this:


text:
Q: Kth smallest element in an array using partition Suppose you are provided with the following function declaration in the C programming language.
int partition(int a[], int n);

The function treats the first element of a[] as a pivot and rearranges the array so that all elements less than or equal to the pivot is in the left part of the array, and all elements greater than the pivot is in the right part. In addition, it moves the pivot so that the pivot is the last element of the left part. The return value is the number of elements in the left part.
The following partially given function in the C programming language is used to find the kth smallest element in an array a[] of size n using the partition function. We assume k≤n.
int kth_smallest (int a[], int n, int k)
{
    int left_end = partition (a, n);
    if (left_end+1==k) {
        return a[left_end];
    }
    if (left_end+1 > k) {
        return kth_smallest (___________);
    } else {
        return kth_smallest (___________);
    }
}

The missing arguments lists are respectively

*

*(a, left_end, k) and  (a+left_end+1, n-left_end-1, k-left_end-1)

*(a, left_end, k) and  (a, n-left_end-1, k-left_end-1)

*(a, left_end+1, n-left_end-1, k-left_end-1) and  (a, left_end, k)

*(a, n-left_end-1, k-left_end-1) and  (a, left_end, k)

I found here a nice explanation about "How to find the kth largest element in an unsorted array of length n in O(n)?"
I've read partition , used in quick sort .Answer is given option (1).I agree with answer . But I need formal explanation .

Can you explain little bit please ?

Edit : AFAIK , Partition algorithm puts the chosen pivot in its correct position . We need recursively partition algorithm to find kth smallest element in an array .Partition algorithm run on a single side of array , either left or right of it's sorted pivot.  I got stuck here . I'm thinking , it depends on kth index number ?

A: Its simple. Say, you pick a q th largest element of the array. In that case, partition has q-1 elements in left half and n-q elements in the right half, while, q th element is the pivot. Now, 3 possibilities:

*

*If q is k, you get the answer, which is your return statement.

*If q > k, then k th element is in the left half of the array, and, in the left half, it is, still, the k th largest element. So, in the partition, we pass left half of the array, and k, that we have to find k th largest element there.

*If q < k, then, k th largest element in in the right half of the array. Also, since there are q elements smaller than smallest element of this right part, k th largest element in the original array is k - q th largest in the right array. So, we pass the right array, and k-q, to find k-q th largest element of the partition.

EDIT:
Adding comments to your code:
int partition(int a[], int n);    //breaks array into 2 parts, according to pivot (1st element of array), left is smaller and right is larger han pivot.

Now, your recursive algorithm:
int kth_smallest (int a[], int n, int k)
{
    int left_end = partition (a, n);    //get index of a[0] in sorted array a
    if (left_end+1==k) {           //kth largest element found
        return a[left_end];
    }
    if (left_end+1 > k) {     //k th largest element in left part of array, and is k th largest in the left part
        return kth_smallest (___________);
    } else {                  ////k th largest element in right part of array, and is (k - left_end) th largest in the right part
        return kth_smallest (___________);
    }
}


text:
Q: call global object method result in null or not an object in IE8 I have the following JS, when it runs in IE8, I get the error: ILL.TEST is null or not an object, it works on other browsers through. any idea why this is happening? thanks for help in advance.
 //global name space
 var ILL={};

 ILL.TEST=(function(){
     function init(){
      }
     return {
        init:init
     };
 })();

 (function(){
      //error ILL.TEST is null or not an object
      ILL.TEST.init();
 })()

A: The problem was that I define the ILL.TEST after it is called. so this will be a problem:
 //global name space
 var ILL={};

 (function(){
    //error ILL.TEST is null or not an object
     ILL.TEST.init();
 })()

 //defining after this fn is called will result in null or not an object in IE8
 ILL.TEST=(function(){
     function init(){
      }
     return {
       init:init
     };
 })();


text:
Q: Ways to create object of ResponseEntity class in spring boot I am new to spring boot and I am trying to create handler methods to create REST API in spring boot. To handle request localhost:8080/stack I created below handler method in which I used constructor of ResponseEntity to create its object and pass it in return statement.
 @GetMapping("/stack")
    public ResponseEntity<String> stack(){
        System.out.println("I am stack method");
        return new ResponseEntity<>("Body",HttpStatus.OK);
    }
}

But I can also do it by using the below method
 @GetMapping("/stack")
    public ResponseEntity<String> stack(){
        System.out.println("I am stack method");
        return ResponseEntity.status(HttpStatus.OK).body("Body");
    }

I don't know which is the best way to create and return an object of ResponseEntity in the handler method using constructors or using build method() and why? Somebody please help here. Which is the most preferred way in the production?

A: It's the same as even 2nd approach returns a new object of ResponseEntity class. If you check the implementation of the body method as below:-
@Override
    public <T> ResponseEntity<T> body(@Nullable T body) {
        return new ResponseEntity<>(body, this.headers, this.statusCode);
    }

A: ResponseEntity is meant to represent the entire HTTP response. You can control anything that goes into it: status code, headers, and body.
@ResponseBody is a marker for the HTTP response body and @ResponseStatus declares the status code of the HTTP response.
@ResponseStatus isn't very flexible, ResponseEntity lets you do more.

A: In that case best way is to return string ("Body") from restcontroller method, it'll be wrapped in responseentity with response status 200 OK automatically


text:
Q: Translate Python function to apply mask to image into Java I'm trying to translate the following Python function, that applies a mask to an image, into Java:
# Applies an image mask.
def region_of_interest(img, vertices):
    #defining a blank mask to start with
    mask = np.zeros_like(img)

    #defining a 3 channel or 1 channel color to fill the mask with depending on the input image
    if len(img.shape) > 2:
        channel_count = img.shape[2]  # i.e. 3 or 4 depending on your image
        ignore_mask_color = (255,) * channel_count
    else:
        ignore_mask_color = 255

    #filling pixels inside the polygon defined by "vertices" with the fill color
    cv2.fillPoly(mask, vertices, ignore_mask_color)

    #returning the image only where mask pixels are nonzero
    masked_image = cv2.bitwise_and(img, mask)
    return masked_image

So far, this is what I've got:
public static opencv_core.Mat applyMask(opencv_core.Mat image, opencv_core.MatVector vertices) {
  opencv_core.Mat mask = opencv_core.Mat.zeros(image.size(), opencv_core.CV_8U).asMat();

  opencv_core.Scalar color = new opencv_core.Scalar(image.channels()); // 3
  double[] colors = new double[] {
    255.0, 255.0, 255.0, 255.0,
    255.0, 255.0, 255.0, 255.0,
    255.0, 255.0, 255.0, 255.0};
  color.put(colors, 0, colors.length);

  opencv_imgproc.fillPoly(mask, vertices, color);

  opencv_core.Mat dst = new opencv_core.Mat();
  opencv_core.bitwise_and(image, mask, dst);
  return dst;
}

But, it isn't working. When I try invoking this method like in the following example:
opencv_core.MatVector points = new opencv_core.MatVector(
  new opencv_core.Mat(2, 3, opencv_core.CV_32F, new IntPointer(1, 2, 3, 4, 5, 6))
);

opencv_core.MatVector vertices = new opencv_core.MatVector(points);
opencv_core.Mat masked = LaneManager.applyMask(src, vertices);

(I'm assuming this is the right way to build a 2x3 matrix of three points with two coordinates each (1,2), (3, 4) and (5,6))
I get an exception:
java.lang.RuntimeException: std::bad_alloc
at org.bytedeco.javacpp.opencv_imgproc.fillPoly(Native Method)

I'm using OpenCV as provided by org.bytedeco.javacpp-presets:opencv-platform:3.2.0-1.3 via Maven Central.
I must admit that I'm at a loss here: What's the idiomatic Java way of doing the same thing as the Python function above?

A: Alright, I finally figured it out. If you define your coordinates with:
int[] points = new int[] {x1, y1, x2, y2, ...};

Then you can simply apply a mask with the following code:
opencv_core.Mat mask = new opencv_core.Mat(image.size(), image.type());

// Array of polygons where each polygon is represented as an array of points
opencv_core.Point polygon = new opencv_core.Point();
polygon.put(points, 0, points.length);
opencv_imgproc.fillPoly(mask, polygon, new int[] {points.length / 2}, 1, new opencv_core.Scalar(255, 255, 255, 0));

opencv_core.Mat masked = new opencv_core.Mat(image.size(), image.type());
opencv_core.bitwise_and(image, mask, masked);

Where image is the original image, and masked is the masked result.
The problem was that the original list of points wasn't defined properly.

A: Maybe some whiz has the complete answers. Here is food for thought:

*

*The Java API is a direct copy of the CPP API: http://opencv.org/opencv-java-api.html

*
The error std::bad_alloc occurs when you fail to allocate required storage space. (http://answers.opencv.org/question/28959/cascade-training-killed-and-bad_alloc/)

*There are two CPP methods:

*

*C++: void fillPoly(Mat& img, const Point** pts, const int* npts, int ncontours, const Scalar& color, int lineType=LINE_8, int shift=0, Point offset=Point() ), and

*C++: void fillPoly(InputOutputArray img, InputArrayOfArrays pts, const Scalar& color, int lineType=LINE_8, int shift=0, Point offset=Point() )

*
You don't need to convert from Mat to InputArray, but you can (and should) just pass a Mat object where an InputArray is requested (https://stackoverflow.com/a/32976883/1587329)


text:
Q: Detect if Image inside Imageview overlaps Textview I have the following Layout:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<com.myapp.imagezoom.ImageViewTouch
    android:id="@+id/image"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />

<TextView
    android:id="@+id/txtTitle"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|center"
    android:layout_marginBottom="3dp"
    android:gravity="center"
    android:maxLines="2"/>

<ProgressBar
    android:id="@+id/loading"
    style="?android:attr/progressBarStyleLarge"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:visibility="gone" />

As you can see there is a zoomable ImageView. The TextView is shown below the ImageView as long as it is not zoomed. If the user zooms into the ImageView it is on top of it.
How can I detect if the showing ImageView overlaps the TextView to show a background to the TextView?
Thanks alot

A: You should add to your ImageViewTouch class a property called isZoomed and then just verify if is true or false into a custom override method or into an AsyncTask and set the background of the TextView or whatever you want there.
To learn more about creating custom override methods I suggest you to read this, it simply explains how to do it.


text:
Q: Function with input of pointer to pointer to I saw this question about the the result of  sizeof() and i didn't understand the output of this function.
#include <stdio.h>
void checkSizes(char matrix3d[10][20][30])
{
    printf ("%lu\t", sizeof(matrix3d));
    printf ("%lu\t", sizeof(*matrix3d));
    printf ("%lu\t", sizeof(**matrix3d));
    printf ("%lu\t", sizeof(***matrix3d));
}
int main()
{
    char matrix[10][20][30];
    checkSizes(matrix);
}

as i was assuming , when a function get an array to work with , it's getting a pointer to the array, so when i'll print the first line of
printf ("%lu\n", sizeof(matrix3d));

the output will be 8.
BUT
isn't the next printf will get me to diffrent  pointer to pointer that his size will be also 8 ?
so i thouth this will lead to
8    8    8    1

the real output is
8    600    30   1

A: In this statement
printf ("%lu\t", sizeof(*matrix3d));
// it is better to use "%zu\t"

expression *matrix3d has type char[20][30].
Using an array in the sizeof operator as an expression does not convert the expression to the pointer to the first element of the array.
Thus you will get output 600.
However if you would write
sizeof( *matrix3d + 0)

then indeed *matrix3d having type char[20][30] will be converted in the expression *matrix3d + 0 implicitly to pointer of type char ( * )[30] and the corresponding printf statement will output 8,
As for the function parameter and its argument then they are implicitly converted to type char ( * )[20][30]
So for example these function declarations are equivalent
void checkSizes(char matrix3d[10][20][30]);
void checkSizes(char ( *matrix3d )[20][30]);

and declare the same one function.

A: First you need to know that sizeof is an operator and not a function. Arrays do not convert to pointer to its first element when it is an operand of sizeof or unary & operator.
In function checkSizes, the parameter matrix3d is of type pointer to an array of 20 arrays of 30 chars . Since it is a pointer, the statement
printf ("%lu\t", sizeof(matrix3d));

will print the size of a pointer.
Dereferencing the pointer matrix3d will give its first element. Its first element is an array of 20 arrays of 30 chars. sizeof(*matrix3d) will return size of array char[20][30] which is 600 Bytes. sizeof(*matrix3d) is equivalent to sizeof(matrix3d[0]).
The type of **matrix3d is an array of 30 chars, sizeof(**matrix3d) will print 30 Bytes.
The type of ***matrix3d is achar, sizeof(***matrix3d) will print 1 Byte.

A: The first is, as you said the size of a pointer, so 8; the last is the size of a character, so 1; the second is sizeof(char)*30*20, because you have dereferenced the first "dimension" of the array, so you are looking at what's contained in one of the 10 elements of that dimension. The third is sizeof(char)*30 because you are looking inside an element of the second dimension.


text:
Q: Stop running JS when class is added to HTML - Run again when class is removed I have a 'theme toggle' which changes the look/feel of my UI. There is also a custom JS cursor that I don't need on one of the themes. I thought it would be a good idea to kill the script when the relevant class is on html as there's a lot of calculation going on with the pointer position. Rather than just use display: none and leave the script running.
There are 3 modes/themes:

*

*Default (always first / onload)

*Dark

*Retro - which is the one where the script should be stopped.

I tried to achieve this using the following method. To test, I add the .retro class to html so it's the first theme, it does stop the script from running and clicking the toggle turns the script on again. But it only does it once.
Obviously removing the class onload doesn't work either but I just wanted to do the above to see if anything was happening. Can someone tell me where I'm going wrong. What's the best approach?
Essentially what I'm trying to achieve is: Run this script, unless the class .retro is present, if so stop it. If the class .retro is removed, run the script again.

/* Toggle */

const html = document.querySelector("html");
const button = document.querySelector(".contrast__link");

button.addEventListener("click", (e) => {
    e.preventDefault();
    if (html.classList.contains("dark-mode")) {
        html.classList.remove("dark-mode");
        html.classList.add("retro");
        let slideIndex = swiper.activeIndex;
        swiper.destroy(true, true);
        swiper = initSwiper("slide", false, 999999999); // Retro: This should slide, no autoplay or loop
        swiper.slideTo(slideIndex, 0);
    } else if (html.classList.contains("retro")) {
        html.classList.remove("retro");
        let slideIndex = swiper.activeIndex;
        swiper.destroy(true, true);
        swiper = initSwiper("fade", true, 1200); // Default: This should fade, autoplay & loop
        swiper.slideTo(slideIndex, 0);
    } else {
        html.classList.add("dark-mode");
    }
});

/* Cursor */

function createHandler(callback) {
    return function(event) {
        if (!document.documentElement.classList.contains('retro')) {
            callback.call(this, event)
        }
    }
}

window.addEventListener('mousemove', createHandler(function() {

    var cursor = document.querySelector(".cursor");
    var cursorTrail = document.querySelector(".cursor-trail");
    var a = document.querySelectorAll("a");
    var timeout;

    window.addEventListener(
        "mousemove",
        function(e) {
            var x = e.clientX;
            var y = e.clientY;
            cursor.style.transform = `translate(${x - 2}px, ${y - 2}px)`;
            if (!timeout) {
                timeout = setTimeout(function() {
                    timeout = null;
                    cursorTrail.style.transform = `translate(${x - 16}px, ${y - 16}px)`;
                }, 24);
            }
        },
        false
    );

    /**
     * Add/remove classes on click (anywhere).
     */

    document.addEventListener("mousedown", function() {
        cursor.classList.add("cursor--click");
    });

    document.addEventListener("mouseup", function() {
        cursor.classList.remove("cursor--click");
    });

    /**
     * Add/remove set classes on hover.
     *
     * 1. This used to start with `a.forEach((item) => {` but changed to `let` so
     *    that an additional (non-anchor) item could be targeted. `#hello` is for
     *    the image on the 404 page.
     */

    // a.forEach((item) => {
    let links = document.querySelectorAll('a, #hello'); /* [1] */
    links.forEach((item) => { /* [1] */
        item.addEventListener("mouseover", () => {
            cursorTrail.classList.add("cursor-trail--hover");
        });
        item.addEventListener("mouseleave", () => {
            cursorTrail.classList.remove("cursor-trail--hover");
        });
    });

    /**
     * Add custom classes on hover if the cursor needs to be manipulated in a
     * unique way. If an element has a `data-interaction=""` value set. This will
     * be added as a class to the cursor on hover. For example, this is used to
     * style the prev/next arrows on the carousel.
     *
     * This could be set using a specific class but I've just left it targeting all
     * `a` elements for now. Which will add a class of `undefined` if no dataset is
     * specified.
     */

    a.forEach((item) => {
        const interaction = item.dataset.interaction;

        item.addEventListener("mouseover", () => {
            cursor.classList.add(interaction);
        });
        item.addEventListener("mouseleave", () => {
            cursor.classList.remove(interaction);
        });
    });
}))
.contrast__link {
  background: white;
}

.cursor {
  background: red;
  height: 20px;
  width: 20px;
  position: fixed;
}

.dark-mode {
  background: black;
}

.retro {
  background: blue;
}
Toggle Classes

A: I would suggest to add and remove "mousemove" listener inside "click" listener, when you toggling the theme. So if user selects "retro", the event listener should be removed, and when it is another theme, the listener should be added.

A: I have tried with simple CSS code, it's working
 .retro .cursor{
    display:none
}

but you want to stop the function also, so tried the following that also worked. When the theme is retro on mouse move the cursor changing function is not calling

/* Toggle */

const html = document.querySelector("html");
const cursor = document.querySelector(".cursor");

function addClass() {
  if (html.classList.contains("dark-mode")) {
    html.classList.remove("dark-mode");
    html.classList.add("retro");
    cursor.style.display = 'none'

  } else if (html.classList.contains("retro")) {
    html.classList.remove("retro");

  } else {
    html.classList.add("dark-mode");
  }
}

document.addEventListener('mousemove', function(e) {
  if (html.classList.contains("retro")) {
    cursor.style.display = 'none'
  } else {
    cursor.style.display = 'block'
    var x = e.clientX;
    var y = e.clientY;
    cursor.style.transform = `translate(${x - 2}px, ${y - 2}px)`;
  }
});
.cursor {
  background: red;
  height: 20px;
  width: 20px;
  position: fixed;
}

.dark-mode {
  background: black;
}

.retro {
  background: blue;
}

<button onclick='addClass()'>Add Class</button>

A: As @Mykhailo Svyrydovych suggested, to avoid any overhead of the unneeded events call, you would need to have explictly named functions for each event handler, then you could use removeEventListener when you're toggling to the retro theme, removing the handler of each mousemove, mouseenter, mouseleave, mouseup and mousedown events that you don't want to run on that theme. Of course, you would need to re-bind all the events again using the proper addEventListener calls when toggling to the other two themes.
But I think that, sometimes, the easiest approach is good enough. If you measure the performance and then discover that the events keeping to fire isn't a big concern for your case, go for it. You can easily avoid the unwanted effects of the custom cursor, inside each event handler, just by checking a simple boolean:

const html = document.documentElement;
const button = document.querySelector(".contrast__link");
const cursor = document.querySelector(".cursor");
const cursorTrail = document.querySelector(".cursor-trail");
const a = document.querySelectorAll("a");
let timeout;
let customCursor = true;

button.addEventListener("click", (e) => {
  e.preventDefault();
  if (html.classList.contains("dark-mode")) {
    html.classList.remove("dark-mode");
    html.classList.add("retro");
    customCursor = false;
    cursor.style.display = "none";
  } else if (html.classList.contains("retro")) {
    html.classList.remove("retro");
    customCursor = true;
    cursor.style.display = "block";
  } else {
    html.classList.add("dark-mode");
    customCursor = true;
    cursor.style.display = "block";
  }
});

window.addEventListener(
  "mousemove",
  function(e) {
    if (!customCursor) return;
    var x = e.clientX;
    var y = e.clientY;
    cursor.style.display = "block";
    cursor.style.transform = `translate(${x - 2}px, ${y - 2}px)`;
    if (!timeout) {
      timeout = setTimeout(function() {
        cursorTrail.style.transform = `translate(${x - 16}px, ${y - 16}px)`;
      }, 24);
    }
  },
  false
);

document.addEventListener("mousedown", () => {
  if (!customCursor) return;
  cursor.classList.add("cursor--click");
});

document.addEventListener("mouseup", () => {
  if (!customCursor) return;
  cursor.classList.remove("cursor--click");
});

let links = document.querySelectorAll('a, #hello');
links.forEach((item) => {
  item.addEventListener("mouseover", () => {
    if (!customCursor) return;
    cursorTrail.classList.add("cursor-trail--hover");
  });
  item.addEventListener("mouseleave", () => {
    if (!customCursor) return;
    cursorTrail.classList.remove("cursor-trail--hover");
  });
});

a.forEach((item) => {
  const interaction = item.dataset.interaction;
  item.addEventListener("mouseover", () => {
    if (!customCursor) return;
    cursor.classList.add(interaction);
  });
  item.addEventListener("mouseleave", () => {
    if (!customCursor) return;
    cursor.classList.remove(interaction);
  });
});
.contrast__link {
  background: white;
}

.cursor {
  background: red;
  height: 20px;
  width: 20px;
  position: fixed;
  display: none;
}

.dark-mode {
  background: black;
}

.retro {
  background: blue;
}
Toggle Classes

P.S.: I removed the Swiper calls from my code sample because they appeared to be totally unrelated to the question being asked, and were causing console errors.

A: You can use element insertion and window properties to load/unload code.
Look at code in snippet, there's simple system for theme changing.
When on retro, mouse clicks will be logged in console.
In my snippet, script will be working only on retro theme, but that doesn't changes concept.

const themeList = {
  'default': {
    enable() {
      app.classList.add('default');
    },
    disable() {
      app.classList.remove('default');
    },
  },
  'dark-mode': {
    enable() {
      app.classList.add('dark-mode');
    },
    disable() {
      app.classList.remove('dark-mode');
    },
  },
  'retro': {
    enable() {
      app.classList.add('retro');
      js = document.createElement("script");
      js.id = 'retroThemeScript';
      js.innerHTML = `
        window.fnToBeRemoved = () => console.log('mouse down');
        app.addEventListener("mousedown", window.fnToBeRemoved);
      ` // you can replace code with next line, so no need to store code in RAM
      //js.src = '/scripts/retroScript.js';
      js.type = 'text/javascript';
      app.appendChild(js);
      this.scriptElement = js;
    },
    disable() {
      app.classList.remove('retro');
      app.removeEventListener('mousedown', window.fnToBeRemoved);
      delete window.fnToBeRemoved;
      app.removeChild(this.scriptElement);
    },
  }
}

const app = document.querySelector('#app');

let currentTheme;

function setTheme(themeName) {
  if (currentTheme)
    themeList[currentTheme].disable();
  themeList[themeName].enable();
  currentTheme = themeName;
}

setTheme('default');
#app {
  font-size: 24px;
  width: 500px;
  height: 500px;
  background: silver;
}

#app.retro{
  background: magenta;
}

#app.dark-mode {
  background: gray;
}
<button onclick="setTheme('default')">Default</button>
<button onclick="setTheme('dark-mode')">Dark</button>
<button onclick="setTheme('retro')">Retro</button>

  Wanna cake?


text:
Q: MongoDB .NET Driver ProjectionDefinition Slice method does not work I work with a MongoDB collection in ASP.NET Core 3 application via a compatible MongoDB Driver.
The document structure in my collection includes, among others, an array field (lets call it "steps").
My task is to project the collection with all its fields, while fetching the last two members of this array per document.
This is a mongo query which I run in Robo 3T:
db.getCollection('MyCollection').find({}, {"steps" : {$slice: -2}})

It works perfectly, and projects the data in the exact same way that I want it to.
However, I cannot successfully copy this to my ASP.NET app.
This is how I build the projection in C#:
ProjectionDefinitionBuilder<BsonDocument> fieldsBuilder = Builders<BsonDocument>.Projection;
ProjectionDefinition<BsonDocument> stepsArrayProjection = fieldsBuilder.Slice("steps", -2);
List<MyCollectionModel> result = await myMongoService.GetDataByFilterDefinitionAsync(filter, stepsArrayProjection);

where filter is a predefined FilterDefinition<BsonDocument> that I use.
When I try to run the query in my ASP.NET controller via Swagger, I get an exception, which says:
MongoDB.Driver.MongoCommandException: Command aggregate failed: Expression $slice takes at least 2 arguments, and at most 3, but 1 were passed in.

What I am trying to understand, is why is it any different from the $slice projection that I use while querying the collection in Robo 3T. It seems that I pass 2 the field name to slice, and which array members to take.
Any help will be appreciated. Thanks.

A: I don't think there is a difference and actually, the C# driver is pretty consistent with the Mongo shell command. I would do it like follows, though:
var filter = Builders<MyCollectionModel>.Filter.Empty;
var project = Builders<MyCollectionModel>.Projection.Slice(x => x.Steps, skip);
var result = context.MyMongoCollection.Find(filter).Project(project).ToList();


text:
Q: ggplot in function using environment variables: arguments imply differing number of rows I have a function to print and save some charts using ggplot.  The data frame being used for the plots has NAs in some of the columns - so I subset the data first (and not in ggplot).  When I run the function for the first time, it works (and when I run the code in R line-by-line and not as a function, it works as well for ALL inputs).  However, when I try to run the function a second time with another input, it receive the error:
Error in data.frame(x = c(1, 21, 41, 53, 75, 80, 87, 100), y = c(1000,  :
arguments imply differing number of rows: 8, 6

After some research, I'm convinced I'm not calling out a correct data frame somewhere in the ggplot layers, and the environment variable is getting used instead of the input variable.  But, I cannot pinpoint the error.  I've listed some sample data that works in the function.
smpl_data <- data.frame(c(2011,2011,2011,2011,2012,2012,2012,2012),c(1,21,41,53,75,80,87,100),c(1000,1100,1200,1300,950,1050,1150,1250),c(2100,NA,2200,2300,2050,2150,NA,2350))
names(smpl_data) <- c("year","Date_Rank","ModWS_00X_3","ModWS_53X_3")

#THE FOLLOWING CODE WORKS:
testfunc(DF=smpl_data,year1=2011,year2=2012,module="00X",workscope=3)
#THIS DOESNT - BUT WILL IF I MANUALLY RESET MY chrt DATASETS:
testfunc(DF=smpl_data,year1=2011,year2=2012,module="53X",workscope=3)

testfunc <- function(DF, year1, year2, module, workscope) {

#SUBSET DATA
mod_ws = paste("ModWS_", module, "_", workscope, sep="")
chrt_data <- subset(DF, !is.na(DF[[mod_ws]]))
chrt_d1 <- subset(chrt_data, chrt_data$year == year1)
chrt_d2 <- subset(chrt_data, chrt_data$year == year2)

#RUN CHART
mean1 <- mean(chrt_d1[[mod_ws]])
mean2 <- mean(chrt_d2[[mod_ws]])
upsig1 <- mean1+(3*(sqrt(var(chrt_d1[[mod_ws]]))))
dnsig1 <- mean1-(3*(sqrt(var(chrt_d1[[mod_ws]]))))
upsig2 <- mean2+(3*(sqrt(var(chrt_d2[[mod_ws]]))))
dnsig2 <- mean2-(3*(sqrt(var(chrt_d2[[mod_ws]]))))
upmax = max(upsig1,upsig2)
dnmin = min(dnsig1, dnsig2)

runchart <- ggplot(chrt_data) +
geom_line(aes(x=chrt_data$Date_Rank,y=chrt_data[[mod_ws]],colour=as.factor(chrt_data$year)),size=2) +
geom_segment(x=0,xend=74,y=mean1,yend=mean1,linetype=2,size=1,colour="red") +
geom_segment(x=61,xend=102,y=mean2,yend=mean2,linetype=2,size=1,colour="blue") +
geom_segment(x=0,xend=74,y=upsig1,yend=upsig1,linetype=2,size=1,colour="green") +
geom_segment(x=0,xend=74,y=dnsig1,yend=dnsig1,linetype=2,size=1,colour="green") +
geom_segment(x=61,xend=102,y=upsig2,yend=upsig2,linetype=2,size=1,colour="green") +
geom_segment(x=61,xend=102,y=dnsig2,yend=dnsig2,linetype=2,size=1,colour="green") +
ylim(dnmin-1000,upmax+1000) + xlab("Date") + ylab("Cost") + scale_colour_discrete(name="Year")

print(runchart)
dev.print(bmp, file=paste("C:/filepath/R function output/R_charts_",mod_ws,"IMR.bmp",sep=""),width=900,height=150,units="px")
dev.off

#DENSITY PLOT
MEANS <- data.frame(c(2011,2012),c(mean(chrt_d1[[mod_ws]]),mean(chrt_d2[[mod_ws]])))
names(MEANS)=c("year","avg")
cmax = max(max(chrt_d1[[mod_ws]]),max(chrt_d2[[mod_ws]]))
cmin = min(min(chrt_d1[[mod_ws]]),min(chrt_d2[[mod_ws]]))
lrange = cmin - (.5*(cmax-cmin))
rrange = cmax + (.5*(cmax-cmin))

Dplot <- ggplot(chrt_data, aes(x=chrt_data[[mod_ws]], colour=as.factor(chrt_data$year))) + geom_density(size=2) + geom_hline(yintercept=0,size=2) +
geom_vline(data=MEANS, xintercept=MEANS$avg, linetype=2, size=1) +
xlim(lrange, rrange) +
xlab(paste(mod_ws," Cost",sep="")) +
scale_colour_discrete(name="Year")

print(Dplot)
dev.print(bmp, file=paste("C:/filepath/R function output/R_charts_",mod_ws,"Density.bmp",sep=""),width=900,height=150,units="px")
dev.off()

#BOX PLOT
BOX <- ggplot(chrt_data, aes(x=as.factor(chrt_data$year),y=chrt_data[[mod_ws]], colour=as.factor(chrt_data$year)))+
geom_boxplot(size=1.5, outlier.colour="green",outlier.size=3) +
guides(fill=FALSE) + ylim(lrange,rrange) + coord_flip() +
ylab(paste(mod_ws," Cost",sep="")) +
xlab("Year") +
scale_colour_discrete(name="Year")

print(BOX)
dev.print(bmp,file=paste("C:/filepath/R function output/R_charts_",mod_ws,"BOX.bmp",sep=""),width=900,height=150,units="px")
dev.off()

return("Done")

}


text:
Q: Setting the max http connections on `[NSURLSession backgroundSessionConfigurationWithIdentifier]` is not working I'm trying to create a simple downloader for our app. The app will download large files from our server (at least 100 MB per file), so I want to implement a downloader that will work even if the app is inactive.
I'm using NSURLSession to handle this requests. Here's how I initialised the session:
@property (nonatomic) NSURLSession *downloadSession;

- (void)viewDidLoad {
   [super viewDidLoad];

   // Initialise the session
   NSURLSessionConfiguration *sessionConfig = [NSURLSession backgroundSessionConfigurationWithIdentifier: @"backgroundSessionIdentifier"];
   [sessionConfig setHTTPMaximumConnectionsPerHost:10];

   _downloadSession = [NSURLSession sessionWithConfiguration: sessionConfig delegate: self delegateQueue: nil];
}

I also implement the NSURLSessionDownloadDelegate function below to check the progress of each download:
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
   float totalProgress = (float)totalBytesWritten / (float)totalBytesExpectedToWrite;
   NSLog(@"URL: %@, progress: %f", downloadTask.originalRequest.URL.absoluteString, totalProgress);
}

I have a UICollectionView and each cell has a button that will create a download task when tapped:
// A delegate function of the custom UICollectionViewCell
- (void)beginDownloadAtIndex:(NSInteger)fileIndex {
    NSString *fileURL = [self.urls objectAtIndex: fileIndex];
    NSURLSessionDownloadTask *downloadTask = [self.downloadSession downloadTaskWithURL: [NSURL URLWithString: fileURL]];
    [downloadTask resume];
}

Now say that I have 10 items in the UICollectionView. I set the HTTPMaximumConnectionsPerHost to 10 so that I can download them simultaneously.
What happens is that the first 3 download tasks I created will begin downloading simultaneously, but the other 7 will not. When one of the first 3 download tasks is complete, one of the "dormant" download task will then begin downloading.
I may be doing something wrong because when I tried using the default session configuration [NSURLSessionConfiguration defaultSessionConfiguration], all 10 download tasks will begin downloading simultaneously.
I'd really appreciate it if anyone can help me to identify what's wrong with my code.

A: Background sessions happen out of process in a separate background daemon.  It seems very likely that Apple deliberately limited the ability to change that parameter to prevent an unusually high number of transfers from being in flight while your app isn't running.
You can file a bug with Apple, but I suspect that they'll send it back as "Behaves correctly".
That said, I'm not sure what you're trying to achieve by using a large number of parallel downloads.  Barring unusually high packet loss or deliberate throttling by the ISP (e.g. burst mode), there shouldn't be much difference between running ten large downloads three at a time and running them ten at a time, on average.


text:
Q: Why is Tkinter missing? Started messing with Tkinter today, but when I tried to run my first program it crashed. It appears the reason is that I don't have Tkinter. This is a standard installation of Python 3.3 on Windows 7, why is it not there? How can I get it?

A: This answer might be irrelevant with more information, but, for now: are you capitalizing "Tkinter" when using the import command?  In Python 3.x, it's imported as lower-case ("import tkinter"), but in 2.x code it's imported with an initial capital ("import Tkinter").

A: Maybe you disabled it during Python installation? It is Tcl/Tk item in install wizard and it can be disabled. Try reinstall Python and do not turn it off.

A: Both of the answers above are perfectly good ideas but if neither of these work make sure you are using this code:
    from tkinter import *

Rather than this code:
    import tkinter


text:
Q: Как отключить сообщения о предупреждениях и ошибках ndk-build? Как отключить сообщения о предупреждениях и ошибках ndk-build?
A: В $NDK_ROOT/build/core/init.mk определен вывод сообщений:
__ndk_name    := Android NDK
__ndk_info     = $(info $(__ndk_name): $1 $2 $3 $4 $5)
__ndk_warning  = $(warning $(__ndk_name): $1 $2 $3 $4 $5)
__ndk_error    = $(error $(__ndk_name): $1 $2 $3 $4 $5)

ifdef NDK_NO_WARNINGS
__ndk_warning :=
endif
ifdef NDK_NO_ERRORS
__ndk_error :=
endif

Определив NDK_NO_WARNINGS, NDK_NO_ERRORS, можно отключить сообщения о предупреждениях и ошибках скрипта. Но сообщения от самого make останутся.


text:
Q: Executing SQL statement stored as a field value Is it possible to execute a SQL statement that has been stored within a table as text.
I am trying to create a configuration table to drive a large number of SSRS subscriptions and don't want to code any values directly into the report I want them all driven from a table for maintance.
E.G.
If part of one reports file name will always be the year of the previous month (2013 for example) but this needs to be generated at run time.
Can I stored this as a text field
CAST(YEAR(DATEADD(month, -1, GETDATE())) AS VARCHAR(4))

Then execute it and resolve the result into a SQL query?

A: If I understand your question correctly, then yes by using dynamic SQL. For example:
DECLARE @SQL NVARCHAR(4000)
DECLARE @YEAR VARCHAR(4)
SET @SQL = 'SELECT @yr = CAST(YEAR(DATEADD(month, -1, GETDATE())) AS VARCHAR(4))'
EXECUTE sp_executesql @SQL, N'@yr VARCHAR(4) OUTPUT', @yr=@YEAR OUTPUT

SELECT @YEAR

...returns 2013 into variable @YEAR.
Here I've hardcoded the query but it is a simple case to build the value of @SQL from a table's column value instead. You can then use the result from this query to build another dynamic query and so on.
Below is a subset of the above showing the SQL being taken from a table instead:
CREATE TABLE Dynamic (id INTEGER, text VARCHAR(4000) )
INSERT Dynamic values (1, 'CAST(YEAR(DATEADD(month, -1, GETDATE())) AS VARCHAR(4))')

SET @SQL = 'SELECT @yr = ' + (SELECT text FROM Dynamic WHERE id =  1)

A: why couldn't you?
Is it only one line of values per report?
I see 2 choices with SSRS.
1) everything in sql, you do dynamic sql.
declare @sql nvarchar(4000)
select @sql = 'select * from mytable where year = ' mavar'
from tablevalue  where uniqueid = blablabla
exec sp_executesql @sql

second possibilty :
You make a first dataset in SSRS getting this value and then you evaluate the value of your condition and send it to a third dataset.
If you have multiple values, you can still imagine to get the value from a first dataset, evaluate them and send this to a subreport.
I don't know your application enought to determine the performance of this.
Until you are in SSRS, i recommand to try to find a solution in SSRS instead of Sql (but it's not a gold rule at all!!!)


text:
Q: How to limit the text of polygons in Voronoi diagram with D3.js? I've see the Example of D3.js-Voronoi Tessellation.But I want to put some text in each of polygons instead of a circle,Here is my js code:
var width = 600, height = 400;

var vertices = d3.range(20).map(function(d){
  return [Math.random() * width, Math.random() * height]
});

var voronoi = d3.geom.voronoi();

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

path = svg.append("g").selectAll("path");

svg.selectAll("info")
    .data(vertices.slice(1))
    .enter().append("text")
    .attr("transform", function(d) {
      return "translate(" + d + ")";
    })
    .text("someText")
    .attr("shape-rendering","crispEdges")
    .style("text-anchor","middle");

redraw();

function redraw(){
  path = path
      .data(voronoi(vertices), polygon);

  path.exit().remove();

  path.enter().append("path")
      .attr("class", function(d, i) {return "q" + (i % 9) + "-9";})
      .attr("d", polygon);

  path.order();
}

function polygon(d){
  return "M" + d.join("L") + "Z";
}

I have a JSFiddle for that basic example here:
my voronoi code
now, I want each of the polygons' text in the center of the polygon, and don't cross with the polygon's border. If the polygon have not enough space to contain the all text, just contain the first part of it!
Let me know if there is anything I can do to solve this issue, thank you!
PS:I'm so sorry to my English, yes, it's so poor!  :)

A: Have a look at this example http://bl.ocks.org/mbostock/6909318 , you probably want to place the text at the polygon centroid and not the seed (point) used to determine the voronoi tessellation.
That should fix the majority of your layout issues.
Automatically scaling the text to fit is a little bit harder, if you are willing to scale and rotate the text you can use a technique similar to the following to determine the length of the line at that point:
https://mathoverflow.net/questions/116418/find-longest-segment-through-centroid-of-2d-convex-polygon
Then you need to determine the angle of the line.  I have a plugin that should help with that:
http://bl.ocks.org/stephen101/7640188/3ffe0c5dbb040f785b91687640a893bae07e36c3
Lastly you need to scale and rotate the text to fit.  To determine the width of the text use getBBox() on the text element:
var text = svg.append("svg:text")
    .attr("x", 480)
    .attr("y", 250)
    .attr("dy", ".35em")
    .attr("text-anchor", "middle")
    .style("font", "300 128px Helvetica Neue")
    .text("Hello, getBBox!");

var bbox = text.node().getBBox();

Then you use the angle you calculated earlier to scale and rotate your text:
text.attr("transform", "rotate(40) scale(7)")

I would love to give a complete example but this is quite a bit of work to get it right.
There are other options to achieve the same effect but none of them are simple (ie you could anneal the layout similar to the way d3 does the Sankey layout)


text:
Q: APK signed with a different APK files of the previous certificate I'm trying to update an application on the play store and it returns an error:

You uploaded an APK signed with a different APK files of the previous certificate. You must use the same certificate. Your APK are signed with a digital certificate that includes the fingerprint
  [SHA1: 8B: FF: 30: 3B: 2A: 02: 3E: DD: 73: EE: 3B: 5F: 3A: C8: C1: B3: 72: F8]
  While the certificate that you used to sign the APK you uploaded has the fingerprint
  [SHA1: B3: 91: 7C: 1B: AF: 1D: 29: 64: 30: E8: 11: 9C: E6: 30: E2: B9: 48: AB]

I formatted my pc and reinstall Android Studio.
I remember the name of my keystore, the alias, and passwords, but I had to create them again.
I read that if you were losing the key you could not use another. I don't understand becouse I don't forget the names or passwords, anyway lost the possibility to update my app?

A: Doesn't make a difference unfortunately. If you lost the keystore you initially created while building your final application, you cannot update the application on the google play store anymore :(
It happened to me last month, so I had to create a new application with different package name (because you cannot have 2 applications with same package name under one google developer account).


text:
Q: How can I resolve error that appear when I write "npm start" command in VSCode Terminal? I have this error when I write
npm start

command in VSCode Terminal:

Error: Could not find a production build in the 'E:\React-Practis\nextjs-project2.next' directory. Try building your app with 'next build' before starting the production server."

How can I resolve this error?

A: Try this:
npm run build

Then do this:
npm run start


text:
Q: Sticky footer, but only sometimes pt. 3 Same issue as before (see Sticky Footer, but only sometimes and Sticky Footer, but only sometimes...continued)...
I have a footer that I want to stick to the bottom of the page unless content fills the page, then I want it to get pushed down.  I've done this a dozen times with other sites, but I can't get this one to work.  Working in Wordpress.  I've checked the order of my divs and I've gone over the css...any help is appreciated.
The main css components:
* {
    margin: 0;
    padding: 0;
}

html, body {
    height:100%;
    min-height:100%;
}

#wrapper {
    background:url("images/shadowborder.png") repeat-y center;
    width:100%;
        max-width:100%;
        min-width:980px;
    min-height:100%!important;
        margin:0 auto;
    margin-bottom:-20px;
    position:relative;
    overflow:auto;
}

#content {
    clear:both;
    float:left;
    padding:20px 20px 60px 20px;
    font-size: 1.6em
}
#spacer {
    height: 40px;
    clear: both;
}

#footer {
    position: relative;
    border-top: 1px solid #e5a5fc;
    padding:3px!important;
    height:20px;
}

The site:
http://www.hcfmissoula.com

A: The recipe I use is:

*

*height: 100% on html

*min-height: 100% and position: relative on body (with height:100% for ie6)

*position: absolute and bottom: 0 on the footer div

Maybe be tricky preventing footer from obscuring some text near the bottom though.


text:
Q: tidyr::spread tidyr::pivot_wider with multiple different values per key Given this data:
+----+---------+----------+------+------+------+
| id |  type   |   name   | var1 | var2 | var3 |
+----+---------+----------+------+------+------+
| 10 | Country | Norway   |  169 | 14   |  164 |
| 10 | Sport   | Skii     |  169 | 14   |  164 |
| 10 | Format  | Video    |  169 | 14   |  164 |
| 11 | Country | Spain    |  150 | 16   |  178 |
| 11 | Format  | Photo    |  150 | 16   |  178 |
| 11 | Sport   | Bike     |  150 | 16   |  178 |
| 11 | Sport   | Soccer   |  150 | 16   |  178 |
| 11 | Sport   | Basket   |  150 | 16   |  178 |
| 12 | Country | USA      |    0 | 0    |    0 |
| 12 | Format  | Video    |    0 | NA   |    0 |
| 12 | Sport   | Baseball |    0 | 0    |    0 |
+----+---------+----------+------+------+------+

what is the easiest and cleanest way to spread it as follows:
+----+------+------+------+---------+--------+----------+---------+---------+
| id | var1 | var2 | var3 | Country | Format | Sport_1  | Sport_2 | Sport_3 |
+----+------+------+------+---------+--------+----------+---------+---------+
| 10 |  169 |   14 |  164 | Norway  | Video  | Skii     | NA      | NA      |
| 11 |  150 |   16 |  178 | Spain   | Photo  | Bike     | Soccer  | Basket  |
| 12 |    0 |    0 |    0 | USA     | Video  | Baseball | NA      | NA      |
+----+------+------+------+---------+--------+----------+---------+---------+

Note the NA for id 12 too.
I've tried using:
data2 <- data %>% pivot_wider(names_from = type, values_from = name)

But it gives me a Warning saying that values in "name" are not uniquely identified, which is true for id 11 (type Sport is repeated three times).
Also, I expect the NA in id 12 to create issues too, since the function would not group together this:
| 12 | Country | USA      |    0 | 0    |    0 |
| 12 | Sport   | Baseball |    0 | 0    |    0 |

and this:
| 12 | Format  | Video    |    0 | NA   |    0 |

because of the NA, despite having the same id.
Any help is much appreciated. Many thanks in advance!

A: We can do this by filtering the 'Sport' elements from 'type' and then do a join on the separate spread datasets
sportdf <- df1 %>%
            filter(type == "Sport") %>%
            group_by(id) %>%
            mutate(type = str_c(type, row_number())) %>%
            spread(type, name)
formatCountrydf <- df1 %>%
                    filter(type != "Sport")  %>%
                    mutate(var2 = replace_na(var2, 0)) %>%
                    spread(type, name)
inner_join(sportdf, formatCountrydf)
# A tibble: 3 x 9
# Groups:   id [3]
#     id  var1  var2  var3 Sport1   Sport2 Sport3 Country Format
#  <int> <int> <dbl> <int> <chr>    <chr>  <chr>  <chr>   <chr>
#1    10   169    14   164 Skii     <NA>   <NA>   Norway  Video
#2    11   150    16   178 Bike     Soccer Basket Spain   Photo
#3    12     0     0     0 Baseball <NA>   <NA>   USA     Video

data
df1 <- structure(list(id = c(10L, 10L, 10L, 11L, 11L, 11L, 11L, 11L,
12L, 12L, 12L), type = c("Country", "Sport", "Format", "Country",
"Format", "Sport", "Sport", "Sport", "Country", "Format", "Sport"
), name = c("Norway", "Skii", "Video", "Spain", "Photo", "Bike",
"Soccer", "Basket", "USA", "Video", "Baseball"), var1 = c(169L,
169L, 169L, 150L, 150L, 150L, 150L, 150L, 0L, 0L, 0L), var2 = c(14L,
14L, 14L, 16L, 16L, 16L, 16L, 16L, 0L, NA, 0L), var3 = c(164L,
164L, 164L, 178L, 178L, 178L, 178L, 178L, 0L, 0L, 0L)),
class = "data.frame", row.names = c(NA,
-11L))

A: Here's a way to do it, borrowing @akrun's data :
library(tidyr)
df1 %>%
  replace_na(list(var2=0)) %>%
  pivot_wider(names_from = "type", values_from = "name", values_fn = list(name=list)) %>%
  mutate_at(vars(Country, Format), unlist) %>%
  mutate_at("Sport", unclass) %>%
  unnest_wider(Sport, names_sep = "_", names_repair = ~sub("..." , "", ., fixed=TRUE))

# New names:
# * `` -> ...1
# New names:
# * `` -> ...1
# * `` -> ...2
# * `` -> ...3
# New names:
# * `` -> ...1
# # A tibble: 3 x 9
#     id  var1  var2  var3 Country Sport_1  Sport_2 Sport_3 Format
#   <int> <int> <dbl> <int> <chr>   <chr>    <chr>   <chr>   <chr>
# 1    10   169    14   164 Norway  Skii     NA      NA      Video
# 2    11   150    16   178 Spain   Bike     Soccer  Basket  Photo
# 3    12     0     0     0 USA     Baseball NA      NA      Video


text:
Q: Implement a button in a table that returns data from the table using Thymeleaf and Spring Boot tl;dr with Spring Boot and Thymeleaf, how do I return the column 1 value of the table in a form when the user clicks the button in column 5 of a particular row?
Hi there!  Long time listener, first time caller.  I'd be much obliged for your help with this issue.
I'm writing a server app using Spring Boot and Thymeleaf.  The server interacts with a number of devices.  I'm creating a web page that will show the list of devices and their IP addresses in a table (in a form). Each row of the table has info about the device and a "Remove" button to remove the device from the list.  When the button is clicked, the form should return the IP address of the device to the underlying Controller so the Controller can remove the device from the (internal) list of devices.
I can get it to either return nothing at all, or ALL of the IP addresses (as a string with commas separating the values), but I can't get it to return ONLY the address on the row of the clicked button.
The searches I've done have turned up ways to do it for static tables, but not dynamically generated ones, or for regular "input" type inputs, not buttons.  Nothing specific to click this button, return this value from the other column of the same row.
I'm trying to do this in relatively pure Java and HTML, but I'm not opposed to some snippets of JavaScript if it solves the problem.  I don't really know anything about JQuery... and JSP pages are also not an option for other project reasons.
HTML:
  <form action="#" th:action="@{/webservice/adddevice}" th:object="${addForm}" method="post">

Device IP
        Status
        Model Name
        Serial No.
        Remove?

        N/A
        N/A
        N/A
        N/A
        <input type="hidden" th:value="${d.address}" name="deviceIP"/><button type="submit" class="removebutton" name="action" value="remove">Remove</button>
        IP Error

My latest (and closest-to-the-mark) attempt uses the hidden input on each row to return the value... but it returns the value for ALL of the rows.
The "devices" (class DeviceStatus) object is a List of your standard data object with a bunch of string members and get/set methods.  It holds the info for the attached devices.
The "addForm" (class AddForm) object is a single object with a string ("deviceIP") and get/set methods for that string.
The controller GET method:
    @RequestMapping(value="/webservice/adddevice", method=RequestMethod.GET)
public String showForm(Model model, AddForm addForm) {
    model.addAttribute("devices", getDevicesStatus());
    addForm.loadPrefs(deviceController);
return "adddevice"; // the webpage is adddevice.html
}

and the controller POST method:
    @RequestMapping(value="/webservice/adddevice", method=RequestMethod.POST, params="action=remove")
public String removeDevice(@Valid AddForm addForm, BindingResult bindingResult) {
//addForm.removeDevice(deviceController);
return "redirect:/webservice/results";
}

For now the POST method doesn't do anything... until I get the HTML Form working, there's not much point.

A: I will show you how we solved that in our application. we generate a form for every action in a table row like this:

    ...

        ...

            <form action="#" th:action="@{/dashboard/myEntries/} + ${{entry.id}}" method="get">
                <button th:id="'table_entry_childs_button_' + ${entry.id}" type="submit">
                    details
                </button>
            </form>

        ...

That solution works fine for us. I'm encouraged that I was able to help you.

A: Thanks to the comment from pDer666 I have a solution!!
Changed the HTML to:

Device IP
        Status
        Model Name
        Serial No.
        Remove?

        <form action="#" th:action="@{/webservice/adddevice}" th:object="${addForm}" method="post">
        N/A
        N/A
        N/A
        N/A
        <input type="hidden" th:value="${d.address}" name="deviceIP"/><button type="submit" class="removebutton" name="action" value="remove">Remove</button>
        IP Error
        </form>

Putting the form inside the table row loop structure creates a separate form for each row, and now when the button is clicked, my POST method receives only the IP address for the corresponding row.
THANK YOU pDer666!


text:
Q: How to do overlay icons on the taskbar in Windows 7 for .NET Microsoft's UX guidelines recommend that I use overlay icons to show when my application has information about statuses, like unread messages or connectivity.
However, I not having much luck finding a clear tutorial on how to get starting using overlay icons in my application. Can someone recommend one, or better yet, create a tutorial on their blog for betterment of mankind?
(The question title specifically mentions Windows 7, but I think it would also be useful for Vista to be included in this tutorial, as well as backwards compatibility issues with Windows XP, etc.)
Edit: This question was really asked for .NET 3.5 using WinForms. Here's a quick snippet of code that should work if you download the Windows API Code Pack referenced below in ken2k's answer.
Imports Microsoft.WindowsAPICodePack.Taskbar
' Add reference to Microsoft.WindowsAPICodePack.Shell.dll
' Snipped...

If TaskbarManager.IsPlatformSupported Then
  TaskbarManager.Instance.SetOverlayIcon(icon, altText)
End If

A: I would suggest using the Windows® API Code Pack for Microsoft® .NET Framework that wraps all the shell programming stuff.
You'll find a very detailed article here that'll show you how to use it.
Note that the Windows® API Code Pack doesn't work with XP (not supported), and is very limited with Vista. Overlay icons are only available on Windows 7 for instance.


text:
Q: How to set a value to single radio button in a group box containing 4 radio buttons with grideview cellclick event in c# How to get value from gridview and set coresponding radio button in group box?
dataGridView1.Rows[e.RowIndex].Cells[2] (how to get this value to a char
variable?)the values are 'V' or 'N' present in the gridview.
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
    dataGridView1.CurrentRow.Selected = true;
    textBox1.Text = dataGridView1.Rows[e.RowIndex].Cells[1].Value+"";
    textBox2.Text = dataGridView1.Rows[e.RowIndex].Cells[3].Value + "";
    comboBox1.Text = dataGridView1.Rows[e.RowIndex].Cells[4].Value + "";
}

A: Assuming the radio button that represents V is called vRadioButton etc, something like:
vRadioButton.Checked = "V".Equals(dataGridView1.CurrentRow.Cells[xxx].Value);
nRadioButton.Checked = "N".Equals(dataGridView1.CurrentRow.Cells[xxx].Value);

where xxx  is either the name or number of the column holding V or N
Ultimately you have to compare the in-grid value with a constant to generate a boolean abd set Checked to that bool


text:
Q: Quest editor in java for big game It's a very specific problem I have:
I'm working on a text-based RPG, where the main work is to implement an editor, that gives the possibility to add NPCs, Items and place them on the map (...) without any knowledge about programming.
All of these things work fine with doing some SQL queries and the whole thing already works. Now I'm working on quest editing. My basic concept is, that every time the player enters a command, a database entry for the specific string is queried, that's linked to a set of conditions and actions, which have unique IDs. Those are queried in the java code, where a specific condition (e.g. that the players money equals 100) has a part of code that returns the result. This means, that hundreds (or more) IFs have to be passed, each time a command is entered - same with the actions according to the command. I'm not even sure if that is the right way (If anyone has a propose to this, feel free to post).
The point is now, that quests basically consist of quest stages, which also have conditions to be enabled and actions, performed when enabled. That means, that also with each entered command, all of these queries have to take place. I thought about using some kind of trigger, but I don't have a good idea how to implement it, because I don't really want to edit java code out of this editor. I also considered using prolog, but also in that case I'd have to add triggers into java code I guess.
I know that this is a little bit hard to handle in a forum like this, but if anyone has a suggestion, I'd be really glad.
EDIT:
As suggested in a comment, I'd like to shorten the whole thing: If any command (out of houndres or thousands) could trigger one particular quest/quest stage (out of thousands) and these triggers should be set with an editor, what's a proper way to implement that?

A: reasoning over lots of facts and triggering actions when a set of facts matches specific conditions is a good match for drools.
you could represent every action/decision that the player has made as a fact, which you could insert into a drools knowledge session.
in that session you could store all of your "triggers" as drools rules, which will fire when a collection of facts in memory match the condition.
drools supports dynamic addition/removal/editing of rules and is explicitely targeted at allowing non-developers to write logic using a simpler rule language.
the specific part of drools to start with is the core - drools expert


text:
Q: How to set the highest bit rate to a flac output on Pydub? I've trying to change the format of all my pack samples, from .WAV to FLAC. I made a script that checks all the subdirectories and finds file paths (WAV files specifically), and after find, it uses Pydub to convert the files. The problem is that the FLAC output bit rate is too smaller than the WAV file. My code below:
import os

import tnt  # My library to get subdirectories
from pydub import AudioSegment

__all__ = ['convert', 'convert_all']

def convert(file_path, remove=False):
    file = AudioSegment.from_wav(file_path)

    # Parameters should be passed here, but I really don't know how to keep
    # the highest bit rate possible according with the input file bit depth.
    # By Default the output bit rate is about 300 kb/s.
    file.export(file_path.replace('.wav', '.flac'), format='flac')

    if remove:
        os.remove(file_path)

def convert_all(root_path, remove=False):
    file_names = tnt.DirWalker(root_path).get_file_names()

    for f in file_names:
        if f.endswith('.wav'):
            convert(f, remove)

Please, a command to put on os.system('ffmpeg -i "input.wav" "output.flac"') to get highest bit rate possible according with the original file bit depth would be nice too.


text:
Q: How enable Deblocking Filter in ffmpeg h264 Encoder I am new to ffmpeg. I have searched Stack Overflow for this question, but was not able to get the exact answer.

export LD_LIBRARY_PATH=:./FFMPEGEncLibs
  ./ffmpegEnc -f rawvideo -r 60 -s 1920x1080 -vcodec rawvideo -i ./encIn/piglab_1frames.yuv -c:v libx264 -x264-params cabac=0:8x8dct=0 -pix_fmt yuv422p -profile:v high422 -psnr -intra -qp 9 ./encOut/EncOut_1frames.h264
export LD_LIBRARY_PATH=:./FFMPEGDecLibs
  ./ffmpegDec -f h264 -i ./encOut/piglab_EncOut_1frames.h264 ./decOut/DecOut_1frames.yuv

A: The deblocking filter (assuming you mean the one part of the h264 standard) is automatically enabled in x264. To control the loopfilter parameters, use the "deblock" private codec option:
Loop filter parameters, in <alpha:beta> form.


text:
Q: Concept of integration and differentiation on any set? I am learning multivariable calculus. I would like to have 2 questions:

*

*Concerning integration, I see that there is the definition of integration of a function from $X \to \mathbb{R}$ ($X$ is any set). Is there any concept of integration of a function from $X \to Y$ where $Y$ is an arbitrary set  ?

*More generally, which is the condition of the set $X, Y$ for which we can define differentiation and integration for a function $f: X \to Y$ ? What makes integration and differentiation "so special" that it requires some conditions to be defined ?
Thank you very much for your help!

A: First, I would just like to point out that "defining integration" is already a vague concept; usually we would like to construct our definitions for a specific purpose. In the case of Riemann integration the symbol $\int$ roughly corresponds to the opposite of differentiation. In real analysis, we redefine the symbol $\int$ with a specific purpose in mind, namely making the class of integrable functions complete.
For example, I can "define" integration as $\int:\bf{R}\rightarrow \bf{R}$ by $x\mapsto x^2$ so that now $\int\,f(x)\,dx = (f(x))^2$. I can't think of a situation where this would be desired, but long story short is you can define $\int$ however you want and take it over any set and map into any set. But I know this isn't really what you are asking.
With this in mind:

*

*The Lebesgue integral is fairly general and defines $\int:X\rightarrow \bf{C}$ for $X$ a measure space, which informally means you can make precise the notion of "size". Other "generalized" integrals you may be interested in are the Bochner integral and the Bessel potential.

*What makes differentiation and integration special is that we have defined them to be special. I find many students starting out in math have thoughts along these lines, and I certainly had them myself.
To elaborate on this second point. The notion of differentiation you have learned is defined in a very special way, and all of the resulting theory is a consequence of our definition, not a consequence of some independent thing called "differentiation"; "differentiation" is just what we call (in calculus at least) the operation of taking a limit of a difference quotient.
So now you want to generalize this thing called "differentiation"; there isn't some straightforward way that mathematicians generalize notions. For example there is a generalization known as Sobolev differentiation or weak differentiation which is very specifically defined to capture one aspect of derivatives, namely that it is the opposite operation of integration. We define a Sobolev derivative by noting that we can integrate "bad" functions, but can only differentiate $C^1$ functions meaningfully (in the sense you've learned in calculus). The Sobolev derivative says that any function which is the integral of a "bad" function has that function as it's Sobolev derivative. This class of functions turns out to be much larger than $C^1$, and is the proper context in which to talk about differential equations.
There is another notion of "fractional differentiation" which, depending on your perspective, further generalizes Sobolev differentiation or agrees with the notion for differentiation of integer order. The point being that this is yet another "generalization", and that these generalizations don't even mess with the domain and range yet!
Long story short: technically yes, but in general when generalizing definitions you would like a specific purpose in mind.


text:
Q: Java - regarding Android Studio alongside PyCharm I'm running LinuxMint and developing in Android Studio while using PyCharm for a class so I can code in Python. I have openJDK7 installed and I'm currently using it for both Android Studio and PyCharm. Whenever I open Android Studio, though, it complains and says that I should use the Oracle JDK, not OpenJDK. Is there a way to install multiple versions of Java and update the environment variables so that Android Studio uses the Oracle JDK and PyCharm sticks with OpenJDK? Or would it make sense to use the Oracle JDK for both?
Thanks in advance!


text:
Q: Hide and Show inputField Based upon Radio Button I have a small problem with a validation here

<apex:selectRadio styleClass="radioinput" onChange="myFunction(this);">
                        <apex:selectOption itemlabel="CPF" itemValue="CPF" />
                        <apex:selectOption itemlabel="CNPJ" itemValue="CNPJ"/>
                    </apex:selectRadio>

                <apex:inputField style="display:none" id="CPF" value="{!Cliente__c.CPF__c}"/>
                <apex:inputField style="display:none" id="CNPJ" value="{!Cliente__c.CNPJ__c}"/>

I want, when I click on cpf, hide cnpj and remove the true request, and the reverse as well. But the function is not working :(

A: JavaScript simply isn't going to work here. Even if you got as far as showing/hiding the fields, the net result would be that you'd get errors when interacting with the controller.
However, while we're on that topic, your JS has two main problems. First, ID values on apex namespace components are "mangled" by the system, so you need to use $Component variable, and second, JavaScript is cAsE-sEnSiTiVe, so it would have been V.value, not V.Value.
The Visualforce way of doing this would be to use apex:actionSupport:
<apex:actionRegion>
  <apex:selectRadio styleClass="radioinput" value="{!typeSelection}">
    <apex:selectOption itemlabel="CPF" itemValue="CPF" />
    <apex:selectOption itemlabel="CNPJ" itemValue="CNPJ"/>
    <apex:actionSupport event="onchange" reRender="CPF,CNPJ" />
  </apex:selectRadio>
</apex:actionRegion>
<apex:outputText rendered="{!typeSelection='CPF'}" id="CPF">
  <apex:inputField required="true" value="{!Cliente__c.CPF__c}"/>
</apex:outputText>
<apex:outputText rendered="{!typeSelection='CPNJ'}" id="CNPJ">
  <apex:inputField required="true" value="{!Cliente__c.CNPJ__c}"/>
</apex:outputText>

Additional tweaks may be necessary, but this should get you started.


text:
Q: android imageview display in bad quality I try to display 3 images medium size.
The problem is that they display in low quality and it damages the UI a lot,I checked over the internet and the best solution is to use is Piccaso,but I want to know how can I display the image in it's full quality without third-library?
I load images like this:
<ImageView
        android:id="@+id/btnring"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/itayring1"

        />

and I also tried this:
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.itayicon);
    b1.setImageBitmap(bb);

When I used Eclipse I could load images easly. There must be a way to do in Android Studio too,
Thanks.

A: Put Images in xhdpi drawable image only and try this code :
    <ImageView
    android:id="@+id/btnring"
    android:layout_height="50dp"
    android:layout_height="wrap_content"
    android:scaleType="centerCrop"
    android:adjustViewBounds="true"
    android:src="@drawable/itayring1"
    />


text:
Q: choosing energy instead of hp count in aodv I am modifying AODV protocol of NS2 to change the criterion of route selection. I have changed the condition into energy residue in the aodv code for receiving packets and reply. Can anyone explain 'precursor' related code's purpose. Should I modify that part also? Is there any other work similar to what I am doing?

A: if u want to choose the path based on energy level means first you have to add new field energy in routing protocol .without that field how the nodes can check the energy levels of its won with the neighbouring nodes..
first try to add energy field in aodv/packet.h


text:
Q: How to get last 4 weeks dates in power query (Excel or Power BI) Using Power Query coding language AKA "m", write a statement to add a custom column that shows a bit value of whether a Delivery Date is in the past 4 weeks including up to the current date.
Please #help
Result in blank query:
5/13/2021
5/12/2021
5/11/2021
5/10/2021
5/09/2021
Until
4/19/2021

A: If I understand your requirement correct, you need the custom column code-
if Duration.Days(DateTime.Date(DateTime.LocalNow()) - [Delivery date]) <= 28 then 1 else 0


text:
Q: Optimization of an SQL Query on multiple tables with Left joins I have created a custom mysql query which is running fine and showing the output I want, but it is currently taking a lot of time as data volumes are high.
So, please help me in optimizing query run time.
SELECT t.*, te + tc + tt AS total, (te + tc + tt)/7 AS weekly_Avg
FROM (SELECT t2.first_name, COUNT(DISTINCT emails.id) AS te,
        COUNT(DISTINCT calls.id) AS tc, COUNT(DISTINCT tasks.id) AS tt
      FROM users AS t2
      LEFT JOIN emails
        ON t2.id = emails.assigned_user_id
        AND emails.date_entered >= '2014-03-20 00:00:00'
        AND emails.date_entered <= '2014-06-30 00:00:00'
      LEFT JOIN calls
        ON t2.id = calls.assigned_user_id
        AND calls.date_entered >= '2014-03-20 00:00:00'
        AND calls.date_entered <= '2014-06-30 00:00:00'
      LEFT JOIN tasks
        ON t2.id = tasks.assigned_user_id
        AND tasks.date_entered >= '2014-03-20 00:00:00'
        AND tasks.date_entered <= '2014-06-30 00:00:00')
      WHERE t2.id IN ('1', '2')
      GROUP BY t2.id) t

A: How many calls / emails / tasks are there per user in the time period? This query is effectively doing a cross join of the results, so if there were (say) 100 of each per user, that is giving you 1000000 records per user and then sorting out the unique ones within that list.
If so it might be easier to have a sub query to get each count and join the results together.
SELECT t . * ,te+tc+tt as total , (,te+tc+tt)/7 as weekly_Avg
FROM
(
    SELECT t2.first_name, emails_count AS te, calls_count AS tc, tasks_count AS tt
    FROM  `users` AS t2
    LEFT JOIN
    (
        SELECT assigned_user_id, COUNT( emails.id ) AS emails_count
        FROM emails
        WHERE emails.assigned_user_id IN ( '1',  '2')
        AND (emails.date_entered >=  '2014-03-20 00:00:00'
        AND emails.date_entered <=  '2014-06-30 00:00:00')
        GROUP BY assigned_user_id
    ) sub_emails
    ON t2.id = sub_emails.assigned_user_id
    LEFT JOIN
    (
        SELECT assigned_user_id, COUNT( calls.id ) AS calls_count
        FROM calls
        WHERE calls.assigned_user_id IN ( '1',  '2')
        AND (calls.date_entered >=  '2014-03-20 00:00:00'
        AND calls.date_entered <=  '2014-06-30 00:00:00')
        GROUP BY assigned_user_id
    ) sub_calls
    ON t2.id = sub_calls.assigned_user_id
    LEFT JOIN
    (
        SELECT assigned_user_id, COUNT( tasks.id ) AS tasks_count
        FROM tasks
        WHERE tasks.assigned_user_id IN ( '1',  '2')
        AND (tasks.date_entered >=  '2014-03-20 00:00:00'
        AND tasks.date_entered <=  '2014-06-30 00:00:00')
        GROUP BY assigned_user_id
    ) sub_tasks
    ON t2.id = sub_tasks.assigned_user_id
    WHERE t2.id IN ('1',  '2')
)t

Note, the checks for user_id within the sub queries are not strictly necessary, but should speed things up a bit.

A: I see you're joining tables and filtering afterward. For instance:
SELECT t2.first_name, COUNT( DISTINCT emails.id ) AS te, COUNT( DISTINCT calls.id ) AS tc, COUNT( DISTINCT tasks.id ) AS tt
FROM  `users` AS t2
LEFT JOIN emails ON t2.id = emails.assigned_user_id
AND (

emails.date_entered >=  '2014-03-20 00:00:00'
AND emails.date_entered <=  '2014-06-30 00:00:00'
)

You should rather do something like this:
SELECT t2.first_name, COUNT( DISTINCT emails.id ) AS te, COUNT( DISTINCT calls.id ) AS tc, COUNT( DISTINCT tasks.id ) AS tt
FROM  `users` AS t2
LEFT JOIN
(SELECT FIELDS_YOU_NEED
 FROM `emails`
 WHERE date_entered >=  '2014-03-20 00:00:00' AND date_entered <=  '2014-06-30 00:00:00'
 ) AS emails2

ON t2.id = emails2.assigned_user_id

This way you'll reduce significantly the time consumed joining tables.


text:
Q: How to hide Calling UI and make calls with custom UI? I have created a custom ui and making a call using telecom manager for direct dialing. But every time Device default Calling UI is opening.
Here is some code for making calls directly...
TelecomManager telecomManager=(TelecomManager)getSystemService(Context.TELECOM_SERVICE);
                Uri uri = Uri.fromParts("tel", phonenumber, null);
                Bundle extras = new Bundle();
                extras.putBoolean(TelecomManager.METADATA_IN_CALL_SERVICE_UI, true);
                extras.putBoolean(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE,true);
                try {
                    if (telecomManager!=null) {
                        telecomManager.showInCallScreen(true);
                    }
                }catch(SecurityException incoming){
                    incoming.printStackTrace();
                }

                try {
                    if (telecomManager!=null) {
                        telecomManager.placeCall(uri, extras);
                    }
                }catch(SecurityException unlikely){
                    unlikely.printStackTrace();
                }

is there a way to hide the default calling ui and use our own calling ui.?
Any help will be appreciated.

A: See the API docs on how to use the placeCall API.  METADATA_IN_CALL_SERVICE_UI should not be passed to placeCall, and EXTRA_PHONE_ACCOUNT_HANDLE is not a boolean extra.  You need to pass in a PhoneAccountHandle.  However, if you're just trying to place a regular mobile call, just omit that extra as the system will pick the right one.
showInCallScreen should also only really be used by the Dialer app to bring its UI to the foreground; its not going to have any impact in your case.
If you want to use your Dialer app as the in-call UI, you need to change it in the system settings.
System Settings --> Apps & Notifications --> Advanced --> Default Apps --> Phone App.  Choose your app there.
To be a default phone app you need to handle the DIAL intent and implement the InCallService API.


text:
Q: How to specify HTTP expiration header? (ASP.NET MVC+IIS) I am already using output caching in my ASP.NET MVC application.
Page speed tells me to specify HTTP cache expiration for css and images in the response header.
I know that the Response object contains some properties that control cache expiration. I know that these properties can be used to control HTTP caching for response that I am serving from my code:
Response.Expires
Response.ExpiresAbsolute
Response.CacheControl

or alternatively
Response.AddHeader("Expires", "Thu, 01 Dec 1994 16:00:00 GMT");

The question is how do I set the Expires header for resources that are served automatically, e.g. images, css and such?

A: Found it:
I need to specify client cache for static content (in web.config).
<configuration>
  <system.webServer>
    <staticContent>
      <clientCache cacheControlCustom="public"
      cacheControlMaxAge="12:00:00" cacheControlMode="UseMaxAge" />
    </staticContent>
   </system.webServer>
</configuration>

from http://www.iis.net/ConfigReference/system.webServer/staticContent/clientCache

A: If you want to do it from code for a resource that you're returning (ie. not a static file being served from IIS), you're better off using Response.Cache:
Response.Cache.SetExpires(DateTime.Now.AddYears(1));
Response.Cache.SetCacheability(HttpCacheability.Public);

I know that's not exactly what you're asking for, but I found this question via Google and figure others might like this answer as it's related to the APIs you show in the original question text.

A: Look at mini static content delivery project. :)


text:
Q: how do I get a document from elasticsearch only by id from all the index i have a project in python where i need to get a document from one of for indexes index_1 2 3 or 4 but i only have the id and in the near future i will have 4 more idexe so 8 in total i can't afford to look for the doc in every one of the 8.
so my question is, is there a way to get the doc directly by the id? if not is there an alternative? thank you very much
here is what i have until now:
url = settings.ES_URL+"/{}/_doc/{}?pretty=false"
url = url.format(index, id)
r = requests.get(url,auth=HTTPBasicAuth('*****', '*******'))

and i try every index but that's not what i want

A: You can make use of Index Alias. Essentially it still searches in multiple indexes, but you don't have to mention individual index names while searching.
Say I have the below two indexes
PUT my_index_001

PUT my_index_002

And below two documents in those indexes
POST my_index_001/_doc/1234
{
  "myfield": "test"
}

POST my_index_002/_doc/1235
{
  "myfield": "test"
}

I can create my alias index my_index in the below fashion
PUT /my_index_001/_alias/my_index

PUT /my_index_002/_alias/my_index

Now you can simply use this index to search the document via any term or match query.
POST my_index/_search.          <--- Note the index used here to search
{
  "query": {
    "term": {
      "_id": "1234"             <--- Note the field `_id`
    }
  }
}

Note that you cannot get the document directly like this GET my_index/_doc/1234 using the concept of Alias as firstly that is a single index operation and I believe the whole purpose of having alias is to enhance search functionality seamlessly and not meant for direct document retrieval.

A: Use alias feature of elasticsearch to map all indices under one alias. Later in place of querying all 8 indices, query associated alias index and that will do the job for you to search through all 8 and return the results.