问:
spring validation: (portlet) issues such as noclassdeffounderror
I'm trying to get spring form validation working.
However I'm having some issues.

When I deploy my application I get:

```<code>Error creating bean wit
h name 'org.springframework.validation.beanvalidation.LocalValidatorFactoryBean#
0': Invocation of init method failed; nested exception is java.lang.NoSuchMethod
Error: org.slf4j.helpers.MessageFormatter.format(Ljava/lang/String;Ljava/lang/Ob
ject;)Lorg/slf4j/helpers/FormattingTuple;

Could not initialize class org.hibernate.validator.engine.ConfigurationImpl
</code>```

When I visit the page I get:

```<code>    org.springframework.beans.factory.BeanCreationException: Error creating bean wit
h name 'org.springframework.validation.beanvalidation.LocalValidatorFactoryBean#
0': Invocation of init method failed; nested exception is java.lang.NoClassDefFo
undError: Could not initialize class org.hibernate.validator.engine.Configuratio
nImpl
</code>```

Bean class:

```<code>public class User{
    @Min(13)
    private int age;
    private String name;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName(){
            return name;
    }

    public void setName(String name){
            this.name = name;
    }
}
</code>```

Controller snippet:

```<code>@ActionMapping(params = "myAction=validateUser")
    public void validateUser(ActionRequest request, ActionResponse response, ModelMap model, @ModelAttribute("user") @Valid User user, BindingResult result ){

        if(result.hasErrors()){
            for(ObjectError oe : result.getAllErrors()){
                System.out.println(oe.getDefaultMessage());
            }
        } else{
            //code
        }
    }
</code>```

JSP:

```<code><form:form action="${registerUser}" method="post" commandName="user">
    <b>User</b>
    <form:input path="age"/>
    <form:input path="name"/>
    <input type="submit" value="register"/>
</form:form>
</code>```

My userRegistration-portlet.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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        ">

    <mvc:annotation-driven />

    <import resource="spring-hibernate.xml"/>

    <context:component-scan base-package="com.johndoe.dao" />
    <context:component-scan base-package="com.johndoe.model" />
    <context:component-scan base-package="com.johndoe.service" />
    <context:component-scan base-package="com.johndoe.util" />
    <context:component-scan base-package="com.johndoe.controller" />

    <bean class="org.springframework.web.portlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>

    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>
</code>```

Pom.xml

```<code><dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-asm</artifactId>
            <version>3.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>3.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>3.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>3.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc-portlet</artifactId>
            <version>3.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>3.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>3.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>3.0.2.RELEASE</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.portlet</groupId>
            <artifactId>portlet-api</artifactId>
            <version>2.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.1.2</version>
        </dependency>
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-hibernate3</artifactId>
            <version>2.0.8</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate</artifactId>
            <version>3.2.7.ga</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>4.0.2.GA</version>
        </dependency>

    </dependencies>
</code>```

答:
Caused by: SPR-6817
So just added the tags myself.</p>

Body:
I'm trying to get spring form validation working.
However I'm having some issues.

When I deploy my application I get:

Error creating bean wit
h name 'org.springframework.validation.beanvalidation.LocalValidatorFactoryBean#
0': Invocation of init method failed; nested exception is java.lang.NoSuchMethod
Error: org.slf4j.helpers.MessageFormatter.format(Ljava/lang/String;Ljava/lang/Ob
ject;)Lorg/slf4j/helpers/FormattingTuple;

Could not initialize class org.hibernate.validator.engine.ConfigurationImpl

When I visit the page I get:

    org.springframework.beans.factory.BeanCreationException: Error creating bean wit
h name 'org.springframework.validation.beanvalidation.LocalValidatorFactoryBean#
0': Invocation of init method failed; nested exception is java.lang.NoClassDefFo
undError: Could not initialize class org.hibernate.validator.engine.Configuratio
nImpl

Bean class:

public class User{
    @Min(13)
    private int age;
    private String name;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName(){
            return name;
    }

    public void setName(String name){
            this.name = name;
    }
}

Controller snippet:

@ActionMapping(params = "myAction=validateUser")
    public void validateUser(ActionRequest request, ActionResponse response, ModelMap model, @ModelAttribute("user") @Valid User user, BindingResult result ){

        if(result.hasErrors()){
            for(ObjectError oe : result.getAllErrors()){
                System.out.println(oe.getDefaultMessage());
            }
        } else{
            //code
        }
    }

JSP:

<form:form action="${registerUser}" method="post" commandName="user">
    User
    <form:input path="age"/>
    <form:input path="name"/>
    <input type="submit" value="register"/>
</form:form>

My userRegistration-portlet.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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        ">

    <mvc:annotation-driven />

    <import resource="spring-hibernate.xml"/>

    <context:component-scan base-package="com.johndoe.dao" />
    <context:component-scan base-package="com.johndoe.model" />
    <context:component-scan base-package="com.johndoe.service" />
    <context:component-scan base-package="com.johndoe.util" />
    <context:component-scan base-package="com.johndoe.controller" />

    <bean class="org.springframework.web.portlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>

    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

Pom.xml

<dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-asm</artifactId>
            <version>3.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>3.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>3.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>3.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc-portlet</artifactId>
            <version>3.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>3.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>3.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>3.0.2.RELEASE</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.portlet</groupId>
            <artifactId>portlet-api</artifactId>
            <version>2.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.1.2</version>
        </dependency>
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-hibernate3</artifactId>
            <version>2.0.8</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate</artifactId>
            <version>3.2.7.ga</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>4.0.2.GA</version>
        </dependency>

    </dependencies>


来源: stackexchange

问:
Loop thru values code
This is what I’m trying to do:
When an order is created, click view link and and get redirected to the show page which contains the invoice.  I'm using the below code to loop thru values in the invoice. But its not working correctly, all invoices are showing up instead of only the selected one.
I already tried deleting the <% @orders.each do |order| %> but without any luck.

What am I missing here? Any idea?

```<code><% @orders.each do |order| %>
<% order.line_items.each do |line_item| %>
Order #<%= line_item.order_id %>
<%= order.first_name %> <%= order.last_name %>
<%= line_item.product.title %>
<%= number_to_currency line_item.product.price %>
<%= line_item.quantity %>
<%= number_to_currency line_item.total_price %>
<% end %>
<% end %>
</code>```

Update 1

route.rb: resources :orders, only: [:index, :new, :create, :show]

I don't have an invoice controller, everything is going thru the orders controller.

```<code>  def show
    @orders = Order.all
  end

 def new
    @cart = current_cart
    if @cart.line_items.empty?
    redirect_to root_url, notice: "Your cart is empty"
    return
    end

   @order = Order.new
    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @order }
   end
  end

  def create
    @order = Order.new(order_params)
    @order.add_line_items_from_cart(current_cart)
    @order.user_id = current_user.id

      if @order.save
      if @order.process
      redirect_to root_path, notice: "Successfully charged."
      and
      return
      end
    end
    render 'new'
  end
</code>```

答:
Change the method In Controller to

```<code> def show
    @order = Order.find(params[:id])
 end
</code>```

and in views remove

```<code><% @orders.each do |order| %>
</code>```

and call the order attributes by

```<code><% @order.line_items.each do |line_item| %>
  Order #<%= line_item.order_id %>
  <%= @order.first_name %> <%= @order.last_name %>
  <%= line_item.product.title %>
  <%= number_to_currency line_item.product.price %>
  <%= line_item.quantity %>
  <%= number_to_currency line_item.total_price %>
