问:
DependencyProperty in my UserControl fails to update bound property in ViewModel
I have made an usercontrol that contains a TextBox with some custom behaviours and I want to bind the Text property to a property in my ViewModel.

I have isolated the problem into a sample solution and manage to update the Text property with the ViewModel property value, but when I write into the textbox and leaves the textbox my Person.Name property is not updated.

My usercontrol xaml:

```<code><UserControl x:Class="WpfCustomUserControlBinding.TextBoxReadOnlyLooksDisabled"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

<Control.Resources>
    <Style x:Key="readOnlyTextbox">
        <Style.Triggers>
            <Trigger Property="TextBoxBase.IsReadOnly" Value="True">
                <Setter Property="TextBoxBase.Background" Value="WhiteSmoke" />
                <Setter Property="TextBoxBase.Foreground" Value="#FF6D6D6D" />
                <Setter Property="TextBox.BorderBrush" Value="DarkGray" />
                <Setter Property="TextBoxBase.BorderThickness" Value="1,1,1,1" />
            </Trigger>
            <Trigger Property="TextBoxBase.IsReadOnly" Value="False">
                <Setter Property="TextBoxBase.Background" Value="White" />
                <Setter Property="TextBoxBase.Foreground" Value="Black" />
            </Trigger>
        </Style.Triggers>
    </Style>
</Control.Resources>

<TextBox Style="{StaticResource readOnlyTextbox}" x:Name="txtTextBoxBase" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
</code>```

The codebehind code:

```<code>public partial class TextBoxReadOnlyLooksDisabled
{
    public TextBoxReadOnlyLooksDisabled()
    {
        InitializeComponent();
    }

    public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof (string)
                                                                                , typeof (TextBoxReadOnlyLooksDisabled)
                                                                                ,new PropertyMetadata(OnTextChange));

    private static void OnTextChange(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var textBoxReadOnlyLooksDisabled = (TextBoxReadOnlyLooksDisabled) d;
        textBoxReadOnlyLooksDisabled.txtTextBoxBase.Text = (string) e.NewValue;
    }

    public string Text
    {
        get { return (string) GetValue(TextProperty); }
        set { SetValue(TextProperty, value); }
    }
}
</code>```

Window where I try to get the sample to work:

```<code><Window x:Class="WpfCustomUserControlBinding.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:src="clr-namespace:WpfCustomUserControlBinding" Title="MainWindow" Height="153" Width="525">
<Window.Resources>
    <src:Person x:Key="myDataSource"/>
</Window.Resources>
<Grid >
    <Label Content="Plain vanilla" Height="26" HorizontalAlignment="Left" Margin="12,12,0,0" Name="label1" VerticalAlignment="Top" Width="143" />
    <Label Content="Messed up version" Height="26" HorizontalAlignment="Left" Margin="12,61,0,0" Name="label2" VerticalAlignment="Top" Width="143" />
    <TextBox Height="23" HorizontalAlignment="Left" Margin="152,15,0,0" x:Name="txtVanlig" VerticalAlignment="Top" Width="251" Text="{Binding Source={StaticResource myDataSource}, Path=Name, Mode=TwoWay}"/>

    <src:TextBoxReadOnlyLooksDisabled Height="23" HorizontalAlignment="Left" Margin="152,61,0,0" x:Name="txtVrien" VerticalAlignment="Top" Width="251" Text="{Binding Source={StaticResource myDataSource}, Path=Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</Grid>
</code>```

The sample value class:

```<code> public class Person
{
    private string _name = "King Chaos";

    public string Name{get{return _name;}set{_name = value;}}
}
</code>```

Thanks in advance. ;)

Edit: Adding INotifyPropertyChanged does not do the trick since the set method of the Name is not accessed when updating my custom TextBox.

答:
The problem is that the TextBox inside your TextBoxReadOnlyLooksDisabled UserControl has no two-way binding to the Text property - you only update the TextBox programmatically (in the OnTextChanged handler) when your property value changes, but not vice-versa.

Why not just drop the changed handler altogether, and add a binding instead, like this:

```<code><UserControl x:Class="WpfCustomUserControlBinding.TextBoxReadOnlyLooksDisabled"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

<Control.Resources>
  //...
</Control.Resources>

<TextBox Style="{StaticResource readOnlyTextbox}"
         x:Name="txtTextBoxBase"
         HorizontalAlignment="Stretch"
         VerticalAlignment="Stretch"
         Text="{Binding Path=Text, Mode=TwoWay}"/>
</code>```

Don't forget to also set the DataContext accordingly:

```<code>public partial class TextBoxReadOnlyLooksDisabled : UserControl
{
    public TextBoxReadOnlyLooksDisabled()
    {
        InitializeComponent();
        DataContext = this;
    }

    public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string),
                                                                                typeof(TextBoxReadOnlyLooksDisabled));

    public string Text
    {
        get { return (string)GetValue(TextProperty); }
        set { SetValue(TextProperty, value); }
    }
}
</code>```

Body:
I have made an usercontrol that contains a TextBox with some custom behaviours and I want to bind the Text property to a property in my ViewModel.

I have isolated the problem into a sample solution and manage to update the Text property with the ViewModel property value, but when I write into the textbox and leaves the textbox my Person.Name property is not updated.

My usercontrol xaml:

<UserControl x:Class="WpfCustomUserControlBinding.TextBoxReadOnlyLooksDisabled"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

<Control.Resources>

    </Style>
</Control.Resources>

<TextBox Style="{StaticResource readOnlyTextbox}" x:Name="txtTextBoxBase" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />

The codebehind code:

public partial class TextBoxReadOnlyLooksDisabled
{
    public TextBoxReadOnlyLooksDisabled()
    {
        InitializeComponent();
    }

    public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof (string)
                                                                                , typeof (TextBoxReadOnlyLooksDisabled)
                                                                                ,new PropertyMetadata(OnTextChange));

    private static void OnTextChange(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var textBoxReadOnlyLooksDisabled = (TextBoxReadOnlyLooksDisabled) d;
        textBoxReadOnlyLooksDisabled.txtTextBoxBase.Text = (string) e.NewValue;
    }

    public string Text
    {
        get { return (string) GetValue(TextProperty); }
        set { SetValue(TextProperty, value); }
    }
}

Window where I try to get the sample to work:

<Window x:Class="WpfCustomUserControlBinding.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:src="clr-namespace:WpfCustomUserControlBinding" Title="MainWindow" Height="153" Width="525">
<Window.Resources>
    <src:Person x:Key="myDataSource"/>
</Window.Resources>
<Grid >

    <TextBox Height="23" HorizontalAlignment="Left" Margin="152,15,0,0" x:Name="txtVanlig" VerticalAlignment="Top" Width="251" Text="{Binding Source={StaticResource myDataSource}, Path=Name, Mode=TwoWay}"/>

    <src:TextBoxReadOnlyLooksDisabled Height="23" HorizontalAlignment="Left" Margin="152,61,0,0" x:Name="txtVrien" VerticalAlignment="Top" Width="251" Text="{Binding Source={StaticResource myDataSource}, Path=Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</Grid>

The sample value class:

 public class Person
{
    private string _name = "King Chaos";

    public string Name{get{return _name;}set{_name = value;}}
}

Thanks in advance. ;)

Edit: Adding INotifyPropertyChanged does not do the trick since the set method of the Name is not accessed when updating my custom TextBox.

Body:
The problem is that the TextBox inside your TextBoxReadOnlyLooksDisabled UserControl has no two-way binding to the Text property - you only update the TextBox programmatically (in the OnTextChanged handler) when your property value changes, but not vice-versa.

Why not just drop the changed handler altogether, and add a binding instead, like this:

<UserControl x:Class="WpfCustomUserControlBinding.TextBoxReadOnlyLooksDisabled"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

<Control.Resources>
  //...
</Control.Resources>

<TextBox Style="{StaticResource readOnlyTextbox}"
         x:Name="txtTextBoxBase"
         HorizontalAlignment="Stretch"
         VerticalAlignment="Stretch"
         Text="{Binding Path=Text, Mode=TwoWay}"/>

Don't forget to also set the DataContext accordingly:

public partial class TextBoxReadOnlyLooksDisabled : UserControl
{
    public TextBoxReadOnlyLooksDisabled()
    {
        InitializeComponent();
        DataContext = this;
    }

    public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string),
                                                                                typeof(TextBoxReadOnlyLooksDisabled));

    public string Text
    {
        get { return (string)GetValue(TextProperty); }
        set { SetValue(TextProperty, value); }
    }
}


来源: stackexchange

问:
C# string array from JSON
I'm currently using Newtonsoft's json library to deserialize json from a file.

JSON:

```<code>{
"name":"test",
"description":"test",
"tags":"Maps"
}
</code>```

C#:

```<code>public class RootObject
{
    public string name { get; set; }
    public string tag { get; set; }
    public string description { get; set; }
    public string[] tags { get; set; }
}
</code>```

The "tags" has to be an array as it is required for steam.

How can I retrieve the "tags" as an string array?
The console prints out this expection:

```<code>Newtonsoft.Json.JsonSerializationException: Error converting value "Maps" to type 'System.String[]'. Path 'tags', line 4, position 17
</code>```

答:
What you need is a Custom JsonConverter.

```<code>public class StringOrArrayToStringConveter<T> : JsonConverter
</code>```

The meat of the solution is the override of the ReadJson which you need to return an array of T.  Then you can use it like

```<code>[JsonConverter(typeof(StringOrArrayToStringConveter<string>))]
public string[] tags { get; set; }
</code>```

Hope that put you in a good starting point.

EDIT:

```<code>  using System;
  using System.Collections.Generic;
  using Newtonsoft.Json;
  using Newtonsoft.Json.Linq;

  namespace ConsoleApp1
  {
      public class RootObject
      {
          public string name { get; set; }
          public string tag { get; set; }
          public string description { get; set; }
          [JsonConverter(typeof(StringOrArrayToStringConveter<string>))]
          public string[] tags { get; set; }
      }

      class Program
      {
          static void Main(string[] args)
          {
              var data1 = "{\"name\":\"test\", \"description\":\"test\",\"tags\":\"Maps\"}";

              var deserialized1 = JsonConvert.DeserializeObject<RootObject>(data1);

              var data2 = "{\"name\":\"test\", \"description\":\"test\",\"tags\":[\"Maps\", \"Maps2\"]}";

              var deserialized2 = JsonConvert.DeserializeObject<RootObject>(data2);

          }
      }

      public class StringOrArrayToStringConveter<T> : JsonConverter
      {
          public override bool CanConvert(Type objectType)
          {
              return true;
          }

          public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
          {
              object returnValue = new Object();
              if (reader.TokenType == JsonToken.StartArray)
              {
                  returnValue = JToken.Load(reader).ToObject<T[]>();
              }
              else if (reader.TokenType == JsonToken.String)
              {
                  T instance = (T)serializer.Deserialize(reader, typeof(T));
                  returnValue = new List<T>() { instance }.ToArray();
              }
              return returnValue;
          }

          public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
          {
              throw new NotImplementedException();
          }
      }
  }
</code>```

ContentLicense: CC BY-SA 3.0

Title: C# string array from JSON

Body:
I'm currently using Newtonsoft's json library to deserialize json from a file.

JSON:

{
"name":"test",
"description":"test",
"tags":"Maps"
}

C#:

public class RootObject
{
    public string name { get; set; }
    public string tag { get; set; }
    public string description { get; set; }
    public string[] tags { get; set; }
}

The "tags" has to be an array as it is required for steam.

How can I retrieve the "tags" as an string array?
The console prints out this expection:

Newtonsoft.Json.JsonSerializationException: Error converting value "Maps" to type 'System.String[]'. Path 'tags', line 4, position 17

Body:
What you need is a Custom JsonConverter.

public class StringOrArrayToStringConveter<T> : JsonConverter

The meat of the solution is the override of the ReadJson which you need to return an array of T.  Then you can use it like

[JsonConverter(typeof(StringOrArrayToStringConveter<string>))]
public string[] tags { get; set; }

Hope that put you in a good starting point.

EDIT:

  using System;
  using System.Collections.Generic;
  using Newtonsoft.Json;
  using Newtonsoft.Json.Linq;

  namespace ConsoleApp1
  {
      public class RootObject
      {
          public string name { get; set; }
          public string tag { get; set; }
          public string description { get; set; }
          [JsonConverter(typeof(StringOrArrayToStringConveter<string>))]
          public string[] tags { get; set; }
      }

      class Program
      {
          static void Main(string[] args)
          {
              var data1 = "{\"name\":\"test\", \"description\":\"test\",\"tags\":\"Maps\"}";

              var deserialized1 = JsonConvert.DeserializeObject<RootObject>(data1);

              var data2 = "{\"name\":\"test\", \"description\":\"test\",\"tags\":[\"Maps\", \"Maps2\"]}";

              var deserialized2 = JsonConvert.DeserializeObject<RootObject>(data2);

          }
      }

      public class StringOrArrayToStringConveter<T> : JsonConverter
      {
          public override bool CanConvert(Type objectType)
          {
              return true;
          }

          public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
          {
              object returnValue = new Object();
              if (reader.TokenType == JsonToken.StartArray)
              {
                  returnValue = JToken.Load(reader).ToObject<T[]>();
              }
              else if (reader.TokenType == JsonToken.String)
              {
                  T instance = (T)serializer.Deserialize(reader, typeof(T));
                  returnValue = new List<T>() { instance }.ToArray();
              }
              return returnValue;
          }

          public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
          {
              throw new NotImplementedException();
          }
      }
  }


问:
prime numbers algorithm efficiency
I have a question about prime numbers algorithm.

why in the following pseudo code i increases by 6 and not by 2 every iteration?

```<code>function is_prime(n)
if n ≤ 1
    return false
else if n ≤ 3
    return true
else if n mod 2 = 0 or n mod 3 = 0
    return false
let i ← 5
while i * i ≤ n
    if n mod i = 0 or n mod (i + 2) = 0
        return false
    i ← i + 6
return true
</code>```

Thanks!

答: The assignment in the loop body is i <- i + 6, not i <- i + 2. In the if statement the expression i + 2 just becomes a new value. There is no assignment operator in that expression.

Title: prime numbers algorithm efficiency

Body:
I have a question about prime numbers algorithm.

why in the following pseudo code i increases by 6 and not by 2 every iteration?

function is_prime(n)
if n ≤ 1
    return false
else if n ≤ 3
    return true
else if n mod 2 = 0 or n mod 3 = 0
    return false
let i ← 5
while i * i ≤ n
    if n mod i = 0 or n mod (i + 2) = 0
        return false
    i ← i + 6
return true

Thanks!


问:
How do I get hgweb to actually display the repository I want?
I am having an infuriating experience with IIS7, Python 2.6, Mercurial 1.7.2, and hgweb.cgi.

After battling for an afternoon getting hgweb.cgi to work, I finally got it to render in the browser using hgweb.cgi and IIS7.  I can now see a blank rendering of the web server, that is, a header with no repositories listed.

Now, according to the multipe sites I've read after scouring through Google results, I know that I have to update my hgweb.config file to point to some repositories.

However, for the life of me, I can't get it to list my repository using either the [paths] or [collections] entries.

I have the following directory structure, (simplified but illustrative...):

c:\code
c:\code\htmlwriter
c:\code\CommandLineProjects\Clean

The latter two directories have mercurial repositories in them.

I am trying to publish the repository in c:\code\htmlwriter

Now, if I make this entry in hgweb.config

```<code>[paths]
htmlwriter = c:\code\htmlwriter
</code>```

I get nothing listed in my output.

If I put

```<code>[paths]
htmlwriter = c:\code\*
</code>```

I get something, but not what I want, i.e. this:

htmlwriter/CommandLineProjects/Clean

(Note that the about drills down one directory level farther than I want it to).

I can't seem to find any combination of paths, asterisks, or anything else that will serve up the repository in c:\code\htmlwriter.  It appears to always want to go one level deeper than I want it to, or to show nothing.

I know that my hgweb.config file is being read because I can change the style tag in it and it changes what is rendered.

I have read and re-read multiple time a number of resources on the web, but they all say what I'm trying should be working.  For instance, I followed this instructions to the letter with no good results:

http://www.jeremyskinner.co.uk/mercurial-on-iis7/

Anyone have any suggestions?

答:
I had about the same luck with hgweb.cgi, and ended up going a different route with wsgi and a "pure python" mercurial install.
I wrote a pretty comprehensive answer here.</p>

ContentLicense: CC BY-SA 2.5

Body:
I am having an infuriating experience with IIS7, Python 2.6, Mercurial 1.7.2, and hgweb.cgi.

After battling for an afternoon getting hgweb.cgi to work, I finally got it to render in the browser using hgweb.cgi and IIS7.  I can now see a blank rendering of the web server, that is, a header with no repositories listed.

Now, according to the multipe sites I've read after scouring through Google results, I know that I have to update my hgweb.config file to point to some repositories.

However, for the life of me, I can't get it to list my repository using either the [paths] or [collections] entries.

I have the following directory structure, (simplified but illustrative...):

c:\code
c:\code\htmlwriter
c:\code\CommandLineProjects\Clean

The latter two directories have mercurial repositories in them.

I am trying to publish the repository in c:\code\htmlwriter

Now, if I make this entry in hgweb.config

[paths]
htmlwriter = c:\code\htmlwriter

I get nothing listed in my output.

If I put

[paths]
htmlwriter = c:\code\*

I get something, but not what I want, i.e. this:

htmlwriter/CommandLineProjects/Clean

(Note that the about drills down one directory level farther than I want it to).

I can't seem to find any combination of paths, asterisks, or anything else that will serve up the repository in c:\code\htmlwriter.  It appears to always want to go one level deeper than I want it to, or to show nothing.

I know that my hgweb.config file is being read because I can change the style tag in it and it changes what is rendered.

I have read and re-read multiple time a number of resources on the web, but they all say what I'm trying should be working.  For instance, I followed this instructions to the letter with no good results:

http://www.jeremyskinner.co.uk/mercurial-on-iis7/

Anyone have any suggestions?


问:
Mongodb java driver connection time outs
I did a fresh install of mongoDB (3.4.5) on my Ubuntu 16.04.

I am able to successfully connect with the python driver, however my java driver keeps returning a connection timed out exception.

```<code>com.mongodb.MongoSocketOpenException: Exception opening socket
at com.mongodb.connection.SocketStream.open(SocketStream.java:63) ~[mongodb-driver-core-3.4.2.jar:?]
at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:115) ~[mongodb-driver-core-3.4.2.jar:?]
at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:113) ~[mongodb-driver-core-3.4.2.jar:?]
at java.lang.Thread.run(Thread.java:745) [?:1.8.0_121]
Caused by: java.net.SocketTimeoutException: connect timed out
at java.net.PlainSocketImpl.socketConnect(Native Method) ~[?:1.8.0_121]
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350) ~[?:1.8.0_121]
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:204) ~[?:1.8.0_121]
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188) ~[?:1.8.0_121]
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) ~[?:1.8.0_121]
at java.net.Socket.connect(Socket.java:589) ~[?:1.8.0_121]
at com.mongodb.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:57) ~[mongodb-driver-core-3.4.2.jar:?]
at com.mongodb.connection.SocketStream.open(SocketStream.java:58) ~[mongodb-driver-core-3.4.2.jar:?]
... 3 more
</code>```

I have started mongo DB with the following config options:

```<code>{ config: "/etc/mongod.conf", net: { bindIp: "0.0.0.0", port: 27017 },
storage: { dbPath: "/var/lib/mongodb", journal: { enabled: true } },
 systemLog: { destination: "file", logAppend: true, path: "/var/log/mongodb/mongod.log", quiet: true } }
</code>```

And in my Java class, I have:

MongoClient mongoClient = new MongoClient(host:"0.0.0.0", port:27017);

I have checked using telnet that port 27017 is accessible. Not sure why else this is causing a connection timed out. I'll really appreciate any help.

Thanks.

答: There was some issues regarding the outgoing port 27017 being blocked. Adding a firewall rule to open that port fixed the issue. </p>

Body:
I did a fresh install of mongoDB (3.4.5) on my Ubuntu 16.04.

I am able to successfully connect with the python driver, however my java driver keeps returning a connection timed out exception.

com.mongodb.MongoSocketOpenException: Exception opening socket
at com.mongodb.connection.SocketStream.open(SocketStream.java:63) ~[mongodb-driver-core-3.4.2.jar:?]
at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:115) ~[mongodb-driver-core-3.4.2.jar:?]
at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:113) ~[mongodb-driver-core-3.4.2.jar:?]
at java.lang.Thread.run(Thread.java:745) [?:1.8.0_121]
Caused by: java.net.SocketTimeoutException: connect timed out
at java.net.PlainSocketImpl.socketConnect(Native Method) ~[?:1.8.0_121]
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350) ~[?:1.8.0_121]
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:204) ~[?:1.8.0_121]
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188) ~[?:1.8.0_121]
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) ~[?:1.8.0_121]
at java.net.Socket.connect(Socket.java:589) ~[?:1.8.0_121]
at com.mongodb.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:57) ~[mongodb-driver-core-3.4.2.jar:?]
at com.mongodb.connection.SocketStream.open(SocketStream.java:58) ~[mongodb-driver-core-3.4.2.jar:?]
... 3 more

I have started mongo DB with the following config options:

{ config: "/etc/mongod.conf", net: { bindIp: "0.0.0.0", port: 27017 },
storage: { dbPath: "/var/lib/mongodb", journal: { enabled: true } },
 systemLog: { destination: "file", logAppend: true, path: "/var/log/mongodb/mongod.log", quiet: true } }

And in my Java class, I have:

MongoClient mongoClient = new MongoClient(host:"0.0.0.0", port:27017);

I have checked using telnet that port 27017 is accessible. Not sure why else this is causing a connection timed out. I'll really appreciate any help.

Thanks.


问:
Spark Dataframe/RDD cannot create new column by counting the contents of another column
I have a Spark RDD (or Dataframe - converting to either is not a problem) that has the following columns (example for each structure):

res248: org.apache.spark.rdd.RDD[(String, Array[String])] = MapPartitionsRDD[1004] at map at <console>:246
org.apache.spark.sql.DataFrame = [id: string, list: array<string>]
```

<p>I want to expand this RDD/DF to have an additional column containing the size of the list array. So the output should be something like this (example):</p>

<pre class="lang-none prettyprint-override"><code>org.apache.spark.sql.DataFrame = [id: string, list: array<string>, length_of_list: int]
</code>```

