问:
Multiline TextView with width "wrap_content"
I am wondering how to have a TextView display its content on several lines without hardcoding the width in the XML.

```<code>    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="right"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:singleLine="false"
            android:text="Long multiline text"/>

        <TextView
            android:textColor="@color/text_color"
            android:layout_width="130dp"
            android:layout_height="wrap_content"
            />

    </LinearLayout>
</code>```

Any thought welcome.

EDIT: my problem is that when the text exceeds the width set (because it reaches the end of the screen) a portion of the text is just not displayed. I would expect the text to be split on two lines

答:
Also add </p>

```<code>android:minLines="2"
android:scrollHorizontally="false"
</code>```

Body:
I am wondering how to have a TextView display its content on several lines without hardcoding the width in the XML.

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="right"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:singleLine="false"
            android:text="Long multiline text"/>

        <TextView
            android:textColor="@color/text_color"
            android:layout_width="130dp"
            android:layout_height="wrap_content"
            />

    </LinearLayout>

Any thought welcome.

EDIT: my problem is that when the text exceeds the width set (because it reaches the end of the screen) a portion of the text is just not displayed. I would expect the text to be split on two lines

Body:
Also add

android:minLines="2"
android:scrollHorizontally="false"


来源: stackexchange

问:
Difference between ThreadCount and StepCount in TIBCO BW Engine
Can anyone explain me the difference between StepCount and ThreadCount property of TIBCO BW Engine . I had tried to understand through TIBCO docs but unable to understand.
So, Please if anyone can explain me this would be great .
Thanks in advance.

答:
ThreadCount

The Thread Count concept states the number of thread a TIBCO BW engine can allocate. The default number of threads is eight.

The number of threads means the number of jobs that can be executed simultaneously in the engine. So the maximum number of jobs that can concurrently in the engine are limited to number threads, that is eight. This property specifies the size of the job thread pool, and is applied to all the AppNodes in the AppSpace if set at the AppSpace level.

Threads carries out a limited number of tasks or activities uninterrupted and then yield to the next job that is ready.  Starting with a default value of eight threads the thread count can be  adjusted to optimum value and now it can be doubled until CPU maximum level is reached.

StepCount

The StepCount concept states the number of activities that are accomplished by an engine thread, without any disruption, before yielding the engine thread to another job that is ready in the job pool. The default value of the step counter is -1. When the value is set to -1, the engine can decide the required StepCount value. A low StepCount value may humiliate engine performance due to frequent thread exchange depending on the situation.

ContentLicense: CC BY-SA 3.0


问:
Not able to get woocommerce featured Product
I am trying to display 6 featured products with their thumbnails, price and title. But I am not able to see anything, however if I use $loop->found_posts I can see there are 6 records fetching back from database.
I have also added these lines in wp-config.php to see the errors but I am not able to see any error on the page

wp-config.php

```<code>define('WP_DEBUG', true);
if (WP_DEBUG) {
    define('WP_DEBUG_LOG', true);
    define('WP_DEBUG_DISPLAY', true);
    @ini_set('display_errors', 0);
}
</code>```

here is my code for displaying featured posts

```<code><?php
    $args = array (
                    'post_type'=>'product',
                    'meta_key'=>'_featured',
    'posts_per_page'=>6
    );
    $loop= new WP_Query($args);
    //echo $loop->found_posts;
    while($loop->have_posts()): the_post();
    echo '
    <div class="col-xs-4">
    <div class="custom-product">
        <img src="'.woocommerce_get_product_thumbnail(300,335).'">
        <div class="price-title">
            <h2>'.the_title().'</h2>
            <h3>'.$product->get_price_html().'</h3>
        </div>
    </div>
    </div>
    ';
    endwhile;
?>
</code>```

答:
I got the same problem. Try this ! Works for me</p>

```<code> <?php
 $featured_query = new WP_Query( array(
     'tax_query' => array(
             array(
                 'taxonomy' => 'product_visibility',
                 'field'    => 'name',
                 'terms'    => 'featured',
                 'operator' => 'IN'
             ),
      ),
 ) );
 ?>
</code>```

Body:
I am trying to display 6 featured products with their thumbnails, price and title. But I am not able to see anything, however if I use $loop->found_posts I can see there are 6 records fetching back from database.
I have also added these lines in wp-config.php to see the errors but I am not able to see any error on the page

wp-config.php

define('WP_DEBUG', true);
if (WP_DEBUG) {
    define('WP_DEBUG_LOG', true);
    define('WP_DEBUG_DISPLAY', true);
    @ini_set('display_errors', 0);
}

here is my code for displaying featured posts

<?php
    $args = array (
                    'post_type'=>'product',
                    'meta_key'=>'_featured',
    'posts_per_page'=>6
    );
    $loop= new WP_Query($args);
    //echo $loop->found_posts;
    while($loop->have_posts()): the_post();
    echo '

'.the_title().'

'.$product->get_price_html().'

    ';
    endwhile;
?>

Body:
I got the same problem. Try this ! Works for me

 <?php
 $featured_query = new WP_Query( array(
     'tax_query' => array(
             array(
                 'taxonomy' => 'product_visibility',
                 'field'    => 'name',
                 'terms'    => 'featured',
                 'operator' => 'IN'
             ),
      ),
 ) );
 ?>


问:
how to get valid json reply in IOS application after making a webservice
After making webservice my JSON response is as following

```<code>$response['success']=1;
$response['message']='enter successfully';
die(json_encode($response));
</code>```

but when I run this in iOS application this gives me error as following

JSON text did not start with array or object and option to allow fragments not set

答: Your json response is not a valid one.Please check your json object.</p>

Body:
After making webservice my JSON response is as following

$response['success']=1;
$response['message']='enter successfully';
die(json_encode($response));

but when I run this in iOS application this gives me error as following

JSON text did not start with array or object and option to allow fragments not set


问:
How do I detect Gear VR inputs in React VR scene?
I am trying to create a web app using React VR and run it using Samsung Gear VR.

I could not see the default white dot (VR pointer) while in VR mode in my scene. Consequently methods such as "onInput" and "onClick" are not working. The same methods work quite fine if I view the same scene outside VR mode - even using the browser provided in Gear VR.

Am I missing something? How do I access those methods while in VR mode in Gear VR?

Example code that works fine in normal web browser (including the one in Gear VR), but not when I am in VR.

```<code><Text
    style={{
        // backgroundColor: '#777879',
        fontSize: 0.2,
        transform: [{translate: [0, 0, -5]}],
        color: this.state.textColor
    }}
    onEnter={() => this.setState({textColor: 'gold'})}
    onExit={() => this.setState({textColor: 'white'})}>
    This text will turn gold when you look at it.
</Text>
</code>```

答:
You need to  add a raycaster:

To do so, you need to do the following:

In your project, go to <project root>/vr/client.js.
 Just before the init method, add a SimpleRaycaster constant.

```<code>const SimpleRaycaster = {
    getType: () => "simple",
    getRayOrigin: () => [0, 0, 0],
    getRayDirection: () => [0, 0, -1],
    drawsCursor: () => true
};

function init(bundle, parent, options) {

//...
</code>```

Then, in the init method, set  cursorVisibility: visible and add the raycaster to the array of raycasters:

```<code>function init(bundle, parent, options) {
  const vr = new VRInstance(bundle, 'Example', parent, {
      raycasters: [
          SimpleRaycaster // Add SimpleRaycaster to the options
      ],
      cursorVisibility: "visible", // Add cursorVisibility
      enableHotReload: true,
    ...options,
  });
  vr.render = function() {
    // Any custom behavior you want to perform on each frame goes here
  };
  // Begin the animation loop
  vr.start();
  return vr;
}

window.ReactVR = {init};
</code>```

That's it. Now you should have a white dot in the middle of your view.

Body:
I am trying to create a web app using React VR and run it using Samsung Gear VR.

I could not see the default white dot (VR pointer) while in VR mode in my scene. Consequently methods such as "onInput" and "onClick" are not working. The same methods work quite fine if I view the same scene outside VR mode - even using the browser provided in Gear VR.

Am I missing something? How do I access those methods while in VR mode in Gear VR?

Example code that works fine in normal web browser (including the one in Gear VR), but not when I am in VR.

<Text
    style={{
        // backgroundColor: '#777879',
        fontSize: 0.2,
        transform: [{translate: [0, 0, -5]}],
        color: this.state.textColor
    }}
    onEnter={() => this.setState({textColor: 'gold'})}
    onExit={() => this.setState({textColor: 'white'})}>
    This text will turn gold when you look at it.
</Text>

Body:
You need to  add a raycaster:

To do so, you need to do the following:

In your project, go to <project root>/vr/client.js.
 Just before the init method, add a SimpleRaycaster constant.

const SimpleRaycaster = {
    getType: () => "simple",
    getRayOrigin: () => [0, 0, 0],
    getRayDirection: () => [0, 0, -1],
    drawsCursor: () => true
};

function init(bundle, parent, options) {

//...

Then, in the init method, set  cursorVisibility: visible and add the raycaster to the array of raycasters:

function init(bundle, parent, options) {
  const vr = new VRInstance(bundle, 'Example', parent, {
      raycasters: [
          SimpleRaycaster // Add SimpleRaycaster to the options
      ],
      cursorVisibility: "visible", // Add cursorVisibility
      enableHotReload: true,
    ...options,
  });
  vr.render = function() {
    // Any custom behavior you want to perform on each frame goes here
  };
  // Begin the animation loop
  vr.start();
  return vr;
}

window.ReactVR = {init};

That's it. Now you should have a white dot in the middle of your view.


问:
C# Prevent resizing of both splitcontainer panels
I have a SplitContainer and was wondering how I would go about setting a static size for both panels and prevent the user from having the ability to resize the panels.  Would FixedPanel be the solution?  From what I read, I don't think it is.</p>

答:
The title of this question is misleading. There are more than one correct answers that satisfy the title of this question, in spite of the chosen answer.

For clarification:

FixedPanel is what you're looking for to have one panel keep its size when resizing the SplitContainer. According to the description in the Properties window:

FixedPanel

Indicates that a particular SplitContainer's Panel should remain fixed in size during resize events

IsSplitterFixed is just a way to temporarily prevent the user from moving the splitter. The panels still resize in proportion to the SplitContainer's size.


问:
Toggle Wordpress Locations on a google map using ACF
I'm building a website with a page that shows all locations (Custom Post Type) on a Google map. I use ACF (Advanced Custom Fields) to add the map location to the specific location. Furthermore I give each location a category (Parking, Hotel, ect.).

At this point all locations are show on the map correctly. But I'm trying to find a way to toggle these locations based on their category. So initially I want to hide all markers on the map and toggle their visibility based on a click (anchor or checkbox, doesn't matter).

I did see some answers that looked promising, but I can't figure this out with the code provided by ACF. I hope someone can help me with this. And can tell me where to add some extra code to setvisibility and toggle this based on a category select.

