问:
Update whole child element of an array field of an document in mongodb nodejs
Considering the following document, i want to update whole field of dataset with _id:123,

```<code>  "data": {
            "_id": "1234546",
            "dataset": [
                {
                    "_id": "123",
                    "el2": "asd",
                    "el3": "sd",
                    "el4": "gfdd",
                    "el5": "asdfa",
                },
                {
                    "_id": "787",
                    "el2": "asd",
                    "el3": "sd",
                    "el4": "gfdd",
                    "el5": "asdfa",
                },
                {
                    "_id": "898",
                    "el2": "asd",
                    "el3": "sd",
                    "el4": "gfdd",
                    "el5": "asdfa",
                },
                {
                    "_id": "564",
                    "el2": "asd",
                    "el3": "sd",
                    "el4": "gfdd",
                    "el5": "asdfa",
                },
            ]
        }
</code>```

I want to update all fields of an array element by using _id of field.

I am using

```<code>    getDB.collection ('data').findOneAndUpdate(
    { _id: new ObjectId(data.userId),
        "dataset._id":new ObjectId(data.dataset),
    },
    { $set: { "userAddress.$":newdataset } },
    {returnOriginal:false}});
</code>```

Please suggest some good option to update it.

Thanks in advance.. :)

答:
If you want to just update the document on the db server without fetching it, you could use update instead of findOneAndUpdate.

Here a way to do it.

```<code>collection('data').update({
      _id:<_id>,
      "dataset._id":<dataset._id>
    },{
      $set:{
        "dataset.$.el2":<el2>,
        "dataset.$.el3":<el3>,
        "dataset.$.el4":<el4>,
        "dataset.$.el5":<el5>
      }
    })
</code>```

Body:
Considering the following document, i want to update whole field of dataset with _id:123,

  "data": {
            "_id": "1234546",
            "dataset": [
                {
                    "_id": "123",
                    "el2": "asd",
                    "el3": "sd",
                    "el4": "gfdd",
                    "el5": "asdfa",
                },
                {
                    "_id": "787",
                    "el2": "asd",
                    "el3": "sd",
                    "el4": "gfdd",
                    "el5": "asdfa",
                },
                {
                    "_id": "898",
                    "el2": "asd",
                    "el3": "sd",
                    "el4": "gfdd",
                    "el5": "asdfa",
                },
                {
                    "_id": "564",
                    "el2": "asd",
                    "el3": "sd",
                    "el4": "gfdd",
                    "el5": "asdfa",
                },
            ]
        }

I want to update all fields of an array element by using _id of field.

I am using

    getDB.collection ('data').findOneAndUpdate(
    { _id: new ObjectId(data.userId),
        "dataset._id":new ObjectId(data.dataset),
    },
    { $set: { "userAddress.$":newdataset } },
    {returnOriginal:false}});

Please suggest some good option to update it.

Thanks in advance.. :)

Body:
If you want to just update the document on the db server without fetching it, you could use update instead of findOneAndUpdate.

Here a way to do it.

collection('data').update({
      _id:<_id>,
      "dataset._id":<dataset._id>
    },{
      $set:{
        "dataset.$.el2":<el2>,
        "dataset.$.el3":<el3>,
        "dataset.$.el4":<el4>,
        "dataset.$.el5":<el5>
      }
    })


来源: stackexchange

问:
"Unfortunately Design1 has stopped"
I am new in Android. My app name is Design1 My app is running successfully in Emulator. I copied the apk file from C:\Users\Rahul\AndroidStudioProjects\Design1\app\build\outputs\apk to my phone and installed it there. But when I try to open the app in my ASUS ZENFONE MAX phone I got a message that "Unfortunately Design1 1 has stopped". I have checked logcat and set the dropdown to ERROR to see if any error occurs or not. But no errors I got when running in simulator. Please tell if there any specific way to build the APK file or I can directly copy from apk file location. If the app is running in emulator then why it is not running in my phone.

答:
May you have have Enabled Instant run just Disable it

First Disable Instant run than Build apk

File → Settings → Build, Execution, Deployment → Instant Run and uncheck Disable Instant Run.

ContentLicense: CC BY-SA 3.0

Title: "Unfortunately Design1 has stopped"


问:
How to count the checkboxes in a asp.net form
ASP.NET:

```<code><asp:Panel ID="pnlFilter" runat="server">
    <div class="dvFilter">
        <input type="checkbox" id="cb01" checked="checked" />
        <label for="cb01">All</label>
    </div>
    <div class="dvFilter">
        <input type="checkbox" id="cb02" checked="checked" />
        <label for="cb02">None</label>
    </div>
</asp:Panel>
</code>```

C#:

```<code>foreach (Control item in this.form1.Controls)
{
    System.Web.UI.HtmlControls.HtmlInputCheckBox _cbx = item as System.Web.UI.HtmlControls.HtmlInputCheckBox;
    if (_cbx != null)
    {
        if (_cbx.Checked)
        {
            //Do something:
            Response.Write(_cbx.Name + " was checked.<br />");
        }
    }

}
</code>```

I am getting a null value for the _cbx variable.

How can I update it so I am able to get the ID of all the checked input type checkboxes.

I tried this answer: Count the number of TextBoxes and CheckBoxes in a form but didn't work for me either.

答:
I think it would be better to access front-end stuff by front-end process.

For example, collect checked checkbox ids you need by JQuery and save them inside HiddenField then get it back-end by request.

Instance

```<code><asp:Panel ID="pnlFilter" runat="server">
    <div class="dvFilter">
        <input type="checkbox" id="cb01" checked="checked" />
        <label for="cb01">All</label>
    </div>
    <div class="dvFilter">
        <input type="checkbox" id="cb02" checked="checked" />
        <label for="cb02">None</label>
    </div>
    <input type="hidden" id="hdfIds" name="hdfIds" />
</asp:Panel>
<asp:Button ID="Button1" runat="server" Text="Button" />
</code>```

JQuery part(link JQuery & json2 lib first)

