问:
400 status code when using $filter parameter in java request to dynamics crm
I'm trying query data from dynamics CRM through java HttpUrlConnection object.
I always get an HTTP 400 status code when my  request include the $filter parameter. But when I remove this parameter my request works fine.
I have tried my request directly on a browser and it works fine too. The code below shows how I built my request

```<code>public String getContactByPhoneNumber(String phoneNumber) throws Exception {
    HttpURLConnection connection = null;
    URL url = new URL(completeURL + "/contacts?select=lastname&$filter=telephone1 eq '"+phoneNumber+"'");
    connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    connection.setRequestProperty("OData-MaxVersion", "4.0");
    connection.setRequestProperty("OData-Version", "4.0");
    connection.setRequestProperty("Accept", "application/json");
    connection.setRequestProperty("Prefer", "odata.include-annotations=\"*\"");
    connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
    connection.addRequestProperty("Authorization", "Bearer " + token);
    if (connection.getResponseCode() == 200) {
        String response = getResponseAsString(connection);
        return response;
    } else {
        String error = getErrorAsString(connection);
        System.err.println(error);
        return null;
    }

}
</code>```

Did anyone met this error? How can I solve it?

答:
I haven't tested this myself, so I can't guarantee that it works, but you could try URL-encoding the $filter parameter name and its value:

```<code>import java.net.URLEncoder;

// ...

  URL url = new URL(
    completeURL + "/contacts?select=lastname&"
    + URLEncoder.encode("$filter", "UTF-8") + "="
    + URLEncoder.encode("telephone1 eq '"+phoneNumber+"'", "UTF-8"));
</code>```

Body:
I'm trying query data from dynamics CRM through java HttpUrlConnection object.
I always get an HTTP 400 status code when my  request include the $filter parameter. But when I remove this parameter my request works fine.
I have tried my request directly on a browser and it works fine too. The code below shows how I built my request

public String getContactByPhoneNumber(String phoneNumber) throws Exception {
    HttpURLConnection connection = null;
    URL url = new URL(completeURL + "/contacts?select=lastname&$filter=telephone1 eq '"+phoneNumber+"'");
    connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    connection.setRequestProperty("OData-MaxVersion", "4.0");
    connection.setRequestProperty("OData-Version", "4.0");
    connection.setRequestProperty("Accept", "application/json");
    connection.setRequestProperty("Prefer", "odata.include-annotations=\"*\"");
    connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
    connection.addRequestProperty("Authorization", "Bearer " + token);
    if (connection.getResponseCode() == 200) {
        String response = getResponseAsString(connection);
        return response;
    } else {
        String error = getErrorAsString(connection);
        System.err.println(error);
        return null;
    }

}

Did anyone met this error? How can I solve it?

Body:
I haven't tested this myself, so I can't guarantee that it works, but you could try URL-encoding the $filter parameter name and its value:

import java.net.URLEncoder;

// ...

  URL url = new URL(
    completeURL + "/contacts?select=lastname&"
    + URLEncoder.encode("$filter", "UTF-8") + "="
    + URLEncoder.encode("telephone1 eq '"+phoneNumber+"'", "UTF-8"));


来源: stackexchange

问:
Sqlite database connectected to a python file is causing errors when imported as a package
I have a sqlite database and a python file in a folder. Now I'm trying to access that as a package but I run into this error sqlite3.OperationalError: no such table:projects where as the same thing works fine when I run that a single python file.

I have created one init.py empty file inside the folder
The code runs perfectly when I m running that python file
database name is project.db and the table name is projects

I red about documentation on modules and packages but not able to understand the problem. I need help in understanding the problem and also any reference to writing our own python packages.

Thanks in advance.

答:
I don't know your project structure exactly, but my best guess is that in your python file with the code you reference the database.db with a relative path like that

```<code>conn = sqlite3.connect("database.db")
</code>```

When you import that file from another python file the new python file is started in its directory and the relative path to your database is wrong. You can easily check that by printing os.getcwd() ("cwd" = current working directory).

The solution is to use an absolute path or change the current working directory with os.chdir(path) before using the python file that opens the database.

ContentLicense: CC BY-SA 3.0

Body:
I don't know your project structure exactly, but my best guess is that in your python file with the code you reference the database.db with a relative path like that

conn = sqlite3.connect("database.db")

When you import that file from another python file the new python file is started in its directory and the relative path to your database is wrong. You can easily check that by printing os.getcwd() ("cwd" = current working directory).

The solution is to use an absolute path or change the current working directory with os.chdir(path) before using the python file that opens the database.


问:
"class X is public, should be in X.java" with Ideone online compiler
I am a student very new to programming and have made a simple program in java to convert units.

I am on a mac using ideone compiler online. I am receiving this error

```<code>Main.java:7: error: class AssessmentOne is public, should be declared in a file named AssessmentOne.java
public class AssessmentOne{
       ^
1 error
</code>```

Here is my code (this is for an assignment I am working on hence the name):

```<code>package assessmentOne.pkg1;
import java.util.Scanner;

// MY NAME Assessment One

public class AssessmentOne{

    public static void main(String[] args)
    { int choice;

    do

    { Scanner input = new Scanner(System.in);
    System.out.println("1 = centimetre to inch, 2 = metres to feet, 3 = finish");
    choice = Integer.parseInt(input.next());

    if (choice == 1)

        {
        // converts centimetre to inch
        System.out.println("centimetre to inch");
            double centimetre;
            double inch;

            inch = 0;
            centimetre = Double.parseDouble(input.next());
            System.out.println("inch = centimetre * 0.3973");
        }

    else if (choice == 2)

        {
        // converts metre to feet
        System.out.println("metre to feet");
        double metre;
        double feet;

        feet = 0;
        metre = Double.parseDouble(input.next());
        System.out.println("feet = metre * 3.28");
        }

    else if (choice == 3)

        {
        // exits
        break;
        }

    } while (choice != 3);

    }
    }
</code>```

答:
Remove public in below line of code and it works straight away.

"public class AssessmentOne{"

Body:
I am a student very new to programming and have made a simple program in java to convert units.

I am on a mac using ideone compiler online. I am receiving this error

Main.java:7: error: class AssessmentOne is public, should be declared in a file named AssessmentOne.java
public class AssessmentOne{
       ^
1 error

Here is my code (this is for an assignment I am working on hence the name):

package assessmentOne.pkg1;
import java.util.Scanner;

// MY NAME Assessment One

public class AssessmentOne{

