问:
Delphi: How to get the address of a static record
```<code>    type
      TMyRecord = record
      private
        class constructor create;
      public
        class var MyField1: string;
        class var MyField2: integer;
        class var MyField3: extended;
        class function ToString: string; static;
      end;

    class constructor TMyRecord.Create;
    begin
        TMyRecord.MyField1 := 'Hello, world!';
        TMyRecord.MyField2 := 123;
        TMyRecord.MyField3 := 3.1415927;
    end;

    class function TMyRecord.ToString: string;
    var
      RecType: TRTTIType;
      RecFields: TArray<TRttiField>;
      I: integer;
    begin
      RecType := TRTTIContext.Create.GetType(TypeInfo(TMyRecord));
      Result := RecType.ToString;
      RecFields := RecType.GetFields;
      for I := 0 to High(RecFields) do
        Result := Result + Format('%s: %s = %s', [RecFields[I].Name, RecFields[I].FieldType.ToString, RecFields[I].GetValue(@TMyRecord).ToString]) + sLineBreak;
    end;
</code>```

I am trying to get TMyRecord.ToString to return:

```<code>    TMyRecord
    MyField1: string = Hello, world!
    MyField2: integer = 123;
    MyField3: extended = 3.1415927;
</code>```

However, I get a compiler error on GetValue(@TMyRecord) - E2029 '(' expected but ')' found

Normally GetValue should be called with the address of the 'instance' of the record. But in this case the record is static.
I do not want to convert this record to a normal record, create an instance etc. I'm trying to solve this for a static record.
How can I get the address that should be passed to GetValue?

答: To the best of my knowledge, class fields are not accessible through RTTI.</p>

Body:
    type
      TMyRecord = record
      private
        class constructor create;
      public
        class var MyField1: string;
        class var MyField2: integer;
        class var MyField3: extended;
        class function ToString: string; static;
      end;

    class constructor TMyRecord.Create;
    begin
        TMyRecord.MyField1 := 'Hello, world!';
        TMyRecord.MyField2 := 123;
        TMyRecord.MyField3 := 3.1415927;
    end;

    class function TMyRecord.ToString: string;
    var
      RecType: TRTTIType;
      RecFields: TArray<TRttiField>;
      I: integer;
    begin
      RecType := TRTTIContext.Create.GetType(TypeInfo(TMyRecord));
      Result := RecType.ToString;
      RecFields := RecType.GetFields;
      for I := 0 to High(RecFields) do
        Result := Result + Format('%s: %s = %s', [RecFields[I].Name, RecFields[I].FieldType.ToString, RecFields[I].GetValue(@TMyRecord).ToString]) + sLineBreak;
    end;

I am trying to get TMyRecord.ToString to return:

    TMyRecord
    MyField1: string = Hello, world!
    MyField2: integer = 123;
    MyField3: extended = 3.1415927;

However, I get a compiler error on GetValue(@TMyRecord) - E2029 '(' expected but ')' found

Normally GetValue should be called with the address of the 'instance' of the record. But in this case the record is static.
I do not want to convert this record to a normal record, create an instance etc. I'm trying to solve this for a static record.
How can I get the address that should be passed to GetValue?


来源: stackexchange

问:
Disable button until checkbox ticked
Apologies if this has already been asked, i have found it difficult to use the answers I have found to use in my code.

Basically, I have a "receive" button, that when the user clicks, will receive an email. But, I want a tick box checked in order for the button to become clickable. I have a code that kind of works, but when the page first loads, the "Receive" button is already clickable. However, when I click the tick box then unclick it, it disables the button.

```<code><td>
    <input type="checkbox"  id="tick" onchange="document.getElementById('terms').disabled = !this.checked;" />
    <td>
    <p> I agree to the <a href="terms.html" target="_blank">Terms & Conditions</a></p>
    </td>
</td>
</tr>
<td class="label1"></td>
<td align="right">
    <button type="submit" class="btn btn1" name="terms" id="terms">Receive</i></button>
</td>
</code>```

答:
Adding "disabled" attribute to the button is a better solution.

The disabled attribute is a boolean attribute.

When present, it specifies that the button should be disabled.

A disabled button is unusable and un-clickable.

ContentLicense: CC BY-SA 3.0

Title: Disable button until checkbox ticked

Body:
Apologies if this has already been asked, i have found it difficult to use the answers I have found to use in my code.

Basically, I have a "receive" button, that when the user clicks, will receive an email. But, I want a tick box checked in order for the button to become clickable. I have a code that kind of works, but when the page first loads, the "Receive" button is already clickable. However, when I click the tick box then unclick it, it disables the button.

    <input type="checkbox"  id="tick" onchange="document.getElementById('terms').disabled = !this.checked;" />

 I agree to the Terms & Conditions

    <button type="submit" class="btn btn1" name="terms" id="terms">Receive</button>


问:
Remove common characters or duplicates in a string
I'm trying to remove duplicates in a string upon user input. Here''s my code:

```<code>userinput = input("Enter a word:")
def duplicates_removal(x):
      for i in range(len(x)-1):
             if x[i] == x[i +1]:
                     return duplicates_removal(x.replace(x[i], ' '))
      return x

print(duplicates_removal(userInput))
</code>```

When I run the code, and input the string Bananas,  it produces the output Bananas with the duplicates not removed. Is there any flaws in the code? Also I prefer not using built in functions for this since I just started learning on string manipulation.

```<code>Input: Bananas
Output desired: Bans
</code>```

答:
```<code>def duplicates_removal(x):
    l = []
    for each in x:
        if each not in l:
            l.append(each)
    return "".join(l)
</code>```

Body:
I'm trying to remove duplicates in a string upon user input. Here''s my code:

userinput = input("Enter a word:")
def duplicates_removal(x):
      for i in range(len(x)-1):
             if x[i] == x[i +1]:
                     return duplicates_removal(x.replace(x[i], ' '))
      return x

print(duplicates_removal(userInput))

When I run the code, and input the string Bananas,  it produces the output Bananas with the duplicates not removed. Is there any flaws in the code? Also I prefer not using built in functions for this since I just started learning on string manipulation.

Input: Bananas
Output desired: Bans


问:
Keycloak 'ExampleDS' in production
I'm following the guide to set up Keycloak 3.0.0 in HA mode for production with an Oracle DB. I see in the standalone-ha.xml file there's a subsystem:

```<code><subsystem xmlns="urn:jboss:domain:ee:4.0">
</code>```

At the bottom of that subsystem section there's a <default-bindings> element that refers to an ExampleDS datasource:

```<code><default-bindings context-service="java:jboss/ee/concurrency/context/default" datasource="java:jboss/datasources/ExampleDS" managed-executor-service="java:jboss/ee/concurrency/executor/default" managed-scheduled-executor-service="java:jboss/ee/concurrency/scheduler/default" managed-thread-factory="java:jboss/ee/concurrency/factory/default"/>
</code>```

ExampleDS is declared to use the h2 driver, which we cannot use in production.

Can I change that <default-bindings> element to refer to my Oracle KeycloakDS datasource?

答: You will need to add and configure the oracle jdbc driver beforehand and then add the datasource that is needed for keycloak. You can follow the example setup that is stated here. What you have seen there with ExampleDS h2 is just the standard example configuration that comes with wildfly by default, so this won't help you as keycloak will complain that there is no KeycloakDS (as stated in the linked tutorial) </p>

Title: Keycloak 'ExampleDS' in production

Body:
I'm following the guide to set up Keycloak 3.0.0 in HA mode for production with an Oracle DB. I see in the standalone-ha.xml file there's a subsystem:

<subsystem xmlns="urn:jboss:domain:ee:4.0">

At the bottom of that subsystem section there's a <default-bindings> element that refers to an ExampleDS datasource:

<default-bindings context-service="java:jboss/ee/concurrency/context/default" datasource="java:jboss/datasources/ExampleDS" managed-executor-service="java:jboss/ee/concurrency/executor/default" managed-scheduled-executor-service="java:jboss/ee/concurrency/scheduler/default" managed-thread-factory="java:jboss/ee/concurrency/factory/default"/>

ExampleDS is declared to use the h2 driver, which we cannot use in production.

Can I change that <default-bindings> element to refer to my Oracle KeycloakDS datasource?


问:
Local install or remote install of a MySQL database?
Could someone explain the advantages and disadvantages of installing a MySQL database on a local machine compared to a remote machine (on a server)?

Thanks.
L.

答:
your computer is used as a client, so you don't make connections with other servers (just your provider), thus is it more time efficient on a server

the support is better on a web hosting environment, so is the security

installing, managing a database server can get complicated, so the web hosting company offers you Mysql out of the box (no complicated configurations/installations)

you might want to shut down your computer once in a while, so the mysql server stops

your hardware and os is optimized for client work, not for a server, so it's not cost efficient

it slows down your computer

The only advantage is if you also host your http server (or application server) on your computer, then you don't have to pay the web hosting fee. But it gets complicated, you can mess up easily and the electricity cost you more then a shared hosting (I did the math).

ContentLicense: CC BY-SA 2.5


问:
Pseudo-WYSIWYG Emacs
With just the few lines in a file file.adoc

```<code>////
-*-iimage-mode-*-
////

.A PNG smiley
image::smiley.png[]
</code>```

I can generate HTML using asciidoctor and MS-word .doc using pandoc.
This toolchain doesn't handle SVG, and so it's not perfect, but it works well, and
it's free.

file.html

There is a snag though:

I'd like iimage-mode to be enabled when I load file.adoc. My attempt (the first three lines in the source above) doesn't work. Can you think of a way that will?

.emacs

```<code>(set-foreground-color "white")
(set-background-color "black")

(require 'adoc-mode)
(setq auto-mode-alist (cons '("\\.adoc\\'" . adoc-mode) auto-mode-alist))
</code>```

Comments

I am writing these comments here to be able to typeset.

