问:
How to get Woocommerce Variation ID?
I've already had this code on functions.php

This code is to add a new field on each product variation to have datetime input field, so variations would automatically expired when the current date is past the input date.

```<code>// Add Variation Settings
add_action( 'woocommerce_product_after_variable_attributes', 'variation_settings_fields', 10, 3 );

// Save Variation Settings
add_action( 'woocommerce_save_product_variation', 'save_variation_settings_fields', 10, 2 );

//Create New fields for Variations
function variation_settings_fields( $loop, $variation_data, $variation ) {
    // Text Field
    woocommerce_wp_text_input(
        array(
            'id'          => '_text_field_date_expire[' . $variation->ID . ']',
            'class'       => '_text_field_date_expire',
            'type'        => 'datetime-local',
            'label'       => __( 'Date of Expiration', 'woocommerce' ),
            'placeholder' => '',
            'desc_tip'    => 'true',
            'description' => __( 'Expiration of Each Product Variation', 'woocommerce' ),
            'value'       => get_post_meta( $variation->ID, '_text_field_date_expire', true )
        )
    );
}

//Save New Fields for Variation
function save_variation_settings_fields( $post_id ) {
    // Text Field
    $text_field = $_POST['_text_field_date_expire'][ $post_id ];
    if( ! empty( $text_field ) ) {
        update_post_meta( $post_id, '_text_field_date_expire', esc_attr( $text_field ) );
    }
}
</code>```

This is to add a new field on each variation of Wocommerce.

What I am trying to do is to get each "_text_field_date_expire" meta so I could delete expired variation for each of the products..

How do I get each woocommerce variation ID on functions.php so I could add a rule that it will expire when it is already past the current date right now?

```<code>var_dump(get_post_meta( $variation_id , '_text_field_date_expire', true ));
</code>```

This code is the one that I will use to get the datetime field, but not sure how I could get each $variation_id field?

答:
In WooCommerce 3+, it's $variation->get_id() from $variation function argument, which is an instance of the WC_Product_Variation.

The method get_id() is inherited from WC_Data class.

So in your code it should be instead:

```<code>'id' => '_text_field_date_expire[' . $variation->get_id() . ']',
</code>```

Since WooCommerce 3, All WC_Product properties can't be accessed directly. Instead, you need to use the available methods.

Also in your hooked function save_variation_settings_fields() you are declaring 2 arguments, so there is one missing. It should be:

```<code>//Save New Fields for Variation// Save Variation Settings
add_action( 'woocommerce_save_product_variation', 'save_variation_settings_fields', 10, 2 );

function save_variation_settings_fields( $variation_id, $i ) {
    // Text Field
    $text_field = $_POST['_text_field_date_expire'][ $variation_id ];
    if( ! empty( $text_field ) ) {
        update_post_meta( $variation_id, '_text_field_date_expire', esc_attr( $text_field ) );
    }
}
</code>```

See the source code for woocommerce_save_product_variation action hook

Title: How to get Woocommerce Variation ID?

Body:
I've already had this code on functions.php

This code is to add a new field on each product variation to have datetime input field, so variations would automatically expired when the current date is past the input date.

// Add Variation Settings
add_action( 'woocommerce_product_after_variable_attributes', 'variation_settings_fields', 10, 3 );

// Save Variation Settings
add_action( 'woocommerce_save_product_variation', 'save_variation_settings_fields', 10, 2 );

//Create New fields for Variations
function variation_settings_fields( $loop, $variation_data, $variation ) {
    // Text Field
    woocommerce_wp_text_input(
        array(
            'id'          => '_text_field_date_expire[' . $variation->ID . ']',
            'class'       => '_text_field_date_expire',
            'type'        => 'datetime-local',
            'label'       => __( 'Date of Expiration', 'woocommerce' ),
            'placeholder' => '',
            'desc_tip'    => 'true',
            'description' => __( 'Expiration of Each Product Variation', 'woocommerce' ),
            'value'       => get_post_meta( $variation->ID, '_text_field_date_expire', true )
        )
    );
}

//Save New Fields for Variation
function save_variation_settings_fields( $post_id ) {
    // Text Field
    $text_field = $_POST['_text_field_date_expire'][ $post_id ];
    if( ! empty( $text_field ) ) {
        update_post_meta( $post_id, '_text_field_date_expire', esc_attr( $text_field ) );
    }
}

This is to add a new field on each variation of Wocommerce.

What I am trying to do is to get each "_text_field_date_expire" meta so I could delete expired variation for each of the products..

How do I get each woocommerce variation ID on functions.php so I could add a rule that it will expire when it is already past the current date right now?

var_dump(get_post_meta( $variation_id , '_text_field_date_expire', true ));

This code is the one that I will use to get the datetime field, but not sure how I could get each $variation_id field?

Body:
In WooCommerce 3+, it's $variation->get_id() from $variation function argument, which is an instance of the WC_Product_Variation.

The method get_id() is inherited from WC_Data class.

So in your code it should be instead:

'id' => '_text_field_date_expire[' . $variation->get_id() . ']',

Since WooCommerce 3, All WC_Product properties can't be accessed directly. Instead, you need to use the available methods.

Also in your hooked function save_variation_settings_fields() you are declaring 2 arguments, so there is one missing. It should be:

//Save New Fields for Variation// Save Variation Settings
add_action( 'woocommerce_save_product_variation', 'save_variation_settings_fields', 10, 2 );

function save_variation_settings_fields( $variation_id, $i ) {
    // Text Field
    $text_field = $_POST['_text_field_date_expire'][ $variation_id ];
    if( ! empty( $text_field ) ) {
        update_post_meta( $variation_id, '_text_field_date_expire', esc_attr( $text_field ) );
    }
}

See the source code for woocommerce_save_product_variation action hook


来源: stackexchange

问:
What is BUCKET_ID in MediaStore?
I was browsing through some code that queries the MediaStore.Images content provider and uses a column named BUCKET_ID:

```<code>Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String projection[] = {
    "DISTINCT " + MediaStore.Images.Media.BUCKET_DISPLAY_NAME,
    MediaStore.Images.Media.BUCKET_ID,
    MediaStore.Images.Media.DATE_TAKEN,
    MediaStore.Images.Media.DATA
};
String BUCKET_GROUP_BY = "1) GROUP BY 1,(2";
String BUCKET_ORDER_BY = "MAX(datetaken) DESC";
Cursor imagecursor = getContentResolver().query(uri, projection, BUCKET_GROUP_BY, null, BUCKET_ORDER_BY);
</code>```

In general, what do these columns represent? Can anyone explain with examples?(The docs have a one-liner about these columns that explains quite less)

答:
Docs are vastly unclear on this and the above answer is a copy-paste from the docs. Anyway, I have found the answer from the source of Gallery 3D in form of comments:

```<code>    // BUCKET_DISPLAY_NAME is a string like "Camera" which is the directory
    // name of where an image or video is in. BUCKET_ID is a hash of the path
    // name of that directory (see computeBucketValues() in MediaProvider for
    // details). MEDIA_TYPE is video, image, audio, etc.
    //
    // The "albums" are not explicitly recorded in the database, but each image
    // or video has the two columns (BUCKET_ID, MEDIA_TYPE). We define an
    // "album" to be the collection of images/videos which have the same value
    // for the two columns.
</code>```

and here is the computeBucketValues() for reference:

```<code>/**
     * @param data The input path
     * @param values the content values, where the bucked id name and bucket display name are updated.
     *
     */
    private static void computeBucketValues(String data, ContentValues values) {
        File parentFile = new File(data).getParentFile();
        if (parentFile == null) {
            parentFile = new File("/");
        }

        // Lowercase the path for hashing. This avoids duplicate buckets if the
        // filepath case is changed externally.
        // Keep the original case for display.
        String path = parentFile.toString().toLowerCase();
        String name = parentFile.getName();

        // Note: the BUCKET_ID and BUCKET_DISPLAY_NAME attributes are spelled the
        // same for both images and video. However, for backwards-compatibility reasons
        // there is no common base class. We use the ImageColumns version here
        values.put(ImageColumns.BUCKET_ID, path.hashCode());
        values.put(ImageColumns.BUCKET_DISPLAY_NAME, name);
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: What is BUCKET_ID in MediaStore?

Body:
I was browsing through some code that queries the MediaStore.Images content provider and uses a column named BUCKET_ID:

Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String projection[] = {
    "DISTINCT " + MediaStore.Images.Media.BUCKET_DISPLAY_NAME,
    MediaStore.Images.Media.BUCKET_ID,
    MediaStore.Images.Media.DATE_TAKEN,
    MediaStore.Images.Media.DATA
};
String BUCKET_GROUP_BY = "1) GROUP BY 1,(2";
String BUCKET_ORDER_BY = "MAX(datetaken) DESC";
Cursor imagecursor = getContentResolver().query(uri, projection, BUCKET_GROUP_BY, null, BUCKET_ORDER_BY);

In general, what do these columns represent? Can anyone explain with examples?(The docs have a one-liner about these columns that explains quite less)

Body:
Docs are vastly unclear on this and the above answer is a copy-paste from the docs. Anyway, I have found the answer from the source of Gallery 3D in form of comments:

    // BUCKET_DISPLAY_NAME is a string like "Camera" which is the directory
    // name of where an image or video is in. BUCKET_ID is a hash of the path
    // name of that directory (see computeBucketValues() in MediaProvider for
    // details). MEDIA_TYPE is video, image, audio, etc.
    //
    // The "albums" are not explicitly recorded in the database, but each image
    // or video has the two columns (BUCKET_ID, MEDIA_TYPE). We define an
    // "album" to be the collection of images/videos which have the same value
    // for the two columns.

and here is the computeBucketValues() for reference:

/**
     * @param data The input path
     * @param values the content values, where the bucked id name and bucket display name are updated.
     *
     */
    private static void computeBucketValues(String data, ContentValues values) {
        File parentFile = new File(data).getParentFile();
        if (parentFile == null) {
            parentFile = new File("/");
        }

        // Lowercase the path for hashing. This avoids duplicate buckets if the
        // filepath case is changed externally.
        // Keep the original case for display.
        String path = parentFile.toString().toLowerCase();
        String name = parentFile.getName();

        // Note: the BUCKET_ID and BUCKET_DISPLAY_NAME attributes are spelled the
        // same for both images and video. However, for backwards-compatibility reasons
        // there is no common base class. We use the ImageColumns version here
        values.put(ImageColumns.BUCKET_ID, path.hashCode());
        values.put(ImageColumns.BUCKET_DISPLAY_NAME, name);
}


问:
cx_Freeze - The appdirs package is required
I`m trying to convert a .py script to an .exe