```<code>function recoverCbxStatus() {
    if (hdfIds.value) {
        var ids = JSON.parse(hdfIds.value);
        ids.forEach(function (id) {
            $('#' + id).prop('checked', true);
        });
    }
}

function refreshIds() {
    var ids = [];
    $('input:checkbox[id^="cb"]:checked').each(function () {
        ids.push($(this).attr("id"));
    });
    hdfIds.value = JSON.stringify(ids);
}

$(document).ready(function () {
    recoverCbxStatus();
    refreshIds();
});

$('input:checkbox[id^="cb"]').change(function () {
    refreshIds();
});
</code>```

Back-end(Nuget Json.NET)

```<code>protected void Page_Load(object sender, EventArgs e)
{
    string idsJson = Request["hdfIds"];
    List<string> ids;
    if (idsJson != null)
    {
        ids = JsonConvert.DeserializeObject<List<string>>(idsJson);
        Response.Write("count: " + ids.Count);
    }
}
</code>```

Body:
ASP.NET:

<asp:Panel ID="pnlFilter" runat="server">

        <input type="checkbox" id="cb01" checked="checked" />
        All

        <input type="checkbox" id="cb02" checked="checked" />
        None

</asp:Panel>

C#:

foreach (Control item in this.form1.Controls)
{
    System.Web.UI.HtmlControls.HtmlInputCheckBox _cbx = item as System.Web.UI.HtmlControls.HtmlInputCheckBox;
    if (_cbx != null)
    {
        if (_cbx.Checked)
        {
            //Do something:
            Response.Write(_cbx.Name + " was checked.
");
        }
    }

}

I am getting a null value for the _cbx variable.

How can I update it so I am able to get the ID of all the checked input type checkboxes.

I tried this answer: Count the number of TextBoxes and CheckBoxes in a form but didn't work for me either.

Body:
I think it would be better to access front-end stuff by front-end process.

For example, collect checked checkbox ids you need by JQuery and save them inside HiddenField then get it back-end by request.

Instance

<asp:Panel ID="pnlFilter" runat="server">
    <div class="dvFilter">
        <input type="checkbox" id="cb01" checked="checked" />
        <label for="cb01">All</label>
    </div>
    <div class="dvFilter">
        <input type="checkbox" id="cb02" checked="checked" />
        <label for="cb02">None</label>
    </div>
    <input type="hidden" id="hdfIds" name="hdfIds" />
</asp:Panel>
<asp:Button ID="Button1" runat="server" Text="Button" />

JQuery part(link JQuery & json2 lib first)

function recoverCbxStatus() {
    if (hdfIds.value) {
        var ids = JSON.parse(hdfIds.value);
        ids.forEach(function (id) {
            $('#' + id).prop('checked', true);
        });
    }
}

function refreshIds() {
    var ids = [];
    $('input:checkbox[id^="cb"]:checked').each(function () {
        ids.push($(this).attr("id"));
    });
    hdfIds.value = JSON.stringify(ids);
}

$(document).ready(function () {
    recoverCbxStatus();
    refreshIds();
});

$('input:checkbox[id^="cb"]').change(function () {
    refreshIds();
});

Back-end(Nuget Json.NET)

protected void Page_Load(object sender, EventArgs e)
{
    string idsJson = Request["hdfIds"];
    List<string> ids;
    if (idsJson != null)
    {
        ids = JsonConvert.DeserializeObject<List<string>>(idsJson);
        Response.Write("count: " + ids.Count);
    }
}


问:
Python Tkinter error with button commands
Hi I was trying to make simple calculator using tkinter gui with python.
But first of all I was trying to create buttons that once they are clicked, they were attached to the result shown on the screen. (Just as real-life calculator, if screen shows 12 and I click 3, the screen then shows 123)

```<code>from Tkinter import *
class Calculator(Frame):

    def __init__(self):
        Frame.__init__(self)
        self.master.title('Calculator')
        self.pack()

        self.screen=Frame(self, borderwidth=20, relief=SUNKEN)
        self.screen.pack()
        self.txtDisplay = Text(self.screen, width=20, height=2)
        self.txtDisplay.pack()
        self.screen.grid(row=0, columnspan=5) #columnspan to span multiple columns

        Contents = ['1','2','3','+','4','5','6','-','7','8','9','*','C','0','=','/']
        Buttons = [None]*16
        j=1
        count=0
        for i in range(16):
            Buttons[i]=Button(self, text=Contents[i], command=lambda : self.txtDisplay.insert(END, Contents[i]), height=2, width=5, borderwidth=5)
            Buttons[i].grid(row=j, column=i%4)
            count+=1
            if count%4==0:
                j+=1
                count=0

Calculator().mainloop()
</code>```

However, the problem is the screen only attaches / whenever I click any button and eventually results in //////////////

/ is last element of Contents list and I guess there is something wrong with

```<code>command=lambda : self.txtDisplay.insert(END, Contents[i])
</code>```

Can I get explanation on why this occurs and how I can deal with it?

答:
Very problem problem with lambda in for loop. You can find many answers.

lambda doesn't use value from i when you create button but when you press button - so all buttons use the same value i which directs to last button.

You have to assign i to argument in lambda and it will copy value from i when you create button

```<code>command=lambda x=i: self.txtDisplay.insert(END, Contents[x])
</code>```

Body:
Hi I was trying to make simple calculator using tkinter gui with python.
But first of all I was trying to create buttons that once they are clicked, they were attached to the result shown on the screen. (Just as real-life calculator, if screen shows 12 and I click 3, the screen then shows 123)

from Tkinter import *
class Calculator(Frame):

    def __init__(self):
        Frame.__init__(self)
        self.master.title('Calculator')
        self.pack()

        self.screen=Frame(self, borderwidth=20, relief=SUNKEN)
        self.screen.pack()
        self.txtDisplay = Text(self.screen, width=20, height=2)
        self.txtDisplay.pack()
        self.screen.grid(row=0, columnspan=5) #columnspan to span multiple columns

        Contents = ['1','2','3','+','4','5','6','-','7','8','9','*','C','0','=','/']
        Buttons = [None]*16
        j=1
        count=0
        for i in range(16):
            Buttons[i]=Button(self, text=Contents[i], command=lambda : self.txtDisplay.insert(END, Contents[i]), height=2, width=5, borderwidth=5)
            Buttons[i].grid(row=j, column=i%4)
            count+=1
            if count%4==0:
                j+=1
                count=0

Calculator().mainloop()

However, the problem is the screen only attaches / whenever I click any button and eventually results in //////////////

/ is last element of Contents list and I guess there is something wrong with

command=lambda : self.txtDisplay.insert(END, Contents[i])

Can I get explanation on why this occurs and how I can deal with it?

Body:
Very problem problem with lambda in for loop. You can find many answers.

lambda doesn't use value from i when you create button but when you press button - so all buttons use the same value i which directs to last button.

You have to assign i to argument in lambda and it will copy value from i when you create button

command=lambda x=i: self.txtDisplay.insert(END, Contents[x])


问:
Scala manifest not Found Spark Streaming
I'm new to Spark Streaming,
From Spark Streaming I created a direct stream to Kafka Using KafkaUtils. like below

```<code>jssc = new JavaStreamingContext(sparkConf, Durations.seconds(KafkaConfig.getInstance().getBatchDuration()));

HashMap<String, String> kafkaParams = new HashMap<>();

kafkaParams.put(KafkaConstants.ZOOKEEPER_CONNECTION_STRING, zookeeperHost + ":" + zookeeperPort);
kafkaParams.put(KafkaConstants.METADATA_BROKER_LIST_STRING, bootstrapHost  + ":" + bootstrapPort);
kafkaParams.put(KafkaConstants.GROUP_ID_STRING, groupId);

HashSet<String> topicSet = new HashSet<String>();
topicSet.add(topic);

JavaPairInputDStream<String, String> topicStream = KafkaUtils.createDirectStream(jssc, String.class,
        String.class, StringDecoder.class, StringDecoder.class, kafkaParams, topicSet);

JavaDStream<String> topicMessages = topicStream.map(Tuple2::_2);
topicMessages.print()
</code>```

When I tried to run the job It is throwing below error

java.lang.NoClassDefFoundError: scala/reflect/ClassManifest

Full Stack is here :

Exception in thread "main" java.lang.NoClassDefFoundError:
  scala/reflect/ClassManifest   at
  kafka.utils.Log4jController$.(Log4jController.scala:29)     at
  kafka.utils.Log4jController$.(Log4jController.scala)  at
  kafka.utils.Logging$class.$init$(Logging.scala:29)    at
  kafka.api.TopicMetadataRequest$.(TopicMetadataRequest.scala:28)
    at
  kafka.api.TopicMetadataRequest$.(TopicMetadataRequest.scala)
    at
  org.apache.spark.streaming.kafka.KafkaCluster.getPartitionMetadata(KafkaCluster.scala:130)
    at
  org.apache.spark.streaming.kafka.KafkaCluster.getPartitions(KafkaCluster.scala:119)
    at
  org.apache.spark.streaming.kafka.KafkaUtils$.getFromOffsets(KafkaUtils.scala:211)
    at
  org.apache.spark.streaming.kafka.KafkaUtils$.createDirectStream(KafkaUtils.scala:484)
    at
  org.apache.spark.streaming.kafka.KafkaUtils$.createDirectStream(KafkaUtils.scala:607)
    at
  org.apache.spark.streaming.kafka.KafkaUtils.createDirectStream(KafkaUtils.scala)
    at
  consumer.spark.KafkaConsumer.consumeMessages(KafkaConsumer.java:103)
    at consumer.spark.KafkaConsumer.executeStream(KafkaConsumer.java:142)
    at
  consumer.spark.KafkaConsumerService.main(KafkaConsumerService.java:27)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)  at
  sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)     at
  org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:743)
    at
  org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:187)
    at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:212)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:126)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala) Caused
  by: java.lang.ClassNotFoundException: scala.reflect.ClassManifest     at
  java.net.URLClassLoader.findClass(URLClassLoader.java:381)    at
  java.lang.ClassLoader.loadClass(ClassLoader.java:424)     at
  java.lang.ClassLoader.loadClass(ClassLoader.java:357)     ... 23 more

