问:
Using batch normalization with dropout in test phase gives Nan
I am trying to add batch normalization to my CNN and have read a lot of posts about how to do so but still my implementation yields an array of nans as a result when setting training to False.

When setting training to True even on test time, results are not Nan but they are worse than on training time if I test on training images.

I used a decay of 0.9 and trained on 15 000 iterations

Here is my graph building, adding update ops as a dependency as recommended in tf.layers.batch_normalization documentation and then using sess

```<code>extra_update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
  with tf.control_dependencies(extra_update_ops):
    phase_train = tf.placeholder(tf.bool, name='phase_train')

    ###### Other placeholders and variables declarations ######

    # Build a Graph that computes the logits predictions from the inference model.

    loss, eval_prediction = inference(train_data_node, train_labels_node, batch_size, phase_train, dropout_out_keep_prob)

    # Build a Graph that trains the model with one batch of examples and updates the model parameters.

    ###### Should I rather put the dependency here ? ######
    train_op = train(loss, global_step)

    saver = tf.train.Saver(tf.global_variables())

    with tf.Session() as sess:
          init = tf.global_variables_initializer()
          sess.run(init)

          # Start the queue runners.
          coord = tf.train.Coordinator()
          threads = tf.train.start_queue_runners(sess=sess, coord=coord)

          for step in range(startstep, startstep + max_steps):
            feed_dict = fill_feed_dict(train_labels_node, train_data_node, dropout_out_keep_prob, phase_train, batch_size, phase_train_val=True,drop_out_keep_prob_val=1.)
            _, loss_value = sess.run([train_op, loss], feed_dict=feed_dict)
</code>```

here is my batch_norm function call:

```<code>def batch_norm_layer(inputT, is_training, scope):
    return tf.layers.batch_normalization(inputT, training=is_training, center=False, reuse=None, momentum=0.9)
</code>```

and now here is how I restore the model for testing:

```<code>phase_train = tf.placeholder(tf.bool, name='phase_train')

###### Other placeholder definitions ######

loss, logits = inference(test_data_node, test_labels_node, batch_size, phase_train, drop_out_keep_prob)
pred = tf.argmax(logits, dimension=3)

saver = tf.train.Saver()

with tf.Session() as sess:
  saver.restore(sess, test_ckpt)

  threads = tf.train.start_queue_runners(sess=sess)

  feed_dict = fill_feed_dict(test_labels_node, test_data_node, drop_out_keep_prob, phase_train, batch_size=1, phase_train_val=False, drop_out_keep_prob_val=1.)

  pred_loss, dense_prediction, predicted_image = sess.run([loss, logits, pred], feed_dict=feed_dict)
</code>```

Here dense_prediction gives an array of Nans and thus predicted_image is all 0
Is there an error in my construction ? How can I fix it / diagnose it ?

Any help would be welcome, I have read a lot of tutorials to use "hand made" batch norm but I couldn't find a well guided tutorial on how to use the official batch norm, guess it is because it's too obvious, but it's not for me !

答:
It appears the problem was coming from the fact that I was using batch normalization along with tf.nn.dropout dropout implementation.

Switching to tf.layers.dropout solved the issue.

Body:
I am trying to add batch normalization to my CNN and have read a lot of posts about how to do so but still my implementation yields an array of nans as a result when setting training to False.

When setting training to True even on test time, results are not Nan but they are worse than on training time if I test on training images.

I used a decay of 0.9 and trained on 15 000 iterations

Here is my graph building, adding update ops as a dependency as recommended in tf.layers.batch_normalization documentation and then using sess

extra_update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
  with tf.control_dependencies(extra_update_ops):
    phase_train = tf.placeholder(tf.bool, name='phase_train')

    ###### Other placeholders and variables declarations ######

    # Build a Graph that computes the logits predictions from the inference model.

    loss, eval_prediction = inference(train_data_node, train_labels_node, batch_size, phase_train, dropout_out_keep_prob)

    # Build a Graph that trains the model with one batch of examples and updates the model parameters.

    ###### Should I rather put the dependency here ? ######
    train_op = train(loss, global_step)

    saver = tf.train.Saver(tf.global_variables())

    with tf.Session() as sess:
          init = tf.global_variables_initializer()
          sess.run(init)

          # Start the queue runners.
          coord = tf.train.Coordinator()
          threads = tf.train.start_queue_runners(sess=sess, coord=coord)

          for step in range(startstep, startstep + max_steps):
            feed_dict = fill_feed_dict(train_labels_node, train_data_node, dropout_out_keep_prob, phase_train, batch_size, phase_train_val=True,drop_out_keep_prob_val=1.)
            _, loss_value = sess.run([train_op, loss], feed_dict=feed_dict)

here is my batch_norm function call:

def batch_norm_layer(inputT, is_training, scope):
    return tf.layers.batch_normalization(inputT, training=is_training, center=False, reuse=None, momentum=0.9)

and now here is how I restore the model for testing:

phase_train = tf.placeholder(tf.bool, name='phase_train')

###### Other placeholder definitions ######

loss, logits = inference(test_data_node, test_labels_node, batch_size, phase_train, drop_out_keep_prob)
pred = tf.argmax(logits, dimension=3)

saver = tf.train.Saver()

with tf.Session() as sess:
  saver.restore(sess, test_ckpt)

  threads = tf.train.start_queue_runners(sess=sess)

  feed_dict = fill_feed_dict(test_labels_node, test_data_node, drop_out_keep_prob, phase_train, batch_size=1, phase_train_val=False, drop_out_keep_prob_val=1.)

  pred_loss, dense_prediction, predicted_image = sess.run([loss, logits, pred], feed_dict=feed_dict)

Here dense_prediction gives an array of Nans and thus predicted_image is all 0
Is there an error in my construction ? How can I fix it / diagnose it ?

Any help would be welcome, I have read a lot of tutorials to use "hand made" batch norm but I couldn't find a well guided tutorial on how to use the official batch norm, guess it is because it's too obvious, but it's not for me !


来源: stackexchange

问:
Problems starting tomcat 7 in centos 7
I'm trying to run tomcat 7 in centos-release-7-4.1708.el7.centos.x86_64

These are the steps followed:

```<code>yum install java-1.7.0-openjdk-devel java-1.7.0-openjdk
</code>```

Test if installed:

```<code>echo $JAVA_HOME
/usr/java/jdk/
echo $JRE_HOME
/usr/java/jdk/jre
</code>```

Install tomcat 7

```<code>yum install tomcat tomcat-webapps tomcat-admin-webapps

systemctl stop tomcat
systemctl start tomcat
systemctl enable tomcat
</code>```

It should create a symlink to tomcat.service, but no...

```<code>systemctl status tomcat

tomcat.service - Apache Tomcat Web Application Container
   Loaded: loaded (/usr/lib/systemd/system/tomcat.service; enabled; vendor preset: disabled)
   Active: failed (Result: exit-code) since Mon 2017-11-13 10:26:33 WET; 4min 7s ago
  Process: 2825 ExecStart=/usr/libexec/tomcat/server start (code=exited, status=127)
 Main PID: 2825 (code=exited, status=127)

systemd[1]: Started Apache Tomcat Web Application Container.
systemd[1]: Starting Apache Tomcat Web Application Container...
server[2825]: /usr/libexec/tomcat/server: Failed to set JAVACMD
systemd[1]: tomcat.service: main process exited, code=exited, status=127/n/a
systemd[1]: Unit tomcat.service entered failed state.
systemd[1]: tomcat.service failed.
</code>```

UPDATE 1

Content of file tomcat.service in /usr/lib/systemd/system

```<code># Systemd unit file for default tomcat
#
# To create clones of this service:
# DO NOTHING, use tomcat@.service instead.

[Unit]
Description=Apache Tomcat Web Application Container
After=syslog.target network.target

[Service]
Type=simple
EnvironmentFile=/etc/tomcat/tomcat.conf
Environment="NAME="
EnvironmentFile=-/etc/sysconfig/tomcat
ExecStart=/usr/libexec/tomcat/server start
SuccessExitStatus=143
User=tomcat
Group=tomcat

[Install]
WantedBy=multi-user.target
</code>```

答: Replace JAVA_HOME in the /etc/tomcat/tomcat.conf with /usr/java/jdk/</p>

ContentLicense: CC BY-SA 3.0

Title: Problems starting tomcat 7 in centos 7

Body:
I'm trying to run tomcat 7 in centos-release-7-4.1708.el7.centos.x86_64

These are the steps followed:

yum install java-1.7.0-openjdk-devel java-1.7.0-openjdk

Test if installed:

echo $JAVA_HOME
/usr/java/jdk/
echo $JRE_HOME
/usr/java/jdk/jre

Install tomcat 7

yum install tomcat tomcat-webapps tomcat-admin-webapps

systemctl stop tomcat
systemctl start tomcat
systemctl enable tomcat

It should create a symlink to tomcat.service, but no...

systemctl status tomcat

tomcat.service - Apache Tomcat Web Application Container
   Loaded: loaded (/usr/lib/systemd/system/tomcat.service; enabled; vendor preset: disabled)
   Active: failed (Result: exit-code) since Mon 2017-11-13 10:26:33 WET; 4min 7s ago
  Process: 2825 ExecStart=/usr/libexec/tomcat/server start (code=exited, status=127)
 Main PID: 2825 (code=exited, status=127)

systemd[1]: Started Apache Tomcat Web Application Container.
systemd[1]: Starting Apache Tomcat Web Application Container...
server[2825]: /usr/libexec/tomcat/server: Failed to set JAVACMD
systemd[1]: tomcat.service: main process exited, code=exited, status=127/n/a
systemd[1]: Unit tomcat.service entered failed state.
systemd[1]: tomcat.service failed.

UPDATE 1

Content of file tomcat.service in /usr/lib/systemd/system

# Systemd unit file for default tomcat
#
# To create clones of this service:
# DO NOTHING, use tomcat@.service instead.

[Unit]
Description=Apache Tomcat Web Application Container
After=syslog.target network.target

[Service]
Type=simple
EnvironmentFile=/etc/tomcat/tomcat.conf
Environment="NAME="
EnvironmentFile=-/etc/sysconfig/tomcat
ExecStart=/usr/libexec/tomcat/server start
SuccessExitStatus=143
User=tomcat
Group=tomcat

[Install]
WantedBy=multi-user.target


问:
Single cell or multiple cells?
I'm working on an iOS project, writing in Swift. It's a social network app where people have profiles and they can post different type of content. There should be 9 type of posts/content:

Normal (text only) post

Images post

Gif post

Video post

Audio post

Quote post

Chat post

Poll post

Link post