cx_Freeze compiles the exe succesfully. However when I run the exe file it throws this error:

ImportError: The 'appdirs' package is required; normally this is bundled with this package so if you get this warning, consult the packager of your distribution

Here is my setup.py

```<code>from cx_Freeze import setup, Executable

setup(
    name = "dbx_sharelink" ,
    version = "0.1" ,
    description = " " ,
    executables = [Executable("dbx_sharelink.py")]  ,
)
</code>```

Source code Python script

```<code>import sys
import dropbox
import pandas as pd
import sys
import os

dbx = dropbox.Dropbox('xxxxxxxxxxxxxxxxx')

def getSharedLink(full_path):
    try:
        link = dbx.sharing_create_shared_link(full_path).url
    except dropbox.exceptions.ApiError as err:
        print('*** API error', err)
        return None
    return link

print(sys.argv[1])
link = getSharedLink("/A_DATA/data")

df = pd.DataFrame([{'link':link}])
df.to_clipboard(index=False,header=False)

os.system("pause")
</code>```

How to resolve this error?

答:
I was having the same problem..
Add options parameter to the setup.py file like this:

```<code>setup (name="MyAPP",
       version="0.1",
       description = "My GUI application!",
       options = {'build_exe': {'packages':packages}},
       .
       .
       .)
</code>```

under packages put(packages should come before the setup):

```<code>packages = ['pkg_resources._vendor']
</code>```

(you can add more packages if you have similar problems like this one..)

you can read more on the options here: http://cx-freeze.readthedocs.io/en/latest/distutils.html#build-exe

This solved the problem for me!

ContentLicense: CC BY-SA 4.0

Body:
I`m trying to convert a .py script to an .exe

cx_Freeze compiles the exe succesfully. However when I run the exe file it throws this error:

ImportError: The 'appdirs' package is required; normally this is bundled with this package so if you get this warning, consult the packager of your distribution

Here is my setup.py

from cx_Freeze import setup, Executable

setup(
    name = "dbx_sharelink" ,
    version = "0.1" ,
    description = " " ,
    executables = [Executable("dbx_sharelink.py")]  ,
)

Source code Python script

import sys
import dropbox
import pandas as pd
import sys
import os

dbx = dropbox.Dropbox('xxxxxxxxxxxxxxxxx')

def getSharedLink(full_path):
    try:
        link = dbx.sharing_create_shared_link(full_path).url
    except dropbox.exceptions.ApiError as err:
        print('*** API error', err)
        return None
    return link

print(sys.argv[1])
link = getSharedLink("/A_DATA/data")

df = pd.DataFrame([{'link':link}])
df.to_clipboard(index=False,header=False)

os.system("pause")

How to resolve this error?

Body:
I was having the same problem..
Add options parameter to the setup.py file like this:

setup (name="MyAPP",
       version="0.1",
       description = "My GUI application!",
       options = {'build_exe': {'packages':packages}},
       .
       .
       .)

under packages put(packages should come before the setup):

packages = ['pkg_resources._vendor']

(you can add more packages if you have similar problems like this one..)

you can read more on the options here: http://cx-freeze.readthedocs.io/en/latest/distutils.html#build-exe

This solved the problem for me!


问:
Python- Function object in class
```<code>class new:
    i=1
    def __init__(self):
        name='sakthi'

    def add(self,one,two):
         return one+two

k=new.add

print(k)
</code>```

When I execute the above program. I get function new.add at 0x0068E270 as output.

Can anyone help me to understand, what has happened and what kind of operation can I do with value k.

答: function new.add at 0x0068E270 In CPython, will be the address of k. Since k is just a function you can still do something like print(k('foo', 1, 2)) that Will print 5

Title: Python- Function object in class

Body:
class new:
    i=1
    def __init__(self):
        name='sakthi'

    def add(self,one,two):
         return one+two

k=new.add

print(k)

When I execute the above program. I get function new.add at 0x0068E270 as output.

Can anyone help me to understand, what has happened and what kind of operation can I do with value k.


问:
How i loop through my class object add in hashtable object
```<code>// this is my class object
Friend f1 = new Friend("Nazir",24);
Friend f2 = new Friend("Hamza", 24);
Friend f3 = new Friend("Abdullah", 23);

Hashtable myhash = new Hashtable();

// add this object in hashtable object
myhash.Add("13b-049-bs",f1);
myhash.Add("13b-034-bs", f1);
myhash.Add("13b-038-bs", f1);

foreach (Friend item in myhash)
{
    Console.WriteLine("Key {0}\tName {1}\tAge {2}",item.Name,item.Age,myhash.Keys);
}
</code>```

I got this error:

An unhandled exception of type 'System.InvalidCastException' occurred in HashTableDemo.exe

答:
try out , as data store in hash tbale is not type of Friend object youare getting error, if you dont know type than make use of var that will resolve error

```<code>  foreach (var  item in myhash)
        {
           string key = de.Key.ToString();
           Friend val  = (Friend) item.Value;
           Console.WriteLine("Key {0}\tName {1}\tAge {2}", key, val.Name, val.Age );
        }
</code>```

or you can do like this

```<code>foreach(DictionaryEntry de in myHashtable)
{
      string key = de.Key.ToString();
   Friend val  = (Friend) de.Value;
   Console.WriteLine("Key {0}\tName {1}\tAge {2}", key, val.Name, val.Age );
}
</code>```

Read out : Hashtable Class

Body:
// this is my class object
Friend f1 = new Friend("Nazir",24);
Friend f2 = new Friend("Hamza", 24);
Friend f3 = new Friend("Abdullah", 23);

Hashtable myhash = new Hashtable();

// add this object in hashtable object
myhash.Add("13b-049-bs",f1);
myhash.Add("13b-034-bs", f1);
myhash.Add("13b-038-bs", f1);

foreach (Friend item in myhash)
{
    Console.WriteLine("Key {0}\tName {1}\tAge {2}",item.Name,item.Age,myhash.Keys);
}

I got this error:

An unhandled exception of type 'System.InvalidCastException' occurred in HashTableDemo.exe

Body:
try out , as data store in hash tbale is not type of Friend object youare getting error, if you dont know type than make use of var that will resolve error

  foreach (var  item in myhash)
        {
           string key = de.Key.ToString();
           Friend val  = (Friend) item.Value;
           Console.WriteLine("Key {0}\tName {1}\tAge {2}", key, val.Name, val.Age );
        }

or you can do like this

foreach(DictionaryEntry de in myHashtable)
{
      string key = de.Key.ToString();
   Friend val  = (Friend) de.Value;
   Console.WriteLine("Key {0}\tName {1}\tAge {2}", key, val.Name, val.Age );
}

Read out : Hashtable Class


问:
menu's dropdown occupies only the navbar space + hover not working
I want to create a dropdown nav menu with a modal like box appearing on hover.

Here in my example, Products heading needs to open 4 columns of subheadings that align themselves into a bootstrap like grid.

I am close to the result but I am facing a couple of hurdles: my hover does not seem to work. Also, my subheading appears only within the perimeter of my navbar - whereas I want it to appear a little below the navbar, with some padding.

I looked at these 2 examples but they did not help me:

stackoverflow reference 1

stackoverflow reference 2

Please find the code and guide me in the right direction:

.topnav {
  background-color: white;
  overflow: hidden;
 }

 .topnav a {
  float: left;
  display: block;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
  color: grey;
 }
 .nav {
  list-style: none;
  display: -webkit-flex;
  -webkit-flex-direction: row;
  -webkit-justify-content: space-between;
  -webkit-flex-wrap: wrap;
 }
 .nav li:first-child {
  margin-right: auto;
 }

 .nav li {
  position: relative;
 }

 .dropdown {
  position: relative;
  display: inline-block;
 }

 .dropdown-content {
  position: absolute;
  background-color: #f9f9f9;
  min-width: 560px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 20;
  border: 1px solid white;
  padding: 80px;
  height: 220px;
 }

 .dropdown-content ul {
  display: block;
 }

 .arrow-up {
  width: 0;
  height: 0;
  border-left: 5px solid transparent;
  border-right: 5px solid transparent;
  border-bottom: 5px solid black;
 }

 .noshow {
  display: none;
 }

 .dropdown-content:hover .noshow {
  display: block
 }

 .subheading {
  font-weight: 700;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav class="topnav">
    <ul class="nav">
     <li> Title</li>
     <li>

      Products
      <div class="dropdown-content arrow-up noshow">
          <ul class="column large-3 each-column">
           <li class="subheading">subheading</li>
            <li>
             subheading1
            </li>
            <li>
             subheading2
            </li>
                        <li>
             subheading3
            </li>
         </ul>
      </div>
     </li>
     <li>link2</li>
     <li>link3</li>
     <li><img src="http://lorempixel.com/30/30/" width="30" height="30" alt="User Account Icon"></li>
    </ul>
   </nav></code>```

答:
```<code>    <!DOCTYPE html>
<html>

<head>
    <style>
    .left_menu {
        float: left;
        width: 50%;
    }

    .right_menu {
        float: left;
        width: 50%;
    }

    .right_menu ul {
        float: right;
    }

    ul {
        list-style-type: none;
        margin: 0;
        padding: 0;
        overflow: hidden;
        background-color: white;
    }

    li {
        float: left;
    }

    li a,
    .dropbtn {
        display: inline-block;
        color: grey;
        text-align: center;
        padding: 14px 16px;
        text-decoration: none;
    }

    li a:hover,
    .dropdown:hover .dropbtn {
        /* background-color: red;*/
        /*color: white;*/
    }

    li.dropdown {
        display: inline-block;
    }

    .dropdown-content {
        display: none;
        position: absolute;
        background-color: #f9f9f9;
        min-width: 160px;
        box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
        z-index: 1;
    }

    .dropdown-content a {
        color: black;
        padding: 12px 16px;
        text-decoration: none;
        display: block;
        text-align: left;
    }

    .dropdown-content a:hover {
        background-color: #f1f1f1;
    }

    .dropdown:hover .dropdown-content {
        display: block;
    }
    </style>
</head>

<body>
    <div class="left_menu">
        <ul>
            <li><a href="">Title</a></li>
        </ul>
    </div>
    <div class="right_menu" style="float: left; width: 50%">
        <ul>
            <li class="dropdown">
                <a href="javascript:void(0)" class="dropbtn">Product</a>
                <div class="dropdown-content">
</code>```

Body:
I want to create a dropdown nav menu with a modal like box appearing on hover.

Here in my example, Products heading needs to open 4 columns of subheadings that align themselves into a bootstrap like grid.

I am close to the result but I am facing a couple of hurdles: my hover does not seem to work. Also, my subheading appears only within the perimeter of my navbar - whereas I want it to appear a little below the navbar, with some padding.

