问:
Jackson Ignores Custom Field Deserializer When Value is "null"
I wrote a custom deserializer for Jackson for a certain field (follows). I use it with this annotation:

```<code>@JsonDeserialize(using = TokenTypeDeserializer.class)
TokenType type;
</code>```

It seems to work fine, as long as I pass a value in the field. When I started testing it, I passed the field with null as value. In this case it ignored my custom deserializer, skipped it and just put null as the value. It's a problem because I have a unique way of action when I get null in that field.

How can I force it to go through my custom deserializer when the value is null?

This is the custom deserializer I wrote:

```<code>public static class TokenTypeDeserializer extends StdDeserializer<TokenType> {

    public TokenTypeDeserializer() {
        this(null);
    }

    protected TokenTypeDeserializer(Class<?> vc) {
        super(vc);
    }

    @Override
    public TokenType deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        ObjectCodec oc = p.getCodec();
        JsonNode node = oc.readTree(p);
        String type = node.asText();

        TokenType tokenType = TokenType.getTokenTypeFromString(type);
        return tokenType;
    }
}
</code>```

I looked a little bit into the ObjectMapper code, and saw this:

```<code>public final Object deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException
{
    JsonToken t = jp.getCurrentToken();
    if (t == JsonToken.VALUE_NULL) {
        return (_nullProvider == null) ? null : _nullProvider.nullValue(ctxt);
    }
    if (_valueTypeDeserializer != null) {
        return _valueDeserializer.deserializeWithType(jp, ctxt, _valueTypeDeserializer);
    }
    return _valueDeserializer.deserialize(jp, ctxt);
}
</code>```

It seems that the ObjectMapper first checks if the value is null, and if thus the case, returns a default value. Any ideas on how to force it to go through my deserializer?

答:
According to this discussion, looks like you can't provide an alternative for null unless it's a primitive type (which can't be null).

All in all this is a common behavior, if you are deserializing a null value into a nullable type, null is the value you should get there.

ContentLicense: CC BY-SA 4.0

Body:
I wrote a custom deserializer for Jackson for a certain field (follows). I use it with this annotation:

@JsonDeserialize(using = TokenTypeDeserializer.class)
TokenType type;

It seems to work fine, as long as I pass a value in the field. When I started testing it, I passed the field with null as value. In this case it ignored my custom deserializer, skipped it and just put null as the value. It's a problem because I have a unique way of action when I get null in that field.

How can I force it to go through my custom deserializer when the value is null?

This is the custom deserializer I wrote:

public static class TokenTypeDeserializer extends StdDeserializer<TokenType> {

    public TokenTypeDeserializer() {
        this(null);
    }

    protected TokenTypeDeserializer(Class<?> vc) {
        super(vc);
    }

    @Override
    public TokenType deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        ObjectCodec oc = p.getCodec();
        JsonNode node = oc.readTree(p);
        String type = node.asText();

        TokenType tokenType = TokenType.getTokenTypeFromString(type);
        return tokenType;
    }
}

I looked a little bit into the ObjectMapper code, and saw this:

public final Object deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException
{
    JsonToken t = jp.getCurrentToken();
    if (t == JsonToken.VALUE_NULL) {
        return (_nullProvider == null) ? null : _nullProvider.nullValue(ctxt);
    }
    if (_valueTypeDeserializer != null) {
        return _valueDeserializer.deserializeWithType(jp, ctxt, _valueTypeDeserializer);
    }
    return _valueDeserializer.deserialize(jp, ctxt);
}

It seems that the ObjectMapper first checks if the value is null, and if thus the case, returns a default value. Any ideas on how to force it to go through my deserializer?


来源: stackexchange

问:
How to ensure atomic transactions for update operations to different NoSQL data tables?

Problem is like the picture, say my application needs to write to two different DynamoDB tables, how I ensure that I don't have data inconsistency when one of my operation fails?

答:
There is a transaction library for DynamoDB

However, note that this is quite expensive (7x normal cost, I believe), and in general it is better to try and design your database in a way that would not require such transactions.

Alternatively, you can have an AWS lambda listening to one table, and triggering update to a second table when update happens on first one.

Finally, if you need such relations, consider using RDS, instead of DynamoDB

ContentLicense: CC BY-SA 3.0


问:
Trying to parse Math Expressions JSON from Wiki API
I'm parsing in my app the JSON from Wiki api using volley requests with no problem, except from the following one.  I'm need to parse these expressions along with the text.

I'm using this URL (for example):

https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&explaintext=&titles=%20Partition%20function%20(statistical%20mechanics)

This is a problematic part in the article:

The parsing works juse fine, but when it comes to a math expression, it looks like this in the API:

and in my app, I get along with the text the" {displaystyle = "part.
I don't get the "/n" or something.
In my app, it looks like this:

I get a lot of spaces and this "{displaystyle". The text freaks out. Is there something that I can do in order to overcome this? I couldnt find an api query for this, but maybe I can do something with the JSON respone itself.

Thanks.

答:
formatversion=2

API:Data formats#JSON parameters

Specify formatversion=2 for to get json (and php) format responses in a cleaner format. This also encodes most non-ASCII characters as UTF-8. MW 1.25+

So: https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&titles=Partition%20function%20(statistical%20mechanics)&formatversion=2 returns JSON containing <math> markup like:

```<code><annotation encoding=\"application/x-tex\">{\\displaystyle \\beta }</annotation>
</code>```

which might be more useful.

More information about formatversion=2 can be found at API:JSON version 2

format=json suffers from a number of shortcomings that make it more difficult to use than necessary. Many of these arise because XML was the original output format and the underlying data structure of API responses was designed around this.

To address this, after discussion MediaWiki 1.25 introduces a new JSON response format. It is not the default, you only get results in the new format if you specify formatversion=2, and it's only for the json and php formats (and their human-readable jsonfm and phpfm variants).

Body:
formatversion=2

API:Data formats#JSON parameters

Specify formatversion=2 for to get json (and php) format responses in a cleaner format. This also encodes most non-ASCII characters as UTF-8. MW 1.25+

So: https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&titles=Partition%20function%20(statistical%20mechanics)&formatversion=2 returns JSON containing <math> markup like:

<annotation encoding=\"application/x-tex\">{\\displaystyle \\beta }</annotation>

which might be more useful.

More information about formatversion=2 can be found at API:JSON version 2

format=json suffers from a number of shortcomings that make it more difficult to use than necessary. Many of these arise because XML was the original output format and the underlying data structure of API responses was designed around this.

To address this, after discussion MediaWiki 1.25 introduces a new JSON response format. It is not the default, you only get results in the new format if you specify formatversion=2, and it's only for the json and php formats (and their human-readable jsonfm and phpfm variants).


问:
Create list with unique id in Java and manipulate it
I want to create a programm that creates a list that looks like this

```<code>ID: 1
Name: Example
Surname: Example
email: example

//New list

ID: 2
Name: Example
Surname: Example
email: example
</code>```

and then when i want to change something (like Name: ) i'd like to change it by id, so it can only be changed inside the list with ID: 2

答:
You should use a HashMap.

