问:
Getting nil response while passing string to another view controller - Swift3
In FirstViewController i'm fetching the response from JSON and want to pass that fetched response to another view controller.Below is the code which i have used so far for parsing and passing the response.

FirstViewController

```<code>var fn:String!  //globally declared variable
</code>```

code i have tried for parsing in FirstViewController

```<code> do {

    let detailsDictionary:NSDictionary = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! Dictionary<String, AnyObject> as NSDictionary

    print(detailsDictionary)
    let details = detailsDictionary["Data"] as! [[String:AnyObject]]
    print(details)
    for dtl in details
    {
        self.fn = dtl["Father_Name"] as? String ?? "NA"
        print(self.fn)  //here i'm getting the exact value from JSON
     }

    }
}
</code>```

SecondViewController

In SecondViewController there is a Label called profile_name and want to set that parsed string(fn) as Label's text. for that i declared another variable as global.

```<code>var pname:String!
</code>```

below is the code i have used to fetch the value from FirstViewController.

```<code>viewDidLoad()
{
       let othervc = FirstViewController()
       self.pname = othervc.fn
       self.profile_name.text = self.pname
}
</code>```

Problem : I tried my best efforts to get the desired output but i'm getting nil response.

Please Help.

答:
In Second ViewController

```<code>let strName:String!
</code>```

In First ViewController

```<code>let strOne = "This is for testing"

let objstory = self.storyboard?.instantiateViewController(withIdentifier: "yout Secoond ViewController Storybord ID") as! YourSecondViewControllerName
objstory.strNam = strOne

self.navigationController?.pushViewController(objstory, animated: true)
</code>```

Body:
In FirstViewController i'm fetching the response from JSON and want to pass that fetched response to another view controller.Below is the code which i have used so far for parsing and passing the response.

FirstViewController

var fn:String!  //globally declared variable

code i have tried for parsing in FirstViewController

 do {

    let detailsDictionary:NSDictionary = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! Dictionary<String, AnyObject> as NSDictionary

    print(detailsDictionary)
    let details = detailsDictionary["Data"] as! [[String:AnyObject]]
    print(details)
    for dtl in details
    {
        self.fn = dtl["Father_Name"] as? String ?? "NA"
        print(self.fn)  //here i'm getting the exact value from JSON
     }

    }
}

SecondViewController

In SecondViewController there is a Label called profile_name and want to set that parsed string(fn) as Label's text. for that i declared another variable as global.

var pname:String!

below is the code i have used to fetch the value from FirstViewController.

viewDidLoad()
{
       let othervc = FirstViewController()
       self.pname = othervc.fn
       self.profile_name.text = self.pname
}

Problem : I tried my best efforts to get the desired output but i'm getting nil response.

Please Help.

Body:
In Second ViewController

let strName:String!

In First ViewController

let strOne = "This is for testing"

let objstory = self.storyboard?.instantiateViewController(withIdentifier: "yout Secoond ViewController Storybord ID") as! YourSecondViewControllerName
objstory.strNam = strOne

self.navigationController?.pushViewController(objstory, animated: true)


来源: stackexchange

问:
Robot Framework: How to redirect console output to file
I was wondering if it was possible to redirect Robot Framework's stdout from console to file? Currently, when I run pybot, the output is in the command prompt (for Windows), can I change it in such a way that it will go to a file instead? (Nothing displayed on the command prompt).</p>

答:
On a linux server you can just pipe the robot commandline to tee</p>

```<code>robot -d results <test name>.robot  | tee <test name>.out
</code>```

ContentLicense: CC BY-SA 3.0

Body:
On a linux server you can just pipe the robot commandline to tee

robot -d results <test name>.robot  | tee <test name>.out


问:
How to mouse hover using java through selenium-webdriver and Java
While trying to automate the portal http://demo.nopcommerce.com/, am not able to select mouse hover over "Electornics" menu and select "Camera & Photo" sub menu.
Used the below script for the same.</p>

```<code>WebElement electronic_Pdts = driver.findElement(By.xpath("//*[@class='title']//*[@title='Show products in category Electronics']"));
action.moveToElement(electronic_Pdts).build().perform();
driver.findElement(By.xpath("//*[@src='http://demo.nopcommerce.com/images/thumbs/0000006_camera-photo_450.jpeg']")).click();
</code>```

答:
To Mouse Hover over Electornics menu and select Camera & Photo you can use the following code block :

```<code>driver.get("http://demo.nopcommerce.com/");
Actions act = new Actions(driver);
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement electronics = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//li/a[@href='/electronics']")));
act.moveToElement(electronics).perform();
WebElement camera_n_photo = driver.findElement(By.xpath("//li/a[@href='/electronics']//following::ul/li/a"));
camera_n_photo.click();
System.out.println("Camera & photo Clicked.");
</code>```

ContentLicense: CC BY-SA 4.0

Body:
While trying to automate the portal http://demo.nopcommerce.com/, am not able to select mouse hover over "Electornics" menu and select "Camera & Photo" sub menu.
Used the below script for the same.

WebElement electronic_Pdts = driver.findElement(By.xpath("//*[@class='title']//*[@title='Show products in category Electronics']"));
action.moveToElement(electronic_Pdts).build().perform();
driver.findElement(By.xpath("//*[@src='http://demo.nopcommerce.com/images/thumbs/0000006_camera-photo_450.jpeg']")).click();

Body:
To Mouse Hover over Electornics menu and select Camera & Photo you can use the following code block :

driver.get("http://demo.nopcommerce.com/");
Actions act = new Actions(driver);
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement electronics = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//li/a[@href='/electronics']")));
act.moveToElement(electronics).perform();
WebElement camera_n_photo = driver.findElement(By.xpath("//li/a[@href='/electronics']//following::ul/li/a"));
camera_n_photo.click();
System.out.println("Camera & photo Clicked.");


问:
perl false values are not printed
when I print false values in perl I get nothing printed. Probably this is a very simple question, but I searched google without finding an answer.

Code:

```<code>print "2 == 2 :", 2 == 2, "\n";
print "2 != 2 :", 2 != 2, "\n";
print "2 == 3 :", 2 == 3, "\n";
print "2 != 3 :", 2 != 3", "\n";
</code>```

This is the output:

```<code>2 == 2:1
2 != 2 :
2 == 3 :
2 != 3 :1
</code>```

why the false value is not being printed?

答:
Perl doesn't have a strict boolean type - it has a bunch of things that evaluate as 'false' and everything else is true.

Now, here's the thing - false is anything that's numerically zero, or an empty string.  Or indeed undef.

So:

```<code>print "Zero" if 0;
print "Empty" if '';
print "Undef" if undef;
</code>```

None will print, because all the conditionals are 'false'.

Now, when you try and create a 'boolean' how should perl know what value to give it?

```<code>#!/usr/bin/env perl

use strict;
use warnings;

my $value = !1;
my $othervalue = !'true';
</code>```

What is $value or $othervalue at this point? I mean, any of 0, 0.00, '' (and a few others) would be 'valid'.  But here's the thing - it doesn't matter, because it's a boolean. As long as when you feed it into if it does the right thing, then perl can return whatever it likes.

Perl cheats - it returns from this operation a dualvar - a variable with two values, one for uses in a string context, and the other for use in a numeric context.

You can do a thing that doesn't work otherwise:

```<code>use Scalar::Util qw ( isdual dualvar );
print "\$value is dual\n" if isdual $value;
print "Coercing numerically:", 0+$value,"\n";
print "Coercing stringifically:", ''.$value,"\n";
</code>```

This won't work for normal numerical (or string) values. You can recreate the same with the dualvar function:

```<code>my $special = dualvar ( 666, "the beast" );
</code>```

Meddling with dualvars isn't generally good practice though. Just print explicitly what you want, with a conditional test and you've got no ambiguity there.

Title: perl false values are not printed

Body:
when I print false values in perl I get nothing printed. Probably this is a very simple question, but I searched google without finding an answer.

Code:

print "2 == 2 :", 2 == 2, "\n";
print "2 != 2 :", 2 != 2, "\n";
print "2 == 3 :", 2 == 3, "\n";
print "2 != 3 :", 2 != 3", "\n";

This is the output:

2 == 2:1
2 != 2 :
2 == 3 :
2 != 3 :1

why the false value is not being printed?

Body:
Perl doesn't have a strict boolean type - it has a bunch of things that evaluate as 'false' and everything else is true.

Now, here's the thing - false is anything that's numerically zero, or an empty string.  Or indeed undef.

So:

print "Zero" if 0;
print "Empty" if '';
print "Undef" if undef;

None will print, because all the conditionals are 'false'.

Now, when you try and create a 'boolean' how should perl know what value to give it?

#!/usr/bin/env perl

use strict;
use warnings;

my $value = !1;
my $othervalue = !'true';

What is $value or $othervalue at this point? I mean, any of 0, 0.00, '' (and a few others) would be 'valid'.  But here's the thing - it doesn't matter, because it's a boolean. As long as when you feed it into if it does the right thing, then perl can return whatever it likes.

Perl cheats - it returns from this operation a dualvar - a variable with two values, one for uses in a string context, and the other for use in a numeric context.

You can do a thing that doesn't work otherwise:

use Scalar::Util qw ( isdual dualvar );
print "\$value is dual\n" if isdual $value;
print "Coercing numerically:", 0+$value,"\n";
print "Coercing stringifically:", ''.$value,"\n";

This won't work for normal numerical (or string) values. You can recreate the same with the dualvar function:

my $special = dualvar ( 666, "the beast" );

Meddling with dualvars isn't generally good practice though. Just print explicitly what you want, with a conditional test and you've got no ambiguity there.


问:
Cannot redirect to different pages after Login with Spring Security
I'm using Spring Security for logging in to my application and I'm trying to redirect to some pages after logging in but I'm unable, I think it's a problem with my spring-security.xml, this is my code:

MyAuthenticationSuccessHandler:

```<code>public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
  ...
  @Override
  public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
    ...
    // check if user is active after successfully logging in
    if (!isActiveStatus(authentication)) {
      logger.info("User [" + username + "] is not longer active.");
      authentication.setAuthenticated(false);
      response.sendRedirect(request.getContextPath() + "/home/welcome?notactive");
      return;
    }
    ...
  }
  ...
}
</code>```

spring-security.xml:

```<code>....
<security:intercept-url pattern="/home/**" access="permitAll" />
<security:intercept-url pattern="/" access="permitAll" />
<security:intercept-url pattern="/**" access="isAuthenticated()" />
<security:form-login login-page="/home/welcome?login"
  default-target-url="/home/welcome"
  authentication-success-handler-ref="MyAuthenticationSuccessHandler"
  authentication-failure-handler-ref="MyAuthenticationFailureHandler" />
....
</code>```

With this code, the application always redirect to /home/welcome?login and never to /home/welcome?notactive. Any idea?

Thanks in advance.

答:
You appear to be trying to manually send a redirect, the SuccessHandler has it's own mechanism for this:</p>

```<code>        getRedirectStrategy().sendRedirect(request, response, "/home/welcome?notactive");
</code>```

Body:
I'm using Spring Security for logging in to my application and I'm trying to redirect to some pages after logging in but I'm unable, I think it's a problem with my spring-security.xml, this is my code:

