问:
Storing sqrt in BigDecimal
I'm calculating the euclidean distance of two numbers and I have this equation :

```<code> import java.lang.*;
 import static java.lang.Math.pow;
 import static java.lang.Math.sqrt;

 public static void main(String[] args)
 {
            double x2 = 0.32061253;
            double x1 = 0.25090585;
            double y2 = 0.33407547;
            double y1 = 0.30716705;

            double distance = sqrt(pow(x2 - x1,2) + pow(y2 - y1,2));
            System.out.println(distance);
 }
</code>```

When I try to save this in a double variable (euclideanDistance), I get 0.0 when I print it (probably because the numbers have many decimals). I tried saving it using the BigDecimal format but it doesn't seem to work. How do I use it correctly in this case, since sqrt returns a double?

答:
This code prints out an answer, but not the one supplied in the comments, and it does not print '0.0' either - JDK 1.8

```<code>import java.lang.*;

import static java.lang.Math.pow;
import static java.lang.Math.sqrt;

public class Main {

    public static void main(String[] args) {
        double x2 = 0.32061253;
        double x1 = 0.25090585;
        double y2 = 0.33407547;
        double y1 = 0.30716705;

        double distance = sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2));
        System.out.println(distance);
    }
}

//result
//0.0747200395042642
</code>```

Also tested with a Pythagorean triple 3,4,5:

(x2-x1) = 3,

(y2-y1) = 4

output: 5

Title: Storing sqrt in BigDecimal

Body:
I'm calculating the euclidean distance of two numbers and I have this equation :

 import java.lang.*;
 import static java.lang.Math.pow;
 import static java.lang.Math.sqrt;

 public static void main(String[] args)
 {
            double x2 = 0.32061253;
            double x1 = 0.25090585;
            double y2 = 0.33407547;
            double y1 = 0.30716705;

            double distance = sqrt(pow(x2 - x1,2) + pow(y2 - y1,2));
            System.out.println(distance);
 }

When I try to save this in a double variable (euclideanDistance), I get 0.0 when I print it (probably because the numbers have many decimals). I tried saving it using the BigDecimal format but it doesn't seem to work. How do I use it correctly in this case, since sqrt returns a double?

Body:
This code prints out an answer, but not the one supplied in the comments, and it does not print '0.0' either - JDK 1.8

import java.lang.*;

import static java.lang.Math.pow;
import static java.lang.Math.sqrt;

public class Main {

    public static void main(String[] args) {
        double x2 = 0.32061253;
        double x1 = 0.25090585;
        double y2 = 0.33407547;
        double y1 = 0.30716705;

        double distance = sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2));
        System.out.println(distance);
    }
}

//result
//0.0747200395042642

Also tested with a Pythagorean triple 3,4,5:

(x2-x1) = 3,

(y2-y1) = 4

output: 5


来源: stackexchange

问:
How to implement container managed authentication with hashed password in weblogic 12c?
Hi I have managed to implement container managed authentication in weblogic 12c with an SQLAuthenticator. I am successfully loging in with the users I create in the database when the password setting is set to PLAINTEXT in the provider specific sqlauthenticator settings and the database value is not encrypted.

If I  am storing the user's password inside the database using the following code though I cannot login:

```<code>String encPass = "{SHA-1}" + new sun.misc.BASE64Encoder()
.encode(java.security.MessageDigest.getInstance("SHA1")
.digest(newUser.getPassword().getBytes()));
</code>```

By providing the password "weblogic1" this value is stored in the db: {SHA-1}r49g3WeQasgoe6ODQ+5fa4Ic5tk=

In my SQLAuthenticator provider specific settings I have "Plaintext Passwords Enabled" set to false, "Password Style Retained" set to true, Password Algorithm: set to SHA-1.

When I run

```<code>request.login(email, password);
</code>```

It throws the Authentication Failed exception...

What am I doing wrong?

答:
A little late, but I think I can answer this one for you.

From the sound of things, your code was in fact correct, however, as you discovered, your tables were not properly set up.

When configuring your RDBMS authentication, it is assumed that you have three tables in your DB, they are:

users (username, password, description)

groupmembers (group name, group member)

groups (group name, group description)

I expect you were mostly there, but lacking the description column for the "users" and "groups" tables was causing your problems.

You can check out this link from Oracle's online documentation for more info:

https://docs.oracle.com/cd/E21764_01/web.1111/e13707/atn.htm#SECMG195

ContentLicense: CC BY-SA 3.0

Body:
Hi I have managed to implement container managed authentication in weblogic 12c with an SQLAuthenticator. I am successfully loging in with the users I create in the database when the password setting is set to PLAINTEXT in the provider specific sqlauthenticator settings and the database value is not encrypted.

If I  am storing the user's password inside the database using the following code though I cannot login:

String encPass = "{SHA-1}" + new sun.misc.BASE64Encoder()
.encode(java.security.MessageDigest.getInstance("SHA1")
.digest(newUser.getPassword().getBytes()));

By providing the password "weblogic1" this value is stored in the db: {SHA-1}r49g3WeQasgoe6ODQ+5fa4Ic5tk=

In my SQLAuthenticator provider specific settings I have "Plaintext Passwords Enabled" set to false, "Password Style Retained" set to true, Password Algorithm: set to SHA-1.

When I run

request.login(email, password);

It throws the Authentication Failed exception...

What am I doing wrong?


问:
Using Tint color on UIImageView
I have my own subclass of UIButton. I add UIImageView on it and add an image. I would like to paint it over the image with a tint color but it doesn't work.

So far I have:

```<code>- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {

        self.backgroundColor = [UIColor clearColor];
        self.clipsToBounds = YES;

        self.circleView = [[UIView alloc]init];
        self.circleView.backgroundColor = [UIColor whiteColor];
        self.circleView.layer.borderColor = [[Color getGraySeparatorColor]CGColor];
        self.circleView.layer.borderWidth = 1;
        self.circleView.userInteractionEnabled = NO;
        self.circleView.translatesAutoresizingMaskIntoConstraints = NO;
        [self addSubview:self.circleView];

        self.iconView = [[UIImageView alloc]init];
        [self.iconView setContentMode:UIViewContentModeScaleAspectFit];
        UIImage * image = [UIImage imageNamed:@"more"];
        [image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        self.iconView.image = image;
        self.iconView.translatesAutoresizingMaskIntoConstraints = NO;
        [self.circleView addSubview:self.iconView];
        ...
</code>```

and on selection :

```<code>- (void) setSelected:(BOOL)selected
{
    if (selected) {
        [self.iconView setTintColor:[UIColor redColor]];
        [self.circleView setTintColor:[UIColor redColor]];
    }
    else{
        [self.iconView setTintColor:[UIColor blueColor]];
        [self.circleView setTintColor:[UIColor blueColor]];
    }
}
</code>```

What did I do wrong? (The color of the image always stays the same as it was originally.)

答:
One step further. This is a drop-in subclass of UIImageView. (Not exact solution for original question.) Use in Interface Builder by setting class name to TintedImageView. Updates in real-time inside the designer as tint color changes.

(Swift 3.1, Xcode 8.3)

