问:
Javascript Redirect Timeout
I am trying to start opera from command line and redirect it to a page in 30 seconds. What I'm trying now is:

```<code>C:\Programme\Opera\opera.exe -newpage javascript:function%20func1(){window.location.href='http://localhost/';}setTimeout('func1()',30000);
</code>```

Which is returing a page with as content "1". Func1 is never called. Is there a good way to solve this inline? Or should I create a page with this content?

答: Regarding the original example, you should have put void() around the setTimeout() call. setTimeout() returns a timeout identifier (in this case the number 1) which becomes the output of the javascript: URL. Whatever a javascript: URL 'returns' is used as the source for a document.</p>

Title: Javascript Redirect Timeout

Body:
I am trying to start opera from command line and redirect it to a page in 30 seconds. What I'm trying now is:

C:\Programme\Opera\opera.exe -newpage javascript:function%20func1(){window.location.href='http://localhost/';}setTimeout('func1()',30000);

Which is returing a page with as content "1". Func1 is never called. Is there a good way to solve this inline? Or should I create a page with this content?


来源: stackexchange

问:
is there any method in pandas to convert dataframe from day to defaullt d/m/y format?
I would like to convert all day in the data-frame into day/feb/2020 format
here date field consist only day

from first one convert the date field like this

My current approach is:

```<code>import datetime

y=[]
for day in planned_ds.Date:
    x=datetime.datetime(2020, 5, day)

    print(x)
</code>```

Is there any easy method to convert all day data-frame to d/m/y format?

答:
One way as assuming you have data like

```<code>df = pd.DataFrame([1,2,3,4,5], columns=["date"])
</code>```

is to convert them to dates and then shift them to start when you need them to:

```<code>pd.to_datetime(df["date"], unit="D") - pd.datetime(1970,1,1) + pd.datetime(2020,1,31)
</code>```

this results in

```<code>0   2020-02-01
1   2020-02-02
2   2020-02-03
3   2020-02-04
4   2020-02-05
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I would like to convert all day in the data-frame into day/feb/2020 format
here date field consist only day

from first one convert the date field like this

My current approach is:

import datetime

y=[]
for day in planned_ds.Date:
    x=datetime.datetime(2020, 5, day)

    print(x)

Is there any easy method to convert all day data-frame to d/m/y format?

Body:
One way as assuming you have data like

df = pd.DataFrame([1,2,3,4,5], columns=["date"])

is to convert them to dates and then shift them to start when you need them to:

pd.to_datetime(df["date"], unit="D") - pd.datetime(1970,1,1) + pd.datetime(2020,1,31)

this results in

0   2020-02-01
1   2020-02-02
2   2020-02-03
3   2020-02-04
4   2020-02-05


问:
Animate change of view background color on Android
How do you animate the change of background color of a view on Android?

For example:

I have a view with a red background color. The background color of the view changes to blue. How can I do a smooth transition between colors?

If this can't be done with views, an alternative will be welcome.

答:
Use the below function for Kotlin:

```<code>private fun animateColorValue(view: View) {
    val colorAnimation =
        ValueAnimator.ofObject(ArgbEvaluator(), Color.GRAY, Color.CYAN)
    colorAnimation.duration = 500L
    colorAnimation.addUpdateListener { animator -> view.setBackgroundColor(animator.animatedValue as Int) }
    colorAnimation.start()
}
</code>```

Pass whatever view you want to change color of.

ContentLicense: CC BY-SA 3.0

Body:
Use the below function for Kotlin:

private fun animateColorValue(view: View) {
    val colorAnimation =
        ValueAnimator.ofObject(ArgbEvaluator(), Color.GRAY, Color.CYAN)
    colorAnimation.duration = 500L
    colorAnimation.addUpdateListener { animator -> view.setBackgroundColor(animator.animatedValue as Int) }
    colorAnimation.start()
}

Pass whatever view you want to change color of.


问:
Why use static_cast rather than dynamic_cast in here?
I copy the following text from the book More Effective C++.

Item 31:  Making functions virtual with respect to more than one object.

```<code>class GameObject { ... };
class SpaceShip: public GameObject { ... };
class SpaceStation: public GameObject { ... };
class Asteroid: public GameObject { ... };
</code>```

The most common approach to double-dispatching returns us to the unforgiving world of virtual function emulation via chains of if-then-elses. In this harsh world, we first discover the real type of otherObject, then we test it against all the possibilities:

```<code>void SpaceShip::collide(GameObject& otherObject)
{
  const type_info& objectType = typeid(otherObject);

  if (objectType == typeid(SpaceShip)) {
    SpaceShip& ss = static_cast<SpaceShip&>(otherObject);

    process a SpaceShip-SpaceShip collision;

  }
  else if (objectType == typeid(SpaceStation)) {
    SpaceStation& ss =
      static_cast<SpaceStation&>(otherObject);

    process a SpaceShip-SpaceStation collision;

  }
...
}
</code>```

Here is the question:

Q1> Why we use static_cast here rather than obvious dynamic_cast?

Q2>　Are they same in this case?

thank you

// updated //

In fact, I am more interested in question 2.

For example,

```<code>class base {};
class subclass : public base {};

base *pSubClass = new subclass;

subclass *pSubClass1 = static_cast<subClass*> (pSubClass);
</code>```

// does the static_cast do the job correctly in this case although I know we should use dynamic_cast here?

答:
Some compilers will generate codes that throws std::bad_cast if dynamic_cast fails. So in this case the two approaches are different. Using dynamic_cast may looks like

```<code>try {
    SpaceShip& ship = dynamic_cast<SpaceShip&>(otherObject);
    // collision logic
    return;
} catch (std::bad_cast&) {}

try {
    SpaceStation& station = dynamic_cast<SpaceStation&>(otherObject);
    // collision logic
    return;
} catch (std::bad_cast&) {}
</code>```

that looks really bad.

Body:
I copy the following text from the book More Effective C++.

Item 31:  Making functions virtual with respect to more than one object.

class GameObject { ... };
class SpaceShip: public GameObject { ... };
class SpaceStation: public GameObject { ... };
class Asteroid: public GameObject { ... };

The most common approach to double-dispatching returns us to the unforgiving world of virtual function emulation via chains of if-then-elses. In this harsh world, we first discover the real type of otherObject, then we test it against all the possibilities:

void SpaceShip::collide(GameObject& otherObject)
{
  const type_info& objectType = typeid(otherObject);

  if (objectType == typeid(SpaceShip)) {
    SpaceShip& ss = static_cast<SpaceShip&>(otherObject);

    process a SpaceShip-SpaceShip collision;

  }
  else if (objectType == typeid(SpaceStation)) {
    SpaceStation& ss =
      static_cast<SpaceStation&>(otherObject);

    process a SpaceShip-SpaceStation collision;

  }
...
}

Here is the question:

Q1> Why we use static_cast here rather than obvious dynamic_cast?

Q2>　Are they same in this case?

thank you

// updated //

In fact, I am more interested in question 2.

For example,

class base {};
class subclass : public base {};

base *pSubClass = new subclass;

subclass *pSubClass1 = static_cast<subClass*> (pSubClass);

// does the static_cast do the job correctly in this case although I know we should use dynamic_cast here?

Body:
Some compilers will generate codes that throws std::bad_cast if dynamic_cast fails. So in this case the two approaches are different. Using dynamic_cast may looks like

try {
    SpaceShip& ship = dynamic_cast<SpaceShip&>(otherObject);
    // collision logic
    return;
} catch (std::bad_cast&) {}

try {
    SpaceStation& station = dynamic_cast<SpaceStation&>(otherObject);
    // collision logic
    return;
} catch (std::bad_cast&) {}

that looks really bad.


问:
How to make angular components full screen with the actual size of the windows
I am working with angular and in my app.component.html i have some component like so :

```<code><app-selector1></app-selector1>
<app-selector2></app-selector2>
...
</code>```

I am wondering how I could make my component full screen with css (100%width & height of the actual window size)
With all my try I always still have a little space something like a margin/padding but the inspector told me that they were at 0 each.

I tried some things and this one:

```<code>body div {
  position: relative;
  width: inherit;
  height: 100%;
  left: 0;
}

</code>```

答:
In css you will find two units perfect for what you want:

vh for viewport-height -> as a percentage of the full height of your device screen

vw for viewport-width-> as a percentage of the full width of your device screen

So if you want the full height of your screen so 100% of it you can achieve it using height: 100vh:

body {
  margin: 0;
  padding: 0;
}

body div {
  width: 100vw;
  height: 100vh;
  background: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div></div></code>```

If you wanted only 60% of the height just use height: 60vh and so on.

Body:
I am working with angular and in my app.component.html i have some component like so :

<app-selector1></app-selector1>
<app-selector2></app-selector2>
...

I am wondering how I could make my component full screen with css (100%width & height of the actual window size)
With all my try I always still have a little space something like a margin/padding but the inspector told me that they were at 0 each.

I tried some things and this one:

body div {
  position: relative;
  width: inherit;
  height: 100%;
  left: 0;
}

Body:
In css you will find two units perfect for what you want:

vh for viewport-height -> as a percentage of the full height of your device screen

vw for viewport-width-> as a percentage of the full width of your device screen

So if you want the full height of your screen so 100% of it you can achieve it using height: 100vh:

body {
  margin: 0;
  padding: 0;
}

body div {
  width: 100vw;
  height: 100vh;
  background: red;
}

<div></div>

If you wanted only 60% of the height just use height: 60vh and so on.


问:
Blazor: Razor component inherited parameter of base class not set
I've got a problem with one of my razor component libraries.

I've got an abstract base class RazorHtmlComponent for my components with a parameter property [Parameter] public string InlineClass { get; set; } which shall be used for css classes to be mapped to the actual component. Then I've got another base class per component containing the component specific properties which is definined like this: abstract class BaseRazorButton: RazorHtmlComponent

My component, in this example RazorButton.razor inherits from the abstract button base class BaseRazorButton.

The problem is, when I instantiate a razor button, and I set the property InlineClass to any value, it stays null within my actual RazorButton instance.

Here's a minimal code example for better understanding:

Base class:

```<code>public abstract class RazorHtmlComponent : ComponentBase, IRazorHtmlComponent
{
  [Parameter] public string InlineClass { get; set; }

  public DomDefinitionMapper ClassMapper { get; }

  ...

  protected RazorHtmlComponent()
  {
    ClassMapper = new DomDefinitionMapper(InlineClass);
  }
</code>```

Dom definition mapper:

```<code>  public class DomDefinitionMapper
  {
    public List<Func<string>> DefinitionRepository { get; } = new List<Func<string>>();

    public DomDefinitionMapper(string definition = "")
    {
      if (!string.IsNullOrEmpty(definition))
      {
        DefinitionRepository.Add(() => definition);
      }
    }

    public string GetDefinitions(char separator = default)
      => separator.Equals(default) ?
          string.Join(" ", DefinitionRepository.Select(i => i()).Where(i => i != null))
        : string.Join($" {separator}", DefinitionRepository.Select(i => i()).Where(i => i != null));
  }
</code>```

Button base class:

```<code>public abstract class BaseRazorButton: RazorHtmlComponent
{
  ...
}
</code>```

Razor button component:

