问:
d3 embeded image displayed twice
I'm embedding an image on a d3 diagram as in this example:

```<code>  var logoCanvas = d3.select("body").append("canvas")
    .attr("id", "newCanvas")
    .attr("width", width / 2)
    .attr("height", height / 2)
    .node();

  var context = logoCanvas.getContext("2d");
  var imageObj = new Image();
  imageObj.src = 'myImage.svg';
  imageObj.onload = function() {
    context.drawImage(imageObj, 0, 0);
    var imageData = document.getElementById("newCanvas").toDataURL("image/png")
    //Add as SVG image element
    d3.select("svg").
    append("image")
      .datum(imageData)
      .attr("height", 100)
      .attr("width", 100)
      .attr('transform', 'translate(' + [offsetX - 50, offsetY - 50] + ')')
      .attr("xlink:href", function(d) {
        return d
      })
  }
</code>```

This works all as expected but unfortunately I get the image displayed twice. Basically I only need the appended one and not the one which is drawn onto the context. The thing is the I can't get the appended one without drawing it first.

Is there a way to hide the Image which is drawn in context?

Or a smarter approach of only getting one image displayed but embedded?

答:
Here's a code snippet of an XMLHTTPRequest() and FileReader() approach to fetch a image and "embed" into a SVG. You don't need a canvas at all.

// append svg
d3.select("body").append("svg").attr("height", "300px").attr("width", "276px");

var xhr1 = new XMLHttpRequest();
xhr1.open('GET', 'https://s7.postimg.org/40f9flc1n/dummy1.png');
xhr1.responseType = 'blob';
xhr1.onload = function () {
  var fs = new FileReader();
  fs.onload = function (result) {
    d3.select("svg").append("image")
      .datum(result.target.result)
      .attr("height", 300)
      .attr("width", 276)
      .attr("xlink:href", function(d) {
        return d
      })
  };
  fs.readAsDataURL(xhr1.response);
};
xhr1.send();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.7/d3.min.js"></script></code>```

Hope this helps. :)

Title: d3 embeded image displayed twice

Body:
I'm embedding an image on a d3 diagram as in this example:

  var logoCanvas = d3.select("body").append("canvas")
    .attr("id", "newCanvas")
    .attr("width", width / 2)
    .attr("height", height / 2)
    .node();

  var context = logoCanvas.getContext("2d");
  var imageObj = new Image();
  imageObj.src = 'myImage.svg';
  imageObj.onload = function() {
    context.drawImage(imageObj, 0, 0);
    var imageData = document.getElementById("newCanvas").toDataURL("image/png")
    //Add as SVG image element
    d3.select("svg").
    append("image")
      .datum(imageData)
      .attr("height", 100)
      .attr("width", 100)
      .attr('transform', 'translate(' + [offsetX - 50, offsetY - 50] + ')')
      .attr("xlink:href", function(d) {
        return d
      })
  }

This works all as expected but unfortunately I get the image displayed twice. Basically I only need the appended one and not the one which is drawn onto the context. The thing is the I can't get the appended one without drawing it first.

Is there a way to hide the Image which is drawn in context?

Or a smarter approach of only getting one image displayed but embedded?

Body:
Here's a code snippet of an XMLHTTPRequest() and FileReader() approach to fetch a image and "embed" into a SVG. You don't need a canvas at all.

// append svg
d3.select("body").append("svg").attr("height", "300px").attr("width", "276px");

var xhr1 = new XMLHttpRequest();
xhr1.open('GET', 'https://s7.postimg.org/40f9flc1n/dummy1.png');
xhr1.responseType = 'blob';
xhr1.onload = function () {
  var fs = new FileReader();
  fs.onload = function (result) {
    d3.select("svg").append("image")
      .datum(result.target.result)
      .attr("height", 300)
      .attr("width", 276)
      .attr("xlink:href", function(d) {
        return d
      })
  };
  fs.readAsDataURL(xhr1.response);
};
xhr1.send();

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.7/d3.min.js"></script>

Hope this helps. :)


来源: stackexchange

问:
Disable default notifications android wear
I have an Android Wear App with a WearableListenerService that shows a custom notification when it receives a DataMap. I have an app on my phone that sends the DataMap to wearable app. This app receives notifications from Firebase and the wearable shows them too. I want only Wearable to show my custom notifications not the phone from where it's initiated.

Can anyone help me out?

Thank you. Kind Regards.

答:
From the official documentation:

By default, notifications are bridged (shared) from an app on a
  companion phone to the paired watch. If you build a standalone watch
  app and you have a companion phone app, the apps may duplicate
  notifications. The Android Wear includes features to handle this
  problem of duplicate notifications.

You need to add the following to your app's manifest file:

```<code><application>

    <meta-data
        android:name="com.google.android.wearable.notificationBridgeMode"
        android:value="NO_BRIDGING" />

</application>
</code>```

Or you can do it in code. See the documentation for more details.

ContentLicense: CC BY-SA 3.0

Body:
From the official documentation:

By default, notifications are bridged (shared) from an app on a
  companion phone to the paired watch. If you build a standalone watch
  app and you have a companion phone app, the apps may duplicate
  notifications. The Android Wear includes features to handle this
  problem of duplicate notifications.

You need to add the following to your app's manifest file:

<application>

    <meta-data
        android:name="com.google.android.wearable.notificationBridgeMode"
        android:value="NO_BRIDGING" />

</application>

Or you can do it in code. See the documentation for more details.


问:
Calculate Percentage in a dataframe according to groups R
I have the following dataframe and would like to calculate percentages according to Stage and Category. Some of my other data have another variable e.g. Year. I need the output on a dataframe to be able to use ggplot2.

```<code>Gender = rep(c("Female", "Male"), 6)
Stage = rep(c("Applied", "Appointed", "Interviewed"), each=2, times = 2)
Category = rep(c("Professional", "Research"), each = 6)
Count = as.integer(c("346", "251", "22", "15", "60", "52", "31", "230", "4", "17", "9", "52"))
df = data.frame(Gender, Stage, Category,Count )
</code>```

The (horrible) code I wrote works for some instance but if the data structure changes e.g. Females with 0 count, the code will not work.

```<code>totals = aggregate(df$Count, by = list(Stage = df$Stage, Category = df$Category),sum)
totals = rep( totals$x, each = 2)
df$Percentage = round(df$Count/totals, 2)
</code>```

This is the output I am after:

```<code>   Gender       Stage     Category Count Percentage
1  Female     Applied Professional   346       0.58
2    Male     Applied Professional   251       0.42
3  Female   Appointed Professional    22       0.59
4    Male   Appointed Professional    15       0.41
5  Female Interviewed Professional    60       0.54
6    Male Interviewed Professional    52       0.46
7  Female     Applied     Research    31       0.12
8    Male     Applied     Research   230       0.88
9  Female   Appointed     Research     4       0.19
10   Male   Appointed     Research    17       0.81
11 Female Interviewed     Research     9       0.15
12   Male Interviewed     Research    52       0.85
</code>```

Thanks for your help!

答:
I suggest using data.table package. There you would be able to write something like:

```<code>library(data.table)
dt[,Percentage := round(Count / sum(Count), 2), by=c("Stage", "Category")]
</code>```

The reason I suggest using data.table packages is that it is one of the fastest packages for data.frames. In general standard data frames are quite bad.

In comparison to dplyr, data.table is faster, but doesn't have transparent interface to SQL data bases.

The speed in data.table is mostly achieved by zero copying in data transformation.

Here is the manual

Body:
I have the following dataframe and would like to calculate percentages according to Stage and Category. Some of my other data have another variable e.g. Year. I need the output on a dataframe to be able to use ggplot2.