MyAuthenticationSuccessHandler:

public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
  ...
  @Override
  public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
    ...
    // check if user is active after successfully logging in
    if (!isActiveStatus(authentication)) {
      logger.info("User [" + username + "] is not longer active.");
      authentication.setAuthenticated(false);
      response.sendRedirect(request.getContextPath() + "/home/welcome?notactive");
      return;
    }
    ...
  }
  ...
}

spring-security.xml:

....
<security:intercept-url pattern="/home/**" access="permitAll" />
<security:intercept-url pattern="/" access="permitAll" />
<security:intercept-url pattern="/**" access="isAuthenticated()" />
<security:form-login login-page="/home/welcome?login"
  default-target-url="/home/welcome"
  authentication-success-handler-ref="MyAuthenticationSuccessHandler"
  authentication-failure-handler-ref="MyAuthenticationFailureHandler" />
....

With this code, the application always redirect to /home/welcome?login and never to /home/welcome?notactive. Any idea?

Thanks in advance.

Body:
You appear to be trying to manually send a redirect, the SuccessHandler has it's own mechanism for this:

        getRedirectStrategy().sendRedirect(request, response, "/home/welcome?notactive");


问:
start of making a mailing list and saving it to notepad (perfectiblely in html)
Hey I'm making a mailing list and I am wondering how do i set up a way for people to send me a message of their email and for it to automatically save to a notepad file or somewhere else?</p>

答:
Really depends on the scale of email list 10s,100s,10000s and the $ budget. There is loads of pre-cooked software for email management/handling from listserv to mailchimp. On the smallest scale some email clients outlook/thunderbird can be set to perform actions on incoming email from/to target address such as put in folder or forward.
Best approach depends on your environment (mac/linux/pc) and email infrastructure on premise, in cloud etc. and ability to code

see https://docs.python.org/2/library/email.parser.html


问:
Using function in Javascript
Example:

```<code>function pcs()
{
    var t1 = document.getElementById("tot1").value
    var pb = document.getElementById("pcbox").value
    var pc = ""

    if (t1==! && pb==!)
    {
        document.getElementId("rbox").innerHTML = ""
    }
}
</code>```

My question is if t1 and pb are null the function pcs() is not called... Why?

答: The line if(t1==! && pb==!) is nonsense - did you mean if (!t1 && !pb)?

OwnerDisplayName: aravinth

LastEditorDisplayName: RoBorg

ContentLicense: CC BY-SA 2.5

Title: Using function in Javascript

Body:
Example:

function pcs()
{
    var t1 = document.getElementById("tot1").value
    var pb = document.getElementById("pcbox").value
    var pc = ""

    if (t1==! && pb==!)
    {
        document.getElementId("rbox").innerHTML = ""
    }
}

My question is if t1 and pb are null the function pcs() is not called... Why?

OwnerDisplayName: RoBorg


问:
What wording in the C++ standard allows static_cast<non-void-type*>(malloc(N)); to work?
As far as I understand the wording in 5.2.9 Static cast, the only time the result of a void*-to-object-pointer conversion is allowed is when the void* was a result of the inverse conversion in the first place.

Throughout the standard there is a bunch of references to the representation of a pointer, and the representation of a void pointer being the same as that of a char pointer, and so on, but it never seems to explicitly say that casting an arbitrary void pointer yields a pointer to the same location in memory, with a different type, much like type-punning is undefined where not punning back to an object's actual type.

So while malloc clearly returns the address of suitable memory and so on, there does not seem to be any way to actually make use of it, portably, as far as I have seen.

答:
C++03, §20.4.6p2

The contents are the same as the Standard C library header <stdlib.h>, with the following changes: [list of changes that don't apply here]

C99, §7.20.3.3p2-3

(Though C++03 is based on C89, I only have C99 to quote.  However, I believe this section is semantically unchanged.  §7.20.3p1 may also be useful.)

The malloc function allocates space for an object whose size is specified by size and
  whose value is indeterminate.

The malloc function returns either a null pointer or a pointer to the allocated space.

From these two quotes, malloc allocates an uninitialized object and returns a pointer to it, or returns a null pointer.  A pointer to an object which you have as a void pointer can be converted to a pointer to that object (first sentence of C++03 §5.2.9p13, mentioned in the previous answer).

This should be less "handwaving", which you complained of, but someone might argue I'm "interpreting" C's definition of malloc as I wish, by, for example, noticing C says "to the allocated space" rather than "to the allocated object".  To those people: first realize that "space" and "object" are synonyms in C, and second please file a defect report with the standard committees, because not even I am pedantic enough to continue. :)

I'll give you the benefit of the doubt and believe you got tripped up in the cross-references, cross-interpretation, and sometimes-confused integration between the standards, rather than "space" vs "object".


问:
Storing nodes at each level of depth in json object in seperate array
i have a json, something like this </p>

```<code>{
   "a": {
      "b1": "blah blah",
      "b2": "ahsbefbasef",
      "b3": "adsfad af"
   },
   "c": {
      "d1":"asef",
      "d2":"fefef",
      "d3":"ffgfgf"
   }
}
</code>```

<p>now i want to traverse through this json and get all the nodes-depth wise, as in i want to store nodes with 0 depth(a, c) in one array, nodes with depth 1 (c1,c2,c3,d1,d2,d3) in another array, and so on and so forth, basically breaking json object and storing nodes present at each depth in seperate array </p>

答:
You could take an recursive approach by using an incremented level for each nested object. Then take the level for the result and for adding the keys of same level.

function iter(object, level) {
    var keys = Object.keys(object);

    level = level || 0;
    result[level] = result[level] || [];
    Array.prototype.push.apply(result[level], keys);

    keys.forEach(function (key) {
        if (object[key] && typeof object[key] === 'object') {
            iter(object[key], level + 1);
        }
    });
}

var object = { a: { b1: "blah blah", b2: "ahsbefbasef", b3: "adsfad af" }, c: { d1: "asef", d2: "fefef", d3: "ffgfgf" } },
    result = [];

iter(object);

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
i have a json, something like this

{
   "a": {
      "b1": "blah blah",
      "b2": "ahsbefbasef",
      "b3": "adsfad af"
   },
   "c": {
      "d1":"asef",
      "d2":"fefef",
      "d3":"ffgfgf"
   }
}

now i want to traverse through this json and get all the nodes-depth wise, as in i want to store nodes with 0 depth(a, c) in one array, nodes with depth 1 (c1,c2,c3,d1,d2,d3) in another array, and so on and so forth, basically breaking json object and storing nodes present at each depth in seperate array

Body:
You could take an recursive approach by using an incremented level for each nested object. Then take the level for the result and for adding the keys of same level.

function iter(object, level) {
    var keys = Object.keys(object);

    level = level || 0;
    result[level] = result[level] || [];
    Array.prototype.push.apply(result[level], keys);

    keys.forEach(function (key) {
        if (object[key] && typeof object[key] === 'object') {
            iter(object[key], level + 1);
        }
    });
}

var object = { a: { b1: "blah blah", b2: "ahsbefbasef", b3: "adsfad af" }, c: { d1: "asef", d2: "fefef", d3: "ffgfgf" } },
    result = [];

iter(object);

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
How to Print Bootstrap Modal Exactly as the Display?
so I'm having difficulties to print a modal with it's css. I wanted to print out a modal window exactly as it shown on the screen. I've used the window.print() command or even the javasript / jquery one. but the css is not attached. instead, it prints my modal only half way through.

So, what I wanted is, this modal image :
Modal Example Image

Will be printed to window.print() as what it shown on the screen. the whole modal block with the borders etc. but without the page behind it.

codes I've tried :

```<code>function printElement(elem) {
        var domClone = elem.cloneNode(true);

        var $printSection = document.getElementById("printSection");

        if (!$printSection) {
            var $printSection = document.createElement("div");
            $printSection.id = "printSection";
            document.body.appendChild($printSection);
        }

        $printSection.innerHTML = "";
        $printSection.appendChild(domClone);
        window.print();
    }
</code>```

If anyone would answer this, Thank You !

答:
You can use @media print tag

```<code>@media print {
  model.class {
     display: none; /* Hidden by default */
     position: fixed; /* Stay in place */
     z-index: 1; /* Sit on top */
     left: 0;
     top: 0;
     width: 100%; /* Full width */
     height: 100%; /* Full height */
     overflow: auto; /* Enable scroll if needed */
     background-color: rgb(0,0,0); /* Fallback color */
     background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
  } // or you can add what ever you want css in print mood
</code>```

All the CSS in the @media print tag will be applied only in print mode, so to test the style and be sure the design deals with needs, you can use print mode in Chrome Browser.

For more information, check this answer.

Body:
so I'm having difficulties to print a modal with it's css. I wanted to print out a modal window exactly as it shown on the screen. I've used the window.print() command or even the javasript / jquery one. but the css is not attached. instead, it prints my modal only half way through.

So, what I wanted is, this modal image :
Modal Example Image

Will be printed to window.print() as what it shown on the screen. the whole modal block with the borders etc. but without the page behind it.

codes I've tried :

function printElement(elem) {
        var domClone = elem.cloneNode(true);

        var $printSection = document.getElementById("printSection");

        if (!$printSection) {
            var $printSection = document.createElement("div");
            $printSection.id = "printSection";
            document.body.appendChild($printSection);
        }

        $printSection.innerHTML = "";
        $printSection.appendChild(domClone);
        window.print();
    }

If anyone would answer this, Thank You !

Body:
You can use @media print tag

