问:
check if there are two or more equal values in Json
How I should process this Json, to extract the cat1 value once in a Spinner, and in the second Spinner based on the first spinner selection I display book1 and book2.

Json:

```<code>{
 "library":
[
{
   "Cat": "cat1",
   "Book": "book1",
   "authur": "authur1"
 },
 {
   "Cat": "cat1",
   "Book": "book2",
   "authur": "authur2"
 },
 {
   "Cat": "cat2",
   "Book": "book3",
   "authur": "authur3"
 }
]
}
</code>```

答:
Parse your JSON data and store it into ArrayList and populate it on Spinner using ArrayAdapter.

Here is a sample code for parsing your JSON data:

```<code>public void parseJson() {
    String response = "{\n" +
            " \"library\":\n" +
            "[\n" +
            "{\n" +
            "   \"Cat\": \"cat1\",\n" +
            "   \"Book\": \"book1\",\n" +
            "   \"authur\": \"authur1\"\n" +
            " },\n" +
            " {\n" +
            "   \"Cat\": \"cat1\",\n" +
            "   \"Book\": \"book2\",\n" +
            "   \"authur\": \"authur2\"\n" +
            " },\n" +
            " {\n" +
            "   \"Cat\": \"cat2\",\n" +
            "   \"Book\": \"book3\",\n" +
            "   \"authur\": \"authur3\"\n" +
            " }\n" +
            "]\n" +
            "}";

    try {
        JSONObject mJsonObject = new JSONObject(response);
        JSONArray libraryJsonArray = mJsonObject.getJSONArray("library");

        ArrayList<String> cats = new ArrayList<>();
        ArrayList<String> books = new ArrayList<>();
        ArrayList<String> authors = new ArrayList<>();

        // Get all jsonObject from jsonArray
        for (int i = 0; i < libraryJsonArray.length(); i++)
        {
            JSONObject jsonObject = libraryJsonArray.getJSONObject(i);

            // Cat
            if (jsonObject.has("Cat") && !jsonObject.isNull("Cat")) {
                cats.add(jsonObject.getString("Cat"));
            }

            // Book
            if (jsonObject.has("Book") && !jsonObject.isNull("Book")) {
                books.add(jsonObject.getString("Book"));
            }

            // Author
            if (jsonObject.has("authur") && !jsonObject.isNull("authur")) {
                authors.add(jsonObject.getString("authur"));
            }

            Log.d("SUCCESS", "JSON Object: " + "\nCat: " + cats.get(i)
                    + "\nBook: " + books.get(i) + "\nAuthor: " + authors.get(i));

            // Do something with ArrayList cats, books and authors
        }
    } catch (JSONException e) {
        Log.e("FAILED", "Json parsing error: " + e.getMessage());
    }
}
</code>```

OUTPUT:

```<code>D/SUCCESS: JSON Object:
           Cat: cat1
           Book: book1
           Author: authur1

D/SUCCESS: JSON Object:
           Cat: cat1
           Book: book2
           Author: authur2

D/SUCCESS: JSON Object:
           Cat: cat2
           Book: book3
           Author: authur3
</code>```

Body:
How I should process this Json, to extract the cat1 value once in a Spinner, and in the second Spinner based on the first spinner selection I display book1 and book2.

Json:

{
 "library":
[
{
   "Cat": "cat1",
   "Book": "book1",
   "authur": "authur1"
 },
 {
   "Cat": "cat1",
   "Book": "book2",
   "authur": "authur2"
 },
 {
   "Cat": "cat2",
   "Book": "book3",
   "authur": "authur3"
 }
]
}

Body:
Parse your JSON data and store it into ArrayList and populate it on Spinner using ArrayAdapter.

Here is a sample code for parsing your JSON data:

public void parseJson() {
    String response = "{\n" +
            " \"library\":\n" +
            "[\n" +
            "{\n" +
            "   \"Cat\": \"cat1\",\n" +
            "   \"Book\": \"book1\",\n" +
            "   \"authur\": \"authur1\"\n" +
            " },\n" +
            " {\n" +
            "   \"Cat\": \"cat1\",\n" +
            "   \"Book\": \"book2\",\n" +
            "   \"authur\": \"authur2\"\n" +
            " },\n" +
            " {\n" +
            "   \"Cat\": \"cat2\",\n" +
            "   \"Book\": \"book3\",\n" +
            "   \"authur\": \"authur3\"\n" +
            " }\n" +
            "]\n" +
            "}";

    try {
        JSONObject mJsonObject = new JSONObject(response);
        JSONArray libraryJsonArray = mJsonObject.getJSONArray("library");

        ArrayList<String> cats = new ArrayList<>();
        ArrayList<String> books = new ArrayList<>();
        ArrayList<String> authors = new ArrayList<>();

        // Get all jsonObject from jsonArray
        for (int i = 0; i < libraryJsonArray.length(); i++)
        {
            JSONObject jsonObject = libraryJsonArray.getJSONObject(i);

            // Cat
            if (jsonObject.has("Cat") && !jsonObject.isNull("Cat")) {
                cats.add(jsonObject.getString("Cat"));
            }

            // Book
            if (jsonObject.has("Book") && !jsonObject.isNull("Book")) {
                books.add(jsonObject.getString("Book"));
            }

            // Author
            if (jsonObject.has("authur") && !jsonObject.isNull("authur")) {
                authors.add(jsonObject.getString("authur"));
            }

            Log.d("SUCCESS", "JSON Object: " + "\nCat: " + cats.get(i)
                    + "\nBook: " + books.get(i) + "\nAuthor: " + authors.get(i));

            // Do something with ArrayList cats, books and authors
        }
    } catch (JSONException e) {
        Log.e("FAILED", "Json parsing error: " + e.getMessage());
    }
}

OUTPUT:

D/SUCCESS: JSON Object:
           Cat: cat1
           Book: book1
           Author: authur1

D/SUCCESS: JSON Object:
           Cat: cat1
           Book: book2
           Author: authur2

D/SUCCESS: JSON Object:
           Cat: cat2
           Book: book3
           Author: authur3


来源: stackexchange

问:
Trying to parse JSON Object from POST Request in Express v4 using body-parser
I'm currently teaching myself more about server code, specifically using Node.js and Express, and I'm having a lot of trouble with receiving and parsing a JSON object sent from a POST request. I have looked at numerous other posts (linked to below) and I can't figure out for the life of me what's going wrong. Here's what I've looked at:

Javascript: Send JSON Object with AJAX
Javascript : Send JSON Object with Ajax?
How do I consume the JSON POST data in an Express application
How do I consume the JSON POST data in an Express application
Send POST data using XMLHttpRequest
Send POST data using XMLHttpRequest
How do you extract POST data in Node.js?
How do you extract POST data in Node.js?

All of these are putting me on the right track, but I'm not quite there and thus looking for help. Here's the code I'm working with:

Send POST Request

```<code>var button = document.querySelector("#button");

button.onclick = function(){
    console.log("Getting data from local server");

    var xhr = new XMLHttpRequest();

    xhr.open("POST", "http://localhost:3000/data/test.json", true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send(JSON.stringify({"latitude": 41.2418, "longitude": -70.8898}));
};
</code>```

Handle POST Request In Server

```<code>var http = require("http");
var fs = require("fs");
var express = require("express");
var app = express();
var path = require("path");
var bodyParser = require("body-parser");

var port = process.env.PORT || 3000;
//tells express where to find all the static files (HTML, CSS, etc) and load them into the browser
app.use(express.static(path.join(__dirname, '../client')));

//tells the application to use body-parser as middleware so it can handle post requests
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

//routing methods
//deal with incoming GET and POST requests to the server
app.get("/", function(req, res){
    res.send("Submitted GET Request");
})

//only handles incoming POST requests to the test.json resource
app.post("/data/test.json", function(req, res){
    console.info("Submitting POST Request to Server");
    console.info("Request body: " + req.body);
    //write the file
    fs.writeFile(__dirname + "/../client/data/test.json", req.body,
    function(err){
        if(err){
            console.error(err); //print out the error in case there is one
            return res.status(500).json(err);
        }

        //resolve the request with the client
        console.info("updated test.json");
        res.send();
    });
})

//tell the express object to create the server and listen on the port
app.listen(port);
console.log("Listening on localhost:" + port);
</code>```

Whenever I try to print out the contents of "req.body" I get the output of "[object Object]". Any ideas?

EDIT:
My issue has been solved. I have changed

```<code>console.info("Request body: " + req.body);
</code>```

To

```<code>console.info("Request body: " + JSON.stringify(req.body));
</code>```

I also changed my Content-Type in my POST XMLHTTPRequest to "application/json" to help with formatting.

答:
If your post body is expected to be JSON, then change this line

```<code>xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
</code>```

To

```<code> xhr.setRequestHeader("Content-Type", "application/json");
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm currently teaching myself more about server code, specifically using Node.js and Express, and I'm having a lot of trouble with receiving and parsing a JSON object sent from a POST request. I have looked at numerous other posts (linked to below) and I can't figure out for the life of me what's going wrong. Here's what I've looked at:

Javascript: Send JSON Object with AJAX
Javascript : Send JSON Object with Ajax?
How do I consume the JSON POST data in an Express application
How do I consume the JSON POST data in an Express application
Send POST data using XMLHttpRequest
Send POST data using XMLHttpRequest
How do you extract POST data in Node.js?
How do you extract POST data in Node.js?

All of these are putting me on the right track, but I'm not quite there and thus looking for help. Here's the code I'm working with:

Send POST Request

var button = document.querySelector("#button");

button.onclick = function(){
    console.log("Getting data from local server");

    var xhr = new XMLHttpRequest();

    xhr.open("POST", "http://localhost:3000/data/test.json", true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send(JSON.stringify({"latitude": 41.2418, "longitude": -70.8898}));
};

Handle POST Request In Server

var http = require("http");
var fs = require("fs");
var express = require("express");
var app = express();
var path = require("path");
var bodyParser = require("body-parser");

var port = process.env.PORT || 3000;
//tells express where to find all the static files (HTML, CSS, etc) and load them into the browser
app.use(express.static(path.join(__dirname, '../client')));

//tells the application to use body-parser as middleware so it can handle post requests
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

//routing methods
//deal with incoming GET and POST requests to the server
app.get("/", function(req, res){
    res.send("Submitted GET Request");
})

//only handles incoming POST requests to the test.json resource
app.post("/data/test.json", function(req, res){
    console.info("Submitting POST Request to Server");
    console.info("Request body: " + req.body);
    //write the file
    fs.writeFile(__dirname + "/../client/data/test.json", req.body,
    function(err){
        if(err){
            console.error(err); //print out the error in case there is one
            return res.status(500).json(err);
        }

        //resolve the request with the client
        console.info("updated test.json");
        res.send();
    });
})

//tell the express object to create the server and listen on the port
app.listen(port);
console.log("Listening on localhost:" + port);

Whenever I try to print out the contents of "req.body" I get the output of "[object Object]". Any ideas?

EDIT:
My issue has been solved. I have changed

console.info("Request body: " + req.body);

To

console.info("Request body: " + JSON.stringify(req.body));

I also changed my Content-Type in my POST XMLHTTPRequest to "application/json" to help with formatting.

Body:
If your post body is expected to be JSON, then change this line

xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

To

 xhr.setRequestHeader("Content-Type", "application/json");


问:
convert to show percentage of the sum of 2 or more combined columns
I have looked at the similar questions and was unable to find anything that answered my question.

I have a column that is the calculation of other columns of which sum I would like to divide by a set number and show results in percentage from. I have tried the below query and am able to show in decimal. Basically find out what percentage of UPH an associate is doing...This way I can tell if they are slacking in their department or exceling. I am using 150 as my base rate

```<code>SELECT
ID
  , DeptCode AS 'DC'
  , OpCode AS 'OC'
  ,Units = sum(Units)
  ,UPH = cast(isnull(sum(Units) / nullif(sum(datediff(minute,StartTime,FinishTime))*1.0,0),0.0)*60  as decimal(10,0))
  ,Percentage = cast(isnull(sum(Units) / nullif(sum(datediff(minute,StartTime,FinishTime))*1.0,0),0.0)*60  as decimal(10,0)) / 150