I tried to do an rdd.map(x=> (x._1,x._2,count(x._2))) but got an error message:

<console>:246: error: overloaded method value count with alternatives:
  (columnName: String)org.apache.spark.sql.TypedColumn[Any,Long] <and>
  (e: org.apache.spark.sql.Column)org.apache.spark.sql.Column
```

Tried adding a new column using DF with the function withColumn("new_column",count($"list")) or any variation thereof. It still doesn't work. I get an error message complaining about aggregation.

Do you know of a way to achieve this without having to collect the RDD?

答:
There is inbuilt function size which returns the length of array or map. </p>

```<code>import org.apache.spark.sql.functions._
df.withColumn("length_of_list", size($"list"))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a Spark RDD (or Dataframe - converting to either is not a problem) that has the following columns (example for each structure):

res248: org.apache.spark.rdd.RDD[(String, Array[String])] = MapPartitionsRDD[1004] at map at <console>:246
org.apache.spark.sql.DataFrame = [id: string, list: array<string>]

I want to expand this RDD/DF to have an additional column containing the size of the list array. So the output should be something like this (example):

org.apache.spark.sql.DataFrame = [id: string, list: array<string>, length_of_list: int]

I tried to do an rdd.map(x=> (x._1,x._2,count(x._2))) but got an error message:

<console>:246: error: overloaded method value count with alternatives:
  (columnName: String)org.apache.spark.sql.TypedColumn[Any,Long] <and>
  (e: org.apache.spark.sql.Column)org.apache.spark.sql.Column

Tried adding a new column using DF with the function withColumn("new_column",count($"list")) or any variation thereof. It still doesn't work. I get an error message complaining about aggregation.

Do you know of a way to achieve this without having to collect the RDD?

Body:
There is inbuilt function size which returns the length of array or map.

import org.apache.spark.sql.functions._
df.withColumn("length_of_list", size($"list"))


问:
How to implement IP filter on 2 billion IP addresses?
We have different projects and one of them is white label DSP solution .
Our client requested to enable the filtering of all incoming traffic by IP.
They gave us the list of addresses which contains 2.05 billion records and it should work in real-time.

These addresses can be compacted into 6 million ranges. We have only 10 milliseconds to conduct this check-up.

This task should be implemented using NodeJS.

Do you have any suggestion on how to get it done or which mechanism should be appropriate for this task?

答:
It is not clear what do you mean by 'all incoming traffic'. If you're filtering IP packets and you need a scalable solution, I would strongly suggest against it. There is some SDN hardware that could be used to do what they want but I guess that's outside of the project's scope.

Anyway, I'll try to answer your question (at least partially) and give you some general tips (not node.js specific). First, there are a few things that should be clarified and those are:

Are we talking only about IPv4?

Is the list dynamic (will they
add/remove IPs from the list)

Regardless, you can apply the similar that routers do when they're doing route lookups. You can build patricia trie (Radix tree) and do the search in it (Also take a look at this article if you're serious about it). Keep in mind that in routing world 10ms is considered to be a lifetime so even the software based router on a 'slow' speed CPU (under 1GHz) could possibly do hundreds of IPv4 lookups in 10ms timeframe. hedgar2017 gave you similar example and depending on how much resources you have (and how much traffic), you probably don't need to worry about performance (if you're checking the IP only when establishing a user session).

If you're also doing IPv6 (and you should at least plan for it) the approach is similar. Only thing i would mention is that even if IPv6 has 128bits, ISPs are assigning each user a /48 (or in the worst case scenario /64) prefix. You can build your tree up to /48 and get a bit faster lookups.

OwnerDisplayName: Irina Kovalenko


问:
JavaFX - Label format changes spontaneously
First of all, let me apologize for not including code. I tried to reproduce this issue with a smaller project but was unsuccessful. The issue itself is sporadic as well, so it is difficult for me to nail down the culprit.

Basically, what is happening: I have my UI defined in FXML and it includes several labels throughout, some of which I have set the font to "Bold."

```<code><Label text="Appetite Info:">
    <font>
        <Font name="System Bold" size="12.0"/>
    </font>
</Label>
</code>```

The problem is that, as the user clicks around the UI, all of these labels will be reset to "Normal" font weight. Sometimes it is giving focus to a text field or scroll pane, other times it happens just when the main UI window loses focus.

I do have the application styled with CSS, but this happens even with a Default.css that doesn't override any formatting:

```<code>.root {

}
</code>```

Has anyone else noticed this behavior or know where I should look for a solution?

答: I'll mark this as answered. Styling all my nodes with CSS instead of through the FXML markup solves this issue.</p>

Body:
First of all, let me apologize for not including code. I tried to reproduce this issue with a smaller project but was unsuccessful. The issue itself is sporadic as well, so it is difficult for me to nail down the culprit.

Basically, what is happening: I have my UI defined in FXML and it includes several labels throughout, some of which I have set the font to "Bold."

The problem is that, as the user clicks around the UI, all of these labels will be reset to "Normal" font weight. Sometimes it is giving focus to a text field or scroll pane, other times it happens just when the main UI window loses focus.

I do have the application styled with CSS, but this happens even with a Default.css that doesn't override any formatting:

.root {

}

Has anyone else noticed this behavior or know where I should look for a solution?


问:
Import JSON file in node application with TypeScript
I'm really getting crazy because I can't find a solution for this.
What I want to archive is to import a JSON file with a configuration into my TypeScript file.
I've learned that I need a declaration file. So I've added a file json-loader.d.ts into my project. I also tried it at several levels (root, typings folder, custom_typings folder) because this are the solutions I've found.
The file content looks like this:

declare module "json!*" {
    let json: any;
    export = json;
}

declare module "*.json" {
    const value: any;
    export default value;
}```
</div>
</div>
</p>

<p>But the compiler still tells me, that it is not possible to import the JSON file, because it isn't a module.
So, how is the compiler getting aware, that there is such a declaration file?</p>

<p>I already tried to modify my tsconfig.json like this:</p>

```{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "outDir": "dist",
    "typeRoots": [
      "./node_modules/@types",
      "./typings"
    ]
  },
  "include": [
    "src/**/*.ts"
  ],
  "exclude": [
    "node_modules"
  ]
}
```

But it still doesn't work. Any suggestions?

Thanks!

答:
Examples on the web that use declare module "*.json" work because Webpack is configured to load JSON files.

If you don't want to bother with that you can use var instead of import:

var json = require('../config.json');

as suggested in this answer

Body:
I'm really getting crazy because I can't find a solution for this.
What I want to archive is to import a JSON file with a configuration into my TypeScript file.
I've learned that I need a declaration file. So I've added a file json-loader.d.ts into my project. I also tried it at several levels (root, typings folder, custom_typings folder) because this are the solutions I've found.
The file content looks like this:

declare module "json!*" {
    let json: any;
    export = json;
}

declare module "*.json" {
    const value: any;
    export default value;
}

But the compiler still tells me, that it is not possible to import the JSON file, because it isn't a module.
So, how is the compiler getting aware, that there is such a declaration file?

I already tried to modify my tsconfig.json like this:

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "outDir": "dist",
    "typeRoots": [
      "./node_modules/@types",
      "./typings"
    ]
  },
  "include": [
    "src/**/*.ts"
  ],
  "exclude": [
    "node_modules"
  ]
}

But it still doesn't work. Any suggestions?

Thanks!


问:
recursion- find the biggest worm in matrix
i have the following question:
for a nXn matrix, we will define a "worm" at the size of k which is a series of adjacent cells with consecutive numbers. adjacent cell is the cell from the right\left\up\down of the current cell ( not diagonal).
i need to write a recursive function which return the longest worm in array
for instance: in matrix:

```<code>{{3,4,5,6},
 {5,6,2,7},
 {12,13,14,15},
 {19,18,17,16}};
</code>```

the longest worm is 8 cells. starting from [2][0] and ends at [3][0].

so far i have written the following code:

```<code>public static int longestWarm(int[][] arr, int row, int col) {
    if (row < 0 || row >= arr.length || col < 0 || col >= arr.length) return 0;
    if (col >= arr.length || row >= arr.length) return 0;

    int sum1 = 1, sum2 = 1, sum3 = 1, sum4 = 1;

    if (row > 0 && arr[row][col] == arr[row - 1][col] - 1)
            sum1 = 1 + longestWarm(arr, row - 1,col);
    else if (row < arr[0].length - 1 && arr[row][col] == arr[row + 1][col] - 1)
            sum2 = 1 + longestWarm(arr, row + 1, col);
    else if (col > 0 && arr[row][col] == arr[row][col - 1] - 1)
            sum3 = 1 + longestWarm(arr, row, col - 1);
    else if (col < arr[0].length - 1 && arr[row][col] == arr[row][col + 1] - 1)
            sum4 = 1 + longestWarm(arr, row, col + 1);

    int max1 = Math.max(sum1, sum2);
    int max2 = Math.max(sum3, sum4);

    return Math.max(max1, max2);
}
</code>```

the problem is that i get the first worm that i find in matrix and not the biggest one. my output is 5 and not 8.
please help finding what i am doing wrong.

答:
I used the method is_tail to trim only check worms that start at a cell with neighbors that aren't 1 less than it. If such a neighbor exists, then it is obviously not the tail of the longest worm. From each tail you find the max sized worm that grows from that cell similarly to what you did.</p>

```<code>import java.util.ArrayList;

//a pair of ints, row and col, that indicate a cell in a matrix
class Cell {
    int row;
    int col;

    public Cell(int row, int col) {
        this.row = row;
        this.col = col;
    }

    public int get_row() {
        return row;
    }

    public int get_col() {
        return col;
    }

    public String toString() {
        return "row: " + row + " col: " + col;
    }
}

// a class to hold the matrix data and methods
// so that every call doesnt require passing the pointer m
class Matrix {
    // m used for the matrix so that i dont have to type matrix repeatedly
    int[][] m;
    int height;
    int width;

    public Matrix(int[][] m) {
        this.m = m;
        height = m.length;
        width = m[0].length;
    }

    public int get_height() {
        return height;
    }

    public int get_width() {
        return width;
    }

    // checks if the cell at row,col is a tail
    // a tail is a cell with 0 neighbors that are 1 less than its value
    public boolean is_tail(int row, int col) {
        if (row < 0 || row >= m.length || col < 0 || col >= m[0].length)
            return false;

        int curVal = m[row][col]; // Value in the cell being checked

        // check if neighbor is out of bounds, then if it is smaller
        if (row - 1 >= 0 && m[row - 1][col] == curVal - 1)
            return false;
        if (row + 1 < m.length && m[row + 1][col] == curVal - 1)
            return false;
        if (col - 1 >= 0 && m[row][col - 1] == curVal - 1)
            return false;
        if (col + 1 < m[0].length && m[row][col + 1] == curVal - 1)
            return false;

        return true;
    }

