问:
bouncycastle and iText versions
I am using iText 5.5.11 following  digital-signatures-chapter.
I have created my KeyStore - ks.jks file and added bouncycastle jar to my classpath.

Using bouncycastle 14-157(latest) version i got -

```<code>java.lang.ClassNotFoundException: org.bouncycastle.tsp.TimeStampTokenInfo
</code>```

following TimeStampTokenInfo-class-not-found I tried to use bouncycastle 14-145 and this error:

```<code>java.lang.ClassNotFoundException: org.bouncycastle.jcajce.provider.digest.MD2$Digest
</code>```

Anyone knows what else can I try?

The full error log:

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: org/bouncycastle/jcajce/provider/digest/MD2$Digest
    at com.mataf.GenSig.PfxDS.sign(PfxDS.java:51)
    at com.mataf.GenSig.PfxDS.main(PfxDS.java:71)
Caused by: java.lang.ClassNotFoundException: org.bouncycastle.jcajce.provider.digest.MD2$Digest
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    ... 2 more
</code>```

Thanks.

答:
A look at the iText 5.5.11 Maven pom.xml reveals:

  <dependencies>
    <dependency>
      <groupId>org.bouncycastle</groupId>
      <artifactId>bcprov-jdk15on</artifactId>
      <version>1.49</version>
      <optional>true</optional>
    </dependency>
    <dependency>
      <groupId>org.bouncycastle</groupId>
      <artifactId>bcpkix-jdk15on</artifactId>
      <version>1.49</version>
      <optional>true</optional>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.8.2</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.santuario</groupId>
      <artifactId>xmlsec</artifactId>
      <version>1.5.1</version>
      <optional>true</optional>
    </dependency>
  </dependencies>
```

Thus, iText is compiled using the Java version 5-8 version of BouncyCastle version 1.49.

Title: bouncycastle and iText versions

Body:
I am using iText 5.5.11 following  digital-signatures-chapter.
I have created my KeyStore - ks.jks file and added bouncycastle jar to my classpath.

Using bouncycastle 14-157(latest) version i got -

java.lang.ClassNotFoundException: org.bouncycastle.tsp.TimeStampTokenInfo

following TimeStampTokenInfo-class-not-found I tried to use bouncycastle 14-145 and this error:

java.lang.ClassNotFoundException: org.bouncycastle.jcajce.provider.digest.MD2$Digest

Anyone knows what else can I try?

The full error log:

Exception in thread "main" java.lang.NoClassDefFoundError: org/bouncycastle/jcajce/provider/digest/MD2$Digest
    at com.mataf.GenSig.PfxDS.sign(PfxDS.java:51)
    at com.mataf.GenSig.PfxDS.main(PfxDS.java:71)
Caused by: java.lang.ClassNotFoundException: org.bouncycastle.jcajce.provider.digest.MD2$Digest
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    ... 2 more

Thanks.

Body:
A look at the iText 5.5.11 Maven pom.xml reveals:

  <dependencies>
    <dependency>
      <groupId>org.bouncycastle</groupId>
      <artifactId>bcprov-jdk15on</artifactId>
      <version>1.49</version>
      <optional>true</optional>
    </dependency>
    <dependency>
      <groupId>org.bouncycastle</groupId>
      <artifactId>bcpkix-jdk15on</artifactId>
      <version>1.49</version>
      <optional>true</optional>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.8.2</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.santuario</groupId>
      <artifactId>xmlsec</artifactId>
      <version>1.5.1</version>
      <optional>true</optional>
    </dependency>
  </dependencies>

Thus, iText is compiled using the Java version 5-8 version of BouncyCastle version 1.49.


来源: stackexchange

问:
Finding unique file names from an html file
```<code>$ cat downloaded_file.html

1373 <A HREF="http://site.com/STDMON11202010_company.txt">STDMON11202010_company.txt</A><br> Monday, November 22, 2010  1:31 AM
</code>```

How do I search an html file from my shell script and select the unique filenames those start with STDMON and end with _company.txt

答:
If you have only digits between STDMON and _company.txt you can do:

```<code>grep -o 'STDMON[0-9]*_company\.txt' input.txt | sort -u
</code>```

See it

And if there can be anything you can do:

```<code>grep -oP 'STDMON.*?_company\.txt' input.txt | sort -u
</code>```

ContentLicense: CC BY-SA 2.5

Body:
$ cat downloaded_file.html

1373 STDMON11202010_company.txt
 Monday, November 22, 2010  1:31 AM

How do I search an html file from my shell script and select the unique filenames those start with STDMON and end with _company.txt

Body:
If you have only digits between STDMON and _company.txt you can do:

grep -o 'STDMON[0-9]*_company\.txt' input.txt | sort -u

See it

And if there can be anything you can do:

grep -oP 'STDMON.*?_company\.txt' input.txt | sort -u


问:
array_flip with an array in the value
Simple one (but not solved yet): this is my array

```<code>[
 [
   "role" => "admin",
   "name" => [
     "Felipy",
     "Ivan",
   ],
 ],
 [
   "role" => "user",
   "name" => [
     "Michel",
     "Paul",
     "Tay",
 ],
]
</code>```

And I would love to see this result:

```<code>[
 "Felipy" => "admin",
 "Ivan" => "admin",
 "Michael" => "user",
 "Paul" => "user",
 "Tay" => "user",
]
</code>```

I've already tried array_flip

答:
Less clear but still working solution:</p>

```<code>$a = [
 [
   "role" => "admin",
   "name" => [
     "Felipy",
     "Ivan",
   ],
 ],
 [
   "role" => "user",
   "name" => [
     "Michel",
     "Paul",
     "Tay",
    ],
 ],
];

$r = [];
foreach ($a as $item) {
    $r = array_merge($r, array_fill_keys($item['name'], $item['role']));
}
echo'```',print_r($r),'```';
</code>```

ContentLicense: CC BY-SA 3.0

Title: array_flip with an array in the value

Body:
Simple one (but not solved yet): this is my array