Asciidoctor
(I'm using to the superior implementation of the asciidoc syntax written in Ruby) does have (now?) line comments in addition to block comments.

Using

// -- mode: iimage --

on the first line works (thanks, Nick). But it replaces the adoc major mode (thanks, phils).

Adding at the bottom of the file:

//// Local Variables:

eval: (iimage-mode 1)

End:

////

switches to minor mode iimage while the major mode remains adoc.

phils's suggestion to use my-adoc-mode-hook works well.

I'm forking the second part to a separate question. This discussion is already long enough for one question.

Update

Using asciidoctor + pandoc may produce a .doc file that is handled correctly with a recent version of MS-Word. Comments welcome. MS-Word 2011 on OS X opens the resulting .doc file fine, but shows an error message in the place of SVG images.

If this works, it will (finally) be a way to send a .doc file to all those people who insist on them, while editing in an environment as flexible as Emacs.

答:
Nick's answer is mostly correct, but iimage-mode is a minor mode, and using mode:... in local variables is (nowadays) intended for major modes only. Using it to enable minor modes is deprecated (even if it still works in some situations1).

Instead use eval:... to call the minor mode function like so2:

//// -*- eval: (iimage-mode 1); -*-
```

<p>or</p>

<pre class="lang-el prettyprint-override"><code>//// Local Variables:
//// eval: (iimage-mode 1)
//// End:
</code>```

Note also that -*- iimage -*- is equivalent to -*- mode: iimage -*-, and that for both forms Emacs appends a -mode suffix to get the actual mode name.

Hence -*-iimage-mode-*- is asking to use iimage-mode-mode -- and in fact Emacs should have produced a message "Ignoring unknown mode `iimage-mode-mode'".

Finally, if you want iimage-mode enabled for all adoc-mode files, then you can use a mode hook in your init file instead of using file-local variables:

(add-hook 'adoc-mode-hook 'my-adoc-mode-hook)

(defun my-adoc-mode-hook ()
  "Custom `adoc-mode' behaviours."
  (iimage-mode 1))
```

1 In this case, if you had used -*-iimage-*- or -*-mode: iimage-*- as the only local variable mode spec, Emacs would treat it as a major mode, and your intended adoc-mode major mode would not be used.

2 I'm following Nick's answer in assuming that //// is the correct line-comment prefix, but the question makes it look more like a block comment syntax, so I don't know if it's correct.

Title: Pseudo-WYSIWYG Emacs

Body:
With just the few lines in a file file.adoc

////
-*-iimage-mode-*-
////

.A PNG smiley
image::smiley.png[]

I can generate HTML using asciidoctor and MS-word .doc using pandoc.
This toolchain doesn't handle SVG, and so it's not perfect, but it works well, and
it's free.

file.html

There is a snag though:

I'd like iimage-mode to be enabled when I load file.adoc. My attempt (the first three lines in the source above) doesn't work. Can you think of a way that will?

.emacs

(set-foreground-color "white")
(set-background-color "black")

(require 'adoc-mode)
(setq auto-mode-alist (cons '("\\.adoc\\'" . adoc-mode) auto-mode-alist))

Comments

I am writing these comments here to be able to typeset.

Asciidoctor
(I'm using to the superior implementation of the asciidoc syntax written in Ruby) does have (now?) line comments in addition to block comments.

Using

// -- mode: iimage --

on the first line works (thanks, Nick). But it replaces the adoc major mode (thanks, phils).

Adding at the bottom of the file:

//// Local Variables:

eval: (iimage-mode 1)

End:

////

switches to minor mode iimage while the major mode remains adoc.

phils's suggestion to use my-adoc-mode-hook works well.

I'm forking the second part to a separate question. This discussion is already long enough for one question.

Update

Using asciidoctor + pandoc may produce a .doc file that is handled correctly with a recent version of MS-Word. Comments welcome. MS-Word 2011 on OS X opens the resulting .doc file fine, but shows an error message in the place of SVG images.

If this works, it will (finally) be a way to send a .doc file to all those people who insist on them, while editing in an environment as flexible as Emacs.

Body:
Nick's answer is mostly correct, but iimage-mode is a minor mode, and using mode:... in local variables is (nowadays) intended for major modes only. Using it to enable minor modes is deprecated (even if it still works in some situations1).

Instead use eval:... to call the minor mode function like so2:

//// -*- eval: (iimage-mode 1); -*-

or

//// Local Variables:
//// eval: (iimage-mode 1)
//// End:

Note also that -*- iimage -*- is equivalent to -*- mode: iimage -*-, and that for both forms Emacs appends a -mode suffix to get the actual mode name.

Hence -*-iimage-mode-*- is asking to use iimage-mode-mode -- and in fact Emacs should have produced a message "Ignoring unknown mode `iimage-mode-mode'".

Finally, if you want iimage-mode enabled for all adoc-mode files, then you can use a mode hook in your init file instead of using file-local variables:

(add-hook 'adoc-mode-hook 'my-adoc-mode-hook)

(defun my-adoc-mode-hook ()
  "Custom `adoc-mode' behaviours."
  (iimage-mode 1))

1 In this case, if you had used -*-iimage-*- or -*-mode: iimage-*- as the only local variable mode spec, Emacs would treat it as a major mode, and your intended adoc-mode major mode would not be used.

2 I'm following Nick's answer in assuming that //// is the correct line-comment prefix, but the question makes it look more like a block comment syntax, so I don't know if it's correct.


问:
Is it possible to interact with a Linux Command line interface (CLI) through a Graphical user interface (GUI)?
I am quite a beginner, any advice is much appreciated.

I have a linux application OpenBTS used to simulate and run a GSM network on a software defined radio device e.g USRP.

I want to build an application that interfaces with the OpenBTS command line on Linux. I want to give the user an easier way to configure and to display the current configurations of the application. The user would have an interface in which he could play with the configurations without the need to use the  terminal.

I don't know if this is possible ?
Is it possible to interact with a Linux CLI through a GUI ? If yes what is the most efficient programming language, coding technique or approach to do that ?

Thanks a lot

答:
You could generate a config file using your GUI and then use standard in to get the configuration into OpenBts. When launching OpenBts with the configuration file config.txt you could simply run it as follows.

./OpenBts < config.txt

You could also do this from you GUI by launching OpenBts in a process from your GUI application in a similar fashion, however this requires a fork() and exec()


问:
Custom file parser slows down with every next file
I have built a simple file parser that reads a csv file line by line and adds it to the DB.

i dont commit changes to the DB till after the file is completely parsed.

It works fine but for some reason with every next file - the parsing becomes slower and slower
here is the code any suggestions on how to speed it up are very welcome.

```<code>using Microsoft.VisualBasic.FileIO;
using System;
using System.IO;

namespace CsvToSQL
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            TransactionsEntities entities = new TransactionsEntities();

            string targetFolderPath = "C:\\Transactions\\";
            string[] allFiles = Directory.GetFiles(targetFolderPath);

            //Loop through files in folder
            foreach (var file in allFiles)
            {
                //parse file
                Console.WriteLine(file);
                using (TextFieldParser parser = new TextFieldParser(file))
                {
                    parser.TextFieldType = FieldType.Delimited;
                    parser.SetDelimiters(",");
                    int lineNo = 0;

                    while (!parser.EndOfData)
                    {

                        TransactionList transaction = new TransactionList();
                        //processing row
                        string[] fields = parser.ReadFields();
                        try
                        {
                         if(lineNo % 20 == 0)
                            {
                                Console.WriteLine(file + " Parsed line no: " + lineNo);
                            }
                            transaction.Account = fields[0];
                            transaction.Timestamp = fields[1];
                            transaction.TransactionType = fields[2];
                            transaction.Status = fields[3];
                            transaction.Product = fields[4];
                            transaction.Price = fields[5];
                            transaction.BuySell = fields[6];
                            transaction.Series = fields[7];
                            transaction.Volume = fields[8];
                            transaction.FillVolume = fields[9];
                            transaction.OrderID = fields[10];
                            transaction.BestBid = fields[11];
                            transaction.BestAsk = fields[12];

                            entities.TransactionLists.Add(transaction);

                            lineNo++;

                        }
                        catch(Exception e)
                        {
                            Console.WriteLine(e.ToString());
                            Console.ReadKey();
                        }

                    }
                    try
                    {
                        entities.SaveChanges();
                    }catch(Exception e)
                    {
                        Console.WriteLine(e.ToString());
                        Console.ReadKey();
                    }

                }

            }
        }
    }
}
</code>```

答:
Hi all i found the memory issue with this - if anyone comes across a similar problem.

 TransactionsEntities entities = new TransactionsEntities();```
</div>
</div>
</p>

<p>This is what is causing it to slow down so incredibly. It uses the same connection to DB replaced it with:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code> using (TransactionsEntities entities = new TransactionsEntities()){
 //Transaciton parsing code for 1 file
 }</code>```

and the application is flying through the files at 100x the speed it was before :)

Body:
I have built a simple file parser that reads a csv file line by line and adds it to the DB.

i dont commit changes to the DB till after the file is completely parsed.

It works fine but for some reason with every next file - the parsing becomes slower and slower
here is the code any suggestions on how to speed it up are very welcome.

using Microsoft.VisualBasic.FileIO;
using System;
using System.IO;

namespace CsvToSQL
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            TransactionsEntities entities = new TransactionsEntities();

            string targetFolderPath = "C:\\Transactions\\";
            string[] allFiles = Directory.GetFiles(targetFolderPath);

            //Loop through files in folder
            foreach (var file in allFiles)
            {
                //parse file
                Console.WriteLine(file);
                using (TextFieldParser parser = new TextFieldParser(file))
                {
                    parser.TextFieldType = FieldType.Delimited;
                    parser.SetDelimiters(",");
                    int lineNo = 0;

                    while (!parser.EndOfData)
                    {

                        TransactionList transaction = new TransactionList();
                        //processing row
                        string[] fields = parser.ReadFields();
                        try
                        {
                         if(lineNo % 20 == 0)
                            {
                                Console.WriteLine(file + " Parsed line no: " + lineNo);
                            }
                            transaction.Account = fields[0];
                            transaction.Timestamp = fields[1];
                            transaction.TransactionType = fields[2];
                            transaction.Status = fields[3];
                            transaction.Product = fields[4];
                            transaction.Price = fields[5];
                            transaction.BuySell = fields[6];
                            transaction.Series = fields[7];
                            transaction.Volume = fields[8];
                            transaction.FillVolume = fields[9];
                            transaction.OrderID = fields[10];
                            transaction.BestBid = fields[11];
                            transaction.BestAsk = fields[12];

                            entities.TransactionLists.Add(transaction);

                            lineNo++;

                        }
                        catch(Exception e)
                        {
                            Console.WriteLine(e.ToString());
                            Console.ReadKey();
                        }

                    }
                    try
                    {
                        entities.SaveChanges();
                    }catch(Exception e)
                    {
                        Console.WriteLine(e.ToString());
                        Console.ReadKey();
                    }

                }

            }
        }
    }
}

Body:
Hi all i found the memory issue with this - if anyone comes across a similar problem.

 TransactionsEntities entities = new TransactionsEntities();

This is what is causing it to slow down so incredibly. It uses the same connection to DB replaced it with:

 using (TransactionsEntities entities = new TransactionsEntities()){
 //Transaciton parsing code for 1 file
 }