I looked at these 2 examples but they did not help me:

stackoverflow reference 1

stackoverflow reference 2

Please find the code and guide me in the right direction:

.topnav {
  background-color: white;
  overflow: hidden;
 }

 .topnav a {
  float: left;
  display: block;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
  color: grey;
 }
 .nav {
  list-style: none;
  display: -webkit-flex;
  -webkit-flex-direction: row;
  -webkit-justify-content: space-between;
  -webkit-flex-wrap: wrap;
 }
 .nav li:first-child {
  margin-right: auto;
 }

 .nav li {
  position: relative;
 }

 .dropdown {
  position: relative;
  display: inline-block;
 }

 .dropdown-content {
  position: absolute;
  background-color: #f9f9f9;
  min-width: 560px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 20;
  border: 1px solid white;
  padding: 80px;
  height: 220px;
 }

 .dropdown-content ul {
  display: block;
 }

 .arrow-up {
  width: 0;
  height: 0;
  border-left: 5px solid transparent;
  border-right: 5px solid transparent;
  border-bottom: 5px solid black;
 }

 .noshow {
  display: none;
 }

 .dropdown-content:hover .noshow {
  display: block
 }

 .subheading {
  font-weight: 700;
 }

 Title

      Products

subheading

             subheading1

             subheading2

             subheading3

link2

link3


问:
Why I user imageview and Change Recurce it,I get "out of memory"Error
I Change Image view  For 19 Times In switch And Get This Error
I Change It with Button Click And Change Resource of Image view
When I Debug It I Get Out Of Memory Error</p>

答:
firstly reduce your image size as compare to normal device and use  "/drawable-nodpi" folder instead of "/drawable" folder

the real problem was the "/drawable" folder! I had all the pictures in "/drawable" generic folder that is considered by the system like "/drawable/mdpi", so when I were running in devices with hdpi or more the images were resized, and became too big which cause OutOfMemoryException!

Now i'm using "/drawable-nodpi" to store my images. This folder works like "/drawable" but the images are never resized!


问:
sum of amount not working by using ajax response
I try this format but its not working

**

```<code>"name": [{
  "id": 3,
  "qty": 2
}, {
  "id": 4,
  "qty": 5
}]
</code>```

**
This is my function once after get response on keyup qty textbox i want to add all amount in one textbox and show all entered value id and qty in above mention format

```<code>function _getPriceCalculation() {
            var sum = 0;
            $.ajax({
                type: "GET",
                url: $('#categoryList').val(),
                dataType: 'json',
                success: function(data) {
                    $.each(data, function(index, item) {
                        $('<div id="price_calculation"><div class="col-lg-4 main"><input type="text" value="'+item.name+'" readonly class="form-control"/></div><div class="col-lg-4 main" style="display:none;"><input type="text" name="id" id="price-'+item.id+'" value="'+item.price+'" readonly class="form-control" onkeypress="return isNumber(event)"/></div><div class="col-lg-4 main"><input type="text" value="" name="qty" id="qty-'+item.id+'" class="form-control qty" onkeypress="return isNumber(event)"/></div><div class="col-lg-4 main"><input type="text" name="amount" id="amount-'+item.id+'" value="" readonly class="form-control amount" onkeypress="return isNumber(event)"/></div>').appendTo("#price-calculation-view");
                        $("#qty-"+item.id).keyup(function(){
                            var qty = $("#qty-"+item.id).val();
                            var price = $("#price-"+item.id).val();
                            var total = qty * price;
                            $("#amount-"+item.id).val(total);
                        });
                    });
                }
            });

        }

$(document).on("keyup", "input[name='qty']", function() {
    //$('input[name="qty"]').change(function(){
       // alert();
      var name = [];
      $('.main').each(function(index,item){
        var obj={};
        obj.id = $(item).find('input[name="id"]').val();
        obj.qty = $(item).find('input[name="qty"]').val();
        name.push(obj)
      });
      console.log(name);
});
</code>```

How to achieve this ?

答:
$("#qty-"+item.id) DOM elements are added dynamically on the page.

You have to use event delegation for elements which were added dynamically.

You should bind keyup event handler using .on() method.

Event delegation allows us to attach a single event listener, to a
  parent element, that will fire for all descendants matching a
  selector, whether those descendants exist now or are added in the
  future.

```<code>$(document).on('keyup','#qty-'+item.id, function(){
     var qty = $("#qty-"+item.id).val();
     var price = $("#price-"+item.id).val();
     var total = qty * price;
     $("#amount-"+item.id).val(total);
});
</code>```

Body:
I try this format but its not working

**

"name": [{
  "id": 3,
  "qty": 2
}, {
  "id": 4,
  "qty": 5
}]

**
This is my function once after get response on keyup qty textbox i want to add all amount in one textbox and show all entered value id and qty in above mention format