    public ArrayList<Cell> longestWorm(int row, int col) {
        if (row < 0 || row >= m.length || col < 0 || col >= m[0].length)
            return new ArrayList<Cell>();

        int curVal = m[row][col];
        ArrayList<Cell> longest_path = new ArrayList<Cell>();

        if (row - 1 >= 0 && m[row - 1][col] == curVal + 1) {
            ArrayList<Cell> path_left = longestWorm(row - 1, col);
            if (path_left.size() > longest_path.size())
                longest_path = path_left;
        }

        if (row + 1 < m.length && m[row + 1][col] == curVal + 1) {
            ArrayList<Cell> path_right = longestWorm(row + 1, col);
            if (path_right.size() > longest_path.size())
                longest_path = path_right;
        }

        if (col - 1 >= 0 && m[row][col - 1] == curVal + 1) {
            ArrayList<Cell> path_up = longestWorm(row, col - 1);
            if (path_up.size() > longest_path.size())
                longest_path = path_up;
        }

        if (col + 1 < m[0].length && m[row][col + 1] == curVal + 1) {
            ArrayList<Cell> path_down = longestWorm(row, col + 1);
            if (path_down.size() > longest_path.size())
                longest_path = path_down;
        }

        longest_path.add(new Cell(row, col));
        return longest_path;
    }
}

class Main {

    public static void main(String[] args) {
        int[][] matrix = { { 3, 4, 5, 6 }, { 5, 6, 2, 7 }, { 12, 13, 14, 15 }, { 19, 18, 17, 16 } };

        ArrayList<Cell> longest_worm = new ArrayList<Cell>();

        Matrix myMatrix = new Matrix(matrix);
        for (int i = 0; i < myMatrix.get_height(); i++) {
            for (int j = 0; j < myMatrix.get_width(); j++) {
                if (myMatrix.is_tail(i, j)) {
                    ArrayList<Cell> new_worm = myMatrix.longestWorm(i, j);
                    if (new_worm.size() > longest_worm.size()) {
                        longest_worm = new_worm;
                    }
                }
            }
        }

        for (int i = longest_worm.size() - 1; i >= 0; i--) {
            System.out.println(longest_worm.get(i));
        }
    }
}
</code>```

Body:
i have the following question:
for a nXn matrix, we will define a "worm" at the size of k which is a series of adjacent cells with consecutive numbers. adjacent cell is the cell from the right\left\up\down of the current cell ( not diagonal).
i need to write a recursive function which return the longest worm in array
for instance: in matrix:

{{3,4,5,6},
 {5,6,2,7},
 {12,13,14,15},
 {19,18,17,16}};

the longest worm is 8 cells. starting from [2][0] and ends at [3][0].

so far i have written the following code:

public static int longestWarm(int[][] arr, int row, int col) {
    if (row < 0 || row >= arr.length || col < 0 || col >= arr.length) return 0;
    if (col >= arr.length || row >= arr.length) return 0;

    int sum1 = 1, sum2 = 1, sum3 = 1, sum4 = 1;

    if (row > 0 && arr[row][col] == arr[row - 1][col] - 1)
            sum1 = 1 + longestWarm(arr, row - 1,col);
    else if (row < arr[0].length - 1 && arr[row][col] == arr[row + 1][col] - 1)
            sum2 = 1 + longestWarm(arr, row + 1, col);
    else if (col > 0 && arr[row][col] == arr[row][col - 1] - 1)
            sum3 = 1 + longestWarm(arr, row, col - 1);
    else if (col < arr[0].length - 1 && arr[row][col] == arr[row][col + 1] - 1)
            sum4 = 1 + longestWarm(arr, row, col + 1);

    int max1 = Math.max(sum1, sum2);
    int max2 = Math.max(sum3, sum4);

    return Math.max(max1, max2);
}

the problem is that i get the first worm that i find in matrix and not the biggest one. my output is 5 and not 8.
please help finding what i am doing wrong.

Body:
I used the method is_tail to trim only check worms that start at a cell with neighbors that aren't 1 less than it. If such a neighbor exists, then it is obviously not the tail of the longest worm. From each tail you find the max sized worm that grows from that cell similarly to what you did.

import java.util.ArrayList;

//a pair of ints, row and col, that indicate a cell in a matrix
class Cell {
    int row;
    int col;

    public Cell(int row, int col) {
        this.row = row;
        this.col = col;
    }

    public int get_row() {
        return row;
    }

    public int get_col() {
        return col;
    }

    public String toString() {
        return "row: " + row + " col: " + col;
    }
}

// a class to hold the matrix data and methods
// so that every call doesnt require passing the pointer m
class Matrix {
    // m used for the matrix so that i dont have to type matrix repeatedly
    int[][] m;
    int height;
    int width;

    public Matrix(int[][] m) {
        this.m = m;
        height = m.length;
        width = m[0].length;
    }

    public int get_height() {
        return height;
    }

    public int get_width() {
        return width;
    }

    // checks if the cell at row,col is a tail
    // a tail is a cell with 0 neighbors that are 1 less than its value
    public boolean is_tail(int row, int col) {
        if (row < 0 || row >= m.length || col < 0 || col >= m[0].length)
            return false;

        int curVal = m[row][col]; // Value in the cell being checked

        // check if neighbor is out of bounds, then if it is smaller
        if (row - 1 >= 0 && m[row - 1][col] == curVal - 1)
            return false;
        if (row + 1 < m.length && m[row + 1][col] == curVal - 1)
            return false;
        if (col - 1 >= 0 && m[row][col - 1] == curVal - 1)
            return false;
        if (col + 1 < m[0].length && m[row][col + 1] == curVal - 1)
            return false;

        return true;
    }

    public ArrayList<Cell> longestWorm(int row, int col) {
        if (row < 0 || row >= m.length || col < 0 || col >= m[0].length)
            return new ArrayList<Cell>();

        int curVal = m[row][col];
        ArrayList<Cell> longest_path = new ArrayList<Cell>();

        if (row - 1 >= 0 && m[row - 1][col] == curVal + 1) {
            ArrayList<Cell> path_left = longestWorm(row - 1, col);
            if (path_left.size() > longest_path.size())
                longest_path = path_left;
        }

        if (row + 1 < m.length && m[row + 1][col] == curVal + 1) {
            ArrayList<Cell> path_right = longestWorm(row + 1, col);
            if (path_right.size() > longest_path.size())
                longest_path = path_right;
        }

        if (col - 1 >= 0 && m[row][col - 1] == curVal + 1) {
            ArrayList<Cell> path_up = longestWorm(row, col - 1);
            if (path_up.size() > longest_path.size())
                longest_path = path_up;
        }

        if (col + 1 < m[0].length && m[row][col + 1] == curVal + 1) {
            ArrayList<Cell> path_down = longestWorm(row, col + 1);
            if (path_down.size() > longest_path.size())
                longest_path = path_down;
        }

        longest_path.add(new Cell(row, col));
        return longest_path;
    }
}

class Main {

    public static void main(String[] args) {
        int[][] matrix = { { 3, 4, 5, 6 }, { 5, 6, 2, 7 }, { 12, 13, 14, 15 }, { 19, 18, 17, 16 } };

        ArrayList<Cell> longest_worm = new ArrayList<Cell>();

        Matrix myMatrix = new Matrix(matrix);
        for (int i = 0; i < myMatrix.get_height(); i++) {
            for (int j = 0; j < myMatrix.get_width(); j++) {
                if (myMatrix.is_tail(i, j)) {
                    ArrayList<Cell> new_worm = myMatrix.longestWorm(i, j);
                    if (new_worm.size() > longest_worm.size()) {
                        longest_worm = new_worm;
                    }
                }
            }
        }

        for (int i = longest_worm.size() - 1; i >= 0; i--) {
            System.out.println(longest_worm.get(i));
        }
    }
}


问:
Python RabbitMQ connection inherited by child
The problem is the following.
Call a python program which does two thing : connect to a rabbitmq server and calls a c program that spawn two process.

When the python program finishes, the connection is still established in charge of a child.

So a child inherits its parent resource when parent dies.

doing a netstat -putan | grep rabbitmqip

```<code>tcp  0 0 localhost:39744   rabbitmqip:5672 ESTABLISHED 25693/child
</code>```

This is what i get when python script finished.

I would imagine that the connection would be lost in a case like this.

This seems to happen with connections to a RabbitMQ server, we cant reproduce with regular TCP connections.

Has anyone had this issue before ? is there any workaround ?

The python code would be my rabbit consumer and the c program would be scripts in background that are spawned or killed based on the worker's job. I cant have the connection established when i kill the consumer, regardless spawns being active or not because then the children would get messages which they dont understand from the queue.

Code as example :

Python :

```<code>connection = pika.BlockingConnection(pika.ConnectionParameters(host='RabbitServer'))
print ("Starting Child...")
system("/home/path/test/child")
print ("Done")
</code>```

Child program.

pid_t pstartId, sessionId;

// Fork 1
pstartId = fork();
if (pstartId < 0) {
    printf("The System can not create a proccess. \n");
    perror("fork");
    exit(EXIT_FAILURE);
}

if (pstartId > 0) { exit(EXIT_SUCCESS);}

// Fork 2
pstartId = fork();
if (pstartId < 0) {
    printf("The System can not create a proccess. \n");
    perror("fork");
    exit(EXIT_FAILURE);
}

if (pstartId > 0) {exit(EXIT_SUCCESS);}

if ((sessionId = setsid()) < 0) {
    printf("The System can not set a id session. \n");
    perror("setid");
    exit(EXIT_FAILURE);
}

if (chdir("/") < 0) {
    printf("The System can not change dir /. \n");
    perror("chdir");
    exit(EXIT_FAILURE);
}

while(1){
    syslog(LOG_INFO, "I'm a child");
    sleep(1);
}
```

答:
When you spawn a subprocess via fork() in unix the child process inherits all of the parent's open file descriptors. The child process is responsible for closing the descriptors it doesn't need.

Your code is calling fork twice, once indirectly via os.system() and then again directly in your C code. So you have two ways of dealing with this:

The first is to close all of the unused file descriptors you don't need in the child process of your C code. This is generally a good practice, if you don't it isn't uncommon to run out of file descriptors in your system if you spawn many children and they all get copies of their parent's fds.

```<code>#include <unistd.h>
#def MAXFD 256

void close_fds() {
  int i;
  for (i = 3; i < MAXFD; i++) {
    close(i);
  }
}
</code>```

The other option would be to have the file descriptors closed in the fork call made by Python. You aren't able to do that if you call os.system(), but you have this option if you make the nearly equivalent call with the subprocess module:

```<code>from subprocess import Popen

Popen("/home/path/test/child", close_fds=True).wait()
</code>```

Body:
The problem is the following.
Call a python program which does two thing : connect to a rabbitmq server and calls a c program that spawn two process.

When the python program finishes, the connection is still established in charge of a child.

So a child inherits its parent resource when parent dies.

doing a netstat -putan | grep rabbitmqip

tcp  0 0 localhost:39744   rabbitmqip:5672 ESTABLISHED 25693/child

This is what i get when python script finished.

I would imagine that the connection would be lost in a case like this.

This seems to happen with connections to a RabbitMQ server, we cant reproduce with regular TCP connections.

Has anyone had this issue before ? is there any workaround ?

The python code would be my rabbit consumer and the c program would be scripts in background that are spawned or killed based on the worker's job. I cant have the connection established when i kill the consumer, regardless spawns being active or not because then the children would get messages which they dont understand from the queue.

Code as example :

Python :

connection = pika.BlockingConnection(pika.ConnectionParameters(host='RabbitServer'))
print ("Starting Child...")
system("/home/path/test/child")
print ("Done")

Child program.

pid_t pstartId, sessionId;