and the application is flying through the files at 100x the speed it was before :)


问:
Gray Box thumbnail icon Google Play Developer Console
i have a problem in the Google Play Developer Console.
After i had uploaded a new update of one of my apps, the thumbnail icon of this app in the "All Applications" page changed to this. I had set a different icon both on android manifest and "Store listing" page.</p>

答:
Yesterday I have updated my app and Yes the mysterious Gray box has not even left me.

Here is Google group discussing the same: https://groups.google.com/forum/#!topic/android-discuss/mJAn1oGRZpQ

According to Peter

It turns out my hdpi icon was 57x57 instead of being the correct size.
  Fixing the size and adding a mdpi version for good measure seems to
  have fixed the issue. Strange how only the website is bothered by it
  but I guess it was my own fault for not bothering to perform what
  seemed like an unnecessary resize when I started the app.

I'll try to do the same for my next update, may be in time Google solve the issue, I'm also going to report this to Google.

Update: Seems like issue resolved, I got back my app icon back without applying any changes(29/3/2017)


问:
PhantomJS error: Cannot access member 'write' of deleted QObject
I need to create web api on port 7788 which will accept json, then pass that json to my api which will render website, and then phantom js will find element on that page and web api on port 7788 should return that element. Everything's go well till moment I try to send reponse to my server on 7788, error:

cannot access member `write' of deleted QObject:

for this: firstResponse.write(imgsrc);

Is it possible to return element with server.listen response after page.open is called?

```<code>var server = require('webserver').create();
    var port = require('system').env.PORT || 7788;

    server.listen(port, {'keepAlive': false}, function (request, response) {

        console.log("request method: ", request.method);  // request.method POST or GET
            var imgsrc;
            var firstResponse = response;

        if (request.method == 'POST') {

            var page = require('webpage').create();
            var settings = {
              operation: "POST",
              encoding: "utf8",
              headers: {
                "Content-Type": "application/json"
              },
              data: JSON.stringify(request.post)
            };
            var url = "http://127.0.0.1:5000/mapapp";

             page.onConsoleMessage = function(msg, lineNum, sourceId) {
                console.log('CONSOLE: ' + msg + ' (from line #' + lineNum + ' in "' + sourceId + '")');
            };

            page.open(url, settings, function (status) {

                setTimeout(function () {
                    page.evaluate(function () {

                        imgsrc = document.getElementById("exportedImg").src;
                    });

                }, 5000);
            });
            page.close();
            setTimeout(function () {
                    firstResponse.write(imgsrc);

                }, 7000);
        firstResponse.close();

        }

    });
</code>```

答:
You call firstResponse.close(); before is called firstResponse.write(imgsrc); after your timeout.
Move firstResponse.close() to setTimeout handler:</p>

```<code>page.close();
setTimeout(function () {
            firstResponse.write(imgsrc);
            firstResponse.close();
}, 7000);
</code>```

Body:
I need to create web api on port 7788 which will accept json, then pass that json to my api which will render website, and then phantom js will find element on that page and web api on port 7788 should return that element. Everything's go well till moment I try to send reponse to my server on 7788, error:

cannot access member `write' of deleted QObject:

for this: firstResponse.write(imgsrc);

Is it possible to return element with server.listen response after page.open is called?

var server = require('webserver').create();
    var port = require('system').env.PORT || 7788;

    server.listen(port, {'keepAlive': false}, function (request, response) {

        console.log("request method: ", request.method);  // request.method POST or GET
            var imgsrc;
            var firstResponse = response;

        if (request.method == 'POST') {

            var page = require('webpage').create();
            var settings = {
              operation: "POST",
              encoding: "utf8",
              headers: {
                "Content-Type": "application/json"
              },
              data: JSON.stringify(request.post)
            };
            var url = "http://127.0.0.1:5000/mapapp";

             page.onConsoleMessage = function(msg, lineNum, sourceId) {
                console.log('CONSOLE: ' + msg + ' (from line #' + lineNum + ' in "' + sourceId + '")');
            };

            page.open(url, settings, function (status) {

                setTimeout(function () {
                    page.evaluate(function () {

                        imgsrc = document.getElementById("exportedImg").src;
                    });

                }, 5000);
            });
            page.close();
            setTimeout(function () {
                    firstResponse.write(imgsrc);

                }, 7000);
        firstResponse.close();

        }

    });

Body:
You call firstResponse.close(); before is called firstResponse.write(imgsrc); after your timeout.
Move firstResponse.close() to setTimeout handler:

page.close();
setTimeout(function () {
            firstResponse.write(imgsrc);
            firstResponse.close();
}, 7000);


问:
How to replace () with empty spacein notepad ++
How to replace empty braces ( ) with empty space in notepad++.

Thanks

答:
In Note pad++ do ctrl+h and then check 'extend' option

now
find what ()
replace with    (empty space)


问:
Duplicate jquery on add and removeclass
I am using addClase and removeClass like this:

```<code>$('.myBar').removeClass('number1');
$('.myBar').addClass('number2');
</code>```

But this gives a error: "Duplicated jQuery selector".

Is this bad and do I have to chance something or do I just ignore it?

Btw, this is my first time working with jQuery so i'm just playing around with it.

答:
Use removeClass and addClass functions in one line to avoid duplicating the selector.

$('.myBar').removeClass('number1').addClass('number2');```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.number1 {
  color: red;
}

.number2 {
  color: green;
}</code>```

Text
```

Title: Duplicate jquery on add and removeclass

Body:
I am using addClase and removeClass like this:

$('.myBar').removeClass('number1');
$('.myBar').addClass('number2');

But this gives a error: "Duplicated jQuery selector".

Is this bad and do I have to chance something or do I just ignore it?

Btw, this is my first time working with jQuery so i'm just playing around with it.

Body:
Use removeClass and addClass functions in one line to avoid duplicating the selector.

$('.myBar').removeClass('number1').addClass('number2');

.number1 {
  color: red;
}

.number2 {
  color: green;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class='myBar number1'>Text</p>


问:
Getting 'unrecognised selector' from NSNotificationCenter
I'm trying to implement an observer in the NSNotificationCenter.  Instead of using self as the observer I want to create a little object that does it:

```<code>typedef void (^ErrorCallback)(NSError*);
typedef void (^SuccessCallback)();
typedef void (^ReplicationChanged) (NSNotification*);

@interface SyncParams : NSObject

@property (copy) ErrorCallback errorCallback;
@property (copy) SuccessCallback successCallback;
@property (copy) ReplicationChanged replicationChanged;//this used to observe

- (void)replicationChanged:(NSNotification*)notification;

@end

@implementation SyncParams

@end
</code>```

Then later I create an instance of the observer:

```<code>SyncParams* params = [SyncParams alloc];
params.replicationChanged = ^(NSNotification* notification) {
    //do stuff here
};
</code>```

And finally add it to the NSNotificationCenter:

```<code>[[NSNotificationCenter defaultCenter] addObserver: params
                                         selector: @selector(replicationChanged:)
                                             name: kCBLReplicationChangeNotification
                                           object: replicationObject];