@media print {
  model.class {
     display: none; /* Hidden by default */
     position: fixed; /* Stay in place */
     z-index: 1; /* Sit on top */
     left: 0;
     top: 0;
     width: 100%; /* Full width */
     height: 100%; /* Full height */
     overflow: auto; /* Enable scroll if needed */
     background-color: rgb(0,0,0); /* Fallback color */
     background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
  } // or you can add what ever you want css in print mood

All the CSS in the @media print tag will be applied only in print mode, so to test the style and be sure the design deals with needs, you can use print mode in Chrome Browser.

For more information, check this answer.


问:
Insert and set value with max()+1 problems
I am trying to insert a new row and set the customer_id with max()+1. The reason for this is the table already has a auto_increatment on another column named id and the table will have multiple rows with the same customer_id.

With this:

```<code>INSERT INTO customers
  ( customer_id, firstname, surname )
VALUES
  ((SELECT MAX( customer_id ) FROM customers) +1, 'jim', 'sock')
</code>```

...I keep getting the following error:

```<code>#1093 - You can't specify target table 'customers' for update in FROM clause
</code>```

Also how would I stop 2 different customers being added at the same time and not having the same customer_id?

答:
None of the about answers works for my case. I got the answer from here, and my SQL is:</p>

```<code>INSERT INTO product (id, catalog_id, status_id, name, measure_unit_id, description, create_time)
VALUES (
  (SELECT id FROM (SELECT COALESCE(MAX(id),0)+1 AS id FROM product) AS temp),
  (SELECT id FROM product_catalog WHERE name="AppSys1"),
  (SELECT id FROM product_status WHERE name ="active"),
  "prod_name_x",
  (SELECT id FROM measure_unit WHERE name ="unit"),
  "prod_description_y",
  UNIX_TIMESTAMP(NOW())
)
</code>```

Body:
I am trying to insert a new row and set the customer_id with max()+1. The reason for this is the table already has a auto_increatment on another column named id and the table will have multiple rows with the same customer_id.

With this:

INSERT INTO customers
  ( customer_id, firstname, surname )
VALUES
  ((SELECT MAX( customer_id ) FROM customers) +1, 'jim', 'sock')

...I keep getting the following error:

#1093 - You can't specify target table 'customers' for update in FROM clause

Also how would I stop 2 different customers being added at the same time and not having the same customer_id?

Body:
None of the about answers works for my case. I got the answer from here, and my SQL is:

INSERT INTO product (id, catalog_id, status_id, name, measure_unit_id, description, create_time)
VALUES (
  (SELECT id FROM (SELECT COALESCE(MAX(id),0)+1 AS id FROM product) AS temp),
  (SELECT id FROM product_catalog WHERE name="AppSys1"),
  (SELECT id FROM product_status WHERE name ="active"),
  "prod_name_x",
  (SELECT id FROM measure_unit WHERE name ="unit"),
  "prod_description_y",
  UNIX_TIMESTAMP(NOW())
)


问:
java.lang.NullPointerException: while take photo
Im getting this error, when click deny permission in  "Allow app to access photos, media and files on your device ? "

```<code>    FATAL EXCEPTION: main
   Process: com.viantti.app, PID: 12349
   java.lang.NullPointerException: file
at android.net.Uri.fromFile(Uri.java:452)
at com.viantti.app.ProfilePage.getOutputMediaFileUri(ProfilePage.java:1011)
at com.viantti.app.ProfilePage.takePicture(ProfilePage.java:996)
at com.viantti.app.ProfilePage.access$2800(ProfilePage.java:87)
at com.viantti.app.ProfilePage$25.onClick(ProfilePage.java:1522)
at android.view.View.performClick(View.java:5205)
at android.view.View$PerformClick.run(View.java:21162)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5468)
at java.lang.reflect.Method.invoke(Native Method)
atcom.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:781)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:671)
</code>```

java error line,

```<code>public Uri getOutputMediaFileUri(int type) {
    return Uri.fromFile(getOutputMediaFile(type));
}
</code>```

答: When user denies the authorization, you cannot access the media files, you should use this code only if the authorization is accepted</p>

Body:
Im getting this error, when click deny permission in  "Allow app to access photos, media and files on your device ? "

    FATAL EXCEPTION: main
   Process: com.viantti.app, PID: 12349
   java.lang.NullPointerException: file
at android.net.Uri.fromFile(Uri.java:452)
at com.viantti.app.ProfilePage.getOutputMediaFileUri(ProfilePage.java:1011)
at com.viantti.app.ProfilePage.takePicture(ProfilePage.java:996)
at com.viantti.app.ProfilePage.access$2800(ProfilePage.java:87)
at com.viantti.app.ProfilePage$25.onClick(ProfilePage.java:1522)
at android.view.View.performClick(View.java:5205)
at android.view.View$PerformClick.run(View.java:21162)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5468)
at java.lang.reflect.Method.invoke(Native Method)
atcom.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:781)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:671)

java error line,

public Uri getOutputMediaFileUri(int type) {
    return Uri.fromFile(getOutputMediaFile(type));
}


问:
cURL returning XML or JSON
I've got a form say here - http://example.com/palreg.php

Once people register I'll be sending them an email with the link that will allow them to edit their details (I know it's a crazy way of doing things, but I am working on someone else's code so don't mind) for instance the url as such http://example.com/palreg.php?paliD=1234, and when they go to that page the form will be populated with their information so that they can make changes.

Now the problem is that the DB is in a different site and the information has to be passed to that site to perform a select action, to do so I use cURL to send the information like so

```<code>$url = "http://example2.com/processXML.php";
$xmlStr will be like this

<table>tab_name</table>
<action>select</action>
<palid>1234</palid>

$ch=curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, 'xmlstr='.$xmlStr);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$data = curl_exec($ch);
</code>```

On the other end (http://example2.com/processXML.php) I convert the xml to an array and perform the query to select pal information based on the id sent.

The real question now is how do I send the retrieved pal information (as xml or json or array) back so that i can populate the form with the returned data.

Also can I do a return $dataArray; in processXML.php and be able to grab it?

OK to make things a bit clearer, what I do in processXML.php is
retrieve the result set and do this

```<code>print json_encode($resultArray);
</code>```

not should I print or return

Thank you, and do let me know if things aren't clear.

答:
just encode it as you want, and echo it to the page. your $data= will contain the echoed contents. Personal preference has been to use JSON since it's so easy to throw around. as in</p>

```<code>//Bunch of DB stuff..
$row=mysql_fetch_however_you_handle_it();
echo json_encode($row);

//on your receiving end, that just did the cURL send,
$row=json_decode($data,true);//decode the JSON straight into an array...
</code>```

Title: cURL returning XML or JSON

Body:
I've got a form say here - http://example.com/palreg.php

Once people register I'll be sending them an email with the link that will allow them to edit their details (I know it's a crazy way of doing things, but I am working on someone else's code so don't mind) for instance the url as such http://example.com/palreg.php?paliD=1234, and when they go to that page the form will be populated with their information so that they can make changes.

Now the problem is that the DB is in a different site and the information has to be passed to that site to perform a select action, to do so I use cURL to send the information like so

$url = "http://example2.com/processXML.php";
$xmlStr will be like this

tab_name

<action>select</action>
<palid>1234</palid>

$ch=curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, 'xmlstr='.$xmlStr);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$data = curl_exec($ch);