```<code>import UIKit

@IBDesignable class TintedImageView: UIImageView {
    override func prepareForInterfaceBuilder() {
        self.configure()
    }

    override func awakeFromNib() {
        super.awakeFromNib()

        self.configure()
    }

    @IBInspectable override var tintColor: UIColor! {
        didSet {
            self.configure()
        }
    }

    private func configure() {
        self.image = self.image?.withRenderingMode(UIImageRenderingMode.alwaysTemplate)
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Using Tint color on UIImageView

Body:
I have my own subclass of UIButton. I add UIImageView on it and add an image. I would like to paint it over the image with a tint color but it doesn't work.

So far I have:

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {

        self.backgroundColor = [UIColor clearColor];
        self.clipsToBounds = YES;

        self.circleView = [[UIView alloc]init];
        self.circleView.backgroundColor = [UIColor whiteColor];
        self.circleView.layer.borderColor = [[Color getGraySeparatorColor]CGColor];
        self.circleView.layer.borderWidth = 1;
        self.circleView.userInteractionEnabled = NO;
        self.circleView.translatesAutoresizingMaskIntoConstraints = NO;
        [self addSubview:self.circleView];

        self.iconView = [[UIImageView alloc]init];
        [self.iconView setContentMode:UIViewContentModeScaleAspectFit];
        UIImage * image = [UIImage imageNamed:@"more"];
        [image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        self.iconView.image = image;
        self.iconView.translatesAutoresizingMaskIntoConstraints = NO;
        [self.circleView addSubview:self.iconView];
        ...

and on selection :

- (void) setSelected:(BOOL)selected
{
    if (selected) {
        [self.iconView setTintColor:[UIColor redColor]];
        [self.circleView setTintColor:[UIColor redColor]];
    }
    else{
        [self.iconView setTintColor:[UIColor blueColor]];
        [self.circleView setTintColor:[UIColor blueColor]];
    }
}

What did I do wrong? (The color of the image always stays the same as it was originally.)

Body:
One step further. This is a drop-in subclass of UIImageView. (Not exact solution for original question.) Use in Interface Builder by setting class name to TintedImageView. Updates in real-time inside the designer as tint color changes.

(Swift 3.1, Xcode 8.3)

import UIKit

@IBDesignable class TintedImageView: UIImageView {
    override func prepareForInterfaceBuilder() {
        self.configure()
    }

    override func awakeFromNib() {
        super.awakeFromNib()

        self.configure()
    }

    @IBInspectable override var tintColor: UIColor! {
        didSet {
            self.configure()
        }
    }

    private func configure() {
        self.image = self.image?.withRenderingMode(UIImageRenderingMode.alwaysTemplate)
    }
}


问:
using netty 4.1.9 for xml message processing
I am using netty 4.1.9 on a server receiving XML messages from a Netty client.  The client is able to send the xml message to the server.  However, on the server end, I need to be able to decode them as a single xml message (not a series of bytes).  I looked at xml frame decoder but could not figure out the best approach.  Would appreciate pointing in the right direction.

Initializer:

```<code>    @Override
    public void initChannel(SocketChannel ch) throws Exception {
        log.info("init channel called");
        ChannelPipeline pipeline = ch.pipeline();
        //add decoder for combining bytes for xml message
        pipeline.addLast("decoder", new XmlMessageDecoder());

        // handler for business logic.
        pipeline.addLast("handler", new XmlServerHandler());
}
</code>```

I was not able to use the xml frame decoder.  If I try to extend xml frame decoder in the mxl message decoder, I get the compilation error "there is no default constructor available in xmlframedecoder".

答:
I ended up using the XmlFrameDecoder in my channel initializer and its output was passed to the handler where I was able to read the XML message from the ByteBuf.

initializer

```<code>@Override
public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    // idle state handler
    pipeline.addLast("idleStateHandler", new IdleStateHandler(60,
            30, 0));
    pipeline.addLast("myHandler", new IdleHandler());

    //add decoder for combining bytes for xml message
    pipeline.addLast("decoder", new XmlFrameDecoder(1048576));

    // handler for business logic.
    pipeline.addLast("handler", new ServerReceiverHandler());
}
</code>```

handler

```<code>public class ServerReceiverHandler extends ChannelInboundHandlerAdapter {

    ChannelHandlerContext ctx;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        final ByteBuf buffer = (ByteBuf)msg;
        //prints out String representation of xml doc
        log.info("read : {}" + buffer.toString((CharsetUtil.UTF_8)));
        ReferenceCountUtil.release(msg);
    }
}
</code>```

Body:
I am using netty 4.1.9 on a server receiving XML messages from a Netty client.  The client is able to send the xml message to the server.  However, on the server end, I need to be able to decode them as a single xml message (not a series of bytes).  I looked at xml frame decoder but could not figure out the best approach.  Would appreciate pointing in the right direction.

Initializer:

    @Override
    public void initChannel(SocketChannel ch) throws Exception {
        log.info("init channel called");
        ChannelPipeline pipeline = ch.pipeline();
        //add decoder for combining bytes for xml message
        pipeline.addLast("decoder", new XmlMessageDecoder());

        // handler for business logic.
        pipeline.addLast("handler", new XmlServerHandler());
}

I was not able to use the xml frame decoder.  If I try to extend xml frame decoder in the mxl message decoder, I get the compilation error "there is no default constructor available in xmlframedecoder".

Body:
I ended up using the XmlFrameDecoder in my channel initializer and its output was passed to the handler where I was able to read the XML message from the ByteBuf.

initializer

@Override
public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    // idle state handler
    pipeline.addLast("idleStateHandler", new IdleStateHandler(60,
            30, 0));
    pipeline.addLast("myHandler", new IdleHandler());

    //add decoder for combining bytes for xml message
    pipeline.addLast("decoder", new XmlFrameDecoder(1048576));

    // handler for business logic.
    pipeline.addLast("handler", new ServerReceiverHandler());
}

handler

public class ServerReceiverHandler extends ChannelInboundHandlerAdapter {

    ChannelHandlerContext ctx;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        final ByteBuf buffer = (ByteBuf)msg;
        //prints out String representation of xml doc
        log.info("read : {}" + buffer.toString((CharsetUtil.UTF_8)));
        ReferenceCountUtil.release(msg);
    }
}


问:
Php how to verify is string is certain function for security verification
I an using the eval() function in an ajax file that will allow me to call functions from Javascript (similar to Securely calling PHP code from JavaScript);

I have around 20 functions that I want to be able to use. I do not want malicious code passed in. How can I verify that the string passed in is one of my functions, and nothing more?

答:
You are overcomplicating things by using eval to achieve this. You can simply define your functions on the server-side and switch to the correct one using a simple switch case. This way you do not have to worry about security-related issues.

jQuery:

```<code>function callPhp(func, callback){
    $.ajax({
    type: 'GET',
    url: 'callPhp.php',
    data: {action:'register'},
    success: function (data) {
        data = JSON.parse(data);
        callback(data);
    }
});
}
</code>```

PHP:

```<code><?php

$action = $_GET['action'];

switch ($action) {
    case "register":
        register_user();
        break;
    case "login":
        login();
        break;

?>
</code>```

If you really want to use eval, which I highly discourage you to use, you can simply implement a sort of whitelist of method names that should be executed on the server side.

```<code><?php

$whiteListMethod = array('register', 'login', 'forgotPassword');
$action = $_GET['action'];

// Is the user supplied function present in my whitelist?

if(in_array($action,$whiteListMethod)){

  // You can call this method safely

}else{

  // Hack attempt detected

}
</code>```

Body:
You are overcomplicating things by using eval to achieve this. You can simply define your functions on the server-side and switch to the correct one using a simple switch case. This way you do not have to worry about security-related issues.

jQuery:

function callPhp(func, callback){
    $.ajax({
    type: 'GET',
    url: 'callPhp.php',
    data: {action:'register'},
    success: function (data) {
        data = JSON.parse(data);
        callback(data);
    }
});
}

PHP:

<?php

$action = $_GET['action'];

switch ($action) {
    case "register":
        register_user();
        break;
    case "login":
        login();
        break;

?>

If you really want to use eval, which I highly discourage you to use, you can simply implement a sort of whitelist of method names that should be executed on the server side.

<?php

$whiteListMethod = array('register', 'login', 'forgotPassword');
$action = $_GET['action'];

// Is the user supplied function present in my whitelist?

if(in_array($action,$whiteListMethod)){

  // You can call this method safely

}else{

  // Hack attempt detected

}


问:
Only IE auto submits login form for MVC website
I have created an MVC website where users can log on and look at certain information. The problem I am facing is with Internet Explorer, this is the only browser that decides to auto submit the login form when the user navigates to the login page (they must have the details saved from a previous log on).

The login page will sit there for about a second and then automatically submit.

I have confirmed (using jquery) that the auto complete fills in the fields and triggers a click on the submit button (again, only in IE).

The website does NOT use windows authentication and is a simple cookie driven username and password login form.

My question is what could be submitting the form and how can I stop this?

I do not really know what code to provide as extra information so if you need any more information, just ask.

答: The first step in troubleshooting ALL web browsers is to test in no Addons mode. For IE testing, go Start>Run>iexplore.exe -extoff [url].</p>


问:
JavaScript Palindrome
I found a solution on how to write palindrome in StackOverFlow. This is the code snippet:

```<code>function palindrome(str) {
    var len = str.length;
    for ( var i = 0; i < Math.floor(len/2); i++ ) {
        if (str[i] !== str[len - 1 - i]) {   //Problem in this line
            return false;
        }
    }
    return true;
}
</code>```

I understand every line except the one I have here. Can anyone please break it down for me? Thanks in advance!

答:
The loop steps through the first half of the string, and it checks consecutive character to see if it is not equal (or not the same character)  to the next consecutive character on the other end of the string, starting from the end.

```<code>|0|1|2|3|4|
|l|e|v|e|l|

len = 5
</code>```

This gives you:

```<code>str[i] !== str[len - 1 - i]
</code>```

When i = 0, str[i] is l, which is equal to str[5-1-0], which is str[4], which also is l

Title: JavaScript Palindrome

Body:
I found a solution on how to write palindrome in StackOverFlow. This is the code snippet:

function palindrome(str) {
    var len = str.length;
    for ( var i = 0; i < Math.floor(len/2); i++ ) {
        if (str[i] !== str[len - 1 - i]) {   //Problem in this line
            return false;
        }
    }
    return true;
}

I understand every line except the one I have here. Can anyone please break it down for me? Thanks in advance!

Body:
The loop steps through the first half of the string, and it checks consecutive character to see if it is not equal (or not the same character)  to the next consecutive character on the other end of the string, starting from the end.

|0|1|2|3|4|
|l|e|v|e|l|

len = 5

This gives you:

str[i] !== str[len - 1 - i]

When i = 0, str[i] is l, which is equal to str[5-1-0], which is str[4], which also is l


问:
ListView not displayed in Fragment (Android)
So im following this tutorial http://www.wingnity.com/blog/android-json-parsing-and-image-loading-tutorial/  on how to parse a JSON Api and displays data into Listview

I tried to adapt the code in my fragment , in onCreateView method , but the Listview is not displayed (blank fragment). And i dont know why.

I imported all the required libs

Actor.java

```<code>public class Actors {

private String name;
private String description;
private String dob;
private String country;
private String height;
private String spouse;
private String children;
private String image;

public Actors() {
    // TODO Auto-generated constructor stub
}

public Actors(String name, String description, String dob, String country,
              String height, String spouse, String children, String image) {
    super();
    this.name = name;
    this.description = description;
    this.dob = dob;
    this.country = country;
    this.height = height;
    this.spouse = spouse;
    this.children = children;
    this.image = image;
}

public String getName() {
    return name;
}

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

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public String getDob() {
    return dob;
}

public void setDob(String dob) {
    this.dob = dob;
}

public String getCountry() {
    return country;
}

public void setCountry(String country) {
    this.country = country;
}

public String getHeight() {
    return height;
}

public void setHeight(String height) {
    this.height = height;
}

public String getSpouse() {
    return spouse;
}

public void setSpouse(String spouse) {
    this.spouse = spouse;
}

public String getChildren() {
    return children;
}

public void setChildren(String children) {
    this.children = children;
}

public String getImage() {
    return image;
}

public void setImage(String image) {
    this.image = image;
}

}
</code>```

ActorAdapter.java

```<code>import java.io.InputStream;
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import info.androidhive.navigationdrawer.R;

public class ActorAdapter extends ArrayAdapter<Actors> {
ArrayList<Actors> actorList;
LayoutInflater vi;
int Resource;
ViewHolder holder;

public ActorAdapter(Context context, int resource, ArrayList<Actors> objects) {
    super(context, resource, objects);
    vi = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    Resource = resource;
    actorList = objects;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // convert view = design
    View v = convertView;
    if (v == null) {
        holder = new ViewHolder();
        v = vi.inflate(Resource, null);
        holder.imageview = (ImageView) v.findViewById(R.id.ivImage);
        holder.tvName = (TextView) v.findViewById(R.id.tvName);
        holder.tvDescription = (TextView) v.findViewById(R.id.tvDescriptionn);
        holder.tvDOB = (TextView) v.findViewById(R.id.tvDateOfBirth);
        holder.tvCountry = (TextView) v.findViewById(R.id.tvCountry);
        holder.tvHeight = (TextView) v.findViewById(R.id.tvHeight);
        holder.tvSpouse = (TextView) v.findViewById(R.id.tvSpouse);
        holder.tvChildren = (TextView) v.findViewById(R.id.tvChildren);
        v.setTag(holder);
    } else {
        holder = (ViewHolder) v.getTag();
    }
    holder.imageview.setImageResource(R.drawable.imgadd);
    new DownloadImageTask(holder.imageview).execute(actorList.get(position).getImage());
    holder.tvName.setText(actorList.get(position).getName());
    holder.tvDescription.setText(actorList.get(position).getDescription());
    holder.tvDOB.setText("B'day: " + actorList.get(position).getDob());
    holder.tvCountry.setText(actorList.get(position).getCountry());
    holder.tvHeight.setText("Height: " + actorList.get(position).getHeight());
    holder.tvSpouse.setText("Spouse: " + actorList.get(position).getSpouse());
    holder.tvChildren.setText("Children: " + actorList.get(position).getChildren());
    return v;

}

static class ViewHolder {
    public ImageView imageview;
    public TextView tvName;
    public TextView tvDescription;
    public TextView tvDOB;
    public TextView tvCountry;
    public TextView tvHeight;
    public TextView tvSpouse;
    public TextView tvChildren;

}

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    ImageView bmImage;

    public DownloadImageTask(ImageView bmImage) {
        this.bmImage = bmImage;
    }

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap mIcon11 = null;
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return mIcon11;
    }

    protected void onPostExecute(Bitmap result) {
        bmImage.setImageBitmap(result);
    }

}
}
</code>```

Articles.xml

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

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <ImageView
        android:id="@+id/ivImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:src="@drawable/imgadd" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/tvName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Tom Cruise"
            android:textColor="#166CED"
            android:textAppearance="?android:attr/textAppearanceLarge" />

        <TextView
            android:id="@+id/tvDateOfBirth"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#D64530"
            android:text="Date of Birth: July 3, 1962" />

        <TextView
            android:id="@+id/tvHeight"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Height: 1.80 m"
            android:textColor="#D64530"
            android:textAppearance="?android:attr/textAppearanceSmall" />

        <TextView
            android:id="@+id/tvCountry"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#D64530"
            android:text="United States" />

    </LinearLayout>

</LinearLayout>

<TextView
    android:id="@+id/tvDescriptionn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="#009A57"
    android:text="Description" />

<TextView
    android:id="@+id/tvSpouse"
    android:layout_width="wrap_content" android:textColor="#166CED"
    android:layout_height="wrap_content"
    android:text="Spouse: Katie Holmes" />

<TextView
    android:id="@+id/tvChildren"
    android:layout_width="wrap_content" android:textColor="#166CED"
    android:layout_height="wrap_content"
    android:text="Children: Suri Cruise, Isabella Jane Cruise, Connor Cruise" />

</LinearLayout>
</code>```