// Fork 1
pstartId = fork();
if (pstartId < 0) {
    printf("The System can not create a proccess. \n");
    perror("fork");
    exit(EXIT_FAILURE);
}

if (pstartId > 0) { exit(EXIT_SUCCESS);}

// Fork 2
pstartId = fork();
if (pstartId < 0) {
    printf("The System can not create a proccess. \n");
    perror("fork");
    exit(EXIT_FAILURE);
}

if (pstartId > 0) {exit(EXIT_SUCCESS);}

if ((sessionId = setsid()) < 0) {
    printf("The System can not set a id session. \n");
    perror("setid");
    exit(EXIT_FAILURE);
}

if (chdir("/") < 0) {
    printf("The System can not change dir /. \n");
    perror("chdir");
    exit(EXIT_FAILURE);
}

while(1){
    syslog(LOG_INFO, "I'm a child");
    sleep(1);
}

Body:
When you spawn a subprocess via fork() in unix the child process inherits all of the parent's open file descriptors. The child process is responsible for closing the descriptors it doesn't need.

Your code is calling fork twice, once indirectly via os.system() and then again directly in your C code. So you have two ways of dealing with this:

The first is to close all of the unused file descriptors you don't need in the child process of your C code. This is generally a good practice, if you don't it isn't uncommon to run out of file descriptors in your system if you spawn many children and they all get copies of their parent's fds.

#include <unistd.h>
#def MAXFD 256

void close_fds() {
  int i;
  for (i = 3; i < MAXFD; i++) {
    close(i);
  }
}

The other option would be to have the file descriptors closed in the fork call made by Python. You aren't able to do that if you call os.system(), but you have this option if you make the nearly equivalent call with the subprocess module:

from subprocess import Popen

Popen("/home/path/test/child", close_fds=True).wait()


问:
Query to retrieve neighbors is too slow
I have a set of Django ORM models representing a directed graph, and I'm trying to retrieve all the adjacent vertices to a given vertex ignoring edge direction:

```<code>class Vertex(models.Model):
    pass

class Edge(models.Model):
    orig = models.ForeignKey(Vertex, related_name='%(class)s_orig', null=True, blank=True)
    dest = models.ForeignKey(Vertex, related_name='%(class)s_dest', null=True, blank=True)
    # ... other data about this edge ...
</code>```

The query Vertex.objects.filter(Q(edge_orig__dest=v) | Q(edge_dest__orig=v)).distinct() returns the correct result, but in my case it takes far too long to execute.

Typically for my application there will be around 50-100 vertices at any given time, and around a million edges. Even reducing it to only 20 vertices and 100000 edges, that query takes about a minute and a half to execute:

```<code>for i in range(20):
    Vertex().save()

vxs = list(Vertex.objects.all())
for i in tqdm.tqdm(range(100000)):
    Edge(orig = random.sample(vxs,1)[0], dest = random.sample(vxs,1)[0]).save()

v = vxs[0]
def f1():
    return list( Vertex.objects.filter(
        Q(edge_orig__dest=v) | Q(edge_dest__orig=v)).distinct() )

t1 = timeit.Timer(f1)

print( t1.timeit(number=1) ) # 84.21138522100227
</code>```

On the other hand, if I split the query up into two pieces I can get the exact same result in only a handful of milliseconds:

```<code>def f2():
    q1 = Vertex.objects.filter(edge_orig__dest=v).distinct()
    q2 = Vertex.objects.filter(edge_dest__orig=v).distinct()
    return list( {x for x in itertools.chain(q1, q2)} )

t2 = timeit.Timer(f2)
print( t2.timeit(number=100)/100 ) # 0.0109818680600074
</code>```

This second version has issues though:

It's not atomic. The list of edges is almost guaranteed to change between the two queries in my application, meaning the results won't represent a single point in time.

I can't perform additional processing and aggregation on the results without manually looping over it. (e.g. If I wanted Vertex.objects.filter(Q(edge_orig__dest=v) | Q(edge_dest__orig=v)).distinct().aggregate(avg=Avg('some_field')))

Why does the second version run so much faster than the first one?
How can I do this, and is there a way to get the first one to run fast enough for practical use?

I'm currently testing with Python 3.5.2, PostgreSQL 9.5.6, and Django 1.11, although if this is an issue with one of those I'm not stuck with them.

Here is the SQL generated by each query, as well as Postgres's explan:

The first one:

```<code>Vertex.objects.filter(Q(edge_orig__dest=v) | Q(edge_dest__orig=v))

SELECT DISTINCT "app_vertex"."id"
FROM "app_vertex"
LEFT OUTER JOIN "app_edge" ON ("app_vertex"."id" = "app_edge"."orig_id")
LEFT OUTER JOIN "app_edge" T4 ON ("app_vertex"."id" = T4."dest_id")
WHERE ("app_edge"."dest_id" = 1061
       OR T4."orig_id" = 1061)

HashAggregate  (cost=8275151.47..8275151.67 rows=20 width=4)
  Group Key: app_vertex.id
  ->  Hash Left Join  (cost=3183.45..8154147.45 rows=48401608 width=4)
        Hash Cond: (app_vertex.id = app_edge.orig_id)
        Filter: ((app_edge.dest_id = 1061) OR (t4.orig_id = 1061))
        ->  Hash Right Join  (cost=1.45..2917.45 rows=100000 width=8)
              Hash Cond: (t4.dest_id = app_vertex.id)
              ->  Seq Scan on app_edge t4  (cost=0.00..1541.00 rows=100000 width=8)
              ->  Hash  (cost=1.20..1.20 rows=20 width=4)
                    ->  Seq Scan on app_vertex  (cost=0.00..1.20 rows=20 width=4)
        ->  Hash  (cost=1541.00..1541.00 rows=100000 width=8)
              ->  Seq Scan on app_edge  (cost=0.00..1541.00 rows=100000 width=8)
</code>```

The second ones:

```<code>Vertex.objects.filter(edge_orig__dest=v).distinct()

SELECT DISTINCT "app_vertex"."id"
FROM "app_vertex"
INNER JOIN "app_edge" ON ("app_vertex"."id" = "app_edge"."orig_id")
WHERE "app_edge"."dest_id" = 1061

HashAggregate  (cost=1531.42..1531.62 rows=20 width=4)
  Group Key: app_vertex.id
  ->  Hash Join  (cost=848.11..1519.04 rows=4950 width=4)
        Hash Cond: (app_edge.orig_id = app_vertex.id)
        ->  Bitmap Heap Scan on app_edge  (cost=846.65..1449.53 rows=4950 width=4)
              Recheck Cond: (dest_id = 1061)
              ->  Bitmap Index Scan on app_edge_dest_id_4254b90f  (cost=0.00..845.42 rows=4950 width=0)
                    Index Cond: (dest_id = 1061)
        ->  Hash  (cost=1.20..1.20 rows=20 width=4)
              ->  Seq Scan on app_vertex  (cost=0.00..1.20 rows=20 width=4)
</code>```

@khampson's version also takes a minute-and-a-half to run, so it's also a no-go.

```<code>Vertex.objects.raw( ... )

SELECT DISTINCT "app_vertex"."id"
FROM "app_vertex"
JOIN "app_edge" ON ("app_vertex"."id" = "app_edge"."orig_id")
JOIN "app_edge" T4 ON ("app_vertex"."id" = T4."dest_id")
WHERE ("app_edge"."dest_id" = 1061
       OR T4."orig_id" = 1061);

HashAggregate  (cost=8275347.47..8275347.67 rows=20 width=4)
  Group Key: app_vertex.id
  ->  Hash Join  (cost=3183.45..8154343.45 rows=48401608 width=4)
        Hash Cond: (app_vertex.id = app_edge.orig_id)
        Join Filter: ((app_edge.dest_id = 1061) OR (t4.orig_id = 1061))
        ->  Hash Join  (cost=1.45..2917.45 rows=100000 width=12)
              Hash Cond: (t4.dest_id = app_vertex.id)
              ->  Seq Scan on app_edge t4  (cost=0.00..1541.00 rows=100000 width=8)
              ->  Hash  (cost=1.20..1.20 rows=20 width=4)
                    ->  Seq Scan on app_vertex  (cost=0.00..1.20 rows=20 width=4)
        ->  Hash  (cost=1541.00..1541.00 rows=100000 width=8)
              ->  Seq Scan on app_edge  (cost=0.00..1541.00 rows=100000 width=8)
</code>```

答:
The query plans for those two queries are radically different. The first (slower) one isn't hitting any indexes, and is doing two left joins, both of which result in way, way more rows being processed and returned. From what I interpret of the intention of the Django ORM syntax, it doesn't sound like you would truly want to do left joins here.

I would recommend considering dropping down into raw SQL in this case from within the Django ORM, and hybridize the two. e.g. if you take the first one, and transform it to something like this:

```<code>SELECT DISTINCT "app_vertex"."id"
FROM "app_vertex"
JOIN "app_edge" ON ("app_vertex"."id" = "app_edge"."orig_id")
JOIN "app_edge" T4 ON ("app_vertex"."id" = T4."dest_id")
WHERE ("app_edge"."dest_id" = 1061
       OR T4."orig_id" = 1061);
</code>```

Two questions there: How does that version perform, and does it give you the results you're looking for?

For more info on raw queries, check out this section of the Django doc.

Response to comment from OP:

The query plan for the query I suggested also shows that it's not hitting any indexes.

Do you have indexes on both tables for the columns involved? I suspect not, especially since for this specific query, we're looking for a single value, which means if there were indexes, I would be very surprised if the query planner determined a sequential scan were a better choice (OTOH, if you were looking for a wide range of rows, say, over 10% of the rows in the tables, the query planner might correctly make such a decision).

Title: Query to retrieve neighbors is too slow

Body:
I have a set of Django ORM models representing a directed graph, and I'm trying to retrieve all the adjacent vertices to a given vertex ignoring edge direction:

class Vertex(models.Model):
    pass

class Edge(models.Model):
    orig = models.ForeignKey(Vertex, related_name='%(class)s_orig', null=True, blank=True)
    dest = models.ForeignKey(Vertex, related_name='%(class)s_dest', null=True, blank=True)
    # ... other data about this edge ...

The query Vertex.objects.filter(Q(edge_orig__dest=v) | Q(edge_dest__orig=v)).distinct() returns the correct result, but in my case it takes far too long to execute.

Typically for my application there will be around 50-100 vertices at any given time, and around a million edges. Even reducing it to only 20 vertices and 100000 edges, that query takes about a minute and a half to execute:

for i in range(20):
    Vertex().save()

vxs = list(Vertex.objects.all())
for i in tqdm.tqdm(range(100000)):
    Edge(orig = random.sample(vxs,1)[0], dest = random.sample(vxs,1)[0]).save()

v = vxs[0]
def f1():
    return list( Vertex.objects.filter(
        Q(edge_orig__dest=v) | Q(edge_dest__orig=v)).distinct() )

t1 = timeit.Timer(f1)

print( t1.timeit(number=1) ) # 84.21138522100227

On the other hand, if I split the query up into two pieces I can get the exact same result in only a handful of milliseconds:

def f2():
    q1 = Vertex.objects.filter(edge_orig__dest=v).distinct()
    q2 = Vertex.objects.filter(edge_dest__orig=v).distinct()
    return list( {x for x in itertools.chain(q1, q2)} )