Gender = rep(c("Female", "Male"), 6)
Stage = rep(c("Applied", "Appointed", "Interviewed"), each=2, times = 2)
Category = rep(c("Professional", "Research"), each = 6)
Count = as.integer(c("346", "251", "22", "15", "60", "52", "31", "230", "4", "17", "9", "52"))
df = data.frame(Gender, Stage, Category,Count )

The (horrible) code I wrote works for some instance but if the data structure changes e.g. Females with 0 count, the code will not work.

totals = aggregate(df$Count, by = list(Stage = df$Stage, Category = df$Category),sum)
totals = rep( totals$x, each = 2)
df$Percentage = round(df$Count/totals, 2)

This is the output I am after:

   Gender       Stage     Category Count Percentage
1  Female     Applied Professional   346       0.58
2    Male     Applied Professional   251       0.42
3  Female   Appointed Professional    22       0.59
4    Male   Appointed Professional    15       0.41
5  Female Interviewed Professional    60       0.54
6    Male Interviewed Professional    52       0.46
7  Female     Applied     Research    31       0.12
8    Male     Applied     Research   230       0.88
9  Female   Appointed     Research     4       0.19
10   Male   Appointed     Research    17       0.81
11 Female Interviewed     Research     9       0.15
12   Male Interviewed     Research    52       0.85

Thanks for your help!

Body:
I suggest using data.table package. There you would be able to write something like:

library(data.table)
dt[,Percentage := round(Count / sum(Count), 2), by=c("Stage", "Category")]

The reason I suggest using data.table packages is that it is one of the fastest packages for data.frames. In general standard data frames are quite bad.

In comparison to dplyr, data.table is faster, but doesn't have transparent interface to SQL data bases.

The speed in data.table is mostly achieved by zero copying in data transformation.

Here is the manual


问:
lombok @Builder vs constructor
Could someone explain me the advantages of using lombok @Builder to create an object instead of constructor call?

```<code>MyObject o1 = MyObject.builder()
              .id(1)
              .name("name")
              .build();

MyObject o2 = new MyObject(1, "name")
</code>```

Is it just a question of better visibility?

答:
Consider:

```<code>Order order = new Order("Alan", "Smith", 2, 6, "Susan", "Smith");
</code>```

What do the parameters mean? We have to look at the constructor spec to find out.

Now with a builder:

```<code>Order order = Order.builder()
    .originatorFirstName("Alan")
    .originatorLastName("Smith")
    .lineItemNumber(2)
    .quantity(6)
    .recipientFirstName("Susan")
    .recipientLastName("Smith")
    .build();
</code>```

It's more wordy, but it's very clear to read, and with IDE assistance it's easy to write too. The builders themselves are a bit of a chore to write, but code-generation tools like Lombok help with that.

Some people argue that if your code needs builders to be readable, that's exposing other smells. You're using too many basic types; you're putting too many fields in one class. For example, consider:

```<code>Order order = new Order(
     new Originator("Alan", "Smith"),
     new ItemSet(new Item(2), 6),
     new Recipient("Susan", "Smith"));
</code>```

... which is self-explanatory without using a builder, because we are using more classes with single-responsibilities and fewer fields.

ContentLicense: CC BY-SA 4.0

Title: lombok @Builder vs constructor

Body:
Could someone explain me the advantages of using lombok @Builder to create an object instead of constructor call?

MyObject o1 = MyObject.builder()
              .id(1)
              .name("name")
              .build();

MyObject o2 = new MyObject(1, "name")

Is it just a question of better visibility?

Body:
Consider:

Order order = new Order("Alan", "Smith", 2, 6, "Susan", "Smith");

What do the parameters mean? We have to look at the constructor spec to find out.

Now with a builder:

Order order = Order.builder()
    .originatorFirstName("Alan")
    .originatorLastName("Smith")
    .lineItemNumber(2)
    .quantity(6)
    .recipientFirstName("Susan")
    .recipientLastName("Smith")
    .build();

It's more wordy, but it's very clear to read, and with IDE assistance it's easy to write too. The builders themselves are a bit of a chore to write, but code-generation tools like Lombok help with that.

Some people argue that if your code needs builders to be readable, that's exposing other smells. You're using too many basic types; you're putting too many fields in one class. For example, consider:

Order order = new Order(
     new Originator("Alan", "Smith"),
     new ItemSet(new Item(2), 6),
     new Recipient("Susan", "Smith"));

... which is self-explanatory without using a builder, because we are using more classes with single-responsibilities and fewer fields.


问:
Android Back Button to specific activity
When I click the back button Android goes to the previous activity.
Is it possible to set for every activity a custom (back) activity
or to set the back button to the home menue of the app?

Help or hints would be great :)

答:
If you need to go back what ever activity, when click on ActionBar back arrow(Home). overide onSupportNavigateUp()

```<code>@Override
public boolean onSupportNavigateUp() {
    //onBackPressed();   //this will be go to parent activity

     //******************//
     // Your intent here //
     //******************//
    return true;
}
</code>```

Body:
If you need to go back what ever activity, when click on ActionBar back arrow(Home). overide onSupportNavigateUp()

@Override
public boolean onSupportNavigateUp() {
    //onBackPressed();   //this will be go to parent activity

     //******************//
     // Your intent here //
     //******************//
    return true;
}


问:
Is it possible to add a string with spaces or special characters to an enum?
Is it possible to add a string with spaces or special characters to an enum?

For example, I have a string Insurance KR Users (Name), I have tried to include this string into an enum:

```<code>    public enum MemberGroup
    {
        Insurance KR Users (Name)
    }
</code>```

but it throws an error.

How can I include these types of strings into enum?

答:
The enum members itself must be a valid identifier, so it can't contain spaces or special characters.

But you could use the DescriptionAttribute to provide a more complete description of each enum value:

```<code>public enum MemberGroup
{
    [Description("Insurance KR Users (Name)")]
    InsuranceKrUsers_Name
}
</code>```

To retrieve the description, use something like this:

```<code>public static string GetDescription(Enum value)
{
   FieldInfo fi = value.GetType().GetField(value.ToString());
   DescriptionAttribute[] attributes =
     (DescriptionAttribute[])fi.GetCustomAttributes(
     typeof(DescriptionAttribute), false);
   return (attributes.Length > 0) ? attributes[0].Description : value.ToString();
}
</code>```

Body:
Is it possible to add a string with spaces or special characters to an enum?

For example, I have a string Insurance KR Users (Name), I have tried to include this string into an enum:

    public enum MemberGroup
    {
        Insurance KR Users (Name)
    }

but it throws an error.

How can I include these types of strings into enum?

Body:
The enum members itself must be a valid identifier, so it can't contain spaces or special characters.

But you could use the DescriptionAttribute to provide a more complete description of each enum value:

public enum MemberGroup
{
    [Description("Insurance KR Users (Name)")]
    InsuranceKrUsers_Name
}

To retrieve the description, use something like this:

public static string GetDescription(Enum value)
{
   FieldInfo fi = value.GetType().GetField(value.ToString());
   DescriptionAttribute[] attributes =
     (DescriptionAttribute[])fi.GetCustomAttributes(
     typeof(DescriptionAttribute), false);
   return (attributes.Length > 0) ? attributes[0].Description : value.ToString();
}

ContentLicense: CC BY-SA 2.5


问:
highcharts-export-server yAxis formatter does not work
highcharts can set yAxis formatter function to change yAxis format,but
using highcharts-export-server to generate image, yAxis formatter does not work.

the demo code is like this:

const exporter = require("highcharts-export-server");
const fs = require("fs");
const options = {
    "xAxis": {
        "categories": ['1', '2', '3', '4']
    },
    "yAxis": {
        title: {
            text: 'times'
        },
        plotLines: [
            {
                value: 0,
                width: 1,
                color: "#808080"
            }
        ],
        labels: {
            enabled: true,
            formatter: function () {
                return this.value * 100
            },
        },
    },
    "series": [{
        "data": [1, 3, 2, 4],
        "type": "line"
    }, {
        "data": [5, 3, 4, 2],
        "type": "line"
    }]
}

const exportSettings = {type: 'png',options}

//Set up a pool of PhantomJS workers
exporter.initPool();

//Perform an export
exporter.export(exportSettings, function (err, res) {
    var dataBuffer = new Buffer(res.data, 'base64');
    fs.writeFile("out.png", dataBuffer, function (err) {
        if (err) {
            console.log(err);
        } else {
            console.log("save success！");
        }
    });

    exporter.killPool();
});
```

any one have some suggestions?thanks!

the result:

demo result

答:
There's a bug associated with this problem: https://github.com/highcharts/node-export-server/issues/70

However you can use the formatter function in callback export parameter like this:

```<code>{
  "type": "Png",
  callback: `function(chart) {
    chart.yAxis[0].update({
      labels: {
        enabled: true,
        formatter: function() {
          return this.value * 100
        }

      }
    });
  }`,
  options: {
    "xAxis": {
      "categories": ['1', '2', '3', '4', '5']
  (...)
</code>```

Notice that the whole function is a String.

Body:
highcharts can set yAxis formatter function to change yAxis format,but
using highcharts-export-server to generate image, yAxis formatter does not work.

the demo code is like this:

const exporter = require("highcharts-export-server");
const fs = require("fs");
const options = {
    "xAxis": {
        "categories": ['1', '2', '3', '4']
    },
    "yAxis": {
        title: {
            text: 'times'
        },
        plotLines: [
            {
                value: 0,
                width: 1,
                color: "#808080"
            }
        ],
        labels: {
            enabled: true,
            formatter: function () {
                return this.value * 100
            },
        },
    },
    "series": [{
        "data": [1, 3, 2, 4],
        "type": "line"
    }, {
        "data": [5, 3, 4, 2],
        "type": "line"
    }]
}

const exportSettings = {type: 'png',options}

//Set up a pool of PhantomJS workers
exporter.initPool();

//Perform an export
exporter.export(exportSettings, function (err, res) {
    var dataBuffer = new Buffer(res.data, 'base64');
    fs.writeFile("out.png", dataBuffer, function (err) {
        if (err) {
            console.log(err);
        } else {
            console.log("save success！");
        }
    });

    exporter.killPool();
});

any one have some suggestions?thanks!

the result:

demo result

Body:
There's a bug associated with this problem: https://github.com/highcharts/node-export-server/issues/70

However you can use the formatter function in callback export parameter like this:

{
  "type": "Png",
  callback: `function(chart) {
    chart.yAxis[0].update({
      labels: {
        enabled: true,
        formatter: function() {
          return this.value * 100
        }

      }
    });
  }`,
  options: {
    "xAxis": {
      "categories": ['1', '2', '3', '4', '5']
  (...)

Notice that the whole function is a String.


问:
Maximum size of xattr in OS X
I would like to use xattr to store some meta-data on my files directly on the files. These are essentially tags that I use for the categorization of files when I do searches on them. My goal is to extend the usual Mac OS X tags by associating more info to each tag, for instance the date of addition of that tag and maybe other thing.

I was thinking to add an xattr to the files, using xattr -w. My first guess would be to store something like a JSON in this xattr value, but I was wondering

1) what are the limits of size I can store in an xattr? (man of xattr is vauge and refers to something called _PC_XATTR_SIZE_BITS which I cannot locate anywhere)

2) anything wrong with storing a JSON formatted string as an xattr?

答:
I seem to be able to write at least 260kB, like this by generating 260kB of nulls and converting them to the letter a so I can see them:

```<code>xattr -w myattr "$(dd if=/dev/zero bs=260000 count=1|tr '\0' a)" fred
1+0 records in
1+0 records out
260000 bytes transferred in 0.010303 secs (25235318 bytes/sec)
</code>```

And then read them back with:

```<code>xattr -l fred
myattr:  aaaaaaaaaaaaaaaaaa...aaa
</code>```

And check the length returned:

```<code>xattr -l fred | wc -c
260009
</code>```

I suspect this is actually a limit of ARGMAX on the command line:

```<code>sysctl kern.argmax
kern.argmax: 262144
</code>```

Also, just because you can store 260kB in an xattr, that does not mean it is advisable. I don't know about HFS+, but on some Unixy filesystems, the attributes can be stored directly in the inode, but if you go over a certain limit, additional space has to be allocated on disk for the data.

——-

With the advent of High Sierra and APFS to replace HFS+, be sure to test on both filesystems - also make sure that Time Machine backs up and restores the data as well and that utilities such as ditto, tar and the Finder propagate them when copying/moving/archiving files.

Also consider what happens when Email a tagged file, or copy it to a FAT-formatted USB Memory Stick.

I also tried setting multiple attributes on a single file and the following script successfully wrote 1,000 attributes (called attr-0, attr-1 ... attr-999) each of 260kB to a single file - meaning that the file effectively carries 260MB of attributes:

```<code>#!/bin/bash
for ((a=1;a<=1000;a++)) ; do
   echo Setting attr-$a
   xattr -w attr-$a "$(dd if=/dev/zero bs=260000 count=1 2> /dev/null | tr '\0' a)" fred
   if [ $? -ne 0 ]; then
      echo ERROR: Failed to set attr
      exit
   fi
done
</code>```

These can all be seen and read back too - I checked.

Title: Maximum size of xattr in OS X

Body:
I seem to be able to write at least 260kB, like this by generating 260kB of nulls and converting them to the letter a so I can see them:

xattr -w myattr "$(dd if=/dev/zero bs=260000 count=1|tr '\0' a)" fred
1+0 records in
1+0 records out
260000 bytes transferred in 0.010303 secs (25235318 bytes/sec)

And then read them back with:

xattr -l fred
myattr:  aaaaaaaaaaaaaaaaaa...aaa

And check the length returned:

xattr -l fred | wc -c
260009

I suspect this is actually a limit of ARGMAX on the command line:

sysctl kern.argmax
kern.argmax: 262144

Also, just because you can store 260kB in an xattr, that does not mean it is advisable. I don't know about HFS+, but on some Unixy filesystems, the attributes can be stored directly in the inode, but if you go over a certain limit, additional space has to be allocated on disk for the data.

——-

With the advent of High Sierra and APFS to replace HFS+, be sure to test on both filesystems - also make sure that Time Machine backs up and restores the data as well and that utilities such as ditto, tar and the Finder propagate them when copying/moving/archiving files.

Also consider what happens when Email a tagged file, or copy it to a FAT-formatted USB Memory Stick.

I also tried setting multiple attributes on a single file and the following script successfully wrote 1,000 attributes (called attr-0, attr-1 ... attr-999) each of 260kB to a single file - meaning that the file effectively carries 260MB of attributes:

#!/bin/bash
for ((a=1;a<=1000;a++)) ; do
   echo Setting attr-$a
   xattr -w attr-$a "$(dd if=/dev/zero bs=260000 count=1 2> /dev/null | tr '\0' a)" fred
   if [ $? -ne 0 ]; then
      echo ERROR: Failed to set attr
      exit
   fi
done

These can all be seen and read back too - I checked.


答:
We can use dplyr

```<code>library(dplyr)
df %>%
   group_by(Stage, Category) %>%
   mutate(Percentage = round(Count/sum(Count), 2))
</code>```

Title: Calculate Percentage in a dataframe according to groups R

Body:
We can use dplyr

library(dplyr)
df %>%
   group_by(Stage, Category) %>%
   mutate(Percentage = round(Count/sum(Count), 2))


问:
Access members of unkown template type of derived template class through pointer to base class C++
I need to have a map holding different value types. I achieved that using a derived template class Derived of type T derived from B  and declaring my map using a pointer to the base class Base like so:

```<code>class Base {
    public:
    ~Base(){}
};

template <class T>
class Derived: public Base {
     public:
     Derived(T value) {
          this->value = value;
     }
     T value;
 };

 std::map<std::string, std::shared_ptr<Base>> my_map;

 using KeyValuePair = std::pair<std::string, std::shared_ptr<Base>>;

 my_map.insert(KeyValuePair("foo1",std::make_shared<Derived<int>>(10)));
 my_map.insert(KeyValuePair("foo2",std::make_shared<Derived<double>>(20.0)));
 my_map.insert(KeyValuePair("foo3",std::make_shared<Derived<std::string>>("bla")));
</code>```

I now for example want to print the value of a map entry

```<code> for (auto const& x : my_map)
{
    std::cout << *x.get() << std::endl;
}
</code>```

However, I now have the problem that I cannot access the the members in the Derived class by casting x to Derived, because I don't know the type of the template parameter. So the following is not possible:

```<code>std::shared_ptr<Derived<?>> derived = std::dynamic_cast<Derived<?>>(x);
</code>```

I thought about having a virtual function in the Base class which returns the member, but I don't know the return type, so not an option.

I also don't want to specify several virtual functions for several return types, as the whole point of the code is to avoid copying code and having a "generic map"

However, I don't see another solution besides using some fancy boost magic by returning a streamable boost::any like the following, as this removes any information about the type.

```<code> using streamable_any = boost::type_erasure::any<boost::mpl::vector<
 boost::type_erasure::copy_constructible<>,
 boost::type_erasure::destructible<>,
 boost::type_erasure::ostreamable<>>>;
</code>```

What are the possibilities I have to achieve what I want? I suspect that I need to consider a design change.

答:
One option would be to make the class B a template, so it could have a method that returns a value of type T:

```<code>template <class T>
class Base {
    public:
    virtual T GetValue();
};
</code>```

Another option is to have a virtual print method:

```<code>class Base {
    public:
    virtual void PrintValue();
};
</code>```

Body:
I need to have a map holding different value types. I achieved that using a derived template class Derived of type T derived from B  and declaring my map using a pointer to the base class Base like so:

class Base {
    public:
    ~Base(){}
};

template <class T>
class Derived: public Base {
     public:
     Derived(T value) {
          this->value = value;
     }
     T value;
 };

 std::map<std::string, std::shared_ptr<Base>> my_map;

 using KeyValuePair = std::pair<std::string, std::shared_ptr<Base>>;

 my_map.insert(KeyValuePair("foo1",std::make_shared<Derived<int>>(10)));
 my_map.insert(KeyValuePair("foo2",std::make_shared<Derived<double>>(20.0)));
 my_map.insert(KeyValuePair("foo3",std::make_shared<Derived<std::string>>("bla")));

I now for example want to print the value of a map entry

 for (auto const& x : my_map)
{
    std::cout << *x.get() << std::endl;
}

However, I now have the problem that I cannot access the the members in the Derived class by casting x to Derived, because I don't know the type of the template parameter. So the following is not possible:

std::shared_ptr<Derived<?>> derived = std::dynamic_cast<Derived<?>>(x);

I thought about having a virtual function in the Base class which returns the member, but I don't know the return type, so not an option.

I also don't want to specify several virtual functions for several return types, as the whole point of the code is to avoid copying code and having a "generic map"

However, I don't see another solution besides using some fancy boost magic by returning a streamable boost::any like the following, as this removes any information about the type.

 using streamable_any = boost::type_erasure::any<boost::mpl::vector<
 boost::type_erasure::copy_constructible<>,
 boost::type_erasure::destructible<>,
 boost::type_erasure::ostreamable<>>>;

What are the possibilities I have to achieve what I want? I suspect that I need to consider a design change.

Body:
One option would be to make the class B a template, so it could have a method that returns a value of type T:

template <class T>
class Base {
    public:
    virtual T GetValue();
};

Another option is to have a virtual print method:

class Base {
    public:
    virtual void PrintValue();
};


答:
We can use the ave function:

```<code>df$Percentage <- df$Count / ave(df$Count, df$Stage, df$Category, FUN = sum)

   Gender       Stage     Category Count Percentage
1  Female     Applied Professional   346  0.5795645
2    Male     Applied Professional   251  0.4204355
3  Female   Appointed Professional    22  0.5945946
4    Male   Appointed Professional    15  0.4054054
5  Female Interviewed Professional    60  0.5357143
6    Male Interviewed Professional    52  0.4642857
7  Female     Applied     Research    31  0.1187739
8    Male     Applied     Research   230  0.8812261
9  Female   Appointed     Research     4  0.1904762
10   Male   Appointed     Research    17  0.8095238
11 Female Interviewed     Research     9  0.1475410
12   Male Interviewed     Research    52  0.8524590
</code>```

Body:
We can use the ave function:

df$Percentage <- df$Count / ave(df$Count, df$Stage, df$Category, FUN = sum)

   Gender       Stage     Category Count Percentage
1  Female     Applied Professional   346  0.5795645
2    Male     Applied Professional   251  0.4204355
3  Female   Appointed Professional    22  0.5945946
4    Male   Appointed Professional    15  0.4054054
5  Female Interviewed Professional    60  0.5357143
6    Male Interviewed Professional    52  0.4642857
7  Female     Applied     Research    31  0.1187739
8    Male     Applied     Research   230  0.8812261
9  Female   Appointed     Research     4  0.1904762
10   Male   Appointed     Research    17  0.8095238
11 Female Interviewed     Research     9  0.1475410
12   Male Interviewed     Research    52  0.8524590


问:
Application is consuming power in the background if I set listener for Firebase Realtime Database in Android
I use Firebase Realtime Database in my android application. When I try to read from database overriding method onDataChange(DataSnapshot dataSnapshot)

```<code>myRef.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot)
        String value = dataSnapshot.getValue(String.class);
        Log.d(TAG, "Value is: " + value);
    }

    @Override
    public void onCancelled(DatabaseError error)
        Log.w(TAG, "Failed to read value.", error.toException());
    }
});
</code>```

it is working nice, but in morning my device (with Android 7.0) give me warning that my app is consuming power in the background. I don't find in documentation how unset listener if activity is paused/destroyed.

答:
In order to stop this from happening, you need to remove the listener accordingly to the life-cycle of your activity. So, please use the following line of code:

```<code>databaseReference.removeEventListener(valueEventListener);
</code>```

So, if you have added the listener in onStart you have to remove it in onStop. If you have added the listener in onResume you have to remove it in onPause. If you have added the listener in onCreate you have to remove it in onDestroy.

But remember onDestroy is not always called!

Here is a graphic representation:

Body:
I use Firebase Realtime Database in my android application. When I try to read from database overriding method onDataChange(DataSnapshot dataSnapshot)

myRef.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot)
        String value = dataSnapshot.getValue(String.class);
        Log.d(TAG, "Value is: " + value);
    }

    @Override
    public void onCancelled(DatabaseError error)
        Log.w(TAG, "Failed to read value.", error.toException());
    }
});

it is working nice, but in morning my device (with Android 7.0) give me warning that my app is consuming power in the background. I don't find in documentation how unset listener if activity is paused/destroyed.

Body:
In order to stop this from happening, you need to remove the listener accordingly to the life-cycle of your activity. So, please use the following line of code:

databaseReference.removeEventListener(valueEventListener);

So, if you have added the listener in onStart you have to remove it in onStop. If you have added the listener in onResume you have to remove it in onPause. If you have added the listener in onCreate you have to remove it in onDestroy.

But remember onDestroy is not always called!

Here is a graphic representation:


问:
On ENTER keyup - Execute Function inside form and not submit the form
I have a table with filterable data using the jQuery DataTables library.
This table is inside a form that, when rows are CHECKED (in one column there is a checkbox), the SUBMIT button will add them to a collection.

Attached to the table is a custom search filter that functions like the built-in search filter that comes with DataTables, but instead of a "filter as you type" functionality, I have a submit button attached so that it will not filter the table results until you click the button.  There is some functionality added to that search filter that actually runs an ajax call to a database, and to reduce the amount of calls to the database, I put the button on the search filter and disabled the "filter as you type" functionality.

I STILL want to be able to click the ENTER key on my keyboard when I have finished typing in my search filter to execute this custom search, but I am unable to stop the form from submitting.  I have the custom search filter in a function called "tableFilter()". The ID of the form is "#addtitle"

```<code>$("#addTitle").on('keyup', function(e){
        var keyCode = e.keyCode || e.which;
        console.log('keyup');
        if (keyCode == 13){
            console.log('ENTER PRESSED');
            if ($("#dataTables_filter_input").is(":focus")){
                console.log('FILTER FOCUS');
                tableFilter();
                e.preventDefault();
                return false;
            }
        }
    });