Here is my pom.xml

```<code><!-- Scala version -->
<dependency>
    <groupId>org.scala-lang</groupId>
    <artifactId>scala-library</artifactId>
    <version>2.10.3</version>
</dependency>

<!--Spark Core -->
<!-- https://mvnrepository.com/artifact/org.apache.spark/spark-core_2.11 -->
<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-core_2.11</artifactId>
    <version>2.1.1</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.spark/spark-streaming-kafka-0-8_2.11 -->
<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-streaming-kafka-0-8_2.11</artifactId>
    <version>2.1.1</version>
</dependency>

<!--Spark Streaming -->
<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-streaming_2.11</artifactId>
    <version>2.1.1</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.spark/spark-hive_2.10 -->
<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-hive_2.11</artifactId>
    <version>2.1.1</version>
</dependency>

<!--Kafka -->
<dependency>
    <groupId>org.apache.kafka</groupId>
    <artifactId>kafka_2.11</artifactId>
    <version>0.8.2.1</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.spark/spark-sql_2.10 -->
<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-sql_2.11</artifactId>
    <version>2.1.1</version>
</dependency>
</code>```

Please let me know how to resolve this.

答: change scala version to 2.11 in your pom.xml it will work</p>

Body:
I'm new to Spark Streaming,
From Spark Streaming I created a direct stream to Kafka Using KafkaUtils. like below

jssc = new JavaStreamingContext(sparkConf, Durations.seconds(KafkaConfig.getInstance().getBatchDuration()));

HashMap<String, String> kafkaParams = new HashMap<>();

kafkaParams.put(KafkaConstants.ZOOKEEPER_CONNECTION_STRING, zookeeperHost + ":" + zookeeperPort);
kafkaParams.put(KafkaConstants.METADATA_BROKER_LIST_STRING, bootstrapHost  + ":" + bootstrapPort);
kafkaParams.put(KafkaConstants.GROUP_ID_STRING, groupId);

HashSet<String> topicSet = new HashSet<String>();
topicSet.add(topic);

JavaPairInputDStream<String, String> topicStream = KafkaUtils.createDirectStream(jssc, String.class,
        String.class, StringDecoder.class, StringDecoder.class, kafkaParams, topicSet);

