text:
Q: use ffmpeg in java ubuntu i try to convert video using ffmpeg in ubuntu.
ffmpeg -i inputfile.flv -sameq outputfile.mpeg

this works if change directory to inputfile directory.
is that posible to use this command ?
ffmpeg -i "home/Documents/inputfile.flv" -sameq "home/Documents/outputfile.mpeg"

i don't want to change directory when i use that command, because that command is using for my java code.
so my input file and output file is variable in my code .
here's my full code
package Converter;

import Controller.ConvertedButtonListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Arrays;

/**
 *
 * @author roylisto
 */
public class VideoConverter {
    private String defaultFile;
    private String convertedFile;
    private ConverterThread myThread;
    private ConvertedButtonListener butListener;
    public VideoConverter(String fileDir,String convertOutput,ConvertedButtonListener buttonListener){
        this.defaultFile=fileDir;
        this.convertedFile=convertOutput;
        this.butListener=buttonListener;
    }
    public void convertToMjpeg(){
        String[] listCommands={"ffmpeg","-i","\""+defaultFile+"\"","-qscale","0","\""+convertedFile+"\""};
        myThread=new ConverterThread(listCommands,this);
        myThread.start();
    }
    public void setCommandStream(String stream){
        butListener.setCommandOutput(stream);
    }
    class ConverterThread extends Thread{
        VideoConverter vc;
        String[] command;
        ConverterThread(String[] command,VideoConverter vc){
            this.command=command;
            this.vc=vc;
        }
        public void run(){
            synchronized(vc){
                try{
                    String s = null;
                    Process process = new ProcessBuilder(command).start();
                    BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
                    BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
                    StringBuffer start= new StringBuffer();
                    // read the output from the command
                        while ((s = stdInput.readLine()) != null)
                        {
                            start.append(s);
                            vc.setCommandStream(s);
                        }
                        stdInput.close();
                        // read any errors from the attempted command
                        while ((s = stdError.readLine()) != null)
                        {
                            start.append(s);
                            vc.setCommandStream(s);
                        }
                }catch(Exception ex){
                    System.out.println(ex.toString());
                }
            }
        }
    }
}

until now my code works well in windows with some modification like change ffmpeg to ffmpeg.exe because ffmpeg isn't native in my windows. but when i use my code in ubuntu
it show this error
"/home/roylisto/Documents/Tugas Akhir/Video Master/3a.avi": No such file or directory

UPDATE
solve problem, here's my code :)
package Converter;

import Controller.ConvertedButtonListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Arrays;

/**
 *
 * @author roylisto
 */
public class VideoConverter {
    private String defaultFile;
    private String convertedFile;
    private ConverterThread myThread;
    private ConvertedButtonListener butListener;
    public VideoConverter(String fileDir,String convertOutput,ConvertedButtonListener buttonListener){
        this.defaultFile=fileDir;
        this.convertedFile=convertOutput;
        this.butListener=buttonListener;
    }
    public void convertToMjpeg(){
        String[] listCommands={"ffmpeg","-i",defaultFile,"-qscale","0",convertedFile};
        myThread=new ConverterThread(listCommands,this);
        myThread.start();
    }
    public void setCommandStream(String stream){
        butListener.setCommandOutput(stream);
    }
    class ConverterThread extends Thread{
        VideoConverter vc;
        String[] command;
        ConverterThread(String[] command,VideoConverter vc){
            this.command=command;
            this.vc=vc;
        }
        public void run(){
            synchronized(vc){
                try{
                    String s = null;
                    Process process = new ProcessBuilder(command).start();
                    BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
                    BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
                    StringBuffer start= new StringBuffer();
                    // read the output from the command
                        while ((s = stdInput.readLine()) != null)
                        {
                            start.append(s);
                            vc.setCommandStream(s);
                        }
                        stdInput.close();
                        // read any errors from the attempted command
                        while ((s = stdError.readLine()) != null)
                        {
                            start.append(s);
                            vc.setCommandStream(s);
                        }
                }catch(Exception ex){
                    System.out.println(ex.toString());
                }
            }
        }
    }
}

A:
is that posible to use this command ?

Yes, it is possible, as long as you specify a valid absolute or a relative path:
"home/Documents/inputfile.flv"

Should be:
"/home/Documents/inputfile.flv"

Otherwise it'd look for a home directory inside the current working directory. Notice the / at the beginning.
And as for this:
"/home/roylisto/Documents/Tugas Akhir/Video Master/3a.avi": No such file or directory

Are you really shure the file is there and you have r/w access to that directory?


text:
Q: what issue tracking software does linux development use? The reason I ask this is because it seems silly to me to contrive an issue tracking system for git when linux development must already have one that works perfectly for git. In fact, git is designed around linux development (from everything I understand), and so as far as I can tell, git must implicitly already have/work-with an issue-tracking system.
Perhaps linux development doesn't use issue tracking software, but surely the developers have some system.
What issue tracking system does linux development use?

A: Bugzilla?
Also, see this.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Trying to understand matrices (3D programming) http://i52.tinypic.com/5mmjoi.png <- take a peek here for the equations
Well, I've been studying matrices lately as I was interested more into the workings of changes of coordinate systems, obj->world and such. And I am looking at this couple of equations which are trying to interpret the vector-matrix multiplication as a linear combination of the matrix's row vectors scaled by the individual components of the u vector.
I do understand that they are just "reshaping" it into a few components, scaling the basis vectors of the translated coordinate system. The standard vector product is exactly the same as the combined row vectors scaled by x,y,z. It's more intuitive to see it when it is decomposed as such than just vague multiplications of the y coordinate with the second vector's x coordinate in the standard version and then added to the z and x values, how the dot product dictates.
My question is: How does one know what alterations are allowed, he just simply picks out the parts of the solution vector, sorting it by x, y and z. Do you simply do that or are there rules. The result certainly is correct, he has all the stuff necessary for a linear combination but how does he know what can and can't he touch?
A little more elaboration, even from the top, would be appreciated? Basically how and why does this work? Thanks everyone!

A: If I understand your question correctly, it's just a matter of grouping like terms.  We start with regular multiplication uM:
            | m11 m12 m13 |
| x y z | * | m21 m22 m23 | = | xm11+ym21+zm31 xm12+ym22+zm32 xm13+ym23+zm33 |
            | m31 m32 m33 |

The author of your image wants to show that the dot product of the vector with each column is the same thing as taking a weighted sum of each row so that's how he breaks the resulting vector apart.  He's free to break it apart any which way he wants so long as the final sum remains the same.
E.g.:
| xm11+ym21+zm31 xm12+ym22+zm32 xm13+ym23+zm33 | =
| xm11+ym21 xm12+ym22 xm13+ym23 | + | zm31 zm32 zm33 | =
| xm11 xm12 xm13 | + | ym21 ym22 ym23 | + | zm31 zm32 zm33 | =
| xm11 ym22 zm33 | + | ym21 zm32 xm13 | + | zm31 xm12 ym23 | =
| xm11+ym21+zm31-1 xm12+ym22+zm32-1 xm13+ym23+zm33-1 | + | 1 1 1 |

Etc.


text:
Q: Can Google Protocol Buffers be serialized/parsed between different languages? The official site as well as some other sources describe one of the benefits of Google Protocol Buffers as being highly inter-operable. I know the technology supports different language bindings out of the box, and many more as third party implementations, but what does that mean exactly?
Is my understanding correct in thinking that as long as I have a common schema file, I can run the protoc compiler and generate code for multiple languages, and then write a program in one language using the generated code, serialize some data to a file, and then parse it in another language in another program?
For example, could my client-side application running in Java serialize a Google Protocol Buffer and send it over the wire to a server implemented in C++ which can then parse it and use it readily as long as both sides were generated from the same schema file?
If that is correct, what allows that to happen - is it that their serialization/parsing logic adhere to a common/consistent wire format detailed here?

A: Yes, you can, and yes, it is because the wire format is fixed (i.e. the same for any language binding).


text:
Q: Systemd timer for the first business day of every month Just wondering if there is a way to schedule a timer for the first business day of every month?
Basically the first day of every month which is not a weekend.
I am trying to avoid creating a wrapper script if possible

A: [Timer]
OnCalendar=Mon..Fri *-*-1..3 00:00:00

This executes the service

*

*only if it is a business day

*only the first 3 days of the month

The intersection of these directives leads to the first business day (Monday to Friday) of every month.
Examples:

*

*Day 1 is Saturday, day 2 is Sunday, day 3 is Monday. Script runs the 3rd

*Day 1 is Sunday, day 2 is Monday. Script runs the 2nd

*Day 1 is Thursday. Script runs the 1st

Source: ArchWiki

A: [Timer]
OnCalendar=Mon..Fri *-*-01
OnCalendar=Mon *-*-02..03

There are two OnCalendar conditions needed. This can be done in one timer.

*

*Mon..Fri *-*-01 will activate if the first day of the month is a business day

*Mon *-*-02..03 will activate if the second or third day of the month is a Monday. This happens if the first was a Sunday, or if the first was a Saturday and the second was a Sunday. There is no overlap.

To verify this you can use:
systemd-analyze calendar 'Mon..Fri *-*-01' 'Mon *-*-02..03' --iterations 10

I find it easier to verify if you filter and sort only the iterations by appending |grep Iteration |sort -k4, but this will cut off the first iteration.
You can do a very similar thing but in reverse with the last business day of the month:
[Timer]
OnCalendar=Mon..Fri *-*~01
OnCalendar=Fri *-*~02..03

With systemd v233 you can specify a day relative to the end of the month. Instead of using - before the day you use ~.

*

*Mon..Fri *-*~01 triggers if the last day of the month is a business day

*Fri *-*~02..03 triggers if the second to last or third to last day of the month was a Friday. This happens if the weekend is on the last day of the month.

Again, you can verify this using:
systemd-analyze calendar 'Mon..Fri *-*~01' 'Fri *-*~02..03' --iterations 10


text:
Q: PHP cURL gives an error but works fine in POSTMAN I have some problem(s) with PHP cURL. I tried to get data from the API using PHP cURL. This is my cURL code in PHP :
<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://www.example.com/dos/AW/API",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => "{\"Filter\" : {\"IsActive\" : \"True\",\"OutputSelector\" : \"Name\"}}",
  CURLOPT_HTTPHEADER => array(
    "API_ACTION: GetItem",
    "API_KEY: MHlIARzQqxVpOg2dUxH4q9w7bx3pOL6K",
    "Accept: application/json"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}

?>

With that code I can get a response but the response contains some errors. I also tried using POSTMAN to check, and the API works fine as I got a successful response with the same data. My question is: "Is there anything wrong with my cURL code that would explain why I got an error when I used cURL and I got successful response in POSTMAN "?
I would appreciate if someone could help me with this.
Thank you very much.