<% end %>
</code>```

you were showing all the orders instead you only need to show order that got created in latest.

ContentLicense: CC BY-SA 3.0

Title: Loop thru values code

Body:
This is what I’m trying to do:
When an order is created, click view link and and get redirected to the show page which contains the invoice.  I'm using the below code to loop thru values in the invoice. But its not working correctly, all invoices are showing up instead of only the selected one.
I already tried deleting the <% @orders.each do |order| %> but without any luck.

What am I missing here? Any idea?

<% @orders.each do |order| %>
<% order.line_items.each do |line_item| %>
Order #<%= line_item.order_id %>
<%= order.first_name %> <%= order.last_name %>
<%= line_item.product.title %>
<%= number_to_currency line_item.product.price %>
<%= line_item.quantity %>
<%= number_to_currency line_item.total_price %>
<% end %>
<% end %>

Update 1

route.rb: resources :orders, only: [:index, :new, :create, :show]

I don't have an invoice controller, everything is going thru the orders controller.

  def show
    @orders = Order.all
  end

 def new
    @cart = current_cart
    if @cart.line_items.empty?
    redirect_to root_url, notice: "Your cart is empty"
    return
    end

   @order = Order.new
    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @order }
   end
  end

  def create
    @order = Order.new(order_params)
    @order.add_line_items_from_cart(current_cart)
    @order.user_id = current_user.id

      if @order.save
      if @order.process
      redirect_to root_path, notice: "Successfully charged."
      and
      return
      end
    end
    render 'new'
  end

Body:
Change the method In Controller to

 def show
    @order = Order.find(params[:id])
 end

and in views remove

<% @orders.each do |order| %>

and call the order attributes by

<% @order.line_items.each do |line_item| %>
  Order #<%= line_item.order_id %>
  <%= @order.first_name %> <%= @order.last_name %>
  <%= line_item.product.title %>
  <%= number_to_currency line_item.product.price %>
  <%= line_item.quantity %>
  <%= number_to_currency line_item.total_price %>
<% end %>

you were showing all the orders instead you only need to show order that got created in latest.


问:
How to use ES6 exports to extend a Backbone Base View?
I have create a Base Backbone View (BaseView.js) using ES6 export default View.extend({}) and would like to use ES6 to then extend this view but having trouble doing this export default BaseView.extend({}) but I get ExtendedView is not a constuctor?

JS

```<code>// BaseView.js
export default View.extend({});
// ExtendedView.js
export default BaseView.extend({});
// Uncaught TypeError: ExtendedView is not a constructor
</code>```

答:
I am working with backbone and ES6 using "module.exports" instead of "export".

```<code>module.exports = class YourView extends Backbone.View {}
</code>```

I hope it helps.

Body:
I have create a Base Backbone View (BaseView.js) using ES6 export default View.extend({}) and would like to use ES6 to then extend this view but having trouble doing this export default BaseView.extend({}) but I get ExtendedView is not a constuctor?

JS

// BaseView.js
export default View.extend({});
// ExtendedView.js
export default BaseView.extend({});
// Uncaught TypeError: ExtendedView is not a constructor

Body:
I am working with backbone and ES6 using "module.exports" instead of "export".

module.exports = class YourView extends Backbone.View {}

I hope it helps.


问:
Convert 1D numpy.array([]) to numpy.array([[]])
Im calculating results for each rows in 2D-array.

```<code>import numpy as np
xyz = np.array([[1, 2, 100],[2, 5, 100]])
resultcolumn1 = (xyz[:,0]+xyz[:,1])*xyz[:,2]
>>array([300, 700])
>>type 'numpy.ndarray'>
</code>```

But when I'm trying to add this resultvector to rest of the 2D-array as a column

```<code>print np.concatenate((xyz, resultcolumn1.T), axis=1)
</code>```

I get this error:

ValueError: all the input arrays must have same number of dimensions.

Declaring the same vector with double brackets. Works:

```<code>resultcolumn2=np.array([[300, 700]])
>>>array([[300, 700]])
>>><type 'numpy.ndarray'>
np.concatenate((xyz, resultcolumn2.T), axis=1)
>>>[[  1   2 100 300]
    [  2   5 100 700]]
</code>```

How do I change resultcolumn1 to match resultcolumn2? Also could this process be done in better fashion?

答:
Simply add an extra dimension:

```<code>>>> np.concatenate((xyz, resultcolumn1.T[..., None]), axis=1)
array([[  1,   2, 100, 300],
       [  2,   5, 100, 700]])
</code>```

Also, note that for a 1d array, .T (i.e. transpose) does nothing so you can simply drop it:

```<code>>>> np.concatenate((xyz, resultcolumn1[..., None]), axis=1)
array([[  1,   2, 100, 300],
       [  2,   5, 100, 700]])
</code>```

Body:
Im calculating results for each rows in 2D-array.

import numpy as np
xyz = np.array([[1, 2, 100],[2, 5, 100]])
resultcolumn1 = (xyz[:,0]+xyz[:,1])*xyz[:,2]
>>array([300, 700])
>>type 'numpy.ndarray'>

But when I'm trying to add this resultvector to rest of the 2D-array as a column

print np.concatenate((xyz, resultcolumn1.T), axis=1)

I get this error:

ValueError: all the input arrays must have same number of dimensions.

Declaring the same vector with double brackets. Works:

resultcolumn2=np.array([[300, 700]])
>>>array([[300, 700]])
>>><type 'numpy.ndarray'>
np.concatenate((xyz, resultcolumn2.T), axis=1)
>>>[[  1   2 100 300]
    [  2   5 100 700]]

How do I change resultcolumn1 to match resultcolumn2? Also could this process be done in better fashion?

Body:
Simply add an extra dimension:

>>> np.concatenate((xyz, resultcolumn1.T[..., None]), axis=1)
array([[  1,   2, 100, 300],
       [  2,   5, 100, 700]])

Also, note that for a 1d array, .T (i.e. transpose) does nothing so you can simply drop it:

>>> np.concatenate((xyz, resultcolumn1[..., None]), axis=1)
array([[  1,   2, 100, 300],
       [  2,   5, 100, 700]])


问:
Using EPPlus Excel - How to ignore excel error checking or remove green tag on top left of the cell
I use EPPlus to export excel 2007 file. The file can export normally but i have some problem with setting column format. My string column with numeric style (Purchase Order No. ex. 49000001) be exported with green tag on the top left of the each cell, How can i remove it?

I try to set number format to "General" but it's not work

Please help.

p.s i use C#

答:
You can use    </p>

```<code>worksheet.Cell[1,1].Formula = "TEXT(" + cellvalue ")";
</code>```

Body:
You can use

worksheet.Cell[1,1].Formula = "TEXT(" + cellvalue ")";


问:
Swift 3: Be able to tap view behind a collectionViewCell?
I am working on a new feature in my app where I want a user to have an image and then be able to swipe through a collectionView on top of that image, adding "filters". The issue that I have is that I want the user to still be able to interact with the image, but it is behind the collectionView. If I set the collectionViews inUsersInteractionEnabled to false, of course I then cannot use the collectionView at all. I am going for a similar functionality to Snapchats "scroll through filters" feature. Any help will be highly appreciated. Thank you guys. Code is below:</p>

```<code>import UIKit

class FirstCell: UICollectionViewCell {

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
    }

    func setupViews() {
        backgroundColor = .clear
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

class SecondCell: UICollectionViewCell {

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
    }

    let cellView: UIView = {
        let view = UIView()
        view.backgroundColor = .red
        view.alpha = 0.25
        return view
    }()

    func setupViews() {
        backgroundColor = .clear
        addSubview(cellView)

        cellView.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

class SecondController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

    lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.scrollDirection = .horizontal
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.backgroundColor = .clear
        cv.dataSource = self
        cv.delegate = self
        cv.translatesAutoresizingMaskIntoConstraints = false
        cv.isPagingEnabled = true
        return cv
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView.register(FirstCell.self, forCellWithReuseIdentifier: "firstCell")
        collectionView.register(SecondCell.self, forCellWithReuseIdentifier: "secondCell")

        view.backgroundColor = .white

        setupViews()
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: view.frame.width, height: view.frame.height)
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 2
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        if indexPath.item == 0 {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "firstCell", for: indexPath) as! FirstCell
            return cell
        } else {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "secondCell", for: indexPath) as! SecondCell
            return cell
        }
    }

    lazy var imageView: UIImageView = {
        let iv = UIImageView()
        let image = UIImage(named: "img")
        iv.image = image
        iv.contentMode = .scaleAspectFill
        iv.translatesAutoresizingMaskIntoConstraints = false
        iv.isUserInteractionEnabled = true
        iv.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTap)))
        return iv
    }()

    func handleTap() {
        print(123)
    }

    func setupViews() {
        view.addSubview(imageView)
        view.addSubview(collectionView)

        imageView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        imageView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
        imageView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        imageView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true

        collectionView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        collectionView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
        collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        collectionView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
    }

}
</code>```

答:
There is a hitTest(_::) method available to override in any of the UIView subclass, which you can implement in your custom UICollectionView subclass and forward taps from it to any other view (the image behind collection view in your case).

```<code>override func hitTest(_ point: CGPoint,
                               with event: UIEvent?) -> UIView? {

    let hitView = super.hitTest(point, with: event)

    if self.parentViewController.forwardTapToImageIfNeeded(point) {
        return nil
    }

    return hitView
}
</code>```

Where parentViewController is a reference to your SecondController instance, which should have forwardTapToImageIfNeeded(_) function to check if user's tap is on top of the image frame, and if it is — automatically pass tap event to it.

```<code>func forwardTapToImageIfNeeded(_ p: CGPoint) -> Bool {
    /* Convert point to local coordinates */
    let pointInSuperView = self.convert(p, from: collectionView)
    /* Check if tap is on top of the image frame */
    if imageBehindCollection.frame.contains(pointInSuperView) {
        // Forward tap to the image `imageBehindCollection`
        return true
    }

    return false
}
</code>```

Note: I didn't test this particular code by myself, so it might need a few fixes in Xcode.

Body:
I am working on a new feature in my app where I want a user to have an image and then be able to swipe through a collectionView on top of that image, adding "filters". The issue that I have is that I want the user to still be able to interact with the image, but it is behind the collectionView. If I set the collectionViews inUsersInteractionEnabled to false, of course I then cannot use the collectionView at all. I am going for a similar functionality to Snapchats "scroll through filters" feature. Any help will be highly appreciated. Thank you guys. Code is below:

import UIKit

class FirstCell: UICollectionViewCell {

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
    }

    func setupViews() {
        backgroundColor = .clear
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

class SecondCell: UICollectionViewCell {

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
    }

    let cellView: UIView = {
        let view = UIView()
        view.backgroundColor = .red
        view.alpha = 0.25
        return view
    }()

    func setupViews() {
        backgroundColor = .clear
        addSubview(cellView)

        cellView.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

class SecondController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

    lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.scrollDirection = .horizontal
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.backgroundColor = .clear
        cv.dataSource = self
        cv.delegate = self
        cv.translatesAutoresizingMaskIntoConstraints = false
        cv.isPagingEnabled = true
        return cv
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView.register(FirstCell.self, forCellWithReuseIdentifier: "firstCell")
        collectionView.register(SecondCell.self, forCellWithReuseIdentifier: "secondCell")

        view.backgroundColor = .white

        setupViews()
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: view.frame.width, height: view.frame.height)
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 2
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        if indexPath.item == 0 {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "firstCell", for: indexPath) as! FirstCell
            return cell
        } else {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "secondCell", for: indexPath) as! SecondCell
            return cell
        }
    }

    lazy var imageView: UIImageView = {
        let iv = UIImageView()
        let image = UIImage(named: "img")
        iv.image = image
        iv.contentMode = .scaleAspectFill
        iv.translatesAutoresizingMaskIntoConstraints = false
        iv.isUserInteractionEnabled = true
        iv.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTap)))
        return iv
    }()

    func handleTap() {
        print(123)
    }

    func setupViews() {
        view.addSubview(imageView)
        view.addSubview(collectionView)

        imageView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        imageView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
        imageView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        imageView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true

        collectionView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        collectionView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
        collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        collectionView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
    }

}

Body:
There is a hitTest(_::) method available to override in any of the UIView subclass, which you can implement in your custom UICollectionView subclass and forward taps from it to any other view (the image behind collection view in your case).

override func hitTest(_ point: CGPoint,
                               with event: UIEvent?) -> UIView? {

    let hitView = super.hitTest(point, with: event)

    if self.parentViewController.forwardTapToImageIfNeeded(point) {
        return nil
    }

    return hitView
}

Where parentViewController is a reference to your SecondController instance, which should have forwardTapToImageIfNeeded(_) function to check if user's tap is on top of the image frame, and if it is — automatically pass tap event to it.

func forwardTapToImageIfNeeded(_ p: CGPoint) -> Bool {
    /* Convert point to local coordinates */
    let pointInSuperView = self.convert(p, from: collectionView)
    /* Check if tap is on top of the image frame */
    if imageBehindCollection.frame.contains(pointInSuperView) {
        // Forward tap to the image `imageBehindCollection`
        return true
    }

    return false
}

Note: I didn't test this particular code by myself, so it might need a few fixes in Xcode.


问:
NotFoundHttpException in RouteCollection.php line 161: error

I get the NotFoundHttpException in RouteCollection.php line 161: but I can't find the error. I'm using Laravel 5.4.

I ran php artisan route:list command and I see the defined (named) route.

And here is the route file.

```<code><?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', 'LinkController@create');

