问:
How to create post taxonomy dropdown shortcode?
I am trying to create a dropdown shortcode for WordPress categories and tags taxonomies. I can seem to get the options to appear, but nothing happens upon selection.

I've managed to modify a code snippet that I am using for my WooCommerce tags filter for part of the solution.

Original Working Code Snippet ==>

```<code>add_shortcode( 'product_tax_dropdown', 'wc_product_taxonomy_dropdown' );
function wc_product_taxonomy_dropdown( $atts ) {
    // Attributes
    $atts = shortcode_atts( array(
        'hide_empty'   => '1', // or '0'
        'show_count'   => '0', // or '0'
        'orderby'      => 'name', // or 'order'
        'taxonomy'     => 'product_tag',
    ), $atts, 'product_tax_dropdown' );

    global $wp_query;

    $taxonomy      = $atts['taxonomy'];
    $taxonomy_name = get_taxonomy( $taxonomy )->labels->singular_name;

    ob_start();

    wp_dropdown_categories( array(
        'hide_empty' => $atts['hide_empty'],
        'show_count' => $atts['show_count'],
        'orderby'    => $atts['orderby'],
        'selected'           => isset( $wp_query->query_vars[$taxonomy] ) ? $wp_query->query_vars[$taxonomy] : '',
        'show_option_none'   => sprintf( __( 'Select a %s', 'woocommerce' ), $taxonomy_name ),
        'option_none_value'  => '',
        'value_field'        => 'slug',
        'taxonomy'   => $taxonomy,
        'name'       => $taxonomy,
        'class'      => 'dropdown_'.$taxonomy,
    ) );

    ?>
    <script type='text/javascript'>
        jQuery(function($){
            var select = '.dropdown_product_tag',
                taxonomy = '<?php echo $taxonomy; ?>';

            function onProductTaxChange() {
                if ( $(select).val() !=='' ) {
                    location.href = '<?php echo esc_url( home_url() ); ?>/?'+taxonomy+'='+$(select).val();
                }
            }
            $(select).change( onProductTaxChange );
        });
    </script>
    <?php

    return ob_get_clean();
}
</code>```

Modified Broken Code Snippet ==>

```<code>add_shortcode( 'tax_dropdown', 'taxonomy_dropdown' );
function taxonomy_dropdown( $atts ) {
    // Attributes
    $atts = shortcode_atts( array(
        'hide_empty'   => '1', // or '0'
        'show_count'   => '0', // or '0'
        'orderby'      => 'name', // or 'order'
        'taxonomy'     => 'post_tag',
    ), $atts, 'tax_dropdown' );

    global $wp_query;

    $taxonomy      = $atts['taxonomy'];
    $taxonomy_name = get_taxonomy( $taxonomy )->labels->singular_name;

    ob_start();

    wp_dropdown_categories( array(
        'hide_empty' => $atts['hide_empty'],
        'show_count' => $atts['show_count'],
        'orderby'    => $atts['orderby'],
        'selected'           => isset( $wp_query->query_vars[$taxonomy] ) ? $wp_query->query_vars[$taxonomy] : '',
        'show_option_none'   => sprintf( __( 'Select a %s', 'post' ), $taxonomy_name ),
        'option_none_value'  => '',
        'value_field'        => 'slug',
        'taxonomy'   => $taxonomy,
        'name'       => $taxonomy,
        'class'      => 'dropdown_'.$taxonomy,
    ) );

    ?>
    <script type='text/javascript'>
        jQuery(function($){
            var select = '.dropdown_tag',
                taxonomy = '<?php echo $taxonomy; ?>';

            function onTaxChange() {
                if ( $(select).val() !=='' ) {
                    location.href = '<?php echo esc_url( home_url() ); ?>/?'+taxonomy+'='+$(select).val();
                }
            }
            $(select).change( onTaxChange );
        });
    </script>
    <?php

    return ob_get_clean();
}
</code>```

The taxonomies are appearing in a dropdown menu, but nothing happens when they are selected.

Upon selecting a taxonomy the user should be directed to the selected archive page:

Category Example: http://www.website.com/category/seleted-category
Tag Example: http://www.website.com/tag/selected-tag

答:
An alternative solution</p>

```<code>add_shortcode('product_tax_dropdown', 'wc_product_taxonomy_dropdown');
function wc_product_taxonomy_dropdown( $atts ) {
    // Attributes
    $atts = shortcode_atts(array(
        'hide_empty'   => '1', // or '0'
        'show_count'   => '0', // or '0'
        'orderby'      => 'name', // or 'order'
        'taxonomy'     => 'product_tag',
    ), $atts, 'product_tax_dropdown');

    ob_start();
   ?>
    <select class="<?php echo $atts['taxonomy']; ?>" name="<?php echo $atts['taxonomy']; ?>">
      <option><?php echo sprintf( __( 'Select a %s', 'woocommerce' ), $taxonomy_name ); ?> </option>
      <?php
        $terms = get_terms(array('taxonomy' => $atts['taxonomy'], 'hide_empty' => $atts['hide_empty'], 'show_count' => $atts['show_count'], 'orderby' => $atts['orderby']));
        foreach ($terms as $key => $term) {
      ?>
        <option value="<?php echo get_term_link($term->term_id, $atts['taxonomy']); ?>"><?php echo $term->name; ?></option>
      <?php } ?>
    </select>
    <script type='text/javascript'>
        jQuery(function(){
            var select = '.'<?php echo $atts['taxonomy']; ?>;
            jQuery(select).on('change', function() {
              if (jQuery(this).val() !== '') {
                  location.href = jQuery(this).val();
              }
            });
        });
    </script>
    <?php
}
</code>```

Body:
I am trying to create a dropdown shortcode for WordPress categories and tags taxonomies. I can seem to get the options to appear, but nothing happens upon selection.

I've managed to modify a code snippet that I am using for my WooCommerce tags filter for part of the solution.

Original Working Code Snippet ==>

add_shortcode( 'product_tax_dropdown', 'wc_product_taxonomy_dropdown' );
function wc_product_taxonomy_dropdown( $atts ) {
    // Attributes
    $atts = shortcode_atts( array(
        'hide_empty'   => '1', // or '0'
        'show_count'   => '0', // or '0'
        'orderby'      => 'name', // or 'order'
        'taxonomy'     => 'product_tag',
    ), $atts, 'product_tax_dropdown' );

    global $wp_query;

    $taxonomy      = $atts['taxonomy'];
    $taxonomy_name = get_taxonomy( $taxonomy )->labels->singular_name;

    ob_start();

    wp_dropdown_categories( array(
        'hide_empty' => $atts['hide_empty'],
        'show_count' => $atts['show_count'],
        'orderby'    => $atts['orderby'],
        'selected'           => isset( $wp_query->query_vars[$taxonomy] ) ? $wp_query->query_vars[$taxonomy] : '',
        'show_option_none'   => sprintf( __( 'Select a %s', 'woocommerce' ), $taxonomy_name ),
        'option_none_value'  => '',
        'value_field'        => 'slug',
        'taxonomy'   => $taxonomy,
        'name'       => $taxonomy,
        'class'      => 'dropdown_'.$taxonomy,
    ) );

    ?>

    <?php

    return ob_get_clean();
}

Modified Broken Code Snippet ==>

add_shortcode( 'tax_dropdown', 'taxonomy_dropdown' );
function taxonomy_dropdown( $atts ) {
    // Attributes
    $atts = shortcode_atts( array(
        'hide_empty'   => '1', // or '0'
        'show_count'   => '0', // or '0'
        'orderby'      => 'name', // or 'order'
        'taxonomy'     => 'post_tag',
    ), $atts, 'tax_dropdown' );

    global $wp_query;

    $taxonomy      = $atts['taxonomy'];
    $taxonomy_name = get_taxonomy( $taxonomy )->labels->singular_name;

    ob_start();

    wp_dropdown_categories( array(
        'hide_empty' => $atts['hide_empty'],
        'show_count' => $atts['show_count'],
        'orderby'    => $atts['orderby'],
        'selected'           => isset( $wp_query->query_vars[$taxonomy] ) ? $wp_query->query_vars[$taxonomy] : '',
        'show_option_none'   => sprintf( __( 'Select a %s', 'post' ), $taxonomy_name ),
        'option_none_value'  => '',
        'value_field'        => 'slug',
        'taxonomy'   => $taxonomy,
        'name'       => $taxonomy,
        'class'      => 'dropdown_'.$taxonomy,
    ) );

    ?>

    <?php

    return ob_get_clean();
}

The taxonomies are appearing in a dropdown menu, but nothing happens when they are selected.

Upon selecting a taxonomy the user should be directed to the selected archive page:

Category Example: http://www.website.com/category/seleted-category
Tag Example: http://www.website.com/tag/selected-tag

Body:
An alternative solution

add_shortcode('product_tax_dropdown', 'wc_product_taxonomy_dropdown');
function wc_product_taxonomy_dropdown( $atts ) {
    // Attributes
    $atts = shortcode_atts(array(
        'hide_empty'   => '1', // or '0'
        'show_count'   => '0', // or '0'
        'orderby'      => 'name', // or 'order'
        'taxonomy'     => 'product_tag',
    ), $atts, 'product_tax_dropdown');

    ob_start();
   ?>
    <select class="<?php echo $atts['taxonomy']; ?>" name="<?php echo $atts['taxonomy']; ?>">
      <option><?php echo sprintf( __( 'Select a %s', 'woocommerce' ), $taxonomy_name ); ?> </option>
      <?php
        $terms = get_terms(array('taxonomy' => $atts['taxonomy'], 'hide_empty' => $atts['hide_empty'], 'show_count' => $atts['show_count'], 'orderby' => $atts['orderby']));
        foreach ($terms as $key => $term) {
      ?>
        <option value="<?php echo get_term_link($term->term_id, $atts['taxonomy']); ?>"><?php echo $term->name; ?></option>
      <?php } ?>
    </select>
    <script type='text/javascript'>
        jQuery(function(){
            var select = '.'<?php echo $atts['taxonomy']; ?>;
            jQuery(select).on('change', function() {
              if (jQuery(this).val() !== '') {
                  location.href = jQuery(this).val();
              }
            });
        });
    </script>
    <?php
}