FROM dbo.TimeLog
 WITH (NOLOCK)

WHERE DeptCode = 'FB'
  and OpCode   = 'PU'
  and Units IS NOT NULL
GROUP BY
    ID
  , DeptCode
  , OpCode
</code>```

Here is my result...

```<code>ID      DC  OC  Units   UPH Percentage
11259   FB  PU  553     114 0.760000
2375935 FB  PU  263     70  0.466666
</code>```

I would like to see column 'Percentage' like the below

```<code>ID      DC  OC  Units   UPH Percentage
11259   FB  PU  553     114 76%
2375935 FB  PU  263     70  47%
</code>```

Any help would be appreciated and I apologize in advance if this is elementary for a lot you, I am relatively new to SQL

答:
Try this instead (SQL 2012 and later):

Percentage = CONCAT(cast(isnull(sum(Units) /
  nullif(sum(datediff(minute,StartTime,FinishTime))*1.0,0),0.0)*60  as
  decimal(10,0)), '%')

Refer: https://learn.microsoft.com/en-us/sql/t-sql/functions/concat-transact-sql

Try this instead (SQL 2008):

(convert(varchar,cast((isnull(sum(Units) / nullif(sum(datediff(minute,StartTime,FinishTime))*1.0,0),0.0)*60)/150*100 as as decimal(10,0))) + '%') as Percentage

Refer: https://learn.microsoft.com/en-us/sql/t-sql/language-elements/string-concatenation-transact-sql

Body:
I have looked at the similar questions and was unable to find anything that answered my question.

I have a column that is the calculation of other columns of which sum I would like to divide by a set number and show results in percentage from. I have tried the below query and am able to show in decimal. Basically find out what percentage of UPH an associate is doing...This way I can tell if they are slacking in their department or exceling. I am using 150 as my base rate

SELECT
ID
  , DeptCode AS 'DC'
  , OpCode AS 'OC'
  ,Units = sum(Units)
  ,UPH = cast(isnull(sum(Units) / nullif(sum(datediff(minute,StartTime,FinishTime))*1.0,0),0.0)*60  as decimal(10,0))
  ,Percentage = cast(isnull(sum(Units) / nullif(sum(datediff(minute,StartTime,FinishTime))*1.0,0),0.0)*60  as decimal(10,0)) / 150

FROM dbo.TimeLog
 WITH (NOLOCK)

WHERE DeptCode = 'FB'
  and OpCode   = 'PU'
  and Units IS NOT NULL
GROUP BY
    ID
  , DeptCode
  , OpCode

Here is my result...

ID      DC  OC  Units   UPH Percentage
11259   FB  PU  553     114 0.760000
2375935 FB  PU  263     70  0.466666

I would like to see column 'Percentage' like the below

ID      DC  OC  Units   UPH Percentage
11259   FB  PU  553     114 76%
2375935 FB  PU  263     70  47%

Any help would be appreciated and I apologize in advance if this is elementary for a lot you, I am relatively new to SQL


问:
Can I default export constants and type alias from the same module?
I have a project with numerous objects containing constant string values in them.

const StringLiterals = {
    a: "LetterA",
    b: "LetterB",
    c: "LetterC"
};

export default StringLiterals;
```

<p>In many cases, these string constants are used as parameters. I want ensure only strings from these constants are being used, so I define a type alias.</p>

<pre class="lang-js prettyprint-override"><code>type StringLiteral = keyof typeof StringLiterals;
</code>```

Right now, I have to redefine this type alias everywhere I want to use it. I'd define the string values and the type alias in the same module such that I can do something like this:

import StringLiteral from "./StringLiteral";

function doSomething(str: StringLiteral) {
    if (str === StringLiteral.a) { ... }
}
```

Also:

I don't want two different modules, one containing the type and the other containing the string values.

I don't want enums, because they don't let you map identifiers to string values; they have to be numeric. I also want to avoid a lot of array referencing to translate between string and numeric values.

Is this at all possible?

答:
```<code>const StringLiterals = {
    a: "LetterA" as "LetterA",
    b: "LetterB" as "LetterB",
    c: "LetterC" as "LetterC"
};

type StringLiterals = (keyof StringLiterals)[keyof typeof StringLiterals];

export default StringLiterals;
</code>```

Body:
I have a project with numerous objects containing constant string values in them.

const StringLiterals = {
    a: "LetterA",
    b: "LetterB",
    c: "LetterC"
};

export default StringLiterals;

In many cases, these string constants are used as parameters. I want ensure only strings from these constants are being used, so I define a type alias.

type StringLiteral = keyof typeof StringLiterals;

Right now, I have to redefine this type alias everywhere I want to use it. I'd define the string values and the type alias in the same module such that I can do something like this:

import StringLiteral from "./StringLiteral";

function doSomething(str: StringLiteral) {
    if (str === StringLiteral.a) { ... }
}

Also:

I don't want two different modules, one containing the type and the other containing the string values.

I don't want enums, because they don't let you map identifiers to string values; they have to be numeric. I also want to avoid a lot of array referencing to translate between string and numeric values.

Is this at all possible?


问:
Xcode 8 A valid provisioning profile for this executable was not found
I know there are other questions asked like this here but I've followed all their solutions yet still end up with this error message.

I have a valid Apple Developer account with program active.

I have tried using managed and unmanaged provisioning with new/fresh bundle ID's (which get recreated provisioning profiles).

I have tried this: A valid provisioning profile for this executable was not found for debug mode

I have tried this: XCode :7 App installation failed :A valid provisioning profile for this executable was not found

I have deleted any old versions of the app from my phone.

I have confirmed my device ID on the developer portal is the same as in Xcode (was also useful for manual provisioning profile management to confirm)

I even tried another developer ID I have out of sheer desperation and yet the same error appears.

I even get this error when building for release scheme with my valid distribution certificate.

I've spent a ton of time trying to figure this out now I'm hoping someone else has felt my pain and actually solved this.

UPDATE: Adding screenshots for usefulness

UPDATE 2: I gave up trying to solve this problem, I created a new project and copied source files into the new project and I now have it working. Clearly something in the project configuration/settings files got corrupted somehow in the previous project which no obvious fix available. Will leave this question open, perhaps someone has a solution eventually. I have my old 'non-working' project so will continue to try those just for curiousities sake.

Before this error message, Build Succeeded is shown.

答: Clearing the DEVELOPMENT_TEAM and DevelopmentTeam entries in the xcodeproj/project.pbxproj file worked for me.</p>

ContentLicense: CC BY-SA 4.0


问:
Rails rake db:structure:load vs. rake db:schema:load
Is the structure just a sql version of the db while the schema is a Rails version of the db? When would you want to load either? Or does it make a difference?

答:
The schema file is the Rails version of your db and doesn't contain any db specific stuff like, views, triggers, and so on.

db/schema.rb cannot express database specific items such as triggers,
  sequences, stored procedures or check constraints, etc. Please note
  that while custom SQL statements can be run in migrations, these
  statements cannot be reconstituted by the schema dumper. If you are
  using features like this, then you should set the schema format to
  :sql.
  http://edgeguides.rubyonrails.org/active_record_migrations.html#schema-dumping-and-you

When would you use one over the other depends on whether you have db specific stuff that you need. If all you use are the basic tables, with indexes and primary and foreign keys you are good to go with schema files.

In my opinion however I always use structure.sql since I always use some db specific things.

You can change what format you want to use by changing this in your config/application.rb file.

```<code>config.active_record.schema_format = :sql # default is :ruby
</code>```

Body:
The schema file is the Rails version of your db and doesn't contain any db specific stuff like, views, triggers, and so on.

db/schema.rb cannot express database specific items such as triggers,
  sequences, stored procedures or check constraints, etc. Please note
  that while custom SQL statements can be run in migrations, these
  statements cannot be reconstituted by the schema dumper. If you are
  using features like this, then you should set the schema format to
  :sql.
  http://edgeguides.rubyonrails.org/active_record_migrations.html#schema-dumping-and-you

When would you use one over the other depends on whether you have db specific stuff that you need. If all you use are the basic tables, with indexes and primary and foreign keys you are good to go with schema files.

In my opinion however I always use structure.sql since I always use some db specific things.

You can change what format you want to use by changing this in your config/application.rb file.

config.active_record.schema_format = :sql # default is :ruby


问:
Segoe MDL2 Assets in HTML page does not see in Windows 7
I've made a simple website in HTML/CSS for a private local network at home and all the PCs and phones are Windows10. Now a friend of mine, arrived at home with his beautiful laptop with mounted on Windows 7 and... his Chrome does not show all the symbols in my pages! There are only some rectangles.
The pages are hosted in a simple webserver on Raspberry PI2 with Windows 10 IoT Core according this posts:

http://bitaware.altervista.org/little-webserver-raspberry-pi/

How can I solve it?

Thanx a lot

答:
According to learn.microsoft.com:

To obtain Segoe MDL2 Assets, you must install Windows 10.

So your icons won't show up on older versions of Windows or on Android, iOS, etc.


问:
Why is System.out.println so slow?
Is this something common to all programming languages? Doing multiple print followed by a println seems faster  but moving everything to a string and just printing that seems fastest. Why?

EDIT: For example, Java can find all the prime numbers up to 1 million in less than a second - but printing then all out each on their own println can take minutes! Up to a 10 billion can hours to print!

EX:

```<code>package sieveoferatosthenes;
public class Main {
    public static void main(String[] args) {
        int upTo = 10000000;
        boolean primes[] = new boolean[upTo];
        for( int b = 0; b < upTo; b++ ){
            primes[b] = true;
        }
        primes[0] = false;
        primes[1] = false;

        int testing = 1;

        while( testing <= Math.sqrt(upTo)){
            testing ++;
            int testingWith = testing;
            if( primes[testing] ){
                while( testingWith < upTo ){
                    testingWith = testingWith + testing;
                    if ( testingWith >= upTo){
                    }
                    else{
                        primes[testingWith] = false;
                    }

                }
            }
        }
        for( int b = 2; b < upTo; b++){
            if( primes[b] ){
                System.out.println( b );
            }
        }
    }
}
</code>```

答:
System.out is a static PrintStream class. PrintStream has, among other things, those methods you're probably quite familiar with, like print() and println() and such.

It's not unique to Java that input and output operations take a long time. "long." printing or writing to a PrintStream takes a fraction of a second, but over 10 billion instances of this print can add up to quite a lot!

This is why your "moving everything to a String" is the fastest. Your huge String is built, but you only print it once. Sure, it's a huge print, but you spend time on actually printing, not on the overhead associated with the print() or println().

As Dvd Prd has mentioned, Strings are immutable. That means whenever you assign a new String to an old one but reusing references, you actually destroy the reference to the old String and create a reference to the new one. So you can make this whole operation go even faster by using the StringBuilder class, which is mutable. This will decrease the overhead associated with building that string you'll eventually print.

ContentLicense: CC BY-SA 2.5

Title: Why is System.out.println so slow?

Body:
Is this something common to all programming languages? Doing multiple print followed by a println seems faster  but moving everything to a string and just printing that seems fastest. Why?

EDIT: For example, Java can find all the prime numbers up to 1 million in less than a second - but printing then all out each on their own println can take minutes! Up to a 10 billion can hours to print!

EX:

package sieveoferatosthenes;
public class Main {
    public static void main(String[] args) {
        int upTo = 10000000;
        boolean primes[] = new boolean[upTo];
        for( int b = 0; b < upTo; b++ ){
            primes[b] = true;
        }
        primes[0] = false;
        primes[1] = false;

        int testing = 1;

        while( testing <= Math.sqrt(upTo)){
            testing ++;
            int testingWith = testing;
            if( primes[testing] ){
                while( testingWith < upTo ){
                    testingWith = testingWith + testing;
                    if ( testingWith >= upTo){
                    }
                    else{
                        primes[testingWith] = false;
                    }

                }
            }
        }
        for( int b = 2; b < upTo; b++){
            if( primes[b] ){
                System.out.println( b );
            }
        }
    }
}


问:
How to ignore Stop words search using Lucene, when analysis of Stop Words is required?
How to ignore Stop words during Lucene Search?

I have analyzed all data including Stop Words using Custom Analyzer because it is requirement in most of the searches.

But in solution another requirement jumps in for one of module, which says to exclude Stop words from searches, on same fields, where Stop words are already Analyzed.

While analysis

```<code>@Fields({@Field(index = Index.YES, store = Store.NO, analyzer = @Analyzer(impl=CustomStopWordsAccepterAnalyzer.class)),
</code>```

Now requirement say to ignore stop word when search string have "Love With Hubby" and return best score results using Love Hubby. Kindly suggest!

答:
Once you enabled stopwords for a Field, the stopwords are effectively not encoded in the index so they can not be made to re-appear during query time.

The problem you have is quite common, as often people need to combine the score of multiple full-text queries performed with different options.

The solution is rather simple: for each property of your Java Entity, use multiple @Field annotations and assign a different index fieldname to each. This way you can target each different field with a BooleanQuery and have the scores of the output take both fields into account.

Body:
How to ignore Stop words during Lucene Search?

I have analyzed all data including Stop Words using Custom Analyzer because it is requirement in most of the searches.

But in solution another requirement jumps in for one of module, which says to exclude Stop words from searches, on same fields, where Stop words are already Analyzed.

While analysis

