问:
Get volley request tag in response
I'm using volley and I have a queue to call some APIs. The queue is filled from a database.

before adding request to volley request queue I set request tag by calling

jsonObjectRequest.setTag(id);

In response, I want to remove a column from the database that column id is equal to request tag id.

So, How can I get request tag in HttpRequest response?

答:
First create a Listener that give response from your volly class

```<code>/** Callback interface for delivering parsed responses. */
public interface Listener {
    /** Called when a response is received. */
    public void onResponse(Object tag, JSONObject response);
    public void onErrorResponse(Object tag, VolleyError error);
}
</code>```

And now create method as below where you pass listener and tag and call volly request. in response you able get tag and response at same time.

```<code>public void callApi(String url, final Listener listener, final Object tag){
    JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
            url, null,
            new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    listener.onResponse(tag,response);
                }
            }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            listener.onErrorResponse(tag,error);
        }
    });

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(jsonObjReq);
}
</code>```

Its just sample code, You can modify on your requirement. If you need any help comment.

Title: Get volley request tag in response

Body:
First create a Listener that give response from your volly class

/** Callback interface for delivering parsed responses. */
public interface Listener {
    /** Called when a response is received. */
    public void onResponse(Object tag, JSONObject response);
    public void onErrorResponse(Object tag, VolleyError error);
}

And now create method as below where you pass listener and tag and call volly request. in response you able get tag and response at same time.

public void callApi(String url, final Listener listener, final Object tag){
    JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
            url, null,
            new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    listener.onResponse(tag,response);
                }
            }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            listener.onErrorResponse(tag,error);
        }
    });

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(jsonObjReq);
}

Its just sample code, You can modify on your requirement. If you need any help comment.


来源: stackexchange

问:
Spring - Autowired not working
This is my situation:
- /WEB-INF/spring/applicationContext.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/util
    http://www.springframework.org/schema/util/spring-util.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/jdbc
    http://www.springframework.org/schema/jdbc/spring-jdbc.xsd">

    <context:annotation-config />

    <bean id="userDAO" class="com.test.repository.user.dao.impl.UserDAOImpl" />