t2 = timeit.Timer(f2)
print( t2.timeit(number=100)/100 ) # 0.0109818680600074

This second version has issues though:

It's not atomic. The list of edges is almost guaranteed to change between the two queries in my application, meaning the results won't represent a single point in time.

I can't perform additional processing and aggregation on the results without manually looping over it. (e.g. If I wanted Vertex.objects.filter(Q(edge_orig__dest=v) | Q(edge_dest__orig=v)).distinct().aggregate(avg=Avg('some_field')))

Why does the second version run so much faster than the first one?
How can I do this, and is there a way to get the first one to run fast enough for practical use?

I'm currently testing with Python 3.5.2, PostgreSQL 9.5.6, and Django 1.11, although if this is an issue with one of those I'm not stuck with them.

Here is the SQL generated by each query, as well as Postgres's explan:

The first one:

Vertex.objects.filter(Q(edge_orig__dest=v) | Q(edge_dest__orig=v))

SELECT DISTINCT "app_vertex"."id"
FROM "app_vertex"
LEFT OUTER JOIN "app_edge" ON ("app_vertex"."id" = "app_edge"."orig_id")
LEFT OUTER JOIN "app_edge" T4 ON ("app_vertex"."id" = T4."dest_id")
WHERE ("app_edge"."dest_id" = 1061
       OR T4."orig_id" = 1061)

HashAggregate  (cost=8275151.47..8275151.67 rows=20 width=4)
  Group Key: app_vertex.id
  ->  Hash Left Join  (cost=3183.45..8154147.45 rows=48401608 width=4)
        Hash Cond: (app_vertex.id = app_edge.orig_id)
        Filter: ((app_edge.dest_id = 1061) OR (t4.orig_id = 1061))
        ->  Hash Right Join  (cost=1.45..2917.45 rows=100000 width=8)
              Hash Cond: (t4.dest_id = app_vertex.id)
              ->  Seq Scan on app_edge t4  (cost=0.00..1541.00 rows=100000 width=8)
              ->  Hash  (cost=1.20..1.20 rows=20 width=4)
                    ->  Seq Scan on app_vertex  (cost=0.00..1.20 rows=20 width=4)
        ->  Hash  (cost=1541.00..1541.00 rows=100000 width=8)
              ->  Seq Scan on app_edge  (cost=0.00..1541.00 rows=100000 width=8)

The second ones:

Vertex.objects.filter(edge_orig__dest=v).distinct()

SELECT DISTINCT "app_vertex"."id"
FROM "app_vertex"
INNER JOIN "app_edge" ON ("app_vertex"."id" = "app_edge"."orig_id")
WHERE "app_edge"."dest_id" = 1061

HashAggregate  (cost=1531.42..1531.62 rows=20 width=4)
  Group Key: app_vertex.id
  ->  Hash Join  (cost=848.11..1519.04 rows=4950 width=4)
        Hash Cond: (app_edge.orig_id = app_vertex.id)
        ->  Bitmap Heap Scan on app_edge  (cost=846.65..1449.53 rows=4950 width=4)
              Recheck Cond: (dest_id = 1061)
              ->  Bitmap Index Scan on app_edge_dest_id_4254b90f  (cost=0.00..845.42 rows=4950 width=0)
                    Index Cond: (dest_id = 1061)
        ->  Hash  (cost=1.20..1.20 rows=20 width=4)
              ->  Seq Scan on app_vertex  (cost=0.00..1.20 rows=20 width=4)

@khampson's version also takes a minute-and-a-half to run, so it's also a no-go.

Vertex.objects.raw( ... )

SELECT DISTINCT "app_vertex"."id"
FROM "app_vertex"
JOIN "app_edge" ON ("app_vertex"."id" = "app_edge"."orig_id")
JOIN "app_edge" T4 ON ("app_vertex"."id" = T4."dest_id")
WHERE ("app_edge"."dest_id" = 1061
       OR T4."orig_id" = 1061);

HashAggregate  (cost=8275347.47..8275347.67 rows=20 width=4)
  Group Key: app_vertex.id
  ->  Hash Join  (cost=3183.45..8154343.45 rows=48401608 width=4)
        Hash Cond: (app_vertex.id = app_edge.orig_id)
        Join Filter: ((app_edge.dest_id = 1061) OR (t4.orig_id = 1061))
        ->  Hash Join  (cost=1.45..2917.45 rows=100000 width=12)
              Hash Cond: (t4.dest_id = app_vertex.id)
              ->  Seq Scan on app_edge t4  (cost=0.00..1541.00 rows=100000 width=8)
              ->  Hash  (cost=1.20..1.20 rows=20 width=4)
                    ->  Seq Scan on app_vertex  (cost=0.00..1.20 rows=20 width=4)
        ->  Hash  (cost=1541.00..1541.00 rows=100000 width=8)
              ->  Seq Scan on app_edge  (cost=0.00..1541.00 rows=100000 width=8)

Body:
The query plans for those two queries are radically different. The first (slower) one isn't hitting any indexes, and is doing two left joins, both of which result in way, way more rows being processed and returned. From what I interpret of the intention of the Django ORM syntax, it doesn't sound like you would truly want to do left joins here.

I would recommend considering dropping down into raw SQL in this case from within the Django ORM, and hybridize the two. e.g. if you take the first one, and transform it to something like this:

SELECT DISTINCT "app_vertex"."id"
FROM "app_vertex"
JOIN "app_edge" ON ("app_vertex"."id" = "app_edge"."orig_id")
JOIN "app_edge" T4 ON ("app_vertex"."id" = T4."dest_id")
WHERE ("app_edge"."dest_id" = 1061
       OR T4."orig_id" = 1061);

Two questions there: How does that version perform, and does it give you the results you're looking for?

For more info on raw queries, check out this section of the Django doc.

Response to comment from OP:

The query plan for the query I suggested also shows that it's not hitting any indexes.

Do you have indexes on both tables for the columns involved? I suspect not, especially since for this specific query, we're looking for a single value, which means if there were indexes, I would be very surprised if the query planner determined a sequential scan were a better choice (OTOH, if you were looking for a wide range of rows, say, over 10% of the rows in the tables, the query planner might correctly make such a decision).


答:
If it increased by 2 it would be testing almost everything twice, that wouldn't make any sense. So I assume you mean: how can it get away with not testing every odd number?

This is because every prime p greater than 3 is of the form 6n±1. Proof:
Consider the remainder r = p mod 6. Obviously r must be odd. Notice also that r cannot be 3, because then p would be divisible by 3, making it not a prime. This leaves only the possibilities 1 and 5, which correspond p being of the form 6n+1 or the form 6n-1 respectively.

The effect is that it avoid testing multiples of 3. Dividing by a multiple of 3 is redundant, because we already know that n is not a multiple of 3, so it cannot be the multiple of a multiple of 3 either.

Title: prime numbers algorithm efficiency


问:
Sending an html form email with PHP
When I click my submit button, It pulls up my form-to-email.php source code. This is my first time using any PHP. How do i get it to send the email? It could just be linked incorrectly or formatted incorrectly.

```<code><form method="post" name="myemailform" action="form-to-email.php">
<div>
  <label for="name">Name:</label><br>
 <input type="text" id="name" name="user_name" size="45"><br>
</div>
<div>
  <label for="email">Email:</label><br>
  <input type="text" id="email" name="user_email" size="45"><br>
</div>
<div>
  <label for="message">Message:</label><br>
  <textarea type="text" id="message" name="user_message" size="600"></textarea><br>
</div>
<div>
  <input type = "submit" value = "Send Form">
  <input type = "reset" value = "reset">
</div>
</form>
</code>```

here is my PHP code

```<code><?php
if(isset($_POST['email'])) {

// EDIT THE 2 LINES BELOW AS REQUIRED
$email_to = "codymaheu@yahoo.com";
$email_subject = "Testing";

function died($error) {
    // your error code can go here
    echo "We are very sorry, but there were error(s) found with the form you submitted. ";
    echo "These errors appear below.<br /><br />";
    echo $error."<br /><br />";
    echo "Please go back and fix these errors.<br /><br />";
    die();
}

// validation expected data exists
if(!isset($_POST['user_name']) ||
    !isset($_POST['user_email']) ||
    !isset($_POST['user_message'])) {
    died('We are sorry, but there appears to be a problem with the form you submitted.');
 }

$name = $_POST['user_name']; // required
$email_from = $_POST['user_email']; // required
$comments = $_POST['user_message']; // required

$error_message = "";
$email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';

if(!preg_match($email_exp,$email_from)) {
$error_message .= 'The Email Address you entered does not appear to be valid.<br />';
}

$string_exp = "/^[A-Za-z .'-]+$/";

if(!preg_match($string_exp,$name)) {
$error_message .= 'The First Name you entered does not appear to be valid.<br />';
 }

if(strlen($comments) < 2) {
$error_message .= 'The Message you entered do not appear to be valid.<br />';
}

if(strlen($error_message) > 0) {
died($error_message);
}

$email_message = "Form details below.\n\n";

function clean_string($string) {
  $bad = array("content-type","bcc:","to:","cc:","href");
  return str_replace($bad,"",$string);
}

$email_message .= "First Name: ".clean_string($name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Message: ".clean_string($comments)."\n";

// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();

@mail($email_to, $email_subject, $email_message, $headers);
?>

<!-- include your own success html here -->

Thank you for contacting us. We will be in touch with you very soon.

<?php

}
?>
</code>```

答:
add name into the button like this then try again </p>

```<code><input type = "submit" value = "Send Form" name="email">
</code>```

Title: Sending an html form email with PHP

Body:
When I click my submit button, It pulls up my form-to-email.php source code. This is my first time using any PHP. How do i get it to send the email? It could just be linked incorrectly or formatted incorrectly.

<form method="post" name="myemailform" action="form-to-email.php">

  Name:

 <input type="text" id="name" name="user_name" size="45">

  Email:

  <input type="text" id="email" name="user_email" size="45">

  Message:

  <textarea type="text" id="message" name="user_message" size="600"></textarea>

  <input type = "submit" value = "Send Form">
  <input type = "reset" value = "reset">

</form>

here is my PHP code