function _getPriceCalculation() {
            var sum = 0;
            $.ajax({
                type: "GET",
                url: $('#categoryList').val(),
                dataType: 'json',
                success: function(data) {
                    $.each(data, function(index, item) {
                        $('

<input type="text" value="'+item.name+'" readonly class="form-control"/>

<input type="text" name="id" id="price-'+item.id+'" value="'+item.price+'" readonly class="form-control" onkeypress="return isNumber(event)"/>

<input type="text" value="" name="qty" id="qty-'+item.id+'" class="form-control qty" onkeypress="return isNumber(event)"/>

<input type="text" name="amount" id="amount-'+item.id+'" value="" readonly class="form-control amount" onkeypress="return isNumber(event)"/>
').appendTo("#price-calculation-view");
                        $("#qty-"+item.id).keyup(function(){
                            var qty = $("#qty-"+item.id).val();
                            var price = $("#price-"+item.id).val();
                            var total = qty * price;
                            $("#amount-"+item.id).val(total);
                        });
                    });
                }
            });

        }

$(document).on("keyup", "input[name='qty']", function() {
    //$('input[name="qty"]').change(function(){
       // alert();
      var name = [];
      $('.main').each(function(index,item){
        var obj={};
        obj.id = $(item).find('input[name="id"]').val();
        obj.qty = $(item).find('input[name="qty"]').val();
        name.push(obj)
      });
      console.log(name);
});

How to achieve this ?

Body:
$("#qty-"+item.id) DOM elements are added dynamically on the page.

You have to use event delegation for elements which were added dynamically.

You should bind keyup event handler using .on() method.

Event delegation allows us to attach a single event listener, to a
  parent element, that will fire for all descendants matching a
  selector, whether those descendants exist now or are added in the
  future.

$(document).on('keyup','#qty-'+item.id, function(){
     var qty = $("#qty-"+item.id).val();
     var price = $("#price-"+item.id).val();
     var total = qty * price;
     $("#amount-"+item.id).val(total);
});


问:
Javers - How to add extra commit metadata?
Currently Javers records the username and the timestamp of the audit in the commit metadata but I would like to store the user id as well. Is it possible to add more fields to Javers commit metadata like user id or ip address?</p>

答: Yes, commit properties. It's the Map of String properties that you can add to each commit and then use in queries. See example - https://javers.org/documentation/jql-examples/#commit-property-filter


问:
How to get spread operator updating state with React
I've defined my initial state in a Component as follows:

```<code>constructor(props) {
    super(props);
    //this.state = {count: props.initialCount};
    this.state = {
        timeArray: [],
        metawords: '',
        description: '',
        currentTime: '',
        inputFieldsDisabled: true
    }
}
</code>```

I have an event that gets called and I want to just update the metawords property.  I was thinking that the following code should work but it does not.

```<code>updateInputValue1(evt) {
    const newMetawords = "abcd";
    this.setState(
        [...this.state,{
            metawords: evt.target.value
        }]
    );
</code>```

Thoughts?

答:
state is an object so updating it the way you are at the moment won't work.

You can simply update only the property you need as:

```<code>this.setState({
  metawords: evt.target.value,
})
</code>```

Since you've mentioned spread operator, you can also (but not always necessary) update your state as:

```<code>this.setState({
  ...this.state,
  metawords: evt.target.value,
})
</code>```

or

```<code>this.setState(prevState => ({
  ...prevState,
  metawords: evt.target.value,
}))
</code>```

Should you need more info about it, I recommend you to have a look at ReactJS documentation.

Body:
I've defined my initial state in a Component as follows:

constructor(props) {
    super(props);
    //this.state = {count: props.initialCount};
    this.state = {
        timeArray: [],
        metawords: '',
        description: '',
        currentTime: '',
        inputFieldsDisabled: true
    }
}

I have an event that gets called and I want to just update the metawords property.  I was thinking that the following code should work but it does not.

updateInputValue1(evt) {
    const newMetawords = "abcd";
    this.setState(
        [...this.state,{
            metawords: evt.target.value
        }]
    );

Thoughts?

Body:
state is an object so updating it the way you are at the moment won't work.

You can simply update only the property you need as:

this.setState({
  metawords: evt.target.value,
})

Since you've mentioned spread operator, you can also (but not always necessary) update your state as:

this.setState({
  ...this.state,
  metawords: evt.target.value,
})

or

this.setState(prevState => ({
  ...prevState,
  metawords: evt.target.value,
}))

Should you need more info about it, I recommend you to have a look at ReactJS documentation.


问:
How to refactor components with almost the same JSX structure
I have a set of components which have almost identical JSX structure. These components are Panel, SidePanel, Card and Modal.

The only differences are the className because I am using BEM naming convention for CSS class name, and the event handler function and where and how the event handler function gets triggered.

How should I refactor these components in order to prevent using duplicated JSX all over the place?

Below are two example from my Panel and SidePanel component JSX,

```<code>  <div>
    <article
      className={classes}
      id={this.props.id}
      style={this.props.style}
    >
      {title && (
        <div className="panel__title">
          <h3>{title}</h3>
        </div>
      )}
      <div className="panel__content">{this.props.children}</div>
      {toolbarButtons && (
        <footer className="panel__footer">{toolbarButtons}</footer>
      )}
    </article>
  </div>
</code>```

SidePanel,

```<code>  <div>
    <article className={classes} id={id} style={style}>
      {title && (
        <div className="side-panel__title">
          <h3>{title}</h3>
        </div>
      )}
      <div className="side-panel__content">{children}</div>
      {toolbarButtons && (
        <footer className="side-panel__footer">{toolbarButtons}</footer>
      )}
    </article>
  </div>
</code>```

And you can already see the similarity between these two components.

答:
All you need to do is pass the css prefix as a prop.

You can use the following basePanel:

```<code>  const basePanel = (props) => (<div>
    <article className={props.classes} id={props.id} style={props.style}>
      {title && (
        <div className={`${props.cssPrefix}__title`}>
          <h3>{props.title}</h3>
        </div>
      )}
      <div className={`${props.cssPrefix}__content`}>{props.children}</div>
      {toolbarButtons && (
        <footer className={`${props.cssPrefix}__footer`}>{props.toolbarButtons}</footer>
      )}
    </article>
  </div>);
</code>```

Then use it like :

Your Panel becomes:

```<code>const Panel = (props) => <BasePanel {...props} cssPrefix="panel" />;
</code>```

Your side Panel becomes:

```<code>const SidePanel = (props) => <BasePanel {...props} cssPrefix="side-panel" />;
</code>```

Body:
I have a set of components which have almost identical JSX structure. These components are Panel, SidePanel, Card and Modal.

The only differences are the className because I am using BEM naming convention for CSS class name, and the event handler function and where and how the event handler function gets triggered.

How should I refactor these components in order to prevent using duplicated JSX all over the place?

Below are two example from my Panel and SidePanel component JSX,

      {title && (

{title}

      )}

{this.props.children}

      {toolbarButtons && (
        {toolbarButtons}
      )}

SidePanel,

      {title && (

{title}

      )}

{children}

      {toolbarButtons && (
        {toolbarButtons}
      )}

And you can already see the similarity between these two components.

Body:
All you need to do is pass the css prefix as a prop.

You can use the following basePanel:

  const basePanel = (props) => (<div>
    <article className={props.classes} id={props.id} style={props.style}>
      {title && (
        <div className={`${props.cssPrefix}__title`}>
          <h3>{props.title}</h3>
        </div>
      )}
      <div className={`${props.cssPrefix}__content`}>{props.children}</div>
      {toolbarButtons && (
        <footer className={`${props.cssPrefix}__footer`}>{props.toolbarButtons}</footer>
      )}
    </article>
  </div>);

Then use it like :

Your Panel becomes:

const Panel = (props) => <BasePanel {...props} cssPrefix="panel" />;

Your side Panel becomes:

const SidePanel = (props) => <BasePanel {...props} cssPrefix="side-panel" />;


问:
Update SharePoint document library file with current meta data
I'm going to make a document library with SharePoint 2010. I'm handling files that would be updated frequently and many meta data fields such as update frequency, filtering flag, monitoring flag, etc.

If SharePoint stores the files in the database, I think, it's possible to update the file content field alone without touching other fields containing meta data. But apparently it's not easy at the first glance.

Any simple way to update document content in the MOSS environment? I guess that check-out the file and update or edit then check-in is a possible solution but requires too much works for the end users.

答:
You could disable check-in/check-out on the document library

Or you could do something like this in a web part

```<code>SPFile file = web.GetFile(url);
file.UndoCheckOut();
string rawdata = Path.Combine(rootdirectory, url);
byte[] data = File.ReadAllBytes(rawdata);
file.CheckOut();
file.SaveBinary(data);
file.Update();
file.CheckIn("some thing");
file.Approve("some thing");
</code>```

ContentLicense: CC BY-SA 2.5

Body:
You could disable check-in/check-out on the document library

Or you could do something like this in a web part

SPFile file = web.GetFile(url);
file.UndoCheckOut();
string rawdata = Path.Combine(rootdirectory, url);
byte[] data = File.ReadAllBytes(rawdata);
file.CheckOut();
file.SaveBinary(data);
file.Update();
file.CheckIn("some thing");
file.Approve("some thing");


问:
How to get returned value without await opeartor
I need to get the returned value without await operator(in below sample I need to get the "hello world" in var y without await operator). Because one method is referred to a lot of places.But my requirement is that method is executed at asynchronously for particular operations. None other time it is enough to be executed as synchronously.

If I put await in all referred places that method needs to change as async and also referred methods need to change as async and await.
Is there any possibility to get the returned value?

Please find below sample code snippet:

```<code>class Program
{
    static void Main(string[] args)
    {
        var x = getString();
    }

    public static async Task<string> getString()
    {
        var y = await GetString2();
        return y;
    }

    public static async Task<string> GetString2()
    {
        return "hello world";
    }

}
</code>```

Here is there any possibility to get "hello world" string in var y without await operator?

答:
You have one of two options:

Either use the Result property of the task. This has the downside that it can block the message pump and cause problems. In a console app this might work, but you need to test.

GetString2().Result;

Use the ContinueWith method to pass an action to perform when the task is complete. The disadvantage being you will not have access to the data immediately, and the calling function will return.

GetString2().ContinueWith(result => Console.WriteLine(result));

Body:
I need to get the returned value without await operator(in below sample I need to get the "hello world" in var y without await operator). Because one method is referred to a lot of places.But my requirement is that method is executed at asynchronously for particular operations. None other time it is enough to be executed as synchronously.

If I put await in all referred places that method needs to change as async and also referred methods need to change as async and await.
Is there any possibility to get the returned value?

Please find below sample code snippet:

class Program
{
    static void Main(string[] args)
    {
        var x = getString();
    }

    public static async Task<string> getString()
    {
        var y = await GetString2();
        return y;
    }

    public static async Task<string> GetString2()
    {
        return "hello world";
    }

}

Here is there any possibility to get "hello world" string in var y without await operator?


问:
usage of attr_accessor in a rails model class
Excuse me for the noob question.I am a newbie to ruby and rails and Needed some help in Understanding the attr_accessor which I have come across in the code

```<code>  create_table "pets", force: :cascade do |t|
            t.string   "name"
            t.string   "colour"
            t.string   "owner_name"
            t.text     "identifying_characteristics"
            t.text     "special_instructions"
            t.datetime "created_at"
            t.datetime "updated_at"
            t.string   "email"
            t.string   "password"
          end
</code>```

model

```<code> class Pet < ActiveRecord::Base
  has_many :pet_photos
  cattr_accessor :form_steps do
    %w(identity characteristics instructions)
  end

  attr_accessor :form_step
  validates :email, presence: true
  validates :name, :owner_name, presence: true, if: -> { required_for_step?(:identity) }
  validates :identifying_characteristics, :colour, presence: true, if: -> { required_for_step?(:characteristics) }
  validates :special_instructions, presence: true, if: -> { required_for_step?(:instructions) }

  def required_for_step?(step)
    return true if form_step.nil?
    return true if self.form_steps.index(step.to_s) <= self.form_steps.index(form_step)
  end

end
</code>```

and

```<code>      class Pet::StepsController < ApplicationController
        include Wicked::Wizard
        steps *Pet.form_steps

        def show
          @pet = Pet.find(params[:pet_id])
          render_wizard
        end

        def update
          @pet = Pet.find(params[:pet_id])
          @pet.update(pet_params(step))

            if params[:images]

                params[:images].each do |image|
                @pet.pet_photos.create(image: image)
              end
            end

          render_wizard @pet
        end

        private

        def pet_params(step)
          permitted_attributes = case step
                                 when "identity"
                                   [:name, :owner_name]
                                 when "characteristics"
                                   [:colour, :identifying_characteristics]
                                 when "instructions"
                                   [:special_instructions]
                                 end

          params.require(:pet).permit(permitted_attributes).merge(form_step: step)
        end

      end
</code>```

routes

```<code>  PetThing::Application.routes.draw do
          resources :pets, only: [:new, :create, :index, :destroy] do
            resources :steps, only: [:show, :update], controller: 'pet/steps'
          end

          root to: 'pets#index'
</code>```

1) what  I all only know about  attr_accessor  is, it nothing more than a getter/setter for an object.I do not have a form_step as an attribute of my Pet Model(pets table).But in the model, there is attr_accessor :form_step.How is getter/setter generated to :form_step ?

2) Is :form_step an object of Pet class?

I am not totally understanding the usage of attr_accessor method in Rails model class.

3) Kindly explain me a scenario where I must generate getter/setter for Model attributes (pets table attributes or fields)

eg: attr_accessor :name
      attr_accessor :colour ..etc

when do we use attr_accessor for model attributes or fields?

答:
Lets starts with OOPs, basically class is template which defines properties and behavior of its instances i.e. objects.

The rails model also a ruby class. Its properties are being defined by attr_accessor and behaviors are defined by static and instance methods.

Consider a class with attr_accessor

```<code>class Animal
      //defines animal properties
      attr_accessor :legs
      //defines animal behavior
      def talk
      end
end
</code>```

and without attr_accessor

```<code>class Animal
      //defines animal properties
      //getter
      def legs
        @legs
      end
      //setter
      def legs=(value)
        @legs = value
      end

      //defines animal behavior
      def talk
      end
end
</code>```

Both representations are exactly same. The attr_accessor automatically add getter and setter for us and makes the life of developer easier.

Lets answer you questions

Ruby attr_accessor automatically adds these for you as explained earlier.

form_step its a attribute of Pet class and can be accessed as petObj.form_step.

If table is associated/mapped with Model, then you don't have to define columns in tables as attr_accessor, Rails automatically takes care for you. If field or attribute not exists in table, then you need to manually define it as attr_accessor in Model.

I hope this answers your question.

Body:
Excuse me for the noob question.I am a newbie to ruby and rails and Needed some help in Understanding the attr_accessor which I have come across in the code

  create_table "pets", force: :cascade do |t|
            t.string   "name"
            t.string   "colour"
            t.string   "owner_name"
            t.text     "identifying_characteristics"
            t.text     "special_instructions"
            t.datetime "created_at"
            t.datetime "updated_at"
            t.string   "email"
            t.string   "password"
          end

model

 class Pet < ActiveRecord::Base
  has_many :pet_photos
  cattr_accessor :form_steps do
    %w(identity characteristics instructions)
  end

  attr_accessor :form_step
  validates :email, presence: true
  validates :name, :owner_name, presence: true, if: -> { required_for_step?(:identity) }
  validates :identifying_characteristics, :colour, presence: true, if: -> { required_for_step?(:characteristics) }
  validates :special_instructions, presence: true, if: -> { required_for_step?(:instructions) }

  def required_for_step?(step)
    return true if form_step.nil?
    return true if self.form_steps.index(step.to_s) <= self.form_steps.index(form_step)
  end

end

and

      class Pet::StepsController < ApplicationController
        include Wicked::Wizard
        steps *Pet.form_steps

        def show
          @pet = Pet.find(params[:pet_id])
          render_wizard
        end

        def update
          @pet = Pet.find(params[:pet_id])
          @pet.update(pet_params(step))

            if params[:images]

                params[:images].each do |image|
                @pet.pet_photos.create(image: image)
              end
            end

          render_wizard @pet
        end

        private

        def pet_params(step)
          permitted_attributes = case step
                                 when "identity"
                                   [:name, :owner_name]
                                 when "characteristics"
                                   [:colour, :identifying_characteristics]
                                 when "instructions"
                                   [:special_instructions]
                                 end

          params.require(:pet).permit(permitted_attributes).merge(form_step: step)
        end

      end