The code provide by ACF is shown below:

```<code><script type="text/javascript">
(function($) {

/*
*  new_map
*
*  This function will render a Google Map onto the selected jQuery element
*
*  @type    function
*  @date    8/11/2013
*  @since   4.3.0
*
*  @param   $el (jQuery element)
*  @return  n/a
*/

function new_map( $el ) {

    // var
    var $markers = $el.find('.marker');

    // vars
    var args = {
        zoom        : 16,
        center      : new google.maps.LatLng(0, 0),
        mapTypeId   : google.maps.MapTypeId.ROADMAP
    };

    // create map
    var map = new google.maps.Map( $el[0], args);

    // add a markers reference
    map.markers = [];

    // add markers
    $markers.each(function(){

        add_marker( $(this), map );

    });

    // center map
    center_map( map );

    // return
    return map;

}

/*
*  add_marker
*
*  This function will add a marker to the selected Google Map
*
*  @type    function
*  @date    8/11/2013
*  @since   4.3.0
*
*  @param   $marker (jQuery element)
*  @param   map (Google Map object)
*  @return  n/a
*/

function add_marker( $marker, map ) {

    // var
    var latlng = new google.maps.LatLng( $marker.attr('data-lat'), $marker.attr('data-lng') );

    // create marker
    var marker = new google.maps.Marker({
        position    : latlng,
        map         : map
    });

    // add to array
    map.markers.push( marker );

    // if marker contains HTML, add it to an infoWindow
    if( $marker.html() )
    {
        // create info window
        var infowindow = new google.maps.InfoWindow({
            content     : $marker.html()
        });

        // show info window when marker is clicked
        google.maps.event.addListener(marker, 'click', function() {

            infowindow.open( map, marker );

        });
    }

}

/*
*  center_map
*
*  This function will center the map, showing all markers attached to this map
*
*  @type    function
*  @date    8/11/2013
*  @since   4.3.0
*
*  @param   map (Google Map object)
*  @return  n/a
*/

function center_map( map ) {

    // vars
    var bounds = new google.maps.LatLngBounds();

    // loop through all markers and create bounds
    $.each( map.markers, function( i, marker ){

        var latlng = new google.maps.LatLng( marker.position.lat(), marker.position.lng() );

        bounds.extend( latlng );

    });

    // only 1 marker?
    if( map.markers.length == 1 )
    {
        // set center of map
        map.setCenter( bounds.getCenter() );
        map.setZoom( 16 );
    }
    else
    {
        // fit to bounds
        map.fitBounds( bounds );
    }

}

/*
*  document ready
*
*  This function will render each map when the document is ready (page has loaded)
*
*  @type    function
*  @date    8/11/2013
*  @since   5.0.0
*
*  @param   n/a
*  @return  n/a
*/
// global var
var map = null;

$(document).ready(function(){

    $('.acf-map').each(function(){

        // create map
        map = new_map( $(this) );

    });

});

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

The code that renders my markers is as follows:

```<code>    <div class="acf-map">

    <?php while ( $wp_query->have_posts() ) : $wp_query->the_post(); ?>

        <?php
            $location = get_field('google_maps_adres');
            if( !empty($location) ):
        ?>

        <div class="marker" data-lat="<?php echo $location['lat']; ?>" data-lng="<?php echo $location['lng']; ?>">
            <h4 class="marker__title"><?php the_title(); ?></h4>
            <div class="marker__address">
                <?php $contact_address = get_field('google_maps_adres');$address = explode( "," , $contact_address['address']); ?>
                <div class="marker__address-street"><?php echo $address[0].', ';?></div>
                <div class="marker__address-city"><?php echo $address[1];?></div>
            </div>
            <a class="marker__link" href="<?php the_permalink();?>">Meer informatie</a>
        </div>

        <?php endif; ?>

    <?php endwhile;?>

    <?php wp_reset_postdata(); ?>

   </div>
</code>```

答:
I could help with this but maybe it's already answered here. Take a look and try the solution proposed there. If that doesn't work for you let me know and we can work it together ;)

EDIT:

Ok, let´s try to do this then. First of all you need to distinguish each marker, with a class or an ID. Let's do it with classes since we are using the categories and each marker can belong to several categories.

Change your code as follows:

```<code><?php while ( $wp_query->have_posts() ) : $wp_query->the_post(); ?>

<?php $cats = get_the_category(); //this gives me the categories of the post (marker) ?>
<?php $catsString = implode(", ",$cats); // this gives me the categories as a String separated with ", " ?>

    <?php
        $location = get_field('google_maps_adres');
        if( !empty($location) ):
    ?>

    <div class="marker <?php echo $catsString; ?>" data-lat="<?php echo $location['lat']; ?>" data-lng="<?php echo $location['lng']; ?>">
        <h4 class="marker__title"><?php the_title(); ?></h4>
        <div class="marker__address">
            <?php $contact_address = get_field('google_maps_adres');$address = explode( "," , $contact_address['address']); ?>
            <div class="marker__address-street"><?php echo $address[0].', ';?></div>
            <div class="marker__address-city"><?php echo $address[1];?></div>
        </div>
        <a class="marker__link" href="<?php the_permalink();?>">Meer informatie</a>
    </div>

    <?php endif; ?>

<?php endwhile;?>
</code>```

All I've done is for each marker get the categories and used them as classes for the main marker container.

Now you have all your markers with their classes set. That's good. The next step is to use some input to control the visibility of those markers. Let's use a checkbox for example.

For each category you should have a checkbox:

```<code><?php $categories = get_categories();
      foreach( $categories as $category ) {
          echo '<label><input class="markerToggle" type="checkbox" id="'. $category->name .'">'. $category->name .'</label>';
      }
?>
</code>```

Then you would need some simple Javascript to hide/show each marker

```<code>$('.markerToggle').change(function() {
   if($(this).is(":checked")) {
      //'checked' event code
      $('.marker.' + this.id).show();
      return;
   }
   $('.marker.' + this.id).hide();
   //'unchecked' event code
});
</code>```

Body:
I'm building a website with a page that shows all locations (Custom Post Type) on a Google map. I use ACF (Advanced Custom Fields) to add the map location to the specific location. Furthermore I give each location a category (Parking, Hotel, ect.).

At this point all locations are show on the map correctly. But I'm trying to find a way to toggle these locations based on their category. So initially I want to hide all markers on the map and toggle their visibility based on a click (anchor or checkbox, doesn't matter).

I did see some answers that looked promising, but I can't figure this out with the code provided by ACF. I hope someone can help me with this. And can tell me where to add some extra code to setvisibility and toggle this based on a category select.

The code provide by ACF is shown below:

The code that renders my markers is as follows:

    <?php while ( $wp_query->have_posts() ) : $wp_query->the_post(); ?>

        <?php
            $location = get_field('google_maps_adres');
            if( !empty($location) ):
        ?>

        <div class="marker" data-lat="<?php echo $location['lat']; ?>" data-lng="<?php echo $location['lng']; ?>">

<?php the_title(); ?>

                <?php $contact_address = get_field('google_maps_adres');$address = explode( "," , $contact_address['address']); ?>

<?php echo $address[0].', ';?>

<?php echo $address[1];?>

            <a class="marker__link" href="<?php the_permalink();?>">Meer informatie

        <?php endif; ?>

    <?php endwhile;?>

    <?php wp_reset_postdata(); ?>

Body:
I could help with this but maybe it's already answered here. Take a look and try the solution proposed there. If that doesn't work for you let me know and we can work it together ;)

EDIT:

Ok, let´s try to do this then. First of all you need to distinguish each marker, with a class or an ID. Let's do it with classes since we are using the categories and each marker can belong to several categories.

Change your code as follows:

<?php while ( $wp_query->have_posts() ) : $wp_query->the_post(); ?>

<?php $cats = get_the_category(); //this gives me the categories of the post (marker) ?>
<?php $catsString = implode(", ",$cats); // this gives me the categories as a String separated with ", " ?>

    <?php
        $location = get_field('google_maps_adres');
        if( !empty($location) ):
    ?>

    <div class="marker <?php echo $catsString; ?>" data-lat="<?php echo $location['lat']; ?>" data-lng="<?php echo $location['lng']; ?>">
        <h4 class="marker__title"><?php the_title(); ?></h4>
        <div class="marker__address">
            <?php $contact_address = get_field('google_maps_adres');$address = explode( "," , $contact_address['address']); ?>
            <div class="marker__address-street"><?php echo $address[0].', ';?></div>
            <div class="marker__address-city"><?php echo $address[1];?></div>
        </div>
        <a class="marker__link" href="<?php the_permalink();?>">Meer informatie</a>
    </div>

    <?php endif; ?>

<?php endwhile;?>

All I've done is for each marker get the categories and used them as classes for the main marker container.

Now you have all your markers with their classes set. That's good. The next step is to use some input to control the visibility of those markers. Let's use a checkbox for example.

For each category you should have a checkbox:

<?php $categories = get_categories();
      foreach( $categories as $category ) {
          echo '<label><input class="markerToggle" type="checkbox" id="'. $category->name .'">'. $category->name .'</label>';
      }
?>

Then you would need some simple Javascript to hide/show each marker

$('.markerToggle').change(function() {
   if($(this).is(":checked")) {
      //'checked' event code
      $('.marker.' + this.id).show();
      return;
   }
   $('.marker.' + this.id).hide();
   //'unchecked' event code
});


问:
CSS Text-overflow Ellipsis Not Displaying Correctly
I have a
 tag to display some information but it should be restricted to 2 lines and if the text is greater then it should show "..." at end. I tried many solutions but i am not able to get exactly what i am looking for. i have tried below css.

```<code>.mw {
   overflow: hidden;
   text-overflow: ellipsis;
   display: -webkit-box;
   -webkit-box-orient: vertical;
   -webkit-line-clamp: 2;
   line-height: 20px;
   max-height: 40px;
   width:100px;
   border:1px solid #ccc;
}
</code>```

but i am getting three different outputs for three different text in
.

TestingTestingTestingTestingTestingTesting

TestingTesting TestingTestingTestingTesting

TestingTesting TestingTesting TestingTesting

答:
Add word-break: break-all;.

.mw {
   overflow: hidden;
   text-overflow: ellipsis;
   display: -webkit-box;
   -webkit-box-orient: vertical;
   -webkit-line-clamp: 2;
   line-height: 20px;
   max-height: 40px;
   width:100px;
   border:1px solid #ccc;
   word-break: break-all;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p class="mw">TestingTestingTestingTestingTestingTesting</p>

<p class="mw">TestingTesting TestingTestingTestingTesting
</p>

<p class="mw">TestingTesting TestingTesting TestingTesting</p></code>```