My question is related to how should I display it on the feed. The feed obviously would be some type of a collection (I think I'll stick with UICollectionView) but should I create 1 type of a cell, add every single element that I might need to display each type of a content embedded into a UIStackView and if it's the database request returns nil for an object (i.e that particular post doesn't have video or an audio, a poll, etc - all it contains is just some images) then I'll hide those UIStackViews from the cell OR should I create a separate type of a cell and its xib file, depending on the the content type?

I feel like the latter would be easier, but I'm not how to that? Meaning, how should I check what type of a content is it? Imagine something like Twitter for example, you see many different type of content, how should you approach the cell creation and displaying them?

PS: Keep in mind that the users should be able to filter their content based on the content type (i.e display only images, only text, only audio, etc). How should I approach this?

答: IMHO, it is better to create separate cell for every content type and manipulate views in it as needed. It is clearer and simpler solution.</p>

Title: Single cell or multiple cells?


问:
Setting `processData: false` in jQuery + Datatables appends unknown stuff to URL of my Ajax calls
In following this post, I wanted to convert all my Ajax requests to JSON automatically and it's been working fine.

However, I've noticed that sometimes jQuery adds a mysterious &[object%20Object] at the end of the URL right before the anti-cache parameter (_=1472476048876 for example), because I also have cache: false set.

When I change processData to be true, the mysterious part disappears. Anyone have any ideas why? I'm using jQuery 2.1.4.

Edit: I've noticed that the error only is produced when I make an Ajax call via Datatables .load() API. Has anyone else had this issue?

Edit 2: In response to @war10ck 's great answer, to clarify, I'm making a GET request but I'm not sending any data with it. I create the URL by hand and thus I think that Datatables is adding some data (even an empty object maybe) to my request which is getting turned into [object%20Object].

答:
Thank you guys! In addition to your researches that helped me to solve my problem I would like to share the corresponding solution.

In my case the problem is a call similar to

http://server/dir/resource.en.json?_=1510566367817

resulted in
http://server/dir/[object%20Object]?_=1510566367817

The main hint is daveslab' one regarding to handling of empty objects.

In combination with a multi language project envinronment I came around thinking about missing resource files. That ist where the empty object joins the game because the relevant resource.fr.json file was missing.

In this case it doesn't matter if processData is set to false or true.
I checked both.

Summary

Json files called by client-side code but missing on the server can cause the same issue.

Client facts in my case:
I use jquery 3.2.1 AJAX Get-Service with the following configuration

```<code>{
    dataType: "json",
    async: true,
    cache: false,
    processData: false
}
</code>```

Body:
Thank you guys! In addition to your researches that helped me to solve my problem I would like to share the corresponding solution.

In my case the problem is a call similar to

http://server/dir/resource.en.json?_=1510566367817

resulted in
http://server/dir/[object%20Object]?_=1510566367817

The main hint is daveslab' one regarding to handling of empty objects.

In combination with a multi language project envinronment I came around thinking about missing resource files. That ist where the empty object joins the game because the relevant resource.fr.json file was missing.

In this case it doesn't matter if processData is set to false or true.
I checked both.

Summary

Json files called by client-side code but missing on the server can cause the same issue.

Client facts in my case:
I use jquery 3.2.1 AJAX Get-Service with the following configuration

{
    dataType: "json",
    async: true,
    cache: false,
    processData: false
}


问:
Cannot access constant through itemRenderer using parentDocument
I have an itemRenderer inside a dataGrid, and I am able to access variables on the mxml file (in a *.as script file referenced from the mxml) using parentDocument. However, I am unable to access a constant in the same script file.  If I change the constant to a regular var, I can access it.

I created a getter function for the constant and it works, but why can't the constant be
accessed directly?

Thanks

答:
Constants are generally static, and therefore access via the class.  Getters / Setters are members, and therefore accessed via an instance.

Therefore, to get access to a constant, you need to have an explicit reference to the class.

Something like parentDocument.MY_CONSTANT wouldn't work, however MyClass(parentDocument).MY_CONSTANT would.

ContentLicense: CC BY-SA 2.5


问:
React-Native: No children allowed in my <image></image>
I'm having an issue with my code.

I'm not allowed to put anything in between my image tags, but I need to in order to load in the rest of my application.

```<code>class BackgroundImage extends Component {
render() {
    return(
        <Image source={require('./img/Sunny.jpg')}
              style={styles.backgroundImage}>
                  {this.props.children}
        </Image>
    )
}
}
</code>```

This is the code I'm using, but for another class-mate it works just fine.
I can't find anything special in his code, sadly.

Here is the error:
image error screen.

EDIT: As it stands right now I put  tags around my whole code.
The only thing that gets loaded in is the background-image and nothing else.

I'm just trying to add a background to my application, it's giving my a haaard time. Any help will be very appreciated, thanks!

EDIT:

Extra pictures of my horrid code:

Start of render

End of render

CSS

This is what I have right now. In my code there are only <Text> and <View> with this.state.x

The code

Attempt with Tim's code (failed)

答:
You need to put a View around your Image and positioned it as absolute, because your are not allowed to pass children to image tag.

```<code>import React, { Component } from 'react';
import { Text } from 'react-native';
import BackgroundImage from './BackgroudImage';

class MainApp extends Component {

render() {
    return (
        <BackgroundImage>
            <Text style={{ backgroundColor: 'transparent', fontSize: 30 }}> Test </Text>
        </BackgroundImage>
    );
  }
}
export default MainApp;
</code>```

And here your BackgroundImage Component:

```<code>import React, { Component } from 'react';
import { View, Image } from 'react-native';
import background from '../../img/test.jpg';

class BackgroundImage extends Component {
    render() {
        return (
            <View style={{ flex: 1, position: 'relative' }}>
            {this.props.children}
            <Image
            source={background}
            style={{ zIndex: -1, position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, resizeMode: 'cover' }}
            />
            </View>
        );
    }
}
export default BackgroundImage;
</code>```

And here the result:

Edit: example

Body:
I'm having an issue with my code.

I'm not allowed to put anything in between my image tags, but I need to in order to load in the rest of my application.

class BackgroundImage extends Component {
render() {
    return(
        <Image source={require('./img/Sunny.jpg')}
              style={styles.backgroundImage}>
                  {this.props.children}
        </Image>
    )
}
}

This is the code I'm using, but for another class-mate it works just fine.
I can't find anything special in his code, sadly.

Here is the error:
image error screen.

EDIT: As it stands right now I put  tags around my whole code.
The only thing that gets loaded in is the background-image and nothing else.

I'm just trying to add a background to my application, it's giving my a haaard time. Any help will be very appreciated, thanks!

EDIT:

Extra pictures of my horrid code:

Start of render

End of render

CSS

This is what I have right now. In my code there are only <Text> and <View> with this.state.x

The code

Attempt with Tim's code (failed)

Body:
You need to put a View around your Image and positioned it as absolute, because your are not allowed to pass children to image tag.

import React, { Component } from 'react';
import { Text } from 'react-native';
import BackgroundImage from './BackgroudImage';

class MainApp extends Component {

render() {
    return (
        <BackgroundImage>
            <Text style={{ backgroundColor: 'transparent', fontSize: 30 }}> Test </Text>
        </BackgroundImage>
    );
  }
}
export default MainApp;

And here your BackgroundImage Component:

import React, { Component } from 'react';
import { View, Image } from 'react-native';
import background from '../../img/test.jpg';

class BackgroundImage extends Component {
    render() {
        return (
            <View style={{ flex: 1, position: 'relative' }}>
            {this.props.children}
            <Image
            source={background}
            style={{ zIndex: -1, position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, resizeMode: 'cover' }}
            />
            </View>
        );
    }
}
export default BackgroundImage;

And here the result:

Edit: example


问:
How to make border radius closer to the center
I want to make a shadow around a rounded image, to do so I used a border-radius: 100px and a box-shadow: 0 0 5px 5px #888; to it, but I want to make it deeper to reach the circle and remove that white part.

Here is a screenshot of what it looks like.

.bubbles {
  border-radius: 100px;
  box-shadow: 0 0 5px 5px #888;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img class="bubbles" src="https://img4.hostingpics.net/thumbs/mini_771288logomesure.png" alt="Heberger image" /></code>```

JSFiddle here

答:
If you can't change the image and need a CSS solution. Use a div and set the background-image instead of using an  tag.

.bubbles {
  width: 147px;
  height: 147px;
  border-radius: 100px;
  box-shadow: 0 0 5px 5px #888;
  background-image: url('https://img4.hostingpics.net/thumbs/mini_771288logomesure.png');
  background-origin: border-box;
  background-position: -10px -10px, center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="bubbles" /></code>```

Body:
I want to make a shadow around a rounded image, to do so I used a border-radius: 100px and a box-shadow: 0 0 5px 5px #888; to it, but I want to make it deeper to reach the circle and remove that white part.

Here is a screenshot of what it looks like.

.bubbles {
  border-radius: 100px;
  box-shadow: 0 0 5px 5px #888;
}

JSFiddle here

Body:
If you can't change the image and need a CSS solution. Use a div and set the background-image instead of using an <img /> tag.

.bubbles {
  width: 147px;
  height: 147px;
  border-radius: 100px;
  box-shadow: 0 0 5px 5px #888;
  background-image: url('https://img4.hostingpics.net/thumbs/mini_771288logomesure.png');
  background-origin: border-box;
  background-position: -10px -10px, center;
}

<a href=""><div class="bubbles" /></a>


问:
MVVM Light DialogMessage
im trying to use the mvvmlight DialogMessage.

```<code>var message = new DialogMessage(
            "Confirm Delete", RemoveAddressAction)
            {
                Button = MessageBoxButton.OKCancel,
                Caption = "Caption??"
            };
</code>```

VS2010 undelines the "Button = MessageBoxButton.OKCancel" line complaining about

"Cannot convert source type 'System.Windows.MessageBoxButton [PresentationFramework, Version=3.0.0.0, Culture...] to target type 'System.Windows.MessageBoxItem [GalaSoft.MvvmLight, Version=3.0.0.29216, ...]

And a similar issue on the code behind on the view when I try to use the DialogMessage to show the messagebox.

Has anyone encountered this before? I have no clue how to fix it.

Thanks.

答:
I copy-pasted your code in mine (VS2010) and it builds with no underline.  Things to try:
Solution Clean and Build; Check if you have the latest of MVVM Light;
Check Button's type and explicitly state System.Windows.MessageBoxButton or System.Windows.MessageBoxItem;  Target .NET 4.0..?;</p>

Title: MVVM Light DialogMessage

Body:
im trying to use the mvvmlight DialogMessage.

var message = new DialogMessage(
            "Confirm Delete", RemoveAddressAction)
            {
                Button = MessageBoxButton.OKCancel,
                Caption = "Caption??"
            };

VS2010 undelines the "Button = MessageBoxButton.OKCancel" line complaining about

"Cannot convert source type 'System.Windows.MessageBoxButton [PresentationFramework, Version=3.0.0.0, Culture...] to target type 'System.Windows.MessageBoxItem [GalaSoft.MvvmLight, Version=3.0.0.29216, ...]

And a similar issue on the code behind on the view when I try to use the DialogMessage to show the messagebox.

Has anyone encountered this before? I have no clue how to fix it.

Thanks.


问:
Why std::begin uses trailing return type syntax?
The range-access function std::begin is declared as follows (for containers):

```<code>template< class C >
auto begin( C& c ) -> decltype(c.begin());
</code>```

I just wonder why it's not simply

```<code>template< class C >
decltype(C::begin) begin( C& c );
</code>```

Is there any difference between these two?

答:
This version

```<code>template< class C >
decltype(C::begin) begin( C& c )
</code>```

won't work, because

decltype(C::begin) means the type of the method, not the type of the result of the method call, and anyway

the begin method is overloaded for standard containers, and without the context of a function call (even if not evaluated), the compiler will be unable to decide which overload should participate

The std::declval version shown by VTT fixes that, by creating an un-evaluated function call context where the overload can be resolved. Using the trailing decltype instead saves repeating the argument type.

Body:
The range-access function std::begin is declared as follows (for containers):

template< class C >
auto begin( C& c ) -> decltype(c.begin());

I just wonder why it's not simply

template< class C >
decltype(C::begin) begin( C& c );

Is there any difference between these two?

Body:
This version

template< class C >
decltype(C::begin) begin( C& c )

won't work, because

decltype(C::begin) means the type of the method, not the type of the result of the method call, and anyway

the begin method is overloaded for standard containers, and without the context of a function call (even if not evaluated), the compiler will be unable to decide which overload should participate

The std::declval version shown by VTT fixes that, by creating an un-evaluated function call context where the overload can be resolved. Using the trailing decltype instead saves repeating the argument type.


问:
javax.servlet.ServletException: HV000030: No validator could be found for type: char[]
I want to validate a form input. Specifically a name parameter which has a maximum length of 255 characters. But I get this exception

```<code>UnexpectedTypeException: HV000030: No validator could be found for constraint org.hibernate.validator.constraints.Length validating type char[]. Check configuration for ...
</code>```

for the following mapping:

```<code>import org.hibernate.validator.constraints.Length;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Validated
@RestController
@RequestMapping("/profile")
public class ProfileController {

    @PostMapping(value = "/savename")
    public Response saveName(
            @Length(max = 255)
            @RequestParam(value = "name", required = true) char[] name
    ) {
        return ...
    }

}
</code>```

What's wrong?

答:
@Length works with Strings only. For character arrays use @Size instead. Here's the correct mapping:

```<code>import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.validation.constraints.Size;

@Validated
@RestController
@RequestMapping("/profile")
public class ProfileController {

    @PostMapping(value = "/savename")
    public Response saveName(
            @Size(max = 255)
            @RequestParam(value = "name", required = true) char[] name
    ) {
        return ...
    }

}
</code>```

Body:
I want to validate a form input. Specifically a name parameter which has a maximum length of 255 characters. But I get this exception

UnexpectedTypeException: HV000030: No validator could be found for constraint org.hibernate.validator.constraints.Length validating type char[]. Check configuration for ...

for the following mapping:

import org.hibernate.validator.constraints.Length;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Validated
@RestController
@RequestMapping("/profile")
public class ProfileController {

    @PostMapping(value = "/savename")
    public Response saveName(
            @Length(max = 255)
            @RequestParam(value = "name", required = true) char[] name
    ) {
        return ...
    }

}

What's wrong?

Body:
@Length works with Strings only. For character arrays use @Size instead. Here's the correct mapping:

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.validation.constraints.Size;

@Validated
@RestController
@RequestMapping("/profile")
public class ProfileController {

    @PostMapping(value = "/savename")
    public Response saveName(
            @Size(max = 255)
            @RequestParam(value = "name", required = true) char[] name
    ) {
        return ...
    }

}


问:
Do not allow past date for drop in fullcalendar
Hi I am using fullcalendar for schdule event
Now I want to disable pas date for drop event, So I fixed using following solution

```<code>$('#calendar').fullCalendar({
  eventConstraint: {
    start: moment().format('YYYY-MM-DD'),
    end: '2100-01-01'
  },
});
</code>```

It working fine, but now I want to disable few days from week too, so I added dow in eventConstraint, now its stop working

```<code>$('#calendar').fullCalendar({
  eventConstraint: {
    start: moment().format('YYYY-MM-DD'),
    end: '2100-01-01',
    dow: [ 3, 5 ]
  },
});
</code>```

In short I want to disable past date and allow to select only wed and fri from calendar.

Is there anyway to fix issue.

答:
Having given this some more thought after your comments, I think this is best solved using some custom code, via the eventDrop callback:

```<code>eventDrop: function(event, delta, revertFunc) {
  var day = event.start.clone();
  day.startOf("day");
  var dayOfWeek = day.isoWeekday();
  if (day.isBefore(moment().startOf("day")) || (dayOfWeek != 3 && dayOfWeek != 5)) {
    revertFunc()
  }
}
</code>```

This will check for both of your constraints: if the day is in the past, or that the day is not a Wednesday and not a Friday, then revertFunc() is executed, which is a fullCalendar-provided callback which sends the event back to its original location on the calendar.

Here you can find a working demo: http://jsfiddle.net/ughug9xx/2/

Body:
Hi I am using fullcalendar for schdule event
Now I want to disable pas date for drop event, So I fixed using following solution

$('#calendar').fullCalendar({
  eventConstraint: {
    start: moment().format('YYYY-MM-DD'),
    end: '2100-01-01'
  },
});

It working fine, but now I want to disable few days from week too, so I added dow in eventConstraint, now its stop working

$('#calendar').fullCalendar({
  eventConstraint: {
    start: moment().format('YYYY-MM-DD'),
    end: '2100-01-01',
    dow: [ 3, 5 ]
  },
});

In short I want to disable past date and allow to select only wed and fri from calendar.

Is there anyway to fix issue.

Body:
Having given this some more thought after your comments, I think this is best solved using some custom code, via the eventDrop callback:

eventDrop: function(event, delta, revertFunc) {
  var day = event.start.clone();
  day.startOf("day");
  var dayOfWeek = day.isoWeekday();
  if (day.isBefore(moment().startOf("day")) || (dayOfWeek != 3 && dayOfWeek != 5)) {
    revertFunc()
  }
}

This will check for both of your constraints: if the day is in the past, or that the day is not a Wednesday and not a Friday, then revertFunc() is executed, which is a fullCalendar-provided callback which sends the event back to its original location on the calendar.

Here you can find a working demo: http://jsfiddle.net/ughug9xx/2/


问:
How to copy top and remaining values to different cell in Excel VBA

I would like to select the top 10 Values from Main table and paste in different range (E3) and REMAINING all values and PASTE and SUM in another range(I3)
I used the code below. It is working for Top 10 values, BUT for remaining,
when i am adding one more row in Main table, it is not working. Help me.

```<code>Private Sub CommandButton1_Click()

'Calculation for Top 10 Countries
Sheets("Sheet1").Range("C" & Rows.Count).End(xlUp).Offset(-9, -2).Resize(10, 3).Copy Sheets("Sheet1").Range("E3")

'Calculation for Remaining Countries
Range("A3:C14").Copy Range("I3")
Range("I15").Select
ActiveCell.FormulaR1C1 = "Remaining"
Range("J15").Select
ActiveCell.FormulaR1C1 = "=SUM(R[-12]C:R[-1]C)"
Range("K15").Select
ActiveCell.FormulaR1C1 = "=SUM(R[-12]C:R[-1]C)"
End Sub
</code>```

答:
You could do it with formulas as well. In the G3 cell type:

```<code>=LARGE(C$3:C$200, ROW()-2)
</code>```

for finding the top country. In F3 and E3 insert:

```<code>=INDEX(B$3:B$200, MATCH(G3,C$3:C$200,0))
</code>```

and

```<code>=INDEX(A$3:A$200, MATCH(G3,C$3:C$200,0))
</code>```

respectively. Then drag then down to 12th row. You have top 10 now. In the cell K3 type:

```<code>=IFERROR(LARGE(C$3:C$200, ROW()+8),"")
</code>```

and in J3 and I3:

```<code>=IFERROR(INDEX(B$3:B$200, MATCH(K3,C$3:C$200,0)),"")
</code>```

and

```<code>=IFERROR(INDEX(A$3:A$200, MATCH(K3,C$3:C$200,0)),"")
</code>```

Then drag then down several screens. There is less than 200 countries and territories on the world, so it should be enough. If there is no macros, you don'tneed the button, everything will update on fly.

Body:
I would like to select the top 10 Values from Main table and paste in different range (E3) and REMAINING all values and PASTE and SUM in another range(I3)
I used the code below. It is working for Top 10 values, BUT for remaining,
when i am adding one more row in Main table, it is not working. Help me.

Private Sub CommandButton1_Click()

'Calculation for Top 10 Countries
Sheets("Sheet1").Range("C" & Rows.Count).End(xlUp).Offset(-9, -2).Resize(10, 3).Copy Sheets("Sheet1").Range("E3")

'Calculation for Remaining Countries
Range("A3:C14").Copy Range("I3")
Range("I15").Select
ActiveCell.FormulaR1C1 = "Remaining"
Range("J15").Select
ActiveCell.FormulaR1C1 = "=SUM(R[-12]C:R[-1]C)"
Range("K15").Select
ActiveCell.FormulaR1C1 = "=SUM(R[-12]C:R[-1]C)"
End Sub

Body:
You could do it with formulas as well. In the G3 cell type:

=LARGE(C$3:C$200, ROW()-2)

for finding the top country. In F3 and E3 insert:

=INDEX(B$3:B$200, MATCH(G3,C$3:C$200,0))

and

=INDEX(A$3:A$200, MATCH(G3,C$3:C$200,0))

respectively. Then drag then down to 12th row. You have top 10 now. In the cell K3 type:

=IFERROR(LARGE(C$3:C$200, ROW()+8),"")

and in J3 and I3:

=IFERROR(INDEX(B$3:B$200, MATCH(K3,C$3:C$200,0)),"")

and

=IFERROR(INDEX(A$3:A$200, MATCH(K3,C$3:C$200,0)),"")

Then drag then down several screens. There is less than 200 countries and territories on the world, so it should be enough. If there is no macros, you don'tneed the button, everything will update on fly.


问:
Sort string without any builtin methods
I want to sort a string in javascript without using a built in method, just by using for's and comparisons like 'a' > 'b';

Something that doesn't work:

function replaceAt(str, i, char) {
    return str.substr(0,i) + char + str.substr(i + 1)
}

function swap(str, i1, i2) {
    return replaceAt(replaceAt(str, i1, str[i2]),i2,str[i1]);
}

function sort(str) {
    var sorted = str;
    for (var i = 0; i < str.length; i++) {
        if (str[i] > str[i + 1]) {
            str = swap(str, i, i+1)
        }
    }
    return str;
}```

Pseudo-code or books, courses recommendations on programming are welcome!

答:
```<code><!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
array=[4, 10, 2, 9, 6, 3, 13, 5];
function arrayOperations()
{
    var count = array.length - 1,
        temp,
        j,
        i;

    for (j = 0; j < count; j++)
    {

        for (i = 0; i < count; i++)
        {

            if (array[i] > array[i + 1])
            {
                temp = array[i + 1];
                array[i + 1] = array[i];
                array[i] = temp;
            }

        }
    }
document.write("ascending order is <br>")
for(k=0;k<=array.length-1;k++){
    document.write(array[k]+ "<br>");
    }

document.write("descending order is <br>")
for(k=array.length-1;k>=0;k--){

        document.write(array[k]+ "<br>");
    }
document.write("biggest number is <br>")
for(k=array.length-1;k>=0;k--){

        if((array[k])>array[k-1]){
        document.write(array[k]+"<br>")
        break;
        }
    }
document.write("smallest number is <br>")
for(k=0;k<=array.length;k++){

        if((array[k])<array[k+1]){
        document.write(array[k]+"<br>")
        break;
        }
    }

    }

</script>
  <title></title>
</head>
<body>
array=[4, 10, 2, 9, 6, 3, 13, 5]
<br>
<input type="button" onclick="arrayOperations()" value="find">
</body>
</html>
</code>```

Title: Sort string without any builtin methods

Body:
I want to sort a string in javascript without using a built in method, just by using for's and comparisons like 'a' > 'b';

Something that doesn't work:

function replaceAt(str, i, char) {
    return str.substr(0,i) + char + str.substr(i + 1)
}

function swap(str, i1, i2) {
    return replaceAt(replaceAt(str, i1, str[i2]),i2,str[i1]);
}

function sort(str) {
    var sorted = str;
    for (var i = 0; i < str.length; i++) {
        if (str[i] > str[i + 1]) {
            str = swap(str, i, i+1)
        }
    }
    return str;
}

Pseudo-code or books, courses recommendations on programming are welcome!


问:
Getting Current Location instead of Cache ios
I have searched a lot and didn't get any satisfactory answer, I have a scenario where I am showing a list of sellers based on user's current location. I am getting a location for the first time and when I run my App afterward whenever I try to get the location I am getting a cache location data. I did try after some time even after every 24 hours but still getting the cache location where my current location is changed as well. Following is the code I am using for reference. please advise.

Property defined in Header file

```<code>@property (nonatomic,retain) CLLocationManager *locationManager;

- (void)startSingleLocationRequest
{
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.distanceFilter = kCLDistanceFilterNone;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;

    [self.locationManager startUpdatingLocation];
    [self.locationManager requestWhenInUseAuthorization];

}

#pragma mark --didUpdateLocations
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{

    self.latitudeValue =  locations.lastObject.coordinate.latitude;
    self.longitudeValue =  locations.lastObject.coordinate.longitude;
// location set for simulation to UK
    if(self.latitudeValue != 51.509979 && self.longitudeValue != -0.133700){
         [MBProgressHUD hideHUDForView:self.outletSearchNearBy animated:YES];
           [self.locationManager stopUpdatingLocation];
        abc *slv =[self.storyboard instantiateViewControllerWithIdentifier:@"abc"];
        slv.receivedLatitudeValue = self.latitudeValue;
        slv.receivedLongitudeValue = self.longitudeValue;

        [self.navigationController pushViewController:slv animated:YES];
    }
    else{}

}
</code>```

答:
Can you try like this

```<code>self.locationManager.pausesLocationUpdatesAutomatically = NO;
</code>```

Because it

Specifies that location updates may automatically be paused when possible.

By default, this is YES for applications linked against iOS 6.0 or later.

On the other hand, kCLLocationAccuracyBestForNavigation uses top speed GPS. So better to use this instead of kCLLocationAccuracyNearestTenMeters.

Body:
I have searched a lot and didn't get any satisfactory answer, I have a scenario where I am showing a list of sellers based on user's current location. I am getting a location for the first time and when I run my App afterward whenever I try to get the location I am getting a cache location data. I did try after some time even after every 24 hours but still getting the cache location where my current location is changed as well. Following is the code I am using for reference. please advise.

Property defined in Header file

@property (nonatomic,retain) CLLocationManager *locationManager;

- (void)startSingleLocationRequest
{
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.distanceFilter = kCLDistanceFilterNone;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;

    [self.locationManager startUpdatingLocation];
    [self.locationManager requestWhenInUseAuthorization];

}

#pragma mark --didUpdateLocations
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{

    self.latitudeValue =  locations.lastObject.coordinate.latitude;
    self.longitudeValue =  locations.lastObject.coordinate.longitude;
// location set for simulation to UK
    if(self.latitudeValue != 51.509979 && self.longitudeValue != -0.133700){
         [MBProgressHUD hideHUDForView:self.outletSearchNearBy animated:YES];
           [self.locationManager stopUpdatingLocation];
        abc *slv =[self.storyboard instantiateViewControllerWithIdentifier:@"abc"];
        slv.receivedLatitudeValue = self.latitudeValue;
        slv.receivedLongitudeValue = self.longitudeValue;

        [self.navigationController pushViewController:slv animated:YES];
    }
    else{}

}

Body:
Can you try like this

self.locationManager.pausesLocationUpdatesAutomatically = NO;

Because it

Specifies that location updates may automatically be paused when possible.

By default, this is YES for applications linked against iOS 6.0 or later.

On the other hand, kCLLocationAccuracyBestForNavigation uses top speed GPS. So better to use this instead of kCLLocationAccuracyNearestTenMeters.


问:
Tkinter Scrollbar
If I call text_area.pack() before scrollbar.pack() (i.e switch them), the scrollbar doesn't show. Why is that? If I am going to create a larger program, I would have absolutely no chance to find out where the problem is.

```<code>from tkinter import *
import tkinter.filedialog

root = Tk()
root.geometry("200x100")
frame = Frame(root,width=150, height=90)
frame.pack()
scrollbar = Scrollbar(frame)
text_area = Text(frame, width=200, height=50,yscrollcommand=scrollbar.set)
scrollbar.config(command=text_area.yview)
scrollbar.pack(side="right", fill="y")
text_area.pack()
root.mainloop()
</code>```

答:
When you switch them, scrollbar.pack() simply is unaware that it needs to go top, instead it goes next place from top to bottom, and right. You can see that when you expand window size.

You can resolve the issue by replacing:

```<code>text_area.pack()
</code>```

with:

```<code>text_area.pack(side="left")
</code>```

When you want to design more complex geometry structures I'd suggest you use grid instead of pack.

Title: Tkinter Scrollbar

Body:
If I call text_area.pack() before scrollbar.pack() (i.e switch them), the scrollbar doesn't show. Why is that? If I am going to create a larger program, I would have absolutely no chance to find out where the problem is.

from tkinter import *
import tkinter.filedialog

root = Tk()
root.geometry("200x100")
frame = Frame(root,width=150, height=90)
frame.pack()
scrollbar = Scrollbar(frame)
text_area = Text(frame, width=200, height=50,yscrollcommand=scrollbar.set)
scrollbar.config(command=text_area.yview)
scrollbar.pack(side="right", fill="y")
text_area.pack()
root.mainloop()

Body:
When you switch them, scrollbar.pack() simply is unaware that it needs to go top, instead it goes next place from top to bottom, and right. You can see that when you expand window size.

You can resolve the issue by replacing:

text_area.pack()

with:

text_area.pack(side="left")

When you want to design more complex geometry structures I'd suggest you use grid instead of pack.


问:
php get google place details from business name
I want to pull business data from google places ip. I can do that by using place_id with the code below;

```<code>$name = urlencode('Business name');
$place_id = 'XXXXXXXXXXXXXXXX';
$url = 'https://maps.googleapis.com/maps/api/place/details/json?placeid='.$place_id.'&key=XXXXXXXXXXXXXXXXX';
$json = file_get_contents($url);
$jsonContent = json_decode($json, TRUE);

$jsonContent['result']['name'];
$jsonContent['result']['formatted_phone_number'];
$jsonContent['result']['formatted_address'];
$jsonContent['result']['website'];
$jsonContent['result']['place_id'];
</code>```

What I want to be able to do is the get business data using business name or get place_id by using business name so i can use the code above to pull the data. Obtaining the the place id with business name is possible on the following link;

Google place ID finder

Can anyone help with how i can obtain either business data using business name or obtain place id using business name?

答:
If your businesses have unique names, you can use web API for that.

```<code>$url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&radius=5000&name=BestBusiness&key=YOUR_API_KEY';
$json = file_get_contents($url);
$data = json_decode($json);
</code>```

Get id out of $data and enjoy it.

Body:
I want to pull business data from google places ip. I can do that by using place_id with the code below;

$name = urlencode('Business name');
$place_id = 'XXXXXXXXXXXXXXXX';
$url = 'https://maps.googleapis.com/maps/api/place/details/json?placeid='.$place_id.'&key=XXXXXXXXXXXXXXXXX';
$json = file_get_contents($url);
$jsonContent = json_decode($json, TRUE);

$jsonContent['result']['name'];
$jsonContent['result']['formatted_phone_number'];
$jsonContent['result']['formatted_address'];
$jsonContent['result']['website'];
$jsonContent['result']['place_id'];

What I want to be able to do is the get business data using business name or get place_id by using business name so i can use the code above to pull the data. Obtaining the the place id with business name is possible on the following link;

Google place ID finder

Can anyone help with how i can obtain either business data using business name or obtain place id using business name?

Body:
If your businesses have unique names, you can use web API for that.

$url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&radius=5000&name=BestBusiness&key=YOUR_API_KEY';
$json = file_get_contents($url);
$data = json_decode($json);

Get id out of $data and enjoy it.


问:
Count vector elements in range when condition is met
I have a vector of numbers:

```<code>x <- c(0, 0, 0, 30, 60, 0, 0, 0, 0, 0, 10, 0, 0, 15, 45, 0, 0)
</code>```

For each element i in x, I would like to do the following

If x[i] > 0, return 0

If all 4 elements before x[i] are 0, return NA

If the 4 elements before x[i] are not 0, count how many elements are between the last not-0 element and x[i]

I expect this output:

```<code>#> x
#[1]  0  0  0 30 60  0  0  0  0  0 10  0  0 15 45  0  0
#> x_out
#[1] NA NA NA  0  0  1  2  3  4 NA  0  1  2  0  0  1  2
</code>```

Notice that the solution should also work when there are less than 4 elements available at the beginning of the vector (i.e. condition 2 and 3 should use as many elements as are available). Does anybody have a solution for this? A vectorised approach is preferred because the vectors are long and the dataset is fairly big.

答:
This is my current approach:

```<code>library(dplyr)
last_x_months <- 4
my_list       <- vector("list", 1 + last_x_months)
my_list[[1]]  <- x

# create lagged variants of vector
for (j in seq_along(1:last_x_months)) {
  my_list[[1 + j]] <- lag(my_list[[1]], n = j, default = NA)
}

# row bind it to a data.frame
i_dat <- do.call(rbind, my_list) %>%
  as.data.frame()

# apply function to each column in dataframe
sapply(i_dat, function(x) {
  if (sum(x, na.rm = TRUE) == 0) {
    NA
  } else if (x[1] > 0) {
    0
  } else {
    rle(x)$lengths[1]
  }
})
</code>```

This is the output I get:

```<code>#> output
#[1] NA  NA  NA   0   0   1   2   3   4  NA   0   1   2   0   0   1   2
</code>```

Is this good practice or could I improve performance with a shortcut? I am pretty inexperienced when it comes to performance optimisation, that's why I posed the question.

Body:
I have a vector of numbers:

x <- c(0, 0, 0, 30, 60, 0, 0, 0, 0, 0, 10, 0, 0, 15, 45, 0, 0)

For each element i in x, I would like to do the following

If x[i] > 0, return 0

If all 4 elements before x[i] are 0, return NA

If the 4 elements before x[i] are not 0, count how many elements are between the last not-0 element and x[i]

I expect this output:

#> x
#[1]  0  0  0 30 60  0  0  0  0  0 10  0  0 15 45  0  0
#> x_out
#[1] NA NA NA  0  0  1  2  3  4 NA  0  1  2  0  0  1  2

Notice that the solution should also work when there are less than 4 elements available at the beginning of the vector (i.e. condition 2 and 3 should use as many elements as are available). Does anybody have a solution for this? A vectorised approach is preferred because the vectors are long and the dataset is fairly big.

Body:
This is my current approach:

library(dplyr)
last_x_months <- 4
my_list       <- vector("list", 1 + last_x_months)
my_list[[1]]  <- x

# create lagged variants of vector
for (j in seq_along(1:last_x_months)) {
  my_list[[1 + j]] <- lag(my_list[[1]], n = j, default = NA)
}

# row bind it to a data.frame
i_dat <- do.call(rbind, my_list) %>%
  as.data.frame()

# apply function to each column in dataframe
sapply(i_dat, function(x) {
  if (sum(x, na.rm = TRUE) == 0) {
    NA
  } else if (x[1] > 0) {
    0
  } else {
    rle(x)$lengths[1]
  }
})

This is the output I get:

#> output
#[1] NA  NA  NA   0   0   1   2   3   4  NA   0   1   2   0   0   1   2

Is this good practice or could I improve performance with a shortcut? I am pretty inexperienced when it comes to performance optimisation, that's why I posed the question.


问:
What could possibly cause JQuery's selector to break?
I am trying to get an element using JQuery's selector, but it does not find it even though the element actually exists. Moreover, I can actually find the element using getElementById.

For example:

$('#outputDiv') gives me a null value. But document.getElementById("outputDiv") returns me the Div I was trying to access.

Any idea?

答: Check that jQuery is actually loaded. Have you tested with Firebug or another debugger? Are javascript errors reported? Do you use another library that uses $ as an alias?</p>

OwnerDisplayName: Marcel Tjandraatmadja

LastEditorDisplayName: Marcel Tjandraatmadja

OwnerDisplayName: kgiannakakis


问:
Apache http/https non-www to ww url redirection
I've got a problem with apache configuration (linux distro).
I want to redirect typed URLs (in browser):

domain.com

www.domain.com

http://domain.com

http://www.domain.com

https://domain.com

to only one: https://www.domain.com
What should I do in .htaccess file?
Notice that I've got only one certificate. Exactly for www.domain.com

Thank you in advance for any help! :)

答:
This rule should do it:

```<code>RewriteCond %{HTTP_HOST} !^www\.
RewriteCond %{HTTP_HOST} (.+) [OR]
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^www\.(.+)
RewriteRule ^ https://www.%1%{REQUEST_URI} [L,R=301]
</code>```

The four conditions are two groups of disjunct conditions where the first condition of each group tests for a missing www. and the non-HTTPS respectively. Each second condition of the groups are just to get the part of the HTTP host without the leading www..

Body:
This rule should do it:

RewriteCond %{HTTP_HOST} !^www\.
RewriteCond %{HTTP_HOST} (.+) [OR]
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^www\.(.+)
RewriteRule ^ https://www.%1%{REQUEST_URI} [L,R=301]

The four conditions are two groups of disjunct conditions where the first condition of each group tests for a missing www. and the non-HTTPS respectively. Each second condition of the groups are just to get the part of the HTTP host without the leading www..


问:
implementing a callback in android with Activities
I am developing an library for Android and have following scenario, I want a response back to MainActivity. How could I do it? I have tried with callbacks but could not as I could not create an object of Activity class by myself. is there any other way to achieve it? in AsyncTaskListener implementation I am doing some network operation. I could not use startActivityForResult as it's not according to my library specification.</p>

```<code>public class MainActivity extends AppCompatActivity implements MyReceiver{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    MyServiceImpl b = new MyServiceImpl();
    String request = "123";
    b.request(this,request);
    }

    @Override
    public void completed(String result) {
        Log.d("MainActivity","Result - "+result);
    }
}

public class MyServiceImpl{

   public void request(Activity appActivity,String req){
        Intent intent = new Intent(appActivity, ActivityB.class);
        appActivity.startActivity(intent);
   }
}

public class ActivityB extends AppCompatActivity imnplements AsyncTaskListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // shows UI
        // network operations
    }

   @Override
   public void taskFinish(String response) {
     //  my result comes here
     //  now  i want this result to propagated to MainActiviy
   }
}
</code>```

答:
I would do it like this :

Create an interface :

```<code>public interface MyReceiver {
  public void onReceive();
}
</code>```

In you activity :

```<code>public class MyActivity implements MyReceiver{

public static MyReceiver myReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.activity_new_booking);
    super.onCreate(savedInstanceState);
    myReceiver = this;
    }

    @Override
    protected void onDestroy() {
        myReceiver = null;
    }

    @Override
    public void onReceive(){
       //Implement your code here or send objects in the parameters
    }

}
</code>```

To Call it just use this:

```<code>if(MyActivity.myReceiver!=null){
  MyActivity.myReceiver.onReceive();
}
</code>```

No need to create activity instances.

In this case i would also suggest you to use startActivityForResult.

Hope this helps.

Body:
I am developing an library for Android and have following scenario, I want a response back to MainActivity. How could I do it? I have tried with callbacks but could not as I could not create an object of Activity class by myself. is there any other way to achieve it? in AsyncTaskListener implementation I am doing some network operation. I could not use startActivityForResult as it's not according to my library specification.

public class MainActivity extends AppCompatActivity implements MyReceiver{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    MyServiceImpl b = new MyServiceImpl();
    String request = "123";
    b.request(this,request);
    }

    @Override
    public void completed(String result) {
        Log.d("MainActivity","Result - "+result);
    }
}

public class MyServiceImpl{

   public void request(Activity appActivity,String req){
        Intent intent = new Intent(appActivity, ActivityB.class);
        appActivity.startActivity(intent);
   }
}

public class ActivityB extends AppCompatActivity imnplements AsyncTaskListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // shows UI
        // network operations
    }

   @Override
   public void taskFinish(String response) {
     //  my result comes here
     //  now  i want this result to propagated to MainActiviy
   }
}