</code>```

But I get this error: Exception '-[SyncParams replicationChanged:]: unrecognized selector sent to instance 0x7ff945c049a0' was thrown

I'm very new to objective-c!  Any pointers?

答:
Yes and no, I ended up with the following:

```<code>[[NSNotificationCenter defaultCenter] addObserverForName:kCBLReplicationChangeNotification object:repl queue:nil usingBlock:^(NSNotification *notification) {

    NSString *status;
    if (repl.status == kCBLReplicationActive) {
        NSLog(@"Repication in progress");
        status = @"in-progrss";
    } else if (repl.status == kCBLReplicationOffline) {
        NSLog(@"Sync in offline");
        status = @"offline";
    } else if (repl.status == kCBLReplicationStopped) {
        NSLog(@"Sync in stopped");
        status = @"stopped";
    } else if (repl.status == kCBLReplicationIdle) {
        NSLog(@"Sync in idle");
        status = @"idle";
    }

    NSError *error = repl.lastError;
    if(error) {
        status = @"error";
        NSLog(@"replication error %@", error.code);
    }

    NSDictionary *dictionary = @{
                                 @"type": type,
                                 @"changesCount": @(repl.changesCount),
                                 @"completedChangesCount": @(repl.completedChangesCount),
                                 @"running": @(repl.running),
                                 @"status": status,
                                 @"suspended": @(repl.suspended),
                                 };

    [self sendEventWithName:@"replicationChanged" body:dictionary];

}];
</code>```

I only ever get one callback though, when it starts up.

Body:
I'm trying to implement an observer in the NSNotificationCenter.  Instead of using self as the observer I want to create a little object that does it:

typedef void (^ErrorCallback)(NSError*);
typedef void (^SuccessCallback)();
typedef void (^ReplicationChanged) (NSNotification*);

@interface SyncParams : NSObject

@property (copy) ErrorCallback errorCallback;
@property (copy) SuccessCallback successCallback;
@property (copy) ReplicationChanged replicationChanged;//this used to observe

- (void)replicationChanged:(NSNotification*)notification;

@end

@implementation SyncParams

@end

Then later I create an instance of the observer:

SyncParams* params = [SyncParams alloc];
params.replicationChanged = ^(NSNotification* notification) {
    //do stuff here
};

And finally add it to the NSNotificationCenter:

[[NSNotificationCenter defaultCenter] addObserver: params
                                         selector: @selector(replicationChanged:)
                                             name: kCBLReplicationChangeNotification
                                           object: replicationObject];

But I get this error: Exception '-[SyncParams replicationChanged:]: unrecognized selector sent to instance 0x7ff945c049a0' was thrown

I'm very new to objective-c!  Any pointers?

Body:
Yes and no, I ended up with the following:

[[NSNotificationCenter defaultCenter] addObserverForName:kCBLReplicationChangeNotification object:repl queue:nil usingBlock:^(NSNotification *notification) {

    NSString *status;
    if (repl.status == kCBLReplicationActive) {
        NSLog(@"Repication in progress");
        status = @"in-progrss";
    } else if (repl.status == kCBLReplicationOffline) {
        NSLog(@"Sync in offline");
        status = @"offline";
    } else if (repl.status == kCBLReplicationStopped) {
        NSLog(@"Sync in stopped");
        status = @"stopped";
    } else if (repl.status == kCBLReplicationIdle) {
        NSLog(@"Sync in idle");
        status = @"idle";
    }

    NSError *error = repl.lastError;
    if(error) {
        status = @"error";
        NSLog(@"replication error %@", error.code);
    }

    NSDictionary *dictionary = @{
                                 @"type": type,
                                 @"changesCount": @(repl.changesCount),
                                 @"completedChangesCount": @(repl.completedChangesCount),
                                 @"running": @(repl.running),
                                 @"status": status,
                                 @"suspended": @(repl.suspended),
                                 };

    [self sendEventWithName:@"replicationChanged" body:dictionary];

}];

I only ever get one callback though, when it starts up.


问:
Best way to represent sets of 3 values
Assume that I have 100 sets of 3 values. first value is time, second value is x position and 3rd value is y position. this is going to be the xy position of a point over 100 seconds for example.
I have a PHP background. in PHP I would do it with a 3D associative array like this :

```<code>position["time"]["x"]["y"]
</code>```

so I can access x,y values at a certain time. How would you do this in c#? I think generics like list and dictionary would do that. but I don't know how to implement key values for a 3D set of data.

答:
In C# there is types concept, you would need to create a concrete custom type either struct (value type )or class (reference type)

Value Types

Refrence Types

You can create a new type in this case i am creating class which would be like:

```<code>public class Position
{
   public DateTime Time {get;set;}
   public int X {get;set;}
   public int Y {get;set;}
}
</code>```

Now at some point you would have a instance of class position:

```<code>Position postion = new Position(); // object created
positon.Time = DateTime.Now;
position.X = 1;
position.Y =0;
</code>```

and the same way you would get the values back from it :

```<code>DateTime time = position.Time;
int positionX = position.X;
int positionY = position.Y;
</code>```

I would suggest to read basics of type from MSDN here

and for sets part, we have Framework provided collections in C# which includes Array,List which can be used to hold multiple objects of Position.

Hope It helps!

Title: Best way to represent sets of 3 values

Body:
Assume that I have 100 sets of 3 values. first value is time, second value is x position and 3rd value is y position. this is going to be the xy position of a point over 100 seconds for example.
I have a PHP background. in PHP I would do it with a 3D associative array like this :

position["time"]["x"]["y"]

so I can access x,y values at a certain time. How would you do this in c#? I think generics like list and dictionary would do that. but I don't know how to implement key values for a 3D set of data.

Body:
In C# there is types concept, you would need to create a concrete custom type either struct (value type )or class (reference type)

Value Types

Refrence Types

You can create a new type in this case i am creating class which would be like:

public class Position
{
   public DateTime Time {get;set;}
   public int X {get;set;}
   public int Y {get;set;}
}

Now at some point you would have a instance of class position:

Position postion = new Position(); // object created
positon.Time = DateTime.Now;
position.X = 1;
position.Y =0;

and the same way you would get the values back from it :

DateTime time = position.Time;
int positionX = position.X;
int positionY = position.Y;

I would suggest to read basics of type from MSDN here

and for sets part, we have Framework provided collections in C# which includes Array,List which can be used to hold multiple objects of Position.

Hope It helps!


问:
C# can't insert into Data Source
Here is my code:

```<code>try
{
    SqlCommand cmd2 = new SqlCommand(@"INSERT INTO Clienti (parola,nume,prenume,adresa,email,kcal_zilnice) VALUES (@Parola,@Nume,@Prenume,@Adresa,@Email,2000)", conn);
    cmd2.Prepare();
    cmd2.Parameters.AddWithValue("@Parola", passBox.Text);
    cmd2.Parameters.Add("@Nume", SqlDbType.VarChar, 50).Value = nameBox.Text;
    cmd2.Parameters.Add("@Prenume", SqlDbType.VarChar, 50).Value = pnameBox.Text;
    cmd2.Parameters.Add("@Adresa", SqlDbType.VarChar, 100).Value = adressBox.Text;
    cmd2.Parameters.Add("@Email", SqlDbType.VarChar, 100).Value = emailBox.Text;
    cmd2.ExecuteNonQuery();
}
catch (SqlException exception)
{
    MessageBox.Show("Failed! " + exception.Message);
}
MessageBox.Show("User Created!");
</code>```

I don't know what am I doing wrong here. I even tried to replace @Parola with 'abc' but it does not work. I don't get any error message. Every time I get "User Created", but when I look into the DB I get all the fields NULL(no records where created).

答:
So, for anyone that has the same problem Prepare() solved it.
Use Add() for params and specify The SqlDbType. Prepare() will not work with AddWithValue().
At the end do Prepare() and then ExecuteNonQuery().</p>

Title: C# can't insert into Data Source

Body:
Here is my code:

try
{
    SqlCommand cmd2 = new SqlCommand(@"INSERT INTO Clienti (parola,nume,prenume,adresa,email,kcal_zilnice) VALUES (@Parola,@Nume,@Prenume,@Adresa,@Email,2000)", conn);
    cmd2.Prepare();
    cmd2.Parameters.AddWithValue("@Parola", passBox.Text);
    cmd2.Parameters.Add("@Nume", SqlDbType.VarChar, 50).Value = nameBox.Text;
    cmd2.Parameters.Add("@Prenume", SqlDbType.VarChar, 50).Value = pnameBox.Text;
    cmd2.Parameters.Add("@Adresa", SqlDbType.VarChar, 100).Value = adressBox.Text;
    cmd2.Parameters.Add("@Email", SqlDbType.VarChar, 100).Value = emailBox.Text;
    cmd2.ExecuteNonQuery();
}
catch (SqlException exception)
{
    MessageBox.Show("Failed! " + exception.Message);
}
MessageBox.Show("User Created!");

I don't know what am I doing wrong here. I even tried to replace @Parola with 'abc' but it does not work. I don't get any error message. Every time I get "User Created", but when I look into the DB I get all the fields NULL(no records where created).


问:
Saving boolean in md-radio-button?
I want to save true on Yes answer and false on No:

```<code>            <div layout-gt-sm="row">
                Insured?

                <md-radio-group ng-model="vehicle.insured">

                    <md-radio-button value="true" class="md-primary">Yes</md-radio-button>
                    <md-radio-button value="false"> No </md-radio-button>

                </md-radio-group>

            </div>
</code>```

it saves the value in the database, but it doesn't bind the existing value, so there is no selected answer when the user retrieve a record

答:
Guess you mean to initialize the md-radio-group, try replace value to ng-value.

var app = angular.module('angularMaterialApp', ['ngMaterial']);
app.controller('mainCtrl', ['$scope',
  function($scope) {
    $scope.vehicle = {
      Insured: true
    };

  }
]);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html lang="en" ng-app="angularMaterialApp">

<head>
  <link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/angular_material/0.8.3/angular-material.min.css">
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular-animate.min.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular-aria.min.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/angular_material/0.8.3/angular-material.min.js"></script>
  <script src='app.js'></script>
</head>

<body ng-controller="mainCtrl">

  <p>Selected Value: <span class="radioValue">{{ vehicle.Insured }}</span>
  </p>
  <md-radio-group ng-model="vehicle.Insured">
    <md-radio-button ng-value="true">Yes</md-radio-button>
    <md-radio-button ng-value="false">No</md-radio-button>
  </md-radio-group>
  <hr />

</body>

</html></code>```

Title: Saving boolean in md-radio-button?

Body:
I want to save true on Yes answer and false on No:

                Insured?

                <md-radio-group ng-model="vehicle.insured">

                    <md-radio-button value="true" class="md-primary">Yes</md-radio-button>
                    <md-radio-button value="false"> No </md-radio-button>

                </md-radio-group>

it saves the value in the database, but it doesn't bind the existing value, so there is no selected answer when the user retrieve a record

Body:
Guess you mean to initialize the md-radio-group, try replace value to ng-value.

var app = angular.module('angularMaterialApp', ['ngMaterial']);
app.controller('mainCtrl', ['$scope',
  function($scope) {
    $scope.vehicle = {
      Insured: true
    };

  }
]);

<html lang="en" ng-app="angularMaterialApp">

<head>
  <link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/angular_material/0.8.3/angular-material.min.css">
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular-animate.min.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular-aria.min.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/angular_material/0.8.3/angular-material.min.js"></script>
  <script src='app.js'></script>
</head>

<body ng-controller="mainCtrl">

  <p>Selected Value: <span class="radioValue">{{ vehicle.Insured }}</span>
  </p>
  <md-radio-group ng-model="vehicle.Insured">
    <md-radio-button ng-value="true">Yes</md-radio-button>
    <md-radio-button ng-value="false">No</md-radio-button>
  </md-radio-group>
  <hr />

</body>

</html>


问:
Classic asp or phonegap
I have a question that keeps me in confusion.. I have knowledge in classic asp and phonegap development. I am now confused to choose the right one for my career. People say classic asp is outdated. But I get opportunities in classic asp even now. But if I choose phonegap , will I have a good opportunity in future.? It is a strange questions  but kindly suggest me friends ..</p>

答:
Phonegap and Cordova developing is based on front-end coding , the asp classic and php and ... is not supported .
If you have skilled in front-end development like HTML CSS JS JQUERY , it is fine to use cordova and phonegap for app development.</p>

Title: Classic asp or phonegap


问:
Oracle PL/SQL : to_date() format not considered
When I execute this in PL/SQL Developer :

```<code>SELECT to_date('29/03/17 14:05','DD/MM/RR HH24:MI')  FROM dual;
</code>```

Here's what I get :

```<code>3/29/2017 2:05:00 PM
</code>```

How is this possible ? I use HH24 but it seems like it's HH that's being used instead. The day and month are also not in the format I entered.

答:
What you are doing with the to_date method is parsing the string into a date object. If you then want to output the date object as string with a different format you should use the to_char method.

Example:

```<code>SELECT to_char(
    to_date('29/03/17 14:05','DD/MM/RR HH24:MI'),
    'DD/MM/RR HH24:MI'
) FROM dual;
</code>```

Body:
When I execute this in PL/SQL Developer :

SELECT to_date('29/03/17 14:05','DD/MM/RR HH24:MI')  FROM dual;

Here's what I get :

3/29/2017 2:05:00 PM

How is this possible ? I use HH24 but it seems like it's HH that's being used instead. The day and month are also not in the format I entered.

Body:
What you are doing with the to_date method is parsing the string into a date object. If you then want to output the date object as string with a different format you should use the to_char method.

Example:

SELECT to_char(
    to_date('29/03/17 14:05','DD/MM/RR HH24:MI'),
    'DD/MM/RR HH24:MI'
) FROM dual;


问:
Can't find named elements
Something is not clicking for me with this code:

```<code>var cfgDoc = XElement.Load(_cfgFile);
foreach (var x in cfgDoc.Elements("property"))
{
    Console.WriteLine(x);
}
</code>```

I am expecting to be able to output only nodes that are named property, but getting zilch. If I leave the XName parameter out, I get the document (below), which shows at least it is being loaded correctly.

What am I missing?

<session-factory xmlns="urn:nhibernate-configuration-2.2">
    <property name="connection.release_mode">on_close</property>
    <property name="show_sql">true</property>
</session-factory>
```

<p><strong>2nd try</strong></p>

```var cfgDoc = XElement.Load(_cfgFile);
XNamespace ns = "urn:nhibernate-configuration-2.2";
var properties = cfgDoc.Elements(ns + "property");
Assert.That(properties.Count() > 0);
foreach (var x in cfgDoc.Elements(ns + "property"))
{
    Console.WriteLine(x);
}
```

答:
One (or both) of these might do it:

```<code>cfgDoc.Descendants(ns + "property")
</code>```

and

```<code>var cfgDoc = XDocument.Load(_cfgFile).Root;
</code>```

(Jon's right too, you'll definitely need the namespace)

Title: Can't find named elements

Body:
Something is not clicking for me with this code:

var cfgDoc = XElement.Load(_cfgFile);
foreach (var x in cfgDoc.Elements("property"))
{
    Console.WriteLine(x);
}

I am expecting to be able to output only nodes that are named property, but getting zilch. If I leave the XName parameter out, I get the document (below), which shows at least it is being loaded correctly.

What am I missing?

<session-factory xmlns="urn:nhibernate-configuration-2.2">
    <property name="connection.release_mode">on_close</property>
    <property name="show_sql">true</property>
</session-factory>

2nd try

var cfgDoc = XElement.Load(_cfgFile);
XNamespace ns = "urn:nhibernate-configuration-2.2";
var properties = cfgDoc.Elements(ns + "property");
Assert.That(properties.Count() > 0);
foreach (var x in cfgDoc.Elements(ns + "property"))
{
    Console.WriteLine(x);
}

Body:
One (or both) of these might do it:

cfgDoc.Descendants(ns + "property")

and

var cfgDoc = XDocument.Load(_cfgFile).Root;

(Jon's right too, you'll definitely need the namespace)


答:
A simple solution might be to use a Tuple, if this is suitable for your needs, e.g.

```<code>Example:

var tuple = Tuple.Create(someBytes, moreBytes, myString);
</code>```

You can access the values using tuple.Item1, tuple.Item2, and tuple.Item3.

You can of course also use multiple Tuples if you require this, e.g.

Example

```<code>var list = new List<Tuple<byte, byte, string>> {
    tuple,
    anotherTuple,
    thirdTuple,
    etc
};
</code>```

As others have mentioned though, if you're referencing "like" data, you should create a class instead.

Title: Best way to represent sets of 3 values

Body:
A simple solution might be to use a Tuple, if this is suitable for your needs, e.g.

Example:

var tuple = Tuple.Create(someBytes, moreBytes, myString);

You can access the values using tuple.Item1, tuple.Item2, and tuple.Item3.

You can of course also use multiple Tuples if you require this, e.g.

Example

var list = new List<Tuple<byte, byte, string>> {
    tuple,
    anotherTuple,
    thirdTuple,
    etc
};

As others have mentioned though, if you're referencing "like" data, you should create a class instead.


问:
How to add an exception test for the below Http call that returns a json
```<code>[HttpPost]
[Route("TnC")]
public IHttpActionResult TnC(CustomViewModel myViewModel)
{
    try
    {
        return Json(_Internal.TnC(myViewModel, LoggedInUser));
    }
    catch (BusinessException exception)
    {
        return Json(BuildErrorModelBase(exception));
    }
}
</code>```

Where the _Internal is a Service with a guaranteed 99.99% up-time and not formalized fault contract interfaces defined.

Exceptions which are handled in my application level(business layer level) as a BusinessException - root class

Where BusinessException is defined as follows

```<code>public class BusinessException : Exception
{
    BusinessException()...
    BusinessExceptionFoo()...
    BusinessExceptionBar()...
    //...
}
</code>```

And the current test Method is

To do : Add Exception test

```<code>[TestMethod]
[ExpectedException(typeof(BusinessException),
        "Not a valid Business Case")]
public void TnCTest()
{
    var bookingService = myContainer.Resolve<mySvc>();

    var controller = new LinkBookingController(mySvc, myContainer);
    var expectedResult = controller.TnC(new myViewModel
    {
        ...params
    });

    var actualResult = GetData<Result<myViewModel>>(expectedResult);

    Assert.AreEqual(expectedResult, actualResult);
}
</code>```

expectedResult==actualResult does not test the exception block of the code.
How do I construct a request that makes the service throw the exception other than manually removing the ethernet cable to get this specific type of server error.

The best I could come up with was

```<code>#if DEBUG && UnitTestExceptions
        throw new BusinessException();
#endif
</code>```

But there is gotta be a better option.

答:
As Nkosi mentioned in his comment, what you need to do is add an interface to whatever type _Internal is so that your controller now depends on an interface as a contract, rather than the specific implementation.

Next, create a second constructor for your controller that accepts a IInternalService (whatever its called) and assigns that to _Internal. Your parameterless constructor can still assign whatever instance you're using now.

Now that you have this configuration (often called "poor mans dependency injection"), your unit test can create an instance of your controller passing in a different implementation of your service that throws an exception. You can do this by creating a new class, or you can do it dynamically using a library like Moq.

Hope that makes sense.

Body:
[HttpPost]
[Route("TnC")]
public IHttpActionResult TnC(CustomViewModel myViewModel)
{
    try
    {
        return Json(_Internal.TnC(myViewModel, LoggedInUser));
    }
    catch (BusinessException exception)
    {
        return Json(BuildErrorModelBase(exception));
    }
}

Where the _Internal is a Service with a guaranteed 99.99% up-time and not formalized fault contract interfaces defined.

Exceptions which are handled in my application level(business layer level) as a BusinessException - root class

Where BusinessException is defined as follows

public class BusinessException : Exception
{
    BusinessException()...
    BusinessExceptionFoo()...
    BusinessExceptionBar()...
    //...
}

And the current test Method is

To do : Add Exception test

[TestMethod]
[ExpectedException(typeof(BusinessException),
        "Not a valid Business Case")]
public void TnCTest()
{
    var bookingService = myContainer.Resolve<mySvc>();

    var controller = new LinkBookingController(mySvc, myContainer);
    var expectedResult = controller.TnC(new myViewModel
    {
        ...params
    });

    var actualResult = GetData<Result<myViewModel>>(expectedResult);

    Assert.AreEqual(expectedResult, actualResult);
}

expectedResult==actualResult does not test the exception block of the code.
How do I construct a request that makes the service throw the exception other than manually removing the ethernet cable to get this specific type of server error.

The best I could come up with was

#if DEBUG && UnitTestExceptions
        throw new BusinessException();
#endif

But there is gotta be a better option.


问:
Read and Split(Parse) data in java
I am trying to split some simple data from a .txt file. I have found some useful structures on the internet but it was not enough to split the data the way I wanted. I get a string like this:

```<code>{X:0.8940594 Y:0.6853521 Z:1.470214}
</code>```

And I want to transform it to like this;

```<code>0.8940594
0.6853521
1.470214
</code>```

And then put them in a matrix in order X=[], Y=[], Z=[]; (the data is the coordinate of an object)

Here is my code:

```<code>BufferedReader in = null; {
        try {
            in = new BufferedReader(new FileReader("file.txt"));
            String read = null;
            while ((read = in.readLine()) != null) {
                String[] splited = read.split("\\s+");
                for (String part : splited) {
                    System.out.println(part);
                }
            }
        } catch (IOException e) {
            System.out.println("There was a problem: " + e);
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (Exception e) {
            }
        }
    }
</code>```

What do I need to add to my code to get the data the way I want?

Right now with this code I receive data like this:

```<code>{X:0.8940594
Y:0.6853521
Z:1.470214}
</code>```

答:
How about this?</p>

```<code>public class Test {
    public static void main(String[] args) {
        String s = "{X:0.8940594 Y:0.6853521 Z:1.470214}";
        String x = s.substring(s.indexOf("X:")+2, s.indexOf("Y:")-1);
        String y = s.substring(s.indexOf("Y:")+2, s.indexOf("Z:")-1);
        String z = s.substring(s.indexOf("Z:")+2, s.lastIndexOf("}"));
        System.out.println(x);
        System.out.println(y);
        System.out.println(z);
    }
}
</code>```

Title: Read and Split(Parse) data in java

Body:
I am trying to split some simple data from a .txt file. I have found some useful structures on the internet but it was not enough to split the data the way I wanted. I get a string like this:

{X:0.8940594 Y:0.6853521 Z:1.470214}

And I want to transform it to like this;

0.8940594
0.6853521
1.470214

And then put them in a matrix in order X=[], Y=[], Z=[]; (the data is the coordinate of an object)

Here is my code:

BufferedReader in = null; {
        try {
            in = new BufferedReader(new FileReader("file.txt"));
            String read = null;
            while ((read = in.readLine()) != null) {
                String[] splited = read.split("\\s+");
                for (String part : splited) {
                    System.out.println(part);
                }
            }
        } catch (IOException e) {
            System.out.println("There was a problem: " + e);
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (Exception e) {
            }
        }
    }

What do I need to add to my code to get the data the way I want?

Right now with this code I receive data like this:

{X:0.8940594
Y:0.6853521
Z:1.470214}

Body:
How about this?

public class Test {
    public static void main(String[] args) {
        String s = "{X:0.8940594 Y:0.6853521 Z:1.470214}";
        String x = s.substring(s.indexOf("X:")+2, s.indexOf("Y:")-1);
        String y = s.substring(s.indexOf("Y:")+2, s.indexOf("Z:")-1);
        String z = s.substring(s.indexOf("Z:")+2, s.lastIndexOf("}"));
        System.out.println(x);
        System.out.println(y);
        System.out.println(z);
    }
}


答:
Your regex splits on whitespace, but does not remove the curly braces.

So instead of splitting on whitespace, you split on a class of characters: whitespace and curly braces.

The line with the regex then becomes:

```<code>String[] splited = read.split("[\\s+\\{\\}]");
</code>```

Here is an ideone link with the full snippet.

After this, you'll want to split the resulting three lines on the :, and parse the righthand side. You can use Double.parseDouble for this purpose.

Personally, I would try to avoid long regex expressions; they are hard to debug.

It may be best to remove the curly braces first, then split the result on whitespace and colons. This is more lines of code, but it's more robust and easier to debug.

Title: Read and Split(Parse) data in java

Body:
Your regex splits on whitespace, but does not remove the curly braces.

So instead of splitting on whitespace, you split on a class of characters: whitespace and curly braces.

The line with the regex then becomes:

String[] splited = read.split("[\\s+\\{\\}]");

Here is an ideone link with the full snippet.

After this, you'll want to split the resulting three lines on the :, and parse the righthand side. You can use Double.parseDouble for this purpose.

Personally, I would try to avoid long regex expressions; they are hard to debug.

It may be best to remove the curly braces first, then split the result on whitespace and colons. This is more lines of code, but it's more robust and easier to debug.


问:
Is there an easier way to get what im trying to achieve here?
I made an app which displays some information about some products, I achieved this by putting the brands in an arraylist on my main activity, and then after the user selects a brand he can choose a specific model, I did this by making a global xml file, and a class for each model with Strings and ints as the details, now the thing is, there are potentially hundreds and even over thousand models, is there an easier way to achieve this? like putting ALL of the data in one class and just pull it from it? or would it make things messier?

just to let you guys know that i'm a total beginner.

This is my code:

main activity shows a list of brands:

```<code>package com.example.ofir.myapplication;

