问:
Iterating object array within object - javascript?
I know iteration has been covered before - I'm usually pretty ok with it but struggling this time.

I have the following information I'm trying to loop through:

```<code>Object { leaving: object { all: array[10] } }
</code>```

I can quite easily return a single result by returning:

```<code> var html = '<p>' + news.leaving.all[0].departure_time + '</p>';
</code>```

But when I try to loop:

```<code>    var html = "";
    var i;
    for (i = 0; i < news.length; i++) {
        html +=
        '<p>' + news[i].leaving.all.departure_time '</p>';
     }
</code>```

I get nothing…

Any help with this will be great.

Thanks

答:
You can use Array.prototype.forEach() to iterate over the array news.leaving.all.

Code example:

var news = {leaving: {all: [{departure_time: '01:00'},{departure_time: '02:00'},{departure_time: '03:00'}]}},
    html = "";

news.leaving.all.forEach(function (n) {
  html += '
' + n.departure_time + '
';
});

console.log(html);```

Body:
I know iteration has been covered before - I'm usually pretty ok with it but struggling this time.

I have the following information I'm trying to loop through:

Object { leaving: object { all: array[10] } }

I can quite easily return a single result by returning:

 var html = '
' + news.leaving.all[0].departure_time + '
';

But when I try to loop:

    var html = "";
    var i;
    for (i = 0; i < news.length; i++) {
        html +=
        '
' + news[i].leaving.all.departure_time '
';
     }

I get nothing…

Any help with this will be great.

Thanks

Body:
You can use Array.prototype.forEach() to iterate over the array news.leaving.all.

Code example:

var news = {leaving: {all: [{departure_time: '01:00'},{departure_time: '02:00'},{departure_time: '03:00'}]}},
    html = "";

news.leaving.all.forEach(function (n) {
  html += '<p>' + n.departure_time + '</p>';
});

console.log(html);


来源: stackexchange

问:
Java classes not accessible
I am trying to build a dynamic web app using Eclipse Helios. I am trying to use a java class inside a jsp page. The page is visible during coding and deployment. In the runtime the java classes are not resolved to a type. Why does this happen?

Update:
Directory structure as in eclipse

```<code> Restarunt JAX-WS Web Services
 Deploymment Descriptor Java
 Resources:src
     default package
       LoginBean build WebContent    WebINF
      lib
      web.xml
      weblogic.xml jsp files
</code>```

答:
Have you added in jsp, and this classes are in class path or is in the WEB-INF/classes after build

```<code><%@ page import="java.util.*,yourpackage.yourClass" %>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Java classes not accessible

Body:
I am trying to build a dynamic web app using Eclipse Helios. I am trying to use a java class inside a jsp page. The page is visible during coding and deployment. In the runtime the java classes are not resolved to a type. Why does this happen?

Update:
Directory structure as in eclipse

 Restarunt JAX-WS Web Services
 Deploymment Descriptor Java
 Resources:src
     default package
       LoginBean build WebContent    WebINF
      lib
      web.xml
      weblogic.xml jsp files

Body:
Have you added in jsp, and this classes are in class path or is in the WEB-INF/classes after build

<%@ page import="java.util.*,yourpackage.yourClass" %>

ContentLicense: CC BY-SA 2.5


问:
Create a Dynamic Angular Directive
I have a html snippet that I'm now having to duplicate a lot which brings me to my question as I'd like to make the html snippet into a directive that can be reused.
I'd like to transform the snippet below into a directive.

```<code>  <a href="#"
    ng-click="vm.orderBy ='UserName'; reverseSort = !reverseSort">
                                    User Name
                                    <span ng-show="vm.orderBy == 'UserName'">
                                        <span ng-show="!reverseSort"><i class="fa fa-sort-alpha-asc"></i></span>
                                        <span ng-show="reverseSort"><i class="fa fa-sort-alpha-desc"></i></span>
                                    </span>
    </a>
</code>```

What I'd  like is a directive that allows me to pass any  string property to the orderBy field which would make it dynamic.
so something like <my-directive sort = 'Username'></my-directive>
I have  vm.orderBy = '' initialised in my main controller.

答:
```<code>angular.module('app_name', []).directive('myDirective', myDirective);

myDirective.$inject = ["$scope"];  // dependecny injection

function myDirective($scope) {
     return {
        restrict: 'E',
        templateUrl: 'mydir.tmpl.html',
        scope: {
            sort: "@"
        }
     }
}
</code>```

mydir.tmpl.html

```<code>  <a href="#" ng-click="vm.orderBy=sort; reverseSort = !reverseSort">
           User Name
           <span ng-show="vm.orderBy == sort">
              <span ng-show="!reverseSort">
                  <i class="fa fa-sort-alpha-asc"></i>
              </span>
              <span ng-show="reverseSort">
                  <i class="fa fa-sort-alpha-desc"></i>
              </span>
          </span>
    </a>
</code>```

Then use

<my-directive sort = 'Username'></my-directive>

Title: Create a Dynamic Angular Directive

Body:
I have a html snippet that I'm now having to duplicate a lot which brings me to my question as I'd like to make the html snippet into a directive that can be reused.
I'd like to transform the snippet below into a directive.

                                    User Name

What I'd  like is a directive that allows me to pass any  string property to the orderBy field which would make it dynamic.
so something like <my-directive sort = 'Username'></my-directive>
I have  vm.orderBy = '' initialised in my main controller.

Body:
angular.module('app_name', []).directive('myDirective', myDirective);

myDirective.$inject = ["$scope"];  // dependecny injection

function myDirective($scope) {
     return {
        restrict: 'E',
        templateUrl: 'mydir.tmpl.html',
        scope: {
            sort: "@"
        }
     }
}

mydir.tmpl.html

  <a href="#" ng-click="vm.orderBy=sort; reverseSort = !reverseSort">
           User Name
           <span ng-show="vm.orderBy == sort">
              <span ng-show="!reverseSort">
                  <i class="fa fa-sort-alpha-asc"></i>
              </span>
              <span ng-show="reverseSort">
                  <i class="fa fa-sort-alpha-desc"></i>
              </span>
          </span>
    </a>

Then use

<my-directive sort = 'Username'></my-directive>


问:
Error when sending variable from AJAX to PHP
I'm generating table rows with data from a database.

Below is my code:

```<code><table class="table table-hover" id="dashEventTable">
    <thead>
        <tr>
            <th>Created at</th>
            <th>Seminar Name</th>
            <th>Quota</th>
            <th>Location</th>
            <th>Option</th>
            <th style="display:none"></th>
        </tr>
    </thead>
    <tbody script="javascript">
    <?php
    $one = 1;
    $Lihat="SELECT * FROM event where status = '$one'";
    $Tampil = mysqli_query( $db, $Lihat );
        while ( $hasil = mysqli_fetch_array ( $Tampil ) ) {
            $id_event = ( $hasil['id_event'] );
            $nama_event =  ( $hasil['nama_event'] );
            $lokasi =  ( $hasil['lokasi'] );
            $kuota  =  ( $hasil['kuota'] );
            $created_at =  ( $hasil['created_at'] );
            { ?>
        <tr>
            <td class="created_at"><?php echo date( 'Y-m-d h:i a', strtotime( $created_at ) ); ?></td>
            <td class="event_name"><?php echo "$nama_event"; ?></td>
            <td class="kuota"><?php echo "$kuota"; ?></td>
            <td class="lokasi"><?php echo "$lokasi"; ?></td>
            <td>
                <a class="btn btn-xs btn-danger btn_delete" data-toggle="modal" href="#deleteDashEvent"><i class="fa fa-trash"></i></a>
            </td>
            <td class="event_id" style="display:none"><?php echo "$id_event"; ?></td>
        </tr><?php }
        } ?>
    </tbody>
</table>
</code>```

Now when I click on the button inside the rows, it does two things, the first is going to this JavaScript function:

```<code>$( ".btn_delete" ).click(function() {
    var $row = $( this ).closest( "tr" ); // Find the row
    var event_id = $row.find( ".event_id" ).text();
    console.log( event_id );
    $.ajax({
        url: "contain_data.php",
        method: 'post',
        data: {
            'send': event_id
        },
        success: function() {
            alert( event_id );
        }
    });
});
</code>```

From the alert and console log, I saw that I got the correct ID for the event id of the row. The data will then be sent to the PHP file above, and inside that PHP is this:

```<code><?php
if ( isset( $_POST['send'] ) ) {
    $id_event = $_POST['send'];
} else {
    echo "The data has not been received!";
}
</code>```

The second thing it does is go to this div for the delete confirmation:

```<code><form action="admin_delete_event.php" enctype="multipart/form-data" id="event_delete_row" method="post" name="delete_event_row">
    <div class="modal fade" id="deleteDashEvent">
        <div class="modal-dialog modal-sm" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button aria-label="Close" class="close" data-dismiss="modal" type="button">
                        <span aria-hidden="true">×</span>
                    </button>
                    <h4 class="modal-title">Delete Confirmation</h4>
                </div>
                <div class="modal-body">
                    <p>Are you sure want to delete this event?</p>
                </div>
                <div class="modal-footer">
                    <a class="btn btn-default" data-dismiss="modal" href="#">Batal</a>
                    <button class="btn btn-primary btn_confirm_delete" name="admin_delete_event" type="submit">DELETE</button>
                </div>
            </div>
        </div>
    </div>
</form>
</code>```

When the DELETE button is clicked, it will then go to this PHP file:

```<code><?php
session_start();
include( "config.php" );

if ( isset( $_POST['admin_delete_event'] ) ) {
    include( "contain_data.php" );

    $zero = 0;

    $delete_query = "UPDATE event, jadwal_acara, waktu_pendaftaran
        SET event.status = '$zero', jadwal_acara.status = '$zero', waktu_pendaftaran.status = '$zero'
        WHERE event.id_event = '$id_event'
        AND jadwal_acara.id_event = '$id_event'
        AND waktu_pendaftaran.id_event = '$id_event'";

    if ( mysqli_query( $db, $delete_query ) ) {
        $delete = "Data has been deleted";
        echo $delete;
    } else {
        echo "Error: " . $delete_query . "<br>" . mysqli_error( $db );
    }
} else {
    echo "The button is not detected!";
}
</code>```

The problem I am having is that I received this error when I click the delete confirmation button:

The data has not been received!

  Undefined variable: id_event in...

Which means that I fail in sending the data.

What am I doing wrong and how can I resolve it?

EDIT: after adding error handling to the php file, the value sent by the ajax is null instead of the id_event, do you guys know why?

答:
Update your AJAX With:

```<code> $.ajax({
        url: "contain_data.php",
        method: 'post',
        data : 'send='+event_id,
        success:function(){
            alert(event_id);
        }
    });
</code>```

try to pass your event_id using this way

```<code>data : 'send='+event_id,
</code>```

because you have taken

```<code>method: 'post',
</code>```

Hope it will help

Body:
I'm generating table rows with data from a database.