Body:
I would do it like this :

Create an interface :

public interface MyReceiver {
  public void onReceive();
}

In you activity :

public class MyActivity implements MyReceiver{

public static MyReceiver myReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.activity_new_booking);
    super.onCreate(savedInstanceState);
    myReceiver = this;
    }

    @Override
    protected void onDestroy() {
        myReceiver = null;
    }

    @Override
    public void onReceive(){
       //Implement your code here or send objects in the parameters
    }

}

To Call it just use this:

if(MyActivity.myReceiver!=null){
  MyActivity.myReceiver.onReceive();
}

No need to create activity instances.

In this case i would also suggest you to use startActivityForResult.

Hope this helps.

ContentLicense: CC BY-SA 4.0


问:
Beginner JS calculator
I am new into the world of JS, and I'm trying to build a basic calculator.
Everything work fine so long but I have problem displaying different elements on the result screen of the calculator.

When I click 1 then 2, 1 will disappear but I want it to stay for my calculation.

Please help!!

var displayText = document.getElementById('displayText');
var output = document.getElementById('output');
function add(){
  var two, plus, result;
  result = displayText.value;
  output.innerHTML = result;
}
function addOne() {
  var one = document.getElementById('one').value = 1;
      displayText.value = one;
}
function addTwo() {
  var two = document.getElementById('two').value = 2;
      displayText.value = two;
}
function addPlus() {
  var plus = document.getElementById('plus').value = "+";
      displayText.value = plus;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div>
  <div class="display">
    <input type="text" id="displayText" name="" value="">
    <p>The result of your calculation is: <span id="output"></span></p>
  </div>
  <div class="btn_wrap">
    <button id="one" onclick="addOne()">1</button>
    <button id="two" onclick="addTwo()">2</button>
    <button id="plus" onclick="addPlus()">+</button>
    <button id="" onclick="add()">Add</button>
  </div>
</div>
      </code>```

答:
Instead of =, you just need to use +=. = will reset the value whereas += will append/concatenate the values. And you can use eval() to get the sum (in this case) of entered expression.

Below is the updated snippet for you:

var displayText = document.getElementById('displayText');
var output = document.getElementById('output');

function add() {
  var two, plus, result;
  result = displayText.value;
  output.innerHTML = eval(result);
}

function addOne() {
  var one = document.getElementById('one').innerText;
  displayText.value += one;
}

function addTwo() {
  var two = document.getElementById('two').innerText ;
  displayText.value += two;
}

function addPlus() {
  var plus = document.getElementById('plus').innerText ;
  displayText.value += plus;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <div class="display">
    <input type="text" id="displayText" name="" value="">
    <p>The result of your calculation is: <span id="output"></span></p>
  </div>
  <div class="btn_wrap">
    <button id="one" onclick="addOne()">1</button>
    <button id="two" onclick="addTwo()">2</button>
    <button id="plus" onclick="addPlus()">+</button>
    <button id="" onclick="add()">Add</button>
  </div>
</div></code>```

Title: Beginner JS calculator

Body:
I am new into the world of JS, and I'm trying to build a basic calculator.
Everything work fine so long but I have problem displaying different elements on the result screen of the calculator.

When I click 1 then 2, 1 will disappear but I want it to stay for my calculation.

Please help!!

var displayText = document.getElementById('displayText');
var output = document.getElementById('output');
function add(){
  var two, plus, result;
  result = displayText.value;
  output.innerHTML = result;
}
function addOne() {
  var one = document.getElementById('one').value = 1;
      displayText.value = one;
}
function addTwo() {
  var two = document.getElementById('two').value = 2;
      displayText.value = two;
}
function addPlus() {
  var plus = document.getElementById('plus').value = "+";
      displayText.value = plus;
}

    <input type="text" id="displayText" name="" value="">

The result of your calculation is:

    <button id="one" onclick="addOne()">1</button>
    <button id="two" onclick="addTwo()">2</button>
    <button id="plus" onclick="addPlus()">+</button>
    <button id="" onclick="add()">Add</button>

Body:
Instead of =, you just need to use +=. = will reset the value whereas += will append/concatenate the values. And you can use eval() to get the sum (in this case) of entered expression.

Below is the updated snippet for you:

var displayText = document.getElementById('displayText');
var output = document.getElementById('output');

function add() {
  var two, plus, result;
  result = displayText.value;
  output.innerHTML = eval(result);
}

function addOne() {
  var one = document.getElementById('one').innerText;
  displayText.value += one;
}

function addTwo() {
  var two = document.getElementById('two').innerText ;
  displayText.value += two;
}

function addPlus() {
  var plus = document.getElementById('plus').innerText ;
  displayText.value += plus;
}

<div>
  <div class="display">
    <input type="text" id="displayText" name="" value="">
    <p>The result of your calculation is: <span id="output"></span></p>
  </div>
  <div class="btn_wrap">
    <button id="one" onclick="addOne()">1</button>
    <button id="two" onclick="addTwo()">2</button>
    <button id="plus" onclick="addPlus()">+</button>
    <button id="" onclick="add()">Add</button>
  </div>
</div>


问:
Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
Whenever I try to run makemigrations or runserver, I get this error:

```<code>RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and
isn't in an application in `INSTALLED_APPS`.
</code>```

HOWEVER:
Here it is in INSTALLED_APPS--

```<code>WSGI_APPLICATION = 'mysite.wsgi.application'
import django
django.setup()

# Application definition

INSTALLED_APPS = [
                    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',

    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_comments',
    'django_comments_xtd',
    'django.contrib.sites',
    'accounts.apps.AccountsConfig',
    'posts.apps.PostsConfig',

    'category',
    #'vote',
    'tinymce',
    'django_wysiwyg',
    'follow',

    'djrichtextfield',
    'ckeditor',
    #'likes',
    'secretballot',

    'hitcount',
    #'pinax',
    'pinax.likes',

    #'pinax',
    #'pinax_theme_bootstrap',
    #'bootstrapform',

    #'voting',
    'actstream',

]
</code>```

What could be causing this? It's explicitly stated in Installed_Apps, as you can see.

答: I got it working by downgrading Django to 1.8. There is some problem with 1.9 I guess!</p>

Body:
Whenever I try to run makemigrations or runserver, I get this error:

RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and
isn't in an application in `INSTALLED_APPS`.

HOWEVER:
Here it is in INSTALLED_APPS--

WSGI_APPLICATION = 'mysite.wsgi.application'
import django
django.setup()

# Application definition

INSTALLED_APPS = [
                    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',

    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_comments',
    'django_comments_xtd',
    'django.contrib.sites',
    'accounts.apps.AccountsConfig',
    'posts.apps.PostsConfig',

    'category',
    #'vote',
    'tinymce',
    'django_wysiwyg',
    'follow',

    'djrichtextfield',
    'ckeditor',
    #'likes',
    'secretballot',

    'hitcount',
    #'pinax',
    'pinax.likes',

    #'pinax',
    #'pinax_theme_bootstrap',
    #'bootstrapform',

    #'voting',
    'actstream',

]

What could be causing this? It's explicitly stated in Installed_Apps, as you can see.


问:
D3.js - plotting images with nested array in json
I am a newbie in d3, the following is my input json file,

```<code>    {

"y_axis_list":["A","B","C","D","E","F","G"],

"Points":[
{
    "y": "A",
    "x": 10,
    "Persona":["link1"]
},
{
    "y" : "B",
    "x": 20,
    "Persona":["link2","link1"]
},
{
    "y" : "C",
    "x": 30,
    "Persona":["link2","link3"]
},
{
    "y" : "D",
    "x": 40,
    "Persona":["link2","link3"]
},
{
    "y" : "E",
    "x" : 50,
    "Persona":["link5","link6"]
},
{
    "y" : "F",
    "x" : 60,
    "Persona":["link7","link8"]
},
{
    "y" : "G",
    "x" : 70,
    "Persona":["link9","link10"]
}
]
}
</code>```

the following is my code:

```<code><!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <title>D3 v4 - linechart</title>
    <style>
    #graph {
        width: 900px;
        height: 500px;
    }
    .tick line {
        stroke-dasharray: 2 2 ;
        stroke: #ccc;
    }

    .x{
        display: none;
    }

    .y path{
        fill: none;
      stroke: none;
 /* set the CSS */
    }

.line {
  fill: none;
  stroke: steelblue;
  stroke-width: 2px;
}

div.tooltip {
  position: absolute;
  text-align: center;
  width: 60px;
  height: 28px;
  padding: 2px;
  font: 12px sans-serif;
  background: lightsteelblue;
  border: 0px;
  border-radius: 8px;
  pointer-events: none;
}

    </style>
    </head>

    <body>
    <div id="graph"></div>

    <script src="https://d3js.org/d3.v4.min.js"></script>

    <script>
    !(function(){
        "use strict"

        var width,height
        var chartWidth, chartHeight
        var margin
        var svg = d3.select("#graph").append("svg")
        var axisLayer = svg.append("g").classed("axisLayer", true)
        var chartLayer = svg.append("g").classed("chartLayer", true)

        var xScale = d3.scaleLinear()
        var yScale = d3.scalePoint()
        var align = 0
        var i=10;

        //d3.tsv("data1.tsv", cast,  main)
        d3.json("http://localhost/newest.json",cast)

        //データの方変換
        function cast(datafull) {
            console.log("got it");
            var data=datafull["Points"];enter code here

            data.forEach(function(data) {
            console.log(data.y);
            data.y = data.y;
            data.x = +data.x;
        });
            main(data,datafull);
        }

        function main(data,datafull) {
            console.log("in main");
            setSize(data,datafull)
            drawAxis()
            drawChart(data,datafull)
        }

        function setSize(data,datafull) {
            width = document.querySelector("#graph").clientWidth
            height = document.querySelector("#graph").clientHeight

            margin = {top:40, left:100, bottom:40, right:0 }

            chartWidth = width - (margin.left+margin.right+8)
            chartHeight = height - (margin.top+margin.bottom)

            svg.attr("width", width).attr("height", height)

            axisLayer.attr("width", width).attr("height", height)

            chartLayer
                .attr("width", chartWidth)
                .attr("height", chartHeight)
                .attr("transform", "translate("+[margin.left, margin.top]+")")

            xScale.domain([0, d3.max(data, function(d) { return d.x; })]).range([0,chartWidth])
            yScale.domain(datafull["y_axis_list"]).range([chartHeight, 0]).align(1)

        }

        function drawChart(data,datafull) {

        console.log("in drawChart");
            var t = d3.transition()
                .duration(4000)
                .ease(d3.easeLinear)
                .on("start", function(d){ console.log("transiton start") })
                .on("end", function(d){ console.log("transiton end") });

           //   var tooltip = d3.tip().attr('class', 'd3-tip').html(function(d) { return 10; });

           var div = d3.select("body").append("div")
                .attr("class", "tooltip")
                .style("opacity", 0);

            var lineGen = d3.line()
                .x(function(d) { i=i+50;console.log(i); return xScale(d.x); })
                .y(function(d) { return yScale(d.y)  })
                .curve(d3.curveStepAfter)

            var line = chartLayer.selectAll(".line")
                .data([data])

            line.enter().append("path").classed("line", true)
                .merge(line)
                .attr("d", lineGen)
                .attr("fill", "none")
                .attr("stroke", "blue")
                .attr("stroke-width","2px")
                .attr("stroke-dasharray", function(d){ return this.getTotalLength() })
                .attr("stroke-dashoffset", function(d){ return this.getTotalLength() })

            chartLayer.selectAll(".line").transition(t)
                .attr("stroke-dashoffset", 0)

        var img = chartLayer.selectAll('image')
        .data(data)
        .enter()
        .append('image')
        .attr("class","logo")
        .attr("xlink:href", "http://localhost/whatsapp-logo.jpg" )
        .attr("x", function(d,i){ return xScale(d.x+5/2) })
        .attr("y", function(d,i){ return yScale(d.y) })
        .attr("width", 16)
        .attr("height", 16)
        .style("opacity",0);

        img.transition().delay(4000).duration(500).ease(d3.easeLinear).style("opacity",1);

        img.on("mouseover", function(d) {
            div.transition()
         .duration(200)
         .style("opacity", .9);
       div.html("Persona people" + "<br/>" + d.x)
         .style("left", (d3.event.pageX) + "px")
         .style("top", (d3.event.pageY - 28) + "px");
       })
     .on("mouseout", function(d) {
       div.transition()
         .duration(500)
         .style("opacity", 0);
       });

        chartLayer.selectAll("circle").classed("circle",true)
        .data(data)
        .enter().append("circle")
        .attr("class", "circle")
        .attr("fill","none")
        .attr("stroke","black")
        .attr("cx", function(d) { return xScale(d.x); })
        .attr("cy", function(d) { return yScale(d.y); })
        .attr("r", 4)

        }

        function drawAxis(){
            var yAxis = d3.axisLeft(yScale)
                .tickSizeInner(-chartWidth)

            axisLayer.append("g")
                .attr("transform", "translate("+[margin.left, margin.top]+")")
                .attr("class", "axis y")
                .call(yAxis);

            var xAxis = d3.axisBottom(xScale)

            axisLayer.append("g")
                .attr("class", "axis x")
                .attr("transform", "translate("+[margin.left, chartHeight+margin.top]+")")
                .call(xAxis);

        }

        function update(){

        }

    }());
    </script>
    </body>
    </html>
</code>```

I want the images given in the persona list to appear in the same line as that of the y coordinate in the json with x-axis changing minutely. The links are the links to images which are to be loaded.

I went through a lot of questions, but I was not able to figure out the method to do that.

My current output is given below.

Now there is one image in each line, I want the number of images in persona list (input json) to appear in each of the corresponding lines.

答:
Rewrite your img variable this way (pay attention to the comments):

```<code>var img = chartLayer
  .selectAll('g')
  .data(data)
  .enter()
  .append('g') // append g element, here we will be append image as child
  .attr("transform", function(d, i) {
    var x = xScale(d.x + 5 / 2);
    var y = yScale(d.y);
    return 'translate(' + x + ', ' + y + ')'
  })
  .selectAll('image')
  .data(function(d) { // here we format data as we need
    return d.Persona.map(function(icon, index) {
        return {
        icon: icon,
        tooltipText: d.Text[index] // set tooltip text
      }
    })
  })
  .enter()
  .append('image') // append image element
  .attr("class", "logo")
  .attr("xlink:href", function(d) { // set appropriate href attribute
    return d.icon;
  })
  .attr("x", function(d, i) { // move image by index
    return 20 * i;
  })
  .attr("width", 16)
  .attr("height", 16)
  .style("opacity", 0);

...
img.on("mouseover", function(d) {
  div.transition()
  .duration(200)
  .style("opacity", .9);

  div.html("Persona people" + "<br/>" + d.tooltipText) // get tooltip text
  .style("left", (d3.event.pageX) + "px")
  .style("top", (d3.event.pageY - 28) + "px");
})
...
</code>```

Look at the working example - https://jsfiddle.net/levsha/og92k0gv/

Body:
I am a newbie in d3, the following is my input json file,

    {

"y_axis_list":["A","B","C","D","E","F","G"],

"Points":[
{
    "y": "A",
    "x": 10,
    "Persona":["link1"]
},
{
    "y" : "B",
    "x": 20,
    "Persona":["link2","link1"]
},
{
    "y" : "C",
    "x": 30,
    "Persona":["link2","link3"]
},
{
    "y" : "D",
    "x": 40,
    "Persona":["link2","link3"]
},
{
    "y" : "E",
    "x" : 50,
    "Persona":["link5","link6"]
},
{
    "y" : "F",
    "x" : 60,
    "Persona":["link7","link8"]
},
{
    "y" : "G",
    "x" : 70,
    "Persona":["link9","link10"]
}
]
}

the following is my code:

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <title>D3 v4 - linechart</title>

I want the images given in the persona list to appear in the same line as that of the y coordinate in the json with x-axis changing minutely. The links are the links to images which are to be loaded.

I went through a lot of questions, but I was not able to figure out the method to do that.

My current output is given below.

Now there is one image in each line, I want the number of images in persona list (input json) to appear in each of the corresponding lines.

Body:
Rewrite your img variable this way (pay attention to the comments):

var img = chartLayer
  .selectAll('g')
  .data(data)
  .enter()
  .append('g') // append g element, here we will be append image as child
  .attr("transform", function(d, i) {
    var x = xScale(d.x + 5 / 2);
    var y = yScale(d.y);
    return 'translate(' + x + ', ' + y + ')'
  })
  .selectAll('image')
  .data(function(d) { // here we format data as we need
    return d.Persona.map(function(icon, index) {
        return {
        icon: icon,
        tooltipText: d.Text[index] // set tooltip text
      }
    })
  })
  .enter()
  .append('image') // append image element
  .attr("class", "logo")
  .attr("xlink:href", function(d) { // set appropriate href attribute
    return d.icon;
  })
  .attr("x", function(d, i) { // move image by index
    return 20 * i;
  })
  .attr("width", 16)
  .attr("height", 16)
  .style("opacity", 0);

...
img.on("mouseover", function(d) {
  div.transition()
  .duration(200)
  .style("opacity", .9);

  div.html("Persona people" + "<br/>" + d.tooltipText) // get tooltip text
  .style("left", (d3.event.pageX) + "px")
  .style("top", (d3.event.pageY - 28) + "px");
})
...

Look at the working example - https://jsfiddle.net/levsha/og92k0gv/


问:
Initialize Constant Using ng-init Variables in AngularJs
I am working with AngularJs and I am initializing a variable in the ng-init of that model.

```<code><body ng-init="allowedState=2" ng-controller="amCtrl">
</body>
</code>```

Now what I want is to declare a constant using this variable which will then be shared within the app.

```<code>angular.module('amModule').constant('temp', ?)
</code>```

I am trying to figure this out and I am now wondering if it's even possible?

答:
Using ng-init;

```<code>ng-init="loader(); firstName = 'John'"
</code>```

It's better not to use the ng-init instead use below methods;

You can constants or values for initializing variables;
Official angular doc link

Example:
With Constant:

```<code>var app = angular.module('myApp', []);
app.constant('appName', 'Application Name');

app.controller('TestCtrl', ['appName', function TestCtrl(appName) {
    console.log(appName);
}]);
</code>```

With Values:

```<code>var app = angular.module('myApp', []);

app.value('usersOnline', 0);
app.controller('TestCtrl', ['usersOnline', function TestCtrl(usersOnline) {
    console.log(usersOnline);
    usersOnline = 15;
    console.log(usersOnline);
}]);
</code>```

Also, using service is good solution;
Using rootScope and service method

Thanks,

Body:
I am working with AngularJs and I am initializing a variable in the ng-init of that model.

Now what I want is to declare a constant using this variable which will then be shared within the app.

angular.module('amModule').constant('temp', ?)

I am trying to figure this out and I am now wondering if it's even possible?

Body:
Using ng-init;

ng-init="loader(); firstName = 'John'"

It's better not to use the ng-init instead use below methods;

You can constants or values for initializing variables;
Official angular doc link

Example:
With Constant:

var app = angular.module('myApp', []);
app.constant('appName', 'Application Name');

app.controller('TestCtrl', ['appName', function TestCtrl(appName) {
    console.log(appName);
}]);

With Values:

var app = angular.module('myApp', []);

app.value('usersOnline', 0);
app.controller('TestCtrl', ['usersOnline', function TestCtrl(usersOnline) {
    console.log(usersOnline);
    usersOnline = 15;
    console.log(usersOnline);
}]);

Also, using service is good solution;
Using rootScope and service method

Thanks,


问:
Text size in dp
So I'm totally lost now I have problems with Text size ruing my UI when user sets his font size through Accessibility -> Font size to Huge so for quick fix I decided to change all text sizes to dp instead of sp that text would always be same size but on some places textviews even when textsize is set to dp resizes any idea why??

Here is button with text size set to dp which maintains font size even after changing through accessibility

```<code>    <Button
        android:id="@+id/video_button"
        android:textSize="16dp"
        android:layout_marginTop="10dp"
        android:layout_height="30dp"
        android:layout_width="180dp"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/webshop_button"
        android:text="@string/button_3dvideo_text"/>
</code>```

And here is textView which ignores textSize even after setting it to dp:

```<code> <TextView
        android:id="@+id/about"
        android:gravity="center"
        android:textSize="16dp"
        android:layout_above="@+id/footer"
        android:layout_marginBottom="20dp"
        android:layout_centerHorizontal="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/color_white"
        android:text="@string/about"/>
</code>```

答:
May be try to use this Not sure whether its going to help you.</p>

```<code>DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
    float dp = 20f;
    float fpixels = metrics.density * dp;
    int pixels = (int) (fpixels + 0.5f);
    Edit_click.setTextSize(pixels);
</code>```

Title: Text size in dp

Body:
So I'm totally lost now I have problems with Text size ruing my UI when user sets his font size through Accessibility -> Font size to Huge so for quick fix I decided to change all text sizes to dp instead of sp that text would always be same size but on some places textviews even when textsize is set to dp resizes any idea why??

Here is button with text size set to dp which maintains font size even after changing through accessibility

    <Button
        android:id="@+id/video_button"
        android:textSize="16dp"
        android:layout_marginTop="10dp"
        android:layout_height="30dp"
        android:layout_width="180dp"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/webshop_button"
        android:text="@string/button_3dvideo_text"/>

And here is textView which ignores textSize even after setting it to dp:

 <TextView
        android:id="@+id/about"
        android:gravity="center"
        android:textSize="16dp"
        android:layout_above="@+id/footer"
        android:layout_marginBottom="20dp"
        android:layout_centerHorizontal="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/color_white"
        android:text="@string/about"/>

Body:
May be try to use this Not sure whether its going to help you.

DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
    float dp = 20f;
    float fpixels = metrics.density * dp;
    int pixels = (int) (fpixels + 0.5f);
    Edit_click.setTextSize(pixels);


问:
Java Beginner: How do I link one linked list to another?
If I have: linkedlist1= 1,2,3,4; and   linkedlist2= 5,6,7;

Am I able to attach linkedlist2 to the end of linkedlist1 in such a way if I invoke: linkedlist2.set(0,9999)  it changes to linkedlist2 = [999,6,7] and  linkedlist1 becomes [1,2,3,4,9999,7,8]; ?

Is that possible ? Or I do need another structure ?

The following code didn't work:

```<code> List<Double> l1 = new LinkedList<Double>(Arrays.asList(1.0,2.0));
 List<Double> l2 = new LinkedList<Double>(Arrays.asList(3.0,4.0));
 l1.addAll(l2);
 System.out.println(l1);
 l2.set(0, 9.0);
 System.out.println(l1);
</code>```

OUTPUT:

```<code> [1.0, 2.0, 3.0, 4.0]
 [1.0, 2.0, 3.0, 4.0]
</code>```

答:
The standard LinkedList classes provided with Java lack this capability.

As Donal Boyle posts you can add the contents of one list to another but this doesn't maintain the linkage as your describe.

Body:
If I have: linkedlist1= 1,2,3,4; and   linkedlist2= 5,6,7;

Am I able to attach linkedlist2 to the end of linkedlist1 in such a way if I invoke: linkedlist2.set(0,9999)  it changes to linkedlist2 = [999,6,7] and  linkedlist1 becomes [1,2,3,4,9999,7,8]; ?

Is that possible ? Or I do need another structure ?

The following code didn't work:

 List<Double> l1 = new LinkedList<Double>(Arrays.asList(1.0,2.0));
 List<Double> l2 = new LinkedList<Double>(Arrays.asList(3.0,4.0));
 l1.addAll(l2);
 System.out.println(l1);
 l2.set(0, 9.0);
 System.out.println(l1);

OUTPUT:

 [1.0, 2.0, 3.0, 4.0]
 [1.0, 2.0, 3.0, 4.0]


问:
print last line from the variable output in python
I am looking to get the last line produced from the line variable

```<code>bash-4.1$ cat file1_dup.py
#!/usr/bin/python
with open("file1.txt") as f:
  lines = f.readlines()
  for line in lines:
    if "!" in line:
      line = line.split()[-1].strip()
      print line
</code>```

output i am getting is as follows ..

```<code>-122.1058
-123.1050
-125.10584323
</code>```

The result i wanted to be printed out is

-125.10584323

Moreover, i got the hint from some goghling and getting the output
  desired but that seems bit complicated to me at the point ..

```<code>bash-4.1$ cat file2_dup.py
#!/usr/bin/python
def file_read_from_tail(fname,n):
  with open(fname) as f:
    f=f.read().splitlines()
    lines=[x for x in f]
    for i in range(len(lines)-n,len(lines)):
      line = lines[i].split()[-1]
      #line = line.split()[-1]
      print line
file_read_from_tail('file1.txt',1)
</code>```

this yeilds teh desired as folows..

```<code>bash-4.1$ ./file2_dup.py
-125.10584323
</code>```

PS: i just borrow the question for the sake of intrest from:
how to read a specific line and print a specific position in this line using python

答:
Try the following:</p>

```<code>print [line.split()[-1].strip() for line in lines if '!' in line][-1]
</code>```

Body:
I am looking to get the last line produced from the line variable

bash-4.1$ cat file1_dup.py
#!/usr/bin/python
with open("file1.txt") as f:
  lines = f.readlines()
  for line in lines:
    if "!" in line:
      line = line.split()[-1].strip()
      print line

output i am getting is as follows ..

-122.1058
-123.1050
-125.10584323

The result i wanted to be printed out is

-125.10584323

Moreover, i got the hint from some goghling and getting the output
  desired but that seems bit complicated to me at the point ..

bash-4.1$ cat file2_dup.py
#!/usr/bin/python
def file_read_from_tail(fname,n):
  with open(fname) as f:
    f=f.read().splitlines()
    lines=[x for x in f]
    for i in range(len(lines)-n,len(lines)):
      line = lines[i].split()[-1]
      #line = line.split()[-1]
      print line
file_read_from_tail('file1.txt',1)

this yeilds teh desired as folows..

bash-4.1$ ./file2_dup.py
-125.10584323

PS: i just borrow the question for the sake of intrest from:
how to read a specific line and print a specific position in this line using python

Body:
Try the following:

print [line.split()[-1].strip() for line in lines if '!' in line][-1]


问:
Hue Tint Color error converting tiff to jpg in python3 with pillow
While saving jpg thumbnails from tiff (CMYK) file I'm encountering the following problem:

Thumbnail created with color mode conversion from CMYK to RGB gets blue hue:

Thumbnail created from the same tiff in photoshop (no ICC profile, not converted to sRGB, RGB only) get the colors the right way:

Thumbnails created without color mode conversion (jpeg with CMYK) gets similar results to the photoshopped ones but are not usable for the web (still blue).

Code snippet:

```<code>img = Image.open(img_tiff)
img.thumbnail(size)
img.convert("RGB").save(img_jpg, quality=70, optimize=True)
</code>```

Also, when trying to include tiff's ICC profile it gets corrupted in some way, and photoshop is complaining about the profile being corrupted. I was including the profile in the save function using:

```<code>icc_profile=img.info.get('icc_profile')
</code>```

What am I doing wrong / missing here?

EDIT:

Searching for the solution I found that the problem was linked to the icc profiles. Tiff file has FOGRA profile, jpeg should have some sRGB. Couldn't get to work profile transformation from within Pillow (ImageCms.profileToProfile() was throwing PyCMSError cannot build transform ,'ImageCmsProfile' object is not subscriptable, 'PIL._imagingcms.CmsProfile' object is not subscriptable ).

Found a workaround to the problem using ImageMagick@7 convert:

```<code>com_proc = subprocess.call(['convert',
                            img_tiff,
                            '-flatten',
                            '-profile', 'path/to/sRGB profile',
                            '-colorspace', 'RGB',
                            img_jpeg])
</code>```

The result of conversion is very good, file size is quite small and most important of all, colours are matching the original tiff file.

Still would like to know how to do it properly from within Pillow (ICC profile reading and applying).

Python 3.6.3, Pillow 4.3.0, OSX 10.13.1

答:
I've finally found the way to convert from CMYK to RGB from within Pillow (PIL) without recurring to external call to ImageMagick.

```<code>#  first - extract the embedded profile:
tiff_embedded_icc_profile = ImageCms.ImageCmsProfile(io.BytesIO(tiff_img.info.get('icc_profile')))

#  second - get the path to desired profile (in my case sRGB)
srgb_profile_path = '/Library/Application Support/Adobe/Color/Profiles/Recommended/sRGB Color Space Profile.icm'

#  third - perform the conversion (must have LittleCMS installed)
converted_image = ImageCms.profileToProfile(
                                     tiff_img,
                                     inputProfile=tiff_embedded_icc_profile,
                                     outputProfile=srgb_profile_path,
                                     renderingIntent=0,
                                     outputMode='RGB'
                                    )
#  finally - save converted image:
converted_image.save(new_name + '.jpg', quality=95, optimize=True)
</code>```

All colors are preserved.

Body:
While saving jpg thumbnails from tiff (CMYK) file I'm encountering the following problem:

Thumbnail created with color mode conversion from CMYK to RGB gets blue hue:

Thumbnail created from the same tiff in photoshop (no ICC profile, not converted to sRGB, RGB only) get the colors the right way:

Thumbnails created without color mode conversion (jpeg with CMYK) gets similar results to the photoshopped ones but are not usable for the web (still blue).

Code snippet:

img = Image.open(img_tiff)
img.thumbnail(size)
img.convert("RGB").save(img_jpg, quality=70, optimize=True)

Also, when trying to include tiff's ICC profile it gets corrupted in some way, and photoshop is complaining about the profile being corrupted. I was including the profile in the save function using:

icc_profile=img.info.get('icc_profile')

What am I doing wrong / missing here?

EDIT:

Searching for the solution I found that the problem was linked to the icc profiles. Tiff file has FOGRA profile, jpeg should have some sRGB. Couldn't get to work profile transformation from within Pillow (ImageCms.profileToProfile() was throwing PyCMSError cannot build transform ,'ImageCmsProfile' object is not subscriptable, 'PIL._imagingcms.CmsProfile' object is not subscriptable ).

Found a workaround to the problem using ImageMagick@7 convert:

com_proc = subprocess.call(['convert',
                            img_tiff,
                            '-flatten',
                            '-profile', 'path/to/sRGB profile',
                            '-colorspace', 'RGB',
                            img_jpeg])

The result of conversion is very good, file size is quite small and most important of all, colours are matching the original tiff file.

Still would like to know how to do it properly from within Pillow (ICC profile reading and applying).

Python 3.6.3, Pillow 4.3.0, OSX 10.13.1

Body:
I've finally found the way to convert from CMYK to RGB from within Pillow (PIL) without recurring to external call to ImageMagick.

#  first - extract the embedded profile:
tiff_embedded_icc_profile = ImageCms.ImageCmsProfile(io.BytesIO(tiff_img.info.get('icc_profile')))

#  second - get the path to desired profile (in my case sRGB)
srgb_profile_path = '/Library/Application Support/Adobe/Color/Profiles/Recommended/sRGB Color Space Profile.icm'

#  third - perform the conversion (must have LittleCMS installed)
converted_image = ImageCms.profileToProfile(
                                     tiff_img,
                                     inputProfile=tiff_embedded_icc_profile,
                                     outputProfile=srgb_profile_path,
                                     renderingIntent=0,
                                     outputMode='RGB'
                                    )
#  finally - save converted image:
converted_image.save(new_name + '.jpg', quality=95, optimize=True)

All colors are preserved.


问:
How to declare several stylable attributes with the same name for different tags?
I want both my ViewA and ViewB to have the "title" tag. But I can't put this in attrs.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="ViewA">
        <attr name="title" format="string" />
    </declare-styleable>
    <declare-styleable name="ViewB">
        <attr name="title" format="string" />
        <attr name="max" format="integer" />
    </declare-styleable>
</resources>
</code>```

because of the error Attribute "title" has already been defined. Another question shows this solution:

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
    <attr name="title" format="string" />
    <declare-styleable name="ViewB">
        <attr name="max" format="integer" />
    </declare-styleable>
</resources>
</code>```

but in that case, R.styleable.ViewA_title and R.styleable.ViewB_title are not generated. I need them for reading the attributes from the AttributeSet using the following code:

```<code>TypedArray a=getContext().obtainStyledAttributes( as, R.styleable.ViewA);
String title = a.getString(R.styleable.ViewA_title);
</code>```

How can I solve this?

答:
```<code><resources>
<declare-styleable name="ViewA">
    <attr name="title" format="string" />
</declare-styleable>

<declare-styleable name="ViewB" parent="ViewA"> // inherit from ViewA
    <attr name="min" format="integer" />
    <attr name="max" format="integer" />
</declare-styleable>
</code>```

This doesn't work。

```<code><resources>
<attr name="title" format="string" />
<declare-styleable name="ViewA">
    <attr name="title" />
</declare-styleable>
<declare-styleable name="ViewB">
    <attr name="title" />
    <attr name="max" format="integer" />
</declare-styleable>
</code>```

This also doesn't work。

```<code><resources>
<declare-styleable name="ViewA">
    <attr name="title" format="string" />
</declare-styleable>

<declare-styleable name="ViewB" >
    <attr name="title" />
    <attr name="min" format="integer" />
    <attr name="max" format="integer" />
</declare-styleable>
</code>```

This was OK!!

Body:
I want both my ViewA and ViewB to have the "title" tag. But I can't put this in attrs.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="ViewA">
        <attr name="title" format="string" />
    </declare-styleable>
    <declare-styleable name="ViewB">
        <attr name="title" format="string" />
        <attr name="max" format="integer" />
    </declare-styleable>
</resources>

because of the error Attribute "title" has already been defined. Another question shows this solution:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <attr name="title" format="string" />
    <declare-styleable name="ViewB">
        <attr name="max" format="integer" />
    </declare-styleable>
</resources>

but in that case, R.styleable.ViewA_title and R.styleable.ViewB_title are not generated. I need them for reading the attributes from the AttributeSet using the following code:

TypedArray a=getContext().obtainStyledAttributes( as, R.styleable.ViewA);
String title = a.getString(R.styleable.ViewA_title);

How can I solve this?

Body:
<resources>
<declare-styleable name="ViewA">
    <attr name="title" format="string" />
</declare-styleable>

<declare-styleable name="ViewB" parent="ViewA"> // inherit from ViewA
    <attr name="min" format="integer" />
    <attr name="max" format="integer" />
</declare-styleable>

This doesn't work。

<resources>
<attr name="title" format="string" />
<declare-styleable name="ViewA">
    <attr name="title" />
</declare-styleable>
<declare-styleable name="ViewB">
    <attr name="title" />
    <attr name="max" format="integer" />
</declare-styleable>

This also doesn't work。

<resources>
<declare-styleable name="ViewA">
    <attr name="title" format="string" />
</declare-styleable>

<declare-styleable name="ViewB" >
    <attr name="title" />
    <attr name="min" format="integer" />
    <attr name="max" format="integer" />
</declare-styleable>

This was OK!!


问:
Alternative to Gatling
I’ve been having issues lately because my dependencies has been updated to use netty 4.1 and Gatling has not been updated for a while, and still work only on Netty 4.0.

Anybody knows any alternative to Gatling to create similar Simulations and scenarios for the performance test to be run automatically in my Maven life cycle?

答:
If you look for something code-based it would be:

Locust

Grinder

For UI and/or XML based scenario definition you can check out:

Tsung (this one can be reliably run on Linux/Unix only)

Apache JMeter

Check out Open Source Load Testing Tools: Which One Should You Use? to learn more about the aforementioned tools and decide which one fits to your most.

Title: Alternative to Gatling


问:
IsolatedContext vs. AndroidTestCase.getContext()
I'm writing some tests to test my sqllite database code. Can someone here explain if there would be a difference writing those tests using the context I get from AndroidTestCase.getContext() or using an IsolatedContext.

答:
The answer:

http://groups.google.com/group/android-developers/browse_thread/thread/3a7bbc78258a194a?tvc=2


问:
Parse error: syntax error, unexpected '<' laravel blade template
Getting error on populating select list</p>

```<code> <select name="notificationtype" required class="form-control">
         <option value="sms" {{isset($template->type) ? @if($template->type=='sms' "selected=true" @endif : 'sms'}}> {{ 'SMS'}}</option>
    <option value="email" {{ isset($template->type) ? @if($template->type=='email' "selected=true" @endif : 'email'}}>{{'Email'}}</option> </select>
</code>```

答:
The problem is in this line :

```<code>{{isset($template->type) ? @if($template->type=='sms' "selected=true" @endif : 'sms'
</code>```

try it like this :

```<code><select name="notificationtype" required class="form-control">
    <option value="sms" @if(isset($template->type) && $template->type=='sms') "selected=true" @endif > SMS </option>
    <option value="email" @if(isset($template->type) && $template->type=='email') "selected=true" @endif > Email </option>
</select>
</code>```

Body:
Getting error on populating select list

 <select name="notificationtype" required class="form-control">
         <option value="sms" {{isset($template->type) ? @if($template->type=='sms' "selected=true" @endif : 'sms'}}> {{ 'SMS'}}</option>
    <option value="email" {{ isset($template->type) ? @if($template->type=='email' "selected=true" @endif : 'email'}}>{{'Email'}}</option> </select>

Body:
The problem is in this line :

{{isset($template->type) ? @if($template->type=='sms' "selected=true" @endif : 'sms'

try it like this :

<select name="notificationtype" required class="form-control">
    <option value="sms" @if(isset($template->type) && $template->type=='sms') "selected=true" @endif > SMS </option>
    <option value="email" @if(isset($template->type) && $template->type=='email') "selected=true" @endif > Email </option>
</select>