On the other end (http://example2.com/processXML.php) I convert the xml to an array and perform the query to select pal information based on the id sent.

The real question now is how do I send the retrieved pal information (as xml or json or array) back so that i can populate the form with the returned data.

Also can I do a return $dataArray; in processXML.php and be able to grab it?

OK to make things a bit clearer, what I do in processXML.php is
retrieve the result set and do this

print json_encode($resultArray);

not should I print or return

Thank you, and do let me know if things aren't clear.

Body:
just encode it as you want, and echo it to the page. your $data= will contain the echoed contents. Personal preference has been to use JSON since it's so easy to throw around. as in

//Bunch of DB stuff..
$row=mysql_fetch_however_you_handle_it();
echo json_encode($row);

//on your receiving end, that just did the cURL send,
$row=json_decode($data,true);//decode the JSON straight into an array...


问:
Why java session.getAttribute() value null while accessing ionic1
On server side I'm using Java and on the client side Ionic1.

I'm setting Java object to session like this:

```<code>session.setAttribute("userId", userObj.getUserId());
</code>```

After setting session i need to get that session in another method, that time I'm using like this

```<code>Long userId = (Long) session.getAttribute("userId");
</code>```

Here if i send request from mobile to server I will get session.getAttribute value.

But I sent request from browser to server that time I will get session.getAttribute value is NULL

答:
Make sure you are calling the getAttribute() only after the session has been created. Its a common mistake to access the session attributes when no session exists.
Basically, validate and make sure session exists and that the attribute value has been set in the application flow before trying to get the session attributes. </p>

```<code>HttpSession session = request.getSession(true);
// true will create a session is does not already exists
if(session != null) {
    // get your session attributes here.
    // Your Session Attributes should be set before you're trying to access them
}
</code>```

Body:
On server side I'm using Java and on the client side Ionic1.

I'm setting Java object to session like this:

session.setAttribute("userId", userObj.getUserId());

After setting session i need to get that session in another method, that time I'm using like this

Long userId = (Long) session.getAttribute("userId");

Here if i send request from mobile to server I will get session.getAttribute value.

But I sent request from browser to server that time I will get session.getAttribute value is NULL

Body:
Make sure you are calling the getAttribute() only after the session has been created. Its a common mistake to access the session attributes when no session exists.
Basically, validate and make sure session exists and that the attribute value has been set in the application flow before trying to get the session attributes.

HttpSession session = request.getSession(true);
// true will create a session is does not already exists
if(session != null) {
    // get your session attributes here.
    // Your Session Attributes should be set before you're trying to access them
}


问:
Using CKeditor 5 with rtl
I wanted to know, how do I set CKeditor 5 for RTL?
I couldn't find this in thier website.

If it's not possiable, what will be a good editor for rtl?

thank you!

答:
At the moment, RTL is not supported. We only released alpha version for developers preview. RTL is however on our mind and we will support it in the final 1.0.0 release.

Having this occasion, I'd like to ask you what exactly do you mean by "supporting RTL". We need users feedback to be able to correctly prioritize features. Of course, we have our ideas, but we will gladly listen to what interested users would like to see in CKE5.

We'd appreciate any feedback. If you like to, you may give it here or create an issue on our GitHub repository

Title: Using CKeditor 5 with rtl


问:
calling store from another store mobx
I have 2 stores like below

store 1

```<code> export default class ContactInformationModel {
    @observable id;
    @observable type;
    @observable description;
    @observable mode;

    constructor(id,type,description,mode,show) {
      this.id=id;
      this.type=type;
      this.description=description;
      this.mode=mode;

        }
}

export default class ContactInformationController {
    @observable contact_informations = [];

    addContactInformation(data){
      var id= data.hasOwnProperty("id") ? data.id: this.getInsertedId(data.mode); //auto increment for store mvc;
      var type=data.type;
      var description=data.description;
      var mode=data.mode;
      this.contact_informations.push(new ContactInformationModel(id,type,description,mode));
     }

     @computed get SellerContact(){
      return this.contact_informations.filter(c => c.mode == 'seller');
     }

}
</code>```

Store 2

```<code>import ContactInformationController from  './ContactInformationController';
var contact_information_store=new ContactInformationController();
export default class SellerController {
    @observable seller = {}; //only one entry

    saveSellerContact(){
      //pull contact_information_store
      var contact_information=contact_information_store.SellerContact;

    }

}
</code>```

when I print contact_information it is blank array however it is rendered in jsx . I am still new on react / mobx , any help will be appreciated . Thanks

答:
I think the issue is that you have two different instances of the ContactInformationController class. It will be resolved if you export an instance of ContactInformationController instead, so you use the same instance over the entire app.

```<code>class ContactInformationModel {
  @observable id;
  @observable type;
  @observable description;
  @observable mode;

  constructor(id, type, description, mode, show) {
    this.id=id;
    this.type=type;
    this.description=description;
    this.mode=mode;
  }
}

class ContactInformationController {
  @observable contact_informations = [];

  addContactInformation(data){
    var id= data.hasOwnProperty("id") ? data.id: this.getInsertedId(data.mode); //auto increment for store mvc;
    var type=data.type;
    var description=data.description;
    var mode=data.mode;
    this.contact_informations.push(new ContactInformationModel(id,type,description,mode));
  }

  @computed get SellerContact(){
    return this.contact_informations.filter(c => c.mode == 'seller');
  }
}

export { ContactInformationModel };
export default new ContactInformationController();
</code>```

Title: calling store from another store mobx

Body:
I have 2 stores like below

store 1

 export default class ContactInformationModel {
    @observable id;
    @observable type;
    @observable description;
    @observable mode;

    constructor(id,type,description,mode,show) {
      this.id=id;
      this.type=type;
      this.description=description;
      this.mode=mode;

        }
}

export default class ContactInformationController {
    @observable contact_informations = [];

    addContactInformation(data){
      var id= data.hasOwnProperty("id") ? data.id: this.getInsertedId(data.mode); //auto increment for store mvc;
      var type=data.type;
      var description=data.description;
      var mode=data.mode;
      this.contact_informations.push(new ContactInformationModel(id,type,description,mode));
     }

     @computed get SellerContact(){
      return this.contact_informations.filter(c => c.mode == 'seller');
     }

}

Store 2

import ContactInformationController from  './ContactInformationController';
var contact_information_store=new ContactInformationController();
export default class SellerController {
    @observable seller = {}; //only one entry

    saveSellerContact(){
      //pull contact_information_store
      var contact_information=contact_information_store.SellerContact;

    }

}

when I print contact_information it is blank array however it is rendered in jsx . I am still new on react / mobx , any help will be appreciated . Thanks

Body:
I think the issue is that you have two different instances of the ContactInformationController class. It will be resolved if you export an instance of ContactInformationController instead, so you use the same instance over the entire app.

class ContactInformationModel {
  @observable id;
  @observable type;
  @observable description;
  @observable mode;

  constructor(id, type, description, mode, show) {
    this.id=id;
    this.type=type;
    this.description=description;
    this.mode=mode;
  }
}

class ContactInformationController {
  @observable contact_informations = [];

  addContactInformation(data){
    var id= data.hasOwnProperty("id") ? data.id: this.getInsertedId(data.mode); //auto increment for store mvc;
    var type=data.type;
    var description=data.description;
    var mode=data.mode;
    this.contact_informations.push(new ContactInformationModel(id,type,description,mode));
  }

  @computed get SellerContact(){
    return this.contact_informations.filter(c => c.mode == 'seller');
  }
}

export { ContactInformationModel };
export default new ContactInformationController();


问:
Parsing an XML file using Element Tree
I have a large number of .xml files (about 70) and i need to extract some co-ordinates from them.
Apparently the best way to do this is to parse the xml file using element tree. I am new to python (very very new!) and am having a difficult time understanding all of the documentation which comes with element tree!
I was wondering if anyone had any code where they have used element tree or if anyone could explain to me how to go about it..
Thank you!

This is a sample from my XML file..

```<code>    <?xml version="1.0" encoding="UTF-8" ?>
- <lev:Leveringsinformatie xmlns:lev="http://www.kadaster.nl/schemas/klic/20080722/leveringsinfo">
  <lev:Version>1.5</lev:Version>
  <lev:Klicnummer>10G179900</lev:Klicnummer>
  <lev:Ordernummer>0065491624</lev:Ordernummer>
  <lev:RelatienummerGrondroerder>0000305605</lev:RelatienummerGrondroerder>
  <lev:Leveringsvolgnummer>1</lev:Leveringsvolgnummer>
  <lev:Meldingsoort>Graafmelding</lev:Meldingsoort>
  <lev:DatumTijdAanvraag>2010-08-10T11:43:02.779+02:00</lev:DatumTijdAanvraag>
  <lev:KlantReferentie>1207-0132-030 - 6</lev:KlantReferentie>
- <lev:Locatie axisLabels="x y" srsDimension="2" srsName="epsg:28992" uomLabels="m m">
- <gml:exterior xmlns:gml="http://www.opengis.net/gml">
- <gml:LinearRing>
  <gml:posList>137800.0 484217.0 137796.0 484222.0 137832.0 483757.0 138178.0 483752.0 138174.0 484222.0 137800.0 484217.0</gml:posList>
  </gml:LinearRing>
  </gml:exterior>
  </lev:Locatie>
- <lev:Pngformaat>
- <lev:OmsluitendeRechthoek xmlns:ns4="http://www.kadaster.nl/schemas/klic/20080722/madt" xmlns:bis="http://www.kadaster.nl/schemas/klic/20080722/klicnetbeheerdersinformatieservicetypes" xmlns:ns0="http://www.kadaster.nl/schemas/klic/20080722/gias" xmlns:ns7="http://www.kadaster.nl/schemas/klic/20080722/klicnetbeheerdersinformatieservicetypes" xmlns:madt="http://www.kadaster.nl/schemas/klic/20080722/madt" xmlns:gia="http://www.kadaster.nl/schemas/klic/20080722/gias" xmlns:klic="http://www.kadaster.nl/schemas/20080722/klic" xmlns:b="http://www.kadaster.nl/schemas/klic/20080722/bundelingtypes" xmlns:ns9="http://www.kadaster.nl/schemas/klic/20081010/bmkltypes" xmlns:gml="http://www.opengis.net/gml" xmlns:ns1="http://www.kadaster.nl/schemas/20080722/klic" xmlns:a="http://www.kadaster.nl/schemas/klic/20080722/bundelingservicetypes" xmlns:bmkl="http://www.kadaster.nl/schemas/klic/20081010/bmkltypes" xmlns:ns3="http://www.opengis.net/gml" xmlns:ns8="http://www.kadaster.nl/schemas/klic/20080722/knts">
- <gml:Envelope srsDimension="2" srsName="epsg:28992">
  <gml:lowerCorner>137796 483752</gml:lowerCorner>
  <gml:upperCorner>138178 484222</gml:upperCorner>
  </gml:Envelope>
  </lev:OmsluitendeRechthoek>
  <lev:PixelsBreed>5348</lev:PixelsBreed>
  <lev:PixelsHoog>6580</lev:PixelsHoog>
  </lev:Pngformaat>
- <lev:NetbeheerderLeveringen>
- <lev:NetbeheerderLevering>
  <lev:RelatienummerNetbeheerder>0000578695</lev:RelatienummerNetbeheerder>
  <lev:Bedrijfsnaam>Gemeente Almere</lev:Bedrijfsnaam>
  <lev:BedrijfsnaamAfkorting>Gemeente Almere</lev:BedrijfsnaamAfkorting>
</code>```

I need to extract the lower and upper corner co-ordinates (lowerCorner/upperCorner)

Update: Here is my full script:

```<code>from xml.etree import ElementTree as ET
import sys, string, os, arcgisscripting
gp = arcgisscripting.create(9.3)

workspace = "D:/J040083"
gp.workspace = workspace

for root, dirs, filenames in os.walk(workspace): # returms root, dirs, and files
    for filename in filenames:
        filename_split = os.path.splitext(filename) # filename and extensionname (extension in [1])
        filename_zero = filename_split[0]
        extension = str.upper(filename_split[1])

        try:
            first_2_letters = str.upper(filename_zero[0] + filename_zero[1])
        except:
            first_2_letters = "XX"

        if first_2_letters == "LI" and extension == ".XML":
            tree = ET.parse(workspace)
            print tree.find('//{http://www.opengis.net/gml}lowerCorner').text
            print tree.find('//{http://www.opengis.net/gml}upperCorner').text
</code>```

I am now getting the error:

Message File Name   Line    Position

Traceback

        D:\J040083\TXT_EXTRACTION.py    32

    parse   C:\Python25\Lib\xml\etree\ElementTree.py    862

    parse   C:\Python25\Lib\xml\etree\ElementTree.py    579

IOError: [Errno 13] Permission denied: 'D:/J040083'

and now i am REALLY confused because i am able to access these files with a different script which is almost exactly the same as this one!!

答:
ElementTree can be tricky when namespaces are involved.  The element you are looking for are named <gml:lowerCorner> and <gml:upperCorner>.  Searching higher in the XML data, gml is defined as an XML namespace: xmlns:gml="http://www.opengis.net/gml".  The way to find a subelement of the XML tree is as follows:

```<code>from xml.etree import ElementTree as ET
tree = ET.parse('file.xml')
print tree.find('//{http://www.opengis.net/gml}lowerCorner').text
print tree.find('//{http://www.opengis.net/gml}upperCorner').text
</code>```

Output

```<code>137796 483752
138178 484222
</code>```

Explanation

Using ElementTree's XPath support, // selects all subelements on all levels of the tree.  ElementTree uses {url}tag notation for a tag in a specific namespace.  gml's URL is http://www.opengis.net/gml.  .text retrieves the data in the element.

Note that // is a shortcut to finding a nested node.  The full path of upperCorner in ElementTree's syntax is actually:

```<code>{http://www.kadaster.nl/schemas/klic/20080722/leveringsinfo}Pngformaat/{http://www.kadaster.nl/schemas/klic/20080722/leveringsinfo}OmsluitendeRechthoek/{http://www.opengis.net/gml}Envelope/{http://www.opengis.net/gml}upperCorner
</code>```

Title: Parsing an XML file using Element Tree

Body:
I have a large number of .xml files (about 70) and i need to extract some co-ordinates from them.
Apparently the best way to do this is to parse the xml file using element tree. I am new to python (very very new!) and am having a difficult time understanding all of the documentation which comes with element tree!
I was wondering if anyone had any code where they have used element tree or if anyone could explain to me how to go about it..
Thank you!

This is a sample from my XML file..

    <?xml version="1.0" encoding="UTF-8" ?>
- <lev:Leveringsinformatie xmlns:lev="http://www.kadaster.nl/schemas/klic/20080722/leveringsinfo">
  <lev:Version>1.5</lev:Version>
  <lev:Klicnummer>10G179900</lev:Klicnummer>
  <lev:Ordernummer>0065491624</lev:Ordernummer>
  <lev:RelatienummerGrondroerder>0000305605</lev:RelatienummerGrondroerder>
  <lev:Leveringsvolgnummer>1</lev:Leveringsvolgnummer>
  <lev:Meldingsoort>Graafmelding</lev:Meldingsoort>
  <lev:DatumTijdAanvraag>2010-08-10T11:43:02.779+02:00</lev:DatumTijdAanvraag>
  <lev:KlantReferentie>1207-0132-030 - 6</lev:KlantReferentie>
- <lev:Locatie axisLabels="x y" srsDimension="2" srsName="epsg:28992" uomLabels="m m">
- <gml:exterior xmlns:gml="http://www.opengis.net/gml">
- <gml:LinearRing>
  <gml:posList>137800.0 484217.0 137796.0 484222.0 137832.0 483757.0 138178.0 483752.0 138174.0 484222.0 137800.0 484217.0</gml:posList>
  </gml:LinearRing>
  </gml:exterior>
  </lev:Locatie>
- <lev:Pngformaat>
- <lev:OmsluitendeRechthoek xmlns:ns4="http://www.kadaster.nl/schemas/klic/20080722/madt" xmlns:bis="http://www.kadaster.nl/schemas/klic/20080722/klicnetbeheerdersinformatieservicetypes" xmlns:ns0="http://www.kadaster.nl/schemas/klic/20080722/gias" xmlns:ns7="http://www.kadaster.nl/schemas/klic/20080722/klicnetbeheerdersinformatieservicetypes" xmlns:madt="http://www.kadaster.nl/schemas/klic/20080722/madt" xmlns:gia="http://www.kadaster.nl/schemas/klic/20080722/gias" xmlns:klic="http://www.kadaster.nl/schemas/20080722/klic" xmlns:b="http://www.kadaster.nl/schemas/klic/20080722/bundelingtypes" xmlns:ns9="http://www.kadaster.nl/schemas/klic/20081010/bmkltypes" xmlns:gml="http://www.opengis.net/gml" xmlns:ns1="http://www.kadaster.nl/schemas/20080722/klic" xmlns:a="http://www.kadaster.nl/schemas/klic/20080722/bundelingservicetypes" xmlns:bmkl="http://www.kadaster.nl/schemas/klic/20081010/bmkltypes" xmlns:ns3="http://www.opengis.net/gml" xmlns:ns8="http://www.kadaster.nl/schemas/klic/20080722/knts">
- <gml:Envelope srsDimension="2" srsName="epsg:28992">
  <gml:lowerCorner>137796 483752</gml:lowerCorner>
  <gml:upperCorner>138178 484222</gml:upperCorner>
  </gml:Envelope>
  </lev:OmsluitendeRechthoek>
  <lev:PixelsBreed>5348</lev:PixelsBreed>
  <lev:PixelsHoog>6580</lev:PixelsHoog>
  </lev:Pngformaat>
- <lev:NetbeheerderLeveringen>
- <lev:NetbeheerderLevering>
  <lev:RelatienummerNetbeheerder>0000578695</lev:RelatienummerNetbeheerder>
  <lev:Bedrijfsnaam>Gemeente Almere</lev:Bedrijfsnaam>
  <lev:BedrijfsnaamAfkorting>Gemeente Almere</lev:BedrijfsnaamAfkorting>

I need to extract the lower and upper corner co-ordinates (lowerCorner/upperCorner)

Update: Here is my full script:

from xml.etree import ElementTree as ET
import sys, string, os, arcgisscripting
gp = arcgisscripting.create(9.3)

workspace = "D:/J040083"
gp.workspace = workspace

for root, dirs, filenames in os.walk(workspace): # returms root, dirs, and files
    for filename in filenames:
        filename_split = os.path.splitext(filename) # filename and extensionname (extension in [1])
        filename_zero = filename_split[0]
        extension = str.upper(filename_split[1])

        try:
            first_2_letters = str.upper(filename_zero[0] + filename_zero[1])
        except:
            first_2_letters = "XX"

        if first_2_letters == "LI" and extension == ".XML":
            tree = ET.parse(workspace)
            print tree.find('//{http://www.opengis.net/gml}lowerCorner').text
            print tree.find('//{http://www.opengis.net/gml}upperCorner').text

I am now getting the error:

Message File Name   Line    Position

Traceback

        D:\J040083\TXT_EXTRACTION.py    32

    parse   C:\Python25\Lib\xml\etree\ElementTree.py    862

    parse   C:\Python25\Lib\xml\etree\ElementTree.py    579

IOError: [Errno 13] Permission denied: 'D:/J040083'

and now i am REALLY confused because i am able to access these files with a different script which is almost exactly the same as this one!!

Body:
ElementTree can be tricky when namespaces are involved.  The element you are looking for are named <gml:lowerCorner> and <gml:upperCorner>.  Searching higher in the XML data, gml is defined as an XML namespace: xmlns:gml="http://www.opengis.net/gml".  The way to find a subelement of the XML tree is as follows:

from xml.etree import ElementTree as ET
tree = ET.parse('file.xml')
print tree.find('//{http://www.opengis.net/gml}lowerCorner').text
print tree.find('//{http://www.opengis.net/gml}upperCorner').text

Output

137796 483752
138178 484222

Explanation

Using ElementTree's XPath support, // selects all subelements on all levels of the tree.  ElementTree uses {url}tag notation for a tag in a specific namespace.  gml's URL is http://www.opengis.net/gml.  .text retrieves the data in the element.

Note that // is a shortcut to finding a nested node.  The full path of upperCorner in ElementTree's syntax is actually:

{http://www.kadaster.nl/schemas/klic/20080722/leveringsinfo}Pngformaat/{http://www.kadaster.nl/schemas/klic/20080722/leveringsinfo}OmsluitendeRechthoek/{http://www.opengis.net/gml}Envelope/{http://www.opengis.net/gml}upperCorner


问:
How are subclasses of an interface get called
This is a question that has been bothering me for a while.

In frameworks like Jersey we have interface(s) that we can subclass to add some functionality to our program. for example to add request filtering in a RESt application we can implement ContainerRequestFilter then Voila we got authentication.

My question is how does the framework/library know that we have subclass one of its interfaces?

as per my understanding you can't instantiate an interface, only its subclass such as:

```<code>public interface Greeter{
    void sayHi();
}

public class SpanishGreeter implements Greeter{
    @override
    void sayHi(){
        System.out.println("Hola");
    }
}

public class Controller{
   public void main(String[] args){
       //We must know the name of subclass to instantiate?
       Greeter spanishG = new SpanishGreeter();
   }
}
</code>```

答:
I think instanceof keyword helps in it.</p>

```<code>System.out.println(spanishG instanceof Greeter);  // true
</code>```

Body:
This is a question that has been bothering me for a while.

In frameworks like Jersey we have interface(s) that we can subclass to add some functionality to our program. for example to add request filtering in a RESt application we can implement ContainerRequestFilter then Voila we got authentication.

My question is how does the framework/library know that we have subclass one of its interfaces?

as per my understanding you can't instantiate an interface, only its subclass such as:

public interface Greeter{
    void sayHi();
}

public class SpanishGreeter implements Greeter{
    @override
    void sayHi(){
        System.out.println("Hola");
    }
}

public class Controller{
   public void main(String[] args){
       //We must know the name of subclass to instantiate?
       Greeter spanishG = new SpanishGreeter();
   }
}

Body:
I think instanceof keyword helps in it.

System.out.println(spanishG instanceof Greeter);  // true


问:
mvn spring-boot:run vs java -jar
I know it may sound silly question but I am unable to understand the difference between mvn spring-boot:run and java -jar (.jar file generated with mvn install)

I have a spring boot application with jsp pages in /src/main/resources/META-INF/resources/WEB-INF/. If I use mvn spring-boot:run these pages are served. But If I use java -jar these pages are not found by application.

The application that I am working on is at https://github.com/ArslanAnjum/angularSpringApi

UPDATE:
It works with spring boot 1.4.2.RELEASE while I intend to use the latest version i.e., 1.5.8.RELEASE.

UPDATE:
Well I solved the problem by putting jsps in src/main/webapp/WEB-INF/views/ and changing packaging type to war and then running this war using java -jar target/myapp.war and its working fine now.

答:
Short answer: spring-boot:run is a java -jar command on steroïd running as part of your Maven build, ensuring all required parameters are passed to your app (such as resources). spring-boot:run will also ensure that your project is compiled by executing test-compile lifecycle goals prior to running your app.

Long answer:

When you run java -jar, you launch a new JVM instance with all the parameters you passed to this JVM. For example, using the Spring doc example

```<code>java -Xdebug -Xrunjdwp:server=y, \
    transport=dt_socket, address=8000, suspend=
    -jar target/myproject-0.0.1-SNAPSHOT.jar
</code>```

You will launch a brand new JVM with the given parameters. You need to make sure to include everything needed, such as classpath elements, application parameters, JVM options, etc. on the command line.

When you run mvn spring-boot:run, you launch a Maven build that will:

Run the test-compile lifecycle goals, by default it will be resources:resources, compiler:compile, resources:testResources, compiler:testCompile goals of the Maven Resources and Compiler plugin.

Launch your application with a bunch of parameters that will depend on the
Spring Boot Maven Plugin configuration you defined in your project (your pom.xml, parents and settings, command line, etc.). This includes among other things:

A lot of classpath elements: your target/classes folder which may contain resources and libraries required by your app, your Maven dependencies, etc.

Whether to fork your JVM or not (whether to create a brand new JVM to run your app or re-use the JVM of the Maven build), see fork and agent parameter of the plugin

As per:

I have a spring boot application with jsp pages in
  /src/main/resources/META-INF/resources/WEB-INF/. If I use mvn
  spring-boot:run these pages are served. But If I use java -jar these
  pages are not found by application.

It's because the mvn spring:boot command will make sure your target/classes folder is present in the Classpath when your app is running. After compilation, this folder will contain target/classes/META-INF/resources/WEB-INF among other things. Your app will then be able to find META-INF/resources/WEB-INF and load them when asked. When you ran java -jar command, this folder was probably not on the classpath, your app was then not able to find your resources. (these resources were copied from the src/main/resources folder during the resources:resources goal)

To have a similar result with your java -jar command, you must include your resources on the classpath such as javar -jar myapp.jar -cp $CLASSPATH;/path/to/my/project/target/classes/

Title: mvn spring-boot:run vs java -jar

Body:
Short answer: spring-boot:run is a java -jar command on steroïd running as part of your Maven build, ensuring all required parameters are passed to your app (such as resources). spring-boot:run will also ensure that your project is compiled by executing test-compile lifecycle goals prior to running your app.

Long answer:

When you run java -jar, you launch a new JVM instance with all the parameters you passed to this JVM. For example, using the Spring doc example

java -Xdebug -Xrunjdwp:server=y, \
    transport=dt_socket, address=8000, suspend=
    -jar target/myproject-0.0.1-SNAPSHOT.jar

You will launch a brand new JVM with the given parameters. You need to make sure to include everything needed, such as classpath elements, application parameters, JVM options, etc. on the command line.

When you run mvn spring-boot:run, you launch a Maven build that will:

Run the test-compile lifecycle goals, by default it will be resources:resources, compiler:compile, resources:testResources, compiler:testCompile goals of the Maven Resources and Compiler plugin.

Launch your application with a bunch of parameters that will depend on the
Spring Boot Maven Plugin configuration you defined in your project (your pom.xml, parents and settings, command line, etc.). This includes among other things:

A lot of classpath elements: your target/classes folder which may contain resources and libraries required by your app, your Maven dependencies, etc.

Whether to fork your JVM or not (whether to create a brand new JVM to run your app or re-use the JVM of the Maven build), see fork and agent parameter of the plugin

As per:

I have a spring boot application with jsp pages in
  /src/main/resources/META-INF/resources/WEB-INF/. If I use mvn
  spring-boot:run these pages are served. But If I use java -jar these
  pages are not found by application.

It's because the mvn spring:boot command will make sure your target/classes folder is present in the Classpath when your app is running. After compilation, this folder will contain target/classes/META-INF/resources/WEB-INF among other things. Your app will then be able to find META-INF/resources/WEB-INF and load them when asked. When you ran java -jar command, this folder was probably not on the classpath, your app was then not able to find your resources. (these resources were copied from the src/main/resources folder during the resources:resources goal)

To have a similar result with your java -jar command, you must include your resources on the classpath such as javar -jar myapp.jar -cp $CLASSPATH;/path/to/my/project/target/classes/


答:
That happens due to Polymorphism. The code you mentioned

```<code>Greeter spanishG = new SpanishGreeter();
</code>```

That has reference of parent(in you case interface). On run time it checks weather there is a child class implementing the method if yes then it calls child class behaviour. And in your class you are instantiating with child class on run time JVM knows you have provided implementation.

Title: How are subclasses of an interface get called

Body:
That happens due to Polymorphism. The code you mentioned

Greeter spanishG = new SpanishGreeter();

That has reference of parent(in you case interface). On run time it checks weather there is a child class implementing the method if yes then it calls child class behaviour. And in your class you are instantiating with child class on run time JVM knows you have provided implementation.


问:
*ngIf equivalent in TypeScript code
How is it possible check if the component property is undefined within the TypeScript code, in a method for instance?

In .html component template it is possible to do such check as a conditional on displaying html elements. To avoid the diplay in case they do not exist or not initialized yet.

```<code><div *ngIf="exampleComponentProperty"></div>
</code>```

Is it possible to do the same check in .ts? How would the expression look then?

```<code>if (this.exampleComponentProperty != null) {
// some code...
}
</code>```

did not seem to work.

答:
You can simply write

```<code>if (this.exampleComponentProperty) {
// some code...
}
</code>```

Or

```<code>if (this.exampleComponentProperty != undefined) {
// some code...
}
</code>```

Title: *ngIf equivalent in TypeScript code

Body:
How is it possible check if the component property is undefined within the TypeScript code, in a method for instance?

In .html component template it is possible to do such check as a conditional on displaying html elements. To avoid the diplay in case they do not exist or not initialized yet.

Is it possible to do the same check in .ts? How would the expression look then?

if (this.exampleComponentProperty != null) {
// some code...
}

did not seem to work.

Body:
You can simply write

if (this.exampleComponentProperty) {
// some code...
}

Or

if (this.exampleComponentProperty != undefined) {
// some code...
}


问:
Eclipse 4.7.1a - open file in editor from code/programatically
I want to add capability to my eclipse plug-in to open specified file in new Eclipse editor. I found solution based on org.eclipse.ui.ide.IDE and import org.eclipse.core.filesystem.EFS:

import java.io.File;
import org.eclipse.core.filesystem.EFS;
import org.eclipse.core.filesystem.IFileStore;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IDE;

File fileToOpen = new File("externalfile.xml");

if (fileToOpen.exists() && fileToOpen.isFile()) {
    IFileStore fileStore = EFS.getLocalFileSystem().getStore(fileToOpen.toURI());
    IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();

    try {
        IDE.openEditorOnFileStore( page, fileStore );
    } catch ( PartInitException e ) {
        //Put your exception handler here if you wish to
    }
} else {
    //Do something if the file does not exist
}
```

Unfortunately, that solution is no longer supported in 4th versions of Eclipse and only works with older IDEs.

Is there any possibility to open editor on specified file programatically in Eclipse 4.x.x or make workaround/deal with compatibility?

答: Eclipse 4 still supports 3.x style code (3.x compatibility mode) so this should still work unless you are writing a pure 'e4' style application.</p>

Body:
I want to add capability to my eclipse plug-in to open specified file in new Eclipse editor. I found solution based on org.eclipse.ui.ide.IDE and import org.eclipse.core.filesystem.EFS:

import java.io.File;
import org.eclipse.core.filesystem.EFS;
import org.eclipse.core.filesystem.IFileStore;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IDE;

File fileToOpen = new File("externalfile.xml");

if (fileToOpen.exists() && fileToOpen.isFile()) {
    IFileStore fileStore = EFS.getLocalFileSystem().getStore(fileToOpen.toURI());
    IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();

    try {
        IDE.openEditorOnFileStore( page, fileStore );
    } catch ( PartInitException e ) {
        //Put your exception handler here if you wish to
    }
} else {
    //Do something if the file does not exist
}

Unfortunately, that solution is no longer supported in 4th versions of Eclipse and only works with older IDEs.

Is there any possibility to open editor on specified file programatically in Eclipse 4.x.x or make workaround/deal with compatibility?


问:
CSS Flexbox - Organizing flex items based on screen size
I have a container of flex items that I am trying to organize in different layouts with different number of flex items depending on screen size. For example, on desktop, I'd like to have 4 containers, each with 2 items laid out in a 2x4 grid and each cell is 1x2. What I can't seem to wrap my head around is the getting the layout on tablet using purely with flexbox. Any pointers in the right direction would be great.

div {
  box-sizing: border-box;
  width: 100%;
}

.container {
  display: flex;
  border: 1px solid red;
  flex-wrap: wrap;
  flex-direction: row;
  padding: 10px;
}

.cell {
  display: flex;
  flex: 50%;
  padding: 10px;
  border: 1px solid blue;
  height: 100px;
}

.data {
  width: 100%;
  justify-content: middle;
  flex: 1;
  border: 1px solid green;
}

@media only screen and (max-width: 1024px) {
  .container {
    display: inline-block;
    position: relative;
  }

  #cell1 {
    width: 66%;
    float: left;
  }

  #cell2 {
    flex-direction: column;
    right: 10px;
    position: absolute;
    width: 33%;
    height: 100%;
  }

  #cell3 {
    width: 66%;
    float: left;
  }

  #cell4 { display: none;}
}

@media only screen and (max-width: 640px) {

  #cell2 {
    flex-direction: row;
    position: static;
    height: 100px;
  }

  #cell4 { display: none; }

  .container {
    flex-direction: row;
    flex-wrap: wrap;
    display: flex;
  }

  .cell {
    flex: 100%;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="cell" id="cell1">
    <span class="data">Image1</span>
    <span class="data">Info1</span>
  </div>
  <div class="cell" id="cell2">
    <span class="data">Image2</span>
    <span class="data">Info2</span>
  </div>
  <div class="cell" id="cell3">
    <span class="data">Image3</span>
    <span class="data">Info3</span>
  </div>
  <div class="cell" id="cell4">
    <span class="data">Image4</span>
    <span class="data">Info4</span>
  </div>
</div></code>```

And here is a codepen here.

Can test responsiveness by resizing window. I was able to correctly get the layouts that I want for desktop and mobile by removing the 4th container and changing flex-direction property. Struggling to do the same for tablet to allow spanning across multiple rows/columns in flex like you can in grid layouts.

Desktop - container: 2x4 | cell: 1x2

```<code>|---------------------------------|
| --------------- --------------- |
| | Cell | Cell | | Cell | Cell | |
| --------------- --------------- |
| --------------- --------------- |
| | Cell | Cell | | Cell | Cell | |
| --------------- --------------- |
|---------------------------------|
</code>```

Tablet - container: 2x3 | cell: 1x2/2x1

```<code>|--------------------------|
| --------------- -------- |
| | Cell | Cell | | Cell | |
| --------------- |______| |
| --------------- |      | |
| | Cell | Cell | | Cell | |
| --------------- -------- |
|--------------------------|
</code>```

Mobile - container: 3x2 | cell: 1x2

```<code>|-----------------|
| --------------- |
| | Cell | Cell | |
| --------------- |
| --------------- |
| | Cell | Cell | |
| --------------- |
| --------------- |
| | Cell | Cell | |
| --------------- |
|-----------------|
</code>```

答:
Since comments can be removed, and to keep their value, I decided to post an answer, with this code snippet as base.

div {
  box-sizing: border-box;
  width: 100%;
}

.container {
  display: flex;
  border: 1px solid red;
  flex-wrap: wrap;
  flex-direction: row;
  padding: 10px;
}

.cell {
  display: flex;
  flex: 50%;
  padding: 10px;
  border: 1px solid blue;
  height: 100px;
}

.data {
  width: 100%;
  justify-content: middle;
  flex: 1;
  border: 1px solid green;
}

@media only screen and (max-width: 1024px) {
  .container {
    display: inline-block;
    position: relative;
  }

  #cell1 {
    width: 66%;
    float: left;
  }

  #cell2 {
    flex-direction: column;
    right: 10px;
    position: absolute;
    width: 33%;
    height: 100%;
  }

  #cell3 {
    width: 66%;
    float: left;
  }

  #cell4 { display: none;}
}