Create a class (let's class it YourClass) that contains ID, name, surname and email instance variables.

Then create a HashMap where the key is the identifier and the value is YourClass:

```<code>Map<Integer,YourClass> map = new HashMap<>();
map.put(objectOfYourClassWithID1.getID(),objectOfYourClassWithID1);
map.put(objectOfYourClassWithID2.getID(),objectOfYourClassWithID2);
if (map.containsKey(2)) {
    map.get(2).setSomeProperty(newValue); // this will only change the object whose ID is 2
}
</code>```

Body:
I want to create a programm that creates a list that looks like this

ID: 1
Name: Example
Surname: Example
email: example

//New list

ID: 2
Name: Example
Surname: Example
email: example

and then when i want to change something (like Name: ) i'd like to change it by id, so it can only be changed inside the list with ID: 2

Body:
You should use a HashMap.

Create a class (let's class it YourClass) that contains ID, name, surname and email instance variables.

Then create a HashMap where the key is the identifier and the value is YourClass:

Map<Integer,YourClass> map = new HashMap<>();
map.put(objectOfYourClassWithID1.getID(),objectOfYourClassWithID1);
map.put(objectOfYourClassWithID2.getID(),objectOfYourClassWithID2);
if (map.containsKey(2)) {
    map.get(2).setSomeProperty(newValue); // this will only change the object whose ID is 2
}


问:
Google Map not loading with separate files
I can't see the google map on my monitor, but when I put all the code in a single html file and use script tags it works.

Index.html file is:

```<code><!DOCTYPE html>
<html>
  <head>
    <title>Simple Map</title>
    <meta name="viewport" content="initial-scale=1.0">
    <meta charset="utf-8">
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>
  <body>
    <div id="map"></div>

    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBIpWlWVDAqVEyW20SX6MfThL-iz9IWeQA&callback=initMap"
    ></script>
  </body>
</html>
</code>```

Script.js file is:

```<code>function initMap() {

    var map;
            map = new google.maps.Map(document.getElementById('map'),
            {
              center: {  lat: -34.397,
                         lng: 150.644
                      },
              zoom: 8
            }
            );
          }
</code>```

style.css file is:

```<code>* element that contains the map. */
  #map {
    height: 100%;
  }
  /* Optional: Makes the sample page fill the window. */
  html, body {
    height: 100%;
    margin: 0;
    padding: 0;
  }
</code>```

答:
According to the documentation : Google Maps APIs, just put your JavaScript (script.js) after your map.

```<code><div id="map"></div>
<script src="script.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBIpWlWVDAqVEyW20SX6MfThL-iz9IWeQA&callback=initMap" async defer></script>
</code>```

Edit : Don't forget "async defer" at the end of the second script.

Body:
I can't see the google map on my monitor, but when I put all the code in a single html file and use script tags it works.

Index.html file is:

<!DOCTYPE html>

    <title>Simple Map</title>
    <meta name="viewport" content="initial-scale=1.0">
    <meta charset="utf-8">
    <link rel="stylesheet" href="style.css">

Script.js file is:

function initMap() {

    var map;
            map = new google.maps.Map(document.getElementById('map'),
            {
              center: {  lat: -34.397,
                         lng: 150.644
                      },
              zoom: 8
            }
            );
          }

style.css file is:

* element that contains the map. */
  #map {
    height: 100%;
  }
  /* Optional: Makes the sample page fill the window. */
  html, body {
    height: 100%;
    margin: 0;
    padding: 0;
  }

Body:
According to the documentation : Google Maps APIs, just put your JavaScript (script.js) after your map.

<div id="map"></div>
<script src="script.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBIpWlWVDAqVEyW20SX6MfThL-iz9IWeQA&callback=initMap" async defer></script>

Edit : Don't forget "async defer" at the end of the second script.


问:
Css div selector multiple classes
I am working on a wordpress theme and I have a this code in HTML:

```<code><body>
        <div class="container-fluid mytheme-container" >
        <div class="container-fluid col-lg-offset-5 col-lg-7 404page">
                    <p id="404">404</p>
                    <p id="page-not-found">Page not found... :(</p>
        </div>
        </div>
</body>
</code>```

I want to add height to the last div and I thought my css in this way:

```<code>body > div.container-fluid.mytheme-container > div.container-fluid.col-lg-offset-5.col-lg-7.404page {
    height: 100vmin;
}
</code>```

That doesn't work, just if I let the selector like this:

```<code>body > div.container-fluid.mytheme-container > div {

}
</code>```

But I think that this will apply to every child of mytheme-container  and I don't want that. So, how can I get the selector for that div ( 404page ) in a more specific way than the last one?

答:
I think your issue is the class '404page'.  class names shouldn't begin with a number.

If you can you should change the class name to 'page404' or something similar,  if not, I think you can still work with the other classes as selectors (without 404page).

See working example here:

body > div.container-fluid.mytheme-container >  div.container-fluid.col-lg-offset-5.col-lg-7 {
    color:red;
}
//same, but without the 404page class```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
        <div class="container-fluid mytheme-container" >
        <div class="container-fluid col-lg-offset-5 col-lg-7 404page">
                    <p id="404">404</p>
                    <p id="page-not-found">Page not found... :(</p>
        </div>
        </div>
</body> </code>```

Title: Css div selector multiple classes

Body:
I am working on a wordpress theme and I have a this code in HTML:

404

Page not found... :(

I want to add height to the last div and I thought my css in this way:

body > div.container-fluid.mytheme-container > div.container-fluid.col-lg-offset-5.col-lg-7.404page {
    height: 100vmin;
}

That doesn't work, just if I let the selector like this:

body > div.container-fluid.mytheme-container > div {

}

But I think that this will apply to every child of mytheme-container  and I don't want that. So, how can I get the selector for that div ( 404page ) in a more specific way than the last one?

Body:
I think your issue is the class '404page'.  class names shouldn't begin with a number.

If you can you should change the class name to 'page404' or something similar,  if not, I think you can still work with the other classes as selectors (without 404page).

See working example here:

body > div.container-fluid.mytheme-container >  div.container-fluid.col-lg-offset-5.col-lg-7 {
    color:red;
}
//same, but without the 404page class

<body>
        <div class="container-fluid mytheme-container" >
        <div class="container-fluid col-lg-offset-5 col-lg-7 404page">
                    <p id="404">404</p>
                    <p id="page-not-found">Page not found... :(</p>
        </div>
        </div>
</body>


问:
How to make an if statement if your pointer is getting garbage
Hi everyone I have a problem taking care of a malfunction, I'm building a dynamic linked list which connects structures with *next and *previous,
now if the structures are unable to connect (long story) I need to print "the way does not exist" now I've made an if statement

```<code>    temp = point_start; // point_start is the head of the list
condition = 2;
for(i=0;i<gagnum;i++) //gagnum is the number of structures
{
    temp=point_start->previous; // previous is the pointer of the previous structure.

    if (temp != 0xcdcdcdcd) // ------> is this legal?
        condition = 1;
    else
    {
        printf("no route found ")
        condition = 2;
        break;
    }

}
</code>```

I have an if statement which says "if (temp != 0xcdcdcdcd)" so when it gets garbage I put out the message and stop the program, is this legal to use? is there a better way to do this? thank you so much for your help!

答:
Wikipedia writes for 0xcdcdcdcd

Used by Microsoft's C/C++ debug malloc() function to mark uninitialized heap memory, usually returned from HeapAlloc()

So I guess you malloc a node and not initializing the pointers.

Body:
Hi everyone I have a problem taking care of a malfunction, I'm building a dynamic linked list which connects structures with *next and *previous,
now if the structures are unable to connect (long story) I need to print "the way does not exist" now I've made an if statement

    temp = point_start; // point_start is the head of the list
condition = 2;
for(i=0;i<gagnum;i++) //gagnum is the number of structures
{
    temp=point_start->previous; // previous is the pointer of the previous structure.

    if (temp != 0xcdcdcdcd) // ------> is this legal?
        condition = 1;
    else
    {
        printf("no route found ")
        condition = 2;
        break;
    }

}

I have an if statement which says "if (temp != 0xcdcdcdcd)" so when it gets garbage I put out the message and stop the program, is this legal to use? is there a better way to do this? thank you so much for your help!


问:
getting node value exception
```<code><amount currency="USD">1000500</amount>
</code>```

while parsing above string i am getting only attribute value .when i try to get node value null pointer exception

for getting node value using

```<code> NodeList amountList= estimateElement.getElementsByTagName("amount");
 Element amtElement= (Element)amountList.item(0);
 String amount=amtElement.getFirstChild().getnodevalue()
</code>```

Thanks in advance

Aswan

答:
Try using the getTextContent() method:

```<code>NodeList amountList= estimateElement.getElementsByTagName("amount");
Element amtElement= (Element)amountList.item(0);
String amount=amtElement.getTextContent();
</code>```

See here for more info.

ContentLicense: CC BY-SA 2.5

Title: getting node value exception

Body:
<amount currency="USD">1000500</amount>

while parsing above string i am getting only attribute value .when i try to get node value null pointer exception

for getting node value using

 NodeList amountList= estimateElement.getElementsByTagName("amount");
 Element amtElement= (Element)amountList.item(0);
 String amount=amtElement.getFirstChild().getnodevalue()

Thanks in advance

Aswan

Body:
Try using the getTextContent() method:

NodeList amountList= estimateElement.getElementsByTagName("amount");
Element amtElement= (Element)amountList.item(0);
String amount=amtElement.getTextContent();

See here for more info.


问:
Get current week start and end date in Java - (MONDAY TO SUNDAY)
Today is 2014-04-06 (Sunday).

The output I get from using the code below is:

```<code>Start Date = 2014-04-07
End Date = 2014-04-13
</code>```

This is the output I would like to get instead:

```<code>Start Date = 2014-03-31
End Date = 2014-04-06
</code>```

How can I achieve this?

This is the code I have completed so far:

```<code>// Get calendar set to current date and time
Calendar c = GregorianCalendar.getInstance();

System.out.println("Current week = " + Calendar.DAY_OF_WEEK);

// Set the calendar to monday of the current week
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println("Current week = " + Calendar.DAY_OF_WEEK);

// Print dates of the current week starting on Monday
DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
String startDate = "", endDate = "";

startDate = df.format(c.getTime());
c.add(Calendar.DATE, 6);
endDate = df.format(c.getTime());

System.out.println("Start Date = " + startDate);
System.out.println("End Date = " + endDate);
</code>```

答:
```<code>Calendar privCalendar = Calendar.getInstance();
Date fdow, ldow;
int dayofWeek = privCalendar.get ( Calendar.DAY_OF_WEEK );
Date fdow, ldow;

                    if( dayofWeek == Calendar.SUNDAY ) {

                        privCalendar.add ( Calendar.DATE, -1 * (dayofWeek -
                                Calendar.MONDAY ) - 7 );

                        fdow = privCalendar.getTime();

                        privCalendar.add( Calendar.DATE, 6 );

                        ldow = privCalendar.getTime();
                    } else {

                        privCalendar.add ( Calendar.DATE, -1 * (dayofWeek -
                                Calendar.MONDAY ) );

                        fdow = privCalendar.getTime();

                        privCalendar.add( Calendar.DATE, 6 );

                        ldow = privCalendar.getTime();
                    }
</code>```

Body:
Today is 2014-04-06 (Sunday).

The output I get from using the code below is:

Start Date = 2014-04-07
End Date = 2014-04-13

This is the output I would like to get instead:

Start Date = 2014-03-31
End Date = 2014-04-06

How can I achieve this?

This is the code I have completed so far:

// Get calendar set to current date and time
Calendar c = GregorianCalendar.getInstance();

System.out.println("Current week = " + Calendar.DAY_OF_WEEK);

// Set the calendar to monday of the current week
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println("Current week = " + Calendar.DAY_OF_WEEK);

// Print dates of the current week starting on Monday
DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
String startDate = "", endDate = "";

startDate = df.format(c.getTime());
c.add(Calendar.DATE, 6);
endDate = df.format(c.getTime());

System.out.println("Start Date = " + startDate);
System.out.println("End Date = " + endDate);


问:
Preventing fixed footer from overlapping content
I've fixed my footer DIV to the bottom of the viewport as follows:

```<code>#Footer
{
    position: fixed;
    bottom: 0;
}
</code>```

This works well if there isn't much content on the page. However, if the content fills the full height of the page (i.e. the vertical scroll bar is visible) the footer overlaps the content, which I don't wont.

How can I get the footer to stick to the bottom of the viewport, but never overlap the content?

答:
This is another solution which I use using jQuery. To get it set-up, you don't need to code much, and you only need HTML.

<!doctype html>

  <meta charset="utf-8">
  <title>Your title</title>
  <link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">

Your Header

         Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...

Your Footer

```

This is from w3schools - fixed toolbars, but I thought it could be more useful than some other answers.

Body:
I've fixed my footer DIV to the bottom of the viewport as follows:

#Footer
{
    position: fixed;
    bottom: 0;
}

This works well if there isn't much content on the page. However, if the content fills the full height of the page (i.e. the vertical scroll bar is visible) the footer overlaps the content, which I don't wont.

How can I get the footer to stick to the bottom of the viewport, but never overlap the content?

Body:
This is another solution which I use using jQuery. To get it set-up, you don't need to code much, and you only need HTML.

<!doctype html>
<html>

<head>
  <meta charset="utf-8">
  <title>Your title</title>
  <link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
  <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
  <script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
</head>

<body>
  <div data-role="page">
    <div data-role="header" data-position="fixed">
      <h1>Your Header</h1>
    </div>
    <div data-role="main" class="ui-content">
      <p style="font-size: 300%;">
         Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
        Some text to enable scrolling...
      </p>
    </div>
    <div data-role="footer" data-position="fixed">
      <h1>Your Footer</h1>
    </div>
  </div>
</body>

</html>

This is from w3schools - fixed toolbars, but I thought it could be more useful than some other answers.


答:
Classes and IDs should not start with numbers. While it's possible to make them work, it's a hassle and kind of goes against the spirit of "identifiers" in every other programming language anyway.

Best to keep to the more-or-less global definition of "identifier", and use page-404 or similar - besides, that's more consistent with your other classes container-fluid, col-lg-offset-5 and so on.

Title: Css div selector multiple classes


问:
Buttons got lock again after unlocking another button
I am having issue regarding the buttons. After succeeding unlocking level 2 based on reaching the score from playing Level 1. I proceed to test Level 2 and ensure it can unlock Level 3 based on the score requirement, however, after succeed in unlocking Level 3. Level 2 become lock again. I am really not sure what went wrong. I may have got my logic wrong or something. It should had already remain enabled(true) after the Level 2 button had been set to enabled true. I will show my code related. Anyone who knows the answer please guide me.

This is in the LevelPage activity where it contains all the Level buttons for the user to choose which level to play, i will show just the relevant since the code in this activity is too long.

```<code>    DBHelper db = new DBHelper(LevelPage.this);
    HashMap<String,String> data = db.getData();
    final String level1Score = data.get("LEVEL1");
    final String level2Score = data.get("LEVEL2");
    final String level3Score = data.get("LEVEL3");
    final String level4Score = data.get("LEVEL4");

    btnLevel1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            clickSound.start();
            Intent intent = new Intent(LevelPage.this, Level1.class);
            startActivity(intent);
        }
    });

    if (level1Score != null && level1Score.equals("30")) {
        btnLevel2.setEnabled(true);
    btnLevel2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
                clickSound.start();
                Intent intent = new Intent(LevelPage.this, Level2.class);
                startActivity(intent);

            }
        });

    } else {
        btnLevel2.setEnabled(false);
    }

    if (level2Score != null && level2Score.equals("35")) {
        btnLevel3.setEnabled(true);
        btnLevel3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clickSound.start();
                Intent intent = new Intent(LevelPage.this, Level3.class);
                startActivity(intent);

            }
        });
    } else {
        btnLevel3.setEnabled(false);
    }
</code>```

This is the Level2 page where the user plays the game and ensure to score 35 points to unlock:

```<code>else if (score == 35) {
                DBHelper db = new DBHelper(Level2.this);
                db.saveData(2,"35");
                AlertDialog.Builder builder = new
AlertDialog.Builder(Level2.this);
                builder.setTitle("Level 2 Complete!");
                builder.setMessage("You have won! You have unlock level 3!
You can proceed to Level 3 or go back.");
                builder.setPositiveButton("Unlock", new
DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(Level2.this,
LevelPage.class);
                        startActivity(intent);
                        finish();
                    }
                });
</code>```

This is the SQLite Database to save and get the score data:

```<code> private static final int DATABASE_VERSION = 1;
 private static final String DATABASE_NAME = "Level";
 private static final String USERTABLE = "USER_INFO";
 private static final String KEY_ID = "id";
 private static final String LEVEL1 = "LEVEL1";
 private static final String LEVEL2 = "LEVEL2";
 private static final String LEVEL3 = "LEVEL3";
 private static final String LEVEL4 = "LEVEL4";

private static final String CREATE_TABLE_USER = "CREATE TABLE IF NOT EXISTS "
        + USERTABLE + "(" + KEY_ID + " INTEGER PRIMARY KEY,"
        + LEVEL1 + " TEXT,"
        + LEVEL2 + " TEXT,"
        + LEVEL3 + " TEXT,"
        + LEVEL4 + " TEXT " + ");";

/*private static final String CREATE_TABLE_USER = "CREATE TABLE IF NOT EXISTS "
        + USERTABLE + "(" + KEY_ID + " INTEGER PRIMARY KEY," + LEVEL1 + " TEXT,"
        + LEVEL2 + " TEXT"+");"; */

private static final String SQL_DELETE_ENTRIES =
        "DROP TABLE IF EXISTS " + USERTABLE;

public DBHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(CREATE_TABLE_USER);
}

//to save score in db according to the level
public void saveData(int level,String score){
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues data = new ContentValues();
    switch(level){
        case 1:
            data.put(LEVEL1, score);
            break;
        case 2:
            data.put(LEVEL2,score);
            break;
        case 3:
            data.put(LEVEL3,score);
            break;
        case 4:
            data.put(LEVEL4,score);
            break;
    }
    db.insert(USERTABLE,null,data);
    db.close();
}

//to get score from db
//you can modify this function if you want to get score for a specific level
public HashMap<String,String> getData(){
    HashMap<String,String> scoreMap = new HashMap<>();
    String selectQuery = "SELECT  * FROM " + USERTABLE ;
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    if (cursor.moveToFirst()) {
        do {

            scoreMap.put(LEVEL1,cursor.getString(cursor.getColumnIndex(LEVEL1)));
            scoreMap.put(LEVEL2,cursor.getString(cursor.getColumnIndex(LEVEL2)));
            scoreMap.put(LEVEL3,cursor.getString(cursor.getColumnIndex(LEVEL3)));
            scoreMap.put(LEVEL4,cursor.getString(cursor.getColumnIndex(LEVEL4)));
        } while (cursor.moveToNext());
    }
    cursor.close();
    return scoreMap;

}
</code>```

Note: The same also applies to Level 3 and Level 4. Even after Level 4 is unlock, Level 3 also got lock again along with Level 2. The result keep on repeating where it unlock next Level but lock the previous Level all of a sudden

To put SharedPrefences:

```<code> else if (score == 30) {
                /*DBHelper db = new DBHelper(Level1.this);
                db.saveData(1,"30"); */
                AlertDialog.Builder builder = new
 AlertDialog.Builder(Level1.this);
                builder.setTitle("Level 1 Complete!");
                builder.setMessage("You have won! You have unlock level 2! You can proceed to Level 2 or go back.");
                builder.setPositiveButton("Unlock", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(Level1.this, LevelPage.class);
                        startActivity(intent);
                        finish();
                    }
                });

                builder.setCancelable(false);
                builder.show();
                runTimer.cancel();
            }
</code>```

答:
Here is an overview of SharedPreference that can be used in our case.

Write Level score to SharedPreference:

Your saveData() method will look like this.

```<code>public void saveData(String level, int score) {
SharedPreferences sharedPref = context.getSharedPreferences("score.xml",
    Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(level, score); editor.commit();
}
</code>```

Reading from SharedPreference:

```<code>public int getLevelScore(String level) {
SharedPreferences sharedPref = context.getSharedPreferences("score.xml", Context.MODE_PRIVATE);
int levelScore = sharedPref.getInt(level, defaultScoreForLevel);
return levelScore;
}
</code>```

You can get more information about SharedPreference here.

Edit:

```<code>final String level1Score = getLevelScore("LEVEL1");
final String level2Score = getLevelScore("LEVEL2");
final String level3Score = getLevelScore("LEVEL3");
final String level4Score = getLevelScore("LEVEL4");
</code>```

Call saveData() method whenever user scores.

Body:
I am having issue regarding the buttons. After succeeding unlocking level 2 based on reaching the score from playing Level 1. I proceed to test Level 2 and ensure it can unlock Level 3 based on the score requirement, however, after succeed in unlocking Level 3. Level 2 become lock again. I am really not sure what went wrong. I may have got my logic wrong or something. It should had already remain enabled(true) after the Level 2 button had been set to enabled true. I will show my code related. Anyone who knows the answer please guide me.

This is in the LevelPage activity where it contains all the Level buttons for the user to choose which level to play, i will show just the relevant since the code in this activity is too long.

    DBHelper db = new DBHelper(LevelPage.this);
    HashMap<String,String> data = db.getData();
    final String level1Score = data.get("LEVEL1");
    final String level2Score = data.get("LEVEL2");
    final String level3Score = data.get("LEVEL3");
    final String level4Score = data.get("LEVEL4");

    btnLevel1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            clickSound.start();
            Intent intent = new Intent(LevelPage.this, Level1.class);
            startActivity(intent);
        }
    });

    if (level1Score != null && level1Score.equals("30")) {
        btnLevel2.setEnabled(true);
    btnLevel2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
                clickSound.start();
                Intent intent = new Intent(LevelPage.this, Level2.class);
                startActivity(intent);

            }
        });

    } else {
        btnLevel2.setEnabled(false);
    }

    if (level2Score != null && level2Score.equals("35")) {
        btnLevel3.setEnabled(true);
        btnLevel3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clickSound.start();
                Intent intent = new Intent(LevelPage.this, Level3.class);
                startActivity(intent);

            }
        });
    } else {
        btnLevel3.setEnabled(false);
    }