</beans>
</code>```

web.xml

```<code><display-name>Test</display-name>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring/applicationContext.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</code>```

UserDaoImpl:

@Log4j2
public class UserDAOImpl implements UserDAO {
 ...
 ...
}

Test:

```<code>@RunWith(SpringJUnit4ClassRunner.class)
 @ContextConfiguration(locations = { "classpath:*applicationContext.xml" })
 public class TestDAO{

@Autowired
UserDAO userDAO;
</code>```

...

}

pom.xml:

...

            org.springframework
            spring-context
            ${springframework.version}

```<code>    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${springframework.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>${springframework.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>${springframework.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${springframework.version}</version>
        <scope>test</scope>
    </dependency>
</code>```

...

Error:

No qualifying bean of type 'com.test.repository.user.dao.impl.UserDAO' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

答:
I don't see any issues unless you have defined the correct package name for UserDAOImpl. I just did the following setup and it is working.

applicationContext.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/util
    http://www.springframework.org/schema/util/spring-util.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/jdbc
    http://www.springframework.org/schema/jdbc/spring-jdbc.xsd">

    <context:annotation-config />

    <bean id="userDAO" class="com.mytest.UserDAOImpl" />

</beans>
</code>```

UserDAO

```<code>package com.mytest;

public interface UserDAO {
    public void mytest();
}
</code>```

UserDAOImpl

```<code>package com.mytest;
public class UserDAOImpl implements UserDAO {
    @Override
    public void mytest() {
        System.out.println("In MY test");
    }
}
</code>```

TestDAO

```<code>package com.mytest;

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = { "file:C://<fully qualified path>//applicationContext.xml" })
    public class TestDAO {
        @Autowired
        UserDAO userDAO;

        @Test
        public void testSysout(){
            userDAO.mytest();//prints "In MY test"
        }
    }
</code>```

ContentLicense: CC BY-SA 3.0

Title: Spring - Autowired not working

Body:
This is my situation:
- /WEB-INF/spring/applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/util
    http://www.springframework.org/schema/util/spring-util.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/jdbc
    http://www.springframework.org/schema/jdbc/spring-jdbc.xsd">

    <context:annotation-config />

    <bean id="userDAO" class="com.test.repository.user.dao.impl.UserDAOImpl" />

</beans>

web.xml

<display-name>Test</display-name>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring/applicationContext.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

UserDaoImpl:

@Log4j2
public class UserDAOImpl implements UserDAO {
 ...
 ...
}

Test:

@RunWith(SpringJUnit4ClassRunner.class)
 @ContextConfiguration(locations = { "classpath:*applicationContext.xml" })
 public class TestDAO{

@Autowired
UserDAO userDAO;

...

}

pom.xml:

...

            org.springframework
            spring-context
            ${springframework.version}

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${springframework.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>${springframework.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>${springframework.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${springframework.version}</version>
        <scope>test</scope>
    </dependency>

...

Error:

No qualifying bean of type 'com.test.repository.user.dao.impl.UserDAO' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

Body:
I don't see any issues unless you have defined the correct package name for UserDAOImpl. I just did the following setup and it is working.

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/util
    http://www.springframework.org/schema/util/spring-util.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/jdbc
    http://www.springframework.org/schema/jdbc/spring-jdbc.xsd">

    <context:annotation-config />

    <bean id="userDAO" class="com.mytest.UserDAOImpl" />

</beans>

UserDAO

package com.mytest;

public interface UserDAO {
    public void mytest();
}

UserDAOImpl

package com.mytest;
public class UserDAOImpl implements UserDAO {
    @Override
    public void mytest() {
        System.out.println("In MY test");
    }
}

TestDAO

package com.mytest;

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = { "file:C://<fully qualified path>//applicationContext.xml" })
    public class TestDAO {
        @Autowired
        UserDAO userDAO;

        @Test
        public void testSysout(){
            userDAO.mytest();//prints "In MY test"
        }
    }


问:
Is there a quick way to remove using statements in C#?
Is there a quick way to determine whether you are using certain namespaces in your application. I want to remove all the unneccessary using statements like using System.Reflection and so on, but I need a way to determine if I am using those libraries or not. I know that the tool Resharper does this for you, but is there a quick and dirty and Free way to do this?</p>

答:
VS2008 can do this on a per-file basis.

Right-click the source code, select "Organize Usings", "Remove Unused Usings".

OwnerDisplayName: Jason

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Jorge

OwnerDisplayName: Timbo


问:
Not able to get the Value from Drop down Menu
Hello I'm having problem in getting the value from the drop down menu bar. When I choose a course and submit no Value is retrieved but a new empty record is entered in DB. I'm sharing my code I will appreciate any sort of help.

My View

```<code><form method="post" action="<?php echo(base_url()."University/std_assign_cousrse/");?>" >
<select>
 <option value="">--- Select Course ---</option>
<?php

foreach($result as $row)
{
    echo "<option value=".$row['course_id'].">".$row['course_name']."</option>";
}
 ?>
</select>
<input type="Submit">
</form>
</code>```

My Controller

```<code>   public function std_assign_cousrse()
    {
        $data = array(
            'std_course' =>$this->input->post('course_id') ,);
    $this->db->Insert('tbl_student',$data);
    print_r($data);

    }
</code>```

答:
Use name attribute</p>

```<code><select name="myselet">
 <option value="">--- Select Course ---</option>
</code>```

Body:
Hello I'm having problem in getting the value from the drop down menu bar. When I choose a course and submit no Value is retrieved but a new empty record is entered in DB. I'm sharing my code I will appreciate any sort of help.

My View

<form method="post" action="<?php echo(base_url()."University/std_assign_cousrse/");?>" >
<select>
 <option value="">--- Select Course ---</option>
<?php

foreach($result as $row)
{
    echo "<option value=".$row['course_id'].">".$row['course_name']."</option>";
}
 ?>
</select>
<input type="Submit">
</form>

My Controller

   public function std_assign_cousrse()
    {
        $data = array(
            'std_course' =>$this->input->post('course_id') ,);
    $this->db->Insert('tbl_student',$data);
    print_r($data);

    }

Body:
Use name attribute

<select name="myselet">
 <option value="">--- Select Course ---</option>


问:
how to get multiple object json values and push to array using jquery
I am trying to get data from json and push to array but it is not working. it is possible or not getting multiple object values from json. anybody can tell it is possible or not? if it is possible how we can do it and where i stucked from my code?

html

```<code>        <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
        <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
        <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
        <script type="text/javascript">

        $( document ).ready(function() {
              var searchVal = [];
            var optionVal = [];
            var autocompVal = [];
            $.getJSON( "datas.json", function( data ) {

          $.each( data, function( key, val ) {
            searchVal.push(  key.searchVal.searchname );
          });

           $.each( data, function( key, val ) {
            optionVal.push(  key.optionVal.optionname );
          });

           $.each( data, function( key, val ) {
            autocompVal.push(  key.autocompVal );
          });

        console.log("Show all Array value="+searchVal +"=="+ optionVal +"=="+autocompVal);

        });

        $("#autoComplete").autocomplete({
                source: autocompVal,
                select: function (event, ui) {//when we select something from the search box
                    this.value = ui.item.label;
                    alert(this.value);
                    return false;
                }
            });

        });

        </script>

        <input type="text" id="autoComplete">
</code>```

datas.json:

```<code>        {
            "searchVal": [
                 { "searchname":"test1"},
                 { "searchname":"test2"}
                 ],
            "optionVal": [
                 { "optionname":"test11"},
                 { "optionname":"test12"},
                 { "optionname":"test13"}
                 ],
           "autocompVal": [
                 { "test11"},
                 { "test12"} ,
                 { "test13"},
                 { "test14"}
                 ]
        }
</code>```

答:
Not quite sure what you mean, but json stands for Javascript Object notation.
So it's quite easy to get to its values.
data = your json object.
So

```<code>data.searchVal[0].searchName === "test1"
data.searchVal.forEach(function(searchVal){....})
</code>```

so you could assign searchVal = data.searchVal, or better yet, simply use the single json object as is.

Edit: I see you want the searchName values out of the searchVal into a new array. You could do something like:

```<code>searchVal = data.searchVal.map(function(searchVal){
  return searchVal.searchName;
});
</code>```

var searchVal, optionVal, autocompVal;

$(document).ready(function() {
  var data = {
    "searchVal": [{
        "searchname": "test1"
      },
      {
        "searchname": "test2"
      }
    ],
    "optionVal": [{
        "optionname": "test11"
      },
      {
        "optionname": "test12"
      },
      {
        "optionname": "test13"
      }
    ],
    "autocompVal": [
      "test11",
      "test12",
      "test13",
      "test14"
    ]
  };
  searchVal = data.searchVal.map(function(searchVal) {
    return searchVal.searchname;
  });
  optionVal = data.optionVal.map(function(optionVal) {
    return optionVal.optionname;
  });
  autocompVal = data.autocompVal;

  console.log("Show all Array value="+searchVal +"=="+ optionVal +"=="+autocompVal);

  $("#autoComplete").autocomplete({
    source: autocompVal,
    select: function(event, ui) {
      this.value = ui.item.label;
      alert(this.value);
      return false;
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" rel="stylesheet" />
<input type="text" id="autoComplete"></code>```

Body:
I am trying to get data from json and push to array but it is not working. it is possible or not getting multiple object values from json. anybody can tell it is possible or not? if it is possible how we can do it and where i stucked from my code?

html

        <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

        <input type="text" id="autoComplete">

datas.json:

        {
            "searchVal": [
                 { "searchname":"test1"},
                 { "searchname":"test2"}
                 ],
            "optionVal": [
                 { "optionname":"test11"},
                 { "optionname":"test12"},
                 { "optionname":"test13"}
                 ],
           "autocompVal": [
                 { "test11"},
                 { "test12"} ,
                 { "test13"},
                 { "test14"}
                 ]
        }

Body:
Not quite sure what you mean, but json stands for Javascript Object notation.
So it's quite easy to get to its values.
data = your json object.
So

data.searchVal[0].searchName === "test1"
data.searchVal.forEach(function(searchVal){....})

so you could assign searchVal = data.searchVal, or better yet, simply use the single json object as is.

Edit: I see you want the searchName values out of the searchVal into a new array. You could do something like:

searchVal = data.searchVal.map(function(searchVal){
  return searchVal.searchName;
});

var searchVal, optionVal, autocompVal;

$(document).ready(function() {
  var data = {
    "searchVal": [{
        "searchname": "test1"
      },
      {
        "searchname": "test2"
      }
    ],
    "optionVal": [{
        "optionname": "test11"
      },
      {
        "optionname": "test12"
      },
      {
        "optionname": "test13"
      }
    ],
    "autocompVal": [
      "test11",
      "test12",
      "test13",
      "test14"
    ]
  };
  searchVal = data.searchVal.map(function(searchVal) {
    return searchVal.searchname;
  });
  optionVal = data.optionVal.map(function(optionVal) {
    return optionVal.optionname;
  });
  autocompVal = data.autocompVal;

  console.log("Show all Array value="+searchVal +"=="+ optionVal +"=="+autocompVal);

  $("#autoComplete").autocomplete({
    source: autocompVal,
    select: function(event, ui) {
      this.value = ui.item.label;
      alert(this.value);
      return false;
    }
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" rel="stylesheet" />
<input type="text" id="autoComplete">


问:
Django Rest Framework : Got AttributeError when attempting to get a value for field `data_params` on serializer `OrderCreateSerializer`
This is my models:

```<code>class Order(models.Model):
    """
    订单
    """
    order_num = models.CharField(max_length=128, unique=True)  # 订单编号
    order_status = models.CharField(max_length=12)  # 订单状态  "未支付"， "已支付，未完成"， "已完成"， "已经删除"，"其他"
    product_describe = models.TextField()  # 产品描述
    billing_type = models.CharField(max_length=16)  # 计费类型
    buytime = models.CharField(max_length=16)  # 比如：1月  永久
    count = models.IntegerField()  # 购买数量
    paytype = models.CharField(max_length=16)  # 支付方式（支付包，微信，xxx）
    cost = models.DecimalField(max_digits=8, decimal_places=2, default=0.00)  # 费用（需要花费多少钱）
    account = models.ForeignKey(to=Account) # 所属账户

    ctime = models.DateTimeField(auto_now_add=True)  # 创建时间
    uptime = models.DateTimeField(auto_now=True)  # 更新时间

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

This is my serializer:

```<code>class OrderCreateSerializer(ModelSerializer):

    data_params = serializers.DictField()  # 根据产品数据模型不同而异

    class Meta:
        model = Order
        fields = (
            "product_describe",  # 产品描述 (购买xx产品 + 参数)
            "billing_type", # 计费类型 ("包年包月")
            # "buytime", # "购买时间"
            # "count", # 数量
            # "paytype", # 支付方式
            "data_params",  # 数据
        )
    def create(self, validated_data):

        request = self.context.get("request")
        if request and hasattr(request, "user"):
            user = request.user

        validated_data["order_num"] = generateOrderNum(userid=user.id)
        validated_data["order_status"] = "未支付"

        data_dic = validated_data.pop("data_params") #

        validated_data["buytime"] = data_dic["data"]["buytime"]
        validated_data["count"] = data_dic["data"]["count"]
        validated_data["paytype"] = ""  # 支付类型

        validated_data["cost"] = 0.00  # 所需钱
        validated_data["account"] = user.account  # 是哪个账户

        return Order.objects.create(**validated_data)
</code>```

You see, in  my serializer I have pop the data_params:

```<code>data_dic = validated_data.pop("data_params")
</code>```

But when I access this API, I get:

AttributeError at /api/financialmanage/order/add/

  Got AttributeError when attempting to get a value for field data_params on serializer OrderCreateSerializer.

  The serializer field might be named incorrectly and not match any attribute or key on the Order instance.

  Original exception text was: 'Order' object has no attribute 'data_params'.

If I don't pop data_params, I will get bellow error:

TypeError at /api/financialmanage/order/add/

  'data_params' is an invalid keyword argument for this function

EDIT

My views.py:

```<code>class OrderSerializerCreateAPIView(CreateAPIView):
    """
    create Order
    """
    serializer_class = OrderCreateSerializer
    permission_classes = []
    queryset = Order.objects.all()
</code>```

EDIT-2

In my case the data_params dictionary is necessary for me.
Because when I buy a product(such as CloudServer), which has count, vcpus, ram, disk, and bandwidth, I through the data_params to get that.

You may want to know why I must use data_params to receive the data, because, the product may be different, if the product is Wine, it can not have the vcpus property now.

答:
```<code>class OrderCreateSerializer(ModelSerializer):
    data_params = DictField(child=serializers.CharField())
    .
    .
    .
    def create(self, validated_data):
        print(validated_data)

        data_dic = validated_data.pop("data_params")
        print(data_dic)
        return super(OrderCreateSerializer, self).create(validated_data)

class OrderSerializer(ModelSerializer):
    class Meta:
        model = Order
        fields = '__all__'

    # by @Vasil Shtiliyanov if you want return data_parms after create
    def to_representation(self, instance):
        serialized_data = super(OrderSerializer, self).to_representation(instance)
        serialized_data['data-params'] = #logic goes here
        return serialized_data

class OrderSerializerCreateAPIView(CreateAPIView):
    """
    create Order
    """
    serializer_class = OrderCreateSerializer
    permission_classes = []
    queryset = Order.objects.all()

   def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        instance = self.perform_create(serializer)
        data = OrderSerializer(instance).data
        headers = self.get_success_headers(data )
        return Response(data , status=status.HTTP_201_CREATED, headers=headers)

    def perform_create(self, serializer):
       return serializer.save()
</code>```

Body:
This is my models:

class Order(models.Model):
    """
    订单
    """
    order_num = models.CharField(max_length=128, unique=True)  # 订单编号
    order_status = models.CharField(max_length=12)  # 订单状态  "未支付"， "已支付，未完成"， "已完成"， "已经删除"，"其他"
    product_describe = models.TextField()  # 产品描述
    billing_type = models.CharField(max_length=16)  # 计费类型
    buytime = models.CharField(max_length=16)  # 比如：1月  永久
    count = models.IntegerField()  # 购买数量
    paytype = models.CharField(max_length=16)  # 支付方式（支付包，微信，xxx）
    cost = models.DecimalField(max_digits=8, decimal_places=2, default=0.00)  # 费用（需要花费多少钱）
    account = models.ForeignKey(to=Account) # 所属账户

    ctime = models.DateTimeField(auto_now_add=True)  # 创建时间
    uptime = models.DateTimeField(auto_now=True)  # 更新时间

    def __str__(self):
        return self.product_describe
    def __unicode__(self):
        return self.product_describe

This is my serializer:

class OrderCreateSerializer(ModelSerializer):

    data_params = serializers.DictField()  # 根据产品数据模型不同而异

    class Meta:
        model = Order
        fields = (
            "product_describe",  # 产品描述 (购买xx产品 + 参数)
            "billing_type", # 计费类型 ("包年包月")
            # "buytime", # "购买时间"
            # "count", # 数量
            # "paytype", # 支付方式
            "data_params",  # 数据
        )
    def create(self, validated_data):

        request = self.context.get("request")
        if request and hasattr(request, "user"):
            user = request.user

        validated_data["order_num"] = generateOrderNum(userid=user.id)
        validated_data["order_status"] = "未支付"

        data_dic = validated_data.pop("data_params") #

        validated_data["buytime"] = data_dic["data"]["buytime"]
        validated_data["count"] = data_dic["data"]["count"]
        validated_data["paytype"] = ""  # 支付类型

        validated_data["cost"] = 0.00  # 所需钱
        validated_data["account"] = user.account  # 是哪个账户

        return Order.objects.create(**validated_data)

You see, in  my serializer I have pop the data_params:

data_dic = validated_data.pop("data_params")

But when I access this API, I get:

AttributeError at /api/financialmanage/order/add/

  Got AttributeError when attempting to get a value for field data_params on serializer OrderCreateSerializer.

  The serializer field might be named incorrectly and not match any attribute or key on the Order instance.

  Original exception text was: 'Order' object has no attribute 'data_params'.

If I don't pop data_params, I will get bellow error:

TypeError at /api/financialmanage/order/add/

  'data_params' is an invalid keyword argument for this function

EDIT

My views.py:

class OrderSerializerCreateAPIView(CreateAPIView):
    """
    create Order
    """
    serializer_class = OrderCreateSerializer
    permission_classes = []
    queryset = Order.objects.all()

EDIT-2

In my case the data_params dictionary is necessary for me.
Because when I buy a product(such as CloudServer), which has count, vcpus, ram, disk, and bandwidth, I through the data_params to get that.

You may want to know why I must use data_params to receive the data, because, the product may be different, if the product is Wine, it can not have the vcpus property now.


答:
Look at the select tag:

Simply add <select name="course_id">. and this is done.

Title: Not able to get the Value from Drop down Menu


问:
Excel VBA inserting row
I have a little problem with my macro.
I just want to insert a dynamic number of rows, above a specific row which should copy everything from that specific row. So formatting, formulas, text, merged cells basically everything.

Now my code actually inserts the number of rows I need and it does copy the formatting. The stuff I am missing is the text/formulas in the cells and the cells are not merged at all(like in the row below).

what I have so far is this:

```<code>Set ins = wsCopyTo.Range("A100")

Do While k > 0 = True

   ins.EntireRow.Insert

k = k - 1

Loop
</code>```

now for easy reasons lets just assume k is 100 since as I said the number of rows which I insert is actually correct.

答:
This works:

```<code>Sub copyXrows()
Dim ins As Range
Dim k As Integer
Set ins = Tabelle1.Range("A10")

ins.Select
k = 2
Do While k > 0 = True

ins.EntireRow.Copy
ins.EntireRow.Insert

k = k - 1

Loop

End Sub
</code>```

You miss a entirerow.copy command.

Title: Excel VBA inserting row

Body:
I have a little problem with my macro.
I just want to insert a dynamic number of rows, above a specific row which should copy everything from that specific row. So formatting, formulas, text, merged cells basically everything.

Now my code actually inserts the number of rows I need and it does copy the formatting. The stuff I am missing is the text/formulas in the cells and the cells are not merged at all(like in the row below).

what I have so far is this:

Set ins = wsCopyTo.Range("A100")

Do While k > 0 = True

   ins.EntireRow.Insert

k = k - 1

Loop

now for easy reasons lets just assume k is 100 since as I said the number of rows which I insert is actually correct.

Body:
This works:

Sub copyXrows()
Dim ins As Range
Dim k As Integer
Set ins = Tabelle1.Range("A10")

ins.Select
k = 2
Do While k > 0 = True

ins.EntireRow.Copy
ins.EntireRow.Insert

k = k - 1

Loop

End Sub

You miss a entirerow.copy command.


问:
Upgrade to studio 3.0 is crashing my app with dalvik.system.BaseDexClassLoader.findClass
This is just happening after a migration from studio 2.x to studio 3.0 with android 4.4. Android 6 runs fine.
I googled this issue but didn't find crisp response. Just a particular app has this behavior. I have other apps which are fine.

The update process has broken something but what? Why is it impacting android 4.x only?

I tried clean sync, rebuild,restart studio, restart tablet, ...

here is my gradle:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'
    defaultConfig {
        applicationId "com.narb.test"
        minSdkVersion 18
        targetSdkVersion 24
        versionName '3.2'
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        versionNameSuffix '-9-nov-2017'
        multiDexEnabled true
        versionCode 53
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile files('libs/commons-net-3.5.jar')
    compile 'com.android.support:appcompat-v7:26.1.0'
    compile 'com.android.support:support-v4:26.1.0'
    compile 'com.google.android.gms:play-services-maps:10.0.1'
    testCompile 'junit:junit:4.12'
    compile 'org.jsoup:jsoup:1.10.3'
}
</code>```

and the logcat:

```<code>java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.narb.test/com.narb.test.MainActivity}: java.lang.ClassNotFoundException: Didn't find class "com.narb.test.MainActivity" on path: DexPathList[[zip file "/data/app/com.narb.test-29.apk"],nativeLibraryDirectories=[/data/app-lib/com.narb.test-29, /vendor/lib, /system/lib]]
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2470)
     at android.app.ActivityThread.access$900(ActivityThread.java:174)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1307)
     at android.os.Handler.dispatchMessage(Handler.java:102)
     at android.os.Looper.loop(Looper.java:146)
     at android.app.ActivityThread.main(ActivityThread.java:5593)
     at java.lang.reflect.Method.invokeNative(Native Method)
     at java.lang.reflect.Method.invoke(Method.java:515)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
     at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.narb.test.MainActivity" on path: DexPathList[[zip file "/data/app/com.narb.test-29.apk"],nativeLibraryDirectories=[/data/app-lib/com.narb.test-29, /vendor/lib, /system/lib]]
     at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:67)
     at java.lang.ClassLoader.loadClass(ClassLoader.java:497)
     at java.lang.ClassLoader.loadClass(ClassLoader.java:457)
     at android.app.Instrumentation.newActivity(Instrumentation.java:1067)
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2296)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2470)
     at android.app.ActivityThread.access$900(ActivityThread.java:174)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1307)
     at android.os.Handler.dispatchMessage(Handler.java:102)
     at android.os.Looper.loop(Looper.java:146)
     at android.app.ActivityThread.main(ActivityThread.java:5593)
     at java.lang.reflect.Method.invokeNative(Native Method)
     at java.lang.reflect.Method.invoke(Method.java:515)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
     at dalvik.system.NativeStart.main(Native Method)
</code>```

and the manifest:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.narb.test">

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

    <application
        android:allowBackup="true"
        android:largeHeap="true"
        android:configChanges="keyboardHidden|screenSize"
        android:icon="@drawable/networksafe"
        android:label="test"
        android:logo="@drawable/networksafe"
        android:screenOrientation="portrait"
        android:supportsRtl="true"

        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service
            android:name=".vpn.services"
            android:enabled="true"
            android:exported="true"
            android:permission="android.permission.BIND_VPN_SERVICE">

            <intent-filter>
                <action android:name="android.Net.Services"/>
            </intent-filter>
        </service>
        <activity
            android:name=".Activities.Settings"
            android:windowSoftInputMode="stateHidden" />
        <activity android:name=".Activities.About" />
        <activity android:name=".Activities.History" />

        <service
            android:name=".Socket"
            android:exported="false" />

        <service
            android:name=".ServiceMonitoring"
            android:exported="false" />

        <!--
             The API key for Google Maps-based APIs is defined as a string resource.
             (See the file "res/values/google_maps_api.xml").
             Note that the API key is linked to the encryption key used to sign the APK.
             You need a different API key for each encryption key, including the release key that is used to
             sign the APK for publishing.
             You can define the keys for the debug and release targets in src/debug/ and src/release/.
        -->
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

        <activity android:name=".Activities.RateMe"></activity>
    </application>

</manifest>
</code>```

答:
The crash was due to this line in build.gradle:

multiDexEnabled true

Once I removed this line the crash was gone.

I don't know why 2.3 has put this line originally but what is sure is that studio 3.0 made sdk 18 and below crash.

Body:
This is just happening after a migration from studio 2.x to studio 3.0 with android 4.4. Android 6 runs fine.
I googled this issue but didn't find crisp response. Just a particular app has this behavior. I have other apps which are fine.

The update process has broken something but what? Why is it impacting android 4.x only?

I tried clean sync, rebuild,restart studio, restart tablet, ...

here is my gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'
    defaultConfig {
        applicationId "com.narb.test"
        minSdkVersion 18
        targetSdkVersion 24
        versionName '3.2'
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        versionNameSuffix '-9-nov-2017'
        multiDexEnabled true
        versionCode 53
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile files('libs/commons-net-3.5.jar')
    compile 'com.android.support:appcompat-v7:26.1.0'
    compile 'com.android.support:support-v4:26.1.0'
    compile 'com.google.android.gms:play-services-maps:10.0.1'
    testCompile 'junit:junit:4.12'
    compile 'org.jsoup:jsoup:1.10.3'
}

and the logcat:

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.narb.test/com.narb.test.MainActivity}: java.lang.ClassNotFoundException: Didn't find class "com.narb.test.MainActivity" on path: DexPathList[[zip file "/data/app/com.narb.test-29.apk"],nativeLibraryDirectories=[/data/app-lib/com.narb.test-29, /vendor/lib, /system/lib]]
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2470)
     at android.app.ActivityThread.access$900(ActivityThread.java:174)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1307)
     at android.os.Handler.dispatchMessage(Handler.java:102)
     at android.os.Looper.loop(Looper.java:146)
     at android.app.ActivityThread.main(ActivityThread.java:5593)
     at java.lang.reflect.Method.invokeNative(Native Method)
     at java.lang.reflect.Method.invoke(Method.java:515)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
     at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.narb.test.MainActivity" on path: DexPathList[[zip file "/data/app/com.narb.test-29.apk"],nativeLibraryDirectories=[/data/app-lib/com.narb.test-29, /vendor/lib, /system/lib]]
     at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:67)
     at java.lang.ClassLoader.loadClass(ClassLoader.java:497)
     at java.lang.ClassLoader.loadClass(ClassLoader.java:457)
     at android.app.Instrumentation.newActivity(Instrumentation.java:1067)
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2296)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2470)
     at android.app.ActivityThread.access$900(ActivityThread.java:174)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1307)
     at android.os.Handler.dispatchMessage(Handler.java:102)
     at android.os.Looper.loop(Looper.java:146)
     at android.app.ActivityThread.main(ActivityThread.java:5593)
     at java.lang.reflect.Method.invokeNative(Native Method)
     at java.lang.reflect.Method.invoke(Method.java:515)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
     at dalvik.system.NativeStart.main(Native Method)