Below is my code:

            Created at
            Seminar Name
            Quota
            Location
            Option

    <?php
    $one = 1;
    $Lihat="SELECT * FROM event where status = '$one'";
    $Tampil = mysqli_query( $db, $Lihat );
        while ( $hasil = mysqli_fetch_array ( $Tampil ) ) {
            $id_event = ( $hasil['id_event'] );
            $nama_event =  ( $hasil['nama_event'] );
            $lokasi =  ( $hasil['lokasi'] );
            $kuota  =  ( $hasil['kuota'] );
            $created_at =  ( $hasil['created_at'] );
            { ?>

            <?php echo date( 'Y-m-d h:i a', strtotime( $created_at ) ); ?>
            <?php echo "$nama_event"; ?>
            <?php echo "$kuota"; ?>
            <?php echo "$lokasi"; ?>

            <?php echo "$id_event"; ?>

<?php }
        } ?>

Now when I click on the button inside the rows, it does two things, the first is going to this JavaScript function:

$( ".btn_delete" ).click(function() {
    var $row = $( this ).closest( "tr" ); // Find the row
    var event_id = $row.find( ".event_id" ).text();
    console.log( event_id );
    $.ajax({
        url: "contain_data.php",
        method: 'post',
        data: {
            'send': event_id
        },
        success: function() {
            alert( event_id );
        }
    });
});

From the alert and console log, I saw that I got the correct ID for the event id of the row. The data will then be sent to the PHP file above, and inside that PHP is this:

<?php
if ( isset( $_POST['send'] ) ) {
    $id_event = $_POST['send'];
} else {
    echo "The data has not been received!";
}

The second thing it does is go to this div for the delete confirmation:

<form action="admin_delete_event.php" enctype="multipart/form-data" id="event_delete_row" method="post" name="delete_event_row">

                    <button aria-label="Close" class="close" data-dismiss="modal" type="button">
                        ×
                    </button>

Delete Confirmation

Are you sure want to delete this event?

                    Batal
                    <button class="btn btn-primary btn_confirm_delete" name="admin_delete_event" type="submit">DELETE</button>

</form>

When the DELETE button is clicked, it will then go to this PHP file:

<?php
session_start();
include( "config.php" );

if ( isset( $_POST['admin_delete_event'] ) ) {
    include( "contain_data.php" );

    $zero = 0;

    $delete_query = "UPDATE event, jadwal_acara, waktu_pendaftaran
        SET event.status = '$zero', jadwal_acara.status = '$zero', waktu_pendaftaran.status = '$zero'
        WHERE event.id_event = '$id_event'
        AND jadwal_acara.id_event = '$id_event'
        AND waktu_pendaftaran.id_event = '$id_event'";

    if ( mysqli_query( $db, $delete_query ) ) {
        $delete = "Data has been deleted";
        echo $delete;
    } else {
        echo "Error: " . $delete_query . "
" . mysqli_error( $db );
    }
} else {
    echo "The button is not detected!";
}

The problem I am having is that I received this error when I click the delete confirmation button:

The data has not been received!

  Undefined variable: id_event in...

Which means that I fail in sending the data.

What am I doing wrong and how can I resolve it?

EDIT: after adding error handling to the php file, the value sent by the ajax is null instead of the id_event, do you guys know why?

Body:
Update your AJAX With:

 $.ajax({
        url: "contain_data.php",
        method: 'post',
        data : 'send='+event_id,
        success:function(){
            alert(event_id);
        }
    });

try to pass your event_id using this way

data : 'send='+event_id,

because you have taken

method: 'post',

Hope it will help


问:
Is there a Datatype in C# for List of comma separated pairs
Is there a datatype in C# for List of comma separated pairs like below?</p>

```<code>[(WAN.XX.1.0, WAN.XX.1.1), (WAN.XX.1.2, WAN.XX.1.3), (WAN.XX.1.4, WAN.XX.1.5), (WAN.XX.1.6, WAN.XX.1.7), (WAN.XX.1.8, WAN.XX.1.9)]
</code>```

答:
Would List<KeyValuePair<string, string>> or List<Tuple<string, string>> do what you need?.

See https://msdn.microsoft.com/en-us/library/dd268536(v=vs.110).aspx and https://msdn.microsoft.com/en-us/library/5tbh8a42(v=vs.110).aspx .

Body:
Is there a datatype in C# for List of comma separated pairs like below?

[(WAN.XX.1.0, WAN.XX.1.1), (WAN.XX.1.2, WAN.XX.1.3), (WAN.XX.1.4, WAN.XX.1.5), (WAN.XX.1.6, WAN.XX.1.7), (WAN.XX.1.8, WAN.XX.1.9)]


问:
display:flex with text and tag inside removes spaces
I am developing an advertisement management solution of certain CMS. I provide admin with few locations in the style to position ads in. Admin will input ad code (in HTML: adsense script, banner, or simple text). To make things as easy for admin as possible, I try to center the content automatically by wrapping ad code with this:

```<code><div style="display: flex; justify-content: center;">
</div>
</code>```

It works perfectly in all cases except for this one:

```<code><div style="display: flex; justify-content: center;">
    Hosting provided by <a href="http://foobar">FooBar Hosting</a> and me
</div>
</code>```

Produces this:

Note missing spaces between "by FooBar" and "Hosting and". Why is that? Is there any way to fix this with CSS only but retain centering feature for other cases?

答:
You could add a margin to the a tag.