This is the Level2 page where the user plays the game and ensure to score 35 points to unlock:

else if (score == 35) {
                DBHelper db = new DBHelper(Level2.this);
                db.saveData(2,"35");
                AlertDialog.Builder builder = new
AlertDialog.Builder(Level2.this);
                builder.setTitle("Level 2 Complete!");
                builder.setMessage("You have won! You have unlock level 3!
You can proceed to Level 3 or go back.");
                builder.setPositiveButton("Unlock", new
DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(Level2.this,
LevelPage.class);
                        startActivity(intent);
                        finish();
                    }
                });

This is the SQLite Database to save and get the score data:

 private static final int DATABASE_VERSION = 1;
 private static final String DATABASE_NAME = "Level";
 private static final String USERTABLE = "USER_INFO";
 private static final String KEY_ID = "id";
 private static final String LEVEL1 = "LEVEL1";
 private static final String LEVEL2 = "LEVEL2";
 private static final String LEVEL3 = "LEVEL3";
 private static final String LEVEL4 = "LEVEL4";

private static final String CREATE_TABLE_USER = "CREATE TABLE IF NOT EXISTS "
        + USERTABLE + "(" + KEY_ID + " INTEGER PRIMARY KEY,"
        + LEVEL1 + " TEXT,"
        + LEVEL2 + " TEXT,"
        + LEVEL3 + " TEXT,"
        + LEVEL4 + " TEXT " + ");";