@Fields({@Field(index = Index.YES, store = Store.NO, analyzer = @Analyzer(impl=CustomStopWordsAccepterAnalyzer.class)),

Now requirement say to ignore stop word when search string have "Love With Hubby" and return best score results using Love Hubby. Kindly suggest!


问:
How to query all values from 1rst table and fill with 2nd table
Sorry if my question isn't clear at first.

I have those 3 tables:

```<code>Table A:
ID  |   DATE_CREATED

Table B:
ID  |   DATE_CREATED

TABLE C:
ID  |   DATE_CREATED
</code>```

What I want is getting all dates from Table A when ID A and B are the same:

```<code>SELECT A.DATE_CREATED
FROM A, B
WHERE A.ID = B.ID
</code>```

Now what I don't get is how to get all the dates from Table C and put them in the query above so that only the ones that don't exist in that query are put in it.

So if the query outputs

```<code>ID  |   DATE_CREATED
1   |        2010
2   |        2009
3   |        2008
</code>```

And table C contains

```<code>ID  |   DATE_CREATED
1   |        2017
2   |        2005
3   |        2003
4   |        2007
5   |        2010
</code>```

My final result should be

```<code>ID  |   DATE_CREATED
1   |        2010
2   |        2009
3   |        2008
4   |        2007
5   |        2010
</code>```

Thank you for reading my question! I am aware that this might question might already have been answered, as it is basic, but even by reading some similar questions my brain isn't able to process how to do it. I guess it's with a left join or something like that from what I read, but I don't get how it works even by checking examples and checking those join graphs.

答:
Here is one method:</p>

```<code>WITH ab as (
      SELECT A.ID, A.DATE_CREATED
      FROM A JOIN
           B
           ON A.ID = B.ID
     )
SELECT ab.*
FROM ab
UNION ALL
SELECT c.ID, c.DATE_CREATED
FROM c
WHERE c.ID NOT IN (SELECT ID FROM ab);
</code>```

Body:
Sorry if my question isn't clear at first.

I have those 3 tables:

Table A:
ID  |   DATE_CREATED

Table B:
ID  |   DATE_CREATED

TABLE C:
ID  |   DATE_CREATED

What I want is getting all dates from Table A when ID A and B are the same:

SELECT A.DATE_CREATED
FROM A, B
WHERE A.ID = B.ID

Now what I don't get is how to get all the dates from Table C and put them in the query above so that only the ones that don't exist in that query are put in it.

So if the query outputs

ID  |   DATE_CREATED
1   |        2010
2   |        2009
3   |        2008

And table C contains

ID  |   DATE_CREATED
1   |        2017
2   |        2005
3   |        2003
4   |        2007
5   |        2010

My final result should be

ID  |   DATE_CREATED
1   |        2010
2   |        2009
3   |        2008
4   |        2007
5   |        2010

Thank you for reading my question! I am aware that this might question might already have been answered, as it is basic, but even by reading some similar questions my brain isn't able to process how to do it. I guess it's with a left join or something like that from what I read, but I don't get how it works even by checking examples and checking those join graphs.

Body:
Here is one method:

WITH ab as (
      SELECT A.ID, A.DATE_CREATED
      FROM A JOIN
           B
           ON A.ID = B.ID
     )
SELECT ab.*
FROM ab
UNION ALL
SELECT c.ID, c.DATE_CREATED
FROM c
WHERE c.ID NOT IN (SELECT ID FROM ab);


问:
socket.io cannot communicate with back-end through express
I am using socket.io for fetching some data from the express app. Everything works fine on localhost:8080 but when i deploy my code to the server, client side socket.io cannot communicate with back-end socket.io through express server. I've an apache on the server that forwards everything to localhost:8080 including domain.com/socket.io/?transform=polling... and it extends the request to the express server but express returns a 404 (it comes from the express, not from apache). I am out of ideas, what could be the problem? Here is my code:

```<code>express = require "express"
jade = require "jade"
fs = require "fs"

class Bootstrap
 _self = undefined
 routes:
   DEFAULT_PATH: "/"
   TEMPLATE_PATH: "/load/:view"
   DIRECTIVE_PATH: "/directive/:template"
 options:
   templatePath: "#{__dirname}/../src/templates"
   isDev: "#{__dirname}/../dev"
 contentPath: "#{__dirname}/../frontend"
 libraryPath: "#{__dirname}/../bower_components"
 port: 8080
 status:
   notFound: 404
 isDev: undefined

 constructor: ->
   _self = @
   @isDev = fs.existsSync @options.isDev
   @app = express()

   @app.use "/frontend", express.static(@options.contentPath)
   @app.use "/bower_components", express.static(@options.libraryPath)
   @app.set "views", @options.templatePath
   @app.set "view engine", "jade"
   @app.engine "jade", jade.__express

   @app.get @routes.DEFAULT_PATH, (request, response)->
     appData =
       data:
         isDev: _self.isDev
     response.render "index", appData
   @app.get @routes.TEMPLATE_PATH, (request, response)->
     view = request.param "view"
     response.render view
   @app.get @routes.DIRECTIVE_PATH, (request, response)->
     template = request.param("template").replace ".html", ""
     response.render "directives/"+template
   @app.use (request, response, next)->
     _self.logger.warning "404 Not Found!: " + request.originalUrl
     response.status(_self.options.status.notFound)
      appData =
        data:
          isDev : _self.isDev
          request: request
      response.render "404", appData

   @server = @app.listen @options.port
   @io = require("socket.io").listen @server

   @logger = require("./logger.js")
   @logger.init @isDev

   @socketConnector = require("./live.js")
   @socketConnector.init @io

   @

new Bootstrap()
</code>```

You can find the entire code here: https://github.com/eyurdakul/ejder.be

答:
A debugging step that you should take is to have a mock client run in your express app and try to connect to the server port using localhost, or whatever the loopback IP address is. In other words (purely as a temporary testing tool) you place a socket.io Node client into your Express app that gets instantiated and immediately tries to connect to the Socket.io server (which is also in the express app). This should work.

If it does work, you've established that your express server is not the problem. Then, on the client you just added to your express app, you should change the connection address from the local IP to the actual IP address of the server.

If it doesn't work, your problem is probably server side.

My guess is that your apache server is forwarding the polling requests properly, but when Socket.io tries to make the handoff to websockets, Apache is denying the WS request and socket.io is handling this denial internally -- which is why the 404 seems to come from express.

Body:
I am using socket.io for fetching some data from the express app. Everything works fine on localhost:8080 but when i deploy my code to the server, client side socket.io cannot communicate with back-end socket.io through express server. I've an apache on the server that forwards everything to localhost:8080 including domain.com/socket.io/?transform=polling... and it extends the request to the express server but express returns a 404 (it comes from the express, not from apache). I am out of ideas, what could be the problem? Here is my code:

express = require "express"
jade = require "jade"
fs = require "fs"

class Bootstrap
 _self = undefined
 routes:
   DEFAULT_PATH: "/"
   TEMPLATE_PATH: "/load/:view"
   DIRECTIVE_PATH: "/directive/:template"
 options:
   templatePath: "#{__dirname}/../src/templates"
   isDev: "#{__dirname}/../dev"
 contentPath: "#{__dirname}/../frontend"
 libraryPath: "#{__dirname}/../bower_components"
 port: 8080
 status:
   notFound: 404
 isDev: undefined

 constructor: ->
   _self = @
   @isDev = fs.existsSync @options.isDev
   @app = express()

   @app.use "/frontend", express.static(@options.contentPath)
   @app.use "/bower_components", express.static(@options.libraryPath)
   @app.set "views", @options.templatePath
   @app.set "view engine", "jade"
   @app.engine "jade", jade.__express

   @app.get @routes.DEFAULT_PATH, (request, response)->
     appData =
       data:
         isDev: _self.isDev
     response.render "index", appData
   @app.get @routes.TEMPLATE_PATH, (request, response)->
     view = request.param "view"
     response.render view
   @app.get @routes.DIRECTIVE_PATH, (request, response)->
     template = request.param("template").replace ".html", ""
     response.render "directives/"+template
   @app.use (request, response, next)->
     _self.logger.warning "404 Not Found!: " + request.originalUrl
     response.status(_self.options.status.notFound)
      appData =
        data:
          isDev : _self.isDev
          request: request
      response.render "404", appData

   @server = @app.listen @options.port
   @io = require("socket.io").listen @server

   @logger = require("./logger.js")
   @logger.init @isDev

   @socketConnector = require("./live.js")
   @socketConnector.init @io

   @

new Bootstrap()

You can find the entire code here: https://github.com/eyurdakul/ejder.be


问:
How can I preserve order with an EnumMap in java
I have an EnumMap that I'm using and I will need to keep the order of the items that I'm passing in. I know that when using a HashMap, I can initialize a LinkedHashMap in order to preserve order like so:

```<code>HashMap<String, List<String>> contentTypeToIdList = new LinkedHashMap<String, List<String>>();
</code>```

However, I'd like to use an EnumMap instead. How would I be able to do something like this:

```<code>EnumMap<ContentType, List<String>> contentTypeToIdList = new LinkedHashMap<ContentType, List<String>>();
</code>```

答:
You really don't need an EnumMap.  You can get away with just using the LinkedHashMap, but you have to be mindful of what you're keying off of.

```<code>Map<ContentType, List<String>> contentTypeToIdList = new LinkedHashMap<>();
</code>```

This will:

Use a LinkedHashMap

Ensure insertion order relative to when the key (and its values) are added

Body:
I have an EnumMap that I'm using and I will need to keep the order of the items that I'm passing in. I know that when using a HashMap, I can initialize a LinkedHashMap in order to preserve order like so:

HashMap<String, List<String>> contentTypeToIdList = new LinkedHashMap<String, List<String>>();

However, I'd like to use an EnumMap instead. How would I be able to do something like this:

EnumMap<ContentType, List<String>> contentTypeToIdList = new LinkedHashMap<ContentType, List<String>>();

Body:
You really don't need an EnumMap.  You can get away with just using the LinkedHashMap, but you have to be mindful of what you're keying off of.

Map<ContentType, List<String>> contentTypeToIdList = new LinkedHashMap<>();

This will:

Use a LinkedHashMap

Ensure insertion order relative to when the key (and its values) are added


问:
DB::raw not using model connection
I'm trying to get a count of model rows from a different database. I have both databases configured fine. My problem is that it doesn't seem to be using the same connection when attempting to perform raw queries.

Code:

```<code>class Lead extends Model
{
    protected $connection = 'infused2';
    public $timestamps = false;

    function campaignCount(Campaign $campaign)
    {
        $leads = $this->join('lead_history', 'leads.id', '=', 'lead_history.id_lead')->join('assignments', 'leads.id', '=', 'assignments.id_lead');

        if (!empty($campaign->lead_date_created_operand)) {
            if ($campaign->leadDateCreatedOperand->name == 'day age') {
                $leads->where(DB::raw("date_format(from_unixtime(lead_history.date_created), '%d-%m-%Y') = date_format(".strtotime($campaign->lead_date_created_value).", '%d-%m-%Y')"));
            }
            else if ($campaign->leadDateCreatedOperand->name == 'month age') {
                $leads->where(DB::raw("date_format(from_unixtime(lead_history.date_created), '%m-%Y') = date_format(".strtotime($campaign->lead_date_created_value).", '%m-%Y')"));
            }
        }

        if (!empty($campaign->lead_date_assigned_operand)) {
            if ($campaign->leadDateAssignedOperand->name == 'day age') {
                $leads->where(DB::raw("date_format(from_unixtime(assignments.date_assigned), '%d-%m-%Y') = date_format(".strtotime($campaign->lead_date_assigned_value).", '%d-%m-%Y')"));
            }
            else if ($campaign->leadDateAssignedOperand->name == 'month age') {
                $leads->where(DB::raw("date_format(from_unixtime(assignments.date_assigned), '%m-%Y') = date_format(".strtotime($campaign->lead_date_assigned_value).", '%m-%Y')"));
            }
        }

        return $leads->count();
    }
}
</code>```

I am getting error Database [mysql] not configured. Why is this happening and how do I make the raw queries use the model connection?

答:
Depending on your configuration you may need to do</p>

```<code>DB::connection('infused2')...
</code>```

Title: DB::raw not using model connection

Body:
I'm trying to get a count of model rows from a different database. I have both databases configured fine. My problem is that it doesn't seem to be using the same connection when attempting to perform raw queries.

Code:

class Lead extends Model
{
    protected $connection = 'infused2';
    public $timestamps = false;

    function campaignCount(Campaign $campaign)
    {
        $leads = $this->join('lead_history', 'leads.id', '=', 'lead_history.id_lead')->join('assignments', 'leads.id', '=', 'assignments.id_lead');

        if (!empty($campaign->lead_date_created_operand)) {
            if ($campaign->leadDateCreatedOperand->name == 'day age') {
                $leads->where(DB::raw("date_format(from_unixtime(lead_history.date_created), '%d-%m-%Y') = date_format(".strtotime($campaign->lead_date_created_value).", '%d-%m-%Y')"));
            }
            else if ($campaign->leadDateCreatedOperand->name == 'month age') {
                $leads->where(DB::raw("date_format(from_unixtime(lead_history.date_created), '%m-%Y') = date_format(".strtotime($campaign->lead_date_created_value).", '%m-%Y')"));
            }
        }

        if (!empty($campaign->lead_date_assigned_operand)) {
            if ($campaign->leadDateAssignedOperand->name == 'day age') {
                $leads->where(DB::raw("date_format(from_unixtime(assignments.date_assigned), '%d-%m-%Y') = date_format(".strtotime($campaign->lead_date_assigned_value).", '%d-%m-%Y')"));
            }
            else if ($campaign->leadDateAssignedOperand->name == 'month age') {
                $leads->where(DB::raw("date_format(from_unixtime(assignments.date_assigned), '%m-%Y') = date_format(".strtotime($campaign->lead_date_assigned_value).", '%m-%Y')"));
            }
        }

        return $leads->count();
    }
}

I am getting error Database [mysql] not configured. Why is this happening and how do I make the raw queries use the model connection?

Body:
Depending on your configuration you may need to do

DB::connection('infused2')...


问:
Add an external child in React
I need to add another react component that's located in an external CDN as a child in my react component. Something like this:

```<code>var RemoteComponent = require('//cdn.com/some-remote-component');
var MyComponent = React.createClass({
  render: function() {
    return (
      <div>
        <RemoteComponent />
      </div>
    );
  }
});
module.exports = MyComponent;
</code>```

Any ideas on how could I do that?

答:
You can also build your own function to load remote react components without using requirejs or scriptjs. It can be very straightforward as follows (I was inspired by the solution here)</p>

```<code>import React from 'react';

export function loadRemoteComponent(url) {
  return fetch(url)
    .then(response => response.text())
    .then(text => {
      // Define exports and require method for eval(text)
      const exports = {};
      function require(name) {
        if (name === 'react') {
          return React;
        }
        throw new Error('Does not support modules other than "react"');
      }
      eval(text);
      return exports.__esModule ? exports.default : exports;
    });
}
</code>```

Title: Add an external child in React

Body:
I need to add another react component that's located in an external CDN as a child in my react component. Something like this:

var RemoteComponent = require('//cdn.com/some-remote-component');
var MyComponent = React.createClass({
  render: function() {
    return (

        <RemoteComponent />

    );
  }
});
module.exports = MyComponent;

Any ideas on how could I do that?

Body:
You can also build your own function to load remote react components without using requirejs or scriptjs. It can be very straightforward as follows (I was inspired by the solution here)

import React from 'react';

export function loadRemoteComponent(url) {
  return fetch(url)
    .then(response => response.text())
    .then(text => {
      // Define exports and require method for eval(text)
      const exports = {};
      function require(name) {
        if (name === 'react') {
          return React;
        }
        throw new Error('Does not support modules other than "react"');
      }
      eval(text);
      return exports.__esModule ? exports.default : exports;
    });
}


问:
CRexport.exe on 64 bit system. Faile to log on to Database
Using CRexport.exe on a 64 bit system gives an error.

.Net is 64 bit

CR Runtime is 64 bit

The report does run on Crystal Reports XI Release 2 when oppened.

Sample Command:

C:\crexport\crexport.exe -F C:\rpt\CheckLogin\LoginCheck.rpt -E "csv"  -a "Token:636300135206847568" -O C:\crexport\CR_LOGIN.tkn -U [username] -P [pasword]

This report uses a PeopleSoft Query as a data source.

Command to execute a reort runs fine on my 32 bit machine.

Full source code being used to troubleshoot issue is on Github.

Same command returns error when ran on 64 bit machine:

Error: Failed to logon to Database. Check username, pasword, server name and database name parameter

Has anyone had issues with database authentication when using crexport.exe crystal reports runtime on a C# app?

I have not had any issues, untill we had a station replaced but with a Windows 7 64 bit system.

Update

I have tested another report that uses a command instead of a PeopleSoft Query as the data source (using trusted connections) and it works just fine.

I suspect that the password is not being set, despite the fact it is being provided. I added crexport.cs#L275-L351 to ensure the password and all connection information is set, but the errorm message Log on failed keeps happening.

Update 2

I have tried with the CristalReport Runtime 64bit v13.0.1, v13.0.13 and v13.0.20

Same error persists.

Update 3

Full source code of Crystal-Reports-Exporter I am using to troubleshoot this issue is found on github, branch issue-logonToDatabase.

Update 4

After a few days of troubleshooting, I believe I have found the problem.

It is related to the PeopleSoft PeopleTools (PeopleSoft) DSN driver. It is 32 bit, and apperently it does not get along well with the Crystal Reports Runtime 64 bit.

More on the answer below.

答:
To be able to connect to PeopleSoft (and use the Queries from Query Manager) you must use the the 32bit version of the Crystal Reports Runtime for Visual Studio, because the PeopleSoft Driver is 32 bit.

This means that you must:

Install .NET Framework 32bit (Offline installer provides the 64 and 32 bit version)

Install Cristal Report Runtime for Visual Studio ( I was successfull using v13.0.13).

Higher versionf would create errors on my report formulas.

Compile your tool/program that will be running the Crystal Reports with a Target Framework: .NET Framework 4+ and Plataform target: x86

Plaform Target: Any CPU + Prefer 32-bit may work but I have not tested it

Notes

I saw issues when I would chain start my tool/program from a 64bit program.

It would not constrain my tool/program to 32 bit libraries and it would try to load the 64bit version of Cristal Reports Runtime.

However, 32bit version of PeopleSoft Driver does not play nice with 64bit version of Cristal Reports Runtime.


答:
Use join statements and it will be much easier:

```<code>SELECT COALESCE(A.ID, C.ID), COALESCE(A.DATE_CREATED, C.DATE_CREATED)
FROM A
  INNER JOIN B ON A.ID = B.ID
  FULL JOIN C ON A.ID = C.ID
WHERE A.ID != C.ID
</code>```

Title: How to query all values from 1rst table and fill with 2nd table

Body:
Use join statements and it will be much easier:

SELECT COALESCE(A.ID, C.ID), COALESCE(A.DATE_CREATED, C.DATE_CREATED)
FROM A
  INNER JOIN B ON A.ID = B.ID
  FULL JOIN C ON A.ID = C.ID
WHERE A.ID != C.ID


问:
Python - Selenium - select an element from a dropdown menu
I need to select an element from a dropdown menu.

For example:

```<code>    <div class="col-sm-4 col-lg-2">
       <label for="rangeFilter" class="sr-only">Date Range</label>
       <select class="selectpicker" id="rangeFilter" data-none-selected-text="Range" name="range">
              <option value="">View by</option>
              <option value="6month">6 months</option>
              <option value="1year">1 Year</option>
              <option value="2year">2 Year</option>
              <option value="all">All time</option>
         </select>
     </div>
</code>```

but i have always some kind of error.

My code is so easy:

```<code>driver = webdriver.Chrome("D:\Python27\selenium\webdriver\chrome\chromedriver.exe")
driver.implicitly_wait(5)
driver.maximize_window()
driver.get("https://ispspeedindex.netflix.com/country/norway/")
time.sleep(15)
select = Select(driver.find_element_by_id('rangeFilter'))
select.select_by_visible_text('All time')
</code>```

but it don´t work. It appears a message about "element not visible: Element is not currently visible and may not be manipulated"

```<code>Traceback (most recent call last):
File "scraping.py", line 23, in <module>
select.select_by_visible_text('All time')
File "D:\Python27\lib\site-packages\selenium\webdriver\support\select.py", line 120, in select_by_visible_text
...
selenium.common.exceptions.ElementNotVisibleException: Message: element not visible: Element is not currently visible and may not be manipulated
</code>```

any idea? i was trying with some fixes from another stackoverflow questions but i didn´t find the way...

答:
You can replace implicit waits by explicit wait which waits until the element is rendered in DOM.</p>

```<code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome("D:\Python27\selenium\webdriver\chrome\chromedriver.exe")
driver.maximize_window()
driver.get("https://ispspeedindex.netflix.com/country/norway/")
try:
    WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "rangeFilter"))
    )
    select = Select(driver.find_element_by_id('rangeFilter'))
    select.select_by_visible_text('All time')
finally:
    driver.quit()
</code>```

Body:
I need to select an element from a dropdown menu.

For example:

       Date Range
       <select class="selectpicker" id="rangeFilter" data-none-selected-text="Range" name="range">
              <option value="">View by</option>
              <option value="6month">6 months</option>
              <option value="1year">1 Year</option>
              <option value="2year">2 Year</option>
              <option value="all">All time</option>
         </select>

but i have always some kind of error.

My code is so easy:

driver = webdriver.Chrome("D:\Python27\selenium\webdriver\chrome\chromedriver.exe")
driver.implicitly_wait(5)
driver.maximize_window()
driver.get("https://ispspeedindex.netflix.com/country/norway/")
time.sleep(15)
select = Select(driver.find_element_by_id('rangeFilter'))
select.select_by_visible_text('All time')

but it don´t work. It appears a message about "element not visible: Element is not currently visible and may not be manipulated"

Traceback (most recent call last):
File "scraping.py", line 23, in <module>
select.select_by_visible_text('All time')
File "D:\Python27\lib\site-packages\selenium\webdriver\support\select.py", line 120, in select_by_visible_text
...
selenium.common.exceptions.ElementNotVisibleException: Message: element not visible: Element is not currently visible and may not be manipulated

any idea? i was trying with some fixes from another stackoverflow questions but i didn´t find the way...

Body:
You can replace implicit waits by explicit wait which waits until the element is rendered in DOM.

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome("D:\Python27\selenium\webdriver\chrome\chromedriver.exe")
driver.maximize_window()
driver.get("https://ispspeedindex.netflix.com/country/norway/")
try:
    WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "rangeFilter"))
    )
    select = Select(driver.find_element_by_id('rangeFilter'))
    select.select_by_visible_text('All time')