import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.example.ofir.myapplication.lists.bmwList;
import com.example.ofir.myapplication.lists.ktmList;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

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

        final ArrayList<Brands> brands = new ArrayList<>();
        brands.add(new Brands("KTM", ContextCompat.getColor(this, R.color.colorOrange)));
        brands.add(new Brands("BMW", ContextCompat.getColor(this, R.color.colorPrimary)));
        brands.add(new Brands("Suzuki", ContextCompat.getColor(this, R.color.colorPrimary)));

        BrandAdapter itemsAdapter = new BrandAdapter(this, brands);

        ListView listView = (ListView) findViewById(R.id.brandlist);

        listView.setAdapter(itemsAdapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(position == 0) {

                    Intent intent = new Intent(MainActivity.this, ktmList.class);
                    startActivity(intent);
                }else if (position == 1) {

                    Intent intent2 = new Intent(MainActivity.this, bmwList.class);
                    startActivity(intent2);
                }
            }
        });

    }

}
</code>```

each brands opens up models list:

for testing purposes I just set 2 brands with lists.

```<code>package com.example.ofir.myapplication.lists;

import com.example.ofir.myapplication.R;
import com.example.ofir.myapplication.models.dukeSmall;
import com.example.ofir.myapplication.models.smc;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;

import static android.media.CamcorderProfile.get;

public class ktmList extends AppCompatActivity {

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

       final ArrayList<String> ktmlist = new ArrayList<String>();
        ktmlist.add("Duke 125");
        ktmlist.add("Duke 200");
        ktmlist.add("Duke 390");
        ktmlist.add("Duke 690");
        ktmlist.add("RC 125");
        ktmlist.add("RC 200");
        ktmlist.add("RC 390");
        ktmlist.add("RC8");
        ktmlist.add("SMC-R 690");
        ktmlist.add("SMR 990");
        ktmlist.add("SuperDuke 990");
        ktmlist.add("SuperDuke 1290");

       final ArrayAdapter<String> itemsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, ktmlist);

        ListView listView = (ListView) findViewById(R.id.models_list);

        listView.setAdapter(itemsAdapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if(position == 0) {
                    Intent intent = new Intent(ktmList.this, dukeSmall.class);
                    startActivity(intent);
                }else if (position == 8){
                    Intent intent = new Intent(ktmList.this, smc.class);
                    startActivity(intent);
                }

            }
        });

            }
        }
</code>```

and then I have a model class for each model with its specification, an example for a model is:

```<code>package com.example.ofir.myapplication.models;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;

import android.widget.TextView;

import com.example.ofir.myapplication.R;

/**
 * Created by Ofir on 23-Mar-17.
 */

public class smc extends AppCompatActivity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.info_page);

        int cc = 690;
        int weight = 150;
        int hp = 67;
        int topspeed = 180;

        ImageView logo = (ImageView) findViewById(R.id.logo_image);
        logo.setImageResource(R.drawable.smc);

        TextView Displacement = (TextView) findViewById(R.id.displacement_text);
        Displacement.setText(cc + "cc");

        TextView  HP = (TextView) findViewById(R.id.hp_text);
        HP.setText(""+hp);

        TextView Weight = (TextView) findViewById(R.id.weight_text);
        Weight.setText(""+weight);

        TextView topSpeed = (TextView) findViewById(R.id.top_speed_text);
        topSpeed.setText(topspeed + " km/h");

    }

}
</code>```

now my questions is, is there an easier way to achieve that? instead of setting a class for each and each model and settings tons of intents?

答:
So for all items, you got common elements (Displacement, weight, topSpeed, etc.). You can make use of the Bundle class.

It's really easy.

Make a instance of a bundle

Bundle bundle = new Bundle();

Then on the bundle, just put whatever items that you like. For example if you want to put a arraylist,

bundle.putIntArray(arrayKey, int[]);

Note: key is there so that the next activity can recognize which item you want in the bundle.

Naturally, put the bundle on your intent.

intent.putExtra(bundleKey, bundle);

In your next activity, get intent, then your bundle.

Bundle bundle = getIntent().getExtras().getBundle(bundleKey);

Extract your arraylist from the bundle.

int yourArrayList[] = bundle.getIntArray(arrayKey);

And you're all done!

Body:
I made an app which displays some information about some products, I achieved this by putting the brands in an arraylist on my main activity, and then after the user selects a brand he can choose a specific model, I did this by making a global xml file, and a class for each model with Strings and ints as the details, now the thing is, there are potentially hundreds and even over thousand models, is there an easier way to achieve this? like putting ALL of the data in one class and just pull it from it? or would it make things messier?

just to let you guys know that i'm a total beginner.

This is my code:

main activity shows a list of brands:

package com.example.ofir.myapplication;

import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.example.ofir.myapplication.lists.bmwList;
import com.example.ofir.myapplication.lists.ktmList;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

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

        final ArrayList<Brands> brands = new ArrayList<>();
        brands.add(new Brands("KTM", ContextCompat.getColor(this, R.color.colorOrange)));
        brands.add(new Brands("BMW", ContextCompat.getColor(this, R.color.colorPrimary)));
        brands.add(new Brands("Suzuki", ContextCompat.getColor(this, R.color.colorPrimary)));

        BrandAdapter itemsAdapter = new BrandAdapter(this, brands);

        ListView listView = (ListView) findViewById(R.id.brandlist);

        listView.setAdapter(itemsAdapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(position == 0) {

                    Intent intent = new Intent(MainActivity.this, ktmList.class);
                    startActivity(intent);
                }else if (position == 1) {

                    Intent intent2 = new Intent(MainActivity.this, bmwList.class);
                    startActivity(intent2);
                }
            }
        });

    }

}

each brands opens up models list:

for testing purposes I just set 2 brands with lists.

package com.example.ofir.myapplication.lists;

import com.example.ofir.myapplication.R;
import com.example.ofir.myapplication.models.dukeSmall;
import com.example.ofir.myapplication.models.smc;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;

import static android.media.CamcorderProfile.get;

public class ktmList extends AppCompatActivity {

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

       final ArrayList<String> ktmlist = new ArrayList<String>();
        ktmlist.add("Duke 125");
        ktmlist.add("Duke 200");
        ktmlist.add("Duke 390");
        ktmlist.add("Duke 690");
        ktmlist.add("RC 125");
        ktmlist.add("RC 200");
        ktmlist.add("RC 390");
        ktmlist.add("RC8");
        ktmlist.add("SMC-R 690");
        ktmlist.add("SMR 990");
        ktmlist.add("SuperDuke 990");
        ktmlist.add("SuperDuke 1290");

       final ArrayAdapter<String> itemsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, ktmlist);

        ListView listView = (ListView) findViewById(R.id.models_list);

        listView.setAdapter(itemsAdapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if(position == 0) {
                    Intent intent = new Intent(ktmList.this, dukeSmall.class);
                    startActivity(intent);
                }else if (position == 8){
                    Intent intent = new Intent(ktmList.this, smc.class);
                    startActivity(intent);
                }

            }
        });

            }
        }

and then I have a model class for each model with its specification, an example for a model is:

package com.example.ofir.myapplication.models;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;

import android.widget.TextView;

import com.example.ofir.myapplication.R;

/**
 * Created by Ofir on 23-Mar-17.
 */

public class smc extends AppCompatActivity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.info_page);

        int cc = 690;
        int weight = 150;
        int hp = 67;
        int topspeed = 180;

        ImageView logo = (ImageView) findViewById(R.id.logo_image);
        logo.setImageResource(R.drawable.smc);

        TextView Displacement = (TextView) findViewById(R.id.displacement_text);
        Displacement.setText(cc + "cc");

        TextView  HP = (TextView) findViewById(R.id.hp_text);
        HP.setText(""+hp);

        TextView Weight = (TextView) findViewById(R.id.weight_text);
        Weight.setText(""+weight);

        TextView topSpeed = (TextView) findViewById(R.id.top_speed_text);
        topSpeed.setText(topspeed + " km/h");

    }

}

now my questions is, is there an easier way to achieve that? instead of setting a class for each and each model and settings tons of intents?


问:
How I can increment counter in firebase database forever through android application when the user clicks on the button
Here is my code.

```<code>package com.example.manali.likeex;

import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

public class MainActivity2 extends Activity implements View.OnClickListener {
    Button senlike;
    private DatabaseReference mdatabase;
    private DatabaseReference user1;

     int c;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        Button sendlike = (Button) findViewById(R.id.b1);
        mdatabase= FirebaseDatabase.getInstance().getReference();
        user1=mdatabase.child("Teacher");
        sendlike.setOnClickListener(this);

    }
</code>```

//when user clicks on button counter on firebase get increased
        public void onClick(View view)
        {

```<code>        if(user1!=null)
        {
            c++;

        }