and the manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.narb.test">

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

    <application
        android:allowBackup="true"
        android:largeHeap="true"
        android:configChanges="keyboardHidden|screenSize"
        android:icon="@drawable/networksafe"
        android:label="test"
        android:logo="@drawable/networksafe"
        android:screenOrientation="portrait"
        android:supportsRtl="true"

        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service
            android:name=".vpn.services"
            android:enabled="true"
            android:exported="true"
            android:permission="android.permission.BIND_VPN_SERVICE">

            <intent-filter>
                <action android:name="android.Net.Services"/>
            </intent-filter>
        </service>
        <activity
            android:name=".Activities.Settings"
            android:windowSoftInputMode="stateHidden" />
        <activity android:name=".Activities.About" />
        <activity android:name=".Activities.History" />

        <service
            android:name=".Socket"
            android:exported="false" />

        <service
            android:name=".ServiceMonitoring"
            android:exported="false" />

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

        <activity android:name=".Activities.RateMe"></activity>
    </application>

</manifest>


问:
Atom package to save header/footer html code
I am using Atom IDE, I am searching for a package where I can store my header, footer etc code and simply put them in other pages, so I have to edit header footer in one place, I used to do this in Dreamweaver but not sure how to do that in Atom.</p>

答:
You can have your custom snippets in Atom IDE as well for that you will have to modify your snippets.cson file which is present in your %USERPROFILE%\.atom.

