问:
How to get parameter name for the JMeter HTTP request?
I'm having a scenario where I want to upload a file to the web page. I recorded the scenario using the Blazemeter plugin and when I set the parameter name in the HTTP Request I have a problem. When I inspect the uploading element(upload button) it is not consistent with the name attribute. Then how can I set the parameter name?

答:
Your screenshot doesn't show the HTML DOM Input FileUpload Object so I'm afraid no one can help.

I would recommend just recording your file upload request using JMeter's HTTP(S) Test Script Recorder, JMeter is smart enough to detect the parameter name on its own.

Just make sure you copy your image to Jmeter's "bin" folder prior to recording as certain browsers don't report the full path of the file being uploaded therefore JMeter might fail to properly record the file upload event if the file is not present in its working directory.

See Recording File Uploads with JMeter guide for detailed instructions on setting up JMeter for recording file upload events.


来源: stackexchange

问:
Adding finished tweenlite to a timeline using deferred promise (Greensock)
We can add multiple tweens to a timeline, like what is explained in this post: https://ihatetomatoes.net/greensock-timelinelite-tutorial/

But how can we add a tween to a timeline only when it is complete? I am asking this is because my project uses tweenLite to create a canvas animation:

```<code>       var tween = TweenLite.to(
            { currentTime: 0 },
            300,
            {
                currentTime:300,
                onUpdate: drawFunction,
                onComplete: endFunction
            }
        );
</code>```

I am thinking of putting a deferred object and resolve it in my endFunction. But how can I get it back from onComplete and add the tween to the timeline? Any suggestion?

答:
First, Instead of TweenLite, please use TimelineLite.

Second, onComplete is a bit buggy. You should try calling a function in your timeline. The function will be called only after the previous tween is complete.

Third, You can also change the position of your tweens using the position parameters for advanced control. More details here : https://greensock.com/position-parameter

Code to create a timeline and call a code inside the timeline:

```<code>function myFunction(num) {
  console.log(num)
}

var tl = new TimelineMax();

tl.from($box, 1, {y: '-=40', autoAlpha: 0, ease:Power4.easeInOut}) // no comma or semi-colon
  .from($box2, 1, {y: '-=40', autoAlpha: 0, ease:Power4.easeInOut}) // no comma or semi-colon
  .from($box3, 1, {y: '-=40', autoAlpha: 0, ease:Power4.easeInOut}); // semi-colon after last tween
  .call(myFunction, ['1'])
</code>```

ContentLicense: CC BY-SA 3.0

Body:
We can add multiple tweens to a timeline, like what is explained in this post: https://ihatetomatoes.net/greensock-timelinelite-tutorial/

But how can we add a tween to a timeline only when it is complete? I am asking this is because my project uses tweenLite to create a canvas animation:

       var tween = TweenLite.to(
            { currentTime: 0 },
            300,
            {
                currentTime:300,
                onUpdate: drawFunction,
                onComplete: endFunction
            }
        );

I am thinking of putting a deferred object and resolve it in my endFunction. But how can I get it back from onComplete and add the tween to the timeline? Any suggestion?

Body:
First, Instead of TweenLite, please use TimelineLite.

Second, onComplete is a bit buggy. You should try calling a function in your timeline. The function will be called only after the previous tween is complete.

Third, You can also change the position of your tweens using the position parameters for advanced control. More details here : https://greensock.com/position-parameter

Code to create a timeline and call a code inside the timeline:

function myFunction(num) {
  console.log(num)
}

var tl = new TimelineMax();

tl.from($box, 1, {y: '-=40', autoAlpha: 0, ease:Power4.easeInOut}) // no comma or semi-colon
  .from($box2, 1, {y: '-=40', autoAlpha: 0, ease:Power4.easeInOut}) // no comma or semi-colon
  .from($box3, 1, {y: '-=40', autoAlpha: 0, ease:Power4.easeInOut}); // semi-colon after last tween
  .call(myFunction, ['1'])


问:
Need to fade in fade out text in sequence
I came across text that fades in and fades out one after the other.

In developer mode, I was able to see the opacity vary for the texts from 0 to 1 to 0 in a sequence. How is this achieved?

```<code><div class="text" style="opacity: 0;">The</div>
<div class="text" style="opacity: 0;">Nomads</div>
</code>```

答:
Here's a very simplistic approach using CSS3 Animations and the keyframes property (Please note I've edited this answer to include improvements from Frits' comment)

Although you might need to tweak it a little as

a text which fade in fade out one after the other

Is a pretty lose specification.

/* Define the key frames for animating the fade in / fade out */

@keyframes fade {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

/* attach the animations to the elements via their id attribute using a delay of 0s and 50% of the runtime respectively */

#one {
  animation: fade 3s infinite 0s;
}

#two {
  animation: fade 3s infinite 1.5s;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="one">
  This line of text will fade out as the next lines fade in
</p>
<p id="two">
  This line of text will fade in as the previous lines fade out
</p></code>```

Body:
I came across text that fades in and fades out one after the other.

In developer mode, I was able to see the opacity vary for the texts from 0 to 1 to 0 in a sequence. How is this achieved?

The

Nomads

Body:
Here's a very simplistic approach using CSS3 Animations and the keyframes property (Please note I've edited this answer to include improvements from Frits' comment)

Although you might need to tweak it a little as

a text which fade in fade out one after the other

Is a pretty lose specification.

/* Define the key frames for animating the fade in / fade out */

@keyframes fade {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

/* attach the animations to the elements via their id attribute using a delay of 0s and 50% of the runtime respectively */

#one {
  animation: fade 3s infinite 0s;
}

#two {
  animation: fade 3s infinite 1.5s;
}

<p id="one">
  This line of text will fade out as the next lines fade in
</p>
<p id="two">
  This line of text will fade in as the previous lines fade out
</p>


问:
How to load current item information if it is being clicked from listview
I am facing a problem with Android app.So. I have 3 activities that are opening one after another with OnItemClickListener. From first to second activity I have no trouble since I just have to load ArrayList in listview in the second activity.The third activity is opening when I click an item from the listview in second activity and in a third activity I want to open data from my database for the clicked item.
Here is some code:

1.The second activity:

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

    ListView listView = (ListView) findViewById(R.id.listView);
        myDB = new DatabaseHelper(this);

        ArrayList<String> theList = new ArrayList<>();
        Cursor data = myDB.getListContents();
        if(data.getCount() == 0){
            Toast.makeText(this, "There are no contents in this list!",Toast.LENGTH_LONG).show();
        }else{
            while(data.moveToNext()){
                theList.add(data.getString(1));
                ListAdapter listAdapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,theList);
                listView.setAdapter(listAdapter);
            }
    }
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intent = new Intent(ViewListContents.this, ElevatorInfo.class);
            startActivity(intent);
        }
    });
}
</code>```

2.Third activity where I want to get the opened item id from a database and load the third column from the database but have no idea how to do it and that is my actual question.Also, im doing the same thing as in second activity just to try to load the info from the third column in a listview but its also not working.

```<code>DatabaseHelper myDB;
@Override

    ListView listView = (ListView) findViewById(R.id.listView);
    myDB = new DatabaseHelper(this);

    ArrayList<String> theList = new ArrayList<>();
    Cursor data = myDB.getListContents();
    if (data.getCount() == 0) {
        Toast.makeText(this, "There are no contents in this list!", Toast.LENGTH_LONG).show();
    } else {
        while (data.moveToNext()) {
            theList.add(data.getString(2));
            ListAdapter listAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, theList);
            listView.setAdapter(listAdapter);
        }
    }
}

public void AddData(String newEntry) {

    boolean insertData = myDB.addData2(newEntry);

    if(insertData == true){
        Toast.makeText(this, "Data Successfully Inserted!", Toast.LENGTH_LONG).show();
    }else{
        Toast.makeText(this, "Something went wrong :(.", Toast.LENGTH_LONG).show();
    }
   }
 }
</code>```

3.My DatabaseHelper class.

```<code>@Override
public void onCreate(SQLiteDatabase db) {
    String createTable = "CREATE TABLE " + MyDatabase.ElevatorEntry.TABLE_NAME + " ( " + MyDatabase.ElevatorEntry.COL1  + "INTEGER PRIMARY KEY AUTOINCREMENT, " +
            MyDatabase.ElevatorEntry.COL2 + "TEXT"  + MyDatabase.ElevatorEntry.DATE + " TEXT " + " )";
    db.execSQL(createTable);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP IF TABLE EXISTS " + MyDatabase.ElevatorEntry.TABLE_NAME);
    onCreate(db);
}

public boolean addData(String item1) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(MyDatabase.ElevatorEntry.COL2, item1);

    long result = db.insert(MyDatabase.ElevatorEntry.TABLE_NAME, null, contentValues);

    if (result == -1) {
        return false;
    } else {
        return true;
    }
}
public boolean addData2(String item2) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(MyDatabase.ElevatorEntry.DATE, item2);

public Cursor getListContents(){
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor data = db.rawQuery("SELECT * FROM " + MyDatabase.ElevatorEntry.TABLE_NAME, null );
    return data;
   }

}
</code>```

答:
you have wrote a lot of code in the question, stay focused on what you want to ask about

side note:  why this

```<code>ListAdapter listAdapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,theList);
listView.setAdapter(listAdapter);
</code>```

is in the while loop? this should be called once, when the loop ends and all the items have been added to the list theList

```<code>while(data.moveToNext()){
    theList.add(data.getString(1));
}//while loop
ListAdapter listAdapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,theList);
listView.setAdapter(listAdapter);
</code>```

Now, for your question, at onItemClick() use position to get the item from theList then do whatever you want with it:

```<code>@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    String selected = theList.get(position);
    Intent intent = new Intent(ViewListContents.this, ElevatorInfo.class);
    intent.putExtra("SELECTED_ITEM",selected);
    startActivity(intent);
}
</code>```

now you can add selected as an extra in the intent and start the next activity.

EDIT:
For how to read the value from the 2nd activity. check this answer
you need to use getIntent().getStringExtra("SELECTED_ITEM");.

Body:
I am facing a problem with Android app.So. I have 3 activities that are opening one after another with OnItemClickListener. From first to second activity I have no trouble since I just have to load ArrayList in listview in the second activity.The third activity is opening when I click an item from the listview in second activity and in a third activity I want to open data from my database for the clicked item.
Here is some code:

1.The second activity:

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

    ListView listView = (ListView) findViewById(R.id.listView);
        myDB = new DatabaseHelper(this);

        ArrayList<String> theList = new ArrayList<>();
        Cursor data = myDB.getListContents();
        if(data.getCount() == 0){
            Toast.makeText(this, "There are no contents in this list!",Toast.LENGTH_LONG).show();
        }else{
            while(data.moveToNext()){
                theList.add(data.getString(1));
                ListAdapter listAdapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,theList);
                listView.setAdapter(listAdapter);
            }
    }
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intent = new Intent(ViewListContents.this, ElevatorInfo.class);
            startActivity(intent);
        }
    });
}

2.Third activity where I want to get the opened item id from a database and load the third column from the database but have no idea how to do it and that is my actual question.Also, im doing the same thing as in second activity just to try to load the info from the third column in a listview but its also not working.

DatabaseHelper myDB;
@Override

    ListView listView = (ListView) findViewById(R.id.listView);
    myDB = new DatabaseHelper(this);

    ArrayList<String> theList = new ArrayList<>();
    Cursor data = myDB.getListContents();
    if (data.getCount() == 0) {
        Toast.makeText(this, "There are no contents in this list!", Toast.LENGTH_LONG).show();
    } else {
        while (data.moveToNext()) {
            theList.add(data.getString(2));
            ListAdapter listAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, theList);
            listView.setAdapter(listAdapter);
        }
    }
}

public void AddData(String newEntry) {

    boolean insertData = myDB.addData2(newEntry);

    if(insertData == true){
        Toast.makeText(this, "Data Successfully Inserted!", Toast.LENGTH_LONG).show();
    }else{
        Toast.makeText(this, "Something went wrong :(.", Toast.LENGTH_LONG).show();
    }
   }
 }

3.My DatabaseHelper class.

@Override
public void onCreate(SQLiteDatabase db) {
    String createTable = "CREATE TABLE " + MyDatabase.ElevatorEntry.TABLE_NAME + " ( " + MyDatabase.ElevatorEntry.COL1  + "INTEGER PRIMARY KEY AUTOINCREMENT, " +
            MyDatabase.ElevatorEntry.COL2 + "TEXT"  + MyDatabase.ElevatorEntry.DATE + " TEXT " + " )";
    db.execSQL(createTable);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP IF TABLE EXISTS " + MyDatabase.ElevatorEntry.TABLE_NAME);
    onCreate(db);
}

public boolean addData(String item1) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(MyDatabase.ElevatorEntry.COL2, item1);

    long result = db.insert(MyDatabase.ElevatorEntry.TABLE_NAME, null, contentValues);

    if (result == -1) {
        return false;
    } else {
        return true;
    }
}
public boolean addData2(String item2) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(MyDatabase.ElevatorEntry.DATE, item2);

public Cursor getListContents(){
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor data = db.rawQuery("SELECT * FROM " + MyDatabase.ElevatorEntry.TABLE_NAME, null );
    return data;
   }

}

Body:
you have wrote a lot of code in the question, stay focused on what you want to ask about

side note:  why this

ListAdapter listAdapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,theList);
listView.setAdapter(listAdapter);

is in the while loop? this should be called once, when the loop ends and all the items have been added to the list theList

while(data.moveToNext()){
    theList.add(data.getString(1));
}//while loop
ListAdapter listAdapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,theList);
listView.setAdapter(listAdapter);

Now, for your question, at onItemClick() use position to get the item from theList then do whatever you want with it:

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    String selected = theList.get(position);
    Intent intent = new Intent(ViewListContents.this, ElevatorInfo.class);
    intent.putExtra("SELECTED_ITEM",selected);
    startActivity(intent);
}

now you can add selected as an extra in the intent and start the next activity.

EDIT:
For how to read the value from the 2nd activity. check this answer
you need to use getIntent().getStringExtra("SELECTED_ITEM");.


问:
How to adjust my code to this situation for SAX XML parsing in Android
On advice on someone here on Stackoverflow I changed my method of parsing to the SAXParser.

Thanks to different tutorials I'm able to get it to work, and I have to say that it does work faster (which is very important for my app).

The problem, however, is that my XML file goes deeper than the tutorial's example XML's I've seen.

This a sample of my XML file:

```<code><Message>

  <Service>servicename</Service>

  <Insurances>

    <BreakdownInsurance>

      <Name>Insurance name</Name>

      <InsuranceNR/>

      <LicenseNr/>

    </BreakdownInsurance>

    <CarDamageInsurance>

      <Name>Insurance name 2</Name>

      <InsuranceNR></InsuranceNR>

    </CarDamageInsurance>
  </Insurances>

  <Personal>
    <Name>my name</Name>
  </Personal>
</Message>
</code>```

I can get the personal details like name, but my code doesn't seem to work with the insurances. I think this is because it's one node more.

This is the code I'm using in my Handler class:

```<code>@Override
public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
    currentElement = true;
    if (localName.equals("Message")) {
        geg = new GegevensXML();
    }
}

@Override
public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
    currentElement = false;

    /********** Autopech **********/
    if (localName.equals("Name")) {
        geg.setAutopechMaatschappij(currentValue);
    }
    else if (localName.equals("InsuranceNR")){
        geg.setAutopechPolis(currentValue);
    }
    else if (localName.equals("LicenseNr")){
        geg.setAutopechKenteken(currentValue);
    }

@Override
public void characters(char ch[], int start, int length) {
    if (currentElement) {
        currentValue = new String(ch, start, length);
        currentElement = false;
    }
</code>```

So how must I adjust it?

答:
```@Override
public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
    currentElement = true;
    if (localName.equals("Message")) {
        geg = new GegevensXML();
    }
    if(localName.equals("BreakdownInsurance"))
    {
      BreakdownInsurance = true;
    }
}

@Override
public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
    currentElement = false;

    /********** Autopech **********/
    if (localName.equals("Name"))
    {
     if(BreakdownInsurance)
     {
       geg.setBreakdownInsuranceName(currentValue);

       BreakdownInsurance = false;
     }
     else
     {
       geg.setAutopechMaatschappij(currentValue);
      }

    }
    else if (localName.equals("InsuranceNR")){
        geg.setAutopechPolis(currentValue);
    }
    else if (localName.equals("LicenseNr")){
        geg.setAutopechKenteken(currentValue);
    }

```

Similarly do it for other cases... 'BreakdownInsurance' is a boolean. use it as a Flag...

ContentLicense: CC BY-SA 2.5

Body:
On advice on someone here on Stackoverflow I changed my method of parsing to the SAXParser.

Thanks to different tutorials I'm able to get it to work, and I have to say that it does work faster (which is very important for my app).

The problem, however, is that my XML file goes deeper than the tutorial's example XML's I've seen.

This a sample of my XML file:

<Message>

  <Service>servicename</Service>

  <Insurances>

    <BreakdownInsurance>

      <Name>Insurance name</Name>

      <InsuranceNR/>

      <LicenseNr/>

    </BreakdownInsurance>

    <CarDamageInsurance>

      <Name>Insurance name 2</Name>

      <InsuranceNR></InsuranceNR>

    </CarDamageInsurance>
  </Insurances>

  <Personal>
    <Name>my name</Name>
  </Personal>
</Message>

I can get the personal details like name, but my code doesn't seem to work with the insurances. I think this is because it's one node more.

This is the code I'm using in my Handler class:

@Override
public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
    currentElement = true;
    if (localName.equals("Message")) {
        geg = new GegevensXML();
    }
}

@Override
public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
    currentElement = false;

    /********** Autopech **********/
    if (localName.equals("Name")) {
        geg.setAutopechMaatschappij(currentValue);
    }
    else if (localName.equals("InsuranceNR")){
        geg.setAutopechPolis(currentValue);
    }
    else if (localName.equals("LicenseNr")){
        geg.setAutopechKenteken(currentValue);
    }

@Override
public void characters(char ch[], int start, int length) {
    if (currentElement) {
        currentValue = new String(ch, start, length);
        currentElement = false;
    }

So how must I adjust it?

Body:
@Override
public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
    currentElement = true;
    if (localName.equals("Message")) {
        geg = new GegevensXML();
    }
    if(localName.equals("BreakdownInsurance"))
    {
      BreakdownInsurance = true;
    }
}

@Override
public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
    currentElement = false;

    /********** Autopech **********/
    if (localName.equals("Name"))
    {
     if(BreakdownInsurance)
     {
       geg.setBreakdownInsuranceName(currentValue);

       BreakdownInsurance = false;
     }
     else
     {
       geg.setAutopechMaatschappij(currentValue);
      }

    }
    else if (localName.equals("InsuranceNR")){
        geg.setAutopechPolis(currentValue);
    }
    else if (localName.equals("LicenseNr")){
        geg.setAutopechKenteken(currentValue);
    }

Similarly do it for other cases... 'BreakdownInsurance' is a boolean. use it as a Flag...