来源: stackexchange

问:
Excess space next to header
I'm having issues with excess space to the left of my header.

I had the same problem with my footer as well using  and
, but edited this to only using  elements instead, and this seemed to do the trick. I would, however, like to keep the  in the header, and preferably without using negative margin-left.

https://jsfiddle.net/thereseel/d75jurzy/6/

```<code><header>
 <nav>
  <ul class="mainnav">
   <li><a href="#">Home</a></li>
   <li><a href="#">Menu</a></li>
   <li><a href="#">Logo</a></li>
   <li><a href="#">Contact</a></li>
   <li><a href="#">Location</a></li>
  </ul>
 </nav>
</header>
</code>```

答:
Try with this code.
HTML code:

```<code><header>
  <nav>
    <ul class="mainnav">
      <li><a href="#">Home</a></li>
      <li><a href="#">Menu</a></li>
      <li><a href="#">Logo</a></li>
      <li><a href="#">Contact</a></li>
      <li><a href="#">Location</a></li>
    </ul>
  </nav>
</header>
<div class="main-body">

</div>

<footer >
  <section class="footnav">
    <a href="#">Home</a>
    <a href="#">About</a>
    <a href="#">Order</a>
    <a href="#">Jobs</a>
    <a href="#">Contact</a>
  </section>
</footer>
</code>```

CSS code:

```<code>.main-body{
  min-height:500px;
}
.mainnav {
    max-width: 800px;
    margin-left: 0;
    margin-bottom: 5px;
    text-align: center;
    display: flex;
    justify-content: space-evenly;
  padding-left:0px;
}

.mainnav li {
    display: inline-block;
}

.footnav {
    width: 100%;
    text-align: center;
    display: flex;
    justify-content: space-evenly;
}
footer{
  position: fixed;
  left:0;
  right:0;
  bottom:0;

}
.footnav a {
    display: inline-block;
    padding: 10px;
}
</code>```

Hope it working.

ContentLicense: CC BY-SA 4.0

Title: Excess space next to header

Body:
I'm having issues with excess space to the left of my header.

I had the same problem with my footer as well using  and
, but edited this to only using  elements instead, and this seemed to do the trick. I would, however, like to keep the  in the header, and preferably without using negative margin-left.

https://jsfiddle.net/thereseel/d75jurzy/6/

Home

Menu

Logo

Contact

Location

Body:
Try with this code.
HTML code:

<header>
  <nav>
    <ul class="mainnav">
      <li><a href="#">Home</a></li>
      <li><a href="#">Menu</a></li>
      <li><a href="#">Logo</a></li>
      <li><a href="#">Contact</a></li>
      <li><a href="#">Location</a></li>
    </ul>
  </nav>
</header>
<div class="main-body">

</div>

<footer >
  <section class="footnav">
    <a href="#">Home</a>
    <a href="#">About</a>
    <a href="#">Order</a>
    <a href="#">Jobs</a>
    <a href="#">Contact</a>
  </section>
</footer>

CSS code:

.main-body{
  min-height:500px;
}
.mainnav {
    max-width: 800px;
    margin-left: 0;
    margin-bottom: 5px;
    text-align: center;
    display: flex;
    justify-content: space-evenly;
  padding-left:0px;
}

.mainnav li {
    display: inline-block;
}

.footnav {
    width: 100%;
    text-align: center;
    display: flex;
    justify-content: space-evenly;
}
footer{
  position: fixed;
  left:0;
  right:0;
  bottom:0;

}
.footnav a {
    display: inline-block;
    padding: 10px;
}

Hope it working.


问:
Hide shipping methods for specific shipping classes in WooCommerce
In WooCommerce, I am hiding shipping methods based on different shipping classes in cart using "Hide shipping methods for specific shipping class in WooCommerce" answer code (the 2nd way), but the problem is that I use WPML plugin which manage 2 languages site, so looking for just one class won't do it.

So I need to handle 2 shipping classes instead of one. I tried addind 2 shipping classes this way:

```<code>// HERE define your shipping classes to find
$class = 3031, 3032;
</code>```

But it breaks the website. So I would like to hide the defined flat rate not only for both shipping classes 3031 and 3032.

What I am doing wrong? How can I enable 2 shipping classes without breaking the web site?

答:
To use multiple shipping classes, you should first defined them in an array and in the IF statement you will use in_array() conditional function this way:

```<code>add_filter( 'woocommerce_package_rates', 'hide_shipping_method_based_on_shipping_class', 10, 2 );
function hide_shipping_method_based_on_shipping_class( $rates, $package )
{
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // HERE define your shipping classes to find
    $classes = [3031, 3032];

    // HERE define the shipping methods you want to hide
    $method_key_ids = array('flat_rate:189');

    // Checking in cart items
    foreach( $package['contents'] as $item ) {
        // If we find one of the shipping classes
        if( in_array( $item['data']->get_shipping_class_id(), $classes ) ){
            foreach( $method_key_ids as $method_key_id ){
                unset($rates[$method_key_id]); // Remove the targeted methods
            }
            break; // Stop the loop
        }
    }
    return $rates;
}
</code>```

Code goes in functions.php file of your active child theme (or active theme). Tested and works.

Sometimes, you should may be need to refresh shipping methods going to shipping areas, then disable / save and re-enable / save your "flat rates" shipping methods.

Related thread: Hide shipping methods for specific shipping class in WooCommerce

Body:
In WooCommerce, I am hiding shipping methods based on different shipping classes in cart using "Hide shipping methods for specific shipping class in WooCommerce" answer code (the 2nd way), but the problem is that I use WPML plugin which manage 2 languages site, so looking for just one class won't do it.

So I need to handle 2 shipping classes instead of one. I tried addind 2 shipping classes this way:

// HERE define your shipping classes to find
$class = 3031, 3032;

But it breaks the website. So I would like to hide the defined flat rate not only for both shipping classes 3031 and 3032.

What I am doing wrong? How can I enable 2 shipping classes without breaking the web site?

Body:
To use multiple shipping classes, you should first defined them in an array and in the IF statement you will use in_array() conditional function this way:

add_filter( 'woocommerce_package_rates', 'hide_shipping_method_based_on_shipping_class', 10, 2 );
function hide_shipping_method_based_on_shipping_class( $rates, $package )
{
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // HERE define your shipping classes to find
    $classes = [3031, 3032];

    // HERE define the shipping methods you want to hide
    $method_key_ids = array('flat_rate:189');

    // Checking in cart items
    foreach( $package['contents'] as $item ) {
        // If we find one of the shipping classes
        if( in_array( $item['data']->get_shipping_class_id(), $classes ) ){
            foreach( $method_key_ids as $method_key_id ){
                unset($rates[$method_key_id]); // Remove the targeted methods
            }
            break; // Stop the loop
        }
    }
    return $rates;
}

Code goes in functions.php file of your active child theme (or active theme). Tested and works.

Sometimes, you should may be need to refresh shipping methods going to shipping areas, then disable / save and re-enable / save your "flat rates" shipping methods.

Related thread: Hide shipping methods for specific shipping class in WooCommerce


问:
Textfield not displaying in ng2-smart-table
I am trying to display a textfield in a column of ng2-smart-table component.
Referred ng2-smart-table documentation but still textfield is not showing. Could you please help to solve this issue.

In component.ts file:

```<code>setting = {
    multimode:true,
    hideSubHeader:true,
    actions: false,
    columns: {
        NAME:
        {
        title: 'Name'
        },

        VALUE: {
            title: 'Value',
            type:'text',
            editor:{
                type:'text'

            }

         }
        },
        attr:
        {
        class: 'table table-bordered'
        }
    }
</code>```

In component.html file:

```<code> <ng2-smart-table [settings]="setting" [source]="ConfigureSource" ></ng2-smart-table>
</code>```

In ConfigureSource.ts file:

```<code>export const ConfigureData: Array<any> = [
        {
                  "Name": "John",
                  "Value": ""

              },
              {
                  "Name": "Sam",
                  "Value": ""
              }

          ];
</code>```

答:
try to set the actions:

actions: { edit: true, position: 'right' }

and the column editable to true

Body:
I am trying to display a textfield in a column of ng2-smart-table component.
Referred ng2-smart-table documentation but still textfield is not showing. Could you please help to solve this issue.

In component.ts file:

setting = {
    multimode:true,
    hideSubHeader:true,
    actions: false,
    columns: {
        NAME:
        {
        title: 'Name'
        },

        VALUE: {
            title: 'Value',
            type:'text',
            editor:{
                type:'text'

            }

         }
        },
        attr:
        {
        class: 'table table-bordered'
        }
    }

In component.html file:

 <ng2-smart-table [settings]="setting" [source]="ConfigureSource" ></ng2-smart-table>

In ConfigureSource.ts file:

export const ConfigureData: Array<any> = [
        {
                  "Name": "John",
                  "Value": ""

              },
              {
                  "Name": "Sam",
                  "Value": ""
              }

          ];


问:
django pandas dataframe download as excel file
I have a Django app that will be placed in a Docker container.

The app prepares data in Dataframe format.   I would like to allow the user to download the data to his/her local drive as excel file.

I have used df.to_excel in the past, but this won't work in this case.

Please advise best way to do this.

答:
As of pandas-0.17, you can let Django write to a BytesIO directly, like:

```<code>from django.http import HttpResponse
from io import <b>BytesIO</b>

def some_view(request):
    with BytesIO() as <b>b</b>:
        # Use the StringIO object as the filehandle.
        <b>writer = pd.ExcelWriter(b, engine='xlsxwriter')</b>
        df.to_excel(writer, sheet_name='Sheet1')
        writer.save()
        # Set up the Http response.
        filename = 'django_simple.xlsx'
        response = HttpResponse(
            b.getvalue(),
            content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        )
        response['Content-Disposition'] = 'attachment; filename=%s' % filename
        return response</code>```

You might need to install an Excel writer module (like xlsxwriter, or openpyxl).

Body:
As of pandas-0.17, you can let Django write to a BytesIO directly, like:

from django.http import HttpResponse
from io import BytesIO

def some_view(request):
    with BytesIO() as b:
        # Use the StringIO object as the filehandle.
        writer = pd.ExcelWriter(b, engine='xlsxwriter')
        df.to_excel(writer, sheet_name='Sheet1')
        writer.save()
        # Set up the Http response.
        filename = 'django_simple.xlsx'
        response = HttpResponse(
            b.getvalue(),
            content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        )
        response['Content-Disposition'] = 'attachment; filename=%s' % filename
        return response

You might need to install an Excel writer module (like xlsxwriter, or openpyxl).


问:
Is there a speed difference in MySQL operations?
I was discussing speed of MySQL statements and someone asked me: Between SELECT, INSERT, UPDATE, and DELETE, which is faster and why?

I didn't know the answer. Does anyone know if one is faster than the other, and if so, why? Or are they all generally the same speed?

答:
Speed in database queries can only really be measured as a relative to each other. For most simple queries, it's a nominal difference in terms of milliseconds.

The better problem should be viewed from the point of view of 'how many things are you effecting?'.

A query can take on a variety of forms but if you are selecting from 3 tables, it will likely be slower than 2 tables.

Using LIMIT will help the query to execute quicker in all cases

Indices can help a query if it uses them properly

Updating indices takes time

Larger tables take more time to work through

The list goes on, but usually I'd built and work on the slow spots after the fact. Most people don't really push their databases all that hard anyways:)

OwnerDisplayName: rocket

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Paulo


问:
Archive MySQL data using PHP every week
I have a MySQL DB that receives a lot of data from a source once every week on a certain day of the week at a given time (about 1.2million rows) and stores it in, lets call it, the "live" table.

I want to copy all the data from "live" table into an archive and truncate the live table to make space for the next "current data" that will come in the following week.

Can anyone suggest an efficient way of doing this. I am really trying to avoid  -- insert into archive_table select * from live --. I would like the ability to run this archiver using PHP so I cant use Maatkit. Any suggestions?

EDIT: Also, the archived data needs to be readily accessible. Since every insert is timestamped, if I want to look for the data from last month, I can just search for it in the archives

答:
This would depend on what you're doing with the data once you've archived it, but have you considered using MySQL replication?

You could set up another server as a replication slave, and once all the data gets replicated, do your delete or truncate with a SET BIN-LOG 0 before it to avoid that statement also being replicated.

ContentLicense: CC BY-SA 3.0

Title: Archive MySQL data using PHP every week


问:
How to update orders of records in SQL table using ajax in C# ASP.NET MVC project?
I want to change OrderNumber using JQUery sortable and Ajax. But formData is empty at all.

I'm using FormData to collect sorted rows and pass to API controller. Each time rows getting resorted, Ajax will call and so on, but the problem is before it the FormData is empty (console log report).

AnswerSteps table in database:

```<code>[ID] [int] IDENTITY(1,1) NOT NULL,
[QuestionID] [int] NOT NULL,
[AnswerFA] [nvarchar](max) NOT NULL,
[AnswerEN] [nvarchar](max) NOT NULL,
[ImageURL] [nvarchar](max) NOT NULL,
[OrderNumber] [int] NOT NULL
</code>```

View model:

```<code>public class SortedAnswersViewModel
{
    public List<string> SortedAnswerIDs { get; set; }
}
</code>```

Jquery:

```<code>    var $sortableList = $("#sortable");
    var sortEventHandler = function (event, ui) {

        var data = new FormData();
        var $listElements = $sortableList.children();
        var listValues = [];

        $.each($listElements, function (i, v) {
            listValues.push(v.id);
        });

        data.append("SortedAnswerIDs", listValues);

        console.log(data); // data is always null here

        var ajaxRequest = $.ajax({
          //Some Codes
        });
    };

    $("#sortable").sortable({
        update: function (event, ui) {
            sortEventHandler();
        },
    });
</code>```

What's wrong in my code?

答:
Try change this: var $sortableList = $("#sortable");

To this: var $sortableList = $("#sortable").val();

Body:
I want to change OrderNumber using JQUery sortable and Ajax. But formData is empty at all.

I'm using FormData to collect sorted rows and pass to API controller. Each time rows getting resorted, Ajax will call and so on, but the problem is before it the FormData is empty (console log report).

AnswerSteps table in database:

[ID] [int] IDENTITY(1,1) NOT NULL,
[QuestionID] [int] NOT NULL,
[AnswerFA] [nvarchar](max) NOT NULL,
[AnswerEN] [nvarchar](max) NOT NULL,
[ImageURL] [nvarchar](max) NOT NULL,
[OrderNumber] [int] NOT NULL

View model:

public class SortedAnswersViewModel
{
    public List<string> SortedAnswerIDs { get; set; }
}

Jquery:

    var $sortableList = $("#sortable");
    var sortEventHandler = function (event, ui) {

        var data = new FormData();
        var $listElements = $sortableList.children();
        var listValues = [];

        $.each($listElements, function (i, v) {
            listValues.push(v.id);
        });

        data.append("SortedAnswerIDs", listValues);

        console.log(data); // data is always null here

        var ajaxRequest = $.ajax({
          //Some Codes
        });
    };

    $("#sortable").sortable({
        update: function (event, ui) {
            sortEventHandler();
        },
    });

What's wrong in my code?


问:
How to Create UI for different size of Android
I have test on two phones.
Moto G5s
Mi note 7 pro

My UI is look perfect on Moto g5s
but on Mi note 7 pro it's look small font size.

I have attached screenshots of both phones.

Moto G5s: http://prntscr.com/nw9rhi

Note 7 pro: http://prntscr.com/nw9r4y

Actual UI: http://prntscr.com/nw9rvv

What I expected It looks same on all device.

This is my layout. I have a viewpager.So created Item layout for Text.When Swipe it.It change text like this.

I want like this. I have issue only on design on different phones.
http://prntscr.com/nw9u1j

```<code>//TourLayout.axml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

 <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/tourbg"
        android:scaleType="fitXY"
        android:adjustViewBounds="true"
        android:id="@+id/imageView" />
    <LinearLayout
          android:layout_width="match_parent"
          android:weightSum="1"
          android:orientation="vertical"
          android:layout_height="match_parent">
           <LinearLayout
                android:layout_width="match_parent"
                android:layout_weight="0.24"
                android:layout_height="0dp">
            <RelativeLayout
                android:id="@+id/welcomeLayout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="bottom">
                <JammberSplits.Droid.Views.PieView
                    android:layout_height="@dimen/margin_90"
                    android:id="@+id/pieView"
                    android:layout_marginLeft="@dimen/margin_30"
                    android:layout_marginTop="@dimen/margin_10"
                    android:layout_width="@dimen/margin_90">
                </JammberSplits.Droid.Views.PieView>
            </RelativeLayout>
          </LinearLayout>
         <LinearLayout
            android:layout_width="match_parent"
            android:layout_weight="0.56"
            android:layout_height="0dp">
             <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:id="@+id/LoginCenterLayout">
                <android.support.v4.view.ViewPager
                    android:id="@+id/viewpager"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"/>

             </RelativeLayout>
        </LinearLayout>
         <LinearLayout
            android:layout_width="match_parent"
            android:layout_weight="0.20"
            android:layout_height="0dp">
           <RelativeLayout
                android:id="@+id/SignUpLayout"
                android:layout_width="match_parent"

                android:layout_height="match_parent"

                android:layout_centerHorizontal="true">

            <LinearLayout
                                android:id="@+id/viewPagerCountDots"
                                android:layout_width="match_parent"
                                android:layout_height="match_parent"
                                android:layout_marginBottom="@dimen/margin_05"
                                android:layout_above="@+id/btnNext"
                                android:layout_centerHorizontal="true"
                                android:gravity="center"
                                android:orientation="horizontal" />
                        <Button
                          android:layout_width="wrap_content"
                          android:layout_height="@dimen/margin_40"
                          android:text="Next"
                          android:layout_marginTop="@dimen/margin_10"
                          android:layout_marginBottom="@dimen/margin_20"
                          android:layout_alignParentBottom="true"
                          android:id="@+id/btnNext"
                         android:textColor="@color/colorWhite"
                         android:textSize="@dimen/textSize_15"
                         android:background="@drawable/button_transparen"
                         app:fontFamily="@font/lato_light"
                         android:paddingLeft="@dimen/margin_50"
                         android:paddingRight="@dimen/margin_50"
                         android:layout_centerHorizontal="true"
                         android:inputType="none|textCapWords" />
                    </RelativeLayout>
            </LinearLayout>
        </LinearLayout>
</RelativeLayout>

//TourItemLayout.axml

 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_centerVertical="true"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="SONG"
            android:lines="1"
            android:maxLines="1"
            android:ellipsize="end"
            android:id="@+id/lblTourWizFirstLine"
            android:layout_marginRight="@dimen/margin_38"
            app:fontFamily="@font/lato_bold"
            android:textColor="@color/colorWhite"
            android:layout_marginLeft="@dimen/margin_38"
            android:textSize="@dimen/textSize_73"
             />
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="SPLITS"
            android:lines="1"
            android:maxLines="1"
            android:ellipsize="end"
            android:layout_marginRight="@dimen/margin_38"
            android:layout_marginTop="@dimen/margin_20_minus"
            android:id="@+id/lblTourWizSecondLine"
            android:layout_below="@+id/lblTourWizFirstLine"
            app:fontFamily="@font/lato_bold"
            android:textColor="@color/colorWhite"
            android:layout_marginLeft="@dimen/margin_38"
            android:textSize="@dimen/textSize_73"/>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="MADE"
            android:lines="1"
            android:maxLines="1"
            android:ellipsize="end"
            android:layout_marginRight="@dimen/margin_38"
            android:layout_marginTop="@dimen/margin_20_minus"
            android:id="@+id/lblTourWizThirdLine"
            android:layout_below="@+id/lblTourWizSecondLine"
            app:fontFamily="@font/lato_bold"
            android:textColor="@color/colorWhite"
            android:layout_marginLeft="@dimen/margin_38"
            android:textSize="@dimen/textSize_73"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="EASY"
            android:lines="1"
            android:maxLines="1"
            android:ellipsize="end"
            android:layout_marginRight="@dimen/margin_38"
            android:layout_marginTop="@dimen/margin_20_minus"
            android:id="@+id/lblTourWizFourthLine"
            android:layout_below="@+id/lblTourWizThirdLine"
            app:fontFamily="@font/lato_bold"
            android:textColor="@color/colorWhite"
            android:layout_marginLeft="@dimen/margin_38"
            android:textSize="@dimen/textSize_73"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Invite your co-writers\nto collaborate on a\nnew project"
            android:layout_marginTop="@dimen/margin_70"
            android:lines="3"
            android:maxLines="3"
            android:ellipsize="end"
            android:id="@+id/lblDescriptionText"
            android:layout_below="@+id/lblTourWizThirdLine"
            app:fontFamily="@font/lato_regular"
            android:textColor="@color/colorWhite"
            android:layout_marginLeft="@dimen/margin_38"
            android:layout_marginRight="@dimen/margin_85"
            android:textSize="@dimen/textSize_18"/>

        <!--<ImageView android:id="@+id/TextTour"
                   android:src="@drawable/tour1text"
                   android:layout_centerVertical="true"

                   android:layout_marginLeft="@dimen/margin_38"
                   android:scaleType="fitStart"
                   android:layout_width="wrap_content"
                   android:layout_height="wrap_content"/>-->

    </RelativeLayout>

</RelativeLayout>
</code>```