@media only screen and (max-width: 640px) {

  #cell2 {
    flex-direction: row;
    position: static;
    height: 100px;
  }

  #cell4 { display: none; }

  .container {
    flex-direction: row;
    flex-wrap: wrap;
    display: flex;
  }

  .cell {
    flex: 100%;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="cell" id="cell1">
    <span class="data">Image1</span>
    <span class="data">Info1</span>
  </div>
  <div class="cell" id="cell2">
    <span class="data">Image2</span>
    <span class="data">Info2</span>
  </div>
  <div class="cell" id="cell3">
    <span class="data">Image3</span>
    <span class="data">Info3</span>
  </div>
  <div class="cell" id="cell4">
    <span class="data">Image4</span>
    <span class="data">Info4</span>
  </div>
</div></code>```

For it to work in tablet mode, you need to either make the container a flex column container, or use absolute or float to position the 2nd cell.

They all have limitations when it comes to responsiveness, where i.e. the flex column container solution will need a fixed height.

The one I find most usable is to stay with the default flex row set up, and combine it with absolute position on the 2nd cell.

This way the 1st and 3rd cell will continue being flex items, and benefit from its responsiveness.

In case of the 2nd cell's content making it higher than the 1st/3rd, one can then either allow it to scroll, or add a small script adjusting its parent's height.

Updated codepen

Stack snippet

div {
  box-sizing: border-box;
  width: 100%;
}

.container {
  display: flex;
  border: 1px solid red;
  flex-wrap: wrap;
  flex-direction: row;
  padding: 10px;
}

.cell {
  display: flex;
  flex: 50%;
  padding: 10px;
  border: 1px solid blue;
  height: 100px;
}

.data {
  width: 100%;
  justify-content: middle;
  flex: 1;
  border: 1px solid green;
}

@media only screen and (max-width: 640px) {

  #cell2 {
    flex-direction: row;
    position: static;
    height: 100px;
  }

  #cell4 { display: none; }

  .container {
    flex-direction: row;
    flex-wrap: wrap;
    display: flex;
  }

  .cell {
    flex: 100%;
  }
}

@media only screen and (min-width: 640px) and (max-width: 1024px) {
  .container {
    position: relative;
  }

  #cell1 {
    flex: 0 0 66%;
  }

  #cell2 {
    flex-direction: column;
    right: 10px;
    position: absolute;
    width: 33%;
    height: calc(100% - 20px);
  }

  #cell3 {
    flex:  0 0 66%;
  }

  #cell4 { display: none;}
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="cell" id="cell1">
    <span class="data">Image1</span>
    <span class="data">Info1</span>
  </div>
  <div class="cell" id="cell2">
    <span class="data">Image2</span>
    <span class="data">Info2</span>
  </div>
  <div class="cell" id="cell3">
    <span class="data">Image3</span>
    <span class="data">Info3</span>
  </div>
  <div class="cell" id="cell4">
    <span class="data">Image4</span>
    <span class="data">Info4</span>
  </div>
</div></code>```

Body:
I have a container of flex items that I am trying to organize in different layouts with different number of flex items depending on screen size. For example, on desktop, I'd like to have 4 containers, each with 2 items laid out in a 2x4 grid and each cell is 1x2. What I can't seem to wrap my head around is the getting the layout on tablet using purely with flexbox. Any pointers in the right direction would be great.

div {
  box-sizing: border-box;
  width: 100%;
}

.container {
  display: flex;
  border: 1px solid red;
  flex-wrap: wrap;
  flex-direction: row;
  padding: 10px;
}

.cell {
  display: flex;
  flex: 50%;
  padding: 10px;
  border: 1px solid blue;
  height: 100px;
}

.data {
  width: 100%;
  justify-content: middle;
  flex: 1;
  border: 1px solid green;
}

@media only screen and (max-width: 1024px) {
  .container {
    display: inline-block;
    position: relative;
  }

  #cell1 {
    width: 66%;
    float: left;
  }

  #cell2 {
    flex-direction: column;
    right: 10px;
    position: absolute;
    width: 33%;
    height: 100%;
  }

  #cell3 {
    width: 66%;
    float: left;
  }

  #cell4 { display: none;}
}