JavaDStream<String> topicMessages = topicStream.map(Tuple2::_2);
topicMessages.print()

When I tried to run the job It is throwing below error

java.lang.NoClassDefFoundError: scala/reflect/ClassManifest

Full Stack is here :

Exception in thread "main" java.lang.NoClassDefFoundError:
  scala/reflect/ClassManifest   at
  kafka.utils.Log4jController$.(Log4jController.scala:29)     at
  kafka.utils.Log4jController$.(Log4jController.scala)  at
  kafka.utils.Logging$class.$init$(Logging.scala:29)    at
  kafka.api.TopicMetadataRequest$.(TopicMetadataRequest.scala:28)
    at
  kafka.api.TopicMetadataRequest$.(TopicMetadataRequest.scala)
    at
  org.apache.spark.streaming.kafka.KafkaCluster.getPartitionMetadata(KafkaCluster.scala:130)
    at
  org.apache.spark.streaming.kafka.KafkaCluster.getPartitions(KafkaCluster.scala:119)
    at
  org.apache.spark.streaming.kafka.KafkaUtils$.getFromOffsets(KafkaUtils.scala:211)
    at
  org.apache.spark.streaming.kafka.KafkaUtils$.createDirectStream(KafkaUtils.scala:484)
    at
  org.apache.spark.streaming.kafka.KafkaUtils$.createDirectStream(KafkaUtils.scala:607)
    at
  org.apache.spark.streaming.kafka.KafkaUtils.createDirectStream(KafkaUtils.scala)
    at
  consumer.spark.KafkaConsumer.consumeMessages(KafkaConsumer.java:103)
    at consumer.spark.KafkaConsumer.executeStream(KafkaConsumer.java:142)
    at
  consumer.spark.KafkaConsumerService.main(KafkaConsumerService.java:27)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)  at
  sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)     at
  org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:743)
    at
  org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:187)
    at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:212)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:126)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala) Caused
  by: java.lang.ClassNotFoundException: scala.reflect.ClassManifest     at
  java.net.URLClassLoader.findClass(URLClassLoader.java:381)    at
  java.lang.ClassLoader.loadClass(ClassLoader.java:424)     at
  java.lang.ClassLoader.loadClass(ClassLoader.java:357)     ... 23 more

Here is my pom.xml

<dependency>
    <groupId>org.scala-lang</groupId>
    <artifactId>scala-library</artifactId>
    <version>2.10.3</version>
</dependency>

<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-core_2.11</artifactId>
    <version>2.1.1</version>
</dependency>

<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-streaming-kafka-0-8_2.11</artifactId>
    <version>2.1.1</version>
</dependency>

<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-streaming_2.11</artifactId>
    <version>2.1.1</version>
</dependency>

<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-hive_2.11</artifactId>
    <version>2.1.1</version>
</dependency>

<dependency>
    <groupId>org.apache.kafka</groupId>
    <artifactId>kafka_2.11</artifactId>
    <version>0.8.2.1</version>
</dependency>

<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-sql_2.11</artifactId>
    <version>2.1.1</version>
</dependency>

Please let me know how to resolve this.


问:
How can Increase performance on my Ionic3 Anguar4 app?
Now I am working with Ionic3, Angular4 android app. It is taking a while to load initially. I mean I got a black blank screen for few seconds.How can I speed up this and avoid the black screen?</p>

答:
I try to keep up-to-date a post about that subject on the Ionic forum, have a look to https://forum.ionicframework.com/t/app-boot-time-current-state-and-best-practices/

But right now, some keywords about your question would be, I guess

Use lazy loading: Lazy loading concept allows you to not load and not load all requirements of your pages and components at boot time. For example, really really summarized, if you've got a first page1 and a page2 which use componentA. Without lazy loading, everything gonna be loaded at boot time. With lazy loading, componentA not gonna be loaded at boot time because it's not needed for the loading sequence and will only be use later and therefore, you save a bit of time

check your code and the libs you use to spare size: Size of the app is the key. Bigger is your app, slower is your boot

check your statics assets: could you delete or compact images? could you delete fonts? or could you not embed fonts? again size is the key

do you use rxjs operators? recently it was announced a new way of importing them and therefore to let you only imports the one you need and not all operators, again, it allows to spare size

you could apply this thinking to other libs you use, like lodash or moment.js vs date-fns I guess. Do you import all the libs or only what you need? Think small is beautiful

I hope this helps ...


问:
Recurring billing with Rails and ActiveMerchant: Best practices, pitfalls, gotchas?
We are prepping for the release of a large web application that has been in development for the past year. We are about to start the process of integrating ActiveMerchant to handle recurring subscription fees for the service.

I am looking for any advice regarding best practices considering our requirements (listed below) and any additional heads-up for common pitfalls or specific issues I should be giving special consideration. The payment gateway we will be using is PaymentExpress as it's one of the few supported gateways that has recurring billing and doesn't have any special conditions for companies operating outside of the USA. The business behind this application is based out of the UK.

Users of the application create an account with a sub-domain where they can access and customise the application and their data. Below are some of the requirements/features that might have an effect on how billing works:

All users get a 30 day trial

There are different plans, including a free one

Higher priced plans have larger limits on the amount of data (e.g. users, projects,  etc) they can have in their account

Billing period will be monthly, beginning after trial

There will be discounts/coupon codes to get a percentage off the normal price for a year on plans, etc.

Plan pricing will change as features are added

Specific hurdles I can foresee will be things including the following:

How to handle downgrading when they violate the plan limits for lower level plans.

Behaviour when credit cards expire or payments don't go through (a read-only mode enforced, perhaps)

When plan pricing changes, we want to honour previous prices for existing users for a time period (such as 6 months), then start charging higher rates. If the plan price decreases, it will take effect immediately.

Other advice that would be helpful would be anything regarding flow of the application. How should billing forms be presented to the user? When should credit card information be required? How should invoices be sent, stored, and accessible?

I should disclose that we plan to base a lot of the code base off SaaSy. SaaSy is designed to be used as a separate Rails app that handles all the signup and account management side of things. However, this doesn't work for us since we never planned for this from the beginning and it would be a tedious process to adapt our application to work like that. Consequently, we'll be pulling code and ideas from SaaSy and merging them into our app, a considerably less tedious task.