a {
  margin: 0 3px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="display: flex; justify-content: center;">
    Hosting provided by FooBar Hosting and me
</div></code>```

Body:
I am developing an advertisement management solution of certain CMS. I provide admin with few locations in the style to position ads in. Admin will input ad code (in HTML: adsense script, banner, or simple text). To make things as easy for admin as possible, I try to center the content automatically by wrapping ad code with this:

It works perfectly in all cases except for this one:

    Hosting provided by FooBar Hosting and me

Produces this:

Note missing spaces between "by FooBar" and "Hosting and". Why is that? Is there any way to fix this with CSS only but retain centering feature for other cases?

Body:
You could add a margin to the a tag.

a {
  margin: 0 3px;
}

<div style="display: flex; justify-content: center;">
    Hosting provided by <a href="http://foobar">FooBar Hosting</a> and me
</div>


问:
Python: Regex Search Special Characters giving errors while searching multiple characters
I am using a simple regex string search with findall() function of the package.
In carrying out my unit tests with negative scenarios I found out that some of the special characters are returning error codes which are given in the comments below after # symbol.
My question is why are these characters returning error codes and how can I replace them with search string with escape sequence?
Please show me the code to replace the escape sequences:

```<code>import re
search="database"
search="c++" # error: multiple repeat
search="c\+\+" #working
search="c+"  #working
search="c#" #working
search="j!!" #working
search="x$$" #working
search="++j" #error: nothing to repeat
search="~~c" #working
search="c@@" #working
search="j##" #working
search="c%%"  #working
search="j&&"  #working
search="j**" #error: multiple repeat
search="j*"  #* is wild card
search="c(github)" #working
search="c--" #working
search="c==" #working
document="i did c++ programming. I am a c++ programming enthusiast. I love
working on c++ algirithms. I have experience in 3.5 years of c++ programming
skills "
n=len(re.findall(search,document))
print("Keyword Frequency: ",search ," Count:  ",n)
</code>```

The output of the last statement of code print() is given against each search term for easy understanding.
Solution I need has to have the ability:

Recognize the special character sequence. (for example it could be: ++ or +++ or +++++ or "++j" or "j**" etc

After recognizing the special character sequence the solution code should replace special characters with "++" or "+++" or "+++++" or "++j" or "j**"

Create the new search string

Thanks in advance for your solutions.

答:
The regex module comes with a function just for that: re.escape(). So:

```<code>import re

search = "c++"
# ...
document = """i did c++ programming. I am a c++ programming enthusiast. I love
working on c++ algirithms. I have experience in 3.5 years of c++ programming
skills """
n = len(re.findall(re.escape(search), document))
print("Keyword Frequency: ", search, " Count:  ", n)
</code>```

should do just fine... Now, why are you using regex instead of str.count() for such a simple task is a question you need to answer yourself.

Body:
I am using a simple regex string search with findall() function of the package.
In carrying out my unit tests with negative scenarios I found out that some of the special characters are returning error codes which are given in the comments below after # symbol.
My question is why are these characters returning error codes and how can I replace them with search string with escape sequence?
Please show me the code to replace the escape sequences:

import re
search="database"
search="c++" # error: multiple repeat
search="c\+\+" #working
search="c+"  #working
search="c#" #working
search="j!!" #working
search="x$$" #working
search="++j" #error: nothing to repeat
search="~~c" #working
search="c@@" #working
search="j##" #working
search="c%%"  #working
search="j&&"  #working
search="j**" #error: multiple repeat
search="j*"  #* is wild card
search="c(github)" #working
search="c--" #working
search="c==" #working
document="i did c++ programming. I am a c++ programming enthusiast. I love
working on c++ algirithms. I have experience in 3.5 years of c++ programming
skills "
n=len(re.findall(search,document))
print("Keyword Frequency: ",search ," Count:  ",n)

The output of the last statement of code print() is given against each search term for easy understanding.
Solution I need has to have the ability:

Recognize the special character sequence. (for example it could be: ++ or +++ or +++++ or "++j" or "j**" etc

After recognizing the special character sequence the solution code should replace special characters with "++" or "+++" or "+++++" or "++j" or "j**"

Create the new search string

Thanks in advance for your solutions.

Body:
The regex module comes with a function just for that: re.escape(). So:

import re

search = "c++"
# ...
document = """i did c++ programming. I am a c++ programming enthusiast. I love
working on c++ algirithms. I have experience in 3.5 years of c++ programming
skills """
n = len(re.findall(re.escape(search), document))
print("Keyword Frequency: ", search, " Count:  ", n)

should do just fine... Now, why are you using regex instead of str.count() for such a simple task is a question you need to answer yourself.


问:
WP Pagination Loop not working in custom theme
Pagination loop not working in custom theme Home page template. Shows same content in all pages.

You can also suggest me some other code to fix the issue.

```<code><?php
// clear any other queries that may be in use!
wp_reset_query();
// check for $_GET paged value
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
// setup post arguments
$args = array( 'posts_per_page' => 7, 'paged' => $paged, );
// run our query
query_posts($args);
// start loop
if (have_posts()) : while (have_posts()) : the_post();
  // if you use the <!-- more --> in your posts.
  global $more;
  $more = 0;
?>
   <div class="post">
     <?php the_title(); ?>
   </div>
<?php endwhile; ?>
<div class="navigation">
   <?php next_posts_link('Next'); ?>
   <?php previous_posts_link('Previous'); ?>
</div>
<?php else: ?>
   <div><h2>Nothing found</h2><p>No posts found for that query</p></div>
<?php endif; ?>
</code>```

答:
```<code><?php
// Get current page and append to custom query parameters array
$paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;
   // Define custom query parameters
   $args = array(  'posts_per_page' => 5, 'paged' => $paged );
    $custom_query_args = array( $args );

  // Instantiate custom query
  $custom_query = new WP_Query( $custom_query_args );

  // Pagination fix
  $temp_query = $wp_query;
  $wp_query   = NULL;
  $wp_query   = $custom_query;

// Output custom query loop
if ( $custom_query->have_posts() ) :
    while ( $custom_query->have_posts() ) :
        $custom_query->the_post();
                 ?>
             <div class="blog-post">
                 <?php the_post_thumbnail('post-thumbnail'); ?>

   <?php  endwhile;
endif;
// Reset postdata
wp_reset_postdata();

echo "<div class='blog-nav'>";

// Custom query loop pagination
previous_posts_link( 'Older Posts' );
next_posts_link( 'Newer Posts', $custom_query->max_num_pages );

$big = 999999999; // need an unlikely integer

echo paginate_links( array(
  'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
  'format' => '?paged=%#%',
  'current' => max( 1, get_query_var('paged') ),
  'total' => $custom_query->max_num_pages
) );

// Reset main query object
echo "</div>";
$wp_query = NULL;
$wp_query = $temp_query;
?>
</code>```

Body:
Pagination loop not working in custom theme Home page template. Shows same content in all pages.

You can also suggest me some other code to fix the issue.

<?php
// clear any other queries that may be in use!
wp_reset_query();
// check for $_GET paged value
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
// setup post arguments
$args = array( 'posts_per_page' => 7, 'paged' => $paged, );
// run our query
query_posts($args);
// start loop
if (have_posts()) : while (have_posts()) : the_post();
  // if you use the  in your posts.
  global $more;
  $more = 0;
?>

     <?php the_title(); ?>

<?php endwhile; ?>

   <?php next_posts_link('Next'); ?>
   <?php previous_posts_link('Previous'); ?>

<?php else: ?>

Nothing found

No posts found for that query

<?php endif; ?>


问:
What is the appropriate value for adSize in the xml file if I want to include an InterstitialAd and not a Banner?
What is the appropriate value for adSize in the xml file if I want to include an InterstitialAd and not a Banner?

My problem is that including an InterstitialAd from Admin to my application does not work properly.

So far I followed the official tutorial, but it says nothing about the value of ads:adSize in the xml. When I implemented a ad with a banner this attribute was set with "BANNER" but I suppose this is not the solution when I want to have an Interstitial ad.

So could you please tell me which other values than BANNER are possible for ads:adSize or what else I should use to make it work?

Thanks a lot

答:
Below code required only when you want to add banner view at your App view.

```<code><com.google.android.gms.ads.AdView
            xmlns:ads="http://schemas.android.com/apk/res-auto"
            android:id="@+id/adView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_alignParentBottom="true"
            ads:adSize="BANNER"
            ads:adUnitId="ca-app-pub-3940256099942544/6300978111">
</com.google.android.gms.ads.AdView>
</code>```

Follow instruction of this link to implement InterstitialAd in your App.

Body:
Below code required only when you want to add banner view at your App view.

<com.google.android.gms.ads.AdView
            xmlns:ads="http://schemas.android.com/apk/res-auto"
            android:id="@+id/adView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_alignParentBottom="true"
            ads:adSize="BANNER"
            ads:adUnitId="ca-app-pub-3940256099942544/6300978111">
</com.google.android.gms.ads.AdView>

Follow instruction of this link to implement InterstitialAd in your App.


问:
How to access polymer properties in observer function
When I try to wrap 'progressbar.js' in a polymer element I can't access circleprop.

```<code>var startColor = '#FC5B3F';
var endColor = '#6FD57F';

Polymer({
  is: "home-view",
  properties: {
    value: {
      type: String,
      observer: '_valueChanged'
    },
    circleProp: {
      type: Object,
      notify: true,
     reflectToAttribute: true
    }
  },

  ready: function() {
    var element = this.$$('#circleValue');
    this.circleProp = new ProgressBar.Circle(element, {
      color: startColor,
      trailColor: '#eee',
      trailWidth: 1,
      duration: 2000,
      easing: 'easeInOut',
      strokeWidth: 5,
      text: {
          value: '0'
      },

      // Set default step function for all animate calls
      step: function(state, circle) {
          circle.path.setAttribute('stroke', state.color);
          circle.setText((circle.value() * 100).toFixed(0));
      }
  });

  this.circleProp.animate(0.3, {
      from: {color: startColor},
      to: {color: endColor}
  });
},

attach : function() {
  if (this.circleProp) {
      this.circleProp.animate(this.value, {
          from: {color: startColor},
          to: {color: endColor}
      });
  }
},

_valueChanged : function(oldValue, newValue) {
  if (this.circleProp) {
    this.circleProp.animate(newValue, {
        from: {color: startColor},
        to: {color: endColor}
    });
  }
}
});
</code>```

How can I access circleProp so I can do my animation. Or how can I access objects in _valueChanged? It is only possible to access the DOM of this element.

答:
_valueChanged is definitly called before ready. try an complex observer

```<code>observers: ['_valueCahnged(value)']
</code>```

This will prevent that the observed value is undefined. Also when writing into properties use

```<code>this.set('circleProp', newValue)
</code>```

Otherwise Polymer won´t notice that there was an change. Within the _valueCahnged observer you can access all Properties via this

Body:
When I try to wrap 'progressbar.js' in a polymer element I can't access circleprop.

var startColor = '#FC5B3F';
var endColor = '#6FD57F';

Polymer({
  is: "home-view",
  properties: {
    value: {
      type: String,
      observer: '_valueChanged'
    },
    circleProp: {
      type: Object,
      notify: true,
     reflectToAttribute: true
    }
  },

  ready: function() {
    var element = this.$$('#circleValue');
    this.circleProp = new ProgressBar.Circle(element, {
      color: startColor,
      trailColor: '#eee',
      trailWidth: 1,
      duration: 2000,
      easing: 'easeInOut',
      strokeWidth: 5,
      text: {
          value: '0'
      },

      // Set default step function for all animate calls
      step: function(state, circle) {
          circle.path.setAttribute('stroke', state.color);
          circle.setText((circle.value() * 100).toFixed(0));
      }
  });

  this.circleProp.animate(0.3, {
      from: {color: startColor},
      to: {color: endColor}
  });
},

attach : function() {
  if (this.circleProp) {
      this.circleProp.animate(this.value, {
          from: {color: startColor},
          to: {color: endColor}
      });
  }
},

_valueChanged : function(oldValue, newValue) {
  if (this.circleProp) {
    this.circleProp.animate(newValue, {
        from: {color: startColor},
        to: {color: endColor}
    });
  }
}
});

How can I access circleProp so I can do my animation. Or how can I access objects in _valueChanged? It is only possible to access the DOM of this element.

Body:
_valueChanged is definitly called before ready. try an complex observer

observers: ['_valueCahnged(value)']

This will prevent that the observed value is undefined. Also when writing into properties use

this.set('circleProp', newValue)

Otherwise Polymer won´t notice that there was an change. Within the _valueCahnged observer you can access all Properties via this


问:
django rest framework RetrieveUpdateAPIView
I come from Vietnam.

I want to update User by Django Rest FrameWork. I can update User by 'pk'. But I can't update User by 'username'. I hope that everyone help me. Thank you so much.

serializers.py

```<code>class UserDetailSerializer(serializers.ModelSerializer):
    url_update = serializers.HyperlinkedIdentityField(view_name='api:UserUpdateAPIView', lookup_field='username')
    class Meta:
        model = User
        fields = ('url_update', 'username', 'email', 'user_permissions', 'is_staff', 'groups', 'last_login')

class UserUpdateSerialier(serializers.ModelSerializer):
    password = serializers.CharField(
        style={'input_type': 'password'}
    )
    class Meta:
        model = User
        fields = ('pk', 'username', 'password')

    def update(self, instance, validated_data):
        instance.username = validated_data.get('username', instance.username)
        instance.set_password(validated_data.get('password', instance.password))
        instance.save()
        return instance
</code>```

views.py

```<code>class UserDetailAPIView(generics.RetrieveAPIView):
    permission_classes = (permissions.IsAdminUser,)
    serializer_class = UserDetailSerializer
    #queryset = User.objects.all()
    lookup_field = 'username'
    def get_object(self):
        username = self.kwargs["username"]
        return get_object_or_404(User, username=username)

class UserUpdateAPIView(generics.RetrieveUpdateAPIView):
    permission_classes = (permissions.IsAdminUser,)
    #queryset = User.objects.all()
    serializer_class = UserUpdateSerialier

    def get_object(self):
        username = self.kwargs["username"]
        return get_object_or_404(User, username=username)

    def put(self, request, *args, **kwargs):
        return self.update(request, *args, **kwargs)
</code>```

urls.py

```<code>url(r'^$', views.UserListAPIView.as_view(), name='UserListAPIView'),
url(r'^(?P<username>.*)/$', views.UserDetailAPIView.as_view(), name='UserDetailAPIView'),
url(r'^(?P<username>.*)/update/$', views.UserUpdateAPIView.as_view(), name='UserUpdateAPIView'),
</code>```

HTTP 404 Not Found

Allow: GET, HEAD, OPTIONS

Content-Type: application/json

Vary: Accept

{
      "detail": "Not found."
  }

答: You need to set lookup_field = 'username' to the UserUpdateAPIView just like you did with the UserDetailAPIView

Body:
I come from Vietnam.

I want to update User by Django Rest FrameWork. I can update User by 'pk'. But I can't update User by 'username'. I hope that everyone help me. Thank you so much.

serializers.py

class UserDetailSerializer(serializers.ModelSerializer):
    url_update = serializers.HyperlinkedIdentityField(view_name='api:UserUpdateAPIView', lookup_field='username')
    class Meta:
        model = User
        fields = ('url_update', 'username', 'email', 'user_permissions', 'is_staff', 'groups', 'last_login')

class UserUpdateSerialier(serializers.ModelSerializer):
    password = serializers.CharField(
        style={'input_type': 'password'}
    )
    class Meta:
        model = User
        fields = ('pk', 'username', 'password')

    def update(self, instance, validated_data):
        instance.username = validated_data.get('username', instance.username)
        instance.set_password(validated_data.get('password', instance.password))
        instance.save()
        return instance

views.py

class UserDetailAPIView(generics.RetrieveAPIView):
    permission_classes = (permissions.IsAdminUser,)
    serializer_class = UserDetailSerializer
    #queryset = User.objects.all()
    lookup_field = 'username'
    def get_object(self):
        username = self.kwargs["username"]
        return get_object_or_404(User, username=username)

class UserUpdateAPIView(generics.RetrieveUpdateAPIView):
    permission_classes = (permissions.IsAdminUser,)
    #queryset = User.objects.all()
    serializer_class = UserUpdateSerialier

    def get_object(self):
        username = self.kwargs["username"]
        return get_object_or_404(User, username=username)

    def put(self, request, *args, **kwargs):
        return self.update(request, *args, **kwargs)

urls.py

url(r'^$', views.UserListAPIView.as_view(), name='UserListAPIView'),
url(r'^(?P<username>.*)/$', views.UserDetailAPIView.as_view(), name='UserDetailAPIView'),
url(r'^(?P<username>.*)/update/$', views.UserUpdateAPIView.as_view(), name='UserUpdateAPIView'),

HTTP 404 Not Found

Allow: GET, HEAD, OPTIONS

Content-Type: application/json

Vary: Accept

{
      "detail": "Not found."
  }


问:
Android Icons Library
Folks, is there a free library of icons based on Material Design, I am working on an app and i want my floating button to have a camera icon, an edit icon and so on. Is there such a place to dowbnload free icon images?

thanks

答:
Google material design official site:
https://material.io/icons/

Free to use Apache license

You can use this library as well to avoid the burden of downloading and adding each icon into your project:
https://android-arsenal.com/details/1/2193

Title: Android Icons Library


问:
jtoken.selecttokens issue when comparing value of one array with another array
i need to fetch amount using following logic. if product.ID equals stores.ID then fetch product.amount
Json

```<code>{
 "stores": [
{
  "ID": 17736791,
  "Name": "ABC"
},
{
  "ID": 154423041,
  "Name": "XYZ"
}
],
"product": [
{
  "ID": 154423041,
  "Amount": 19865337
}
]
}
</code>```

i am using jtoken.selecttoken to fetch data as below. but it throws error as could not read query operator.

```<code>string path = ToJsonPath(product[ID=stores[*].ID].Amount);
var data= token.SelectTokens(path)
</code>```

Updated, ToJsonPath

```<code>public string ToJsonPath(string query)
    {
        string normalizedQuery = query.Replace(DoubleQuotes, SingleQuotes);

        StringBuilder jsonPath = new StringBuilder();
        jsonPath.Append(string.Concat(RootElement, ChildOperator));
        jsonPath.Append(normalizedQuery);

        MatchCollection expressions = Regex.Matches(normalizedQuery, ExpressionRegexPattern);

        StringBuilder expression = new StringBuilder();
        for (int i = 0; i < expressions.Count; i++)
        {
            if (!Regex.IsMatch(expressions[i].Value, OperatorRegexPattern))
            {
                continue;
            }

            expression.Length = 0;
            expression.Capacity = 0;

            expression.Append(expressions[i].Value);
            jsonPath.Replace(expression.ToString(), Placeholder);

            string[] expressionTerms = expression.ToString()
                .Split(new[] { AndOperator, OrOperator }, StringSplitOptions.RemoveEmptyEntries)
                .Select(t => t.Trim())
                .ToArray();

            foreach (string expressionTerm in expressionTerms)
            {
                expression.Replace(expressionTerm, Placeholder);
                expression.Replace(Placeholder, string.Concat(CurrentElement, ChildOperator, expressionTerm));
            }

            string expressionWithEscapedOperators = Regex.Replace(expression.ToString(), OperatorRegexPattern, " $& ");
            string expressionWithDoubleEqualOperators = Regex.Replace(expressionWithEscapedOperators, EqualOperatorPattern, "$&$&");

            string jsonExpression = string.Format(JsonExpressionTemplate, expressionWithDoubleEqualOperators);
            jsonPath.Replace(Placeholder, jsonExpression);
        }

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

答:
Not sure about JSONPath but with LINQ to JSON this can be achieved as follows:

```<code>var obj = JObject.Parse(json);
var storeIds = obj["stores"]
    .Select(s => (int)s["ID"])
    .ToList();
var selectedAmount = obj["product"]
    .Where(p => storeIds.Contains((int)p["ID"]))
    .Select(p => (int)p["Amount"])
    .FirstOrDefault();
</code>```

Demo: https://dotnetfiddle.net/CRn5Az

Body:
i need to fetch amount using following logic. if product.ID equals stores.ID then fetch product.amount
Json

{
 "stores": [
{
  "ID": 17736791,
  "Name": "ABC"
},
{
  "ID": 154423041,
  "Name": "XYZ"
}
],
"product": [
{
  "ID": 154423041,
  "Amount": 19865337
}
]
}

i am using jtoken.selecttoken to fetch data as below. but it throws error as could not read query operator.

string path = ToJsonPath(product[ID=stores[*].ID].Amount);
var data= token.SelectTokens(path)

Updated, ToJsonPath

public string ToJsonPath(string query)
    {
        string normalizedQuery = query.Replace(DoubleQuotes, SingleQuotes);

        StringBuilder jsonPath = new StringBuilder();
        jsonPath.Append(string.Concat(RootElement, ChildOperator));
        jsonPath.Append(normalizedQuery);

        MatchCollection expressions = Regex.Matches(normalizedQuery, ExpressionRegexPattern);

        StringBuilder expression = new StringBuilder();
        for (int i = 0; i < expressions.Count; i++)
        {
            if (!Regex.IsMatch(expressions[i].Value, OperatorRegexPattern))
            {
                continue;
            }

            expression.Length = 0;
            expression.Capacity = 0;

            expression.Append(expressions[i].Value);
            jsonPath.Replace(expression.ToString(), Placeholder);

            string[] expressionTerms = expression.ToString()
                .Split(new[] { AndOperator, OrOperator }, StringSplitOptions.RemoveEmptyEntries)
                .Select(t => t.Trim())
                .ToArray();

            foreach (string expressionTerm in expressionTerms)
            {
                expression.Replace(expressionTerm, Placeholder);
                expression.Replace(Placeholder, string.Concat(CurrentElement, ChildOperator, expressionTerm));
            }

            string expressionWithEscapedOperators = Regex.Replace(expression.ToString(), OperatorRegexPattern, " $& ");
            string expressionWithDoubleEqualOperators = Regex.Replace(expressionWithEscapedOperators, EqualOperatorPattern, "$&$&");

            string jsonExpression = string.Format(JsonExpressionTemplate, expressionWithDoubleEqualOperators);
            jsonPath.Replace(Placeholder, jsonExpression);
        }

        return jsonPath.ToString();
    }

Body:
Not sure about JSONPath but with LINQ to JSON this can be achieved as follows:

var obj = JObject.Parse(json);
var storeIds = obj["stores"]
    .Select(s => (int)s["ID"])
    .ToList();
var selectedAmount = obj["product"]
    .Where(p => storeIds.Contains((int)p["ID"]))
    .Select(p => (int)p["Amount"])
    .FirstOrDefault();

Demo: https://dotnetfiddle.net/CRn5Az


问:
FirebaseDatabase: Model is missing a constructor with no arguments
So I've added Firebase data like this:

and I called the data inside a ListView:

```<code>private void displayStudentChatMessages() {
    listofMessages = (ListView) findViewById(R.id.list_msg);
    DatabaseReference ref = FirebaseDatabase.getInstance().getReference(String.valueOf(generateChatID));

    adapter = new FirebaseListAdapter<StudentMessageModel>(this, StudentMessageModel.class, R.layout.item_chat_right, ref) {
        @Override
        protected void populateView(View v, StudentMessageModel model, int position) {
            TextView messageUsername = (TextView) findViewById(R.id.message_user_sender);
            TextView messageText = (TextView) findViewById(R.id.message_user);
            TextView messageTime = (TextView) findViewById(R.id.message_usertime);

            messageUsername.setText(model.getStudentName());
            messageText.setText(model.getStudentMessage());
            messageTime.setText(DateFormat.format("yyyy-MM-dd (HH:mm:ss)", model.getStudentTime()));
        }
    };

    listofMessages.setAdapter(adapter);
    listofMessages.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
}
</code>```

But I got the error:

com.google.firebase.database.DatabaseException: Class com.androidports.autosiskola.StudentMessageModel is missing a constructor with no arguments

I need those data where the root's child is the generated-name (test-testteacher-student-teacher).

Here is how I added the constructor:

```<code>public class StudentMessageModel {

private String studentUsername;
private String studentName;
private String studentMessage;
private String generatedChatID;
private long studentTime;

public StudentMessageModel(String studentUsername, String studentName, String studentMessage, String generatedChatID) {
    this.studentUsername = studentUsername;
    this.studentName = studentName;
    this.studentMessage = studentMessage;
    this.generatedChatID = generatedChatID;

    studentTime = new Date().getTime();
}
</code>```

and getters and setters.

答:
As the error message says, you must have a public constructor without arguments. This is used when re-creating your object from the database.

In addition you must either mark your fields as public, or provide getters and setters for them. That way Firebase knows what fields to populate from the JSON properties in the database.

So:

```<code>public class StudentMessageModel {

    public String studentUsername;
    public String studentName;
    public String studentMessage;
    public String generatedChatID;
    public long studentTime;

    public StudentMessageModel(String studentUsername, String studentName, String studentMessage, String generatedChatID) {
        this.studentUsername = studentUsername;
        this.studentName = studentName;
        this.studentMessage = studentMessage;
        this.generatedChatID = generatedChatID;

        studentTime = new Date().getTime();
    }
    public StudentMessageModel() {
        // public default constructor, which Firebase uses
    }
</code>```

Body:
So I've added Firebase data like this:

and I called the data inside a ListView:

private void displayStudentChatMessages() {
    listofMessages = (ListView) findViewById(R.id.list_msg);
    DatabaseReference ref = FirebaseDatabase.getInstance().getReference(String.valueOf(generateChatID));

    adapter = new FirebaseListAdapter<StudentMessageModel>(this, StudentMessageModel.class, R.layout.item_chat_right, ref) {
        @Override
        protected void populateView(View v, StudentMessageModel model, int position) {
            TextView messageUsername = (TextView) findViewById(R.id.message_user_sender);
            TextView messageText = (TextView) findViewById(R.id.message_user);
            TextView messageTime = (TextView) findViewById(R.id.message_usertime);

            messageUsername.setText(model.getStudentName());
            messageText.setText(model.getStudentMessage());
            messageTime.setText(DateFormat.format("yyyy-MM-dd (HH:mm:ss)", model.getStudentTime()));
        }
    };

    listofMessages.setAdapter(adapter);
    listofMessages.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
}

But I got the error:

com.google.firebase.database.DatabaseException: Class com.androidports.autosiskola.StudentMessageModel is missing a constructor with no arguments

I need those data where the root's child is the generated-name (test-testteacher-student-teacher).

Here is how I added the constructor:

public class StudentMessageModel {

private String studentUsername;
private String studentName;
private String studentMessage;
private String generatedChatID;
private long studentTime;

public StudentMessageModel(String studentUsername, String studentName, String studentMessage, String generatedChatID) {
    this.studentUsername = studentUsername;
    this.studentName = studentName;
    this.studentMessage = studentMessage;
    this.generatedChatID = generatedChatID;

    studentTime = new Date().getTime();
}

and getters and setters.

Body:
As the error message says, you must have a public constructor without arguments. This is used when re-creating your object from the database.

In addition you must either mark your fields as public, or provide getters and setters for them. That way Firebase knows what fields to populate from the JSON properties in the database.

So:

public class StudentMessageModel {

    public String studentUsername;
    public String studentName;
    public String studentMessage;
    public String generatedChatID;
    public long studentTime;

    public StudentMessageModel(String studentUsername, String studentName, String studentMessage, String generatedChatID) {
        this.studentUsername = studentUsername;
        this.studentName = studentName;
        this.studentMessage = studentMessage;
        this.generatedChatID = generatedChatID;

        studentTime = new Date().getTime();
    }
    public StudentMessageModel() {
        // public default constructor, which Firebase uses
    }


问:
Ordering rows by joined tables in postgres
I had difficulties to even come up with the correct question title. I'll take any advice to edit it.

My problem: I have an app (job board) with two models: User, Job. User can have many jobs and jobs can be premium or free. Jobs can be expired or active as well. They are active if valid_until parameter IS NOT NULL, otherwise they are expired (I have a background job to set this automatically every day).

I am trying to select Users, who have active jobs but I want users with premium jobs come before users with free jobs assuming users can have active both premium and free job postings at the same time.

```<code>SELECT DISTINCT users.id, users.email FROM users
LEFT OUTER JOIN jobs ON jobs.owner_id = users.id
WHERE jobs.valid_until IS NOT NULL;
</code>```

Above query correctly selects users with at least one active job (either premium or free), I just need to order users according to jobs table. I will appreciate any help/hint. Thanks!

答:
I believe the following will do what you want:

```<code>SELECT users.id, users.email FROM users
JOIN jobs ON jobs.owner_id = users.id
WHERE jobs.valid_until IS NOT NULL
GROUP BY users.id, users.email
ORDER BY min(case when jobs.type = 'premium' then 1 else 2 end)
</code>```

I couldn't see a name for the field which holds Premium vs Free, so I made one up! Also, I changed your JOIN to an INNER JOIN since the WHERE clause has that effect in any case.

Body:
I had difficulties to even come up with the correct question title. I'll take any advice to edit it.

My problem: I have an app (job board) with two models: User, Job. User can have many jobs and jobs can be premium or free. Jobs can be expired or active as well. They are active if valid_until parameter IS NOT NULL, otherwise they are expired (I have a background job to set this automatically every day).

I am trying to select Users, who have active jobs but I want users with premium jobs come before users with free jobs assuming users can have active both premium and free job postings at the same time.

SELECT DISTINCT users.id, users.email FROM users
LEFT OUTER JOIN jobs ON jobs.owner_id = users.id
WHERE jobs.valid_until IS NOT NULL;

Above query correctly selects users with at least one active job (either premium or free), I just need to order users according to jobs table. I will appreciate any help/hint. Thanks!

Body:
I believe the following will do what you want:

SELECT users.id, users.email FROM users
JOIN jobs ON jobs.owner_id = users.id
WHERE jobs.valid_until IS NOT NULL
GROUP BY users.id, users.email
ORDER BY min(case when jobs.type = 'premium' then 1 else 2 end)

I couldn't see a name for the field which holds Premium vs Free, so I made one up! Also, I changed your JOIN to an INNER JOIN since the WHERE clause has that effect in any case.


问:
Python: Checking if a key is part of a dictionary
I'm trying to make my own irc bot (for twitch) in Python. I have a dictionary with my commands:

```<code>commands = {

    '!ping': {
        'cooldown': 30,
        'return': '!pong'
    },

    '!random': {
        'cooldown': 30,
        'return': 'command',
        'argc': 2,
        'arg_username': True,
        'usage': '!random <min> <max>'
    }

} # End of commands
</code>```

Then I have a function to check if the message that was send is indeed a command:

```<code>import string

def is_valid_command(command):
    return True if command in commands.keys() else False
</code>```

So when i test this function out, it don't seems to work, and I don't know what I am doiing wrong:

```<code>message = "!ping"
print(str(is_valid_command(message)))
>>> False
</code>```

I tried to change '!ping' inside the dictionary to "!ping", and virsa versa with the message, even deleted the '!' and it always says it's False.

Thanks in regards,
Laurens

EDIT:

```<code>def is_valid_command(command):
    for key in commands.keys():
        print(key)
    print("input " + str(command))
    print(command in commands.keys())
    return command in commands.keys()
</code>```

This result in this:

```<code>!ping
!random
input !ping
False
</code>```

EDIT2: @e4c5 wanted me to use try/except, as i quickly try it (inside that methode), it still return False

```<code>try:
    cmd = commands[command]
    print ('Try True')
    return True
except KeyError:
    print('Try False')
    return False
</code>```

EDIT3: u'!ping' before fixed this (message = u'!ping'), but when I read a string from somewhere else, is there a function that does this unicoding?

答:
Why are you not returning just:

```<code>return command in commands.keys()
</code>```

That should be True/False already! hope this clarify!

As mentioned above to create a unicode string out of your messages just:

```<code>u'%s' % message
</code>```

Body:
I'm trying to make my own irc bot (for twitch) in Python. I have a dictionary with my commands:

commands = {

    '!ping': {
        'cooldown': 30,
        'return': '!pong'
    },

    '!random': {
        'cooldown': 30,
        'return': 'command',
        'argc': 2,
        'arg_username': True,
        'usage': '!random <min> <max>'
    }

} # End of commands

Then I have a function to check if the message that was send is indeed a command:

import string

def is_valid_command(command):
    return True if command in commands.keys() else False

So when i test this function out, it don't seems to work, and I don't know what I am doiing wrong:

message = "!ping"
print(str(is_valid_command(message)))
>>> False

I tried to change '!ping' inside the dictionary to "!ping", and virsa versa with the message, even deleted the '!' and it always says it's False.

Thanks in regards,
Laurens

EDIT:

def is_valid_command(command):
    for key in commands.keys():
        print(key)
    print("input " + str(command))
    print(command in commands.keys())
    return command in commands.keys()

This result in this:

!ping
!random
input !ping
False

EDIT2: @e4c5 wanted me to use try/except, as i quickly try it (inside that methode), it still return False

try:
    cmd = commands[command]
    print ('Try True')
    return True
except KeyError:
    print('Try False')
    return False

EDIT3: u'!ping' before fixed this (message = u'!ping'), but when I read a string from somewhere else, is there a function that does this unicoding?

Body:
Why are you not returning just:

return command in commands.keys()

That should be True/False already! hope this clarify!

As mentioned above to create a unicode string out of your messages just:

u'%s' % message


答:
I just tested your script and it seems to work fine.

Did some simplifications, but basically have the same code as you.

```<code>commands = {
    '!ping': {
        'cooldown': 30,
        'return': '!pong'
    },
    '!random': {
        'cooldown': 30,
        'return': 'command',
        'argc': 2,
        'arg_username': True,
        'usage': '!random <min> <max>'
    }
}

def is_valid_command(command):
    return command in commands.keys()

print(is_valid_command("!ping"))
</code>```

Which returns True. If I try command !pong it returns False.

Title: Python: Checking if a key is part of a dictionary

Body:
I just tested your script and it seems to work fine.

Did some simplifications, but basically have the same code as you.

commands = {
    '!ping': {
        'cooldown': 30,
        'return': '!pong'
    },
    '!random': {
        'cooldown': 30,
        'return': 'command',
        'argc': 2,
        'arg_username': True,
        'usage': '!random <min> <max>'
    }
}

def is_valid_command(command):
    return command in commands.keys()

print(is_valid_command("!ping"))

Which returns True. If I try command !pong it returns False.


答:
If FQN of your class is your.package.YourClass then make sure your class deploys to:

```<code>YOUR_WEB_APP.war \
    WEB-INF \
        classes \
            your \
               package \
                  YourClass.class
</code>```

Title: Java classes not accessible

Body:
I am trying to build a dynamic web app using Eclipse Helios. I am trying to use a java class inside a jsp page. The page is visible during coding and deployment. In the runtime the java classes are not resolved to a type. Why does this happen?

Update:
Directory structure as in eclipse

 Restarunt JAX-WS Web Services
 Deploymment Descriptor Java
 Resources:src
     default package
       LoginBean build WebContent    WebINF
      lib
      web.xml
      weblogic.xml jsp files

Body:
If FQN of your class is your.package.YourClass then make sure your class deploys to:

YOUR_WEB_APP.war \
    WEB-INF \
        classes \
            your \
               package \
                  YourClass.class


问:
How to get old value and new value using SQL Trigger?
I have a lot of fields in a table and I am trying to audit any insert - update - delete in another table.

I just have a problem of getting the value of the exact field I've Chosen.

I wrote this code and I expect to get the old and new value of an exact field.

```<code>DECLARE @ColName NVARCHAR(225) ,
        @FieldID INT;
    DECLARE columnCursor CURSOR
    FOR
        SELECT  COLUMN_NAME
        FROM    INFORMATION_SCHEMA.COLUMNS
        WHERE   TABLE_NAME = 'acc_Account'
                AND TABLE_SCHEMA = 'dbo';

    DECLARE @deleted_colmn INT;

    DECLARE CurDB CURSOR
    FOR
        SELECT  @deleted_colmn
        FROM    #Deleted;

    OPEN columnCursor;

    FETCH NEXT FROM columnCursor INTO @ColName;

    WHILE ( @@FETCH_STATUS <> -1 )
        BEGIN

            --OPEN CurDB;
            --FETCH NEXT FROM CurDB INTO @deleted_colmn;

            SET @FieldID = ( SELECT TOP 1
                                    FieldID
                             FROM   fld_Field
                             WHERE  fld_Field.FieldName = @ColName
                           );

            SET @newvalue = ( SELECT TOP 1
                                        @ColName
                              FROM      Inserted
                              WHERE     @ColName = @ColName
                            );
            SET @oldvalue = ( SELECT TOP 1
                                        @ColName
                              FROM      Deleted
              IF @newvalue <> @oldvalue
                BEGIN

                    INSERT  INTO dbo.utl_Audit_Trail_Field
                            ( AuditTrailID ,
                              FieldID ,
                              OldValue ,
                              NewValue ,
                              CreatedDate ,
                              CreatedUserID ,
                              UpdatedDate ,
                              UpdatedUserID
                            )
                    VALUES  ( @AuditTrailID , -- AuditTrailID - bigint
                              @FieldID , -- FieldID - bigint
                              @oldvalue , -- OldValue - nvarchar(1000)
                              @newvalue , -- NewValue - nvarchar(1000)
                              @CreatedDate , -- CreatedDate - datetime
                              @CreatedUserID , -- CreatedUserID - bigint
                              @CreatedDate , -- UpdatedDate - datetime
                              @CreatedUserID  -- UpdatedUserID - bigint
                            );

                END;

            FETCH NEXT FROM columnCursor INTO @ColName;

        END;                WHERE     @ColName = @ColName

                            );
</code>```

答:
Rethink your architecture. Attempting to individually detect changes in a table and store each one separately is a recipe for disaster.

Just store the entire contents of the Deleted table in your audit table and then ensure you compress the table to cut down on the amount of space used by huge numbers of duplicates.

Disk storage space is cheap, CPU power is not.

Edit: Read your comment that you can't change the architecture; I'd say you HAVE to because the alternative is to have a trigger like this that WILL cause major problems if that table is even remotely heavily used. Even doing individual inserts outside of a cursor will bite you so badly you'll wish you'd never been born. For every ms the trigger runs, the risk of lock contention (or even worse, deadlocks) grows exponentially.

Body:
I have a lot of fields in a table and I am trying to audit any insert - update - delete in another table.

I just have a problem of getting the value of the exact field I've Chosen.

I wrote this code and I expect to get the old and new value of an exact field.

DECLARE @ColName NVARCHAR(225) ,
        @FieldID INT;
    DECLARE columnCursor CURSOR
    FOR
        SELECT  COLUMN_NAME
        FROM    INFORMATION_SCHEMA.COLUMNS
        WHERE   TABLE_NAME = 'acc_Account'
                AND TABLE_SCHEMA = 'dbo';

    DECLARE @deleted_colmn INT;

    DECLARE CurDB CURSOR
    FOR
        SELECT  @deleted_colmn
        FROM    #Deleted;

    OPEN columnCursor;

    FETCH NEXT FROM columnCursor INTO @ColName;

    WHILE ( @@FETCH_STATUS <> -1 )
        BEGIN

            --OPEN CurDB;
            --FETCH NEXT FROM CurDB INTO @deleted_colmn;

            SET @FieldID = ( SELECT TOP 1
                                    FieldID
                             FROM   fld_Field
                             WHERE  fld_Field.FieldName = @ColName
                           );

            SET @newvalue = ( SELECT TOP 1
                                        @ColName
                              FROM      Inserted
                              WHERE     @ColName = @ColName
                            );
            SET @oldvalue = ( SELECT TOP 1
                                        @ColName
                              FROM      Deleted
              IF @newvalue <> @oldvalue
                BEGIN

                    INSERT  INTO dbo.utl_Audit_Trail_Field
                            ( AuditTrailID ,
                              FieldID ,
                              OldValue ,
                              NewValue ,
                              CreatedDate ,
                              CreatedUserID ,
                              UpdatedDate ,
                              UpdatedUserID
                            )
                    VALUES  ( @AuditTrailID , -- AuditTrailID - bigint
                              @FieldID , -- FieldID - bigint
                              @oldvalue , -- OldValue - nvarchar(1000)
                              @newvalue , -- NewValue - nvarchar(1000)
                              @CreatedDate , -- CreatedDate - datetime
                              @CreatedUserID , -- CreatedUserID - bigint
                              @CreatedDate , -- UpdatedDate - datetime
                              @CreatedUserID  -- UpdatedUserID - bigint
                            );

                END;

            FETCH NEXT FROM columnCursor INTO @ColName;

        END;                WHERE     @ColName = @ColName

                            );


问:
How do I get one column with one row and one column with two rows nested in HTML/CSS
I'm looking for the easiest way to get a icon on the left vertical aligned with the two lines of text on the right.

What I'm struggling with is the way I have to organize my HTML. I can functionally build this, but I think it's not efficient/clean the way I do this (too much code). So any advice on how this problem can be tackled is highly appreciated :). A screenshot from what I want to achieve is below. I'm using Font Awesome and Bootstrap 3 for development.

Screenshot of what I want to achieve

答:
You mean something like this? Just change the image used and the text, and whatever you need to change

.col-xs-12 {
  background-color: pink;
}

._imgContainer {
  position: relative;
}

._imgContainer>._icon {
  position: absolute;
  left: 50%;
  transform:translate(-50%,25%);
  width: 50px;
  height: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<div class="container">
  <div class="row">

    <div class="col-xs-12">
      <div class="row">
        <div class="col-xs-2 _imgContainer">
          <image class="_icon" src="http://www.jqueryscript.net/images/jQuery-Plugin-For-Fullscreen-Image-Viewer-Chroma-Gallery.jpg" />
        </div>
        <div class="col-xs-10 _textContainer">
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat..</p>
        </div>
      </div>
    </div>

  </div>
</div></code>```

Body:
You mean something like this? Just change the image used and the text, and whatever you need to change

.col-xs-12 {
  background-color: pink;
}

._imgContainer {
  position: relative;
}

._imgContainer>._icon {
  position: absolute;
  left: 50%;
  transform:translate(-50%,25%);
  width: 50px;
  height: 50px;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<div class="container">
  <div class="row">

    <div class="col-xs-12">
      <div class="row">
        <div class="col-xs-2 _imgContainer">
          <image class="_icon" src="http://www.jqueryscript.net/images/jQuery-Plugin-For-Fullscreen-Image-Viewer-Chroma-Gallery.jpg" />
        </div>
        <div class="col-xs-10 _textContainer">
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat..</p>
        </div>
      </div>
    </div>

  </div>
</div>


问:
How can get data complicated json response in angular 2?
I have a booking listing page. I tried to get data from json file. In first format result is getting but second format data is not getting. I have explained two format below. Please help me to solve this problem. I have added my code in plunker.

Plunker Link

First

```<code>    [
       {"_id": "57ee4e32f8f888dc11000029", "cabinname": "Foo", "user": "5818355ad2ae67e505431d5b"
       },
       {"_id": "57f22cf3f8f888800c000030", "cabinname": "Joo", "user": "5818355ad2ae67e505431d5b"
       },
       { "_id": "57f22cf3f8f888800c000031", "cabinname": "Maria", "user": "5818355ad2ae67e505431d5b"
       },
      {
       "_id": "57f22cf3f8f888800c000032", "cabinname": "Peter", "user": "5818355ad2ae67e505431d5b"
      },
      {"_id": "57f22cf3f8f888800c000033", "cabinname": "Declan", "user": "5818355ad2ae67e505431d5b"
       }
   ]
</code>```

Second

```<code>{
  "bookingDetails": {
    "data": [
      {"_id": "57ee4e32f8f888dc11000029", "cabinname": "Foo", "user": "5818355ad2ae67e505431d5b"
      },
      {"_id": "57f22cf3f8f888800c000030", "cabinname": "Joo", "user": "5818355ad2ae67e505431d5b"
      },
      {
        "_id": "57f22cf3f8f888800c000031", "cabinname": "Maria", "user": "5818355ad2ae67e505431d5b"
      },
      {
        "_id": "57f22cf3f8f888800c000032", "cabinname": "Peter", "user": "5818355ad2ae67e505431d5b"
      },
      {
        "_id": "57f22cf3f8f888800c000033", "cabinname": "Declan", "user": "5818355ad2ae67e505431d5b"
      }
    ]
  }
}
</code>```

Json file is oncluded in apidata -> testData.json

app -> booking -> booking.service.ts

```<code>getBooking(): Promise<Bookings[]> {
        return this.http.get(this._url)
            .toPromise()
            .then(response => response.json() as Bookings[])
            .catch(this.handleError);
    }
</code>```

app -> booking -> booking.component.ts

```<code>export class BookingComponent implements OnInit {
    bookings: Bookings[];
    constructor(private employeeService: BookingService) {}
    getBooking(): void {
        /*this.employeeService.getEmployee().then(employees => this.employees = employees);*/
        this.employeeService.getBooking().then(bookings => this.bookings = bookings);
    }
    ngOnInit(): void {
        this.getBooking();
    }
}
</code>```

答:
You should look into using subscribe instead of promise.
But, if you want to use promises, change your booking.service.ts file to

```<code>getBooking(): Promise<Bookings[]> {
        return this.http.get(this._url)
            .map(response => response.json().bookingDetails.data as Bookings[])
            .toPromise()
            .catch(this.handleError);
    }
</code>```

Body:
I have a booking listing page. I tried to get data from json file. In first format result is getting but second format data is not getting. I have explained two format below. Please help me to solve this problem. I have added my code in plunker.

Plunker Link

First

    [
       {"_id": "57ee4e32f8f888dc11000029", "cabinname": "Foo", "user": "5818355ad2ae67e505431d5b"
       },
       {"_id": "57f22cf3f8f888800c000030", "cabinname": "Joo", "user": "5818355ad2ae67e505431d5b"
       },
       { "_id": "57f22cf3f8f888800c000031", "cabinname": "Maria", "user": "5818355ad2ae67e505431d5b"
       },
      {
       "_id": "57f22cf3f8f888800c000032", "cabinname": "Peter", "user": "5818355ad2ae67e505431d5b"
      },
      {"_id": "57f22cf3f8f888800c000033", "cabinname": "Declan", "user": "5818355ad2ae67e505431d5b"
       }
   ]

Second

{
  "bookingDetails": {
    "data": [
      {"_id": "57ee4e32f8f888dc11000029", "cabinname": "Foo", "user": "5818355ad2ae67e505431d5b"
      },
      {"_id": "57f22cf3f8f888800c000030", "cabinname": "Joo", "user": "5818355ad2ae67e505431d5b"
      },
      {
        "_id": "57f22cf3f8f888800c000031", "cabinname": "Maria", "user": "5818355ad2ae67e505431d5b"
      },
      {
        "_id": "57f22cf3f8f888800c000032", "cabinname": "Peter", "user": "5818355ad2ae67e505431d5b"
      },
      {
        "_id": "57f22cf3f8f888800c000033", "cabinname": "Declan", "user": "5818355ad2ae67e505431d5b"
      }
    ]
  }
}

Json file is oncluded in apidata -> testData.json

app -> booking -> booking.service.ts

getBooking(): Promise<Bookings[]> {
        return this.http.get(this._url)
            .toPromise()
            .then(response => response.json() as Bookings[])
            .catch(this.handleError);
    }

app -> booking -> booking.component.ts

export class BookingComponent implements OnInit {
    bookings: Bookings[];
    constructor(private employeeService: BookingService) {}
    getBooking(): void {
        /*this.employeeService.getEmployee().then(employees => this.employees = employees);*/
        this.employeeService.getBooking().then(bookings => this.bookings = bookings);
    }
    ngOnInit(): void {
        this.getBooking();
    }
}

Body:
You should look into using subscribe instead of promise.
But, if you want to use promises, change your booking.service.ts file to

getBooking(): Promise<Bookings[]> {
        return this.http.get(this._url)
            .map(response => response.json().bookingDetails.data as Bookings[])
            .toPromise()
            .catch(this.handleError);
    }


问:
js get item[1] from nested array with item[0] = somevalue
I have the following object:

```<code>GLOBALS = [
   [...],
   [...],
   [
       [...],
       ["searchValue", [<interestingInfo>]]
   ]
]
</code>```

I want to find a way to get the  array based on the searchValue.

EDIT: here is my non working attempt:

```<code>GLOBALS.map(function(item){
    if(item && item.constructor === Array)
        return item.map(function(itemLvl2) {
            if(itemLvl2 && itemLvl2.constructor === Array)
                return itemLvl2.map(function(itemLvl3) {
                    return itemLvl3 && itemLvl3.constructor === Array && itemLvl3[0] == 'searchValue'
                });
            else
                return false;
        });
    else
        return false;
})
</code>```

EDIT: SAMPLE DATA / USE CASE

In need this in order to get all alias email addresses from gmail. You can get them when you open gmail and enter the following into the console:

```<code>GLOBALS[17][15][1].map(function(item) { return item[1]; })
</code>```

Now I try to do this in a more generic way (i.e. not hard coding the array indices)

The search value is 'cfs'

答:
As suggested, you can use recursion to get rid of hard coded levels.

Optimisations:

if (JSON.stringify(array).indexOf(search) < 0) return;. This will make sure if current object tree has specified value. If not, the entire tree will be skipped.

Array.isArray(array) will enfore check only on Arrays.

array.indexOf(search) < 0 will check if search is in this array or not. If not found, value exists in some child node. This will also remove the dependency of just checking 1st value. Yes, this will add to performance, but will work even if order is changed.

Array.some because is will short-circuit loop on first correct value.

function getSearchValue(array, search) {
  if (JSON.stringify(array).indexOf(search) < 0) return;
  if (Array.isArray(array)) {
    if (array.indexOf(search) < 0) {
      var r = null;
      array.some(function(item) {
        r = getSearchValue(item, search)
        return !!r
      })
      return r;
    } else {
      return array;
    }
  }
}
```

Body:
I have the following object:

GLOBALS = [
   [...],
   [...],
   [
       [...],
       ["searchValue", [<interestingInfo>]]
   ]
]

I want to find a way to get the  array based on the searchValue.

EDIT: here is my non working attempt:

GLOBALS.map(function(item){
    if(item && item.constructor === Array)
        return item.map(function(itemLvl2) {
            if(itemLvl2 && itemLvl2.constructor === Array)
                return itemLvl2.map(function(itemLvl3) {
                    return itemLvl3 && itemLvl3.constructor === Array && itemLvl3[0] == 'searchValue'
                });
            else
                return false;
        });
    else
        return false;
})

EDIT: SAMPLE DATA / USE CASE

In need this in order to get all alias email addresses from gmail. You can get them when you open gmail and enter the following into the console:

GLOBALS[17][15][1].map(function(item) { return item[1]; })

Now I try to do this in a more generic way (i.e. not hard coding the array indices)

The search value is 'cfs'


问:
Invert some values in SQL Server
I have a table like this one:

```<code>ID   |   Description  |  Account  |  DepAccount  |  Value
----------------------------------------------------------
0    |  Something     | 110       | 0            | 500,50
1    |  Something x   | 0         | 110          | -320,95
</code>```

Now I need a query to sum the values but there is an issue with it.

Like in the example, if the account is 110, it is fine, if the DepAccount is 110, I need to invert the value so I sum 320,95 instead of -320,95

So the query should return value: 821,45

So something like:

```<code>SELECT SUM(Value) As Total
FROM Table
WHERE Account = 110 OR DepAccount = 110 WHERE etc...
</code>```

Who can help? I'm using SQL Server 2008 Express Edition

答:
The sample set is small so it's a bit unclear what you're trying to do, but it sounds something like this:

```<code>SELECT
  sum(case
        when Account = 110 then Value
        when DepAccount = 100 then -1 * Value
        else 0
      end)
from MyTable
</code>```

That assumes that "invert" means "reverse the sign". If you only need to make negatives positive, use

```<code>SELECT
  sum(case
        when Account = 110 then Value
        when DepAccount = 100 then abs(Value)
        else 0
      end)
from MyTable
</code>```

Title: Invert some values in SQL Server

Body:
I have a table like this one:

ID   |   Description  |  Account  |  DepAccount  |  Value
----------------------------------------------------------
0    |  Something     | 110       | 0            | 500,50
1    |  Something x   | 0         | 110          | -320,95

Now I need a query to sum the values but there is an issue with it.

Like in the example, if the account is 110, it is fine, if the DepAccount is 110, I need to invert the value so I sum 320,95 instead of -320,95

So the query should return value: 821,45

So something like:

SELECT SUM(Value) As Total
FROM Table
WHERE Account = 110 OR DepAccount = 110 WHERE etc...

Who can help? I'm using SQL Server 2008 Express Edition

Body:
The sample set is small so it's a bit unclear what you're trying to do, but it sounds something like this:

SELECT
  sum(case
        when Account = 110 then Value
        when DepAccount = 100 then -1 * Value
        else 0
      end)
from MyTable

That assumes that "invert" means "reverse the sign". If you only need to make negatives positive, use

SELECT
  sum(case
        when Account = 110 then Value
        when DepAccount = 100 then abs(Value)
        else 0
      end)
from MyTable


问:
Send Data packet to Client
I need to sent NSData which holds JSON Strings as well total number of length in form of (length of actual string+actual string).I need to send a packet of data that reserves first 10 bytes for length of string and followed by string

while sending NSData object I also need to send its length in first 10 bytes followed by data  like :

length of data + JSON string = total data sent to java client .

further java client will read first 10 byte to know actual length of data coming to make an byte array and move further.

答:
This brute force example uses first 10 characters for string representation of payload length followed by actual payload.

```<code>NSArray *arrPayload = @[@"Hello", @"world"];

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arrPayload
                                                   options:0
                                                     error:nil];

NSString *jsonString = [[NSString alloc] initWithData:jsonData
                                             encoding:NSUTF8StringEncoding];

NSString *comboString = [NSString stringWithFormat:@"%010lu%@",
                            (unsigned long)jsonString.length, jsonString];

NSLog(@"%@", comboString);

NSData* combinedData = [comboString dataUsingEncoding:NSUTF8StringEncoding];
</code>```

result:

0000000017["Hello","world"]

But: if this is supposed to be sent as a HTTP request you might want to consider using Content-Length header to pass the length information instead.

Title: Send Data packet to Client

Body:
This brute force example uses first 10 characters for string representation of payload length followed by actual payload.

NSArray *arrPayload = @[@"Hello", @"world"];

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arrPayload
                                                   options:0
                                                     error:nil];

NSString *jsonString = [[NSString alloc] initWithData:jsonData
                                             encoding:NSUTF8StringEncoding];

NSString *comboString = [NSString stringWithFormat:@"%010lu%@",
                            (unsigned long)jsonString.length, jsonString];

NSLog(@"%@", comboString);

NSData* combinedData = [comboString dataUsingEncoding:NSUTF8StringEncoding];

result:

0000000017["Hello","world"]

But: if this is supposed to be sent as a HTTP request you might want to consider using Content-Length header to pass the length information instead.


问:
XML conditional parsing by javascript
I have the following xml file and I am trying to extract some elements

```<code><entry>
    <form>
        <orth>Agathe</orth>
        <pron>agat</pron>
    </form>
    <gramGrp>
        <pos>n</pos>
    </gramGrp>
    <sense>
        <cit type="trans">
            <quote>Agatha</quote>
        </cit>
    </sense>
</entry>
<entry>
    <form>
        <orth>Aix-la-Chapelle</orth>
    </form>
    <gramGrp>
        <pos>n</pos>
    </gramGrp>
    <sense>
        <cit type="trans">
            <quote>Aix-la-Chapelle</quote>
        </cit>
    </sense>
</entry>
</code>```

I already extracted all the elements  and  but I need only those that have n in the pos element.

```<code>function parseWordsAlt(xml) {

    // this reads the XML and puts the whole structure in the variable xmlDoc
    var xmlDoc = xml.responseXML;
    // this takes all the entries which has tag names orth
    var resultOrth = xmlDoc.getElementsByTagName("orth");
    // this takes all the entries which has tag names orth
    var resultTranslation = xmlDoc.getElementsByTagName("quote");

    // cycles through the first n tags named orth
    var n=20;
    for (var i=0;i<n;i++) {
        for (var j=0;j<n;j++) {
            var resultWord1=resultOrth[i].childNodes[0].nodeValue;
            var resultWord2=resultTranslation[j].childNodes[0].nodeValue;
        }
    }
}
</code>```

I am sorry for my bad jargon but I am new to this.
Can you help me with this?

答:
There are a few details that we don't know, as the environment that you are using, but here you have a small proof of concept that may help you to get a solution: check each entry and if it fulfill your condition, then take the values you need:

var xml=document.getElementById("xml").innerHTML;

function parseWordsAlt(xmlDoc) {

    // this takes all the entries
    var entries = xmlDoc.getElementsByTagName("entry");
    for (var i=0;i<entries.length;i++) {
      var pos=entries[i].getElementsByTagName("pos");
      if (pos[0].textContent==="n") {
         var orth = entries[i].getElementsByTagName("orth")[0].textContent;
         var quote = entries[i].getElementsByTagName("quote")[0].textContent;
         console.log(`${orth},${quote}`);
      }
    }
}

parseWordsAlt(new DOMParser().parseFromString(xml, "text/xml"));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><template id="xml">
<entries>
<entry>
    <form>
        <orth>Agathe</orth>
        <pron>agat</pron>
    </form>
    <gramGrp>
        <pos>n</pos>
    </gramGrp>
    <sense>
        <cit type="trans">
            <quote>Agatha</quote>
        </cit>
    </sense>
</entry>
<entry>
    <form>
        <orth>Aix-la-Chapelle</orth>
    </form>
    <gramGrp>
        <pos>n</pos>
    </gramGrp>
    <sense>
        <cit type="trans">
            <quote>Aix-la-Chapelle</quote>
        </cit>
    </sense>
</entry>
</entries>
</template></code>```

Title: XML conditional parsing by javascript

Body:
I have the following xml file and I am trying to extract some elements

<entry>
    <form>
        <orth>Agathe</orth>
        <pron>agat</pron>
    </form>
    <gramGrp>
        <pos>n</pos>
    </gramGrp>
    <sense>
        <cit type="trans">
            <quote>Agatha</quote>
        </cit>
    </sense>
</entry>
<entry>
    <form>
        <orth>Aix-la-Chapelle</orth>
    </form>
    <gramGrp>
        <pos>n</pos>
    </gramGrp>
    <sense>
        <cit type="trans">
            <quote>Aix-la-Chapelle</quote>
        </cit>
    </sense>
</entry>

I already extracted all the elements  and  but I need only those that have n in the pos element.

function parseWordsAlt(xml) {

    // this reads the XML and puts the whole structure in the variable xmlDoc
    var xmlDoc = xml.responseXML;
    // this takes all the entries which has tag names orth
    var resultOrth = xmlDoc.getElementsByTagName("orth");
    // this takes all the entries which has tag names orth
    var resultTranslation = xmlDoc.getElementsByTagName("quote");

    // cycles through the first n tags named orth
    var n=20;
    for (var i=0;i<n;i++) {
        for (var j=0;j<n;j++) {
            var resultWord1=resultOrth[i].childNodes[0].nodeValue;
            var resultWord2=resultTranslation[j].childNodes[0].nodeValue;
        }
    }
}

I am sorry for my bad jargon but I am new to this.
Can you help me with this?

Body:
There are a few details that we don't know, as the environment that you are using, but here you have a small proof of concept that may help you to get a solution: check each entry and if it fulfill your condition, then take the values you need:

var xml=document.getElementById("xml").innerHTML;

function parseWordsAlt(xmlDoc) {

    // this takes all the entries
    var entries = xmlDoc.getElementsByTagName("entry");
    for (var i=0;i<entries.length;i++) {
      var pos=entries[i].getElementsByTagName("pos");
      if (pos[0].textContent==="n") {
         var orth = entries[i].getElementsByTagName("orth")[0].textContent;
         var quote = entries[i].getElementsByTagName("quote")[0].textContent;
         console.log(`${orth},${quote}`);
      }
    }
}

parseWordsAlt(new DOMParser().parseFromString(xml, "text/xml"));

<template id="xml">
<entries>
<entry>
    <form>
        <orth>Agathe</orth>
        <pron>agat</pron>
    </form>
    <gramGrp>
        <pos>n</pos>
    </gramGrp>
    <sense>
        <cit type="trans">
            <quote>Agatha</quote>
        </cit>
    </sense>
</entry>
<entry>
    <form>
        <orth>Aix-la-Chapelle</orth>
    </form>
    <gramGrp>
        <pos>n</pos>
    </gramGrp>
    <sense>
        <cit type="trans">
            <quote>Aix-la-Chapelle</quote>
        </cit>
    </sense>
</entry>
</entries>
</template>


问:
Angular2 file upload component that returns data
I want to create a file upload component that reads the file, parse it and returns the Object.
This is my main component.

import { Component,OnInit } from '@angular/core';
import { Parameter } from './parameter.interface';
import { FlexUpload } from './flexUpload.component';

@Component({
  selector: 'app-root',
  template: `
    <app-flexUpload></app-flexUpload>
  `
})
export class AppComponent implements OnInit  {

  fUp : FlexUpload = new FlexUpload();

  ngOnInit(){
    this.fUp.getData().then(data => console.log(data));
  }

}  ```
</div>
</div>
</p>

<p>The data received from fUp.getData should be used.</p>

<p>This is my FlexUpload component</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { Component,ElementRef, Input, ViewChild,Injectable } from '@angular/core';

@Component({
  selector: 'app-flexUpload',
  templateUrl : './flexUpload.component.html',
})

@Injectable()
export class FlexUpload{

  @ViewChild('fileInput') inputEl: ElementRef;

  changed(){
    let res: HTMLInputElement = this.inputEl.nativeElement;
    let myFile = res.files[0];

    var data;

    data = io.readZipFile([myFile]);
    console.log(data); //--> this works, want to return it in getData()

  };

  getData():Promise<any>{
    return new Promise(resolve => {
    setTimeout(()=> resolve(4),5000);// instead of 4, I want to return data when it is  parsed
    });
  }

}</code>```

Till now getData() only returns 4 after waiting 5 seconds, I would like to return data, when a file was uploaded and the data was parsed.
How can I do this?
Can I somehow observe data?

Best and Thanks in advance,
P

答:
I figured it out. I wasn't aware of the @Output.
I could solve it after watching this video:
https://youtu.be/xFYzfHGCJBw.

This is my new AppComponent

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <app-flexUpload (onYell)="yell($event)"></app-flexUpload>
  `
})
export class AppComponent implements OnInit  {

yell(data:any){
  console.log(data);//data comes out here
}

}  ```
</div>
</div>
</p>

<p>It waits for the onYell event and then calls the yell($event) function.
The onYell event is transmitted after a file was selected and read in FlexUpload's changed() function</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>declare var io:any;

import { Component,ElementRef, Input, ViewChild,Injectable,Output,EventEmitter } from '@angular/core';

@Component({
  selector: 'app-flexUpload',
  template: `<input type="file" [multiple]="multiple" #fileInput (change)="changed()" >`,
})