A: given that you aren't showing us the successful postman request, we can't know for sure what errors you make, that said, you are making a couple of obvious mistakes here.
first off, when debugging curl code, use CURLOPT_VERBOSE , it gies you a lot of useful information when debugging your curl requests (and if you did this, you would probably notice how the Postman requests's content-type is completely different from curl's content-type  http headers - more on this soon)
second, when you want a POST request, don't use CURLOPT_CUSTOMREQUEST, use CURLOPT_POST.
third, when passing a string to CURLOPT_POSTFIELDS, the content-type implicitly becomes Content-Type: application/x-www-urlencoded, unless you override it. and you are obviously NOT sending x-www-urlencoded data, but JSON-encoded data, so your content-type is all wrong, its supposed to be Content-type: application/json
fourth, you can hardcode the json if you want, but the code looks much prettier if you json_encode it
fifth, don't use setopt / setopt_array without checking the return type.
fixing all that, you'll end up with something like:
function ecurl_setopt_array($ch, array $options) {
    if (! curl_setopt_array ( $ch, $options )) {
        throw new \RuntimeException ( 'curl_setopt_array failed. ' . curl_errno ( $ch ) . ': ' . curl_error ( $ch ) );
    }
}

$curl = curl_init ();

ecurl_setopt_array ( $curl, array (
        CURLOPT_URL => "https://www.example.com/dos/AW/API",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_VERBOSE => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode ( array (
                'Filter' => array (
                        'IsActive' => 'True',
                        'OutputSelector' => 'Name'
                )
        ) ),
        CURLOPT_HTTPHEADER => array (
                "API_ACTION: GetItem",
                "API_KEY: MHlIARzQqxVpOg2dUxH4q9w7bx3pOL6K",
                "Accept: application/json",
                'Content-Type: application/json'
        )
) );

$response = curl_exec ( $curl );
$err = curl_error ( $curl );

curl_close ( $curl );

if ($err) {
    echo "cURL Error #:" . $err;
} else {
    echo $response;
}

Edit: fixed the json data, when i wrote it, i didn't see that isActive is not an actual boolean, but the string literal True - i mistakenly encoded it as a json boolean true instead, sorry, fixed. (although i suspect it's supposed to be a boolean anyway, and that your original code just encodes it wrong, perhaps you should double check isActive's type in the api docs, assuming there is one)

A: @Antonio, Response you are getting is from the other end, might be you are missing something which restrict the processing of query at other end. try to print http_code, or use curl_getinfo to get complete information.
in case of response code is 200, then you may ask from another end to validate the request.
PS: not able to comment because of repo restrictions.


text:
Q: What status code to return when an invalidly generated link has been clicked? Consider the following situation:
I have a MVC setup where the view invokes a mapper to get a specific URL for a href attribute. The mapper holds keys to make the referencing easy.
Now the view requests an invalid key, so the mapper responds with say /invalid_url. But the dispatcher knows this URL and when a user clicks the link an error message will be displayed about how bad we feel.
But what if the Google Bot visits this invalid URL?
What would a search engine friendly status code be? I feel like 500 would be appropriate because it is a server side failure. But then this has the feeling of being a temporary error or somehow not related to the URL but to the internal mechanics. The other option that comes to mind is 404. This is also valid because the requested page does not exist. However 4xx errors are client side errors ("You requested the wrong URL. So it's basically your error"). And it just doesn't feel like a client side error to me.
Am I overthinking things? Should I just go with 404?

A: When I have a question like this, I refer to a site like http://www.restapitutorial.com/httpstatuscodes.html
5xx error codes imply that the server made a mistake. But you're saying the view (client-side) requested the wrong key. That sounds like a client-side error to me. While it's not the user's fault, the server doesn't know this, and the requested URL really doesn't exist. So a 404 would be appropriate.
But this is a weird case, and you should still want to fix the underlying issue of the client consistently(?) requesting a bad url.


text:
Q: Re-making Logo in CSS Would it be possible to re-make this logo using CSS so I can have it as text?
http://acquiremedia.com/templates/amc/images/icon/acquire-media.png

A: You could do something like this: https://jsfiddle.net/b3jtc7v5/1/

acquiremedia

CSS
h1 {
    font-family:arial;
    color:#000;
    position:relative;
    display:inline-block;
}

h1 span {
    color:lime;
}

h1:before {
    content:"";
    position:absolute;
    top:0;
    left:75px;
    color:lime;
    width:10px;
    height:10px;
    background-color:lime;
    border-radius:50%;
}

h1 span:after {
   content:"";
    position:absolute;
    top:0;
    left:180px;
    width:10px;
    height:10px;
    background-color:black;
    border-radius:50%;
}

Using the :before pseudo element we can add a small circle and position it over the the i in the text.


text:
Q: How to get the email address of a Facebook user using the graph API? I have read through this post over and over, and yet it doesn't make sense to me.
What I am trying to do is acquire a Facebook user's email address so that I can store it in a string and compare to see if it matches the emails of existing users in my MySQL database. I only need to to do this when the user first grants access rights to the app.
In the "Authenticated Referrals" section of my app developer interface, I have set "User & Friend Permissions" to include "email".
Within the "canvas" area of my site, I have this code:
include('facebook/base_facebook.php');
include('facebook/facebook.php');
$facebook = new Facebook(array(
    'appId'  => "XXXXXXXXXXXXXXX",
    'secret' => "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
));
$user = $facebook->getUser();
if ($user)
{
    try {
        $user_profile = $facebook->api('/me');
    } catch (FacebookApiException $e) {
        $user = null;
    }
}

If I var_dup() $user, I can see the user id (though not much else) which seems to be correct, so I believe I'm connecting to the right place on Facebook.
But then there was this suggested line of code, which implies that it returns an email address, but when I echo it out to see what it looks like, it doesn't return an email address:
echo "<br/>" . $facebook->getLoginUrl(array('req_perms' => 'email'));

I kind of thought it wouldn't, as it doesn't look quite right to me, but on the other hand, I just have no idea what else to do with it or where to put it.
And then I also came across this post, which has code mixed in with the HTML in a way that baffles me even further.
Assuming that my user has granted permission for my app to see their email, isn't there a simple way of getting at it? Something an inexperienced programmer like myself can grasp?