答:
There are a lot of ways to achieve such a behavior. For example, you may define dimens resources for a different phones with smallest width qualifiers.

https://developer.android.com/training/multiscreen/screensizes

Body:
I have test on two phones.
Moto G5s
Mi note 7 pro

My UI is look perfect on Moto g5s
but on Mi note 7 pro it's look small font size.

I have attached screenshots of both phones.

Moto G5s: http://prntscr.com/nw9rhi

Note 7 pro: http://prntscr.com/nw9r4y

Actual UI: http://prntscr.com/nw9rvv

What I expected It looks same on all device.

This is my layout. I have a viewpager.So created Item layout for Text.When Swipe it.It change text like this.

I want like this. I have issue only on design on different phones.
http://prntscr.com/nw9u1j

//TourLayout.axml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

 <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/tourbg"
        android:scaleType="fitXY"
        android:adjustViewBounds="true"
        android:id="@+id/imageView" />
    <LinearLayout
          android:layout_width="match_parent"
          android:weightSum="1"
          android:orientation="vertical"
          android:layout_height="match_parent">
           <LinearLayout
                android:layout_width="match_parent"
                android:layout_weight="0.24"
                android:layout_height="0dp">
            <RelativeLayout
                android:id="@+id/welcomeLayout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="bottom">
                <JammberSplits.Droid.Views.PieView
                    android:layout_height="@dimen/margin_90"
                    android:id="@+id/pieView"
                    android:layout_marginLeft="@dimen/margin_30"
                    android:layout_marginTop="@dimen/margin_10"
                    android:layout_width="@dimen/margin_90">
                </JammberSplits.Droid.Views.PieView>
            </RelativeLayout>
          </LinearLayout>
         <LinearLayout
            android:layout_width="match_parent"
            android:layout_weight="0.56"
            android:layout_height="0dp">
             <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:id="@+id/LoginCenterLayout">
                <android.support.v4.view.ViewPager
                    android:id="@+id/viewpager"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"/>

             </RelativeLayout>
        </LinearLayout>
         <LinearLayout
            android:layout_width="match_parent"
            android:layout_weight="0.20"
            android:layout_height="0dp">
           <RelativeLayout
                android:id="@+id/SignUpLayout"
                android:layout_width="match_parent"

                android:layout_height="match_parent"

                android:layout_centerHorizontal="true">

            <LinearLayout
                                android:id="@+id/viewPagerCountDots"
                                android:layout_width="match_parent"
                                android:layout_height="match_parent"
                                android:layout_marginBottom="@dimen/margin_05"
                                android:layout_above="@+id/btnNext"
                                android:layout_centerHorizontal="true"
                                android:gravity="center"
                                android:orientation="horizontal" />
                        <Button
                          android:layout_width="wrap_content"
                          android:layout_height="@dimen/margin_40"
                          android:text="Next"
                          android:layout_marginTop="@dimen/margin_10"
                          android:layout_marginBottom="@dimen/margin_20"
                          android:layout_alignParentBottom="true"
                          android:id="@+id/btnNext"
                         android:textColor="@color/colorWhite"
                         android:textSize="@dimen/textSize_15"
                         android:background="@drawable/button_transparen"
                         app:fontFamily="@font/lato_light"
                         android:paddingLeft="@dimen/margin_50"
                         android:paddingRight="@dimen/margin_50"
                         android:layout_centerHorizontal="true"
                         android:inputType="none|textCapWords" />
                    </RelativeLayout>
            </LinearLayout>
        </LinearLayout>
</RelativeLayout>

//TourItemLayout.axml

 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_centerVertical="true"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="SONG"
            android:lines="1"
            android:maxLines="1"
            android:ellipsize="end"
            android:id="@+id/lblTourWizFirstLine"
            android:layout_marginRight="@dimen/margin_38"
            app:fontFamily="@font/lato_bold"
            android:textColor="@color/colorWhite"
            android:layout_marginLeft="@dimen/margin_38"
            android:textSize="@dimen/textSize_73"
             />
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="SPLITS"
            android:lines="1"
            android:maxLines="1"
            android:ellipsize="end"
            android:layout_marginRight="@dimen/margin_38"
            android:layout_marginTop="@dimen/margin_20_minus"
            android:id="@+id/lblTourWizSecondLine"
            android:layout_below="@+id/lblTourWizFirstLine"
            app:fontFamily="@font/lato_bold"
            android:textColor="@color/colorWhite"
            android:layout_marginLeft="@dimen/margin_38"
            android:textSize="@dimen/textSize_73"/>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="MADE"
            android:lines="1"
            android:maxLines="1"
            android:ellipsize="end"
            android:layout_marginRight="@dimen/margin_38"
            android:layout_marginTop="@dimen/margin_20_minus"
            android:id="@+id/lblTourWizThirdLine"
            android:layout_below="@+id/lblTourWizSecondLine"
            app:fontFamily="@font/lato_bold"
            android:textColor="@color/colorWhite"
            android:layout_marginLeft="@dimen/margin_38"
            android:textSize="@dimen/textSize_73"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="EASY"
            android:lines="1"
            android:maxLines="1"
            android:ellipsize="end"
            android:layout_marginRight="@dimen/margin_38"
            android:layout_marginTop="@dimen/margin_20_minus"
            android:id="@+id/lblTourWizFourthLine"
            android:layout_below="@+id/lblTourWizThirdLine"
            app:fontFamily="@font/lato_bold"
            android:textColor="@color/colorWhite"
            android:layout_marginLeft="@dimen/margin_38"
            android:textSize="@dimen/textSize_73"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Invite your co-writers\nto collaborate on a\nnew project"
            android:layout_marginTop="@dimen/margin_70"
            android:lines="3"
            android:maxLines="3"
            android:ellipsize="end"
            android:id="@+id/lblDescriptionText"
            android:layout_below="@+id/lblTourWizThirdLine"
            app:fontFamily="@font/lato_regular"
            android:textColor="@color/colorWhite"
            android:layout_marginLeft="@dimen/margin_38"
            android:layout_marginRight="@dimen/margin_85"
            android:textSize="@dimen/textSize_18"/>

    </RelativeLayout>

</RelativeLayout>


答:
Inorder to support multiple devices and multiple screen support , there are different options available.

1) You can create different dimens file,dimens.xml(small,normal,large,xlarge) inside res->values folder.

2) Provide different xml files for different screen sizes. (Not preferable)

3) Use Constraint Layouts.

Title: How to Create UI for different size of Android


问:
the web page changes the style when I resize the size of my window.Can i make it look the same for any size of the window

```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>

<header>MY PROFILE</header>

<div>insert image</div>

<body>

  <section>

    <p id="ii"><b>PERSONAL DETAILS</b></p>

  </section>

  <section id="intro">

    <p>
      <B><br><br>Name       :</B> [name of the person] </p>

  </section>

</body>

</html></code>```

Web page created changes the looks or style when i resize the size of the window. Can I make the alignment of web page stay the same?

Eg: When the window is in full screen the alignment of left and right sides are perfect .But when I make the size of the window smaller. The content in the left remains but the content on the right moves to the bottom after the whole left content is over

I have tried changing the viewport in the image the details of name moved down after I made window smaller.

答:
Is this what your looking for?

```<code><!DOCTYPE html>
<html>
<body onresize="resize()">
<p id="size"></p>
<script>
function resize()
{
  var width = window.outerWidth;
  var height = window.outerHeight;
  var sizes = "Window size: width=" + width + ", height=" + height;
  document.getElementById("size").innerHTML = sizes;
}
</script>
</body>
</html>
</code>```

You can use the window.outerWidth and height to position the text/elements...
If you need any more help, would you mind posting the code so I could take a look?
Thanks :)

Body:
MY PROFILE

insert image

PERSONAL DETAILS

Name       : [name of the person]

Web page created changes the looks or style when i resize the size of the window. Can I make the alignment of web page stay the same?

Eg: When the window is in full screen the alignment of left and right sides are perfect .But when I make the size of the window smaller. The content in the left remains but the content on the right moves to the bottom after the whole left content is over

I have tried changing the viewport in the image the details of name moved down after I made window smaller.

Body:
Is this what your looking for?

<!DOCTYPE html>
<html>
<body onresize="resize()">
<p id="size"></p>
<script>
function resize()
{
  var width = window.outerWidth;
  var height = window.outerHeight;
  var sizes = "Window size: width=" + width + ", height=" + height;
  document.getElementById("size").innerHTML = sizes;
}
</script>
</body>
</html>

You can use the window.outerWidth and height to position the text/elements...
If you need any more help, would you mind posting the code so I could take a look?
Thanks :)


