问:
How do i change only the chosen option in listview in flutter
I am trying to display the answer user have chosen.

In the code below i have fetched a list of quizzes and displayed. I tried to change the background color of the chosen option by the user to different color than the others but when i execute the codes all of the quizzes get affected.

Please suggest a simple and easy way because i am not really a programmer of flutter developer i am just learning and have gotten quite not far.

Thanks in advance

```<code>
  Widget MyQuizzesCardUI(String question, String OptionID, String Option1, String Option2, String Option3, String Option4, String MyChoice, String Status, int index) {
    bool opt1 = false;
    bool opt2 = false;
    return Container(
      padding: EdgeInsets.all(10),
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(8),
          border: Border.all(color: Color(0xffefefef), width: 0.5)),
      child: Column(
        children: [
          Container(
              child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    Container(
                      child: InkWell(
                        onTap: () {
                          opt1 = true;
                          opt2 = false;
                          setState(() {
                            opt1 = true;
                            opt2 = false;
                          });
                        },
                        child: Align(
                          alignment: Alignment.centerLeft,
                          child: Container(
                            width: double.infinity,
                            padding: EdgeInsets.all(10),
                            decoration: BoxDecoration(
                              color: opt1 ? Color(0xffa4c3ff) : Colors.white,
                            ),
                            child: Text(
                              "${Option1}",
                            ),
                          ),
                        ),
                      ),
                    ),
                    Container(
                      child: InkWell(
                        onTap: () {
                          opt1 = false;
                          opt2 = true;
                          setState(() {
                            opt1 = false;
                            opt2 = true;
                          });
                        },
                        child: Align(
                          alignment: Alignment.centerLeft,
                          child: Container(
                            width: double.infinity,
                            padding: EdgeInsets.all(10),
                            decoration: BoxDecoration(
                              color: opt2 ? Color(0xffa4c3ff) : Colors.white,
                            ),
                            child: Text(
                              "${Option2}",
                            ),
                          ),
                        ),
                      ),
                    ),
                  ]
              ))
        ],
      ),
    );
  }

</code>```

答:
it doesen't change becase when you call setState it reload the whole class so also it will set again to the begining value.

let's create a list like this:

```<code>List<Map<String, Bool>> options = [
  {
    "opt1": false;
    "opt2": false;
  }
];
</code>```

and to fill up the list you can use this code in the initState like this:

```<code>@override
  void initState() {
    super.initState();

    for(int i = 0; i>questions.length; i++) {
      options.add({"opt1": false, "opt2": false});
    }

</code>```

in your widget it works than like this:

```<code>Widget MyQuizzesCardUI(String question, String OptionID, String Option1, String Option2, String Option3, String Option4, String MyChoice, String Status, int index) {
    return Container(
      padding: EdgeInsets.all(10),
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(8),
          border: Border.all(color: Color(0xffefefef), width: 0.5)),
      child: Column(
        children: [
          Container(
              child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    Container(
                      child: InkWell(
                        onTap: () {
                          options[index]["opt1"] = true;
                          options[index]["opt2"] = false;
                          setState(() {
                            options[index]["opt1"] = true;
                            options[index]["opt2"] = false;
                          });
                        },
                        child: Align(
                          alignment: Alignment.centerLeft,
                          child: Container(
                            width: double.infinity,
                            padding: EdgeInsets.all(10),
                            decoration: BoxDecoration(
                              color: options[index]["opt1"] ? Color(0xffa4c3ff) : Colors.white,
                            ),
                            child: Text(
                              "${options[index]["opt1"]}",
                            ),
                          ),
                        ),
                      ),
                    ),
                    Container(
                      child: InkWell(
                        onTap: () {
                          options[index]["opt1"] = false;
                          options[index]["opt2"] = true;
                          setState(() {
                            options[index]["opt1"] = false;
                            options[index]["opt2"] = true;
                          });
                        },
                        child: Align(
                          alignment: Alignment.centerLeft,
                          child: Container(
                            width: double.infinity,
                            padding: EdgeInsets.all(10),
                            decoration: BoxDecoration(
                              color: options[index]["opt2"] ? Color(0xffa4c3ff) : Colors.white,
                            ),
                            child: Text(
                              "${options[index]["opt2"]}",
                            ),
                          ),
                        ),
                      ),
                    ),
                  ]
              ))
        ],
      ),
</code>```

Body:
I am trying to display the answer user have chosen.

In the code below i have fetched a list of quizzes and displayed. I tried to change the background color of the chosen option by the user to different color than the others but when i execute the codes all of the quizzes get affected.

Please suggest a simple and easy way because i am not really a programmer of flutter developer i am just learning and have gotten quite not far.

Thanks in advance

  Widget MyQuizzesCardUI(String question, String OptionID, String Option1, String Option2, String Option3, String Option4, String MyChoice, String Status, int index) {
    bool opt1 = false;
    bool opt2 = false;
    return Container(
      padding: EdgeInsets.all(10),
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(8),
          border: Border.all(color: Color(0xffefefef), width: 0.5)),
      child: Column(
        children: [
          Container(
              child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    Container(
                      child: InkWell(
                        onTap: () {
                          opt1 = true;
                          opt2 = false;
                          setState(() {
                            opt1 = true;
                            opt2 = false;
                          });
                        },
                        child: Align(
                          alignment: Alignment.centerLeft,
                          child: Container(
                            width: double.infinity,
                            padding: EdgeInsets.all(10),
                            decoration: BoxDecoration(
                              color: opt1 ? Color(0xffa4c3ff) : Colors.white,
                            ),
                            child: Text(
                              "${Option1}",
                            ),
                          ),
                        ),
                      ),
                    ),
                    Container(
                      child: InkWell(
                        onTap: () {
                          opt1 = false;
                          opt2 = true;
                          setState(() {
                            opt1 = false;
                            opt2 = true;
                          });
                        },
                        child: Align(
                          alignment: Alignment.centerLeft,
                          child: Container(
                            width: double.infinity,
                            padding: EdgeInsets.all(10),
                            decoration: BoxDecoration(
                              color: opt2 ? Color(0xffa4c3ff) : Colors.white,
                            ),
                            child: Text(
                              "${Option2}",
                            ),
                          ),
                        ),
                      ),
                    ),
                  ]
              ))
        ],
      ),
    );
  }

Body:
it doesen't change becase when you call setState it reload the whole class so also it will set again to the begining value.

let's create a list like this:

List<Map<String, Bool>> options = [
  {
    "opt1": false;
    "opt2": false;
  }
];

and to fill up the list you can use this code in the initState like this:

@override
  void initState() {
    super.initState();

    for(int i = 0; i>questions.length; i++) {
      options.add({"opt1": false, "opt2": false});
    }

in your widget it works than like this:

Widget MyQuizzesCardUI(String question, String OptionID, String Option1, String Option2, String Option3, String Option4, String MyChoice, String Status, int index) {
    return Container(
      padding: EdgeInsets.all(10),
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(8),
          border: Border.all(color: Color(0xffefefef), width: 0.5)),
      child: Column(
        children: [
          Container(
              child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    Container(
                      child: InkWell(
                        onTap: () {
                          options[index]["opt1"] = true;
                          options[index]["opt2"] = false;
                          setState(() {
                            options[index]["opt1"] = true;
                            options[index]["opt2"] = false;
                          });
                        },
                        child: Align(
                          alignment: Alignment.centerLeft,
                          child: Container(
                            width: double.infinity,
                            padding: EdgeInsets.all(10),
                            decoration: BoxDecoration(
                              color: options[index]["opt1"] ? Color(0xffa4c3ff) : Colors.white,
                            ),
                            child: Text(
                              "${options[index]["opt1"]}",
                            ),
                          ),
                        ),
                      ),
                    ),
                    Container(
                      child: InkWell(
                        onTap: () {
                          options[index]["opt1"] = false;
                          options[index]["opt2"] = true;
                          setState(() {
                            options[index]["opt1"] = false;
                            options[index]["opt2"] = true;
                          });
                        },
                        child: Align(
                          alignment: Alignment.centerLeft,
                          child: Container(
                            width: double.infinity,
                            padding: EdgeInsets.all(10),
                            decoration: BoxDecoration(
                              color: options[index]["opt2"] ? Color(0xffa4c3ff) : Colors.white,
                            ),
                            child: Text(
                              "${options[index]["opt2"]}",
                            ),
                          ),
                        ),
                      ),
                    ),
                  ]
              ))
        ],
      ),


来源: stackexchange

问:
Set default team view filter selection on page load in Twilio flex UI - Reactjs
In the team view filters of Twilio flex UI, I want to set the filter selection dynamically. I need to pass an array or object on dynamically to set the filters selection and the results need to be displayed accordingly based on the new filter selection. Any idea on how to achieve it? Thank you.</p>

答:
Use this

```<code>let defaultTwilioAgentList = [
  {
      query: 'data.activity_name == "Available" OR data.activity_name == "Idle"',
      text: "Active Agents"
  },
  {
      query: '',
      text: "All Agents"
  },
];
Flex.AgentsDataTable.defaultProps.filters = departmentList;
</code>```

This works for me at Flex version 1.21.1

ContentLicense: CC BY-SA 4.0

Body:
Use this

let defaultTwilioAgentList = [
  {
      query: 'data.activity_name == "Available" OR data.activity_name == "Idle"',
      text: "Active Agents"
  },
  {
      query: '',
      text: "All Agents"
  },
];
Flex.AgentsDataTable.defaultProps.filters = departmentList;

This works for me at Flex version 1.21.1


问:
I m not getting Dms console.log on discord.js npmjs plugin
The console.log() in the "messageCreate" event is not firing when sending a DM.

```<code>
const Client = new Discord.Client({
    intents: [
        "GUILDS",
        "GUILD_MESSAGES",
        "DIRECT_MESSAGES"
    ]
})

Client.on('messageCreate', (msg) => {
   msgArray = msg.content.toLowerCase().split(' ')

   if (msgArray[0] == "/botmsg"){
    Client.users.fetch(msgArray[1], false).then((user) => {
        user.send(msgArray[2]);
       });
   } else {
    console.log(msg.content);
   }
})

Client.login('token hidden')
</code>```

My goal is to log the message when a DM is received, how can I do this?

答:
You should put your console.log function in the "true" part of code.

```<code>if (msgArray[0] == "/botmsg"){
    Client.users.fetch(msgArray[1], false).then((user) => {
        user.send(msgArray[2]);
    });
    console.log(msg.content);
} else {
    console.log(msg.content);
}
</code>```

Body:
The console.log() in the "messageCreate" event is not firing when sending a DM.

const Client = new Discord.Client({
    intents: [
        "GUILDS",
        "GUILD_MESSAGES",
        "DIRECT_MESSAGES"
    ]
})

Client.on('messageCreate', (msg) => {
   msgArray = msg.content.toLowerCase().split(' ')

   if (msgArray[0] == "/botmsg"){
    Client.users.fetch(msgArray[1], false).then((user) => {
        user.send(msgArray[2]);
       });
   } else {
    console.log(msg.content);
   }
})

Client.login('token hidden')

My goal is to log the message when a DM is received, how can I do this?

Body:
You should put your console.log function in the "true" part of code.