Fragment_accueil.xml (my fragment layout)

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="4dp"
android:orientation="vertical"
tools:context="info.androidhive.navigationdrawer.fragment.AccueilFragment">

<ListView
    android:id="@+id/list"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:listitem="@layout/articles">

</ListView>

</LinearLayout>
</code>```

fragment_accueil.java (my fragment activity)

```<code>//import.....
public class AccueilFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

private String mParam1;
private String mParam2;
int score = 0;
TextView t1, t2, t3,t4;
ImageView img;

private OnFragmentInteractionListener mListener;

public AccueilFragment() {
}

public static AccueilFragment newInstance(String param1, String param2) {
    AccueilFragment fragment = new AccueilFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_accueil, container, false);

    t1 = (TextView) view.findViewById(R.id.tvName);
    t2 = (TextView) view.findViewById(R.id.tvDateOfBirth);
    t3 = (TextView) view.findViewById(R.id.tvHeight);
    t3 = (TextView) view.findViewById(R.id.tvCountry);
    img = (ImageView) view.findViewById(R.id.ivImage);
    ArrayList actorsList = new ArrayList<Actors>();

    ListView listview = (ListView) view.findViewById(R.id.list);
    ListAdapter adapter = new ActorAdapter(getActivity().getApplicationContext(), R.layout.articles, actorsList);

    listview.setAdapter(adapter);

    new getData().execute();

    return view;

}

public void onButtonPressed(Uri uri) {
    if (mListener != null) {
        mListener.onFragmentInteraction(uri);
    }
}

class getData extends AsyncTask<String, String, String> {

    HttpURLConnection urlConnection;