Body:
I have a
 tag to display some information but it should be restricted to 2 lines and if the text is greater then it should show "..." at end. I tried many solutions but i am not able to get exactly what i am looking for. i have tried below css.

.mw {
   overflow: hidden;
   text-overflow: ellipsis;
   display: -webkit-box;
   -webkit-box-orient: vertical;
   -webkit-line-clamp: 2;
   line-height: 20px;
   max-height: 40px;
   width:100px;
   border:1px solid #ccc;
}

but i am getting three different outputs for three different text in
.

TestingTestingTestingTestingTestingTesting

TestingTesting TestingTestingTestingTesting

TestingTesting TestingTesting TestingTesting

Body:
Add word-break: break-all;.

.mw {
   overflow: hidden;
   text-overflow: ellipsis;
   display: -webkit-box;
   -webkit-box-orient: vertical;
   -webkit-line-clamp: 2;
   line-height: 20px;
   max-height: 40px;
   width:100px;
   border:1px solid #ccc;
   word-break: break-all;
}

<p class="mw">TestingTestingTestingTestingTestingTesting</p>

<p class="mw">TestingTesting TestingTestingTestingTesting
</p>

<p class="mw">TestingTesting TestingTesting TestingTesting</p>


问:
Django : Migration of polymorphic models back to a single base class
Let's suppose I have a polymorphic model and I want to get rid of it.

```<code>class AnswerBase(models.Model):

    question = models.ForeignKey(Question, related_name="answers")
    response = models.ForeignKey(Response, related_name="answers")

class AnswerText(AnswerBase):
    body = models.TextField(blank=True, null=True)

class AnswerInteger(AnswerBase):
    body = models.IntegerField(blank=True, null=True)
</code>```

When I want to get all the answers I can never access "body" or I need to try to get the instance of a sub-class by trial and error.

```<code># Query set of answerBase, no access to body
AnswerBase.objects.all()
question = Question.objects.get(pk=1)
# Query set of answerBase, no access to body (even with django-polymorphic)
question.answers.all()
</code>```

I don't want to use django-polymorphic because of performances, because it does not seem to work for foreignKey relation, and because I don't want my model to be too complicated. So I want this polymorphic architecture to become this simplified one :

```<code>class Answer(models.Model):

    question = models.ForeignKey(Question, related_name="answers")
    response = models.ForeignKey(Response, related_name="answers")
    body = models.TextField(blank=True, null=True)
</code>```

The migrations cannot be created automatically, it would delete all older answers in the database. I've read the Schema Editor documentation but it does not seem there is a buildin to migrate a model to something that already exists. So I want to create my own operation to save the AnswerText and AnswerInteger as an Answer then delete AnswerText and AnswerInteger. I'm hoping I won't have to write SQL directly, but maybe that's the only solution ? My migration file looks like this. I created an Operation called MigrateAnswer :

```<code>from myapp.migrations import MigrateAnswer

class Migration(migrations.Migration):

    operations = [
        migrations.RenameModel("AnswerBase", "Answer"),
        migrations.AddField(
            model_name='answer',
            name='body',
            field=models.TextField(blank=True, null=True),
        ),
        MigrateAnswer("AnswerInteger"),
        MigrateAnswer("AnswerText"),
        migrations.DeleteModel(name='AnswerInteger',),
        migrations.DeleteModel(name='AnswerText',),
    ]
</code>```

So what I want to do in MigrateAnswer is to migrate the value for an old model (AnswerInteger and AnswerText) to the base class (now named Answer, previousely AnswerBase). Here's my operation class :

```<code>from django.db.migrations.operations.base import Operation

class MigrateAnswer(Operation):

    reversible = False

    def __init__(self, model_name):
        self.old_name = model_name

    def database_forwards(self, app_label, schema_editor, from_state,
                          to_state):
        new_model = to_state.apps.get_model(app_label, "Answer")
        old_model = from_state.apps.get_model(app_label, self.old_name)
        for field in old_model._meta.local_fields:
            # loop on "question", "reponse" and "body"
            # schema_editor.alter_field() Alter a field on a single model
            # schema_editor.add_field() + remove_field() Does not permit
            # to migrate the value from the old field to the new one
            pass
</code>```

So my question is : Is it possible to do this wihout using "execute" (ie : without writing SQL). If so what should I do in the for loop of my Operation ?

Thanks in advance !

答:
You could create an empty migration for the app you want to do these modifications and use the migrations.RunPython Class to execute custom python functions.

Inside these functions you can have access to your models

The Django ORM that you can do data manipulation.

Pure python, no raw SQL.

Body:
Let's suppose I have a polymorphic model and I want to get rid of it.

class AnswerBase(models.Model):

    question = models.ForeignKey(Question, related_name="answers")
    response = models.ForeignKey(Response, related_name="answers")

class AnswerText(AnswerBase):
    body = models.TextField(blank=True, null=True)

class AnswerInteger(AnswerBase):
    body = models.IntegerField(blank=True, null=True)

When I want to get all the answers I can never access "body" or I need to try to get the instance of a sub-class by trial and error.

# Query set of answerBase, no access to body
AnswerBase.objects.all()
question = Question.objects.get(pk=1)
# Query set of answerBase, no access to body (even with django-polymorphic)
question.answers.all()

I don't want to use django-polymorphic because of performances, because it does not seem to work for foreignKey relation, and because I don't want my model to be too complicated. So I want this polymorphic architecture to become this simplified one :

class Answer(models.Model):

    question = models.ForeignKey(Question, related_name="answers")
    response = models.ForeignKey(Response, related_name="answers")
    body = models.TextField(blank=True, null=True)

The migrations cannot be created automatically, it would delete all older answers in the database. I've read the Schema Editor documentation but it does not seem there is a buildin to migrate a model to something that already exists. So I want to create my own operation to save the AnswerText and AnswerInteger as an Answer then delete AnswerText and AnswerInteger. I'm hoping I won't have to write SQL directly, but maybe that's the only solution ? My migration file looks like this. I created an Operation called MigrateAnswer :

from myapp.migrations import MigrateAnswer

class Migration(migrations.Migration):

    operations = [
        migrations.RenameModel("AnswerBase", "Answer"),
        migrations.AddField(
            model_name='answer',
            name='body',
            field=models.TextField(blank=True, null=True),
        ),
        MigrateAnswer("AnswerInteger"),
        MigrateAnswer("AnswerText"),
        migrations.DeleteModel(name='AnswerInteger',),
        migrations.DeleteModel(name='AnswerText',),
    ]

So what I want to do in MigrateAnswer is to migrate the value for an old model (AnswerInteger and AnswerText) to the base class (now named Answer, previousely AnswerBase). Here's my operation class :

from django.db.migrations.operations.base import Operation

class MigrateAnswer(Operation):

    reversible = False

    def __init__(self, model_name):
        self.old_name = model_name

    def database_forwards(self, app_label, schema_editor, from_state,
                          to_state):
        new_model = to_state.apps.get_model(app_label, "Answer")
        old_model = from_state.apps.get_model(app_label, self.old_name)
        for field in old_model._meta.local_fields:
            # loop on "question", "reponse" and "body"
            # schema_editor.alter_field() Alter a field on a single model
            # schema_editor.add_field() + remove_field() Does not permit
            # to migrate the value from the old field to the new one
            pass

So my question is : Is it possible to do this wihout using "execute" (ie : without writing SQL). If so what should I do in the for loop of my Operation ?

Thanks in advance !


问:
Using Mercurial when I've done a complete rewrite
This is my repository:

https://bitbucket.org/sergiotapia/sharpdic

Basically, I've rewritten the entire library. It doesn't resemble the original at all. What command can I run to completely erase/neglect the existing code base and replace it with my newer code version?

I've done an hg init on the folder on my local disc (it has the newer code), do I have to delete that before trying to upload?

Thanks.

答:
Just go to revision 0 (hg up null), commit (creates a new branch), and then close the old branch. That's what I would do if not replacing the repo altogether.

I assume that your new files are currently not yet in the repo directory. Make a backup first!

```<code>hg up tip -C
hg commit -m 'Old code branch' --close-branch
hg up null -C
</code>```

You'll now have an empty reporsitory directoy, starting at revision 0. Copy your new files into it (don't copy the .hg folder from the new file directory).

```<code>hg addremove
hg commit -m 'New code branch'
</code>```

That should do the trick. Did I mention to backup the files and repo first? ;-)

Another option is to force a push of the new repo onto the remote repo, but you'll still need to close the old branch after doing this in order to have only one active head. Choose this option if you did commit already to the nbew repo (you only mentionned having done a init, so I assumed no commit yet).

OwnerDisplayName: delete

ContentLicense: CC BY-SA 2.5

Body:
Just go to revision 0 (hg up null), commit (creates a new branch), and then close the old branch. That's what I would do if not replacing the repo altogether.

I assume that your new files are currently not yet in the repo directory. Make a backup first!

hg up tip -C
hg commit -m 'Old code branch' --close-branch
hg up null -C

You'll now have an empty reporsitory directoy, starting at revision 0. Copy your new files into it (don't copy the .hg folder from the new file directory).

hg addremove
hg commit -m 'New code branch'

That should do the trick. Did I mention to backup the files and repo first? ;-)

Another option is to force a push of the new repo onto the remote repo, but you'll still need to close the old branch after doing this in order to have only one active head. Choose this option if you did commit already to the nbew repo (you only mentionned having done a init, so I assumed no commit yet).


问:
Custom post type not displaying in custom wp query loop
I'm trying not to repeat questions that've already been asked but I haven't been able to debug this so far - I'm sure it's a small thing I'm missing!

I have a single-project.php template that I'd like to include a sidebar with all project custom post types as links. I only seem to be getting 'post' post_type, not my custom post_type (project)

Registered custom post type in functions.php