finally:
    driver.quit()


问:
Centralizing RecyclerView with LinearLayoutManager
I am trying to centralize a RecyclerView list in the screen. Its going to be a single list, so I will use the LinearLayoutManager (LLM).
However using the LLM its not centralizing the items, and it looks like this on the landscape mode:

The XML code looks like this:

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical" android:layout_width="match_parent"

    android:layout_height="match_parent">

    <android.support.v7.widget.CardView
        android:id="@+id/recipe_card"
        android:layout_gravity="center"
        android:layout_width="400dp"
        android:layout_height="186dp"
        style="@style/CardViewStyle">

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <ImageView
                android:id="@+id/recipe_image"
                android:layout_width="120dp"
                android:layout_height="163dp"
                app:srcCompat="@mipmap/ic_pan"
                app:layout_constraintTop_toTopOf="parent"
                android:layout_marginTop="8dp"
                app:layout_constraintBottom_toBottomOf="parent"
                android:layout_marginBottom="8dp"
                android:layout_marginLeft="8dp"
                app:layout_constraintLeft_toLeftOf="parent"
                tools:layout_editor_absoluteY="3dp" />

            <TextView
                android:id="@+id/recipe_name"
                android:layout_width="250dp"
                android:layout_height="119dp"
                android:text="TextView"
                app:layout_constraintLeft_toRightOf="@+id/recipe_image"
                android:layout_marginLeft="8dp"
                app:layout_constraintTop_toTopOf="parent"
                android:layout_marginTop="16dp" />

            <TextView
                android:id="@+id/recipe_servings"
                android:layout_width="164dp"
                android:layout_height="32dp"
                android:text="TextView"
                android:layout_marginTop="8dp"
                app:layout_constraintTop_toBottomOf="@+id/recipe_name"
                app:layout_constraintBottom_toBottomOf="parent"
                android:layout_marginBottom="8dp"
                app:layout_constraintLeft_toRightOf="@+id/recipe_image"
                android:layout_marginLeft="94dp"
                app:layout_constraintVertical_bias="0.0" />
        </android.support.constraint.ConstraintLayout>

    </android.support.v7.widget.CardView>

</FrameLayout>
</code>```

On the Android Studio's Preview, it looks fine, but on the app, it does not.
I manage to fix it by changing the LLM for a GridLayoutManager with only one column. But it looks ugly.

Does anyone knows what is going on?
Thanks.

答:
if I were you I would get my display size width and set my ViewHolder some margin accordingly.

this is my code in my application class:

```<code>public class MyApp extends Application {
public static Point displaySize = new Point();
public static float density = 1;
public static Context appContext = null;
public static int height;

@Override
public void onCreate() {
    super.onCreate();
    ActiveAndroid.initialize(this);
    appContext = getApplicationContext();
    checkDisplaySize();
    density = appContext.getResources().getDisplayMetrics().density;
}

public static void checkDisplaySize() {
    try {
        WindowManager manager = (WindowManager)
appContext.getSystemService(Context.WINDOW_SERVICE);
        if (manager != null) {
            Display display = manager.getDefaultDisplay();
            if (display != null) {
                    display.getSize(displaySize);
            }
           height = (int) (displaySize.x / 1.777f); //Aspect Ratio 16:9
        }
    } catch (Exception e) {
    }
}
}
</code>```

and after all this in your adapter where you get the holder view just do the following:

```<code>int marginWidth = (MyApp.desplaySize.x - itemView.getMeasuredWidth())/2;
LayoutParams params = new LayoutParams(
    LayoutParams.WRAP_CONTENT,
    LayoutParams.WRAP_CONTENT
);
params.setMargins(marginWidth, 0, marginWidth, 0);
itemView.setLayoutParams(params);
</code>```

I am not really sure that this exact code will solve your issue but you could easily change this so it will.

Body:
I am trying to centralize a RecyclerView list in the screen. Its going to be a single list, so I will use the LinearLayoutManager (LLM).
However using the LLM its not centralizing the items, and it looks like this on the landscape mode:

The XML code looks like this:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical" android:layout_width="match_parent"

    android:layout_height="match_parent">

    <android.support.v7.widget.CardView
        android:id="@+id/recipe_card"
        android:layout_gravity="center"
        android:layout_width="400dp"
        android:layout_height="186dp"
        style="@style/CardViewStyle">

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <ImageView
                android:id="@+id/recipe_image"
                android:layout_width="120dp"
                android:layout_height="163dp"
                app:srcCompat="@mipmap/ic_pan"
                app:layout_constraintTop_toTopOf="parent"
                android:layout_marginTop="8dp"
                app:layout_constraintBottom_toBottomOf="parent"
                android:layout_marginBottom="8dp"
                android:layout_marginLeft="8dp"
                app:layout_constraintLeft_toLeftOf="parent"
                tools:layout_editor_absoluteY="3dp" />

            <TextView
                android:id="@+id/recipe_name"
                android:layout_width="250dp"
                android:layout_height="119dp"
                android:text="TextView"
                app:layout_constraintLeft_toRightOf="@+id/recipe_image"
                android:layout_marginLeft="8dp"
                app:layout_constraintTop_toTopOf="parent"
                android:layout_marginTop="16dp" />

            <TextView
                android:id="@+id/recipe_servings"
                android:layout_width="164dp"
                android:layout_height="32dp"
                android:text="TextView"
                android:layout_marginTop="8dp"
                app:layout_constraintTop_toBottomOf="@+id/recipe_name"
                app:layout_constraintBottom_toBottomOf="parent"
                android:layout_marginBottom="8dp"
                app:layout_constraintLeft_toRightOf="@+id/recipe_image"
                android:layout_marginLeft="94dp"
                app:layout_constraintVertical_bias="0.0" />
        </android.support.constraint.ConstraintLayout>

    </android.support.v7.widget.CardView>

</FrameLayout>

On the Android Studio's Preview, it looks fine, but on the app, it does not.
I manage to fix it by changing the LLM for a GridLayoutManager with only one column. But it looks ugly.

Does anyone knows what is going on?
Thanks.

Body:
if I were you I would get my display size width and set my ViewHolder some margin accordingly.

this is my code in my application class:

public class MyApp extends Application {
public static Point displaySize = new Point();
public static float density = 1;
public static Context appContext = null;
public static int height;

@Override
public void onCreate() {
    super.onCreate();
    ActiveAndroid.initialize(this);
    appContext = getApplicationContext();
    checkDisplaySize();
    density = appContext.getResources().getDisplayMetrics().density;
}

public static void checkDisplaySize() {
    try {
        WindowManager manager = (WindowManager)
appContext.getSystemService(Context.WINDOW_SERVICE);
        if (manager != null) {
            Display display = manager.getDefaultDisplay();
            if (display != null) {
                    display.getSize(displaySize);
            }
           height = (int) (displaySize.x / 1.777f); //Aspect Ratio 16:9
        }
    } catch (Exception e) {
    }
}
}

and after all this in your adapter where you get the holder view just do the following:

int marginWidth = (MyApp.desplaySize.x - itemView.getMeasuredWidth())/2;
LayoutParams params = new LayoutParams(
    LayoutParams.WRAP_CONTENT,
    LayoutParams.WRAP_CONTENT
);
params.setMargins(marginWidth, 0, marginWidth, 0);
itemView.setLayoutParams(params);

I am not really sure that this exact code will solve your issue but you could easily change this so it will.


问:
SQL Server order by case
I want to create a fourth column with this query:

```<code>select * from (select ID, column0, column1, column2, column3 = Case when
column2 = '' then column1 else column2 end, row_number() over(partition by
column0 order by [column3]) as column4 from myTable) ti
</code>```

But this error appears:

```<code>Invalid column name 'column3'.
</code>```

I want this result: (red marked column):

答:
you need to use order by from outside of subquery as below:

```<code>Select *, row_number() over(partition by
 column3 order by [Id]) as column4
 from (select ID, column0, column1, column2, column3 = Case when
      column2 = '' then column1 else column2 end
        from myTable) ti