//sets value to user1 node
        user1.setValue(c);

    }
    public DatabaseReference getUser1()
    {
        return user1;

    }
}
</code>```

This code only increases counter when app is active. When we close the app, and restart it again. The counter starts again with 1. Hence I want to maintain this counter.

答:
You could have a count column under your Teacher table:

```<code>App
---Teacher
------Count
</code>```

Then with that you could query the count and put it in a variable so you could increment the value then update the value in firebase:

```<code>public void onClick(View view) {
    DatabaseReference ref = mdatabase.child("Teacher");
    ref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            int count = (int) dataSnapshot.child("count").getValue();
            ref.child("count").setValue(count++);
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) { }
    });
}
</code>```

Body:
Here is my code.

package com.example.manali.likeex;

import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

public class MainActivity2 extends Activity implements View.OnClickListener {
    Button senlike;
    private DatabaseReference mdatabase;
    private DatabaseReference user1;

     int c;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        Button sendlike = (Button) findViewById(R.id.b1);
        mdatabase= FirebaseDatabase.getInstance().getReference();
        user1=mdatabase.child("Teacher");
        sendlike.setOnClickListener(this);

    }

//when user clicks on button counter on firebase get increased
        public void onClick(View view)
        {

        if(user1!=null)
        {
            c++;

        }

//sets value to user1 node
        user1.setValue(c);

    }
    public DatabaseReference getUser1()
    {
        return user1;

    }
}

This code only increases counter when app is active. When we close the app, and restart it again. The counter starts again with 1. Hence I want to maintain this counter.

Body:
You could have a count column under your Teacher table:

App
---Teacher
------Count

Then with that you could query the count and put it in a variable so you could increment the value then update the value in firebase:

public void onClick(View view) {
    DatabaseReference ref = mdatabase.child("Teacher");
    ref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            int count = (int) dataSnapshot.child("count").getValue();
            ref.child("count").setValue(count++);
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) { }
    });
}


问:
how to auto resize/scale amazon aws ec2 instance
currently am on the t2.micro & i read that amazon allow an auto scaling option to allow the server to expand/shrink according to the traffic which is perfect.

so my question is:

what exactly should i do in-order to enable the auto scaling/resizing
  of the server when needed or when the traffic start to spike ?

is there an option to allow changing the instance type automatically ?

auto scaling i believe means adding more instances and balance the load in between them, so does this mean i need to have a background about load balancing and all that jargon that comes with it or does amazon take care of that automatically ?

am totaly new to the whole server maintenance/provisioning land, so please try to explain as simple as possible. also the only reason i went with amazon because of the automation capabilities it offer but sadly their docs are very complex and many things could go wrong.

答:
If you want to scale your instance and you don't mind about uptime, I can suggest this workaround.

TL;DR: set an alert on AWS CloudWatch to "ping" SNS when a specific alert is triggered (i.e. CPU, RAM > %) and setup a Skeddly action to automatic scale your instance when a SNS endpoint is pinged.

Details:

subscribe to Skeddly, a service to automate actions on AWS.
It's free if you don't use it a lot;

setup a "Change EC2 Instances" action and activate the SNS feature,
then copy the SNS endpoint link; screenshot

be sure to clearly define the instance(s) affected by the action!

go on AWS Simple Notification Service dashboard and create a new
"topic", then select it and choose "subscribe to topic" from the
Actions menu;

you can paste here the SNS endpoint provided by Skeddly, then wait
until the subscription is confirmed (it takes a while);

now move to AWS CloudWatch and setup an alert for any metric that
you find meaningful for your instance up/downscaling, i.e. CPU >= 90%
for 1 day;

for each alarm add a notification selecting the "topic" previously
defined on SNS.

You are done!

ContentLicense: CC BY-SA 4.0


问:
XAML Path - Draw a Circle without using Arcs
In a WPF application, I understand I can draw a Circle using the following Path Syntax:

```<code><Path
    Stretch="Fill"
    StrokeThickness="1"
    Data="M -1,0 A 1,1 0 1 1 1,0 M -1,0 A 1,1 0 1 0 1,0" />
</code>```

However, I am working in a compiler that does not yet support Arcs (C# & XAML for HTML5).

How would I draw this circle without using Arcs?
Is the solution to draw a point-by-point item - essentially a Hexagon, give or take?

答:
Better than drawing an Ellipse element would be to use a EllipseGeometry.

Instead of being top/left aligned, your drawing is centered at specific coordinates. In addition, the StrokeThickness contributes to the total width and height of an Ellipse, while a Geometry exactly defines the rendered shape.

```<code><Path Stretch="Fill" StrokeThickness="1">
    <Path.Data>
        <EllipseGeometry Center="0,0" RadiusX="1" RadiusY="1"/>
    </Path.Data>