Route::post('/create', 'LinkController@store');

Route::get('show/{id}', 'LinkController@show')->name('show');
</code>```

And here is the part from the resource controller.

```<code>public function store(Request $request)
{
    $this->validate($request, [
        'url' => 'required|url'
    ]);

    // Generate string length of 6 characters
    $newHash = Str::random(6);

    // creates a $link object
    $link = new Link;

    //checks if link already exists in the database
    $link_in_db = DB::table('links')->where('url', '=', $request->url)->get();

    if($link_in_db === null){
        // sets the $link variables
        $link->url = $request->url;
        $link->hash = $newHash;

        // $link is saved in the database
        $link->save();

        // redirects to the route
        return redirect()->route('show', $link->id);
    }else{ // link is in the database
        // print_r($link_in_db); // testing purposes
        return redirect()->route('show', $link->id);
    }
}
</code>```

And I highly appreciate any suggestion. If there are any other methods to redirect with data, please suggest.

Thank you!

答:
show route should be GET:

```<code>Route::get('show/{id}', 'LinkController@show')->name('show');
</code>```

Body:
I get the NotFoundHttpException in RouteCollection.php line 161: but I can't find the error. I'm using Laravel 5.4.

I ran php artisan route:list command and I see the defined (named) route.

And here is the route file.

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', 'LinkController@create');

Route::post('/create', 'LinkController@store');

Route::get('show/{id}', 'LinkController@show')->name('show');

And here is the part from the resource controller.

public function store(Request $request)
{
    $this->validate($request, [
        'url' => 'required|url'
    ]);

    // Generate string length of 6 characters
    $newHash = Str::random(6);

    // creates a $link object
    $link = new Link;

    //checks if link already exists in the database
    $link_in_db = DB::table('links')->where('url', '=', $request->url)->get();

    if($link_in_db === null){
        // sets the $link variables
        $link->url = $request->url;
        $link->hash = $newHash;

        // $link is saved in the database
        $link->save();

        // redirects to the route
        return redirect()->route('show', $link->id);
    }else{ // link is in the database
        // print_r($link_in_db); // testing purposes
        return redirect()->route('show', $link->id);
    }
}

And I highly appreciate any suggestion. If there are any other methods to redirect with data, please suggest.

Thank you!

Body:
show route should be GET:

Route::get('show/{id}', 'LinkController@show')->name('show');


问:
Controlling initial shift status (and layout?) of iPhone keyboard from web form
I would like to be able to control the initial shift state of the iPhone keyboard from a Javascript prompt (updates added for web forms). It seems to mostly default to an initial capital but I feel sure I've typed into/seen prompts that are initially lower-case. I also feel sure that I've seen custom layouts used from the web.

Googling around initially (see updates) didn't reveal any obvious documentation or previous answers besides saying that having "phone" or "zip" in the class of the input would bring up the numeric keyboard (although this may have stopped working). Apparently "url" or "email" could select the appropriate layouts also. This obviously doesn't apply to javascript prompts, and may not work in some versions.

Is there any official source for all this stuff? Does it work across all firmware versions? Has anyone got a general solution for changing keyboard layout or for doing this in Javascript prompts?

UPDATE
For web forms: found this from Apple straight after posting the question, along with this. The question still stands for Javascript prompts.

UPDATE 2
Doh! This is also useful; placeholder text and search button not mentioned in the Apple links. Some more relevant info here.

答:
How do I control which keyboard is displayed when a user touches a text field?
You can control which type of keyboard is displayed when a user touches a text field in a web page. To display a telephone keypad, an email keyboard, or a URL keyboard, use the tel, email, or url keywords for the type attribute on an input element, respectively. To display a numeric keyboard, set the value of the pattern attribute to "[0-9]" or "\d".

These keywords and the pattern attribute are part of HTML 5, and are available in iPhone OS 3.1 and later. See Listing 15 to see how to display each type of keyboard, including the standard keyboard.

Listing 15: Controlling keyboard display
Text:
Telephone:
URL:
Email:
Zip Code:

See http://developer.apple.com/library/safari/#codinghowtos/Mobile/UserExperience/index.html

ContentLicense: CC BY-SA 2.5


问:
repmat vs simple matrix multiplication in MATLAB
Let v be a row vector of length n. The goal is to create a matrix A with m rows that are all equal to v.

MATLAB has a function for this that is called repmat. Possible code would be

A = repmat(v,[m 1])

There is an alternative equally concise way using simple matrix operations

A = ones(m,1)*v

Is any of the two methods preferable for large m and n?

答:
Lets compare them!

When testing algorithms 2 metrics are important: time, and memory.

Lets start with time:

Clearly repmat wins!

Memory:

```<code>profile -memory on
for m=1000:1000:50000
f1=@()(repmat(v,[m 1]));
f2=@()(ones(m,1)*v);
ii=ii+1;
t1(ii)=timeit(f1);
t2(ii)=timeit(f2);
end
profreport
</code>```

It seems that both take the same amount of memory. However, the profiler is known for not showing all the memory, so we can not fully trust it.

Still, it is clear that repmat is better

Body:
Lets compare them!

When testing algorithms 2 metrics are important: time, and memory.

Lets start with time:

Clearly repmat wins!

Memory:

profile -memory on
for m=1000:1000:50000
f1=@()(repmat(v,[m 1]));
f2=@()(ones(m,1)*v);
ii=ii+1;
t1(ii)=timeit(f1);
t2(ii)=timeit(f2);
end
profreport

It seems that both take the same amount of memory. However, the profiler is known for not showing all the memory, so we can not fully trust it.

Still, it is clear that repmat is better


问:
Convert canvas to an image with resize
My code is working fine its convert canvas into image but i want to give exact height & width of an Image, My code is below

```<code>//Converts canvas to image
    function convertCanvasToImage(can) {
            var image = new Image();
            image.src = can.toDataURL("image/jpg");
            return image;
        }
</code>```

// Converts image to canvas; returns new canvas element

```<code>function convertImageToCanvas(image) {
    var canvas = document.createElement("canvas");
    canvas.width = image.width;
    canvas.height = image.height;
    canvas.getContext("2d").drawImage(image, 0, 0);

    return canvas;
}
</code>```

How can i give height & width of image on my 1st code which is convert canvas to image

答:
Unless you are downloading or uploading the canvas there is no need to convert it to an image. Using a DataURL for the image src uses much more memory that using the canvas element directly in place of an image.

You can set the canvas or image display size using the element's style.width and height properties

```<code>element.style.width = w + "px";
element.style.height = h + "px";
</code>```

Title: Convert canvas to an image with resize

Body:
My code is working fine its convert canvas into image but i want to give exact height & width of an Image, My code is below

//Converts canvas to image
    function convertCanvasToImage(can) {
            var image = new Image();
            image.src = can.toDataURL("image/jpg");
            return image;
        }

// Converts image to canvas; returns new canvas element

function convertImageToCanvas(image) {
    var canvas = document.createElement("canvas");
    canvas.width = image.width;
    canvas.height = image.height;
    canvas.getContext("2d").drawImage(image, 0, 0);

    return canvas;
}

How can i give height & width of image on my 1st code which is convert canvas to image

Body:
Unless you are downloading or uploading the canvas there is no need to convert it to an image. Using a DataURL for the image src uses much more memory that using the canvas element directly in place of an image.

You can set the canvas or image display size using the element's style.width and height properties

element.style.width = w + "px";
element.style.height = h + "px";


问:
C++ macro expression containing return (like Rust's try!)
Rust has a macro which is an expression that either evaluates to some value, or returns from the function. Is there any way to do this in C++?

Something like this:

```<code>struct Result
{
    bool ok;
    int value;
}