You can refer to Atom's flight manual docs: Creating your own Snippets.

And if you need multi line snippet you can have a look at: Multi line snippet body


问:
Why does code write this way the method indexOf() in String.class?
I'm reading the source code of String.class.

In the method indexOf() I see something I can't understand.

Here is the method indexOf() code snippet from String.class source code.

```<code>/**
 * Code shared by String and StringBuffer to do searches. The
 * source is the character array being searched, and the target
 * is the string being searched for.
 *
 * @param   source       the characters being searched.
 * @param   sourceOffset offset of the source string.
 * @param   sourceCount  count of the source string.
 * @param   target       the characters being searched for.
 * @param   targetOffset offset of the target string.
 * @param   targetCount  count of the target string.
 * @param   fromIndex    the index to begin searching from.
 */
static int indexOf(char[] source, int sourceOffset, int sourceCount,
        char[] target, int targetOffset, int targetCount,
        int fromIndex) {
    if (fromIndex >= sourceCount) {
        return (targetCount == 0 ? sourceCount : -1);
    }
    if (fromIndex < 0) {
        fromIndex = 0;
    }
    if (targetCount == 0) {
        return fromIndex;
    }

    char first = target[targetOffset];
    int max = sourceOffset + (sourceCount - targetCount);

    for (int i = sourceOffset + fromIndex; i <= max; i++) {
        /* Look for first character. */
        if (source[i] != first) {
            while (++i <= max && source[i] != first);
        }

        /* Found first character, now look at the rest of v2 */
        if (i <= max) {
            int j = i + 1;
            int end = j + targetCount - 1;
            for (int k = targetOffset + 1; j < end && source[j]
                    == target[k]; j++, k++);

            if (j == end) {
                /* Found whole string. */
                return i - sourceOffset;
            }
        }
    }
    return -1;
}
</code>```