@Injectable()
export class FlexUpload{

  @ViewChild('fileInput') inputEl: ElementRef;
  @Output() onYell = new EventEmitter();

  changed(){// is called when a file is selected
    let res: HTMLInputElement = this.inputEl.nativeElement;
    let myFile = res.files[0];

    var data;

    data = io.readZipFile([myFile]);//uses HTML5 file api
    this.onYell.emit(data);// emit data
  };

}</code>```

Body:
I want to create a file upload component that reads the file, parse it and returns the Object.
This is my main component.

import { Component,OnInit } from '@angular/core';
import { Parameter } from './parameter.interface';
import { FlexUpload } from './flexUpload.component';

@Component({
  selector: 'app-root',
  template: `
    <app-flexUpload></app-flexUpload>
  `
})
export class AppComponent implements OnInit  {

  fUp : FlexUpload = new FlexUpload();

  ngOnInit(){
    this.fUp.getData().then(data => console.log(data));
  }

}

The data received from fUp.getData should be used.

This is my FlexUpload component

import { Component,ElementRef, Input, ViewChild,Injectable } from '@angular/core';

@Component({
  selector: 'app-flexUpload',
  templateUrl : './flexUpload.component.html',
})

@Injectable()
export class FlexUpload{

  @ViewChild('fileInput') inputEl: ElementRef;

  changed(){
    let res: HTMLInputElement = this.inputEl.nativeElement;
    let myFile = res.files[0];

    var data;

    data = io.readZipFile([myFile]);
    console.log(data); //--> this works, want to return it in getData()

  };

  getData():Promise<any>{
    return new Promise(resolve => {
    setTimeout(()=> resolve(4),5000);// instead of 4, I want to return data when it is  parsed
    });
  }

}

Till now getData() only returns 4 after waiting 5 seconds, I would like to return data, when a file was uploaded and the data was parsed.
How can I do this?
Can I somehow observe data?

Best and Thanks in advance,
P

Body:
I figured it out. I wasn't aware of the @Output.
I could solve it after watching this video:
https://youtu.be/xFYzfHGCJBw.

This is my new AppComponent

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <app-flexUpload (onYell)="yell($event)"></app-flexUpload>
  `
})
export class AppComponent implements OnInit  {

yell(data:any){
  console.log(data);//data comes out here
}

}