A: As suggested in comments you should replace req_perms with scope since it is the name for field indicating which permissions to be granted by users.
Once email permission is granted (do you see it's asked in the Auth Dialog?) you'll be able to get email field via Graph API. You can also retrieve only required fields in results by specifying 'em in the fields parameter:
$facebook->api('/me', array('fields' => 'id,email'));

BTW, Please not that both posts you refer to are old (2010), way many things changed in the platform. Be sure to read updated documentation on Permissions and Authentication

A: You are using outdated method. You can use the code below to retrieve the email.
You can find more information about Facebook Connect from : http://25labs.com/tutorial-integrate-facebook-connect-to-your-website-using-php-sdk-v-3-x-x-which-uses-graph-api/
$app_id     = "xxxxxxxxx";
$app_secret = "xxxxxxxxxx";
$site_url   = "xxxxxxxxxxxxx";

include_once "src/facebook.php";

$facebook = new Facebook(array(
    'appId'     => $app_id,
    'secret'    => $app_secret,
    ));

$user = $facebook->getUser();

if($user){
    try{
        $user_profile = $facebook->api('/me');
    }catch(FacebookApiException $e){
        $user = NULL;
    }
}

if($user){
    $logoutUrl = $facebook->getLogoutUrl();
}else{
    $loginUrl = $facebook->getLoginUrl(array(
        'scope'         => 'email',
        'redirect_uri'  => $site_url,
        ));
}

if($user){
    Echo "Email : " . $user_profile['email'];
}

A: You can concatenate a Facebook username with the e-mail address. For example, my username is "umair.hamid.79" on Facebook. It will be "umair.hamid.79@facebook.com".


text:
Q: Randomly allot values to the rows in python I have the following input table (y):

parameter1
parameter2

1
12

2
23

3
66

4
98

5
90

6
14

7
7

8
56

9
1

I would like to randomly allot values from A1 to A9. The output table should look like the following:

parameter1
parameter2
parameter3

1
12
A5

2
23
A2

3
66
A4

4
98
A8

5
90
A3

6
14
A7

7
7
A1

8
56
A9

9
1
A6

n = 9

TGn = round(len(y)/n)
idx = set(y.index // TGn)

y = y.apply(lambda x: x.sample(frac=1,random_state=1234)).reset_index(drop=True)

treatment_groups = [f"A{i}" for i in range(1, n+1)]
y['groupAfterRandomization'] = (y.index // TGn).map(dict(zip(idx, treatment_groups)))

I am unable to fill the first row value it prints as NaN. How do I tackle this problem?

A: Series.sample
We can use sample with frac=1 to sample the values from the column parameter1 then use radd to concatenate prefix A with the sampled values
df['parameter3'] = df['parameter1'].sample(frac=1).astype(str).radd('A').values

   parameter1  parameter2 parameter3
0           1          12         A2
1           2          23         A8
2           3          66         A1
3           4          98         A4
4           5          90         A9
5           6          14         A3
6           7           7         A6
7           8          56         A7
8           9           1         A5


text:
Q: Is a probability measure uqual to the product of the marginal measures? Let $P$ a probability measure on $\mathbb{R}^d$. Is it true that $P(\prod_{k=1}^d(A_k))=\prod_{k=1}^d (P\circ\pi^{-1}_k(A_k))$ where $\pi_k:\mathbb{R}^d\rightarrow\mathbb{R}$ is the kth projection?
This fact is trivially false if the measure is not a probability measure (for example take the Lebesgue measure). Can someone help me to prove the statement or to find a counterexample?
Moreover, why $P$ is tight if and only if $(P\circ\pi^{-1}_k)$ are tight for all k?

A: Try the joint distribution of any $d$ random variables that are not independent.


text: Q: I copied my hdd to ssd with ddrescue it worked earlier but didn't work this time why? I generally use this command sudo ddrescue /dev/sda /dev/sdb --force to clone my hdd ubuntu to ssd and the ssd would boot and work like a charm but .. this time the new ssd drive is not booting. does have to do with the file system in target ssd doesn't ddrescue or dd do a complete clone including file system and all.What can I do to clone my harddrive to ssd make that ssd a fully independent bootable disk;


text:
Q: Browser Extension (CrossRider) iframe origin and parent access I am developing with Crossrider an extension at the moment. I am now in the process of making it working also on IE and Chrome. The extension adds an IFrame to every page as a sidebar and from the iframe interacts with the parent window. To make this work I use Crossriders "recommendation" of using a data encoded block for the iframe instead of a URL to work around the same domain issue for security.
This works in Firefox (and with some hacking also in IE), however in Chrome i have the following issues:

Blocked a frame with origin "null" from accessing a cross-origin
  frame.

From what I read the only way around it is to actually be on the same domain (not possible as the plugin works for every website) or use cross window messaging (because of a rich interaction we have with the parent a lot of overhead). So my question is, how can I configure override or whatever to fix this for Chrome, is there a way? As a quick work around it can even be a setting I have to do in chrome.
But in general I think there should be a way around this because in the end I already have full access to the browser because the extension is installed, so I assume I should be able to override this somehow?

A: In general, iframes are protected by security policies implemented by browsers. Hence, the simplest way to interact between an iframe and the extension running on its parent page, is to send messages between them.
You can achieve this by enabling the (Settings >) Run in Iframes feature in the IDE, and then differentiate between the iframe and its parent in the extension.js code. The following example should help you understand the general idea:
extension.js:
appAPI.ready(function($) {
  if (appAPI.dom.isIframe()) {
    // iframe code
    appAPI.message.addListener(function(msg) {
      if (msg.action === 'someAction') {
        ...
        // send response
        appAPI.message.toCurrentTabWindow({
          action:'otherAction',
          response:'otherResponse'
        });
      }
    });
    // end iframe code
    return;
  }
  // Parent window code
  appAPI.message.addListener(function(msg) {
    if (msg.action === 'otherAction') {
      ...
      // send response
      appAPI.message.toCurrentTabIframes({
        action:'someAction',
        response:'someResponse'
      });
    }
  });
});

For more information on the methods used in the example, see appAPI.dom.isIframe, appAPI.message.toCurrentTabIframes, and appAPI.message.toCurrentTabWindow.
[Disclosure: I am a Crossrider employee]

A: You can use object urls as your iframe src. they considered as the same origin as the creating page.
https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL


text:
Q: Proving the induced derivation of endomorphism equals trace on top exterior power Let $V$ be a finite-dimensional vector space over a field $K$ of dimension $r:= \dim_K(V)$ (let's say $K$ equals the real or complex numbers).
If $\varphi: V\to V$ is an endomorphism, we know that $\varphi$ can be naturally extended to act as a derivation on $\bigwedge^k V $ for each $1\leq k\leq r$  by $\widetilde\varphi_k\colon \bigwedge^k V \to \bigwedge^k V  $ defined as
$$ \widetilde\varphi_k(v_1\wedge\cdots\wedge v_k):=\sum_{j=1}^k v_1\wedge\cdots\wedge \varphi (v_j)\wedge\cdots\wedge v_k. $$
Now, I want a formal explanation/proof of why does this extension acts as just the scalar multiplication by the trace of $\varphi$ on the top exterior power $\bigwedge^r V \cong  K$. Namely, I want to prove that
$$(*)\qquad\qquad\widetilde\varphi_r(v_1\wedge\cdots\wedge v_r)=\mathrm{tr}(\varphi)v_1\wedge\cdots\wedge v_r  .$$
This has appeared in my path in the context of differential geometry. Namely, if $E$ is a vector bundle of rank $r$ with connection $\nabla$ and curvature form $\Omega$, then it is asserted or implicitely used in several places that the curvature form of the determinant line bundle $\det E:=\bigwedge^r E$ is given by $\widetilde\Omega=\mathrm{tr}(\Omega)$ with respect to the natural connection $\widetilde\nabla$ on $\bigwedge^r E$, namely, the extension of $\nabla$ as a derivation: $\widetilde\nabla(\xi_1\wedge\cdots\wedge \xi_r):=\sum\limits_{j=1}^r \xi_1\wedge\cdots\wedge \nabla \xi_j\wedge\cdots\wedge \xi_r$.
By what we said above, this just amounts to a multilinear algebra problem, that is, $(*)$.
It is also worth noting that the identity $(*)$ is a sister identity of the more well-known identity
$$\bigwedge\nolimits^r \varphi(v_1\wedge\cdots\wedge v_r):= \varphi(v_1)\wedge\cdots\wedge\varphi(v_r)=\det(\varphi)v_1\wedge\cdots\wedge v_r,$$
and that give us a nice overpowered definition of both the determinant and the trace. Any hint or proof is appreciated.

A: Let's choose a basis $(e_1,\dots,e_r)$ for $V$ and write $\varphi(e_i) = \sum_{j=1}^r \varphi_i^j e_j$. Then $\operatorname{tr}(\varphi) = \sum_{j=1}^r \varphi^j_j$ and
$$ \tilde{\varphi}(e_1 \wedge \dots \wedge e_r) = \sum_{j=1}^r e_1 \wedge \dots \wedge e_{j-1} \wedge \varphi(e_j) \wedge e_{j+1} \wedge \dots \wedge e_r = \\
\sum_{j=1}^r e_1 \wedge \dots \wedge e_{j-1} \wedge \varphi_j^k e_k \wedge e_{j+1} \wedge \dots \wedge e_r
= \sum_{j=1}^r \varphi_j^j e_1 \wedge \dots \wedge e_r = \operatorname{tr}(\varphi) e_1 \wedge \dots \wedge e_r $$
where we used the fact that $e_1 \wedge \dots \wedge e_{j-1} \wedge e_k \wedge e_{j+1} \wedge e_r = 0$ unless $k = j$.


text:
Q: Prove that $E[E[Y \mid X] \cdot E[Y \mid Z]] = (E[Y])^2$ if $X$ and $Z$ are independent $X,Y,Z$ are random variables. $Y$ is integrable. $X$ and $Z$ are independent, so the espectation of $X$ doesn't affect the expectation of $Z$.
$\sigma(\cdot)$ is the $\sigma$-algebra generated by the respective random variable. This is my resoning:
$$
\sigma(E[Y\mid X]) \subset \sigma(X)
$$
$$
\sigma(E[Y\mid Z]) \subset \sigma(Z)
$$
Then $\sigma(E[Y\mid X])$ and $\sigma(E[Y\mid Z])$ are independient too:
$$
E(E[Y\mid X]\cdot E[Y\mid Z]) = E(E[Y\mid X])\cdot E(E[Y\mid Z]) = E[Y]\cdot E[Y] = (E[Y])^2
$$
I want to know if I'm right.

A: Your calculations are correct.


text:
Q: How to display city limits using google maps API V3 If I do a search for a city or neighbourhood which google recognizes, like Fernwood, Victoria, I get a pretty map with a drawn boundary. Is there any way to access this kind of information with the google maps API?
I am not looking to draw my own lines on maps, I am looking to make a map showing multiple neighbourhoods with limits on the same map. Bonus points for the ability to style these limits (eg: fill them in like a regular polygon)?

A: I'm pretty sure that this kind of functionality is not supported by the api and works only for google maps.
I had implement this by finding the boundaries that i needed insert them in my postgis db and then send them with json whenever the polygon was within the map viewport.
Hope it helps


text:
Q: Docker Checkpoint/Restore with CRIU - Kernel doesn't support PTRACE_O_SUSPEND_SECCOMP I am attempting to do a hello-world example of docker checkpoint/restore with CRIU (https://criu.org/Docker).
Here is the output from criu check --all
Error (criu/cr-check.c:648): Kernel doesn't support
PTRACE_O_SUSPEND_SECCOMP
Error (criu/cr-check.c:692): Dumping seccomp filters not supported:
Input/output error
Error (criu/cr-check.c:919): cgroupns not supported. This is not fatal.
Looks good but some kernel features are missing
which, depending on your process tree, may cause
dump or restore failure.

I am having trouble when I go to actually create the checkpoint, it does not stop the running container, but says it creates the checkpoint. I assume this is because of the above errors reported with --all. Of course thereafter, when I go to restore, it does not actually restore.
I see multiple kernel patches towards the bottom necessary to support CRIU with Docker. Are these patches supported on RHEL7.4? The best discussion i've found about the kernel patches is here: https://trello.com/c/CqLRhFSk/91-follow-up-on-criu-checkpoint-restart-in-userspace-support-and-test-basic-scenarios-snapshot-restore
My current environment:

*

*RHEL 7.4

*Docker version 17.12.0-ce, build c97c6d6

*Running a centos 7.4 docker image as the base

A: After some digging, I found the following open issues on Moby:

*

*https://github.com/moby/moby/issues/35691

*https://github.com/moby/moby/issues/35690
Downgrading to docker-ce-17.03 fixed the problem.


text:
Q: How add product to cart with Angular and Firestore I manage to fetch the product data through the URL and when I am on the product details page there is a button that allows me to add the product to a sub-collection of the logged in user.
Below is what I want:
users/{userID}/shopping/{productID}
details-product.component.html displaying information in product details

              <button class="uk-modal-close-default" type="button" uk-close></button>

 {{ (product | async)?.name }}

                  {{ (product | async)?.price | currency: 'XOF' }}

              <button class="uk-button uk-button-default uk-form-width-medium" (click)="showDialog()">

                J'achète le produit
              </button>

shopping-cart.service.ts
import { AngularFirestore, AngularFirestoreCollection } from '@angular/fire/compat/firestore';
import "firebase/auth";

import { User } from 'src/app/models/user.model';
import { Product } from 'src/app/models/product.model';

@Injectable({
  providedIn: 'root'
})
export class ShoppingCardService {

  userCollection: AngularFirestoreCollection<User>;
  productsCollection: AngularFirestoreCollection<Product>;

  constructor(private readonly dbstore: AngularFirestore) {
    this.userCollection = this.dbstore.collection('users');
    this.productsCollection = this.dbstore.collection('products');
  }

  addToMyCart(product: Product, userID: string, qteProduct: number) {
    const userDoc = this.dbstore.firestore.collection('users').doc(userID);
    const productDoc = this.dbstore.firestore.collection('products').doc(product.id);
    const userShoppingProduct = userDoc.collection('shopping');
    return userShoppingProduct.doc(product.id).set(product);
  }
}

product.service.ts
import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection } from '@angular/fire/compat/firestore';
import { Router } from '@angular/router';
import { Observable } from 'rxjs';
import { Product } from 'src/app/models/product.model';

@Injectable({
  providedIn: 'root'
})
export class ProductsService {

    productCollection: AngularFirestoreCollection<Product>;

    constructor(private dbstore: AngularFirestore, private router: Router) {
      this.productCollection = this.dbstore.collection('products', (ref) =>
        ref.orderBy('category', 'desc')
      );
    }
    getDetailProduct(productId: string): Observable<any> {
      return this.productCollection.doc(productId).valueChanges();
    }
}

details-product.component.ts

import { ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs/internal/Observable';
import { User } from 'src/app/models/user.model';
import { Product } from 'src/app/models/product.model';
import { ProductsService } from '../../shared/services/products.service';
import { ShoppingCardService } from 'src/app/shared/services/shopping-card.service';
import { AngularFirestoreCollection } from '@angular/fire/compat/firestore';
import { AddToCartComponent } from './add-to-cart.component'
import { MatDialog } from '@angular/material/dialog';

@Component({
  selector: 'app-details-product',
  templateUrl: './details-product.component.html',
  styleUrls: ['./details-product.component.css']
})
export class DetailsProductComponent implements OnInit {

  quantity: number = 0;
  productIdRoute: string;
  isMyProduct: boolean = false;
  product: Observable<Product>;
  userCollection!: AngularFirestoreCollection<User>

  constructor(
    private route: ActivatedRoute,
    private productService: ProductsService,
    private shoppingCardService: ShoppingCardService,
    private titleService: Title,
    private dialog: MatDialog,
  ) {
    const routeParams = this.route.snapshot.paramMap;
    this.productIdRoute = String(routeParams.get('productId'));
    this.product = this.productService.getDetailProduct(this.productIdRoute);
  }

  showDialog(): void {
    const data = this.dialog.open(AddToCartComponent, {
      width: '30rem',
      data: { productID: this.productIdRoute },
    });
    console.log(data);
  }

add-to-cart.component.ts
component in modal to confirm adding to cart
import { Component, OnInit, Inject } from '@angular/core';
import { MatDialog, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { ShoppingCardService } from '../../shared/services/shopping-card.service';
import { Product } from 'src/app/models/product.model';

@Component({
  selector: 'app-add-to-cart',
  template: `

                <svg aria-hidden="true" class="mx-auto mb-4 w-14 h-14 text-gray-400 dark:text-gray-200" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>

Do you want to add this product?

                <button (click)="onAddPubpik(data.product, data.userID)" type="button" class="text-white bg-gray-800 hover:bg-gray-800 focus:ring-4 focus:outline-none font-medium rounded-lg text-sm inline-flex items-center px-5 py-2.5 text-center mr-2">
                   Yes, i add to cart
                </button>

  `,
  styleUrls: ['./details-product.component.css']
})
export class AddToCartComponent implements OnInit {

  constructor(
    @Inject(MAT_DIALOG_DATA) public data: { product: Product, userID: string, qteProduct: number },
    private dialog: MatDialog,
    private shoppingService: ShoppingCardService
  ) {}

  ngOnInit(): void {
  }

  async onAddPubpik(product: Product, userID: string): Promise<void> {
    this.dialog.closeAll();
    const qteProduct = (product.quantity += 1);
    product.isMyProduct = true;
    await this.shoppingService.addToMyCart(product, userID, qteProduct);
  }

}

When i confirm, in console :

A: On this line const qteProduct = (product.quantity += 1);, product is undefined. You're not passing product to the matdialog component in your showDialog() method hence the error.


text:
Q: How to add an event in the device calendar using swift? I would be interested in knowing how to add a calendar event in the device, but using swift. I know there are some examples made in Objective-C, but at the moment nothing in swift. Many thanks.

A: Note: If your app is crashing with This app has crashed because it attempted to access privacy-sensitive data without a usage description.  The app's Info.plist must contain an NSCalendarsUsageDescription key with a string value explaining to the user how the app uses this data., you'll need to add NSCalendarsUsageDescription to your info.plist. Can follow the example here.
Swift 5.0 Version
import Foundation
import EventKit

let eventStore : EKEventStore = EKEventStore()

// 'EKEntityTypeReminder' or 'EKEntityTypeEvent'

eventStore.requestAccess(to: .event) { (granted, error) in

  if (granted) && (error == nil) {
      print("granted \(granted)")
      print("error \(error)")

      let event:EKEvent = EKEvent(eventStore: eventStore)

      event.title = "Test Title"
      event.startDate = Date()
      event.endDate = Date()
      event.notes = "This is a note"
      event.calendar = eventStore.defaultCalendarForNewEvents
      do {
          try eventStore.save(event, span: .thisEvent)
      } catch let error as NSError {
          print("failed to save event with error : \(error)")
      }
      print("Saved Event")
  }
  else{

      print("failed to save event with error : \(error) or access not granted")
  }
}

Reference : https://gist.github.com/mchirico/d072c4e38bda61040f91

A: Swift 3.0 compatible:
func addEventToCalendar(title: String, description: String?, startDate: Date, endDate: Date, completion: ((_ success: Bool, _ error: NSError?) -> Void)? = nil) {
    let eventStore = EKEventStore()

    eventStore.requestAccess(to: .event, completion: { (granted, error) in
        if (granted) && (error == nil) {
            let event = EKEvent(eventStore: eventStore)
            event.title = title
            event.startDate = startDate
            event.endDate = endDate
            event.notes = description
            event.calendar = eventStore.defaultCalendarForNewEvents
            do {
                try eventStore.save(event, span: .thisEvent)
            } catch let e as NSError {
                completion?(false, e)
                return
            }
            completion?(true, nil)
        } else {
            completion?(false, error as NSError?)
        }
    })
}

And also import EventKit
So you can easily call this method from everywhere:
addEventToCalendar(title: "Girlfriend birthday", description: "Remember or die!", startDate: NSDate(), endDate: NSDate())

If you prefer, you can put this method inside an utiliy class and define it as 'static'.

A: I was able to adjust this and eliminate the compiler error mentioned in the comments to the answers above (and a few others), as follows:
 var eventStore : EKEventStore = EKEventStore()

    // 'EKEntityTypeReminder' or 'EKEntityTypeEvent'

    eventStore.requestAccessToEntityType(EKEntityType.Event, completion: {
        (granted, error) in

        if (granted) && (error == nil) {
            print("granted \(granted)")
            print("error \(error)")

            var event:EKEvent = EKEvent(eventStore: eventStore)

            event.title = "Test Title"
            event.startDate = NSDate()
            event.endDate = NSDate()
            event.notes = "This is a note"
            event.calendar = eventStore.defaultCalendarForNewEvents

            eventStore.saveEvent(event, span: EKSpan.ThisEvent, error: nil)

            print("Saved Event")
        }
    })

However, I still get the following error at the bottom regarding "EKSpan.ThisEvent" : Incorrect argument label in call (have ':span:error:', expected ':span:commit:').
I tried changing "error" to "commit," but it gave me a compiler error saying it expected a Bool instead of nil. It seems like a problem having to do with updates in swift syntax.
Edit: I ended up following this tutorial and was able to get it to work.

*

*First, ask permission to access the calendar and (if that permission is granted) call a function to add the event.
var savedEventId : String = ""

func requestAccessPermission() {
    let eventStore = EKEventStore()

    let startDate = NSDate()
    let endDate = startDate.dateByAddingTimeInterval(60 * 60) // Ends one hour later

    if (EKEventStore.authorizationStatusForEntityType(.Event) != EKAuthorizationStatus.Authorized) {
        eventStore.requestAccessToEntityType(.Event, completion: {
        granted, error in
            self.createEvent(eventStore, title: "Test Title", startDate: startDate, endDate: endDate)
        })
    } else {
        createEvent(eventStore, title: "Test Title", startDate: startDate, endDate: endDate)
    }
}

*The function that is called in the above code snippet to add the event:
func createEvent(eventStore: EKEventStore, title: String, startDate: NSDate, endDate: NSDate) {
    let event = EKEvent(eventStore: eventStore)
    event.title = title
    event.startDate = startDate
    event.endDate = endDate
    event.calendar = eventStore.defaultCalendarForNewEvents
    do {
        try eventStore.saveEvent(event, span: .ThisEvent)
        savedEventId = event.eventIdentifier
    } catch {
        print("Error Saving")
    }
}

A: This was really slow on iOS 11.2 Xcode 9.2, so I modified Luca Davanzo's  answer to use queues (works a lot faster):
func addEventToCalendar(title: String, description: String?, startDate: Date, endDate: Date, completion: ((_ success: Bool, _ error: NSError?) -> Void)? = nil) {
        DispatchQueue.global(qos: .background).async { () -> Void in
            let eventStore = EKEventStore()

            eventStore.requestAccess(to: .event, completion: { (granted, error) in
                if (granted) && (error == nil) {
                    let event = EKEvent(eventStore: eventStore)
                    event.title = title
                    event.startDate = startDate
                    event.endDate = endDate
                    event.notes = description
                    event.calendar = eventStore.defaultCalendarForNewEvents
                    do {
                        try eventStore.save(event, span: .thisEvent)
                    } catch let e as NSError {
                        completion?(false, e)
                        return
                    }
                    completion?(true, nil)
                } else {
                    completion?(false, error as NSError?)
                }
            })
        }
    }

A: You need to add "Privacy - Calendars Usage Description" to info.plist.
Following code works with latest version of xcode and swift 3.
import EventKit
class EventHelper
{
    let appleEventStore = EKEventStore()
    var calendars: [EKCalendar]?
    func generateEvent() {
        let status = EKEventStore.authorizationStatus(for: EKEntityType.event)

        switch (status)
        {
        case EKAuthorizationStatus.notDetermined:
            // This happens on first-run
            requestAccessToCalendar()
        case EKAuthorizationStatus.authorized:
            // User has access
            print("User has access to calendar")
            self.addAppleEvents()
        case EKAuthorizationStatus.restricted, EKAuthorizationStatus.denied:
            // We need to help them give us permission
            noPermission()
        }
    }
    func noPermission()
    {
        print("User has to change settings...goto settings to view access")
    }
    func requestAccessToCalendar() {
        appleEventStore.requestAccess(to: .event, completion: { (granted, error) in
            if (granted) && (error == nil) {
                DispatchQueue.main.async {
                    print("User has access to calendar")
                    self.addAppleEvents()
                }
            } else {
                DispatchQueue.main.async{
                    self.noPermission()
                }
            }
        })
    }
    func addAppleEvents()
    {
        let event:EKEvent = EKEvent(eventStore: appleEventStore)
        event.title = "Test Event"
        event.startDate = NSDate() as Date
        event.endDate = NSDate() as Date
        event.notes = "This is a note"
        event.calendar = appleEventStore.defaultCalendarForNewEvents

        do {
            try appleEventStore.save(event, span: .thisEvent)
            print("events added with dates:")
        } catch let e as NSError {
            print(e.description)
            return
        }
        print("Saved Event")
    }
}

A: same with location and alert
   func addEventToCalendar(title: String, description: String?, startDate: Date, endDate: Date, location: String?, completion: ((_ success: Bool, _ error: NSError?) -> Void)? = nil) {
    DispatchQueue.global(qos: .background).async { () -> Void in
        let eventStore = EKEventStore()

        eventStore.requestAccess(to: .event, completion: { (granted, error) in
            if (granted) && (error == nil) {
                let alarm = EKAlarm(relativeOffset: -3600.0)
                let event = EKEvent(eventStore: eventStore)
                event.title = title
                event.startDate = startDate
                event.endDate = endDate
                event.notes = description
                event.alarms = [alarm]
                event.location = location
                event.calendar = eventStore.defaultCalendarForNewEvents
                do {
                    try eventStore.save(event, span: .thisEvent)
                } catch let e as NSError {
                    completion?(false, e)
                    print ("\(#file) - \(#function) error: \(e.localizedDescription)")
                    return
                }
                completion?(true, nil)
            } else {
                completion?(false, error as NSError?)
                print ("\(#file) - \(#function) error: \(error)")
            }
        })
    }
}

A: Async/await without completion handlers:
func addCalendarEvent(eventTitle: String, startDate: Date, endDate: Date) {
    Task {
        do {
            let eventStore = EKEventStore()
            let requestResult: Bool = try await eventStore.requestAccess(to: .event)
            guard requestResult else {
                debugPrint("Couldn't not create a calendar event. Calendar access denied.")
                return
            }
            let event = EKEvent(eventStore: eventStore)
            event.title = eventTitle
            event.startDate = startDate
            event.endDate = endDate
            event.calendar = eventStore.defaultCalendarForNewEvents
            try eventStore.save(event, span: .thisEvent)
        } catch {
            debugPrint("Couldn't not create a calendar event. Error: \(error.localizedDescription)")
            return
        }
    }
}


text:
Q: Prior for the regression coefficients in the logistic regression I'm trying to model Bayesian logistic regression model with my dependent variable (status: 0=alive, 1 death) & independent variable (age) in the categorical form (0=patients < 65 yrs old, 1=patients >=65 yrs old). I'm using normal dist. as a prior for constant term, b0 and Dirichlet dist. as the prior for the regression coefficient,b1. However, i got the error of incorrect number of parameters in distribution ddirch. Am i using the correct prior for b1? or should i just assigned normal prior for it? Below are the codes i used:
# Bayesian logistic model for JAGS #
bayes.mod<-function(){
    for( i in 1 : N ) {
        status[i] ~ dbern(mu[i])
        mu[i]<-1/(1+exp(-(b0 + b1*age[i] )))
    }
    # Prior on constant term, b0
    b0 ~ dnorm(0, 1.0E-4)
    # Prior on regression coefficient, b1
    b1 ~ ddirch(1,1)
}

A: The Dirchlet distribution describes a random vector of multiple components.  In your case, the random parameter $\beta_1$ is a random varaible (i.e. a numeric valued random quantity).  So you want to use a prior distribution that describes a random variable, the normal is one option.


text:
Q: How to center align the title in a JFrame? I have a JFrame with a Title. I want center align the title, so that it appears in the middle of the JFrame's title.
Thanks.

A: Adapting the answer's source of @Java42, I did a "workaround" to adjust title when resizing JFrame:
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;

import javax.swing.JFrame;

public class JFrameTitleCenter {

    public void createAndShowGUI() {

        JFrame frame = new JFrame();
        frame.setPreferredSize(new Dimension(300, 200));
        frame.setTitle("Hello Center");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.addComponentListener(new ComponentAdapter() {
            @Override
            public void componentResized(ComponentEvent e) {
                titleAlign(frame);
            }

        });

        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

    }

    private void titleAlign(JFrame frame) {

        Font font = frame.getFont();

        String currentTitle = frame.getTitle().trim();
        FontMetrics fm = frame.getFontMetrics(font);
        int frameWidth = frame.getWidth();
        int titleWidth = fm.stringWidth(currentTitle);
        int spaceWidth = fm.stringWidth(" ");
        int centerPos = (frameWidth / 2) - (titleWidth / 2);
        int spaceCount = centerPos / spaceWidth;
        String pad = "";
        pad = String.format("%" + (spaceCount - 14) + "s", pad);
        frame.setTitle(pad + currentTitle);

    }

    public static void main(String[] args) {

        EventQueue.invokeLater(() -> {
            new JFrameTitleCenter().createAndShowGUI();
        });
    }
}

Working:

A: I have a JFrame with a Title. I want center align the title, so that
it appears in the middle of the JFrame's title.

simple not possible to centering narrarive in the JFrames TitleBar, this container came from Native OS

*

*dirty hack are possible by implements getSystemLookAndFeel in Windows OS

*create undecorated JFrame by adding JPanel (simulated Toolbar) with JButtons (JButtons with icons simulating standards buttons )

A: Consider leaving the title left-justified...but...this will get you near the center.  For resizable frames, you need to rewrite the title on resize.
JFrame t = new JFrame();
t.setSize(600,300);
t.setFont(new Font("System", Font.PLAIN, 14));
Font f = t.getFont();
FontMetrics fm = t.getFontMetrics(f);
int x = fm.stringWidth("Hello Center");
int y = fm.stringWidth(" ");
int z = t.getWidth()/2 - (x/2);
int w = z/y;
String pad ="";
//for (int i=0; i!=w; i++) pad +=" ";
pad = String.format("%"+w+"s", pad);
t.setTitle(pad+"Hello Center");

A: I don't know that you can without using a complicated scheme. If it's to your liking, you could apply a titled border with centered text to the frame's content pane.

A: center align the title in a jFrame is very easy in netbeans, what u need to do is below:
1.

2.

*run your app.


text:
Q: Cost and Power of EEPROM and Flash? I am working on a project which requires low power persistent storage. It needs to store 1 kB of data at most. The data is organized in blocks logically. So, a update of one block requires 100 B to be written to storage.
The project will be powered from a coin cell so it needs to be power efficient.
Low endurance of flash is not a problem. The deciding factor for my project is power, cost and write speed.
25LC640 EEPROM datasheet at http://ww1.microchip.com/downloads/en/DeviceDoc/21223H.pdf states that it needs up to 5 ms to write a single byte. So, to update my logical block, it would require 500 ms. This is the problem for my project.
I need to decide whether to use flash or EEPROM and deciding factors are cost, power and write speed.
Please help by telling me typical write speed, cost and power of flash and EEPROM of approx. size 1 kilo bytes.

Edit-1 :
I understand that they will be trade-offs.
All I want from this community is to share their design experience with me. I am not asking for a particular product. I am looking for typical figures for cost, power and write speed.

Edit 2:
My project is a BLE device. It needs to store bonding information, service context, application context and other information persistently. I am implementing a very simple filesystem and each information can be stored in a file. The problem with larger write cycle is that i can't write data instantaneously and i have to queue the request to store the data persistently. It may lead to inconsistent state in my device. Again, i can solve it by making my firmware smart enough but i want to look for other alternatives from the community.

A: FeRAM (F-RAM, FRAM) is probably the lowest power writable non-volatile storage around. It can be rewritten without having to worry about limited numbers of writes and it is very fast (read and write.) And with only a need of 1 kB total, it's the way I'd lean for coin cell use. You can either select from Cypress or TI for inexpensive parts that are generally available. TI includes MSP430-based microcontrollers which include enough for your use, too. You'll spend about $1 for a Cypress part (memory only) and you'll spend about about the same to get the memory with a TI MSP430 microcontroller added in, too.
(There is also MRAM, but it is very expensive and only available in small quantities and hard to find, besides. I'd avoid it for now.)

A: Other way round: you find a part supplier (e.g. digikey) and then use parametric search to find a suitable part. You should be able to get much faster than 500ms, more like 0.1ms. Consider also FRAM.
Random example: http://www.digikey.co.uk/product-detail/en/fremont-micro-devices-usa/FT25H04S-RT/1219-1190-2-ND/5875675


text:
Q: How can I modify and transpose a messy dataset? I plan to transform my dataset from the one shown on left to right:
I am still learning how to use R for analysis, so would be really appreciated if anyone knows how to do that in R :)

A: There is a good functionality available in data.table package in R
dcast(table, Test ~ Column1, value.var = "Preference")

You can check the functionality of the function
here.
There is also option to return back to the initial long version of the table using melt function.

A: pivot_wider from the tidyr package should do the trick
library(tidyverse)

foo <- tibble(
  ID = paste0('Female00', c(1, 1, 1, 2, 2, 3, 3, 3, 4, 5, 5, 5, 6)),
  Test = c('Food', 'Beverage', 'Color', 'Beverage', 'Food', 'Color', 'Food', 'Beverage', 'Food', 'Beverage', 'Color', 'Food', 'Color'),
  Preference = c('Strong', 'Strong', 'Medium', 'Low', 'Medium', 'Medium', 'Strong', 'Low', 'Low', 'Strong', 'Low', 'Medium', 'Medium')
)

foo %>%
  pivot_wider(
    names_from = ID,
    values_from = Preference,
    values_fill = NA
  )

A: It is just a matter of transposing the data frame :
df
         Id     Test Preference
1 Female001     Food     Strong
2 Female001 Beverage     Strong
3 Female001    Color     Medium
4 Female002     Food     Medium
5 Female002 Beverage        Low
6 Female003    Color     Medium
7 Female003     Food     Strong
8 Female003 Beverage        Low
> library(tidyr)
> df %>% spread(Id,Preference)
      Test Female001 Female002 Female003
1 Beverage    Strong       Low       Low
2    Color    Medium      <NA>    Medium
3     Food    Strong    Medium    Strong


text:
Q: Check my proof that right-sided limit doesn't exist here Let $f:\mathbb{R^*} - >\mathbb{R}, f(x) =\sin (\frac{1+x}{\sqrt x}) $. Prove that $\lim_{x \to 0^+} f(x) $ doesn't exist.
My solution : Since $f$ is continuous, we have
$\lim_{x \to 0^+} f(x)=f(\lim_{x\to 0^+} (\frac{1+x}{\sqrt x}))=lim_{x\to \infty} f(x) $
However, the last limit doesn't exist and hence the result.

A: We have that
$$\frac{1+x}{\sqrt x} \to \infty$$
then the limit doesn't exist, to prove that we can consider

*

*$x_n=\frac1{(2\pi n)^2}\to 0^+\implies \frac{1+x_n}{\sqrt x_n}\sim2\pi n\to \infty \implies \sin (\frac{1+x_n}{\sqrt x_n})\to 0$

*$x_n=\frac1{(\pi/2+2\pi n)^2}\to 0^+\implies \frac{1+x_n}{\sqrt x_n}\sim \frac{\pi}2+2\pi n\to \infty \implies \sin (\frac{1+x_n}{\sqrt x_n})\to 1$


text:
Q: installing components of the single unit type My question is how to use unit components like following in our projects.
I installed the following component but i cant to use it anymore.
All of things that i do is : 1- create a package 2- add unit to package 3- with right click on package name in its palette i choose build and after that in the next step i install that 4- next i go to component menu and i choose install component and than by choosing unit and exist package in the next page i add package name and click on finish.
It sounds that all of things is good but i cant able to call that and it not appears in tool pallete after installing.
Basically i always have problem with installing and using components like this...
 unit U_Usb;

 interface

uses
Windows, Messages, SysUtils, Classes, Forms;

type

PDevBroadcastHdr = ^DEV_BROADCAST_HDR;
DEV_BROADCAST_HDR = packed record
dbch_size: DWORD;
dbch_devicetype: DWORD;
dbch_reserved: DWORD;
end;

PDevBroadcastDeviceInterface = ^DEV_BROADCAST_DEVICEINTERFACE;
 DEV_BROADCAST_DEVICEINTERFACE = record
 dbcc_size: DWORD;
 dbcc_devicetype: DWORD;
 dbcc_reserved: DWORD;
  dbcc_classguid: TGUID;
  dbcc_name: short;
 end;

const
  GUID_DEVINTERFACE_USB_DEVICE: TGUID = '{A5DCBF10-6530-11D2-901F-00C04FB951ED}';
  DBT_DEVICEARRIVAL = $8000; // system detected a new device
  DBT_DEVICEREMOVECOMPLETE = $8004; // device is gone
  DBT_DEVTYP_DEVICEINTERFACE = $00000005; // device interface class

type

 TComponentUSB = class(TComponent)
   private
   FWindowHandle: HWND;
   FOnUSBArrival: TNotifyEvent;
   FOnUSBRemove: TNotifyEvent;
   procedure WndProc(var Msg: TMessage);
   function USBRegister: Boolean;
   protected
   procedure WMDeviceChange(var Msg: TMessage); dynamic;
  public
  constructor Create(AOwner: TComponent); override;
  destructor Destroy; override;
  published
    property OnUSBArrival: TNotifyEvent read FOnUSBArrival write FOnUSBArrival;
    property OnUSBRemove: TNotifyEvent read FOnUSBRemove write FOnUSBRemove;
  end;

  implementation

constructor TComponentUSB.Create(AOwner: TComponent);
   begin
     inherited Create(AOwner);
     FWindowHandle := AllocateHWnd(WndProc);
     USBRegister;
   end;

   destructor TComponentUSB.Destroy;
    begin
   DeallocateHWnd(FWindowHandle);
    inherited Destroy;
   end;

 procedure TComponentUSB.WndProc(var Msg: TMessage);
     begin
     if (Msg.Msg = WM_DEVICECHANGE) then
      begin
      try
      WMDeviceChange(Msg);
    except
  Application.HandleException(Self);
   end;
   end
  else
     Msg.Result := DefWindowProc(FWindowHandle, Msg.Msg, Msg.wParam, Msg.lParam);
   end;

  procedure TComponentUSB.WMDeviceChange(var Msg: TMessage);
   var
   devType: Integer;
     Datos: PDevBroadcastHdr;
   begin
    if (Msg.wParam = DBT_DEVICEARRIVAL) or (Msg.wParam = DBT_DEVICEREMOVECOMPLETE) then
    begin
  Datos := PDevBroadcastHdr(Msg.lParam);
    devType := Datos^.dbch_devicetype;
     if devType = DBT_DEVTYP_DEVICEINTERFACE then
    begin // USB Device
     if Msg.wParam = DBT_DEVICEARRIVAL then
     begin
      if Assigned(FOnUSBArrival) then
       FOnUSBArrival(Self);
       end
        else
      begin
     if Assigned(FOnUSBRemove) then
      FOnUSBRemove(Self);
   end;
  end;
   end;
  end;

  function TComponentUSB.USBRegister: Boolean;
    var
      dbi: DEV_BROADCAST_DEVICEINTERFACE;
       Size: Integer;
     r: Pointer;
      begin
     Result := False;
     Size := SizeOf(DEV_BROADCAST_DEVICEINTERFACE);
      ZeroMemory(@dbi, Size);
      dbi.dbcc_size := Size;
      dbi.dbcc_devicetype := DBT_DEVTYP_DEVICEINTERFACE;
     dbi.dbcc_reserved := 0;
     dbi.dbcc_classguid := GUID_DEVINTERFACE_USB_DEVICE;
     dbi.dbcc_name := 0;

     r := RegisterDeviceNotification(FWindowHandle, @dbi,
      DEVICE_NOTIFY_WINDOW_HANDLE
     );
      if Assigned(r) then Result := True;
    end;

    end.

A: The unit you have does not have a Register procedure. This is a requirement to be able to install components into the IDE.
When you install a package, any unit where a Register procedure is found in the interface will call this Register procedure when the package is "installed". Within there, you then call RegisterComponents to actually install the component(s) into the IDE.
It should look something like this:
...

procedure Register;

implementation

procedure Register;
begin
  RegisterComponents('My Components', [TComponentUSB]);
end;

...

Keep in mind that the Register procedure doesn't necessarily need to be in the same unit. Normal design of packages with many components is to have a single unit in the design-time package which has the only Register procedure. The rest of the units with the actual components would then presumably be part of a separate run-time package which the design-time package requires.
Also, you can have many components in a single unit. Only those which are in your call to RegisterComponents will be installed into your IDE.
Don't forget to also include the location of this unit in the Library Path of your IDE.


text:
Q: Firefox 6 :Problem with QueryInterface(nsIDOMWindow::GetIID() in XPCOM component, for browser content window passed from js I am working on adding support for Firefox 6 for my add-on on Mac OS, where the following logic is working in Firefox 4,5 versions but fails in Firefox 6.
XPCOM component has subclass of IObserverClient and which adds itself as observer for a custom event.
This custom event is posted from browser overlay.js  passing the selected browser's content window.
var observerService = Components.classes["@mozilla.org/observer-service;1"]
                                .getService(Components.interfaces.nsIObserverService);
if (observerService) {
    var data =  gBrowser.selectedBrowser.contentWindow.location.href;

    observerService.notifyObservers(gBrowser.selectedBrowser.contentWindow, JSEventTopic, data);
}

In XPCOM components handler, trying to get the nsIDOMWindow interface from nsISupports
void XXX::Observe(nsISupports *aSubject, const char *aTopic, const PRUnichar *aData)
{
    nsCOMPtr<nsIDOMWindow> pWin;
    aSubject->QueryInterface(nsIDOMWindow::GetIID(), getter_AddRefs(pWin));
}

The problem is, with Firefox 6 pWin is nil. In Firefox 4 and 5 pWin is as expected and not nil.

A: The immediate problem seems to be that whatever object is being delivered as aSubject doesn't implement the nsIDOMWindow interface, which naturally causes the QueryInterface to fail and yield null. You can't QI an object to an interface that it doesn't implement, and you can't QI null to anything.
I don't know off-hand what causred this change, but here are a few things to check that might help you find the real problem:

*

*Make sure the subject you're receiving isn't null, and that the pointer you're trying to QI is the argument received by the listener method.

*In your JavaScript code, check that the window object you're passing isn't nil, and is actually something that should implement nsIDOMWindow.

*Check that aTopic contains the value you expect, and not some other event string.

A: I am not much familiar with add-on development.  But this works for me in my application(C++).
nsCOMPtr<nsIDOMWindow> domWindow;
nsresult rv = mWebBrowser->GetContentDOMWindow(getter_AddRefs(domWindow));

nsCOMPtr<nsIDOMWindowUtils> windowUtils(do_GetInterface(domWindow));


text:
Q: Conditional Go Routine/Channel I would like to make the statistics routine conditional so that it only runs on certain cases otherwise it will waste cycles half the time. Right now I have one go routine act as a producer to feed the two consumer routines via buffered channels. Is there a way I can make it so the statistics routine is conditional or is there a better pattern I should follow? Thanks in advance for any and all help!
func main() {
    options()
    go produce(readCSV(loc))
    go process()
    go statistics() // only on flag
    <-done
}

func produce(entries [][]string) {
    regex, err := regexp.Compile(reg)
    if err != nil {
        log.Error(reg + ", is not a valid regular expression")
    } else {
        for _, each := range entries {
            if regex.MatchString(each[col]) {
                matches <- each
                stats <- each // only on flag
            }
        }
    }
    done <- true
}

func process() {
    for {
        match := <-matches
        if len(match) != 0 {
            // PROCESS
        }
    }
}

func statistics() {
    for {
        stat := <-stats
        if len(stat) != 0 {
            // STATISTICS
        }
    }
}

A: There is nothing wrong with making this conditional:
var stats chan []string  // Don't initialize stats.

func main() {
    options()
    go produce(readCSV(loc))
    go process()
    if flag {
        stats = make(chan []string, 1024)
        go statistics() // only on flag
    }
    <-done
}

func produce(entries [][]string) {
    regex, err := regexp.Compile(reg)
    if err != nil {
        log.Error(reg + ", is not a valid regular expression")
    } else {
        for _, each := range entries {
            if regex.MatchString(each[col]) {
                matches <- each
                if stats != nil {
                    stats <- each // only on flag
                }
            }
        }
    }
    close(done)
}

func process() {
    for {
        select {
        case match := <-matches:
            if len(match) != 0 {
              // PROCESS
            }
        case <-done:
            return
        }
    }
}

func statistics() {
    for {
        select {
        case stat := <-stats:
            if len(stat) != 0 {
                // STATISTICS
            }
        case <-done:
            return
        }
    }
}

A: Perhaps you're looking for the flag package.
import "flag"

var withStats = flag.Boolean("s", false, "Do statistics")

func main() {
    flag.Parse()
    ...
    if *withStats == true {
        t := statType
        size := 100
        stats := make(chan, t, size)
        go statistics() // only on flag
    }
    ...
}

A: If you update statistics from many places in your code you might want to add some helper methods. Something like:
type stats struct {
    ch chan []string
}

func (s *stats) update(a []string) {
    if s != nil {
        s.ch <- a
    }
}

func (s *stats) start() {
    if s != nil {
        s.ch = make(chan []string)
        go statistics()
    }
}

var s *stats
if enabled {
    s = new(stats)
}
s.start()

// later in the code
s.update(each)


text:
Q: alternative of jbrowse on centos Is there an alternative Software of JBrowse (on Centos6).
I need to integrate one into my webpage, but jbrowse is giving error of zlib while installing PerlIO::gzip. Although all related modules (libpng,libpng-devel,gd-devel,zlib-devel,perl-ExtUtils-MakeMaker,Development Tools, perl-Compress-Zlib) are installed.
Any suggestion will be helpful.
An alternative for windows8 os will also work.

A: Note that there is a mailing list cross link for the JBrowse issue here here https://sourceforge.net/p/gmod/mailman/message/36349221/
Alternatives to JBrowse could include igv.js, pileup.js, genomeview, or other HTML5 genome browsers
Also note, if we take the stance that Perl pre-requisites really are impossible to install on your system, then we can take an alternative approach because JBrowse does not actually require Perl pre-requisites to be installed for operation. Modern JBrowse can load native file formats without using the Perl scripts for conversion.
In this case, you can simply create file directory like
data/genome.fa
data/genome.fa.fai
data/tracks.conf
data/annotations.sorted.gff.gz
data/annotations.sorted.gff.gz.tbi

where genome.fa.fai is generated by samtools faidx genome.fa and annotations.sorted.gff.gz is generated by sort -k1,1 -k4,4n annotations.gff > annotations.sorted.gff and then bgzip annotations.sorted.gff.gz and finally tabix -p vcf annotations.sorted.gff.gz
Then the tracks.conf file can contain
[GENERAL]
refSeqs=genome.fa.fai

[tracks.refseq]
urlTemplate=genome.fa
storeClass=JBrowse/Store/SeqFeature/IndexedFasta
type=Sequence
[tracks.annotations]
urlTemplate=annotations.sorted.gz
type=CanvasFeatures
storeClass=JBrowse/Store/SeqFeature/GFF3Tabix

In this sense, your browser can be fully created without perl pre-requisites


text:
Q: ios http request sending json format I am trying to call a web service with these parameters:
{"Class":"Authorization","method":"login","user":"","pass":""}

as follows
NSString *user = [NSString stringWithFormat:@"username=%@",_username.text];
NSString *pass = [NSString stringWithFormat:@"password=%@",_password.text];
NSString *Class = @"Authorization";
NSString *method = @"login";

//NSString *post = [NSString stringWithFormat:@"%@&%@&%@&%@", user, pass, Class, method ];

NSString *jsonPostBody = [NSString stringWithFormat:@"'json' = '{\"Class\":"
                              "\"%@\""
                              ",\"method\":"
                              "\"%@\""
                              ",\"pass\":"
                              "\"%@\""
                              ",\"user\":"
                              "\"%@\""
                              "}'",
                              [Class stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
                              [method stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
                              [pass stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
                              [user stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSData *postData = [jsonPostBody dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];

    NSURL *url = [NSURL URLWithString:@"http://212.119.87.45:8080/IktissabServices/index.php/service"];
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url
                                                           cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                       timeoutInterval:180.0];

    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/x-www-form-urlencoded"   forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:[[jsonPostBody stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]
                          dataUsingEncoding:NSUTF8StringEncoding
                          allowLossyConversion:YES]];

    [request setHTTPBody:postData];

    NSString* postDataLengthString = [[NSString alloc] initWithFormat:@"%d", [postData length]];
    [request setValue:postDataLengthString forHTTPHeaderField:@"Content-Length"];

    NSURLResponse *response;
    NSError *err;
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
    NSError *error;
    NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error];//
    if (! error) {
        NSLog(@"%@",jsonDict);
    }else{
        NSLog(@"%@",error.localizedDescription);
    }

Every time the result is:

Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: 'data parameter is nil'

The web service has:

input-content-type: text/json
output-content-type: text/json

Any help or examples will be appreciated.

A: I'm not getting any exception with the following code (though obviously I don't have access to your server, so I can't test it end-to-end):
NSDictionary *dictionary = @{
    @"Class"  : @"Authorization",
    @"method" : @"login",
    @"pass"   : _password.text,
    @"user"   : _username.text
};

NSError *error;
NSData *postData = [NSJSONSerialization dataWithJSONObject:dictionary
                                                   options:0
                                                     error:&error];
if (error)
    NSLog(@"Failure to serialize JSON object %@", error);

NSURL *url = [NSURL URLWithString:@"http://212.119.87.45:8080/IktissabServices/index.php/service"];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url
                                                       cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                   timeoutInterval:180.0];

[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

NSURLResponse *response;

NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (error)
    NSLog(@"%s sendSynchronousRequest error %@", __FUNCTION__, error);

NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error];//
if (!error) {
    NSLog(@"%@",jsonDict);
} else {
    NSLog(@"%s JSONObjectWithData error %@", __FUNCTION__, error);
}

Or, if you're not using the latest Xcode and don't have access to the Modern Objective C definition of the dictionary, you could obviously define your dictionary the traditional way:
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                            @"Authorization", @"Class",
                            @"login",         @"method",
                            _password.text,   @"pass",
                            _username.text,   @"user",
                            nil];

Edit:
Inferring from your jsonPostBody, the dictionary entry might need to be:
NSDictionary *dictionary = @{
    @"json" : @{
        @"Class"  : @"Authorization",
        @"method" : @"login",
        @"pass"   : _password.text,
        @"user"   : _username.text
    }
};

or possibly (though, even less likely), inferring from your user and pass definitions:
NSDictionary *dictionary = @{
    @"json" : @{
        @"Class"  : @"Authorization",
        @"method" : @"login",
        @"pass"   : [NSString stringWithFormat:@"password=%@",_password.text],
        @"user"   : [NSString stringWithFormat:@"username=%@",_username.text]
    }
};

It's a question of how the JSON needs to be formatted for your server.


text:
Q: Thread.interrupt is not called when using ExecutorService I need MyThread.interrupt() to be called when I cancel currently executing task. Why isn't itpublic class Main {
public static void main(String[] args) {
    ExecutorService executor = Executors.newFixedThreadPool(10);
    List<MyThread> threads = new ArrayList<Main.MyThread>();

    List<Future> futureList = new ArrayList<Future>();
    for (int i = 0; i < 30; i++) {
        MyThread myThread = new MyThread(i);
        futureList.add(executor.submit(myThread));
        threads.add(myThread);
    }
    for (Future future : futureList) {
        if (future != null) {
            future.cancel(true);
        }
    }

    // Calling interrupt directly. It works
    for (MyThread myThread : threads) {
        myThread.interrupt();
    }
    shutdownAndAwaitTermination(executor);

}

static void shutdownAndAwaitTermination(ExecutorService pool) {
    pool.shutdown(); // Disable new tasks from being submitted
    try {
        // Wait a while for existing tasks to terminate
        if (!pool.awaitTermination(10, TimeUnit.SECONDS)) {
            pool.shutdownNow(); // Cancel currently executing tasks
            // Wait a while for tasks to respond to being cancelled
            if (!pool.awaitTermination(10, TimeUnit.SECONDS)) System.err.println("Pool did not terminate");
            else System.out.println("Maybe OK");
        } else {
            System.out.println("OK");
        }
    } catch (InterruptedException ie) {
        // (Re-)Cancel if current thread also interrupted
        pool.shutdownNow();
        // Preserve interrupt status
        Thread.currentThread().interrupt();
    }
}

private static class MyThread extends Thread {

    HttpURLConnection connection;

    final int i;

    public MyThread(int i) {
        this.i = i;
    }

    @Override
    public void interrupt() {
        super.interrupt();
        if (connection != null) {
            connection.disconnect();
        }
    }

    @Override
    public void run() {
        // Initialize HttpURLConnection and upload / download data
    }

}

}

A: It is called, change it here and see output
...
            } catch (InterruptedException e) {
                System.out.println(i + " interrupted");
                Thread.currentThread().interrupt();
            }
...

the problem is that ThreadPoolExecutor uses its own Thread to run your task and it will interrupt this thread not yours. It makes no sense to extend Thread, implement Runnable instead. If you still to use Thread then you can call MyThread.interrupt() directly from MyThread.run()

A: executor.submit(new MyThread(i)) works because MyThread extends Thread which implements Runnable.
As such, the run method is actually executed by one of the 10 threads your started in the thread pool. When cancelling the Future, the interrupt method of MyThread is not executed as it is not the executing thread but considered a Runnable. Nevertheless, The interrupt of the threads started by your pool is called.


text:
Q: Exchange 2007 - Message Tracking Logs - Undelivered Email I am administering an Exchange 2007 server with around 15user mailboxes.
One user is having trouble receiving emails from an email address outside the organisation.
I've run the message tracking tool with EVENTID as 'Receive' and can see this particular sender email address  in the results.
If i run the same tracking search with EVENTID as 'DELIVER' - The emails do not show up.Therefore I can see the email is getting to the exchange server, but NOT delivering to the mailbox.
I've heard I should disable IPV6 if its not in use as this can cause problems, is there any truth to that?

A: For such a small number of users, I'd probably run the message tracking around the time the message was sent and see all the activity around that message and not just the RECEIVE and DELIVER events. If it's not being delivered to the mailbox, you might see some deferred messages or NDRs going back. You might also have some odd configuration issue which results in Exchange not thinking this message is for any of your users and forwarding it on to another SMTP server.
My initial reaction would be to check the user is not over quota. If that's no good I'd have a look at transport rules to see if you've got something crazy which bounces particular messages, or maybe the built in anti-spam agents are rejecting the message.
As for disabling IPv6, I really wouldn't do that. TechNet says there's no need to disable it, and I really can't think of any reason to ever disable it these days.

Exchange servers fully support IPv6 networks, and there is no need to disable IPv6 on your Exchange servers.


text:
Q: R: using factor variables in nlme function library(nlme)
model <- nlme(height ~ (R0) + 1,
              data = Loblolly,
              fixed = list(R0 ~ 1),
              random = list(Seed = pdDiag(list(R0 ~ 1))),
              start = list(fixed = c(R0 = -8.5)))

Here is a simple model with just 1 fixed effect parameter. This model fits fine, but when I wanted to introduce a factor level covariate (i.e. age), I ran into the following error.
Loblolly$age2 <- as.factor(ifelse(Loblolly$age < 12.5, 0, 1))
model2 <- nlme(height ~ (R0 + age2) + 1,
              data = Loblolly,
              fixed = list(R0 ~ 1 + (age2)),
              random = list(Seed = pdDiag(list(R0 ~ 1))),
              start = list(fixed = c(R0 = -8.5, age2 = 1)))

Error in chol.default((value + t(value))/2) :
  the leading minor of order 1 is not positive definite
In addition: Warning messages:
1: In Ops.factor(R0, age2) : '+' not meaningful for factors
2: In Ops.factor(R0, age2) : '+' not meaningful for factors
3: In Ops.factor(R0, age2) : '+' not meaningful for factors

This appears to be a syntax error, but I'm not sure how to go about fixing it.

A: First, your model specification is not correct: as you define fixed effects as RO in fixed = list(R0 ~ 1 + (age2)), you must use this definition in model definition.
Model fitting instruction then becomes:
model2 <- nlme(height ~ (R0) + 1,
          data = Loblolly,
          fixed = list(R0 ~ 1 + (age2)),
          random = list(Seed = pdDiag(list(R0 ~ 1))),
          start = list(fixed = c(R0 = -8.5, age2 = 1)))

Now this leads to a new error message:
Error in nlme.formula(height ~ (R0) + 1, data = Loblolly, fixed = list(R0 ~  :
  step halving factor reduced below minimum in PNLS step

Note that nlme has a verbose argument (is not so informative in our case).
But it appears that this error happens when there is no convergence.
In this case, this is due to your starting values, that are not adequate anymore with this model specification.
I just tried a different set of values, for instance:
model2 <- nlme(height ~ (R0) + 1,
               data = Loblolly,
               fixed = list(R0 ~ 1 + (age2)),
               random = list(Seed = pdDiag(list(R0 ~ 1))),
               start = list(fixed = c(R0 = 0, age2 = 30)), verbose=TRUE)

that one converges and provide a model
> model2
Nonlinear mixed-effects model fit by maximum likelihood
  Model: height ~ (R0) + 1
  Data: Loblolly
  Log-likelihood: -305.1093
  Fixed: list(R0 ~ 1 + (age2))
R0.(Intercept)       R0.age21
      12.96167       36.80548

Random effects:
 Formula: R0 ~ 1 | Seed
        R0.(Intercept) Residual
StdDev:   0.0002761926 9.145988

Number of Observations: 84
Number of Groups: 14


text:
Q: Store result from SQL in array for JSON delivery in Php This is my definition to handle result from MySQL. I need to put records from my request into data defined as array (data => array()). How do I put all my records from MySQL into my array?
$mydata = array('dataset_data' =>
(array('limit' => null,
 'transform' => null,
 'column_index' => null,
 'column_names' => array ('Name1','Name2', 'Name3', 'Name4', 'Name6', 'Name6', 'Age','Birthday'),
 'start_date' => '2006-08-28',
 'end_date' => '2018-08-24',
 'frequency' => 'daily',
 'data' => array()
)));


text:
Q: Java Stream API storing lambda expression as variable This title sounds stupid even to me, but there must be at least somewhat clever way to achieve such effect and I don't know how else to explain it. I need to sort array using sorted in stream API. Here is my stream so far:
Arrays.stream(sequence.split(" "))
        .mapToInt(Integer::parseInt)
        .boxed()
        .sorted((a, b) -> a.compareTo(b))
        .forEach(a -> System.out.print(a + " "));

Now I have two different sorts of course - ascending and descending and the sort I need to use is specified in the user input. So what I want to do is having something like switch with 2 cases: "ascending" and "descending" and a variable to store the lambda expression respectively:
switch(command) {
    case "ascending": var = a.compareTo(b);
    case "descending": var = b.compareTo(a);
}

Then I my sorted looks like:
 .sorted((a, b) -> var)

I got the idea in a python course I attended. There it was available to store an object in variable, thus making the variable "executable". I realize that this lambda is not an object, but an expression, but I'm asking is there any clever way that can achieve such result, or should I just have
if(var)

and two diferent streams for each sort order.

A: You can switch between using Comparator.reverseOrder() and Comparator.naturalOrder:
Comparator<Integer> comparator = youWantToHaveItReversed ? Comparator.reverseOrder(): Comparator.naturalOrder();
Arrays.stream(sequence.split(" "))
      .map(Integer::valueOf)
      .sorted(comparator)
      .forEach(a -> System.out.print(a + " "));

A: The question is not stupid at all. Answering it in a broader sense: Unfortunately, there is no generic solution for that. This is due to the type inference, which determines one particular type for the lambda expression, based on the target type. (The section about type inference may be helpful here, but does not cover all details regarding lambdas).
Particularly, a lambda like x -> y does not have any type. So there is no way of writing
GenericLambdaTypefunction = x -> y;
and later use function as a drop-in replacement for the actual lambda x -> y.
For example, when you have two functions like
static void useF(Function<Integer, Boolean> f) { ... }
static void useP(Predicate<Integer> p) { ... }

you can call them both with the same lambda
useF(x -> true);
useP(x -> true);

but there is no way of "storing" the x -> true lambda in a way so that it later may be passed to both functions - you can only store it in a reference with the type that it will be needed in later:
Function<Integer, Boolean> f = x -> true;
Predicate<Integer>         p = x -> true;
useF(f);
useP(p);

For your particular case, the answer by Konstantin Yovkov already showed the solution: You have to store it as a Comparator<Integer> (ignoring the fact that you wouldn't have needed a lambda here in the first place...)

A: In Lambdas you can use a functionblock
(a,b) -> { if(anything) return 0; else return -1;}


text:
Q: Is there a silent fail for Selenium driver driver.Navigate().GoToUrl(); Hi I am using PhantomJS with Selenium to query some web pages.
Throughout I have used the following code to go from the main product page to a minisite
var miniSiteSrc1 = miniSite1.GetAttribute("href");
driver.Navigate().GoToUrl(miniSiteSrc1);

With a particular URl it doesn't seem to work:
http://media.flixcar.com/delivery/minisite/show/2348/en/823885
When using the exact same code with the following url it seems to work fine:
http://www.isitetv.com/en062124184249062123148173198223-p10.htm
Any ideas why this might be happening and if there's anything I can do about it?
Many thanks


text:
Q: THREE.SkinnedMesh boneTexture leaks It appears that the DataTexture boneTexture created in SkinnedMesh is never disposed automatically.
Are we supposed to dispose of it ourselves when the mesh is removed from the scene? I can't seem to find any documentation or examples that cover this.

A: Follow the pattern in this example and add
mesh.boneTexture.dispose();

three.js r.61


text:
Q: Desabilitar todos os inputs de um form utilizando apenas css? Problema
Estou implementado alguns controles em um protótipo, e estou criando um painel overlay para representar processamentos em background, carregamento de asserts do servidor, busca de dados no servidor, enfim para representar que o sistema está trabalhando e o usuário deve aguardar.
Para isso estou criando uma div sobre toda aplicação, com um z-index maior do que o conteúdo que desejo deixar imutável para o cliente, enquanto ele aguarda o processo. Mas verifiquei que mesmo com a div sobre o conteúdo é possível acessa-lo através de tab, como podem ver aqui no exemplo.
Então gostaria de alguma forma de desabilitar os inputs ou evitar o acesso a ele através de tab, mas isso utilizando apenas css (javascript não é viável), algo nesse sentido:
form.disabled input {
    /*  o que procuro é algo assim: */
    disabled: disabled; /* isso não funciona e nem existe no css, é só para exemplificar o que pretendo */
    /* como desabilitar todos os inputs deste form com css, sem usar javascript? */
    /* ou no minimo como não permitir da o foco no inputs quando o form estiver desabilitado */
}

Pergunta?
Há alguma forma via css de desabilitar um input html?

A: Não é possível bloquear o acesso aos inputs apenas com CSS.
O que você pode fazer é simular este bloqueio, de forma que o usuário entenda que o input não deva ser utilizado, exemplo:
form.disabled input{
    pointer-events:none;
    outline:none;
    text-indent:-9999px;
}

Exemplo: FIDDLE
O problema desta "simulação" é que ao pressionar tab o usuário ainda acaba selecionando o campo "desabilitado", o que poderia causar confusão. Fora isso ainda tem o problema de o campo ainda aceitar valores, ou seja, se eu apertar tab e começar a escrever nele, mesmo sem mostrar ele ainda aceitaria o que eu escrevesse.

A: Unico ponto a acrescentar aos comentários acima é que, caso o usuário tenha qualquer debugador, ele consegue reabilitar os campos do formulário.... pelo menos o suficiente pra editar o conteúdo.. e assim talvez enviar o formulário..
Uma possivel solução seria modificar o imput="text" por um label com a informação, mas acho que isso teria que ser bem ardiloso
Sem contar os diversos navegadores onde cada um aceita uma quantidade limitada de atributos que por sua vez é diferente dos outros.... ai a coisa começa a embaçar pro lado do programador
Meio que não se trabalha muito com a hipótese de que o usuário tenha conhecimento o suficiente  para saber desses paranaue de HTML/JS/CSS.. então o que podemos fazer é disfarçar mesmo...
-----EDIT--------
testa isso pra bloquear o tab:
function teste(evt){
    tecla = evt.keyCode;
    if (tecla==9) {$("#aa").focus();}
}

e coloca isso no form:
<form id="esse" onkeypress="teste(event)">

o primeiro campo do formulario eu coloquei o id 'aa' pra receber o focus, ai é como se ele entendesse que o tab voltou pro indice 0, e toda vez que ele digita tab, ele adiciona 1 ao indice, e retira 1 do indice.
Ai quando o formulário for bloqueado voce remove o evento teste(event) do form, quando o formulario for desbloqueado, adiciona o evento teste(event).
Enfim, é uma grande gambiarra, mas é a melhor solução que encontrei rs

A: Desenvolvi uma solução (type == POG), que resolveu meu problema em particular, e só irá funcionar se for utilizado com uma div overlay sobre o conteúdo que não permita a manipulação direta do usuário com o formulário, minha solução evita a entrada do focus no inputs filhos de um formulário com a class = disabled. Além do focus, também estou manipulando os eventos de mousedown click change e tentando os cancelar. Segue minha solução:
$('body').on('focus mousedown click change', 'form.disabled input', function(e){
    // cancel stack events
    e.preventDefault();
    e.stopPropagation();
    e.stopImmediatePropagation();

    // remove focus
    $(this).blur();

    return false;
});

Infelizmente tive que utilizar javascript.
Acompanhe o exemplo online de minha solução.

Obs: Essa não é uma solução definitiva, nem perto disso, é a solução para o meu problema em particular, e continuo aguardando uma solução mais eficiente.


text:
Q: Creating error/result function in node I'm having trouble understanding how to create functions that would return in the format of (err, result) for an Express app.
My current db query function is:
pool.query(
  'SELECT id FROM users WHERE email = ? LIMIT 1',
  [email],
  (results) => { // I'd like this to be (err, results)
    if(results instanceof Error){...}
  }
})

In my db.js file, pool looks like this:
module.exports = {
  query: (query, args, cb) => {
    pool.getConnection( (err, connection) => {
      if(err){
        new Error('No database connections available in pool')
      } else {
        connection.query(query, args, (error, results, fields) => {
          connection.release()
          // I got a MySQL error here and I'd like to handle it in my callback function
          if(error){
            new Error('Bad query')
          } else {
            cb(results)
          }
        })
      }
    })
  }
}

For this and other functions, I'd like to return a proper Error if there is one, and have my callback listen for err, result as parameters.
I tried using new Error('Bad query') but that came back as the first variable in my callback no matter what (which is how I ended up with instanceof Error.
How do you structure a callback and response so that your callback can be in the err, result format and check for/handle errors properly on functions you're creating? (I understand how to use it for modules already in this format - I'm talking about writing/formatting your own code.)
Thanks!

A: You can do it like this:
module.exports = {
  query: (query, args, cb) => {
    pool.getConnection( (err, connection) => {
      if(err){
        cb(new Error('No database connections available in pool'));
      } else {
        connection.query(query, args, (error, results, fields) => {
          connection.release();
          // I got a MySQL error here and I'd like to handle it in my callback function
          if(error){
            cb(new Error('Bad query'));
          } else {
            cb(null, results);
          }
        });
      }
    });
  }
}

You always pass the error value as the first argument to the callback and, if there is a result, you pass it as the second.  Then, within the callback, you check to see if err is non-null and, if so, there is an error.  If it's null, then the second argument contains the result.
Note that by not returning or including the actual err value that the database gave you, you may be hiding useful information (like why the query failed).

Then, where you use this, you do something like this:
let query = 'SELECT id FROM users WHERE email = ? LIMIT 1';
pool.query(query, [email], (err, result) => {
    if (err) {
        // handle error here
    } else {
        // process result here
    }
});


text:
Q: The executable is absent yet I can execute the command on the command line There's such utility for Windows developers called regtlib. I have three computers - one with WinXP, another two with Win2k3. If I run built-in Windows search for file with wildcard regtlib* on the whole filesystem search finds nothing on all three computers.
If I try to execute regtlib on WinXP command line it says it can't find such a file or built-in command. The same on one of the two Win2k3 computers. But when I do that on the other Win2k3 computer I see typical regtlib output.
What happens? What is the magic that invokes regtlib without the file being present on the filesystem?

A: regtlib does have to be present on the file-system.  There are a couple of things you can do to find it.  First, if it is not in the current directory it has to be in one of the directories in the PATH environment variable.  You can see the directories using this command:
echo %PATH%

If that doesn't help you could use Sysinternals Process Explorer or Process Monitor to help you track down the path to the executable that is running.

A: You can try the following:
for %x in (regtlib.exe) do @echo.%~dp$PATH:x

which should show you the place where the program resides.

A: Make sure you are searching hidden folders/files.

A: It could be coming from a Windows cache.