</code>```

I figured that if the input field of the search was still in focus, that would be enough of a difference for the code to know that when I click ENTER, it would execute the search filter and not submit the form - yet the form still submits.

Do I have things out of order? Am I not calling the right functions?

答:
we must know the mechanical first.

```<code><form>
<input type="text">
<input type="submit">
</form>
</code>```

if you pressed ENTER in input text. it will trigger:

button submit clicked

form submitted

input text keyup [ENTER]

if you want prevent default behaviour. You must use preventDefault() on $('form').submit [only], in other word you dont  need type preventDefault() in $('input[type="submit"]').click or $('input[type="text"]').keyup

so, your jquery will like this

```<code>$('form').submit(function(e){
e.preventDefault();
})

$('input[type="text"]').keyup(function(e){
var keyCode = e.keyCode || e.which;
        if (keyCode == 13){
            //do something
        }
})
</code>```

but you will never can use submit button to trigger form input. To do form submit you must use type="button" to trigger form submit.

Demo: http://jsbin.com/pirepahuhu/edit?html,output

===============

this what i think to force solved this problem

demo: http://jsbin.com/hiqatetoti/2/edit?html,output

```<code><form>
    another text input<input type="text"><br>
    add title<input type="text" id="addTitle"><br>
    another text input<input type="text"><br>
    <input type="button" value="button"><br>
    <input type="submit" value="submit"><br>
  </form>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<Script>
  $(function(){
  $("#addTitle").on('keyup', function(e){
        var keyCode = e.keyCode || e.which;
        if (keyCode == 13){
            console.log("ENTER PRESSED on input text");
        }
    });

  $('form').submit(function(e){
    e.preventDefault();
    if($(this).find('#addTitle').is(':focus') === false){
      doAjaxForm();
    }
  });

  function doAjaxForm(){
    console.log('do ajax form');
  }

})
  </script>