It waits for the onYell event and then calls the yell($event) function.
The onYell event is transmitted after a file was selected and read in FlexUpload's changed() function

declare var io:any;

import { Component,ElementRef, Input, ViewChild,Injectable,Output,EventEmitter } from '@angular/core';

@Component({
  selector: 'app-flexUpload',
  template: `<input type="file" [multiple]="multiple" #fileInput (change)="changed()" >`,
})

@Injectable()
export class FlexUpload{

  @ViewChild('fileInput') inputEl: ElementRef;
  @Output() onYell = new EventEmitter();

  changed(){// is called when a file is selected
    let res: HTMLInputElement = this.inputEl.nativeElement;
    let myFile = res.files[0];

    var data;

    data = io.readZipFile([myFile]);//uses HTML5 file api
    this.onYell.emit(data);// emit data
  };

}


问:
Case insensitive unicode collation in MySQL
I've got a database where we store usernames with a capital first letter of each name -- ie, IsaacSparling.  I'm trying to do case insensitive autocomplete against my MySQL (v5.1.46) db.  Table has a charset of UTF8 and a collation of utf8_unicode_ci.  I've done these tests against the utf8_general_ci collation as well.

Plain ASCII text works fine:

```<code>mysql> select username from users where username like 'j%';
+----------------+
| username       |
+----------------+
| J********      |
| J***********   |
| J************* |
+----------------+
3 rows in set (0.00 sec)

mysql> select username from users where username like 'J%';
+----------------+
| username       |
+----------------+
| J********      |
| J***********   |
| J************* |
+----------------+
3 rows in set (0.00 sec)
</code>```