[
 [
   "role" => "admin",
   "name" => [
     "Felipy",
     "Ivan",
   ],
 ],
 [
   "role" => "user",
   "name" => [
     "Michel",
     "Paul",
     "Tay",
 ],
]

And I would love to see this result:

[
 "Felipy" => "admin",
 "Ivan" => "admin",
 "Michael" => "user",
 "Paul" => "user",
 "Tay" => "user",
]

I've already tried array_flip

Body:
Less clear but still working solution:

$a = [
 [
   "role" => "admin",
   "name" => [
     "Felipy",
     "Ivan",
   ],
 ],
 [
   "role" => "user",
   "name" => [
     "Michel",
     "Paul",
     "Tay",
    ],
 ],
];

$r = [];
foreach ($a as $item) {
    $r = array_merge($r, array_fill_keys($item['name'], $item['role']));
}
echo'<pre>',print_r($r),'</pre>';


问:
Auto generate index.d.ts, type definitions, from a typescript module
If I have a TypeScript module saved as my-function.ts as follows :

```<code>export function myFunction (param: number): number { return param }
</code>```

This will be compiled to JavaScript in whichever way and loose its type definitions. I am then able to create a index.d.ts file which declare this module's definitions, but this seems a bit tedious to redefine/redeclare the definitions.

Are there ways to generate the type definitions automatically from the my-function.ts file to a index.d.ts file?

答:
If you compile with the --declaration flag, TypeScript will automatically generate .d.ts files for you.

This mode will require that you certain types are visible so that they can be described in your .d.ts files.

Body:
If I have a TypeScript module saved as my-function.ts as follows :

export function myFunction (param: number): number { return param }

This will be compiled to JavaScript in whichever way and loose its type definitions. I am then able to create a index.d.ts file which declare this module's definitions, but this seems a bit tedious to redefine/redeclare the definitions.

Are there ways to generate the type definitions automatically from the my-function.ts file to a index.d.ts file?


问:
MySQL Table - Display name once along with their total score
I have the below data entered into a database from a website:

```<code> USER  |  SCORE
 abc   |    4
 ghi   |    2
 abc   |    6
 def   |    1
 abc   |    3
</code>```

I want to now display a list of all the users, in alphabetical order, without repeating itself, and their total score. So with the table above, it would look something like:

```<code> abc: 13
 def: 1
 ghi: 2
</code>```

How do I do that? I would use php, right? Or javascript?

答:
Your query will be something like: </p>

```<code>select user, sum(score) as total_score from table group by user order by user asc;
</code>```

<p>It can be done in MySQL without involving any other programming language. </p>

Body:
I have the below data entered into a database from a website:

 USER  |  SCORE
 abc   |    4
 ghi   |    2
 abc   |    6
 def   |    1
 abc   |    3

I want to now display a list of all the users, in alphabetical order, without repeating itself, and their total score. So with the table above, it would look something like:

 abc: 13
 def: 1
 ghi: 2

How do I do that? I would use php, right? Or javascript?

Body:
Your query will be something like:

select user, sum(score) as total_score from table group by user order by user asc;

It can be done in MySQL without involving any other programming language.


问:
C# Unit testing - check if a private method was reached
I am using C# MOQ library.

Lets say I want to create a UnitTest for this piece of code:

```<code>if(condition){
    privateMethod();
}
else{
    logger.info("didn't hit")
}
</code>```

I want to check if privateMethod was hit, I can't use the Verify function as it is private. How can I do that?

I thought about adding a Status member dedicated for the unit testing, which will hold the last location before exiting the tested method.

答:
I use MSTest and this is the solution I use in the Test Class to invoke Private Method:

```<code>Class target = new Class();
PrivateObject obj = new PrivateObject(target);
var retVal = obj.Invoke("PrivateMethod");
Assert.AreEqual(retVal);
</code>```

It use the PrivateObject Class

Body:
I am using C# MOQ library.

Lets say I want to create a UnitTest for this piece of code:

if(condition){
    privateMethod();
}
else{
    logger.info("didn't hit")
}

I want to check if privateMethod was hit, I can't use the Verify function as it is private. How can I do that?

I thought about adding a Status member dedicated for the unit testing, which will hold the last location before exiting the tested method.

Body:
I use MSTest and this is the solution I use in the Test Class to invoke Private Method:

Class target = new Class();
PrivateObject obj = new PrivateObject(target);
var retVal = obj.Invoke("PrivateMethod");
Assert.AreEqual(retVal);

It use the PrivateObject Class


问:
problem regarding transferring file to server using socket connection
I'm able to transfer a file to the server using Java, but I'm not able to transfer the file using socket programming in Android. How do I do this? Here is my Java code:</p>

```<code>import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {
    InputStream is;
    OutputStream os;
    FileReader fread;
    BufferedReader bfrewad;
    FileInputStream fis;
    FileOutputStream fos;
    static Socket client;
    String str="";
    static File f1;

    public static void main(String[] args) {
         f1=new File("abc.dat");
        Client c1=new Client();
        try {
            //c1.writeToAlocalfilefortesting();
            client = new Socket("192.168.0.180", 34000);
            System.out.println(client.isBound());
            System.out.println("socket created ");
            c1.createAlinkForFile();
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            System.out.println("--------"+e.toString());
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            System.out.println("--------"+e.toString());
            e.printStackTrace();
        }
        catch (Exception e) {
            // TODO Auto-generated catch block
            System.out.println("--------"+e.toString()+"-----");
            e.printStackTrace();
        }
    }

    private void writeToAlocalfilefortesting() throws IOException {
        System.out.println("inside the function");
         //TODO Auto-generated method stub
        int len;
        int count=0;
        System.out.println("here ");
        File file=new File("Nas123456789123.dat");
        System.out.println("file opened");
        fis=new FileInputStream(file);
        System.out.println("getting input stream");
        byte[] buffer =new byte[25];
        os=new FileOutputStream(f1);
        System.out.println("out put stream ");
        //int i=fis.read(buf)
        while((len=fis.read(buffer))>0){
        if(len==25){
            count=count+len;
            fos.write(buffer, 0, len);
            System.out.println("sritten");
        }
        }
    }

    private  void createAlinkForFile() throws IOException {
        // TODO Auto-generated method stub
        os=client.getOutputStream();
        File file=new File("Nas123456789123.dat");
        fis=new FileInputStream(file);
        byte[] b =new byte[25];
        int len1;
        int count1=0;
        while((len1=fis.read(b))>0){
            if(len1==25){
                count1=count1+len1;
                os.write(b, 0, len1);
                os.flush();
                System.out.println("sritten");
            }
       }
    }
}
</code>```

答:
int filelenghth=(int)myFile.length();

byte [] mybytearray  = new byte [filelenghth];
BufferedInputStream bis1 = new BufferedInputStream(new FileInputStream(myFile));

bis1.read(mybytearray,0,mybytearray.length);
dos.write(mybytearray,0,mybytearray.length); // data outputstream
```

Body:
I'm able to transfer a file to the server using Java, but I'm not able to transfer the file using socket programming in Android. How do I do this? Here is my Java code:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {
    InputStream is;
    OutputStream os;
    FileReader fread;
    BufferedReader bfrewad;
    FileInputStream fis;
    FileOutputStream fos;
    static Socket client;
    String str="";
    static File f1;

    public static void main(String[] args) {
         f1=new File("abc.dat");
        Client c1=new Client();
        try {
            //c1.writeToAlocalfilefortesting();
            client = new Socket("192.168.0.180", 34000);
            System.out.println(client.isBound());
            System.out.println("socket created ");
            c1.createAlinkForFile();
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            System.out.println("--------"+e.toString());
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            System.out.println("--------"+e.toString());
            e.printStackTrace();
        }
        catch (Exception e) {
            // TODO Auto-generated catch block
            System.out.println("--------"+e.toString()+"-----");
            e.printStackTrace();
        }
    }

    private void writeToAlocalfilefortesting() throws IOException {
        System.out.println("inside the function");
         //TODO Auto-generated method stub
        int len;
        int count=0;
        System.out.println("here ");
        File file=new File("Nas123456789123.dat");
        System.out.println("file opened");
        fis=new FileInputStream(file);
        System.out.println("getting input stream");
        byte[] buffer =new byte[25];
        os=new FileOutputStream(f1);
        System.out.println("out put stream ");
        //int i=fis.read(buf)
        while((len=fis.read(buffer))>0){
        if(len==25){
            count=count+len;
            fos.write(buffer, 0, len);
            System.out.println("sritten");
        }
        }
    }

    private  void createAlinkForFile() throws IOException {
        // TODO Auto-generated method stub
        os=client.getOutputStream();
        File file=new File("Nas123456789123.dat");
        fis=new FileInputStream(file);
        byte[] b =new byte[25];
        int len1;
        int count1=0;
        while((len1=fis.read(b))>0){
            if(len1==25){
                count1=count1+len1;
                os.write(b, 0, len1);
                os.flush();
                System.out.println("sritten");
            }
       }
    }
}

ContentLicense: CC BY-SA 4.0


问:
SQL query to get the count by applying group by
I want to get the below result:

source table :

```<code>Cnt  A    B
4   ABC YU/FGH
5   ABC YU/DFE
5   ABC KL
2   LKP BN/ER
4   JK  RE
</code>```

Result:

```<code>Cnt  A  B
9   ABC YU
5   ABC KL
2   LKP BN
4   JK  RE
</code>```

Here I want the count by grouping 'B' and want to display the 'B' record only till the special character (/)

答:
By using String and CharIndex Functions.</p>

```<code>;WITH SourceTable(Cnt,A,B) AS
(
SELECT 4,'ABC','YU/FGH'UNION ALL
SELECT 5,'ABC','YU/DFE'UNION ALL
SELECT 5,'ABC','KL'  UNION ALL
SELECT 2,'LKP','BN/ER' UNION ALL
SELECT 4,'JK','RE'
)

SELECT SUM(Cnt) AS Cnt,A,CASE WHEN CHARINDEX('/',B) = 0 THEN B
                              ELSE SUBSTRING(B,0,CHARINDEX('/',B)) END AS [B] FROM SourceTable
GROUP BY A,CASE WHEN CHARINDEX('/',B) = 0 THEN B
                ELSE SUBSTRING(B,0,CHARINDEX('/',B)) END
ORDER BY Cnt DESC
</code>```

Body:
I want to get the below result:

source table :

Cnt  A    B
4   ABC YU/FGH
5   ABC YU/DFE
5   ABC KL
2   LKP BN/ER
4   JK  RE

Result:

Cnt  A  B
9   ABC YU
5   ABC KL
2   LKP BN
4   JK  RE

Here I want the count by grouping 'B' and want to display the 'B' record only till the special character (/)

Body:
By using String and CharIndex Functions.

;WITH SourceTable(Cnt,A,B) AS
(
SELECT 4,'ABC','YU/FGH'UNION ALL
SELECT 5,'ABC','YU/DFE'UNION ALL
SELECT 5,'ABC','KL'  UNION ALL
SELECT 2,'LKP','BN/ER' UNION ALL
SELECT 4,'JK','RE'
)

SELECT SUM(Cnt) AS Cnt,A,CASE WHEN CHARINDEX('/',B) = 0 THEN B
                              ELSE SUBSTRING(B,0,CHARINDEX('/',B)) END AS [B] FROM SourceTable
GROUP BY A,CASE WHEN CHARINDEX('/',B) = 0 THEN B
                ELSE SUBSTRING(B,0,CHARINDEX('/',B)) END
ORDER BY Cnt DESC


问:
Close Bootstrap Modal
I have a bootstrap modal dialog box that I want to show initially, then when the user clicks on the page, it disappears. I have the following:

```<code>$(function () {
   $('#modal').modal(toggle)
});

 <div class="modal" id='modal'>
     <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h3 id="myModalLabel">Error:</h3>
        </div>
        <div class="modal-body">
        <p>Please correct the following errors:</p>
        </div>
     </div>
 </div>
</code>```

The modal is displayed initially, but it does not close when clicked outside of the modal. Also, the content area is not greyed out.. How can I get the modal to display initially, then close after the user clicks outside the area? And how can I get the background to be grayed out as in the demo?

答:
We can close the modal pop-up in the following ways:

```<code>// We use data-dismiss property of modal-up in html to close the modal-up,such as

<div class='modal-footer'><button type='button' class="btn btn-default" data-dismiss='modal'>Close</button></div>

 // We can close the modal pop-up through java script, such as

 <div class='modal fade pageModal'  id='openModal' tabindex='-1' data-keyboard='false' data-backdrop='static'>

    $('#openModal').modal('hide'); //Using modal pop-up Id.
    $('.pageModal').modal('hide'); //Using class that is defined in modal html.
</code>```

Title: Close Bootstrap Modal

Body:
I have a bootstrap modal dialog box that I want to show initially, then when the user clicks on the page, it disappears. I have the following:

$(function () {
   $('#modal').modal(toggle)
});

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Error:

Please correct the following errors:

The modal is displayed initially, but it does not close when clicked outside of the modal. Also, the content area is not greyed out.. How can I get the modal to display initially, then close after the user clicks outside the area? And how can I get the background to be grayed out as in the demo?

Body:
We can close the modal pop-up in the following ways:

// We use data-dismiss property of modal-up in html to close the modal-up,such as

<div class='modal-footer'><button type='button' class="btn btn-default" data-dismiss='modal'>Close</button></div>

 // We can close the modal pop-up through java script, such as

 <div class='modal fade pageModal'  id='openModal' tabindex='-1' data-keyboard='false' data-backdrop='static'>

    $('#openModal').modal('hide'); //Using modal pop-up Id.
    $('.pageModal').modal('hide'); //Using class that is defined in modal html.


答:
The following should do the trick using MySql query:

```<code>SELECT USER , SUM(SCORE) FROM table GROUP BY USER ORDER BY USER ASC
</code>```

Title: MySQL Table - Display name once along with their total score

Body:
The following should do the trick using MySql query:

SELECT USER , SUM(SCORE) FROM table GROUP BY USER ORDER BY USER ASC


问:
Understanding ServiceWorker registration
I'm reading the ServiceWorker getting started docs https://developers.google.com/web/fundamentals/getting-started/primers/service-workers.

So first we register our ServiceWorker with the scope. So I did that as below

```<code><!DOCTYPE html>
<html>
<head>
    <title>Getting started with Service Worker</title>
</head>
<body>

<script type="text/javascript">

if ('serviceWorker' in navigator) {
  window.addEventListener('load', function() {
    navigator.serviceWorker.register('/sw.js').then(function(registration) {
      // Registration was successful
      console.log('ServiceWorker registration successful with scope: ', registration.scope);
    }, function(err) {
      // registration failed :(
      console.log('ServiceWorker registration failed: ', err);
    });
  });
}

</script>

</body>
</html>
</code>```

and created a sw.js file and wrote a console.log inside sw.js

```<code>console.log("This is sw.js")
</code>```

So when I access the index.html file the first time, that console.log is executed and ServiceWorker registration successful message is printed. But when I refresh the page second time, it only prints the message ServiceWorker registration successful. So why didn't it executed the console.log inside sw.js for the second time. I was expecting it to execute that console.log second time. Am I missing the point here?

答:
Service workers are scripts that are basically executed once (in background) when they are registered. If you need to execute some recurrent code, you need to use service worker API:

A service worker is an event-driven worker registered against an origin and a path.

The install event is called asynchronously after you call navigator.serviceWorker.register('/sw.js'); that's why it returns a Promise, to which you pass a callback function (the one with the content console.log('ServiceWorker registration successful ...');).

Body:
I'm reading the ServiceWorker getting started docs https://developers.google.com/web/fundamentals/getting-started/primers/service-workers.

So first we register our ServiceWorker with the scope. So I did that as below

<!DOCTYPE html>

    <title>Getting started with Service Worker</title>

and created a sw.js file and wrote a console.log inside sw.js

console.log("This is sw.js")

So when I access the index.html file the first time, that console.log is executed and ServiceWorker registration successful message is printed. But when I refresh the page second time, it only prints the message ServiceWorker registration successful. So why didn't it executed the console.log inside sw.js for the second time. I was expecting it to execute that console.log second time. Am I missing the point here?


问:
On clicking the back button Activity is restarting itself
I am starting an activity using intent like this:

```<code>Bundle bundle = new Bundle();
bundle.putParcelableArrayList("datacover",arrayList);
Intent intent = new Intent(TroubleShootActivity.this,SearchResultsActivity.class);
intent.putExtra("bundle",bundle);
startActivity(intent);
</code>```

Im not finishing the activity, but still when i click on back button in the next activity it does not return to the previous activity instead restarts itself.

Code for the other activity:

```<code>public class SearchResultsActivity extends AppCompatActivity implements InnerDetailsFragment.OntroubleshootinneritemsListener,InnerDetailsFragment.OnHandleBack,CompleteDetailsFragment.OnHandleBack {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_search_results);
    if(!getResources().getBoolean(R.bool.twoPaneMode)){
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }else{
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }

    Bundle bundle=getIntent().getBundleExtra("bundle");

    FragmentManager fragmentManager = getSupportFragmentManager();
    Fragment Inner = new InnerDetailsFragment();
    bundle.putString("val", "search");
    Inner.setArguments(bundle);
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction().replace(R.id.activity_search_results,Inner);

    fragmentTransaction.commit();

}