问:
How to add the search bar to mobile menu in wordpress?
I've added this code to my functions.php file:

```<code>function wpgood_nav_search( $items, $args ) {
$items .= '<li>' . get_search_form( false ) . '</li>';
return $items;
}
add_filter( 'wp_nav_menu_items','wpgood_nav_search', 10, 2 );
</code>```

I've found it here:
adding search bar to the nav menu in wordpress

The problem: this code adds the search bar to desktop and mobile menus, but I need to add the search bar only to my mobile menu, because the desktop version of my site already has a search widget in the left sidebar.

How can I do this? Please, help me. Thanks!

Initializiation of my menus in functions.php :

```<code>// Initialize navigation menus
register_nav_menus(
    array(
        'primary-menu' => esc_html__( 'Primary Menu', 'bento' ),
        'footer-menu' => esc_html__( 'Footer Menu', 'bento' ),
    )
);
</code>```

Thank you so much for your help! Finally I have decided to use my initial code and edit the searchbar's position and style with css, because I am not so good in coding:)

答:
Basically do you do that by several process. Like following

By using jquery append function you can do. Paste this code in template JS file

$("here_put_menu_selector").append('

<form role="search" method="get" id="searchform" class="search-form" action="https://yourdomain.com/">

  <input type="text" value="" name="s" id="s" class="search-form-input" placeholder="search any"/>
  <input type="submit" id="searchsubmit" class="button submit-button" value="Search"/>

</form>

');```

Only on mobile devices visible that using CSS display property & hide that part from desktop/tablet devices.

Body:
I've added this code to my functions.php file:

function wpgood_nav_search( $items, $args ) {
$items .= '
' . get_search_form( false ) . '
';
return $items;
}
add_filter( 'wp_nav_menu_items','wpgood_nav_search', 10, 2 );

I've found it here:
adding search bar to the nav menu in wordpress

The problem: this code adds the search bar to desktop and mobile menus, but I need to add the search bar only to my mobile menu, because the desktop version of my site already has a search widget in the left sidebar.

How can I do this? Please, help me. Thanks!

Initializiation of my menus in functions.php :

// Initialize navigation menus
register_nav_menus(
    array(
        'primary-menu' => esc_html__( 'Primary Menu', 'bento' ),
        'footer-menu' => esc_html__( 'Footer Menu', 'bento' ),
    )
);

Thank you so much for your help! Finally I have decided to use my initial code and edit the searchbar's position and style with css, because I am not so good in coding:)

Body:
Basically do you do that by several process. Like following

By using jquery append function you can do. Paste this code in template JS file

$("here_put_menu_selector").append('
<li>
<form role="search" method="get" id="searchform" class="search-form" action="https://yourdomain.com/">
 <div class="search-form-wrap">
  <input type="text" value="" name="s" id="s" class="search-form-input" placeholder="search any"/>
  <input type="submit" id="searchsubmit" class="button submit-button" value="Search"/>
 </div>
</form>
</li>
');

Only on mobile devices visible that using CSS display property & hide that part from desktop/tablet devices.


问:
R Passing Name of List Objects to List Objects Themselves
I receive a named list of data frames using an R API to a data vendor. Below is how I would struct a similar structure.

```<code>spec1 <- data.frame(speed = 100, wt = 5, price = 10)
spec2 <- data.frame(speed = 1000, wt = 1, price = 100)
spec3 <- data.frame(speed = 1, wt = 50, price = 5)
mylist <- list(car = spec1,exotic = spec2, truck = spec3)
</code>```

My goal is to turn this into a flat data frame like below so that I can export it into an SQL database.

```<code>car_type   speed     wt     price
--------   ------    ----   -----
car        100       5      10
exotic     1000      1      100
truck      1         50     5
</code>```

My problem is that the identifier for "car_type" is stored as the name of the data frame in the list, and I don't know how to pass it to a repeat function to populate the table.

For example I use the following to get the car_type from the names of the items in the list

```<code>car_type <- sapply(seq_along(mylist), function(x) names(mylist)[x])
</code>```

And then I use the following to repeat the a car_type (substituted by "X") in the underlying tables and then append.

```<code>category <- lapply(mylist, function(y) rep("X" ,dim(y)[1]))
mylist <- lapply(seq_along(mylist), function(x)
</code>```

However, I can't seem to manage to pass the names found in car_type back into create a new category column in my dataset, which will persist when it's flattened.

答:
Maybe more readable:</p>

```<code>library(magrittr)
mylist %>% do.call(rbind,.) %>% transform(car_type = rownames(.)) %>% set_rownames(NULL)
</code>```

Body:
I receive a named list of data frames using an R API to a data vendor. Below is how I would struct a similar structure.

spec1 <- data.frame(speed = 100, wt = 5, price = 10)
spec2 <- data.frame(speed = 1000, wt = 1, price = 100)
spec3 <- data.frame(speed = 1, wt = 50, price = 5)
mylist <- list(car = spec1,exotic = spec2, truck = spec3)

My goal is to turn this into a flat data frame like below so that I can export it into an SQL database.

car_type   speed     wt     price
--------   ------    ----   -----
car        100       5      10
exotic     1000      1      100
truck      1         50     5

My problem is that the identifier for "car_type" is stored as the name of the data frame in the list, and I don't know how to pass it to a repeat function to populate the table.

For example I use the following to get the car_type from the names of the items in the list

car_type <- sapply(seq_along(mylist), function(x) names(mylist)[x])

And then I use the following to repeat the a car_type (substituted by "X") in the underlying tables and then append.

category <- lapply(mylist, function(y) rep("X" ,dim(y)[1]))
mylist <- lapply(seq_along(mylist), function(x)

However, I can't seem to manage to pass the names found in car_type back into create a new category column in my dataset, which will persist when it's flattened.

Body:
Maybe more readable:

library(magrittr)
mylist %>% do.call(rbind,.) %>% transform(car_type = rownames(.)) %>% set_rownames(NULL)


问:
Loading MNIST dataset from Keras JS in node
How to load MNIST dataset from KerasJS in Node?

I imported their header file

```<code>const KerasJS = require('keras-js')
var mnist = KerasJS.mnist
</code>```

This gives no error,
But whenever i try the load_data()

```<code>var x_train, y_train, x_test, y_test = mnist.load_data()
</code>```

It gives error

```<code>TypeError: Cannot read property 'load_data' of undefined
</code>```

So what is the acceptable syntax to load MNIST dataset by KerasJS in Node?

I also can't find anything much on their documentation.

答:
I found out another way to import mnist dataset in Nodejs,
instead of requiring Keras-js use mnist</p>

```<code>var mnist = require("mnist");
var set = mnist.set(8000,2000);
var trainingSet = set.training;
var testSet = set.test;
</code>```

Body:
How to load MNIST dataset from KerasJS in Node?

I imported their header file

const KerasJS = require('keras-js')
var mnist = KerasJS.mnist

This gives no error,
But whenever i try the load_data()

var x_train, y_train, x_test, y_test = mnist.load_data()

It gives error

TypeError: Cannot read property 'load_data' of undefined

So what is the acceptable syntax to load MNIST dataset by KerasJS in Node?

I also can't find anything much on their documentation.

Body:
I found out another way to import mnist dataset in Nodejs,
instead of requiring Keras-js use mnist

var mnist = require("mnist");
var set = mnist.set(8000,2000);
var trainingSet = set.training;
var testSet = set.test;


问:
Emulator failed to start
When i try to launch an emulator based on system image Android 4.4 armeabi-v7a (because my system does not support virtualization) in Android Studio, it starts and fades away within 2-3 seconds and the status bar shows "Starting device".

When i try to start it through cmd by going to the path "C:\Users\USER_NAME\AppData\Local\Android\sdk\tools" and using the command "emulator -avd AVD_NAME -memory 768 -no-accel -gpu on" the following error comes: Error while starting emulator

Please help.

答:
Have you try to open your bios setting  and enable virtualization there?

If virtualization is not in pc then you can install zenymotion in the system

Title: Emulator failed to start


问:
the name of the driver class for the datasource is missing
From How to set up a JDBC Connection Pool on Glassfish I would like to connect MyQueue to the Birds JDBC resource in Glassfish.  I'm getting an error similar to: The name of the driver class for the datasource is missing; the only difference being that I'm using MySQl instead of PostgreSql:

birds resource:

successful ping:

(the ping does indicate that the connection properties are correct?)

facelets:

```<code><!DOCTYPE    html  PUBLIC "-//W3C//DTD XHTML 1.0  Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core">
    <h:head></h:head>
    <h:body>
        This and everything before will be ignored
        <ui:composition template="template.xhtml">
            <ui:define name="navigation">
                <ui:include src="menu.xhtml"/>
            </ui:define>
            <ui:define name="main">
                <h1>bird</h1>
                #{myQueue.next}
            </ui:define>
        </ui:composition>
        This and everything after will be ignored
    </h:body>
</html>
</code>```

and the bean:

```<code>package dur;

import java.io.Serializable;
import java.util.logging.Logger;
import javax.inject.Named;
import javax.ejb.Singleton;
import javax.enterprise.context.ApplicationScoped;
//import javax.inject.Singleton;

@Named
@ApplicationScoped
@Singleton
public class MyQueue implements Serializable {

    private static final long serialVersionUID = 403250971215465050L;
    private final Logger log = Logger.getLogger(MyQueue.class.getName());
    private int next = 1;

    public MyQueue() {
    }

    public int getNext() {
        log.info("next\t" + next);
        return next++;
    }
}
</code>```

The bean and facelet are functioning correctly, I just want to connect MyQueue to the database.  I would like to use JPA to connect to the database.

The option to edit the field is grayed out.

--------------------------------------------edit---------------------------------

Netbeans did some magic and created the connection (I think) by right clicking the enterprise app and select new -> glassfish > jdbc connection pool.

sun-resources.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE resources PUBLIC "-//Sun Microsystems, Inc.//DTD Application Server 9.0 Resource Definitions //EN" "http://www.sun.com/software/appserver/dtds/sun-resources_1_3.dtd">
<resources>
  <jdbc-resource enabled="true" jndi-name="jdbc/birdsPool" object-type="user" pool-name="birdsPool">
    <description/>
  </jdbc-resource>
  <jdbc-connection-pool allow-non-component-callers="false" associate-with-thread="false" connection-creation-retry-attempts="0" connection-creation-retry-interval-in-seconds="10" connection-leak-reclaim="false" connection-leak-timeout-in-seconds="0" connection-validation-method="auto-commit" datasource-classname="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" fail-all-connections="false" idle-timeout-in-seconds="300" is-connection-validation-required="false" is-isolation-level-guaranteed="true" lazy-connection-association="false" lazy-connection-enlistment="false" match-connections="false" max-connection-usage-count="0" max-pool-size="32" max-wait-time-in-millis="60000" name="birdsPool" non-transactional-connections="false" pool-resize-quantity="2" res-type="javax.sql.ConnectionPoolDataSource" statement-timeout-in-seconds="-1" steady-pool-size="8" validate-atmost-once-period-in-seconds="0" wrap-jdbc-objects="false">
    <property name="URL" value="jdbc:mysql://localhost:3306/legacy?zeroDateTimeBehavior=convertToNull"/>
    <property name="User" value="user"/>
    <property name="Password" value="gtjropjre"/>
  </jdbc-connection-pool>
</resources>
</code>```

persistence.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
  <persistence-unit name="EnterpriseBirdsJPA-warPU" transaction-type="JTA">
    <jta-data-source>jdbc/birdsPool</jta-data-source>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties/>
  </persistence-unit>
</persistence>
</code>```

I'm a bit uneasy with sun-resources.xml and would prefer to see that configuration directly on glassfish.  I'm not exactly sure that this will work, but it allowed netbeans to then create an entity class from this connection, so that seems like progress.  Again, though, that sun-resources.xml isn't actually in glassfish makes this a less than perfect solution.

答:
To solve the same issue you had, I had to add a "driverClass" additional properties in your connection pool (beside "password", "user", "URL").
Its value would be "com.mysql.jdbc.Driver".

Source : http://www.blogarama.com/programming-blogs/194794-wings-hermes-berins-infosec-blog/259237-glassfish-netbeans-name-driver-class-for-datasource-missing

Body:
From How to set up a JDBC Connection Pool on Glassfish I would like to connect MyQueue to the Birds JDBC resource in Glassfish.  I'm getting an error similar to: The name of the driver class for the datasource is missing; the only difference being that I'm using MySQl instead of PostgreSql:

birds resource:

successful ping:

(the ping does indicate that the connection properties are correct?)

facelets:

<!DOCTYPE    html  PUBLIC "-//W3C//DTD XHTML 1.0  Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <h:head></h:head>
    <h:body>
        This and everything before will be ignored
        <ui:composition template="template.xhtml">
            <ui:define name="navigation">
                <ui:include src="menu.xhtml"/>
            </ui:define>
            <ui:define name="main">

bird

                #{myQueue.next}
            </ui:define>
        </ui:composition>
        This and everything after will be ignored
    </h:body>

and the bean:

package dur;

import java.io.Serializable;
import java.util.logging.Logger;
import javax.inject.Named;
import javax.ejb.Singleton;
import javax.enterprise.context.ApplicationScoped;
//import javax.inject.Singleton;

@Named
@ApplicationScoped
@Singleton
public class MyQueue implements Serializable {

    private static final long serialVersionUID = 403250971215465050L;
    private final Logger log = Logger.getLogger(MyQueue.class.getName());
    private int next = 1;

    public MyQueue() {
    }

    public int getNext() {
        log.info("next\t" + next);
        return next++;
    }
}

The bean and facelet are functioning correctly, I just want to connect MyQueue to the database.  I would like to use JPA to connect to the database.

The option to edit the field is grayed out.

--------------------------------------------edit---------------------------------

Netbeans did some magic and created the connection (I think) by right clicking the enterprise app and select new -> glassfish > jdbc connection pool.

sun-resources.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE resources PUBLIC "-//Sun Microsystems, Inc.//DTD Application Server 9.0 Resource Definitions //EN" "http://www.sun.com/software/appserver/dtds/sun-resources_1_3.dtd">
<resources>
  <jdbc-resource enabled="true" jndi-name="jdbc/birdsPool" object-type="user" pool-name="birdsPool">
    <description/>
  </jdbc-resource>
  <jdbc-connection-pool allow-non-component-callers="false" associate-with-thread="false" connection-creation-retry-attempts="0" connection-creation-retry-interval-in-seconds="10" connection-leak-reclaim="false" connection-leak-timeout-in-seconds="0" connection-validation-method="auto-commit" datasource-classname="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" fail-all-connections="false" idle-timeout-in-seconds="300" is-connection-validation-required="false" is-isolation-level-guaranteed="true" lazy-connection-association="false" lazy-connection-enlistment="false" match-connections="false" max-connection-usage-count="0" max-pool-size="32" max-wait-time-in-millis="60000" name="birdsPool" non-transactional-connections="false" pool-resize-quantity="2" res-type="javax.sql.ConnectionPoolDataSource" statement-timeout-in-seconds="-1" steady-pool-size="8" validate-atmost-once-period-in-seconds="0" wrap-jdbc-objects="false">
    <property name="URL" value="jdbc:mysql://localhost:3306/legacy?zeroDateTimeBehavior=convertToNull"/>
    <property name="User" value="user"/>
    <property name="Password" value="gtjropjre"/>
  </jdbc-connection-pool>
</resources>

persistence.xml:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
  <persistence-unit name="EnterpriseBirdsJPA-warPU" transaction-type="JTA">
    <jta-data-source>jdbc/birdsPool</jta-data-source>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties/>
  </persistence-unit>
</persistence>

I'm a bit uneasy with sun-resources.xml and would prefer to see that configuration directly on glassfish.  I'm not exactly sure that this will work, but it allowed netbeans to then create an entity class from this connection, so that seems like progress.  Again, though, that sun-resources.xml isn't actually in glassfish makes this a less than perfect solution.


问:
Template match nodes that have a particular child node - streaming XSLT
I want to select the Worker nodes, that have a Plan child node coming up in Addl_Information section

```<code><xsl:mode streamable="yes"/>
<xsl:template match="Worker[Addl_Information/Plan]">
</code>```

When I use the above code, I get error from Saxon-EE 9.6.0.5 processor saying

```<code>XTSE3430: Template rule is declared streamable but it does not satisfy the streamability rules. * The match pattern is not motionless
</code>```

What am I doing wrong?

I see examples of (similar) motionless patterns in w3c site but it is not working for me, kindly advise.

Update: Here is my stylesheet. I am trying to include only the people who have a record of a certain plan in their worker data. Note, the below patth variable was another angle I was trying to evaluate - basically having an IF condition right after, around the remaining code. That also does not work.

```<code>    <?xml version="1.0" encoding="UTF-8"?>
    <xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
        <xsl:mode streamable="yes"/>
        <xsl:template match="Worker_Sync">
            <File>
                <xsl:apply-templates select="Worker"/>
            </File>
        </xsl:template>

        <xsl:template match="Worker">
            <xsl:variable name="ThisPerson" select="copy-of()"/>
            <xsl:variable name="patth" select="Additional_Information/ws:plan"/>
            <xsl:if test="$ThisPerson/$patth">
                <Row>
                    <A1_Account_Number><xsl:value-of select="$ThisPerson/Additional_Information/Account_Number"/></A1_Account_Number>
                    <A2_Employee_Number>...</A2_Employee_Number>
                </Row>
            </xsl:if>
        </xsl:template>
    </xsl:stylesheet>
</code>```

答:
I would suggest to use

```<code>    <xsl:template match="Worker_Sync">
        <File>
            <xsl:apply-templates select="copy-of(Worker)[Addl_Information/Plan]" mode="some-non-streamable-mode"/>
        </File>
    </xsl:template>
</code>```

then in your template for Worker you don't need the test and just

```<code>    <xsl:template match="Worker" mode="some-non-streamable-mode">
            <Row>
                <A1_Account_Number><xsl:value-of select="Additional_Information/Account_Number"/></A1_Account_Number>
                <A2_Employee_Number>...</A2_Employee_Number>
            </Row>
    </xsl:template>
</code>```

Body:
I want to select the Worker nodes, that have a Plan child node coming up in Addl_Information section

<xsl:mode streamable="yes"/>
<xsl:template match="Worker[Addl_Information/Plan]">

When I use the above code, I get error from Saxon-EE 9.6.0.5 processor saying

XTSE3430: Template rule is declared streamable but it does not satisfy the streamability rules. * The match pattern is not motionless

What am I doing wrong?

I see examples of (similar) motionless patterns in w3c site but it is not working for me, kindly advise.

Update: Here is my stylesheet. I am trying to include only the people who have a record of a certain plan in their worker data. Note, the below patth variable was another angle I was trying to evaluate - basically having an IF condition right after, around the remaining code. That also does not work.

    <?xml version="1.0" encoding="UTF-8"?>
    <xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
        <xsl:mode streamable="yes"/>
        <xsl:template match="Worker_Sync">
            <File>
                <xsl:apply-templates select="Worker"/>
            </File>
        </xsl:template>

        <xsl:template match="Worker">
            <xsl:variable name="ThisPerson" select="copy-of()"/>
            <xsl:variable name="patth" select="Additional_Information/ws:plan"/>
            <xsl:if test="$ThisPerson/$patth">
                <Row>
                    <A1_Account_Number><xsl:value-of select="$ThisPerson/Additional_Information/Account_Number"/></A1_Account_Number>
                    <A2_Employee_Number>...</A2_Employee_Number>
                </Row>
            </xsl:if>
        </xsl:template>
    </xsl:stylesheet>

Body:
I would suggest to use

    <xsl:template match="Worker_Sync">
        <File>
            <xsl:apply-templates select="copy-of(Worker)[Addl_Information/Plan]" mode="some-non-streamable-mode"/>
        </File>
    </xsl:template>

then in your template for Worker you don't need the test and just

    <xsl:template match="Worker" mode="some-non-streamable-mode">
            <Row>
                <A1_Account_Number><xsl:value-of select="Additional_Information/Account_Number"/></A1_Account_Number>
                <A2_Employee_Number>...</A2_Employee_Number>
            </Row>
    </xsl:template>


问:
m2eclipse: add group id to project name when importing existing maven project into Eclipse
in Eclipse I use file -> import -> existing maven project to create Eclipse-projects for existing Maven projects. Unfortunately the names of the created Eclipse projects equals the name of the Maven-projects and do not contain the group id.
For the maven goal eclipse:eclipse you can set the parameter "addGroupIdToProjectName". How can I set this parameter for the project creation by m2eclipse?

Thanks for answers,
Timk

答:
up to now I could not find any possibility to set the name for the Eclipse-projects to [groupId].[artifactId] globally. But you can set it every time you import existing Maven projects into eclipse: In the import-dialog open the "advanced" options and set the "name template" to "[groupId].[artifactId]".

Tomka.


问:
Only allow certain characters to be entered in database
I was checking for an answer to only accept certain type of characters and ignoring some.

I found a link in stack itself, here

But, even though that prevents from entering the data in text box, anyone with a little knowledge of how to inspect the content and delete the pattern from client side will allow it to enter any detail it wants and send to database.

Is there any way I can prevent it for my website? I don't want certain characters like space, semicolon, etc.

Frontend in html & php
Backend in MySQL

答:
It could be done with pattern attribute on clients side, but HTML5 textarea element does not support the pattern attribute.

The another way is to use JavaScript (as you mentioned)

```<code>var text = $('textarea').val();
var expres = /[^a-zA-Z0-9\!\@\#\$\%\^\*\|]+/;
if(expres.test(text)){
     //... some action
}
</code>```

If you would like to replace invalid characters, you can use jQuery function replace() which is similar to preg_replace() in PHP and it accepts regular expresions.

You could check validity on server side (in PHP) too (before inserting the values to db)

```<code>preg_replace("/[^A-Za-z0-9 ]/", '', $string);
</code>```

Body:
It could be done with pattern attribute on clients side, but HTML5 textarea element does not support the pattern attribute.

The another way is to use JavaScript (as you mentioned)

var text = $('textarea').val();
var expres = /[^a-zA-Z0-9\!\@\#\$\%\^\*\|]+/;
if(expres.test(text)){
     //... some action
}

If you would like to replace invalid characters, you can use jQuery function replace() which is similar to preg_replace() in PHP and it accepts regular expresions.

You could check validity on server side (in PHP) too (before inserting the values to db)

preg_replace("/[^A-Za-z0-9 ]/", '', $string);


问:
Jquery - Scroll to bottom not working within bootstrap modal
I am doing a simple task of opening a bootstrap modal & there is a div within that modal with scrollbar & i am scrolling directly to the bottom.

Below is my code :-

```<code><div id="ul_chats" style="height: 300px; overflow: auto;">
....
</div>

jq.ajax({
                url : "/Controller/GetComments",
                type : "get",
                dataType: "html",
                async: false,
                success : function(dataHtml) {
                    jq(".partialChats").html(dataHtml);
                    jq("#chatModal").modal('toggle');
                }
            });

            var objDiv = document.getElementById("ul_chats");
            objDiv.scrollTop = objDiv.scrollHeight;
</code>```

My Modal opens up but the div is not scrolled to the bottom. If i execute last 2 lines from the console then the div gets to the bottom.

答:
Try a code like this

```<code>$("#ul_chats").animate({ scrollTop: $("#ul_chats").height() }, "slow");
</code>```

if it does not work where you put the scroll, try to put it inside the sucess:

```<code> success : function(dataHtml) {
                jq(".partialChats").html(dataHtml);
                jq("#chatModal").modal('toggle');
                $("#ul_chats").animate({ scrollTop: $("#ul_chats").height() }, "slow");
            }
</code>```

Body:
I am doing a simple task of opening a bootstrap modal & there is a div within that modal with scrollbar & i am scrolling directly to the bottom.

Below is my code :-

....

jq.ajax({
                url : "/Controller/GetComments",
                type : "get",
                dataType: "html",
                async: false,
                success : function(dataHtml) {
                    jq(".partialChats").html(dataHtml);
                    jq("#chatModal").modal('toggle');
                }
            });

            var objDiv = document.getElementById("ul_chats");
            objDiv.scrollTop = objDiv.scrollHeight;

My Modal opens up but the div is not scrolled to the bottom. If i execute last 2 lines from the console then the div gets to the bottom.

Body:
Try a code like this

$("#ul_chats").animate({ scrollTop: $("#ul_chats").height() }, "slow");

if it does not work where you put the scroll, try to put it inside the sucess:

 success : function(dataHtml) {
                jq(".partialChats").html(dataHtml);
                jq("#chatModal").modal('toggle');
                $("#ul_chats").animate({ scrollTop: $("#ul_chats").height() }, "slow");
            }


问:
LEFT JOIN and WHERE clause - list all records even those with a value of null
The goal is to display on a grid a list of all sellers with sales and values.

The list of sellers should always be displayed, even when they have no sales.

Something like:

```<code>seller | sales | value
 John      10      1000
 Marie     20      2000
 Jamie     15      1500
 Arnold     0         0
 Peter      0         0
</code>```

For that the next query works fine:

```<code> SELECT tsl.sellers,
       COUNT(ts.sales) AS sales,
       COALESCE(SUM(ts.value),0) AS value
 FROM tab_sellers tsl
 LEFT JOIN tab_sales ts ON  tsl.id_seller = ts.seller
 GROUP BY tsl.seller
</code>```

The problem is when I need to filter by date range.

```<code> SELECT tsl.sellers,
       COUNT(ts.sales) AS sales,
       COALESCE(SUM(ts.value),0) AS value
 FROM tab_sellers tsl
 LEFT JOIN tab_sales ts ON  tsl.id_seller = ts.seller
 WHERE ts.date_sale BETWEEN '2017-05-01' and '2017-07-04'
 GROUP BY tsl.seller
</code>```

Considering that only John and Marie have sales in this date range, the result is:

```<code>seller | sales | value
 John       5       500
 Marie     10      1000
</code>```

However, the intended result is:

```<code>seller | sales | value
 John       5       500
 Marie     10      1000
 Jamie      0         0
 Arnold     0         0
 Peter      0         0
</code>```

I appreciated ideas to solve this.

答:
Place condition in And oprtation instead of where.

Try below query:

```<code> SELECT tsl.sellers,
       COUNT(ts.sales) AS sales,
       COALESCE(SUM(ts.value),0) AS value
 FROM tab_sellers tsl
 LEFT JOIN tab_sales ts ON  tsl.id_seller = ts.seller AND ts.date_sale BETWEEN '2017-05-01' and '2017-07-04'
 GROUP BY tsl.seller
</code>```

Hope this may helpful to you.

Body:
The goal is to display on a grid a list of all sellers with sales and values.

The list of sellers should always be displayed, even when they have no sales.

Something like:

seller | sales | value
 John      10      1000
 Marie     20      2000
 Jamie     15      1500
 Arnold     0         0
 Peter      0         0

For that the next query works fine:

 SELECT tsl.sellers,
       COUNT(ts.sales) AS sales,
       COALESCE(SUM(ts.value),0) AS value
 FROM tab_sellers tsl
 LEFT JOIN tab_sales ts ON  tsl.id_seller = ts.seller
 GROUP BY tsl.seller

The problem is when I need to filter by date range.

 SELECT tsl.sellers,
       COUNT(ts.sales) AS sales,
       COALESCE(SUM(ts.value),0) AS value
 FROM tab_sellers tsl
 LEFT JOIN tab_sales ts ON  tsl.id_seller = ts.seller
 WHERE ts.date_sale BETWEEN '2017-05-01' and '2017-07-04'
 GROUP BY tsl.seller

Considering that only John and Marie have sales in this date range, the result is:

seller | sales | value
 John       5       500
 Marie     10      1000

However, the intended result is:

seller | sales | value
 John       5       500
 Marie     10      1000
 Jamie      0         0
 Arnold     0         0
 Peter      0         0

I appreciated ideas to solve this.

Body:
Place condition in And oprtation instead of where.

Try below query:

 SELECT tsl.sellers,
       COUNT(ts.sales) AS sales,
       COALESCE(SUM(ts.value),0) AS value
 FROM tab_sellers tsl
 LEFT JOIN tab_sales ts ON  tsl.id_seller = ts.seller AND ts.date_sale BETWEEN '2017-05-01' and '2017-07-04'
 GROUP BY tsl.seller

Hope this may helpful to you.


问:
How to make the Drawer of RadSideDrawer cover the full page
I am using a telerik SizeDrawer control for UWP. and in it I want the drawer content to cover full page when it opens. So I tried to bind to Actual-Width of the page but that didn't work and then I tried to register it with sizeChanged event but width of drawer content still remains 0. unless I explicitly define it to some value like 300 then it remains 300 but I want it to cover full screen.

CODE

```<code><telerik:RadSideDrawer Name="MainDrawer" SizeChanged="MainDrawer_SizeChanged"
                       Loaded="MainDrawer_Loaded">
    <telerik:RadSideDrawer.MainContent>
        <Grid />

    </telerik:RadSideDrawer.MainContent>
    <telerik:RadSideDrawer.DrawerContent>
        <Grid  Name="DrawerGrid" Background="Yellow">

        </Grid>
    </telerik:RadSideDrawer.DrawerContent>
</telerik:RadSideDrawer>
</code>```

C#

```<code>private void MainDrawer_SizeChanged(object sender, SizeChangedEventArgs e)
{
    DrawerGrid.Width = e.NewSize.Width;
}
private void MainDrawer_Loaded(object sender, RoutedEventArgs e)
{
    DrawerGrid.Width = MainDrawer.Width;
}
</code>```

Note that height of drawer grid is alright and stretches to full screen but width remains 0 and if width is untouched totally then it is 240 fixed.

答:
This is how you do it -

First, define a double property that gets the width of the current Window.

```<code>public double WindowWidth => Window.Current.Bounds.Width;
</code>```

Then use it as a one-time binding source for the DrawerLength of your RadSideDrawer.

```<code><primitives:RadSideDrawer x:Name="MainDrawer"
                          DrawerLength="{x:Bind WindowWidth}" ... />
</code>```

Finally, update the DrawerLength whenever the size of the MainDrawer gets updated.

```<code>private void MainDrawer_SizeChanged(object sender, SizeChangedEventArgs e) =>
    MainDrawer.DrawerLength = e.NewSize.Width;
</code>```

Also note if you don't feel like doing bindings, you can replace the first two steps with one line of code, right after InitializeComponent();

```<code>MainDrawer.DrawerLength = Window.Current.Bounds.Width;
</code>```

Update

Looks like when the drawer is collapsed, the control itself resets its Opacity back to 1, and then when you constantly update the DrawerLength, the edge of the drawer could come out and give a bad user experience.

You can try to throttle page size changes with Reactive Extensions, or you can simply set the Opacity of the drawer back to 0 when it's collapsed.

To do this, you just need to monitor the DrawerState property and when it's Closed, set the DrawerGrid.Opacity to 0.

But remember you will also need to set it back to 1 before it gets expanded. Unfortunately there isn't an Opening state and Opened fires too late, so you have to locate the menu button and do it inside its Click event.

```<code>public MainPage()
{
    InitializeComponent();

    MainDrawer.DrawerLength = Window.Current.Bounds.Width;

    Loaded += (s, e) =>
    {
        // GetChildByName: https://github.com/JustinXinLiu/Continuity/blob/master/Continuity/Extensions/UtilExtensions.cs#L44
        var menuButton = MainDrawer.GetChildByName<Button>("PART_SideDrawerButton");
        menuButton.Click += (s1, e1) => DrawerGrid.Opacity = 1;
    };

    MainDrawer.RegisterPropertyChangedCallback(RadSideDrawer.DrawerStateProperty, (s, e) =>
    {
        var state = MainDrawer.DrawerState;

        if (state == DrawerState.Closed)
        {
            DrawerGrid.Opacity = 0;
        }
    });
}
</code>```

Body:
I am using a telerik SizeDrawer control for UWP. and in it I want the drawer content to cover full page when it opens. So I tried to bind to Actual-Width of the page but that didn't work and then I tried to register it with sizeChanged event but width of drawer content still remains 0. unless I explicitly define it to some value like 300 then it remains 300 but I want it to cover full screen.

CODE

<telerik:RadSideDrawer Name="MainDrawer" SizeChanged="MainDrawer_SizeChanged"
                       Loaded="MainDrawer_Loaded">
    <telerik:RadSideDrawer.MainContent>
        <Grid />

    </telerik:RadSideDrawer.MainContent>
    <telerik:RadSideDrawer.DrawerContent>
        <Grid  Name="DrawerGrid" Background="Yellow">

        </Grid>
    </telerik:RadSideDrawer.DrawerContent>
</telerik:RadSideDrawer>

C#

private void MainDrawer_SizeChanged(object sender, SizeChangedEventArgs e)
{
    DrawerGrid.Width = e.NewSize.Width;
}
private void MainDrawer_Loaded(object sender, RoutedEventArgs e)
{
    DrawerGrid.Width = MainDrawer.Width;
}

Note that height of drawer grid is alright and stretches to full screen but width remains 0 and if width is untouched totally then it is 240 fixed.

Body:
This is how you do it -

First, define a double property that gets the width of the current Window.

public double WindowWidth => Window.Current.Bounds.Width;

Then use it as a one-time binding source for the DrawerLength of your RadSideDrawer.

<primitives:RadSideDrawer x:Name="MainDrawer"
                          DrawerLength="{x:Bind WindowWidth}" ... />

Finally, update the DrawerLength whenever the size of the MainDrawer gets updated.

private void MainDrawer_SizeChanged(object sender, SizeChangedEventArgs e) =>
    MainDrawer.DrawerLength = e.NewSize.Width;

Also note if you don't feel like doing bindings, you can replace the first two steps with one line of code, right after InitializeComponent();

MainDrawer.DrawerLength = Window.Current.Bounds.Width;

Update

Looks like when the drawer is collapsed, the control itself resets its Opacity back to 1, and then when you constantly update the DrawerLength, the edge of the drawer could come out and give a bad user experience.

You can try to throttle page size changes with Reactive Extensions, or you can simply set the Opacity of the drawer back to 0 when it's collapsed.

To do this, you just need to monitor the DrawerState property and when it's Closed, set the DrawerGrid.Opacity to 0.

But remember you will also need to set it back to 1 before it gets expanded. Unfortunately there isn't an Opening state and Opened fires too late, so you have to locate the menu button and do it inside its Click event.

public MainPage()
{
    InitializeComponent();

    MainDrawer.DrawerLength = Window.Current.Bounds.Width;

    Loaded += (s, e) =>
    {
        // GetChildByName: https://github.com/JustinXinLiu/Continuity/blob/master/Continuity/Extensions/UtilExtensions.cs#L44
        var menuButton = MainDrawer.GetChildByName<Button>("PART_SideDrawerButton");
        menuButton.Click += (s1, e1) => DrawerGrid.Opacity = 1;
    };

    MainDrawer.RegisterPropertyChangedCallback(RadSideDrawer.DrawerStateProperty, (s, e) =>
    {
        var state = MainDrawer.DrawerState;

        if (state == DrawerState.Closed)
        {
            DrawerGrid.Opacity = 0;
        }
    });
}


问:
need to check this col-md(col-sm-4 col-md-4 col-lg-4) clarification
I need 3*3 service box for my website with responsive.But alignment is not proper.each box in 1st row differs in 2nd row and last box is moving to 4th row.so need code for 3*3 box type.</p>

```<code>       <div class="col-sm-4 col-md-4 col-lg-4">
                    <div class="serviceBox_2">
                        <i class="fa fa-bell"></i>
                        <h3>Broadband Services</h3>
                        <p>Integer ultrices scelerisque nulla fringilla.
      Praesent leo massa, ullamcorper venenatis tempor.</p>
                    </div>
                </div>
                <div class="col-sm-4 col-md-4 col-lg-4">
                    <div class="serviceBox_2">
                        <i class="fa fa-briefcase"></i>
                        <h3>Dedicated Leased Line</h3>
                        <p>Integer ultrices scelerisque nulla fringilla.
     Praesent leo massa, ullamcorper venenatis tempor.</p>
                    </div>
                </div>
                <div class="col-sm-4 col-md-4 col-lg-4">
                    <div class="serviceBox_2">
                        <i class="fa fa-rocket"></i>
                        <h3>Dark Fibre</h3>
                        <p>Integer ultrices scelerisque nulla fringilla.
       Praesent leo massa, ullamcorper venenatis tempor.</p>
                    </div>
                </div>
            </div>

                <div class="col-sm-4 col-md-4 col-lg-4">
                    <div class="serviceBox_2">
                        <i class="fa fa-rocket"></i>
                        <h3>CCTV Installation</h3>
                        <p>Integer ultrices scelerisque nulla fringilla.
     Praesent leo massa, ullamcorper venenatis tempor.</p>
                    </div>

            <div class="col-sm-12 col-sm-offset-12 col-xs-12 col-md-12">

                    <div class="serviceBox_2">
                        <i class="fa fa-rocket"></i>
                        <h3>CCTV Installation</h3>
                        <p>Integer ultrices scelerisque nulla fringilla.
     Praesent leo massa, ullamcorper venenatis tempor.</p>
                    </div>

                </div>

            </div>
</code>```

答:
You need to add row for every 12 columns.

Also if you want to use sm,md and lg with same values then you just have to use sm.

```<code> <div class="row">
      <div class="col-sm-4">
        <div class="serviceBox_2">
          <i class="fa fa-bell"></i>
          <h3>Broadband Services</h3>
          <p>Integer ultrices scelerisque nulla fringilla. Praesent leo massa, ullamcorper venenatis tempor.</p>
        </div>
      </div>
      <div class="col-sm-4 ">
        <div class="serviceBox_2">
          <i class="fa fa-briefcase"></i>
          <h3>Dedicated Leased Line</h3>
          <p>Integer ultrices scelerisque nulla fringilla. Praesent leo massa, ullamcorper venenatis tempor.</p>
        </div>
      </div>
      <div class="col-sm-4">
        <div class="serviceBox_2">
          <i class="fa fa-rocket"></i>
          <h3>Dark Fibre</h3>
          <p>Integer ultrices scelerisque nulla fringilla. Praesent leo massa, ullamcorper venenatis tempor.</p>
        </div>
      </div>
    </div>
    <div class="row">
      <div class="col-sm-4">
        <div class="serviceBox_2">
          <i class="fa fa-rocket"></i>
          <h3>CCTV Installation</h3>
          <p>Integer ultrices scelerisque nulla fringilla. Praesent leo massa, ullamcorper venenatis tempor.</p>
        </div>
      </div>
      <div class="col-sm-4">

        <div class="serviceBox_2">
          <i class="fa fa-rocket"></i>
          <h3>CCTV Installation</h3>
          <p>Integer ultrices scelerisque nulla fringilla. Praesent leo massa, ullamcorper venenatis tempor.</p>
        </div>

      </div>

    </div>
</code>```

Body:
I need 3*3 service box for my website with responsive.But alignment is not proper.each box in 1st row differs in 2nd row and last box is moving to 4th row.so need code for 3*3 box type.

Broadband Services

Integer ultrices scelerisque nulla fringilla.
      Praesent leo massa, ullamcorper venenatis tempor.

Dedicated Leased Line

Integer ultrices scelerisque nulla fringilla.
     Praesent leo massa, ullamcorper venenatis tempor.

Dark Fibre

Integer ultrices scelerisque nulla fringilla.
       Praesent leo massa, ullamcorper venenatis tempor.

CCTV Installation

Integer ultrices scelerisque nulla fringilla.
     Praesent leo massa, ullamcorper venenatis tempor.

CCTV Installation

Integer ultrices scelerisque nulla fringilla.
     Praesent leo massa, ullamcorper venenatis tempor.

Body:
You need to add row for every 12 columns.

Also if you want to use sm,md and lg with same values then you just have to use sm.

 <div class="row">
      <div class="col-sm-4">
        <div class="serviceBox_2">
          <i class="fa fa-bell"></i>
          <h3>Broadband Services</h3>
          <p>Integer ultrices scelerisque nulla fringilla. Praesent leo massa, ullamcorper venenatis tempor.</p>
        </div>
      </div>
      <div class="col-sm-4 ">
        <div class="serviceBox_2">
          <i class="fa fa-briefcase"></i>
          <h3>Dedicated Leased Line</h3>
          <p>Integer ultrices scelerisque nulla fringilla. Praesent leo massa, ullamcorper venenatis tempor.</p>
        </div>
      </div>
      <div class="col-sm-4">
        <div class="serviceBox_2">
          <i class="fa fa-rocket"></i>
          <h3>Dark Fibre</h3>
          <p>Integer ultrices scelerisque nulla fringilla. Praesent leo massa, ullamcorper venenatis tempor.</p>
        </div>
      </div>
    </div>
    <div class="row">
      <div class="col-sm-4">
        <div class="serviceBox_2">
          <i class="fa fa-rocket"></i>
          <h3>CCTV Installation</h3>
          <p>Integer ultrices scelerisque nulla fringilla. Praesent leo massa, ullamcorper venenatis tempor.</p>
        </div>
      </div>
      <div class="col-sm-4">

        <div class="serviceBox_2">
          <i class="fa fa-rocket"></i>
          <h3>CCTV Installation</h3>
          <p>Integer ultrices scelerisque nulla fringilla. Praesent leo massa, ullamcorper venenatis tempor.</p>
        </div>

      </div>

    </div>


问:
CVS download on windows 10 laptop
I am very new to CVS concurrent versioning system. I want to install the server as well as a client to access the same on my windows 10 laptop.

Can you please let me know if CVS supports on windows.

and need the link to the downloadable softwares

答:
CVS is available for windows.

e.g. SmartCVS

http://www.syntevo.com/smartcvs/

But I would highly recomment Git instead of CVS.

https://git-scm.com/

Title: CVS download on windows 10 laptop


问:
Generics with optional multiple bounds, e.g. List<? extends Integer OR String>
I have a method that should only accept a Map whose key is of type String and value of type Integer or String, but not, say, Boolean.

For example,

```<code>map.put("prop1", 1); // allowed
map.put("prop2", "value"); // allowed
map.put("prop3", true); // compile time error
</code>```

It is not possible to declare a Map as below (to enforce compile time check).

```<code>void setProperties(Map<String, ? extends Integer || String> properties)
</code>```

What is the best alternative other than declaring the value type as an unbounded wildcard and validating for Integer or String at runtime?

```<code>void setProperties(Map<String, ?> properties)
</code>```

This method accepts a set of properties to configure an underlying service entity. The entity supports property values of type String and Integer alone. For example, a property maxLength=2 is valid, defaultTimezone=UTC is also valid, but allowDuplicate=false is invalid.

答:
Since Integer and String closest common ancestor in the class hierarchy is Object you cannot achieve what you are trying to do - you can help compiler to narrow the type to Object only.

You can either

wrap your value into a class which can contain either Integer or String, or

extend Map as in the @RC's answer, or

wrap 2 Maps in a class

Body:
I have a method that should only accept a Map whose key is of type String and value of type Integer or String, but not, say, Boolean.

For example,

map.put("prop1", 1); // allowed
map.put("prop2", "value"); // allowed
map.put("prop3", true); // compile time error

It is not possible to declare a Map as below (to enforce compile time check).

void setProperties(Map<String, ? extends Integer || String> properties)

What is the best alternative other than declaring the value type as an unbounded wildcard and validating for Integer or String at runtime?

void setProperties(Map<String, ?> properties)

This method accepts a set of properties to configure an underlying service entity. The entity supports property values of type String and Integer alone. For example, a property maxLength=2 is valid, defaultTimezone=UTC is also valid, but allowDuplicate=false is invalid.


问:
Restarting animation when I touch a button
I need to restart my animation when I click a button.

This is the code of the my animation:

```<code>imgStar.frame = CGRectMake(205, 6, imgStar.frame.size.width, imgStar.frame.size.height);
[UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:1.5];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(animationFinished:finished:context:)];
    imgStar.transform = CGAffineTransformMakeTranslation(-4, 340);
    [UIView commitAnimations];
</code>```

The problem is that: when I re-click(click for the second time) my button the animation don't work!

Can you help me, please?

答:
I found the problem.
The error is imgStar.transform. I try to use this code:

```<code>[imgStar setFrame:CGRectOffset([imgStar frame], -4, 340)];
</code>```

instead of

```<code>imgStar.transform = CGAffineTransformMakeTranslation(-4, 340);
</code>```

and now it work!!

Body:
I need to restart my animation when I click a button.

This is the code of the my animation:

imgStar.frame = CGRectMake(205, 6, imgStar.frame.size.width, imgStar.frame.size.height);
[UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:1.5];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(animationFinished:finished:context:)];
    imgStar.transform = CGAffineTransformMakeTranslation(-4, 340);
    [UIView commitAnimations];

The problem is that: when I re-click(click for the second time) my button the animation don't work!

Can you help me, please?

Body:
I found the problem.
The error is imgStar.transform. I try to use this code:

[imgStar setFrame:CGRectOffset([imgStar frame], -4, 340)];

instead of

imgStar.transform = CGAffineTransformMakeTranslation(-4, 340);

and now it work!!


问:
Django rest framework - cant serialize query set
I try to serialize query set

```<code>def do(self):
        reservations = Reservation.objects.all()
        serializer = ReservationSerializer(data=reservations, many=True)
        if serializer.is_valid():
            encoded_data = json.dumps(serializer.data)
            r = requests.post('http://httpbin.org/post', headers={'Content-Type': 'application/json'}, data=encoded_data)
            print(r.text)
        else:
            print(serializer.errors)
</code>```

And I always get error of

{u'non_field_errors': [u'Expected a list of items but got type "QuerySet".']}

I tried to use values() on query set, and then convert to list, but this way I get objects without nested models

model

```<code>class Reservation(models.Model):
    start = models.DateField(verbose_name='Заезд', auto_now=False, auto_now_add=False, blank=False)
    end = models.DateField(verbose_name='Выезд', auto_now=False, auto_now_add=False, blank=False)
    check_in_time = models.TimeField(verbose_name='Время заезда', blank=False)
    check_out_time = models.TimeField(verbose_name='Время выезда', blank=False)
    has_refund = models.BooleanField(verbose_name='Возвратная бронь', default=True)
    payed = models.BooleanField(verbose_name='Оплачено', default=False)
    reserved_days = models.ManyToManyField(Day, blank=False)
    additional_services = models.ManyToManyField(AdditionalService)
    guest_name = models.CharField(verbose_name='Имя гостя', max_length=200, blank=True)
    reservation_number = models.CharField(verbose_name='Номер брони', max_length=200, blank=True)

class AdditionalService(models.Model):
    payment_date = models.CharField(verbose_name='Дата оплаты', max_length=200, blank=True)
    payment_type = models.CharField(verbose_name='Форма оплаты', max_length=200, blank=False)
    service = models.CharField(verbose_name='Услуга', max_length=200, blank=False)
    quantity = models.IntegerField(blank=False)
    price = models.FloatField(blank=False)

class Day(models.Model):
    date = models.DateField(auto_now=False, auto_now_add=False)
    price = models.FloatField()
    payment_method = models.CharField(max_length = 200, blank=True)
    payment_date = models.CharField(max_length=200, blank=True)
    room = models.ForeignKey(Room, null=True, blank=True, verbose_name='Номер', on_delete=models.CASCADE)

class Room(models.Model):
    name = models.CharField(max_length = 200, null=True)
    id = models.AutoField(primary_key=True)
    room_id = models.CharField(max_length = 200, null=False)

    def __unicode__(self):
        return self.name
</code>```

serializers

```<code>class ReservationSerializer(serializers.ModelSerializer):
    reserved_days = DaySerializer(many=True)
    additional_services = AdditionalServicesSerializer(many=True)

    class Meta:
        model = Reservation
        fields = [
            'start',
            'end',
            'check_in_time',
            'check_out_time',
            'reserved_days',
            'additional_services',
            'has_refund',
            'payed',
            'guest_name',
            'reservation_number',
        ]

class DaySerializer(serializers.ModelSerializer):
    room = RoomSerializer()

    class Meta:
        model = Day
        fields = [
            'date',
            'price',
            'payment_method',
            'payment_date',
            'room',
        ]

class AdditionalServicesSerializer(serializers.ModelSerializer):
    class Meta:
        model = AdditionalService
        fields = [
            'payment_date',
            'payment_type',
            'service',
            'quantity',
            'price',
        ]

class RoomSerializer(serializers.ModelSerializer):
    class Meta:
        model = Room
        fields = [
            'room_id',
        ]
</code>```

答:
For serialization you don't need to use data keyword, just pass queryset as first positional argument:

```<code>serializer = ReservationSerializer(reservations, many=True)
return serializer.data
</code>```

Body:
I try to serialize query set

def do(self):
        reservations = Reservation.objects.all()
        serializer = ReservationSerializer(data=reservations, many=True)
        if serializer.is_valid():
            encoded_data = json.dumps(serializer.data)
            r = requests.post('http://httpbin.org/post', headers={'Content-Type': 'application/json'}, data=encoded_data)
            print(r.text)
        else:
            print(serializer.errors)

And I always get error of

{u'non_field_errors': [u'Expected a list of items but got type "QuerySet".']}

I tried to use values() on query set, and then convert to list, but this way I get objects without nested models

model

class Reservation(models.Model):
    start = models.DateField(verbose_name='Заезд', auto_now=False, auto_now_add=False, blank=False)
    end = models.DateField(verbose_name='Выезд', auto_now=False, auto_now_add=False, blank=False)
    check_in_time = models.TimeField(verbose_name='Время заезда', blank=False)
    check_out_time = models.TimeField(verbose_name='Время выезда', blank=False)
    has_refund = models.BooleanField(verbose_name='Возвратная бронь', default=True)
    payed = models.BooleanField(verbose_name='Оплачено', default=False)
    reserved_days = models.ManyToManyField(Day, blank=False)
    additional_services = models.ManyToManyField(AdditionalService)
    guest_name = models.CharField(verbose_name='Имя гостя', max_length=200, blank=True)
    reservation_number = models.CharField(verbose_name='Номер брони', max_length=200, blank=True)

class AdditionalService(models.Model):
    payment_date = models.CharField(verbose_name='Дата оплаты', max_length=200, blank=True)
    payment_type = models.CharField(verbose_name='Форма оплаты', max_length=200, blank=False)
    service = models.CharField(verbose_name='Услуга', max_length=200, blank=False)
    quantity = models.IntegerField(blank=False)
    price = models.FloatField(blank=False)

class Day(models.Model):
    date = models.DateField(auto_now=False, auto_now_add=False)
    price = models.FloatField()
    payment_method = models.CharField(max_length = 200, blank=True)
    payment_date = models.CharField(max_length=200, blank=True)
    room = models.ForeignKey(Room, null=True, blank=True, verbose_name='Номер', on_delete=models.CASCADE)

class Room(models.Model):
    name = models.CharField(max_length = 200, null=True)
    id = models.AutoField(primary_key=True)
    room_id = models.CharField(max_length = 200, null=False)

    def __unicode__(self):
        return self.name

serializers

class ReservationSerializer(serializers.ModelSerializer):
    reserved_days = DaySerializer(many=True)
    additional_services = AdditionalServicesSerializer(many=True)

    class Meta:
        model = Reservation
        fields = [
            'start',
            'end',
            'check_in_time',
            'check_out_time',
            'reserved_days',
            'additional_services',
            'has_refund',
            'payed',
            'guest_name',
            'reservation_number',
        ]

class DaySerializer(serializers.ModelSerializer):
    room = RoomSerializer()

    class Meta:
        model = Day
        fields = [
            'date',
            'price',
            'payment_method',
            'payment_date',
            'room',
        ]

class AdditionalServicesSerializer(serializers.ModelSerializer):
    class Meta:
        model = AdditionalService
        fields = [
            'payment_date',
            'payment_type',
            'service',
            'quantity',
            'price',
        ]

class RoomSerializer(serializers.ModelSerializer):
    class Meta:
        model = Room
        fields = [
            'room_id',
        ]

Body:
For serialization you don't need to use data keyword, just pass queryset as first positional argument:

serializer = ReservationSerializer(reservations, many=True)
return serializer.data


问:
Getting a value from XML File (no unique ID for node)
I have a following XML:

<?xml version="1.0"?>
<Objects>
    <Object Type="System.Management.Automation.PSCustomObject">
        <Property Type="System.String" Name="FolderName">Mozilla_Firefox</Property>
        <Property Type="System.Int32" Name="Export">6</Property>
    </Object>
    <Object Type="System.Management.Automation.PSCustomObject">
        <Property Type="" Name="ExportListing"/>
        <Property Type="System.String" Name="FolderName">Notepad</Property>
        <Property Type="System.Int32" Name="ExportCountZips">1</Property>
    </Object>
</Objects>
```

<p>I want to get a value of property 'Export' for particular 'FolderName'.
Here is how I obtain a XML Line with Notepad:</p>

<pre class="lang-bsh prettyprint-override"><code>$t = $xml.Objects.Object.Property |
     ? { $_.Name -eq 'FolderName'} |
     Where '#text' -eq 'Notepad'
</code>```

How to get a proper 'ExportCountZips' with a value of 1?

答:
Use an XPath expression:</p>

```<code>$name  = 'Notepad'
$xpath = "//Object[Property[@Name='FolderName']/text()='$name']/Property[@Name='ExportCountZips']"
$xml.SelectSingleNode($xpath) | Select-Object -Expand '#text'
</code>```

Body:
I have a following XML:

<?xml version="1.0"?>
<Objects>
    <Object Type="System.Management.Automation.PSCustomObject">
        <Property Type="System.String" Name="FolderName">Mozilla_Firefox</Property>
        <Property Type="System.Int32" Name="Export">6</Property>
    </Object>
    <Object Type="System.Management.Automation.PSCustomObject">
        <Property Type="" Name="ExportListing"/>
        <Property Type="System.String" Name="FolderName">Notepad</Property>
        <Property Type="System.Int32" Name="ExportCountZips">1</Property>
    </Object>
</Objects>

I want to get a value of property 'Export' for particular 'FolderName'.
Here is how I obtain a XML Line with Notepad:

$t = $xml.Objects.Object.Property |
     ? { $_.Name -eq 'FolderName'} |
     Where '#text' -eq 'Notepad'

How to get a proper 'ExportCountZips' with a value of 1?

Body:
Use an XPath expression:

$name  = 'Notepad'
$xpath = "//Object[Property[@Name='FolderName']/text()='$name']/Property[@Name='ExportCountZips']"
$xml.SelectSingleNode($xpath) | Select-Object -Expand '#text'


问:
Recursively delete all sublists in a list
I have a Node class. It has a children ArrayList. That list consists of Nodes as well. And said nodes have children lists, and so on.

Basically, it's a tree in somewhat not so convenient form. Let's say I want to delete someNode from it.  So how to clear all of the child lists recursively?

I have a hasChildren() method, which returns if specified node has children, I think it has to help me, but can't figure out how yet. I've also got getChildren() method which returns list of children.

Here's some of my code, but it is wrong all over the place.

```<code>    public void removeChild()
    {
        while(hasChildren())
        {
            getChildren();
            removeChild();
        }

    children.clear();
}
</code>```

答:
In my opinion you just need to clear the children (as shown below) and the Garbage collector will automatically free rest of the objects.</p>

```<code>public void removeChild()
{
    if(hasChildren())
    {
      children.clear();
    }
}
</code>```

Body:
I have a Node class. It has a children ArrayList. That list consists of Nodes as well. And said nodes have children lists, and so on.

Basically, it's a tree in somewhat not so convenient form. Let's say I want to delete someNode from it.  So how to clear all of the child lists recursively?

I have a hasChildren() method, which returns if specified node has children, I think it has to help me, but can't figure out how yet. I've also got getChildren() method which returns list of children.

Here's some of my code, but it is wrong all over the place.

    public void removeChild()
    {
        while(hasChildren())
        {
            getChildren();
            removeChild();
        }

    children.clear();
}

Body:
In my opinion you just need to clear the children (as shown below) and the Garbage collector will automatically free rest of the objects.

public void removeChild()
{
    if(hasChildren())
    {
      children.clear();
    }
}


问:
FOSUser bundle: Is it possible to stop user registration inside REGISTRATION_SUCCESS or REGISTRATION_INITIALIZE events?
I am implementing recaptcha with fosuserbundle.

Is it possible to stop user registration or password reset with an error message through event listeners?

Or should I just override the controllers?

I would prefer to avoid using a third bundle to integrate recaptcha

Thanks a lot for your time.

答: The registration_success occure just after sucessful submitting and perform the result in database so, just before performing you can send a httresponse (inside the response event) that provide redirection (or otherelse)</p>