```<code>function custom_post_type() {
$labels = array(
'name'                  => _x( 'Project', 'Post Type General Name', 'text_domain' ),
    'singular_name'         => _x( 'Project', 'Post Type Singular Name', 'text_domain' ),
    'menu_name'             => __( 'Projects', 'text_domain' ),
    'name_admin_bar'        => __( 'Projects', 'text_domain' ),
    'archives'              => __( 'Item Archives', 'text_domain' ),
    'attributes'            => __( 'Item Attributes', 'text_domain' ),
    'parent_item_colon'     => __( 'Parent Item:', 'text_domain' ),
    'all_items'             => __( 'All Projects', 'text_domain' ),
    'add_new_item'          => __( 'Add New Item', 'text_domain' ),
    'add_new'               => __( 'Add New', 'text_domain' ),
    'new_item'              => __( 'New Item', 'text_domain' ),
    'edit_item'             => __( 'Edit Item', 'text_domain' ),
    'update_item'           => __( 'Update Item', 'text_domain' ),
    'view_item'             => __( 'View Item', 'text_domain' ),
    'view_items'            => __( 'View Items', 'text_domain' ),
    'search_items'          => __( 'Search Item', 'text_domain' ),
    'not_found'             => __( 'Not found', 'text_domain' ),
    'not_found_in_trash'    => __( 'Not found in Trash', 'text_domain' ),
    'featured_image'        => __( 'Featured Image', 'text_domain' ),
    'set_featured_image'    => __( 'Set featured image', 'text_domain' ),
    'remove_featured_image' => __( 'Remove featured image', 'text_domain' ),
    'use_featured_image'    => __( 'Use as featured image', 'text_domain' ),
    'insert_into_item'      => __( 'Insert into item', 'text_domain' ),
    'uploaded_to_this_item' => __( 'Uploaded to this item', 'text_domain' ),
    'items_list'            => __( 'Items list', 'text_domain' ),
    'items_list_navigation' => __( 'Items list navigation', 'text_domain' ),
    'filter_items_list'     => __( 'Filter items list', 'text_domain' ),
);
$args = array(
    'label'                 => __( 'Project', 'text_domain' ),
    'description'           => __( 'Spaceworks projects', 'text_domain' ),
    'labels'                => $labels,
    'supports'              => array( ),
    'hierarchical'          => false,
    'public'                => true,
    'show_ui'               => true,
    'show_in_menu'          => true,
    'menu_position'         => 5,
    'show_in_admin_bar'     => true,
    'show_in_nav_menus'     => true,
    'can_export'            => true,
    'has_archive'           => true,
    'exclude_from_search'   => false,
    'publicly_queryable'    => true,
    'capability_type'       => 'post',
);
register_post_type( 'project', $args );

}
add_action( 'init', 'custom_post_type', 0 );
</code>```

Register custom taxonomy in functions.php

```<code>function my_taxonomies_project() {
$labels = array(
'name'              => _x( 'Project Categories', 'taxonomy general name' ),
'singular_name'     => _x( 'Project Category', 'taxonomy singular name' ),
'search_items'      => __( 'Search Project Categories' ),
'all_items'         => __( 'All Project Categories' ),
'parent_item'       => __( 'Parent Project Category' ),
'parent_item_colon' => __( 'Parent Project Category:' ),
'edit_item'         => __( 'Edit Project Category' ),
'update_item'       => __( 'Update Project Category' ),
'add_new_item'      => __( 'Add New Project Category' ),
'new_item_name'     => __( 'New Project Category' ),
'menu_name'         => __( 'Project Categories' ),
);
$args = array(
'labels' => $labels,
'hierarchical' => true,
);
register_taxonomy( 'project_category', 'project', $args );
}
add_action( 'init', 'my_taxonomies_project', 0 );`
</code>```

Single project template: single-project.php

```<code><?php
get_header();

while ( have_posts() ) : the_post(); ?>

<div class="projects">
<?php the_title( '<h1 class="entry-title">', '</h1>' ); ?>
<?php the_content(); ?>
</div>

<?php
endwhile;
wp_reset_query();
?>

<div class="col-12 col-lg-3 col-xl-3 hidden-lg-up allProjects">
#project loop for mobile

<?php
$tax_query_args = array(
    array(
        'post_type'         => array('post', 'project'),
     ),
);

$taxQuery = new WP_Query( $tax_query_args );

if ($taxQuery->have_posts())
while ($taxQuery->have_posts() ) : $taxQuery->the_post();
?>

<div class="projectCard">
<a href="<?php echo get_permalink(); ?>">
<p><?php the_title() ?></p>
</a>
</div>

<?php endwhile; wp_reset_query();

get_footer();
?>
</code>```

Can anyone spot an issue? This has been bugging me for a few days!
All the best

答:
Display project by using project category wise</p>

```<code><?php
$project_args=array(
    'type'                     => 'project',
    'child_of'                 => 0,
    'parent'                   => 0,
    'orderby'                  => 'name',
    'order'                    => 'ASC',
    'hide_empty'               => 0,
    'hierarchical'             => 1,
    'exclude'                  => '',
    'include'                  => '',
    'number'                   => '',
    'taxonomy'                 => 'project_category',
    'pad_counts'               => false
);
$project_my_query = null;
$project_my_query = new WP_Query($project_args);

if( $project_my_query->have_posts() )
{
        while ($project_my_query->have_posts()) : $project_my_query->the_post();

        ?>
        <div class="projectCard">
        <a href="<?php echo get_the_permalink($post->ID); ?>"><p><?php the_title() ?></p></a>
        </div
        <?php
       endwhile;
}
wp_reset_query($project_my_query);
?>
</code>```

Body:
I'm trying not to repeat questions that've already been asked but I haven't been able to debug this so far - I'm sure it's a small thing I'm missing!

I have a single-project.php template that I'd like to include a sidebar with all project custom post types as links. I only seem to be getting 'post' post_type, not my custom post_type (project)

Registered custom post type in functions.php

function custom_post_type() {
$labels = array(
'name'                  => _x( 'Project', 'Post Type General Name', 'text_domain' ),
    'singular_name'         => _x( 'Project', 'Post Type Singular Name', 'text_domain' ),
    'menu_name'             => __( 'Projects', 'text_domain' ),
    'name_admin_bar'        => __( 'Projects', 'text_domain' ),
    'archives'              => __( 'Item Archives', 'text_domain' ),
    'attributes'            => __( 'Item Attributes', 'text_domain' ),
    'parent_item_colon'     => __( 'Parent Item:', 'text_domain' ),
    'all_items'             => __( 'All Projects', 'text_domain' ),
    'add_new_item'          => __( 'Add New Item', 'text_domain' ),
    'add_new'               => __( 'Add New', 'text_domain' ),
    'new_item'              => __( 'New Item', 'text_domain' ),
    'edit_item'             => __( 'Edit Item', 'text_domain' ),
    'update_item'           => __( 'Update Item', 'text_domain' ),
    'view_item'             => __( 'View Item', 'text_domain' ),
    'view_items'            => __( 'View Items', 'text_domain' ),
    'search_items'          => __( 'Search Item', 'text_domain' ),
    'not_found'             => __( 'Not found', 'text_domain' ),
    'not_found_in_trash'    => __( 'Not found in Trash', 'text_domain' ),
    'featured_image'        => __( 'Featured Image', 'text_domain' ),
    'set_featured_image'    => __( 'Set featured image', 'text_domain' ),
    'remove_featured_image' => __( 'Remove featured image', 'text_domain' ),
    'use_featured_image'    => __( 'Use as featured image', 'text_domain' ),
    'insert_into_item'      => __( 'Insert into item', 'text_domain' ),
    'uploaded_to_this_item' => __( 'Uploaded to this item', 'text_domain' ),
    'items_list'            => __( 'Items list', 'text_domain' ),
    'items_list_navigation' => __( 'Items list navigation', 'text_domain' ),
    'filter_items_list'     => __( 'Filter items list', 'text_domain' ),
);
$args = array(
    'label'                 => __( 'Project', 'text_domain' ),
    'description'           => __( 'Spaceworks projects', 'text_domain' ),
    'labels'                => $labels,
    'supports'              => array( ),
    'hierarchical'          => false,
    'public'                => true,
    'show_ui'               => true,
    'show_in_menu'          => true,
    'menu_position'         => 5,
    'show_in_admin_bar'     => true,
    'show_in_nav_menus'     => true,
    'can_export'            => true,
    'has_archive'           => true,
    'exclude_from_search'   => false,
    'publicly_queryable'    => true,
    'capability_type'       => 'post',
);
register_post_type( 'project', $args );

}
add_action( 'init', 'custom_post_type', 0 );

Register custom taxonomy in functions.php

function my_taxonomies_project() {
$labels = array(
'name'              => _x( 'Project Categories', 'taxonomy general name' ),
'singular_name'     => _x( 'Project Category', 'taxonomy singular name' ),
'search_items'      => __( 'Search Project Categories' ),
'all_items'         => __( 'All Project Categories' ),
'parent_item'       => __( 'Parent Project Category' ),
'parent_item_colon' => __( 'Parent Project Category:' ),
'edit_item'         => __( 'Edit Project Category' ),
'update_item'       => __( 'Update Project Category' ),
'add_new_item'      => __( 'Add New Project Category' ),
'new_item_name'     => __( 'New Project Category' ),
'menu_name'         => __( 'Project Categories' ),
);
$args = array(
'labels' => $labels,
'hierarchical' => true,
);
register_taxonomy( 'project_category', 'project', $args );
}
add_action( 'init', 'my_taxonomies_project', 0 );`

Single project template: single-project.php

<?php
get_header();

while ( have_posts() ) : the_post(); ?>