</code>```

if form submitted but #addTitle has focused = do nothing, then addTtitle keyup will do your job

if form submitted but #addTitle not focussed = do ajax form

if you press enter on another text input (except #addTitle) , this will trigger form submit = do ajax form

if submit button clicked = do ajax form

i hope this will work for you, since you dont give us your datatables script.

Body:
I have a table with filterable data using the jQuery DataTables library.
This table is inside a form that, when rows are CHECKED (in one column there is a checkbox), the SUBMIT button will add them to a collection.

Attached to the table is a custom search filter that functions like the built-in search filter that comes with DataTables, but instead of a "filter as you type" functionality, I have a submit button attached so that it will not filter the table results until you click the button.  There is some functionality added to that search filter that actually runs an ajax call to a database, and to reduce the amount of calls to the database, I put the button on the search filter and disabled the "filter as you type" functionality.

I STILL want to be able to click the ENTER key on my keyboard when I have finished typing in my search filter to execute this custom search, but I am unable to stop the form from submitting.  I have the custom search filter in a function called "tableFilter()". The ID of the form is "#addtitle"

$("#addTitle").on('keyup', function(e){
        var keyCode = e.keyCode || e.which;
        console.log('keyup');
        if (keyCode == 13){
            console.log('ENTER PRESSED');
            if ($("#dataTables_filter_input").is(":focus")){
                console.log('FILTER FOCUS');
                tableFilter();
                e.preventDefault();
                return false;
            }
        }
    });

I figured that if the input field of the search was still in focus, that would be enough of a difference for the code to know that when I click ENTER, it would execute the search filter and not submit the form - yet the form still submits.

Do I have things out of order? Am I not calling the right functions?

Body:
we must know the mechanical first.

<form>
<input type="text">
<input type="submit">
</form>

if you pressed ENTER in input text. it will trigger:

button submit clicked

form submitted

input text keyup [ENTER]

if you want prevent default behaviour. You must use preventDefault() on $('form').submit [only], in other word you dont  need type preventDefault() in $('input[type="submit"]').click or $('input[type="text"]').keyup

so, your jquery will like this

$('form').submit(function(e){
e.preventDefault();
})

$('input[type="text"]').keyup(function(e){
var keyCode = e.keyCode || e.which;
        if (keyCode == 13){
            //do something
        }
})

but you will never can use submit button to trigger form input. To do form submit you must use type="button" to trigger form submit.

Demo: http://jsbin.com/pirepahuhu/edit?html,output

===============

this what i think to force solved this problem

demo: http://jsbin.com/hiqatetoti/2/edit?html,output

<form>
    another text input<input type="text"><br>
    add title<input type="text" id="addTitle"><br>
    another text input<input type="text"><br>
    <input type="button" value="button"><br>
    <input type="submit" value="submit"><br>
  </form>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<Script>
  $(function(){
  $("#addTitle").on('keyup', function(e){
        var keyCode = e.keyCode || e.which;
        if (keyCode == 13){
            console.log("ENTER PRESSED on input text");
        }
    });

  $('form').submit(function(e){
    e.preventDefault();
    if($(this).find('#addTitle').is(':focus') === false){
      doAjaxForm();
    }
  });

  function doAjaxForm(){
    console.log('do ajax form');
  }

})
  </script>

if form submitted but #addTitle has focused = do nothing, then addTtitle keyup will do your job

if form submitted but #addTitle not focussed = do ajax form

if you press enter on another text input (except #addTitle) , this will trigger form submit = do ajax form

if submit button clicked = do ajax form

i hope this will work for you, since you dont give us your datatables script.


问:
issue with image_tag when using html in helper
I have a situation where I need to insert a part of the html inside an existing html block so I am trying first to create this html and as it will be used in many places hence I am using an helper to create this fragment
But the image_tag is throwing errors and it works perfectly if directly used in the view

my helper code

```<code>def create_banner_html_helper(banner)

    if banner.logo.present?
      return "<div class='m3-news_wrap m3-mdcast-banner slide'>
    <a href='" + banner.link_url + "' target=_'blank'>
    <div class='m3-article'>