routes

  PetThing::Application.routes.draw do
          resources :pets, only: [:new, :create, :index, :destroy] do
            resources :steps, only: [:show, :update], controller: 'pet/steps'
          end

          root to: 'pets#index'

1) what  I all only know about  attr_accessor  is, it nothing more than a getter/setter for an object.I do not have a form_step as an attribute of my Pet Model(pets table).But in the model, there is attr_accessor :form_step.How is getter/setter generated to :form_step ?

2) Is :form_step an object of Pet class?

I am not totally understanding the usage of attr_accessor method in Rails model class.

3) Kindly explain me a scenario where I must generate getter/setter for Model attributes (pets table attributes or fields)

eg: attr_accessor :name
      attr_accessor :colour ..etc

when do we use attr_accessor for model attributes or fields?

Body:
Lets starts with OOPs, basically class is template which defines properties and behavior of its instances i.e. objects.

The rails model also a ruby class. Its properties are being defined by attr_accessor and behaviors are defined by static and instance methods.

Consider a class with attr_accessor

class Animal
      //defines animal properties
      attr_accessor :legs
      //defines animal behavior
      def talk
      end
end

and without attr_accessor

class Animal
      //defines animal properties
      //getter
      def legs
        @legs
      end
      //setter
      def legs=(value)
        @legs = value
      end

      //defines animal behavior
      def talk
      end
end

Both representations are exactly same. The attr_accessor automatically add getter and setter for us and makes the life of developer easier.

Lets answer you questions

Ruby attr_accessor automatically adds these for you as explained earlier.

form_step its a attribute of Pet class and can be accessed as petObj.form_step.

If table is associated/mapped with Model, then you don't have to define columns in tables as attr_accessor, Rails automatically takes care for you. If field or attribute not exists in table, then you need to manually define it as attr_accessor in Model.

I hope this answers your question.


问:
In Leaflet, how to make a style the default style from now on
I have geoJson map regions rendered on a map with an initial opacity.  I have a slider to change that opacity on the fly.

Here is the bit where I set the opacity on the fly (typescript), which I perform on the input change event within my custom leaflet control:

```<code>this.layers.forEach((r: L.GeoJSON<any>) => {
      r.eachLayer((layer: any) => {
             layer.setStyle({ fillOpacity: vm.mapOptions.heatmapOpacity });
      });
});
setTimeout(() => this.map.invalidateSize());
</code>```

I also have the ability to hover over the regions, in which case I lower the opacity and put a border on the active region when they hover.

When they leave the region, it currently uses resetStyles on that region to reset it back to the previous style. I set this up in the options onFeature callback. The region is highlighted in the mouseover event, and reset in the mouseout event, as seen below.

```<code>options = {
            style: { stroke: false,
                     fillColor: regionColor,
                     fillOpacity: mapOptions.heatmapOpacity },
            onEachFeature: (feature, layer) => {
                layer.on({
                    mouseover: (e)=> {
                         const lr = e.target;
                         lr.setStyle({
                            weight: 5,
                            color: "#666",
                            dashArray: "",
                            fillOpacity: 0.7,
                           stroke: true
                         });
                        if (!L.Browser.ie && !L.Browser.opera12 && !L.Browser.edge) {
                           lr.bringToFront();
                        }
                    },
                    mouseout: (e) => {
                       prop.featureGeoJson.resetStyle(e.target);
                    }
                });
            }
        };
</code>```

The problem is, if I have used setStyle to set the opacity to a different value, then I go into a region, then I leave the region again, calling resetStyle resets the style back to the original default style, before the change to the opacity was made.

Is it possible to set the default style on the layer, so that calling resetStyle will set the styles to my value with the new opacity, and not to the original opacity set when the region was created? How would I do that?

答:
The resetStyle method of a Leaflet GeoJSON Layer Group re-applies the style that was applied at the time of creation of that group, or the default one if you did not provide style:

Resets the given vector layer's style to the original GeoJSON style, useful for resetting style after hover events.

If you later change the style of one or all of the vector layers in that group, it will be therefore overridden when you use resetStyle, and the initial style will be applied.

An easy workaround is simply to modify the GeoJSON Layer Group's style option as well. However, it will affect all its child layers:

group.options.style = newStyle;
```

<p>(that is what is suggested in @GabyakaGPetrioli's answer, but you have to apply it on the <em>group</em>, not on individual features)</p>

<p>Another solution would be to record the new style of each vector layer, and use that recorded value when you want to restore the previous state, instead of using the group's <code>resetStyle</code> method.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var map = L.map("map").setView([48.85, 2.35], 12);

var geojson = {
  type: "Feature",
  geometry: {
    type: "Point",
    coordinates: [2.35, 48.85]
  }
};

var point;
var startStyle = {
  color: "red"
};
var newStyle = {
  color: 'green'
};

var group = L.geoJSON(geojson, {
  style: startStyle,
  pointToLayer: function(feature, latlng) {
    point = L.circleMarker(latlng);
    assignStyle(point, startStyle);
    return point;
  }
}).addTo(map);

// Record the style to the individual vector layer if necessary.
function assignStyle(leafletLayer, newStyle) {
  leafletLayer.setStyle(newStyle);
  leafletLayer._recordedStyle = newStyle;
}

// When desired, apply the style that has been previously recorded.
function reassignStyle(leafletLayer) {
  leafletLayer.setStyle(leafletLayer._recordedStyle);
}

document.getElementById('button').addEventListener('click', function(event) {
  event.preventDefault();

  // Either use the wrapper function that records the new style…
  //assignStyle(point, newStyle);

  // Or simply modify the group's style option, if it is acceptable affecting all child layers.
  point.setStyle(newStyle);
  group.options.style = newStyle;
});

group.on({
  mouseover: function(e) {
    e.target.setStyle({
      color: 'blue'
    });
  },
  mouseout: function(e) {
    //reassignStyle(e.layer);
    group.resetStyle(e.layer);
  }
});

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  attribution: '© OpenStreetMap contributors'
}).addTo(map);</code>```

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.0.3/dist/leaflet.css">

<button id="button">Change color to Green…</button>

…then mouseover and mouseout
```

Body:
I have geoJson map regions rendered on a map with an initial opacity.  I have a slider to change that opacity on the fly.

Here is the bit where I set the opacity on the fly (typescript), which I perform on the input change event within my custom leaflet control:

this.layers.forEach((r: L.GeoJSON<any>) => {
      r.eachLayer((layer: any) => {
             layer.setStyle({ fillOpacity: vm.mapOptions.heatmapOpacity });
      });
});
setTimeout(() => this.map.invalidateSize());

I also have the ability to hover over the regions, in which case I lower the opacity and put a border on the active region when they hover.

When they leave the region, it currently uses resetStyles on that region to reset it back to the previous style. I set this up in the options onFeature callback. The region is highlighted in the mouseover event, and reset in the mouseout event, as seen below.

options = {
            style: { stroke: false,
                     fillColor: regionColor,
                     fillOpacity: mapOptions.heatmapOpacity },
            onEachFeature: (feature, layer) => {
                layer.on({
                    mouseover: (e)=> {
                         const lr = e.target;
                         lr.setStyle({
                            weight: 5,
                            color: "#666",
                            dashArray: "",
                            fillOpacity: 0.7,
                           stroke: true
                         });
                        if (!L.Browser.ie && !L.Browser.opera12 && !L.Browser.edge) {
                           lr.bringToFront();
                        }
                    },
                    mouseout: (e) => {
                       prop.featureGeoJson.resetStyle(e.target);
                    }
                });
            }
        };

The problem is, if I have used setStyle to set the opacity to a different value, then I go into a region, then I leave the region again, calling resetStyle resets the style back to the original default style, before the change to the opacity was made.

Is it possible to set the default style on the layer, so that calling resetStyle will set the styles to my value with the new opacity, and not to the original opacity set when the region was created? How would I do that?

Body:
The resetStyle method of a Leaflet GeoJSON Layer Group re-applies the style that was applied at the time of creation of that group, or the default one if you did not provide style:

Resets the given vector layer's style to the original GeoJSON style, useful for resetting style after hover events.

If you later change the style of one or all of the vector layers in that group, it will be therefore overridden when you use resetStyle, and the initial style will be applied.

An easy workaround is simply to modify the GeoJSON Layer Group's style option as well. However, it will affect all its child layers:

group.options.style = newStyle;

(that is what is suggested in @GabyakaGPetrioli's answer, but you have to apply it on the group, not on individual features)

Another solution would be to record the new style of each vector layer, and use that recorded value when you want to restore the previous state, instead of using the group's resetStyle method.

var map = L.map("map").setView([48.85, 2.35], 12);

var geojson = {
  type: "Feature",
  geometry: {
    type: "Point",
    coordinates: [2.35, 48.85]
  }
};

var point;
var startStyle = {
  color: "red"
};
var newStyle = {
  color: 'green'
};

var group = L.geoJSON(geojson, {
  style: startStyle,
  pointToLayer: function(feature, latlng) {
    point = L.circleMarker(latlng);
    assignStyle(point, startStyle);
    return point;
  }
}).addTo(map);

// Record the style to the individual vector layer if necessary.
function assignStyle(leafletLayer, newStyle) {
  leafletLayer.setStyle(newStyle);
  leafletLayer._recordedStyle = newStyle;
}

// When desired, apply the style that has been previously recorded.
function reassignStyle(leafletLayer) {
  leafletLayer.setStyle(leafletLayer._recordedStyle);
}

document.getElementById('button').addEventListener('click', function(event) {
  event.preventDefault();

  // Either use the wrapper function that records the new style…
  //assignStyle(point, newStyle);

  // Or simply modify the group's style option, if it is acceptable affecting all child layers.
  point.setStyle(newStyle);
  group.options.style = newStyle;
});

group.on({
  mouseover: function(e) {
    e.target.setStyle({
      color: 'blue'
    });
  },
  mouseout: function(e) {
    //reassignStyle(e.layer);
    group.resetStyle(e.layer);
  }
});

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.0.3/dist/leaflet.css">
<script src="https://unpkg.com/leaflet@1.0.3/dist/leaflet-src.js"></script>

<div id="map" style="height: 100px"></div>
<button id="button">Change color to Green…</button>
<p>…then mouseover and mouseout</p>


问:
Capture Entity argument to webtarget.request.put in with mockito
I'm trying to capture an argument passed to my webtarget. But IntelliJ keeps telling me it is wrong

aren't you able to capture the Entity.class or am I doing it wrong?

Code snippet

```<code>private WebTarget webTarget;