答:
RailsKits has a Software as a Service kit that should do what you need.  It has built-in support for free trials, upgrading, downgrading, plan limits, etc., and it supports PaymentExpress (and some others).

I've researched it a bit for a project I'm doing, but I haven't purchased it yet so I can't vouch for it.  However, I have seen a few blog posts praising this kit.

While the RailsKit is relatively inexpensive when compared what it would cost you to implement all of its features yourself, there are a couple open source versions out there that aim to accomplish the same thing.  The one I remember off the top of my head is called Freemium.

EDIT: I forgot to mention that Ryan Bates said in his most recent Railscast that his next episode or two will deal with recurring billing, so keep an eye out for that.  He usually does one episode per week, and the five he's done since December 22 all cover handling payments of different types.

OwnerDisplayName: bjeanes

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: bjeanes

OwnerDisplayName: Nick


问:
Firebase Database change node ID
How can I change the naming of the nodes of my children in the image below?
questions_stats is a List<Integer>, I'm aware that I get integers as nodes Id because this is a List. I create each of the children randomly with a number between 0 and 1000. I set this ID as part of the object and to find it I loop trough the list. What I want is to set the "0671" as the Key of the Object at the moment I create it.

How should I define my object in order to access each child with an Id that I define as a String.

Each of the questions_stats is an object.

This is my UserProfile Class definition.

```<code>public class UserProfile implements Parcelable {
    private List<Integer> questions_list;
    private List<QuestionsStats> questions_stats;
    private String country_name, share_code, user_name;
    private int token_count;
    private Boolean is_guest;

    public UserProfile() {
    }

    public UserProfile(List<Integer> questions_list, List<QuestionsStats> questions_stats, String country_name, String share_code, String user_name, int token_count, Boolean is_guest) {
        this.questions_list = questions_list;
        this.questions_stats = questions_stats;
        this.country_name = country_name;
        this.share_code = share_code;
        this.user_name = user_name;
        this.token_count = token_count;
        this.is_guest = is_guest;
    }
 }
</code>```

I know I can set them using the child("0159").setValue(QuestionStats) individually.

But for my purpose I need to retrieve the data of the "user" as a whole and then iterate whithin questions_stats like it is a List.

How should I define my UserProfile class in order to achieve what I want?

Anybody could give me a hint?

答:
How can I change the node names of my children in the image below?

Answer: There is no way in which you can change the names of the nodes from your Firebase database. There is no API for doing that. What can you do instead is to attach a listener on that node and get the dataSnapshot object. Having that data, you can write it in another place using other names. You cannot simply rename them from 0 to 0000, 1 to 0001 and so on.

Title: Firebase Database change node ID

Body:
How can I change the naming of the nodes of my children in the image below?
questions_stats is a List<Integer>, I'm aware that I get integers as nodes Id because this is a List. I create each of the children randomly with a number between 0 and 1000. I set this ID as part of the object and to find it I loop trough the list. What I want is to set the "0671" as the Key of the Object at the moment I create it.

How should I define my object in order to access each child with an Id that I define as a String.

Each of the questions_stats is an object.

This is my UserProfile Class definition.

public class UserProfile implements Parcelable {
    private List<Integer> questions_list;
    private List<QuestionsStats> questions_stats;
    private String country_name, share_code, user_name;
    private int token_count;
    private Boolean is_guest;

    public UserProfile() {
    }

    public UserProfile(List<Integer> questions_list, List<QuestionsStats> questions_stats, String country_name, String share_code, String user_name, int token_count, Boolean is_guest) {
        this.questions_list = questions_list;
        this.questions_stats = questions_stats;
        this.country_name = country_name;
        this.share_code = share_code;
        this.user_name = user_name;
        this.token_count = token_count;
        this.is_guest = is_guest;
    }
 }

I know I can set them using the child("0159").setValue(QuestionStats) individually.

But for my purpose I need to retrieve the data of the "user" as a whole and then iterate whithin questions_stats like it is a List.

How should I define my UserProfile class in order to achieve what I want?

Anybody could give me a hint?


问:
I need a CSharp script (.csx) runner, like csi.exe, for a build agent machine
I'm writing .csx build scripts. On my local machine I run them with CSharp interactive from visual studio or via C:\Program Files (x86)\MSBuild\14.0\bin\csi.exe. I've tried running .csx scripts on a TeamCity build agent machine (agent machines perform actual build tasks like compilation), which has Microsoft Built Tools 2015 installed. Surprisingly, there was no csi.exe in MSBuild folders.

I'm looking for a way to install csi.exe or a compatible standalone .csx runner on my build agent machines. The options found in Google, like https://github.com/cake-build/cake , all seem to have their distinct flavor of scripts or lots of additional functionality, whereas I'm looking for a csi.exe clone ideally.

答:
You can compile your own runner with any customization you like using Roslyn API.

This code would do the basic job of running a script:

static void Main(string[] args)
{
    Task<object> result = CSharpScript.EvaluateAsync(File.ReadAllText(args[0]));
    result.Wait();
}
```


问:
Object of type 'function' has no len() in python
I have been searching for a solution for this error for a while but the solutions that have helped others have not been much help for me.

Here is the code that I've wrote.

```<code>def main():
    while True:
        userInput()
        characterCount(userInput)
        middleLetter()
        spaceCount()
        letterReplace()
        displayOutput()

def userInput():
    sentence = str(input('Enter a sentence at least 10 letters long, or type STOP to quit:'))
    if sentence == 'STOP':
        quit()
    return sentence

def characterCount(sentence):
    characterCount = len(sentence) - sentence.count(' ')
    if characterCount < 10:
        print('Sorry that is less than 10 letters')
    return characterCount

def middleLetter(sentence):
    sentence = len(sentence)/2
    middleLetter = [sentence +1]
    return middleLetter

def spaceCount(sentence):
    spaceCount = sentence.count(' ')
    return spaceCount

def letterReplace(sentence):
    letterReplace= sentence.replace("a", "&")
    return letterReplace