<div class='m3-section m3-img_holder'>"
      image_tag banner.logo(:small)
      "</div>
    <div class='m3-section m3-desc'>
         <h3 class='m3-title'>" + banner.title+ "</h3>
                    <p>" + banner.subtitle + "</p>
         <a href='" + banner.link_url + "' target='_blank'>" + banner.link_text + "</a>
                  </div>
                </div>
              </a>".html_safe

    end

    return "<div class='m3-news_wrap m3-mdcast-banner slide'>
    <a href='" + banner.link_url + "' target=_'blank'>
    <div class='m3-article'>

    <div class='m3-section m3-desc'>
         <h3 class='m3-title'>" + banner.title+ "</h3>
                    <p>" + banner.subtitle + "</p>
         <a href='" + banner.link_url + "' target='_blank'>" + banner.link_text + "</a>
                  </div>
                </div>
              </a>".html_safe
  end
</code>```

banner passed is an ActiveRecord object.

I really don't know what is the issue so any help will be highly appreciated

答:
Thank you everybody for your efforts but I wanted to keep my view file clean and hence I put this code in a helper..

This is the code I am using and it might help somebody in future..

```<code>banner_logo_snippet = if self.logo.present?
        "<div class='m3-section m3-img_holder'><img src='#{self.logo(:small)}' /></div>"
      else
        ''
      end
      banner_snippet = <<"END"
  <div class="m3-news_wrap m3-mdcast-self slide" style="border: 1px solid ##{self.border_color}; background-color: ##{self.background_color};">
  <a href="#{self.link_url}" target="_blank">
    <div class="m3-article">
      #{banner_logo_snippet}
      <div class='m3-section m3-desc'>
        <h3 class='m3-title'>#{self.title}</h3>
        <p>#{self.subtitle}</p>
        <a href="#{self.link_url}" target="_blank">#{self.link_text}</a>
      </div>
    </div>
  </a>
</div>
END
</code>```

Thank you everybody for your time and cheers to the community..
Take care and happy coding

Body:
I have a situation where I need to insert a part of the html inside an existing html block so I am trying first to create this html and as it will be used in many places hence I am using an helper to create this fragment
But the image_tag is throwing errors and it works perfectly if directly used in the view

my helper code

def create_banner_html_helper(banner)

    if banner.logo.present?
      return "

"
      image_tag banner.logo(:small)
      "

" + banner.title+ "

" + banner.subtitle + "

         " + banner.link_text + "

              ".html_safe

    end

    return "

" + banner.title+ "

" + banner.subtitle + "

         " + banner.link_text + "

              ".html_safe
  end

banner passed is an ActiveRecord object.

I really don't know what is the issue so any help will be highly appreciated

Body:
Thank you everybody for your efforts but I wanted to keep my view file clean and hence I put this code in a helper..

This is the code I am using and it might help somebody in future..

banner_logo_snippet = if self.logo.present?
        "<div class='m3-section m3-img_holder'><img src='#{self.logo(:small)}' /></div>"
      else
        ''
      end
      banner_snippet = <<"END"
  <div class="m3-news_wrap m3-mdcast-self slide" style="border: 1px solid ##{self.border_color}; background-color: ##{self.background_color};">
  <a href="#{self.link_url}" target="_blank">
    <div class="m3-article">
      #{banner_logo_snippet}
      <div class='m3-section m3-desc'>
        <h3 class='m3-title'>#{self.title}</h3>
        <p>#{self.subtitle}</p>
        <a href="#{self.link_url}" target="_blank">#{self.link_text}</a>
      </div>
    </div>
  </a>
</div>
END

Thank you everybody for your time and cheers to the community..
Take care and happy coding


问:
Why is this only printing one letter every time I try?
```<code>from random import choice
print ("Enigma")

list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
range (0,25)

cha2 = choice(list)

complete = choice(list)

for x in range (0, 90000):
    ("Type alphabet")
    cha1=input()
    print (complete)
</code>```

When I run it and input an alphabet the same alphabet outputs as the first time. However I want it to output a different random alphabet each time I enter an alphabet. Thanks

答:
Chris_Rands has it right in the comments...

complete = choice(list) is the line that choose a letter to return, and you are only running it one time.  If you wanted it to run every time, you need to put it inside your while loop:

```<code>from random import choice
print ("Enigma")

list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

for x in range (0, 90000):
    ("Type alphabet")
    cha1=input()
    complete = choice(list) # This is the key change here
    print (complete)
</code>```

Body:
from random import choice
print ("Enigma")

list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
range (0,25)

cha2 = choice(list)

complete = choice(list)

for x in range (0, 90000):
    ("Type alphabet")
    cha1=input()
    print (complete)

When I run it and input an alphabet the same alphabet outputs as the first time. However I want it to output a different random alphabet each time I enter an alphabet. Thanks

Body:
Chris_Rands has it right in the comments...

complete = choice(list) is the line that choose a letter to return, and you are only running it one time.  If you wanted it to run every time, you need to put it inside your while loop:

from random import choice
print ("Enigma")

list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

for x in range (0, 90000):
    ("Type alphabet")
    cha1=input()
    complete = choice(list) # This is the key change here
    print (complete)


问:
Ruby - How do you perform an operation on each item of two (maybe more) arrays and populate them in a new array?
```<code>a = [6, 7, 8, 9, 10]
b = [1, 2, 3, 4, 5]
</code>```

each of array a's items are divided by each of array b's items and put into a new array called c.

```<code>c = [6, 3, 2, 2, 2]
</code>```

答:
```<code>a = [6, 7, 8, 9, 10]
b = [1, 2, 3, 4, 5]

c = a.zip(b).map { |e| e.reduce :/ }
#⇒  [
#    [0] 6,
#    [1] 3,
#    [2] 2,
#    [3] 2,
#    [4] 2
# ]
</code>```

Array#zip zips the arrays together and then each element (array of 2 items zipped) is reduced with Integer#/.

Body:
a = [6, 7, 8, 9, 10]
b = [1, 2, 3, 4, 5]

each of array a's items are divided by each of array b's items and put into a new array called c.

c = [6, 3, 2, 2, 2]

Body:
a = [6, 7, 8, 9, 10]
b = [1, 2, 3, 4, 5]

c = a.zip(b).map { |e| e.reduce :/ }
#⇒  [
#    [0] 6,
#    [1] 3,
#    [2] 2,
#    [3] 2,
#    [4] 2
# ]

Array#zip zips the arrays together and then each element (array of 2 items zipped) is reduced with Integer#/.


问:
UIImageView not updating with new image after picture taken or picture chosen from photo library
I'm trying to populate an image within a UIImageView after I either take a picture or choose a picture from my photo library.

here is the code handling the camera and photo library activations:

```<code>@IBAction func activateCmera(_ sender: Any) {
    if (UIImagePickerController.isSourceTypeAvailable(.camera)) {
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = .camera
        imagePicker.allowsEditing = false
        self.present(imagePicker, animated: true, completion: nil)
    }
}

@IBAction func activatePhotoLib(_ sender: Any) {
    if (UIImagePickerController.isSourceTypeAvailable(.photoLibrary)) {
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = .photoLibrary
        imagePicker.allowsEditing = false
        self.present(imagePicker, animated: true, completion: nil)
    }
}
</code>```

Here is the code that populates the image within the UIImageView:

```<code>@IBOutlet weak var imageView: UIImageView!

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
    let image = info[UIImagePickerControllerOriginalImage] as! UIImage
    self.imageView.contentMode = .scaleAspectFit
    self.imageView.image = image
    self.dismiss(animated: true, completion: nil);
}
</code>```

currently after I take a picture with my camera or choose an image from my photo library, I'm redirected to the initial view of the app without UIImageView space updated with the photo.

Any help is appreciated thanks!

答:
**You need to save the UIImagePickerController like Global Object, after that, you need push this code on your action function
 **  </p>

```<code>@objc func getImage() {

    imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary

    imagePicker.allowsEditing = false

    imagePicker.modalPresentationStyle = .overCurrentContext

    present(imagePicker, animated: true)

}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

    if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
    imageView.image = image
 }