if (msgArray[0] == "/botmsg"){
    Client.users.fetch(msgArray[1], false).then((user) => {
        user.send(msgArray[2]);
    });
    console.log(msg.content);
} else {
    console.log(msg.content);
}


问:
Akka-Typed Actor unit tests
I've been trying to learn how to test akka-typed Actors. I've been referencing various examples online. I am successful at running the sample code but my efforts to write simple unit tests fail.

Can someone point out what I'm doing wrong? My goal is to be able to write unit test that verify each behavior.

build.sbt

```<code>import Dependencies._

ThisBuild / scalaVersion := "2.13.7"
ThisBuild / version := "0.1.0-SNAPSHOT"
ThisBuild / organization := "com.example"
ThisBuild / organizationName := "example"

val akkaVersion = "2.6.18"

lazy val root = (project in file("."))
  .settings(
    name := "akkat",
    libraryDependencies ++= Seq(
      scalaTest % Test,
      "com.typesafe.akka" %% "akka-actor-typed" % akkaVersion,
      "com.typesafe.akka" %% "akka-actor-testkit-typed" % akkaVersion % Test,
      "ch.qos.logback" % "logback-classic" % "1.2.3"
    )
  )
</code>```

EmotionalFunctionalActor.scala

```<code>package example

import akka.actor.typed.{ActorRef, Behavior}
import akka.actor.typed.scaladsl.Behaviors

object EmotionalFunctionalActor {

  trait SimpleThing
  object EatChocolate extends SimpleThing
  object WashDishes extends SimpleThing
  object LearnAkka extends SimpleThing
  final case class Value(happiness: Int) extends SimpleThing
  final case class HowHappy(replyTo: ActorRef[SimpleThing]) extends SimpleThing

  def apply(happiness: Int = 0): Behavior[SimpleThing] = Behaviors.receive { (context, message) =>
    message match {
      case EatChocolate =>
        context.log.info(s"($happiness) eating chocolate")
        EmotionalFunctionalActor(happiness + 1)

      case WashDishes =>
        context.log.info(s"($happiness) washing dishes, womp womp")
        EmotionalFunctionalActor(happiness - 2)

      case LearnAkka =>
        context.log.info(s"($happiness) Learning Akka, yes!!")
        EmotionalFunctionalActor(happiness + 100)

      case HowHappy(replyTo) =>
        replyTo ! Value(happiness)
        Behaviors.same

      case _ =>
        context.log.warn("Received something i don't know")
        Behaviors.same
    }
  }
}
</code>```

EmoSpec.scala

```<code>package example

import akka.actor.testkit.typed.scaladsl.ActorTestKit
import akka.actor.typed.scaladsl.AskPattern.Askable
import akka.util.Timeout
import org.scalatest.BeforeAndAfterAll
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers

import scala.concurrent.duration.DurationInt

class EmoSpec extends AnyFlatSpec
  with BeforeAndAfterAll
  with Matchers {

  val testKit = ActorTestKit()

  override def afterAll(): Unit = testKit.shutdownTestKit()

  "Happiness Leve" should "Increase by 1" in {
    val emotionActor = testKit.spawn(EmotionalFunctionalActor())
    val probe = testKit.createTestProbe[EmotionalFunctionalActor.SimpleThing]()

    implicit val timeout: Timeout = 2.second
    implicit val sched = testKit.scheduler
    import EmotionalFunctionalActor._

    emotionActor ! EatChocolate
    probe.expectMessage(EatChocolate)

    emotionActor ? HowHappy
    probe.expectMessage(EmotionalFunctionalActor.Value(1))

    val current = probe.expectMessageType[EmotionalFunctionalActor.Value]
    current shouldBe 1
  }
}
</code>```

答:
It's not really clear what problems you're encountering, so this answer is a bit of a shot in the dark with some observations.