response = target.request("application/hal+json").put(Entity.entity(inputString, MediaType.APPLICATION_JSON_TYPE));
</code>```

My test

```<code>@RunWith(MockitoJUnitRunner.class)
public class ConnectorClientTest {

    @Mock
    WebTarget webTarget;

    @Mock
    Invocation.Builder builder;

    @InjectMocks
    ConnectorClient connectorClient;

    @Before
    public void setUp() throws Exception {
        Response response = null;
        when(webTarget.path(any())).thenReturn(webTarget);
        when(webTarget.path(any())).thenReturn(webTarget);
        when(webTarget.request(anyString())).thenReturn(builder);
        when(builder.put(any(Entity.class)))
            .thenReturn(response);
    }

        @Test
        public void initiatePropertyIdentifierSearchTest(){

        PropertyIdentifierSearchInput input = new
        PropertyIdentifierSearchInput("12345670", BigInteger.valueOf(123));

        connectorClient.initiatePropertyIdentifierSearch(input);
        ArgumentCaptor<Entity> argument = ArgumentCaptor.forClass(Entity.class);
        verify(webTarget.request((String[])
        Mockito.any()).put(argument.capture()));
        Entity entity = argument.getValue();
        //assert the entity

    }
</code>```

答:
The verify line is wrong. You have to verify the builder:

```<code>verify(builder).put(argument.capture());
</code>```

Body:
I'm trying to capture an argument passed to my webtarget. But IntelliJ keeps telling me it is wrong

aren't you able to capture the Entity.class or am I doing it wrong?

Code snippet

private WebTarget webTarget;

response = target.request("application/hal+json").put(Entity.entity(inputString, MediaType.APPLICATION_JSON_TYPE));

My test

@RunWith(MockitoJUnitRunner.class)
public class ConnectorClientTest {

    @Mock
    WebTarget webTarget;

    @Mock
    Invocation.Builder builder;

    @InjectMocks
    ConnectorClient connectorClient;

    @Before
    public void setUp() throws Exception {
        Response response = null;
        when(webTarget.path(any())).thenReturn(webTarget);
        when(webTarget.path(any())).thenReturn(webTarget);
        when(webTarget.request(anyString())).thenReturn(builder);
        when(builder.put(any(Entity.class)))
            .thenReturn(response);
    }

        @Test
        public void initiatePropertyIdentifierSearchTest(){

        PropertyIdentifierSearchInput input = new
        PropertyIdentifierSearchInput("12345670", BigInteger.valueOf(123));

        connectorClient.initiatePropertyIdentifierSearch(input);
        ArgumentCaptor<Entity> argument = ArgumentCaptor.forClass(Entity.class);
        verify(webTarget.request((String[])
        Mockito.any()).put(argument.capture()));
        Entity entity = argument.getValue();
        //assert the entity

    }

Body:
The verify line is wrong. You have to verify the builder:

verify(builder).put(argument.capture());


问:
How do I close the timer channel?
I have a timer which is reset by certain events. A go function listens to the channel using range. How do I close the channel so that for loop exits? </p>

```<code>func resetTimer(){
        if rf.electionTimer != nil {
             rf.electionTimer.Stop()
        }
}

rf.electionTimer = time.NewTimer(electionTime)

for _ = range rf.electionTimer.C {
  // Do something
}
</code>```

答:
The channel from the timer does not output a time several times. It will only output a time once after the timer has ended. Therefore, it is useless to use the rf.electionTimer in a for loop.

Try replacing your for loop with:

```<code>t := <-rf.electionTimer.C
// Do something with t
</code>```

This will pause execution until the timer has stopped.

Keep in mind, using rf.electionTimer.Stop() will prevent the timer from ever ending and your <-rf.electionTimer.C line will freeze.

How do I close the channel so that for loop exits?

To prevent the <-rf.electionTimer.C from preventing execution of code, I suggest you use:

```<code>rf.electionTimer.Reset(0)
</code>```

Title: How do I close the timer channel?

Body:
I have a timer which is reset by certain events. A go function listens to the channel using range. How do I close the channel so that for loop exits?

func resetTimer(){
        if rf.electionTimer != nil {
             rf.electionTimer.Stop()
        }
}

rf.electionTimer = time.NewTimer(electionTime)

for _ = range rf.electionTimer.C {
  // Do something
}

Body:
The channel from the timer does not output a time several times. It will only output a time once after the timer has ended. Therefore, it is useless to use the rf.electionTimer in a for loop.

Try replacing your for loop with:

t := <-rf.electionTimer.C
// Do something with t

This will pause execution until the timer has stopped.

Keep in mind, using rf.electionTimer.Stop() will prevent the timer from ever ending and your <-rf.electionTimer.C line will freeze.

How do I close the channel so that for loop exits?

To prevent the <-rf.electionTimer.C from preventing execution of code, I suggest you use:

rf.electionTimer.Reset(0)


问:
Receiving "Attempted to update a stale object: User" exception when updating current_user before logging out
I enabled optimistic locking on my User model to handle possible conflicts in various parts of my codebase. However, I'm experiencing an unexpected conflict and I don't know how to handle it because I don't know what's causing it.

I'm using the Devise gem for authentication and I'm using the before_logout method to reset a security token...

```<code>class SessionsController < Devise::SessionsController
  after_filter :after_login, :only => :create
  before_filter :before_logout, :only => :destroy

  def after_login
    # logic to set the security token
  end