问:
Remove leading zeros before decimal in Datatables
I want to remove the number to the left side of the decimal if that digit is less than 1.  Basically, I want to remove a zero if its there.

Meaning 0.25 would become .25 but 1.50 would remain 1.50

```<code>$(document).ready(function() {
  $('#mytabl').DataTable({
    "searching": true,
    "pageLength": 40,
    "scrollX": true,
    "paging": false,
    "info": false,
    drawCallback: () => {
      const table = $('#mytabl').DataTable();
      const tableData = table.rows({
        search: 'applied'
      }).data().toArray();
      const totals = tableData.reduce((total, rowData) => {
        total[0] += parseFloat(rowData[1]);
        total[1] += parseFloat(rowData[2]);
        return total;
      }, [0, 0]);
      $(table.column(1).footer()).text(totals[0]);
      $(table.column(2).footer()).text(totals[1]);
    }
  })
});
</code>```

答:
You can use a simple regex

```<code>^0+(?=\d*\.\d+)
</code>```

^ - start of string

0+ - Match 0 one or more time

(?=\d*\.\d+) - Match must be followed by digit zero or time and a decimal and one or more digits after it

let nums = ["0.25","1.25","001.23",".23",'0.0']

nums.forEach(value=>{
  value = value.replace(/^0+(?=\d*\.\d+)/,'')
  console.log(value)
})```

Body:
I want to remove the number to the left side of the decimal if that digit is less than 1.  Basically, I want to remove a zero if its there.

Meaning 0.25 would become .25 but 1.50 would remain 1.50

$(document).ready(function() {
  $('#mytabl').DataTable({
    "searching": true,
    "pageLength": 40,
    "scrollX": true,
    "paging": false,
    "info": false,
    drawCallback: () => {
      const table = $('#mytabl').DataTable();
      const tableData = table.rows({
        search: 'applied'
      }).data().toArray();
      const totals = tableData.reduce((total, rowData) => {
        total[0] += parseFloat(rowData[1]);
        total[1] += parseFloat(rowData[2]);
        return total;
      }, [0, 0]);
      $(table.column(1).footer()).text(totals[0]);
      $(table.column(2).footer()).text(totals[1]);
    }
  })
});

Body:
You can use a simple regex

^0+(?=\d*\.\d+)

^ - start of string

0+ - Match 0 one or more time

(?=\d*\.\d+) - Match must be followed by digit zero or time and a decimal and one or more digits after it

let nums = ["0.25","1.25","001.23",".23",'0.0']

nums.forEach(value=>{
  value = value.replace(/^0+(?=\d*\.\d+)/,'')
  console.log(value)
})


问:
Getting row Count only returns value of 1
I am using Sql Server 2005 and Vb Studios 2010 on a .net Framework of 4.0. I am trying to get the exact number of rows from a database and populate a datatable then have a label show the number of rows.

```<code>Dim comm2 = db.selectcommand(db.conn, "*", "Tablename", " columnname = '" & Session(sessionvariable) & "' AND columnname = 'Unread '")
    Dim sqlda2 As New SqlDataAdapter(comm2)
    Dim dt2 As New DataTable
    sqlda2.Fill(dt2)
    Dim recordcount As Integer = dt2.Rows.Count
    messagecountlbl.Text = recordcount
</code>```

this will always return the value of 1 and I know for a fact that I have multiple values for the data I am trying to pull. I have atleast 50 and the label should be displaying that amount.

I have also tried the Select Count statement and it does the same thing.

Fix I have added this to the post since there is a 24 hr wait to answer question:
I have found a quick and simple fix that I will shorten later in a class file that I have written but this should help alot of people out.

```<code>Dim sqlresult As Object
    Dim constring As String = "Connection string goes here"
    Dim dbcon As SqlConnection = New SqlConnection(constring)
    Dim sql As New SqlCommand
    dbcon.Open()
    sql.Connection = dbcon
    sql.CommandText = "SELECT COUNT (*) FROM Tablename WHERE Columnname = 'Unread' AND columnname = '" & Session("sessionvariable") & "'"
    sqlresult = sql.ExecuteScalar
    messagecountlbl.Text = sqlresult
</code>```

答:
I note that your first line declares a variable called comm2 but you don't use it later - instead you're using simply comm.

With that in mind, the fact that you've omitted the quotes around Unread will still be relevant.

Body:
I am using Sql Server 2005 and Vb Studios 2010 on a .net Framework of 4.0. I am trying to get the exact number of rows from a database and populate a datatable then have a label show the number of rows.

Dim comm2 = db.selectcommand(db.conn, "*", "Tablename", " columnname = '" & Session(sessionvariable) & "' AND columnname = 'Unread '")
    Dim sqlda2 As New SqlDataAdapter(comm2)
    Dim dt2 As New DataTable
    sqlda2.Fill(dt2)
    Dim recordcount As Integer = dt2.Rows.Count
    messagecountlbl.Text = recordcount

this will always return the value of 1 and I know for a fact that I have multiple values for the data I am trying to pull. I have atleast 50 and the label should be displaying that amount.

I have also tried the Select Count statement and it does the same thing.

Fix I have added this to the post since there is a 24 hr wait to answer question:
I have found a quick and simple fix that I will shorten later in a class file that I have written but this should help alot of people out.

Dim sqlresult As Object
    Dim constring As String = "Connection string goes here"
    Dim dbcon As SqlConnection = New SqlConnection(constring)
    Dim sql As New SqlCommand
    dbcon.Open()
    sql.Connection = dbcon
    sql.CommandText = "SELECT COUNT (*) FROM Tablename WHERE Columnname = 'Unread' AND columnname = '" & Session("sessionvariable") & "'"
    sqlresult = sql.ExecuteScalar
    messagecountlbl.Text = sqlresult


问:
Plotting with ggplot and chron - label change to %H:%M:%S
I am working with some chron data of the class 'times' and am plotting it in a scatter plot. However, I want the labeling to be in %H:%M:%S format for the variable on the x axis Tim.V. Simply adding scale_x_continuous(labels = "%H:%M:%S")  to the code below does not seem to do the trick. I don't need to convert the data in any way - just the format of the label on the x axis. Any insight on how to do this? It seems like it should be simple.

doeplotnet <- ggplot(division, aes(x =Tim.V, y = Age)) + geom_point() + scale_x_reverse()

Sample Data (Age is numeric and Tim.V is 'times')

```<code>Age     Tim.V
40       00:33:08
36       00:59:27
29       01:05:33
52       00:49:14
49       01:08:00
44       00:30:45
</code>```

答:
You can also use lubridate::ymd_hms to convert to a datetime with a dummy date, and plot that with ggplot2:

```<code>library(tidyverse); library(lubridate)
mydata3 <- mydata2 %>%
  mutate(time3 = lubridate::ymd_hms(paste(
    "2000-01-01", hour(time2), minute(time2), second(time2))))

ggplot(mydata3, aes(x=time3, y=pending, color=server, group=tradedate)) +
    geom_point() +
    facet_wrap(~ tradedate)
</code>```

Sample data used:

```<code>mydata2 <-
  data_frame(time2 = new(
    "Period",
    .Data = c(23, 23, 42, 42, 24, 24, 42, 42),
    year = c(0,  0, 0, 0, 0, 0, 0, 0),
    month = c(0, 0, 0, 0, 0, 0, 0, 0),
    day = c(0,
            0, 0, 0, 0, 0, 0, 0),
    hour = c(14, 14, 14, 14, 14, 14, 14, 14),
    minute = c(5, 5, 5, 5, 6, 6, 6, 6)
  ),
  pending = runif(8),
  server = "server1",
  tradedate = rep(ymd(c(20190101, 20190102)), 4)
  )
</code>```

Body:
I am working with some chron data of the class 'times' and am plotting it in a scatter plot. However, I want the labeling to be in %H:%M:%S format for the variable on the x axis Tim.V. Simply adding scale_x_continuous(labels = "%H:%M:%S")  to the code below does not seem to do the trick. I don't need to convert the data in any way - just the format of the label on the x axis. Any insight on how to do this? It seems like it should be simple.

doeplotnet <- ggplot(division, aes(x =Tim.V, y = Age)) + geom_point() + scale_x_reverse()

Sample Data (Age is numeric and Tim.V is 'times')

Age     Tim.V
40       00:33:08
36       00:59:27
29       01:05:33
52       00:49:14
49       01:08:00
44       00:30:45

Body:
You can also use lubridate::ymd_hms to convert to a datetime with a dummy date, and plot that with ggplot2:

library(tidyverse); library(lubridate)
mydata3 <- mydata2 %>%
  mutate(time3 = lubridate::ymd_hms(paste(
    "2000-01-01", hour(time2), minute(time2), second(time2))))

ggplot(mydata3, aes(x=time3, y=pending, color=server, group=tradedate)) +
    geom_point() +
    facet_wrap(~ tradedate)

Sample data used:

mydata2 <-
  data_frame(time2 = new(
    "Period",
    .Data = c(23, 23, 42, 42, 24, 24, 42, 42),
    year = c(0,  0, 0, 0, 0, 0, 0, 0),
    month = c(0, 0, 0, 0, 0, 0, 0, 0),
    day = c(0,
            0, 0, 0, 0, 0, 0, 0),
    hour = c(14, 14, 14, 14, 14, 14, 14, 14),
    minute = c(5, 5, 5, 5, 6, 6, 6, 6)
  ),
  pending = runif(8),
  server = "server1",
  tradedate = rep(ymd(c(20190101, 20190102)), 4)
  )


问:
Java Properties class bug
I have this piece of code.

```<code>// On a thread
try {
    WatchService watcher = FileSystems.getDefault().newWatchService();
    Path directory = Paths.get("properties");
    WatchKey watchKey = directory.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY);
    while (true) {
        for (WatchEvent<?> event : watchKey.pollEvents()) {
            Path changed = (Path) event.context();
            if (changed.toString().equals("radar.properties")) {
                System.out.println("read call:");
                readProperties();
            }

        }

        if (!watchKey.reset()) {
            break;
        }
    }
} catch (IOException e) {
    FCSLogger.LOGGER.log(Level.SEVERE, "Exception while setting up WatchService", e);
}