```<code>@inherits BaseRazorButton

<button class="@ClassMapper.GetDefinitions()">
  @Text
</button>
</code>```

Instantiation of a Razor button:

```<code><RazorButton InlineClass="page"
             Text="1"/>
</code>```

When I inspect within in the browse, the class "page" defined within using the InlineClass parameter is not set. In debug mode, the  ClassMapper DefinitionRepository does not contain the class.

Am I missing something? I just don't understand why it doesn't work :/

答:
If you call that in the construtor : </p>

<pre class="lang-cs prettyprint-override"><code>[Parameter] public string InlineClass { get; set; }
...
protected RazorHtmlComponent()
{
    ClassMapper = new DomDefinitionMapper(InlineClass);
}
</code>```

<p>The parameter is not yet set. It'll be when <code>OnInitialized</code> or <code>OnInitializedAsync</code> is called.<br>
And your <code>RazorHtmlComponent</code> must derived from <code>ComponentBase</code></p>

<pre class="lang-cs prettyprint-override"><code>public abstract class RazorHtmlComponent : ComponentBase, IRazorHtmlComponent
{
  [Parameter] public string InlineClass { get; set; }

  public DomDefinitionMapper ClassMapper { get; }

  ...

  protected override void OnInitialized()
  {
    ClassMapper = new DomDefinitionMapper(InlineClass);
  }
</code>```

Body:
I've got a problem with one of my razor component libraries.

I've got an abstract base class RazorHtmlComponent for my components with a parameter property [Parameter] public string InlineClass { get; set; } which shall be used for css classes to be mapped to the actual component. Then I've got another base class per component containing the component specific properties which is definined like this: abstract class BaseRazorButton: RazorHtmlComponent

My component, in this example RazorButton.razor inherits from the abstract button base class BaseRazorButton.

The problem is, when I instantiate a razor button, and I set the property InlineClass to any value, it stays null within my actual RazorButton instance.

Here's a minimal code example for better understanding:

Base class:

public abstract class RazorHtmlComponent : ComponentBase, IRazorHtmlComponent
{
  [Parameter] public string InlineClass { get; set; }

  public DomDefinitionMapper ClassMapper { get; }

  ...

  protected RazorHtmlComponent()
  {
    ClassMapper = new DomDefinitionMapper(InlineClass);
  }

Dom definition mapper:

  public class DomDefinitionMapper
  {
    public List<Func<string>> DefinitionRepository { get; } = new List<Func<string>>();

    public DomDefinitionMapper(string definition = "")
    {
      if (!string.IsNullOrEmpty(definition))
      {
        DefinitionRepository.Add(() => definition);
      }
    }

    public string GetDefinitions(char separator = default)
      => separator.Equals(default) ?
          string.Join(" ", DefinitionRepository.Select(i => i()).Where(i => i != null))
        : string.Join($" {separator}", DefinitionRepository.Select(i => i()).Where(i => i != null));
  }

Button base class:

public abstract class BaseRazorButton: RazorHtmlComponent
{
  ...
}

Razor button component:

@inherits BaseRazorButton

<button class="@ClassMapper.GetDefinitions()">
  @Text
</button>

Instantiation of a Razor button:

<RazorButton InlineClass="page"
             Text="1"/>

When I inspect within in the browse, the class "page" defined within using the InlineClass parameter is not set. In debug mode, the  ClassMapper DefinitionRepository does not contain the class.

Am I missing something? I just don't understand why it doesn't work :/

Body:
If you call that in the construtor :

[Parameter] public string InlineClass { get; set; }
...
protected RazorHtmlComponent()
{
    ClassMapper = new DomDefinitionMapper(InlineClass);
}

The parameter is not yet set. It'll be when OnInitialized or OnInitializedAsync is called.

And your RazorHtmlComponent must derived from ComponentBase

public abstract class RazorHtmlComponent : ComponentBase, IRazorHtmlComponent
{
  [Parameter] public string InlineClass { get; set; }

  public DomDefinitionMapper ClassMapper { get; }

  ...

  protected override void OnInitialized()
  {
    ClassMapper = new DomDefinitionMapper(InlineClass);
  }


问:
PHPDoc return type for trait function
I have functions like the following in my code that return the object (for chaining):

```<code>    /**
     * Set properties
     *
     * @param $name
     * @param $value
     *
     * @return \Boka10\Page\MenuItemConfig
     */
    public function __set($name, $value)
    {

        $this->$name = $value;

        return $this;
    }
</code>```

I want to move this function into a trait because, well, basically it is reused all the time.

My problem is, that the return $this line makes problems in the documentation section. In my PHPDoc it says (in this example) @return \Boka10\Page\MenuItemConfig.

How do I create a "global" trait method whose return documentation contains the correct typecast? Is it possible to do that or should I just add the __set function to each class?

I am not sure if I can explain what problem I am having here ;) What exactly would be the content of the @return tag in a globally used trait if all of these objects return their own instance?

答:
After some digging and "hacking" I checked out the tests in Psalm and found, that the following seems to be the best method to comment these cases:

/**
 * @method string somefunction($name, $value)
 * @property string $name
 */
class ImplementTrait {