<?php
if(isset($_POST['email'])) {

// EDIT THE 2 LINES BELOW AS REQUIRED
$email_to = "codymaheu@yahoo.com";
$email_subject = "Testing";

function died($error) {
    // your error code can go here
    echo "We are very sorry, but there were error(s) found with the form you submitted. ";
    echo "These errors appear below.

";
    echo $error."

";
    echo "Please go back and fix these errors.

";
    die();
}

// validation expected data exists
if(!isset($_POST['user_name']) ||
    !isset($_POST['user_email']) ||
    !isset($_POST['user_message'])) {
    died('We are sorry, but there appears to be a problem with the form you submitted.');
 }

$name = $_POST['user_name']; // required
$email_from = $_POST['user_email']; // required
$comments = $_POST['user_message']; // required

$error_message = "";
$email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';

if(!preg_match($email_exp,$email_from)) {
$error_message .= 'The Email Address you entered does not appear to be valid.
';
}

$string_exp = "/^[A-Za-z .'-]+$/";

if(!preg_match($string_exp,$name)) {
$error_message .= 'The First Name you entered does not appear to be valid.
';
 }

if(strlen($comments) < 2) {
$error_message .= 'The Message you entered do not appear to be valid.
';
}

if(strlen($error_message) > 0) {
died($error_message);
}

$email_message = "Form details below.\n\n";

function clean_string($string) {
  $bad = array("content-type","bcc:","to:","cc:","href");
  return str_replace($bad,"",$string);
}

$email_message .= "First Name: ".clean_string($name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Message: ".clean_string($comments)."\n";

// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();

@mail($email_to, $email_subject, $email_message, $headers);
?>

Thank you for contacting us. We will be in touch with you very soon.

<?php

}
?>

Body:
add name into the button like this then try again

<input type = "submit" value = "Send Form" name="email">


问:
Removing special characters from string in python
I am using beautiful soup to scrape some html/xhtml webpages as follows:

```<code>response = requests.get(url)
soup = BeautifulSoup(response.text)
tables_list = soup.find_all("table")
</code>```

However, my output shows several special characters (e.g. Â â ) which I want to filter out. I think I am missing something with respect to decoding.

Could you please point me to what I might be missing here? Thanks.

答:
If response.text contains your response, and you want to filter out those special characters, what you can do is re-encode your string so as to retain only the ascii characters (and ignore the others) and then decode it again, like this (Python3):

```<code>In [7]: text = '<tag> normal text Â â˙∆¬˚∆ hello ©µµ </tag>'

In [8]: text.encode('ascii', 'ignore').decode('ascii')
Out[8]: '<tag> normal text   hello  </tag>'
</code>```

Do this for response.text, and then you can continue with the rest of your processing.

Body:
I am using beautiful soup to scrape some html/xhtml webpages as follows:

response = requests.get(url)
soup = BeautifulSoup(response.text)
tables_list = soup.find_all("table")

However, my output shows several special characters (e.g. Â â ) which I want to filter out. I think I am missing something with respect to decoding.

Could you please point me to what I might be missing here? Thanks.

Body:
If response.text contains your response, and you want to filter out those special characters, what you can do is re-encode your string so as to retain only the ascii characters (and ignore the others) and then decode it again, like this (Python3):

In [7]: text = '<tag> normal text Â â˙∆¬˚∆ hello ©µµ </tag>'

In [8]: text.encode('ascii', 'ignore').decode('ascii')
Out[8]: '<tag> normal text   hello  </tag>'

Do this for response.text, and then you can continue with the rest of your processing.


问:
IE7 problems with displaying text in TD
I can not figure out why the text inside the TD is not displayed in IE7. I am frustrated to the core cuz it works in FF! All I am trying to do is dynamically build a table onload... Any help will be greatly appreciated.
The complete script is at pastebin </p>

答:
use the insertRow(-1) to add a row instead, and insertCell(-1) to add a column

updated code: http://pastebin.com/mTym410P

Title: IE7 problems with displaying text in TD


问:
Why am I getting this error when attempting to use postgresql as database in RoR?
I am working on starting a new project and I am getting an error I can't resolve after following the error's suggestions. Anybody out there know of any reason why Ruby 2.1.2 should not play well with Rails 4.2.6 when installing postgresql database?
I am getting this type of error:

```<code>Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension.

    /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/ruby extconf.rb
checking for pg_config... no
No pg_config... trying anyway. If building fails, please try again with
 --with-pg-config=/path/to/pg_config
checking for libpq-fe.h... no
Can't find the 'libpq-fe.h header
 extconf.rb failed
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.
</code>```

I checked the logs and it might as well have been in hieroglyphics:

```<code>"gcc -E -I/Users/danale/.rvm/rubies/ruby-2.3.3/include/ruby-2.3.0/x86_64-darwin16 -I/Users/danale/.rvm/rubies/ruby-2.3.3/include/ruby-2.3.0/ruby/backward -I/Users/danale/.rvm/rubies/ruby-2.3.3/include/ruby-2.3.0 -I.  -I/usr/local/opt/libyaml/include -I/usr/local/opt/readline/include -I/usr/local/opt/libksba/include -I/usr/local/opt/openssl/include -I/usr/local/opt/libyaml/include -I/usr/local/opt/readline/include -I/usr/local/opt/libksba/include -I/usr/local/opt/openssl/include -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT    -O3 -fno-fast-math -ggdb3 -Wall -Wextra -Wno-unused-parameter -Wno-parentheses -Wno-long-long -Wno-missing-field-initializers -Wunused-variable -Wpointer-arith -Wwrite-strings -Wdeclaration-after-statement -Wshorten-64-to-32 -Wimplicit-function-declaration -Wdivision-by-zero -Wdeprecated-declarations -Wextra-tokens  -fno-common -pipe  conftest.c -o conftest.i"
conftest.c:3:10: fatal error: 'libpq-fe.h' file not found
#include <libpq-fe.h>
         ^
1 error generated.
checked program was:
/* begin */
1: #include "ruby.h"
2:
3: #include <libpq-fe.h>
/* end */
</code>```

I since changed to Ruby version 2.1.2, hoping it was a compatibility issue, but it did not resolve the error. When I try to follow the suggestions of error:

```<code>Gem files will remain installed in /Users/danale/.rvm/gems/ruby-2.1.2/gems/pg-0.19.0 for inspection.
Results logged to /Users/danale/.rvm/gems/ruby-2.1.2/extensions/x86_64-darwin-16/2.1.0/pg-0.19.0/gem_make.out
danales-MacBook-Pro:Projects danale$ bundle exec spring binstub --all
Could not locate Gemfile or .bundle/ directory
danales-MacBook-Pro:Projects danale$ bundle install
Could not locate Gemfile
</code>```

I get what you see above.

答:
Daniel nailed this in the comments and I don't need credit for it, but if you're a Mac user you need to use:</p>

```<code>brew install postgresql
</code>```

Body:
I am working on starting a new project and I am getting an error I can't resolve after following the error's suggestions. Anybody out there know of any reason why Ruby 2.1.2 should not play well with Rails 4.2.6 when installing postgresql database?
I am getting this type of error:

Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension.

    /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/ruby extconf.rb
checking for pg_config... no
No pg_config... trying anyway. If building fails, please try again with
 --with-pg-config=/path/to/pg_config
checking for libpq-fe.h... no
Can't find the 'libpq-fe.h header
 extconf.rb failed
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

I checked the logs and it might as well have been in hieroglyphics:

"gcc -E -I/Users/danale/.rvm/rubies/ruby-2.3.3/include/ruby-2.3.0/x86_64-darwin16 -I/Users/danale/.rvm/rubies/ruby-2.3.3/include/ruby-2.3.0/ruby/backward -I/Users/danale/.rvm/rubies/ruby-2.3.3/include/ruby-2.3.0 -I.  -I/usr/local/opt/libyaml/include -I/usr/local/opt/readline/include -I/usr/local/opt/libksba/include -I/usr/local/opt/openssl/include -I/usr/local/opt/libyaml/include -I/usr/local/opt/readline/include -I/usr/local/opt/libksba/include -I/usr/local/opt/openssl/include -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT    -O3 -fno-fast-math -ggdb3 -Wall -Wextra -Wno-unused-parameter -Wno-parentheses -Wno-long-long -Wno-missing-field-initializers -Wunused-variable -Wpointer-arith -Wwrite-strings -Wdeclaration-after-statement -Wshorten-64-to-32 -Wimplicit-function-declaration -Wdivision-by-zero -Wdeprecated-declarations -Wextra-tokens  -fno-common -pipe  conftest.c -o conftest.i"
conftest.c:3:10: fatal error: 'libpq-fe.h' file not found
#include <libpq-fe.h>
         ^
1 error generated.
checked program was:
/* begin */
1: #include "ruby.h"
2:
3: #include <libpq-fe.h>
/* end */

I since changed to Ruby version 2.1.2, hoping it was a compatibility issue, but it did not resolve the error. When I try to follow the suggestions of error:

Gem files will remain installed in /Users/danale/.rvm/gems/ruby-2.1.2/gems/pg-0.19.0 for inspection.
Results logged to /Users/danale/.rvm/gems/ruby-2.1.2/extensions/x86_64-darwin-16/2.1.0/pg-0.19.0/gem_make.out
danales-MacBook-Pro:Projects danale$ bundle exec spring binstub --all
Could not locate Gemfile or .bundle/ directory
danales-MacBook-Pro:Projects danale$ bundle install
Could not locate Gemfile

I get what you see above.

Body:
Daniel nailed this in the comments and I don't need credit for it, but if you're a Mac user you need to use:

brew install postgresql


问:
angular 2 sidenav items not displaying as row
hi there I'm trying to display a sidenav with angular 2 with links listed as rows been screatching my head for half a day trying to get it working this is what it looks like:

http://imgur.com/a/Muu2F

and this is my code:

```<code><md-sidenav-container class="sidenav-fab-container" fullscreen>
<md-toolbar>
  <button (click)="sidenav.toggle()">
    <md-icon>add</md-icon>
  </button>
</md-toolbar>

<md-sidenav #sidenav mode="over" opened="false">
  <div>
  <md-list>
    <!--<h3>links:</h3>-->
    <md-list-item>
      <button (click)="sidenav.toggle()">
        <md-icon>add</md-icon>
      </button>
    </md-list-item>
    <md-list-item>
      <md-icon md-list-icon>folder</md-icon>
      <a md-line>hello World</a>
    </md-list-item>
    <md-list-item>
      <md-icon md-list-icon>folder</md-icon>
      <a>hello World</a>
    </md-list-item >
    <md-divider></md-divider>
    <md-list-item>
      <md-icon md-list-icon>folder</md-icon>
      <a>hello World</a>
    </md-list-item>
  </md-list>
  </div>
</md-sidenav>

<main-view-template></main-view-template>
</code>```

```<code>sidenav.ts

import {Component, ViewEncapsulation} from '@angular/core';
import 'hammerjs';

@Component({
  moduleId : module.id,
  selector: 'side-nav-component',
  templateUrl: 'sideNav.component.html',
  encapsulation: ViewEncapsulation.None,
})

export class sideNavComponent{
}
</code>```

any help would be greatly appreciated. can't for the life of me figure it out.

答:
solved it in the end. changed the item type to spans and it displays properly:

```<code><md-list-item>
    <button md-button>
      <md-icon>add</md-icon>
      <span>this is text</span>
    </button>
  </md-list-item>
  <br>
  <md-list-item class="side-nav-container">
    <button md-button>
      <md-icon>add</md-icon>
      <span>this is text</span>
    </button>
  </md-list-item>
  <br>
  <md-list-item>
    <button md-button>
      <md-icon>add</md-icon>
      <span>this is text</span>
    </button>
</code>```

which now displays like this

http://imgur.com/a/lOxEp

thanks for the help!

Body:
hi there I'm trying to display a sidenav with angular 2 with links listed as rows been screatching my head for half a day trying to get it working this is what it looks like:

http://imgur.com/a/Muu2F

and this is my code:

<md-sidenav-container class="sidenav-fab-container" fullscreen>
<md-toolbar>
  <button (click)="sidenav.toggle()">
    <md-icon>add</md-icon>
  </button>
</md-toolbar>

<md-sidenav #sidenav mode="over" opened="false">

  <md-list>

    <md-list-item>
      <button (click)="sidenav.toggle()">
        <md-icon>add</md-icon>
      </button>
    </md-list-item>
    <md-list-item>
      <md-icon md-list-icon>folder</md-icon>
      hello World
    </md-list-item>
    <md-list-item>
      <md-icon md-list-icon>folder</md-icon>
      hello World
    </md-list-item >
    <md-divider></md-divider>
    <md-list-item>
      <md-icon md-list-icon>folder</md-icon>
      hello World
    </md-list-item>
  </md-list>

</md-sidenav>

sidenav.ts

import {Component, ViewEncapsulation} from '@angular/core';
import 'hammerjs';

@Component({
  moduleId : module.id,
  selector: 'side-nav-component',
  templateUrl: 'sideNav.component.html',
  encapsulation: ViewEncapsulation.None,
})

export class sideNavComponent{
}

any help would be greatly appreciated. can't for the life of me figure it out.

Body:
solved it in the end. changed the item type to spans and it displays properly:

<md-list-item>
    <button md-button>
      <md-icon>add</md-icon>
      <span>this is text</span>
    </button>
  </md-list-item>
  <br>
  <md-list-item class="side-nav-container">
    <button md-button>
      <md-icon>add</md-icon>
      <span>this is text</span>
    </button>
  </md-list-item>
  <br>
  <md-list-item>
    <button md-button>
      <md-icon>add</md-icon>
      <span>this is text</span>
    </button>

which now displays like this

http://imgur.com/a/lOxEp

thanks for the help!


问:
How paging in Linux distinguishes pages from page frames?
The book Understanding the Linux Kernel, 3rd Edition
By Daniel P. Bovet, Marco Cesati
talks about advantages of Paging in Chapter 2 Memory Addressing.

Here it says one of the advantages is,

Distinguish pages (groups of data) from page frames (physical addresses in main memory). This allows the same page to be stored in a page frame, then saved to disk and later reloaded in a different page frame. This is the basic ingredient of the virtual memory mechanism.

I am unable to fully understand this. Does it mean that the when a swapped page is loaded back in the Physical memory, its virtual address remains the same but the Physical address changes?

答:
A process address space is organized into logical pages. A logical page may be mapped to a physical page frame.

Does it mean that the when a swapped page is loaded back in the Physical memory, its virtual address remains the same but the Physical address changes?

It means a lot more than that. However, yes, a logical page may be mapped to different physical page frames over time.


问:
How to take a datetime.time object in UT and convert to local time given a longitude
I need to convert a time in UT combined with a longitude into local time. I am working on analyzing a future Earth observing satellite mission and need to do this conversion to continue.

I found a general solution to this problem here: T(lt) = T(ut) + lon/(360/24), however implementing it is driving me absolutely bonkers.

My data are datetime time objects:

```<code>In[9]: sattime[0]
Out[9]: datetime.time(18, 0)
</code>```

and longitude coordinates from 0 to 360 degrees.

I need to take this object and use the above equation to convert to a local time. I ONLY care about the time relative to midnight and NOT about the date (in fact the rest of my code is currently using the datetime.time object only and preferably the local time output would be the same type of object).

I have tried the following from here but am stuck getting the local variable back into a time object.

```<code>test = 4
for (i,j) in zip(sattime, satloncor):
    td = datetime.datetime.combine(datetime.datetime.min, i) - datetime.datetime.min
    seconds = td  // datetime.timedelta(milliseconds=1)
    local = (seconds + (j/(360/86400)))/1000
    print (local)
    if test<0:
        break
    test-=1
</code>```

The test part of the code just makes sure I am not wasting time doing the conversion for all ~400,000 data points.

So to summarize, I want to take a datetime.time object in UT coupled with a corresponding longitude, and convert it to local solar time as a datetime.time object.

This all seems super convoluted and seems like there should be an easier way. Any help is greatly appreciated! Thanks!

答:
Sorry, but it is super convoluted because it's a complicated subject. For just one example, did you know that every few years there is a day with 86401 seconds in it?

A couple of good web sites to start with:

http://www.ephemeris.com/books.html

I can recommend the "Practical Astronomy with your Calculator" book.

https://www.timeanddate.com/

Hope this helps.

Body:
I need to convert a time in UT combined with a longitude into local time. I am working on analyzing a future Earth observing satellite mission and need to do this conversion to continue.

I found a general solution to this problem here: T(lt) = T(ut) + lon/(360/24), however implementing it is driving me absolutely bonkers.

My data are datetime time objects:

In[9]: sattime[0]
Out[9]: datetime.time(18, 0)

and longitude coordinates from 0 to 360 degrees.

I need to take this object and use the above equation to convert to a local time. I ONLY care about the time relative to midnight and NOT about the date (in fact the rest of my code is currently using the datetime.time object only and preferably the local time output would be the same type of object).

I have tried the following from here but am stuck getting the local variable back into a time object.

test = 4
for (i,j) in zip(sattime, satloncor):
    td = datetime.datetime.combine(datetime.datetime.min, i) - datetime.datetime.min
    seconds = td  // datetime.timedelta(milliseconds=1)
    local = (seconds + (j/(360/86400)))/1000
    print (local)
    if test<0:
        break
    test-=1

The test part of the code just makes sure I am not wasting time doing the conversion for all ~400,000 data points.

So to summarize, I want to take a datetime.time object in UT coupled with a corresponding longitude, and convert it to local solar time as a datetime.time object.

This all seems super convoluted and seems like there should be an easier way. Any help is greatly appreciated! Thanks!


问:
Is it possible to change the package being used at runtime?
I have a large application that I am working to expand upon to allow customized usage by other departments within my organization.

Each department has different needs but may share some of the same classes as-is but other must be modified to accommodate the department's specific needs.

What I am wanting to do is create a new package for each department and move the relevant classes under those packages, thus keeping them separated, but all contained within the same overall application.

Right now, my package structure is similar to this:

```<code>[src]
    - Main.java
    [view]
        - D1 FXMLs
    [controllers]
        - D1 Controllers
    [model]
        -D1 Classes
</code>```

What I am hoping to do is restructure the project to include additional departments, many using the same class names as D1 (department 1).

```<code>[src]
    - Main.java
    [D1]
        [view]
            - D1 FXMLs
        [controllers]
            - D1 Controllers
        [model]
            -D1 Classes
    [D2]
        [view]
            - D2 FXMLs
        [controllers]
            - D2 Controllers
        [model]
            - D2 Classes
...etc
</code>```

I would need my Main.java to determine which package the operate out of, based on the value of a variable at runtime.

Is this even possible or would I still need to create entirely separate projects for each department and have a "Loader" program determine which one to run?

EDIT: Perhaps I have just stumbled on the answer myself. Would it work to just have Main.java call a class within the D1 or D2 package and have that class properly assign the packages going forward?

答:
While possibly not the most elegant solution, I used a simple approach (as my skill is not yet to the point where I understand Factories).

I just implemented what my edit to the question suggested, calling a different package's RootLayoutController depending on which package was needed.

Body:
I have a large application that I am working to expand upon to allow customized usage by other departments within my organization.

Each department has different needs but may share some of the same classes as-is but other must be modified to accommodate the department's specific needs.

What I am wanting to do is create a new package for each department and move the relevant classes under those packages, thus keeping them separated, but all contained within the same overall application.

Right now, my package structure is similar to this:

[src]
    - Main.java
    [view]
        - D1 FXMLs
    [controllers]
        - D1 Controllers
    [model]
        -D1 Classes

What I am hoping to do is restructure the project to include additional departments, many using the same class names as D1 (department 1).

[src]
    - Main.java
    [D1]
        [view]
            - D1 FXMLs
        [controllers]
            - D1 Controllers
        [model]
            -D1 Classes
    [D2]
        [view]
            - D2 FXMLs
        [controllers]
            - D2 Controllers
        [model]
            - D2 Classes
...etc

I would need my Main.java to determine which package the operate out of, based on the value of a variable at runtime.

Is this even possible or would I still need to create entirely separate projects for each department and have a "Loader" program determine which one to run?

EDIT: Perhaps I have just stumbled on the answer myself. Would it work to just have Main.java call a class within the D1 or D2 package and have that class properly assign the packages going forward?


问:
Defining the directory to save outputs in Python for text files
I would like to save my outputs (which are text files) from a Python script to a different directory. Following is my code to define the directory for my  outputs:

```<code>headers = list(uniq)
output_headers = open(save_path, "headers_dash1" + "_" + str(count) + ".raw", "w")
for item in headers:
    output_headers.write("%s\n" % item)
</code>```

How can I generate these outputs to a different fixed directory like:
D:\Test\"The file name"

答:
You can use os.path.join(path, filename) to create the desired path.

os.path.join('path/to','file.jpg')

Body:
I would like to save my outputs (which are text files) from a Python script to a different directory. Following is my code to define the directory for my  outputs:

headers = list(uniq)
output_headers = open(save_path, "headers_dash1" + "_" + str(count) + ".raw", "w")
for item in headers:
    output_headers.write("%s\n" % item)

How can I generate these outputs to a different fixed directory like:
D:\Test\"The file name"


问:
duplicate entries on datagridview
I'd like to find duplicated entries one of the columns on datagridview. After that I need to send an email to users for arrange collection for those duplicated numbers. It doesnt matter how many duplicated numbers we have on column so i dont want to count them, i just need to know all those duplicated numbers itself on column.. I have sorted e-mail already, but i couldnt figure out how i can easily find duplicated entries.

attached a screen shot here, for example on this screen shot i already have four 0's on column, it needs to tell me that " I have duplicated 0 on sending_location" .

Datagridview taking information from MS Access Datasource.

I am using visual studio.

Many thanks!
Charlie

答:
If you are using EntityFramework

```<code>//resultset is the result from the query that return all data
var duplicates = resultset
                     .GroupBy(i => i.ColumnName)
                     .Where(x => x.Count() > 1)
                     .Select();
</code>```

if using datatable

```<code>DataTable dt = new DataTable();
        dt.Columns.Add("Id", typeof(int));
        dt.Columns.Add("Name", typeof(string));
        dt.Columns.Add("City", typeof(string));

        //populate table
        dt.Rows.Add(1, "David", "New York");
        dt.Rows.Add(2, "Emma","Albany");
        dt.Rows.Add(3, "Michael", "Chicago");
        dt.Rows.Add(4, "Jennifer", "Chicago");
        dt.Rows.Add(5, "Steve", "Albany");

        var duplicates = dt.AsEnumerable()
                       .GroupBy(r => r.Field<string>("City"))
                       .Select(g => g.First())
                       .CopyToDataTable();
</code>```

duplicates will have unique duplicated rows

Title: duplicate entries on datagridview

Body:
If you are using EntityFramework

//resultset is the result from the query that return all data
var duplicates = resultset
                     .GroupBy(i => i.ColumnName)
                     .Where(x => x.Count() > 1)
                     .Select();

if using datatable

DataTable dt = new DataTable();
        dt.Columns.Add("Id", typeof(int));
        dt.Columns.Add("Name", typeof(string));
        dt.Columns.Add("City", typeof(string));

        //populate table
        dt.Rows.Add(1, "David", "New York");
        dt.Rows.Add(2, "Emma","Albany");
        dt.Rows.Add(3, "Michael", "Chicago");
        dt.Rows.Add(4, "Jennifer", "Chicago");
        dt.Rows.Add(5, "Steve", "Albany");

        var duplicates = dt.AsEnumerable()
                       .GroupBy(r => r.Field<string>("City"))
                       .Select(g => g.First())
                       .CopyToDataTable();

duplicates will have unique duplicated rows