@media only screen and (max-width: 640px) {

  #cell2 {
    flex-direction: row;
    position: static;
    height: 100px;
  }

  #cell4 { display: none; }

  .container {
    flex-direction: row;
    flex-wrap: wrap;
    display: flex;
  }

  .cell {
    flex: 100%;
  }
}

    Image1
    Info1

    Image2
    Info2

    Image3
    Info3

    Image4
    Info4

And here is a codepen here.

Can test responsiveness by resizing window. I was able to correctly get the layouts that I want for desktop and mobile by removing the 4th container and changing flex-direction property. Struggling to do the same for tablet to allow spanning across multiple rows/columns in flex like you can in grid layouts.

Desktop - container: 2x4 | cell: 1x2

|---------------------------------|
| --------------- --------------- |
| | Cell | Cell | | Cell | Cell | |
| --------------- --------------- |
| --------------- --------------- |
| | Cell | Cell | | Cell | Cell | |
| --------------- --------------- |
|---------------------------------|

Tablet - container: 2x3 | cell: 1x2/2x1

|--------------------------|
| --------------- -------- |
| | Cell | Cell | | Cell | |
| --------------- |______| |
| --------------- |      | |
| | Cell | Cell | | Cell | |
| --------------- -------- |
|--------------------------|

Mobile - container: 3x2 | cell: 1x2