/*private static final String CREATE_TABLE_USER = "CREATE TABLE IF NOT EXISTS "
        + USERTABLE + "(" + KEY_ID + " INTEGER PRIMARY KEY," + LEVEL1 + " TEXT,"
        + LEVEL2 + " TEXT"+");"; */

private static final String SQL_DELETE_ENTRIES =
        "DROP TABLE IF EXISTS " + USERTABLE;

public DBHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(CREATE_TABLE_USER);
}

//to save score in db according to the level
public void saveData(int level,String score){
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues data = new ContentValues();
    switch(level){
        case 1:
            data.put(LEVEL1, score);
            break;
        case 2:
            data.put(LEVEL2,score);
            break;
        case 3:
            data.put(LEVEL3,score);
            break;
        case 4:
            data.put(LEVEL4,score);
            break;
    }
    db.insert(USERTABLE,null,data);
    db.close();
}

//to get score from db
//you can modify this function if you want to get score for a specific level
public HashMap<String,String> getData(){
    HashMap<String,String> scoreMap = new HashMap<>();
    String selectQuery = "SELECT  * FROM " + USERTABLE ;
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    if (cursor.moveToFirst()) {
        do {

            scoreMap.put(LEVEL1,cursor.getString(cursor.getColumnIndex(LEVEL1)));
            scoreMap.put(LEVEL2,cursor.getString(cursor.getColumnIndex(LEVEL2)));
            scoreMap.put(LEVEL3,cursor.getString(cursor.getColumnIndex(LEVEL3)));
            scoreMap.put(LEVEL4,cursor.getString(cursor.getColumnIndex(LEVEL4)));
        } while (cursor.moveToNext());
    }
    cursor.close();
    return scoreMap;

}

Note: The same also applies to Level 3 and Level 4. Even after Level 4 is unlock, Level 3 also got lock again along with Level 2. The result keep on repeating where it unlock next Level but lock the previous Level all of a sudden

To put SharedPrefences:

 else if (score == 30) {
                /*DBHelper db = new DBHelper(Level1.this);
                db.saveData(1,"30"); */
                AlertDialog.Builder builder = new
 AlertDialog.Builder(Level1.this);
                builder.setTitle("Level 1 Complete!");
                builder.setMessage("You have won! You have unlock level 2! You can proceed to Level 2 or go back.");
                builder.setPositiveButton("Unlock", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(Level1.this, LevelPage.class);
                        startActivity(intent);
                        finish();
                    }
                });

                builder.setCancelable(false);
                builder.show();
                runTimer.cancel();
            }

Body:
Here is an overview of SharedPreference that can be used in our case.

Write Level score to SharedPreference:

Your saveData() method will look like this.