I can't understand the code here.

```<code>if (fromIndex >= sourceCount) {
    return (targetCount == 0 ? sourceCount : -1);
}
</code>```

If the source String is "abcdedefg", sourceOffset is 2, sourceCount is 3,
and I want to search "d" from this,
why can't I search from index 4?

/**

* Ps:If the sourceCount means the length of the whole string, why not use source.length

* instead ?

*/

答:
```<code>    if (fromIndex >= sourceCount) {
        return (targetCount == 0 ? sourceCount : -1);
    }
</code>```

This says that in the search index (fromIndex) is after the end, string length (sourceCount), then return -1 (not found) unless the sought string is "" - which is "always found." Quite specific.

Body:
I'm reading the source code of String.class.

In the method indexOf() I see something I can't understand.

Here is the method indexOf() code snippet from String.class source code.

/**
 * Code shared by String and StringBuffer to do searches. The
 * source is the character array being searched, and the target
 * is the string being searched for.
 *
 * @param   source       the characters being searched.
 * @param   sourceOffset offset of the source string.
 * @param   sourceCount  count of the source string.
 * @param   target       the characters being searched for.
 * @param   targetOffset offset of the target string.
 * @param   targetCount  count of the target string.
 * @param   fromIndex    the index to begin searching from.
 */
static int indexOf(char[] source, int sourceOffset, int sourceCount,
        char[] target, int targetOffset, int targetCount,
        int fromIndex) {
    if (fromIndex >= sourceCount) {
        return (targetCount == 0 ? sourceCount : -1);
    }
    if (fromIndex < 0) {
        fromIndex = 0;
    }
    if (targetCount == 0) {
        return fromIndex;
    }

    char first = target[targetOffset];
    int max = sourceOffset + (sourceCount - targetCount);

    for (int i = sourceOffset + fromIndex; i <= max; i++) {
        /* Look for first character. */
        if (source[i] != first) {
            while (++i <= max && source[i] != first);
        }

        /* Found first character, now look at the rest of v2 */
        if (i <= max) {
            int j = i + 1;
            int end = j + targetCount - 1;
            for (int k = targetOffset + 1; j < end && source[j]
                    == target[k]; j++, k++);

            if (j == end) {
                /* Found whole string. */
                return i - sourceOffset;
            }
        }
    }
    return -1;
}

I can't understand the code here.

if (fromIndex >= sourceCount) {
    return (targetCount == 0 ? sourceCount : -1);
}

If the source String is "abcdedefg", sourceOffset is 2, sourceCount is 3,
and I want to search "d" from this,
why can't I search from index 4?

/**

* Ps:If the sourceCount means the length of the whole string, why not use source.length

* instead ?

*/

Body:
    if (fromIndex >= sourceCount) {
        return (targetCount == 0 ? sourceCount : -1);
    }

This says that in the search index (fromIndex) is after the end, string length (sourceCount), then return -1 (not found) unless the sought string is "" - which is "always found." Quite specific.


问:
Use the template parameter type of derived as return type for function (CRTP)?
I've recreated the problem I'm having in the code below:

```<code>template<typename T>
class A{
    using type = T::type;
    type someFunction(/*some parameters*/){/*code for the function*/}
    //other stuff
};

template<typename T>
class B : public A<B<T>>{
    typedef T type;
    //other stuff
};
</code>```

The problem is that I need to have A have a function with a return type of T::type, but because B isn't completely declared at the time when A is compiled, I get the error invalid use of incomplete type ‘class B<int>’ when I try to compile it (where int could be replaced with any other type). Is there any way to get this to work?

答:
You can achieve it if you move the definition of B<T>::type to an external traits-class:

```<code>template <typename T>
struct Traits { /* maybe some default values */ };

template<typename T>
class A{
    using type = typename Traits<T>::type;
    type someFunction(/*some parameters*/){/*code for the function*/}
    //other stuff
};

template<typename T>
class B : public A<B<T>>{
    using type = typename Traits<B<T>>::type;
};

template <typename T>
struct Traits<B<T>> {
    using type = T;
};
</code>```

Body:
I've recreated the problem I'm having in the code below:

template<typename T>
class A{
    using type = T::type;
    type someFunction(/*some parameters*/){/*code for the function*/}
    //other stuff
};

template<typename T>
class B : public A<B<T>>{
    typedef T type;
    //other stuff
};

The problem is that I need to have A have a function with a return type of T::type, but because B isn't completely declared at the time when A is compiled, I get the error invalid use of incomplete type ‘class B<int>’ when I try to compile it (where int could be replaced with any other type). Is there any way to get this to work?

Body:
You can achieve it if you move the definition of B<T>::type to an external traits-class:

template <typename T>
struct Traits { /* maybe some default values */ };

template<typename T>
class A{
    using type = typename Traits<T>::type;
    type someFunction(/*some parameters*/){/*code for the function*/}
    //other stuff
};

template<typename T>
class B : public A<B<T>>{
    using type = typename Traits<B<T>>::type;
};

template <typename T>
struct Traits<B<T>> {
    using type = T;
};


问:
Adding column names to dataframe while reading a csv in r
I have multiple .csv files in my directory which don't have a column name. So while reading them without header gives error

Error in match.names(clabs, names(xi)) :
    names do not match previous names.

So for that reason, I want to append column names to those csv files and combine them all to one single dataframe, but I'm not able to add a column name to those multiple csv file while reading them. File names are like test_abc.csv , test_pqr.csv, test_xyz.csv etc.
here is what I tried

```<code>temp = list.files(pattern="*.csv")
read_csv_filename <- function(filename){
  ret <- read.csv(filename,header = F)
  ret$city <- gsub(".*[_]([^.]+)[.].*", "\\1", filename)
  ret
}

df_all <- do.call(rbind,lapply(temp,read_csv_filename))
</code>```

How do I add header here to every file while reading?

This is a names that I want to add while reading

```<code>colnames = c("Age","Gender","height","weight")
</code>```

Any suggestion?

答:
You can put colnames inside the loop itself like this </p>

```<code>temp = list.files(pattern="*.csv")
read_csv_filename <- function(filename){
  ret <- read.csv(filename,header = F)
  ret$city <- gsub(".*[_]([^.]+)[.].*", "\\1", filename)
  colnames(ret) <- c("Age","Gender","height","weight","city")

  ret
}

df_all <- do.call(rbind,lapply(temp,read_csv_filename))
</code>```

Body:
I have multiple .csv files in my directory which don't have a column name. So while reading them without header gives error

Error in match.names(clabs, names(xi)) :
    names do not match previous names.

So for that reason, I want to append column names to those csv files and combine them all to one single dataframe, but I'm not able to add a column name to those multiple csv file while reading them. File names are like test_abc.csv , test_pqr.csv, test_xyz.csv etc.
here is what I tried

temp = list.files(pattern="*.csv")
read_csv_filename <- function(filename){
  ret <- read.csv(filename,header = F)
  ret$city <- gsub(".*[_]([^.]+)[.].*", "\\1", filename)
  ret
}

df_all <- do.call(rbind,lapply(temp,read_csv_filename))

How do I add header here to every file while reading?

This is a names that I want to add while reading

colnames = c("Age","Gender","height","weight")

Any suggestion?

Body:
You can put colnames inside the loop itself like this

temp = list.files(pattern="*.csv")
read_csv_filename <- function(filename){
  ret <- read.csv(filename,header = F)
  ret$city <- gsub(".*[_]([^.]+)[.].*", "\\1", filename)
  colnames(ret) <- c("Age","Gender","height","weight","city")

  ret
}

df_all <- do.call(rbind,lapply(temp,read_csv_filename))


问:
Status bar overlay image shifted down in android nought
I am trying to add an image to the status bar in xamarin forms android..
But the image is completely shifted down and coming under the normal status bar color i set in android nougat.

This happened when i updated the xamarin forms version to 2.4.0.74863
in 2.3.4.270 its working fine. Is this the xamrin forms issue or my code issue.

The code i used to draw overlay on status bar is

```<code>activity.Window.AddFlags(WindowManagerFlags.DrawsSystemBarBackgrounds);
                activity.Window.ClearFlags(WindowManagerFlags.TranslucentStatus);
                activity.Window.SetStatusBarColor(Android.Graphics.Color.Transparent);

ViewGroup contentView = (ViewGroup)activity.FindViewById(Android.Resource.Id.Content);
            //if (contentView.ChildCount > 1)
            //{
            //  contentView.RemoveViewAt(1);
            //}

            // get status bar height
            int res = activity.Resources.GetIdentifier("status_bar_height", "dimen", "android");
            int height = 0;
            if (res != 0)
                height = activity.Resources.GetDimensionPixelSize(res);

            // create new imageview and set resource id
            ImageView image = new ImageView(activity);
            LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, height);
            params1.Width = LinearLayout.LayoutParams.MatchParent;
            image.LayoutParameters = params1;
            image.SetImageResource(imageRes);

            image.SetScaleType(ImageView.ScaleType.FitXy);

            // add image view to content view
            contentView.AddView(image);
            contentView.SetFitsSystemWindows(true);
</code>```

I call this as a dependedncy from the xaml page.

EDIT

After i added the flags that @york mentioned the bottom navigation bar has become translucent and the app view went down.

答:
Just need add the following code in your Activity style :

```<code><style name="MyTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar">
    ...
    <item name="android:windowTranslucentStatus">false</item>
    <item name="android:windowTranslucentNavigation">true</item>
    <item name="android:statusBarColor">@android:color/transparent</item>
</style>
</code>```

Effect :

Body:
I am trying to add an image to the status bar in xamarin forms android..
But the image is completely shifted down and coming under the normal status bar color i set in android nougat.

This happened when i updated the xamarin forms version to 2.4.0.74863
in 2.3.4.270 its working fine. Is this the xamrin forms issue or my code issue.

The code i used to draw overlay on status bar is

activity.Window.AddFlags(WindowManagerFlags.DrawsSystemBarBackgrounds);
                activity.Window.ClearFlags(WindowManagerFlags.TranslucentStatus);
                activity.Window.SetStatusBarColor(Android.Graphics.Color.Transparent);