|-----------------|
| --------------- |
| | Cell | Cell | |
| --------------- |
| --------------- |
| | Cell | Cell | |
| --------------- |
| --------------- |
| | Cell | Cell | |
| --------------- |
|-----------------|

Body:
Since comments can be removed, and to keep their value, I decided to post an answer, with this code snippet as base.

div {
  box-sizing: border-box;
  width: 100%;
}

.container {
  display: flex;
  border: 1px solid red;
  flex-wrap: wrap;
  flex-direction: row;
  padding: 10px;
}

.cell {
  display: flex;
  flex: 50%;
  padding: 10px;
  border: 1px solid blue;
  height: 100px;
}

.data {
  width: 100%;
  justify-content: middle;
  flex: 1;
  border: 1px solid green;
}

@media only screen and (max-width: 1024px) {
  .container {
    display: inline-block;
    position: relative;
  }

  #cell1 {
    width: 66%;
    float: left;
  }

  #cell2 {
    flex-direction: column;
    right: 10px;
    position: absolute;
    width: 33%;
    height: 100%;
  }

  #cell3 {
    width: 66%;
    float: left;
  }

  #cell4 { display: none;}
}

@media only screen and (max-width: 640px) {

  #cell2 {
    flex-direction: row;
    position: static;
    height: 100px;
  }

  #cell4 { display: none; }

  .container {
    flex-direction: row;
    flex-wrap: wrap;
    display: flex;
  }

  .cell {
    flex: 100%;
  }
}

<div class="container">
  <div class="cell" id="cell1">
    <span class="data">Image1</span>
    <span class="data">Info1</span>
  </div>
  <div class="cell" id="cell2">
    <span class="data">Image2</span>
    <span class="data">Info2</span>
  </div>
  <div class="cell" id="cell3">
    <span class="data">Image3</span>
    <span class="data">Info3</span>
  </div>
  <div class="cell" id="cell4">
    <span class="data">Image4</span>
    <span class="data">Info4</span>
  </div>
</div>

For it to work in tablet mode, you need to either make the container a flex column container, or use absolute or float to position the 2nd cell.

They all have limitations when it comes to responsiveness, where i.e. the flex column container solution will need a fixed height.

The one I find most usable is to stay with the default flex row set up, and combine it with absolute position on the 2nd cell.

This way the 1st and 3rd cell will continue being flex items, and benefit from its responsiveness.

In case of the 2nd cell's content making it higher than the 1st/3rd, one can then either allow it to scroll, or add a small script adjusting its parent's height.

Updated codepen

Stack snippet

div {
  box-sizing: border-box;
  width: 100%;
}

.container {
  display: flex;
  border: 1px solid red;
  flex-wrap: wrap;
  flex-direction: row;
  padding: 10px;
}

.cell {
  display: flex;
  flex: 50%;
  padding: 10px;
  border: 1px solid blue;
  height: 100px;
}

.data {
  width: 100%;
  justify-content: middle;
  flex: 1;
  border: 1px solid green;
}

@media only screen and (max-width: 640px) {

  #cell2 {
    flex-direction: row;
    position: static;
    height: 100px;
  }

  #cell4 { display: none; }

  .container {
    flex-direction: row;
    flex-wrap: wrap;
    display: flex;
  }

  .cell {
    flex: 100%;
  }
}

@media only screen and (min-width: 640px) and (max-width: 1024px) {
  .container {
    position: relative;
  }

  #cell1 {
    flex: 0 0 66%;
  }

  #cell2 {
    flex-direction: column;
    right: 10px;
    position: absolute;
    width: 33%;
    height: calc(100% - 20px);
  }

  #cell3 {
    flex:  0 0 66%;
  }

  #cell4 { display: none;}
}

<div class="container">
  <div class="cell" id="cell1">
    <span class="data">Image1</span>
    <span class="data">Info1</span>
  </div>
  <div class="cell" id="cell2">
    <span class="data">Image2</span>
    <span class="data">Info2</span>
  </div>
  <div class="cell" id="cell3">
    <span class="data">Image3</span>
    <span class="data">Info3</span>
  </div>
  <div class="cell" id="cell4">
    <span class="data">Image4</span>
    <span class="data">Info4</span>
  </div>
</div>


问:
Pexpect: Not able to redirect outputs to a file
Problem: Outputs from the device not getting redirected to a file.
Program: According to my program I have logged into one device and trying to collect few outputs.Here is the program.

```<code>     #!/usr/bin/python
     import pexpect
     import time
     import sys

     IP_Address= '10.197.225.226'
     Username = 'hey'
     Password= 'hey'

     session = pexpect.spawn("telnet " + IP_Address)
     result= session.expect(["Username:"])

     if result!=0:
      print("-----Failure connection")
      exit()
     session.sendline(Username)
     result= session.expect(["Password:"])
     session.sendline(Password)

     result= session.expect(["#"])
     print('success')

     C2=input('How many commands you want to enter:')
     for i in range (0,C2):
       C1=raw_input('Enter the commands:' )
       session.expect('#')
       session.sendline(C1)
       session.logfile= open("Result1.txt","w")

     print('Done')
</code>```

Please help!

Note: I am new here.

I am using Python 2.7.6 (default, Oct 26 2016, 20:30:19)
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.

答:
I fixed it myself.
Using a+ in open function.</p>

Body:
Problem: Outputs from the device not getting redirected to a file.
Program: According to my program I have logged into one device and trying to collect few outputs.Here is the program.

     #!/usr/bin/python
     import pexpect
     import time
     import sys

     IP_Address= '10.197.225.226'
     Username = 'hey'
     Password= 'hey'

     session = pexpect.spawn("telnet " + IP_Address)
     result= session.expect(["Username:"])

     if result!=0:
      print("-----Failure connection")
      exit()
     session.sendline(Username)
     result= session.expect(["Password:"])
     session.sendline(Password)

     result= session.expect(["#"])
     print('success')

     C2=input('How many commands you want to enter:')
     for i in range (0,C2):
       C1=raw_input('Enter the commands:' )
       session.expect('#')
       session.sendline(C1)
       session.logfile= open("Result1.txt","w")

     print('Done')

Please help!

Note: I am new here.

I am using Python 2.7.6 (default, Oct 26 2016, 20:30:19)
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.


答:
At first read about Android Runtime Permissions here .
If you deny your app from accessing media you won't be able to take photos.</p>

Title: java.lang.NullPointerException: while take photo

Body:
Im getting this error, when click deny permission in  "Allow app to access photos, media and files on your device ? "

    FATAL EXCEPTION: main
   Process: com.viantti.app, PID: 12349
   java.lang.NullPointerException: file
at android.net.Uri.fromFile(Uri.java:452)
at com.viantti.app.ProfilePage.getOutputMediaFileUri(ProfilePage.java:1011)
at com.viantti.app.ProfilePage.takePicture(ProfilePage.java:996)
at com.viantti.app.ProfilePage.access$2800(ProfilePage.java:87)
at com.viantti.app.ProfilePage$25.onClick(ProfilePage.java:1522)
at android.view.View.performClick(View.java:5205)
at android.view.View$PerformClick.run(View.java:21162)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5468)
at java.lang.reflect.Method.invoke(Native Method)
atcom.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:781)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:671)

java error line,

public Uri getOutputMediaFileUri(int type) {
    return Uri.fromFile(getOutputMediaFile(type));
}


问:
after build any window is opened c++
I did a disk partition to get Linux to be able to practise with c++ and it is impossible because I don't find the error I did install code blocks.
I tried to use the xterminal but it's a bit annoying just for practice!

Every time I try to run my program in codeblocks appears this message "Can't create output directory bin/Debug/" and I cant see my program... do I have to install anything else?

my program doesn't appear after build

答:
I think you don't have permission to the directory to build.

Change the build or output directory from settings of CodeBlocks then try...

Title: after build any window is opened c++


问:
WSO2 Governance Not Finding All Assets in JDBC Database
I'm new to WSO2 and working on an existing application that uses WSO2.
We load our database of assets into wso2 but not all of the assets show up in the store or publisher when queried.
It seems there is some disconnect between what is in the database/carbon and what can be seen in store/publisher.

the missing assets can be found by:

Calling the database directly

looking them up in carbon

using the store or publisher url with the asset id

the governance rest api through id only

the assets are missing in:

doing searches in the store/publisher gui

doing searches with the governance api

All the ones missing have invalid asset names according to our rxt definitions. I removed these validations in carbon but still was not able to find them.

We have validations in the rxt files for asset names, would this affect what is seen in store/publisher?

Is there a way to sync up the governance registry with the database so that it would show all the assets in the store and publisher?

Any help is much appreciated!!

答:
I'm facing the same problem with store/publisher. After searching for a solution, we found some info about this issue. WSO2 is not indexing some assets in Solr.

You could try to reindex the assets with this steps:

1 - Backup the solr folder which resides in /solr and remove from API Manager home location.

2 - Open /repository/conf/registry.xml

3 - Under indexingConfiguration tag there is a value called lastAccessTimeLocation.

Default value is

/_system/local/repository/components/org.wso2.carbon.registry/indexing/lastaccesstime

Change that value to