<?php the_title( '
', '
' ); ?>
<?php the_content(); ?>

<?php
endwhile;
wp_reset_query();
?>

#project loop for mobile

<?php
$tax_query_args = array(
    array(
        'post_type'         => array('post', 'project'),
     ),
);

$taxQuery = new WP_Query( $tax_query_args );

if ($taxQuery->have_posts())
while ($taxQuery->have_posts() ) : $taxQuery->the_post();
?>

<a href="<?php echo get_permalink(); ?>">

<?php the_title() ?>

<?php endwhile; wp_reset_query();

get_footer();
?>

Can anyone spot an issue? This has been bugging me for a few days!
All the best

Body:
Display project by using project category wise

<?php
$project_args=array(
    'type'                     => 'project',
    'child_of'                 => 0,
    'parent'                   => 0,
    'orderby'                  => 'name',
    'order'                    => 'ASC',
    'hide_empty'               => 0,
    'hierarchical'             => 1,
    'exclude'                  => '',
    'include'                  => '',
    'number'                   => '',
    'taxonomy'                 => 'project_category',
    'pad_counts'               => false
);
$project_my_query = null;
$project_my_query = new WP_Query($project_args);

if( $project_my_query->have_posts() )
{
        while ($project_my_query->have_posts()) : $project_my_query->the_post();

        ?>
        <div class="projectCard">
        <a href="<?php echo get_the_permalink($post->ID); ?>"><p><?php the_title() ?></p></a>
        </div
        <?php
       endwhile;
}
wp_reset_query($project_my_query);
?>


问:
How can I create a BehaviorSubject that subscribes to an observable?
I have a function which should return a BehaviorSubject. The subject is meant to return the most current version of a Profile

(user)Profile is just a POJO that contains references to three members:

- a User,

- that User's MeasurementList,

- and a Deadline.

Two of these properties is obtained via a retrofit call, and one of them is already held in a class variable.

Whenever the observable emits a new measurement list or deadline, the BehaviorSubject should emit a new updated Profile.

Here is a (hopefully helpful) diagram of what should be happening

This is what I have so far

```<code> public BehaviorSubject<Profile> observeProfile() {

        if (profileBS == null) {

            profileBS = BehaviorSubject.create();

            Observable o = Observable.combineLatest(
                    Observable.just(userAccount),
                    observeMeasurements(),
                    observeDeadline(),
                    Profile::new
            );

            profileBS.subscribeTo(o); //subscribeTo does not exist, but this is what I am trying to figure out how to do.

        }
        return profileBS;
    }
</code>```

Can anyone help me to create this BehaviorSubject properly?

Thanks.

答:
I think I'm facing the same problem with you. I want to tell some history before I put my answer.
So I think lots of people saw the talk that JakeWharton give at Devoxx: The State of Managing State with RxJava

So He came up with an Architecture which based on some transformers. But the thing is that even those Transformer instance survive outside of your ViewObservables. They still create new Observable everytime your ViewObservable using them. It's because of the concept of operator.

So a common solution for this is that using subject as a gateway as you did in your question. But the new problem is you subscribe your source too early.

The subscribe action should be done in subscribeActual() which will triggered by the subscribe() method by your downstream. But you subscribe to your upstream in the middle. You lose your events.
I was struggle a lot by fixing this problem but never find a solution.

But recently thanks to Davik's answer: RxJava - .doAfterSubscribe()?
I came up with something like this:

```<code>public BehaviorSubject<Profile> observeProfile() {
    public Observable resultObservable;
    if (profileBS == null) {

        profileBS = BehaviorSubject.create();
        //this source observable should save as a field as well
        o = Observable.combineLatest(
                Observable.just(userAccount),
                observeMeasurements(),
                observeDeadline(),
                Profile::new
        );
        //return this observable instead of your subject
        resultObservable = profileBS.mergeWith(
            Observable.empty()
                      .doOnComplete(() -> {
                          o.subscribe(profileBS);
                      }))
    } return resultObservable;
}
</code>```

The trick is that. You using this approche to make a operator like doAfterSubscribe. So only the downstream already subscribe to your subject. your subject will subscribe to your original upstream source.

Hope this can help. And sorry for my bad English.

Body:
I have a function which should return a BehaviorSubject. The subject is meant to return the most current version of a Profile

(user)Profile is just a POJO that contains references to three members:

- a User,

- that User's MeasurementList,

- and a Deadline.

Two of these properties is obtained via a retrofit call, and one of them is already held in a class variable.

Whenever the observable emits a new measurement list or deadline, the BehaviorSubject should emit a new updated Profile.

Here is a (hopefully helpful) diagram of what should be happening

This is what I have so far

 public BehaviorSubject<Profile> observeProfile() {

        if (profileBS == null) {

            profileBS = BehaviorSubject.create();

            Observable o = Observable.combineLatest(
                    Observable.just(userAccount),
                    observeMeasurements(),
                    observeDeadline(),
                    Profile::new
            );

            profileBS.subscribeTo(o); //subscribeTo does not exist, but this is what I am trying to figure out how to do.

        }
        return profileBS;
    }

Can anyone help me to create this BehaviorSubject properly?

Thanks.

Body:
I think I'm facing the same problem with you. I want to tell some history before I put my answer.
So I think lots of people saw the talk that JakeWharton give at Devoxx: The State of Managing State with RxJava

So He came up with an Architecture which based on some transformers. But the thing is that even those Transformer instance survive outside of your ViewObservables. They still create new Observable everytime your ViewObservable using them. It's because of the concept of operator.

So a common solution for this is that using subject as a gateway as you did in your question. But the new problem is you subscribe your source too early.

The subscribe action should be done in subscribeActual() which will triggered by the subscribe() method by your downstream. But you subscribe to your upstream in the middle. You lose your events.
I was struggle a lot by fixing this problem but never find a solution.

But recently thanks to Davik's answer: RxJava - .doAfterSubscribe()?
I came up with something like this:

public BehaviorSubject<Profile> observeProfile() {
    public Observable resultObservable;
    if (profileBS == null) {

        profileBS = BehaviorSubject.create();
        //this source observable should save as a field as well
        o = Observable.combineLatest(
                Observable.just(userAccount),
                observeMeasurements(),
                observeDeadline(),
                Profile::new
        );
        //return this observable instead of your subject
        resultObservable = profileBS.mergeWith(
            Observable.empty()
                      .doOnComplete(() -> {
                          o.subscribe(profileBS);
                      }))
    } return resultObservable;
}

The trick is that. You using this approche to make a operator like doAfterSubscribe. So only the downstream already subscribe to your subject. your subject will subscribe to your original upstream source.

Hope this can help. And sorry for my bad English.


问:
Vue.js image v-for bind
Any way to use v-for to get an array of images loaded?

Have tried with the following code:

Im pretty new to Vue, I still have a lot to learn. So any help will be greatly appreciated. Thanks

<template>

         <app-header></app-header>

About

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Est, aperiam doloremque possimus nemo incidunt, consequatur quidem facere in ipsam ratione quod? Provident laborum magnam accusantium sequi optio error sunt, sit.

        <app-footer></app-footer>

</template>

```

答:
Use image object element, not images object array here in src and alt.

```

ContentLicense: CC BY-SA 4.0

Title: Vue.js image v-for bind

Body:
Use image object element, not images object array here in src and alt.

<img v-for="image in images" :src="image.url" :alt="image.alt" />


问:
ES 6 import Vue
I created my service file like this:

```<code>import Vue from 'vue'

var service = {
    counter : 1,
    loadProducts : function(){
        return Vue.http.get('http://www.json-generator.com/api/json/get/cqLJAlYsPm?indent=2');
    }
}

export default service
</code>```

and I have imported it in my single component

```<code><!-- src/components/ProductList.vue -->
<template>
    <table class="table table-hover product-table">
        <thead>
            <tr>
                <th>Name</th>
                <th>Description</th>
                <th>Price</th>
            </tr>
        </thead>
        <tbody>
            <tr v-for="product in products" track-by="id">
                <td>{{product.about}}</td>
                <td>{{product.address}}</td>
                <td>{{product.age}}</td>
            </tr>
        </tbody>
    </table>
</template>

<script>
    import service from './my-service.js'

export default {
    created: function(){
        service.counter++;
        console.log(service);
        console.log('created');

        service.loadProducts().then(response => {
            this.products = response.data;
        });

    },
  data () {
    return {
        products: []
    }
  }
}
</script>
</code>```

Is this proper method to write API calls? If I import Vue in service file:

```<code>import Vue from 'vue'
</code>```

will this be included in my js file again? So everytime I write import Vue the my JS file would keep bloating?

答:
If I import Vue in service file [...] will this be included in my js file again? So everytime I write import Vue the my JS file would keep bloating?

If you are not code splitting, then no, the vue module will not be included multiple times in the same chunk, nor will that module be initialized every time it is imported. If you are code splitting, then you need to use the CommonsChunkPlugin to prevent duplication of the same module across multiple chunks (if that concerns you).

Title: ES 6 import Vue

Body:
I created my service file like this:

import Vue from 'vue'

var service = {
    counter : 1,
    loadProducts : function(){
        return Vue.http.get('http://www.json-generator.com/api/json/get/cqLJAlYsPm?indent=2');
    }
}

export default service

and I have imported it in my single component

<template>

                Name
                Description
                Price

                {{product.about}}
                {{product.address}}
                {{product.age}}

</template>

Is this proper method to write API calls? If I import Vue in service file:

import Vue from 'vue'

will this be included in my js file again? So everytime I write import Vue the my JS file would keep bloating?


问:
Getting error on building the project Embed Interop types Property to false
On buliding my project it says Embed Interop types Property to false.

I am using VS:2010

And MS Office 2013.

I am not able to make Property false as i am not able to find it.

Please tell me guys what needs to be done

答: Try by loading the excel interop by referencing it from Programfiles folder rather than from GAC</p>


问:
Converting to JSTL (Specificlly on calling methods)
I'm in the process of going the full JSTL way, and I've got an issue with the following scriplet, I have already transformed the variable displaying and conditions to the expression language (EL) but I'm not so sure of how to do it with method calling : here's my JSP code its positioned before the html markup:

            UserDTO user = (UserDTO) session.getAttribute("user");

```<code>        OrderDAO lnkOrder = new OrderDAO();
        OrderDTO order = new OrderDTO();

        CoverDAO lnkCover = new CoverDAO();
        CoverDTO cover = new CoverDTO();

        UpgradesDAO lnkUpgrades = new UpgradesDAO();
        UpgradesDTO upgrades = new UpgradesDTO();

        OrderAccessorieDAO lnkOrderAcc = new OrderAccessorieDAO();
        List<OrderAccessorieDTO> orderAccessories = new ArrayList<OrderAccessorieDTO>();

        GroupColorsDAO lnkColors = new GroupColorsDAO();
        List<ColorDTO> ColorList = new ArrayList<ColorDTO>();
        ColorList = lnkColors.getGroupColors(user.getGroup());

        AccessoryDAO lnkAcc = new AccessoryDAO();
        List<AccessoryDTO> groupAccessories = new ArrayList<AccessoryDTO>();
        groupAccessories = lnkAcc.getGroupAccessories(user.getGroup());

        ChangesDAO lnkChanges = new ChangesDAO();
        List<ChangeDTO> orderChanges = new ArrayList<ChangeDTO>();

        String CurrentOrder = request.getParameter("CurrentOrder");

        if (lnkOrder.exists(CurrentOrder)) {
            order = lnkOrder.find(CurrentOrder);
            cover = lnkCover.find(order.getReferenceNumber());
            upgrades = lnkUpgrades.find(order.getReferenceNumber());
            orderAccessories = lnkOrderAcc.getOrderAccessories(order.getReferenceNumber());
            orderChanges = lnkChanges.getOrderChanges(order.getReferenceNumber());
        }
</code>```

As yo can see it's pretty much DAO and DTO objects, I know that it can be done using static methods and making custom taglibs but that would mean writing a code for each method call, any other approach?, suggestions accepted. A brief description of the VIEW(HTML markup) it displays the details of a given order, the order name is extracted from a get request.

Also I have another small question, suppose I port everything to JSTL, would I have to import the corresponding myDTO and myDAO packages to access its getters and setters for each DTO?

Regards Tristian.

答:
The only work around (dirty) that I know is to expose the methods as a fake map, that is have a method that has a sig like "Object getSomething(Object o)". In this way you can pass an argument, and it gets around the imposed rules. Fugly but it works.

Agree with axtavt though

Body:
I'm in the process of going the full JSTL way, and I've got an issue with the following scriplet, I have already transformed the variable displaying and conditions to the expression language (EL) but I'm not so sure of how to do it with method calling : here's my JSP code its positioned before the html markup:

            UserDTO user = (UserDTO) session.getAttribute("user");

        OrderDAO lnkOrder = new OrderDAO();
        OrderDTO order = new OrderDTO();

        CoverDAO lnkCover = new CoverDAO();
        CoverDTO cover = new CoverDTO();

        UpgradesDAO lnkUpgrades = new UpgradesDAO();
        UpgradesDTO upgrades = new UpgradesDTO();

        OrderAccessorieDAO lnkOrderAcc = new OrderAccessorieDAO();
        List<OrderAccessorieDTO> orderAccessories = new ArrayList<OrderAccessorieDTO>();

        GroupColorsDAO lnkColors = new GroupColorsDAO();
        List<ColorDTO> ColorList = new ArrayList<ColorDTO>();
        ColorList = lnkColors.getGroupColors(user.getGroup());

        AccessoryDAO lnkAcc = new AccessoryDAO();
        List<AccessoryDTO> groupAccessories = new ArrayList<AccessoryDTO>();
        groupAccessories = lnkAcc.getGroupAccessories(user.getGroup());

        ChangesDAO lnkChanges = new ChangesDAO();
        List<ChangeDTO> orderChanges = new ArrayList<ChangeDTO>();

        String CurrentOrder = request.getParameter("CurrentOrder");

        if (lnkOrder.exists(CurrentOrder)) {
            order = lnkOrder.find(CurrentOrder);
            cover = lnkCover.find(order.getReferenceNumber());
            upgrades = lnkUpgrades.find(order.getReferenceNumber());
            orderAccessories = lnkOrderAcc.getOrderAccessories(order.getReferenceNumber());
            orderChanges = lnkChanges.getOrderChanges(order.getReferenceNumber());
        }

As yo can see it's pretty much DAO and DTO objects, I know that it can be done using static methods and making custom taglibs but that would mean writing a code for each method call, any other approach?, suggestions accepted. A brief description of the VIEW(HTML markup) it displays the details of a given order, the order name is extracted from a get request.

Also I have another small question, suppose I port everything to JSTL, would I have to import the corresponding myDTO and myDAO packages to access its getters and setters for each DTO?

Regards Tristian.


问:
Plotting age group with gender with ggplot2 in R
I have the following dataset of credit history.

How to plot the age group (applied for loan) for each gender using ggplot2.

Thanks in advance.

答:
```<code>library(ggplot)
german_credit$Sex <- as.factor(german_credit$Sex)
ggplot(german_credit, aes(x = Age)) + geom_histogram() + facet_wrap(~Sex)
</code>```


问:
jQuery alert when row with specific attribute is clicked
I have html table like below:

```<code><table id='messagelist'>

  <tr id="rcmrowMTM" class="message selected" aria-selected="true">
    <td class="threads"><span class="threads"></span></td>
    <td class="subject" tabindex="0"><span class="fromto skip-on-drag"><span class="adr"><span title="test@example.com" class="rcmContactAddress">test@example.com</span></span>
      </span><span class="date skip-on-drag">Today 08:27</span><span class="subject"><span id="msgicnrcmrowMTM" class="msgicon status" title=""></span><a href="./?_task=mail&_mbox=INBOX&_uid=13&_action=show" onclick="return rcube_event.keyboard_only(event)"
      onmouseover="rcube_webmail.long_subject_title(this,1)" tabindex="-1"><span>test</span></a></span>
    </td>
    <td class="flags"><span class="flag"><span id="flagicnrcmrowMTM" class="unflagged" title="Not Flagged"></span></span><span class="attachment"><span class="attachment" title="With attachment"></span></span>
    </td>
  </tr>

  <tr id="rcmrowNw" class="message">
    <td class="threads"><span class="threads"></span></td>
    <td class="subject"><span class="fromto skip-on-drag"><span class="adr"><span title="test@example.com" class="rcmContactAddress">test@example.com</span></span>
      </span><span class="date skip-on-drag">Sun 12:22</span><span class="subject"><span id="msgicnrcmrowNw" class="msgicon status" title=""></span><a href="./?_task=mail&_mbox=INBOX&_uid=7&_action=show" onclick="return rcube_event.keyboard_only(event)"
      onmouseover="rcube_webmail.long_subject_title(this,1)" tabindex="-1"><span>test</span></a></span>
    </td>
    <td class="flags"><span class="flag"><span id="flagicnrcmrowNw" class="unflagged" title="Not Flagged"></span></span><span class="attachment"> </span></td>
  </tr>

</table>
</code>```

Every time user click a row new class "selected" is added in tr.

What I want is to show alert if user click on a row and row has title="With attachment" like in last td of first row

Here is my code that I tried but it's not working.

```<code>$('#messagelist tr.selected').on('click', function() {
  if ($(this).find("span[title|='With attachment']")) {
    alert('with attachment');
  }
});
</code>```

any help is appreciated. Thanks in advance.

JSFiddle

答:
Checked for last TD and then it will check for title="With attachment" in span tag.

Also in your code messagelist is class instead of ID so you should use dot(.) in code.

```<code>$('.messagelist tr.selected').on('click', function () {
    if ($(this).find('td:last').find("span[title|='With attachment']")) {
        alert('with attachment');
    }
});
</code>```

Body:
I have html table like below:

    test@example.com
      Today 08:27test

    test@example.com
      Sun 12:22test

Every time user click a row new class "selected" is added in tr.

What I want is to show alert if user click on a row and row has title="With attachment" like in last td of first row

Here is my code that I tried but it's not working.

$('#messagelist tr.selected').on('click', function() {
  if ($(this).find("span[title|='With attachment']")) {
    alert('with attachment');
  }
});

any help is appreciated. Thanks in advance.

JSFiddle

Body:
Checked for last TD and then it will check for title="With attachment" in span tag.

Also in your code messagelist is class instead of ID so you should use dot(.) in code.

$('.messagelist tr.selected').on('click', function () {
    if ($(this).find('td:last').find("span[title|='With attachment']")) {
        alert('with attachment');
    }
});


问:
ListView grid in React Native
I'm building a simple app in React Native that fetches listings from a remote JSON source and displays them on screen.

So far, using the excellent example here, I've managed to get the results to display using the ListView components in rows (i.e. 1 result per row, see screenshot). I need the results to display in a grid, i.e. 3 to 6 items per row, depending on the screen size and orientation.

What is the best way to get these results into a grid? Can I use ListView for this, or is that only for one-per-row results? I've tried playing around with flexbox styles but, since React doesn't seem to accept % values and ListView doesn't accept styles, I haven't yet had any success.

答: use FlatList instead of Listview in react-native. it has more value added feature and better performance. checkout the example here</p>

Title: ListView grid in React Native


问:
what does constant property means in swift?
I am learning SWIFT. I don't understand one sentence while reading book. What does the sentence below means?: </p>

<blockquote>
  <p>“Add a constant property called elementList to ViewController.swift
  and initialize it with the following element names: let elementList =
  ["Carbon", "Gold", "Chlorine", "Sodium"]”
  does it mean create new class or I have to create struct? </p>
</blockquote>

答: In you situation, you are creating an array of string and store it into a constant variable called elementList. When you use let to create this variable, it means that the value cannot be changed afterwords. So you cannot add or remove element after declaring this array in this way, etc

Body:
I am learning SWIFT. I don't understand one sentence while reading book. What does the sentence below means?:

“Add a constant property called elementList to ViewController.swift
  and initialize it with the following element names: let elementList =
  ["Carbon", "Gold", "Chlorine", "Sodium"]”
  does it mean create new class or I have to create struct?


问:
MYSQL Error 1406 "Data to long" in blob field
I obtain this error when I try to insert a text that is approx. 85K long in a blob field.

I tried also to change the field to longblob ant to turn off strict mode, but with no result.

Thanks for your answer

答: try change the column type to text in de BBDD</p>


问:
Font weight turns lighter on Mac/Safari
On my last website, the text is perfect naturally on chrome and firefox without touching font-smoothing or anything else.

But on Mac / Safari 7 the text appears well then turns immediately thinner (too much thinner / not nice to read).

After doing some research [cf http://www.usabilitypost.com/2012/11/05/stop-fixing-font-smoothing/]

and some tests playing with

```<code>-webkit-font-smoothing
</code>```

It looks like Safari display the text first with :

```<code>-webkit-font-smoothing: subpixel-antialiased;
</code>```

Then just after you got the flickering effect, when it is turning font to :

```<code>-webkit-font-smoothing: antialiased;
</code>```

So it seems to me that I had no choice but to force

```<code>-webkit-font-smoothing: subpixel-antialiased;
</code>```

to make my website consistent on all browsers.

I am using font-face Avenir Std Roman.

Some explanations to that Safari problem ?
Any better solutions ?
Could my font be part of the problem ?

Thanks.

答:
Just use this:
link href="https://fonts.googleapis.com/css?family=Lato:100,100i,300,300i,400,400i,700,700i,900,900i" rel="stylesheet"

Instead of this:
link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet"

problem solved for me this way!

Title: Font weight turns lighter on Mac/Safari

Body:
On my last website, the text is perfect naturally on chrome and firefox without touching font-smoothing or anything else.

But on Mac / Safari 7 the text appears well then turns immediately thinner (too much thinner / not nice to read).

After doing some research [cf http://www.usabilitypost.com/2012/11/05/stop-fixing-font-smoothing/]

and some tests playing with

-webkit-font-smoothing

It looks like Safari display the text first with :

-webkit-font-smoothing: subpixel-antialiased;

Then just after you got the flickering effect, when it is turning font to :

-webkit-font-smoothing: antialiased;

So it seems to me that I had no choice but to force

-webkit-font-smoothing: subpixel-antialiased;

to make my website consistent on all browsers.

I am using font-face Avenir Std Roman.

Some explanations to that Safari problem ?
Any better solutions ?
Could my font be part of the problem ?

Thanks.


问:
io.Reader and Line Break issue involving a CSV file
I have an application which deals with CSV's being delivered via RabbitMQ from many different upstream applications - typically 5000-15,000 rows per file. Most of the time it works great. However a couple of these upstream applications are old (12-15 years) and the people who wrote them are long gone.

I'm unable to read CSV files from these older aplications due to the line breaks. I'm finding this a bit weird as the line breaks see to map to UTF-8 Carriage Returns (http://www.fileformat.info/info/unicode/char/000d/index.htm). Typically the app reads in only the headers from those older files and nothing else.

If I open one of these files in a text editor and save as utf-8 encoding  overwriting the exiting file then it works with no issues at all.

Things I've tried I expected to work:

-Using a Reader:

```<code>    ba := make([]byte, 262144000)
    if _, err := file.Read(ba); err != nil {
        return nil, err
    }
    ba = bytes.Trim(ba, "\x00")
    bb := bytes.NewBuffer(ba)
    reader := csv.NewReader(bb)
    records, err := reader.ReadAll()
    if err != nil {
        return nil, err
    }
</code>```

-Using the Scanner to read line by line (get a bufio.Scanner: token too long)

```<code>    scanner := bufio.NewScanner(file)
    var bb bytes.Buffer
    for scanner.Scan() {
        bb.WriteString(fmt.Sprintf("%s\n", scanner.Text()))
    }

    // check for errors
    if err = scanner.Err(); err != nil {
        return nil, err
    }

reader := csv.NewReader(&bb)
records, err := reader.ReadAll()
if err != nil {
    return nil, err
}
</code>```

Things I tried I expected not to work (and didn't):

Writing file contents to a new file (.txt) and reading the file back in (including running dos2unix against the created txt file)

Reading file into a standard string (hoping Go's UTF-8 encoding would magically kick in which of course it doesn't)

Reading file to Rune slice, then transforming to a string via byte slice

I'm aware of the https://godoc.org/golang.org/x/text/transform package but not too sure of a viable approach - it looks like the src encoding needs to be known to transform.

Am I stupidly overlooking something? Are there any suggestions how to transform these files into UTF-8 or update the line endings without knowing the file encoding whilst keeping the application working for all the other valid CSV files being delivered? Are there any options that don't involve me going byte to byte and doing a bytes.Replace I've not considered?
I'm hoping there's something really obvious I've overlooked.

Apologies - I can't share the CSV files for obvious reasons.

答: Have you tried to replace all line endings from \r\n or \r to \n ?</p>

Body:
I have an application which deals with CSV's being delivered via RabbitMQ from many different upstream applications - typically 5000-15,000 rows per file. Most of the time it works great. However a couple of these upstream applications are old (12-15 years) and the people who wrote them are long gone.

I'm unable to read CSV files from these older aplications due to the line breaks. I'm finding this a bit weird as the line breaks see to map to UTF-8 Carriage Returns (http://www.fileformat.info/info/unicode/char/000d/index.htm). Typically the app reads in only the headers from those older files and nothing else.

If I open one of these files in a text editor and save as utf-8 encoding  overwriting the exiting file then it works with no issues at all.

Things I've tried I expected to work:

-Using a Reader:

    ba := make([]byte, 262144000)
    if _, err := file.Read(ba); err != nil {
        return nil, err
    }
    ba = bytes.Trim(ba, "\x00")
    bb := bytes.NewBuffer(ba)
    reader := csv.NewReader(bb)
    records, err := reader.ReadAll()
    if err != nil {
        return nil, err
    }

-Using the Scanner to read line by line (get a bufio.Scanner: token too long)

    scanner := bufio.NewScanner(file)
    var bb bytes.Buffer
    for scanner.Scan() {
        bb.WriteString(fmt.Sprintf("%s\n", scanner.Text()))
    }

    // check for errors
    if err = scanner.Err(); err != nil {
        return nil, err
    }

reader := csv.NewReader(&bb)
records, err := reader.ReadAll()
if err != nil {
    return nil, err
}

Things I tried I expected not to work (and didn't):

Writing file contents to a new file (.txt) and reading the file back in (including running dos2unix against the created txt file)

Reading file into a standard string (hoping Go's UTF-8 encoding would magically kick in which of course it doesn't)

Reading file to Rune slice, then transforming to a string via byte slice

I'm aware of the https://godoc.org/golang.org/x/text/transform package but not too sure of a viable approach - it looks like the src encoding needs to be known to transform.

Am I stupidly overlooking something? Are there any suggestions how to transform these files into UTF-8 or update the line endings without knowing the file encoding whilst keeping the application working for all the other valid CSV files being delivered? Are there any options that don't involve me going byte to byte and doing a bytes.Replace I've not considered?
I'm hoping there's something really obvious I've overlooked.

Apologies - I can't share the CSV files for obvious reasons.


问:
Bullet proof solution for page break on table row (
) for printing
It's been days after days we are failing breaking tables as per our need. The solution works for Firefox, but never worked for my favorite browser Chrome in a better way. What we've tried so far is:

We made a class .page-break and made necessary CSS for the different level holders:

```<code>@media print{
   /* applied to our table */
   #report-table {
     /*-webkit-region-break-inside: auto; //tried for Chrome */
     page-break-inside:auto
  }

  /* applied to all our <tr> */
  #report-table tbody tr,
  #report-table .behave-tbody .behave-tr{
     /*-webkit-region-break-inside: avoid; //tried for Chrome */
     page-break-inside:avoid;
     break-after: auto;
     page-break-after: auto;
  }

  /* page break specific class */
  .page-break{
     break-after: always;
     /*-webkit-region-break-after: always; //tried for Chrome */
     page-break-after: always;
  }
}
</code>```

We've learned/found so far

Page break works with a block-level element like

 etc.

Page break works buggy in Google Chrome for Table CSS

Keeping them in mind we proceeded in different ways:

Step #1: Trying the solution with

```<code>    <table id="report-table">
        <thead>
        <tr>
            <th>Head</th>
        </tr>
        </thead>
        <tbody>
        <tr>
            <td>Body Content</td>
        </tr>
        <tr class="page-break">
            <td>Body Content</td>
        </tr>
        <tr>
            <td>Body Content</td>
        </tr>
        </tbody>
    </table>
</code>```

But that didn't work in Google Chrome. Even though we've learnt that,
 itself is a block-level element.

Step #2: Making table absolutely
 based

```<code><style>
.behave-table{
    display: table;
    width: 100%;
    height: 100%;
    position: relative;
}
.behave-thead{
    display: table-header-group;
}
/* th */
.behave-thead .behave-td{
    background-color: #ededed;
    font-weight: 700;
}
.behave-tbody{
    display: table-row-group;
}
.behave-tr{
    display: table-row;
}
.behave-td{
    display: table-cell;
    padding: 5px;
    vertical-align: top;
}
</style>
<div id="report-table" class="behave-table">
   <div class="behave-thead">
      <div class="behave-tr">
         <div class="behave-td">Head</div>
      </div> <!-- /.behave-tr -->
   </div><!-- /.behave-thead -->
   <div class="behave-tbody">
      <div class="behave-tr">
         <div class="behave-td">Body Content</div>
      </div> <!-- /.behave-tr -->
      <div class="behave-tr page-break">
         <div class="behave-td">Body Content</div>
      </div> <!-- /.behave-tr -->
      <div class="behave-tr">
         <div class="behave-td">Body Content</div>
      </div> <!-- /.behave-tr -->
   </div> <!-- /.behave-tbody -->
</div>
</code>```

But that didn't work in Google Chrome.

Step #3: Entering Block Level element inside table cell

Being instructed by the SO thread we've tried a block level element inside a blank table cell like below:

```<code><tr><td>Body Content</td></tr>
<tr style="page-break-after: always"><td><h1>Next Section</h1></td></tr>
<tr><td>Body Content</td></tr>
</code>```

It works partially, for the first page only. We tried hiding the awkward Text block with Bootstrap .sr-only class but with that it din't work at all. We tried replacing the "Next Section" with   - it din't work too.

Step #4: Placing a
 to break using known Block-level elem

```<code><tr><td>Body Content</td></tr>
<div class="page-break"></div>
<tr><td>Body Content</td></tr>
</code>```

But you know it won't work, because
 inside a table only work inside a table cell:

What you need to do is make sure the div is inside an actual table cell, a td or th element
- Chris Coyier

Aftermath

We failed our table to break nicely in Google Chrome. :(

答:
It is not nice but you could try to go with separat tables for each row. By using the following syntax you can make sure the columns are rendered in the same widths.</p>

```<code><style>
    table {
        page-break-inside: avoid;
    }
</style>

<table>
    <colgroup>
        <col width="25%" />
        <col width="50%" />
        <col width="25%" />
    </colgroup>
    <tr>
        <td>Narrow column</td>
        <td>Wide column</td>
        <td>Narrow column</td>
    </tr>
</table>
<!-- can break -->
<table>
    <colgroup>
        <col width="25%" />
        <col width="50%" />
        <col width="25%" />
    </colgroup>
    <tr>
        <td>Narrow column</td>
        <td>Wide column</td>
        <td>Narrow column</td>
    </tr>
</table>
</code>```

Title: Bullet proof solution for page break on table row (<tr>) for printing

Body:
It's been days after days we are failing breaking tables as per our need. The solution works for Firefox, but never worked for my favorite browser Chrome in a better way. What we've tried so far is:

We made a class .page-break and made necessary CSS for the different level holders:

@media print{
   /* applied to our table */
   #report-table {
     /*-webkit-region-break-inside: auto; //tried for Chrome */
     page-break-inside:auto
  }

  /* applied to all our
 */
  #report-table tbody tr,
  #report-table .behave-tbody .behave-tr{
     /*-webkit-region-break-inside: avoid; //tried for Chrome */
     page-break-inside:avoid;
     break-after: auto;
     page-break-after: auto;
  }

  /* page break specific class */
  .page-break{
     break-after: always;
     /*-webkit-region-break-after: always; //tried for Chrome */
     page-break-after: always;
  }
}

We've learned/found so far

Page break works with a block-level element like

 etc.

Page break works buggy in Google Chrome for Table CSS

Keeping them in mind we proceeded in different ways:

Step #1: Trying the solution with

            Head

            Body Content

            Body Content

            Body Content

But that didn't work in Google Chrome. Even though we've learnt that,
 itself is a block-level element.

Step #2: Making table absolutely
 based

Head

Body Content

Body Content

Body Content

But that didn't work in Google Chrome.

Step #3: Entering Block Level element inside table cell

Being instructed by the SO thread we've tried a block level element inside a blank table cell like below:

Body Content

Next Section

Body Content

It works partially, for the first page only. We tried hiding the awkward Text block with Bootstrap .sr-only class but with that it din't work at all. We tried replacing the "Next Section" with   - it din't work too.

Step #4: Placing a
 to break using known Block-level elem

Body Content

Body Content

But you know it won't work, because
 inside a table only work inside a table cell:

What you need to do is make sure the div is inside an actual table cell, a td or th element
- Chris Coyier

Aftermath

We failed our table to break nicely in Google Chrome. :(

Body:
It is not nice but you could try to go with separat tables for each row. By using the following syntax you can make sure the columns are rendered in the same widths.

<style>
    table {
        page-break-inside: avoid;
    }
</style>

<table>
    <colgroup>
        <col width="25%" />
        <col width="50%" />
        <col width="25%" />
    </colgroup>
    <tr>
        <td>Narrow column</td>
        <td>Wide column</td>
        <td>Narrow column</td>
    </tr>
</table>
<!-- can break -->
<table>
    <colgroup>
        <col width="25%" />
        <col width="50%" />
        <col width="25%" />
    </colgroup>
    <tr>
        <td>Narrow column</td>
        <td>Wide column</td>
        <td>Narrow column</td>
    </tr>
</table>


问:
How to check a radio button based on some other value?
I have a bootstrap radio button which needs to get selected based on what value the user gives. Suppose the user enters 'male', male radio button should be selected. Consider the user enters the value in lower case.

    function check(){
    var val = document.getElementById("inp").value;
    if( val == "male"){
        //select male radio button
        }
    if(val == "female"){
         //select female radio button
        }
    }

    ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

    <div class="btn-group" data-toggle="buttons">
                  <p>Gender <span>*</span></p>
                  <label class="btn btn-default">
                    <input class="form-control input-sm" style="width: 0px;" value="M" type="radio" name="gender" />M</label>
                  <label class="btn btn-default">
                    <input class="form-control input-sm" style="width: 0px;" type="radio" value="F" name="gender" />F</label>

                </div><br><br>
    <input id="inp" type="text" onblur="check()"/>

    </code>```

答:
First notice that you have to match user input value to some value of element so that It could be selected dynamically otherwise you have to define it already that which element would be selected throughout the array of elements.
So I have changed your input values a little bit to "male" and "female".
Then it would be easy to perform checking operation based on user input and radio button values.

function check()
{
  var val = document.getElementById("inp").value;
  var elements = document.getElementsByName("gender");
  for(i of elements)
  {
      if(val == i.value)
      {
        i.checked= true;
        i.parentNode.classList.add("active");
     }
     else
     {
      if(i.checked)
      i.parentNode.classList.remove("active");
     }
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

    <div class="btn-group" data-toggle="buttons">
                  <p>Gender <span>*</span></p>
                  <label class="btn btn-default">
                    <input class="form-control input-sm" style="width: 10px;" value="male" type="radio" name="gender" />M</label>
                  <label class="btn btn-default">
                    <input class="form-control input-sm" type="radio" value="female" name="gender" />F</label>

                </div><br><br>
    <input id="inp" type="text" onblur="check()"/></code>```

Body:
I have a bootstrap radio button which needs to get selected based on what value the user gives. Suppose the user enters 'male', male radio button should be selected. Consider the user enters the value in lower case.

    function check(){
    var val = document.getElementById("inp").value;
    if( val == "male"){
        //select male radio button
        }
    if(val == "female"){
         //select female radio button
        }
    }

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Gender *

                    <input class="form-control input-sm" style="width: 0px;" value="M" type="radio" name="gender" />M

                    <input class="form-control input-sm" style="width: 0px;" type="radio" value="F" name="gender" />F

    <input id="inp" type="text" onblur="check()"/>

Body:
First notice that you have to match user input value to some value of element so that It could be selected dynamically otherwise you have to define it already that which element would be selected throughout the array of elements.
So I have changed your input values a little bit to "male" and "female".
Then it would be easy to perform checking operation based on user input and radio button values.

function check()
{
  var val = document.getElementById("inp").value;
  var elements = document.getElementsByName("gender");
  for(i of elements)
  {
      if(val == i.value)
      {
        i.checked= true;
        i.parentNode.classList.add("active");
     }
     else
     {
      if(i.checked)
      i.parentNode.classList.remove("active");
     }
  }
}

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

    <div class="btn-group" data-toggle="buttons">
                  <p>Gender <span>*</span></p>
                  <label class="btn btn-default">
                    <input class="form-control input-sm" style="width: 10px;" value="male" type="radio" name="gender" />M</label>
                  <label class="btn btn-default">
                    <input class="form-control input-sm" type="radio" value="female" name="gender" />F</label>

                </div><br><br>
    <input id="inp" type="text" onblur="check()"/>


问:
Mapping parsed json to java object not working-LibGdx
First time I am using json parsing in my LibGDX project and I am not able to get the parsed results properly.

Here I want to manage the obstacles with properties;name,direction,gap and speed.

I have a json file like this:

```<code>"obstacles": [
 {"name":"eagle","dir":"up","gap":"100","speed":"0"},
 {"name":"bigbird","dir":"up","gap":"200","speed":"0"},
 {"name":"elephant","dir":"middle","gap":"300","speed":"0"},
 {"name":"tiger","dir":"middle","gap":"400","speed":"0"},
 {"name":"bear","dir":"down","gap":"500","speed":"0"},

],
</code>```

and I am reading the array like this:

```<code>public class ReadJson {
static int levelNum = 0;

public ReadJson()
    {
    }

    public static synchronized ArrayList<String> loadLevelJson(int levelno, String name) {
        ArrayList obs = new ArrayList<String>();

        JsonValue jsonValue = new JsonReader().parse(Gdx.files.internal("levels/level1.json"));
        JsonValue objList = jsonValue.get(name);
        System.out.println("name:" + objList);
        if (name.equals("obstacles")) {
            Constants.OBS_COUNT = 0;
            for (JsonValue values : objList.iterator()) // iterator() returns a
                                                            // list of children
            {
                obs.add(values.getString("dir"));
                Constants.OBS_POSITION[obs.size() - 1] = Integer.parseInt(values.getString("gap"));
                Constants.OBS_NAME[obs.size() - 1] = values.getString("name");
                Constants.OBS_SPEED[obs.size() - 1] = Integer.parseInt(values.getString("speed"));
                Constants.OBS_COUNT++;
            }
        }

        else if (.....)) {
            //code
        }
        return obs;
    }

}
</code>```

Arrays are defined in constant class like this:

```<code>public static int OBS_COUNT =20;
public static int[] OBS_POSITION= new int[50];
public static String[] OBS_NAME= new String[50];
public static int[] OBS_SPEED= new int[50];
public static ArrayList<String> obsArray;
</code>```

I want to map the parsed json to the object bear.For that,I did like this:

```<code>private ReadJson readJson;
public ObsObjectFactory() {
    readJson = new ReadJson();
    readJson.loadLevelJson(1,"obstacles");

    Constants.obsArray=readJson.loadLevelJson(1,"obstacles");

}
public Bear createBear() {

    Bear bear = new Bear();

    bear.setName(Constants.OBS_NAME[Constants.OBS_COUNT]);
    bear.setDirection(Constants.obsArray.get(Constants.OBS_COUNT));
    bear.setSpeed(Constants.OBS_SPEED[Constants.OBS_COUNT]);
    bear.setGap(Constants.OBS_POSITION[Constants.OBS_COUNT]);
    bear.setPosition(Constants.EAGLE_X,Constants.EAGLE_Y);
    bear.setSize(Constants.BEAR_WIDTH,Constants.BEAR_HEIGHT);
    return bear;
}
}
</code>```

But when I call this createBear()method and run this code,it is throwing IndexOutOfBoundsException in this line:

```<code>bear.setDirection(Constants.obsArray.get(Constants.OBS_COUNT));
</code>```

Parsed values are displaying properly in console.

What mistake I did here?

答:
Your constants don't seem to be constants, as they can change. I found that odd, and as another aside, the code is quite confusing to follow. I'm not entirely sure what you're trying to achieve.

But the index error is likely caused by incrementing your constant (hint, not a constant then, is it?) Constants.OBS_COUNT++; in the readJson method. Given your json file, OBS_COUNT might end up being 5, so Constants.obsArray.get(Constants.OBS_COUNT) is failing as your array only has index positions 0 through 4.

Body:
First time I am using json parsing in my LibGDX project and I am not able to get the parsed results properly.

Here I want to manage the obstacles with properties;name,direction,gap and speed.

I have a json file like this:

"obstacles": [
 {"name":"eagle","dir":"up","gap":"100","speed":"0"},
 {"name":"bigbird","dir":"up","gap":"200","speed":"0"},
 {"name":"elephant","dir":"middle","gap":"300","speed":"0"},
 {"name":"tiger","dir":"middle","gap":"400","speed":"0"},
 {"name":"bear","dir":"down","gap":"500","speed":"0"},

],

and I am reading the array like this:

public class ReadJson {
static int levelNum = 0;

public ReadJson()
    {
    }

    public static synchronized ArrayList<String> loadLevelJson(int levelno, String name) {
        ArrayList obs = new ArrayList<String>();

        JsonValue jsonValue = new JsonReader().parse(Gdx.files.internal("levels/level1.json"));
        JsonValue objList = jsonValue.get(name);
        System.out.println("name:" + objList);
        if (name.equals("obstacles")) {
            Constants.OBS_COUNT = 0;
            for (JsonValue values : objList.iterator()) // iterator() returns a
                                                            // list of children
            {
                obs.add(values.getString("dir"));
                Constants.OBS_POSITION[obs.size() - 1] = Integer.parseInt(values.getString("gap"));
                Constants.OBS_NAME[obs.size() - 1] = values.getString("name");
                Constants.OBS_SPEED[obs.size() - 1] = Integer.parseInt(values.getString("speed"));
                Constants.OBS_COUNT++;
            }
        }

        else if (.....)) {
            //code
        }
        return obs;
    }

}

Arrays are defined in constant class like this:

public static int OBS_COUNT =20;
public static int[] OBS_POSITION= new int[50];
public static String[] OBS_NAME= new String[50];
public static int[] OBS_SPEED= new int[50];
public static ArrayList<String> obsArray;

I want to map the parsed json to the object bear.For that,I did like this:

private ReadJson readJson;
public ObsObjectFactory() {
    readJson = new ReadJson();
    readJson.loadLevelJson(1,"obstacles");

    Constants.obsArray=readJson.loadLevelJson(1,"obstacles");

}
public Bear createBear() {

    Bear bear = new Bear();

    bear.setName(Constants.OBS_NAME[Constants.OBS_COUNT]);
    bear.setDirection(Constants.obsArray.get(Constants.OBS_COUNT));
    bear.setSpeed(Constants.OBS_SPEED[Constants.OBS_COUNT]);
    bear.setGap(Constants.OBS_POSITION[Constants.OBS_COUNT]);
    bear.setPosition(Constants.EAGLE_X,Constants.EAGLE_Y);
    bear.setSize(Constants.BEAR_WIDTH,Constants.BEAR_HEIGHT);
    return bear;
}
}

But when I call this createBear()method and run this code,it is throwing IndexOutOfBoundsException in this line:

bear.setDirection(Constants.obsArray.get(Constants.OBS_COUNT));

Parsed values are displaying properly in console.

What mistake I did here?


问:
Getting bound parameter value
How should one refer to the value set up within an object passed to v-bind to display it?

Example:

```<code><p v-bind="{id: 'myId'}">{{ /*what to state here to have 'myId' displayed?*/ }}</p>
</code>```

答:
The
 is not a child component, everything here is all in the same scope. You cannot refer to its attributes from its contents. As in Bert's example, you simply have to put what you want in both places.

If you want to use a variable for the id and for the contents, you can do that, but you have to explicitly put it in both places:

```<code><p :id="myIdVariable">{{myIdVariable}}</p>
</code>```

Title: Getting bound parameter value

Body:
How should one refer to the value set up within an object passed to v-bind to display it?

Example:

{{ /*what to state here to have 'myId' displayed?*/ }}

Body:
The <p> is not a child component, everything here is all in the same scope. You cannot refer to its attributes from its contents. As in Bert's example, you simply have to put what you want in both places.

If you want to use a variable for the id and for the contents, you can do that, but you have to explicitly put it in both places:

<p :id="myIdVariable">{{myIdVariable}}</p>