</code>```

For your 4th column in image you need to partition by column3 order by id. If you do Partition by column0 then you will get all 1's

Title: SQL Server order by case

Body:
I want to create a fourth column with this query:

select * from (select ID, column0, column1, column2, column3 = Case when
column2 = '' then column1 else column2 end, row_number() over(partition by
column0 order by [column3]) as column4 from myTable) ti

But this error appears:

Invalid column name 'column3'.

I want this result: (red marked column):

Body:
you need to use order by from outside of subquery as below:

Select *, row_number() over(partition by
 column3 order by [Id]) as column4
 from (select ID, column0, column1, column2, column3 = Case when
      column2 = '' then column1 else column2 end
        from myTable) ti

For your 4th column in image you need to partition by column3 order by id. If you do Partition by column0 then you will get all 1's


问:
I use at-command for get Caller ID but just write ok ring
I am using the following method to detect the CallerID when someone calls.

```<code>private void Form1_Load(object sender, EventArgs e)
{
    serialPort1.PortName = "COM3";
    serialPort1.RtsEnable = true;
    serialPort1.BaudRate = 9600;
    serialPort1.DataBits = 8;
    serialPort1.RtsEnable = true;
    serialPort1.Open();
    serialPort1.WriteLine("AT+VCID=1" + System.Environment.NewLine);
}

private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
    textBox1.Text += serialPort1.ReadLine();
}
</code>```

I excepted something like this :

```<code>RING               //On 1st Ring
DATE = xxxxx       //On 2nd Ring
TIME = xxxx
NMBR = xxxxxxxxx

RING               //On 3rd Ring
RING               //On 4th Ring
</code>```

But I have just :

```<code>OK
RING
RING
RING
</code>```

NOTE:

line support CallerID

I guess modem support CallerID too because I see the word RING for each incoming ring

Confirmed: I have caller id device and I checked it; I'm sure that I have caller id service.

答: most common CALLER ID command is "AT#CID=1"</p>

Body:
I am using the following method to detect the CallerID when someone calls.

private void Form1_Load(object sender, EventArgs e)
{
    serialPort1.PortName = "COM3";
    serialPort1.RtsEnable = true;
    serialPort1.BaudRate = 9600;
    serialPort1.DataBits = 8;
    serialPort1.RtsEnable = true;
    serialPort1.Open();
    serialPort1.WriteLine("AT+VCID=1" + System.Environment.NewLine);
}

private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
    textBox1.Text += serialPort1.ReadLine();
}

I excepted something like this :

RING               //On 1st Ring
DATE = xxxxx       //On 2nd Ring
TIME = xxxx
NMBR = xxxxxxxxx

RING               //On 3rd Ring
RING               //On 4th Ring

But I have just :

OK
RING
RING
RING

NOTE:

line support CallerID

I guess modem support CallerID too because I see the word RING for each incoming ring

Confirmed: I have caller id device and I checked it; I'm sure that I have caller id service.


问:
Read all buffer data from serial port with C#
I have some problems using System.IO.Ports in C# to read data from a serial port. The only method thar works is the "Read" method, but it only read "defined" number of characters and i need to read all available data like "Tera Term" or "Hercules" do. Here is my DLL method that reads the buffer:

```<code>public String ReadMessage(String port, int timeout, int dataSize)
{
    String res;

    try
    {
        _serial_port = new SerialPort();
        _serial_port.PortName = port;
        _serial_port.BaudRate = 19200;
        _serial_port.Parity = Parity.None;
        _serial_port.DataBits = 8;
        _serial_port.StopBits = StopBits.One;
        _serial_port.Handshake = Handshake.None;
        _serial_port.ReadTimeout = timeout;
        _serial_port.DtrEnable = true;
        _serial_port.RtsEnable = true;

        _serial_port.Open();
        _serial_port.DiscardInBuffer();

        int totalBytes = _serial_port.BytesToRead;

        if (totalBytes > 0)
        {
            byte[] buffer = new byte[totalBytes];
            _serial_port.Read(buffer, 0, totalBytes);
            res = ByteArrayToString(buffer);
        }
        else
        {
            byte[] buffer = new byte[dataSize];

            for (int len = 0; len < buffer.Length;)
            {
                len += _serial_port.Read(buffer, len, buffer.Length - len);
            }

            res = ByteArrayToString(buffer);
        }

        _serial_port.Close();

        return res;
    }
    catch (Exception ex)
    {
        if (ex is UnauthorizedAccessException || ex is TimeoutException)
        {
            _serial_port.Close();
        }

        return ex.ToString();
    }
}
</code>```

I know there are other methods to read data like: "ReadByte", "ReadChar", "ReadExisting", "ReadLine" and "ReadTo" but none of them are working, am i doing something wrong?

答:
The serial port is a stream device, it can continuously receive data. You'll need to set a timer as long the serial port is open to continuously check if there's anything in the buffer and copy it to a buffer or file on disk as soon as possible to prevent a buffer overflow.

You need to check the data contents to find out what is received and when all of it is received. This depends on the sender. You can't just say receive all there is to receive, it's a continous stream as far as the serial port is concerned. The actual data needs to specify the protocol, start and stop conditions.

EDIT

Here's a code snippet I use to capture floppy disk data through a usb to rs232 device at 5mbit/sec:

```<code>    // Capture handler
    private void timer2_Tick(object sender, EventArgs e)
    {
        // Read data from serial port, poll every 10ms
        // If data is there, read a block and write it to array
        int bytestoread = 0;
        //byte buf;

        timer2.Stop();
        try
        {
            bytestoread = serialPort1.BytesToRead;
        }

        catch (InvalidOperationException ex)
        {
            tbr.Append("Serial connection lost. Exception type:" + ex.ToString());
            if ((uint)ex.HResult == 0x80131509)
            {
                timer2.Stop();
            }
        }

        if (serialPort1.IsOpen)
        {
            if (bytestoread != 0)
            {
                bytespersecond += bytestoread;

                byte[] temp = new byte[bytestoread];

                if (serialPort1.IsOpen)
                    serialPort1.Read(temp, 0, bytestoread);

                tempbuffer.Add(temp);
                processing.indexrxbuf += bytestoread;
                recentreadbuflength += bytestoread;

                //update the scatterplot, this may have a performance hit
                processing.rxbuf = tempbuffer.SelectMany(a => a).ToArray();
                rxbuf = processing.rxbuf;
                if (Setrxbufcontrol == null) return;
                Setrxbufcontrol();

            }
            timer2.Start();
        }
    }
</code>```

setup code for serial port. I defined large buffers to prevent overflows:

```<code>        serialPort1.BaudRate = 5000000;
        serialPort1.NewLine = "\r\n";
        serialPort1.ReceivedBytesThreshold = 500000;
        serialPort1.ReadBufferSize = 1048576;