@Override
public void onBackClick(String inner) {
    super.onBackPressed();
}

@Override
public void ontroubleinneritemelected(int position, String heading, CoverageData coverageData) {
    Bundle bundle = new Bundle();
    bundle.putParcelable("coverage",coverageData);

    FragmentManager fragmentManager = getSupportFragmentManager();
    Fragment Detailsf= new CompleteDetailsFragment();
    Detailsf.setArguments(bundle);
    FragmentTransaction ft = fragmentManager.beginTransaction().replace(R.id.activity_search_results,Detailsf);
    ft.addToBackStack("completedetails");
    ft.commit();

}

@Override
public void onBackPressed() {
    super.onBackPressed();
}
}
</code>```

答:
Just try this in the second activity

```<code>@Override
public void onBackPressed() {
   finish();
}
</code>```

fragmentManager.beginTransaction().add(R.id.activity_search_results,Detailsf);
    ft.commit();

Body:
I am starting an activity using intent like this:

Bundle bundle = new Bundle();
bundle.putParcelableArrayList("datacover",arrayList);
Intent intent = new Intent(TroubleShootActivity.this,SearchResultsActivity.class);
intent.putExtra("bundle",bundle);
startActivity(intent);

Im not finishing the activity, but still when i click on back button in the next activity it does not return to the previous activity instead restarts itself.

Code for the other activity:

public class SearchResultsActivity extends AppCompatActivity implements InnerDetailsFragment.OntroubleshootinneritemsListener,InnerDetailsFragment.OnHandleBack,CompleteDetailsFragment.OnHandleBack {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_search_results);
    if(!getResources().getBoolean(R.bool.twoPaneMode)){
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }else{
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }

    Bundle bundle=getIntent().getBundleExtra("bundle");

    FragmentManager fragmentManager = getSupportFragmentManager();
    Fragment Inner = new InnerDetailsFragment();
    bundle.putString("val", "search");
    Inner.setArguments(bundle);
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction().replace(R.id.activity_search_results,Inner);

    fragmentTransaction.commit();

}

@Override
public void onBackClick(String inner) {
    super.onBackPressed();
}

@Override
public void ontroubleinneritemelected(int position, String heading, CoverageData coverageData) {
    Bundle bundle = new Bundle();
    bundle.putParcelable("coverage",coverageData);

    FragmentManager fragmentManager = getSupportFragmentManager();
    Fragment Detailsf= new CompleteDetailsFragment();
    Detailsf.setArguments(bundle);
    FragmentTransaction ft = fragmentManager.beginTransaction().replace(R.id.activity_search_results,Detailsf);
    ft.addToBackStack("completedetails");
    ft.commit();

}

@Override
public void onBackPressed() {
    super.onBackPressed();
}
}

Body:
Just try this in the second activity

@Override
public void onBackPressed() {
   finish();
}

fragmentManager.beginTransaction().add(R.id.activity_search_results,Detailsf);
    ft.commit();


答:
User the Query to fetch data from database

```<code>SELECT USER,
SUM (SCORE) as SCORE
FROM table
GROUP BY USER  ORDER BY USER ASC;
</code>```

You should use PHP to fetch data from DB and print.

Body:
User the Query to fetch data from database

SELECT USER,
SUM (SCORE) as SCORE
FROM table
GROUP BY USER  ORDER BY USER ASC;

You should use PHP to fetch data from DB and print.


问:
Airflow unpause dag programmatically?
I have a dag that we'll deploy to multiple different airflow instances and in our airflow.cfg we have dags_are_paused_at_creation = True but for this specific dag we want it to be turned on without having to do so manually by clicking on the UI. Is there a way to do it programmatically?

答:
supply your dag_id and run this command on your command line.

```<code>airflow pause dag_id.
</code>```

For more information on the airflow command line interface: https://airflow.incubator.apache.org/cli.html

Title: Airflow unpause dag programmatically?

Body:
supply your dag_id and run this command on your command line.

airflow pause dag_id.

For more information on the airflow command line interface: https://airflow.incubator.apache.org/cli.html


问:
Any way to make the code more simple?
I have made jQuery code which is addclass when click and remove others.

```<code>$('.list_qna li a').on('click', function (e) {
    $(this).parent('li').addClass('selected').siblings('.selected').removeClass('selected');
    e.preventDefault();
});

$('.list_box li a').on('click', function (e) {
    $(this).parent('li').addClass('selected').siblings('.selected').removeClass('selected');
    e.preventDefault();
});

$('.list_contact li a').on('click', function (e) {
    $(this).parent('li').addClass('selected').siblings('.selected').removeClass('selected');
    e.preventDefault();
});

<ul class="list_qna">
    <li>
        <a href="#">list</a>
    </li>
    <li>
        <a href="#">list</a>
    </li>
</ul>

<ul class="list_box ">
    <li>
        <a href="#">list</a>
    </li>
    <li>
        <a href="#">list</a>
    </li>
</ul>

<ul class="list_contact ">
    <li>
        <a href="#">list</a>
    </li>
    <li>
        <a href="#">list</a>
    </li>
</ul>
</code>```

Is there any way to make the code more simple for different elements?
Please help.

*updated with HTML structure

答:
If you want same behavior for all lists, than it is best to use same class on all of them. Here is an example:

$('.list_selection li a').on('click', function(e) {
 e.preventDefault();
 $(this).parent('li').addClass('selected').siblings('.selected').removeClass('selected');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
.list_selection {
    list-style: none;
    overflow: hidden;
}
.list_selection li {
    width: 30%;
    float: left;
    margin: 5px;
    border: 1px solid black;
}
.list_selection a {
    display: block;
    background: none red;
    cursor: pointer;
    text-align: center;
}
.list_selection .selected a {
    background: none yellow;
}</code>```

List qna 1select

List qna 2select

List qna 3select

List box 1select

List box 2select

List box 3select

List contact 1select

List contact 2select

List contact 3select

```
</div>
</div>
</p>

<p>Also on JSFiddle.</p>

<p>I case you cannot or do not want to add the class, than you can use jQuery Multiple Selector (read: comma separated selectors) this way:</p>

```$('.list_qna li a, .list_box li a, .list_contact li a').on('click', function(e) {
    e.preventDefault();
    $(this).parent('li').addClass('selected').siblings('.selected').removeClass('selected');
});
```

Selects the combined results of all the specified selectors.

Title: Any way to make the code more simple?

Body:
I have made jQuery code which is addclass when click and remove others.

$('.list_qna li a').on('click', function (e) {
    $(this).parent('li').addClass('selected').siblings('.selected').removeClass('selected');
    e.preventDefault();
});

$('.list_box li a').on('click', function (e) {
    $(this).parent('li').addClass('selected').siblings('.selected').removeClass('selected');
    e.preventDefault();
});

$('.list_contact li a').on('click', function (e) {
    $(this).parent('li').addClass('selected').siblings('.selected').removeClass('selected');
    e.preventDefault();
});

        list

        list

        list

        list

        list

        list

Is there any way to make the code more simple for different elements?
Please help.

*updated with HTML structure

Body:
If you want same behavior for all lists, than it is best to use same class on all of them. Here is an example:

$('.list_selection li a').on('click', function(e) {
 e.preventDefault();
 $(this).parent('li').addClass('selected').siblings('.selected').removeClass('selected');
});

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
.list_selection {
    list-style: none;
    overflow: hidden;
}
.list_selection li {
    width: 30%;
    float: left;
    margin: 5px;
    border: 1px solid black;
}
.list_selection a {
    display: block;
    background: none red;
    cursor: pointer;
    text-align: center;
}
.list_selection .selected a {
    background: none yellow;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="list_qna list_selection">
    <li>List qna 1<a>select</a></li>
    <li>List qna 2<a>select</a></li>
    <li>List qna 3<a>select</a></li>
</ul>
<ul class="list_box list_selection">
    <li>List box 1<a>select</a></li>
    <li>List box 2<a>select</a></li>
    <li>List box 3<a>select</a></li>
</ul>
<ul class="list_contact list_selection">
    <li>List contact 1<a>select</a></li>
    <li>List contact 2<a>select</a></li>
    <li>List contact 3<a>select</a></li>
</ul>

Also on JSFiddle.

I case you cannot or do not want to add the class, than you can use jQuery Multiple Selector (read: comma separated selectors) this way:

$('.list_qna li a, .list_box li a, .list_contact li a').on('click', function(e) {
    e.preventDefault();
    $(this).parent('li').addClass('selected').siblings('.selected').removeClass('selected');
});

Selects the combined results of all the specified selectors.


答:
You can do this in database itself using the below SQL query.</p>

```<code>SELECT SUM( SCORE ) , USER
FROM  SampleTable
GROUP BY USER
ORDER BY USER
</code>```

Body:
I have the below data entered into a database from a website:

 USER  |  SCORE
 abc   |    4
 ghi   |    2
 abc   |    6
 def   |    1
 abc   |    3

I want to now display a list of all the users, in alphabetical order, without repeating itself, and their total score. So with the table above, it would look something like:

 abc: 13
 def: 1
 ghi: 2

How do I do that? I would use php, right? Or javascript?

Body:
You can do this in database itself using the below SQL query.

SELECT SUM( SCORE ) , USER
FROM  SampleTable
GROUP BY USER
ORDER BY USER


问:
How to test private field is set to supplied value using public method in JUnit?
I have a class:

```<code>public class MyEncryptor {

    private StringEncryptor stringEncryptor; // this is an interface ref

    public void setStringEncryptor(StringEncryptor stringEncryptorImpl) {

        if(condition){
            this.stringEncryptor = stringEncryptorImpl;
        }

    }
}
</code>```

When Testing in JUnit for method setStringEncryptor, i want to test if instance value stringEncryptor is set to what i've supplied in parameter as implementation? or i'm going the wrong way for testing this method?

Below is my failed attempt in a junit test method:

```<code>MyEncryptor decryptor = new MyEncryptor ();

        StringEncryptor spbe = new StandardPBEStringEncryptor();
        decryptor.setStringEncryptor(spbe);

        Field f = MyEncryptor .class.getDeclaredField("stringEncryptor");
        f.setAccessible(true);

        Assert.assertSame(f, spbe);