  def before_logout
    current_user.update(security_token: nil) # <--"Attempted to update a stale object: User"
  end
end
</code>```

I'm new to Rails (only a few weeks in), so I don't really know where else in my code to look or why this code is throwing the exception. Any suggestions or ideas are greatly appreciated.

Thanks in advance for your wisdom!

答: You need to set a default value (0) for the lock_version column in the migration file

Body:
I enabled optimistic locking on my User model to handle possible conflicts in various parts of my codebase. However, I'm experiencing an unexpected conflict and I don't know how to handle it because I don't know what's causing it.

I'm using the Devise gem for authentication and I'm using the before_logout method to reset a security token...

class SessionsController < Devise::SessionsController
  after_filter :after_login, :only => :create
  before_filter :before_logout, :only => :destroy

  def after_login
    # logic to set the security token
  end

  def before_logout
    current_user.update(security_token: nil) # <--"Attempted to update a stale object: User"
  end
end

I'm new to Rails (only a few weeks in), so I don't really know where else in my code to look or why this code is throwing the exception. Any suggestions or ideas are greatly appreciated.

Thanks in advance for your wisdom!


问:
Java generic array from null generic type
Consider the Array.newInstance static method as a way of creating a generic type array in Java.
What I'm failing to see how to do is create a generic array from a null generic type argument:

```<code>/**
* Creates and fills a generic array with the given item
*/
public static <T> T[] create(T item, int length)
{
   T[] result = (T[]) Array.newInstance(item.getClass(), length);

   for(int i = 0; i < length; i++)
      result[i] = item;

   return result;
}
</code>```

The above works when I call e.g. create("abc", 10); I'm getting a String[] of length 10 with "abc" in all positions of the array.
But how could I make a null string argument return a String array of length 10 and null in all positions?

e.g.

```<code>String nullStr = null;
String[] array = create(nullStr, 10); // boom! NullPointerException
</code>```

Is there perhaps a  way to get the class of "item" without using one of its members (as it's null)?

I know I can just new up an array String[] array = new String[10], but that's not the point.

Thanks

答:
As you point out, you can't call:

```<code>create(null, 10)
</code>```

because your code can't determine the type (it ends up calling null.getClass() => NPE).

You could pass the class separately:

```<code>public static <T> T[] create(Class<T> type, int length, T fillValue)
{
   T[] result = (T[]) Array.newInstance(type, length);

   for(int i = 0; i < length; i++)
      result[i] = fillValue;

   return result;
}

// Some optional convenience signatures:

public static <T> T[] create(Class<T> type, int length) {
    return create(type, length, null);
}

public static <T> T[] create(T fillValue, int length) {
    if (fillValue == null) {
        throw new IllegalArgumentException("fillValue cannot be null");
    }
    return create(fillValue.getClass(), length, fillValue);
}

public static void main(String[] args) {
    String[] a = create(String.class, 10, null);
}
</code>```

Body:
Consider the Array.newInstance static method as a way of creating a generic type array in Java.
What I'm failing to see how to do is create a generic array from a null generic type argument:

/**
* Creates and fills a generic array with the given item
*/
public static <T> T[] create(T item, int length)
{
   T[] result = (T[]) Array.newInstance(item.getClass(), length);

   for(int i = 0; i < length; i++)
      result[i] = item;

   return result;
}

The above works when I call e.g. create("abc", 10); I'm getting a String[] of length 10 with "abc" in all positions of the array.
But how could I make a null string argument return a String array of length 10 and null in all positions?

e.g.

String nullStr = null;
String[] array = create(nullStr, 10); // boom! NullPointerException

Is there perhaps a  way to get the class of "item" without using one of its members (as it's null)?

I know I can just new up an array String[] array = new String[10], but that's not the point.

Thanks

Body:
As you point out, you can't call:

create(null, 10)

because your code can't determine the type (it ends up calling null.getClass() => NPE).

You could pass the class separately:

public static <T> T[] create(Class<T> type, int length, T fillValue)
{
   T[] result = (T[]) Array.newInstance(type, length);

   for(int i = 0; i < length; i++)
      result[i] = fillValue;

   return result;
}

// Some optional convenience signatures:

public static <T> T[] create(Class<T> type, int length) {
    return create(type, length, null);
}

public static <T> T[] create(T fillValue, int length) {
    if (fillValue == null) {
        throw new IllegalArgumentException("fillValue cannot be null");
    }
    return create(fillValue.getClass(), length, fillValue);
}

public static void main(String[] args) {
    String[] a = create(String.class, 10, null);
}


问:
Xcode beginner. New file problems and error
I'm new to Xcode and am having problems. I'll go through my steps and describe my problem. So, I want to code in C++... I

Open Xcode

New Project... Command line tool

Add the project to my designated programming folder

Run the Hello World program given and everything works well.

The problem is when I try to add a new file to my current project. I click file -> new file -> C++ class. So lets say I name this file practice.cpp, when I do this it also creates practice.h with all the headers. I however, would prefer all my code with headers in one window as my programs are minimal for now. Also, if I do try to create a simple program, say copied from the Hello World that previously worked or anything else I get an error. "linker command failed with exit code 1 (use -v to see invocation)"
I've scoured the internet and have not found a fix. Thank you all!

Edit: Sorry about that, I think maybe there's a duplicate but I'm not sure how to go about understanding or fixing the error. Anyway, here's the error...

Ld /Users/Finn/Library/Developer/Xcode/DerivedData/CSE1222-caatcfzekizvqkcdenxbphbfseon/Build/Products/Debug/CSE1222 normal x86_64
    cd "/Users/Finn/Desktop/School/CSE 1222/CSE1222/CSE1222"
    setenv MACOSX_DEPLOYMENT_TARGET 10.9
    /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang++ -arch x86_64 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk -L/Users/Finn/Library/Developer/Xcode/DerivedData/CSE1222-caatcfzekizvqkcdenxbphbfseon/Build/Products/Debug -F/Users/Finn/Library/Developer/Xcode/DerivedData/CSE1222-caatcfzekizvqkcdenxbphbfseon/Build/Products/Debug -filelist /Users/Finn/Library/Developer/Xcode/DerivedData/CSE1222-caatcfzekizvqkcdenxbphbfseon/Build/Intermediates/CSE1222.build/Debug/CSE1222.build/Objects-normal/x86_64/CSE1222.LinkFileList -mmacosx-version-min=10.9 -stdlib=libc++ -Xlinker -dependency_info -Xlinker /Users/Finn/Library/Developer/Xcode/DerivedData/CSE1222-caatcfzekizvqkcdenxbphbfseon/Build/Intermediates/CSE1222.build/Debug/CSE1222.build/Objects-normal/x86_64/CSE1222_dependency_info.dat -o /Users/Finn/Library/Developer/Xcode/DerivedData/CSE1222-caatcfzekizvqkcdenxbphbfseon/Build/Products/Debug/CSE1222

duplicate symbol _main in:
    /Users/Finn/Library/Developer/Xcode/DerivedData/CSE1222-caatcfzekizvqkcdenxbphbfseon/Build/Intermediates/CSE1222.build/Debug/CSE1222.build/Objects-normal/x86_64/main.o
    /Users/Finn/Library/Developer/Xcode/DerivedData/CSE1222-caatcfzekizvqkcdenxbphbfseon/Build/Intermediates/CSE1222.build/Debug/CSE1222.build/Objects-normal/x86_64/File1.o
ld: 1 duplicate symbol for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

答: I just untick the target membership in one .cpp file and the other one can be built. </p>


问:
Whats the last digit in css class col-md-x for? Where x is an integer
Example. We have col-md-4, but we can also have col-md-1 all the way until 12.
What exactly does the number represent?</p>

答: It specifies the auto-layout columns when using bootstrap. Please see the documentation at getbootstrap.com</p>


问:
Config SSL mosquitto error
I tried to config SSL for mostquitto following these steps.

When I restart mosquitto, there is an error:

```<code>1435120150: mosquitto version 1.4.2 (build date Mon, 18 May 2015 15:25:19 +0100) starting

1435120150: Config loaded from /etc/mosquitto/mosquitto.conf.

1435120150: Opening ipv4 listen socket on port 8883.

1435120150: Error: Unable to create TLS context.
</code>```

This is my  mosquitto config:

```<code>pid_file /var/run/mosquitto.pid
persistence true
persistence_location /var/lib/mosquitto/

log_dest file /var/log/mosquitto/mosquitto.log

include_dir /etc/mosquitto/conf.d

bind_address Dell
port 8883
cafile /etc/mosquitto/ca_certificates/ca.crt
certfile /etc/mosquitto/certs/Dell.crt
keyfile /etc/mosquitto/certs/Dell.key
tls_version tlsv1
</code>```

How to configure it correctly?

答:
Please check client system time and ssl certificate end date, client system time must be in between ssl certificate start time and end time

Check Client System Date :

date

Check openssl certificate end date :

openssl x509 -enddate -noout -in cacert.pem

Title: Config SSL mosquitto error

Body:
I tried to config SSL for mostquitto following these steps.

When I restart mosquitto, there is an error:

1435120150: mosquitto version 1.4.2 (build date Mon, 18 May 2015 15:25:19 +0100) starting

1435120150: Config loaded from /etc/mosquitto/mosquitto.conf.

1435120150: Opening ipv4 listen socket on port 8883.

1435120150: Error: Unable to create TLS context.

This is my  mosquitto config:

pid_file /var/run/mosquitto.pid
persistence true
persistence_location /var/lib/mosquitto/

log_dest file /var/log/mosquitto/mosquitto.log

include_dir /etc/mosquitto/conf.d

bind_address Dell
port 8883
cafile /etc/mosquitto/ca_certificates/ca.crt
certfile /etc/mosquitto/certs/Dell.crt
keyfile /etc/mosquitto/certs/Dell.key
tls_version tlsv1

How to configure it correctly?


问:
Having issues with activating constraints programmatically and getting errors
Last night I posted a question on here where I used storyboards to set the constraints. I decided to test it with anchors and do constraints programmatically.

I am getting this error:

Terminating app due to uncaught exception 'NSGenericException',
  reason: 'Unable to activate constraint with anchors
   and

  because they have no common ancestor.  Does the constraint or its
  anchors reference items in different view hierarchies?  That's
  illegal.'

I know this has to do with views not being a subview of a certain other view however, I have checked it plenty of times and I don't know what to do.

here is the code:

```<code>import UIKit
import CoreData
class editViewController: UIViewController {

let screenSize: CGRect = UIScreen.main.bounds
let moContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

var editnotes: addednotes?

let mainbackgroundview: UIView =
{
    let view = UIView()
    view.backgroundColor = .black
    view.alpha = 0.3

    return view
}()

let backgroundview1: UIView =
{
    let view = UIView()
    view.backgroundColor = .purple

    return view
}()

let edittasktextview1: UITextView = {
    let tv = UITextView()
    tv.backgroundColor = .black
    return tv
}()

    let cancelButton : UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("Cancel", for: .normal)
        button.addTarget(self, action: #selector(handleCancelButton), for:
.touchUpInside)
    return button
}()

let doneButton1 : UIButton = {
    let button = UIButton(type: .system)
    button.setTitle("Done", for: .normal)
    button.addTarget(self, action: #selector(handleDoneButton), for: .touchUpInside)
    return button
}()

@objc func handleCancelButton() {

    edittasktextview1.endEditing(true)
    dismiss(animated: true, completion: nil)
}

@objc func handleDoneButton()
{
    dismiss(animated: true, completion: nil)

    if edittasktextview1.text.isEmpty == true
    {
        moContext.delete(editnotes!)
    }
    else
    {
        editnotes?.sNote = edittasktextview1.text
    }
    var error: NSError?
    do {
        // Save The object

        try moContext.save()
        print("SAVED")
    } catch let error1 as NSError {
        error = error1
    }

    edittasktextview1.endEditing(true)

}

override func viewWillDisappear(_ animated: Bool) {
    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "NotificationID"), object: nil)

}
override func viewDidAppear(_ animated: Bool) {
    //add something here
   // edittasktextview.becomeFirstResponder()
}

override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationController?.navigationBar.tintColor = UIColor.white
    navigationItem.title = "Edit Tasks"
    edittasktextview1.text = editnotes?.sNote
    backgroundview1.backgroundColor = editnotes?.sPriorityColor
    edittasktextview1.backgroundColor = .clear
    setupviews()
    //adding gesture to the background view to dismiss keyboard
    let dismisskeyboardgesture = UITapGestureRecognizer()
    dismisskeyboardgesture.addTarget(self, action: #selector(dismisskeyboard))

    let maskPath = UIBezierPath.init(roundedRect: self.backgroundview1.bounds, byRoundingCorners:[.topLeft, .topRight], cornerRadii: CGSize.init(width: 20.0, height: 0))
    let maskLayer = CAShapeLayer()
    maskLayer.frame = self.backgroundview1.bounds
    maskLayer.path = maskPath.cgPath
    self.backgroundview1.layer.mask = maskLayer
     view.backgroundColor = .clear

    //view.addGestureRecognizer(dismisskeyboardgesture)
    view.addSubview(mainbackgroundview)
   mainbackgroundview.addSubview(backgroundview1)
// view.addSubview(backgroundview1)
    backgroundview1.addSubview(edittasktextview1)
    backgroundview1.addSubview(cancelButton)
    backgroundview1.addSubview(doneButton1)
}

    @objc func dismisskeyboard()
   {
    edittasktextview1.endEditing(true)
   }

func setupviews()
{
   mainbackgroundview.anchorToTop(view.topAnchor, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor)
    backgroundview1.anchor(view.topAnchor, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, topConstant: 45, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0)

    edittasktextview1.anchor(view.topAnchor, left: view.leftAnchor, bottom: nil, right: view.rightAnchor, topConstant: 40, leftConstant: 8, bottomConstant: 0, rightConstant: 8, widthConstant: 0, heightConstant: 150)

    cancelButton.anchor(edittasktextview1.bottomAnchor, left: nil, bottom: nil, right: view.rightAnchor, topConstant: 18, leftConstant: 0, bottomConstant: 0, rightConstant: 8, widthConstant: 40, heightConstant: 30)

   doneButton1.anchor(edittasktextview1.bottomAnchor, left: view.leftAnchor, bottom: nil, right: nil, topConstant: 18, leftConstant: 8, bottomConstant: 0, rightConstant: 0, widthConstant: 40, heightConstant: 30)

}

}
</code>```

Help will be appreciated, as I am stuck at this problem for nearly 18 hours :(

UPDATE #1

Not getting the same error now, however, I am not able to set the backgroundview1 on the mainbackgroundview.

I am adding it as a subview:

```<code>mainbackgroundview.addSubview(backgroundview1)
</code>```

In setupviews() I am placing the constraint like so:

```<code> NSLayoutConstraint.activate([
        backgroundview1.leftAnchor.constraint(equalTo: mainbackgroundview.leftAnchor, constant: 0),
        backgroundview1.rightAnchor.constraint(equalTo: mainbackgroundview.rightAnchor, constant: 0),
        backgroundview1.bottomAnchor.constraint(equalTo: mainbackgroundview.bottomAnchor, constant: 0),
        backgroundview1.topAnchor.constraint(equalTo: mainbackgroundview.topAnchor, constant: 45)

        ])
</code>```

Still I am not getting the backgroundview1 to be placed on the mainbackgroundview. The mainbackgroundview is showing up though on the simulator.

I am adding mainbackgroundview like so:

```<code> NSLayoutConstraint.activate([
        mainbackgroundview.leftAnchor.constraint(equalTo: view.leftAnchor),
        mainbackgroundview.rightAnchor.constraint(equalTo: view.rightAnchor),
        mainbackgroundview.topAnchor.constraint(equalTo: view.topAnchor),
        mainbackgroundview.bottomAnchor.constraint(equalTo: view.bottomAnchor)
        ])