(names redacted, but they're there).

However, when I try to do the same for unicode characters outside the ASCII set, no such luck:

```<code>mysql> select username from users where username like 'ø%';
Empty set (0.00 sec)

mysql> select username from users where username like 'Ø%';
+-------------+
| username    |
+-------------+
| Ø*********  |
+-------------+
1 row in set (0.00 sec)
</code>```

Some investigation has lead me to this:  http://bugs.mysql.com/bug.php?id=19567  (tl;dr, this is a known bug with the unicode collations, and fixing it is at 'new feature' priority -- ie, won't be finished in any reasonable timeframe).

Has anybody discovered any effective workarounds that allow for case-insensitive searching for unicode characters in MySQL?  Any thoughts appreciated!

答:
Have you tried using CONVERT?  Something like

```<code>WHERE `lastname` LIKE CONVERT( _utf8 'ø%' USING latin1 )
</code>```

might work for you.

Body:
I've got a database where we store usernames with a capital first letter of each name -- ie, IsaacSparling.  I'm trying to do case insensitive autocomplete against my MySQL (v5.1.46) db.  Table has a charset of UTF8 and a collation of utf8_unicode_ci.  I've done these tests against the utf8_general_ci collation as well.

Plain ASCII text works fine:

mysql> select username from users where username like 'j%';
+----------------+
| username       |
+----------------+
| J********      |
| J***********   |
| J************* |
+----------------+
3 rows in set (0.00 sec)

mysql> select username from users where username like 'J%';
+----------------+
| username       |
+----------------+
| J********      |
| J***********   |
| J************* |
+----------------+
3 rows in set (0.00 sec)

(names redacted, but they're there).

However, when I try to do the same for unicode characters outside the ASCII set, no such luck:

mysql> select username from users where username like 'ø%';
Empty set (0.00 sec)

mysql> select username from users where username like 'Ø%';
+-------------+
| username    |
+-------------+
| Ø*********  |
+-------------+
1 row in set (0.00 sec)

Some investigation has lead me to this:  http://bugs.mysql.com/bug.php?id=19567  (tl;dr, this is a known bug with the unicode collations, and fixing it is at 'new feature' priority -- ie, won't be finished in any reasonable timeframe).

Has anybody discovered any effective workarounds that allow for case-insensitive searching for unicode characters in MySQL?  Any thoughts appreciated!

Body:
Have you tried using CONVERT?  Something like

WHERE `lastname` LIKE CONVERT( _utf8 'ø%' USING latin1 )

might work for you.


问:
How do I apply border bottom to more than one line of text?
I'm using border-bottom for all the CATs on my website. Great when it a word or two. On trying to apply it to a CTA that's more than a sentence, the words break on mobile and the border-bottom only affects the last line of the sentence. How do I make the border-bottom affect the lines of text? I don't want to use underline for the sake of transition on hover, and the fact that underlines does not give my the 1px border I want.

See images for desktop, mobile and tab here

答:
This seems to work for me!

.underline {
  border-bottom: 1px solid black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span class="underline">Read more on research, empathy and personas on Medium</span></code>```

Body:
This seems to work for me!

.underline {
  border-bottom: 1px solid black;
}

<span class="underline">Read more on research, empathy and personas on Medium</span>


问:
Python, Sqlite - Is there any way to neuter a condition in WHERE clause of a query?
I have some Entry boxes on a form and a button that will search a db's table by executing a query that is composed of a WHERE clause with several conditions corresponding to the input boxes.
The user may or may not fill all the input boxes, so I just want to have a predefined query with all columns on the where clause like:

```<code>column01=? AND column02=? AND ... AND columnN=?
</code>```

and then have a tuple or list which simply I have constructed on a loop where inputed data is placed on the same order, columns of the WHERE clause were arranged and each input only checked whether it was "" (not been input) and if so the respective place in the list would be assigned something that makes that specific condition transparent!. To clarify myself, see what means if user filled no input box (imagine that thing would be an asterisk):

```<code>"SELECT * FROM sometable WHERE column01=* AND ... AND columnN=*"
</code>```

that is desirable to work like this query:

```<code>"SELECT * FROM sometable"
</code>```

which bears no constrain on any column. Is this credible?

答:
As Christos correctly pointed out above, pattern matching in SQL queries is the way to do this and lots of other much more complicated things.
I just need to use LIKE instead of equality sign and assign '%' to any condition I want to make transparent. more information here

Body:
I have some Entry boxes on a form and a button that will search a db's table by executing a query that is composed of a WHERE clause with several conditions corresponding to the input boxes.
The user may or may not fill all the input boxes, so I just want to have a predefined query with all columns on the where clause like:

column01=? AND column02=? AND ... AND columnN=?

and then have a tuple or list which simply I have constructed on a loop where inputed data is placed on the same order, columns of the WHERE clause were arranged and each input only checked whether it was "" (not been input) and if so the respective place in the list would be assigned something that makes that specific condition transparent!. To clarify myself, see what means if user filled no input box (imagine that thing would be an asterisk):

"SELECT * FROM sometable WHERE column01=* AND ... AND columnN=*"

that is desirable to work like this query:

"SELECT * FROM sometable"

which bears no constrain on any column. Is this credible?