ViewGroup contentView = (ViewGroup)activity.FindViewById(Android.Resource.Id.Content);
            //if (contentView.ChildCount > 1)
            //{
            //  contentView.RemoveViewAt(1);
            //}

            // get status bar height
            int res = activity.Resources.GetIdentifier("status_bar_height", "dimen", "android");
            int height = 0;
            if (res != 0)
                height = activity.Resources.GetDimensionPixelSize(res);

            // create new imageview and set resource id
            ImageView image = new ImageView(activity);
            LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, height);
            params1.Width = LinearLayout.LayoutParams.MatchParent;
            image.LayoutParameters = params1;
            image.SetImageResource(imageRes);

            image.SetScaleType(ImageView.ScaleType.FitXy);

            // add image view to content view
            contentView.AddView(image);
            contentView.SetFitsSystemWindows(true);

I call this as a dependedncy from the xaml page.

EDIT

After i added the flags that @york mentioned the bottom navigation bar has become translucent and the app view went down.

Body:
Just need add the following code in your Activity style :

<style name="MyTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar">
    ...
    <item name="android:windowTranslucentStatus">false</item>
    <item name="android:windowTranslucentNavigation">true</item>
    <item name="android:statusBarColor">@android:color/transparent</item>
</style>

Effect :


问:
Handling of JOptionPane cancel button, which takes string as input
I want to take input as string from user through a Input dialog box, and also handle the situation if user presses cancel button.

Any suggestions?

答:
Try this:</p>

```<code>if(result == null){
    System.out.println("User pressed CANCEL, or window has been closed");
    System.exit(0);
}
</code>```

Body:
Try this:

if(result == null){
    System.out.println("User pressed CANCEL, or window has been closed");
    System.exit(0);
}


问:
Filling 2D Array with DIV-Container and display it
i want to program a 4x4 Game and need to create 2D Array to store Div-Containers within. My current Code is this:

```<code>$(function(){
var columns = 6;
var rows = 6;
var f = [];
var $square = $('<div class="squares"></div>');

for (var i = 0; i < columns; i++) {
    f[i] = [];
    for (var j = 0; j < rows; j++) {
        f[i][j] = $square;
    }
}
console.log(f);
    $('.board').appendTo(f);
});
</code>```

In the Console i see the Array is created correct. But i cant display it. It only shows something like:

```<code>[object Object],[object Object],[object Object],[object Object],[object
Object],[object Object][object Object],[object Object],[object Object],
[object Object],[object Object],[object Object][object Object],[object
Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object
Object],[object Object][object Object],[object Object],[object Object],
[object Object],[object Object],[object Object][object Object],[object
Object],[object Object],[object Object],[object Object],[object Object]
</code>```

What is the correct Method to show the generated DIV's corretly?

答:
Usually you'd want to store only the raw data in your array and then have a render function that reads the array and renders the objects (in your case seemingly squares)

From your example you'll have to print the objects in a loop since you're not telling the browser to print the objects but rather the array itself.

Try this:

```<code>for(i=0;i<f.length;i++)
{
    for(j=0;j<f[i].length;j++)
    {
        $('.board').appendTo(f[i][j]);
    }
}
</code>```

Body:
i want to program a 4x4 Game and need to create 2D Array to store Div-Containers within. My current Code is this:

$(function(){
var columns = 6;
var rows = 6;
var f = [];
var $square = $('

');

for (var i = 0; i < columns; i++) {
    f[i] = [];
    for (var j = 0; j < rows; j++) {
        f[i][j] = $square;
    }
}
console.log(f);
    $('.board').appendTo(f);
});

In the Console i see the Array is created correct. But i cant display it. It only shows something like:

[object Object],[object Object],[object Object],[object Object],[object
Object],[object Object][object Object],[object Object],[object Object],
[object Object],[object Object],[object Object][object Object],[object
Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object
Object],[object Object][object Object],[object Object],[object Object],
[object Object],[object Object],[object Object][object Object],[object
Object],[object Object],[object Object],[object Object],[object Object]

What is the correct Method to show the generated DIV's corretly?

Body:
Usually you'd want to store only the raw data in your array and then have a render function that reads the array and renders the objects (in your case seemingly squares)

From your example you'll have to print the objects in a loop since you're not telling the browser to print the objects but rather the array itself.

Try this:

for(i=0;i<f.length;i++)
{
    for(j=0;j<f[i].length;j++)
    {
        $('.board').appendTo(f[i][j]);
    }
}


问:
Blueprism: how to use the replace function in a calculation stage?
I am reading a text from an application using BluePrism. The text has the following structure (the number varies from case to case): "Please take note of your order reference: 525". I need to be able to extract the number from the text. Looking at the calculation stage, there is a replace function: replace(text, pattern, new-text). I want to use this function to replace all alphabetic characters in my text with an empty string to return only whatever is numeric. How can I input that in the pattern?
So I want something like this: </p>

```<code>Replace([Order confirmation text ], /^[A-z]+$/, " ")
</code>```

<p>Also, I tried to look for a proper documentation for the VBOs that are shipped with blueprism, but couldn't find any. Does anyone know where we can get documentations for blueprism functions? </p>

答:
The Replace() function in calculate stage is the simplest possible one. It's not a regex one!

So, if the stirng is always in that format, then you can use:

```<code>Replace([Text],"Please take note of your order reference:","")
</code>```

If the text is not always that standard, then you should rather use a regular expressions. To do that, you need to use an object, that will invoke a regex code.

In the standard blueprism objects, you can find:

```<code>Object: Utility - Strings C#
Action: Extract Regex Values
</code>```

I think there is no Regex Replace action, by default, so if you'd like to, then you have to implement it. Below you can find a code that I am using:

```<code>Dim R as New Regex(Regex_Pattern, RegexOptions.SingleLine)
Dim M as Match = R.Match(Text)
replacement_result = R.Replace(Text,Regex_Pattern,replacement_string)
</code>```

Body:
I am reading a text from an application using BluePrism. The text has the following structure (the number varies from case to case): "Please take note of your order reference: 525". I need to be able to extract the number from the text. Looking at the calculation stage, there is a replace function: replace(text, pattern, new-text). I want to use this function to replace all alphabetic characters in my text with an empty string to return only whatever is numeric. How can I input that in the pattern?
So I want something like this:

Replace([Order confirmation text ], /^[A-z]+$/, " ")

Also, I tried to look for a proper documentation for the VBOs that are shipped with blueprism, but couldn't find any. Does anyone know where we can get documentations for blueprism functions?

Body:
The Replace() function in calculate stage is the simplest possible one. It's not a regex one!

So, if the stirng is always in that format, then you can use:

Replace([Text],"Please take note of your order reference:","")

If the text is not always that standard, then you should rather use a regular expressions. To do that, you need to use an object, that will invoke a regex code.

In the standard blueprism objects, you can find:

Object: Utility - Strings C#
Action: Extract Regex Values

I think there is no Regex Replace action, by default, so if you'd like to, then you have to implement it. Below you can find a code that I am using:

Dim R as New Regex(Regex_Pattern, RegexOptions.SingleLine)
Dim M as Match = R.Match(Text)
replacement_result = R.Replace(Text,Regex_Pattern,replacement_string)

ContentLicense: CC BY-SA 4.0


问:
how can I relate webView and listView items using Fragment
In my app, there is a fragment class and webView class with simple xml files. I want to click a ListView item(mail, stack etc.), then loading their URL's. I could not it. please help.
This is fragment class:

```<code>public class frags extends Fragment {
   final String[] items={"google", "facebook", "twitter", "mail", "stack"};
</code>```

//there are some codes.

```<code>    myListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
        @Override
        public void onItemClick(AdapterView<?> parent, View v, int position, long id)  {

           intent = new Intent ( context, web.class);
           startActivity(intent);
        }
    });
    return vw;    }
</code>```

}