</code>```

I want to test that stringEnctyptor is set to spbe in junit

答:
i want to test if instance value stringEncryptor is set to what i've
  supplied in parameter as implementation? or i'm going the wrong way
  for testing this method?

I think you're going the wrong way. Wherever possible I would test that the unit under test does the encryption as expected, not specifically if a private field is being set. You really want to test the unit functionality, and not the details of its implementation.

Body:
I have a class:

public class MyEncryptor {

    private StringEncryptor stringEncryptor; // this is an interface ref

    public void setStringEncryptor(StringEncryptor stringEncryptorImpl) {

        if(condition){
            this.stringEncryptor = stringEncryptorImpl;
        }

    }
}

When Testing in JUnit for method setStringEncryptor, i want to test if instance value stringEncryptor is set to what i've supplied in parameter as implementation? or i'm going the wrong way for testing this method?

Below is my failed attempt in a junit test method:

MyEncryptor decryptor = new MyEncryptor ();

        StringEncryptor spbe = new StandardPBEStringEncryptor();
        decryptor.setStringEncryptor(spbe);

        Field f = MyEncryptor .class.getDeclaredField("stringEncryptor");
        f.setAccessible(true);

        Assert.assertSame(f, spbe);

I want to test that stringEnctyptor is set to spbe in junit


问:
Hadoop Syntax error: word unexpected (expecting ")")
sh start-all.sh

```<code>This script is Deprecated. Instead use start-dfs.sh and start-yarn.sh
start-all.sh: 99: /home/songtian/下载/hadoop-2.6.0/sbin/../libexec/hadoop-config.sh: Syntax error: word unexpected (expecting ")")
</code>```

And I open the hadoop-config.sh,but there is no error in 99.The next content is hadoop-config and there is no error in line 99.I don't know whether I understand the error of the sh start-all.sh. What should I modify.

```<code># Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# included in all the hadoop scripts with source command
# should not be executable directly
# also should not be passed any arguments, since we need original $*

# Resolve links ($0 may be a softlink) and convert a relative path
# to an absolute path.  NB: The -P option requires bash built-ins
# or POSIX:2001 compliant cd and pwd.

#   HADOOP_CLASSPATH Extra Java CLASSPATH entries.
#
#   HADOOP_USER_CLASSPATH_FIRST      When defined, the HADOOP_CLASSPATH is
#                                    added in the beginning of the global
#                                    classpath. Can be defined, for example,
#                                    by doing
#                                    export HADOOP_USER_CLASSPATH_FIRST=true
#
#   HADOOP_USE_CLIENT_CLASSLOADER    When defined, HADOOP_CLASSPATH and the jar
#                                    as the hadoop jar argument are handled by
#                                    by a separate isolated client classloader.
#                                    If it is set, HADOOP_USER_CLASSPATH_FIRST
#                                    is ignored. Can be defined by doing
#                                    export HADOOP_USE_CLIENT_CLASSLOADER=true
#
#   HADOOP_CLIENT_CLASSLOADER_SYSTEM_CLASSES
#                                    When defined, it overrides the default
#                                    definition of system classes for the client
#                                    classloader when
#                                    HADOOP_USE_CLIENT_CLASSLOADER is enabled.
#                                    Names ending in '.' (period) are treated as
#                                    package names, and names starting with a
#                                    '-' are treated as negative matches.
#                                    For example,
#                                    export HADOOP_CLIENT_CLASSLOADER_SYSTEM_CLASSES="-org.apache.hadoop.UserClass,java.,javax.,org.apache.hadoop."

this="${BASH_SOURCE-$0}"
common_bin=$(cd -P -- "$(dirname -- "$this")" && pwd -P)
script="$(basename -- "$this")"
this="$common_bin/$script"

[ -f "$common_bin/hadoop-layout.sh" ] && . "$common_bin/hadoop-layout.sh"

HADOOP_COMMON_DIR=${HADOOP_COMMON_DIR:-"share/hadoop/common"}
HADOOP_COMMON_LIB_JARS_DIR=${HADOOP_COMMON_LIB_JARS_DIR:-"share/hadoop/common/lib"}
HADOOP_COMMON_LIB_NATIVE_DIR=${HADOOP_COMMON_LIB_NATIVE_DIR:-"lib/native"}
HDFS_DIR=${HDFS_DIR:-"share/hadoop/hdfs"}
HDFS_LIB_JARS_DIR=${HDFS_LIB_JARS_DIR:-"share/hadoop/hdfs/lib"}
YARN_DIR=${YARN_DIR:-"share/hadoop/yarn"}
YARN_LIB_JARS_DIR=${YARN_LIB_JARS_DIR:-"share/hadoop/yarn/lib"}
MAPRED_DIR=${MAPRED_DIR:-"share/hadoop/mapreduce"}
MAPRED_LIB_JARS_DIR=${MAPRED_LIB_JARS_DIR:-"share/hadoop/mapreduce/lib"}

# the root of the Hadoop installation
# See HADOOP-6255 for directory structure layout
HADOOP_DEFAULT_PREFIX=$(cd -P -- "$common_bin"/.. && pwd -P)
HADOOP_PREFIX=${HADOOP_PREFIX:-$HADOOP_DEFAULT_PREFIX}
export HADOOP_PREFIX