    public static void main(String[] args)
    { int choice;

    do

    { Scanner input = new Scanner(System.in);
    System.out.println("1 = centimetre to inch, 2 = metres to feet, 3 = finish");
    choice = Integer.parseInt(input.next());

    if (choice == 1)

        {
        // converts centimetre to inch
        System.out.println("centimetre to inch");
            double centimetre;
            double inch;

            inch = 0;
            centimetre = Double.parseDouble(input.next());
            System.out.println("inch = centimetre * 0.3973");
        }

    else if (choice == 2)

        {
        // converts metre to feet
        System.out.println("metre to feet");
        double metre;
        double feet;

        feet = 0;
        metre = Double.parseDouble(input.next());
        System.out.println("feet = metre * 3.28");
        }

    else if (choice == 3)

        {
        // exits
        break;
        }

    } while (choice != 3);

    }
    }


问:
Why does arm::standardize() fail to work on a lm object in a loop?
standardize() in the arm package fails for me when I define the formula object using as.formula and use it in lm(formula, data = df).

Option A (which I don't want) standardizes inputs outside of lm. Option B tries (and fails) to standardize the lm object.

(note: keeping my loop structure since my actual use case is a bit more complicated)

```<code># create data
  library(arm)
  set.seed(324)
  df <- data.frame(y=sample(0:50, 100, replace=T),
                   x1=sample(0:1, 100, replace=T),
                   x2=sample(0:50, 100, replace=T))

# rescale outside of lm for comparison
  df$x1Z <- rescale(df$x1, binary.inputs = "0/1")
  df$x2Z <- rescale(df$x2, binary.inputs = "0/1")

# actual use case has more vars
  var <- c("x1", "x2")
  varZ <- c("x1Z", "x2Z")

# Option A: lm on rescaled
  a <- data.frame(matrix(NA, nrow = 0, ncol = 6))
  for (i in 1:length(var)) {
    formula <- as.formula(paste("y ~", varZ[i])) # use standardized
    m1 <- lm(formula, data = df)
    ms1 <- summary(m1)
    a[i, 1] <- var[i]
    a[i, 2] <- coefficients(ms1)[1,1]
    a[i, 3] <- coefficients(ms1)[2,1]
    a[i, 4] <- coefficients(ms1)[2,4]
    a[i, 5] <- confint(m1)[2,1]
    a[i, 6] <- confint(m1)[2,2]
  }
  names(a) <- c("predictor", "intercept", "est", "p", "L95CI", "U95CI")

# Option B: lm, rescaling within lm
  b <- data.frame(matrix(NA, nrow = 0, ncol = 6))
  for (i in 1:length(var)) {
    formula <- as.formula(paste("y ~", var[i]))  # use raw
    m2 <- lm(formula, data = df)
    m2Z <- standardize(m2, binary.inputs="0/1")  # error
    ms2 <- summary(m2Z)
    b[i, 1] <- var[i]
    b[i, 2] <- coefficients(ms2)[1,1]
    b[i, 3] <- coefficients(ms2)[2,1]
    b[i, 4] <- coefficients(ms2)[2,4]
    b[i, 5] <- confint(m2)[2,1]
    b[i, 6] <- confint(m2)[2,2]
  }
  names(b) <- c("predictor", "intercept", "est", "p", "L95CI", "U95CI")
</code>```

Just to show standardize works:

```<code>m3 <- lm(y ~ x2, data=df)
standardize(m3, binary.inputs="0/1")
</code>```

答:
Use

```<code>m2 <- do.call("lm", list(formula = formula, data = quote(df)))
</code>```

in your loop for Option B.

Your issue is more or less similar to this one: Showing string in formula and not as variable in lm fit. You want to keep a decent formula in m2$call.

If you want to know why this is important, see source code of standardize:

```<code>getMethod("standardize", "lm")
</code>```

This function works by extracting and analyzing $call of an lm object.

Body:
standardize() in the arm package fails for me when I define the formula object using as.formula and use it in lm(formula, data = df).

Option A (which I don't want) standardizes inputs outside of lm. Option B tries (and fails) to standardize the lm object.

(note: keeping my loop structure since my actual use case is a bit more complicated)

# create data
  library(arm)
  set.seed(324)
  df <- data.frame(y=sample(0:50, 100, replace=T),
                   x1=sample(0:1, 100, replace=T),
                   x2=sample(0:50, 100, replace=T))

# rescale outside of lm for comparison
  df$x1Z <- rescale(df$x1, binary.inputs = "0/1")
  df$x2Z <- rescale(df$x2, binary.inputs = "0/1")

# actual use case has more vars
  var <- c("x1", "x2")
  varZ <- c("x1Z", "x2Z")

# Option A: lm on rescaled
  a <- data.frame(matrix(NA, nrow = 0, ncol = 6))
  for (i in 1:length(var)) {
    formula <- as.formula(paste("y ~", varZ[i])) # use standardized
    m1 <- lm(formula, data = df)
    ms1 <- summary(m1)
    a[i, 1] <- var[i]
    a[i, 2] <- coefficients(ms1)[1,1]
    a[i, 3] <- coefficients(ms1)[2,1]
    a[i, 4] <- coefficients(ms1)[2,4]
    a[i, 5] <- confint(m1)[2,1]
    a[i, 6] <- confint(m1)[2,2]
  }
  names(a) <- c("predictor", "intercept", "est", "p", "L95CI", "U95CI")

# Option B: lm, rescaling within lm
  b <- data.frame(matrix(NA, nrow = 0, ncol = 6))
  for (i in 1:length(var)) {
    formula <- as.formula(paste("y ~", var[i]))  # use raw
    m2 <- lm(formula, data = df)
    m2Z <- standardize(m2, binary.inputs="0/1")  # error
    ms2 <- summary(m2Z)
    b[i, 1] <- var[i]
    b[i, 2] <- coefficients(ms2)[1,1]
    b[i, 3] <- coefficients(ms2)[2,1]
    b[i, 4] <- coefficients(ms2)[2,4]
    b[i, 5] <- confint(m2)[2,1]
    b[i, 6] <- confint(m2)[2,2]
  }
  names(b) <- c("predictor", "intercept", "est", "p", "L95CI", "U95CI")

Just to show standardize works:

m3 <- lm(y ~ x2, data=df)
standardize(m3, binary.inputs="0/1")

Body:
Use

m2 <- do.call("lm", list(formula = formula, data = quote(df)))

in your loop for Option B.

Your issue is more or less similar to this one: Showing string in formula and not as variable in lm fit. You want to keep a decent formula in m2$call.

If you want to know why this is important, see source code of standardize:

getMethod("standardize", "lm")

This function works by extracting and analyzing $call of an lm object.


问:
How to detect duplicate words in a list and count them in a specific way
I've been learning python 3 for about 1 week now and I just can't find a way to do this, so here is my question.

I have this list:

```<code>['apple', 'banana', 'apple', 'tomato', 'carrot', 'apple', 'banana']
</code>```

Now I want to detect the duplicated words, count them, put the result in front of the word and print in a single string like this example:

Apple 3, Banana 2, tomato, carrot

Order doesn't matter.

答:
You can use Counter from collections:</p>

```<code>from collections import Counter

the_list = ['apple', 'banana', 'apple', 'tomato', 'carrot', 'apple', 'banana']

dct = Counter(the_list)

for i in range(len(dct.keys())):
     print dct.keys()[i], str(dct.values()[i])+", ",
</code>```

Body:
I've been learning python 3 for about 1 week now and I just can't find a way to do this, so here is my question.

I have this list:

['apple', 'banana', 'apple', 'tomato', 'carrot', 'apple', 'banana']

Now I want to detect the duplicated words, count them, put the result in front of the word and print in a single string like this example:

Apple 3, Banana 2, tomato, carrot

Order doesn't matter.

Body:
You can use Counter from collections:

from collections import Counter

the_list = ['apple', 'banana', 'apple', 'tomato', 'carrot', 'apple', 'banana']

dct = Counter(the_list)

for i in range(len(dct.keys())):
     print dct.keys()[i], str(dct.values()[i])+", ",


问:
"Module '" + loader.path + "' is not a loader webpack error
webpack version - 2.3.2

node version -4.6.1

Ii am getting this strange error

```<code>    /home/ubuntu/workspace/node_modules/webpack/node_modules/loader-runner/lib/loadLoader.js:35
                        throw new Error("Module '" + loader.path + "' is not a loader (must have normal or pitch function)");
                        ^

Error: Module '/home/ubuntu/workspace/node_modules/file/lib/file.js' is not a loader (must have normal or pitch function)
    at loadLoader (/home/ubuntu/workspace/node_modules/webpack/node_modules/loader-runner/lib/loadLoader.js:35:10)
    at iteratePitchingLoaders (/home/ubuntu/workspace/node_modules/webpack/node_modules/loader-runner/lib/LoaderRunner.js:169:2)
    at runLoaders (/home/ubuntu/workspace/node_modules/webpack/node_modules/loader-runner/lib/LoaderRunner.js:362:2)
    at NormalModule.doBuild (/home/ubuntu/workspace/node_modules/webpack/lib/NormalModule.js:179:3)
    at NormalModule.build (/home/ubuntu/workspace/node_modules/webpack/lib/NormalModule.js:268:15)
    at Compilation.buildModule (/home/ubuntu/workspace/node_modules/webpack/lib/Compilation.js:142:10)
</code>```

I checked the github questions and answers. Looks like I need to add -loaders in all the used loaders. But, I am already using -loaders. Check out my webpack config

```<code>    var webpack = require("webpack");
var path = require("path");
var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
  entry: {app: './src/app.js' },
  output: {filename: 'public/build/bundle.js',
        sourceMapFilename: 'public/build/bundle.map' },
  module: {
    loaders: [
      { test: /\.(js|jsx)$/, loader: 'babel-loader',options: {
        presets: ['stage-0','react','es2015'],
        plugins: ["transform-decorators-legacy","transform-class-properties"]
    } },
      { test: /\.css$/, loaders: [ 'style-loader', 'css-loader' ] },
      { test: /\.(eot|svg|ttf|woff|woff2)$/, loader: 'file?name=public/fonts/[name].[ext]'  },
   {
  test: /\.(jpe?g|png|gif|svg)$/i,
  use: [
    {
      loader: 'file-loader',
      options: {
        name: '[sha512:hash:hex].[ext]'
      }
    },
    {
      loader: 'image-webpack-loader',
      options: {
        bypassOnDebug: true,
        mozjpeg: {
          progressive: true
        },
        gifsicle: {
          interlaced: true
        },
        optipng: {
          optimizationLevel: 7
        }
      }
    }
  ]
}
    ]
  }
}
</code>```

There is no other thread on stackoverflow which solves this issue. Thats why I have to open a new thread.

答:
The issue is with this line:

```<code>{ test: /\.(eot|svg|ttf|woff|woff2)$/, loader: 'file?name=public/fonts/[name].[ext]' }
</code>```

You have a module called file installed, that Webpack is trying to load. Because it's not a loader, you're getting the error (AFAIK, with any loader configuration, Webpack will always first try to load the module by name verbatim, so file in this case, and only when the module doesn't exist will it retry by appending -loader, so file-loader; however, since file exists, Webpack thinks is has found the correct loader module).

Change it to this:

```<code>{ test: /\.(eot|svg|ttf|woff|woff2)$/, loader: 'file-loader?name=public/fonts/[name].[ext]' }
</code>```

Body:
webpack version - 2.3.2

node version -4.6.1

Ii am getting this strange error

    /home/ubuntu/workspace/node_modules/webpack/node_modules/loader-runner/lib/loadLoader.js:35
                        throw new Error("Module '" + loader.path + "' is not a loader (must have normal or pitch function)");
                        ^

Error: Module '/home/ubuntu/workspace/node_modules/file/lib/file.js' is not a loader (must have normal or pitch function)
    at loadLoader (/home/ubuntu/workspace/node_modules/webpack/node_modules/loader-runner/lib/loadLoader.js:35:10)
    at iteratePitchingLoaders (/home/ubuntu/workspace/node_modules/webpack/node_modules/loader-runner/lib/LoaderRunner.js:169:2)
    at runLoaders (/home/ubuntu/workspace/node_modules/webpack/node_modules/loader-runner/lib/LoaderRunner.js:362:2)
    at NormalModule.doBuild (/home/ubuntu/workspace/node_modules/webpack/lib/NormalModule.js:179:3)
    at NormalModule.build (/home/ubuntu/workspace/node_modules/webpack/lib/NormalModule.js:268:15)
    at Compilation.buildModule (/home/ubuntu/workspace/node_modules/webpack/lib/Compilation.js:142:10)

I checked the github questions and answers. Looks like I need to add -loaders in all the used loaders. But, I am already using -loaders. Check out my webpack config

    var webpack = require("webpack");
var path = require("path");
var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
  entry: {app: './src/app.js' },
  output: {filename: 'public/build/bundle.js',
        sourceMapFilename: 'public/build/bundle.map' },
  module: {
    loaders: [
      { test: /\.(js|jsx)$/, loader: 'babel-loader',options: {
        presets: ['stage-0','react','es2015'],
        plugins: ["transform-decorators-legacy","transform-class-properties"]
    } },
      { test: /\.css$/, loaders: [ 'style-loader', 'css-loader' ] },
      { test: /\.(eot|svg|ttf|woff|woff2)$/, loader: 'file?name=public/fonts/[name].[ext]'  },
   {
  test: /\.(jpe?g|png|gif|svg)$/i,
  use: [
    {
      loader: 'file-loader',
      options: {
        name: '[sha512:hash:hex].[ext]'
      }
    },
    {
      loader: 'image-webpack-loader',
      options: {
        bypassOnDebug: true,
        mozjpeg: {
          progressive: true
        },
        gifsicle: {
          interlaced: true
        },
        optipng: {
          optimizationLevel: 7
        }
      }
    }
  ]
}
    ]
  }
}

There is no other thread on stackoverflow which solves this issue. Thats why I have to open a new thread.

Body:
The issue is with this line:

{ test: /\.(eot|svg|ttf|woff|woff2)$/, loader: 'file?name=public/fonts/[name].[ext]' }

You have a module called file installed, that Webpack is trying to load. Because it's not a loader, you're getting the error (AFAIK, with any loader configuration, Webpack will always first try to load the module by name verbatim, so file in this case, and only when the module doesn't exist will it retry by appending -loader, so file-loader; however, since file exists, Webpack thinks is has found the correct loader module).

Change it to this:

{ test: /\.(eot|svg|ttf|woff|woff2)$/, loader: 'file-loader?name=public/fonts/[name].[ext]' }


问:
Accesing ContentProviders data from another application in android
I have ContentProvider with database in one application and I inserted some data in to database.

Now i want to access the database data from another application through ContentProviders.

please help me.

答: set android:exported="true" on your content provider declaration in your AndroidManifest.xml

ContentLicense: CC BY-SA 2.5


问:
Bootstrap Carousel: Cannot read property 'offsetWidth' of undefined
I'm using bootstrap carousel and have come up with a function to generate the "item"s inside carousel-inner that works as expected.

When the user clicks one of many pictures on the page I show the carousel full-screen and populate it with other images from that folder (each image has its own folder with extra images related to it).

However, around 1 out of 5 times that I click on a picture I'm able to see the first item full-screen but the controls won't work (and I get the 'Cannot read property 'offsetWidth' of undefined' error on the console). The strange thing is that if I try to click that same picture again it will work fine.

HTML

```<code><div class="row carousel-holder" id="fotenha2">
  <div class="col-md-12" id="carCol">
    <div id="banners" class="carousel slide" data-ride="carousel">
      <div class="carousel-inner" role="listbox" id="carCont" oncontextmenu="return false;">
      </div>
      <a class="left carousel-control" href="#banners" role="button" data-slide="prev">
        <span class="glyphicon glyphicon-chevron-left" aria-hidden:"true"></span>
        <span class="sr-only">Previous</span>
      </a>
      <a class="right carousel-control" href="#banners" data-slide="next">
        <span class="glyphicon glyphicon-chevron-right" aria-hidden:"true"></span>
        <span class="sr-only">Next</span>
      </a>
    </div>
  </div>
</div>
</code>```

JavaScript

```<code>function createCarousel(folder, items) {
  for (var i=1; i<=items; i++) {
    var content = document.getElementById('travelCont');
    var imageCont = document.getElementById('fotenha2');
    imageCont.style.display = "block";
    content.style.display = "none";
    var path = 'assets/travel/'+folder+'/000'+i+'.jpg';
    var item = document.createElement("DIV");
    var anchor = document.createElement("a");
    var img = document.createElement("IMG");
    img.className="slide-image";
    img.src = path;
    anchor.appendChild(img);
    anchor.href = "";
    item.appendChild(anchor);
    item.className="item";
    if (i === 1) {
      item.className = "item active";
    }
  item.onclick="closeTravelArticle()";
  document.getElementById('carCont').appendChild(item);
  }
}
</code>```

Any ideas of why this is happening will be very helpful.

PS: The solution for other questions like mine was to add "active" to the first item, which I'm already doing

答:
I suggest to use AngularJS, they have a nice feature you can use called ng-repeat. All you need is an object with your data and the ng-repeat on the element you want to repeat.

var app = angular.module("app", []);
app.controller("myCtrl", function($scope) {
    $scope.items = {
      0 : {
        'id' : 1,
        'name' : 'Item 1'
      },
      1 : {
        'id' : 2,
        'name': 'Item 2'
      }
    };
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div ng-app="app" ng-controller="myCtrl">
  <ul>
    <li ng-repeat="x in items" id="{{ x.id }}">{{ x.name }}</li>
  </ul>
</div></code>```

I suggest this based on my own experience. I am creating multiple projects with AngularJS now and I think it's one of the best frameworks there is. Also, for one of my projects I wanted to do the same as you, this worked excellent for me.

Body:
I'm using bootstrap carousel and have come up with a function to generate the "item"s inside carousel-inner that works as expected.

When the user clicks one of many pictures on the page I show the carousel full-screen and populate it with other images from that folder (each image has its own folder with extra images related to it).

However, around 1 out of 5 times that I click on a picture I'm able to see the first item full-screen but the controls won't work (and I get the 'Cannot read property 'offsetWidth' of undefined' error on the console). The strange thing is that if I try to click that same picture again it will work fine.

HTML

        Previous

        Next

JavaScript

function createCarousel(folder, items) {
  for (var i=1; i<=items; i++) {
    var content = document.getElementById('travelCont');
    var imageCont = document.getElementById('fotenha2');
    imageCont.style.display = "block";
    content.style.display = "none";
    var path = 'assets/travel/'+folder+'/000'+i+'.jpg';
    var item = document.createElement("DIV");
    var anchor = document.createElement("a");
    var img = document.createElement("IMG");
    img.className="slide-image";
    img.src = path;
    anchor.appendChild(img);
    anchor.href = "";
    item.appendChild(anchor);
    item.className="item";
    if (i === 1) {
      item.className = "item active";
    }
  item.onclick="closeTravelArticle()";
  document.getElementById('carCont').appendChild(item);
  }
}

Any ideas of why this is happening will be very helpful.

PS: The solution for other questions like mine was to add "active" to the first item, which I'm already doing

Body:
I suggest to use AngularJS, they have a nice feature you can use called ng-repeat. All you need is an object with your data and the ng-repeat on the element you want to repeat.

var app = angular.module("app", []);
app.controller("myCtrl", function($scope) {
    $scope.items = {
      0 : {
        'id' : 1,
        'name' : 'Item 1'
      },
      1 : {
        'id' : 2,
        'name': 'Item 2'
      }
    };
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div ng-app="app" ng-controller="myCtrl">
  <ul>
    <li ng-repeat="x in items" id="{{ x.id }}">{{ x.name }}</li>
  </ul>
</div>

I suggest this based on my own experience. I am creating multiple projects with AngularJS now and I think it's one of the best frameworks there is. Also, for one of my projects I wanted to do the same as you, this worked excellent for me.


问:
How to fake a file merge after making changes?
I have pasted another version of a file in my project, it has additions and deletions. I want to fake a merge into current committed version so that I could see and resolve conflicts easier than comparing the files by eye.

How can I initiate a merge of a modified file (working tree) into HEAD version of the same file?

```<code>config/routes.rb # (1) commited version HEAD
config/routes.rb # (2) modified version in working tree
</code>```

I have pasted the (2) config/routes.rb from a file that my friend sent me into my existing routes file (1).

Thanks

答:
In order to truly "merge" two files, you need a "base" version from which they were both derived.  Otherwise, the computer can't tell the difference between an addition in one file and a deletion in the other, so it can't tell which version is newer and can't make any automatic changes (i.e., every change would be a conflict).  For example:

```<code>file1:
...
here is a line
this line was added in file 1, or was it deleted in file 2?
here's the next line
...

file2:
...
here is a line
here's the next line
...
</code>```

Without a base file, there's no way to tell what happened here, so it's not clear if file1 or file2 is the correct version.

If you have a base version checked into git, say at commit 123abc then the easiest way to do it is:

make sure your tree is clean (i.e., move the new version out of the way and re-checkout your HEAD version)

do a git branch topic_merge_friends_changes 123abc to create a temporary branch at the commit containing the base version

check out the branch: git checkout topic_merge_friends_changes -- note that this can be combined with the previous step using the -b flag with checkout

now, move your new file into place and git commit it

switch back to master: git checkout master

and git merge topic_merge_friends_changes

Alternatively, you can skip the committing and merging and instead copy the base version (call it base.txt) and the two later versions (mine.txt and friends.txt) somewhere and then run git merge-file mine.txt base.txt friends.txt to merge your friend's changes into mine.txt without actually generating and commits or new branchs.

Finally, if you don't have a base file, the best you can do is manually examine and edit a diff between the two files.  You can either

write the output of git diff to a file and manually edit the result to get the file you want (and of course you'll need to remove the indenting that diff adds to the areas where the files agree)

use a visual diff tool -- Emacs has a nice visual diff mode (e.g., M-x ediff-merge-files) that let's you view each change side-by-side and select the version you want with a keystroke, and many other editors will have similar facilities

Body:
I have pasted another version of a file in my project, it has additions and deletions. I want to fake a merge into current committed version so that I could see and resolve conflicts easier than comparing the files by eye.

How can I initiate a merge of a modified file (working tree) into HEAD version of the same file?

config/routes.rb # (1) commited version HEAD
config/routes.rb # (2) modified version in working tree

I have pasted the (2) config/routes.rb from a file that my friend sent me into my existing routes file (1).

Thanks

Body:
In order to truly "merge" two files, you need a "base" version from which they were both derived.  Otherwise, the computer can't tell the difference between an addition in one file and a deletion in the other, so it can't tell which version is newer and can't make any automatic changes (i.e., every change would be a conflict).  For example:

file1:
...
here is a line
this line was added in file 1, or was it deleted in file 2?
here's the next line
...

file2:
...
here is a line
here's the next line
...

Without a base file, there's no way to tell what happened here, so it's not clear if file1 or file2 is the correct version.

If you have a base version checked into git, say at commit 123abc then the easiest way to do it is:

make sure your tree is clean (i.e., move the new version out of the way and re-checkout your HEAD version)

do a git branch topic_merge_friends_changes 123abc to create a temporary branch at the commit containing the base version

check out the branch: git checkout topic_merge_friends_changes -- note that this can be combined with the previous step using the -b flag with checkout

now, move your new file into place and git commit it

switch back to master: git checkout master

and git merge topic_merge_friends_changes

Alternatively, you can skip the committing and merging and instead copy the base version (call it base.txt) and the two later versions (mine.txt and friends.txt) somewhere and then run git merge-file mine.txt base.txt friends.txt to merge your friend's changes into mine.txt without actually generating and commits or new branchs.

Finally, if you don't have a base file, the best you can do is manually examine and edit a diff between the two files.  You can either

write the output of git diff to a file and manually edit the result to get the file you want (and of course you'll need to remove the indenting that diff adds to the areas where the files agree)

use a visual diff tool -- Emacs has a nice visual diff mode (e.g., M-x ediff-merge-files) that let's you view each change side-by-side and select the version you want with a keystroke, and many other editors will have similar facilities


问:
spring boot error 404 while starting jar
I’m trying to run a spring boot application. I downloaded a code from a tutorial so I know the code works. When I run my jar file, it looks like the applications I running on port 8080 but still I get 404 for any URL, I never got the spring white label page. I checked that I don’t have anything else running on port 8080, and the server I up and running.

I have no clue why my applications are not responding.

running the jar

error 404

```<code>package com.virtualpairprogrammers;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by masn on 2017-04-01.
*/

@RestController
public class HelloController {

    @RequestMapping("/hello")
    public String sayHello(){
        return "Hello";
    }
}

enter code here
</code>```

package com.virtualpairprogrammers;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class FleetmanApplication {

```<code>public static void main(String[] args) {
    SpringApplication.run(FleetmanApplication.class, args);
}
</code>```

}

```<code>enter code here
</code>```

http://maven.apache.org/xsd/maven-4.0.0.xsd">
    4.0.0

```<code><groupId>com.virtualpairprogrammers</groupId>
<artifactId>fleetman</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>fleetman</name>
<description>VPP´s Fleet Management Application</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.2.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
</code>```

答:
Just try like this and it will work:

```<code>@RestController
public class HelloController {

    @RequestMapping(path = "/hello", method = RequestMethod.GET)
    public String hello() {
        return "hello";
    }
}
</code>```

Here's the screenshot I've taken from my computer:

Body:
I’m trying to run a spring boot application. I downloaded a code from a tutorial so I know the code works. When I run my jar file, it looks like the applications I running on port 8080 but still I get 404 for any URL, I never got the spring white label page. I checked that I don’t have anything else running on port 8080, and the server I up and running.

I have no clue why my applications are not responding.

running the jar

error 404

package com.virtualpairprogrammers;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by masn on 2017-04-01.
*/

@RestController
public class HelloController {

    @RequestMapping("/hello")
    public String sayHello(){
        return "Hello";
    }
}

enter code here

package com.virtualpairprogrammers;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class FleetmanApplication {

public static void main(String[] args) {
    SpringApplication.run(FleetmanApplication.class, args);
}

}

enter code here

http://maven.apache.org/xsd/maven-4.0.0.xsd">
    4.0.0

<groupId>com.virtualpairprogrammers</groupId>
<artifactId>fleetman</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>fleetman</name>
<description>VPP´s Fleet Management Application</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.2.RELEASE</version>
    <relativePath/>
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

Body:
Just try like this and it will work:

@RestController
public class HelloController {

    @RequestMapping(path = "/hello", method = RequestMethod.GET)
    public String hello() {
        return "hello";
    }
}

Here's the screenshot I've taken from my computer:


问:
What is wrong with this bower.json?
I'm using following bower.json:

```<code>{
  "name": "angularSeedApp",
  "version": "0.0.0",
  "dependencies": {
    "angular-material": "~1.1.0",
    "angular-animate": "1.5.9",
    "angular-aria": "1.5.9",
    "angular-material-icons": "x",
    "material-design-icons": "x",
    "angular-cookies": "~1.5.0",
    "angular-sanitize": "~1.5.0",
    "angular-resource": "~1.4.0",
    "angular-ui-router": "~0.3.1",
    "moment": "^2.17.0",
    "angular": "~1.5.0",
    "angular-filter": "x",
    "fontawesome": "~4.3.0",
    "hello": "^1.14.0",
    "cloudinary_ng": "^1.0.0",
    "moment-timezone": "^0.5.10",
    "angular-timezone-selector": "^1.6.0",
    "moment-range": "^2.1.0",
    "underscore": "^1.8.3"
  },
  "devDependencies": {
    "angular-mocks": "~1.5.0"
  },
  "resolutions": {
    "angular": "~1.5.0",
    "lodash": "4.0.1",
    "moment": ">= 1",
    "moment-timezone": "^0.5.10"
  }
}
</code>```

My problem is following -> A friend of mine was working on the project for a long time - and all the files get served from the src folder instead of dist folder. Now when I build the project all the libs get not detected anymore - so serving from dist produces the typical angular error "module not found".

The reason why I think it has to do with the bower_components:
When I pulled the project the bower_components were not updated - so it worked. After updating the bower_components it showed me these errors. So I believe it has to do with bower libs.

We are using this base setup: https://github.com/PauloLuan/angular-gulp-seed

Can anyone tell me what is wrong with this bower.json?
Can you also give me hints how to approach these kind of bugs?

答:
The solution is basically to use fixed versions for all angular-(resources).</p>

```<code>  {
  "name": "angularSeedApp",
  "version": "0.0.0",
  "dependencies": {
    "jquery": "^3.2.1",
    "angular-material": "1.1.3",
    "angular-animate": "1.5.9",
    "angular-aria": "1.5.9",
    "angular-material-icons": "x",
    "material-design-icons": "x",
    "angular-cookies": "1.5.9",
    "angular-sanitize": "1.5.9",
    "angular-resource": "1.5.9",
    "angular-messages": "1.5.9",
    "angular-ui-router": "~0.3.1",
    "moment": "^2.17.0",
    "angular-filter": "x",
    "fontawesome": "~4.3.0",
    "hello": "^1.14.0",
    "cloudinary_ng": "^1.0.0",
    "moment-timezone": "^0.5.10",
    "angular-timezone-selector": "^1.6.0",
    "moment-range": "^2.1.0",
    "underscore": "^1.8.3",
    "angular": "1.5.9"
  },
  "devDependencies": {
    "angular-mocks": "1.5.9"
  },
  "resolutions": {
    "moment": ">= 2.6.0",
    "angular": "1.5.9",
    "moment-timezone": "^0.5.10",
    "lodash": "4.0.1"
  }
}
</code>```

Title: What is wrong with this bower.json?

Body:
I'm using following bower.json:

{
  "name": "angularSeedApp",
  "version": "0.0.0",
  "dependencies": {
    "angular-material": "~1.1.0",
    "angular-animate": "1.5.9",
    "angular-aria": "1.5.9",
    "angular-material-icons": "x",
    "material-design-icons": "x",
    "angular-cookies": "~1.5.0",
    "angular-sanitize": "~1.5.0",
    "angular-resource": "~1.4.0",
    "angular-ui-router": "~0.3.1",
    "moment": "^2.17.0",
    "angular": "~1.5.0",
    "angular-filter": "x",
    "fontawesome": "~4.3.0",
    "hello": "^1.14.0",
    "cloudinary_ng": "^1.0.0",
    "moment-timezone": "^0.5.10",
    "angular-timezone-selector": "^1.6.0",
    "moment-range": "^2.1.0",
    "underscore": "^1.8.3"
  },
  "devDependencies": {
    "angular-mocks": "~1.5.0"
  },
  "resolutions": {
    "angular": "~1.5.0",
    "lodash": "4.0.1",
    "moment": ">= 1",
    "moment-timezone": "^0.5.10"
  }
}

My problem is following -> A friend of mine was working on the project for a long time - and all the files get served from the src folder instead of dist folder. Now when I build the project all the libs get not detected anymore - so serving from dist produces the typical angular error "module not found".

The reason why I think it has to do with the bower_components:
When I pulled the project the bower_components were not updated - so it worked. After updating the bower_components it showed me these errors. So I believe it has to do with bower libs.

We are using this base setup: https://github.com/PauloLuan/angular-gulp-seed

Can anyone tell me what is wrong with this bower.json?
Can you also give me hints how to approach these kind of bugs?

Body:
The solution is basically to use fixed versions for all angular-(resources).

  {
  "name": "angularSeedApp",
  "version": "0.0.0",
  "dependencies": {
    "jquery": "^3.2.1",
    "angular-material": "1.1.3",
    "angular-animate": "1.5.9",
    "angular-aria": "1.5.9",
    "angular-material-icons": "x",
    "material-design-icons": "x",
    "angular-cookies": "1.5.9",
    "angular-sanitize": "1.5.9",
    "angular-resource": "1.5.9",
    "angular-messages": "1.5.9",
    "angular-ui-router": "~0.3.1",
    "moment": "^2.17.0",
    "angular-filter": "x",
    "fontawesome": "~4.3.0",
    "hello": "^1.14.0",
    "cloudinary_ng": "^1.0.0",
    "moment-timezone": "^0.5.10",
    "angular-timezone-selector": "^1.6.0",
    "moment-range": "^2.1.0",
    "underscore": "^1.8.3",
    "angular": "1.5.9"
  },
  "devDependencies": {
    "angular-mocks": "1.5.9"
  },
  "resolutions": {
    "moment": ">= 2.6.0",
    "angular": "1.5.9",
    "moment-timezone": "^0.5.10",
    "lodash": "4.0.1"
  }
}


问:
Is it possible to remove a behavior from an element that was added using $create?
I am using the following code to create calendar controls on textboxes that have been dynamically created using cloneNode.  The problem is that in IE it seems to add the behavior twice to the textbox causing it not to work.  Is there a way that I can remove this behavior before it is added in ie only to prevent it from being added again?  This works perfectly in firefox.  Thanks!</p>

```<code>var rawDateControlID = ctrlPrefix + 'txtStartDate' + tblPatientMedicationsRowCount;
var $tstCalendar = $("#" + rawDateControlID);
$create(AjaxControlToolkit.CalendarBehavior, { "id": $tstCalendar.attr("id") + "cld" }, null, null, $get($tstCalendar.attr("id")));
</code>```

答:
This seems to help in certain cases:

```<code>var $tstCalendar = $('#' + txtStartDateID);
if ($find($tstCalendar.attr("id") + "cld"))
{
   $find($tstCalendar.attr("id") + "cld").dispose();
}
$create(AjaxControlToolkit.CalendarBehavior, { "id": $tstCalendar.attr("id") + "cld" }, null, null, $get($tstCalendar.attr("id")));
</code>```

Just checking if the behaviour exists and if it does get rid of it before creating the new one.

Body:
I am using the following code to create calendar controls on textboxes that have been dynamically created using cloneNode.  The problem is that in IE it seems to add the behavior twice to the textbox causing it not to work.  Is there a way that I can remove this behavior before it is added in ie only to prevent it from being added again?  This works perfectly in firefox.  Thanks!

var rawDateControlID = ctrlPrefix + 'txtStartDate' + tblPatientMedicationsRowCount;
var $tstCalendar = $("#" + rawDateControlID);
$create(AjaxControlToolkit.CalendarBehavior, { "id": $tstCalendar.attr("id") + "cld" }, null, null, $get($tstCalendar.attr("id")));

Body:
This seems to help in certain cases:

var $tstCalendar = $('#' + txtStartDateID);
if ($find($tstCalendar.attr("id") + "cld"))
{
   $find($tstCalendar.attr("id") + "cld").dispose();
}
$create(AjaxControlToolkit.CalendarBehavior, { "id": $tstCalendar.attr("id") + "cld" }, null, null, $get($tstCalendar.attr("id")));

Just checking if the behaviour exists and if it does get rid of it before creating the new one.


问:
setText() not working from another Activity's onClickListener
I can't figure out why my code is not working:

First Activity

```<code>public static TextView name_contact;
public static TextView message_contact;
public static TextView count_contact;
public static TextView timestamp_contact;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.researchpurpose);

    final ListView listView = (ListView) findViewById(R.id.listViewConvlist);
    chatRoomsAdapter = new ChatRoomsAdapter(getApplicationContext(), R.layout.chat_rooms_list_row);
    listView.setAdapter(chatRoomsAdapter);

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3)
        {
            message_contact = (TextView) v.findViewById(R.id.message);
        }
    });
}
</code>```

Second Activity

```<code>@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.second_acitivy);

    ImageButton buttonSend = (ImageButton) findViewById(R.id.imageButton);
    buttonSend.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            FirstActivity.message_contact.setText("IL N'Y A QUE TOI");
        }
    });
}
</code>```

Because if I put the code below in Second Activity, it works!

```<code> @Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.second_acitivy);

    FirstActivity.message_contact.setText("IL N'Y A QUE TOI");

}
</code>```

And when checking the log, I do NOT get any error...

答:
I figured it out ! Turns out that the virtual keyboard is stopping the order when shown (when I say the order I mean FirstActivity.message_contact.setText("IL N'Y A QUE TOI");).

So I am closing/hiding the virtual keyboard before sending the order with this piece of code :

```<code>View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
</code>```

And after this, the text is being set properly.

But I have to say I don't understand why the code doesn't work when the keyboard is shown.

Body:
I can't figure out why my code is not working:

First Activity

public static TextView name_contact;
public static TextView message_contact;
public static TextView count_contact;
public static TextView timestamp_contact;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.researchpurpose);

    final ListView listView = (ListView) findViewById(R.id.listViewConvlist);
    chatRoomsAdapter = new ChatRoomsAdapter(getApplicationContext(), R.layout.chat_rooms_list_row);
    listView.setAdapter(chatRoomsAdapter);

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3)
        {
            message_contact = (TextView) v.findViewById(R.id.message);
        }
    });
}

Second Activity

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.second_acitivy);

    ImageButton buttonSend = (ImageButton) findViewById(R.id.imageButton);
    buttonSend.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            FirstActivity.message_contact.setText("IL N'Y A QUE TOI");
        }
    });
}

Because if I put the code below in Second Activity, it works!

 @Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.second_acitivy);

    FirstActivity.message_contact.setText("IL N'Y A QUE TOI");

}

And when checking the log, I do NOT get any error...

Body:
I figured it out ! Turns out that the virtual keyboard is stopping the order when shown (when I say the order I mean FirstActivity.message_contact.setText("IL N'Y A QUE TOI");).

So I am closing/hiding the virtual keyboard before sending the order with this piece of code :

View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}

And after this, the text is being set properly.

But I have to say I don't understand why the code doesn't work when the keyboard is shown.


问:
How to use syntaxnet output
I started playing with Syntaxnet two days ago and I'm wondering how to use/export the output (ascii tree or conll ) in a format that is easy to parse (ie : Json, XML, python graph).

Thanks for your help !

答:
I wrote a blog post explaining how to get the output of SyntaxNet for any given language, into Python, specifically into NLTK, and use it's output with Dependency Graph and Tree classes.

You can check it here: http://www.davidsbatista.net/blog/2017/03/25/syntaxnet/

Title: How to use syntaxnet output


问:
Best practices for making HTTP Requests from a stateless bean
I am planning to use Apache HttpClient with BasicHttpClientConnectionManager on a TOMEE stateless bean to perform HTTP GET/POST/DELETE requests to a remote server. Are there any gotchas with this approach ? Does HttpClient spawn new threads that negatively impact EJB container?

Are there any other alternatives? How do you usually perform http request from your webserver to other servers.

答:
Since you are using Tomee you can use the JAX-RS client builtin to Tomee. You can find more information on it in the Java EE tutorial (chapter 30) here.

e.g.

```<code>Client client = ClientBuilder.newClient();
String name = client.target("http://example.com/webapi/hello")
        .request(MediaType.TEXT_PLAIN)
        .get(String.class);