Result foo() { ... }

#define TRY(x) (auto& ref = (x), ref.ok ? ref.value : return -1)

int main()
{
    int i = TRY(foo());
}
</code>```

Unfortunately it doesn't work because return is a statement not an expression. There are other problems with the above code but it roughly gives an idea of what I want. Does anyone have any bright ideas?

答:
Thanks to NathanOliver's link it looks like you can do it with statement expressions which are apparently only supported by Clang and GCC. Something like this:</p>

```<code>#define TRY(x)                                                     \
    ({                                                             \
        auto& ref = (x);                                           \
        if (!ref.ok) {                                             \
            return -1;                                             \
        }                                                          \
        ref.value; // The block evaluates to the last expression.  \
    })
</code>```

Body:
Rust has a macro which is an expression that either evaluates to some value, or returns from the function. Is there any way to do this in C++?

Something like this:

struct Result
{
    bool ok;
    int value;
}

Result foo() { ... }

#define TRY(x) (auto& ref = (x), ref.ok ? ref.value : return -1)

int main()
{
    int i = TRY(foo());
}

Unfortunately it doesn't work because return is a statement not an expression. There are other problems with the above code but it roughly gives an idea of what I want. Does anyone have any bright ideas?

Body:
Thanks to NathanOliver's link it looks like you can do it with statement expressions which are apparently only supported by Clang and GCC. Something like this:

#define TRY(x)                                                     \
    ({                                                             \
        auto& ref = (x);                                           \
        if (!ref.ok) {                                             \
            return -1;                                             \
        }                                                          \
        ref.value; // The block evaluates to the last expression.  \
    })


问:
ASTNode - qualifiedName.getFullyQualifiedName() does not return package name
I have written a plugin that returns the fully qualified names for that code in the editor that my cursor lies on.

When the cursor lies on WHITE within the line jButton[i].setForeground(Color.WHITE);, I need to get the following information: java.awt.Color.White.

I am wondering why qualifiedName.getFullyQualifiedName() returns Color.WHITE without the name of the package.

Is there any possibility to get the name of the package except for extracting the name from what qualifiedName.resolveBinding().getKey() returns, i.e. Ljava/awt/Color;.WHITE)Ljava/awt/Color; ?

This is how I get the qualifiedName:

```<code>IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
IEditorPart editor = page.getActiveEditor();
ITextSelection sel = (ITextSelection) editor.getSite().getSelectionProvider().getSelection();
ITypeRoot root = JavaUI.getEditorInputTypeRoot(editor.getEditorInput());
ICompilationUnit cU = (ICompilationUnit) root.getAdapter(ICompilationUnit.class);
CompilationUnit compilationUnit = parse(cU);
NodeFinder finder = new NodeFinder(compilationUnit, sel.getOffset(),
    sel.getLength());
QualifiedName qualifiedName = (QualifiedName) finder.getCoveringNode();
</code>```

Any help is appreciated.

答:
You can construct the qualified name including the package yourself. Here is a basic example. You may need to add code to cover other situations.

```<code>IBinding nameBinding = qualifiedName.resolveBinding();
if (nameBinding != null && nameBinding.getKind() == IBinding.VARIABLE) {
    IVariableBinding variableBinding = (IVariableBinding) nameBinding;
    String result = variableBinding.getDeclaringClass().getQualifiedName() + '.' + variableBinding.getName();
}
</code>```

A little word of warning when analyzing AST bindings. Always check bindings for being null. I can't stress this enough.

Body:
I have written a plugin that returns the fully qualified names for that code in the editor that my cursor lies on.

When the cursor lies on WHITE within the line jButton[i].setForeground(Color.WHITE);, I need to get the following information: java.awt.Color.White.

I am wondering why qualifiedName.getFullyQualifiedName() returns Color.WHITE without the name of the package.

Is there any possibility to get the name of the package except for extracting the name from what qualifiedName.resolveBinding().getKey() returns, i.e. Ljava/awt/Color;.WHITE)Ljava/awt/Color; ?

This is how I get the qualifiedName:

IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
IEditorPart editor = page.getActiveEditor();
ITextSelection sel = (ITextSelection) editor.getSite().getSelectionProvider().getSelection();
ITypeRoot root = JavaUI.getEditorInputTypeRoot(editor.getEditorInput());
ICompilationUnit cU = (ICompilationUnit) root.getAdapter(ICompilationUnit.class);
CompilationUnit compilationUnit = parse(cU);
NodeFinder finder = new NodeFinder(compilationUnit, sel.getOffset(),
    sel.getLength());
QualifiedName qualifiedName = (QualifiedName) finder.getCoveringNode();

Any help is appreciated.

Body:
You can construct the qualified name including the package yourself. Here is a basic example. You may need to add code to cover other situations.

IBinding nameBinding = qualifiedName.resolveBinding();
if (nameBinding != null && nameBinding.getKind() == IBinding.VARIABLE) {
    IVariableBinding variableBinding = (IVariableBinding) nameBinding;
    String result = variableBinding.getDeclaringClass().getQualifiedName() + '.' + variableBinding.getName();
}

A little word of warning when analyzing AST bindings. Always check bindings for being null. I can't stress this enough.


问:
How can I pass code into a method without it running first?
Please help as how can I achieve below in java.

```<code>public class TestUserFunctions {

    public static boolean equals(int val1, int val2){
        if(val1==val2){
            return true;
        } else{
            return false;
        }
    }
    public static Object iterateValue(String ittr, int iterations){
        for(int i=1; i <= iterations; i++){
            System.out.println("Printing iteration #"+i);
        }
        return ittr;
    }

    private static void ifElse(boolean condition, Object returnstr, Object elsestr){
        if(condition){
            System.out.println("TRUE");
            //Need a code here which will iterate string value only once.
        } else{
            System.out.println("FALSE");
            //Need a code here which will iterate string value thrice as specified.
        }
    }

    public static void main(String[] args){
        ifElse(equals(1, 1), iterateValue("Value", 1), iterateValue("Value", 3));
    }
}
</code>```

I may be wrong in many aspect here with my above code. I am sorry for that.
The expected output here is

```<code>TRUE
Printing iteration #1
</code>```

In case of ifElse(equals(1, 1), iterateValue("Value", 1), iterateValue("Value", 3)); the expected output is

```<code>FALSE
Printing iteration #1
Printing iteration #2
Printing iteration #3
</code>```

答:
You need to defer execution of the if and else block using Java 8 lambda expressions to obtain what you want to achieve

```<code>import java.util.function.Supplier;

public class TestUserFunctions {

    public static Supplier<Boolean> equals(int val1, int val2){
        if(val1==val2){
            return () -> true;
        } else{
            return () -> false;
        }
    }
    public static Supplier<String> iterateValue(String ittr, int iterations){
      return () ->  {
         for(int i=1; i <= iterations; i++){
            System.out.println("Printing iteration #"+i);
         }
        return ittr;
      };
    }

    private static void ifElse(Supplier<Boolean> condition, Supplier<String> returnstr, Supplier<String> elsestr){
        if(condition.get()){
            System.out.println("TRUE");
            returnstr.get();
        } else{
            System.out.println("FALSE");
            elsestr.get();
        }
    }

    public static void main(String[] args){
        ifElse(equals(1, 1), iterateValue("Value", 1), iterateValue("Value", 3));
    }
}
</code>```

Using Java < 8 the readability is greatly decreased

```<code>interface Supplier<T> {
  public T get();
}

public class TestUserFunctions {

    public static Supplier<Boolean> equals(int val1, int val2){
        if(val1==val2){
          return new Supplier<Boolean>() {
            public Boolean get() { return true; }
          };
        } else{
          return new Supplier<Boolean>() {
            public Boolean get() { return false; }
          };
        }
    }
    public static Supplier<String> iterateValue(String ittr, int iterations){
      return new Supplier<String>() {
        public String get() {
          for(int i=1; i <= iterations; i++){
            System.out.println("Printing iteration #"+i);
          }
          return ittr;
        };
      };
    }

    private static void ifElse(Supplier<Boolean> condition, Supplier<String> returnstr, Supplier<String> elsestr){
        if(condition.get()){
            System.out.println("TRUE");
            returnstr.get();
        } else{
            System.out.println("FALSE");
            elsestr.get();
        }
    }