#check to see if the conf dir is given as an optional argument
if [ $# -gt 1 ]
then
    if [ "--config" = "$1" ]
      then
          shift
          confdir=$1
          if [ ! -d "$confdir" ]; then
                echo "Error: Cannot find configuration directory: $confdir"
                exit 1
             fi
          shift
          HADOOP_CONF_DIR=$confdir
    fi
fi

# Allow alternate conf dir location.
if [ -e "${HADOOP_PREFIX}/conf/hadoop-env.sh" ]; then
  DEFAULT_CONF_DIR="conf"
else
  DEFAULT_CONF_DIR="etc/hadoop"
fi

export HADOOP_CONF_DIR="${HADOOP_CONF_DIR:-$HADOOP_PREFIX/$DEFAULT_CONF_DIR}"

# User can specify hostnames or a file where the hostnames are (not both)
if [[("$HADOOP_SLAVES"!='')&&("$HADOOP_SLAVE_NAMES"!='')]]; then
  echo \
    "Error: Please specify one variable HADOOP_SLAVES or " \
    "HADOOP_SLAVE_NAME and not both."
  exit 1
fi

# Process command line options that specify hosts or file with host
# list
if [ $# -gt 1 ]
then
    if [ "--hosts" = "$1" ]
    then
        shift
        export HADOOP_SLAVES="${HADOOP_CONF_DIR}/$1"
        shift
    elif [ "--hostnames" = "$1" ]
    then
        shift
        export HADOOP_SLAVE_NAMES=$1
        shift
    fi
fi

# User can specify hostnames or a file where the hostnames are (not both)
# (same check as above but now we know it's command line options that cause
# the problem)
if [[("$HADOOP_SLAVES"!='')&&("$HADOOP_SLAVE_NAMES"!='')]]; then
  echo \
    "Error: Please specify one of --hosts or --hostnames options and not both."
  exit 1
fi

if [ -f "${HADOOP_CONF_DIR}/hadoop-env.sh" ]; then
  . "${HADOOP_CONF_DIR}/hadoop-env.sh"
fi

# check if net.ipv6.bindv6only is set to 1
bindv6only=$(/sbin/sysctl -n net.ipv6.bindv6only 2> /dev/null)
if [ -n "$bindv6only" ] && [ "$bindv6only" -eq "1" ] && [ "$HADOOP_ALLOW_IPV6" != "yes" ]
then
  echo "Error: \"net.ipv6.bindv6only\" is set to 1 - Java networking could be broken"
  echo "For more info: http://wiki.apache.org/hadoop/HadoopIPv6"
  exit 1
fi

# Newer versions of glibc use an arena memory allocator that causes virtual
# memory usage to explode. This interacts badly with the many threads that
# we use in Hadoop. Tune the variable down to prevent vmem explosion.
export MALLOC_ARENA_MAX=${MALLOC_ARENA_MAX:-4}

# Attempt to set JAVA_HOME if it is not set
if [[ -z $JAVA_HOME ]]; then
  # On OSX use java_home (or /Library for older versions)
  if [ "Darwin" == "$(uname -s)" ]; then
    if [ -x /usr/libexec/java_home ]; then
      export JAVA_HOME=($(/usr/libexec/java_home))
    else
      export JAVA_HOME=(/Library/Java/Home)
    fi
  fi

  # Bail if we did not detect it
  if [[ -z $JAVA_HOME ]]; then
    echo "Error: JAVA_HOME is not set and could not be found." 1>&2
    exit 1
  fi
fi

JAVA=$JAVA_HOME/bin/java
# some Java parameters
JAVA_HEAP_MAX=-Xmx1000m

# check envvars which might override default args
if [ "$HADOOP_HEAPSIZE" != "" ]; then
  #echo "run with heapsize $HADOOP_HEAPSIZE"
  JAVA_HEAP_MAX="-Xmx""$HADOOP_HEAPSIZE""m"
  #echo $JAVA_HEAP_MAX
fi

# CLASSPATH initially contains $HADOOP_CONF_DIR
CLASSPATH="${HADOOP_CONF_DIR}"

# so that filenames w/ spaces are handled correctly in loops below
IFS=

if [ "$HADOOP_COMMON_HOME" = "" ]; then
  if [ -d "${HADOOP_PREFIX}/$HADOOP_COMMON_DIR" ]; then
    export HADOOP_COMMON_HOME=$HADOOP_PREFIX
  fi
fi

# for releases, add core hadoop jar & webapps to CLASSPATH
if [ -d "$HADOOP_COMMON_HOME/$HADOOP_COMMON_DIR/webapps" ]; then
  CLASSPATH=${CLASSPATH}:$HADOOP_COMMON_HOME/$HADOOP_COMMON_DIR
fi

if [ -d "$HADOOP_COMMON_HOME/$HADOOP_COMMON_LIB_JARS_DIR" ]; then
  CLASSPATH=${CLASSPATH}:$HADOOP_COMMON_HOME/$HADOOP_COMMON_LIB_JARS_DIR'/*'
fi

CLASSPATH=${CLASSPATH}:$HADOOP_COMMON_HOME/$HADOOP_COMMON_DIR'/*'

# default log directory & file
if [ "$HADOOP_LOG_DIR" = "" ]; then
  HADOOP_LOG_DIR="$HADOOP_PREFIX/logs"
fi
if [ "$HADOOP_LOGFILE" = "" ]; then
  HADOOP_LOGFILE='hadoop.log'
fi

# default policy file for service-level authorization
if [ "$HADOOP_POLICYFILE" = "" ]; then
  HADOOP_POLICYFILE="hadoop-policy.xml"
fi

# restore ordinary behaviour
unset IFS

# setup 'java.library.path' for native-hadoop code if necessary

if [ -d "${HADOOP_PREFIX}/build/native" -o -d "${HADOOP_PREFIX}/$HADOOP_COMMON_LIB_NATIVE_DIR" ]; then

  if [ -d "${HADOOP_PREFIX}/$HADOOP_COMMON_LIB_NATIVE_DIR" ]; then
    if [ "x$JAVA_LIBRARY_PATH" != "x" ]; then
      JAVA_LIBRARY_PATH=${JAVA_LIBRARY_PATH}:${HADOOP_PREFIX}/$HADOOP_COMMON_LIB_NATIVE_DIR
    else
      JAVA_LIBRARY_PATH=${HADOOP_PREFIX}/$HADOOP_COMMON_LIB_NATIVE_DIR
    fi
  fi
fi

# setup a default TOOL_PATH
TOOL_PATH="${TOOL_PATH:-$HADOOP_PREFIX/share/hadoop/tools/lib/*}"

HADOOP_OPTS="$HADOOP_OPTS -Dhadoop.log.dir=$HADOOP_LOG_DIR"
HADOOP_OPTS="$HADOOP_OPTS -Dhadoop.log.file=$HADOOP_LOGFILE"
HADOOP_OPTS="$HADOOP_OPTS -Dhadoop.home.dir=$HADOOP_PREFIX"
HADOOP_OPTS="$HADOOP_OPTS -Dhadoop.id.str=$HADOOP_IDENT_STRING"
HADOOP_OPTS="$HADOOP_OPTS -Dhadoop.root.logger=${HADOOP_ROOT_LOGGER:-INFO,console}"
if [ "x$JAVA_LIBRARY_PATH" != "x" ]; then
  HADOOP_OPTS="$HADOOP_OPTS -Djava.library.path=$JAVA_LIBRARY_PATH"
  export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$JAVA_LIBRARY_PATH
fi
HADOOP_OPTS="$HADOOP_OPTS -Dhadoop.policy.file=$HADOOP_POLICYFILE"

# Disable ipv6 as it can cause issues
HADOOP_OPTS="$HADOOP_OPTS -Djava.net.preferIPv4Stack=true"

# put hdfs in classpath if present
if [ "$HADOOP_HDFS_HOME" = "" ]; then
  if [ -d "${HADOOP_PREFIX}/$HDFS_DIR" ]; then
    export HADOOP_HDFS_HOME=$HADOOP_PREFIX
  fi
fi

if [ -d "$HADOOP_HDFS_HOME/$HDFS_DIR/webapps" ]; then
  CLASSPATH=${CLASSPATH}:$HADOOP_HDFS_HOME/$HDFS_DIR
fi

if [ -d "$HADOOP_HDFS_HOME/$HDFS_LIB_JARS_DIR" ]; then
  CLASSPATH=${CLASSPATH}:$HADOOP_HDFS_HOME/$HDFS_LIB_JARS_DIR'/*'
fi

CLASSPATH=${CLASSPATH}:$HADOOP_HDFS_HOME/$HDFS_DIR'/*'

# put yarn in classpath if present
if [ "$HADOOP_YARN_HOME" = "" ]; then
  if [ -d "${HADOOP_PREFIX}/$YARN_DIR" ]; then
    export HADOOP_YARN_HOME=$HADOOP_PREFIX
  fi
fi

if [ -d "$HADOOP_YARN_HOME/$YARN_DIR/webapps" ]; then
  CLASSPATH=${CLASSPATH}:$HADOOP_YARN_HOME/$YARN_DIR
fi

if [ -d "$HADOOP_YARN_HOME/$YARN_LIB_JARS_DIR" ]; then
  CLASSPATH=${CLASSPATH}:$HADOOP_YARN_HOME/$YARN_LIB_JARS_DIR'/*'
fi

CLASSPATH=${CLASSPATH}:$HADOOP_YARN_HOME/$YARN_DIR'/*'

# put mapred in classpath if present AND different from YARN
if [ "$HADOOP_MAPRED_HOME" = "" ]; then
  if [ -d "${HADOOP_PREFIX}/$MAPRED_DIR" ]; then
    export HADOOP_MAPRED_HOME=$HADOOP_PREFIX
  fi
fi

if [ "$HADOOP_MAPRED_HOME/$MAPRED_DIR" != "$HADOOP_YARN_HOME/$YARN_DIR" ] ; then
  if [ -d "$HADOOP_MAPRED_HOME/$MAPRED_DIR/webapps" ]; then
    CLASSPATH=${CLASSPATH}:$HADOOP_MAPRED_HOME/$MAPRED_DIR
  fi

  if [ -d "$HADOOP_MAPRED_HOME/$MAPRED_LIB_JARS_DIR" ]; then
    CLASSPATH=${CLASSPATH}:$HADOOP_MAPRED_HOME/$MAPRED_LIB_JARS_DIR'/*'
  fi

  CLASSPATH=${CLASSPATH}:$HADOOP_MAPRED_HOME/$MAPRED_DIR'/*'
fi

# Add the user-specified CLASSPATH via HADOOP_CLASSPATH
# Add it first or last depending on if user has
# set env-var HADOOP_USER_CLASSPATH_FIRST
# if the user set HADOOP_USE_CLIENT_CLASSLOADER, HADOOP_CLASSPATH is not added
# to the classpath
if [[("$HADOOP_CLASSPATH"!="")&&("$HADOOP_USE_CLIENT_CLASSLOADER"="")]]; then
  # Prefix it if its to be preceded
  if [ "$HADOOP_USER_CLASSPATH_FIRST" != "" ]; then
    CLASSPATH=${HADOOP_CLASSPATH}:${CLASSPATH}
  else
    CLASSPATH=${CLASSPATH}:${HADOOP_CLASSPATH}
  fi
fi
</code>```

答: I solve it.I think I should install English Ubuntu 16.04 and then I reinstall Java and Hadoop.Then the hadoop works,so amazing!</p>

Body:
sh start-all.sh

This script is Deprecated. Instead use start-dfs.sh and start-yarn.sh
start-all.sh: 99: /home/songtian/下载/hadoop-2.6.0/sbin/../libexec/hadoop-config.sh: Syntax error: word unexpected (expecting ")")

And I open the hadoop-config.sh,but there is no error in 99.The next content is hadoop-config and there is no error in line 99.I don't know whether I understand the error of the sh start-all.sh. What should I modify.

# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# included in all the hadoop scripts with source command
# should not be executable directly
# also should not be passed any arguments, since we need original $*

# Resolve links ($0 may be a softlink) and convert a relative path
# to an absolute path.  NB: The -P option requires bash built-ins
# or POSIX:2001 compliant cd and pwd.

#   HADOOP_CLASSPATH Extra Java CLASSPATH entries.
#
#   HADOOP_USER_CLASSPATH_FIRST      When defined, the HADOOP_CLASSPATH is
#                                    added in the beginning of the global
#                                    classpath. Can be defined, for example,
#                                    by doing
#                                    export HADOOP_USER_CLASSPATH_FIRST=true
#
#   HADOOP_USE_CLIENT_CLASSLOADER    When defined, HADOOP_CLASSPATH and the jar
#                                    as the hadoop jar argument are handled by
#                                    by a separate isolated client classloader.
#                                    If it is set, HADOOP_USER_CLASSPATH_FIRST
#                                    is ignored. Can be defined by doing
#                                    export HADOOP_USE_CLIENT_CLASSLOADER=true
#
#   HADOOP_CLIENT_CLASSLOADER_SYSTEM_CLASSES
#                                    When defined, it overrides the default
#                                    definition of system classes for the client
#                                    classloader when
#                                    HADOOP_USE_CLIENT_CLASSLOADER is enabled.
#                                    Names ending in '.' (period) are treated as
#                                    package names, and names starting with a
#                                    '-' are treated as negative matches.
#                                    For example,
#                                    export HADOOP_CLIENT_CLASSLOADER_SYSTEM_CLASSES="-org.apache.hadoop.UserClass,java.,javax.,org.apache.hadoop."

this="${BASH_SOURCE-$0}"
common_bin=$(cd -P -- "$(dirname -- "$this")" && pwd -P)
script="$(basename -- "$this")"
this="$common_bin/$script"

[ -f "$common_bin/hadoop-layout.sh" ] && . "$common_bin/hadoop-layout.sh"

HADOOP_COMMON_DIR=${HADOOP_COMMON_DIR:-"share/hadoop/common"}
HADOOP_COMMON_LIB_JARS_DIR=${HADOOP_COMMON_LIB_JARS_DIR:-"share/hadoop/common/lib"}
HADOOP_COMMON_LIB_NATIVE_DIR=${HADOOP_COMMON_LIB_NATIVE_DIR:-"lib/native"}
HDFS_DIR=${HDFS_DIR:-"share/hadoop/hdfs"}
HDFS_LIB_JARS_DIR=${HDFS_LIB_JARS_DIR:-"share/hadoop/hdfs/lib"}
YARN_DIR=${YARN_DIR:-"share/hadoop/yarn"}
YARN_LIB_JARS_DIR=${YARN_LIB_JARS_DIR:-"share/hadoop/yarn/lib"}
MAPRED_DIR=${MAPRED_DIR:-"share/hadoop/mapreduce"}
MAPRED_LIB_JARS_DIR=${MAPRED_LIB_JARS_DIR:-"share/hadoop/mapreduce/lib"}

# the root of the Hadoop installation
# See HADOOP-6255 for directory structure layout
HADOOP_DEFAULT_PREFIX=$(cd -P -- "$common_bin"/.. && pwd -P)
HADOOP_PREFIX=${HADOOP_PREFIX:-$HADOOP_DEFAULT_PREFIX}
export HADOOP_PREFIX

#check to see if the conf dir is given as an optional argument
if [ $# -gt 1 ]
then
    if [ "--config" = "$1" ]
      then
          shift
          confdir=$1
          if [ ! -d "$confdir" ]; then
                echo "Error: Cannot find configuration directory: $confdir"
                exit 1
             fi
          shift
          HADOOP_CONF_DIR=$confdir
    fi
fi

# Allow alternate conf dir location.
if [ -e "${HADOOP_PREFIX}/conf/hadoop-env.sh" ]; then
  DEFAULT_CONF_DIR="conf"
else
  DEFAULT_CONF_DIR="etc/hadoop"
fi

export HADOOP_CONF_DIR="${HADOOP_CONF_DIR:-$HADOOP_PREFIX/$DEFAULT_CONF_DIR}"

# User can specify hostnames or a file where the hostnames are (not both)
if [[("$HADOOP_SLAVES"!='')&&("$HADOOP_SLAVE_NAMES"!='')]]; then
  echo \
    "Error: Please specify one variable HADOOP_SLAVES or " \
    "HADOOP_SLAVE_NAME and not both."
  exit 1
fi

# Process command line options that specify hosts or file with host
# list
if [ $# -gt 1 ]
then
    if [ "--hosts" = "$1" ]
    then
        shift
        export HADOOP_SLAVES="${HADOOP_CONF_DIR}/$1"
        shift
    elif [ "--hostnames" = "$1" ]
    then
        shift
        export HADOOP_SLAVE_NAMES=$1
        shift
    fi
fi

# User can specify hostnames or a file where the hostnames are (not both)
# (same check as above but now we know it's command line options that cause
# the problem)
if [[("$HADOOP_SLAVES"!='')&&("$HADOOP_SLAVE_NAMES"!='')]]; then
  echo \
    "Error: Please specify one of --hosts or --hostnames options and not both."
  exit 1
fi

if [ -f "${HADOOP_CONF_DIR}/hadoop-env.sh" ]; then
  . "${HADOOP_CONF_DIR}/hadoop-env.sh"
fi

# check if net.ipv6.bindv6only is set to 1
bindv6only=$(/sbin/sysctl -n net.ipv6.bindv6only 2> /dev/null)
if [ -n "$bindv6only" ] && [ "$bindv6only" -eq "1" ] && [ "$HADOOP_ALLOW_IPV6" != "yes" ]
then
  echo "Error: \"net.ipv6.bindv6only\" is set to 1 - Java networking could be broken"
  echo "For more info: http://wiki.apache.org/hadoop/HadoopIPv6"
  exit 1
fi

# Newer versions of glibc use an arena memory allocator that causes virtual
# memory usage to explode. This interacts badly with the many threads that
# we use in Hadoop. Tune the variable down to prevent vmem explosion.
export MALLOC_ARENA_MAX=${MALLOC_ARENA_MAX:-4}

# Attempt to set JAVA_HOME if it is not set
if [[ -z $JAVA_HOME ]]; then
  # On OSX use java_home (or /Library for older versions)
  if [ "Darwin" == "$(uname -s)" ]; then
    if [ -x /usr/libexec/java_home ]; then
      export JAVA_HOME=($(/usr/libexec/java_home))
    else
      export JAVA_HOME=(/Library/Java/Home)
    fi
  fi

  # Bail if we did not detect it
  if [[ -z $JAVA_HOME ]]; then
    echo "Error: JAVA_HOME is not set and could not be found." 1>&2
    exit 1
  fi
fi

JAVA=$JAVA_HOME/bin/java
# some Java parameters
JAVA_HEAP_MAX=-Xmx1000m

# check envvars which might override default args
if [ "$HADOOP_HEAPSIZE" != "" ]; then
  #echo "run with heapsize $HADOOP_HEAPSIZE"
  JAVA_HEAP_MAX="-Xmx""$HADOOP_HEAPSIZE""m"
  #echo $JAVA_HEAP_MAX
fi

# CLASSPATH initially contains $HADOOP_CONF_DIR
CLASSPATH="${HADOOP_CONF_DIR}"

# so that filenames w/ spaces are handled correctly in loops below
IFS=

if [ "$HADOOP_COMMON_HOME" = "" ]; then
  if [ -d "${HADOOP_PREFIX}/$HADOOP_COMMON_DIR" ]; then
    export HADOOP_COMMON_HOME=$HADOOP_PREFIX
  fi
fi

# for releases, add core hadoop jar & webapps to CLASSPATH
if [ -d "$HADOOP_COMMON_HOME/$HADOOP_COMMON_DIR/webapps" ]; then
  CLASSPATH=${CLASSPATH}:$HADOOP_COMMON_HOME/$HADOOP_COMMON_DIR
fi

if [ -d "$HADOOP_COMMON_HOME/$HADOOP_COMMON_LIB_JARS_DIR" ]; then
  CLASSPATH=${CLASSPATH}:$HADOOP_COMMON_HOME/$HADOOP_COMMON_LIB_JARS_DIR'/*'
fi

CLASSPATH=${CLASSPATH}:$HADOOP_COMMON_HOME/$HADOOP_COMMON_DIR'/*'

# default log directory & file
if [ "$HADOOP_LOG_DIR" = "" ]; then
  HADOOP_LOG_DIR="$HADOOP_PREFIX/logs"
fi
if [ "$HADOOP_LOGFILE" = "" ]; then
  HADOOP_LOGFILE='hadoop.log'
fi

# default policy file for service-level authorization
if [ "$HADOOP_POLICYFILE" = "" ]; then
  HADOOP_POLICYFILE="hadoop-policy.xml"
fi

# restore ordinary behaviour
unset IFS

# setup 'java.library.path' for native-hadoop code if necessary

if [ -d "${HADOOP_PREFIX}/build/native" -o -d "${HADOOP_PREFIX}/$HADOOP_COMMON_LIB_NATIVE_DIR" ]; then

  if [ -d "${HADOOP_PREFIX}/$HADOOP_COMMON_LIB_NATIVE_DIR" ]; then
    if [ "x$JAVA_LIBRARY_PATH" != "x" ]; then
      JAVA_LIBRARY_PATH=${JAVA_LIBRARY_PATH}:${HADOOP_PREFIX}/$HADOOP_COMMON_LIB_NATIVE_DIR
    else
      JAVA_LIBRARY_PATH=${HADOOP_PREFIX}/$HADOOP_COMMON_LIB_NATIVE_DIR
    fi
  fi
fi

# setup a default TOOL_PATH
TOOL_PATH="${TOOL_PATH:-$HADOOP_PREFIX/share/hadoop/tools/lib/*}"

HADOOP_OPTS="$HADOOP_OPTS -Dhadoop.log.dir=$HADOOP_LOG_DIR"
HADOOP_OPTS="$HADOOP_OPTS -Dhadoop.log.file=$HADOOP_LOGFILE"
HADOOP_OPTS="$HADOOP_OPTS -Dhadoop.home.dir=$HADOOP_PREFIX"
HADOOP_OPTS="$HADOOP_OPTS -Dhadoop.id.str=$HADOOP_IDENT_STRING"
HADOOP_OPTS="$HADOOP_OPTS -Dhadoop.root.logger=${HADOOP_ROOT_LOGGER:-INFO,console}"
if [ "x$JAVA_LIBRARY_PATH" != "x" ]; then
  HADOOP_OPTS="$HADOOP_OPTS -Djava.library.path=$JAVA_LIBRARY_PATH"
  export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$JAVA_LIBRARY_PATH
fi
HADOOP_OPTS="$HADOOP_OPTS -Dhadoop.policy.file=$HADOOP_POLICYFILE"

# Disable ipv6 as it can cause issues
HADOOP_OPTS="$HADOOP_OPTS -Djava.net.preferIPv4Stack=true"

# put hdfs in classpath if present
if [ "$HADOOP_HDFS_HOME" = "" ]; then
  if [ -d "${HADOOP_PREFIX}/$HDFS_DIR" ]; then
    export HADOOP_HDFS_HOME=$HADOOP_PREFIX
  fi
fi

if [ -d "$HADOOP_HDFS_HOME/$HDFS_DIR/webapps" ]; then
  CLASSPATH=${CLASSPATH}:$HADOOP_HDFS_HOME/$HDFS_DIR
fi

if [ -d "$HADOOP_HDFS_HOME/$HDFS_LIB_JARS_DIR" ]; then
  CLASSPATH=${CLASSPATH}:$HADOOP_HDFS_HOME/$HDFS_LIB_JARS_DIR'/*'
fi

CLASSPATH=${CLASSPATH}:$HADOOP_HDFS_HOME/$HDFS_DIR'/*'

# put yarn in classpath if present
if [ "$HADOOP_YARN_HOME" = "" ]; then
  if [ -d "${HADOOP_PREFIX}/$YARN_DIR" ]; then
    export HADOOP_YARN_HOME=$HADOOP_PREFIX
  fi
fi

if [ -d "$HADOOP_YARN_HOME/$YARN_DIR/webapps" ]; then
  CLASSPATH=${CLASSPATH}:$HADOOP_YARN_HOME/$YARN_DIR
fi

if [ -d "$HADOOP_YARN_HOME/$YARN_LIB_JARS_DIR" ]; then
  CLASSPATH=${CLASSPATH}:$HADOOP_YARN_HOME/$YARN_LIB_JARS_DIR'/*'
fi

CLASSPATH=${CLASSPATH}:$HADOOP_YARN_HOME/$YARN_DIR'/*'

# put mapred in classpath if present AND different from YARN
if [ "$HADOOP_MAPRED_HOME" = "" ]; then
  if [ -d "${HADOOP_PREFIX}/$MAPRED_DIR" ]; then
    export HADOOP_MAPRED_HOME=$HADOOP_PREFIX
  fi
fi

if [ "$HADOOP_MAPRED_HOME/$MAPRED_DIR" != "$HADOOP_YARN_HOME/$YARN_DIR" ] ; then
  if [ -d "$HADOOP_MAPRED_HOME/$MAPRED_DIR/webapps" ]; then
    CLASSPATH=${CLASSPATH}:$HADOOP_MAPRED_HOME/$MAPRED_DIR
  fi

  if [ -d "$HADOOP_MAPRED_HOME/$MAPRED_LIB_JARS_DIR" ]; then
    CLASSPATH=${CLASSPATH}:$HADOOP_MAPRED_HOME/$MAPRED_LIB_JARS_DIR'/*'
  fi

  CLASSPATH=${CLASSPATH}:$HADOOP_MAPRED_HOME/$MAPRED_DIR'/*'
fi

# Add the user-specified CLASSPATH via HADOOP_CLASSPATH
# Add it first or last depending on if user has
# set env-var HADOOP_USER_CLASSPATH_FIRST
# if the user set HADOOP_USE_CLIENT_CLASSLOADER, HADOOP_CLASSPATH is not added
# to the classpath
if [[("$HADOOP_CLASSPATH"!="")&&("$HADOOP_USE_CLIENT_CLASSLOADER"="")]]; then
  # Prefix it if its to be preceded
  if [ "$HADOOP_USER_CLASSPATH_FIRST" != "" ]; then
    CLASSPATH=${HADOOP_CLASSPATH}:${CLASSPATH}
  else
    CLASSPATH=${CLASSPATH}:${HADOOP_CLASSPATH}
  fi
fi


问:
PHP - Do (and echo) operation only when remainder from is 0 - Going into infinite loop
Let me start by the end and the actual question:

I'm trying to write a PHP script that from two random numbers $x and $y will only we outputted and resolved when modulo == 0 (it should always echo a valid function)

What do I mean:

The script echos:

4 / 2 => GOOD!

The script echos:

4 / 3 => BAD!

NOTHING => BAD!

I'll try to guide you through my reasoning but be warned:

I'm a newbie so: I learn something, up the ante, and try to apply it conveniently.

First I generate the random numbers, easy:

```<code>$x = mt_rand(1,10);
$y = mt_rand(1,10);
</code>```

Now I say, I have two possibilities after division, remainder 0 or not 0, so an if() statement looks like a good idea, so I do:

if($x % $y == 0){

echo $x . "/" . $y;

}else{

echo "The remainder is not 0";

}

This works as expected except of course, I always want to generate this remainder is not 0 divisions.

So my approach was the following, why not use user generated functions (never used the before but could come in handy) so, if I know this works just fine:

```<code><?php

function hello(){
      echo "Hello!";
}

hello();
?>
</code>```

Why not up the ante as I said before and use it, so I mix the up:

```<code><?php
$x = mt_rand(1,10);
$y = mt_rand(1,10);

function foo(){

if($x % $y == 0){

echo $x . "/" . $y;

}else{

foo();

}

}

?>
</code>```

It doesn't work, I get a blank screen.

What was I expecting from this script:

Create a function with an if() statement on it

If the remainder is 0, great, echo.

else, start all over, again and again, till you get a division with no remainder.

This does't work.

So I basically ask, what I am doing wrong? What is wrong with the line of though behind this?

Can this work with a subtle change?

To experienced coders, I know you could all make a script that does this (but has nothing to do with mine) using MS PAINT as an IDE, BUT:

I have no interest in the code itself since this is ONLY for learning purposes.

This is not the first time it has happened to me, I keep hitting the wall with infinite loops VERY often, so the slighter the change (and the bigger the explanation) the better, and will be very much appreciated.

Thanks in advance!

Now that finish I've just realized the problem might not even be a infinite loop, even if it's not the question still stands, what do you think think of my approach? (of course I will also edit and remove the infinite loop from the question)

答:
Your problem is that you're not redeclaring $x and $y. Hypothetically, this should go into infinite recursion. If you want to do this recursively, you're going to have to define $x and $y in your foo() function. Make sure the variables are declared outside and before your if() statement.

Good luck!

Dennis M.

Body:
Let me start by the end and the actual question:

I'm trying to write a PHP script that from two random numbers $x and $y will only we outputted and resolved when modulo == 0 (it should always echo a valid function)

What do I mean:

The script echos:

4 / 2 => GOOD!

The script echos:

4 / 3 => BAD!

NOTHING => BAD!

I'll try to guide you through my reasoning but be warned:

I'm a newbie so: I learn something, up the ante, and try to apply it conveniently.

First I generate the random numbers, easy:

$x = mt_rand(1,10);
$y = mt_rand(1,10);

Now I say, I have two possibilities after division, remainder 0 or not 0, so an if() statement looks like a good idea, so I do:

if($x % $y == 0){

echo $x . "/" . $y;

}else{

echo "The remainder is not 0";

}

This works as expected except of course, I always want to generate this remainder is not 0 divisions.

So my approach was the following, why not use user generated functions (never used the before but could come in handy) so, if I know this works just fine:

<?php

function hello(){
      echo "Hello!";
}

hello();
?>

Why not up the ante as I said before and use it, so I mix the up:

<?php
$x = mt_rand(1,10);
$y = mt_rand(1,10);

function foo(){

if($x % $y == 0){

echo $x . "/" . $y;

}else{

foo();

}

}

?>

It doesn't work, I get a blank screen.

What was I expecting from this script:

Create a function with an if() statement on it

If the remainder is 0, great, echo.

else, start all over, again and again, till you get a division with no remainder.

This does't work.

So I basically ask, what I am doing wrong? What is wrong with the line of though behind this?

Can this work with a subtle change?

To experienced coders, I know you could all make a script that does this (but has nothing to do with mine) using MS PAINT as an IDE, BUT:

I have no interest in the code itself since this is ONLY for learning purposes.

This is not the first time it has happened to me, I keep hitting the wall with infinite loops VERY often, so the slighter the change (and the bigger the explanation) the better, and will be very much appreciated.

Thanks in advance!

Now that finish I've just realized the problem might not even be a infinite loop, even if it's not the question still stands, what do you think think of my approach? (of course I will also edit and remove the infinite loop from the question)


问:
Symfony 2 - disable translations on certain paths/routes
I would like to disable translations or force using english ones for paths which starts with /admin.

Is there a way to approach it in config?

If not what would be the best practice? EventListener checking routes and forcing english translation no matter the locale set in request?

答:
I think the EventListener approach is the most comfortable: http://symfony.com/doc/current/translation/locale.html

Set the locale within Request object. Hint: you can check a route name using _route attribute instead of checking an absolute URL.


问:
Disable PM2 logging(.pm2/pm2.log NOT .pm2/logs)
I have to run a process with PM2 on a device with very limited disk space, so I need to disable all logging otherwise the device will run out of space after several days.

I'm using:

```<code>"out_file": "/dev/null",
"error_file": "/dev/null"
</code>```

It stops PM2 from creating logs for the process. However, PM2 still creates another log file in .pm2/pm2.log

The size of pm2.log can grow up to 9Mb, which is large for the device.
Is there any way to stop PM2 from creating pm2.log? Or at least some way to clean the log file automatically.

答:
I open an issue at https://github.com/Unitech/pm2/issues/2921

Turns out that pm2.log cannot be disabled in current version of PM2(2.4.6), but the maintainer of PM2 said that this feature will be added in future update.

For now, I'm using the following code to clean log files:

var cmd_flush ='pm2 flush';
var exec = require('child_process').exec;
exec(cmd_flush ,function(error){
        debugLog('error: ' + error);
});
```

It's slow, but at least it works.

Body:
I have to run a process with PM2 on a device with very limited disk space, so I need to disable all logging otherwise the device will run out of space after several days.

I'm using:

"out_file": "/dev/null",
"error_file": "/dev/null"

It stops PM2 from creating logs for the process. However, PM2 still creates another log file in .pm2/pm2.log

The size of pm2.log can grow up to 9Mb, which is large for the device.
Is there any way to stop PM2 from creating pm2.log? Or at least some way to clean the log file automatically.

Body:
I open an issue at https://github.com/Unitech/pm2/issues/2921

Turns out that pm2.log cannot be disabled in current version of PM2(2.4.6), but the maintainer of PM2 said that this feature will be added in future update.

For now, I'm using the following code to clean log files:

var cmd_flush ='pm2 flush';
var exec = require('child_process').exec;
exec(cmd_flush ,function(error){
        debugLog('error: ' + error);
});

It's slow, but at least it works.


问:
rendering alternate components under the same flow:router URL
How can I render two different views in a one page app without changing URLs. I'm using meteor with the default blaze as well as the flow:router package. Right now I have it set up like this:
routes.js..

```<code>FlowRouter.route("/", {
  name: "App.home",
  action() {
    BlazeLayout.render("App_body", {
      main: "App_home",
      mainContent: "calendar"
    });
  }
});

FlowRouter.route("/list", {
  name: "App.list",
  action() {
    BlazeLayout.render("App_body", { main: "App_home", mainContent: "list" });
  }
});
</code>```

but this way I'm using the url /list and i dont want that. I would like to simply render an alternate component template in the same url. I'm very new to coding so forgive me if this is obvious. Essentially I just want two different view styles: a list and a calendar. So I would like a way to set it up so that a spacebars template can be rendered if a certain button is clicked, and a different one can be rendered instead if another button is clicked.

Thanks so much for any help, i've been at this for a couple of days :)

答:
You can handle this within a single template like so:

```<code>FlowRouter.route('/', {
  name: 'App.home',
  action() {
  BlazeLayout.render('App_body', { main: 'App_home', mainContent: 'ListOrCalendar' });
}
</code>```

And then the ListOrCalendar template would look like this:

```<code>{{#if displayList}}
  {{> List}}
{{else}}
  {{> Calendar}}
{{/if}}
<button>Switch</button>
</code>```

You would set up a ReactiveVar in the ListOrCalendar template:

```<code>Template.ListOrCalendar.onCreated(function() {
  const instance = this;
  instance.displayList = new ReactiveVar(true);
});
</code>```

See ReactiveVar explanation here (ignore Session)

Then you would have a helper which returns the value of your ReactiveVar:

```<code>Template.ListOrCalendar.helpers({
  displayList() {
    const instance = Template.instance();
    return instance.displayList.get();
  }
});
</code>```

Finally, you would hook up an event to change the value of displayList to switch between templates:

```<code>Template.ListOrCalendar.events({
  "click button"(event, instance) {
    const displayListCurrent = instance.displayList.get();
    const displayListNew = !displayListCurrent;
    instance.displayList.set(displayListNew);
    // or, more concisely, instance.displayList.set(!instance.displayList.get());
  }
});
</code>```

So, in summary:

When the template is created, your ReactiveVar is true

so your displayList returns true

so the #if displayList condition in the template is satisfied

and so the List template is displayed

When the button is clicked

The ReactiveVar is set to false

so the displayList helper returns false

so the #if displayList condition in the template is not satisfied and it goes to the else statement

and so, finally, the Calendar template is displayed

When the button is clicked again, the ReactiveVar is toggled back to true, and on we go as above

This might seem daunting or over-complicated, but there's nothing fancy going on here at all. You'll get used to it pretty quickly

Body:
How can I render two different views in a one page app without changing URLs. I'm using meteor with the default blaze as well as the flow:router package. Right now I have it set up like this:
routes.js..

FlowRouter.route("/", {
  name: "App.home",
  action() {
    BlazeLayout.render("App_body", {
      main: "App_home",
      mainContent: "calendar"
    });
  }
});

FlowRouter.route("/list", {
  name: "App.list",
  action() {
    BlazeLayout.render("App_body", { main: "App_home", mainContent: "list" });
  }
});

but this way I'm using the url /list and i dont want that. I would like to simply render an alternate component template in the same url. I'm very new to coding so forgive me if this is obvious. Essentially I just want two different view styles: a list and a calendar. So I would like a way to set it up so that a spacebars template can be rendered if a certain button is clicked, and a different one can be rendered instead if another button is clicked.

Thanks so much for any help, i've been at this for a couple of days :)

Body:
You can handle this within a single template like so:

FlowRouter.route('/', {
  name: 'App.home',
  action() {
  BlazeLayout.render('App_body', { main: 'App_home', mainContent: 'ListOrCalendar' });
}

And then the ListOrCalendar template would look like this:

{{#if displayList}}
  {{> List}}
{{else}}
  {{> Calendar}}
{{/if}}
<button>Switch</button>

You would set up a ReactiveVar in the ListOrCalendar template:

Template.ListOrCalendar.onCreated(function() {
  const instance = this;
  instance.displayList = new ReactiveVar(true);
});

See ReactiveVar explanation here (ignore Session)

Then you would have a helper which returns the value of your ReactiveVar:

Template.ListOrCalendar.helpers({
  displayList() {
    const instance = Template.instance();
    return instance.displayList.get();
  }
});

Finally, you would hook up an event to change the value of displayList to switch between templates:

Template.ListOrCalendar.events({
  "click button"(event, instance) {
    const displayListCurrent = instance.displayList.get();
    const displayListNew = !displayListCurrent;
    instance.displayList.set(displayListNew);
    // or, more concisely, instance.displayList.set(!instance.displayList.get());
  }
});

So, in summary:

When the template is created, your ReactiveVar is true

so your displayList returns true

so the #if displayList condition in the template is satisfied

and so the List template is displayed

When the button is clicked

The ReactiveVar is set to false

so the displayList helper returns false

so the #if displayList condition in the template is not satisfied and it goes to the else statement

and so, finally, the Calendar template is displayed

When the button is clicked again, the ReactiveVar is toggled back to true, and on we go as above

This might seem daunting or over-complicated, but there's nothing fancy going on here at all. You'll get used to it pretty quickly


问:
How can I select an element in jquery?
I'm a beginner in this programming language. I beg your pardon.

How can I select an element in JQuery?  What is wrong with my code? SOmeone help me.

```<code>    <!DOCTYPE html>
    <html>
         <head>
         <title></title>
         <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
         </head>
    <body>
    <input type="password">

    <script type="text/javascript">
         $(document).ready(function(){

         $('input[type=password]').attr({
              name: 'pass'
              style: [
                  color: 'blue',
                  font-size: '20px'
              ],
            });
        )};
    </script>
</code>```

答:
Looks like you meant to write:

$(document).ready(function() {
  $('input[type=password]').attr({
    name: 'pass',
    style: 'color: blue; font-size: 20px'
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="password"></code>```

Title: How can I select an element in jquery?

Body:
I'm a beginner in this programming language. I beg your pardon.

How can I select an element in JQuery?  What is wrong with my code? SOmeone help me.

    <!DOCTYPE html>

         <title></title>

    <input type="password">

Body:
Looks like you meant to write:

$(document).ready(function() {
  $('input[type=password]').attr({
    name: 'pass',
    style: 'color: blue; font-size: 20px'
  });
});

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="password">


问:
Corner cases while calculating pow(x,n)%d
I've come up with a working code for the above problem, for both positive and negative values of x. And the answers for the majority of situations is correct, however the code fails at a corner case and I can't seem to find what the issue is! What condition am I missing:`

int pow(int x, int n, int d) {
int i=0,rem=1;
long long l;
    if(x==0)
    {
        return 0;
    }
    if(x==1)
    {
        return 1;
    }
    if(n==0)
    {
        return 1;
    }
    x=x%d;
    if(n%2==0||n==0)
    {
        l = ((pow(x,n/2,d))*(pow((x),n/2,d)))%d;
    }
    else
    {
        l = ((x)*(pow(x,(n-1)/2,d))*(pow((x),(n-1)/2,d)))%d;
    }
    if(x<0 && n%2!=0)
    {
        return d+l;
    }
    else
    {
        return l;
    }
}
```

<p>`
The case at which the code gives wrong ans:</p>

```A: 71045970
B : 41535484
C : 64735492
My Output: 12942068
Actual Output:20805472
```

答:
Here is the simplified version of yours.

```<code>int pow(int x, int n, int d) {
    long long l;
    if(n==0)
    {
        return 1;
    }
    if(n%2==0)
    {
        l = (long long)pow(x,n/2,d);
        return (int)((l * l) % (long long)d);
    }
    else
    {
        //check negative value of x, and make it positive, so that negative values never come in result
        if (x < 0) {
            x += d;
        }
        return (int)(((long long)x * (long long)pow(x,n-1,d)) % (long long)d);
    }
}
</code>```

I think your code is logically correct but there exists a data overflow problem on int data type if the modulo d value is large enough.

eg. (pow(x,n/2,d))*(pow((x),n/2,d)) here two big int value multiplication can result in datatype overflow.

Body:
I've come up with a working code for the above problem, for both positive and negative values of x. And the answers for the majority of situations is correct, however the code fails at a corner case and I can't seem to find what the issue is! What condition am I missing:`

int pow(int x, int n, int d) {
int i=0,rem=1;
long long l;
    if(x==0)
    {
        return 0;
    }
    if(x==1)
    {
        return 1;
    }
    if(n==0)
    {
        return 1;
    }
    x=x%d;
    if(n%2==0||n==0)
    {
        l = ((pow(x,n/2,d))*(pow((x),n/2,d)))%d;
    }
    else
    {
        l = ((x)*(pow(x,(n-1)/2,d))*(pow((x),(n-1)/2,d)))%d;
    }
    if(x<0 && n%2!=0)
    {
        return d+l;
    }
    else
    {
        return l;
    }
}

`
The case at which the code gives wrong ans:

A: 71045970
B : 41535484
C : 64735492
My Output: 12942068
Actual Output:20805472

Body:
Here is the simplified version of yours.

int pow(int x, int n, int d) {
    long long l;
    if(n==0)
    {
        return 1;
    }
    if(n%2==0)
    {
        l = (long long)pow(x,n/2,d);
        return (int)((l * l) % (long long)d);
    }
    else
    {
        //check negative value of x, and make it positive, so that negative values never come in result
        if (x < 0) {
            x += d;
        }
        return (int)(((long long)x * (long long)pow(x,n-1,d)) % (long long)d);
    }
}

I think your code is logically correct but there exists a data overflow problem on int data type if the modulo d value is large enough.

eg. (pow(x,n/2,d))*(pow((x),n/2,d)) here two big int value multiplication can result in datatype overflow.


问:
my app working on api23 and crashed on api11
my app working on api23 and crashed on api11 or android4
i think class G causing  the crash.
in class G I've copied sqlite database on assets folder to external storage.
when i clear android:name=".G" on androidmanifest my app working on api11 but in layout click on button to read database does not read from database and crashed my app

```<code>androidmanifest is=
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="view.viramaham.quiz.viraquiz">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

<application

    android:name=".G"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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

    </activity>

    <activity android:name=".Main_soalat">

    </activity>

    <activity android:name=".pasokhnameh">

    </activity>

  </application>
 </manifest>
</code>```

and class G  in my project is=

```<code>package view.viramaham.quiz.viraquiz;
 import android.app.Application;
 import android.content.Context;
 import android.content.Intent;
 import android.database.SQLException;
 import android.database.sqlite.SQLiteDatabase;
 import android.os.Environment;
 import android.support.v7.app.AppCompatActivity;

 import java.io.File;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;

 public   class  G extends Application {
public static Context context;
public static String SDK_DIR =      Environment.getExternalStorageDirectory().getAbsolutePath();
public static String APP_DIR = SDK_DIR + "/database/";
public static SQLiteDatabase database;

@Override
public  void onCreate() {

    super.onCreate();

    context = getApplicationContext();
    File file = new File(APP_DIR);

    if (!file.exists()) {
        try {
            file.mkdirs();
            file.createNewFile();
                copyFromAssets(getBaseContext().     getAssets()  .  open     ("viraquiz.sqlite"),
                    new FileOutputStream(APP_DIR + "/viraquiz.sqlite"));

        } catch (IOException e) {

            e.printStackTrace();
        }
    }//payandatabase

}//oncreate

public void copyFromAssets(InputStream inputStream, OutputStream   outputStream) {

    byte[] buffer = new byte[1024];
    int length;
    try {
        while ((length = inputStream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, length);

        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        inputStream.close();
        outputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}//payan copyFromAssets

}
</code>```

答:
api 11 the first check class G. my class have a eror.i change the class G and working my program on all api.
class G is=

```<code>  package view.viramaham.quiz.viraquiz;
 import android.app.Application;
 import android.content.Context;
 import android.content.Intent;
 import android.database.SQLException;
 import android.database.sqlite.SQLiteDatabase;
 import android.os.Environment;
 import android.support.v7.app.AppCompatActivity;

 import java.io.File;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;

 public   class  G extends Application {
public static Context context;
public static String SDK_DIR =   Environment.getExternalStorageDirectory().getAbsolutePath();
public static String APP_DIR = SDK_DIR + "/database/";
public static SQLiteDatabase database;

@Override
public  void onCreate() {

    super.onCreate();

    context = getApplicationContext();
    File file = new File(APP_DIR);

    if (!file.exists()) {
        try {
            file.mkdirs();
            file.createNewFile();
            copyFromAssets(getBaseContext().getAssets().open("viraquiz.sqlite"),
                    new FileOutputStream(APP_DIR + "/viraquiz.sqlite"));

        } catch (IOException e) {

            e.printStackTrace();
        }
    }//payandatabase

}//oncreate

public void copyFromAssets(InputStream inputStream, OutputStream  outputStream) {

    byte[] buffer = new byte[1024];
    int length;
    try {
        while ((length = inputStream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, length);

        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        inputStream.close();
        outputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}//payan copyFromAssets
</code>```

}

Body:
my app working on api23 and crashed on api11 or android4
i think class G causing  the crash.
in class G I've copied sqlite database on assets folder to external storage.
when i clear android:name=".G" on androidmanifest my app working on api11 but in layout click on button to read database does not read from database and crashed my app

androidmanifest is=
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="view.viramaham.quiz.viraquiz">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

<application

    android:name=".G"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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

    </activity>

    <activity android:name=".Main_soalat">

    </activity>

    <activity android:name=".pasokhnameh">

    </activity>

  </application>
 </manifest>

and class G  in my project is=

package view.viramaham.quiz.viraquiz;
 import android.app.Application;
 import android.content.Context;
 import android.content.Intent;
 import android.database.SQLException;
 import android.database.sqlite.SQLiteDatabase;
 import android.os.Environment;
 import android.support.v7.app.AppCompatActivity;

 import java.io.File;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;

 public   class  G extends Application {
public static Context context;
public static String SDK_DIR =      Environment.getExternalStorageDirectory().getAbsolutePath();
public static String APP_DIR = SDK_DIR + "/database/";
public static SQLiteDatabase database;

@Override
public  void onCreate() {

    super.onCreate();

    context = getApplicationContext();
    File file = new File(APP_DIR);

    if (!file.exists()) {
        try {
            file.mkdirs();
            file.createNewFile();
                copyFromAssets(getBaseContext().     getAssets()  .  open     ("viraquiz.sqlite"),
                    new FileOutputStream(APP_DIR + "/viraquiz.sqlite"));

        } catch (IOException e) {

            e.printStackTrace();
        }
    }//payandatabase

}//oncreate

public void copyFromAssets(InputStream inputStream, OutputStream   outputStream) {

    byte[] buffer = new byte[1024];
    int length;
    try {
        while ((length = inputStream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, length);

        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        inputStream.close();
        outputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}//payan copyFromAssets

}

Body:
api 11 the first check class G. my class have a eror.i change the class G and working my program on all api.
class G is=

  package view.viramaham.quiz.viraquiz;
 import android.app.Application;
 import android.content.Context;
 import android.content.Intent;
 import android.database.SQLException;
 import android.database.sqlite.SQLiteDatabase;
 import android.os.Environment;
 import android.support.v7.app.AppCompatActivity;

 import java.io.File;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;

 public   class  G extends Application {
public static Context context;
public static String SDK_DIR =   Environment.getExternalStorageDirectory().getAbsolutePath();
public static String APP_DIR = SDK_DIR + "/database/";
public static SQLiteDatabase database;

@Override
public  void onCreate() {

    super.onCreate();

    context = getApplicationContext();
    File file = new File(APP_DIR);

    if (!file.exists()) {
        try {
            file.mkdirs();
            file.createNewFile();
            copyFromAssets(getBaseContext().getAssets().open("viraquiz.sqlite"),
                    new FileOutputStream(APP_DIR + "/viraquiz.sqlite"));

        } catch (IOException e) {

            e.printStackTrace();
        }
    }//payandatabase

}//oncreate

public void copyFromAssets(InputStream inputStream, OutputStream  outputStream) {

    byte[] buffer = new byte[1024];
    int length;
    try {
        while ((length = inputStream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, length);

        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        inputStream.close();
        outputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}//payan copyFromAssets

}