def displayOutput(characterCount,middleLetter,spaceCount,letterReplace):
    print('Number of letters: '(characterCount))
    print('Middle letter: '(middleLetter))
    print('Spaces counted: '(spaceCount))
    print('Sentence with letter replaced: '(letterReplace))

main()
</code>```

The problem I have is that when I run the program I get the error.

```<code>Traceback (most recent call last):
  File "C:\Users\wood\Desktop\Software design\Program 4\program3_4QuinnWood.py", line 59, in <module>
    main()
  File "C:\Users\wood\Desktop\Software design\Program 4\program3_4QuinnWood.py", line 18, in main
    characterCount(userInput)
  File "C:\Users\wood\Desktop\Software design\Program 4\program3_4QuinnWood.py", line 32, in characterCount
    characterCount = len(sentence) - sentence.count(' ')
TypeError: object of type 'function' has no len()
</code>```

Most of the times I have seen this error is because of a int being used instead of a string but I can not see what would be causing this error. Any help would be appreciated.

Using some of the given suggestions I have fixed the original error but now when I try to run it I receive the error.

```<code>Traceback (most recent call last):
  File "C:\Users\wood\Desktop\Software design\Program 4\program3_4QuinnWood.py", line 59, in <module>
    main()
  File "C:\Users\wood\Desktop\Software design\Program 4\program3_4QuinnWood.py", line 22, in main
    displayOutput(characterCount,middleLetter,spaceCount,letterReplace)
  File "C:\Users\wood\Desktop\Software design\Program 4\program3_4QuinnWood.py", line 53, in displayOutput
    print('Number of letters:'(characterCount))