</code>```

Body:
Since you are using Tomee you can use the JAX-RS client builtin to Tomee. You can find more information on it in the Java EE tutorial (chapter 30) here.

e.g.

Client client = ClientBuilder.newClient();
String name = client.target("http://example.com/webapi/hello")
        .request(MediaType.TEXT_PLAIN)
        .get(String.class);


问:
Can sprintf / formatted strings be passed directly to a function?
Is something like this allowed in C++? If so, how do I do it?

```<code>myFunction("User input: %s", a);
</code>```

Or is the only way to format it first and then pass it?

答:
It is possible using the vsprintf() function from the C library, and writing myFunction() as taking variable arguments.

However, the usual disclaimers regarding variable argument methods apply: it's very easy to introduce buffer overruns or segmentation violations this way. Some compilers allow you to declare myFunction() as "printf-like", so that you could get some degree of compile-time checking of the arguments, but that is not portable.

Body:
Is something like this allowed in C++? If so, how do I do it?

myFunction("User input: %s", a);

Or is the only way to format it first and then pass it?


问:
How to "import" a controller.js file in the angular.module file
I'm just starting to learn Angular so the issue I'm trying to figure out here might be a bit awkwardly formulated. I'll try my best and explain what I'm dealig with.

I have a main main.js module file where I have declared

```<code>angular.module('app', [
'ngRoute'
</code>```

])

Now I have a separrate file for the controller as home.controller.js which contains

```<code>angular
.module('app')
.controller('HomeController', ['$scope', function($scope) {
}]);
</code>```

Is there any way to include the home.controller.js file withing the main.js file without having to put the script src in the html ? I have tried to import 'path/home.conntroller.js but I get this error

Module 'app' is not available! You either misspelled the module name or forgot to load it.

Appreciate the help.

答:
Make sure main.js is included in your HTML file before home.controller.js ... for example:

```

Body:
I'm just starting to learn Angular so the issue I'm trying to figure out here might be a bit awkwardly formulated. I'll try my best and explain what I'm dealig with.

I have a main main.js module file where I have declared

angular.module('app', [
'ngRoute'

])

Now I have a separrate file for the controller as home.controller.js which contains

angular
.module('app')
.controller('HomeController', ['$scope', function($scope) {
}]);

Is there any way to include the home.controller.js file withing the main.js file without having to put the script src in the html ? I have tried to import 'path/home.conntroller.js but I get this error

Module 'app' is not available! You either misspelled the module name or forgot to load it.

Appreciate the help.

Body:
Make sure main.js is included in your HTML file before home.controller.js ... for example:

<script src="main.js"></script>
<script src="home.controller.js"></script>


问:
Update files with awk to delete a pattern occuring within a multilined string
I want to process and modify several YAML files, using awk to update and delete the below input file.

Here is a sample input file:

```<code>    #Modify this
    sss:
      - ccc:
          brr: 'mmm'
          jdk: 'jdk8'
      - bbb:
          brr: 'rel/bbb'
          jdk: 'jdk8'
      - aaa:
          brr: 'rel/aaa'
          jdk: 'jdk7'

    #dont change me
    sss: ccc
    ppp: 'vvv'
    pname: 'vvv'
    brr: 'mmm'
    jdk: jdk8
    jdks:
      - jdk8
      - jdk7
    file:
      - test:
          exec: 'input'
</code>```

Expected output once processed by the awk snippet below:

```<code>    #Modify this
    sss:
      - ddd:
          brr: 'mmm'
          jdk: 'jdk8'
      - ccc:
          brr: 'rel/ccc'
          jdk: 'jdk8'
      - bbb:
          brr: 'rel/bbb'
          jdk: 'jdk8'

    #dont change me
    sss: ccc
    ppp: 'vvv'
    pname: 'vvv'
    jdk: jdk8
    jdks:
      - jdk8
      - jdk7
    file:
      - test:
          exec: 'input'
</code>```

Till now I already have an awk snippet which processes the first part of the input without any issue:

```<code>/sss:/ { sss = 1; }
/- ccc:/ { ccc = 1; i = substr($0, 1, index($0, "-")-1); next; }
$1 == "brr:" && $2 == "'mmm'" {
    if (sss && ccc) {
        print i "- ddd:";
        print i "    brr: 'mmm'";
        print i "    jdk: 'jdk8'";
        print i "- ccc:";
        print i "    brr: 'rel/ccc'";
        sss = 0; ccc = 0;
    }
    next;
}
{ print }
</code>```

How to improve the above snippet to delete these lines:

```<code>    - aaa:
        brr: 'rel/aaa'
        jdk: 'jdk7'
        file: optional-line
</code>```

and make sure that the does not update second part of the input where brr: 'mmm' the line gets deleted.

答:
```<code>$ cat tst.awk
/^[[:space:]]*sss:[[:space:]]*$/ { print; inBlocks=1 }
inBlocks {
    if ( /^[[:space:]]*-/ ) {
        ++numBlocks
    }

    block[numBlocks,++blockNumLines[numBlocks]] = $0

    if ( !NF ) {
        blockNr = 1
        numLines = blockNumLines[blockNr]
        line = block[blockNr,1]
        sub(/[[:alpha:]]+/,"ddd",line)
        print line
        for (lineNr=2; lineNr<=numLines; lineNr++) {
            print block[blockNr,lineNr]
        }

        type = block[blockNr,1]
        gsub(/[^[:alpha:]]+/,"",type)
        sub(/[^[:space:]]+[[:space:]]*$/,"\047rel/"type"\047",block[blockNr,2])

        for (blockNr=1; blockNr<numBlocks; blockNr++) {
            numLines = blockNumLines[blockNr]
            for (lineNr=1; lineNr<=numLines; lineNr++) {
                print block[blockNr,lineNr]
            }
        }
        inBlocks = 0
        numBlocks = 0
    }
}
!inBlocks
</code>```

<p>.</p>

```<code>$ awk -f tst.awk file
    #Modify this
    sss:
      - ddd:
          brr: 'mmm'
          jdk: 'jdk8'
      - ccc:
          brr: 'rel/ccc'
          jdk: 'jdk8'
      - bbb:
          brr: 'rel/bbb'
          jdk: 'jdk8'

    #dont change me
    sss: ccc
    ppp: 'vvv'
    pname: 'vvv'
    brr: 'mmm'
    jdk: jdk8
    jdks:
      - jdk8
      - jdk7
    file:
      - test:
          exec: 'input'
</code>```

Body:
I want to process and modify several YAML files, using awk to update and delete the below input file.

Here is a sample input file:

    #Modify this
    sss:
      - ccc:
          brr: 'mmm'
          jdk: 'jdk8'
      - bbb:
          brr: 'rel/bbb'
          jdk: 'jdk8'
      - aaa:
          brr: 'rel/aaa'
          jdk: 'jdk7'

    #dont change me
    sss: ccc
    ppp: 'vvv'
    pname: 'vvv'
    brr: 'mmm'
    jdk: jdk8
    jdks:
      - jdk8
      - jdk7
    file:
      - test:
          exec: 'input'

Expected output once processed by the awk snippet below:

    #Modify this
    sss:
      - ddd:
          brr: 'mmm'
          jdk: 'jdk8'
      - ccc:
          brr: 'rel/ccc'
          jdk: 'jdk8'
      - bbb:
          brr: 'rel/bbb'
          jdk: 'jdk8'

    #dont change me
    sss: ccc
    ppp: 'vvv'
    pname: 'vvv'
    jdk: jdk8
    jdks:
      - jdk8
      - jdk7
    file:
      - test:
          exec: 'input'

Till now I already have an awk snippet which processes the first part of the input without any issue:

/sss:/ { sss = 1; }
/- ccc:/ { ccc = 1; i = substr($0, 1, index($0, "-")-1); next; }
$1 == "brr:" && $2 == "'mmm'" {
    if (sss && ccc) {
        print i "- ddd:";
        print i "    brr: 'mmm'";
        print i "    jdk: 'jdk8'";
        print i "- ccc:";
        print i "    brr: 'rel/ccc'";
        sss = 0; ccc = 0;
    }
    next;
}
{ print }

How to improve the above snippet to delete these lines:

    - aaa:
        brr: 'rel/aaa'
        jdk: 'jdk7'
        file: optional-line

and make sure that the does not update second part of the input where brr: 'mmm' the line gets deleted.

Body:
$ cat tst.awk
/^[[:space:]]*sss:[[:space:]]*$/ { print; inBlocks=1 }
inBlocks {
    if ( /^[[:space:]]*-/ ) {
        ++numBlocks
    }

    block[numBlocks,++blockNumLines[numBlocks]] = $0

    if ( !NF ) {
        blockNr = 1
        numLines = blockNumLines[blockNr]
        line = block[blockNr,1]
        sub(/[[:alpha:]]+/,"ddd",line)
        print line
        for (lineNr=2; lineNr<=numLines; lineNr++) {
            print block[blockNr,lineNr]
        }

        type = block[blockNr,1]
        gsub(/[^[:alpha:]]+/,"",type)
        sub(/[^[:space:]]+[[:space:]]*$/,"\047rel/"type"\047",block[blockNr,2])

        for (blockNr=1; blockNr<numBlocks; blockNr++) {
            numLines = blockNumLines[blockNr]
            for (lineNr=1; lineNr<=numLines; lineNr++) {
                print block[blockNr,lineNr]
            }
        }
        inBlocks = 0
        numBlocks = 0
    }
}
!inBlocks

.

$ awk -f tst.awk file
    #Modify this
    sss:
      - ddd:
          brr: 'mmm'
          jdk: 'jdk8'
      - ccc:
          brr: 'rel/ccc'
          jdk: 'jdk8'
      - bbb:
          brr: 'rel/bbb'
          jdk: 'jdk8'

    #dont change me
    sss: ccc
    ppp: 'vvv'
    pname: 'vvv'
    brr: 'mmm'
    jdk: jdk8
    jdks:
      - jdk8
      - jdk7
    file:
      - test:
          exec: 'input'


问:
TableView return repeated items every time app runs
So, I am using Realm database and my TableView returns new set of data every time. So, for the first time, I got 3 items. The second time it's 6 items and etc.

```<code>import UIKit
import RealmSwift

class TableViewController: UITableViewController {

var ModelName = [String]()
var Power = [String]()

func addPanel () {

    let realm = try! Realm()
    let allPanels = realm.objects(Panel)
    try! realm.write {
        realm.add(Panel(model: "Hyundai", power: 260))
        realm.add(Panel(model: "Honda", power: 420))
        realm.add(Panel(model: "Siemens", power: 280))
    }

    tableView.reloadData()

    for i in allPanels {
        ModelName.append(i.model)
        Power.append("\(i.power)")
    }

}

override func viewDidLoad() {
    super.viewDidLoad()
    addPanel()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: - Table view data source

override func numberOfSections(in tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return ModelName.count //changed from 3
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell:TableViewCell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TableViewCell
    //connect NameLabel cell to the name of Model and PowerLabel cell to the power

    cell.NameLabel.text = ModelName[indexPath.row]
    cell.PowerLabel.text = Power [indexPath.row]

    return cell
}
</code>```

If I limit my the number of rows to 3, the app works.

```<code>override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return ModelName.count //changed from 3
}
</code>```

I will appreciate any help. Thank you

答:
I believe it's because every time this controller is loaded, you add three objects to Realm. Since by default, update is false, you will be adding three new objects to Realm every time. If you change update to true, then it should use the primary key of the object and "update" these objects every view controller load.</p>

```<code>public func add(_ object: Object, update: Bool = false)
</code>```

Body:
So, I am using Realm database and my TableView returns new set of data every time. So, for the first time, I got 3 items. The second time it's 6 items and etc.

import UIKit
import RealmSwift

class TableViewController: UITableViewController {

var ModelName = [String]()
var Power = [String]()

func addPanel () {

    let realm = try! Realm()
    let allPanels = realm.objects(Panel)
    try! realm.write {
        realm.add(Panel(model: "Hyundai", power: 260))
        realm.add(Panel(model: "Honda", power: 420))
        realm.add(Panel(model: "Siemens", power: 280))
    }

    tableView.reloadData()

    for i in allPanels {
        ModelName.append(i.model)
        Power.append("\(i.power)")
    }

}

override func viewDidLoad() {
    super.viewDidLoad()
    addPanel()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: - Table view data source

override func numberOfSections(in tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return ModelName.count //changed from 3
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell:TableViewCell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TableViewCell
    //connect NameLabel cell to the name of Model and PowerLabel cell to the power

    cell.NameLabel.text = ModelName[indexPath.row]
    cell.PowerLabel.text = Power [indexPath.row]

    return cell
}

If I limit my the number of rows to 3, the app works.

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return ModelName.count //changed from 3
}

I will appreciate any help. Thank you

Body:
I believe it's because every time this controller is loaded, you add three objects to Realm. Since by default, update is false, you will be adding three new objects to Realm every time. If you change update to true, then it should use the primary key of the object and "update" these objects every view controller load.

public func add(_ object: Object, update: Bool = false)


问:
represent a stacked bar chart graphically with openGL using C++
i figured out how to make the bar pieces but my problem is with the positioning of each piece's bottom edge, i can't figure out how to make them perfectly stacked on each other, so most of them end up being on top of the other, making the bar look wrong.
here's my function:

```<code>void StackedBar(void)
{
// Clear the Screen
glClear(GL_COLOR_BUFFER_BIT);

float colors[6][3] = { { 1,0,0 },{ 1,1,0 },{ 0,1,0 },{ 0,1,1 },{ 1,0,1 },{0,0,1} };
float data[6] = { 20,66,42,28,71,23 };
float x = 0, y = 0;
float dy;

glBegin(GL_QUADS);
for (int i = 0; i < 6; i++) {
    glColor3f(colors[i][0], colors[i][1], colors[i][2]);
    dy = data[i];
    glVertex2f(x, y);
    glVertex2f(x + 5, y);
    glVertex2f(x + 5, y + dy);
    glVertex2f(x, y + dy);
    y  = dy;
    //x +=5; incremented x just to see how the pieces are positioned
}
glEnd();

// force execution of GL commands
glFlush();
}
</code>```

output:

result

result with x incremented with 5 just to see the pieces are positioned

答:
If you want to stack the bars on top of each other, just increment y in each iteration by dy.</p>

```<code>for (int i = 0; i < 6; i++) {
    glColor3f(colors[i][0], colors[i][1], colors[i][2]);
    dy = data[i];
    glVertex2f(x, y);
    glVertex2f(x + 5, y);
    glVertex2f(x + 5, y + dy);
    glVertex2f(x, y + dy);
    y += dy;
}
</code>```

Body:
i figured out how to make the bar pieces but my problem is with the positioning of each piece's bottom edge, i can't figure out how to make them perfectly stacked on each other, so most of them end up being on top of the other, making the bar look wrong.
here's my function:

void StackedBar(void)
{
// Clear the Screen
glClear(GL_COLOR_BUFFER_BIT);

float colors[6][3] = { { 1,0,0 },{ 1,1,0 },{ 0,1,0 },{ 0,1,1 },{ 1,0,1 },{0,0,1} };
float data[6] = { 20,66,42,28,71,23 };
float x = 0, y = 0;
float dy;

glBegin(GL_QUADS);
for (int i = 0; i < 6; i++) {
    glColor3f(colors[i][0], colors[i][1], colors[i][2]);
    dy = data[i];
    glVertex2f(x, y);
    glVertex2f(x + 5, y);
    glVertex2f(x + 5, y + dy);
    glVertex2f(x, y + dy);
    y  = dy;
    //x +=5; incremented x just to see how the pieces are positioned
}
glEnd();

// force execution of GL commands
glFlush();
}

output:

result

result with x incremented with 5 just to see the pieces are positioned

Body:
If you want to stack the bars on top of each other, just increment y in each iteration by dy.

for (int i = 0; i < 6; i++) {
    glColor3f(colors[i][0], colors[i][1], colors[i][2]);
    dy = data[i];
    glVertex2f(x, y);
    glVertex2f(x + 5, y);
    glVertex2f(x + 5, y + dy);
    glVertex2f(x, y + dy);
    y += dy;
}


问:
Concurrency: Processes vs Threads
What are the main advantages of using a model for concurrency based on processes over one
based on threads and in what contexts is the latter appropriate?</p>

答:
First and foremost, processes differ from threads mostly in the way their memory is handled:

```<code>Process = n*Thread + memory region  (n>=1)
</code>```

Processes have their own isolated memory.
Processes can have multiple threads.

Processes are isolated from each other on the operating system level.
Threads share their memory with their peers in the process.
(This is often undesirable. There are libraries and methods out there to remedy this, but that is usually an artificial layer over operating system threads.)

The memory thing is the most important discerning factor, as it has certain implications:

Exchanging data between processes is slower than between threads. Breaking the process isolation always requires some involvement of kernel calls and memory remapping.

Threads are more lightweight than processes. The operating system has to allocate resources and do memory management for each process.

Using processes gives you memory isolation and synchronization. Common problems with access to memory shared between threads do not concern you. Since you have to make a special effort to share data between processes, you will most likely sync automatically with that.

Using processes gives you good (or ultimate) encapsulation. Since inter process communication needs special effort, you will be forced to define a clean interface. It is a good idea to break certain parts of your application out of the main executable. Maybe you can split dependencies like that.
e.g. Process_RobotAi <-> Process_RobotControl
The AI will have vastly different dependencies compared to the control component. The interface might be simple: Process_RobotAI --DriveXY--> Process_RobotControl.
Maybe you change the robot platform. You only have to implement a new RobotControl executable with that simple interface. You don't have to touch or even recompile anything in your AI component.

It will also, for the same reasons, speed up compilation in most cases.

Edit: Just for completeness I will shamelessly add what the others have reminded me of :
A crashing process does not (necessarily) crash your whole application.

In General:

Want to create something highly concurrent or synchronuous, like an algorithm with n>>1 instances running in parallel and sharing data, use threads.

Have a system with multiple components that do not need to share data or algorithms, nor do they exchange data too often, use processes. If you use a RPC library for the inter process communication, you get a network-distributable solution at no extra cost.

1 and 2 are the extreme and no-brainer scenarios, everything in between must be decided individually.

For a good (or awesome) example of a system that uses IPC/RPC heavily, have a look at ros.

Title: Concurrency: Processes vs Threads

Body:
First and foremost, processes differ from threads mostly in the way their memory is handled:

Process = n*Thread + memory region  (n>=1)

Processes have their own isolated memory.
Processes can have multiple threads.

Processes are isolated from each other on the operating system level.
Threads share their memory with their peers in the process.
(This is often undesirable. There are libraries and methods out there to remedy this, but that is usually an artificial layer over operating system threads.)

The memory thing is the most important discerning factor, as it has certain implications:

Exchanging data between processes is slower than between threads. Breaking the process isolation always requires some involvement of kernel calls and memory remapping.

Threads are more lightweight than processes. The operating system has to allocate resources and do memory management for each process.

Using processes gives you memory isolation and synchronization. Common problems with access to memory shared between threads do not concern you. Since you have to make a special effort to share data between processes, you will most likely sync automatically with that.

Using processes gives you good (or ultimate) encapsulation. Since inter process communication needs special effort, you will be forced to define a clean interface. It is a good idea to break certain parts of your application out of the main executable. Maybe you can split dependencies like that.
e.g. Process_RobotAi <-> Process_RobotControl
The AI will have vastly different dependencies compared to the control component. The interface might be simple: Process_RobotAI --DriveXY--> Process_RobotControl.
Maybe you change the robot platform. You only have to implement a new RobotControl executable with that simple interface. You don't have to touch or even recompile anything in your AI component.

It will also, for the same reasons, speed up compilation in most cases.

Edit: Just for completeness I will shamelessly add what the others have reminded me of :
A crashing process does not (necessarily) crash your whole application.

In General:

Want to create something highly concurrent or synchronuous, like an algorithm with n>>1 instances running in parallel and sharing data, use threads.

Have a system with multiple components that do not need to share data or algorithms, nor do they exchange data too often, use processes. If you use a RPC library for the inter process communication, you get a network-distributable solution at no extra cost.

1 and 2 are the extreme and no-brainer scenarios, everything in between must be decided individually.

For a good (or awesome) example of a system that uses IPC/RPC heavily, have a look at ros.


问:
Node stops responding after a while
My node server is running normally. Working with absolutely no issues.
Then at a certain (random?) point in time, it stops responding to requests.
(It did respond for hours uninterrupted before.)

There are no errors. The server is still able to do internal processes, but is not responding to requests.

With that, the requests are making their way to the server as the log shows:

```<code>GET / - - ms - -
GET / - - ms - -
GET /upload - - ms - -
GET /profile - - ms - -
</code>```

I can't figure out when it is triggered, what is happening, and why it's happening.

Once the server stopped responding, it will never respond again. Restarting the server solves the issue until it happens again.

Anybody ever encountered this behavior?

Update:

The server never crashes, just stops responding.

This app is over a year old, and was working fine, so I doubt it's a basic, but rather something else.

Recent change: Started using YouTube SPF

Recent change: Connecting to a MongoDB on a remote server rather than localhost

Again, the server never crashes, just stop responding.

These are the components I am using for the server:

```<code>var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
var morgan = require('morgan');
var cookieParse = require('cookie-parser');
var session = require('express-session');
var mongoose = require ('mongoose');
var bodyParser = require('body-parser');
var configDB = require('./config/database');
var passport = require('passport');
var flash = require('connect-flash');
var MongoStore = require('connect-mongo')(session);
var https = require("https");
var path = require('path');
var helmet = require ("helmet");
var robots = require("express-robots");
var Sitemap = require('sitemap')
var async = require('async')
var cron = require('node-schedule');
var compression = require('compression')
</code>```

Update:

Added annotated pm2 logs:

```<code>0|server   | GET /public/js/fullscreen.js 304 72.626 ms - -
0|server   | GET /public/js/mathUtils.js 304 72.291 ms - -
0|server   | GET /public/js/snap.svg.js 304 74.047 ms - -
0|server   | GET /views/58dc059bf5ac4394447e7a4d/82z7rw8qbvgqfr 304 95.918 ms - -
0|server   | GET /public/js/playerTransport.js 304 96.425 ms - -
0|server   | GET /public/res/img/rightarrow.png 304 82.923 ms - -
0|server   | GET /public/res/img/BecomicsLogo.png 304 93.323 ms - -
0|server   | GET /public/res/img/leftarrow.png 304 84.158 ms - -
0|server   | GET /public/res/img/fullscreen.png 304 93.776 ms - -
0|server   | GET /public/fonts/foundation-icons.woff 304 61.611 ms - -
0|server   | GET /public/images/ui-bg_glass_100_f6f6f6_1x400.png 404 57.253 ms - 39
0|server   | GET /public/images/ui-icons_ef8c08_256x240.png 404 57.646 ms - 39
0|server   | POST /rating/get 200 111.758 ms - 37
0|server   | POST /player/getBook?id=58dc059bf5ac4394447e7a4d 200 99.961 ms - -
0|server   | GET /public/res/img/loading.gif 304 70.614 ms - -
0|server   | POST /stats/pageView 200 73.545 ms - 2
0|server   | GET /subscriptions 304 655.215 ms - -
0|server   | GET /public/css/discover.css 304 72.171 ms - -
0|server   | GET /public/css/becomics.css 304 73.344 ms - -
0|server   | GET /public/js/spf.js 304 65.621 ms - -
0|server   | GET /public/res/img/hamburgerMenu.png 304 58.525 ms - -

0|server   | POST /subscriptions/count 200 111.033 ms - 11 <--- This is the last time the server will respond
0|server   | GET /profile/5825063e47234fc77cbc7694/$otherUserPic - - ms - -
0|server   | GET /profile/5825063e47234fc77cbc7694/$picTheWhat - - ms - -

0|server   | So far so good <--This prints just before the res.send(). It verifies that the request makes it all the way to the response. But still. No response...
0|server   | So far so good
0|server   | GET /profile/5825063e47234fc77cbc7694/$otherUserPic - - ms - -
0|server   | GET /profile/5825063e47234fc77cbc7694/$picTheWhat - - ms - -
0|server   | GET /subscriptions - - ms - -
0|server   | GET /profile/5825063e47234fc77cbc7694 - - ms - -
0|server   | GET /profile/5825063e47234fc77cbc7694 - - ms - -

0|server   | Counting Views. <--- this is a croned operation. It executes with no problem. Even after server stopped responding.
0|server   | GET /profile/5825063e47234fc77cbc7694 - - ms - -
0|server   | GET / - - ms - -
0|server   | GET /profile/5806a8116b9b49b4201f5487 - - ms - -
0|server   | GET /trendy?spf=navigate - - ms - -
0|server   | GET /trendy?spf=navigate - - ms - -
0|server   | GET /fresh?spf=navigate - - ms - -
0|server   | GET /series/58dc032ef5ac4394447e7a3c - - ms - -
0|server   | GET / - - ms - -
0|server   | GET /featured?spf=navigate - - ms - -
0|server   | GET / - - ms - -
0|server   | GET /featured - - ms - -
0|server   | GET / - - ms - -
0|server   | GET /ping - - ms - -
</code>```

As you can see. No errors. Any ideas?

Also note that /ping is a route that is just supposed to return status 200. No db querying, no nothing. The simplest response possible, and that fails too.

Update
Tried using different browser + chrome's incognito to verify that it is not a cache issue. Still no response.

PM2 Monit:

```<code>Mem: 140MB CPU:0%
Loop delay 1.46ms
</code>```

CPU Profile:

Heap snapshot

Update 4/2/2017:
After some debugging I think it has to do with a disconnect from the remote server... Once I resolve this I will post answer.

Update 4/3/2017
Here is my mongooose connect code:

```<code>mongoose.connect(configDB.url,{user:configDB.user,pass:configDB.pwd,server:{reconnectTries:60,reconnectInterval:1000}});
// CONNECTION EVENTS
// When successfully connected
mongoose.connection.on('connected', function () {
    console.log('Mongoose default connection open to ' + configDB.url);
});

// If the connection throws an error
mongoose.connection.on('error',function (err) {
    console.log('Mongoose default connection error: ' + err);
    console.log("Disconnecting")
    mongoose.disconnect();
});
// When the connection is disconnected
mongoose.connection.on('disconnected', function () {
    console.log('Mongoose default connection disconnected');
    //It automatically reconnects with not issues
});
</code>```

The thing is, non of these listeners fire when my problem occurs. No errors or exceptions thrown. No disconnect triggered. Just Halts..

答:
It would be better if you could share your code so that we're more clear about the problem.

If you're using express, It could simply be the wrong ordering of app.use , or its possible that you have a faulty middleware. You can use a debugger or just find out on which requests your server crashes and give it a fix .

Title: Node stops responding after a while

Body:
My node server is running normally. Working with absolutely no issues.
Then at a certain (random?) point in time, it stops responding to requests.
(It did respond for hours uninterrupted before.)

There are no errors. The server is still able to do internal processes, but is not responding to requests.

With that, the requests are making their way to the server as the log shows:

GET / - - ms - -
GET / - - ms - -
GET /upload - - ms - -
GET /profile - - ms - -

I can't figure out when it is triggered, what is happening, and why it's happening.

Once the server stopped responding, it will never respond again. Restarting the server solves the issue until it happens again.

Anybody ever encountered this behavior?

Update:

The server never crashes, just stops responding.

This app is over a year old, and was working fine, so I doubt it's a basic, but rather something else.

Recent change: Started using YouTube SPF

Recent change: Connecting to a MongoDB on a remote server rather than localhost

Again, the server never crashes, just stop responding.

These are the components I am using for the server:

var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
var morgan = require('morgan');
var cookieParse = require('cookie-parser');
var session = require('express-session');
var mongoose = require ('mongoose');
var bodyParser = require('body-parser');
var configDB = require('./config/database');
var passport = require('passport');
var flash = require('connect-flash');
var MongoStore = require('connect-mongo')(session);
var https = require("https");
var path = require('path');
var helmet = require ("helmet");
var robots = require("express-robots");
var Sitemap = require('sitemap')
var async = require('async')
var cron = require('node-schedule');
var compression = require('compression')

Update:

Added annotated pm2 logs:

0|server   | GET /public/js/fullscreen.js 304 72.626 ms - -
0|server   | GET /public/js/mathUtils.js 304 72.291 ms - -
0|server   | GET /public/js/snap.svg.js 304 74.047 ms - -
0|server   | GET /views/58dc059bf5ac4394447e7a4d/82z7rw8qbvgqfr 304 95.918 ms - -
0|server   | GET /public/js/playerTransport.js 304 96.425 ms - -
0|server   | GET /public/res/img/rightarrow.png 304 82.923 ms - -
0|server   | GET /public/res/img/BecomicsLogo.png 304 93.323 ms - -
0|server   | GET /public/res/img/leftarrow.png 304 84.158 ms - -
0|server   | GET /public/res/img/fullscreen.png 304 93.776 ms - -
0|server   | GET /public/fonts/foundation-icons.woff 304 61.611 ms - -
0|server   | GET /public/images/ui-bg_glass_100_f6f6f6_1x400.png 404 57.253 ms - 39
0|server   | GET /public/images/ui-icons_ef8c08_256x240.png 404 57.646 ms - 39
0|server   | POST /rating/get 200 111.758 ms - 37
0|server   | POST /player/getBook?id=58dc059bf5ac4394447e7a4d 200 99.961 ms - -
0|server   | GET /public/res/img/loading.gif 304 70.614 ms - -
0|server   | POST /stats/pageView 200 73.545 ms - 2
0|server   | GET /subscriptions 304 655.215 ms - -
0|server   | GET /public/css/discover.css 304 72.171 ms - -
0|server   | GET /public/css/becomics.css 304 73.344 ms - -
0|server   | GET /public/js/spf.js 304 65.621 ms - -
0|server   | GET /public/res/img/hamburgerMenu.png 304 58.525 ms - -

0|server   | POST /subscriptions/count 200 111.033 ms - 11 <--- This is the last time the server will respond
0|server   | GET /profile/5825063e47234fc77cbc7694/$otherUserPic - - ms - -
0|server   | GET /profile/5825063e47234fc77cbc7694/$picTheWhat - - ms - -

0|server   | So far so good <--This prints just before the res.send(). It verifies that the request makes it all the way to the response. But still. No response...
0|server   | So far so good
0|server   | GET /profile/5825063e47234fc77cbc7694/$otherUserPic - - ms - -
0|server   | GET /profile/5825063e47234fc77cbc7694/$picTheWhat - - ms - -
0|server   | GET /subscriptions - - ms - -
0|server   | GET /profile/5825063e47234fc77cbc7694 - - ms - -
0|server   | GET /profile/5825063e47234fc77cbc7694 - - ms - -

0|server   | Counting Views. <--- this is a croned operation. It executes with no problem. Even after server stopped responding.
0|server   | GET /profile/5825063e47234fc77cbc7694 - - ms - -
0|server   | GET / - - ms - -
0|server   | GET /profile/5806a8116b9b49b4201f5487 - - ms - -
0|server   | GET /trendy?spf=navigate - - ms - -
0|server   | GET /trendy?spf=navigate - - ms - -
0|server   | GET /fresh?spf=navigate - - ms - -
0|server   | GET /series/58dc032ef5ac4394447e7a3c - - ms - -
0|server   | GET / - - ms - -
0|server   | GET /featured?spf=navigate - - ms - -
0|server   | GET / - - ms - -
0|server   | GET /featured - - ms - -
0|server   | GET / - - ms - -
0|server   | GET /ping - - ms - -

As you can see. No errors. Any ideas?

Also note that /ping is a route that is just supposed to return status 200. No db querying, no nothing. The simplest response possible, and that fails too.

Update
Tried using different browser + chrome's incognito to verify that it is not a cache issue. Still no response.

PM2 Monit:

Mem: 140MB CPU:0%
Loop delay 1.46ms

CPU Profile:

Heap snapshot

Update 4/2/2017:
After some debugging I think it has to do with a disconnect from the remote server... Once I resolve this I will post answer.

Update 4/3/2017
Here is my mongooose connect code:

mongoose.connect(configDB.url,{user:configDB.user,pass:configDB.pwd,server:{reconnectTries:60,reconnectInterval:1000}});
// CONNECTION EVENTS
// When successfully connected
mongoose.connection.on('connected', function () {
    console.log('Mongoose default connection open to ' + configDB.url);
});

// If the connection throws an error
mongoose.connection.on('error',function (err) {
    console.log('Mongoose default connection error: ' + err);
    console.log("Disconnecting")
    mongoose.disconnect();
});
// When the connection is disconnected
mongoose.connection.on('disconnected', function () {
    console.log('Mongoose default connection disconnected');
    //It automatically reconnects with not issues
});

The thing is, non of these listeners fire when my problem occurs. No errors or exceptions thrown. No disconnect triggered. Just Halts..


问:
Cron job does not load virtualenv env var for working with django.setup()
Well, I have a project structure like this one:

```<code>my_project
   |-scripts
   |  |- my_script.py
   |
   |-django_project
      |- myApp
      |  |- models.py
      |  |- ...
      |- django_project
         |- settings.py
         |- ...
</code>```

I run Django inside a virtualenv and in my_script.py I have to use some of myApp.models

So, here is how I did:

my_script.py:

```<code>#!/usr/bin/env python
import django
django.setup()

from myApp.models import foo

# do things
</code>```

Since I am inside a virtualenv, to make django.setup() work properly I set in my virtualenv ($VIRTUAL_ENV/bin/postactivate):

```<code>export DJANGO_SETTINGS_MODULE = django_project.settings
</code>```

and I added django_project to the path:

```<code>$ workon my_virtualenv
$ python -c "import sys; print sys.path"
['', '/my_project/django_project', ...]
</code>```

And that's all.

If I activate my virtualenv and then I run my_script.py all works fine.

But If I schedule a similar cron job:

00 00 * * * /.../.virtualenvs/my_virtualenv/bin/python /.../my_project/scripts/my_script.py >> /.../test/test.log 2>&1

I get this error:

django.core.exceptions.ImproperlyConfigured: Requested setting
  LOGGING_CONFIG, but settings are not configured. You must either
  define the environment variable DJANGO_SETTINGS_MODULE or call
  settings.configure() before accessing settings.

It seems like my_virtualenv activation settings are not properly loaded.

Why does this happen, and how can I fix?

答:
We use a small shell script to activate the virtualenv:

```<code>$ cat run-python.sh
#!/bin/bash

# put run-python.sh's directory on path (probably not needed, we call
# auxiliary scripts in the same directory)
myname="$0"
binprefix="$(dirname ${myname})"
export PATH=${binprefix}:${PATH}

VENV_DIR = '/path/to/venv/root'

# activate virtualenv
pushd ${VENV_DIR} > /dev/null
. bin/activate
popd > /dev/null

# set DJANGO_SETTINGS_MODULE
if [ "x$DJANGO_SETTINGS_MODULE" == "x" ]; then
  export DJANGO_SETTINGS_MODULE="default.settings"
else
  export DJANGO_SETTINGS_MODULE
fi

exec python $@
</code>```

and use it in crontab like:

```<code>0/15 * * * *    DJANGO_SETTINGS_MODULE=myapp.settings run-python.sh /path/to/python/script.py
</code>```

Body:
Well, I have a project structure like this one:

my_project
   |-scripts
   |  |- my_script.py
   |
   |-django_project
      |- myApp
      |  |- models.py
      |  |- ...
      |- django_project
         |- settings.py
         |- ...

I run Django inside a virtualenv and in my_script.py I have to use some of myApp.models

So, here is how I did:

my_script.py:

#!/usr/bin/env python
import django
django.setup()

from myApp.models import foo

# do things

Since I am inside a virtualenv, to make django.setup() work properly I set in my virtualenv ($VIRTUAL_ENV/bin/postactivate):

export DJANGO_SETTINGS_MODULE = django_project.settings

and I added django_project to the path:

$ workon my_virtualenv
$ python -c "import sys; print sys.path"
['', '/my_project/django_project', ...]

And that's all.

If I activate my virtualenv and then I run my_script.py all works fine.

But If I schedule a similar cron job:

00 00 * * * /.../.virtualenvs/my_virtualenv/bin/python /.../my_project/scripts/my_script.py >> /.../test/test.log 2>&1

I get this error:

django.core.exceptions.ImproperlyConfigured: Requested setting
  LOGGING_CONFIG, but settings are not configured. You must either
  define the environment variable DJANGO_SETTINGS_MODULE or call
  settings.configure() before accessing settings.

It seems like my_virtualenv activation settings are not properly loaded.

Why does this happen, and how can I fix?

Body:
We use a small shell script to activate the virtualenv:

$ cat run-python.sh
#!/bin/bash

# put run-python.sh's directory on path (probably not needed, we call
# auxiliary scripts in the same directory)
myname="$0"
binprefix="$(dirname ${myname})"
export PATH=${binprefix}:${PATH}

VENV_DIR = '/path/to/venv/root'

# activate virtualenv
pushd ${VENV_DIR} > /dev/null
. bin/activate
popd > /dev/null

# set DJANGO_SETTINGS_MODULE
if [ "x$DJANGO_SETTINGS_MODULE" == "x" ]; then
  export DJANGO_SETTINGS_MODULE="default.settings"
else
  export DJANGO_SETTINGS_MODULE
fi

exec python $@

and use it in crontab like:

0/15 * * * *    DJANGO_SETTINGS_MODULE=myapp.settings run-python.sh /path/to/python/script.py


问:
instance Of Operator in java
```<code>class A {}

class B {}

public class Demo {

    public static void main(String[] args) {

        A a = new A();
        System.out.println(a instanceof B);
    }

}
</code>```

This code is giving compile time error.
How can I use instanceof to give false instead of compile time error when object is not an instance of class specified.

答:
Java knows an A cannot be a B so it won't compile. If you change the line to

```<code>Object a = new A();
</code>```

it will compile (and return false) as it can no longer tell if an Object can be cast into type B.

Title: instance Of Operator in java

Body:
class A {}

class B {}

public class Demo {

    public static void main(String[] args) {

        A a = new A();
        System.out.println(a instanceof B);
    }

}

This code is giving compile time error.
How can I use instanceof to give false instead of compile time error when object is not an instance of class specified.

Body:
Java knows an A cannot be a B so it won't compile. If you change the line to

Object a = new A();

it will compile (and return false) as it can no longer tell if an Object can be cast into type B.


问:
security / codesign in Sierra: Keychain ignores access control settings and UI-prompts for permission
Starting with macOS Sierra, I can't import a codesign-identity into a keychain with /usr/bin/security any more without usr/bin/codesign UI-prompting for access when using this identity. This breaks the packaging scripts of build server. There seems to be no workaround. This affects custom created keychains, but also the login.keychain.

Steps to Reproduce:
Execute the following commands in Terminal (requires a signing identity to be available to import):

```<code>security create-keychain -p test buildagent.keychain
security unlock-keychain -p test buildagent.keychain

security list-keychains -d user -s buildagent.keychain
security default-keychain -s buildagent.keychain

security import identity.p12 -k buildagent.keychain -P password -T /usr/bin/codesign

codesign -vfs '$IDENTITY' '${PRODUCT}' --keychain 'buildagent.keychain'
</code>```

Result: macOS shows a UI-prompt asking for permission to access the previously imported private key.

I have tried many workarounds, but nothing seems to work:

Using the new .keychain-db extension when specifying the keychain-name

Using the login.keychain instead of the custom one

Importing the p12 with -A ('Allow any application to access the
imported key')

Importing the Cert und Key separately (being extracted
from the p12 before with openssl pkcs12)

Importing the identity definitely works, I can see the cert and key when displaying the contents of the keychain in the Keychain Access application. The access control setting for the private key is also correctly configured (with the desired codesign exception rule).

How can I avoid the UI prompt from Sierra?

答:
The command from this answer only unlocked the keychain for me, but I still had the UI-prompt asking  whether the current application could use the key.

I prevented the prompt like this:

Go to the keychain in Keychain Access, double click on all the keys there, and in the tab Access Control, check 'Allow all applications to access this item'.

I was able to upload the new keychain file then to my Jenkins build server, where it is unlocked by the Keychains and Provisioning Profiles Plugin. The build now succeeds signing.

Body:
Starting with macOS Sierra, I can't import a codesign-identity into a keychain with /usr/bin/security any more without usr/bin/codesign UI-prompting for access when using this identity. This breaks the packaging scripts of build server. There seems to be no workaround. This affects custom created keychains, but also the login.keychain.

Steps to Reproduce:
Execute the following commands in Terminal (requires a signing identity to be available to import):

security create-keychain -p test buildagent.keychain
security unlock-keychain -p test buildagent.keychain

security list-keychains -d user -s buildagent.keychain
security default-keychain -s buildagent.keychain

security import identity.p12 -k buildagent.keychain -P password -T /usr/bin/codesign

codesign -vfs '$IDENTITY' '${PRODUCT}' --keychain 'buildagent.keychain'

Result: macOS shows a UI-prompt asking for permission to access the previously imported private key.

I have tried many workarounds, but nothing seems to work:

Using the new .keychain-db extension when specifying the keychain-name

Using the login.keychain instead of the custom one

Importing the p12 with -A ('Allow any application to access the
imported key')

Importing the Cert und Key separately (being extracted
from the p12 before with openssl pkcs12)

Importing the identity definitely works, I can see the cert and key when displaying the contents of the keychain in the Keychain Access application. The access control setting for the private key is also correctly configured (with the desired codesign exception rule).

How can I avoid the UI prompt from Sierra?