You appear to be using the "command-then-query" pattern in testing this aspect of the behavior, which is OK (but see below for a different approach which I've found works really well).  There are two basic ways you can approach this and your test looks like a bit of a mixture of the two in a way that probably is not working.

Regardless of approach, when sending the initial EatChocolate message to the actor:

emotionActor ! EatChocolate
```
<p>That message is sent to actor, not to the probe, so <code>probe.expectMessage</code> won't succeed.</p>
<p>There are two flavors of ask in Akka Typed.  There's a <code>Future</code>-based one for outside of an actor, where the asking machinery injects a special <code>ActorRef</code> to receive the reply and returns a <code>Future</code> which will be completed when the reply is received.  You can arrange for that <code>Future</code> to send its result to the probe:</p>
<pre class="lang-scala prettyprint-override"><code>val testKit = ActorTestKit()
implicit val ec = testKit.system.executionContext

// after sending EatChocolate
val replyFut: Future[EmotionalFunctionalActor.SimpleThing] = emotionActor ? HowHappy
replyFut.foreach { reply =>
  probe.ref ! reply
}
probe.expectMessage(EmotionalFunctionalActor.Value(1))
</code>```

More succinctly, you can dispense with Askable, Futures, and an ExecutionContext and use probe.ref as the replyTo field in your HowHappy message:

emotionActor ! HowHappy(probe.ref`)
probe.expectMessage(EmotionalFunctionalActor.Value(1))
```
<p>This is more succinct and will probably be less flaky (being less prone to timing issues) than the <code>Future</code>-based approach.  Conversely, since the <code>HowHappy</code> message appears designed for use with the ask pattern, the <code>Future</code>-based approach may better fulfill a "test as documentation" purpose for describing how to interact with the actor.</p>
<p>If using the <code>Future</code>-based approach with ScalaTest, it might be useful to have your suite extend <code>akka.actor.testkit.typed.scaladsl.ScalaTestWithActorTestKit</code>: this will provide some of the boilerplate and also mix in ScalaTest's <code>ScalaFutures</code> trait, which would let you write something like</p>
<pre class="lang-scala prettyprint-override"><code>val replyFut: Future[EmotionalFunctionalActor.SimpleThing] = emotionActor ? HowHappy
assert(replyFut.futureValue == EmotionalFunctionalActor.Value(1))
</code>```

I tend to prefer the BehaviorTestKit, especially for cases where I'm not testing how two actors interact (this can still be done, it's just a bit laborious with the BehaviorTestKit).  This has the advantage of not having any timing at all and generally has less overhead for running tests.

val testKit = BehaviorTestKit(EmotionalFunctionalActor())
val testInbox = TestInbox[EmotionalFunctionalActor.SimpleThing]()

testKit.run(HowHappy(testInbox.ref))
testInbox.expectMessage(EmotionalFunctionalActor.Value(1))
```
<p>As a side note, when designing a request-response protocol, it's generally a good idea to restrict the response type to the responses that might actually be sent, e.g.:</p>
<pre class="lang-scala prettyprint-override"><code>final case class HowHappy(replyTo: ActorRef[Value]) extends SimpleThing
</code>```

This ensures that the actor can't reply with anything but a Value message and means that the asker doesn't have to handle any other type of message.  If there's a couple of different message types it could respond with, it might be worth having a trait which is only extended (or mixed in) by those responses:

trait HappinessReply
final case class Value(happiness: Int) extends HappinessReply
final case class HowHappy(replyTo: ActorRef[HappinessReply]) extends SimpleThing
```

Further, the reply often won't make sense as a message received by the sending actor (as indicated in this case by it being handled by the "Received something I don't know" case).  In this situation, Value shouldn't extend SimpleThing: it might even just be a bare case class and not extend anything.

Title: Akka-Typed Actor unit tests

Body:
I've been trying to learn how to test akka-typed Actors. I've been referencing various examples online. I am successful at running the sample code but my efforts to write simple unit tests fail.

Can someone point out what I'm doing wrong? My goal is to be able to write unit test that verify each behavior.

build.sbt

import Dependencies._

ThisBuild / scalaVersion := "2.13.7"
ThisBuild / version := "0.1.0-SNAPSHOT"
ThisBuild / organization := "com.example"
ThisBuild / organizationName := "example"

val akkaVersion = "2.6.18"

lazy val root = (project in file("."))
  .settings(
    name := "akkat",
    libraryDependencies ++= Seq(
      scalaTest % Test,
      "com.typesafe.akka" %% "akka-actor-typed" % akkaVersion,
      "com.typesafe.akka" %% "akka-actor-testkit-typed" % akkaVersion % Test,
      "ch.qos.logback" % "logback-classic" % "1.2.3"
    )
  )

EmotionalFunctionalActor.scala

package example

import akka.actor.typed.{ActorRef, Behavior}
import akka.actor.typed.scaladsl.Behaviors

object EmotionalFunctionalActor {

  trait SimpleThing
  object EatChocolate extends SimpleThing
  object WashDishes extends SimpleThing
  object LearnAkka extends SimpleThing
  final case class Value(happiness: Int) extends SimpleThing
  final case class HowHappy(replyTo: ActorRef[SimpleThing]) extends SimpleThing

  def apply(happiness: Int = 0): Behavior[SimpleThing] = Behaviors.receive { (context, message) =>
    message match {
      case EatChocolate =>
        context.log.info(s"($happiness) eating chocolate")
        EmotionalFunctionalActor(happiness + 1)

      case WashDishes =>
        context.log.info(s"($happiness) washing dishes, womp womp")
        EmotionalFunctionalActor(happiness - 2)

      case LearnAkka =>
        context.log.info(s"($happiness) Learning Akka, yes!!")
        EmotionalFunctionalActor(happiness + 100)

      case HowHappy(replyTo) =>
        replyTo ! Value(happiness)
        Behaviors.same

      case _ =>
        context.log.warn("Received something i don't know")
        Behaviors.same
    }
  }
}

EmoSpec.scala

package example

import akka.actor.testkit.typed.scaladsl.ActorTestKit
import akka.actor.typed.scaladsl.AskPattern.Askable
import akka.util.Timeout
import org.scalatest.BeforeAndAfterAll
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers

import scala.concurrent.duration.DurationInt

class EmoSpec extends AnyFlatSpec
  with BeforeAndAfterAll
  with Matchers {

  val testKit = ActorTestKit()

  override def afterAll(): Unit = testKit.shutdownTestKit()

  "Happiness Leve" should "Increase by 1" in {
    val emotionActor = testKit.spawn(EmotionalFunctionalActor())
    val probe = testKit.createTestProbe[EmotionalFunctionalActor.SimpleThing]()

    implicit val timeout: Timeout = 2.second
    implicit val sched = testKit.scheduler
    import EmotionalFunctionalActor._

    emotionActor ! EatChocolate
    probe.expectMessage(EatChocolate)

    emotionActor ? HowHappy
    probe.expectMessage(EmotionalFunctionalActor.Value(1))

    val current = probe.expectMessageType[EmotionalFunctionalActor.Value]
    current shouldBe 1
  }
}

Body:
It's not really clear what problems you're encountering, so this answer is a bit of a shot in the dark with some observations.

You appear to be using the "command-then-query" pattern in testing this aspect of the behavior, which is OK (but see below for a different approach which I've found works really well).  There are two basic ways you can approach this and your test looks like a bit of a mixture of the two in a way that probably is not working.

Regardless of approach, when sending the initial EatChocolate message to the actor:

emotionActor ! EatChocolate

That message is sent to actor, not to the probe, so probe.expectMessage won't succeed.

There are two flavors of ask in Akka Typed.  There's a Future-based one for outside of an actor, where the asking machinery injects a special ActorRef to receive the reply and returns a Future which will be completed when the reply is received.  You can arrange for that Future to send its result to the probe:

val testKit = ActorTestKit()
implicit val ec = testKit.system.executionContext

// after sending EatChocolate
val replyFut: Future[EmotionalFunctionalActor.SimpleThing] = emotionActor ? HowHappy
replyFut.foreach { reply =>
  probe.ref ! reply
}
probe.expectMessage(EmotionalFunctionalActor.Value(1))

More succinctly, you can dispense with Askable, Futures, and an ExecutionContext and use probe.ref as the replyTo field in your HowHappy message:

emotionActor ! HowHappy(probe.ref`)
probe.expectMessage(EmotionalFunctionalActor.Value(1))

This is more succinct and will probably be less flaky (being less prone to timing issues) than the Future-based approach.  Conversely, since the HowHappy message appears designed for use with the ask pattern, the Future-based approach may better fulfill a "test as documentation" purpose for describing how to interact with the actor.

If using the Future-based approach with ScalaTest, it might be useful to have your suite extend akka.actor.testkit.typed.scaladsl.ScalaTestWithActorTestKit: this will provide some of the boilerplate and also mix in ScalaTest's ScalaFutures trait, which would let you write something like

val replyFut: Future[EmotionalFunctionalActor.SimpleThing] = emotionActor ? HowHappy
assert(replyFut.futureValue == EmotionalFunctionalActor.Value(1))

I tend to prefer the BehaviorTestKit, especially for cases where I'm not testing how two actors interact (this can still be done, it's just a bit laborious with the BehaviorTestKit).  This has the advantage of not having any timing at all and generally has less overhead for running tests.

val testKit = BehaviorTestKit(EmotionalFunctionalActor())
val testInbox = TestInbox[EmotionalFunctionalActor.SimpleThing]()

testKit.run(HowHappy(testInbox.ref))
testInbox.expectMessage(EmotionalFunctionalActor.Value(1))

As a side note, when designing a request-response protocol, it's generally a good idea to restrict the response type to the responses that might actually be sent, e.g.:

final case class HowHappy(replyTo: ActorRef[Value]) extends SimpleThing

This ensures that the actor can't reply with anything but a Value message and means that the asker doesn't have to handle any other type of message.  If there's a couple of different message types it could respond with, it might be worth having a trait which is only extended (or mixed in) by those responses:

trait HappinessReply
final case class Value(happiness: Int) extends HappinessReply
final case class HowHappy(replyTo: ActorRef[HappinessReply]) extends SimpleThing

Further, the reply often won't make sense as a message received by the sending actor (as indicated in this case by it being handled by the "Received something I don't know" case).  In this situation, Value shouldn't extend SimpleThing: it might even just be a bare case class and not extend anything.


问:
Resolve Azure Private DNS zone entry from domain joined VM
We have a virtual machine created in Azure which is using a private VNet configured with custom DNS servers in order to domain join the VM (eg. contoso.com)

Now we have a private DNS zone (eg subdomain.contoso.com) created in Azure which is linked to the same VNet as the VM. However, we are not able to resolve the private DNS entries from within the domain joined VM as I believe, Azure query the Azure private DNS with the IP 168.63.129.16

Is there a way we can forward DNS requests from a VM in Azure VNet using custom DNS servers to Azure private DNS zone linked to the same VNet?

Any help is much appreciated. Thanks.

答:
By using Azure Private DNS, you can resolve domain names in a virtual network without the need to add a custom DNS solution.

By using private DNS zones, you can use your own custom domain names rather than the Azure-provided names available today

Is there a way we can forward DNS requests from a VM in Azure VNet
using custom DNS servers to Azure private DNS zone linked to the same
VNet?

If you have created custom DNS private zone, you can enable Autoregistration feature so that DNS requests from your VM in the VNET will be forwarded to the Azure private DNS zone


问:
Do we still need Richter's AsyncEnumerator?
Recently I stumbled across the AsyncEnumerator class form Jeffrey Richter's Power Threading Library which seems to solve several problems I'm usually encountering when programming asynchronous stuff.

The idea for this class has been around for quite a while now and I'm wondering if current versions of .NET / C# have built-in support for this mechanism by now or if it is still necessary to rely on a third party library? Or maybe newer versions of .NET have some alternative approach which simplifies asynchronous programming as much as Richter's AsyncEnumerator does?

Or in other words: Is there a reason to not start using Richter's AsyncEnumerator today?

Edit:

Some links with information on AsyncEnumerator:

Jeffrey Richter and his AsyncEnumerator

Simplified APM With The AsyncEnumerator

More AsyncEnumerator Features

答:
.net 4.0 includes the PLINQ framework and various other means of threaded computation.

See Parallel Programming in the .NET Framework for more details.

ContentLicense: CC BY-SA 3.0


问:
What Is Can Order In Django Formsets Actually For?
I've spent a fair amount of time the last day or so exploring the can order field with Django Formsets but I can't for the life of me actually figure out what it's for.  Apparently it doesn't update the database...and it does put an order number field with the form....but beyond that what is it for?

I can't find any useful documentation on how to actually use this field.  Do I have to write Javascript in order to get this field to do anything actually meaningful?

I get the delete option...and you have to add code in to delete the record...So I guess I'm to take it the same is required for the can_order field?

Sorry if this is a silly question but I've spent more time trying to figure this out than what would be reasonable by now.

答:
The can_order adds a field to the formset, just like the can_delete does.  You do not NEED JavaScript, but you can use it, for example if you use JavaScript to drag and drop the forms in the formset. You can sort them and then you can change the name attribute to reflect the new order by accessing the specific form by using it's id in your JavaScript.

The can_order IS like the can_delete, in that the can_order` will simply add  the following to each of the forms in your formset, where N = 0, 1, 2, 3, 4...

<input type="number" name="form-N-ORDER" id="id_form-N-ORDER">
```

What can you do with this without JavaScript?  Add an order field to your model, and then you can get the forms order in your post, and set the order field of your model to equal that.

Body:
The can_order adds a field to the formset, just like the can_delete does.  You do not NEED JavaScript, but you can use it, for example if you use JavaScript to drag and drop the forms in the formset. You can sort them and then you can change the name attribute to reflect the new order by accessing the specific form by using it's id in your JavaScript.

The can_order IS like the can_delete, in that the can_order` will simply add  the following to each of the forms in your formset, where N = 0, 1, 2, 3, 4...

<input type="number" name="form-N-ORDER" id="id_form-N-ORDER">

What can you do with this without JavaScript?  Add an order field to your model, and then you can get the forms order in your post, and set the order field of your model to equal that.


问:
How to set delay in Kotlin?
I just want to wait 2 or 3 seconds, I know how to do it in Java and I tried it, but no idea about kotlin

something simple like:

```<code>println("hello")
// a 2 seconds delay
println("world")
</code>```

答:
there are some ways:

1- use Handler(base on mili-second)(Deprecated):

```<code>println("hello")
Handler().postDelayed({
   println("world")
}, 2000)
</code>```

2- by using Executors(base on second):

```<code>println("hello")
Executors.newSingleThreadScheduledExecutor().schedule({
    println("world")
}, 2, TimeUnit.SECONDS)
</code>```

3- by using Timer(base on mili-second):

```<code>println("hello")
Timer().schedule(2000) {
  println("world")
}
</code>```

Title: How to set delay in Kotlin?

Body:
I just want to wait 2 or 3 seconds, I know how to do it in Java and I tried it, but no idea about kotlin

something simple like:

println("hello")
// a 2 seconds delay
println("world")

Body:
there are some ways:

1- use Handler(base on mili-second)(Deprecated):

println("hello")
Handler().postDelayed({
   println("world")
}, 2000)

2- by using Executors(base on second):

println("hello")
Executors.newSingleThreadScheduledExecutor().schedule({
    println("world")
}, 2, TimeUnit.SECONDS)

3- by using Timer(base on mili-second):

println("hello")
Timer().schedule(2000) {
  println("world")
}


问:
JWT Token making Blob return a blank PDF on REACT
I have everything on back-end working to generate this pdf. Tested on postman with token and the function return the pdf as he should.

But on front-end (react) I'm having this problem with the blob opening a blank pdf page. I guess the problem is how I'm passing the JWT Token, because when I comment on back-end all this security stuff, and delete the token on the function of React, he works and generate the pdf.

Can u enlight me?

```<code>import { Form, Row, Col, Button } from "react-bootstrap";
import "./Styles.css";
import api from '../../../Services/api'
import axios from 'axios'
import React, {useState} from 'react'
export default function Form_Recibo() {

  const token = localStorage.getItem("tokenA")

  const [form, setForm] = useState({
    nomeMedico:"",
    nomePaciente:"",
    servico:"",
    valor:"",

  },{
    headers:{"Authorization":`Bearer ${token}`}
   })
  const [verificar, setVerificar] = useState(false)

  function changeVerificar(){

  console.log('entrou')

  if(verificar == false){

    console.log("entrou no if")
    setVerificar(true)

  }else{
    console.log("entrou no else")
    setVerificar(false)
  }

   console.log(verificar)

}

  function gerarRecibo(){
      api.post("recibos/pdf",{
        nomeMedico:form.nomeMedico,
        nomePaciente:form.nomePaciente,
        servico:form.servico,
        valor:form.valor,
        tipoLayout:0,
        exibicaoCampos:{
          exibeNomeMedico:true,
          exibeNomePaciente: true,
          exibeServico:true,
          exibeValor:true
        }
       },{
        headers:{"Authorization":`Bearer ${token}`,responseType :"blob"}
       }).then(response => {

      let blob = new Blob([response.data], {
      type: 'application/pdf'
    });
    let url = window.URL.createObjectURL(blob)
    window.open(url);

      }).catch((erro)=>console.log(erro))

  }

  function changeForm(e){
    const {name, value} = e.target;

    setForm({...form, [name]: value})

}

  return (
    <div className="">
      <Col sm={12}>
        <div>
          <Form>
            <Form.Group className="mb-2" controlId="formBasicPaciente">
              <Form.Label>
                <h6>Nome do Paciente</h6>
              </Form.Label>
              <Form.Control
                type="name"
                placeholder="Digite o nome do paciente"
                name="nomePaciente"
                 value={form.nomePaciente}
                  onChange={changeForm}
              />
              <Form.Text className="text-muted"></Form.Text>
            </Form.Group>
          </Form>
        </div>
      </Col>
      <Col sm={12}>
        <div>
          <Form>
            <Form.Group className="mb-2" controlId="formBasicMedico">
              <Form.Label>
                <h6>Nome do Médico</h6>
              </Form.Label>
              <Form.Control type="name" name="nomeMedico" value={form.nomeMedico} onChange={changeForm} placeholder="Digite o nome do médico" />
              <Form.Text className="text-muted"></Form.Text>
            </Form.Group>
          </Form>
        </div>
      </Col>
      <Row>
        <Col sm={8}>
          <div>
            <Form>
              <Form.Group className="mb-2" controlId="formBasicServico">
                <Form.Label>
                  <h6>Serviço</h6>
                </Form.Label>
                <Form.Control
                  type="name"
                  placeholder="Digite o serviço realizado"
                  name="servico"
                  value={form.servico}
                   onChange={changeForm}
                />
                <Form.Text className="text-muted"></Form.Text>
              </Form.Group>
            </Form>
          </div>
        </Col>
        <Col sm={4}>
          <div>
            <Form>
              <Form.Group className="mb-2" controlId="formBasicValor">
                <Form.Label>
                  <div className="container-valor">
                  <h6>Valor</h6>
                  <Form.Check aria-label="option 1" onClick={changeVerificar}/>
                  </div>
                </Form.Label>
                <Form.Control type="name" name="valor" value={form.valor} onChange={changeForm} placeholder="Digite o valor" />
                <Form.Text className="text-muted"></Form.Text>
              </Form.Group>
            </Form>
          </div>
        </Col>
      </Row>
      <Row>
        <Col className="col-pdf">
          <Button className="botao-pdf" onClick={gerarRecibo}>
            <h6>Gerar PDF</h6>
          </Button>
        </Col>
      </Row>
      <Col className="col-voltar-recibo">
        <Button className="botao-voltar-recibo" href="/">
          <h6>Voltar</h6>
        </Button>
      </Col>
    </div>
  );
}
</code>```

答:
The problem was here

```<code>{
        headers:{"Authorization":`Bearer ${token}`,responseType :"blob"}
       }).then(response => {
</code>```

Should be

```<code>{
        headers:{"Authorization":`Bearer ${token}`}, responseType :"blob"
       }).then(response => {
</code>```

Body:
I have everything on back-end working to generate this pdf. Tested on postman with token and the function return the pdf as he should.

But on front-end (react) I'm having this problem with the blob opening a blank pdf page. I guess the problem is how I'm passing the JWT Token, because when I comment on back-end all this security stuff, and delete the token on the function of React, he works and generate the pdf.

Can u enlight me?

import { Form, Row, Col, Button } from "react-bootstrap";
import "./Styles.css";
import api from '../../../Services/api'
import axios from 'axios'
import React, {useState} from 'react'
export default function Form_Recibo() {

  const token = localStorage.getItem("tokenA")

  const [form, setForm] = useState({
    nomeMedico:"",
    nomePaciente:"",
    servico:"",
    valor:"",

  },{
    headers:{"Authorization":`Bearer ${token}`}
   })
  const [verificar, setVerificar] = useState(false)

  function changeVerificar(){

  console.log('entrou')

  if(verificar == false){

    console.log("entrou no if")
    setVerificar(true)

  }else{
    console.log("entrou no else")
    setVerificar(false)
  }

   console.log(verificar)

}

  function gerarRecibo(){
      api.post("recibos/pdf",{
        nomeMedico:form.nomeMedico,
        nomePaciente:form.nomePaciente,
        servico:form.servico,
        valor:form.valor,
        tipoLayout:0,
        exibicaoCampos:{
          exibeNomeMedico:true,
          exibeNomePaciente: true,
          exibeServico:true,
          exibeValor:true
        }
       },{
        headers:{"Authorization":`Bearer ${token}`,responseType :"blob"}
       }).then(response => {

      let blob = new Blob([response.data], {
      type: 'application/pdf'
    });
    let url = window.URL.createObjectURL(blob)
    window.open(url);

      }).catch((erro)=>console.log(erro))

  }

  function changeForm(e){
    const {name, value} = e.target;

    setForm({...form, [name]: value})

}

  return (

      <Col sm={12}>

          <Form>
            <Form.Group className="mb-2" controlId="formBasicPaciente">
              <Form.Label>

Nome do Paciente

              </Form.Label>
              <Form.Control
                type="name"
                placeholder="Digite o nome do paciente"
                name="nomePaciente"
                 value={form.nomePaciente}
                  onChange={changeForm}
              />
              <Form.Text className="text-muted"></Form.Text>
            </Form.Group>
          </Form>

      </Col>
      <Col sm={12}>

          <Form>
            <Form.Group className="mb-2" controlId="formBasicMedico">
              <Form.Label>

Nome do Médico

              </Form.Label>
              <Form.Control type="name" name="nomeMedico" value={form.nomeMedico} onChange={changeForm} placeholder="Digite o nome do médico" />
              <Form.Text className="text-muted"></Form.Text>
            </Form.Group>
          </Form>

      </Col>
      <Row>
        <Col sm={8}>

            <Form>
              <Form.Group className="mb-2" controlId="formBasicServico">
                <Form.Label>

Serviço

                </Form.Label>
                <Form.Control
                  type="name"
                  placeholder="Digite o serviço realizado"
                  name="servico"
                  value={form.servico}
                   onChange={changeForm}
                />
                <Form.Text className="text-muted"></Form.Text>
              </Form.Group>
            </Form>

        </Col>
        <Col sm={4}>

            <Form>
              <Form.Group className="mb-2" controlId="formBasicValor">
                <Form.Label>

Valor

                  <Form.Check aria-label="option 1" onClick={changeVerificar}/>

                </Form.Label>
                <Form.Control type="name" name="valor" value={form.valor} onChange={changeForm} placeholder="Digite o valor" />
                <Form.Text className="text-muted"></Form.Text>
              </Form.Group>
            </Form>

        </Col>
      </Row>
      <Row>
        <Col className="col-pdf">
          <Button className="botao-pdf" onClick={gerarRecibo}>

Gerar PDF

          </Button>
        </Col>
      </Row>
      <Col className="col-voltar-recibo">
        <Button className="botao-voltar-recibo" href="/">

Voltar

        </Button>
      </Col>

  );
}

Body:
The problem was here

{
        headers:{"Authorization":`Bearer ${token}`,responseType :"blob"}
       }).then(response => {

Should be

{
        headers:{"Authorization":`Bearer ${token}`}, responseType :"blob"
       }).then(response => {


问:
Get output from executing an applescript within a bash script
I tried this technique for storing the output of a command in a BASH variable.  It works with "ls -l", but it doesn't work when I run an apple script.  For example, below is my BASH script calling an apple script.

I tried this:

```<code>OUTPUT="$(osascript myAppleScript.scpt)"
echo "Error is ${OUTPUT}"
</code>```

I can see my apple script running on the command line, and I can see the error outputting on the command line, but when it prints "Error is " it's printing a blank as if the apple script output isn't getting stored.

Note:  My apple script is erroring out on purpose to test this. I'm trying to handle errors correctly by collecting the apple scripts output

答:
You can also use the clipboard as a data bridge. For example, if you wanted to get the stdout into the clipboard you could use:

osascript myAppleScript.scpt | pbcopy
```
<p>In fact, you can copy to clipboard directly from your applescript eg. with:</p>
```set the clipboard to "precious data"

-- or to set the clipboard from a variable
set the clipboard to myPreciousVar
```
<p>To get the data inside a bash script you can read the clipboard to a variable with:</p>
<pre class="lang-sh prettyprint-override"><code>data="$(pbpaste)"
</code>```

See also man pbpase.

Body:
I tried this technique for storing the output of a command in a BASH variable.  It works with "ls -l", but it doesn't work when I run an apple script.  For example, below is my BASH script calling an apple script.

I tried this:

OUTPUT="$(osascript myAppleScript.scpt)"
echo "Error is ${OUTPUT}"

I can see my apple script running on the command line, and I can see the error outputting on the command line, but when it prints "Error is " it's printing a blank as if the apple script output isn't getting stored.

Note:  My apple script is erroring out on purpose to test this. I'm trying to handle errors correctly by collecting the apple scripts output

Body:
You can also use the clipboard as a data bridge. For example, if you wanted to get the stdout into the clipboard you could use:

osascript myAppleScript.scpt | pbcopy

In fact, you can copy to clipboard directly from your applescript eg. with:

set the clipboard to "precious data"

-- or to set the clipboard from a variable
set the clipboard to myPreciousVar

To get the data inside a bash script you can read the clipboard to a variable with:

data="$(pbpaste)"

See also man pbpase.


问:
How can i fetch the element inside 2 {{}} in c #
```<code>var options = new RestClientOptions(Endpoint)
var client = new RestClient(options);
vsr request = new RestRequest();
var response = await client.GetAsync(request);
var requestContent = response.Content;
var parsed = JsonConvert.DeserializeObject(responseContent);
</code>```

the value in parsed is :

```<code>{{
"value1" : "input1",
"value2" : null,
"value3" : {"valuex" : 4,
"valuey" : 5,
"valuez" : 6}
"value4" : 17
}}
</code>```

the value in requestContent :

```<code>"{
\"value1\" : \"input1\",
\"value2\" : null,
\"value3\" : {\"valuex\" : 4,
\"valuey\" : 5,
\"valuez\" : 6}
\"value4\" : 17
}"
</code>```

I'm new to c#, all I want is to parse the data inside valuez which is 6 in this case, I tried so many things on request content like trying like deserializing and trying to parse the parsed value where I debugged and tried to access its child by putting . after parsed similar to what we'd do in javascript for example but nothing seems to be working.

答:
You need to DeserializeObject to an object of your type . example:

```<code>var parsed = JsonConvert.DeserializeObject<object>(responseContent);
</code>```

or

```<code>public class MyClass
{
    public string value1 { get; set; }
    public string value2 { get; set; }
}
var parsed = JsonConvert.DeserializeObject<MyClass>(responseContent);
</code>```

Body:
var options = new RestClientOptions(Endpoint)
var client = new RestClient(options);
vsr request = new RestRequest();
var response = await client.GetAsync(request);
var requestContent = response.Content;
var parsed = JsonConvert.DeserializeObject(responseContent);

the value in parsed is :

{{
"value1" : "input1",
"value2" : null,
"value3" : {"valuex" : 4,
"valuey" : 5,
"valuez" : 6}
"value4" : 17
}}

the value in requestContent :

"{
\"value1\" : \"input1\",
\"value2\" : null,
\"value3\" : {\"valuex\" : 4,
\"valuey\" : 5,
\"valuez\" : 6}
\"value4\" : 17
}"

I'm new to c#, all I want is to parse the data inside valuez which is 6 in this case, I tried so many things on request content like trying like deserializing and trying to parse the parsed value where I debugged and tried to access its child by putting . after parsed similar to what we'd do in javascript for example but nothing seems to be working.

Body:
You need to DeserializeObject to an object of your type . example:

var parsed = JsonConvert.DeserializeObject<object>(responseContent);

or

public class MyClass
{
    public string value1 { get; set; }
    public string value2 { get; set; }
}
var parsed = JsonConvert.DeserializeObject<MyClass>(responseContent);


问:
delete number column in pandas
Can you help me with removing number in read_csv pandas?  For example I want

turn into

I'm wondering if some could help me do this!
Thank you in advance!
My code:

```<code>from time import sleep
from pywebio.input import *
from pywebio.output import *
from pywebio import start_server

import pandas

def app():
    pandas.options.display.max_rows = 6000
    pandas.set_option('display.float_format', lambda x: '%.0f' % x)

    a = pandas.read_csv("https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/latest/owid-covid-latest.csv", delimiter=",", )

    out = (a[["location",  "new_cases", "total_cases","new_deaths","total_deaths"]].to_string().replace('\n','\n'+' '*12))
    out1 = '{:<11} {}'.format('',out)

    Titles1 = out1.replace("location", "Location")
    Titles2 = Titles1.replace("new_cases", "New Cases")
    Titles3 = Titles2.replace("total_deaths", "Total Deaths")
    Titles4 = Titles3.replace("total_cases", "Total Cases")
    Titles5 = Titles4.replace("new_deaths", "New deaths")
    No0 = Titles5.replace(".0", "")
    print(No0)
    put_code(No0)
    while True:
        sleep(1)

start_server(app,636)
</code>```

答: That's the index, and you can't get rid of it unless you make another column the index, which you can do with df = df.set_index('your column').

Title: delete number column in pandas

Body:
Can you help me with removing number in read_csv pandas?  For example I want

turn into

I'm wondering if some could help me do this!
Thank you in advance!
My code:

from time import sleep
from pywebio.input import *
from pywebio.output import *
from pywebio import start_server

import pandas

def app():
    pandas.options.display.max_rows = 6000
    pandas.set_option('display.float_format', lambda x: '%.0f' % x)

    a = pandas.read_csv("https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/latest/owid-covid-latest.csv", delimiter=",", )

    out = (a[["location",  "new_cases", "total_cases","new_deaths","total_deaths"]].to_string().replace('\n','\n'+' '*12))
    out1 = '{:<11} {}'.format('',out)

    Titles1 = out1.replace("location", "Location")
    Titles2 = Titles1.replace("new_cases", "New Cases")
    Titles3 = Titles2.replace("total_deaths", "Total Deaths")
    Titles4 = Titles3.replace("total_cases", "Total Cases")
    Titles5 = Titles4.replace("new_deaths", "New deaths")
    No0 = Titles5.replace(".0", "")
    print(No0)
    put_code(No0)
    while True:
        sleep(1)

start_server(app,636)


问:
How to set a property value based on a variable in Javascript
The problem is I have this piece of code (Jquery UI):

```<code>    $("#dialog-confirm").dialog({
        resizable: false,
        modal: true,
        buttons: {
            "Remove": function() {
                $(this).dialog("close");
            },
            "Cancel": function() {
                $(this).dialog("close");
            }
        }
    });
</code>```

and now I have to internationalize it by giving to each button a word translation. I have the translation on the variables STR_REMOVE and STR_CANCEL, but if I do something like

```<code>        buttons: {
            STR_REMOVE: function() {
                $(this).dialog("close");
            },
            STR_CANCEL: function() {
                $(this).dialog("close");
            }
        }
</code>```

the buttons (the properties) take the value "STR_REMOVE" and "STR_CANCEL", not its content. So, the question is, what can I do?

答:
Try this, not tested:</p>

```<code>$("#dialog-confirm").dialog({
    resizable: false,
    modal: true,
    buttons: {
        "Remove": function() {
            $(this).html(STR_REMOVE);
            $(this).dialog("close");
        },
        "Cancel": function() {
            $(this).html(STR_REMOVE);
            $(this).dialog("close");
        }
    }
});
</code>```

Body:
The problem is I have this piece of code (Jquery UI):

    $("#dialog-confirm").dialog({
        resizable: false,
        modal: true,
        buttons: {
            "Remove": function() {
                $(this).dialog("close");
            },
            "Cancel": function() {
                $(this).dialog("close");
            }
        }
    });

and now I have to internationalize it by giving to each button a word translation. I have the translation on the variables STR_REMOVE and STR_CANCEL, but if I do something like

        buttons: {
            STR_REMOVE: function() {
                $(this).dialog("close");
            },
            STR_CANCEL: function() {
                $(this).dialog("close");
            }
        }

the buttons (the properties) take the value "STR_REMOVE" and "STR_CANCEL", not its content. So, the question is, what can I do?

Body:
Try this, not tested:

$("#dialog-confirm").dialog({
    resizable: false,
    modal: true,
    buttons: {
        "Remove": function() {
            $(this).html(STR_REMOVE);
            $(this).dialog("close");
        },
        "Cancel": function() {
            $(this).html(STR_REMOVE);
            $(this).dialog("close");
        }
    }
});


问:
Implement follow/unfollow in Node.js
I am a beginner and i want to create follow/unfollow functionality in my app.

```<code>router.put('/user/:id/follow', auth.verifyuser, (req, res)=>{

user.findById(req.params.id)
.then((otherUser)=>{
    if(otherUser.followers.includes(req.userInfo._id)){

        return res.json({message: "Already following user"});
    }
    req.userInfo.updateOne({$push: {followings: req.params.id}});
    otherUser.updateOne({ $push: {followers: req.userInfo._id}});
    res.json({message: "following user"});
    console.log(otherUser.followers);

})
.catch((e)=>{
    res.json(e);
})})
</code>```

when running the code it recieves the message "following user" but dosen't add to the database i.e. Mongodb (i'm using MERN stack)

It seems like this block of code is not executing.

```<code>req.userInfo.updateOne({$push: {followings: req.params.id}});
otherUser.updateOne({ $push: {followers: req.userInfo._id}});
</code>```

what am i doing wrong here?

答:
I think that is because req.userInfo and otherUser is an immutable mongo object. try this instead (assuming "user" is your model object):

```<code>user.updateOne(
   { _id:  req.userInfo._id},
   {$push: {followings: req.params.id}
)

  user.updateOne(
       { _id:  otherUser._id},
       { $push: {followers: req.userInfo._id}}
    )
</code>```

note: while comparing _id please check if you are storing as objectId or string.

for your reference: Comparing mongoose _id and strings

Title: Implement follow/unfollow in Node.js

Body:
I am a beginner and i want to create follow/unfollow functionality in my app.

router.put('/user/:id/follow', auth.verifyuser, (req, res)=>{

user.findById(req.params.id)
.then((otherUser)=>{
    if(otherUser.followers.includes(req.userInfo._id)){

        return res.json({message: "Already following user"});
    }
    req.userInfo.updateOne({$push: {followings: req.params.id}});
    otherUser.updateOne({ $push: {followers: req.userInfo._id}});
    res.json({message: "following user"});
    console.log(otherUser.followers);

})
.catch((e)=>{
    res.json(e);
})})

when running the code it recieves the message "following user" but dosen't add to the database i.e. Mongodb (i'm using MERN stack)

It seems like this block of code is not executing.

req.userInfo.updateOne({$push: {followings: req.params.id}});
otherUser.updateOne({ $push: {followers: req.userInfo._id}});

what am i doing wrong here?

Body:
I think that is because req.userInfo and otherUser is an immutable mongo object. try this instead (assuming "user" is your model object):

user.updateOne(
   { _id:  req.userInfo._id},
   {$push: {followings: req.params.id}
)

  user.updateOne(
       { _id:  otherUser._id},
       { $push: {followers: req.userInfo._id}}
    )

note: while comparing _id please check if you are storing as objectId or string.

for your reference: Comparing mongoose _id and strings


问:
Iterate each cell in a specific column in csv by using pandas in Python
I have a CSV file, I want to iterate each row of only one specific column.

Let's say, the column name is "phrase", there are 1000 rows in this column as follows:

ID
phrase

1
apple

2
banana

...
...

How can I iterate each cell in this column?

I have tried to use:

```<code>df = pd.read_csv('myfile.csv', usecols=[1])
for row in df:
    print(row)
</code>```

I only get value of the first row of this column, not iterate each row, as follows:

```<code>Current output:
phrase
</code>```
```<code>Desired output:
phrase # with or without this one are all OK
apple
banana

</code>```

Does anyone know how can I get the desired result? Thanks!

答:
Don't convert row to list. list('abc') is ['a', 'b', 'c'].

The simplest way to achieve this is with df.phrase.tolist():

import pandas as pd

df = pd.read_csv('myfile.csv')
print(df.phrase.tolist())
```
<p>outputs</p>
<pre class="lang-py prettyprint-override"><code>['apple', 'banana']
</code>```

Since you commented that you don't actually have to use pandas, this can be done with the built-in csv module which might be a bit less overwhelming for a beginner:

import csv

with open('myfile.csv') as f:
    reader = csv.DictReader(f)
    phrases = [line['phrase'] for line in reader]

print(phrases)
```
<p>Also outputs</p>
<pre class="lang-py prettyprint-override"><code>['apple', 'banana']
</code>```

Body:
I have a CSV file, I want to iterate each row of only one specific column.

Let's say, the column name is "phrase", there are 1000 rows in this column as follows:

ID
phrase

1
apple

2
banana

...
...

How can I iterate each cell in this column?

I have tried to use:

df = pd.read_csv('myfile.csv', usecols=[1])
for row in df:
    print(row)

I only get value of the first row of this column, not iterate each row, as follows:

Current output:
phrase

Desired output:
phrase # with or without this one are all OK
apple
banana

Does anyone know how can I get the desired result? Thanks!

Body:
Don't convert row to list. list('abc') is ['a', 'b', 'c'].

The simplest way to achieve this is with df.phrase.tolist():

import pandas as pd

df = pd.read_csv('myfile.csv')
print(df.phrase.tolist())

outputs

['apple', 'banana']

Since you commented that you don't actually have to use pandas, this can be done with the built-in csv module which might be a bit less overwhelming for a beginner:

import csv

with open('myfile.csv') as f:
    reader = csv.DictReader(f)
    phrases = [line['phrase'] for line in reader]

print(phrases)

Also outputs

['apple', 'banana']


问:
Best way to loop the angular flex layout with two rows?
I would like to know how to do the ngFor with two rows in angular flex layout.

```<code><div *ngFor="let item of items">
    <div class="container" fxLayout fxLayout.xs="column" fxLayoutAlign="center" fxLayoutGap.xs="0">
        <div class="item item-1" fxFlex="50%">
            <div fxLayoutAlign="center" class="item-label">
                {{item.name}}
            </div>
            <div fxLayoutAlign="center" class="item-value">{{item.value}}</div>
        </div>
        <div class="item item-2" fxFlex="50%">
            <div fxLayoutAlign="center" class="item-label">
                {{item.name}}
            </div>
            <div fxLayoutAlign="center" class="item-value">{{item.value}}</div>
        </div>
    </div>

    <div class="container" fxLayout fxLayout.xs="column" fxLayoutAlign="center" fxLayoutGap.xs="0">
        <div class="item item-3" fxFlex="100%">
            <div fxLayoutAlign="center" class="item-label">
                {{item.name}}
            </div>
            <div fxLayoutAlign="center" class="item-value">{{item.value}}</div>
        </div>
    </div>
</div>
</code>```

Here its looping but each time its printing 3 values for every index. I would like to print index 0 value of first column, index 1 on second column and index 2 value on second row.

答: The "wrap" parameter in the "fxLayout" is used to wrap the child content with the help of "fxFlex"</p>

Body:
I would like to know how to do the ngFor with two rows in angular flex layout.

                {{item.name}}

{{item.value}}

                {{item.name}}

{{item.value}}

                {{item.name}}

{{item.value}}

Here its looping but each time its printing 3 values for every index. I would like to print index 0 value of first column, index 1 on second column and index 2 value on second row.


问:
Understanding x86-64 assembly for simple program in C with a function call
I have simple C program that produces this x86-64 assembly for function func

```<code>#include <stdio.h>
#include <string.h>

void func(char *name)
{
    char buf[90];
    strcpy(buf, name);
    printf("Welcome %s\n", buf);
}

int main(int argc, char *argv[])
{
   func(argv[1]);
   return 0;
}
</code>```

So I think this

```<code>   0x000000000000118d <+4>: push   %rbp
</code>```

pushes the base pointer like placed argument which is char *name

then 0x000000000000118e <+5>:  mov    %rsp,%rbp set stack pointer to what at base pointer I belive that above and this makes stack point points to char *name at this point

then

```<code>   0x0000000000001191 <+8>: add    $0xffffffffffffff80,%rsp
</code>```

I am little unsure about this. Why is 0xffffffffffffff80 added to rsp? What is the point of this instruction. Can any one please tell.

then in next instruction 0x0000000000001195 <+12>: mov    %rdi,-0x78(%rbp)
its just setting -128 decimal to rdi. But still no buffer char buf[90] can be seen, where is my buffer? in following assmebly, can anyone please tell?

also what this line 0x00000000000011a2 <+25>:  mov    %rax,-0x8(%rbp)

```<code>Dump of assembler code for function func:
   0x0000000000001189 <+0>: endbr64
   0x000000000000118d <+4>: push   %rbp
   0x000000000000118e <+5>: mov    %rsp,%rbp
   0x0000000000001191 <+8>: add    $0xffffffffffffff80,%rsp
   0x0000000000001195 <+12>:    mov    %rdi,-0x78(%rbp)
   0x0000000000001199 <+16>:    mov    %fs:0x28,%rax
   0x00000000000011a2 <+25>:    mov    %rax,-0x8(%rbp)
   0x00000000000011a6 <+29>:    xor    %eax,%eax
   0x00000000000011a8 <+31>:    mov    -0x78(%rbp),%rdx
   0x00000000000011ac <+35>:    lea    -0x70(%rbp),%rax
   0x00000000000011b0 <+39>:    mov    %rdx,%rsi
   0x00000000000011b3 <+42>:    mov    %rax,%rdi
   0x00000000000011b6 <+45>:    call   0x1070 <strcpy@plt>
   0x00000000000011bb <+50>:    lea    -0x70(%rbp),%rax
   0x00000000000011bf <+54>:    mov    %rax,%rsi
   0x00000000000011c2 <+57>:    lea    0xe3b(%rip),%rax        # 0x2004
   0x00000000000011c9 <+64>:    mov    %rax,%rdi
   0x00000000000011cc <+67>:    mov    $0x0,%eax
   0x00000000000011d1 <+72>:    call   0x1090 <printf@plt>
   0x00000000000011d6 <+77>:    nop
   0x00000000000011d7 <+78>:    mov    -0x8(%rbp),%rax
   0x00000000000011db <+82>:    sub    %fs:0x28,%rax
   0x00000000000011e4 <+91>:    je     0x11eb <func+98>
   0x00000000000011e6 <+93>:    call   0x1080 <__stack_chk_fail@plt>
   0x00000000000011eb <+98>:    leave
   0x00000000000011ec <+99>:    ret
End of assembler dump.
</code>```

also what in above assembly the use of fs register what this instruction actually doing 0x0000000000001199 <+16>:  mov    %fs:0x28,%rax

答:
As already mentioned in comments, your buffer is on the stack.
In the beginning of the function the rsp is decreased to allow more space (stack grows towards lower addresses, thus rsp is decreased as stack grows). This space is generally used for local variables, arguments passed to the function, and also for other purposes (will get back to it below).
In your case, you may trace back where your buffer buf is by looking at what arguments are passed to the strcpy - the first argument is passed in rdi register, the second - in rsi.

```<code>   0x00000000000011b0 <+39>:    mov    %rdx,%rsi
   0x00000000000011b3 <+42>:    mov    %rax,%rdi
   0x00000000000011b6 <+45>:    call   0x1070 <strcpy@plt>
</code>```

In the snippet above you can see that the pointer to buf (first argument to strcpy) was in rax prior to being put to rdi. And rax got its value from this instruction:

```<code>   0x00000000000011ac <+35>:    lea    -0x70(%rbp),%rax
</code>```

which means "load effective address (i.e. a pointer) that resides at offset -0x70 from the address rbp is pointing to". rbp points to where the stack pointer was in the beginning of the function (function frame pointer).

So it answers where the compiler has put your buffer.

Now for other questions:

then in next instruction 0x0000000000001195 <+12>:
mov   %rdi,-0x78(%rbp) its just setting -128 decimal to rdi.

As we said, rdi holds the first argument to a function. Here it holds a first argument to func(), which is a pointer to name. This instruction puts this argument onto a stack at an offset of -0x78 from rbp - 8 bytes right before the space reserved for your buffer buf.

And the last two questions are related:

also what this line 0x00000000000011a2 <+25>:  mov    %rax,-0x8(%rbp)

and

also what in above assembly the use of fs register what this instruction actually doing 0x0000000000001199 <+16>:  mov    %fs:0x28,%rax

```<code>   0x0000000000001199 <+16>:    mov    %fs:0x28,%rax
   0x00000000000011a2 <+25>:    mov    %rax,-0x8(%rbp)
   ...
   ...
   0x00000000000011d7 <+78>:    mov    -0x8(%rbp),%rax
   0x00000000000011db <+82>:    sub    %fs:0x28,%rax
   0x00000000000011e4 <+91>:    je     0x11eb <func+98>
   0x00000000000011e6 <+93>:    call   0x1080 <__stack_chk_fail@plt>
   0x00000000000011eb <+98>:    leave
</code>```

There is some value at %fs:0x28 (which denotes an offset of 0x28 in an fs segment). And this value is being placed (via rax) to the stack. To the very first 8 bytes in the space allocated for your function. And there it stays, hopefully untouched, until the function is about to return. There, it checks whether the value on the stack was changed. If it remained unchanged, the jump (je) will take you to the leave and the function will return. If, by any chance, the value on the stack got changed - your code has caused a stack overflow (aha!) and a call to __stack_chk_fail will be triggered, which perhaps will warn you about the overflow, and perhaps dump some debug information. So the value at %fs:0x28 is a kind of a unique magic/canary value.

And one last thing - about why add    $0xffffffffffffff80,%rsp was used to allocate space on the stack, and not sub - other compilers do use sub as did GCC (version 8.5.0 20210514):

```<code>    sub    $0x70,%rsp
</code>```

It allocated less, and one of the reasons is that the compiler did not reserve space for the stack overflow check.

Body:
I have simple C program that produces this x86-64 assembly for function func

#include <stdio.h>
#include <string.h>

void func(char *name)
{
    char buf[90];
    strcpy(buf, name);
    printf("Welcome %s\n", buf);
}

int main(int argc, char *argv[])
{
   func(argv[1]);
   return 0;
}

So I think this

   0x000000000000118d <+4>: push   %rbp

pushes the base pointer like placed argument which is char *name

then 0x000000000000118e <+5>:  mov    %rsp,%rbp set stack pointer to what at base pointer I belive that above and this makes stack point points to char *name at this point

then

   0x0000000000001191 <+8>: add    $0xffffffffffffff80,%rsp

I am little unsure about this. Why is 0xffffffffffffff80 added to rsp? What is the point of this instruction. Can any one please tell.

then in next instruction 0x0000000000001195 <+12>: mov    %rdi,-0x78(%rbp)
its just setting -128 decimal to rdi. But still no buffer char buf[90] can be seen, where is my buffer? in following assmebly, can anyone please tell?

also what this line 0x00000000000011a2 <+25>:  mov    %rax,-0x8(%rbp)

Dump of assembler code for function func:
   0x0000000000001189 <+0>: endbr64
   0x000000000000118d <+4>: push   %rbp
   0x000000000000118e <+5>: mov    %rsp,%rbp
   0x0000000000001191 <+8>: add    $0xffffffffffffff80,%rsp
   0x0000000000001195 <+12>:    mov    %rdi,-0x78(%rbp)
   0x0000000000001199 <+16>:    mov    %fs:0x28,%rax
   0x00000000000011a2 <+25>:    mov    %rax,-0x8(%rbp)
   0x00000000000011a6 <+29>:    xor    %eax,%eax
   0x00000000000011a8 <+31>:    mov    -0x78(%rbp),%rdx
   0x00000000000011ac <+35>:    lea    -0x70(%rbp),%rax
   0x00000000000011b0 <+39>:    mov    %rdx,%rsi
   0x00000000000011b3 <+42>:    mov    %rax,%rdi
   0x00000000000011b6 <+45>:    call   0x1070 <strcpy@plt>
   0x00000000000011bb <+50>:    lea    -0x70(%rbp),%rax
   0x00000000000011bf <+54>:    mov    %rax,%rsi
   0x00000000000011c2 <+57>:    lea    0xe3b(%rip),%rax        # 0x2004
   0x00000000000011c9 <+64>:    mov    %rax,%rdi
   0x00000000000011cc <+67>:    mov    $0x0,%eax
   0x00000000000011d1 <+72>:    call   0x1090 <printf@plt>
   0x00000000000011d6 <+77>:    nop
   0x00000000000011d7 <+78>:    mov    -0x8(%rbp),%rax
   0x00000000000011db <+82>:    sub    %fs:0x28,%rax
   0x00000000000011e4 <+91>:    je     0x11eb <func+98>
   0x00000000000011e6 <+93>:    call   0x1080 <__stack_chk_fail@plt>
   0x00000000000011eb <+98>:    leave
   0x00000000000011ec <+99>:    ret
End of assembler dump.

also what in above assembly the use of fs register what this instruction actually doing 0x0000000000001199 <+16>:  mov    %fs:0x28,%rax

Body:
As already mentioned in comments, your buffer is on the stack.
In the beginning of the function the rsp is decreased to allow more space (stack grows towards lower addresses, thus rsp is decreased as stack grows). This space is generally used for local variables, arguments passed to the function, and also for other purposes (will get back to it below).
In your case, you may trace back where your buffer buf is by looking at what arguments are passed to the strcpy - the first argument is passed in rdi register, the second - in rsi.

   0x00000000000011b0 <+39>:    mov    %rdx,%rsi
   0x00000000000011b3 <+42>:    mov    %rax,%rdi
   0x00000000000011b6 <+45>:    call   0x1070 <strcpy@plt>

In the snippet above you can see that the pointer to buf (first argument to strcpy) was in rax prior to being put to rdi. And rax got its value from this instruction:

   0x00000000000011ac <+35>:    lea    -0x70(%rbp),%rax

which means "load effective address (i.e. a pointer) that resides at offset -0x70 from the address rbp is pointing to". rbp points to where the stack pointer was in the beginning of the function (function frame pointer).

So it answers where the compiler has put your buffer.

Now for other questions:

then in next instruction 0x0000000000001195 <+12>:
mov   %rdi,-0x78(%rbp) its just setting -128 decimal to rdi.

As we said, rdi holds the first argument to a function. Here it holds a first argument to func(), which is a pointer to name. This instruction puts this argument onto a stack at an offset of -0x78 from rbp - 8 bytes right before the space reserved for your buffer buf.

And the last two questions are related:

also what this line 0x00000000000011a2 <+25>:  mov    %rax,-0x8(%rbp)

and

also what in above assembly the use of fs register what this instruction actually doing 0x0000000000001199 <+16>:  mov    %fs:0x28,%rax

   0x0000000000001199 <+16>:    mov    %fs:0x28,%rax
   0x00000000000011a2 <+25>:    mov    %rax,-0x8(%rbp)
   ...
   ...
   0x00000000000011d7 <+78>:    mov    -0x8(%rbp),%rax
   0x00000000000011db <+82>:    sub    %fs:0x28,%rax
   0x00000000000011e4 <+91>:    je     0x11eb <func+98>
   0x00000000000011e6 <+93>:    call   0x1080 <__stack_chk_fail@plt>
   0x00000000000011eb <+98>:    leave

There is some value at %fs:0x28 (which denotes an offset of 0x28 in an fs segment). And this value is being placed (via rax) to the stack. To the very first 8 bytes in the space allocated for your function. And there it stays, hopefully untouched, until the function is about to return. There, it checks whether the value on the stack was changed. If it remained unchanged, the jump (je) will take you to the leave and the function will return. If, by any chance, the value on the stack got changed - your code has caused a stack overflow (aha!) and a call to __stack_chk_fail will be triggered, which perhaps will warn you about the overflow, and perhaps dump some debug information. So the value at %fs:0x28 is a kind of a unique magic/canary value.

And one last thing - about why add    $0xffffffffffffff80,%rsp was used to allocate space on the stack, and not sub - other compilers do use sub as did GCC (version 8.5.0 20210514):

    sub    $0x70,%rsp

It allocated less, and one of the reasons is that the compiler did not reserve space for the stack overflow check.


问:
I'm trying to store ID of three employees using Dynamic Memory Allocation
Code -

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char *e;
    int len;

    for (int i = 1; i < 4; i++)
    {
        printf("Enter the size of the ID of the Employee %d\n", i);
        scanf("%d", &len);

        printf("Enter Employee ID of Employee %d\n", i);
        scanf("%s", &e);
    }

    e = (char *)malloc((len + 1) * sizeof(char));

    for (int i = 1; i < 4; i++)
    {
        printf("ID of Employee %d is %s\n", i, e);
    }

    return 0;
}
</code>```

Terminal -

```<code>Enter the size of the ID of the Employee 1
2
Enter Employee ID of Employee 1
A2
Enter the size of the ID of the Employee 2
2
Enter Employee ID of Employee 2
A7
Enter the size of the ID of the Employee 3
3
Enter Employee ID of Employee 3
AA1
</code>```

Expected Output -

```<code>ID of Employee 1 is A2
ID of Employee 2 is A7
ID of Employee 3 is AA1
</code>```

Output I am getting -

```<code>»D of Employee 1 is Φ
»D of Employee 2 is Φ
»D of Employee 3 is Φ
</code>```

Here, »D and Φ refers to Garbage Value that changes every time when I run it in another terminal

I'm just learning the basics of Dynamic Memory Allocation but getting problems even in that

Pls Help

答:
In addition to the comments above, you have a glaring mistake in that you are attempting to use the memory before you've allocated it. Try this:

```<code>#include <string.h>

#define MAX_EMP 3

int main()
{
    char *e[MAX_EMP];
    int len[3];

    for (int i = 0; i < MAX_EMP; i++)
    {
        printf("Enter the size of the ID of the Employee %d\n", i + 1);
        scanf(" %d ", &len[i]);

        e[i] = (char*)malloc((len + 1) * sizeof(char));
        printf("Enter Employee ID of Employee %d\n", i + 1);
        scanf(" %s ", e[i]);
    }

    for (int i = 0; i < MAX_EMP; i++)
        printf("ID of Employee %d is %s\n", i + 1, e[i]);

    return 0;
}
</code>```

Also, note that memory resources are rarely at such a premium that dynamic memory allocation makes sense for such small strings. It's more practical to just do this:

```<code>#include <string.h>

#define MAX_EMP 3
#define MAX_LEN 10

int main()
{
    char e[MAX_EMP][MAX_LEN + 1];

    for (int i = 0; i < MAX_EMP; i++)
    {
        printf("Enter Employee ID of Employee #%d\n", i + 1);
        fgets(e[i],MAX_LEN + 1,stdin);
    }

    for (int i = 0; i < MAX_EMP; i++)
        printf("ID of Employee #%d is %s\n", i + 1, e[i]);

    return 0;
}
</code>```

Body:
Code -

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char *e;
    int len;

    for (int i = 1; i < 4; i++)
    {
        printf("Enter the size of the ID of the Employee %d\n", i);
        scanf("%d", &len);

        printf("Enter Employee ID of Employee %d\n", i);
        scanf("%s", &e);
    }

    e = (char *)malloc((len + 1) * sizeof(char));

    for (int i = 1; i < 4; i++)
    {
        printf("ID of Employee %d is %s\n", i, e);
    }

    return 0;
}

Terminal -

Enter the size of the ID of the Employee 1
2
Enter Employee ID of Employee 1
A2
Enter the size of the ID of the Employee 2
2
Enter Employee ID of Employee 2
A7
Enter the size of the ID of the Employee 3
3
Enter Employee ID of Employee 3
AA1

Expected Output -

ID of Employee 1 is A2
ID of Employee 2 is A7
ID of Employee 3 is AA1

Output I am getting -

»D of Employee 1 is Φ
»D of Employee 2 is Φ
»D of Employee 3 is Φ

Here, »D and Φ refers to Garbage Value that changes every time when I run it in another terminal

I'm just learning the basics of Dynamic Memory Allocation but getting problems even in that

Pls Help

Body:
In addition to the comments above, you have a glaring mistake in that you are attempting to use the memory before you've allocated it. Try this:

#include <string.h>

#define MAX_EMP 3

int main()
{
    char *e[MAX_EMP];
    int len[3];

    for (int i = 0; i < MAX_EMP; i++)
    {
        printf("Enter the size of the ID of the Employee %d\n", i + 1);
        scanf(" %d ", &len[i]);

        e[i] = (char*)malloc((len + 1) * sizeof(char));
        printf("Enter Employee ID of Employee %d\n", i + 1);
        scanf(" %s ", e[i]);
    }

    for (int i = 0; i < MAX_EMP; i++)
        printf("ID of Employee %d is %s\n", i + 1, e[i]);

    return 0;
}

Also, note that memory resources are rarely at such a premium that dynamic memory allocation makes sense for such small strings. It's more practical to just do this:

#include <string.h>

#define MAX_EMP 3
#define MAX_LEN 10

int main()
{
    char e[MAX_EMP][MAX_LEN + 1];

    for (int i = 0; i < MAX_EMP; i++)
    {
        printf("Enter Employee ID of Employee #%d\n", i + 1);
        fgets(e[i],MAX_LEN + 1,stdin);
    }

    for (int i = 0; i < MAX_EMP; i++)
        printf("ID of Employee #%d is %s\n", i + 1, e[i]);

    return 0;
}


问:
Error in summary.connection(connection) : invalid connection when running GeoLift example
I am working through https://github.com/ArturoEsquerra/GeoLift/blob/master/vignettes/GeoLift_Walkthrough.md and getting error message: Error in summary.connection(connection) : invalid connection. when I try to execute the following:

```<code>resultsSearch <- GeoLiftPower.search(data = GeoTestData_PreTest,
                                     treatment_periods = c(15),
                                     N = c(2,3,4),
                                     horizon = 50,
                                     Y_id = "Y",
                                     location_id = "location",
                                     time_id = "time",
                                     top_results = 20,
                                     alpha = 0.1,
                                     type = "pValue",
                                     fixed_effects = TRUE,
                                     ProgressBar = TRUE)
</code>```

I have tried the solution here: Error in summary.connection(connection) : invalid connection, but it hasnt resolved the issue.

Any ideas / solutions for this?

答: You should try adding parallel = FALSE in the GeoLiftPower.Search parameters.</p>

Body:
I am working through https://github.com/ArturoEsquerra/GeoLift/blob/master/vignettes/GeoLift_Walkthrough.md and getting error message: Error in summary.connection(connection) : invalid connection. when I try to execute the following:

resultsSearch <- GeoLiftPower.search(data = GeoTestData_PreTest,
                                     treatment_periods = c(15),
                                     N = c(2,3,4),
                                     horizon = 50,
                                     Y_id = "Y",
                                     location_id = "location",
                                     time_id = "time",
                                     top_results = 20,
                                     alpha = 0.1,
                                     type = "pValue",
                                     fixed_effects = TRUE,
                                     ProgressBar = TRUE)

I have tried the solution here: Error in summary.connection(connection) : invalid connection, but it hasnt resolved the issue.

Any ideas / solutions for this?


问:
Textfield with arial regular and arial bold does not work together in flashcs5?
I have two dynamic classic TextFields in a  MovieClip, one with Arial Regular embedded and the other with Arial Bold, but the second TextField is not showing the bold text. It shows regular text. Here is how I am doing it:

a busy cat http://cubixshade.com/textz/sample.jpg

I change the text of two fields using

```<code>mc.txt1.text="changed text90";

mc.txt2.text="changed text90";
</code>```

Both are shown in Arial Regular style.

答: i noticed when working with fonts in flash that some font won't diplay correctelly even when i embedded them just try another font and everything gonna be alright</p>

Body:
I have two dynamic classic TextFields in a  MovieClip, one with Arial Regular embedded and the other with Arial Bold, but the second TextField is not showing the bold text. It shows regular text. Here is how I am doing it:

a busy cat http://cubixshade.com/textz/sample.jpg

I change the text of two fields using

mc.txt1.text="changed text90";

mc.txt2.text="changed text90";

Both are shown in Arial Regular style.


问:
Read file line by line using non-blocking IO with reactive wrapper in Java
Is there any way to read a local file line by line without blocking any thread (background thread pool counts as blocking) using built-in CompletableFuture or a reactive stream library like RxJava or Reactor?

(It's interesting that there are many non-blocking IO libraries for HTTP and different databases like Mongo, Redis, etc., but I wasn't able to find anything for a simple file read.)

答:
Although, I got answer for my question from Alexander, I'd like to share the most reactive ways that I found to read a file line by line. Both solutions use AsynchronousFileChannel under the hood which is not always non-blocking but still okay to use in a reactive environment since it uses a dedicated thread pool for IO work.

Using utils from Spring Framework (ideal in WebFlux application)

import org.springframework.core.codec.StringDecoder;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;

import java.nio.channels.AsynchronousFileChannel;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

public class AsyncFileRead {
    public Flux<String> lines() {
        StringDecoder stringDecoder = StringDecoder.textPlainOnly();

        return DataBufferUtils.readAsynchronousFileChannel(() -> AsynchronousFileChannel.open(Path.of("test/sample.txt"),
                StandardOpenOption.READ), DefaultDataBufferFactory.sharedInstance, 4096)
            .transform(dataBufferFlux -> stringDecoder.decode(dataBufferFlux, null, null, null));
    }
}
```
<h1>Using RxIo library</h1>
<pre class="lang-java prettyprint-override"><code>import org.javaync.io.AsyncFiles;
import reactor.core.publisher.Flux;

import java.nio.file.Path;

public class AsyncFileRead {
    public Flux<String> lines() {
        return Flux.from(AsyncFiles.lines(Path.of("test/sample.txt")));
    }
}
</code>```

Body:
Although, I got answer for my question from Alexander, I'd like to share the most reactive ways that I found to read a file line by line. Both solutions use AsynchronousFileChannel under the hood which is not always non-blocking but still okay to use in a reactive environment since it uses a dedicated thread pool for IO work.

Using utils from Spring Framework (ideal in WebFlux application)

import org.springframework.core.codec.StringDecoder;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;

import java.nio.channels.AsynchronousFileChannel;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

public class AsyncFileRead {
    public Flux<String> lines() {
        StringDecoder stringDecoder = StringDecoder.textPlainOnly();

        return DataBufferUtils.readAsynchronousFileChannel(() -> AsynchronousFileChannel.open(Path.of("test/sample.txt"),
                StandardOpenOption.READ), DefaultDataBufferFactory.sharedInstance, 4096)
            .transform(dataBufferFlux -> stringDecoder.decode(dataBufferFlux, null, null, null));
    }
}

Using RxIo library

import org.javaync.io.AsyncFiles;
import reactor.core.publisher.Flux;

import java.nio.file.Path;

public class AsyncFileRead {
    public Flux<String> lines() {
        return Flux.from(AsyncFiles.lines(Path.of("test/sample.txt")));
    }
}


问:
Mocking react-native-async-storage on Jest
I am testing functions which depend on @react-native-community/async-storage, so obviously my tests must mock that library.

And so I do this inside of my jestSetupFile.js:

```<code>import mockAsyncStorage from '@react-native-community/async-storage/jest/async-storage-mock';
jest.mock('@react-native-community/async-storage', () => mockAsyncStorage);
</code>```

Which is direct instruction from https://github.com/react-native-community/react-native-async-storage/blob/master/docs/Jest-integration.md

However, the file being exported has type keywords, which my JavaScript environment cannot parse:

```<code>  ● Test suite failed to run

    /Users/someuser/myprojects/myproject/node_modules/@react-native-community/async-storage/jest/async-storage-mock.js:6
    type KeysType = Array<string>;
         ^^^^^^^^

    SyntaxError: Unexpected identifier
</code>```

Sure enough, when I inspect the async-storage-mock.js file at that path, it contains the type keywords, which I believe are the root cause of this issue.

What am I doing wrong here?

答:
As of 2022, you can do that with community package @react-native-community/async-storage recommended by React-Native official documentation

Everything is explain in their doc

In your Jest config (probably in package.json) add setup files location:

"jest": {
  "setupFiles": ["./path/to/jestSetupFile.js"]
}
```
<ol start="2">
<li>Inside your setup file, set up Async Storage mocking:</li>
</ol>
<pre class="lang-js prettyprint-override"><code>import mockAsyncStorage from '@react-native-async-storage/async-storage/jest/async-storage-mock';

jest.mock('@react-native-async-storage/async-storage', () => mockAsyncStorage);
</code>```

Body:
I am testing functions which depend on @react-native-community/async-storage, so obviously my tests must mock that library.

And so I do this inside of my jestSetupFile.js:

import mockAsyncStorage from '@react-native-community/async-storage/jest/async-storage-mock';
jest.mock('@react-native-community/async-storage', () => mockAsyncStorage);

Which is direct instruction from https://github.com/react-native-community/react-native-async-storage/blob/master/docs/Jest-integration.md

However, the file being exported has type keywords, which my JavaScript environment cannot parse:

  ● Test suite failed to run

    /Users/someuser/myprojects/myproject/node_modules/@react-native-community/async-storage/jest/async-storage-mock.js:6
    type KeysType = Array<string>;
         ^^^^^^^^

    SyntaxError: Unexpected identifier

Sure enough, when I inspect the async-storage-mock.js file at that path, it contains the type keywords, which I believe are the root cause of this issue.

What am I doing wrong here?

Body:
As of 2022, you can do that with community package @react-native-community/async-storage recommended by React-Native official documentation

Everything is explain in their doc

In your Jest config (probably in package.json) add setup files location:

"jest": {
  "setupFiles": ["./path/to/jestSetupFile.js"]
}

Inside your setup file, set up Async Storage mocking:

import mockAsyncStorage from '@react-native-async-storage/async-storage/jest/async-storage-mock';

jest.mock('@react-native-async-storage/async-storage', () => mockAsyncStorage);


问:
Count total amount of parts in a dataset
I have the attached Dataset and would like to count the total amount for each part.
How can I do that in Excel ? :)

Feel free to directly edit the spreadsheet:

https://docs.google.com/spreadsheets/d/11p9aj_QUhnPMCeXKrZ6-bIZ-v8PTLw6hKDtOmxQHELQ/edit?usp=sharing

Thank you ! :)

Pic of the Dataset

答:
Mayukh Bhattacharya's Answer:

Use a UNIQUE Formula for PART → =UNIQUE(B5:B13)

For AMOUNT, use the formula =SUMIF(B5:B13,G5,C5:C13).

I have already updated in the link!


问:
NodeJS - https - TypeError [ERR_INVALID_HTTP_TOKEN]: Header name must be a valid HTTP token ["Accept"]
I have a NodeJS code that uses https module as: https.request(options, (res) => {...... where options is an object like

```<code>const options = {
    hostname: SERVICE_HOSTNAME,
    path: BASE_PATH,
    method: 'GET',
    headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        ApplicationId,
        Authorization
    }
  };
</code>```

My problems start when I add Accept header. I getting an error:

```<code>TypeError [ERR_INVALID_HTTP_TOKEN]: Header name must be a valid HTTP token ["Accept"]
    at ClientRequest.setHeader (_http_outgoing.js:472:3)
    at new ClientRequest (_http_client.js:203:14)
    at Object.request (https.js:289:10)
</code>```

How Accept header would be invalid?

答: If you have problem with res.writeHead(200,  {'Content-Type':'text/json'}); ------> You should rename word (text) to (Application) like this.

Body:
I have a NodeJS code that uses https module as: https.request(options, (res) => {...... where options is an object like

const options = {
    hostname: SERVICE_HOSTNAME,
    path: BASE_PATH,
    method: 'GET',
    headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        ApplicationId,
        Authorization
    }
  };

My problems start when I add Accept header. I getting an error:

TypeError [ERR_INVALID_HTTP_TOKEN]: Header name must be a valid HTTP token ["Accept"]
    at ClientRequest.setHeader (_http_outgoing.js:472:3)
    at new ClientRequest (_http_client.js:203:14)
    at Object.request (https.js:289:10)

How Accept header would be invalid?


问:
Find the last value in a "rolled-over" sequence with a stored procedure?
Suppose I had a set of alpha-character identifiers of a set length, e.g. always five letters, and they are assigned in such a way that they are always incremented sequentially (GGGGZ --> GGGHA, etc.).   Now, if I get to ZZZZZ, since the length is fixed, I must "roll over" to AAAAA.  I might have a contiguous block from ZZZAA through AAAAM.  I want to write a sproc that will give me the "next" identifier, in this case AAAAN.

If I didn't have this "rolling over" issue, of course, I'd just ORDER BY DESC and grab the top result.  But I'm at a bit of a loss now -- and it doesn't help at all that SQL is not my strongest language.

If I have to I can move this to my C# calling code, but a sproc would be a better fit.

ETA: I would like to avoid changing the schema (new column or new table); I'd rather just be able to "figure it out".  I might even prefer to do it brute force (e.g. start at the lowest value and increment until I find a "hole"), even though that could get expensive.  If you have an answer that does not modify the schema, it'd be a better solution for my needs.

答:
A problem here is that you can't really tell from the data where the "last" entry is unless there is more detail as to how the old entries are deleted.

If I understand correctly, you are wrapping around at the end of the sequence, which means you must be deleting some of your old data to make space. However if the data isn't deleted in a perfectly uniform manner, you'll end up with fragments, like below:

```<code>ABCD   HIJKL NOPQRS   WXYZ
</code>```

You'll notice that there is no obvious next value...D could be the last value created, but it might also be L or S.

At best you could look for the first or last missing element (use a stored procedure to perform a x+1 check just like you would to find a missing element in an integer sequence), but it's not going to provide any special result for rolled-over lists.

OwnerDisplayName: Coderer

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Coderer

Body:
A problem here is that you can't really tell from the data where the "last" entry is unless there is more detail as to how the old entries are deleted.

If I understand correctly, you are wrapping around at the end of the sequence, which means you must be deleting some of your old data to make space. However if the data isn't deleted in a perfectly uniform manner, you'll end up with fragments, like below:

ABCD   HIJKL NOPQRS   WXYZ

You'll notice that there is no obvious next value...D could be the last value created, but it might also be L or S.

At best you could look for the first or last missing element (use a stored procedure to perform a x+1 check just like you would to find a missing element in an integer sequence), but it's not going to provide any special result for rolled-over lists.

OwnerDisplayName: David


问:
select * only return one value
I want select multiple (all) values from table Account.

```<code>string query = "SELECT * FROM Account";
        SqlConnection connection = new SqlConnection(connectionString);
        SqlCommand command = new SqlCommand(query, connection);
        SqlDataReader reader;
        connection.Open();
        reader = command.ExecuteReader();
        reader.Read();
        label1.Text = reader["PasswordHash"].ToString();
        connection.Close();
</code>```

Why is this always returning only the first row. Actually it return one row, because if I set in where clause something like where id = 2 and id = 3 it still returns only one value.
Table have more than one value i checked form Management Studio, there query run as they should.

Thanks in advance.

答:
Because you are not looping through the query results, it shows up only one result.

```<code>string query = "SELECT * FROM Account";
    SqlConnection connection = new SqlConnection(connectionString);
    SqlCommand command = new SqlCommand(query, connection);
    SqlDataReader reader;
    connection.Open();
    reader = command.ExecuteReader();
    While(reader.Read())
{
    label1.Text += " " +reader["PasswordHash"].ToString();
}
    connection.Close();
</code>```

The above code loops through the query results and will give you what you want in a concatenated string assigned to label1.text. You can also view the results by inserting Console.WriteLine(reader["PasswordHash"].ToString()); in the while loop

Title: select * only return one value

Body:
I want select multiple (all) values from table Account.

string query = "SELECT * FROM Account";
        SqlConnection connection = new SqlConnection(connectionString);
        SqlCommand command = new SqlCommand(query, connection);
        SqlDataReader reader;
        connection.Open();
        reader = command.ExecuteReader();
        reader.Read();
        label1.Text = reader["PasswordHash"].ToString();
        connection.Close();

Why is this always returning only the first row. Actually it return one row, because if I set in where clause something like where id = 2 and id = 3 it still returns only one value.
Table have more than one value i checked form Management Studio, there query run as they should.

Thanks in advance.

Body:
Because you are not looping through the query results, it shows up only one result.

string query = "SELECT * FROM Account";
    SqlConnection connection = new SqlConnection(connectionString);
    SqlCommand command = new SqlCommand(query, connection);
    SqlDataReader reader;
    connection.Open();
    reader = command.ExecuteReader();
    While(reader.Read())
{
    label1.Text += " " +reader["PasswordHash"].ToString();
}
    connection.Close();

The above code loops through the query results and will give you what you want in a concatenated string assigned to label1.text. You can also view the results by inserting Console.WriteLine(reader["PasswordHash"].ToString()); in the while loop