// Method called by the above code

private void readProperties() {
    try {
        InputStream input = new FileInputStream(Paths.get("properties", "radar.properties").toString());
        Properties prop = new Properties();
        prop.load(input);
        updateRate = Integer.parseInt(prop.getProperty("updateRate"));
        System.out.println(updateRate);
        input.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
</code>```

It returns the right result on the first call and then blocks the whole thread. I've isolated the bug to be in this method since everything else works flawlessly when there is no calling this method. I'm wondering what am I doing wrong here.
Snapshot of console output:

```<code>// First change of file:
read call:
10
read call:
10

// Second change of file:
read call:

// I keep changing but nothing happens:
</code>```

答:
It can be that readProperties throws NumberFormatException, and that causes your watcher thread to exit.

You could wrap calls to readProperties and catch exceptions; so that at least the watcher will keep watching in case of exceptions.

And you should use take, so that the watcher thread blocks. Your current solution causes 100% cpu usage.

See below the modified code. I added a writer thread to update the file, and (unsurprisingly?) readProperties can fail since we are accessing the file while it is being written. A possible output is:

```<code>....
property=5000
property=null
java.lang.NumberFormatException: null
  at java.base/java.lang.Integer.parseInt(Integer.java:614)
  at java.base/java.lang.Integer.parseInt(Integer.java:770)
  at cl.ClientPoll.readProperties(ClientPoll.java:26)
  at cl.ClientPoll.run(ClientPoll.java:46)
property=6000
property=7000
....
</code>```

So when watching, you can either: skip on error and continue; or use other APIs so that the file being written is locked while writing.

Sample code

```<code>package cl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.Properties;

public class ClientPoll extends Thread {
  private void readProperties() {
    try {
      Path path = Paths.get("radar.properties");
      InputStream input =new FileInputStream(path.toString());
      Properties prop = new Properties();
      prop.load(input);
      String property = prop.getProperty("updateRate");
      System.out.println("property="+property);
      int updateRate = Integer.parseInt(property);
//      System.out.println(updateRate);
      input.close();
    } catch (IOException e) {
      e.printStackTrace(System.out);
    }
  }

  @Override
  public void run() {
    try {
      WatchService watcher = FileSystems.getDefault().newWatchService();
      Path directory = Paths.get(".");
      WatchKey watchKey = directory.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY);
      while (true) {
        WatchKey wk = watcher.take();
        for (WatchEvent<?> event : wk.pollEvents()) {
          Path changed = (Path) event.context();
          if (changed.toString().equals("radar.properties")) {
            try {
              readProperties();
            } catch (Exception e) {
              e.printStackTrace(System.out);
            }
          }
        }
        if (!watchKey.reset()) {
          break;
        }
      }
    } catch (IOException e) {
      e.printStackTrace(System.out);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }

  public static void main(String[] args) {
    new ClientPoll().start();
    new Writer().start();
  }
}

class Writer extends Thread {
  @Override
  public void run() {
    try {
      for (int i=0;i<10;i++) {
        File f = new File("radar.properties");
        FileWriter fw = new FileWriter(f);
        fw.write("updateRate="+i*1000);
        fw.close();
        sleep(1000L);
      }
    } catch (Exception e) {
      e.printStackTrace(System.out);
    }
    System.out.println("exit");
    System.exit(0);
  }
}
</code>```

Title: Java Properties class bug

Body:
I have this piece of code.

// On a thread
try {
    WatchService watcher = FileSystems.getDefault().newWatchService();
    Path directory = Paths.get("properties");
    WatchKey watchKey = directory.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY);
    while (true) {
        for (WatchEvent<?> event : watchKey.pollEvents()) {
            Path changed = (Path) event.context();
            if (changed.toString().equals("radar.properties")) {
                System.out.println("read call:");
                readProperties();
            }

        }

        if (!watchKey.reset()) {
            break;
        }
    }
} catch (IOException e) {
    FCSLogger.LOGGER.log(Level.SEVERE, "Exception while setting up WatchService", e);
}

// Method called by the above code

private void readProperties() {
    try {
        InputStream input = new FileInputStream(Paths.get("properties", "radar.properties").toString());
        Properties prop = new Properties();
        prop.load(input);
        updateRate = Integer.parseInt(prop.getProperty("updateRate"));
        System.out.println(updateRate);
        input.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

It returns the right result on the first call and then blocks the whole thread. I've isolated the bug to be in this method since everything else works flawlessly when there is no calling this method. I'm wondering what am I doing wrong here.
Snapshot of console output:

// First change of file:
read call:
10
read call:
10

// Second change of file:
read call:

// I keep changing but nothing happens:

Body:
It can be that readProperties throws NumberFormatException, and that causes your watcher thread to exit.

You could wrap calls to readProperties and catch exceptions; so that at least the watcher will keep watching in case of exceptions.

And you should use take, so that the watcher thread blocks. Your current solution causes 100% cpu usage.

See below the modified code. I added a writer thread to update the file, and (unsurprisingly?) readProperties can fail since we are accessing the file while it is being written. A possible output is:

....
property=5000
property=null
java.lang.NumberFormatException: null
  at java.base/java.lang.Integer.parseInt(Integer.java:614)
  at java.base/java.lang.Integer.parseInt(Integer.java:770)
  at cl.ClientPoll.readProperties(ClientPoll.java:26)
  at cl.ClientPoll.run(ClientPoll.java:46)
property=6000
property=7000
....

So when watching, you can either: skip on error and continue; or use other APIs so that the file being written is locked while writing.

Sample code

package cl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.Properties;

public class ClientPoll extends Thread {
  private void readProperties() {
    try {
      Path path = Paths.get("radar.properties");
      InputStream input =new FileInputStream(path.toString());
      Properties prop = new Properties();
      prop.load(input);
      String property = prop.getProperty("updateRate");
      System.out.println("property="+property);
      int updateRate = Integer.parseInt(property);
//      System.out.println(updateRate);
      input.close();
    } catch (IOException e) {
      e.printStackTrace(System.out);
    }
  }

  @Override
  public void run() {
    try {
      WatchService watcher = FileSystems.getDefault().newWatchService();
      Path directory = Paths.get(".");
      WatchKey watchKey = directory.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY);
      while (true) {
        WatchKey wk = watcher.take();
        for (WatchEvent<?> event : wk.pollEvents()) {
          Path changed = (Path) event.context();
          if (changed.toString().equals("radar.properties")) {
            try {
              readProperties();
            } catch (Exception e) {
              e.printStackTrace(System.out);
            }
          }
        }
        if (!watchKey.reset()) {
          break;
        }
      }
    } catch (IOException e) {
      e.printStackTrace(System.out);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }

  public static void main(String[] args) {
    new ClientPoll().start();
    new Writer().start();
  }
}

class Writer extends Thread {
  @Override
  public void run() {
    try {
      for (int i=0;i<10;i++) {
        File f = new File("radar.properties");
        FileWriter fw = new FileWriter(f);
        fw.write("updateRate="+i*1000);
        fw.close();
        sleep(1000L);
      }
    } catch (Exception e) {
      e.printStackTrace(System.out);
    }
    System.out.println("exit");
    System.exit(0);
  }
}


问:
How to fix this problem with clean method in forms.ModelForm?
I'm doing a application to upload Images. I need validation of one of two fields. By file or by url. I wrote such code, but the view method does not call clean_image in forms.py. Thanks for the help (sorry for my bad English)

forms.py

```<code>class UploadForm(forms.ModelForm):
    image = forms.ImageField(required=False)
    url = forms.CharField(max_length=64, required=False)

    class Meta:
        model = Image
        fields = (
            'image',
            'url'
        )

    def clean_image(self):
        image = self.cleaned_data.get('image')
        url = self.cleaned_data.get('url')
        if (image != None and url != '') or (image == None and url == ''):
            raise forms.ValidationError('Fill one field')

    def save(self):
        self.clean_image()
        new_image = Image.objects.create(
            image=self.cleaned_data.get('image'),
            url=self.cleaned_data.get('url')
        )
        return new_image
</code>```

views.py

```<code>def upload(request):
    if request.method == 'POST':
        upload_form = UploadForm(request.POST, request.FILES)
        if upload_form.is_valid():
            upload_form.save()
            return redirect('/')
    else:
        upload_form = UploadForm()
    context = {
        'form': upload_form,
    }
    return render(request, 'upload_page.html', context)
</code>```

答:
Maybe you can use clean() method:

```<code>def clean(self):
    cleaned_data = super().clean()
    image = cleaned_data.get('image')
    url = cleaned_data.get('url')
    if not image and not url:
        raise forms.ValidationError('Fill either url or image field')
    return cleaned_data
</code>```

And update template to show error:

```<code>{% if form.errors %}
    {% for error in form.non_field_errors %}
        <div class="alert alert-danger">
            <strong>{{ error|escape }}</strong>
        </div>
    {% endfor %}
{% endif %}
</code>```

Body:
I'm doing a application to upload Images. I need validation of one of two fields. By file or by url. I wrote such code, but the view method does not call clean_image in forms.py. Thanks for the help (sorry for my bad English)

forms.py

class UploadForm(forms.ModelForm):
    image = forms.ImageField(required=False)
    url = forms.CharField(max_length=64, required=False)

    class Meta:
        model = Image
        fields = (
            'image',
            'url'
        )

    def clean_image(self):
        image = self.cleaned_data.get('image')
        url = self.cleaned_data.get('url')
        if (image != None and url != '') or (image == None and url == ''):
            raise forms.ValidationError('Fill one field')

    def save(self):
        self.clean_image()
        new_image = Image.objects.create(
            image=self.cleaned_data.get('image'),
            url=self.cleaned_data.get('url')
        )
        return new_image

views.py

def upload(request):
    if request.method == 'POST':
        upload_form = UploadForm(request.POST, request.FILES)
        if upload_form.is_valid():
            upload_form.save()
            return redirect('/')
    else:
        upload_form = UploadForm()
    context = {
        'form': upload_form,
    }
    return render(request, 'upload_page.html', context)

Body:
Maybe you can use clean() method:

def clean(self):
    cleaned_data = super().clean()
    image = cleaned_data.get('image')
    url = cleaned_data.get('url')
    if not image and not url:
        raise forms.ValidationError('Fill either url or image field')
    return cleaned_data

And update template to show error:

{% if form.errors %}
    {% for error in form.non_field_errors %}
        <div class="alert alert-danger">
            <strong>{{ error|escape }}</strong>
        </div>
    {% endfor %}
{% endif %}


问:
How to change the colour of a button when clicked on? (Vue)
I'm trying to get a button that changes its color when pressed on it. When it is pressed again, it should change back to its original color. What am I doing wrong?

The Button in my template:

```<code><th><Button v-bind:class="{'white': !clicked, 'blue': clicked}" v-on:click ="!clicked" ></Button></th>

<script>
    export default {
        data: {

clicked: false
        }

    }

</script>

<style>
   .white {
       background-color: white;
       width: 200px;
       height: 200px;

   }
   .blue {
       width: 200px;
       height: 200px;
       background-color: blue;

   }

</style>
</code>```

答:
You should set clicked property explicitly by @click="clicked = !clicked":

  <Button
    v-bind:class="{'white': !clicked, 'blue': clicked}"
    v-on:click ="clicked = !clicked"
  />

```

Body:
I'm trying to get a button that changes its color when pressed on it. When it is pressed again, it should change back to its original color. What am I doing wrong?

The Button in my template:

<Button v-bind:class="{'white': !clicked, 'blue': clicked}" v-on:click ="!clicked" ></Button>

Body:
You should set clicked property explicitly by @click="clicked = !clicked":

<th>
  <Button
    v-bind:class="{'white': !clicked, 'blue': clicked}"
    v-on:click ="clicked = !clicked"
  />
</th>


问:
Uncaught TypeError: Cannot read property 'checked' of undefined Javascript
The first time the loop runs, there's no problem. The get's shown when the loop ends, and every other time the loop runs.
The .checked property works fine, to my knowledge, there's just the error...
Does someone know what to do about this?
My background in javascript isn't that broad, and I'm still learning.
Thanks you.

I have already tried .checked === true and
             .checked == checked
              ...

In the code snippet below dishes is an array of radiobuttons.

```<code>    for (i = 0; i <= dishes.length; i++) {
       if (dishes[i].checked) {
         switch (dishesClass) {
        .........
         }
       }
     }
</code>```

I expect no error in the console, but there are multiple. Every time the loop ends, the console states the same error.

Uncaught TypeError: Cannot read property 'checked' of undefined

答:
In your for loop you are testing if i is less than or equal to dishes.lengh. You just need to check if it is less than, since i starts from 0, as does array indexes in computing.

So just replace i <= dishes.length; with i < dishes.length;

Hope that helps

This code will work

```<code>for (i = 0; i < dishes.length; i++) {
   if (dishes[i].checked) {
     switch (dishesClass) {
    .........
     }
   }
 }
</code>```

This resource, on Loops and Iteration may help you.

Body:
The first time the loop runs, there's no problem. The get's shown when the loop ends, and every other time the loop runs.
The .checked property works fine, to my knowledge, there's just the error...
Does someone know what to do about this?
My background in javascript isn't that broad, and I'm still learning.
Thanks you.

I have already tried .checked === true and
             .checked == checked
              ...

In the code snippet below dishes is an array of radiobuttons.

    for (i = 0; i <= dishes.length; i++) {
       if (dishes[i].checked) {
         switch (dishesClass) {
        .........
         }
       }
     }

I expect no error in the console, but there are multiple. Every time the loop ends, the console states the same error.

Uncaught TypeError: Cannot read property 'checked' of undefined

Body:
In your for loop you are testing if i is less than or equal to dishes.lengh. You just need to check if it is less than, since i starts from 0, as does array indexes in computing.

So just replace i <= dishes.length; with i < dishes.length;

Hope that helps

This code will work

for (i = 0; i < dishes.length; i++) {
   if (dishes[i].checked) {
     switch (dishesClass) {
    .........
     }
   }
 }

This resource, on Loops and Iteration may help you.


问:
Make a phrase column out of columns with value of 1 in Pandas Dataframe
Let's say I have this dataset, I want to create a phrase column that adds a word for each column with value of 1...

```<code>    SINNOUVEAU  PERTETOTAL  CHANGGARAN  SOCLOCATIO  SINISAMEDI  NOMASCONDU  SINIREPET
0            1           0           0           0           0           1          0
1            0           1           0           0           0           1          0
2            0           0           1           0           0           1          0
</code>```

This is the dataframe for the phrase values for each column if set to 1:

```<code>          col                  phr
0  SINNOUVEAU     sinistre nouveau
1  PERTETOTAL         perte totale
2  CHANGGARAN  changement garantie
3  SOCLOCATIO     societe location
4  SINISAMEDI               samedi
5  NOMASCONDU        nom different
6   SINIREPET   sinistre repetitif
</code>```

So, for the dataframe above, this is the result I expect:

```<code>    SINNOUVEAU  PERTETOTAL  CHANGGARAN  SOCLOCATIO  SINISAMEDI  NOMASCONDU  SINIREPET  Phrase
0            1           0           0           0           0           1          0  sinistre nouveau, nom different
1            0           1           0           0           0           1          0  perte totale, nom different
2            0           0           1           0           0           1          0  changement garantie, nom different
</code>```

答:
Assuming the first dataset is named df and the second one as df1:
We take help of df.dot() like below:

```<code>m=df.rename(columns=df1.set_index('col')['phr'].to_dict())
df['Phrase']=m.dot(m.columns+',').str.rstrip(',')
print(df)
</code>```

```<code>   SINNOUVEAU  PERTETOTAL  CHANGGARAN  SOCLOCATIO  SINISAMEDI  NOMASCONDU  \
0           1           0           0           0           0           1
1           0           1           0           0           0           1
2           0           0           1           0           0           1

   SINIREPET                             Phrase
0          0     sinistre nouveau,nom different
1          0         perte totale,nom different
2          0  changement garantie,nom different
</code>```

Body:
Let's say I have this dataset, I want to create a phrase column that adds a word for each column with value of 1...

    SINNOUVEAU  PERTETOTAL  CHANGGARAN  SOCLOCATIO  SINISAMEDI  NOMASCONDU  SINIREPET
0            1           0           0           0           0           1          0
1            0           1           0           0           0           1          0
2            0           0           1           0           0           1          0

This is the dataframe for the phrase values for each column if set to 1:

          col                  phr
0  SINNOUVEAU     sinistre nouveau
1  PERTETOTAL         perte totale
2  CHANGGARAN  changement garantie
3  SOCLOCATIO     societe location
4  SINISAMEDI               samedi
5  NOMASCONDU        nom different
6   SINIREPET   sinistre repetitif

So, for the dataframe above, this is the result I expect:

    SINNOUVEAU  PERTETOTAL  CHANGGARAN  SOCLOCATIO  SINISAMEDI  NOMASCONDU  SINIREPET  Phrase
0            1           0           0           0           0           1          0  sinistre nouveau, nom different
1            0           1           0           0           0           1          0  perte totale, nom different
2            0           0           1           0           0           1          0  changement garantie, nom different

Body:
Assuming the first dataset is named df and the second one as df1:
We take help of df.dot() like below:

m=df.rename(columns=df1.set_index('col')['phr'].to_dict())
df['Phrase']=m.dot(m.columns+',').str.rstrip(',')
print(df)

   SINNOUVEAU  PERTETOTAL  CHANGGARAN  SOCLOCATIO  SINISAMEDI  NOMASCONDU  \
0           1           0           0           0           0           1
1           0           1           0           0           0           1
2           0           0           1           0           0           1

   SINIREPET                             Phrase
0          0     sinistre nouveau,nom different
1          0         perte totale,nom different
2          0  changement garantie,nom different


问:
API to set the timestamps on files & directories in btrfs
BTRFS files/directories contains the timestamps:

Creation (otime)

Modification (mtime)

Attribute modification (ctime)

Access (atime)

Is there some API where I could set these all these timestamps for a file? I googled a bit but haven't found anything yet.

Programming languages doesn't matter, I would expect there to be some C API, but python is fine too and would be nicer.

答:
From C, the mtime and atime can be set using utime(2) and its relatives.  utime(2) itself gives you seconds precision, utimes(2) has microseconds, and utimensat(2) gives you nanoseconds.  There are variants like futime if you have a file handle instead of a file name.

Python can provide the same via the os.utime function.

Traditionally it is not possible to arbitrarily modify the otime or ctime, other than by manually editing the raw filesystem.  I am not aware that Linux has provided any kernel API to modify them.  Of course, you can update the ctime to the current time by changing its status in some way, and you can update the otime to the current time by deleting and recreating the file.  In principle you can set them to a different time by changing the system clock first (if you are root), but this is likely to mess up lots of other stuff on the system and is probably a bad idea.


问:
How to get only one answer if there is no match after loop
My code has a for loop in array and has if statement, and I want to get only one answer if there is no match.

```<code>for (int i = 0; i < arr.Length; i++)
{
    if (arr[i].GetSomeValue() >= 1 && i].GetSomeValue() <= 5)
        Console.WriteLine(arr[i]);
    else
       Console.WriteLine("No data");
}
</code>```

However, I get these:

```<code>No data
No data
No data
No data
</code>```

I want only one "No data" if there is no match.
I tried adding

```<code>    else break;
}
Console.WriteLine("No data");
</code>```

But it does not work.

How do I get what I want?

答:
```<code>// Don't check the no data condition until after the loop
  int noData = -1;
    for (int i = 0; i < arr.Length; i++)
                {
                    if (arr[i].GetSomeValue() >= 1 && arr[i].GetSomeValue() <= 5) {
                        Console.WriteLine(arr[i]);
                        noData = 0;
                    }
                }
    if (noData == -1) {Console.WriteLine("No data");}
</code>```

Body:
My code has a for loop in array and has if statement, and I want to get only one answer if there is no match.

for (int i = 0; i < arr.Length; i++)
{
    if (arr[i].GetSomeValue() >= 1 && i].GetSomeValue() <= 5)
        Console.WriteLine(arr[i]);
    else
       Console.WriteLine("No data");
}

However, I get these:

No data
No data
No data
No data

I want only one "No data" if there is no match.
I tried adding

    else break;
}
Console.WriteLine("No data");