self.dismiss(animated: true, completion: nil);

}
</code>```

Body:
I'm trying to populate an image within a UIImageView after I either take a picture or choose a picture from my photo library.

here is the code handling the camera and photo library activations:

@IBAction func activateCmera(_ sender: Any) {
    if (UIImagePickerController.isSourceTypeAvailable(.camera)) {
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = .camera
        imagePicker.allowsEditing = false
        self.present(imagePicker, animated: true, completion: nil)
    }
}

@IBAction func activatePhotoLib(_ sender: Any) {
    if (UIImagePickerController.isSourceTypeAvailable(.photoLibrary)) {
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = .photoLibrary
        imagePicker.allowsEditing = false
        self.present(imagePicker, animated: true, completion: nil)
    }
}

Here is the code that populates the image within the UIImageView:

@IBOutlet weak var imageView: UIImageView!

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
    let image = info[UIImagePickerControllerOriginalImage] as! UIImage
    self.imageView.contentMode = .scaleAspectFit
    self.imageView.image = image
    self.dismiss(animated: true, completion: nil);
}

currently after I take a picture with my camera or choose an image from my photo library, I'm redirected to the initial view of the app without UIImageView space updated with the photo.

Any help is appreciated thanks!

Body:
**You need to save the UIImagePickerController like Global Object, after that, you need push this code on your action function
 **

@objc func getImage() {

    imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary

    imagePicker.allowsEditing = false

    imagePicker.modalPresentationStyle = .overCurrentContext

    present(imagePicker, animated: true)

}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

    if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
    imageView.image = image
 }

self.dismiss(animated: true, completion: nil);

}


答:
I have fixed my problem by adding this option in my global.R script before calling the libraries:

```<code>options(java.parameters = "-Xss2048k")
</code>```

It is linked with problem using the package "xlsx".

Title: Can't find error in shinyapp

Body:
I have been trying to resolve my problem for 2 days but I am blocked.
I have used many techniques to trace and find my errors. I can't resole the last one.
I can't show you my app (because of info which is protected) but I could show you my log :

   2017-11-17T12:30:42.395529+00:00 shinyapps[236114]: RECV {"method":"update","data":{"Refresh:shiny.action":2}}
2017-11-17T12:30:42.399510+00:00 shinyapps[236114]: SEND {"custom":{"shinyjs-enable":{"id":"resCheck1"}}}
2017-11-17T12:30:42.400628+00:00 shinyapps[236114]: SEND {"custom":{"shinyjs-enable":{"id":"resCheck2"}}}
2017-11-17T12:30:42.401726+00:00 shinyapps[236114]: SEND {"custom":{"shinyjs-disable":{"id":"resCheck3"}}}
2017-11-17T12:30:42.402768+00:00 shinyapps[236114]: SEND {"custom":{"shinyjs-disable":{"id":"resCheck4"}}}
2017-11-17T12:30:42.403806+00:00 shinyapps[236114]: SEND {"custom":{"shinyjs-disable":{"id":"resCheck5"}}}
2017-11-17T12:30:42.404840+00:00 shinyapps[236114]: SEND {"custom":{"shinyjs-disable":{"id":"resCheck6"}}}
2017-11-17T12:30:42.409212+00:00 shinyapps[236114]: SEND {"custom":{"shinyjs-show":{"id":"Table1"}}}
2017-11-17T12:30:42.410277+00:00 shinyapps[236114]: SEND {"custom":{"shinyjs-show":{"id":"Table2"}}}
2017-11-17T12:30:42.411293+00:00 shinyapps[236114]: SEND {"custom":{"shinyjs-show":{"id":"Table3"}}}
2017-11-17T12:30:42.412261+00:00 shinyapps[236114]: SEND {"custom":{"shinyjs-show":{"id":"Table4"}}}
2017-11-17T12:30:42.413233+00:00 shinyapps[236114]: SEND {"custom":{"shinyjs-show":{"id":"Table5"}}}
2017-11-17T12:30:42.414218+00:00 shinyapps[236114]: SEND {"custom":{"shinyjs-show":{"id":"Table6"}}}
2017-11-17T12:30:42.415206+00:00 shinyapps[236114]: SEND {"custom":{"shinyjs-show":{"id":"Table7"}}}
2017-11-17T12:30:42.988820+00:00 shinyapps[236114]: Warning: Specifying width/height in layout() is now deprecated.
2017-11-17T12:30:42.990293+00:00 shinyapps[236114]: Warning in origRenderFunc() :
2017-11-17T12:30:42.989834+00:00 shinyapps[236114]: SEND {"progress":{"type":"close","message":{"id":"18d29890333552a1","style":"notification"}}}
2017-11-17T12:30:42.988824+00:00 shinyapps[236114]: Please specify in ggplotly() or plot_ly()
2017-11-17T12:30:42.990320+00:00 shinyapps[236114]:   Ignoring explicitly provided widget ID "10958d701"; Shiny doesn't use them
2017-11-17T12:30:43.073852+00:00 shinyapps[236114]: SEND {"recalculating":{"name":"plot2","status":"recalculating"}}
2017-11-17T12:30:43.061909+00:00 shinyapps[236114]: SEND {"recalculating":{"name":"resultatNull1","status":"recalculating"}}
2017-11-17T12:30:43.060594+00:00 shinyapps[236114]: SEND {"recalculating":{"name":"plot1","status":"recalculated"}}
2017-11-17T12:30:43.071686+00:00 shinyapps[236114]: SEND {"recalculating":{"name":"table2","status":"recalculating"}}
2017-11-17T12:30:43.070562+00:00 shinyapps[236114]: SEND {"recalculating":{"name":"resultatNull1","status":"recalculated"}}
2017-11-17T12:30:43.072729+00:00 shinyapps[236114]: SEND {"recalculating":{"name":"table2","status":"recalculated"}}
2017-11-17T12:30:43.075189+00:00 shinyapps[236114]: SEND {"progress":{"type":"open","message":{"id":"fc51ab4582ef7a14","style":"notification"}}}
2017-11-17T12:30:43.076200+00:00 shinyapps[236114]: SEND {"progress":{"type":"update","message":{"id":"fc51ab4582ef7a14","message":"Patientez quelques instants...","style":"notification"}}}
2017-11-17T12:30:43.152755+00:00 shinyapps[236114]: We recommend that you use the dev version of ggplot2 with `ggplotly()`
2017-11-17T12:30:43.152758+00:00 shinyapps[236114]: Install it with: `devtools::install_github('hadley/ggplot2')`

When I click on the button refresh my outputs are done. But when I click after that without changing any inputs, the application is stopped.

Many thanks!

Body:
I have fixed my problem by adding this option in my global.R script before calling the libraries:

options(java.parameters = "-Xss2048k")

It is linked with problem using the package "xlsx".


问:
Worker spark webUI is not working in Apache Spark
I have installed spark in 3 ubuntu VM's, 1 is control node and 2 data node. After starting all nodes by sbin/start-master.sh and sbin/start-slaves.sh Master webUI working but while we click the worker node WebUI not loading showing error in picture`Master webUIWorker webUI</p>

答:
Possible reasons to cause this problem:

1.First you try to start the slave nodes with spark master URL as follows.
./sbin/start-slave.sh  spark://:7077

If above fix does not resolve the issue, try to fix it by accessing the worker UI with actual IP as 192.168.x.x instead of 127.0.0.1

If above steps are not resolving the issue just follow the below instructions, http://chennaihug.org/knowledgebase/spark-master-and-slaves-multi-node-installation/


问:
Moving business rules into model
I asked a question earlier which elicited some great responses.

Here's the earlier question

On the back of some advice given there, I've tried moving the following controller logic