</Path>
</code>```

Body:
In a WPF application, I understand I can draw a Circle using the following Path Syntax:

<Path
    Stretch="Fill"
    StrokeThickness="1"
    Data="M -1,0 A 1,1 0 1 1 1,0 M -1,0 A 1,1 0 1 0 1,0" />

However, I am working in a compiler that does not yet support Arcs (C# & XAML for HTML5).

How would I draw this circle without using Arcs?
Is the solution to draw a point-by-point item - essentially a Hexagon, give or take?

Body:
Better than drawing an Ellipse element would be to use a EllipseGeometry.

Instead of being top/left aligned, your drawing is centered at specific coordinates. In addition, the StrokeThickness contributes to the total width and height of an Ellipse, while a Geometry exactly defines the rendered shape.

<Path Stretch="Fill" StrokeThickness="1">
    <Path.Data>
        <EllipseGeometry Center="0,0" RadiusX="1" RadiusY="1"/>
    </Path.Data>
</Path>


问:
PHP/Javascript: Javascript not sending data to PHP
I'm making a search system whereby the user enters data into a text area and when he presses 'enter', the search text is sent to the php search query via javascript so that the page doesn't have to reload.

Javascript:

```<code><script type="text/javascript">
function search(str)
{
if (str=="")
  {
  document.getElementById("search").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {//IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {//IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("search").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","leaderboard.php?q="+str,true);
xmlhttp.send();
}
</script>
</code>```

Text input:

```<code><form>
<input type="text" value="search for user" onfocus="if
(this.value==this.defaultValue) this.value='';" onblur="if (this.value!==this.defaultValue) this.value='search for user';" id="search" name="search" style="background-color: white; color: black; border: 1px solid black; font-family: verdana; font-size: 9px; height: 20px; text-align: center;" onchange="search(this.value)">
</form>
</code>```

PHP:

```<code><?php
$con = mysql_connect('localhost', 'refrigerator', 'XXX');
mysql_select_db('refrigerator');
if($q=$_GET["q"]){
$sql="SELECT * FROM users WHERE username = '".$q."'";
$result = mysql_query($sql);
$User = array(); $Count = array(); $t=0; $i=0;
 while($row = mysql_fetch_array($result)){
  $User[] = $row['username']; $Count[] = $row['count'];
  $t=mysql_num_rows($sql);
 }

  echo '<tr><td>' .$a. '</td><td>'.$row['username'].'</td><td>'.$row['count'].'</td></tr>';

mysql_close($con);
}

if ($q=!$_GET["q"]){

  $User = array(); $Count = array(); $t=0; $i=0;
 while($row = mysql_fetch_array($result)){
  $User[] = $row['username']; $Count[] = $row['count'];
  $t=13;
 }
   $User[] = $row['username']; $Count[] = $row['count'];
 while($i<$t) {
  $a = $i + 1;
  echo '<tr><td>' .$a. '</td><td>'.$User[$i].'</td><td>'.$Count[$i].'</td></tr>';
  $i++;
 }
 }
?>
</code>```

The javascript definitely works up to the penultimate line, because the url changes to 'http://localhost/%5bclickphilia%5d/leaderboard.php?search=whatever was searched' but then nothing happens.

I'm very new to this so I might have made a blindingly obvious mistake so don't rule out that possibility :D

Thanks

EDIT:

Here is the full code for the table including the php:

```<code><table border="0" cellspacing="15" padding="0" width="200">

<th><font color="#00FF00">Rank</font></th>
<th><font color="#00FF00">Username</font></th>
<th><font color="#00FF00">Score</font></th>
<?php
$con = mysql_connect('localhost', 'refrigerator', 'XXXX');
mysql_select_db('refrigerator');
if($q=$_GET["q"]){
$sql="SELECT * FROM users WHERE username = '".$q."'";
$result = mysql_query($sql);
$result=mysql_real_escape_string($result);
$User = array(); $Count = array(); $t=0; $i=0;
while($row = mysql_fetch_array($result)){
}

    echo '<tr><td>' .$a. '</td><td>'.$row['username'].'</td><td>'.$row['count'].'</td></tr>';

mysql_close($con);
}

if ($q=!$_GET["q"]){

    $User = array(); $Count = array(); $t=0; $i=0;
while($row = mysql_fetch_array($result)){
    $User[] = $row['username']; $Count[] = $row['count'];
    $t=13;
}
    $User[] = $row['username']; $Count[] = $row['count'];
while($i<$t) {
    $a = $i + 1;
    echo '<tr><td>' .$a. '</td><td>'.$User[$i].'</td><td>'.$Count[$i].'</td></tr>';
    $i++;
}
}
?>
</table>
</code>```

I'm sure the inserting the php echo into the table works, because the event for if ($q=!$_GET["q"]) works fine. The data is entered into the table okay.

答:
Well this line here:

```<code>document.getElementById("search").innerHTML=xmlhttp.responseText;
</code>```

doesn't make sense to me.  The "search" element is that <input> field.  Setting that element's "innerHTML" property may do nothing at all to the page, because "text" input elements are "void" elements and have no content.

Maybe you've got a "search_results" table somewhere? If so, you may have some trouble updating the "middle" of a
 like that, in IE at least. Try it however and you should be able to mess with that to come up with something.

edit — I'll re-state what I think the problem is: your PHP code seems to be putting together the response to the search in some sort of table form; it's creating
 and  elements. Those need to go into a
 somewhere (actually technically a
 but whatever).  Exactly how, or even if, you want to refine that, I can't say. What you might try however is to add this to your page:

```<code><div id='search_results'>Results Go Here</div>
</code>```

and put it just somewhere where it'll show up. Then change your "search()" function so that wherever you're setting "innerHTML", change the "id" you search for to "search_results".

Body:
I'm making a search system whereby the user enters data into a text area and when he presses 'enter', the search text is sent to the php search query via javascript so that the page doesn't have to reload.

Javascript:

Text input:

<form>
<input type="text" value="search for user" onfocus="if
(this.value==this.defaultValue) this.value='';" onblur="if (this.value!==this.defaultValue) this.value='search for user';" id="search" name="search" style="background-color: white; color: black; border: 1px solid black; font-family: verdana; font-size: 9px; height: 20px; text-align: center;" onchange="search(this.value)">
</form>

PHP:

<?php
$con = mysql_connect('localhost', 'refrigerator', 'XXX');
mysql_select_db('refrigerator');
if($q=$_GET["q"]){
$sql="SELECT * FROM users WHERE username = '".$q."'";
$result = mysql_query($sql);
$User = array(); $Count = array(); $t=0; $i=0;
 while($row = mysql_fetch_array($result)){
  $User[] = $row['username']; $Count[] = $row['count'];
  $t=mysql_num_rows($sql);
 }

  echo '
' .$a. '	'.$row['username'].'	'.$row['count'].'
';

mysql_close($con);
}

if ($q=!$_GET["q"]){

  $User = array(); $Count = array(); $t=0; $i=0;
 while($row = mysql_fetch_array($result)){
  $User[] = $row['username']; $Count[] = $row['count'];
  $t=13;
 }
   $User[] = $row['username']; $Count[] = $row['count'];
 while($i<$t) {
  $a = $i + 1;
  echo '
' .$a. '	'.$User[$i].'	'.$Count[$i].'
';
  $i++;
 }
 }
?>

The javascript definitely works up to the penultimate line, because the url changes to 'http://localhost/%5bclickphilia%5d/leaderboard.php?search=whatever was searched' but then nothing happens.

I'm very new to this so I might have made a blindingly obvious mistake so don't rule out that possibility :D

Thanks

EDIT:

Here is the full code for the table including the php:

Rank
Username
Score
<?php
$con = mysql_connect('localhost', 'refrigerator', 'XXXX');
mysql_select_db('refrigerator');
if($q=$_GET["q"]){
$sql="SELECT * FROM users WHERE username = '".$q."'";
$result = mysql_query($sql);
$result=mysql_real_escape_string($result);
$User = array(); $Count = array(); $t=0; $i=0;
while($row = mysql_fetch_array($result)){
}

    echo '
' .$a. '	'.$row['username'].'	'.$row['count'].'
';

mysql_close($con);
}

if ($q=!$_GET["q"]){

    $User = array(); $Count = array(); $t=0; $i=0;
while($row = mysql_fetch_array($result)){
    $User[] = $row['username']; $Count[] = $row['count'];
    $t=13;
}
    $User[] = $row['username']; $Count[] = $row['count'];
while($i<$t) {
    $a = $i + 1;
    echo '
' .$a. '	'.$User[$i].'	'.$Count[$i].'
';
    $i++;
}
}
?>

I'm sure the inserting the php echo into the table works, because the event for if ($q=!$_GET["q"]) works fine. The data is entered into the table okay.

Body:
Well this line here:

document.getElementById("search").innerHTML=xmlhttp.responseText;

doesn't make sense to me.  The "search" element is that <input> field.  Setting that element's "innerHTML" property may do nothing at all to the page, because "text" input elements are "void" elements and have no content.

Maybe you've got a "search_results" table somewhere? If so, you may have some trouble updating the "middle" of a <table> like that, in IE at least. Try it however and you should be able to mess with that to come up with something.

edit — I'll re-state what I think the problem is: your PHP code seems to be putting together the response to the search in some sort of table form; it's creating <tr> and <td> elements. Those need to go into a <table> somewhere (actually technically a <tbody> but whatever).  Exactly how, or even if, you want to refine that, I can't say. What you might try however is to add this to your page:

<div id='search_results'>Results Go Here</div>

and put it just somewhere where it'll show up. Then change your "search()" function so that wherever you're setting "innerHTML", change the "id" you search for to "search_results".


问:
Rest Assured - deserialize Response JSON as List<POJO>
I have a POJO Artwork. I'm retrieving a List of those objects from a RESTful webservice in the HTTP response body in JSON format. I'm trying to write a Rest Assured-based test that would analyze the returned list. The code looks like this:

```<code>Response response = get("/artwork");
List returnedArtworks = response.getBody().as(List.class)
</code>```

The problem is, I can't get Rest Assured to parse the returned JSON as List<Artwork>. Instead, I get a List<LinkedHashMap>. The map has a proper structure, i.e. could be mapped by Jackson to Artwork object, but I'd like to avoid mapping it manually.

JSON mappings in my model are OK, because when I map single object like this:

```<code>Artwork returnedArtwork = response.getBody().as(Artwork.class);
</code>```

it works fine.

Is it possible to get returnedArtworks as List<Artwork>?

答:
this solution works for version 3.0.2 (io.restassured):

```<code>  JsonPath jsonPath = RestAssured.given()
     .when()
     .get("/order")
     .then()
     .assertThat()
     .statusCode(Response.Status.OK.getStatusCode())
     .assertThat()
     .extract().body().jsonPath();

  List<Order> orders = jsonPath.getList("", Order.class);
</code>```

This will extract the objects for a structure like this:

```<code>public class Order {

private String id;

public String getId(){
return id; }

public void setId(String id){
this.id = id;
}

}
</code>```

with the given json:

```<code>[
{ "id" : "5" },
{ "id" : "6" }
]
</code>```

Body:
I have a POJO Artwork. I'm retrieving a List of those objects from a RESTful webservice in the HTTP response body in JSON format. I'm trying to write a Rest Assured-based test that would analyze the returned list. The code looks like this:

Response response = get("/artwork");
List returnedArtworks = response.getBody().as(List.class)

The problem is, I can't get Rest Assured to parse the returned JSON as List<Artwork>. Instead, I get a List<LinkedHashMap>. The map has a proper structure, i.e. could be mapped by Jackson to Artwork object, but I'd like to avoid mapping it manually.

JSON mappings in my model are OK, because when I map single object like this:

Artwork returnedArtwork = response.getBody().as(Artwork.class);

it works fine.

Is it possible to get returnedArtworks as List<Artwork>?

Body:
this solution works for version 3.0.2 (io.restassured):

  JsonPath jsonPath = RestAssured.given()
     .when()
     .get("/order")
     .then()
     .assertThat()
     .statusCode(Response.Status.OK.getStatusCode())
     .assertThat()
     .extract().body().jsonPath();

  List<Order> orders = jsonPath.getList("", Order.class);

This will extract the objects for a structure like this:

public class Order {

private String id;

public String getId(){
return id; }

public void setId(String id){
this.id = id;
}

}

with the given json:

[
{ "id" : "5" },
{ "id" : "6" }
]


问:
React Native NativeModules.TextViewManager is null
I'm trying to extend the built in react native TextInput component with a method to return the text selection rectangles for a given range. I followed this pattern here but I'm stuck at this step

```<code>import React, { Component } from 'react';
import {AppRegistry, StyleSheet, Text, View, NativeModules } from 'react-native';
var TextViewManager = NativeModules.TextViewManager;
</code>```

TextViewManager is always null. Does anyone know why or how to get access to TextViewManager so I can call the method I've added to it?

I've tried accessing other managers (eg. WebViewManager) in the same way and it's worked a treat. It just seems like TextViewManager is a special case.

答: Ok I got itworking and it was because I didn't run react-native run-ios after changing my TextViewManager category source in Xcode. I mistakingly thought react-native log-ios built, installed and logged but it only logs.

Body:
I'm trying to extend the built in react native TextInput component with a method to return the text selection rectangles for a given range. I followed this pattern here but I'm stuck at this step

import React, { Component } from 'react';
import {AppRegistry, StyleSheet, Text, View, NativeModules } from 'react-native';
var TextViewManager = NativeModules.TextViewManager;

TextViewManager is always null. Does anyone know why or how to get access to TextViewManager so I can call the method I've added to it?

I've tried accessing other managers (eg. WebViewManager) in the same way and it's worked a treat. It just seems like TextViewManager is a special case.


问:
Rails 4: assets not loading in production
I'm trying to put my app into production and image and css asset paths aren't working.

Here's what I'm currently doing:

Image assets live in /app/assets/images/image.jpg

Stylesheets live in /app/assets/stylesheets/style.css

In my layout, I reference the css file like this: <%= stylesheet_link_tag    "styles", media: "all", "data-turbolinks-track" => true %>

Before restarting unicorn, I run RAILS_ENV=production bundle exec rake assets:precompile and it succeeds and I see the fingerprinted files in the public/assets directory.

When I browse to my site, I get a 404 not found error for mysite.com/stylesheets/styles.css.

What am I doing wrong?

Update:
In my layout, it looks like this:

```<code><%= stylesheet_link_tag    "bootstrap.min", media: "all", "data-turbolinks-track" => true %>
<%= stylesheet_link_tag    "styles", media: "all", "data-turbolinks-track" => true %>
<%= javascript_include_tag "application", "data-turbolinks-track" => true %>
</code>```

The generate source is this:

```<code><link data-turbolinks-track="true" href="/stylesheets/bootstrap.min.css" media="all" rel="stylesheet" />
<link data-turbolinks-track="true" href="/stylesheets/styles.css" media="all" rel="stylesheet" />
<script data-turbolinks-track="true" src="/assets/application-0c647c942c6eff10ad92f1f2b0c64efe.js"></script>
</code>```

Looks like Rails is not properly looking for the compiled css files. But it's very confusing why it's working correctly for javascripts (notice the /assets/****.js path).

答:
```<code>location ~ ^/assets/ {
  expires 1y;
  add_header Cache-Control public;
  add_header ETag "";
}
</code>```

This fixed the problem for me in production. Put it into the nginx config.

Body:
I'm trying to put my app into production and image and css asset paths aren't working.

Here's what I'm currently doing:

Image assets live in /app/assets/images/image.jpg

Stylesheets live in /app/assets/stylesheets/style.css

In my layout, I reference the css file like this: <%= stylesheet_link_tag    "styles", media: "all", "data-turbolinks-track" => true %>

Before restarting unicorn, I run RAILS_ENV=production bundle exec rake assets:precompile and it succeeds and I see the fingerprinted files in the public/assets directory.

When I browse to my site, I get a 404 not found error for mysite.com/stylesheets/styles.css.

What am I doing wrong?

Update:
In my layout, it looks like this:

<%= stylesheet_link_tag    "bootstrap.min", media: "all", "data-turbolinks-track" => true %>
<%= stylesheet_link_tag    "styles", media: "all", "data-turbolinks-track" => true %>
<%= javascript_include_tag "application", "data-turbolinks-track" => true %>

The generate source is this:

<link data-turbolinks-track="true" href="/stylesheets/bootstrap.min.css" media="all" rel="stylesheet" />
<link data-turbolinks-track="true" href="/stylesheets/styles.css" media="all" rel="stylesheet" />

Looks like Rails is not properly looking for the compiled css files. But it's very confusing why it's working correctly for javascripts (notice the /assets/****.js path).

Body:
location ~ ^/assets/ {
  expires 1y;
  add_header Cache-Control public;
  add_header ETag "";
}

This fixed the problem for me in production. Put it into the nginx config.