But it does not work.

How do I get what I want?


问:
Pythonic way to avoid a mountain of if...else statements?
This has come up several times recently and I'd like to deal with it better than I have been: I have a series of attributes that I'm cross referencing between an object and a dictionary.  If the value is different between them, I want to set the object.attribute to the dictionary['attribute'] value.  I also want to keep track of what's getting changed.

Now, my first thought is to just use an if else statement for every attribute, but after writing a few of these it's apparent that I'm re-writing the same code again and again.  There has to be a DRY way to do this, where I specify only the parts that are changing every time, and then loop through all the attributes.

In production code, there are 15 different attributes, but my example below will just use 2 for simplicity.  I have some idea about how to do this in a clever way, but I'm missing the final step of actually setting the object.attribute equal to the dictionary['attribute'] value.

```<code># Simulated data setup - not under my control IRL
class someClass:
    def __init__(self, name, version):
        self.name = name
        self.version = version

objA = someClass('Test1','1.1')
dictA = {'name':'Test1','revision':'1.2'}

# My code below

# option 1 - a series of for loops
def updateAttributesSimple(obj, adict, msg):
    if obj.name == adict['name']:
        msg.append('Name is the same')
    else:
        msg.append('Name was updated from %s to %s' % (obj.name, adict['name']))
        obj.name = adict['name']

    if obj.version == adict['revision']:
        msg.append('Version is the same')
    else:
        msg.append('Version was updated from %s to %s' % (obj.version, adict['revision']))
        obj.version = adict['revision']

# option 2 - trying to be clever about this
def updateAttributesClever(obj, adict, msg):
    attributeList = (('Name', obj.name, adict['name']),
                     ('Version', obj.version, adict['revision']))

    for valTuple in attributeList:
        if valTuple[1] == valTuple[2]:
            msg.append('%s is the same' % (valTuple[0]))
        else:
            msg.append('%s was updated from %s to %s' % (valTuple[0], valTuple[1], valTuple[2]))
            # code to set valTuple[1] = valTuple[2] goes here, but what is it?
            # valTuple[1] = valTuple[2] attempts to set the desired value to a string, rather than the attribute of obj itself

msg = ['Updating Attributes simple way:']
updateAttributesSimple(objA, dictA, msg)
print '\n\t'.join(msg)

#reset data
objA = someClass('Test1','1.1')
dictA = {'name':'Test1','revision':'1.2'}

msg = ['Updating Attributes clever way:']
updateAttributesClever(objB, dictB, msg)
print '\n\t'.join(msg)
</code>```