</code>```

EDIT 2

Steps to read from a serial port:

Define a received data array to hold the data

Open serial port

Set a timer to read data continuously until user hits disconnect button

timer tick method checks the length of data in serial buffer, then read that length into the receive buffer defined in step 1. Keep track of total received data by adding the serial buffer length to a static variable.

In another timer you could check the received data array for new lines. Copy all data to an array of strings, or to a textbox. Or just copy the data as a string to the textbox to see what's in it.

Body:
I have some problems using System.IO.Ports in C# to read data from a serial port. The only method thar works is the "Read" method, but it only read "defined" number of characters and i need to read all available data like "Tera Term" or "Hercules" do. Here is my DLL method that reads the buffer:

public String ReadMessage(String port, int timeout, int dataSize)
{
    String res;

    try
    {
        _serial_port = new SerialPort();
        _serial_port.PortName = port;
        _serial_port.BaudRate = 19200;
        _serial_port.Parity = Parity.None;
        _serial_port.DataBits = 8;
        _serial_port.StopBits = StopBits.One;
        _serial_port.Handshake = Handshake.None;
        _serial_port.ReadTimeout = timeout;
        _serial_port.DtrEnable = true;
        _serial_port.RtsEnable = true;

        _serial_port.Open();
        _serial_port.DiscardInBuffer();

        int totalBytes = _serial_port.BytesToRead;

        if (totalBytes > 0)
        {
            byte[] buffer = new byte[totalBytes];
            _serial_port.Read(buffer, 0, totalBytes);
            res = ByteArrayToString(buffer);
        }
        else
        {
            byte[] buffer = new byte[dataSize];

            for (int len = 0; len < buffer.Length;)
            {
                len += _serial_port.Read(buffer, len, buffer.Length - len);
            }

            res = ByteArrayToString(buffer);
        }

        _serial_port.Close();

        return res;
    }
    catch (Exception ex)
    {
        if (ex is UnauthorizedAccessException || ex is TimeoutException)
        {
            _serial_port.Close();
        }

        return ex.ToString();
    }
}

I know there are other methods to read data like: "ReadByte", "ReadChar", "ReadExisting", "ReadLine" and "ReadTo" but none of them are working, am i doing something wrong?

Body:
The serial port is a stream device, it can continuously receive data. You'll need to set a timer as long the serial port is open to continuously check if there's anything in the buffer and copy it to a buffer or file on disk as soon as possible to prevent a buffer overflow.

You need to check the data contents to find out what is received and when all of it is received. This depends on the sender. You can't just say receive all there is to receive, it's a continous stream as far as the serial port is concerned. The actual data needs to specify the protocol, start and stop conditions.

EDIT

Here's a code snippet I use to capture floppy disk data through a usb to rs232 device at 5mbit/sec:

    // Capture handler
    private void timer2_Tick(object sender, EventArgs e)
    {
        // Read data from serial port, poll every 10ms
        // If data is there, read a block and write it to array
        int bytestoread = 0;
        //byte buf;

        timer2.Stop();
        try
        {
            bytestoread = serialPort1.BytesToRead;
        }

        catch (InvalidOperationException ex)
        {
            tbr.Append("Serial connection lost. Exception type:" + ex.ToString());
            if ((uint)ex.HResult == 0x80131509)
            {
                timer2.Stop();
            }
        }

        if (serialPort1.IsOpen)
        {
            if (bytestoread != 0)
            {
                bytespersecond += bytestoread;

                byte[] temp = new byte[bytestoread];

                if (serialPort1.IsOpen)
                    serialPort1.Read(temp, 0, bytestoread);

                tempbuffer.Add(temp);
                processing.indexrxbuf += bytestoread;
                recentreadbuflength += bytestoread;

                //update the scatterplot, this may have a performance hit
                processing.rxbuf = tempbuffer.SelectMany(a => a).ToArray();
                rxbuf = processing.rxbuf;
                if (Setrxbufcontrol == null) return;
                Setrxbufcontrol();

            }
            timer2.Start();
        }
    }

setup code for serial port. I defined large buffers to prevent overflows:

        serialPort1.BaudRate = 5000000;
        serialPort1.NewLine = "\r\n";
        serialPort1.ReceivedBytesThreshold = 500000;
        serialPort1.ReadBufferSize = 1048576;

EDIT 2

Steps to read from a serial port:

Define a received data array to hold the data

Open serial port

Set a timer to read data continuously until user hits disconnect button

timer tick method checks the length of data in serial buffer, then read that length into the receive buffer defined in step 1. Keep track of total received data by adding the serial buffer length to a static variable.

In another timer you could check the received data array for new lines. Copy all data to an array of strings, or to a textbox. Or just copy the data as a string to the textbox to see what's in it.


问:
Trying to parse JSON Object from POST Request in Express v4 using body-parser
I'm currently teaching myself more about server code, specifically using Node.js and Express, and I'm having a lot of trouble with receiving and parsing a JSON object sent from a POST request. I have looked at numerous other posts (linked to below) and I can't figure out for the life of me what's going wrong. Here's what I've looked at:

Javascript: Send JSON Object with AJAX
Javascript : Send JSON Object with Ajax?
How do I consume the JSON POST data in an Express application
How do I consume the JSON POST data in an Express application
Send POST data using XMLHttpRequest
Send POST data using XMLHttpRequest
How do you extract POST data in Node.js?
How do you extract POST data in Node.js?

All of these are putting me on the right track, but I'm not quite there and thus looking for help. Here's the code I'm working with:

Send POST Request

```<code>var button = document.querySelector("#button");

button.onclick = function(){
    console.log("Getting data from local server");

    var xhr = new XMLHttpRequest();

    xhr.open("POST", "http://localhost:3000/data/test.json", true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send(JSON.stringify({"latitude": 41.2418, "longitude": -70.8898}));
};
</code>```

Handle POST Request In Server

```<code>var http = require("http");
var fs = require("fs");
var express = require("express");
var app = express();
var path = require("path");
var bodyParser = require("body-parser");

var port = process.env.PORT || 3000;
//tells express where to find all the static files (HTML, CSS, etc) and load them into the browser
app.use(express.static(path.join(__dirname, '../client')));

//tells the application to use body-parser as middleware so it can handle post requests
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

//routing methods
//deal with incoming GET and POST requests to the server
app.get("/", function(req, res){
    res.send("Submitted GET Request");
})

//only handles incoming POST requests to the test.json resource
app.post("/data/test.json", function(req, res){
    console.info("Submitting POST Request to Server");
    console.info("Request body: " + req.body);
    //write the file
    fs.writeFile(__dirname + "/../client/data/test.json", req.body,
    function(err){
        if(err){
            console.error(err); //print out the error in case there is one
            return res.status(500).json(err);
        }

        //resolve the request with the client
        console.info("updated test.json");
        res.send();
    });
})

//tell the express object to create the server and listen on the port
app.listen(port);
console.log("Listening on localhost:" + port);
</code>```

Whenever I try to print out the contents of "req.body" I get the output of "[object Object]". Any ideas?

EDIT:
My issue has been solved. I have changed

```<code>console.info("Request body: " + req.body);
</code>```

To

```<code>console.info("Request body: " + JSON.stringify(req.body));
</code>```

I also changed my Content-Type in my POST XMLHTTPRequest to "application/json" to help with formatting.

答:
"[object Object]" is the default result of JavaScript's implicit toString operation, which it uses when trying to write a string representation of that object to the file.

Try writing JSON.stringify(req.data) to the file instead.

Also, on the client side – consider changing your Content-Type header to match:

xhr.setRequestHeader("Content-Type", "application/json");

Body:
I'm currently teaching myself more about server code, specifically using Node.js and Express, and I'm having a lot of trouble with receiving and parsing a JSON object sent from a POST request. I have looked at numerous other posts (linked to below) and I can't figure out for the life of me what's going wrong. Here's what I've looked at:

Javascript: Send JSON Object with AJAX
Javascript : Send JSON Object with Ajax?
How do I consume the JSON POST data in an Express application
How do I consume the JSON POST data in an Express application
Send POST data using XMLHttpRequest
Send POST data using XMLHttpRequest
How do you extract POST data in Node.js?
How do you extract POST data in Node.js?

All of these are putting me on the right track, but I'm not quite there and thus looking for help. Here's the code I'm working with:

Send POST Request

var button = document.querySelector("#button");

button.onclick = function(){
    console.log("Getting data from local server");

    var xhr = new XMLHttpRequest();

    xhr.open("POST", "http://localhost:3000/data/test.json", true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send(JSON.stringify({"latitude": 41.2418, "longitude": -70.8898}));
};

Handle POST Request In Server

var http = require("http");
var fs = require("fs");
var express = require("express");
var app = express();
var path = require("path");
var bodyParser = require("body-parser");

var port = process.env.PORT || 3000;
//tells express where to find all the static files (HTML, CSS, etc) and load them into the browser
app.use(express.static(path.join(__dirname, '../client')));

//tells the application to use body-parser as middleware so it can handle post requests
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

//routing methods
//deal with incoming GET and POST requests to the server
app.get("/", function(req, res){
    res.send("Submitted GET Request");
})

//only handles incoming POST requests to the test.json resource
app.post("/data/test.json", function(req, res){
    console.info("Submitting POST Request to Server");
    console.info("Request body: " + req.body);
    //write the file
    fs.writeFile(__dirname + "/../client/data/test.json", req.body,
    function(err){
        if(err){
            console.error(err); //print out the error in case there is one
            return res.status(500).json(err);
        }

        //resolve the request with the client
        console.info("updated test.json");
        res.send();
    });
})

//tell the express object to create the server and listen on the port
app.listen(port);
console.log("Listening on localhost:" + port);

Whenever I try to print out the contents of "req.body" I get the output of "[object Object]". Any ideas?

EDIT:
My issue has been solved. I have changed

console.info("Request body: " + req.body);

To

console.info("Request body: " + JSON.stringify(req.body));

I also changed my Content-Type in my POST XMLHTTPRequest to "application/json" to help with formatting.


问:
D Templates: Coolest Hack
What is the coolest somewhat practical metaprogramming hack you've done or seen done in the D programming language?  Somewhat practical means excluding, for example, the compile-time raytracer.

答:
I wrote a memoize() function whose header is this (the code is a bit long for pasting here):

auto memoize(TFunc)(TFunc func);

What it does is, you give it a function's address, and it returns a strongly-typed delegate (same signature and return type as the original function) that caches the return values of the original function, so that calling it twice with the same parameter only calls the underlying function once. For instance, here is a memoized, "recursive" definition of the Fibonacci sequence that executes in linear, rather than exponential, time:

uint fib(uint n)
{ return n > 0 ? n > 1 ? memoize(&fib)(n - 1) + memoize(&fib)(n - 2) : 1 : 0; }

You can call it normally, as in: fib(1000);

Edit: The previous code whose link I posted was rather hideous; this version is much more elegant.

OwnerDisplayName: dsimcha

Title: D Templates: Coolest Hack

LastEditorDisplayName: KiwiBastard


问:
How to hash some String with SHA-256 in Java?
How can I hash some String with SHA-256 in Java?

答:
```<code>String hashWith256(String textToHash) {
    MessageDigest digest = MessageDigest.getInstance("SHA-256");
    byte[] byteOfTextToHash = textToHash.getBytes(StandardCharsets.UTF_8);
    byte[] hashedByetArray = digest.digest(byteOfTextToHash);
    String encoded = Base64.getEncoder().encodeToString(hashedByetArray);
    return encoded;
}
</code>```


问:
How to make readonly all inputs in some div in Angular2?
I have a page with many inputs, and I want to make it 'readOnly'
I find this solution: How to change HTML element readonly and required attribute in Angular2 Typescript?

But I don't want to do it for every input separately.

How can I add readOnly property to all inputs in some div.

答: If using reactive forms, you can also disable the entire form or any sub-set of controls in a FormGroup with myFormGroup.disable().


问:
AggregateException C# example
I have seen an example of AggregateException on the web and I'm trying to figure out how it works. I have written a simple example, but my code for some reason doesn't work.

Could someone explain to me what the problem is?

```<code>public static void Main()
{
    try
    {
        Parallel.For(0, 500000, i =>
        {
            if (i == 10523)
                throw new TimeoutException("i = 10523");
            Console.WriteLine(i + "\n");
        });
    }
    catch (AggregateException exception)
    {
        foreach (Exception ex in exception.InnerExceptions)
        {
            Console.WriteLine(ex.ToString());
        }
    }
}
</code>```

答:
You need to call Handle on the inner exceptions. From MSDN's documentation on Handle:

Each invocation of the predicate returns true or false to indicate whether the Exception was handled. After all invocations, if any exceptions went unhandled, all unhandled exceptions will be put into a new AggregateException which will be thrown. Otherwise, the Handle method simply returns. If any invocations of the predicate throws an exception, it will halt the processing of any more exceptions and immediately propagate the thrown exception as-is.

The example code, also from MSDN:

```<code>public static void Main()
{
    var task1 = Task.Run(() => { throw new CustomException("This exception is expected!"); });

    try
    {
        task1.Wait();
    }
    catch (AggregateException ae)
    {
        // Call the Handle method to handle the custom exception,
        // otherwise rethrow the exception.
        ae.Handle(ex =>
        {
            if (ex is CustomException)
                Console.WriteLine(ex.Message);
            return ex is CustomException;
        });
    }
}
</code>```

Title: AggregateException C# example

Body:
I have seen an example of AggregateException on the web and I'm trying to figure out how it works. I have written a simple example, but my code for some reason doesn't work.

Could someone explain to me what the problem is?

public static void Main()
{
    try
    {
        Parallel.For(0, 500000, i =>
        {
            if (i == 10523)
                throw new TimeoutException("i = 10523");
            Console.WriteLine(i + "\n");
        });
    }
    catch (AggregateException exception)
    {
        foreach (Exception ex in exception.InnerExceptions)
        {
            Console.WriteLine(ex.ToString());
        }
    }
}

Body:
You need to call Handle on the inner exceptions. From MSDN's documentation on Handle:

Each invocation of the predicate returns true or false to indicate whether the Exception was handled. After all invocations, if any exceptions went unhandled, all unhandled exceptions will be put into a new AggregateException which will be thrown. Otherwise, the Handle method simply returns. If any invocations of the predicate throws an exception, it will halt the processing of any more exceptions and immediately propagate the thrown exception as-is.

The example code, also from MSDN:

public static void Main()
{
    var task1 = Task.Run(() => { throw new CustomException("This exception is expected!"); });

    try
    {
        task1.Wait();
    }
    catch (AggregateException ae)
    {
        // Call the Handle method to handle the custom exception,
        // otherwise rethrow the exception.
        ae.Handle(ex =>
        {
            if (ex is CustomException)
                Console.WriteLine(ex.Message);
            return ex is CustomException;
        });
    }
}


问:
PHP CURLOPT_PROGRESSFUNCTION add extra custom parameter to function
I was wondering if it is possible to add an custom parameter to the function called when using

```<code>curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, array($this, 'progressFunction'));
</code>```

so the function signature would look like

```<code>private function progressFunction($clientp, $dltotal, $dlnow, $ultotal, $ulnow, $myCustomParameter) { }
</code>```

instead of

```<code>private function progressFunction($clientp, $dltotal, $dlnow, $ultotal, $ulnow) { }
</code>```

Thanks.

答:
Inside a PHP class, you can pass additional arguments like $statusName to another function as shown here:

```<code>curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, function ($resource, $downloadSize, $downloaded, $uploadSize, $uploaded) use ($statusName) {
    $this->progress($resource, $downloadSize, $downloaded, $uploadSize, $uploaded, $statusName);
});
</code>```

Then your dedicated progress function doesn't uglify the code even more than it is:

```<code>private function progress($resource, $downloadSize, $downloaded, $uploadSize, $uploaded, $statusName="curl_download_status")
{
    // emit the progress
    Cache::put($statusName, [
        'resource' => $resource,
        'download_size' => $downloadSize,
        'downloaded' => $downloaded,
        'upload_size' => $uploadSize,
        'uploaded' => $uploaded
    ], 10);

}
</code>```

Body:
I was wondering if it is possible to add an custom parameter to the function called when using

curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, array($this, 'progressFunction'));

so the function signature would look like

private function progressFunction($clientp, $dltotal, $dlnow, $ultotal, $ulnow, $myCustomParameter) { }

instead of

private function progressFunction($clientp, $dltotal, $dlnow, $ultotal, $ulnow) { }

Thanks.

Body:
Inside a PHP class, you can pass additional arguments like $statusName to another function as shown here:

curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, function ($resource, $downloadSize, $downloaded, $uploadSize, $uploaded) use ($statusName) {
    $this->progress($resource, $downloadSize, $downloaded, $uploadSize, $uploaded, $statusName);
});

Then your dedicated progress function doesn't uglify the code even more than it is:

private function progress($resource, $downloadSize, $downloaded, $uploadSize, $uploaded, $statusName="curl_download_status")
{
    // emit the progress
    Cache::put($statusName, [
        'resource' => $resource,
        'download_size' => $downloadSize,
        'downloaded' => $downloaded,
        'upload_size' => $uploadSize,
        'uploaded' => $uploaded
    ], 10);

}


问:
XAMPP: Another web server is already running
I get the following error after installing gitlab..

```<code>root@Blase:~# sudo /opt/lampp/lampp start
Starting XAMPP for Linux 7.0.9-1...
XAMPP: Starting Apache...fail.
[XAMPP:  Another web server is already running.][1]
XAMPP: Starting MySQL...already running.
</code>```

I cannot access my localhost/phpmyadmin or any projects folder as am redirected to Gitlab.

I tried to view which program is using port 80 by running:
"netstat -tulpn | grep --color :80" and i got the output shown in attached image.
Any help guys?

答:
I had to stop all the services,

```<code>$sudo /etc/init.d/apache2 stop