    @Override
    protected String doInBackground(String... args) {

        StringBuilder result = new StringBuilder();

        try {
            URL url = new URL("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
            urlConnection = (HttpURLConnection) url.openConnection();
            InputStream in = new BufferedInputStream(urlConnection.getInputStream());

            BufferedReader reader = new BufferedReader(new InputStreamReader(in));

            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            urlConnection.disconnect();
        }

        return result.toString();
    }

    @Override
    protected void onPostExecute(String result) {
        try {
            JSONObject jsono = new JSONObject(result);
            JSONArray jarray = jsono.getJSONArray("actors");

            for (int i = 0; i < jarray.length(); i++) {
                JSONObject object = jarray.getJSONObject(i);

                Actors actor = new Actors();

                actor.setName(object.getString("name"));
                actor.setDescription(object.getString("description"));
                actor.setDob(object.getString("dob"));
                actor.setCountry(object.getString("country"));
                actor.setHeight(object.getString("height"));
                actor.setSpouse(object.getString("spouse"));
                actor.setChildren(object.getString("children"));
                actor.setImage(object.getString("image"));

            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}
public interface OnFragmentInteractionListener {

    void onFragmentInteraction(Uri uri);
}

}
</code>```

What's the problem and how to fix that ? thanks

答:
There is couple of things wrong:

1.You are not adding Actors actor = new Actors(); to the actorsList

2.Calling this:

```<code> ArrayList actorsList = new ArrayList<Actors>();

 ListView listview = (ListView) view.findViewById(R.id.list);
 ListAdapter adapter = new ActorAdapter(getActivity().getApplicationContext(), R.layout.articles, actorsList);
</code>```

will reuslt in blank data in listview

I would suggest you to add the data in your onPostExecute() to the Arraylist and then initialize the adapter with the data.

or you can also call

```<code>adapter.notifyDataSetChanged() in onPostExecute()
</code>```

Body:
So im following this tutorial http://www.wingnity.com/blog/android-json-parsing-and-image-loading-tutorial/  on how to parse a JSON Api and displays data into Listview

I tried to adapt the code in my fragment , in onCreateView method , but the Listview is not displayed (blank fragment). And i dont know why.

I imported all the required libs

Actor.java

public class Actors {

private String name;
private String description;
private String dob;
private String country;
private String height;
private String spouse;
private String children;
private String image;

public Actors() {
    // TODO Auto-generated constructor stub
}

public Actors(String name, String description, String dob, String country,
              String height, String spouse, String children, String image) {
    super();
    this.name = name;
    this.description = description;
    this.dob = dob;
    this.country = country;
    this.height = height;
    this.spouse = spouse;
    this.children = children;
    this.image = image;
}

public String getName() {
    return name;
}

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

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public String getDob() {
    return dob;
}

public void setDob(String dob) {
    this.dob = dob;
}

public String getCountry() {
    return country;
}

public void setCountry(String country) {
    this.country = country;
}

public String getHeight() {
    return height;
}

public void setHeight(String height) {
    this.height = height;
}

public String getSpouse() {
    return spouse;
}

public void setSpouse(String spouse) {
    this.spouse = spouse;
}

public String getChildren() {
    return children;
}

public void setChildren(String children) {
    this.children = children;
}

public String getImage() {
    return image;
}

public void setImage(String image) {
    this.image = image;
}

}

ActorAdapter.java

import java.io.InputStream;
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import info.androidhive.navigationdrawer.R;

public class ActorAdapter extends ArrayAdapter<Actors> {
ArrayList<Actors> actorList;
LayoutInflater vi;
int Resource;
ViewHolder holder;

public ActorAdapter(Context context, int resource, ArrayList<Actors> objects) {
    super(context, resource, objects);
    vi = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    Resource = resource;
    actorList = objects;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // convert view = design
    View v = convertView;
    if (v == null) {
        holder = new ViewHolder();
        v = vi.inflate(Resource, null);
        holder.imageview = (ImageView) v.findViewById(R.id.ivImage);
        holder.tvName = (TextView) v.findViewById(R.id.tvName);
        holder.tvDescription = (TextView) v.findViewById(R.id.tvDescriptionn);
        holder.tvDOB = (TextView) v.findViewById(R.id.tvDateOfBirth);
        holder.tvCountry = (TextView) v.findViewById(R.id.tvCountry);
        holder.tvHeight = (TextView) v.findViewById(R.id.tvHeight);
        holder.tvSpouse = (TextView) v.findViewById(R.id.tvSpouse);
        holder.tvChildren = (TextView) v.findViewById(R.id.tvChildren);
        v.setTag(holder);
    } else {
        holder = (ViewHolder) v.getTag();
    }
    holder.imageview.setImageResource(R.drawable.imgadd);
    new DownloadImageTask(holder.imageview).execute(actorList.get(position).getImage());
    holder.tvName.setText(actorList.get(position).getName());
    holder.tvDescription.setText(actorList.get(position).getDescription());
    holder.tvDOB.setText("B'day: " + actorList.get(position).getDob());
    holder.tvCountry.setText(actorList.get(position).getCountry());
    holder.tvHeight.setText("Height: " + actorList.get(position).getHeight());
    holder.tvSpouse.setText("Spouse: " + actorList.get(position).getSpouse());
    holder.tvChildren.setText("Children: " + actorList.get(position).getChildren());
    return v;

}

static class ViewHolder {
    public ImageView imageview;
    public TextView tvName;
    public TextView tvDescription;
    public TextView tvDOB;
    public TextView tvCountry;
    public TextView tvHeight;
    public TextView tvSpouse;
    public TextView tvChildren;

}

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    ImageView bmImage;

    public DownloadImageTask(ImageView bmImage) {
        this.bmImage = bmImage;
    }

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap mIcon11 = null;
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return mIcon11;
    }

    protected void onPostExecute(Bitmap result) {
        bmImage.setImageBitmap(result);
    }

}
}

Articles.xml

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

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <ImageView
        android:id="@+id/ivImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:src="@drawable/imgadd" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/tvName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Tom Cruise"
            android:textColor="#166CED"
            android:textAppearance="?android:attr/textAppearanceLarge" />

        <TextView
            android:id="@+id/tvDateOfBirth"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#D64530"
            android:text="Date of Birth: July 3, 1962" />

        <TextView
            android:id="@+id/tvHeight"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Height: 1.80 m"
            android:textColor="#D64530"
            android:textAppearance="?android:attr/textAppearanceSmall" />

        <TextView
            android:id="@+id/tvCountry"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#D64530"
            android:text="United States" />

    </LinearLayout>

</LinearLayout>

<TextView
    android:id="@+id/tvDescriptionn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="#009A57"
    android:text="Description" />

<TextView
    android:id="@+id/tvSpouse"
    android:layout_width="wrap_content" android:textColor="#166CED"
    android:layout_height="wrap_content"
    android:text="Spouse: Katie Holmes" />

<TextView
    android:id="@+id/tvChildren"
    android:layout_width="wrap_content" android:textColor="#166CED"
    android:layout_height="wrap_content"
    android:text="Children: Suri Cruise, Isabella Jane Cruise, Connor Cruise" />

</LinearLayout>

Fragment_accueil.xml (my fragment layout)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="4dp"
android:orientation="vertical"
tools:context="info.androidhive.navigationdrawer.fragment.AccueilFragment">

<ListView
    android:id="@+id/list"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:listitem="@layout/articles">

</ListView>

</LinearLayout>

fragment_accueil.java (my fragment activity)

//import.....
public class AccueilFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

private String mParam1;
private String mParam2;
int score = 0;
TextView t1, t2, t3,t4;
ImageView img;

private OnFragmentInteractionListener mListener;

public AccueilFragment() {
}

public static AccueilFragment newInstance(String param1, String param2) {
    AccueilFragment fragment = new AccueilFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_accueil, container, false);

    t1 = (TextView) view.findViewById(R.id.tvName);
    t2 = (TextView) view.findViewById(R.id.tvDateOfBirth);
    t3 = (TextView) view.findViewById(R.id.tvHeight);
    t3 = (TextView) view.findViewById(R.id.tvCountry);
    img = (ImageView) view.findViewById(R.id.ivImage);
    ArrayList actorsList = new ArrayList<Actors>();

    ListView listview = (ListView) view.findViewById(R.id.list);
    ListAdapter adapter = new ActorAdapter(getActivity().getApplicationContext(), R.layout.articles, actorsList);

    listview.setAdapter(adapter);

    new getData().execute();

    return view;

}

public void onButtonPressed(Uri uri) {
    if (mListener != null) {
        mListener.onFragmentInteraction(uri);
    }
}

class getData extends AsyncTask<String, String, String> {

    HttpURLConnection urlConnection;

    @Override
    protected String doInBackground(String... args) {

        StringBuilder result = new StringBuilder();

        try {
            URL url = new URL("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
            urlConnection = (HttpURLConnection) url.openConnection();
            InputStream in = new BufferedInputStream(urlConnection.getInputStream());

            BufferedReader reader = new BufferedReader(new InputStreamReader(in));

            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            urlConnection.disconnect();
        }

        return result.toString();
    }

    @Override
    protected void onPostExecute(String result) {
        try {
            JSONObject jsono = new JSONObject(result);
            JSONArray jarray = jsono.getJSONArray("actors");

            for (int i = 0; i < jarray.length(); i++) {
                JSONObject object = jarray.getJSONObject(i);

                Actors actor = new Actors();

                actor.setName(object.getString("name"));
                actor.setDescription(object.getString("description"));
                actor.setDob(object.getString("dob"));
                actor.setCountry(object.getString("country"));
                actor.setHeight(object.getString("height"));
                actor.setSpouse(object.getString("spouse"));
                actor.setChildren(object.getString("children"));
                actor.setImage(object.getString("image"));

            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}
public interface OnFragmentInteractionListener {

    void onFragmentInteraction(Uri uri);
}

}

What's the problem and how to fix that ? thanks

Body:
There is couple of things wrong:

1.You are not adding Actors actor = new Actors(); to the actorsList

2.Calling this:

 ArrayList actorsList = new ArrayList<Actors>();

 ListView listview = (ListView) view.findViewById(R.id.list);
 ListAdapter adapter = new ActorAdapter(getActivity().getApplicationContext(), R.layout.articles, actorsList);

will reuslt in blank data in listview

I would suggest you to add the data in your onPostExecute() to the Arraylist and then initialize the adapter with the data.

or you can also call

adapter.notifyDataSetChanged() in onPostExecute()


问:
Delete a selected div
Script explanation : I have a text area which user is typing notes and those notes are added to the DOM (as div elements) . I created an icon inside that divs that when you click on it i want the parent of the icon that is clicked to be removed from the DOM . I achieve this with JQuery , but i cant do it in pure JS. The code i use to achieve this in:

```<code>$('.fa-window-close').on('click', function(event){
                event.preventDefault();
                console.log($(this).parents('div')[0]);
                $(this).parents('div')[0].remove();

           });
</code>```

Iam posting a link from gist, its a part code of my project so you can understand what iam trying to achieve.

https://gist.github.com/Clickys/43856fe26ee4c061cf910a9211f0c142

Basically what i want to achieve is , lets assume that we have a button that is creating divs elements inside DOM. Each of this div has an icon(fontawesome) that if we click on it , the selected target should be removed from the DOM(the target div) but not the other divs . I tried to use event.target and a lot of things but sadly i couldn't solve this with pure JS.

I tried this

```<code>closeTolPos.addEventListener('click', function(e){
      var parentEl = e.currentTarget.parentNode.parentNode;
      parentEl.removeChild(this.parentElement);
      console.log(this.parentElement);
});
</code>```

But it seems that when there are more than 1 element , it doesnt work . It only works if there is one element.

答:
We make some changes and now the code works:

```<code> (function() {
    document.addEventListener('click',function(e) {
      if (e.target.closest('.notesDecoration')) {
        e.target.closest('.notesDecoration').parentNode.removeChild(e.target.parentNode);
      }
    });
 })();
</code>```

Now click event is binded to a document, so the element exists, when the page is loaded. Then I check if the clicked element was the element, which was recently created and added to DOM.

Title: Delete a selected div

Body:
Script explanation : I have a text area which user is typing notes and those notes are added to the DOM (as div elements) . I created an icon inside that divs that when you click on it i want the parent of the icon that is clicked to be removed from the DOM . I achieve this with JQuery , but i cant do it in pure JS. The code i use to achieve this in:

$('.fa-window-close').on('click', function(event){
                event.preventDefault();
                console.log($(this).parents('div')[0]);
                $(this).parents('div')[0].remove();

           });

Iam posting a link from gist, its a part code of my project so you can understand what iam trying to achieve.

https://gist.github.com/Clickys/43856fe26ee4c061cf910a9211f0c142

Basically what i want to achieve is , lets assume that we have a button that is creating divs elements inside DOM. Each of this div has an icon(fontawesome) that if we click on it , the selected target should be removed from the DOM(the target div) but not the other divs . I tried to use event.target and a lot of things but sadly i couldn't solve this with pure JS.

I tried this

closeTolPos.addEventListener('click', function(e){
      var parentEl = e.currentTarget.parentNode.parentNode;
      parentEl.removeChild(this.parentElement);
      console.log(this.parentElement);
});

But it seems that when there are more than 1 element , it doesnt work . It only works if there is one element.

Body:
We make some changes and now the code works:

 (function() {
    document.addEventListener('click',function(e) {
      if (e.target.closest('.notesDecoration')) {
        e.target.closest('.notesDecoration').parentNode.removeChild(e.target.parentNode);
      }
    });
 })();

Now click event is binded to a document, so the element exists, when the page is loaded. Then I check if the clicked element was the element, which was recently created and added to DOM.


问:
Which is better Scala style?
Although I know this might be purely preference based, I have a question about style.
Given the code below:

```<code>map {
  updateWriteResult =>
    logger.debug(....
    Utils.wrFeedback(.....
    auditAction(....
    //HTTP 200
    Ok(".....
}
</code>```

Is the above formatting considered better style than the below?

```<code>map { updateWriteResult =>
  logger.debug(....
  Utils.wrFeedback(.....
  auditAction(....
  //HTTP 200
  Ok(".....
}
</code>```

答: According to the official documentation (last paragraph), it should be the latter.</p>

Title: Which is better Scala style?

Body:
Although I know this might be purely preference based, I have a question about style.
Given the code below:

map {
  updateWriteResult =>
    logger.debug(....
    Utils.wrFeedback(.....
    auditAction(....
    //HTTP 200
    Ok(".....
}

Is the above formatting considered better style than the below?

map { updateWriteResult =>
  logger.debug(....
  Utils.wrFeedback(.....
  auditAction(....
  //HTTP 200
  Ok(".....
}


问:
How to use merge layer "concatenate" with Keras 2.0?
I am currently trying to update this densenet implementation for Keras 2.0. Everything works, except for

```<code>from keras.layers import Input, merge
[...]
concat_axis = 1 if K.image_dim_ordering() == "th" else -1

feature_list = [x]

for i in range(nb_layers):
    x = conv_block(x, growth_rate, bottleneck, dropout_rate, weight_decay)
    feature_list.append(x)
    x = merge(feature_list, mode='concat', concat_axis=concat_axis)
    nb_filter += growth_rate

return x, nb_filter
</code>```

I changed it to

```<code>from keras.layers import Input, concatenate
[...]
feature_list = [x]

for i in range(nb_layers):
    x = conv_block(x, growth_rate, bottleneck, dropout_rate, weight_decay)
    feature_list.append(x)
    x = concatenate(feature_list, axis=concat_axis)
    nb_filter += growth_rate

return x, nb_filter
</code>```

But this gives

```<code>Traceback (most recent call last):
  File "./run_training.py", line 87, in <module>
    config=experiment_meta)
  File "/home/moose/GitHub/msthesis-experiments/train/train_keras.py", line 74, in main
    model = model_module.create_model(nb_classes, input_shape)
  File "/home/moose/GitHub/msthesis-experiments/models/densenet.py", line 173, in create_model
    densenet = Model(inputs=model_input, outputs=x, name="create_dense_net")
  File "/usr/local/lib/python2.7/dist-packages/keras/legacy/interfaces.py", line 87, in wrapper
    return func(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/topology.py", line 1700, in __init__
    str(layers_with_complete_input))
RuntimeError: Graph disconnected: cannot obtain value for tensor Tensor("conv2d_2/convolution:0", shape=(?, 32, 32, 12), dtype=float32) at layer "concatenate_1". The following previous layers were accessed without issue: ['input_1', 'initial_conv2D', 'batch_normalization_1', 'activation_1', 'conv2d_1']
</code>```

How can I fix this?

答:
This was fixed with https://github.com/fchollet/keras/commit/c2321e61e1732f7a27841eca36cdaf34ed5d26dd.

In the meantime you can use

```<code>x = concatenate(feature_list[:], axis=concat_axis)
</code>```

Body:
I am currently trying to update this densenet implementation for Keras 2.0. Everything works, except for

from keras.layers import Input, merge
[...]
concat_axis = 1 if K.image_dim_ordering() == "th" else -1

feature_list = [x]

for i in range(nb_layers):
    x = conv_block(x, growth_rate, bottleneck, dropout_rate, weight_decay)
    feature_list.append(x)
    x = merge(feature_list, mode='concat', concat_axis=concat_axis)
    nb_filter += growth_rate

return x, nb_filter

I changed it to

from keras.layers import Input, concatenate
[...]
feature_list = [x]

for i in range(nb_layers):
    x = conv_block(x, growth_rate, bottleneck, dropout_rate, weight_decay)
    feature_list.append(x)
    x = concatenate(feature_list, axis=concat_axis)
    nb_filter += growth_rate

return x, nb_filter

But this gives

Traceback (most recent call last):
  File "./run_training.py", line 87, in <module>
    config=experiment_meta)
  File "/home/moose/GitHub/msthesis-experiments/train/train_keras.py", line 74, in main
    model = model_module.create_model(nb_classes, input_shape)
  File "/home/moose/GitHub/msthesis-experiments/models/densenet.py", line 173, in create_model
    densenet = Model(inputs=model_input, outputs=x, name="create_dense_net")
  File "/usr/local/lib/python2.7/dist-packages/keras/legacy/interfaces.py", line 87, in wrapper
    return func(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/topology.py", line 1700, in __init__
    str(layers_with_complete_input))
RuntimeError: Graph disconnected: cannot obtain value for tensor Tensor("conv2d_2/convolution:0", shape=(?, 32, 32, 12), dtype=float32) at layer "concatenate_1". The following previous layers were accessed without issue: ['input_1', 'initial_conv2D', 'batch_normalization_1', 'activation_1', 'conv2d_1']

How can I fix this?

Body:
This was fixed with https://github.com/fchollet/keras/commit/c2321e61e1732f7a27841eca36cdaf34ed5d26dd.

In the meantime you can use

x = concatenate(feature_list[:], axis=concat_axis)


问:
Check record exists db - error show
How do I check if username or email exists and then put a error message in my error array. Right now i have:

```<code>$sql = "SELECT username, email FROM users WHERE username = '" . $username . "' OR email = '" . $email . "'";

$query = mysql_query($sql);

if (mysql_num_rows($query) > 0)
{
 echo "That username or email already exists";
}
</code>```

But I want to check if it is the username OR the email that is existing and then put:

error[] = "username is existing"; //if the username is existing

error[] = "email is existing"; //if the email is existing

How to do?

答:
Sounds like you're trying to let users know whether a username or email already exists at registration time.  Here's what you can do:

```<code><?php
//----------------------------------------
// Create first query
$usernameQuery = 'SELECT username FROM users WHERE username="'.mysql_real_escape_string($username).'"';

//----------------------------------------
// Query db
$usernameResult = mysql_query($userNameQuery);

//----------------------------------------
// Check if result is empty
if(mysql_num_rows($usernameResult) > 0){

   //----------------------------------------
   // Username already exists
   $error[] = 'Username already exists';

   //----------------------------------------
   // Return error to user and stop execution
   // of additional queries/code
} else {

  //----------------------------------------
  // Check if email exists

  //----------------------------------------
  // Create query
  $emailQuery = 'SELECT email FROM users WHERE email="'.mysql_real_escape_string($email).'"';

  //----------------------------------------
  // Query the db
  $emailResult = mysql_query($emailQuery);

  //----------------------------------------
  // Check if the result is empty
  if(mysql_num_rows($emailResult) > 0){

     //----------------------------------------
     // Email already exists
     $error[] = 'Email already exists';

     //----------------------------------------
     // Return error to user and stop execution
     // of additional queries/code
  } else {

     //----------------------------------------
     // Continue with registration...
  }
}
?>
</code>```

Please note that you should always escape your values before executing the actual query.

Additional Resources:

http://us.php.net/manual/en/function.mysql-real-escape-string.php
http://us.php.net/manual/en/function.mysql-escape-string.php

Title: Check record exists db - error show

Body:
How do I check if username or email exists and then put a error message in my error array. Right now i have:

$sql = "SELECT username, email FROM users WHERE username = '" . $username . "' OR email = '" . $email . "'";

$query = mysql_query($sql);

if (mysql_num_rows($query) > 0)
{
 echo "That username or email already exists";
}

But I want to check if it is the username OR the email that is existing and then put:

error[] = "username is existing"; //if the username is existing

error[] = "email is existing"; //if the email is existing

How to do?

Body:
Sounds like you're trying to let users know whether a username or email already exists at registration time.  Here's what you can do:

<?php
//----------------------------------------
// Create first query
$usernameQuery = 'SELECT username FROM users WHERE username="'.mysql_real_escape_string($username).'"';

//----------------------------------------
// Query db
$usernameResult = mysql_query($userNameQuery);

//----------------------------------------
// Check if result is empty
if(mysql_num_rows($usernameResult) > 0){

   //----------------------------------------
   // Username already exists
   $error[] = 'Username already exists';

   //----------------------------------------
   // Return error to user and stop execution
   // of additional queries/code
} else {

  //----------------------------------------
  // Check if email exists

  //----------------------------------------
  // Create query
  $emailQuery = 'SELECT email FROM users WHERE email="'.mysql_real_escape_string($email).'"';

  //----------------------------------------
  // Query the db
  $emailResult = mysql_query($emailQuery);

  //----------------------------------------
  // Check if the result is empty
  if(mysql_num_rows($emailResult) > 0){

     //----------------------------------------
     // Email already exists
     $error[] = 'Email already exists';

     //----------------------------------------
     // Return error to user and stop execution
     // of additional queries/code
  } else {

     //----------------------------------------
     // Continue with registration...
  }
}
?>

Please note that you should always escape your values before executing the actual query.

Additional Resources:

http://us.php.net/manual/en/function.mysql-real-escape-string.php
http://us.php.net/manual/en/function.mysql-escape-string.php

ContentLicense: CC BY-SA 2.5


问:
Android - cancel/replace calendar notification with a custom one
I am trying to replace the built in calendar reminder's notification with a custom built notification using the NotificationManager.

I have added a BroadCastReceiver, that intercepts the calendar reminder's notification, as such:

```<code>     <receiver
        android:name=".receivers.CalendarNotificationBroadcastReceiver">
        <intent-filter>
            <action android:name="android.intent.action.EVENT_REMINDER"/>
            <data android:scheme="content"/>
            <data android:host="com.android.calendar"/>
        </intent-filter>
    </receiver>
</code>```

The intent is passed on to the onReceive method as follows:

Q1: How can I use the ContentResolver API in order to find information about the event that triggered the notification (I need the TITLE field for example for building the new notification)?

Q2: How can I cancel the intent so that the calendar event's reminder notification does not get triggered?
I've tried following the recomendations in this post, but to no avail:
How to cancel this repeating alarm?
Also, I have tried (with no success):

```<code>PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT).cancel();
</code>```

EDIT ******************

After following Ovidiu Latcu's proposal, I have provided an implementation for the NotificationListenerService that also has a BroadcastReceiver for the new notifications

AndroidManifest

```<code><service android:name=".service.CalendarNotificationListenerService"
    android:label="@string/app_name"
    android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
    <intent-filter>
        <action android:name="android.service.notification.NotificationListenerService" />
    </intent-filter>
</service>
</code>```

NotificationListenerService

```<code>@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
/**
 * Due to an android bug: https://stackoverflow.com/questions/17911883/cannot-get-the-notificationlistenerservice-class-to-work
 * This class' name should be changed before each debug use, because if not, onReceive will never get called.
 */
public class CalendarNotificationListenerService extends NotificationListenerService {

    private String TAG = this.getClass().getSimpleName();
    private CalendarNotificationBroadcastReceiver receiver;

@Override
public void onCreate() {
    Log.i(TAG,"********** Service is created");
    super.onCreate();
    receiver = new CalendarNotificationBroadcastReceiver();
    IntentFilter intentFilter = new IntentFilter("android.intent.action.EVENT_REMINDER");
    intentFilter.addDataScheme("content");
    registerReceiver(receiver, intentFilter);
}

@Override
public void onDestroy() {
    Log.i(TAG,"**********  Service is destroyed");
    super.onDestroy();
    unregisterReceiver(receiver);
}

@Override
public IBinder onBind(Intent mIntent) {
    IBinder mIBinder = super.onBind(mIntent);
    Log.i(TAG, "**********  onBind");
    return mIBinder;
}

@Override
public boolean onUnbind(Intent mIntent) {
    boolean mOnUnbind = super.onUnbind(mIntent);
    Log.i(TAG, "**********  onUnbind");
    return mOnUnbind;
}

@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
    Log.i(TAG,"**********  onNotificationPosted");
    Log.i(TAG,"ID :" + sbn.getId() + "\t" + sbn.getNotification().tickerText + "\t" + sbn.getPackageName());

    Notification currentNotification = sbn.getNotification();

    String notificationTitle = (String) sbn.getNotification().extras.get("android.title");

    if(notificationTitle == null || !notificationTitle.startsWith("CALLERQ:")){
        return;
    }

    //Seem to only be able to cancel a notification after it is posted.
    CalendarNotificationListenerService.this.cancelNotification(sbn.getKey());

    Intent i = new  Intent("com.enginizer.NOTIFICATION_LISTENER_EXAMPLE");
    i.putExtra("notification_event","onNotificationPosted :" + sbn.getPackageName() + "\n");
    sendBroadcast(i);
}

@Override
public void onNotificationRemoved(StatusBarNotification sbn) {
    Log.i(TAG,"********** onNOtificationRemoved");
    Log.i(TAG,"ID :" + sbn.getId() + "\t" + sbn.getNotification().tickerText +"\t" + sbn.getPackageName());
    Intent i = new  Intent("com.enginizer.NOTIFICATION_LISTENER_EXAMPLE");
    i.putExtra("notification_event","onNotificationRemoved :" + sbn.getPackageName() + "\n");

    sendBroadcast(i);
}

class CalendarNotificationBroadcastReceiver extends BroadcastReceiver {

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i(TAG, "********** Notification received");
        String intentAction = intent.getAction();
        Log.i(TAG, "********** " + intentAction);
        intent.getBundleExtra(CalendarContract.EXTRA_CUSTOM_APP_URI);

        ContentResolver contentResolver = context.getContentResolver();

        //This throws an java.lang.IllegalArgumentException
        Cursor cursor = contentResolver.query(intent.getData(), new String[]{CalendarContract.Events.DESCRIPTION}, null, null, null);

        CalendarNotificationListenerService.this.cancelAllNotifications();
    }
}

@Override
public void onListenerConnected() {
    Log.i(TAG,"********** Listener connected");
    super.onListenerConnected();
}
</code>```

}

For what was answered in Q1, I am trying to query the calendar for the event noted in the mData field. When doing so, I receive the following:

```<code>java.lang.IllegalArgumentException: Unknown URL content://com.android.calendar/1491653055193
</code>```

For Q2, I am not able to cancel the notification from within the onReceive method since I was not able to find it on the intent. I am only able to cancel the notification in the onNotificationPosted method, which is later than expected.

Should it really be so tangled to cancel a calendar reminder notification and replace it with a custom one?

答:
Q1: The mData field contains the URI of that event. You should probably query that URI and find all the information about the event.

Q2: Since API 18 you can use the NotificationListenerService to intercept when a notification was posted, and cancel it using cancelNotification(String key)

Body:
I am trying to replace the built in calendar reminder's notification with a custom built notification using the NotificationManager.

I have added a BroadCastReceiver, that intercepts the calendar reminder's notification, as such:

     <receiver
        android:name=".receivers.CalendarNotificationBroadcastReceiver">
        <intent-filter>
            <action android:name="android.intent.action.EVENT_REMINDER"/>
            <data android:scheme="content"/>
            <data android:host="com.android.calendar"/>
        </intent-filter>
    </receiver>

The intent is passed on to the onReceive method as follows:

Q1: How can I use the ContentResolver API in order to find information about the event that triggered the notification (I need the TITLE field for example for building the new notification)?

Q2: How can I cancel the intent so that the calendar event's reminder notification does not get triggered?
I've tried following the recomendations in this post, but to no avail:
How to cancel this repeating alarm?
Also, I have tried (with no success):

PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT).cancel();

EDIT ******************

After following Ovidiu Latcu's proposal, I have provided an implementation for the NotificationListenerService that also has a BroadcastReceiver for the new notifications

AndroidManifest

<service android:name=".service.CalendarNotificationListenerService"
    android:label="@string/app_name"
    android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
    <intent-filter>
        <action android:name="android.service.notification.NotificationListenerService" />
    </intent-filter>
</service>

NotificationListenerService

@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
/**
 * Due to an android bug: https://stackoverflow.com/questions/17911883/cannot-get-the-notificationlistenerservice-class-to-work
 * This class' name should be changed before each debug use, because if not, onReceive will never get called.
 */
public class CalendarNotificationListenerService extends NotificationListenerService {

    private String TAG = this.getClass().getSimpleName();
    private CalendarNotificationBroadcastReceiver receiver;

@Override
public void onCreate() {
    Log.i(TAG,"********** Service is created");
    super.onCreate();
    receiver = new CalendarNotificationBroadcastReceiver();
    IntentFilter intentFilter = new IntentFilter("android.intent.action.EVENT_REMINDER");
    intentFilter.addDataScheme("content");
    registerReceiver(receiver, intentFilter);
}

@Override
public void onDestroy() {
    Log.i(TAG,"**********  Service is destroyed");
    super.onDestroy();
    unregisterReceiver(receiver);
}

@Override
public IBinder onBind(Intent mIntent) {
    IBinder mIBinder = super.onBind(mIntent);
    Log.i(TAG, "**********  onBind");
    return mIBinder;
}

@Override
public boolean onUnbind(Intent mIntent) {
    boolean mOnUnbind = super.onUnbind(mIntent);
    Log.i(TAG, "**********  onUnbind");
    return mOnUnbind;
}

@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
    Log.i(TAG,"**********  onNotificationPosted");
    Log.i(TAG,"ID :" + sbn.getId() + "\t" + sbn.getNotification().tickerText + "\t" + sbn.getPackageName());

    Notification currentNotification = sbn.getNotification();

    String notificationTitle = (String) sbn.getNotification().extras.get("android.title");

    if(notificationTitle == null || !notificationTitle.startsWith("CALLERQ:")){
        return;
    }

    //Seem to only be able to cancel a notification after it is posted.
    CalendarNotificationListenerService.this.cancelNotification(sbn.getKey());

    Intent i = new  Intent("com.enginizer.NOTIFICATION_LISTENER_EXAMPLE");
    i.putExtra("notification_event","onNotificationPosted :" + sbn.getPackageName() + "\n");
    sendBroadcast(i);
}

@Override
public void onNotificationRemoved(StatusBarNotification sbn) {
    Log.i(TAG,"********** onNOtificationRemoved");
    Log.i(TAG,"ID :" + sbn.getId() + "\t" + sbn.getNotification().tickerText +"\t" + sbn.getPackageName());
    Intent i = new  Intent("com.enginizer.NOTIFICATION_LISTENER_EXAMPLE");
    i.putExtra("notification_event","onNotificationRemoved :" + sbn.getPackageName() + "\n");

    sendBroadcast(i);
}

class CalendarNotificationBroadcastReceiver extends BroadcastReceiver {

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i(TAG, "********** Notification received");
        String intentAction = intent.getAction();
        Log.i(TAG, "********** " + intentAction);
        intent.getBundleExtra(CalendarContract.EXTRA_CUSTOM_APP_URI);

        ContentResolver contentResolver = context.getContentResolver();

        //This throws an java.lang.IllegalArgumentException
        Cursor cursor = contentResolver.query(intent.getData(), new String[]{CalendarContract.Events.DESCRIPTION}, null, null, null);

        CalendarNotificationListenerService.this.cancelAllNotifications();
    }
}

@Override
public void onListenerConnected() {
    Log.i(TAG,"********** Listener connected");
    super.onListenerConnected();
}

}

For what was answered in Q1, I am trying to query the calendar for the event noted in the mData field. When doing so, I receive the following:

java.lang.IllegalArgumentException: Unknown URL content://com.android.calendar/1491653055193

For Q2, I am not able to cancel the notification from within the onReceive method since I was not able to find it on the intent. I am only able to cancel the notification in the onNotificationPosted method, which is later than expected.

Should it really be so tangled to cancel a calendar reminder notification and replace it with a custom one?


问:
render a partial on ajax:success in coffeescript in rails 5
I am trying to render a partial after ajax call using coffee script but could not make it.

Controller which is called on AJAX request

```<code> def unfollow
     @user = User.find(params[:follow][:followed_id])
     current_user.unfollow!(@user)
     render json: {result: "success"}
 end
</code>```

partial: User/follow.html.erb

```<code> <div id="follow_button">
   <%=form_for(:follow,url: follow_users_path,remote:true) do |f| %>
     <%= f.hidden_field :followed_id, value: @user.id %>
     <%= f.submit "Follow", id: "Follow_button", class: "btn btn-primary" %>
   <% end %>
 </div>
</code>```

Ajax:success function

```<code> $ ->
     $('#unfollow_button').on "ajax:success", (e,data,status,xhr)  ->
     $('#follow_unfollow_button').html("<%= escape_javascript( render partial: 'users/follow') %>")
</code>```

HTML which is on That place

```<code> <div id="unfollow_button">
      <%=form_for(:follow,url: unfollow_users_path,remote:true) do |f| %>
      <%= f.hidden_field :followed_id, value: @user.id %>
      <%= f.submit "Unfollow", id: "unfollow_button", class: "btn btn-primary" %>
      <% end %>
 </div>
</code>```

I am not getting any value from the server I just want to render it when ajax success. But it render like this

```<code>    <%= escape_javascript( render partial: 'users/follow') %>
</code>```

How to solve this? what am I missing?

答:
Don't try to render it from the coffeescript in this case. Instead, render the result from controller and return that as data to ajax.

1)  Change controller method to

```<code>def unfollow
     @user = User.find(params[:follow][:followed_id])
     current_user.unfollow!(@user)
     render 'users/follow', :layout => false
 end
</code>```

2) Change JS function to

```<code>$ ->
     $('#unfollow_button').on "ajax:success", (e,data,status,xhr)  ->
     $('#follow_unfollow_button').html(data)
</code>```

As your controller will return something (and not an error), the ajax:success will fire up and instead of trying to render it in JS/coffeescript, just render it in controller and that way, you also don't need to render something just for the sake of returning information to client.

Body:
I am trying to render a partial after ajax call using coffee script but could not make it.

Controller which is called on AJAX request

 def unfollow
     @user = User.find(params[:follow][:followed_id])
     current_user.unfollow!(@user)
     render json: {result: "success"}
 end

partial: User/follow.html.erb

   <%=form_for(:follow,url: follow_users_path,remote:true) do |f| %>
     <%= f.hidden_field :followed_id, value: @user.id %>
     <%= f.submit "Follow", id: "Follow_button", class: "btn btn-primary" %>
   <% end %>

Ajax:success function

 $ ->
     $('#unfollow_button').on "ajax:success", (e,data,status,xhr)  ->
     $('#follow_unfollow_button').html("<%= escape_javascript( render partial: 'users/follow') %>")

HTML which is on That place

      <%=form_for(:follow,url: unfollow_users_path,remote:true) do |f| %>
      <%= f.hidden_field :followed_id, value: @user.id %>
      <%= f.submit "Unfollow", id: "unfollow_button", class: "btn btn-primary" %>
      <% end %>

I am not getting any value from the server I just want to render it when ajax success. But it render like this

    <%= escape_javascript( render partial: 'users/follow') %>

How to solve this? what am I missing?

Body:
Don't try to render it from the coffeescript in this case. Instead, render the result from controller and return that as data to ajax.

1)  Change controller method to

def unfollow
     @user = User.find(params[:follow][:followed_id])
     current_user.unfollow!(@user)
     render 'users/follow', :layout => false
 end

2) Change JS function to

$ ->
     $('#unfollow_button').on "ajax:success", (e,data,status,xhr)  ->
     $('#follow_unfollow_button').html(data)

As your controller will return something (and not an error), the ajax:success will fire up and instead of trying to render it in JS/coffeescript, just render it in controller and that way, you also don't need to render something just for the sake of returning information to client.


问:
How to add ClientCeritifcates, The HTTP request was forbidden with client authentication scheme 'Anonymous'
I'm getting the follwing error when calling a method from a auto-generated web service proxy class:

System.ServiceModel.Security.MessageSecurityException was unhandled

  HResult=-2146233087   Message=The HTTP request was forbidden with
  client authentication scheme 'Anonymous'.   Source=mscorlib

  StackTrace:
      Server stack trace:
         at System.ServiceModel.Channels.HttpChannelUtilities.ValidateAuthentication(HttpWebRequest
  request, HttpWebResponse response, WebException responseException,
  HttpChannelFactory'1 factory)
         at System.ServiceModel.Channels.HttpChannelUtilities.ValidateRequestReplyResponse(HttpWebRequest
  request, HttpWebResponse response, HttpChannelFactory'1 factory,
  WebException responseException, ChannelBinding channelBinding)
         at System.ServiceModel.Channels.HttpChannelFactory'1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan
  timeout)
         at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
         at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message
  message, TimeSpan timeout)
         at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins,
  Object[] outs, TimeSpan timeout)
         at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins,
  Object[] outs)
         at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage
  methodCall, ProxyOperationRuntime operation)
         at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage
  message)
      Exception rethrown at [0]:
         at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage
  reqMsg, IMessage retMsg)
         at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData&
  msgData, Int32 type)
         at RPS.LoteNFe.LoteNFeSoap.TesteEnvioLoteRPS(TesteEnvioLoteRPSRequest
  request)
         at RPS.LoteNFe.LoteNFeSoapClient.RPS.LoteNFe.LoteNFeSoap.TesteEnvioLoteRPS(TesteEnvioLoteRPSRequest
  request) in c:\Users\Marcelo\Documents\Visual Studio
  2015\Projects\RPS\RPS\Service References\LoteNFe\Reference.cs:line 560
         at RPS.LoteNFe.LoteNFeSoapClient.TesteEnvioLoteRPS(Int32 VersaoSchema, String MensagemXML) in c:\Users\Marcelo\Documents\Visual
  Studio 2015\Projects\RPS\RPS\Service
  References\LoteNFe\Reference.cs:line 567
         at RPS.Assinador.button5_Click(Object sender, EventArgs e) in c:\Users\Marcelo\Documents\Visual Studio
  2015\Projects\RPS\RPS\Assinador.cs:line 76
         at System.Windows.Forms.Control.OnClick(EventArgs e)
         at System.Windows.Forms.Button.OnClick(EventArgs e)
         at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
         at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
         at System.Windows.Forms.Control.WndProc(Message& m)
         at System.Windows.Forms.ButtonBase.WndProc(Message& m)
         at System.Windows.Forms.Button.WndProc(Message& m)
         at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
         at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
         at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
         at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
         at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr
  dwComponentID, Int32 reason, Int32 pvLoopData)
         at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32
  reason, ApplicationContext context)
         at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32
  reason, ApplicationContext context)
         at System.Windows.Forms.Application.Run(Form mainForm)
         at RPS.Program.Main() in c:\Users\Marcelo\Documents\Visual Studio 2015\Projects\RPS\RPS\Program.cs:line 19
         at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
         at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
         at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
         at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
         at System.Threading.ExecutionContext.RunInternal(ExecutionContext
  executionContext, ContextCallback callback, Object state, Boolean
  preserveSyncCtx)
         at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean
  preserveSyncCtx)
         at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
         at System.Threading.ThreadHelper.ThreadStart()   InnerException: System.Net.WebException
         HResult=-2146233079
         Message=The remote server returned an error: (403) Forbidden.
         Source=System
         StackTrace:
              at System.Net.HttpWebRequest.GetResponse()
              at System.ServiceModel.Channels.HttpChannelFactory'1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan
  timeout)
         InnerException:

This is how a call it

```<code>X509Certificate2 x509Certificate = new X509Certificate2();
X509Store store = new X509Store("MY", StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
X509Certificate2Collection collection = ((X509Certificate2Collection)store.Certificates).Find(X509FindType.FindByTimeValid, DateTime.Now, false);
X509Certificate2Collection collection1 = X509Certificate2UI.SelectFromCollection(collection, "Certificados disponiveis", "Selecione o certificado", X509SelectionFlag.SingleSelection);
x509Certificate = collection1[0];

LoteNFeSoapClient loteNFe = new LoteNFeSoapClient();
loteNFe.ClientCredentials.ClientCertificate.SetCertificate(x509Certificate.Subject, StoreLocation.CurrentUser, StoreName.My);
Retorno.Text = loteNFe.TesteEnvioLoteRPS(1, Assinado.Text);
</code>```

How I added this web service reference:

In MS Visual Studio 2013 community, Project > Add > Service Reference:

Service Reference window

Service Reference advanced settings window

Obs: Those are default configs. This a municipal gorvernment webservice used to send eletronic invoices of transportation or logistics services provided.

Ive read somewhere that is necessary to add a certificate like:

```<code>LoteNFeSoapClient loteNFe = new LoteNFeSoapClient();
loteNFe.ClientCertificates.Add(clientCertificate);
</code>```

But its not possible because:

This auto-generated webservice class doesnt inherit from an class
that has this method ClientCertificates.Add() like HttpWebClientProtocol class for example.

LoteNFeSoapClient() class is already inheriting from a
interface that makes the messagecontract to match values between
request and response.

In c# a class can't have multiple base classes.

So, what could be done? Thanks in advance.

答:
Solved, I just generated the webservice proxy class via command line using wsdl.exe, this class now inherits from System.Web.Services.Protocols.SoapHttpClientProtocol, so I can add the certificate using

```<code>LoteNFe loteNFe = new LoteNFe();
loteNFe.ClientCertificates.Add(x509Certificate);
</code>```

Note: The class generated via command line is completely different from the one generated using VS2013 UI.

Body:
I'm getting the follwing error when calling a method from a auto-generated web service proxy class:

System.ServiceModel.Security.MessageSecurityException was unhandled

  HResult=-2146233087   Message=The HTTP request was forbidden with
  client authentication scheme 'Anonymous'.   Source=mscorlib

  StackTrace:
      Server stack trace:
         at System.ServiceModel.Channels.HttpChannelUtilities.ValidateAuthentication(HttpWebRequest
  request, HttpWebResponse response, WebException responseException,
  HttpChannelFactory'1 factory)
         at System.ServiceModel.Channels.HttpChannelUtilities.ValidateRequestReplyResponse(HttpWebRequest
  request, HttpWebResponse response, HttpChannelFactory'1 factory,
  WebException responseException, ChannelBinding channelBinding)
         at System.ServiceModel.Channels.HttpChannelFactory'1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan
  timeout)
         at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
         at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message
  message, TimeSpan timeout)
         at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins,
  Object[] outs, TimeSpan timeout)
         at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins,
  Object[] outs)
         at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage
  methodCall, ProxyOperationRuntime operation)
         at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage
  message)
      Exception rethrown at [0]:
         at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage
  reqMsg, IMessage retMsg)
         at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData&
  msgData, Int32 type)
         at RPS.LoteNFe.LoteNFeSoap.TesteEnvioLoteRPS(TesteEnvioLoteRPSRequest
  request)
         at RPS.LoteNFe.LoteNFeSoapClient.RPS.LoteNFe.LoteNFeSoap.TesteEnvioLoteRPS(TesteEnvioLoteRPSRequest
  request) in c:\Users\Marcelo\Documents\Visual Studio
  2015\Projects\RPS\RPS\Service References\LoteNFe\Reference.cs:line 560
         at RPS.LoteNFe.LoteNFeSoapClient.TesteEnvioLoteRPS(Int32 VersaoSchema, String MensagemXML) in c:\Users\Marcelo\Documents\Visual
  Studio 2015\Projects\RPS\RPS\Service
  References\LoteNFe\Reference.cs:line 567
         at RPS.Assinador.button5_Click(Object sender, EventArgs e) in c:\Users\Marcelo\Documents\Visual Studio
  2015\Projects\RPS\RPS\Assinador.cs:line 76
         at System.Windows.Forms.Control.OnClick(EventArgs e)
         at System.Windows.Forms.Button.OnClick(EventArgs e)
         at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
         at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
         at System.Windows.Forms.Control.WndProc(Message& m)
         at System.Windows.Forms.ButtonBase.WndProc(Message& m)
         at System.Windows.Forms.Button.WndProc(Message& m)
         at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
         at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
         at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
         at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
         at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr
  dwComponentID, Int32 reason, Int32 pvLoopData)
         at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32
  reason, ApplicationContext context)
         at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32
  reason, ApplicationContext context)
         at System.Windows.Forms.Application.Run(Form mainForm)
         at RPS.Program.Main() in c:\Users\Marcelo\Documents\Visual Studio 2015\Projects\RPS\RPS\Program.cs:line 19
         at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
         at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
         at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
         at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
         at System.Threading.ExecutionContext.RunInternal(ExecutionContext
  executionContext, ContextCallback callback, Object state, Boolean
  preserveSyncCtx)
         at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean
  preserveSyncCtx)
         at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
         at System.Threading.ThreadHelper.ThreadStart()   InnerException: System.Net.WebException
         HResult=-2146233079
         Message=The remote server returned an error: (403) Forbidden.
         Source=System
         StackTrace:
              at System.Net.HttpWebRequest.GetResponse()
              at System.ServiceModel.Channels.HttpChannelFactory'1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan
  timeout)
         InnerException:

This is how a call it

X509Certificate2 x509Certificate = new X509Certificate2();
X509Store store = new X509Store("MY", StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
X509Certificate2Collection collection = ((X509Certificate2Collection)store.Certificates).Find(X509FindType.FindByTimeValid, DateTime.Now, false);
X509Certificate2Collection collection1 = X509Certificate2UI.SelectFromCollection(collection, "Certificados disponiveis", "Selecione o certificado", X509SelectionFlag.SingleSelection);
x509Certificate = collection1[0];

LoteNFeSoapClient loteNFe = new LoteNFeSoapClient();
loteNFe.ClientCredentials.ClientCertificate.SetCertificate(x509Certificate.Subject, StoreLocation.CurrentUser, StoreName.My);
Retorno.Text = loteNFe.TesteEnvioLoteRPS(1, Assinado.Text);

How I added this web service reference:

In MS Visual Studio 2013 community, Project > Add > Service Reference:

Service Reference window

Service Reference advanced settings window

Obs: Those are default configs. This a municipal gorvernment webservice used to send eletronic invoices of transportation or logistics services provided.

Ive read somewhere that is necessary to add a certificate like:

LoteNFeSoapClient loteNFe = new LoteNFeSoapClient();
loteNFe.ClientCertificates.Add(clientCertificate);

But its not possible because:

This auto-generated webservice class doesnt inherit from an class
that has this method ClientCertificates.Add() like HttpWebClientProtocol class for example.

LoteNFeSoapClient() class is already inheriting from a
interface that makes the messagecontract to match values between
request and response.

In c# a class can't have multiple base classes.

So, what could be done? Thanks in advance.

Body:
Solved, I just generated the webservice proxy class via command line using wsdl.exe, this class now inherits from System.Web.Services.Protocols.SoapHttpClientProtocol, so I can add the certificate using

LoteNFe loteNFe = new LoteNFe();
loteNFe.ClientCertificates.Add(x509Certificate);

Note: The class generated via command line is completely different from the one generated using VS2013 UI.


问:
UUID mismatch detected with the loaded library
I get a "UUID mismatch" warning at the console when I try to build and run my app on my iPhone.

warning: UUID mismatch detected with
  the loaded library - on disk is:
  /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS2.1.sdk/usr/lib/liblockdown.dylib
  =uuid-mismatch-with-loaded-file,file="/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS2.1.sdk/usr/lib/liblockdown.dylib

Anyone has this issue and managed to resolve the warning ?

答: The current final SDK is only 4.2 while the iOS out in the wild on the devices is 4.2.1.  When you first plug in your device in XCode, the Organizer window will collect the debug symbols for your device.  If you need to do this again, you can explicitly delete the /Developer/Platforms/iPhoneOS.platform/DeviceSupport/.  Funny thing is that occasionally you still get those annoying "Unable to find symbols" error.  But at least you'll be able to debug on device now.</p>

OwnerDisplayName: ronin

LastEditorDisplayName: Ned Batchelder


问:
SuiteCRM 403 Error (Forbidden) when trying to save template
Usually i try to resolve issue by my self, but in this case i am lost ;-)

I had install suiteCRM 7.8.2 on my server (managed with plesk onyx)

Everything work great except one thing :

When i am trying to save a pdf template or an email template, i get an 403 error (Fobidden acces)

Things i have already done :

trying chmod 777 for all files and folders of suiteCRM => Not working

Change permission in config.php => Not working

Quick Repair  => Not working

Delete cache folder => Not working

hitting on my laptop => Not working ... grrr..

I have no access to more information, in browser console i can see that SuiteCRM trying to send POST request to index.php and index.php answer 403 error, nothing in log file in debug mode...

I don't have more ideas ....

Thank you.
Rémi.

答:
Solved :

I have look "/var/www/vhosts/system/YOUR-DOMAIN.COM/logs"

[Sun Apr 02 21:34:58.173943 2017] [:error] [pid 29185] [client 82.227.112.246] ModSecurity: Access denied with code 403 (phase 2). Match of "rx ((?:submit(?:\\+| )?(request)?(?:\\+| )?>+|<<(?:\\+| )remove|(?:sign ?in|log ?(?:in|out)|next|modifier|envoyer|add|continue|weiter|account|results|select)?(?:\\+| )?>+)$|^< ?\\??(?: |\\+)?xml|^> ?$)" against "ARGS:sample" required. [file "/etc/apache2/modsecurity.d/rules/tortix/modsec/50_plesk_basic_asl_rules.conf"] [line "308"] [id "350147"] [rev "143"] [msg "Protected by Atomicorp.com Basic Non-Realtime WAF Rules: Potentially Untrusted Web Content Detected"] [data ""] [severity "CRITICAL"] [hostname "XXXXXXXX"] [uri "/SuiteCRM/index.php"] [unique_id "WOFSYtX2OSwAAHIBsoAAAAAF"]

It's modsecurity firewall !

So i have disabled the 350147 rules from modsecurity (https://docs.plesk.com/en-US/12.5/administrator-guide/73383/ + Switching off Rules)

It's work !

Thanks to  UFHH01 , i love you ;-)