    use MagicTrait;

}
```

The properties and methods are documented on the implementing class.

Note: I am using Psalm to check the code quality and this is psalms accepted way:

Psalm Tests for __call annotations

Psalm tests for __get/__set annotations

Title: PHPDoc return type for trait function

Body:
I have functions like the following in my code that return the object (for chaining):

    /**
     * Set properties
     *
     * @param $name
     * @param $value
     *
     * @return \Boka10\Page\MenuItemConfig
     */
    public function __set($name, $value)
    {

        $this->$name = $value;

        return $this;
    }

I want to move this function into a trait because, well, basically it is reused all the time.

My problem is, that the return $this line makes problems in the documentation section. In my PHPDoc it says (in this example) @return \Boka10\Page\MenuItemConfig.

How do I create a "global" trait method whose return documentation contains the correct typecast? Is it possible to do that or should I just add the __set function to each class?

I am not sure if I can explain what problem I am having here ;) What exactly would be the content of the @return tag in a globally used trait if all of these objects return their own instance?

Body:
After some digging and "hacking" I checked out the tests in Psalm and found, that the following seems to be the best method to comment these cases:

/**
 * @method string somefunction($name, $value)
 * @property string $name
 */
class ImplementTrait {

    use MagicTrait;

}

The properties and methods are documented on the implementing class.

Note: I am using Psalm to check the code quality and this is psalms accepted way:

Psalm Tests for __call annotations

Psalm tests for __get/__set annotations


答:
You can use the vh as unit for height and vw for width.

```<code>body div {
  height: 100vh;
  width: 100vw;
}
</code>```

Check it here: https://www.w3schools.com/css/css_rwd_viewport.asp

Title: How to make angular components full screen with the actual size of the windows

Body:
You can use the vh as unit for height and vw for width.

body div {
  height: 100vh;
  width: 100vw;
}

Check it here: https://www.w3schools.com/css/css_rwd_viewport.asp


问:
Kafka cluster configuration issue
I am facing an issue with the Kafka clustering setup that I have. I have a Kafka cluster with two broker that are connected to two zookeepers. I am posting data to a topic that have replication factor and partition two each with a spring boot Kafka producer and consuming the same with another spring boot app.

I found one strange behavior when testing the cluster in the following manner -

```<code> Turned off node1 and node 2
 Turned on node 1
 Turned off node 1
 Turned on node 2
</code>```

After turning on node 2 Kafka cluster got failed and I am not able to produce data to Kafka. My consumer started throwing the message continuously as given below.

[Producer clientId=producer-1] Connection to node 1 (/server1-ip:9092) could not be established. Broker may not be available.

Issue is visible in both nodes. But if I kept both system up for a while issue will get resolved and I can turn off any of the node without breaking the cluster.

My broker configuration is as below.

 broker.id=0

 listeners=PLAINTEXT://server1-ip:9092

advertised.listeners=PLAINTEXT://serever1-ip:9092

num.network.threads=3

num.io.threads=8

socket.send.buffer.bytes=102400

socket.receive.buffer.bytes=102400

socket.request.max.bytes=104857600

log.dirs=/home/user/kafka/data/kafka-logs

num.partitions=1

num.recovery.threads.per.data.dir=2

offsets.topic.replication.factor=2

transaction.state.log.replication.factor=2

transaction.state.log.min.isr=2

log.retention.hours=168

log.segment.bytes=1073741824

log.retention.check.interval.ms=300000

zookeeper.connect=serever1-ip:2181,serever2-ip:2181

zookeeper.connection.timeout.ms=6000

group.initial.rebalance.delay.ms=3000

auto.leader.rebalance.enable=true

leader.imbalance.check.interval.seconds=5

Zookeeper configuration

dataDir=/home/user/kafka/data

clientPort=2181

maxClientCnxns=0

initLimit=10

syncLimit=5

tickTime=2000

server.1=server1-ip:2888:3888

server.2=server2-ip:2888:3888

Is this is an expected behavior of Kafka or am I doing something wrong with this configuration ?

Can somebody help me with this issue ..

答:
You should add all broker addresses to bootstrap.servers properties in both producer and consumer configs. By this way you can connect to Kafka cluster in case of failure of one or more servers.

bootstrap.servers: A list of host/port pairs to use for establishing the initial connection to the Kafka cluster. The client
  will make use of all servers irrespective of which servers are
  specified here for bootstrapping—this list only impacts the initial
  hosts used to discover the full set of servers. This list should be in
  the form host1:port1,host2:port2,.... Since these servers are just
  used for the initial connection to discover the full cluster
  membership (which may change dynamically), this list need not contain
  the full set of servers (you may want more than one, though, in case a
  server is down).

Title: Kafka cluster configuration issue

Body:
I am facing an issue with the Kafka clustering setup that I have. I have a Kafka cluster with two broker that are connected to two zookeepers. I am posting data to a topic that have replication factor and partition two each with a spring boot Kafka producer and consuming the same with another spring boot app.

I found one strange behavior when testing the cluster in the following manner -

 Turned off node1 and node 2
 Turned on node 1
 Turned off node 1
 Turned on node 2

After turning on node 2 Kafka cluster got failed and I am not able to produce data to Kafka. My consumer started throwing the message continuously as given below.

[Producer clientId=producer-1] Connection to node 1 (/server1-ip:9092) could not be established. Broker may not be available.

Issue is visible in both nodes. But if I kept both system up for a while issue will get resolved and I can turn off any of the node without breaking the cluster.

My broker configuration is as below.

 broker.id=0

 listeners=PLAINTEXT://server1-ip:9092

advertised.listeners=PLAINTEXT://serever1-ip:9092

num.network.threads=3

num.io.threads=8

socket.send.buffer.bytes=102400

socket.receive.buffer.bytes=102400

socket.request.max.bytes=104857600

log.dirs=/home/user/kafka/data/kafka-logs

num.partitions=1

num.recovery.threads.per.data.dir=2

offsets.topic.replication.factor=2

transaction.state.log.replication.factor=2

transaction.state.log.min.isr=2

log.retention.hours=168

log.segment.bytes=1073741824

log.retention.check.interval.ms=300000

zookeeper.connect=serever1-ip:2181,serever2-ip:2181

zookeeper.connection.timeout.ms=6000

group.initial.rebalance.delay.ms=3000

auto.leader.rebalance.enable=true

leader.imbalance.check.interval.seconds=5

Zookeeper configuration

dataDir=/home/user/kafka/data

clientPort=2181

maxClientCnxns=0

initLimit=10

syncLimit=5

tickTime=2000

server.1=server1-ip:2888:3888

server.2=server2-ip:2888:3888

Is this is an expected behavior of Kafka or am I doing something wrong with this configuration ?

Can somebody help me with this issue ..


问:
Design Tips for PHP Function Include Files
Good design dictates only writing each function once.  In PHP I'm doing this by using include files (like Utils.php and Authenticate.php), with the PHP command include_once.  However I haven't been able to find any standards or best practices for PHP include files.  What would you at StackOverflow suggest?

I'm looking for:

Naming Standards

Code Standards

Design Patterns

Suggestions for defining return types of common functions
(now I'm just using associative arrays).

答: Whatever naming convention you end up using (I prefer to take cues from either Java or C# wherever possible) make sure if you use include files for functions that they do not actually execute any code upon including, and never include the same file twice. (use include-once or require-once)</p>

OwnerDisplayName: C. Ross

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Kris


问:
How can I parse email text for components like <salutation><signature><reply text> etc?
I'm writing an application that analyzes emails and it would save me a bunch of time if I could use a python library that would parse email text down into named components like <salutation><signature><reply text> etc.

For example, the following text "Hi Dave,\nLets meet up this Tuesday\nCheers, Tom\n\nOn Sunday, 15 May 2011 at 5:02 PM, Dave Trindall wrote: Hey Tom,\nHow about we get together ..." would be parsed as

```<code>Salutation: "Hi Dave,\n"
Body: "Lets meet up this Tuesday\n"
Signature: "Cheers, Tom\n\n"
Reply Text: "On Sunday, 15 May 2011 at 5:02 PM, Dave Trindal wrote: ..."
</code>```

I know there's no perfect solution for this kind of problem, but even a library that does good approximation would help. Where can I find one?

答:
The first approach that comes to mind (not necessarily the best...) would be to start off by using split. here's a little bit of code and stuff

linearray=emailtext.split('\n')
now you have an array of strings, each one like a paragraph or whatever

so linearray[0] would contain the salutation

deciding where the reply text starts is a little more tricky, i noticed that there is a double newline just before it so maybe do a search for that from the back and hope that the last one indicates the start of the reply text.

Or store some signature words you might expect and search for those from the front, like cheers, regards, and whatever else.

Once you figure out where the signature is the rest is the rest is easy

hope this helped

Title: How can I parse email text for components like <salutation><body><signature><reply text> etc?

Body:
I'm writing an application that analyzes emails and it would save me a bunch of time if I could use a python library that would parse email text down into named components like <salutation><signature><reply text> etc.

For example, the following text "Hi Dave,\nLets meet up this Tuesday\nCheers, Tom\n\nOn Sunday, 15 May 2011 at 5:02 PM, Dave Trindall wrote: Hey Tom,\nHow about we get together ..." would be parsed as

Salutation: "Hi Dave,\n"
Body: "Lets meet up this Tuesday\n"
Signature: "Cheers, Tom\n\n"
Reply Text: "On Sunday, 15 May 2011 at 5:02 PM, Dave Trindal wrote: ..."

I know there's no perfect solution for this kind of problem, but even a library that does good approximation would help. Where can I find one?


问:
How do i get the name of all the elastic pools i have in SQL Server?
I am trying to get the name of the elastic pools I have in a SQL Server on Azure. The problem I am currently facing is that the only way i can get the name of all the Elastic Pools in my SQL Server is by writing

```<code>var elasticPool = azure.SqlServers.ElasticPools.GetBySqlServer(sqlServer, elasticPoolName);
elasticPool.Name;
</code>```

Here i only get one elastic pool, and to get it, I need to specify the name of the elastic pool that I am trying to get which is kinda sub optimal.

So my question is, is it possible to get the name of all the Elastic Pools in my SQL Server?

答:
So my question is, is it possible to get the name of all the Elastic
  Pools in my SQL Server?

You should be able to get it.

I have not tried it myself but ISqlServer interface exposes a property called ElasticPools and that has a List operation which should give you the list of elastic pools in a SQL Server.

I found some relevant code here, that you may find useful: https://github.com/Azure-Samples/sql-database-dotnet-manage-sql-dbs-in-elastic-pool/blob/master/Program.cs

Body:
I am trying to get the name of the elastic pools I have in a SQL Server on Azure. The problem I am currently facing is that the only way i can get the name of all the Elastic Pools in my SQL Server is by writing

var elasticPool = azure.SqlServers.ElasticPools.GetBySqlServer(sqlServer, elasticPoolName);
elasticPool.Name;

Here i only get one elastic pool, and to get it, I need to specify the name of the elastic pool that I am trying to get which is kinda sub optimal.

So my question is, is it possible to get the name of all the Elastic Pools in my SQL Server?


问:
How can multiple consumers subscribe to same topic and get same message in RabbitMQ
First of all, I know there is already an answer to a similar question here, but I am still not sure this is because of RabbitMQ's impossibility or because I haven't researched enough.

I come from JS/Node background where event pub/sub pattern works like this: when many consumers subscribe to the same topic with pub/sub pattern, all of them should get the same message whenever some producer publishes it.

I expect to implement the same pattern with a message broker.

For example:

Consumer 1 listens to 'request.user.#'

Consumer 2 listens to 'request.user.#'

Consumer 3 listens to 'request.#.#'

Producer 1 publishes to topic 'request.user.add'

Producer 2 publishes to topic 'request.user.detail'

What RabbitMQ actually does (according to this RabbitMQ example about Topics)

Consumer 3 gets both messages, while either Consumer 1 or Consumer 2 gets the first message, and only either of them gets the second message.

What I expect to implement

Three of them gets both messages.

Do you have any idea to implement this with a message broker (RabbitMQ in top priority)? Please point out if I miss something or am not clear somewhere in my question.

Thanks in advance.

EDIT with SOLUTION:

Thanks to @cantSleepNow, here is the code (NodeJS) for Consumer 1 and Consumer 2 that I have come up with after his hint:

```<code>var amqp = require('amqplib/callback_api');

amqp.connect('amqp://localhost', (err, conn) => {
  conn.createChannel((err, ch) => {
    var ex = 'topic_exchange'; // Exchange name
    ch.assertExchange(ex, 'topic'); // Exchange with 'topic' type
    ch.assertQueue('', {exclusive: true}, (err, q) => {
      ch.bindQueue(q.queue, ex, 'request.user.#'); // Topic pattern
      ch.consume(q.queue, (msg) => {
        // Process message
      });
    });
  });
});
</code>```

答:
Well this is possible using the fanout method. You can use RabbitMQ as a broadcast mechanism.

This will have one Sender and multiple subscribers and the link is here and you can find it under the Tutorial three: Publish/Subscribe senction

Body:
First of all, I know there is already an answer to a similar question here, but I am still not sure this is because of RabbitMQ's impossibility or because I haven't researched enough.

I come from JS/Node background where event pub/sub pattern works like this: when many consumers subscribe to the same topic with pub/sub pattern, all of them should get the same message whenever some producer publishes it.

I expect to implement the same pattern with a message broker.

For example:

Consumer 1 listens to 'request.user.#'

Consumer 2 listens to 'request.user.#'

Consumer 3 listens to 'request.#.#'

Producer 1 publishes to topic 'request.user.add'

Producer 2 publishes to topic 'request.user.detail'

What RabbitMQ actually does (according to this RabbitMQ example about Topics)

Consumer 3 gets both messages, while either Consumer 1 or Consumer 2 gets the first message, and only either of them gets the second message.

What I expect to implement

Three of them gets both messages.

Do you have any idea to implement this with a message broker (RabbitMQ in top priority)? Please point out if I miss something or am not clear somewhere in my question.

Thanks in advance.

EDIT with SOLUTION:

Thanks to @cantSleepNow, here is the code (NodeJS) for Consumer 1 and Consumer 2 that I have come up with after his hint:

var amqp = require('amqplib/callback_api');

amqp.connect('amqp://localhost', (err, conn) => {
  conn.createChannel((err, ch) => {
    var ex = 'topic_exchange'; // Exchange name
    ch.assertExchange(ex, 'topic'); // Exchange with 'topic' type
    ch.assertQueue('', {exclusive: true}, (err, q) => {
      ch.bindQueue(q.queue, ex, 'request.user.#'); // Topic pattern
      ch.consume(q.queue, (msg) => {
        // Process message
      });
    });
  });
});


问:
Sharekit - sending a url link to facebook
Below is the method I'm using with Sharekit to send an image and a title to facebook. I also want to send a URL along with the facebook post. If I try

```<code>SHKItem *item = [SHKItem image:image url:url title:titleString];
</code>```

I get a too many arguments error message. Does anyone have any ideas on how this should be done? thanks for any help.

```<code>- (IBAction)myButtonHandlerAction
    {
                    NSURL *url = [NSURL URLWithString:@"http://example.com/"];
                NSString *titleString = [[NSString alloc] initWithFormat:@"*** %@ * \n\nGet the ***** App - It's Free!", entity.name];

                UIImage *image = [[[UIImage alloc] initWithData:entity.image] autorelease];

                SHKItem *item = [SHKItem image:image title:titleString];

                // Get the ShareKit action sheet
                SHKActionSheet *actionSheet = [SHKActionSheet actionSheetForItem:item];

                // Display the action sheet
                [actionSheet showFromBarButtonItem:barbtn animated:YES];
}
</code>```

答: There is no method -[SHKItem image:url:title:]. So an error is being raised. Currently there is no mechanism to do what you require using ShareKit so you will have to customize ShareKit for your needs. You should also look at the Graph API.

Body:
Below is the method I'm using with Sharekit to send an image and a title to facebook. I also want to send a URL along with the facebook post. If I try

SHKItem *item = [SHKItem image:image url:url title:titleString];

I get a too many arguments error message. Does anyone have any ideas on how this should be done? thanks for any help.

- (IBAction)myButtonHandlerAction
    {
                    NSURL *url = [NSURL URLWithString:@"http://example.com/"];
                NSString *titleString = [[NSString alloc] initWithFormat:@"*** %@ * \n\nGet the ***** App - It's Free!", entity.name];

                UIImage *image = [[[UIImage alloc] initWithData:entity.image] autorelease];

                SHKItem *item = [SHKItem image:image title:titleString];

                // Get the ShareKit action sheet
                SHKActionSheet *actionSheet = [SHKActionSheet actionSheetForItem:item];

                // Display the action sheet
                [actionSheet showFromBarButtonItem:barbtn animated:YES];
}


问:
Update a List's object using Linq
I would like to assign an object in a list using Linq, but I can't find how to do it.
I tried this:

Items.Where(i => i.Code == line.Code).Single() = line;

But it seems I simply cannot give the statement an object.
I can modify properties of those objects (Like this) :

```<code>Items.Where(i => i.Code == line.Code).Single().name = line.name;
</code>```

But giving it the full item doesn't seem to be accepted.
Is there a reason to prevent this / a way to assign my value to the compatible item ?
Thank you for your answer.

答:
You cannot replace the value in the list using LINQ, because LINQ is a projection of a collection.

You can get your item and then find it in the list using IndexOf:

```<code>var item = Items.Single(i => i.Code == line.Code);
int index = Items.IndexOf(item);
Items[index] = new Item(); // replace the value
</code>```

However, this approach is far from optimal in terms of algorithmic complexity, because it has to read through your list multiple times.

You can try to read more on Dictionary to find, add or replace items by key (in your case, Code) efficiently.

Title: Update a List's object using Linq

Body:
I would like to assign an object in a list using Linq, but I can't find how to do it.
I tried this:

Items.Where(i => i.Code == line.Code).Single() = line;

But it seems I simply cannot give the statement an object.
I can modify properties of those objects (Like this) :

Items.Where(i => i.Code == line.Code).Single().name = line.name;

But giving it the full item doesn't seem to be accepted.
Is there a reason to prevent this / a way to assign my value to the compatible item ?
Thank you for your answer.

Body:
You cannot replace the value in the list using LINQ, because LINQ is a projection of a collection.

You can get your item and then find it in the list using IndexOf:

var item = Items.Single(i => i.Code == line.Code);
int index = Items.IndexOf(item);
Items[index] = new Item(); // replace the value

However, this approach is far from optimal in terms of algorithmic complexity, because it has to read through your list multiple times.

You can try to read more on Dictionary to find, add or replace items by key (in your case, Code) efficiently.


问:
HTTP Request in AWS Lambda is not working / NodeJS
i know, this topic was discussed very often. But these posts are either very old, or do not fix my problem. So i try it with opening a new (other) one.
I recently started making Alexa Skills. So now i managed to set up my AWS Lambda function with the help of (an also old) Tutorial. Everything worked fine in the first step.
So now i want to sent a GET Request to a website, just to get the status code. In the next step, Alexa should tell me this code- but thats a diffrent story.
So i tried to get the request done with many different code snippets- but nothing worked. After reading various posts, i understand that the code runs faster then the request can be executed. So the answer of the request does never show up in the logs. Which means, i cannot make use of it.

This is my current code:

```<code>exports.handler = async (event, context, callback) => {
  try {
    console.log(event)
    if (event.session.new) {
      console.log("new session");
    }
    switch (event.request.type) {
      case "LaunchRequest":
        console.log("LAUNCH REQUEST");
        context.succeed(
          generateResponse(
            buildSpeechletResponse("This is a launch request", true), {}
          )
        )
        break;
      case "IntentRequest":
        console.log("INTENT REQUEST")
        switch (event.request.intent.name) {
          case "checkConnection":
            console.log("INTENT CHECK CONNECTION")
            const https = require('https')
            let url = "xxx/xxx/bc/alexa"
            exports.handler = async function(event) {
              console.log("async function")
              const promise = new Promise(function(resolve, reject) {
                https.get(url, (res) => {
                  resolve(res.statusCode)
                }).on('error', (e) => {
                  reject(Error(e))
                })
              })
              return promise
            }
            context.succeed(null, generateResponse(
              buildSpeechletResponse("server answered with code " + this.statusCode, true), {}));
            break;
        }
      case ("SessionEndedRequest"):
        console.log("SESSION ENEDED REQUEST")
        break;
      default:
        context.fail(`INVALID REQUEST TYPE: ${event.request.type}`);
        break;
    }
  }
  catch (error) { context.fail(`Exception: ${error}`) }
}
// Helpers
buildSpeechletResponse = (outputText, shouldEndSession) => {
  console.log("buildSpeechletResponse");
  return {
    outputSpeech: {
      type: "PlainText",
      text: outputText
    },
    shouldEndSession: shouldEndSession
  }
};
generateResponse = (speechletResponse, sessionAttributes) => {
  console.log("generateResponse")
  return {
    version: "1.0",
    sessionAttributes: sessionAttributes,
    response: speechletResponse
  }
};

</code>```

If i test the code via the lambda test (including the JSON from Alexa to check connection), the log look like this.

14:48:14 START RequestId: c8790cd2-81c9-4b8e-98ac-91b2ae6493f6 Version: $LATEST

14:48:14 2020-02-13T14:48:14.802Z c8790cd2-81c9-4b8e-98ac-91b2ae6493f6 INFO { version: '1.0', session: { new: true, sessionId: 'amzn1.echo-api.session.0a26e495-1085-44e0-83f3-13937d026c1b', application: { applicationId: 'amzn1.ask.skill.42b0dea7-952e-4695-a3d2-ab951c98ac9c' }, user: { userId: 'amzn1.ask.account.AHKG3FP33CDNS5PBKQESKQ73PAWMYTB7PRL4A2UGJTG77NOGSKKQBG5QNKVZ

14:48:14 2020-02-13T14:48:14.802Z c8790cd2-81c9-4b8e-98ac-91b2ae6493f6 INFO new session

14:48:14 2020-02-13T14:48:14.802Z c8790cd2-81c9-4b8e-98ac-91b2ae6493f6 INFO INTENT REQUEST

14:48:14 2020-02-13T14:48:14.802Z c8790cd2-81c9-4b8e-98ac-91b2ae6493f6 INFO INTENT CHECK CONNECTION

14:48:14 2020-02-13T14:48:14.964Z c8790cd2-81c9-4b8e-98ac-91b2ae6493f6 INFO buildSpeechletResponse

14:48:14 2020-02-13T14:48:14.964Z c8790cd2-81c9-4b8e-98ac-91b2ae6493f6 INFO generateResponse

14:48:15 2020-02-13T14:48:15.042Z c8790cd2-81c9-4b8e-98ac-91b2ae6493f6 INFO SESSION ENEDED REQUEST

So as far as i see, th code runs to "INTENT CHECK CONNECTION", but the log "async function" never shows up. So what happens here? Is the code skipped? How do i manage to get a working http request state of the art? (Sorry, if my post is not the "common way". It is also my first post)

答:
So i figured it out. The code i provided was nearly correct. The request function needed to be capsuled into another function. With minor adjustments, it worked with this code:</p>

```<code>    // HTTP Request Function
function httpGet(options) {
  const https = require('https');
  return new Promise(((resolve, reject) => {
    const request = https.request(options, (response) => {
      response.setEncoding('utf8');
      let returnData = '';
      if (response.statusCode < 200 || response.statusCode >= 300) {
        return reject(new Error(`${response.statusCode}: ${response.req.getHeader('host')} ${response.req.path}`));
      }
      response.on('data', (chunk) => {
        returnData += chunk;
      });
      response.on('end', () => {
        resolve(response.statusCode); //Fill response with status code
      });
      response.on('error', (error) => {
        reject(error);
      });
    });
    request.end();
  }));
}
</code>```

Body:
i know, this topic was discussed very often. But these posts are either very old, or do not fix my problem. So i try it with opening a new (other) one.
I recently started making Alexa Skills. So now i managed to set up my AWS Lambda function with the help of (an also old) Tutorial. Everything worked fine in the first step.
So now i want to sent a GET Request to a website, just to get the status code. In the next step, Alexa should tell me this code- but thats a diffrent story.
So i tried to get the request done with many different code snippets- but nothing worked. After reading various posts, i understand that the code runs faster then the request can be executed. So the answer of the request does never show up in the logs. Which means, i cannot make use of it.

This is my current code:

exports.handler = async (event, context, callback) => {
  try {
    console.log(event)
    if (event.session.new) {
      console.log("new session");
    }
    switch (event.request.type) {
      case "LaunchRequest":
        console.log("LAUNCH REQUEST");
        context.succeed(
          generateResponse(
            buildSpeechletResponse("This is a launch request", true), {}
          )
        )
        break;
      case "IntentRequest":
        console.log("INTENT REQUEST")
        switch (event.request.intent.name) {
          case "checkConnection":
            console.log("INTENT CHECK CONNECTION")
            const https = require('https')
            let url = "xxx/xxx/bc/alexa"
            exports.handler = async function(event) {
              console.log("async function")
              const promise = new Promise(function(resolve, reject) {
                https.get(url, (res) => {
                  resolve(res.statusCode)
                }).on('error', (e) => {
                  reject(Error(e))
                })
              })
              return promise
            }
            context.succeed(null, generateResponse(
              buildSpeechletResponse("server answered with code " + this.statusCode, true), {}));
            break;
        }
      case ("SessionEndedRequest"):
        console.log("SESSION ENEDED REQUEST")
        break;
      default:
        context.fail(`INVALID REQUEST TYPE: ${event.request.type}`);
        break;
    }
  }
  catch (error) { context.fail(`Exception: ${error}`) }
}
// Helpers
buildSpeechletResponse = (outputText, shouldEndSession) => {
  console.log("buildSpeechletResponse");
  return {
    outputSpeech: {
      type: "PlainText",
      text: outputText
    },
    shouldEndSession: shouldEndSession
  }
};
generateResponse = (speechletResponse, sessionAttributes) => {
  console.log("generateResponse")
  return {
    version: "1.0",
    sessionAttributes: sessionAttributes,
    response: speechletResponse
  }
};

If i test the code via the lambda test (including the JSON from Alexa to check connection), the log look like this.

14:48:14 START RequestId: c8790cd2-81c9-4b8e-98ac-91b2ae6493f6 Version: $LATEST

14:48:14 2020-02-13T14:48:14.802Z c8790cd2-81c9-4b8e-98ac-91b2ae6493f6 INFO { version: '1.0', session: { new: true, sessionId: 'amzn1.echo-api.session.0a26e495-1085-44e0-83f3-13937d026c1b', application: { applicationId: 'amzn1.ask.skill.42b0dea7-952e-4695-a3d2-ab951c98ac9c' }, user: { userId: 'amzn1.ask.account.AHKG3FP33CDNS5PBKQESKQ73PAWMYTB7PRL4A2UGJTG77NOGSKKQBG5QNKVZ

14:48:14 2020-02-13T14:48:14.802Z c8790cd2-81c9-4b8e-98ac-91b2ae6493f6 INFO new session

14:48:14 2020-02-13T14:48:14.802Z c8790cd2-81c9-4b8e-98ac-91b2ae6493f6 INFO INTENT REQUEST

14:48:14 2020-02-13T14:48:14.802Z c8790cd2-81c9-4b8e-98ac-91b2ae6493f6 INFO INTENT CHECK CONNECTION

14:48:14 2020-02-13T14:48:14.964Z c8790cd2-81c9-4b8e-98ac-91b2ae6493f6 INFO buildSpeechletResponse

14:48:14 2020-02-13T14:48:14.964Z c8790cd2-81c9-4b8e-98ac-91b2ae6493f6 INFO generateResponse

14:48:15 2020-02-13T14:48:15.042Z c8790cd2-81c9-4b8e-98ac-91b2ae6493f6 INFO SESSION ENEDED REQUEST

So as far as i see, th code runs to "INTENT CHECK CONNECTION", but the log "async function" never shows up. So what happens here? Is the code skipped? How do i manage to get a working http request state of the art? (Sorry, if my post is not the "common way". It is also my first post)

Body:
So i figured it out. The code i provided was nearly correct. The request function needed to be capsuled into another function. With minor adjustments, it worked with this code:

    // HTTP Request Function
function httpGet(options) {
  const https = require('https');
  return new Promise(((resolve, reject) => {
    const request = https.request(options, (response) => {
      response.setEncoding('utf8');
      let returnData = '';
      if (response.statusCode < 200 || response.statusCode >= 300) {
        return reject(new Error(`${response.statusCode}: ${response.req.getHeader('host')} ${response.req.path}`));
      }
      response.on('data', (chunk) => {
        returnData += chunk;
      });
      response.on('end', () => {
        resolve(response.statusCode); //Fill response with status code
      });
      response.on('error', (error) => {
        reject(error);
      });
    });
    request.end();
  }));
}


问:
how to select data of a date which the largest of dates less than a specific date in Mysql
say I have data of multiple date and I just want to select the data of a date which is the maximum of dates smaller than a specific date.

eg.

```<code>id  other_columns date
------------------------
1   ...          2020-01-12
2   ...          2019-12-31
3   ...          2019-12-31
4   ...          2019-11-01
5   ...          2019-11-01
6   ...          2018-12-21
</code>```

for above case, if the condition is smaller than '2020-01-01', row 2 and 3 will be selected.
Since row 2 and row 3 have date just smaller than '2020-01-01'.

while if condition is smaller than '2019-12-31', then row 4 and row 5 will be selected.

I would like to see the most optimized query.
Thanks

答:
This will give your desired output.</p>

```<code>SELECT *
FROM Your_Table
WHERE date =   (
        SELECT MAX(date)
            FROM Your_Table
        WHERE date < '2020-01-01'
        )
</code>```

Body:
say I have data of multiple date and I just want to select the data of a date which is the maximum of dates smaller than a specific date.

eg.

id  other_columns date
------------------------
1   ...          2020-01-12
2   ...          2019-12-31
3   ...          2019-12-31
4   ...          2019-11-01
5   ...          2019-11-01
6   ...          2018-12-21

for above case, if the condition is smaller than '2020-01-01', row 2 and 3 will be selected.
Since row 2 and row 3 have date just smaller than '2020-01-01'.

while if condition is smaller than '2019-12-31', then row 4 and row 5 will be selected.

I would like to see the most optimized query.
Thanks

Body:
This will give your desired output.

SELECT *
FROM Your_Table
WHERE date =   (
        SELECT MAX(date)
            FROM Your_Table
        WHERE date < '2020-01-01'
        )


问:
How to change the text color of items in MaterialAlertDialog?
I am trying to change the text color of the items in a single choice MaterialViewAlertDialog. I achieved to change the "RadioButton" color and the title color but I can't change the text color of the items. For now I am using the following style:

```<code><style name="AlertDialog" parent="ThemeOverlay.MaterialComponents.Dialog.Alert">
        <item name="android:titleTextColor">@color/colorText</item>
        <item name="android:textColorSecondary">@color/colorText</item>
        <item name="android:textColorAlertDialogListItem">@color/colorText</item>
</style>
</code>```

I also tried to cahnge the text color of the items with textAppearanceListItem but it didn't work.

答:
To change the color of the text in the items you can use something like:

```<code><style name="AlertDialog" parent="@style/ThemeOverlay.MaterialComponents.MaterialAlertDialog">
    <item name="android:checkedTextViewStyle" ns2:ignore="NewApi">@style/myCheckedTextView</item>
</style>
</code>```

with:

```<code>  <style name="myCheckedTextView" parent="@style/Widget.MaterialComponents.CheckedTextView">
    <item name="android:textColor">@color/.....</item>
  </style>
</code>```

Otherwise you can also use:

```<code><style name="AlertDialog"
   parent="ThemeOverlay.MaterialComponents.MaterialAlertDialog">
     <item name="colorSecondary">@color/selected</item> <!-- selected -->
 </style>
</code>```

Body:
I am trying to change the text color of the items in a single choice MaterialViewAlertDialog. I achieved to change the "RadioButton" color and the title color but I can't change the text color of the items. For now I am using the following style:

I also tried to cahnge the text color of the items with textAppearanceListItem but it didn't work.

Body:
To change the color of the text in the items you can use something like:

<style name="AlertDialog" parent="@style/ThemeOverlay.MaterialComponents.MaterialAlertDialog">
    <item name="android:checkedTextViewStyle" ns2:ignore="NewApi">@style/myCheckedTextView</item>
</style>

with:

  <style name="myCheckedTextView" parent="@style/Widget.MaterialComponents.CheckedTextView">
    <item name="android:textColor">@color/.....</item>
  </style>

Otherwise you can also use:

<style name="AlertDialog"
   parent="ThemeOverlay.MaterialComponents.MaterialAlertDialog">
     <item name="colorSecondary">@color/selected</item> <!-- selected -->
 </style>


问:
Same or different instances of a JavaScript code?
This is the bottom of my webpages. As you can see, there are several instances of jquery.min.js.

```<code>    <!-- JavaScript at the bottom for fast page loading -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script><!-- Changed from src="/ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" -->
    <script>window.jQuery || document.write('<script src="/mysite/js/jquery-1.7.2.min.js"><\/script>')</script>
<!-- Responsive Grid System -->
    <script src="/mysite/js/responsivegridsystem.js"></script>
<!-- Responsive Menu Acordeón -->
    <script src="/mysite/js/accordionmenu.js"></script>
<!-- For automatic applying of a webp or no-webp class to HTML element, depending on browser support -->
    <script src="/mysite/js/modernizr-custom.js"></script>
    <script>
      Modernizr.on('webp', function (result) {
        if (result) {
          // supported
        } else {
          // not-supported
        }
      });
    </script>
<!-- Carousel -->
    <script src="/mysite/js/jquery.min.js"></script>
    <script src="/mysite/js/slick.min.js"></script>
    <script>
    $('.carousel-view').slick({
      dots: false,
      infinite: false,
      speed: 300,
      slidesToShow: 3,
      slidesToScroll: 3,
      responsive: [
        {
          breakpoint: 600,
          settings: {
            slidesToShow: 2,
            slidesToScroll: 2
          }
        },
        {
          breakpoint: 480,
          settings: {
            slidesToShow: 1,
            slidesToScroll: 1
          }
        }
      ]
    });
    </script>
<!-- modal box to work in IE9 -->
    <script src="/mysite/js/jquery.hoverTransition.js"></script>
    <script> amenu.open("88", true); </script>
    <!--[if (lt IE 9) & (!IEMobile)]>
    <script src="/mysite/js/selectivizr-min.js"></script>
    <![endif]-->
<!-- Pretty float pictures-->
    <script src="/mysite/js/prettyfloat.js"></script>
<!-- Make all divs in a row the same height (Responsive Grid System) -->
    <script src="/mysite/js/jquery.matchHeight-min.js"></script>
    <script>
    jQuery(function($){
        $('.matchheight').matchHeight();
    });
    </script>
<!-- Table (tabla) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
    <script>
     $(function() {
            /* For zebra striping */
            $("table tr:nth-child(odd)").addClass("odd-row");
            /* For cell text alignment */
            $("table td:first-child, table th:first-child").addClass("first");
            /* For removing the last border */
            $("table td:last-child, table th:last-child").addClass("last");
    });
    </script>
<!-- Usado para colapsos -->
    <script>
        function toggleDiv(divid){
        if(document.getElementById(divid).style.display == 'none'){
        document.getElementById(divid).style.display = 'block';
        }else{
        document.getElementById(divid).style.display = 'none';
        }
        }
    </script>
<!-- Menu navigation -->
    <script src="/mysite/js/jquery-1.7.2.min.js"></script>
    <script src="/mysite/js/script.js"></script>
<!-- Tooltips -->
    <script src="/mysite/js/jquery.min.js"></script>
    <script src="/mysite/js/tooltip.js"></script>
<!-- Zendesk Live Chat Script -->
    <script>
    window.$zopim||(function(d,s){var z=$zopim=function(c){z._.push(c)},$=z.s=
    d.createElement(s),e=d.getElementsByTagName(s)[0];z.set=function(o){z.set.
    _.push(o)};z._=[];z.set._=[];$.async=!0;$.setAttribute("charset","utf-8");
    $.src="https://v2.zopim.com/?26AnsOGmySbDiEq6CAIx8dIxyvck1SUC";z.t=+new Date;$.
    type="text/javascript";e.parentNode.insertBefore($,e)})(document,"script");
    </script>
<!-- TrustedSite Script -->
    <!-- Grab Google CDN's jQuery, with a protocol relative URL; fall back to local if necessary -->
    <script src="https://cdn.ywxi.net/js/1.js" async></script>
</body>
</code>```

This is because each time I use a JavaScript solution for implementing say, a carousel, a menu, etc., the developer gives you instructions about the .js that will be needed.

As I am a newbie in web design, there are several questions I have regarding this:

The source of one instance is https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js. Is that better than having the .js in a folder of the website?

Are the 4 or 5 instances of this particular .js the same code, I mean, are all of them the same?

1.1 If not, can I have all of them in a js folder renaming each one differently and then pointing the webpage to them?

1.2 How the browser/site/software knows which version to call?

2 If yes, should I take all but one out and everything will work OK? I made a small experiment and took one instance of jquery.min.js out trying to make a carousel work, and even though it still didn't work, at least it behaved better than before.

My googling with different versions of “css3 html5 can a java script file appear several times in the document” brought not an answer.

Body:
This is the bottom of my webpages. As you can see, there are several instances of jquery.min.js.

This is because each time I use a JavaScript solution for implementing say, a carousel, a menu, etc., the developer gives you instructions about the .js that will be needed.

As I am a newbie in web design, there are several questions I have regarding this:

The source of one instance is https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js. Is that better than having the .js in a folder of the website?

Are the 4 or 5 instances of this particular .js the same code, I mean, are all of them the same?

1.1 If not, can I have all of them in a js folder renaming each one differently and then pointing the webpage to them?

1.2 How the browser/site/software knows which version to call?

2 If yes, should I take all but one out and everything will work OK? I made a small experiment and took one instance of jquery.min.js out trying to make a carousel work, and even though it still didn't work, at least it behaved better than before.

My googling with different versions of “css3 html5 can a java script file appear several times in the document” brought not an answer.

Body:
The source of one instance is https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js. Is that better than having the .js in a folder of the website?

"Better" is subjective.

There's a greater chance that Google's CDN version is already cached by any given visitor's browser, and that Google's CDN will be faster than your server. The user's browser will load more stuff in parallel if it is split across multiple hostnames.

But adding another server adds an additional single point of failure, and you're trusting Google to not serve up tainted code, and people might not be able to access Google's server (e.g. behind the Great Firewall of China).

Are the 4 or 5 instances of this particular .js the same code, I mean, are all of them the same?

If multiple <script> elements define values for the same variables (e.g. jQuery will define $ and jQuery as globals) then subsequent <script> elements will overwrite earlier ones.

Best case scenario is that you've wasted bandwidth and CPU loading scripts you aren't using.

Worse case is that you load jQuery, attach plugins to it, then load a new version of jQuery and blow away all the plugins.

Load jQuery once … and use a version which is current and supported (so not, for example, 1.7.2 which has known security issues).


问:
Can I create a Windows installer that can add the program path to the environment variables?
I have developed an application in Go that I want to create a Windows installer for. The problem is that it is a console app that would preferably be run with just a simple call from the Terminal/Cmd Prompt. For that I need to add the installation directory to the system environment variables. Is it possible to do this through a custom Windows installer of some sorts?

I already have the exe that I will want to be added to the system environment variables. I want it to be possible for the user to install the program wherever they want and then that the installer can add that directory to the environment variables. Is this possible?

答:
You can use Wix Toolset, here is an example of how to add an environment variable:

Setting environment variables requires reboot on 64-bit

Commercial installer authoring tools can also do this. For example, you can use the free edition of Advanced Installer, you need to add your env var from Environment Variables page, in the project you are creating.

I imagine others like InstallShield, etc. provide similar support (don't know in which of their editions)

Disclaimer: I work on the team building Advanced Installer


答: Think about what the Single method returns. It returns a reference to the object that much the predicate you pass in the Where method. Specifically, when there is only one item in the Items that pass the predicate in the Where method, you will get a reference to this object. If there are more than one items, you will get an exception and if there are no items you will get null. Let's think about the happy case, in which you will have only one item. In that case, essentially you try to assign to this reference a new object. This does not make any sense. On the other hand that you try afterwards, makes sense, holding the reference you can mutate its state.

Title: Update a List's object using Linq


问:
Where to integrate getStream.io
I am a noob in backend programming. I have been looking into getstream activity feed api for a while and I am still not clear where to integrate the api. Consider that I have built an Instagram like application using native android (say JAVA) and the backend is PHP or PYTHON. Is getStream api still helpful for me? If so should I be integrating in into frontend or backend?</p>

答:
Unfortunately right now there is no Android SDK for Feeds. The development is planned, although there is still no exact date when it will be ready.

There is iOS SDK for Feeds: https://getstream.io/ios-activity-feed/tutorial/

And ReactNative: https://getstream.io/react-native-activity-feed/tutorial/

Title: Where to integrate getStream.io


答:
From MSDN Documentation: Language Integrated Query

By using query syntax, you can perform filtering, ordering, and
  grouping operations on data sources with a minimum of code.

You can not perform assignment using LINQ, you need to use index to update particular record from the list

To update record you can try FindIndex()

```<code>int index = Items.FindIndex(x => x.Code == line.Code); //returns -1 if record not found
Items[index]?.Name = "Stackoverflow";
</code>```

Title: Update a List's object using Linq

Body:
From MSDN Documentation: Language Integrated Query

By using query syntax, you can perform filtering, ordering, and
  grouping operations on data sources with a minimum of code.

You can not perform assignment using LINQ, you need to use index to update particular record from the list

To update record you can try FindIndex()

int index = Items.FindIndex(x => x.Code == line.Code); //returns -1 if record not found
Items[index]?.Name = "Stackoverflow";


问:
For loop is returning only last value
For the below for loop I am able to see all values. But when I assign new object to it, the value returned is only last (Refer last code). can anyone help me here please. Is it not possible to all values displayed with assigning a value?

```<code>for(i in 1:5)
+ {
+     for(j in 1:2)
+     {
+         print(i*j);
+     }
+ }
</code>```

Assigned a object.

```<code>for(i in 1:5)
+ {
+     for(j in 1:2)
+     {
+         as <- i*j
+     }
+ }
</code>```

答:
for loop approach

If you want to append new values to as, you can try to update as by as <- c(as,i*j), which concatenates i*j with existing as and the result is assigned to as, i.e.,

```<code>as <- c()
for(i in 1:5)
{
     for(j in 1:2)
     {
         as <- c(as,i*j)
     }
}
</code>```

outer approach

A more efficient way to achieve the same goal can be using outer, i.e.,

```<code>as <- c(t(outer(1:5,1:2)))
</code>```

Title: For loop is returning only last value

Body:
For the below for loop I am able to see all values. But when I assign new object to it, the value returned is only last (Refer last code). can anyone help me here please. Is it not possible to all values displayed with assigning a value?

for(i in 1:5)
+ {
+     for(j in 1:2)
+     {
+         print(i*j);
+     }
+ }

Assigned a object.

for(i in 1:5)
+ {
+     for(j in 1:2)
+     {
+         as <- i*j
+     }
+ }

Body:
for loop approach

If you want to append new values to as, you can try to update as by as <- c(as,i*j), which concatenates i*j with existing as and the result is assigned to as, i.e.,

as <- c()
for(i in 1:5)
{
     for(j in 1:2)
     {
         as <- c(as,i*j)
     }
}

outer approach

A more efficient way to achieve the same goal can be using outer, i.e.,

as <- c(t(outer(1:5,1:2)))


问:
One of the child processes can't read from pipe
I am trying to implement a small IPC in C, but I have an issue that I can't solve.

My main process have two children, child A and child B; Child A gets created first.
I have two pipes to pass information to these processes, pipefd and pipefd2.

First, parent process reads a file's content, and writes to both pipes these two values:

```<code>1-length of the string
2-string itself
</code>```

Once they get the length of string, they create a char array with the given length, and then read the string into this array.

Then both children read from their pipes. Child B can get these values correctly from the pipe, but child A gets 0 as size.

Here's my code, thanks for your time!

Output :

```<code>Child A here, input read, size is: 0
Size is 45169child reads input, size : 45169
Child B here, input read, size is: 45169

//
//  Created by Dilara on 16.02.2020.
//

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <time.h>
#include <signal.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <sys/ipc.h>
#include <sys/msg.h>

#define MESSAGESIZE 10
#define READ_END    0
#define WRITE_END    1

int fsize(FILE *fp){
    int prev=ftell(fp);
    fseek(fp, 0L, SEEK_END);
    int sz=ftell(fp);
    fseek(fp,prev,SEEK_SET); //go back to where we were
    return sz;
}

void writeToPipe(int fd[2], char string[], long stell){
       close(fd[READ_END]);
        write(fd[WRITE_END], stell, sizeof(stell));
         write(fd[WRITE_END], string, strlen(string)+1);
         close(fd[WRITE_END]);
}

static void readFromPipe(int pipefd[2], char input[],long size){
         // wait(NULL);
           close(pipefd[WRITE_END]);
           read(pipefd[READ_END], input, size);
           printf("child reads input, size : %d \n",size);
           close(pipefd[READ_END]);
}

static long readSize(int pipefd[2]){
       long size;
     close(pipefd[WRITE_END]);
     read(pipefd[READ_END], size, sizeof(size));
     printf("Size is %d",size);
     close(pipefd[READ_END]);
    return size;
}

int main()
{

    int pipefd[2];
    int pipefd2[2];
      int childA_pid;
      int childB_pid;

    if (pipe(pipefd) == -1)
           {
               perror(" pipe");
               return 0;
           }

    if (pipe(pipefd2) == -1)
           {
               perror(" pipe");
               return 0;
           }

       childA_pid = fork();

        if(childA_pid == 0){
            //childA

        long SIZE = readSize(pipefd);
        char input[SIZE];
        readFromPipe(pipefd, input, SIZE);
          printf("Child A here, input read, size is: %d \n",SIZE);

        }
    else{
        childB_pid = fork();
        if(childB_pid == 0){

             long SIZE = readSize(pipefd2);
             char input[SIZE];
             readFromPipe(pipefd2, input, SIZE);
              printf("Child B here, input read, size is: %d \n",SIZE);

        }else{
            //parent
               char *buffer;
                       FILE *fp = fopen("try.txt", "r");
                 if (fp != NULL)
                 {
                     fseek(fp, 0L, SEEK_END);
                     long stell = ftell(fp);
                     rewind(fp);
                     char str[stell];
                     buffer = (char *)malloc(stell);

                     if (buffer != NULL)
                     {
                         //fread(buffer, stell, 1, fp);

                             fread(str,stell,1, fp);
                          // printf("%s", str);
                         fclose(fp);
                         fp = NULL;
                         free(buffer);
                     }

                       printf("SIZE: %d", stell);

                     writeToPipe(pipefd2, str,stell);
                     writeToPipe(pipefd, str,stell);

                 }

        }

}
    return 0;
}
</code>```

答:
```<code>write(fd[WRITE_END], stell, sizeof(stell));
</code>```

I think your code lacks an ampersand here. Instead of the stell variable you should use its address:

```<code>write(fd[WRITE_END], &stell, sizeof(stell));
</code>```

Body:
I am trying to implement a small IPC in C, but I have an issue that I can't solve.

My main process have two children, child A and child B; Child A gets created first.
I have two pipes to pass information to these processes, pipefd and pipefd2.

First, parent process reads a file's content, and writes to both pipes these two values:

1-length of the string
2-string itself

Once they get the length of string, they create a char array with the given length, and then read the string into this array.

Then both children read from their pipes. Child B can get these values correctly from the pipe, but child A gets 0 as size.

Here's my code, thanks for your time!

Output :

Child A here, input read, size is: 0
Size is 45169child reads input, size : 45169
Child B here, input read, size is: 45169

//
//  Created by Dilara on 16.02.2020.
//

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <time.h>
#include <signal.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <sys/ipc.h>
#include <sys/msg.h>

#define MESSAGESIZE 10
#define READ_END    0
#define WRITE_END    1

int fsize(FILE *fp){
    int prev=ftell(fp);
    fseek(fp, 0L, SEEK_END);
    int sz=ftell(fp);
    fseek(fp,prev,SEEK_SET); //go back to where we were
    return sz;
}

void writeToPipe(int fd[2], char string[], long stell){
       close(fd[READ_END]);
        write(fd[WRITE_END], stell, sizeof(stell));
         write(fd[WRITE_END], string, strlen(string)+1);
         close(fd[WRITE_END]);
}

static void readFromPipe(int pipefd[2], char input[],long size){
         // wait(NULL);
           close(pipefd[WRITE_END]);
           read(pipefd[READ_END], input, size);
           printf("child reads input, size : %d \n",size);
           close(pipefd[READ_END]);
}

static long readSize(int pipefd[2]){
       long size;
     close(pipefd[WRITE_END]);
     read(pipefd[READ_END], size, sizeof(size));
     printf("Size is %d",size);
     close(pipefd[READ_END]);
    return size;
}

int main()
{

    int pipefd[2];
    int pipefd2[2];
      int childA_pid;
      int childB_pid;

    if (pipe(pipefd) == -1)
           {
               perror(" pipe");
               return 0;
           }

    if (pipe(pipefd2) == -1)
           {
               perror(" pipe");
               return 0;
           }

       childA_pid = fork();

        if(childA_pid == 0){
            //childA

        long SIZE = readSize(pipefd);
        char input[SIZE];
        readFromPipe(pipefd, input, SIZE);
          printf("Child A here, input read, size is: %d \n",SIZE);

        }
    else{
        childB_pid = fork();
        if(childB_pid == 0){

             long SIZE = readSize(pipefd2);
             char input[SIZE];
             readFromPipe(pipefd2, input, SIZE);
              printf("Child B here, input read, size is: %d \n",SIZE);

        }else{
            //parent
               char *buffer;
                       FILE *fp = fopen("try.txt", "r");
                 if (fp != NULL)
                 {
                     fseek(fp, 0L, SEEK_END);
                     long stell = ftell(fp);
                     rewind(fp);
                     char str[stell];
                     buffer = (char *)malloc(stell);

                     if (buffer != NULL)
                     {
                         //fread(buffer, stell, 1, fp);

                             fread(str,stell,1, fp);
                          // printf("%s", str);
                         fclose(fp);
                         fp = NULL;
                         free(buffer);
                     }

                       printf("SIZE: %d", stell);

                     writeToPipe(pipefd2, str,stell);
                     writeToPipe(pipefd, str,stell);

                 }

        }

}
    return 0;
}

Body:
write(fd[WRITE_END], stell, sizeof(stell));

I think your code lacks an ampersand here. Instead of the stell variable you should use its address:

write(fd[WRITE_END], &stell, sizeof(stell));


问:
How to start an Unity App with an Intent from another App?
I tried to open the application with some testing apps which allow me to create the intent. But this was not working and also not with my code. My guess for the root of the problem is the generated manifest file from Unity. There are 2 projects exported, the packagename which is visible for adb etc. is within this manifest.

```<code><?xml version="1.0" encoding="utf-8"?>
<!-- GENERATED BY UNITY. REMOVE THIS COMMENT TO PREVENT OVERWRITING WHEN EXPORTING AGAIN-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.app" xmlns:tools="http://schemas.android.com/tools" android:installLocation="preferExternal">
  <supports-screens android:smallScreens="true" android:normalScreens="true" android:largeScreens="true" android:xlargeScreens="true" android:anyDensity="true" />
  <application android:label="@string/app_name" android:icon="@mipmap/app_icon" />
</manifest>
</code>```

This manifest has no intent-filter and since there is no activity within this project, I'm not sure how I could add one. I think I need an intent filter to make the intent call from outside of my app work. Has anyone solved this before or has an idea how to solve it?

The other manifest looks like this, but has a generic package name which is also not visible from the outside (adb). But this one has an intent-filter. But I'm pretty sure, that I can't access this with an intent.

```<code><?xml version="1.0" encoding="utf-8"?>
<!-- GENERATED BY UNITY. REMOVE THIS COMMENT TO PREVENT OVERWRITING WHEN EXPORTING AGAIN-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.unity3d.player" xmlns:tools="http://schemas.android.com/tools">
  <application>
    <activity android:name="com.unity3d.player.UnityPlayerActivity" android:theme="@style/UnityThemeSelector" android:screenOrientation="fullSensor" android:launchMode="singleTask" android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|uiMode|screenSize|smallestScreenSize|fontScale|layoutDirection|density" android:hardwareAccelerated="false">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
      <meta-data android:name="unityplayer.UnityActivity" android:value="true" />
      <meta-data android:name="android.notch_support" android:value="true" />
    </activity>
    <meta-data android:name="unity.splash-mode" android:value="0" />
    <meta-data android:name="unity.splash-enable" android:value="True" />
    <meta-data android:name="notch.config" android:value="portrait|landscape" />
    <meta-data android:name="unity.build-id" android:value="f5abdf68-b589-4d67-acb2-5c55e15b3fd3" />
  </application>
  <uses-feature android:glEsVersion="0x00030000" />
  <uses-feature android:name="android.hardware.vulkan.version" android:required="false" />
  <uses-feature android:name="android.hardware.touchscreen" android:required="false" />
  <uses-feature android:name="android.hardware.touchscreen.multitouch" android:required="false" />
  <uses-feature android:name="android.hardware.touchscreen.multitouch.distinct" android:required="false" />
</manifest>
</code>```

答:
If this is the android manifest in the temp->staging area folder and you modify it.. it wont work. because unity creates a new android manifest everytime you build it. Instead create an android manifest file in Plugins->Android folder and create the intent-filter and unity will automatically merge the 2 android manifest.

And make sure you make your modifications to the second intent filter the one with VIEW data. add something like android:scheme(im on mobile and just google it and you will find it) and your intent etc.

Body:
I tried to open the application with some testing apps which allow me to create the intent. But this was not working and also not with my code. My guess for the root of the problem is the generated manifest file from Unity. There are 2 projects exported, the packagename which is visible for adb etc. is within this manifest.

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.app" xmlns:tools="http://schemas.android.com/tools" android:installLocation="preferExternal">
  <supports-screens android:smallScreens="true" android:normalScreens="true" android:largeScreens="true" android:xlargeScreens="true" android:anyDensity="true" />
  <application android:label="@string/app_name" android:icon="@mipmap/app_icon" />
</manifest>

This manifest has no intent-filter and since there is no activity within this project, I'm not sure how I could add one. I think I need an intent filter to make the intent call from outside of my app work. Has anyone solved this before or has an idea how to solve it?

The other manifest looks like this, but has a generic package name which is also not visible from the outside (adb). But this one has an intent-filter. But I'm pretty sure, that I can't access this with an intent.

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.unity3d.player" xmlns:tools="http://schemas.android.com/tools">
  <application>
    <activity android:name="com.unity3d.player.UnityPlayerActivity" android:theme="@style/UnityThemeSelector" android:screenOrientation="fullSensor" android:launchMode="singleTask" android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|uiMode|screenSize|smallestScreenSize|fontScale|layoutDirection|density" android:hardwareAccelerated="false">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
      <meta-data android:name="unityplayer.UnityActivity" android:value="true" />
      <meta-data android:name="android.notch_support" android:value="true" />
    </activity>
    <meta-data android:name="unity.splash-mode" android:value="0" />
    <meta-data android:name="unity.splash-enable" android:value="True" />
    <meta-data android:name="notch.config" android:value="portrait|landscape" />
    <meta-data android:name="unity.build-id" android:value="f5abdf68-b589-4d67-acb2-5c55e15b3fd3" />
  </application>
  <uses-feature android:glEsVersion="0x00030000" />
  <uses-feature android:name="android.hardware.vulkan.version" android:required="false" />
  <uses-feature android:name="android.hardware.touchscreen" android:required="false" />
  <uses-feature android:name="android.hardware.touchscreen.multitouch" android:required="false" />
  <uses-feature android:name="android.hardware.touchscreen.multitouch.distinct" android:required="false" />
</manifest>


问:
How to execute psql interactive in its docker container?
I want to run a query in Postgres interactive shell. I'm using a docker container for this purpose as follows:

Here is the relevant piece of docker-compose:

```<code>  db_of_ivms:
    image: postgres:10
    restart: unless-stopped
    ports:
     - 5432:5432
    container_name: db_of_ivms
    environment:
      POSTGRES_PASSWORD: xxx
      POSTGRES_USER: ivms_usr
      POSTGRES_DB: ivms_db
</code>```

Nevertheless, I'm dealing with this error:

docker exec -it -u 0 db_of_ivms bash

```<code># psql

psql: FATAL:  role "root" does not exist
</code>```

答:
You need shell  in with the postgres user

```<code>docker exec -it -u postgres db_of_ivms bash
</code>```

Now for containers that you dont specify POSTGRES_USER: ivms_usr:

```<code>postgres@d9b097b8db8c:/$ psql
postgres=# \l
                                 List of databases
   Name    |  Owner   | Encoding |  Collate   |   Ctype    |   Access privileges
-----------+----------+----------+------------+------------+-----------------------
 postgres  | postgres | UTF8     | en_US.utf8 | en_US.utf8 |
 template0 | postgres | UTF8     | en_US.utf8 | en_US.utf8 | =c/postgres          +
           |          |          |            |            | postgres=CTc/postgres
 template1 | postgres | UTF8     | en_US.utf8 | en_US.utf8 | =c/postgres          +
           |          |          |            |            | postgres=CTc/postgres
(3 rows)

</code>```

If you specify POSTGRES_USER: ivms_usr and Database (note psql command arguments):

```<code>docker exec -it -u postgres db_of_ivms bash
postgres@2cec2435bb83:/$ psql -U ivms_usr -d ivms_db
psql (10.12 (Debian 10.12-1.pgdg90+1))
Type "help" for help.

ivms_db=# \l
                                 List of databases
   Name    |  Owner   | Encoding |  Collate   |   Ctype    |   Access privileges
-----------+----------+----------+------------+------------+-----------------------
 ivms_db   | ivms_usr | UTF8     | en_US.utf8 | en_US.utf8 |
 postgres  | ivms_usr | UTF8     | en_US.utf8 | en_US.utf8 |
 template0 | ivms_usr | UTF8     | en_US.utf8 | en_US.utf8 | =c/ivms_usr          +
           |          |          |            |            | ivms_usr=CTc/ivms_usr
 template1 | ivms_usr | UTF8     | en_US.utf8 | en_US.utf8 | =c/ivms_usr          +
           |          |          |            |            | ivms_usr=CTc/ivms_usr
(4 rows)
</code>```

Body:
I want to run a query in Postgres interactive shell. I'm using a docker container for this purpose as follows:

Here is the relevant piece of docker-compose:

  db_of_ivms:
    image: postgres:10
    restart: unless-stopped
    ports:
     - 5432:5432
    container_name: db_of_ivms
    environment:
      POSTGRES_PASSWORD: xxx
      POSTGRES_USER: ivms_usr
      POSTGRES_DB: ivms_db

Nevertheless, I'm dealing with this error:

docker exec -it -u 0 db_of_ivms bash

# psql

psql: FATAL:  role "root" does not exist

Body:
You need shell  in with the postgres user

docker exec -it -u postgres db_of_ivms bash

Now for containers that you dont specify POSTGRES_USER: ivms_usr:

postgres@d9b097b8db8c:/$ psql
postgres=# \l
                                 List of databases
   Name    |  Owner   | Encoding |  Collate   |   Ctype    |   Access privileges
-----------+----------+----------+------------+------------+-----------------------
 postgres  | postgres | UTF8     | en_US.utf8 | en_US.utf8 |
 template0 | postgres | UTF8     | en_US.utf8 | en_US.utf8 | =c/postgres          +
           |          |          |            |            | postgres=CTc/postgres
 template1 | postgres | UTF8     | en_US.utf8 | en_US.utf8 | =c/postgres          +
           |          |          |            |            | postgres=CTc/postgres
(3 rows)

If you specify POSTGRES_USER: ivms_usr and Database (note psql command arguments):

docker exec -it -u postgres db_of_ivms bash
postgres@2cec2435bb83:/$ psql -U ivms_usr -d ivms_db
psql (10.12 (Debian 10.12-1.pgdg90+1))
Type "help" for help.

ivms_db=# \l
                                 List of databases
   Name    |  Owner   | Encoding |  Collate   |   Ctype    |   Access privileges
-----------+----------+----------+------------+------------+-----------------------
 ivms_db   | ivms_usr | UTF8     | en_US.utf8 | en_US.utf8 |
 postgres  | ivms_usr | UTF8     | en_US.utf8 | en_US.utf8 |
 template0 | ivms_usr | UTF8     | en_US.utf8 | en_US.utf8 | =c/ivms_usr          +
           |          |          |            |            | ivms_usr=CTc/ivms_usr
 template1 | ivms_usr | UTF8     | en_US.utf8 | en_US.utf8 | =c/ivms_usr          +
           |          |          |            |            | ivms_usr=CTc/ivms_usr
(4 rows)


问:
Upload to Google Drive not working using oauth PlayGround (java)
I want to use google drive api to upload some files to my drive using java
The thing is that the upload is successfull but when i open my drive i can't find the file so i've edited the permission and added my email (to share it with me) but i can't download the file there is just the name of the upload any idea why ?</p>

```<code>public static void connect() throws IOException, GeneralSecurityException {
    UL.debug("Creating HTTP_TRANSPORT & a JSON_FACTORY");
    HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();

    UL.debug("Login-in with credentials");
    GoogleCredential credential = GoogleCredential.fromStream(new FileInputStream(CREDENTIALS_FILE))
            .createScoped(Collections.singleton(DriveScopes.DRIVE));

    UL.debug("User: " + credential.getServiceAccountUser() + " ID: " + credential.getServiceAccountProjectId());
    UL.debug("Creating Drive Instance");
    DRIVE_SERVICE = new Drive.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, credential)
            .setApplicationName("Backup")
            .build();

}