</code>```

What am I doing wrong now?

答:
In setupViews() function you are adding constraints but not setting them as active. This is a sample anchor constraint that can be added successfully:

```<code>myView.bottomAnchor.constraint(equalTo: view.topAnchor,
   constant: 8).isActive=true
</code>```

Try adding .isActive at the end of each of your constraint.

Moreover you can add relevant anchor constraints for example: topAnchor, bottomAnchor, widthAnchor, heightAnchor, leadingAnchor etc. Try simplifying your constraints.

Body:
Last night I posted a question on here where I used storyboards to set the constraints. I decided to test it with anchors and do constraints programmatically.

I am getting this error:

Terminating app due to uncaught exception 'NSGenericException',
  reason: 'Unable to activate constraint with anchors
   and

  because they have no common ancestor.  Does the constraint or its
  anchors reference items in different view hierarchies?  That's
  illegal.'

I know this has to do with views not being a subview of a certain other view however, I have checked it plenty of times and I don't know what to do.

here is the code:

import UIKit
import CoreData
class editViewController: UIViewController {

let screenSize: CGRect = UIScreen.main.bounds
let moContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

var editnotes: addednotes?

let mainbackgroundview: UIView =
{
    let view = UIView()
    view.backgroundColor = .black
    view.alpha = 0.3

    return view
}()

let backgroundview1: UIView =
{
    let view = UIView()
    view.backgroundColor = .purple

    return view
}()

let edittasktextview1: UITextView = {
    let tv = UITextView()
    tv.backgroundColor = .black
    return tv
}()

    let cancelButton : UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("Cancel", for: .normal)
        button.addTarget(self, action: #selector(handleCancelButton), for:
.touchUpInside)
    return button
}()

let doneButton1 : UIButton = {
    let button = UIButton(type: .system)
    button.setTitle("Done", for: .normal)
    button.addTarget(self, action: #selector(handleDoneButton), for: .touchUpInside)
    return button
}()

@objc func handleCancelButton() {

    edittasktextview1.endEditing(true)
    dismiss(animated: true, completion: nil)
}

@objc func handleDoneButton()
{
    dismiss(animated: true, completion: nil)

    if edittasktextview1.text.isEmpty == true
    {
        moContext.delete(editnotes!)
    }
    else
    {
        editnotes?.sNote = edittasktextview1.text
    }
    var error: NSError?
    do {
        // Save The object

        try moContext.save()
        print("SAVED")
    } catch let error1 as NSError {
        error = error1
    }

    edittasktextview1.endEditing(true)

}

override func viewWillDisappear(_ animated: Bool) {
    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "NotificationID"), object: nil)

}
override func viewDidAppear(_ animated: Bool) {
    //add something here
   // edittasktextview.becomeFirstResponder()
}

override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationController?.navigationBar.tintColor = UIColor.white
    navigationItem.title = "Edit Tasks"
    edittasktextview1.text = editnotes?.sNote
    backgroundview1.backgroundColor = editnotes?.sPriorityColor
    edittasktextview1.backgroundColor = .clear
    setupviews()
    //adding gesture to the background view to dismiss keyboard
    let dismisskeyboardgesture = UITapGestureRecognizer()
    dismisskeyboardgesture.addTarget(self, action: #selector(dismisskeyboard))

    let maskPath = UIBezierPath.init(roundedRect: self.backgroundview1.bounds, byRoundingCorners:[.topLeft, .topRight], cornerRadii: CGSize.init(width: 20.0, height: 0))
    let maskLayer = CAShapeLayer()
    maskLayer.frame = self.backgroundview1.bounds
    maskLayer.path = maskPath.cgPath
    self.backgroundview1.layer.mask = maskLayer
     view.backgroundColor = .clear

    //view.addGestureRecognizer(dismisskeyboardgesture)
    view.addSubview(mainbackgroundview)
   mainbackgroundview.addSubview(backgroundview1)
// view.addSubview(backgroundview1)
    backgroundview1.addSubview(edittasktextview1)
    backgroundview1.addSubview(cancelButton)
    backgroundview1.addSubview(doneButton1)
}

    @objc func dismisskeyboard()
   {
    edittasktextview1.endEditing(true)
   }

func setupviews()
{
   mainbackgroundview.anchorToTop(view.topAnchor, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor)
    backgroundview1.anchor(view.topAnchor, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, topConstant: 45, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0)

    edittasktextview1.anchor(view.topAnchor, left: view.leftAnchor, bottom: nil, right: view.rightAnchor, topConstant: 40, leftConstant: 8, bottomConstant: 0, rightConstant: 8, widthConstant: 0, heightConstant: 150)

    cancelButton.anchor(edittasktextview1.bottomAnchor, left: nil, bottom: nil, right: view.rightAnchor, topConstant: 18, leftConstant: 0, bottomConstant: 0, rightConstant: 8, widthConstant: 40, heightConstant: 30)

   doneButton1.anchor(edittasktextview1.bottomAnchor, left: view.leftAnchor, bottom: nil, right: nil, topConstant: 18, leftConstant: 8, bottomConstant: 0, rightConstant: 0, widthConstant: 40, heightConstant: 30)

}

}

Help will be appreciated, as I am stuck at this problem for nearly 18 hours :(

UPDATE #1

Not getting the same error now, however, I am not able to set the backgroundview1 on the mainbackgroundview.

I am adding it as a subview:

mainbackgroundview.addSubview(backgroundview1)

In setupviews() I am placing the constraint like so:

 NSLayoutConstraint.activate([
        backgroundview1.leftAnchor.constraint(equalTo: mainbackgroundview.leftAnchor, constant: 0),
        backgroundview1.rightAnchor.constraint(equalTo: mainbackgroundview.rightAnchor, constant: 0),
        backgroundview1.bottomAnchor.constraint(equalTo: mainbackgroundview.bottomAnchor, constant: 0),
        backgroundview1.topAnchor.constraint(equalTo: mainbackgroundview.topAnchor, constant: 45)

        ])

Still I am not getting the backgroundview1 to be placed on the mainbackgroundview. The mainbackgroundview is showing up though on the simulator.

I am adding mainbackgroundview like so:

 NSLayoutConstraint.activate([
        mainbackgroundview.leftAnchor.constraint(equalTo: view.leftAnchor),
        mainbackgroundview.rightAnchor.constraint(equalTo: view.rightAnchor),
        mainbackgroundview.topAnchor.constraint(equalTo: view.topAnchor),
        mainbackgroundview.bottomAnchor.constraint(equalTo: view.bottomAnchor)
        ])

What am I doing wrong now?

Body:
In setupViews() function you are adding constraints but not setting them as active. This is a sample anchor constraint that can be added successfully:

myView.bottomAnchor.constraint(equalTo: view.topAnchor,
   constant: 8).isActive=true

Try adding .isActive at the end of each of your constraint.

Moreover you can add relevant anchor constraints for example: topAnchor, bottomAnchor, widthAnchor, heightAnchor, leadingAnchor etc. Try simplifying your constraints.


问:
Alignment of dynamic views
I want the alignment of the editext and the imageviewin the same horizontal line but I am getting the imageview below the edittext.

main fragment code

```<code> final LinearLayout lnrView = (LinearLayout)
 child.findViewById(R.id.lnrView);
                Button btnad = (Button) child.findViewById(R.id.btnad);
                btnad.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        lnrView.addView(newedittext());
                        lnrView.addView(newImageview(getActivity()));
                    }
                });
</code>```

neweditext method

```<code>  private View newedittext() {
    final ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    final EditText editText = new EditText(getActivity());
    int id = 0;
    editText.setId(id);
    editText.setTextSize(14);
    editText.setTextColor(Color.rgb(0, 0, 0));
    editText.setMaxEms(2);
    editText.setInputType(InputType.TYPE_CLASS_TEXT);
    return editText;
}
</code>```

newImageview method

```<code> public ImageView newImageview(Context context) {
    final ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    final ImageView imgView = new ImageView(context);
    int id = 0;
    imgView.setId(id);
    imgView.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_close_red));
    return imgView;
}
</code>```

main fragment xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
    android:id="@+id/btnad"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="add" />

<LinearLayout
    android:id="@+id/lnrView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

</LinearLayout>

</LinearLayout>
</code>```

when i click the Add button an edittext and  Imageview is created dynamically and my output screen look like below

i want the imageview and the edittext in the same line. can anyone help me.

when i add "Horizontal" this is the output

this my expected result

答:
You need add first a Horizontal Linearlayout in Your lnrView than add EditText and Imageview

Try this

```<code> button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            LinearLayout layout = new LinearLayout(MainActivity.this);
            layout.setOrientation(LinearLayout.HORIZONTAL);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);

            layout.setLayoutParams(lp);
            layout.addView(newedittext());
            layout.addView(newImageview(MainActivity.this));

            lnrView.addView(layout);
        }
    });
</code>```

Title: Alignment of dynamic views

Body:
I want the alignment of the editext and the imageviewin the same horizontal line but I am getting the imageview below the edittext.

main fragment code

 final LinearLayout lnrView = (LinearLayout)
 child.findViewById(R.id.lnrView);
                Button btnad = (Button) child.findViewById(R.id.btnad);
                btnad.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        lnrView.addView(newedittext());
                        lnrView.addView(newImageview(getActivity()));
                    }
                });

neweditext method

  private View newedittext() {
    final ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    final EditText editText = new EditText(getActivity());
    int id = 0;
    editText.setId(id);
    editText.setTextSize(14);
    editText.setTextColor(Color.rgb(0, 0, 0));
    editText.setMaxEms(2);
    editText.setInputType(InputType.TYPE_CLASS_TEXT);
    return editText;
}

newImageview method

 public ImageView newImageview(Context context) {
    final ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    final ImageView imgView = new ImageView(context);
    int id = 0;
    imgView.setId(id);
    imgView.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_close_red));
    return imgView;
}

main fragment xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
    android:id="@+id/btnad"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="add" />

<LinearLayout
    android:id="@+id/lnrView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

</LinearLayout>

</LinearLayout>

when i click the Add button an edittext and  Imageview is created dynamically and my output screen look like below

i want the imageview and the edittext in the same line. can anyone help me.

when i add "Horizontal" this is the output

this my expected result

Body:
You need add first a Horizontal Linearlayout in Your lnrView than add EditText and Imageview

Try this

 button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            LinearLayout layout = new LinearLayout(MainActivity.this);
            layout.setOrientation(LinearLayout.HORIZONTAL);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);

            layout.setLayoutParams(lp);
            layout.addView(newedittext());
            layout.addView(newImageview(MainActivity.this));

            lnrView.addView(layout);
        }
    });