/_system/local/repository/components/org.wso2.carbon.registry/indexing/lastaccesstime1

4 - Restart the server

For me this didn't work, but in some questions here many people said that could be the best solution for this issue.

WSO2 loss APIs after changes in docker container

WSO2 API Manager issues with solr


问:
Unable to send ajax response to the controller in yii2
I have a view in which I have a detailview and a gridview. In my gridview I have a checkbox. And on clicking on any check box I am able to get the id of the column(s) selected. Below is my view

```<code>//my DetailView
?= GridView::widget([
         'dataProvider' => $dataProvider,
          /*'filterModel' => $searchModel,*/

          'columns' => [

         ['class' => 'yii\grid\CheckboxColumn', 'checkboxOptions' => function($d) {
             return ['value' => $d['meter_id']];
         }],

         'Meter_Serial_Number',
         'Issued_To',
         'Store',
       ],
]); ?>
<a href="<?= URL::toRoute(['ogpheader/viewsetpdf', 'id'=>$model->id])?>" name="redirect" class="btn btn-primary" id="myid">Set PDF</a>
</code>```

UI

Note:

The detail view is coming from the model and gridview is generated from query to view and then select the data.

Now I have placed an ajax call that will send the data to the controller.

```<code><?php
$url = Url::toRoute(['/ogpheader/viewsetpdf']);
$script = <<< JS
$(document).ready(function () {

$('#myid').click(function() {
 var strValue = "";

    $('input[name="selection[]"]:checked').each(function() {

    if(strValue!="")
        {
        strValue = strValue + " , " + this.value;

        }
    else
        strValue = this.value;

});
$.ajax({
     url: '$url',
     data: {
           data: strValue,
     },
     type: 'post',
     dataType: 'json',
     success: function(data) {
        alert(data);
     },
  });
 })
});

JS;
$this->registerJs($script, static::POS_END);
?>
</code>```

Action Controller

```<code> public function actionViewsetpdf($id)
{
    $model = $this->findModel($id);
    print_r($model);
    $data = "";
    if(isset($_POST['data']))
    {
        $data = json_decode($_POST['data']);
        print_r($data);
    }
    else{
        echo 'no data';
    }
    exit();

}
</code>```

The $id is the id of the model i.e. the id of my detail view. I want to pass both my detail view and grid view selected items to process things forward.

Now when i click on Set PDF button I got the following result

In output image I am getting the details of my model i.e. my detail view items but for my selected grid view items I am getting no data. I have searched for it but unable to find the solution that helps me

Update 1

Changed my JS and ajax call

```<code>$('#myid').on('click',function(e) {
e.preventDefault();
 var strValue = "";
    $('input[name="selection[]"]:checked').each(function() {

    if(strValue!="")
        {
        strValue = strValue + " , " + this.value;

        }
    else
        strValue = this.value;

});
   // alert(strValue);
  $.ajax({
     url: '$url',
     type: 'POST',
     dataType: 'json',
     data: 'data='+ strValue,
     success: function(data) {
        alert(data);
      },
    });
   })
  });
</code>```

The output in my Xhr I am getting is

```<code>common\models\Ogpheader Object( [_attributes:yii\db\BaseActiveRecord:private] => Array ( [id] => 54 [created_by] => 12 [created_at] => 2017-11-13 05:26:04 [updated_at] => [canceled_at] => [store_id] => 10 [status] => Prepared [issuer] => 88 [admin_incharge] => Faisal [project_manager] => Ali ) [_oldAttributes:yii\db\BaseActiveRecord:private] => Array ( [id] => 54 [created_by] => 12 [created_at] => 2017-11-13 05:26:04 [updated_at] => [canceled_at] => [store_id] => 10 [status] => Prepared [issuer] => 88 [admin_incharge] => Faisal [project_manager] => Ali ) [_related:yii\db\BaseActiveRecord:private] => Array ( ) [_errors:yii\base\Model:private] => [_validators:yii\base\Model:private] => [_scenario:yii\base\Model:private] => default [_events:yii\base\Component:private] => Array ( ) [_behaviors:yii\base\Component:private] => Array ( ))array(1) { ["data"]=> string(26) "99 , 100 , 101 , 102 , 103"}
</code>```

But when I remove the e.preventDefault() then the page is redirected to the another view and the response i get is

```<code>common\models\Ogpheader Object( [_attributes:yii\db\BaseActiveRecord:private] => Array ( [id] => 54 [created_by] => 12 [created_at] => 2017-11-13 05:26:04 [updated_at] => [canceled_at] => [store_id] => 10 [status] => Prepared [issuer] => 88 [admin_incharge] => Faisal [project_manager] => Ali ) [_oldAttributes:yii\db\BaseActiveRecord:private] => Array ( [id] => 54 [created_by] => 12 [created_at] => 2017-11-13 05:26:04 [updated_at] => [canceled_at] => [store_id] => 10 [status] => Prepared [issuer] => 88 [admin_incharge] => Faisal [project_manager] => Ali ) [_related:yii\db\BaseActiveRecord:private] => Array ( ) [_errors:yii\base\Model:private] => [_validators:yii\base\Model:private] => [_scenario:yii\base\Model:private] => default [_events:yii\base\Component:private] => Array ( ) [_behaviors:yii\base\Component:private] => Array ( )) no data
</code>```

Any help would be highly appreciated.

答:
I think $url is not available into js code,
for example you can get the url via jquery when you click on #myid link like this way :</p>

```<code>var url;
$('#myid').click(function() {
 var strValue = "";
   url = $(this).attr("href");
    $('input[name="selection[]"]:checked').each(function() {

    if(strValue!="")
        {
        strValue = strValue + " , " + this.value;

        }
    else
        strValue = this.value;

   $.ajax({
     url: url,
     data: {
           data: strValue,
     },
     type: 'post',
     dataType: 'json',
     success: function(data) {
        alert(data);
     },
  });
 });
</code>```

Body:
I have a view in which I have a detailview and a gridview. In my gridview I have a checkbox. And on clicking on any check box I am able to get the id of the column(s) selected. Below is my view

//my DetailView
?= GridView::widget([
         'dataProvider' => $dataProvider,
          /*'filterModel' => $searchModel,*/

          'columns' => [

         ['class' => 'yii\grid\CheckboxColumn', 'checkboxOptions' => function($d) {
             return ['value' => $d['meter_id']];
         }],

         'Meter_Serial_Number',
         'Issued_To',
         'Store',
       ],
]); ?>
<a href="<?= URL::toRoute(['ogpheader/viewsetpdf', 'id'=>$model->id])?>" name="redirect" class="btn btn-primary" id="myid">Set PDF

UI

Note:

The detail view is coming from the model and gridview is generated from query to view and then select the data.

Now I have placed an ajax call that will send the data to the controller.

<?php
$url = Url::toRoute(['/ogpheader/viewsetpdf']);
$script = <<< JS
$(document).ready(function () {

$('#myid').click(function() {
 var strValue = "";

    $('input[name="selection[]"]:checked').each(function() {

    if(strValue!="")
        {
        strValue = strValue + " , " + this.value;

        }
    else
        strValue = this.value;

});
$.ajax({
     url: '$url',
     data: {
           data: strValue,
     },
     type: 'post',
     dataType: 'json',
     success: function(data) {
        alert(data);
     },
  });
 })
});

JS;
$this->registerJs($script, static::POS_END);
?>

Action Controller

 public function actionViewsetpdf($id)
{
    $model = $this->findModel($id);
    print_r($model);
    $data = "";
    if(isset($_POST['data']))
    {
        $data = json_decode($_POST['data']);
        print_r($data);
    }
    else{
        echo 'no data';
    }
    exit();

}

The $id is the id of the model i.e. the id of my detail view. I want to pass both my detail view and grid view selected items to process things forward.

Now when i click on Set PDF button I got the following result

In output image I am getting the details of my model i.e. my detail view items but for my selected grid view items I am getting no data. I have searched for it but unable to find the solution that helps me

Update 1

Changed my JS and ajax call

$('#myid').on('click',function(e) {
e.preventDefault();
 var strValue = "";
    $('input[name="selection[]"]:checked').each(function() {

    if(strValue!="")
        {
        strValue = strValue + " , " + this.value;

        }
    else
        strValue = this.value;

});
   // alert(strValue);
  $.ajax({
     url: '$url',
     type: 'POST',
     dataType: 'json',
     data: 'data='+ strValue,
     success: function(data) {
        alert(data);
      },
    });
   })
  });

The output in my Xhr I am getting is

common\models\Ogpheader Object( [_attributes:yii\db\BaseActiveRecord:private] => Array ( [id] => 54 [created_by] => 12 [created_at] => 2017-11-13 05:26:04 [updated_at] => [canceled_at] => [store_id] => 10 [status] => Prepared [issuer] => 88 [admin_incharge] => Faisal [project_manager] => Ali ) [_oldAttributes:yii\db\BaseActiveRecord:private] => Array ( [id] => 54 [created_by] => 12 [created_at] => 2017-11-13 05:26:04 [updated_at] => [canceled_at] => [store_id] => 10 [status] => Prepared [issuer] => 88 [admin_incharge] => Faisal [project_manager] => Ali ) [_related:yii\db\BaseActiveRecord:private] => Array ( ) [_errors:yii\base\Model:private] => [_validators:yii\base\Model:private] => [_scenario:yii\base\Model:private] => default [_events:yii\base\Component:private] => Array ( ) [_behaviors:yii\base\Component:private] => Array ( ))array(1) { ["data"]=> string(26) "99 , 100 , 101 , 102 , 103"}

But when I remove the e.preventDefault() then the page is redirected to the another view and the response i get is

common\models\Ogpheader Object( [_attributes:yii\db\BaseActiveRecord:private] => Array ( [id] => 54 [created_by] => 12 [created_at] => 2017-11-13 05:26:04 [updated_at] => [canceled_at] => [store_id] => 10 [status] => Prepared [issuer] => 88 [admin_incharge] => Faisal [project_manager] => Ali ) [_oldAttributes:yii\db\BaseActiveRecord:private] => Array ( [id] => 54 [created_by] => 12 [created_at] => 2017-11-13 05:26:04 [updated_at] => [canceled_at] => [store_id] => 10 [status] => Prepared [issuer] => 88 [admin_incharge] => Faisal [project_manager] => Ali ) [_related:yii\db\BaseActiveRecord:private] => Array ( ) [_errors:yii\base\Model:private] => [_validators:yii\base\Model:private] => [_scenario:yii\base\Model:private] => default [_events:yii\base\Component:private] => Array ( ) [_behaviors:yii\base\Component:private] => Array ( )) no data

Any help would be highly appreciated.

Body:
I think $url is not available into js code,
for example you can get the url via jquery when you click on #myid link like this way :

var url;
$('#myid').click(function() {
 var strValue = "";
   url = $(this).attr("href");
    $('input[name="selection[]"]:checked').each(function() {

    if(strValue!="")
        {
        strValue = strValue + " , " + this.value;

        }
    else
        strValue = this.value;

   $.ajax({
     url: url,
     data: {
           data: strValue,
     },
     type: 'post',
     dataType: 'json',
     success: function(data) {
        alert(data);
     },
  });
 });