public static void upload() throws IOException {
    UL.debug("Creating file metadata");
    File fileMetadata = new File();
    fileMetadata.setName("Test");
    fileMetadata.setMimeType("application/rar");

    UL.debug("creating new filepath");
    java.io.File filePath = new java.io.File(DATA_FOLDER, "test3.rar");

    UL.debug("Creating file content (rar)");
    FileContent rarContent = new FileContent("application/rar", filePath);

    UL.debug("Pushing the file to drive !");
    Drive.Files.Create upload = DRIVE_SERVICE.files().create(fileMetadata, rarContent);
    upload.getMediaHttpUploader().setProgressListener(new FileUploadProgressListener());
    upload.setFields("*");

    File e = upload.execute();

    UL.debug("Push success: " + e.getId() + " " + e.getName() + " " + e.getMimeType());

    Permission newPermission = new Permission();

    newPermission.setEmailAddress("eaglezledozo@gmail.com");
    newPermission.setType("user");
    newPermission.setRole("writer");
    DRIVE_SERVICE.permissions().create(e.getId(), newPermission).execute();
}
</code>```

答:
You are performing an upload with a service account

The way you doing it, the file will be uploaded to the service'accounts Drive - not to yours.

If you want to perform an upload with a service account which is supposed to act on your behalf (that is upload a file to YOUR drive), you need to use impersonation.

In java, when building DRIVE_SERVICE, you have to add the line

.setServiceAccountId(emailAddress)

specifying the email address of the user on whose behalf the service account is supposed to act (so in this case - your email address).

Body:
I want to use google drive api to upload some files to my drive using java
The thing is that the upload is successfull but when i open my drive i can't find the file so i've edited the permission and added my email (to share it with me) but i can't download the file there is just the name of the upload any idea why ?

public static void connect() throws IOException, GeneralSecurityException {
    UL.debug("Creating HTTP_TRANSPORT & a JSON_FACTORY");
    HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();

    UL.debug("Login-in with credentials");
    GoogleCredential credential = GoogleCredential.fromStream(new FileInputStream(CREDENTIALS_FILE))
            .createScoped(Collections.singleton(DriveScopes.DRIVE));

    UL.debug("User: " + credential.getServiceAccountUser() + " ID: " + credential.getServiceAccountProjectId());
    UL.debug("Creating Drive Instance");
    DRIVE_SERVICE = new Drive.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, credential)
            .setApplicationName("Backup")
            .build();

}

public static void upload() throws IOException {
    UL.debug("Creating file metadata");
    File fileMetadata = new File();
    fileMetadata.setName("Test");
    fileMetadata.setMimeType("application/rar");

    UL.debug("creating new filepath");
    java.io.File filePath = new java.io.File(DATA_FOLDER, "test3.rar");

    UL.debug("Creating file content (rar)");
    FileContent rarContent = new FileContent("application/rar", filePath);

    UL.debug("Pushing the file to drive !");
    Drive.Files.Create upload = DRIVE_SERVICE.files().create(fileMetadata, rarContent);
    upload.getMediaHttpUploader().setProgressListener(new FileUploadProgressListener());
    upload.setFields("*");

    File e = upload.execute();

    UL.debug("Push success: " + e.getId() + " " + e.getName() + " " + e.getMimeType());

    Permission newPermission = new Permission();

    newPermission.setEmailAddress("eaglezledozo@gmail.com");
    newPermission.setType("user");
    newPermission.setRole("writer");
    DRIVE_SERVICE.permissions().create(e.getId(), newPermission).execute();
}


问:
Using CoreML Word Tagger on iOS 12.4
I trained a Core ML Text Classifier with Transfer Learning and Dynamic Embedding. It works great, but when I tried testing on a device running iOS 12.4, it failed to predict and gave me the error:

```<code>Error Domain=com.apple.CoreML Code=0 "Prediction failed" UserInfo={NSLocalizedDescription=Prediction failed}
</code>```

I also get this error when running on a simulator. I made sure the model could only be used on devices running iOS 12+. Is this model not supported on iOS 13? I saw these new features were released at this WWDC, but I was hoping/assuming they were backward compatible. Was I mistaken? If this model can't be run on iOS 12 devices, is there any way to export the model so it can be. Lastly, is there anywhere I can find a list of what models are supported on each iOS.

Thanks so much!

答:
New features that were introduced with Core ML 3 don't run on older devices, only on iOS 13 and up.

However, if your model has such features, I would have expected an error message when loading the model. Does the debug output pane show any other messages?

Title: Using CoreML Word Tagger on iOS 12.4

Body:
I trained a Core ML Text Classifier with Transfer Learning and Dynamic Embedding. It works great, but when I tried testing on a device running iOS 12.4, it failed to predict and gave me the error:

Error Domain=com.apple.CoreML Code=0 "Prediction failed" UserInfo={NSLocalizedDescription=Prediction failed}

I also get this error when running on a simulator. I made sure the model could only be used on devices running iOS 12+. Is this model not supported on iOS 13? I saw these new features were released at this WWDC, but I was hoping/assuming they were backward compatible. Was I mistaken? If this model can't be run on iOS 12 devices, is there any way to export the model so it can be. Lastly, is there anywhere I can find a list of what models are supported on each iOS.

Thanks so much!


问:
sqlite-nodejs3: How do I notify nodejs when sqlite trigger has been triggered?
Here is what I need:

Nodejs creates a trigger in sqlite db (using node-sqlite3 module)

Trigger, well, gets triggered.

Nodejs process gets notified of that.

Here is what I am exloring:

Is it possible to supply a js callback when creating a trigger?

If not, is there an event in nodejs that I can listen to?

If not, can I use RAISE() in sqlite and catch it in nodejs?

What other possibilities are there? Perhaps have sqlite write to a socket?

Any wise man out there to nudge me in a right direction?

答:
You can listen for the 'trace' event emitted from the sqlite module. There is currently no way to intercept or stop queries in the module, so the most you can do is listen for this event which is emitted immediately when a query is executed and create your logic from there.

https://github.com/mapbox/node-sqlite3/wiki/Debugging


问:
How can i increase a counter via editText?
My program involves calculating multiple expenses,

I made it so that you can increase or decrease the values using + or - buttons.

upon pressing on the buttons, it updates a counter which the program will then access to display total expenses.

i am now trying to update the counter via EditText but could not figure it out.
(basically, enter amount instead of relying on buttons)

This is my counterhandler code

```<code>    public class CounterHandler implements View.OnClickListener {

    private int counter;
    private EditText editAmount;

    public int getCounter() { return counter; }

    public CounterHandler(ConstraintLayout layout) {
        editAmount = layout.findViewById(R.id.editAmount);
        layout.findViewById(R.id.buttonPlus)
                .setOnClickListener(CounterHandler.this);
        layout.findViewById(R.id.buttonMinus)
                .setOnClickListener(CounterHandler.this);
        counter = 0;
    }

    @Override
    public void onClick(View v) {
        if (v.getId()==R.id.buttonMinus) {
            counter = Math.max(0, --counter);
        }
        else if (v.getId()==R.id.buttonPlus) {
            counter++;
        }
        else {
            counter = Integer.parseInt(editAmount.getText().toString());
        }
        editAmount.setText(String.valueOf(counter));
    }
}
</code>```

this is the mainactivity code where the program accessed the info and calculates the total expenses

```<code>    public void onClick(View v) {
        if (v.getId()==R.id.buttonCalculate) {

            totalSum = counterBills.getCounter() + counterDrink.getCounter() +
                    counterTransportation.getCounter() + counterRent.getCounter() +
                    counterMeal.getCounter() + counterCollege.getCounter() + counterOthers.getCounter();

            Intent intent = new Intent(MainActivity.this, Summary.class);
            intent.putExtra("total", totalSum);
            startActivity(intent);

            Toast.makeText(MainActivity.this, "Total Expenses Calculated", Toast.LENGTH_LONG) .show();
        }
    }
}
</code>```

答:
Remove the else case from your onClickListener, only update the text in EditText in case of plus and minus button clicks.

For editing text in your EditText use TextWatcher.

```<code>    editAmount.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        //Do nothing
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        //Do nothing
    }

    @Override
    public void afterTextChanged(Editable s) {

        counter = Math.max(0, Integer.parseInt(s.toString()));
    }
});
</code>```

Body:
My program involves calculating multiple expenses,

I made it so that you can increase or decrease the values using + or - buttons.

upon pressing on the buttons, it updates a counter which the program will then access to display total expenses.

i am now trying to update the counter via EditText but could not figure it out.
(basically, enter amount instead of relying on buttons)

This is my counterhandler code

    public class CounterHandler implements View.OnClickListener {

    private int counter;
    private EditText editAmount;

    public int getCounter() { return counter; }

    public CounterHandler(ConstraintLayout layout) {
        editAmount = layout.findViewById(R.id.editAmount);
        layout.findViewById(R.id.buttonPlus)
                .setOnClickListener(CounterHandler.this);
        layout.findViewById(R.id.buttonMinus)
                .setOnClickListener(CounterHandler.this);
        counter = 0;
    }

    @Override
    public void onClick(View v) {
        if (v.getId()==R.id.buttonMinus) {
            counter = Math.max(0, --counter);
        }
        else if (v.getId()==R.id.buttonPlus) {
            counter++;
        }
        else {
            counter = Integer.parseInt(editAmount.getText().toString());
        }
        editAmount.setText(String.valueOf(counter));
    }
}

this is the mainactivity code where the program accessed the info and calculates the total expenses

    public void onClick(View v) {
        if (v.getId()==R.id.buttonCalculate) {

            totalSum = counterBills.getCounter() + counterDrink.getCounter() +
                    counterTransportation.getCounter() + counterRent.getCounter() +
                    counterMeal.getCounter() + counterCollege.getCounter() + counterOthers.getCounter();

            Intent intent = new Intent(MainActivity.this, Summary.class);
            intent.putExtra("total", totalSum);
            startActivity(intent);

            Toast.makeText(MainActivity.this, "Total Expenses Calculated", Toast.LENGTH_LONG) .show();
        }
    }
}

Body:
Remove the else case from your onClickListener, only update the text in EditText in case of plus and minus button clicks.

For editing text in your EditText use TextWatcher.

    editAmount.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        //Do nothing
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        //Do nothing
    }

    @Override
    public void afterTextChanged(Editable s) {

        counter = Math.max(0, Integer.parseInt(s.toString()));
    }
});