The idea being that this way, whenever I need to add another attribute, I can just update the list of attributes being inspected and the rest of the code is already written.  What's the Pythonic way to accomplish this?

答:
setattr() is what you're looking for:

```<code>attributeList = (('Name',    'name',    'name'),
                 ('Version', 'version', 'revision'))

for title, obj_attribute, dict_key in attributeList:
    obj_value = getattr(obj, obj_attribute)
    adict_value = adict[dict_key]

    if obj_value == adict_value:
        msg.append('%s is the same' % (obj_value))
    else:
        msg.append('%s was updated from %s to %s' % (title, obj_value, adict_value))

        setattr(obj, obj_attribute, adict_value)
</code>```

Body:
This has come up several times recently and I'd like to deal with it better than I have been: I have a series of attributes that I'm cross referencing between an object and a dictionary.  If the value is different between them, I want to set the object.attribute to the dictionary['attribute'] value.  I also want to keep track of what's getting changed.

Now, my first thought is to just use an if else statement for every attribute, but after writing a few of these it's apparent that I'm re-writing the same code again and again.  There has to be a DRY way to do this, where I specify only the parts that are changing every time, and then loop through all the attributes.

In production code, there are 15 different attributes, but my example below will just use 2 for simplicity.  I have some idea about how to do this in a clever way, but I'm missing the final step of actually setting the object.attribute equal to the dictionary['attribute'] value.

# Simulated data setup - not under my control IRL
class someClass:
    def __init__(self, name, version):
        self.name = name
        self.version = version

objA = someClass('Test1','1.1')
dictA = {'name':'Test1','revision':'1.2'}

# My code below

# option 1 - a series of for loops
def updateAttributesSimple(obj, adict, msg):
    if obj.name == adict['name']:
        msg.append('Name is the same')
    else:
        msg.append('Name was updated from %s to %s' % (obj.name, adict['name']))
        obj.name = adict['name']

    if obj.version == adict['revision']:
        msg.append('Version is the same')
    else:
        msg.append('Version was updated from %s to %s' % (obj.version, adict['revision']))
        obj.version = adict['revision']

# option 2 - trying to be clever about this
def updateAttributesClever(obj, adict, msg):
    attributeList = (('Name', obj.name, adict['name']),
                     ('Version', obj.version, adict['revision']))

    for valTuple in attributeList:
        if valTuple[1] == valTuple[2]:
            msg.append('%s is the same' % (valTuple[0]))
        else:
            msg.append('%s was updated from %s to %s' % (valTuple[0], valTuple[1], valTuple[2]))
            # code to set valTuple[1] = valTuple[2] goes here, but what is it?
            # valTuple[1] = valTuple[2] attempts to set the desired value to a string, rather than the attribute of obj itself

msg = ['Updating Attributes simple way:']
updateAttributesSimple(objA, dictA, msg)
print '\n\t'.join(msg)

#reset data
objA = someClass('Test1','1.1')
dictA = {'name':'Test1','revision':'1.2'}

msg = ['Updating Attributes clever way:']
updateAttributesClever(objB, dictB, msg)
print '\n\t'.join(msg)

The idea being that this way, whenever I need to add another attribute, I can just update the list of attributes being inspected and the rest of the code is already written.  What's the Pythonic way to accomplish this?

Body:
setattr() is what you're looking for:

attributeList = (('Name',    'name',    'name'),
                 ('Version', 'version', 'revision'))

for title, obj_attribute, dict_key in attributeList:
    obj_value = getattr(obj, obj_attribute)
    adict_value = adict[dict_key]

    if obj_value == adict_value:
        msg.append('%s is the same' % (obj_value))
    else:
        msg.append('%s was updated from %s to %s' % (title, obj_value, adict_value))

        setattr(obj, obj_attribute, adict_value)


问:
Swift 4.2 parse json to use it on UIPickerview
I want to use a json to show a picker view with one field of the json

```<code>data = {
        account = {
             id=0;
             accountNumber:534534535;
             institution:"bank1";
             balance:800.3;
          };
        account = {
                 id=1;
                 accountNumber:8353454535;
                 institution:"bank2";
                 balance:1200.87;
              }
        account = {
                 id=2;
                 accountNumber:31231231;
                 institution:"bank3";
                 balance:150.3;
              }
    };
</code>```

For the json of accounts I've tried

```<code>var accounts:[AccountResponse] = []

let jsonAccounts = response["data"]
                let userAccounts = jsonAccounts["accounts"]
                for acc in userAccounts{
                    accounts = AccountResponse(accountResponse: acc)//doesn't work
                }
</code>```

don't know how to use it as array to set it on the UIPickerView, wants to display bank1,bank2,bank3

```<code>func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return accounts.count
    }
    func pickerView(pickerView: UIPickerView, titleForRow row: Int) -> String? {
        return accounts[row]
    }
</code>```

Main.storyboard

the purpose is to allow the user select the name and display the balance on the texview, also I would like to have the id stored in a variable

I'm really new in swift, Previously I'm consuming a service and it returns json, before someone helped me with the dependency SwiftyJSON. I used it to get user information.

```<code>data =     {
    email = "vpozo@email.com";
    fullName = "Victor Pozo";
    id = 6;
    phoneNumber = 099963212;
    token = 6;
};
</code>```

Now I can have it as an Object using

```<code>      let userJson = response["data"]
      let user = UserResponse(userResponse:userJson)
</code>```

答:
You are not saving the accounts anywhere at the moment.

```<code>accounts = AccountResponse(accountResponse: acc)
</code>```

should be something like

```<code>accounts.append(AccountResponse(accountResponse: acc))
</code>```

Body:
I want to use a json to show a picker view with one field of the json

data = {
        account = {
             id=0;
             accountNumber:534534535;
             institution:"bank1";
             balance:800.3;
          };
        account = {
                 id=1;
                 accountNumber:8353454535;
                 institution:"bank2";
                 balance:1200.87;
              }
        account = {
                 id=2;
                 accountNumber:31231231;
                 institution:"bank3";
                 balance:150.3;
              }
    };

For the json of accounts I've tried

var accounts:[AccountResponse] = []

let jsonAccounts = response["data"]
                let userAccounts = jsonAccounts["accounts"]
                for acc in userAccounts{
                    accounts = AccountResponse(accountResponse: acc)//doesn't work
                }

don't know how to use it as array to set it on the UIPickerView, wants to display bank1,bank2,bank3

func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return accounts.count
    }
    func pickerView(pickerView: UIPickerView, titleForRow row: Int) -> String? {
        return accounts[row]
    }

Main.storyboard

the purpose is to allow the user select the name and display the balance on the texview, also I would like to have the id stored in a variable

I'm really new in swift, Previously I'm consuming a service and it returns json, before someone helped me with the dependency SwiftyJSON. I used it to get user information.

data =     {
    email = "vpozo@email.com";
    fullName = "Victor Pozo";
    id = 6;
    phoneNumber = 099963212;
    token = 6;
};

Now I can have it as an Object using

      let userJson = response["data"]
      let user = UserResponse(userResponse:userJson)

Body:
You are not saving the accounts anywhere at the moment.

accounts = AccountResponse(accountResponse: acc)

should be something like

accounts.append(AccountResponse(accountResponse: acc))