    public static void main(String[] args){
        ifElse(equals(1, 2), iterateValue("Value", 1), iterateValue("Value", 3));
    }
}
</code>```

Body:
Please help as how can I achieve below in java.

public class TestUserFunctions {

    public static boolean equals(int val1, int val2){
        if(val1==val2){
            return true;
        } else{
            return false;
        }
    }
    public static Object iterateValue(String ittr, int iterations){
        for(int i=1; i <= iterations; i++){
            System.out.println("Printing iteration #"+i);
        }
        return ittr;
    }

    private static void ifElse(boolean condition, Object returnstr, Object elsestr){
        if(condition){
            System.out.println("TRUE");
            //Need a code here which will iterate string value only once.
        } else{
            System.out.println("FALSE");
            //Need a code here which will iterate string value thrice as specified.
        }
    }

    public static void main(String[] args){
        ifElse(equals(1, 1), iterateValue("Value", 1), iterateValue("Value", 3));
    }
}

I may be wrong in many aspect here with my above code. I am sorry for that.
The expected output here is

TRUE
Printing iteration #1

In case of ifElse(equals(1, 1), iterateValue("Value", 1), iterateValue("Value", 3)); the expected output is

FALSE
Printing iteration #1
Printing iteration #2
Printing iteration #3

Body:
You need to defer execution of the if and else block using Java 8 lambda expressions to obtain what you want to achieve

import java.util.function.Supplier;

public class TestUserFunctions {

    public static Supplier<Boolean> equals(int val1, int val2){
        if(val1==val2){
            return () -> true;
        } else{
            return () -> false;
        }
    }
    public static Supplier<String> iterateValue(String ittr, int iterations){
      return () ->  {
         for(int i=1; i <= iterations; i++){
            System.out.println("Printing iteration #"+i);
         }
        return ittr;
      };
    }

    private static void ifElse(Supplier<Boolean> condition, Supplier<String> returnstr, Supplier<String> elsestr){
        if(condition.get()){
            System.out.println("TRUE");
            returnstr.get();
        } else{
            System.out.println("FALSE");
            elsestr.get();
        }
    }

    public static void main(String[] args){
        ifElse(equals(1, 1), iterateValue("Value", 1), iterateValue("Value", 3));
    }
}

Using Java < 8 the readability is greatly decreased

interface Supplier<T> {
  public T get();
}

public class TestUserFunctions {

    public static Supplier<Boolean> equals(int val1, int val2){
        if(val1==val2){
          return new Supplier<Boolean>() {
            public Boolean get() { return true; }
          };
        } else{
          return new Supplier<Boolean>() {
            public Boolean get() { return false; }
          };
        }
    }
    public static Supplier<String> iterateValue(String ittr, int iterations){
      return new Supplier<String>() {
        public String get() {
          for(int i=1; i <= iterations; i++){
            System.out.println("Printing iteration #"+i);
          }
          return ittr;
        };
      };
    }

    private static void ifElse(Supplier<Boolean> condition, Supplier<String> returnstr, Supplier<String> elsestr){
        if(condition.get()){
            System.out.println("TRUE");
            returnstr.get();
        } else{
            System.out.println("FALSE");
            elsestr.get();
        }
    }

    public static void main(String[] args){
        ifElse(equals(1, 2), iterateValue("Value", 1), iterateValue("Value", 3));
    }
}


问:
Java Reading Strings to a 2D Boolean Array
I am trying to read a txt file which consists of # and spaces to a 2D boolean array, so that technically a # represents true and a space represents false.

With the help of similar posts i got together a code, although they were reading integers to an array.

My code is:

```<code>public static void main(String[] args) {
    String x;
    String y;
    Scanner fileName = null;
    try {
        fileName = new Scanner(new File("C:/Users/USER/Desktop/hashtag.txt"));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    x = fileName.nextLine();
    y = fileName.nextLine();

    boolean[][] cells = new boolean[x][y];

    String finalX = fileName.nextLine();
    String finalY = fileName.nextLine();
    cells[finalX][finalY] = true;

    for (int i = 0; i < cells.length; i++) {
        for (int j = 0; j < cells[i].length; j++) {
            if (cells[i][j])
                System.out.print("#");
            else
                System.out.print(" ");
        }
        System.out.println();
    }

}
</code>```

In my code where I have written boolean[][] cells = new boolean[x][y];

It says the [x] and [y] requires an int, but found a string. The same issue is for cells[finalX][finalY] = true;

I tried parsing i.e. Integer.parseInt(x) however this gets me an error:
Exception in thread "main" java.lang.NumberFormatException: For input string: "#####################"

At what point is my issue? If I parse to an Int, then it can't read the # correct?

答:
I think this would solve it:

1- read each line of file until the end of it to get the number of cells rows which is n then take length of any String line to get number of columns which is m.

2- create boolean array cells[n][m].

3- read file line by line and put each line in String variable and iterate over the string variable characters if character is # put true in cells array otherwise put false.

```<code>      String line="";
      int n=0;
      while(fileName.hasNextLine()){
        line = fileName.nextLine();
        n++;
      }
      int m = line.length();
      boolean[][] cells = new boolean[n][m];
      // initialize Scanner to read file again
      Scanner in = new Scanner(new File("C:/Users/USER/Desktop/hashtag.txt"));
      int i=0;
      while(in.hasNextLine()){
            line = in.nextLine();
        for(int j=0; j < line.length(); j++){
            char c = line.charAt(j);
            if(c == '#'){
                cells[i][j] = true;
            }
            else{
                cells[i][j] = false;
            }
        }
        i++;
     }
</code>```

Body:
I am trying to read a txt file which consists of # and spaces to a 2D boolean array, so that technically a # represents true and a space represents false.

With the help of similar posts i got together a code, although they were reading integers to an array.

My code is:

public static void main(String[] args) {
    String x;
    String y;
    Scanner fileName = null;
    try {
        fileName = new Scanner(new File("C:/Users/USER/Desktop/hashtag.txt"));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    x = fileName.nextLine();
    y = fileName.nextLine();

    boolean[][] cells = new boolean[x][y];

    String finalX = fileName.nextLine();
    String finalY = fileName.nextLine();
    cells[finalX][finalY] = true;

    for (int i = 0; i < cells.length; i++) {
        for (int j = 0; j < cells[i].length; j++) {
            if (cells[i][j])
                System.out.print("#");
            else
                System.out.print(" ");
        }
        System.out.println();
    }

}

In my code where I have written boolean[][] cells = new boolean[x][y];

It says the [x] and [y] requires an int, but found a string. The same issue is for cells[finalX][finalY] = true;

I tried parsing i.e. Integer.parseInt(x) however this gets me an error:
Exception in thread "main" java.lang.NumberFormatException: For input string: "#####################"

At what point is my issue? If I parse to an Int, then it can't read the # correct?

Body:
I think this would solve it:

1- read each line of file until the end of it to get the number of cells rows which is n then take length of any String line to get number of columns which is m.

2- create boolean array cells[n][m].

3- read file line by line and put each line in String variable and iterate over the string variable characters if character is # put true in cells array otherwise put false.

      String line="";
      int n=0;
      while(fileName.hasNextLine()){
        line = fileName.nextLine();
        n++;
      }
      int m = line.length();
      boolean[][] cells = new boolean[n][m];
      // initialize Scanner to read file again
      Scanner in = new Scanner(new File("C:/Users/USER/Desktop/hashtag.txt"));
      int i=0;
      while(in.hasNextLine()){
            line = in.nextLine();
        for(int j=0; j < line.length(); j++){
            char c = line.charAt(j);
            if(c == '#'){
                cells[i][j] = true;
            }
            else{
                cells[i][j] = false;
            }
        }
        i++;
     }


问:
Linq to objects List in list
I have a list of movies

```<code>List<Movie> MovieList
</code>```

and I have a list of selected categories

```<code>List<string> SelCat
</code>```

And say I want to select from the movie list where it matches 2 categories, like the SQL statement below:

SELECT * FROM MovieList WHERE MovieList.Category = 'Action' AND MovieList.Category = 'Drama'

I can get kinda close with linq like so:

var q = (from b in MovieList where b.Categories.Any(p=> SelCat.Contains(p)) select b);

But it acts like an OR query, not an AND. I want it to select all movies that have a category of action and drama.

BTW: Movie.Categories is a List of string. AND Movie.Categories must contain items in the SelCat.

How do I achieve this with Linq to Objects?

答:
```<code>var q = from m in MovieList where SelCat.All(c => m.Categories.Contains(c))
</code>```

Quite close to what you would say describing the problem in English:

Select movies where the movie categories contain all the categories in SelCat.

Title: Linq to objects List in list

Body:
I have a list of movies

List<Movie> MovieList

and I have a list of selected categories

List<string> SelCat

And say I want to select from the movie list where it matches 2 categories, like the SQL statement below:

SELECT * FROM MovieList WHERE MovieList.Category = 'Action' AND MovieList.Category = 'Drama'

I can get kinda close with linq like so:

var q = (from b in MovieList where b.Categories.Any(p=> SelCat.Contains(p)) select b);

But it acts like an OR query, not an AND. I want it to select all movies that have a category of action and drama.

BTW: Movie.Categories is a List of string. AND Movie.Categories must contain items in the SelCat.

How do I achieve this with Linq to Objects?

Body:
var q = from m in MovieList where SelCat.All(c => m.Categories.Contains(c))

Quite close to what you would say describing the problem in English:

Select movies where the movie categories contain all the categories in SelCat.


问:
Find if value exists in multiple list and get names of it
I found similar question, but I'm not able to convert answer to match my needs.
(Find if value exists in multiple lists)

So, basicly, I have multiple lists, and I want to list all of them, which contain current user username.

```<code>import getpass

value = getpass.getuser()
rep_WOHTEL = ['user1','user2','user3']
rep_REPDAY = ['user4','user1','user3']
rep_ZARKGL = ['user3','user1','user2']
rep_WOHOPL = ['user3','user2','user5']

#No idea how code below works
w = next(n for n,v in filter(lambda t: isinstance(t[1],list) and t[0].startswith('rep_'), globals().items()) if value in v)
print(w)
</code>```

If current user is user1, I want it to print rep_WOHTEL, rep_REPDAY and rep_ZARKGL. Code above print only ony of them.

How should I change this part of script, to print all I want?

答:
Checking if value is in all global lists, and if true, print which list(s) contains the required value.

Code:

```<code>rep_WOHTEL = ['user1','user2','user3']
rep_REPDAY = ['user4','user1','user3']
rep_ZARKGL = ['user3','user1','user2']
rep_WOHOPL = ['user3','user2','user5']

value = 'user1'
x = globals().items()
for n,v in filter(lambda t: isinstance(t[1],list) and t[0].startswith('rep_'), x):
    if value in v:
        print(n)
</code>```

Output:

```<code>rep_REPDAY
rep_ZARKGL
rep_WOHTEL
</code>```

More info about the used functions:

globals()

dict.items()

filter()

isinstance()

startswith()

Body:
I found similar question, but I'm not able to convert answer to match my needs.
(Find if value exists in multiple lists)

So, basicly, I have multiple lists, and I want to list all of them, which contain current user username.

import getpass

value = getpass.getuser()
rep_WOHTEL = ['user1','user2','user3']
rep_REPDAY = ['user4','user1','user3']
rep_ZARKGL = ['user3','user1','user2']
rep_WOHOPL = ['user3','user2','user5']

#No idea how code below works
w = next(n for n,v in filter(lambda t: isinstance(t[1],list) and t[0].startswith('rep_'), globals().items()) if value in v)
print(w)

If current user is user1, I want it to print rep_WOHTEL, rep_REPDAY and rep_ZARKGL. Code above print only ony of them.

How should I change this part of script, to print all I want?

Body:
Checking if value is in all global lists, and if true, print which list(s) contains the required value.

Code:

rep_WOHTEL = ['user1','user2','user3']
rep_REPDAY = ['user4','user1','user3']
rep_ZARKGL = ['user3','user1','user2']
rep_WOHOPL = ['user3','user2','user5']

value = 'user1'
x = globals().items()
for n,v in filter(lambda t: isinstance(t[1],list) and t[0].startswith('rep_'), x):
    if value in v:
        print(n)

Output:

rep_REPDAY
rep_ZARKGL
rep_WOHTEL

More info about the used functions:

globals()

dict.items()

filter()

isinstance()

startswith()


问:
DataHandler structure for creating parent/child record relations
I'm trying to create nested record structures using TYPO3's DataHandler data structures (tested with TYPO3 v7). However relations are not created as expected. Consider the following data structure:

        $data = array(
                'sys_category' =>
                        array(
                                'NEW_1' =>
                                        array(
                                                'title' => 'Category 1',
                                                'pid' => $pid,
                                        ),
                                'NEW_2' =>
                                        array(
                                                'title' => 'Category 3',
                                                'pid' => $pid,
                                        ),
                                'NEW_3' =>
                                        array(
                                                'title' => 'Category 2',
                                                'pid' => $pid,
                                        ),
                                'NEW_4' =>
                                        array(
                                                'title' => 'Category 1.1',
                                                'pid' => $pid,
                                                'parent' => 'NEW_1',
                                        ),
                                'NEW_5' =>
                                        array(
                                                'title' => 'Category 1.2',
                                                'pid' => $pid,
                                                'parent' => 'NEW_1',
                                        ),
                                'NEW_6' =>
                                        array(
                                                'title' => 'Category 3.1',
                                                'pid' => $pid,
                                                'parent' => 'NEW_2',
                                        ),
                        ),
        );
```

<p>This gives the following result in the database:</p>

```uid title           parent
1   Category 1      0
2   Category 3      0
3   Category 2      0
4   Category 1.1    0
5   Category 1.2    0
6   Category 3.1    0
```

Note the "0" value for all "parent" fields. Why is it that the "NEW_*" values are not interpreted for the "parent" fields set in the data structure?

答:
As mentioned in a comment above, the situation changed between TYPO3 6.2 and 7.6. The difference lies in \TYPO3\CMS\Core\DataHandling\DataHandler::processRemapStack(). Starting with TYPO3 7.6, it checks if the "NEW*" placeholders contain a low dash (_). If yes, the placeholder is split on that character and the first part of the string is considered to be the related table name.

This is a change from before, where the low dash had no special meaning. Indeed, the documentation mentions examples using a low dash.

So the above code works fine with just removing the low dash from all the placeholders.

Body:
I'm trying to create nested record structures using TYPO3's DataHandler data structures (tested with TYPO3 v7). However relations are not created as expected. Consider the following data structure:

        $data = array(
                'sys_category' =>
                        array(
                                'NEW_1' =>
                                        array(
                                                'title' => 'Category 1',
                                                'pid' => $pid,
                                        ),
                                'NEW_2' =>
                                        array(
                                                'title' => 'Category 3',
                                                'pid' => $pid,
                                        ),
                                'NEW_3' =>
                                        array(
                                                'title' => 'Category 2',
                                                'pid' => $pid,
                                        ),
                                'NEW_4' =>
                                        array(
                                                'title' => 'Category 1.1',
                                                'pid' => $pid,
                                                'parent' => 'NEW_1',
                                        ),
                                'NEW_5' =>
                                        array(
                                                'title' => 'Category 1.2',
                                                'pid' => $pid,
                                                'parent' => 'NEW_1',
                                        ),
                                'NEW_6' =>
                                        array(
                                                'title' => 'Category 3.1',
                                                'pid' => $pid,
                                                'parent' => 'NEW_2',
                                        ),
                        ),
        );

This gives the following result in the database:

uid title           parent
1   Category 1      0
2   Category 3      0
3   Category 2      0
4   Category 1.1    0
5   Category 1.2    0
6   Category 3.1    0

Note the "0" value for all "parent" fields. Why is it that the "NEW_*" values are not interpreted for the "parent" fields set in the data structure?


问:
functions with arguments in Django's template
I have formally constructed the function in my models.py file :

```<code>from datetime import datetime
from django.template.defaultfilters import date as datefilter
from django.utils import translation

def date_customerprofile(language):
    now_ = datetime.today()
    if language == 'English':
        translation.activate('en')
        return datefilter(now_, 'l, F j, Y')
    else:
        translation.activate('fr')
        return datefilter(now_, 'l, j F Y')
</code>```

I would like to use this function in a template, but it is unclear it will work fine. I'd like to use {{ date_customerprofile('French') }}, but it didn't work. Any suggestions?

Thanks!

答:
I'd like to use {{ date_customerprofile('French') }}, but it didn't work

Of course. Django's template language is NOT Python. It's smart enough to apply some lookup rules on objects but does not allow functions or method calls - and yes, this is by design:

If you have a background in programming, or if you’re used to languages which mix programming code directly into HTML, you’ll want to bear in mind that the Django template system is not simply Python embedded into HTML. This is by design: the template system is meant to express presentation, not program logic.

https://docs.djangoproject.com/en/1.10/ref/templates/language/

The solution here is to create a custom templatetag. Also note that translation.activate will change the active language for the remaining of the request/response cycle which is certainly not what you want - using the translation.override context manager is certainly a better idea.

Finally it looks like you're reinventing the square wheel - the correct language should already be activated for the current request so instead of manually forcing it (with a non standard language code), you should probably just use the current one to select the appropriate date format.

Body:
I have formally constructed the function in my models.py file :

from datetime import datetime
from django.template.defaultfilters import date as datefilter
from django.utils import translation

def date_customerprofile(language):
    now_ = datetime.today()
    if language == 'English':
        translation.activate('en')
        return datefilter(now_, 'l, F j, Y')
    else:
        translation.activate('fr')
        return datefilter(now_, 'l, j F Y')

I would like to use this function in a template, but it is unclear it will work fine. I'd like to use {{ date_customerprofile('French') }}, but it didn't work. Any suggestions?

Thanks!


问:
Best practice for configuration in multi maven projects
given the following spring boot application layout:

```<code>app
  --api
  --component
  --data
  --xyz
libs
  --lib1
  --lib2
</code>```

Each one is a seperate maven project where "app" contains the spring bootstrap class. Other modules are maven dependencies that are used within the application.

Each modules comes with its own profiled property file (application-dev.properies, application-qa.properties...)

What is the best way to consolidate now all property files within the application?

答:
My proposal for consolidation:

Each module defines own profile, for example:

application-DEV-lib1.properties

application-QA-lib1.properties

application-DEV-lib2.properties

application-QA-lib2.properties

app defines profiles DEV and QA:

application-DEV.properties

```<code>spring.profiles.include=DEV-lib1,DEV-lib2
aaa=123
...
</code>```

application-QA.properties

```<code>spring.profiles.include=QA-lib1,QA-lib2
aaa=456
...
</code>```

Body:
given the following spring boot application layout:

app
  --api
  --component
  --data
  --xyz
libs
  --lib1
  --lib2

Each one is a seperate maven project where "app" contains the spring bootstrap class. Other modules are maven dependencies that are used within the application.

Each modules comes with its own profiled property file (application-dev.properies, application-qa.properties...)

What is the best way to consolidate now all property files within the application?

Body:
My proposal for consolidation:

Each module defines own profile, for example:

application-DEV-lib1.properties

application-QA-lib1.properties

application-DEV-lib2.properties

application-QA-lib2.properties

app defines profiles DEV and QA:

application-DEV.properties

spring.profiles.include=DEV-lib1,DEV-lib2
aaa=123
...

application-QA.properties

spring.profiles.include=QA-lib1,QA-lib2
aaa=456
...


问:
Webshpere Cast Iron Salesforce integration Unable to retrieve AccountContactRelation object from Salesforce
I am trying to retrieve records from Account Contact Relationship object in Salesforce in Cast Iron, but I am prompted with "Object type 'accountcontactrelation' unknown" error.</p>

答: found the answer to my question.  the cast iron orchestration is using salesforce api v29.  the account contact relation object is only available for api v32 or higher</p>


问:
Python Importing exact hexa value and display
I have the Data structure where I defined the list.

```<code>data_items = [  {"ID":0x0202,  "Name":"Country"},
                { "ID":0x2007, "Name":"Sports"}]
</code>```

I want to import complete 'ID' value including '0', like example:

```<code>'0202'
'2007'
</code>```

Now it is printing as below:

```<code>'202'
'2007'
</code>```

Code:

```<code>Input = 1
SMI = data_items[Input-1]['ID']
hex(SMI)[2:]
</code>```

Suggest me how can I proceed?

答: hex removes any leading zeros. If you want to maintain a length of 4 characters in the string, try doing hex(SMI)[2:].zfill(4) where it will ad leading zeros until it reaches the specified length.

Body:
I have the Data structure where I defined the list.

data_items = [  {"ID":0x0202,  "Name":"Country"},
                { "ID":0x2007, "Name":"Sports"}]

I want to import complete 'ID' value including '0', like example:

'0202'
'2007'

Now it is printing as below:

'202'
'2007'

Code:

Input = 1
SMI = data_items[Input-1]['ID']
hex(SMI)[2:]

Suggest me how can I proceed?


问:
JSON Array of objects to plain old java object
this is my first time making an external api call in Java, so please bear with me as I'm not very experienced. I got the http request working and got a response, but now I need to parse it.

I'm trying to convert a json array to java objects. I understand the gist of it, but all examples I've seen don't apply to my issue.

I need the 'entities' objects from the json string. The details (which are an array, too) can contain any key/value pair, so I was thinking of putting that in a hashmap in each Entity object. I've tried the gson library, but I can't find any gson example that goes deeper than a single dimensional json array.

I realize this is kind of a broad question, and I don't expect anyone to deliver me a working solution, but a few tips or a link to a relevant guide would go a long way. :)

```<code>{
   "return": {
      "entities": [
         {
            "id": 2385,
            "details": [
               {
                  "name": "Other Known Name",
                  "value": "John Wick",
                  "match": false
               }
            ],
            "proofs": [],
            "link": "http://domain.gg/users?id=2385"
         },
         {
            "id": 2384,
            "details": [
               {
                  "name": "Discord ID",
                  "value": "159985870458322944",
                  "match": false
               },
               {
                  "name": "SteamID64",
                  "value": "76561197991558078",
                  "match": true
               },
               {
                  "name": "SteamVanity",
                  "value": "test",
                  "match": false
               },
               {
                  "name": "PS4",
                  "value": "John_S",
                  "match": false
               },
               {
                  "name": "XBox",
                  "value": "John S",
                  "match": false
               },
               {
                  "name": "Email",
                  "value": "john_smith@gmail.com",
                  "match": true
               },
               {
                  "name": "Comment",
                  "value": "Test user",
                  "match": false
               },
               {
                  "name": "Other Known Name",
                  "value": "Jonathan",
                  "match": false
               },
               {
                  "name": "Reddit",
                  "value": "/u/johns",
                  "match": true
               }
            ],
            "proofs": [],
            "link": "http://domain.gg/users?id=2384"
         },
         {
            "id": 1680,
            "details": [
               {
                  "name": "Other Known Name",
                  "value": "Johny",
                  "match": false
               },
               {
                  "name": "SteamID64",
                  "value": "76561198213003675",
                  "match": true
               }
            ],
            "proofs": [],
            "link": "http://domain.gg/users?id=1680"
         },
         {
            "id": 1689,
            "details": [
               {
                  "name": "Other Known Name",
                  "value": "JohnnyPeto",
                  "match": false
               },
               {
                  "name": "SteamID64",
                  "value": "76561198094228192",
                  "match": true
               }
            ],
            "proofs": [],
            "link": "http://domain.gg/users?id=1689"
         }
      ],
      "notice": "Showing 4 out of 4 matches."
   }
}
</code>```

答:
There are many json serialization/deserialization frameworks available. I would recommend having a look at Jackson.

Basically, you have to create Model corresponding to json schema and deserialize json into object. Based on the example in the question, model will look like this:

```<code>@JsonIgnoreProperties(ignoreUnknown = true)
class Response {

    @JsonProperty("return")
    private ResponseObject responseObject;

    public ResponseObject getResponseObject() {
        return responseObject;
    }

    public void setResponseObject(ResponseObject responseObject) {
        this.responseObject = responseObject;
    }
}

@JsonIgnoreProperties(ignoreUnknown = true)
class ResponseObject {
    private List<Entity> entities;

    public List<Entity> getEntities() {
        return entities;
    }

    public void setEntities(List<Entity> entities) {
        this.entities = entities;
    }

}

@JsonIgnoreProperties(ignoreUnknown = true)
class Entity {
    private String id;
    private List<Details> details;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public List<Details> getDetails() {
        return details;
    }

    public void setDetails(List<Details> details) {
        this.details = details;
    }

}

@JsonIgnoreProperties(ignoreUnknown = true)
class Details {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
</code>```

Once the model is defined, you can use ObjectMapper class to perform serialization/deserialization, e.g.:

```<code>ObjectMapper mapper = new ObjectMapper();
Response response = mapper.readValue("{\"return\": {\"entities\": [{\"id\": 2385,\"details\": [{\"name\": \"Other Known Name\",\"value\": \"John Wick\",\"match\": false}],\"proofs\": [],\"link\": \"http://domain.gg/users?id=2385\"},{\"id\": 2384,\"details\": [{\"name\": \"Discord ID\",\"value\": \"159985870458322944\",\"match\": false},{\"name\": \"SteamID64\",\"value\": \"76561197991558078\",\"match\": true},{\"name\": \"SteamVanity\",\"value\": \"test\",\"match\": false},{\"name\": \"PS4\",\"value\": \"John_S\",\"match\": false},{\"name\": \"XBox\",\"value\": \"John S\",\"match\": false},{\"name\": \"Email\",\"value\": \"john_smith@gmail.com\",\"match\": true},{\"name\": \"Comment\",\"value\": \"Test user\",\"match\": false},{\"name\": \"Other Known Name\",\"value\": \"Jonathan\",\"match\": false},{\"name\": \"Reddit\",\"value\": \"/u/johns\",\"match\": true}],\"proofs\": [],\"link\": \"http://domain.gg/users?id=2384\"},{\"id\": 1680,\"details\": [{\"name\": \"Other Known Name\",\"value\": \"Johny\",\"match\": false},{\"name\": \"SteamID64\",\"value\": \"76561198213003675\",\"match\": true}],\"proofs\": [],\"link\": \"http://domain.gg/users?id=1680\"},{\"id\": 1689,\"details\": [{\"name\": \"Other Known Name\",\"value\": \"JohnnyPeto\",\"match\": false},{\"name\": \"SteamID64\",\"value\": \"76561198094228192\",\"match\": true}],\"proofs\": [],\"link\": \"http://domain.gg/users?id=1689\"}],\"notice\": \"Showing 4 out of 4 matches.\"}}", Response.class);
System.out.println(response.getResponseObject().getEntities().get(0).getId());
</code>```

Here's the Javadoc.

Body:
this is my first time making an external api call in Java, so please bear with me as I'm not very experienced. I got the http request working and got a response, but now I need to parse it.

I'm trying to convert a json array to java objects. I understand the gist of it, but all examples I've seen don't apply to my issue.

I need the 'entities' objects from the json string. The details (which are an array, too) can contain any key/value pair, so I was thinking of putting that in a hashmap in each Entity object. I've tried the gson library, but I can't find any gson example that goes deeper than a single dimensional json array.

I realize this is kind of a broad question, and I don't expect anyone to deliver me a working solution, but a few tips or a link to a relevant guide would go a long way. :)

{
   "return": {
      "entities": [
         {
            "id": 2385,
            "details": [
               {
                  "name": "Other Known Name",
                  "value": "John Wick",
                  "match": false
               }
            ],
            "proofs": [],
            "link": "http://domain.gg/users?id=2385"
         },
         {
            "id": 2384,
            "details": [
               {
                  "name": "Discord ID",
                  "value": "159985870458322944",
                  "match": false
               },
               {
                  "name": "SteamID64",
                  "value": "76561197991558078",
                  "match": true
               },
               {
                  "name": "SteamVanity",
                  "value": "test",
                  "match": false
               },
               {
                  "name": "PS4",
                  "value": "John_S",
                  "match": false
               },
               {
                  "name": "XBox",
                  "value": "John S",
                  "match": false
               },
               {
                  "name": "Email",
                  "value": "john_smith@gmail.com",
                  "match": true
               },
               {
                  "name": "Comment",
                  "value": "Test user",
                  "match": false
               },
               {
                  "name": "Other Known Name",
                  "value": "Jonathan",
                  "match": false
               },
               {
                  "name": "Reddit",
                  "value": "/u/johns",
                  "match": true
               }
            ],
            "proofs": [],
            "link": "http://domain.gg/users?id=2384"
         },
         {
            "id": 1680,
            "details": [
               {
                  "name": "Other Known Name",
                  "value": "Johny",
                  "match": false
               },
               {
                  "name": "SteamID64",
                  "value": "76561198213003675",
                  "match": true
               }
            ],
            "proofs": [],
            "link": "http://domain.gg/users?id=1680"
         },
         {
            "id": 1689,
            "details": [
               {
                  "name": "Other Known Name",
                  "value": "JohnnyPeto",
                  "match": false
               },
               {
                  "name": "SteamID64",
                  "value": "76561198094228192",
                  "match": true
               }
            ],
            "proofs": [],
            "link": "http://domain.gg/users?id=1689"
         }
      ],
      "notice": "Showing 4 out of 4 matches."
   }
}

Body:
There are many json serialization/deserialization frameworks available. I would recommend having a look at Jackson.

Basically, you have to create Model corresponding to json schema and deserialize json into object. Based on the example in the question, model will look like this:

@JsonIgnoreProperties(ignoreUnknown = true)
class Response {

    @JsonProperty("return")
    private ResponseObject responseObject;

    public ResponseObject getResponseObject() {
        return responseObject;
    }

    public void setResponseObject(ResponseObject responseObject) {
        this.responseObject = responseObject;
    }
}

@JsonIgnoreProperties(ignoreUnknown = true)
class ResponseObject {
    private List<Entity> entities;

    public List<Entity> getEntities() {
        return entities;
    }

    public void setEntities(List<Entity> entities) {
        this.entities = entities;
    }

}

@JsonIgnoreProperties(ignoreUnknown = true)
class Entity {
    private String id;
    private List<Details> details;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public List<Details> getDetails() {
        return details;
    }

    public void setDetails(List<Details> details) {
        this.details = details;
    }

}

@JsonIgnoreProperties(ignoreUnknown = true)
class Details {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Once the model is defined, you can use ObjectMapper class to perform serialization/deserialization, e.g.:

ObjectMapper mapper = new ObjectMapper();
Response response = mapper.readValue("{\"return\": {\"entities\": [{\"id\": 2385,\"details\": [{\"name\": \"Other Known Name\",\"value\": \"John Wick\",\"match\": false}],\"proofs\": [],\"link\": \"http://domain.gg/users?id=2385\"},{\"id\": 2384,\"details\": [{\"name\": \"Discord ID\",\"value\": \"159985870458322944\",\"match\": false},{\"name\": \"SteamID64\",\"value\": \"76561197991558078\",\"match\": true},{\"name\": \"SteamVanity\",\"value\": \"test\",\"match\": false},{\"name\": \"PS4\",\"value\": \"John_S\",\"match\": false},{\"name\": \"XBox\",\"value\": \"John S\",\"match\": false},{\"name\": \"Email\",\"value\": \"john_smith@gmail.com\",\"match\": true},{\"name\": \"Comment\",\"value\": \"Test user\",\"match\": false},{\"name\": \"Other Known Name\",\"value\": \"Jonathan\",\"match\": false},{\"name\": \"Reddit\",\"value\": \"/u/johns\",\"match\": true}],\"proofs\": [],\"link\": \"http://domain.gg/users?id=2384\"},{\"id\": 1680,\"details\": [{\"name\": \"Other Known Name\",\"value\": \"Johny\",\"match\": false},{\"name\": \"SteamID64\",\"value\": \"76561198213003675\",\"match\": true}],\"proofs\": [],\"link\": \"http://domain.gg/users?id=1680\"},{\"id\": 1689,\"details\": [{\"name\": \"Other Known Name\",\"value\": \"JohnnyPeto\",\"match\": false},{\"name\": \"SteamID64\",\"value\": \"76561198094228192\",\"match\": true}],\"proofs\": [],\"link\": \"http://domain.gg/users?id=1689\"}],\"notice\": \"Showing 4 out of 4 matches.\"}}", Response.class);
System.out.println(response.getResponseObject().getEntities().get(0).getId());

Here's the Javadoc.


问:
another $(...).datepicker is not a function error
If this seems not-so-helpful (Noting the 'too localized' close votes), then please tell me why. I think Django and JQuery UI make a pretty good team so it's worth working out any gotchas about using them. The answer to this question is not something I've found documented or in another question and is relevant to use of other widgets in other places.

And on to the question...

I have a django project in development mode. Inside its static directory I have the following file structure:

```<code>directory: js
            jquery-1.9.1.js
            jquery-ui-1.10.1.custom.js
            other_stuff.js
directory: css
            directory: ui-lightness
                directory: images
                jquery-ui-1.10.1.custom.css
                jquery-ui-1.10.1.custom.min.css
</code>```

I'm trying to get the datepicker to work on one of my forms:

In my html head I have:

```<code><link type="text/css" rel="stylesheet" href="/static/css/ui-lightness/jquery-ui-1.10.1.custom.css"/>
<script src="/static/js/jquery-1.9.1.js" type="text/javascript"></script>
<script src="/static/js/jquery-ui-1.10.1.custom.js" type="text/javascript"></script>
<script type="text/javascript">
        $(document).ready(function() {
              $("#id_date_of_birth").datepicker();
        });
</script>
</code>```

And the input I am trying to change looks like:

```<code><input type="text" size="10" id="id_date_of_birth" class="vDateField" value="1987-01-19" name="date_of_birth"/>
</code>```

Now I know this question has been asked like a billion times before but none of the listed solutions I have read so far seem to work...Can anybody hazard a guess as to why I am getting the error$(...).datepicker is not a function ?

Stuff I've considered:

Everything seems to be included in the correct order. Other solutions mention including jquery ui's ...core.js but I think everything is included in jquery-ui-1.10.1.custom.js because otherwise the jquery ui download page is very misleading (I chose to download every component and there is no effect)

No other errors came up except the one I mentioned. All scripts loaded correctly

Nothing is included more than once

I'm waiting until the document is ready before calling anything at all so my problem is not due to bad timing

答:
This happened to me several times.

What i did was to copy the whole code (script) and placed it in the parent view.

If you're trying to place the script in a partial it may not work, try to put it in a higher level until you get the job done.

One example in django-oscar i had to place the script in the basket.html template to make it work in here:

{% include 'basket/partials/basket_content.html' %}

Body:
If this seems not-so-helpful (Noting the 'too localized' close votes), then please tell me why. I think Django and JQuery UI make a pretty good team so it's worth working out any gotchas about using them. The answer to this question is not something I've found documented or in another question and is relevant to use of other widgets in other places.

And on to the question...

I have a django project in development mode. Inside its static directory I have the following file structure:

directory: js
            jquery-1.9.1.js
            jquery-ui-1.10.1.custom.js
            other_stuff.js
directory: css
            directory: ui-lightness
                directory: images
                jquery-ui-1.10.1.custom.css
                jquery-ui-1.10.1.custom.min.css

I'm trying to get the datepicker to work on one of my forms:

In my html head I have:

<link type="text/css" rel="stylesheet" href="/static/css/ui-lightness/jquery-ui-1.10.1.custom.css"/>

And the input I am trying to change looks like:

<input type="text" size="10" id="id_date_of_birth" class="vDateField" value="1987-01-19" name="date_of_birth"/>

Now I know this question has been asked like a billion times before but none of the listed solutions I have read so far seem to work...Can anybody hazard a guess as to why I am getting the error$(...).datepicker is not a function ?

Stuff I've considered:

Everything seems to be included in the correct order. Other solutions mention including jquery ui's ...core.js but I think everything is included in jquery-ui-1.10.1.custom.js because otherwise the jquery ui download page is very misleading (I chose to download every component and there is no effect)

No other errors came up except the one I mentioned. All scripts loaded correctly

Nothing is included more than once

I'm waiting until the document is ready before calling anything at all so my problem is not due to bad timing


问:
.php downloads instead of opening in Chrome and FF
I'm using sftp to reach my folder on a server at uni. Both chrome and firefox would download my simple test.php instead of opening the page.

Is there any suggestion where should I look with the preferences to change this? (Ubuntu 16.04)

答:
Oh, okay I understand it now, my bad.

I literally mounted the server to my local machine with ssh, thus I had no server whatsoever.
I had to reach directly with the url to open it, so I couldn't just open it from editor (VS Code - open with browser).


问:
How to make an a tag border wrap around an image
I need the border to be applied to the a tag but when I do this the border doesn't wrap around the image how can I make this happen?

```<code><div>
  <a href="#">
    <img src="https://cdn.pixabay.com/photo/2015/04/23/17/41/javascript-736400_960_720.png">
  </a>
</div>
</code>```

css:

```<code>a{
  border: 5px solid blue;
}
</code>```

https://jsfiddle.net/b7qdcub1/

答:
Just put a border on the div.

div {
border:solid;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>

    <img src="https://cdn.pixabay.com/photo/2015/04/23/17/41/javascript-736400_960_720.png">

</div></code>```

Body:
I need the border to be applied to the a tag but when I do this the border doesn't wrap around the image how can I make this happen?

css:

a{
  border: 5px solid blue;
}

https://jsfiddle.net/b7qdcub1/

Body:
Just put a border on the div.

div {
border:solid;}

<div>
  <a href="#">
    <img src="https://cdn.pixabay.com/photo/2015/04/23/17/41/javascript-736400_960_720.png">
  </a>
</div>