public void saveData(String level, int score) {
SharedPreferences sharedPref = context.getSharedPreferences("score.xml",
    Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(level, score); editor.commit();
}

Reading from SharedPreference:

public int getLevelScore(String level) {
SharedPreferences sharedPref = context.getSharedPreferences("score.xml", Context.MODE_PRIVATE);
int levelScore = sharedPref.getInt(level, defaultScoreForLevel);
return levelScore;
}

You can get more information about SharedPreference here.

Edit:

final String level1Score = getLevelScore("LEVEL1");
final String level2Score = getLevelScore("LEVEL2");
final String level3Score = getLevelScore("LEVEL3");
final String level4Score = getLevelScore("LEVEL4");

Call saveData() method whenever user scores.


问:
Change active state if the page is 50px from top
I am trying to stop the div when it reaches 50px from the top. It works while I made the change on scrollTop: $($anchor.attr('href')).offset().top - 50 but the active state on navigation doesn't change. It only change if I scroll that 50px  too. Please help.

I am using this template

Body:
It is answered here

Just update the body to

<body id="page-top" data-spy="scroll" data-target=".navbar-fixed-top" data-offset="100">


问:
Unable to find error in below code
I am trying to display the users firstName and mobile number in a web page after he/she has successfully signed up. But while redirecting to that page, it is showing the below error :

D:\myRobustApp\app\views\mydashboard.jade:5 3| block content 4| h1= title > 5| p Hi #{myuser.firstName} 6| p Your email is #{myuser.email} 7| p Your mobile number is #{myuser.mobileNumber} 8| p Cannot read property 'firstName' of undefined

I have made a jade template file called "mydashboard.jade" with the below code:After successful signup user should be redirected to the above page and should be able to see his/her details.

```<code>extends mylayout

block content
  h1= title
  p Hi #{myuser.firstName}
  p Your email is #{myuser.email}
  p Your mobile number is #{myuser.mobileNumber}
  p
      a(href='http://localhost:3000/users/logout') logout
</code>```

Can anyone help me in the issue?

答:
The user is undefined, so first check it.</p>

```<code>extends mylayout

block content
  h1= title
  - if(typeof myuser !== 'undefined'){
  p Hi #{myuser.firstName}
  p Your email is #{myuser.email}
  p Your mobile number is #{myuser.mobileNumber}
  p
      a(href='http://localhost:3000/users/logout') logout
  - } else {

  - }
</code>```

Title: Unable to find error in below code

Body:
I am trying to display the users firstName and mobile number in a web page after he/she has successfully signed up. But while redirecting to that page, it is showing the below error :

D:\myRobustApp\app\views\mydashboard.jade:5 3| block content 4| h1= title > 5| p Hi #{myuser.firstName} 6| p Your email is #{myuser.email} 7| p Your mobile number is #{myuser.mobileNumber} 8| p Cannot read property 'firstName' of undefined

I have made a jade template file called "mydashboard.jade" with the below code:After successful signup user should be redirected to the above page and should be able to see his/her details.

extends mylayout

block content
  h1= title
  p Hi #{myuser.firstName}
  p Your email is #{myuser.email}
  p Your mobile number is #{myuser.mobileNumber}
  p
      a(href='http://localhost:3000/users/logout') logout

Can anyone help me in the issue?

Body:
The user is undefined, so first check it.

extends mylayout

block content
  h1= title
  - if(typeof myuser !== 'undefined'){
  p Hi #{myuser.firstName}
  p Your email is #{myuser.email}
  p Your mobile number is #{myuser.mobileNumber}
  p
      a(href='http://localhost:3000/users/logout') logout
  - } else {

  - }


问:
How to pass html table to laravel controller using ajax request?
How can I pass html array to laravel controller using ajax request?
I did like below in my view:

```<code><form>
                <table class="table table-striped border-top" id="modalTable">
                    <thead>
                        <tr>
                           <th>start-time</th>
                           <th></th>
                           <th>end-time</th>
                           <th>reserve</th>
                        </tr>
                    </thead>
                    <tbody id="change">
                        <tr>
                            <td name="startTime[]"></td>
                            <td></td>
                            <td name="endTime[]"></td>
                            <td name="reserved[]"></td>
                        </tr>
                    </tbody>
                </table>
                <input type="hidden" id="token" value="{{ csrf_token() }}">
            </form>
</code>```

and the ajax code is below:

```<code><script>
    $(document).on('click','.btn',function(){

        var startTime = $('#startTime').text();
        //alert(startTime);
        var endTime = $('#endTime').text();
        //alert(endTime);
        var token = $('#token').val();

        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
            }
        })

        $.ajax
        ({
            url:'reservePrivateChat',
            type:'post',
            data:{startTime:startTime,endTime:endTime,'_token':token},
            success:function()
            {
                alert('success');
            },
            error:function()
            {
                alert('error');
            }
        })

    });
</script>
</code>```

and in controller I did like below :

```<code>public function reservePrivateChat(Request $request)
{
    $startTime = $request->startTime;
    print_r ($startTime);
    $endTime = $_POST['endTime'];
    print_r($endTime);
}
</code>```

In controller there is no difference between $request and $_POST. Both return just one column of the table that sent by ajax but I want all values of the columns...

答:
You can't do what you're trying to do. You have to manually construct the array based on the correct names of the table data. The #startTime selector does not exist because it's looking for an element with id startTime but you only have an element with name startTime[].

You an probably create an array as follows:

```<code>    var startTime = [];
    $("[name='startTime[]]'").each(function () {
        startTime.push($(this).text());
    });
    var endTime = [];
    $('[name='endTime[]]'').each(function () {
        endTime.push($(this).text());
    });
    var token = $('#token').val();
    //No need for ajax setup if you're sending the token as a parameter
    $.ajax({
        url:'reservePrivateChat',
        type:'post',
        data:{ startTime:startTime,endTime:endTime,'_token':token},
</code>```

Body:
How can I pass html array to laravel controller using ajax request?
I did like below in my view:

<form>

                           start-time

                           end-time
                           reserve

                <input type="hidden" id="token" value="{{ csrf_token() }}">
            </form>

and the ajax code is below:

and in controller I did like below :

public function reservePrivateChat(Request $request)
{
    $startTime = $request->startTime;
    print_r ($startTime);
    $endTime = $_POST['endTime'];
    print_r($endTime);
}

In controller there is no difference between $request and $_POST. Both return just one column of the table that sent by ajax but I want all values of the columns...

Body:
You can't do what you're trying to do. You have to manually construct the array based on the correct names of the table data. The #startTime selector does not exist because it's looking for an element with id startTime but you only have an element with name startTime[].

You an probably create an array as follows:

    var startTime = [];
    $("[name='startTime[]]'").each(function () {
        startTime.push($(this).text());
    });
    var endTime = [];
    $('[name='endTime[]]'').each(function () {
        endTime.push($(this).text());
    });
    var token = $('#token').val();
    //No need for ajax setup if you're sending the token as a parameter
    $.ajax({
        url:'reservePrivateChat',
        type:'post',
        data:{ startTime:startTime,endTime:endTime,'_token':token},


问:
Macros/Shapeless to control string value in method
I'm creating a DSL where users have a given when then, where they pass a string with the action they want.

All those actions are controlled using some regular expressions.
Now using shapeless or macros I would like to control what users compones using the DSL, and in case the string does not fit the string as we expect make the code don't compile.

Si for instance

```<code>Given("a good action") -> fine
When("wrong string action") -> compilation error
</code>```

Can anybody please point me to a good blog or documentation of how to achieve this?

Regards

After the solution of Gabriele now I´m facing a design issue. This is my vaidator class

```<code>object DSLValidator {

  import scala.language.experimental.macros

  def Given(message: String): Any = macro checkActionImpl

  def When(message: String): Any = macro checkActionImpl

  def Then(message: String): Any = macro checkActionImpl

  def And(message: String): Any = macro checkActionImpl

  def checkActionImpl(c: blackbox.Context)(message: c.Tree): c.Tree = {
    import c.universe._
    def isValidAction(s: String): Boolean = checkMessage(s)

    message match {
      case _tree@Literal(Constant(s: String)) if isValidAction(s) => _tree
      case _ => c.abort(c.enclosingPosition, "Invalid action for DSL. Check the allowed actions in RegexActions")
    }
  }

  val PARAMS = "(.*)=(.*)"
  val PAYLOAD_VALUE_REGEX = s"^Payload $PARAMS".r

  def checkMessage(action: String): Boolean = {
    action match {
      case PAYLOAD_VALUE_REGEX(c, c1) => true
      case "Make a request to server" => true
      case _ => false
    }
  }
}
</code>```

And if I invoke the Given/When/Then from another class with wrong arguments the compiler complain as we expect.

```<code>  @Test
  def TestDSL(): Unit = {
    DSLValidator.Given("Make a request to wrong")--> not compiling
    DSLValidator.When("Payload code=works") --> compiling
    println("End")
  }
</code>```

But now thinking the whole idea of was not only to check the values on compilation time but also execute the logic of the Given/When/then

And I realize than when I use macros in a function there´s nothing else that we can do so.

```<code>   def Given(message: String): Any =  {
          macro checkActionImpl
          //My bussiness logic
      }
</code>```

is not compiling, so my question is, where can I put now the business logic and where the invocation of the macro function to continue working.

Also using a static class as bridge does not work and wont compile since the string message does not fit.

```<code>object Macros {

  def Given(message: String) = {
    DSLValidator.Given(message)
    //Logic here
    println("Given")
  }
}

Macros.Given("Make a request to wrong")
</code>```

Any idea?

Regards

答:
I think shapeless cannot help you in this case, so a macro would be the way to go.

Here's a skeleton for a macro you can start from:

```<code>import scala.language.experimental.macros
def Given(message: String): /* the return type of Given */ = macro givenImpl

def givenImpl(c: Context)(message: c.Tree): c.Tree = {
  import c.universe._
  def isValid(s: String): Boolean = ??? // your validation logic here

  message match {
    case case t @ Literal(Constant(s: String)) if isValid(s) => t
    case _ => c.abort(c.enclosingPosition, "Invalid message")
  }

}
</code>```

In order to fully understand this I can recommend you to read:

http://docs.scala-lang.org/overviews/macros/overview.html

https://blog.scalac.io/2016/02/25/def-hello-macro-world.html

Body:
I'm creating a DSL where users have a given when then, where they pass a string with the action they want.

All those actions are controlled using some regular expressions.
Now using shapeless or macros I would like to control what users compones using the DSL, and in case the string does not fit the string as we expect make the code don't compile.

Si for instance

Given("a good action") -> fine
When("wrong string action") -> compilation error

Can anybody please point me to a good blog or documentation of how to achieve this?

Regards

After the solution of Gabriele now I´m facing a design issue. This is my vaidator class

object DSLValidator {

  import scala.language.experimental.macros

  def Given(message: String): Any = macro checkActionImpl

  def When(message: String): Any = macro checkActionImpl

  def Then(message: String): Any = macro checkActionImpl

  def And(message: String): Any = macro checkActionImpl

  def checkActionImpl(c: blackbox.Context)(message: c.Tree): c.Tree = {
    import c.universe._
    def isValidAction(s: String): Boolean = checkMessage(s)

    message match {
      case _tree@Literal(Constant(s: String)) if isValidAction(s) => _tree
      case _ => c.abort(c.enclosingPosition, "Invalid action for DSL. Check the allowed actions in RegexActions")
    }
  }

  val PARAMS = "(.*)=(.*)"
  val PAYLOAD_VALUE_REGEX = s"^Payload $PARAMS".r

  def checkMessage(action: String): Boolean = {
    action match {
      case PAYLOAD_VALUE_REGEX(c, c1) => true
      case "Make a request to server" => true
      case _ => false
    }
  }
}

And if I invoke the Given/When/Then from another class with wrong arguments the compiler complain as we expect.

  @Test
  def TestDSL(): Unit = {
    DSLValidator.Given("Make a request to wrong")--> not compiling
    DSLValidator.When("Payload code=works") --> compiling
    println("End")
  }

But now thinking the whole idea of was not only to check the values on compilation time but also execute the logic of the Given/When/then

And I realize than when I use macros in a function there´s nothing else that we can do so.

   def Given(message: String): Any =  {
          macro checkActionImpl
          //My bussiness logic
      }

is not compiling, so my question is, where can I put now the business logic and where the invocation of the macro function to continue working.

Also using a static class as bridge does not work and wont compile since the string message does not fit.

object Macros {

  def Given(message: String) = {
    DSLValidator.Given(message)
    //Logic here
    println("Given")
  }
}

Macros.Given("Make a request to wrong")

Any idea?

Regards

Body:
I think shapeless cannot help you in this case, so a macro would be the way to go.

Here's a skeleton for a macro you can start from:

import scala.language.experimental.macros
def Given(message: String): /* the return type of Given */ = macro givenImpl

def givenImpl(c: Context)(message: c.Tree): c.Tree = {
  import c.universe._
  def isValid(s: String): Boolean = ??? // your validation logic here

  message match {
    case case t @ Literal(Constant(s: String)) if isValid(s) => t
    case _ => c.abort(c.enclosingPosition, "Invalid message")
  }

}

In order to fully understand this I can recommend you to read:

http://docs.scala-lang.org/overviews/macros/overview.html

https://blog.scalac.io/2016/02/25/def-hello-macro-world.html


答:
```<code>Element amtElement= (Element)amountList.item(0);
</code>```

seems to be your  element - so why are you calling getFirstChild()?

try this:

```<code>String amount=amtElement.getnodevalue()
</code>```

have you checked out jdom? it has a nice documentation and is easy to use..

Title: getting node value exception

Body:
Element amtElement= (Element)amountList.item(0);

seems to be your  element - so why are you calling getFirstChild()?

try this:

String amount=amtElement.getnodevalue()

have you checked out jdom? it has a nice documentation and is easy to use..


问:
Groovy: group xml segments by ID
I have a requirement to create an additional XML tag say myGroup & in that I need to create groups of each ID_Number that comes in from my input.

Here is my input:

```<code><mySegment>
<Field1>AB</Field1>
<Field2>AB</Field2>
<Field3>AB</Field3>
<Field4>AB</Field4>
<ID_Number>1</ID_Number>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
</mySegment>
<mySegment>
<Field1>AB</Field1>
<Field2>AB</Field2>
<Field3>AB</Field3>
<Field4>AB</Field4>
<ID_Number>2</ID_Number>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
</mySegment>
<mySegment>
<Field1>AB</Field1>
<Field2>AB</Field2>
<Field3>AB</Field3>
<Field4>AB</Field4>
<ID_Number>2</ID_Number>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
</mySegment>
<mySegment>
<Field1>AB</Field1>
<Field2>AB</Field2>
<Field3>AB</Field3>
<Field4>AB</Field4>
<ID_Number>3</ID_Number>
</mySegment>
<mySegment>
<Field1>AB</Field1>
<Field2>AB</Field2>
<Field3>AB</Field3>
<Field4>AB</Field4>
<ID_Number>3</ID_Number>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
</mySegment>
</code>```

I want to create groups based on the ID_Numbers so that all the mySegments with common ID come under the myGroup tag as:

```<code><myGroup>
<mySegment>
<Field1>AB</Field1>
<Field2>AB</Field2>
<Field3>AB</Field3>
<Field4>AB</Field4>
<ID_Number>1</ID_Number>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
</mySegment>

</myGroup>
<myGroup>
<mySegment>
<Field1>AB</Field1>
<Field2>AB</Field2>
<Field3>AB</Field3>
<Field4>AB</Field4>
<ID_Number>2</ID_Number>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
</mySegment>
<mySegment>
<Field1>AB</Field1>
<Field2>AB</Field2>
<Field3>AB</Field3>
<Field4>AB</Field4>
<ID_Number>2</ID_Number>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
</mySegment>
</myGroup>
<myGroup>
<mySegment>
<Field1>AB</Field1>
<Field2>AB</Field2>
<Field3>AB</Field3>
<Field4>AB</Field4>
<ID_Number>3</ID_Number>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
</mySegment>
<mySegment>
<Field1>AB</Field1>
<Field2>AB</Field2>
<Field3>AB</Field3>
<Field4>AB</Field4>
<ID_Number>3</ID_Number>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
</mySegment>
<myGroup>
</code>```

I understand that it can be done easily using XSLT but I have to achieve this using Groovy. Pls advise if this can be done by Groovy. I have tried below links but not sure how they can be applied to my case.
Grouping and sorting nested collections in Groovy

答:
Assuming your mySegment elements have a common root element here is an example:

```<code>def xml = '''
<Root>
<mySegment>
<Field1>AB</Field1>
<Field2>AB</Field2>
<Field3>AB</Field3>
<Field4>AB</Field4>
<ID_Number>1</ID_Number>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
</mySegment>
<mySegment>
<Field1>AB</Field1>
<Field2>AB</Field2>
<Field3>AB</Field3>
<Field4>AB</Field4>
<ID_Number>2</ID_Number>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
</mySegment>
<mySegment>
<Field1>AB</Field1>
<Field2>AB</Field2>
<Field3>AB</Field3>
<Field4>AB</Field4>
<ID_Number>2</ID_Number>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
</mySegment>
<mySegment>
<Field1>AB</Field1>
<Field2>AB</Field2>
<Field3>AB</Field3>
<Field4>AB</Field4>
<ID_Number>3</ID_Number>
</mySegment>
<mySegment>
<Field1>AB</Field1>
<Field2>AB</Field2>
<Field3>AB</Field3>
<Field4>AB</Field4>
<ID_Number>3</ID_Number>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
</mySegment>
</Root>
'''

def slurper = new XmlSlurper()
def root = slurper.parseText(xml)
def newRoot = slurper.parseText('<Root/>')
root.mySegment.groupBy{s -> s.ID_Number.text()}.each{key, value -> def group = slurper.parseText('<group/>'); value.each{v -> group.appendNode(v)}; newRoot.appendNode(group)}
groovy.xml.XmlUtil.serialize newRoot
</code>```

I guess there are better ways to create the new elements than doing e.g. slurper.parseText('<group/>') but the grouping seems to work fine.

If your mySegment elements are not children of the root you can find them with root.'**'.findAll{el -> el.name() == 'mySegment'} so the grouping would be done with

```<code>root.'**'.findAll{el -> el.name() == 'mySegment'}.groupBy{s -> s.ID_Number.text()}.each{key, value -> def group = slurper.parseText('<group/>'); value.each{v -> group.appendNode(v)}; newRoot.appendNode(group)}
</code>```

Title: Groovy: group xml segments by ID

Body:
I have a requirement to create an additional XML tag say myGroup & in that I need to create groups of each ID_Number that comes in from my input.

Here is my input:

<mySegment>
<Field1>AB</Field1>
<Field2>AB</Field2>
<Field3>AB</Field3>
<Field4>AB</Field4>
<ID_Number>1</ID_Number>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
</mySegment>
<mySegment>
<Field1>AB</Field1>
<Field2>AB</Field2>
<Field3>AB</Field3>
<Field4>AB</Field4>
<ID_Number>2</ID_Number>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
</mySegment>
<mySegment>
<Field1>AB</Field1>
<Field2>AB</Field2>
<Field3>AB</Field3>
<Field4>AB</Field4>
<ID_Number>2</ID_Number>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
</mySegment>
<mySegment>
<Field1>AB</Field1>
<Field2>AB</Field2>
<Field3>AB</Field3>
<Field4>AB</Field4>
<ID_Number>3</ID_Number>
</mySegment>
<mySegment>
<Field1>AB</Field1>
<Field2>AB</Field2>
<Field3>AB</Field3>
<Field4>AB</Field4>
<ID_Number>3</ID_Number>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
</mySegment>

I want to create groups based on the ID_Numbers so that all the mySegments with common ID come under the myGroup tag as:

<myGroup>
<mySegment>
<Field1>AB</Field1>
<Field2>AB</Field2>
<Field3>AB</Field3>
<Field4>AB</Field4>
<ID_Number>1</ID_Number>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
</mySegment>

</myGroup>
<myGroup>
<mySegment>
<Field1>AB</Field1>
<Field2>AB</Field2>
<Field3>AB</Field3>
<Field4>AB</Field4>
<ID_Number>2</ID_Number>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
</mySegment>
<mySegment>
<Field1>AB</Field1>
<Field2>AB</Field2>
<Field3>AB</Field3>
<Field4>AB</Field4>
<ID_Number>2</ID_Number>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
</mySegment>
</myGroup>
<myGroup>
<mySegment>
<Field1>AB</Field1>
<Field2>AB</Field2>
<Field3>AB</Field3>
<Field4>AB</Field4>
<ID_Number>3</ID_Number>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
</mySegment>
<mySegment>
<Field1>AB</Field1>
<Field2>AB</Field2>
<Field3>AB</Field3>
<Field4>AB</Field4>
<ID_Number>3</ID_Number>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
</mySegment>
<myGroup>

I understand that it can be done easily using XSLT but I have to achieve this using Groovy. Pls advise if this can be done by Groovy. I have tried below links but not sure how they can be applied to my case.
Grouping and sorting nested collections in Groovy

Body:
Assuming your mySegment elements have a common root element here is an example:

def xml = '''
<Root>
<mySegment>
<Field1>AB</Field1>
<Field2>AB</Field2>
<Field3>AB</Field3>
<Field4>AB</Field4>
<ID_Number>1</ID_Number>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
</mySegment>
<mySegment>
<Field1>AB</Field1>
<Field2>AB</Field2>
<Field3>AB</Field3>
<Field4>AB</Field4>
<ID_Number>2</ID_Number>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
</mySegment>
<mySegment>
<Field1>AB</Field1>
<Field2>AB</Field2>
<Field3>AB</Field3>
<Field4>AB</Field4>
<ID_Number>2</ID_Number>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
</mySegment>
<mySegment>
<Field1>AB</Field1>
<Field2>AB</Field2>
<Field3>AB</Field3>
<Field4>AB</Field4>
<ID_Number>3</ID_Number>
</mySegment>
<mySegment>
<Field1>AB</Field1>
<Field2>AB</Field2>
<Field3>AB</Field3>
<Field4>AB</Field4>
<ID_Number>3</ID_Number>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
<child>
<Field5>AB</Field5>
<Field6>AB</Field6>
<Field7>AB</Field7>
</child>
</mySegment>
</Root>
'''

def slurper = new XmlSlurper()
def root = slurper.parseText(xml)
def newRoot = slurper.parseText('<Root/>')
root.mySegment.groupBy{s -> s.ID_Number.text()}.each{key, value -> def group = slurper.parseText('<group/>'); value.each{v -> group.appendNode(v)}; newRoot.appendNode(group)}
groovy.xml.XmlUtil.serialize newRoot

I guess there are better ways to create the new elements than doing e.g. slurper.parseText('<group/>') but the grouping seems to work fine.

If your mySegment elements are not children of the root you can find them with root.'**'.findAll{el -> el.name() == 'mySegment'} so the grouping would be done with

root.'**'.findAll{el -> el.name() == 'mySegment'}.groupBy{s -> s.ID_Number.text()}.each{key, value -> def group = slurper.parseText('<group/>'); value.each{v -> group.appendNode(v)}; newRoot.appendNode(group)}


问:
How can I easily access data both inside and outside a container?
I have a docker container with MinGW compiler set up inside it. I want to use it for development. That is I want to compile, test, edit, compile, test ...

The container will also be used in the CI pipeline, and eventually for producing production builds. By using the same container we ensure consistency in the build environment.

My host has my development tools for code editing etc. while the container has the compiler, so clearly the files need to be shared.

I have set up a volume. Unfortunately I cannot access it with my user account:

```<code># ls -lAFd /var/lib/docker
drwx--x--x 11 root docker 4096 Jul  4 09:11 /var/lib/docker/
# ls -lAFd /var/lib/docker/volumes/mingw_build/_data
drwxr-xr-x 6 alastair docker 4096 Jul  3 14:31 /var/lib/docker/volumes/mingw_build/_data/
</code>```

My user is in group docker but group docker does NOT have read permissions on /var/lib/docker and so cannot access the _data directory of the volume.

I have tried cheating and using sudo to tweak the folder permissions so that group docker has read permissions all the way down the path, but those permissions get rewritten on reboot - no doubt when the docker server starts.

Can anyone figure out a way around this? I have tried using symlinks, but they always inherit the most restrictive permissions of the path elements.

答:
When I originally read the documentation it looked like only named volumes can be used, but I have just found out that directories can also be used as the source. E.g.:

```<code>mkdir /home/alastair/mingw_build
docker run -v /home/alastair/mingw_build:/home/mingw_build/build mingw_build
</code>```

Since I want to use the same container and run script for CI testing as for local development, I set an environment variable in my .bashrc, and test for it in my run script. If it is present I use the directory it points to, and if not I use a named container, creating it if necessary.

Body:
I have a docker container with MinGW compiler set up inside it. I want to use it for development. That is I want to compile, test, edit, compile, test ...

The container will also be used in the CI pipeline, and eventually for producing production builds. By using the same container we ensure consistency in the build environment.

My host has my development tools for code editing etc. while the container has the compiler, so clearly the files need to be shared.

I have set up a volume. Unfortunately I cannot access it with my user account:

# ls -lAFd /var/lib/docker
drwx--x--x 11 root docker 4096 Jul  4 09:11 /var/lib/docker/
# ls -lAFd /var/lib/docker/volumes/mingw_build/_data
drwxr-xr-x 6 alastair docker 4096 Jul  3 14:31 /var/lib/docker/volumes/mingw_build/_data/

My user is in group docker but group docker does NOT have read permissions on /var/lib/docker and so cannot access the _data directory of the volume.

I have tried cheating and using sudo to tweak the folder permissions so that group docker has read permissions all the way down the path, but those permissions get rewritten on reboot - no doubt when the docker server starts.

Can anyone figure out a way around this? I have tried using symlinks, but they always inherit the most restrictive permissions of the path elements.

Body:
When I originally read the documentation it looked like only named volumes can be used, but I have just found out that directories can also be used as the source. E.g.:

mkdir /home/alastair/mingw_build
docker run -v /home/alastair/mingw_build:/home/mingw_build/build mingw_build

Since I want to use the same container and run script for CI testing as for local development, I set an environment variable in my .bashrc, and test for it in my run script. If it is present I use the directory it points to, and if not I use a named container, creating it if necessary.


问:
Send data from fragment to activity android C#
i'm new to xamarin android. i want to send data from fragment to MainActivity.
i searched google a lot almost all of them was in Java.</p>

答:
You have few options:

Access the parent activity.

Create a function called SetData(data) in your activity class.
Your fragmnet have the "Activity" property, so cast to your activity type and then call the setData function with your data.

((ParentActivity)this.Activity).SetData(data);

Use the SharedPreferences

Set (in fragment):

```<code>ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(context);
ISharedPreferencesEditor editor = prefs.Edit();
editor.PutString("my_data", "some_data");
editor.Apply();
</code>```

Get (in activity):

```<code>ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences (context);
String myData = prefs.GetString ("my_data", "");
</code>```

Body:
You have few options:

Access the parent activity.

Create a function called SetData(data) in your activity class.
Your fragmnet have the "Activity" property, so cast to your activity type and then call the setData function with your data.

((ParentActivity)this.Activity).SetData(data);

Use the SharedPreferences

Set (in fragment):

ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(context);
ISharedPreferencesEditor editor = prefs.Edit();
editor.PutString("my_data", "some_data");
editor.Apply();

Get (in activity):

ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences (context);
String myData = prefs.GetString ("my_data", "");


问:
Tabs navigation ionic 2
I have already search lots to find solution, but no luck.

I need to redirect on different page when click on tab
My code:

in app.html

```<code><ion-footer>
  <ion-toolbar>
    <ion-tabs>
      <ion-tab tabIcon="md-home" [root]="rootPage" tabTitle="Home"></ion-tab>
      <ion-tab tabIcon="md-person" [root]="profilePage" tabTitle="Profile"></ion-tab>
      <ion-tab tabIcon="md-notifications" [root]="updatePage" tabTitle="Updates"></ion-tab>
    </ion-tabs>
  </ion-toolbar>
</ion-footer>
</code>```

in app.component.ts

```<code>rootPage: any = HomePage;
profilePage: any = ProfilePage;
updatePage: any = UpdatePage;
</code>```

When i click on Home it's call homepage constructor, but did not redirect to home page.
suppose i'm on cart page and click on homepage Tab. it's call homepage constructor but page remains same.

Please help me. I'm ne in IONIC2

答:
You may try to add the pages to app.modules.ts

```<code>entryComponents: [
   MyApp,
   HomePage,
   rootPage,profilePage,updatePage
],
</code>```

and try to move the ion-tabs as root element, or inside ion-content

```<code><ion-content padding>
<ion-tabs tabbarPlacement="top">
  <ion-tab tabIcon="md-home" [root]="rootPage" tabTitle="Home"></ion-tab>
  <ion-tab tabIcon="md-person" [root]="profilePage" tabTitle="Profile"></ion-tab>
  <ion-tab tabIcon="md-notifications" [root]="updatePage" tabTitle="Updates"></ion-tab>
</ion-tabs>
</ion-content>
</code>```

change to tabbarPlacement attribute if you wish to place the control in the bottom.

Title: Tabs navigation ionic 2

Body:
I have already search lots to find solution, but no luck.

I need to redirect on different page when click on tab
My code:

in app.html

<ion-footer>
  <ion-toolbar>
    <ion-tabs>
      <ion-tab tabIcon="md-home" [root]="rootPage" tabTitle="Home"></ion-tab>
      <ion-tab tabIcon="md-person" [root]="profilePage" tabTitle="Profile"></ion-tab>
      <ion-tab tabIcon="md-notifications" [root]="updatePage" tabTitle="Updates"></ion-tab>
    </ion-tabs>
  </ion-toolbar>
</ion-footer>

in app.component.ts

rootPage: any = HomePage;
profilePage: any = ProfilePage;
updatePage: any = UpdatePage;

When i click on Home it's call homepage constructor, but did not redirect to home page.
suppose i'm on cart page and click on homepage Tab. it's call homepage constructor but page remains same.

Please help me. I'm ne in IONIC2

Body:
You may try to add the pages to app.modules.ts

entryComponents: [
   MyApp,
   HomePage,
   rootPage,profilePage,updatePage
],

and try to move the ion-tabs as root element, or inside ion-content

<ion-content padding>
<ion-tabs tabbarPlacement="top">
  <ion-tab tabIcon="md-home" [root]="rootPage" tabTitle="Home"></ion-tab>
  <ion-tab tabIcon="md-person" [root]="profilePage" tabTitle="Profile"></ion-tab>
  <ion-tab tabIcon="md-notifications" [root]="updatePage" tabTitle="Updates"></ion-tab>
</ion-tabs>
</ion-content>

change to tabbarPlacement attribute if you wish to place the control in the bottom.


问:
how to change element CSS position with animation
I want to change an HTML element position from static to fixed at top 50% and left 50% of the browser window but the code just leads to background-color change!</p>

```<code>div {
    width: 100px;
    height: 100px;
    background-color: red;
    position: static;
    top: auto;
    left: auto;
    animation-name: example;
    animation-duration: 4s;
}

@keyframes example {
    from {
        background-color: red;
        position: static;
        top: auto;
        left: auto;
    }
    to {
      background-color: yellow;
      position: fixed;
      top: 50%;
      left: 50%;
     }
}
</code>```

答:
I found the answer via 'Vangel Tzo' help :</p>

```<code>div {
    width: 100px;
    height: 100px;
    background-color: red;
    animation-name: example;
    animation-duration: 4s;
}

@keyframes example {
    from {
        background-color: red;
    }
    to {
      background-color: yellow;
      transform: translate(50vw, 50vh);
     }
}
</code>```

Body:
I want to change an HTML element position from static to fixed at top 50% and left 50% of the browser window but the code just leads to background-color change!

div {
    width: 100px;
    height: 100px;
    background-color: red;
    position: static;
    top: auto;
    left: auto;
    animation-name: example;
    animation-duration: 4s;
}

@keyframes example {
    from {
        background-color: red;
        position: static;
        top: auto;
        left: auto;
    }
    to {
      background-color: yellow;
      position: fixed;
      top: 50%;
      left: 50%;
     }
}

Body:
I found the answer via 'Vangel Tzo' help :

div {
    width: 100px;
    height: 100px;
    background-color: red;
    animation-name: example;
    animation-duration: 4s;
}

@keyframes example {
    from {
        background-color: red;
    }
    to {
      background-color: yellow;
      transform: translate(50vw, 50vh);
     }
}


问:
Jupyter notebook hanging with sklearn return?
Copied code from https://github.com/llSourcell/predicting_stock_prices/blob/master/demo.py
when I run it in jupyter notebook it hangs and hangs at the last line. I have the .csv in the notebook and the download folder... not sure if that's the error

```<code>import csv
import numpy as np
from sklearn.svm import SVR
import matplotlib.pyplot as plt

#plt.switch_backend('newbackend')

dates = []
prices = []

def get_data(filename):
    with open(filename, 'r') as csvfile:
        csvFileReader = csv.reader(csvfile)
        next(csvFileReader) # skipping column names
        for row in csvFileReader:
            dates.append(int(row[0].split('-')[0]))
            prices.append(float(row[1]))
    return

def predict_price(dates, prices, x):
    dates = np.reshape(dates,(len(dates), 1)) # converting to matrix of n X 1

    svr_lin = SVR(kernel= 'linear', C= 1e3)
    svr_poly = SVR(kernel= 'poly', C= 1e3, degree= 2)
    svr_rbf = SVR(kernel= 'rbf', C= 1e3, gamma= 0.1) # defining the support vector regression models
    svr_rbf.fit(dates, prices) # fitting the data points in the models
    svr_lin.fit(dates, prices)
    svr_poly.fit(dates, prices)

    plt.scatter(dates, prices, color= 'black', label= 'Data') # plotting the initial datapoints
    plt.plot(dates, svr_rbf.predict(dates), color= 'red', label= 'RBF model') # plotting the line made by the RBF kernel
    plt.plot(dates,svr_lin.predict(dates), color= 'green', label= 'Linear model') # plotting the line made by linear kernel
    plt.plot(dates,svr_poly.predict(dates), color= 'blue', label= 'Polynomial model') # plotting the line made by polynomial kernel
    plt.xlabel('Date')
    plt.ylabel('Price')
    plt.title('Support Vector Regression')
    plt.legend()
    plt.show()

    return svr_rbf.predict(x)[0], svr_lin.predict(x)[0], svr_poly.predict(x)[0]

get_data('table.csv') # calling get_data method by passing the csv file to it

predicted_price = predict_price(dates, prices, 29)
</code>```

I've divided the code into cells in jupyter and the

  predicted_price appears to hang  In [*]:

答:
The code is fine.  SVR takes time to compute. learn more here. you can try the following code with linear regression.

with import

```<code>from sklearn import linear_model

# defining the linear regression model
linear_mod = linear_model.LinearRegression()

# fitting the data points in the model
linear_mod.fit(dates, prices)

plt.scatter(dates, prices, color='black', label='Data')
# plotting the initial datapoints
plt.plot(dates, linear_mod.predict(dates), color='red',
             label='Linear model')
</code>```

Body:
Copied code from https://github.com/llSourcell/predicting_stock_prices/blob/master/demo.py
when I run it in jupyter notebook it hangs and hangs at the last line. I have the .csv in the notebook and the download folder... not sure if that's the error

import csv
import numpy as np
from sklearn.svm import SVR
import matplotlib.pyplot as plt

#plt.switch_backend('newbackend')

dates = []
prices = []

def get_data(filename):
    with open(filename, 'r') as csvfile:
        csvFileReader = csv.reader(csvfile)
        next(csvFileReader) # skipping column names
        for row in csvFileReader:
            dates.append(int(row[0].split('-')[0]))
            prices.append(float(row[1]))
    return

def predict_price(dates, prices, x):
    dates = np.reshape(dates,(len(dates), 1)) # converting to matrix of n X 1

    svr_lin = SVR(kernel= 'linear', C= 1e3)
    svr_poly = SVR(kernel= 'poly', C= 1e3, degree= 2)
    svr_rbf = SVR(kernel= 'rbf', C= 1e3, gamma= 0.1) # defining the support vector regression models
    svr_rbf.fit(dates, prices) # fitting the data points in the models
    svr_lin.fit(dates, prices)
    svr_poly.fit(dates, prices)

    plt.scatter(dates, prices, color= 'black', label= 'Data') # plotting the initial datapoints
    plt.plot(dates, svr_rbf.predict(dates), color= 'red', label= 'RBF model') # plotting the line made by the RBF kernel
    plt.plot(dates,svr_lin.predict(dates), color= 'green', label= 'Linear model') # plotting the line made by linear kernel
    plt.plot(dates,svr_poly.predict(dates), color= 'blue', label= 'Polynomial model') # plotting the line made by polynomial kernel
    plt.xlabel('Date')
    plt.ylabel('Price')
    plt.title('Support Vector Regression')
    plt.legend()
    plt.show()

    return svr_rbf.predict(x)[0], svr_lin.predict(x)[0], svr_poly.predict(x)[0]

get_data('table.csv') # calling get_data method by passing the csv file to it

predicted_price = predict_price(dates, prices, 29)

I've divided the code into cells in jupyter and the

  predicted_price appears to hang  In [*]:

Body:
The code is fine.  SVR takes time to compute. learn more here. you can try the following code with linear regression.

with import

from sklearn import linear_model

# defining the linear regression model
linear_mod = linear_model.LinearRegression()

# fitting the data points in the model
linear_mod.fit(dates, prices)

plt.scatter(dates, prices, color='black', label='Data')
# plotting the initial datapoints
plt.plot(dates, linear_mod.predict(dates), color='red',
             label='Linear model')


问:
IE8 Render Issue
Why doesn't this document render in IE8 ??

http://arabiannights.thestagingurl.com/

答:
On ~line 55, if I change the last line of this:

```<code><!--[if IE 7]>
<style type="text/css">
    .sf-contener {position: absolute; left: 0;}
    #right_column #cart_block .block_content a {position: relative; padding-top: 38px; top: -15px}
</style>
<! [endif] -->
</code>```

to this:

```<code><![endif]-->
</code>```

Somehow the malformed IE conditional close comment was stopping the rest of the page from being parsed.

Title: IE8 Render Issue

Body:
On ~line 55, if I change the last line of this:

<!--[if IE 7]>
<style type="text/css">
    .sf-contener {position: absolute; left: 0;}
    #right_column #cart_block .block_content a {position: relative; padding-top: 38px; top: -15px}
</style>
<! [endif] -->

to this:

<![endif]-->

Somehow the malformed IE conditional close comment was stopping the rest of the page from being parsed.


问:
What is the type of the super object returned by super()?
From here:

```<code>super( [ type [ , object-or-type ]] )
</code>```

Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class. The search order is same as that used by getattr() except that the type itself is skipped.

If the second argument is omitted, the super object returned is
  unbound.

If the second argument is an object, isinstance(obj, type) must be
  true.

If the second argument is a type, issubclass(type2, type) must be
  true (this is useful for classmethods).

If I am correct, a type is a class, and a class is a type. A class
is an object, so a type is also an object.  Why does the quote
distinguish the two cases when the second argument being an object
when it is a type?

When the second argument is a type, why is issubclass(type2, type)
required to be true?

What is the type of the super object    returned by super in each of the three cases respectively? Or how do you determine the type of the super object returned by super?

When the second argument is an object, because "The search order is same as that used by getattr() except that the type itself is skipped", I guessed that the type of the superobject returned by super function should be a subclass of any ancestry class of the first argument type, but I found that it is actually not by testing with issubclass. So did I misunderstand something?

答:
You seem to be confusing the word type with the type() built-in. Here they simply references the first argument passed into super().

What the documentation tells you is that if you pass in two arguments, then the second argument either has to be an instance of the first argument, or it has to be a subclass. In other words, either isinstance(first_argument, second_argument) or issubclass(first_argument, second_argument) must be true. There is no other meaning here.

Just like int() or str() or any of the other built-in types, the type of the object returned by calling super() is that type. There are no separate types returned for different arguments. See the C source code defining the object.

The super() object implements a __getattribute__ hook that implements specific attribute behaviour. The documentation tells you that the rules for attribute lookups are the same as for getattr() (but with the documented MRO skip), but that does not mean that super() returns an ancestor class.

What actually happens is that super().__getattribute__ takes the MRO of the second argument (either type(instance).__mro__ or cls.__mro__, depending on wether isinstance() or issubclass() was true), find the first argument in that sequence and start testing for attributes after that. Because the MRO is scanned for the (type of) the second argument first, it does have to be findable, which is why the constraints are what they are.

In Pure Python, this is what super() does (simplified to focus on just the two argument behaviour):

```<code>def _supercheck(type_, obj):
    try:
        if issubclass(obj, type_):
            return obj
    except TypeError:
        # obj is not a type so issubclass throws a TypeError
        pass
    if isinstance(obj, type_):
        return type(obj)
    raise TypeError(
        "super(type, obj): obj must be an instance or subtype of type")

class super_:
    def __init__(self, type_, obj):
        # simplified for the two-argument case
        self.type_ = type_
        self.obj = obj
        self.obj_type = _supercheck(type_, obj)

    def __getattribute__(self, name):
        if name == '__class__':
            # __class__ should always come from this object, not
            # the represented MRO.
            return super().__getattribute__(name)

        # avoid infinite recursion issues
        sd = super().__getattribute__('__dict__')
        starttype = sd['obj_type']
        type_ = sd['type_']
        obj = sd['obj']

        mro = iter(starttype.__mro__)

        # skip past the start type in the MRO
        for tp in mro:
            if tp == type_:
                break

        # Search for the attribute on the remainder of the MRO
        for tp in mro:
            attrs = vars(tp)
            if name in attrs:
                res = attrs[name]
                # if it is a descriptor object, bind it
                descr = getattr(type(res), '__get__', None)
                if descr is not None:
                    res = descr(
                        res,
                        None if obj is starttype else obj,
                        starttype)
                return res

        return super().__getattribute__(name)
</code>```

Body:
From here:

super( [ type [ , object-or-type ]] )

Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class. The search order is same as that used by getattr() except that the type itself is skipped.

If the second argument is omitted, the super object returned is
  unbound.

If the second argument is an object, isinstance(obj, type) must be
  true.

If the second argument is a type, issubclass(type2, type) must be
  true (this is useful for classmethods).

If I am correct, a type is a class, and a class is a type. A class
is an object, so a type is also an object.  Why does the quote
distinguish the two cases when the second argument being an object
when it is a type?

When the second argument is a type, why is issubclass(type2, type)
required to be true?

What is the type of the super object    returned by super in each of the three cases respectively? Or how do you determine the type of the super object returned by super?

When the second argument is an object, because "The search order is same as that used by getattr() except that the type itself is skipped", I guessed that the type of the superobject returned by super function should be a subclass of any ancestry class of the first argument type, but I found that it is actually not by testing with issubclass. So did I misunderstand something?

Body:
You seem to be confusing the word type with the type() built-in. Here they simply references the first argument passed into super().

What the documentation tells you is that if you pass in two arguments, then the second argument either has to be an instance of the first argument, or it has to be a subclass. In other words, either isinstance(first_argument, second_argument) or issubclass(first_argument, second_argument) must be true. There is no other meaning here.

Just like int() or str() or any of the other built-in types, the type of the object returned by calling super() is that type. There are no separate types returned for different arguments. See the C source code defining the object.

The super() object implements a __getattribute__ hook that implements specific attribute behaviour. The documentation tells you that the rules for attribute lookups are the same as for getattr() (but with the documented MRO skip), but that does not mean that super() returns an ancestor class.

What actually happens is that super().__getattribute__ takes the MRO of the second argument (either type(instance).__mro__ or cls.__mro__, depending on wether isinstance() or issubclass() was true), find the first argument in that sequence and start testing for attributes after that. Because the MRO is scanned for the (type of) the second argument first, it does have to be findable, which is why the constraints are what they are.

In Pure Python, this is what super() does (simplified to focus on just the two argument behaviour):

def _supercheck(type_, obj):
    try:
        if issubclass(obj, type_):
            return obj
    except TypeError:
        # obj is not a type so issubclass throws a TypeError
        pass
    if isinstance(obj, type_):
        return type(obj)
    raise TypeError(
        "super(type, obj): obj must be an instance or subtype of type")

class super_:
    def __init__(self, type_, obj):
        # simplified for the two-argument case
        self.type_ = type_
        self.obj = obj
        self.obj_type = _supercheck(type_, obj)

    def __getattribute__(self, name):
        if name == '__class__':
            # __class__ should always come from this object, not
            # the represented MRO.
            return super().__getattribute__(name)

        # avoid infinite recursion issues
        sd = super().__getattribute__('__dict__')
        starttype = sd['obj_type']
        type_ = sd['type_']
        obj = sd['obj']

        mro = iter(starttype.__mro__)

        # skip past the start type in the MRO
        for tp in mro:
            if tp == type_:
                break

        # Search for the attribute on the remainder of the MRO
        for tp in mro:
            attrs = vars(tp)
            if name in attrs:
                res = attrs[name]
                # if it is a descriptor object, bind it
                descr = getattr(type(res), '__get__', None)
                if descr is not None:
                    res = descr(
                        res,
                        None if obj is starttype else obj,
                        starttype)
                return res

        return super().__getattribute__(name)