$sudo /etc/init.d/mysql stop

$sudo /etc/init.d/proftpd stop
</code>```

Then I restarted the server

```<code>sudo /opt/lampp/lampp restart
</code>```

Body:
I get the following error after installing gitlab..

root@Blase:~# sudo /opt/lampp/lampp start
Starting XAMPP for Linux 7.0.9-1...
XAMPP: Starting Apache...fail.
[XAMPP:  Another web server is already running.][1]
XAMPP: Starting MySQL...already running.

I cannot access my localhost/phpmyadmin or any projects folder as am redirected to Gitlab.

I tried to view which program is using port 80 by running:
"netstat -tulpn | grep --color :80" and i got the output shown in attached image.
Any help guys?

Body:
I had to stop all the services,

$sudo /etc/init.d/apache2 stop

$sudo /etc/init.d/mysql stop

$sudo /etc/init.d/proftpd stop

Then I restarted the server

sudo /opt/lampp/lampp restart


问:
Static method heritation
I have a parent class with methods for writing and reading it from the db. The problem is I have a static method which I want to generalise. What is the best practice for doing this? I've came up with some solutions but all don't work with the static method.

Is there a way to force the childobject to implement the abstract method?

Parent Class:

```<code>public class Data_object  {

    public byte[] toByteArray() throws IOException  {
        return null;
    }
    public static Data_object fromByteArray(byte[] data){
        return null
    }
}
</code>```

Child class:

```<code>public class ModelObject extends Data_object {

    public static Data_object fromByteArray(byte[] data){
        ModelObject result = new ModelObject();
        //set data from byte arrray
        return result;
    }
}
</code>```

thanks

答:
Inheritance does not apply to static methods that way. You call a static method on a specific class, like this:

```<code>MonkeyModelObject.fromByteArray(data)
</code>```

Even when you do this from "inside" a class, you're behind-the-scenes still invoking that specific method on that specific class. So if you "override" a static method, you're just making a new method with the same name in another class (the child class). There's no run-time selection of methods for static methods.

For the specific case that you're working on, it seems like you're doing serialization from/to byte arrays. Perhaps you're serializing messages from a network stream, or something like that? I would recommend the following approach, maybe this pseudocode can inspire you:

```<code>abstract class Message
{
    void write(stream)
    {
        stream.write(getMessageTypeCode());
        writeParameters(stream);
    }
    abstract int getMessageTypeCode();
    abstract void writeParameters(stream);
    abstract void readParamters(stream);
}
class ChatMessage
{
    String text;
    int getMessageTypeCode() { return 1; }
    void writeParameters(stream)
    {
        stream.write(text);
    }
    void readParameters(stream)
    {
        text = stream.read();
    }
}
class MessageDecoder
{
    Message decode(stream)
    {
        int type = stream.read();
        message = createMessage(type);
        message.readParameters(stream);
        return message;
    }
    Message createMessage(int type)
    {
        if (type == 1)
        {
            return new ChatMessage();
        }
        throw new error;
    }
}
</code>```

Title: Static method heritation

Body:
I have a parent class with methods for writing and reading it from the db. The problem is I have a static method which I want to generalise. What is the best practice for doing this? I've came up with some solutions but all don't work with the static method.

Is there a way to force the childobject to implement the abstract method?

Parent Class:

public class Data_object  {

    public byte[] toByteArray() throws IOException  {
        return null;
    }
    public static Data_object fromByteArray(byte[] data){
        return null
    }
}

Child class:

public class ModelObject extends Data_object {

    public static Data_object fromByteArray(byte[] data){
        ModelObject result = new ModelObject();
        //set data from byte arrray
        return result;
    }
}

thanks

Body:
Inheritance does not apply to static methods that way. You call a static method on a specific class, like this:

MonkeyModelObject.fromByteArray(data)

Even when you do this from "inside" a class, you're behind-the-scenes still invoking that specific method on that specific class. So if you "override" a static method, you're just making a new method with the same name in another class (the child class). There's no run-time selection of methods for static methods.

For the specific case that you're working on, it seems like you're doing serialization from/to byte arrays. Perhaps you're serializing messages from a network stream, or something like that? I would recommend the following approach, maybe this pseudocode can inspire you:

abstract class Message
{
    void write(stream)
    {
        stream.write(getMessageTypeCode());
        writeParameters(stream);
    }
    abstract int getMessageTypeCode();
    abstract void writeParameters(stream);
    abstract void readParamters(stream);
}
class ChatMessage
{
    String text;
    int getMessageTypeCode() { return 1; }
    void writeParameters(stream)
    {
        stream.write(text);
    }
    void readParameters(stream)
    {
        text = stream.read();
    }
}
class MessageDecoder
{
    Message decode(stream)
    {
        int type = stream.read();
        message = createMessage(type);
        message.readParameters(stream);
        return message;
    }
    Message createMessage(int type)
    {
        if (type == 1)
        {
            return new ChatMessage();
        }
        throw new error;
    }
}


答:
This way it will work:</p>

```<code>select *, row_number() over(partition by
column0 order by [column3]) as column4 from
(select ID, column0, column1, column2, column3 = Case when
column2 = '' then column1 else column2 end from myTable) ti
</code>```

Title: SQL Server order by case

Body:
This way it will work:

select *, row_number() over(partition by
column0 order by [column3]) as column4 from
(select ID, column0, column1, column2, column3 = Case when
column2 = '' then column1 else column2 end from myTable) ti