答:
In your Listview Click Listener Pass your Clicked Iitem Like this

```<code> myListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
        @Override
        public void onItemClick(AdapterView<?> parent, View v, int position, long id)  {

           intent = new Intent ( context, web.class);
           intent.putExtra("item_name",items.get(position));
           startActivity(intent);
        }
    });
</code>```

and in your web.class receive item name

```<code>Bundle b = getIntent.getExtras;
if(b.getString("item_name").equals("facebook")){
//open facebook url
}else if (b.getString("item_name").equals("twitter")){
//open twitter url
}
</code>```

Body:
In my app, there is a fragment class and webView class with simple xml files. I want to click a ListView item(mail, stack etc.), then loading their URL's. I could not it. please help.
This is fragment class:

public class frags extends Fragment {
   final String[] items={"google", "facebook", "twitter", "mail", "stack"};

//there are some codes.

    myListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
        @Override
        public void onItemClick(AdapterView<?> parent, View v, int position, long id)  {

           intent = new Intent ( context, web.class);
           startActivity(intent);
        }
    });
    return vw;    }

}

Body:
In your Listview Click Listener Pass your Clicked Iitem Like this

 myListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
        @Override
        public void onItemClick(AdapterView<?> parent, View v, int position, long id)  {

           intent = new Intent ( context, web.class);
           intent.putExtra("item_name",items.get(position));
           startActivity(intent);
        }
    });

and in your web.class receive item name

Bundle b = getIntent.getExtras;
if(b.getString("item_name").equals("facebook")){
//open facebook url
}else if (b.getString("item_name").equals("twitter")){
//open twitter url
}


问:
DynamoDB conflict resolution strategy
What is the conflict resolution strategy for DynamoDB ? The white paper on Dynamo talks about returning multiple versions by GetItem to be resolved by the client.

This SO  Question  says that Dynamo and DynamoDB are different and GetItem returns only one value. In that case, what is the conflict resolution strategy that DynamoDB employs ?

答:
As stated, your question is not very clear: "What is the conflict resolution strategy for DynamoDB" - what conflicts? Are you referring to potentially inconsistent reads?

DynamoDB, for GetItem queries, allows both eventual consistent and strongly consistent reads, configurable with a parameter on the request (as described in the docs here: http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.ReadConsistency.html). For strongly consistent reads the value returned is the most recent value at the time the query was executed. For eventual consistent reads it is possible to read a slightly out of date version of an item but there is no "conflict resolution" per se.

You may be thinking about conditional updates which allow for requests to fail if an expected condition is not met at the time the query is executed.

Title: DynamoDB conflict resolution strategy


问:
MonoDroid - setting background color from colors.xml throws InvalidOperationException
I have a simple layout as follows:

```<code><?xml version="1.0" encoding="utf-8"?>
  <LinearLayout
  android:id="@+id/widget30"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:background="@color/translucent_red"
  android:orientation="vertical"
  xmlns:android="http://schemas.android.com/apk/res/android">
</code>```

My colors.xml file is as follows:

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
  <color name="opaque_red">#f00</color>
  <color name="translucent_red">#80ff0000</color>
</resources>
</code>```

When I compile in VS2010 I get an error "System.InvalidOperationException: Command failed...." I have tried to place the colors.xml in res/values and res/color but I still
get the error. If I reference the color directly like:

```<code>android:background="#80ff0000"
</code>```

everything works fine.

Does anyone know if the colors.xml is supported by MonoDroid and if so why I'm getting this error?

Thanks for the help!

答: Figured it out, the Build Action for colors.xml was set to Content instead of AndroidResource !</p>

Body:
I have a simple layout as follows:

<?xml version="1.0" encoding="utf-8"?>
  <LinearLayout
  android:id="@+id/widget30"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:background="@color/translucent_red"
  android:orientation="vertical"
  xmlns:android="http://schemas.android.com/apk/res/android">

My colors.xml file is as follows:

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <color name="opaque_red">#f00</color>
  <color name="translucent_red">#80ff0000</color>
</resources>

When I compile in VS2010 I get an error "System.InvalidOperationException: Command failed...." I have tried to place the colors.xml in res/values and res/color but I still
get the error. If I reference the color directly like:

android:background="#80ff0000"

everything works fine.

Does anyone know if the colors.xml is supported by MonoDroid and if so why I'm getting this error?

Thanks for the help!


问:
Ignoring rows while using LOAD DATA LOCAL INFILE
I would like to skip 1st row from the csv I am loading.
Is there any option for that while using LOAD DATA LOCAL INFILE</p>

答:
You can use IGNORE 1 LINES or IGNORE 1 ROWS:

```<code>LOAD DATA INFILE 'example.txt' INTO TABLE table_name
IGNORE 1 LINES

-- or

LOAD DATA INFILE 'example.txt' INTO TABLE table_name
IGNORE 1 ROWS
</code>```

The IGNORE number LINES option can be used to ignore lines at the start of the file. For example, you can use IGNORE 1 LINES to skip over an initial header line containing column names.

Body:
You can use IGNORE 1 LINES or IGNORE 1 ROWS:

LOAD DATA INFILE 'example.txt' INTO TABLE table_name
IGNORE 1 LINES

-- or

LOAD DATA INFILE 'example.txt' INTO TABLE table_name
IGNORE 1 ROWS

The IGNORE number LINES option can be used to ignore lines at the start of the file. For example, you can use IGNORE 1 LINES to skip over an initial header line containing column names.


答:
Is there any way to get this to work?

You can use a traits class to derive the type instead of using:

```<code>using type = T::type;
</code>```

Example:

```<code>// Declare TypeSelector
template <typename T> struct TypeSelector;

template <typename T>
class A
{
    using type = typename TypeSelector<T>::type;
    type someFunction(/*some parameters*/){ return type {}; }
};

// Declare B.
template <typename T> class B;

// Define TypeSelector for <B<T>> first before defining B<T>
template <typename T> struct TypeSelector<B<T>>
{
    using type = T;
};

template<typename T>
class B : public A<B<T>>{
    using type = typename TypeSelector<T>::type;
    //other stuff
};

int main()
{
   // Compiles fine.
   B<int> a;
}
</code>```

Title: Use the template parameter type of derived as return type for function (CRTP)?

Body:
Is there any way to get this to work?

You can use a traits class to derive the type instead of using:

using type = T::type;

Example:

// Declare TypeSelector
template <typename T> struct TypeSelector;

template <typename T>
class A
{
    using type = typename TypeSelector<T>::type;
    type someFunction(/*some parameters*/){ return type {}; }
};

// Declare B.
template <typename T> class B;

// Define TypeSelector for <B<T>> first before defining B<T>
template <typename T> struct TypeSelector<B<T>>
{
    using type = T;
};

template<typename T>
class B : public A<B<T>>{
    using type = typename TypeSelector<T>::type;
    //other stuff
};

int main()
{
   // Compiles fine.
   B<int> a;
}