```<code> if params[:concept][:consulted_legal] == 0 && params[:concept][:consulted_marketing] == 1
  @concept.attributes = {:status => 'Awaiting Compliance Approval'}
elsif params[:concept][:consulted_marketing] == 0 && params[:concept][:consulted_legal] == 1
  @concept.attributes = {:status => 'Awaiting Marketing Approval'}
elsif params[:concept][:consulted_marketing] == 0 && params[:concept][:consulted_legal] == 0
  @concept.attributes = {:status => 'Awaiting Marketing & Legal Approval'}
else
  @concept.attributes = {:status => 'Pending Approval'}
end
</code>```

into the model, as so:

```<code>def set_status
if status.blank?
  if (consulted_legal == true) && (consulted_marketing == true)
      status = "Pending Approval"
  elsif (consulted_legal == true) && (consulted_marketing == false)
    status = "Awaiting Marketing Approval"
  elsif (consulted_legal == false) && (consulted_marketing == true)
    status = "Awaiting Legal Approval"
  elsif (consulted_legal == false) && (consulted_marketing == false)
    status = "Awaiting Marketing & Legal Approval"
  end
end
true # Needs to return true for the update to go through
  end
</code>```

I am calling that from a before_save callback.

As a default, both the consulted_legal and consulted_marketing attributes are set to false and not null, which is why I am testing for == false or true here, instead of asking

```<code>if consulted_legal?
</code>```

for instance.

However, this logic doesn't seem to be working. If I inspect the object, status is not being set to anything, ever. Can anyone spot why this might be happening? Have I got how attributes are accessed wrong in models, for instance?

TIA

答:
Are you setting the parameters from user input?

If they're not defined as boolean database columns, then you'll be assigning a string to them, which will never be equal to true.

OwnerDisplayName: The Pied Pipes

Title: Moving business rules into model

Body:
I asked a question earlier which elicited some great responses.

Here's the earlier question

On the back of some advice given there, I've tried moving the following controller logic

 if params[:concept][:consulted_legal] == 0 && params[:concept][:consulted_marketing] == 1
  @concept.attributes = {:status => 'Awaiting Compliance Approval'}
elsif params[:concept][:consulted_marketing] == 0 && params[:concept][:consulted_legal] == 1
  @concept.attributes = {:status => 'Awaiting Marketing Approval'}
elsif params[:concept][:consulted_marketing] == 0 && params[:concept][:consulted_legal] == 0
  @concept.attributes = {:status => 'Awaiting Marketing & Legal Approval'}
else
  @concept.attributes = {:status => 'Pending Approval'}
end

into the model, as so:

def set_status
if status.blank?
  if (consulted_legal == true) && (consulted_marketing == true)
      status = "Pending Approval"
  elsif (consulted_legal == true) && (consulted_marketing == false)
    status = "Awaiting Marketing Approval"
  elsif (consulted_legal == false) && (consulted_marketing == true)
    status = "Awaiting Legal Approval"
  elsif (consulted_legal == false) && (consulted_marketing == false)
    status = "Awaiting Marketing & Legal Approval"
  end
end
true # Needs to return true for the update to go through
  end

I am calling that from a before_save callback.

As a default, both the consulted_legal and consulted_marketing attributes are set to false and not null, which is why I am testing for == false or true here, instead of asking

if consulted_legal?

for instance.

However, this logic doesn't seem to be working. If I inspect the object, status is not being set to anything, ever. Can anyone spot why this might be happening? Have I got how attributes are accessed wrong in models, for instance?

TIA


问:
MySQL: Select from table A, if ID matches 2 (or arbitrary n) rows in table B
The scenario is quite straight forward: I have content in table A and tags for contents in table B:

```<code>Table A:
+----+-------+-...
| id | title | ...
+----+-------+-...

Table B:
+------+-----+
| id_A | tag |
+------+-----+
</code>```

I want to select all content rows in A, that have tag 'foo':

```<code>SELECT A.* FROM A, B WHERE A.id = B.id_A AND B.tag = 'foo'
</code>```

So far, that's simple.

My problem is: How can I select content rows, that have both tag 'foo' and tag 'bar'? Especially, how can I select rows that have n tags 'foo', 'bar', ... for arbitrary n > 1?

A solution would be to join B n times, but that feels bad, and I assume, that it's not really performant.

Since I use MySQL, PHP and PDO with prepared statements, if there is a solution that goes without necessary string concatenation (like in the 'Join n times' solution) in the PHP part, that would be my favourite.

答:
```<code>SELECT  *
FROM    a
WHERE   (
        SELECT  COUNT(*)
        FROM    b
        WHERE   b.id_a = a.id
                AND b.tag IN ('foo', 'bar', 'baz')
        ) = 3
</code>```

Body:
The scenario is quite straight forward: I have content in table A and tags for contents in table B:

Table A:
+----+-------+-...
| id | title | ...
+----+-------+-...

Table B:
+------+-----+
| id_A | tag |
+------+-----+

I want to select all content rows in A, that have tag 'foo':

SELECT A.* FROM A, B WHERE A.id = B.id_A AND B.tag = 'foo'

So far, that's simple.

My problem is: How can I select content rows, that have both tag 'foo' and tag 'bar'? Especially, how can I select rows that have n tags 'foo', 'bar', ... for arbitrary n > 1?

A solution would be to join B n times, but that feels bad, and I assume, that it's not really performant.

Since I use MySQL, PHP and PDO with prepared statements, if there is a solution that goes without necessary string concatenation (like in the 'Join n times' solution) in the PHP part, that would be my favourite.


问:
How to get message of alert dialog?
How to capture message of alert dialog using dotnetbrowser ? I have tried to capture message using CustomDialogHandler.customDialogueParams_OnAlert, but still not getting any message.</p>

答: The following article demonstrates how to catch and customize the JavaScript Alert dialog by registering custom DialogHandler implementation:  https://dotnetbrowser.support.teamdev.com/solution/articles/9000109867-winforms-customizing-javascript-dialogs

Title: How to get message of alert dialog?


问:
SPA vs MPA || React-Router vs ExpressJs
Could you please explain me why would I use React-Router vs when ExpressJs. I somewhat understand React-Router does client side rendering which is good for SPA, whereas Express is for MPA. However I can't get the grasp as of WHEN should I be using which, I would be greatly appreciated if you could give an insight on this. Thanks. </p>

答:
ExpressJS is a nodejs library for building web servers. Express has routing capabilities but this is for server side HTTP calls, where as react-router is for frontend application routing.

React-router will tell you which part of your application to display, components within that application may make HTTP calls to your server, ExpressJS will receive these requests and route them off to the particular middleware / controllers that should handle that request.

They are two very separate things, one is client side and one is server side, you will find that you'll need both for your application. React-Router indicates what to display on the frontend, where as ExpressJS's router will direct HTTP calls to the appropriate request handler.

ExpressJS is simply a HTTP server package built for nodejs and is not restricted to the type of application wish to build. You can use templating and build a multi-page application, or you can just build HTTP API endpoints and use those to service a single page application.

I'd recommend taking a few tutorials around nodejs and Express, this will help you build a foundation of knowledge around the split between server-side and client-side services.

Title: SPA vs MPA || React-Router vs ExpressJs


问:
Do I violate the abstraction law?
I have two variables, the first with the type Either String Int and the second with the type IO (Either String Int).

As you can see, the structure of two variables are almost the same, except the second is wrapped into IO.

To make it composable, I am planing to lift both into MonadTransformer EitherT, but the first variable I have to lift into IO.

Is it wrong to lift the first variable into IO to make it composable, although there has no side effect happened on it.

It is just about to put into IO context.

答: No, it is not wrong; in fact, it is encouraged.</p>

Title: Do I violate the abstraction law?