TypeError: 'str' object is not callable
</code>```

答: In Yours code the object userInput has no len().  But object userInput() - has.

Body:
I have been searching for a solution for this error for a while but the solutions that have helped others have not been much help for me.

Here is the code that I've wrote.

def main():
    while True:
        userInput()
        characterCount(userInput)
        middleLetter()
        spaceCount()
        letterReplace()
        displayOutput()

def userInput():
    sentence = str(input('Enter a sentence at least 10 letters long, or type STOP to quit:'))
    if sentence == 'STOP':
        quit()
    return sentence

def characterCount(sentence):
    characterCount = len(sentence) - sentence.count(' ')
    if characterCount < 10:
        print('Sorry that is less than 10 letters')
    return characterCount

def middleLetter(sentence):
    sentence = len(sentence)/2
    middleLetter = [sentence +1]
    return middleLetter

def spaceCount(sentence):
    spaceCount = sentence.count(' ')
    return spaceCount

def letterReplace(sentence):
    letterReplace= sentence.replace("a", "&")
    return letterReplace

def displayOutput(characterCount,middleLetter,spaceCount,letterReplace):
    print('Number of letters: '(characterCount))
    print('Middle letter: '(middleLetter))
    print('Spaces counted: '(spaceCount))
    print('Sentence with letter replaced: '(letterReplace))

main()

The problem I have is that when I run the program I get the error.

Traceback (most recent call last):
  File "C:\Users\wood\Desktop\Software design\Program 4\program3_4QuinnWood.py", line 59, in <module>
    main()
  File "C:\Users\wood\Desktop\Software design\Program 4\program3_4QuinnWood.py", line 18, in main
    characterCount(userInput)
  File "C:\Users\wood\Desktop\Software design\Program 4\program3_4QuinnWood.py", line 32, in characterCount
    characterCount = len(sentence) - sentence.count(' ')
TypeError: object of type 'function' has no len()

Most of the times I have seen this error is because of a int being used instead of a string but I can not see what would be causing this error. Any help would be appreciated.

Using some of the given suggestions I have fixed the original error but now when I try to run it I receive the error.

Traceback (most recent call last):
  File "C:\Users\wood\Desktop\Software design\Program 4\program3_4QuinnWood.py", line 59, in <module>
    main()
  File "C:\Users\wood\Desktop\Software design\Program 4\program3_4QuinnWood.py", line 22, in main
    displayOutput(characterCount,middleLetter,spaceCount,letterReplace)
  File "C:\Users\wood\Desktop\Software design\Program 4\program3_4QuinnWood.py", line 53, in displayOutput
    print('Number of letters:'(characterCount))
TypeError: 'str' object is not callable


问:
Using localStorage() in Angular
I'm trying to use localStorage to save language preference in my app, but I can't seem to get it. Can anyone see why this isn't working and how I Can fix it?

This is my code:

```<code>export class AppComponent implements OnInit {
  title: string = 'app';
  currentLanguage = localStorage.getItem('language');
  currentPage: string;
  @ViewChild('bottom') bottomSection: ElementRef;
  @ViewChild('top') topSection: ElementRef;

  constructor(private global: GlobalProvider, private translate: TranslateService, private scrollService: ScrollToService, private elementRef: ElementRef, private route: ActivatedRoute, private router: Router) {
    translate.setDefaultLang('en');
    this.changeLanguage('en');
  }

  changeLanguage(language: string) {
    this.translate.use(language);
    this.currentLanguage = language;
    localStorage.setItem('language',language);
  }
</code>```

答:
localStorage isn't recognised by typescript, hence it would be throwing an error compile time. Declare ambient variable for localStorage so that typescript will analyse that localStorage variable has been defined and tooling system won't yell at it.

```<code>//write below line `AppComponent` class
declare var localStorage: any;
</code>```

Title: Using localStorage() in Angular

Body:
I'm trying to use localStorage to save language preference in my app, but I can't seem to get it. Can anyone see why this isn't working and how I Can fix it?

This is my code:

export class AppComponent implements OnInit {
  title: string = 'app';
  currentLanguage = localStorage.getItem('language');
  currentPage: string;
  @ViewChild('bottom') bottomSection: ElementRef;
  @ViewChild('top') topSection: ElementRef;

  constructor(private global: GlobalProvider, private translate: TranslateService, private scrollService: ScrollToService, private elementRef: ElementRef, private route: ActivatedRoute, private router: Router) {
    translate.setDefaultLang('en');
    this.changeLanguage('en');
  }

  changeLanguage(language: string) {
    this.translate.use(language);
    this.currentLanguage = language;
    localStorage.setItem('language',language);
  }

Body:
localStorage isn't recognised by typescript, hence it would be throwing an error compile time. Declare ambient variable for localStorage so that typescript will analyse that localStorage variable has been defined and tooling system won't yell at it.

//write below line `AppComponent` class
declare var localStorage: any;


问:
SQL Complex calculation and updating bulk records
Consider the below scenario,

I am having
Table A,
Table B and
Table C.

In these above tables needs to get updated their records as per calculation formula in respective columns on regular time interval.
(For example 24 hours once.)

So I tried in stored procedure and made in job scheduler by writing the queries to update the records.

When I am executing the procedure , it is taking 15 to 20 minutes to execute and complete SQL Server management studio getting hanged because of 5000 records in each table.

So I splitted the updation process into 3 seperate procedures and noted the time for execution as 1 minute for each procedure based on count of records.

Even After optimization of the procedure,

What kind of transaction needs to provide for updating the data for avoiding exceptions?

Is there any other possibility to retain the server from timeout issue?

My DB Plan Information:

I am developing Rental systems product.
In that Room Information will be available in a table 1.
Rented Customer Information will be available in table 2.
Rented room and its tenant invoice will be available in table 3
Rented room and its tenant receipt will be available in table 4

Step 1  : Need to calculate total due amount for all tenant, Dues in days,Dues in months for each invoice in a while loop for updating in the table records.

Step 2  : Need to calculate total late fee for each invoice on regular basis.
(Note: Late fee will vary based on per day calculation basis for same invoice.)

So I am storing into table 5 as common table for all leases with their respective calculated value on daily basis.
For that I have created a common stored procedure for calculating all data and Based on user defined function, It will update into table 5.

I am fetching from table 5 to all my reports and grid.

Problem statement:
Even I have optimized the procedure, When I am executing it, It is taking around 150 seconds approximately.

Question : How can I implement transaction for this action and How to make it in proper way by avoiding any deadlocks and other's data in the same table has to get accessed at the same time ?

答:
you can go to the below link to change the timeout session for your SQL server management studio

https://learn.microsoft.com/en-us/sql/database-engine/configure-windows/configure-the-remote-query-timeout-server-configuration-option

And I suggest you keep your drive space free as much as you as can by compressing your ldf and mdf files.


问:
How do you have a workflow in hg, where one does very frequent commits?
Workflow I have is to do very frequent commits and pushes, then later when I am ready, combine the commits into a single commit (with histedit etc.) to cleanup the log.

With git, I would do a rebase and push. The dangling head left behind would not litter my log, and would eventually be garbage collected.

With mercurial, I end up with multiple heads. And if I close the branch to get rid of the stale heads, I end up with a million closed branches that still show up in the log. That defeats the original purpose.

How do you have such a workflow in mercurial without completely screwing up the log? Is there an alternative workflow that does work under mercurial?

NOTE that the frequent commits also get pushed out to a repo (just for safety). Which means I can't quite use things like strip.

答:
While @Ry4an suggested really The Best Way (tm), you can use another way wth only "classic" released tools

Use [phases] publish=False on push-target (read and grok phases) (see also After pushing to a review repository, "abort: can't rebase immutable changeset" on rebase and http://www.logilab.org/blogentry/88203 for intro into phases)

Use any history rewriting methods on your side

If pushing mutated history to not-publishing repo still will create additional heads (I'm too lazy to test it for you) - eliminate all unwanted anonymous branches (with "dirty" history) by using dummy merges - you'll have a lot of mergesets in history, but only one real head


问:
How do you trace/debug Apache Camel or AOP-modified code?
I'm trying to debug a webapp using Apache Camel from Eclipse and while I'm 'tracing into' I arrive at a point where Eclipse says that no source file is available and I can see bytecode shown in Eclipse (where usually I see sourcecode) but apparently I cannot advance into that bytecode (I try 'F6 / Step Over' but nothing happens) anyway (not that it would have been that useful compared to source code).

So how are you supposed to trace into such a beast?

I'm wondering if all these code-generating/code-intercepting layers aren't creating more problems than they're trying to solve.  It seems like it's helpful as long as everything works but as soon as there's a problem, things become very hard to diagnose.

EDIT I don't want to trace Apache Camel itself.  I just want to trace a program that is using Apache Camel and I realize that things quickly gets very messy: basically you kinda lose your tracing ability because you jump from your Java source code to "something".

答:
Apache Camel does not do any bytecode manipulator or instrumentation. At most it uses the Proxy from the JDK library if you use the Camel Proxy feature.

So it must be other libraries which causes your eclipse debugger not being able to step into the source code.

All the source code for Apache Camel is distributed as -source JARs using the maven standard.
If you use maven there is a maven command to download the -source JARs which I assume Eclipse is then capable of using.

I am not using Eclipse, but use IDEA which has can auto download the -source JARs from the maven repos.


问:
flag always returns 0 to another class
```<code>import java.util.ArrayList;
import java.util.List;

public class QueryParser {
    QueryParameter queryParameter = new QueryParameter();
    public static int flag = 0;

    public QueryParameter parseQuery(String queryString) {
        queryParameter.setGroupByFields(getGroupByFields(queryString));

        queryParameter.setAggregateFunctions(getAggregateFunctions(queryString));

        return queryParameter;
    }

    private List<AggregateFunction> getAggregateFunctions(String queryString) {
        List<AggregateFunction> aggregateFunctionList = null;
        AggregateFunction aggregateFunction;
        if (queryString.contains("count") || queryString.contains("sum") || queryString.contains("min")
                || queryString.contains("max") || queryString.contains("avg")) {
            flag = flag + 1;
        }
        return aggregateFunctionList;
    }

    private List<String> getGroupByFields(String queryString) {
        List<String> groupByFieldList = null;
        if (queryString.contains("group by")) {
            flag = flag+2;
        return groupByFieldList;
    }
}
</code>```

this is my code, now i am accessing flag from another class using
 int i = queryParser.flag,
but it always returns 0. How to declare flag so that it will hold the values from the inner methods and also can be accessed from other classes. /* if anyone need more details please ask i'll add more details, and what more should i write,my main doubt is only to know how i can utilise my flag in another class, thank you for being patient*/

答:
An MCVE could look like this:

```<code>public class QueryParser {

    public static int flag = 0;

    void getAggregateFunctions(String queryString) {

        if (queryString.contains("count") || queryString.contains("sum") || queryString.contains("min")
                || queryString.contains("max") || queryString.contains("avg")) {
            flag = flag + 1;
        }
    }

    void getGroupByFields(String queryString) {

        if (queryString.contains("group by")) {
            flag = flag+2;
        }
    }

    public static void main(String[] args) {

        QueryParser q = new QueryParser();
        System.out.println(flag); //prints out 0
        q.getAggregateFunctions("max"); System.out.println(flag); //prints out 1
        q.getAggregateFunctions("aString"); System.out.println(flag); //prints out 1
        q.getAggregateFunctions("avgNumber"); System.out.println(flag); //prints out 2
        q.getGroupByFields("group by"); System.out.println(flag); //prints out 4
    }
}
</code>```

It helps those who want to help you, and far more important: it is a great debugging tool.

Making on helps you isolate the problem, and focus on it.

Like in this case: you can see that the problem is not in the declaration of flag, nor changing its value, but maybe with the input values.

Title: flag always returns 0 to another class

Body:
import java.util.ArrayList;
import java.util.List;

public class QueryParser {
    QueryParameter queryParameter = new QueryParameter();
    public static int flag = 0;

    public QueryParameter parseQuery(String queryString) {
        queryParameter.setGroupByFields(getGroupByFields(queryString));

        queryParameter.setAggregateFunctions(getAggregateFunctions(queryString));

        return queryParameter;
    }

    private List<AggregateFunction> getAggregateFunctions(String queryString) {
        List<AggregateFunction> aggregateFunctionList = null;
        AggregateFunction aggregateFunction;
        if (queryString.contains("count") || queryString.contains("sum") || queryString.contains("min")
                || queryString.contains("max") || queryString.contains("avg")) {
            flag = flag + 1;
        }
        return aggregateFunctionList;
    }

    private List<String> getGroupByFields(String queryString) {
        List<String> groupByFieldList = null;
        if (queryString.contains("group by")) {
            flag = flag+2;
        return groupByFieldList;
    }
}

this is my code, now i am accessing flag from another class using
 int i = queryParser.flag,
but it always returns 0. How to declare flag so that it will hold the values from the inner methods and also can be accessed from other classes. /* if anyone need more details please ask i'll add more details, and what more should i write,my main doubt is only to know how i can utilise my flag in another class, thank you for being patient*/

Body:
An MCVE could look like this:

public class QueryParser {

    public static int flag = 0;

    void getAggregateFunctions(String queryString) {

        if (queryString.contains("count") || queryString.contains("sum") || queryString.contains("min")
                || queryString.contains("max") || queryString.contains("avg")) {
            flag = flag + 1;
        }
    }

    void getGroupByFields(String queryString) {

        if (queryString.contains("group by")) {
            flag = flag+2;
        }
    }

    public static void main(String[] args) {

        QueryParser q = new QueryParser();
        System.out.println(flag); //prints out 0
        q.getAggregateFunctions("max"); System.out.println(flag); //prints out 1
        q.getAggregateFunctions("aString"); System.out.println(flag); //prints out 1
        q.getAggregateFunctions("avgNumber"); System.out.println(flag); //prints out 2
        q.getGroupByFields("group by"); System.out.println(flag); //prints out 4
    }
}

It helps those who want to help you, and far more important: it is a great debugging tool.

Making on helps you isolate the problem, and focus on it.

Like in this case: you can see that the problem is not in the declaration of flag, nor changing its value, but maybe with the input values.


问:
Remove all event listener of document in javascript not using the event name
I have to remove all the event listener that is added to document.

So according to THIS POST, I have built a function like this but it is showing TypeError: document.parentNode is null!

var msg = document.getElementById('state-msg');
var button =  document.getElementById('removeListener');
document.addEventListener('keydown', function(e) {
  msg.textContent = 'keydown:' + e.keyCode;
});

document.addEventListener('keyup', function(e) {
  msg.textContent = 'keyup:' + e.keyCode;
});

document.addEventListener('keypress', function(e) {
  msg.textContent += 'keypress:' + e.keyCode;
});

button.addEventListener('click', function(e) {
  var elClone = document.cloneNode(true);
  document.parentNode.replaceChild(elClone, document);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Press any key and get the message here: <span id="state-msg"></span>
<button id = "removeListener">RemoveListener</button></code>```

This can be very basic question but still, no success, Any kind of comment will be greatly appreciate.

UPDATE:

I also tried document = elNode, but not working.

答:
Personally, I would name the event listeners, so you can remove them properly.
I get what you are trying to do though. However, since this is the document node, it is unlikely you will find a parent node for it. It is the root of your DOM tree after all.
If this was a specific element to which you have bound the event listener, your approach would work.

You could extend the addEventListener and removeEventListener to register the functions in a data-structure that you could later use in your function to methodically remove every event listener. See this answer for details.

Yet another option, if you do not mind moving to JQuery, is to use JQuery to attach the listeners and then simply using $(document).off() would remove the listeners attached. It may not work in conjunction with native addEventListener methods.

Body:
I have to remove all the event listener that is added to document.

So according to THIS POST, I have built a function like this but it is showing TypeError: document.parentNode is null!

var msg = document.getElementById('state-msg');
var button =  document.getElementById('removeListener');
document.addEventListener('keydown', function(e) {
  msg.textContent = 'keydown:' + e.keyCode;
});

document.addEventListener('keyup', function(e) {
  msg.textContent = 'keyup:' + e.keyCode;
});

document.addEventListener('keypress', function(e) {
  msg.textContent += 'keypress:' + e.keyCode;
});

button.addEventListener('click', function(e) {
  var elClone = document.cloneNode(true);
  document.parentNode.replaceChild(elClone, document);
});

Press any key and get the message here:
<button id = "removeListener">RemoveListener</button>

This can be very basic question but still, no success, Any kind of comment will be greatly appreciate.

UPDATE:

I also tried document = elNode, but not working.