问:
Create a dataframe from a hashmap with keys as column names and values as rows in Spark
I have a dataframe and I have a column which is a map in dataframe like this -

```<code>scala> df.printSchema
</code>```

root
 |-- A1: map (nullable = true)
 |    |-- key: string
 |    |-- value: string (valueContainsNull = true)
```

<p>I need to select all the keys from dataframe as column name and values as rows.</p>

<p>For eg:
Let say I have 2 records like this-</p>

<pre class="lang-none prettyprint-override"><code>1. key1 -> value1, key2 -> value2, key3 -> value3 ....
2. key1 -> value11, key3 -> value13, key4 -> value14 ...
</code>```

I want the output dataframe as

key1             key2                 key3             key4
value1           value2               value3            null
value11          null                 value13           value14
```

How can I do this?

答:
Assuming that column with the Map is named "my_map"

Get set of unique keys (skip this step if you already has the keys beforehand):

```<code>val keys = df
  .select(explode(expr("map_keys(my_map)")).as("keys_to_rows"))
  .agg(collect_set("keys_to_rows"))
  .collect()
  .head.getSeq[String](0)
</code>```

Select map values by keys as a columns:

```<code>df.select(
  keys.map(key => col(s"B.$key").as(key)): _*
)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a dataframe and I have a column which is a map in dataframe like this -

scala> df.printSchema

root
 |-- A1: map (nullable = true)
 |    |-- key: string
 |    |-- value: string (valueContainsNull = true)

I need to select all the keys from dataframe as column name and values as rows.

For eg:
Let say I have 2 records like this-

1. key1 -> value1, key2 -> value2, key3 -> value3 ....
2. key1 -> value11, key3 -> value13, key4 -> value14 ...

I want the output dataframe as

key1             key2                 key3             key4
value1           value2               value3            null
value11          null                 value13           value14

How can I do this?

Body:
Assuming that column with the Map is named "my_map"

Get set of unique keys (skip this step if you already has the keys beforehand):

val keys = df
  .select(explode(expr("map_keys(my_map)")).as("keys_to_rows"))
  .agg(collect_set("keys_to_rows"))
  .collect()
  .head.getSeq[String](0)

Select map values by keys as a columns:

df.select(
  keys.map(key => col(s"B.$key").as(key)): _*
)


来源: stackexchange

问:
calculate method execution time in Visual Studio Express (No profiler available)?
I am using Visual Studio Express Edition and it don't have any profiler or code analyzer.

Code having two delegate performing same task, one by using anonymous method and one by Lambda expression. I want to compare which one is taking less time.

How can I do this in VS express? (not only for delegate for methods also)

If it is Duplicate, please link it.

Thanks

I tried Like This:

```<code>        /** Start Date time**/
        DateTime startTime = DateTime.Now;
        /********do the square of a number by using LAMBDA EXPRESSIONS********/
        returnSqr myDel = x => x * x;
        Console.WriteLine("By Lambda Expression Square of {0} is: {1}", a,myDel(a));
        /** Stop Date time**/
        DateTime stopTime = DateTime.Now;
        TimeSpan duration = stopTime - startTime;
        Console.WriteLine("Execution time 1:" + duration.Milliseconds);

        /** Start Date time**/
        DateTime startTime2 = DateTime.Now;
        /*****do the square of a number by using ANONYMOUS EXPRESSIONS********/
        returnSqr myDel1 = delegate(int x) { return x * x;};
        Console.WriteLine("By Anonymous Method Square of  {0} is: {1}", a, myDel1(a));
        /** Stop Date time**/
        DateTime stopTime2 = DateTime.Now;
        TimeSpan duration2 = stopTime2 - startTime2;
        Console.WriteLine("Execution Time 2:" + duration.Milliseconds);
</code>```

Output gives:

Execution time 1 : 0

Execution time 2 : 0

Why like this?

答:
You can use the stopwatch class.</p>

```<code>Stopwatch sw = Stopwatch.StartNew();
// rest of the code
sw.Stop();
Console.WriteLine("Total time (ms): {0}", (long) sw.ElapsedMilliseconds);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am using Visual Studio Express Edition and it don't have any profiler or code analyzer.

Code having two delegate performing same task, one by using anonymous method and one by Lambda expression. I want to compare which one is taking less time.

How can I do this in VS express? (not only for delegate for methods also)

If it is Duplicate, please link it.

Thanks

I tried Like This:

        /** Start Date time**/
        DateTime startTime = DateTime.Now;
        /********do the square of a number by using LAMBDA EXPRESSIONS********/
        returnSqr myDel = x => x * x;
        Console.WriteLine("By Lambda Expression Square of {0} is: {1}", a,myDel(a));
        /** Stop Date time**/
        DateTime stopTime = DateTime.Now;
        TimeSpan duration = stopTime - startTime;
        Console.WriteLine("Execution time 1:" + duration.Milliseconds);

        /** Start Date time**/
        DateTime startTime2 = DateTime.Now;
        /*****do the square of a number by using ANONYMOUS EXPRESSIONS********/
        returnSqr myDel1 = delegate(int x) { return x * x;};
        Console.WriteLine("By Anonymous Method Square of  {0} is: {1}", a, myDel1(a));
        /** Stop Date time**/
        DateTime stopTime2 = DateTime.Now;
        TimeSpan duration2 = stopTime2 - startTime2;
        Console.WriteLine("Execution Time 2:" + duration.Milliseconds);

Output gives:

Execution time 1 : 0

Execution time 2 : 0

Why like this?

Body:
You can use the stopwatch class.

Stopwatch sw = Stopwatch.StartNew();
// rest of the code
sw.Stop();
Console.WriteLine("Total time (ms): {0}", (long) sw.ElapsedMilliseconds);


问:
React CDN based page not working with Babel 6.1.19
The following React code works when the Babel-Core CDN is changed to version 5.8.24 but not when the version is 6.1.19 as included. I am heavily confused as to why this would matter? Shouldn't things be forward-compatible? Or am I just missing something really obvious here?

Thanks in advance.

```<code><html>
<head>
    <script src="https://unpkg.com/react@15/dist/react.min.js">
</script>
    <script src="https://unpkg.com/react-dom@15/dist/react-dom.min.js">
</script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-
core/6.1.19/browser.min.js"></script>
</head>
<body>
    <div id="app"></div>
    <script type="text/babel">
        const HelloMessage = React.createClass({
            render: function() {
                return <div>Hello {this.props.name}</div>;
            }
        });

        ReactDOM.render(<HelloMessage name="John" />,
document.getElementById('app'));
    </script>
</body>
</html>
</code>```

答:
Use this script:

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.js"></script>
</code>```

Check the babel-standalone DOC.

Check the working code:

<!DOCTYPE html>

```

ContentLicense: CC BY-SA 3.0

Body:
Use this script:

<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.js"></script>

Check the babel-standalone DOC.

Check the working code:

<!DOCTYPE html>
<html>
    <head>
       <script src="https://unpkg.com/react@15/dist/react.min.js"></script>
       <script src="https://unpkg.com/react-dom@15/dist/react-dom.min.js"></script>
       <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.js"></script>
    </head>
    <body>
       <div id="app"></div>
           <script type="text/babel">
              const HelloMessage = React.createClass({
                 render: function() {
                     return <div>Hello {this.props.name}</div>;
                 }
              });

              ReactDOM.render(<HelloMessage name="John" />,
                  document.getElementById('app'));
          </script>
    </body>
</html>


问:
label constraints not working
```<code>class videoCell:UICollectionViewCell
{
    override init(frame: CGRect) {
    super.init(frame: frame)
        setUpViews()

    }
   let titlelabel : UILabel =
        {
            var label = UILabel()
        label.backgroundColor = UIColor.brown
        label.translatesAutoresizingMaskIntoConstraints = false
            return label
        }()

    func setUpViews()
    {

        addSubview(titlelabel)

        addConstraint(NSLayoutConstraint(item: titlelabel, attribute:.top, relatedBy: .equal, toItem: thumbNailImageView, attribute: .bottom, multiplier: 1, constant: 8))
        addConstraint(NSLayoutConstraint(item: titlelabel, attribute:.left, relatedBy: .equal, toItem: thumbNailImageView, attribute: .right, multiplier: 1, constant: 8))
        addConstraint(NSLayoutConstraint(item: titlelabel, attribute: .right, relatedBy: .equal, toItem: thumbNailImageView, attribute: .right, multiplier: 1, constant: 0))

        addConstraintsWithFormat(format: "V:[v0(20)]", views:titlelabel)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension UIView
{

    func addConstraintsWithFormat(format:String,views:UIView...)
    {
        var allViews = [String:UIView]()
        for data in 0...views.count-1
        {
            let key = "v\(data)"
            allViews[key] = views[data]
        }
        addConstraints(NSLayoutConstraint.constraints(withVisualFormat: format, options: NSLayoutFormatOptions(), metrics: nil, views: allViews))

    }

}
</code>```

My above function setUpViews() is not rendering my label on view.Can anyone help me out here. I am not getting any error it compiles fine but no output.

Is there any issue with addConstraints method.??

please help thanks.

It works if I add this constraint-:

```<code>addConstraintsWithFormat(format: "H:|[v0]|", views:titlelabel)
</code>```

And comment this line of code-:

```<code>addConstraint(NSLayoutConstraint(item: titlelabel, attribute:.left, relatedBy: .equal, toItem: thumbNailImageView, attribute: .right, multiplier: 1, constant: 8))
        addConstraint(NSLayoutConstraint(item: titlelabel, attribute: .right, relatedBy: .equal, toItem: thumbNailImageView, attribute: .right, multiplier: 1, constant: 0))
</code>```

But that doesn't pin my view where I need to and how I want it to work .

答:
Ok solved it like this-:

```<code>addConstraint(NSLayoutConstraint(item: titlelabel, attribute: .top, relatedBy: .equal, toItem: thumbNailImageView, attribute: .bottom, multiplier: 1.0, constant: 8))
        addConstraint(NSLayoutConstraint(item: titlelabel, attribute: .leading, relatedBy: .equal, toItem: thumbNailImageView, attribute: .leading, multiplier: 4.0, constant: 8))
        addConstraint(NSLayoutConstraint(item: titlelabel, attribute: .trailing, relatedBy: .equal, toItem: thumbNailImageView, attribute: .trailing, multiplier: 1.0, constant: 0))
        addConstraint(NSLayoutConstraint(item: titlelabel, attribute: .height, relatedBy: .equal, toItem: self, attribute: .height, multiplier: 0, constant: 20))
</code>```

But can anyone explain me how this works in detail. This is googled out answer.

Title: label constraints not working

Body:
class videoCell:UICollectionViewCell
{
    override init(frame: CGRect) {
    super.init(frame: frame)
        setUpViews()

    }
   let titlelabel : UILabel =
        {
            var label = UILabel()
        label.backgroundColor = UIColor.brown
        label.translatesAutoresizingMaskIntoConstraints = false
            return label
        }()

    func setUpViews()
    {

        addSubview(titlelabel)

        addConstraint(NSLayoutConstraint(item: titlelabel, attribute:.top, relatedBy: .equal, toItem: thumbNailImageView, attribute: .bottom, multiplier: 1, constant: 8))
        addConstraint(NSLayoutConstraint(item: titlelabel, attribute:.left, relatedBy: .equal, toItem: thumbNailImageView, attribute: .right, multiplier: 1, constant: 8))
        addConstraint(NSLayoutConstraint(item: titlelabel, attribute: .right, relatedBy: .equal, toItem: thumbNailImageView, attribute: .right, multiplier: 1, constant: 0))

        addConstraintsWithFormat(format: "V:[v0(20)]", views:titlelabel)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension UIView
{

    func addConstraintsWithFormat(format:String,views:UIView...)
    {
        var allViews = [String:UIView]()
        for data in 0...views.count-1
        {
            let key = "v\(data)"
            allViews[key] = views[data]
        }
        addConstraints(NSLayoutConstraint.constraints(withVisualFormat: format, options: NSLayoutFormatOptions(), metrics: nil, views: allViews))

    }

}

My above function setUpViews() is not rendering my label on view.Can anyone help me out here. I am not getting any error it compiles fine but no output.

Is there any issue with addConstraints method.??

please help thanks.

It works if I add this constraint-:

addConstraintsWithFormat(format: "H:|[v0]|", views:titlelabel)

And comment this line of code-:

addConstraint(NSLayoutConstraint(item: titlelabel, attribute:.left, relatedBy: .equal, toItem: thumbNailImageView, attribute: .right, multiplier: 1, constant: 8))
        addConstraint(NSLayoutConstraint(item: titlelabel, attribute: .right, relatedBy: .equal, toItem: thumbNailImageView, attribute: .right, multiplier: 1, constant: 0))

But that doesn't pin my view where I need to and how I want it to work .

Body:
Ok solved it like this-:

addConstraint(NSLayoutConstraint(item: titlelabel, attribute: .top, relatedBy: .equal, toItem: thumbNailImageView, attribute: .bottom, multiplier: 1.0, constant: 8))
        addConstraint(NSLayoutConstraint(item: titlelabel, attribute: .leading, relatedBy: .equal, toItem: thumbNailImageView, attribute: .leading, multiplier: 4.0, constant: 8))
        addConstraint(NSLayoutConstraint(item: titlelabel, attribute: .trailing, relatedBy: .equal, toItem: thumbNailImageView, attribute: .trailing, multiplier: 1.0, constant: 0))
        addConstraint(NSLayoutConstraint(item: titlelabel, attribute: .height, relatedBy: .equal, toItem: self, attribute: .height, multiplier: 0, constant: 20))

But can anyone explain me how this works in detail. This is googled out answer.


问:
using c# linq to populate/load a list one time to enhance performance
I'm working on an ASP.NET MVC 4.5 application. I need to populate a list in a dropdown. I t works fine, anyhow, when I click the field there is allways a server request.

I'd like to store the values after the initial load on the client side to speed up the application.

I'm using a ViewModel to populate the list in my Razor View.

Do you know how to achieve an initial load of the this?

Here is my DataSource Controller:

```<code>public JsonResult GetBusinessLineList(string id = null, string query = null)
{

    return
        Json(Db.BusinessLine.AsQueryable()
            .Where(x => x.Label.Contains(query))
            .Take(10)
            .Select(x => new { id = x.BusinessLineId, text = x.Label })
            .ToList(),
            JsonRequestBehavior.AllowGet);
}
</code>```

The Razor View:

```<code><div class="form-group">
    @Html.LabelFor(model => model.BusinessLineIdList, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.Select2AjaxFor(model => model.BusinessLineIdList, @Url.Action("GetBusinessLineList", "DataSource"),
               new { @class = "form-control"))

    </div>
</div>
</code>```

Many thanks and kind regards!

答:
You can try to use output cache:

```<code>[OutputCache(Location = OutputCacheLocation.Client, VaryByParam = "id;query", Duration = 3600)]
public JsonResult GetBusinessLineList(string id = null, string query = null)
{
    return Json(Db.BusinessLine.AsQueryable()
        .Where(x => x.Label.Contains(query))
        .Take(10)
        .Select(x => new { id = x.BusinessLineId, text = x.Label })
        .ToList(),
        JsonRequestBehavior.AllowGet);
}
</code>```

OutputCacheLocation.Client - Specifies that you want to cache the results on client only. There are other options available.

VaryByParam = "id;query" - Is needed to differ cache results based on method arguments.

Duration - cache duration in seconds.

Body:
I'm working on an ASP.NET MVC 4.5 application. I need to populate a list in a dropdown. I t works fine, anyhow, when I click the field there is allways a server request.

I'd like to store the values after the initial load on the client side to speed up the application.

I'm using a ViewModel to populate the list in my Razor View.

Do you know how to achieve an initial load of the this?

Here is my DataSource Controller:

public JsonResult GetBusinessLineList(string id = null, string query = null)
{

    return
        Json(Db.BusinessLine.AsQueryable()
            .Where(x => x.Label.Contains(query))
            .Take(10)
            .Select(x => new { id = x.BusinessLineId, text = x.Label })
            .ToList(),
            JsonRequestBehavior.AllowGet);
}

The Razor View:

    @Html.LabelFor(model => model.BusinessLineIdList, htmlAttributes: new { @class = "control-label col-md-2" })

        @Html.Select2AjaxFor(model => model.BusinessLineIdList, @Url.Action("GetBusinessLineList", "DataSource"),
               new { @class = "form-control"))

Many thanks and kind regards!

Body:
You can try to use output cache:

[OutputCache(Location = OutputCacheLocation.Client, VaryByParam = "id;query", Duration = 3600)]
public JsonResult GetBusinessLineList(string id = null, string query = null)
{
    return Json(Db.BusinessLine.AsQueryable()
        .Where(x => x.Label.Contains(query))
        .Take(10)
        .Select(x => new { id = x.BusinessLineId, text = x.Label })
        .ToList(),
        JsonRequestBehavior.AllowGet);
}

OutputCacheLocation.Client - Specifies that you want to cache the results on client only. There are other options available.

VaryByParam = "id;query" - Is needed to differ cache results based on method arguments.

Duration - cache duration in seconds.


问:
Extract 'p' data from 'div' with Class of div = ""
I am trying to extract the data in the div with "" as className followed by p tag.
My html looks like this

```<code><div class=""><p>I've been with USAA since 1981 - they've been a good, helpful company and easy to deal with except with making payments on their website. Every time I try to make a payment the website has a problem and I end up calling them. Today, I tried to make a credit card update (same account, different exp. date and code) before I made a payment. The website kept telling me it wouldn't accept the information.</p><p>I called the company to make the payment and was told the system had accepted the information but I couldn't make the payment until tomorrow because of the update. They refused to let me make my payment by phone. 4 times in the past 2 years it wouldn't accept my password, even after I confirmed it by - yes calling in. Other payments have not been accepted for unknown reasons - I've had to call them in. No point having a website if it doesn't work. I avoid calling because it takes so many steps to reach a live person. It's a minor complaint but it happens every time.</p></div></div>
</code>```

I am using Beautifulsoup and my code to extarct this data is :

```<code>reviewAllList = [row.text for row in soup.find_all('div',attrs={"class" : ""})]
</code>```

However, I am not able to extarct the correct data from the same. Is it that I am missing something? I am using Python 3.5.

答:
You can just print the text only by saying.

```<code>sometxt = <div class=""><p>I've been with USAA since 1981 - they've been a good, helpful company and easy to deal with except with making payments on their website. Every time I try to make a payment the website has a problem and I end up calling them. Today, I tried to make a credit card update (same account, different exp. date and code) before I made a payment. The website kept telling me it wouldn't accept the information.</p><p>I called the company to make the payment and was told the system had accepted the information but I couldn't make the payment until tomorrow because of the update. They refused to let me make my payment by phone. 4 times in the past 2 years it wouldn't accept my password, even after I confirmed it by - yes calling in. Other payments have not been accepted for unknown reasons - I've had to call them in. No point having a website if it doesn't work. I avoid calling because it takes so many steps to reach a live person. It's a minor complaint but it happens every time.</p></div></div>
</code>```

and now just print(sometxt.text)
if you're only looking for the div class= > "" <
You can print it by print(sometxt['class']) remember that you might have to itterate through your findAll with a for loop to do this.(if there's multiple class)

```<code>**row.text**
</code>```

Body:
I am trying to extract the data in the div with "" as className followed by p tag.
My html looks like this

I've been with USAA since 1981 - they've been a good, helpful company and easy to deal with except with making payments on their website. Every time I try to make a payment the website has a problem and I end up calling them. Today, I tried to make a credit card update (same account, different exp. date and code) before I made a payment. The website kept telling me it wouldn't accept the information.

I called the company to make the payment and was told the system had accepted the information but I couldn't make the payment until tomorrow because of the update. They refused to let me make my payment by phone. 4 times in the past 2 years it wouldn't accept my password, even after I confirmed it by - yes calling in. Other payments have not been accepted for unknown reasons - I've had to call them in. No point having a website if it doesn't work. I avoid calling because it takes so many steps to reach a live person. It's a minor complaint but it happens every time.

I am using Beautifulsoup and my code to extarct this data is :

reviewAllList = [row.text for row in soup.find_all('div',attrs={"class" : ""})]

However, I am not able to extarct the correct data from the same. Is it that I am missing something? I am using Python 3.5.

Body:
You can just print the text only by saying.

sometxt = <div class=""><p>I've been with USAA since 1981 - they've been a good, helpful company and easy to deal with except with making payments on their website. Every time I try to make a payment the website has a problem and I end up calling them. Today, I tried to make a credit card update (same account, different exp. date and code) before I made a payment. The website kept telling me it wouldn't accept the information.</p><p>I called the company to make the payment and was told the system had accepted the information but I couldn't make the payment until tomorrow because of the update. They refused to let me make my payment by phone. 4 times in the past 2 years it wouldn't accept my password, even after I confirmed it by - yes calling in. Other payments have not been accepted for unknown reasons - I've had to call them in. No point having a website if it doesn't work. I avoid calling because it takes so many steps to reach a live person. It's a minor complaint but it happens every time.</p></div></div>

and now just print(sometxt.text)
if you're only looking for the div class= > "" <
You can print it by print(sometxt['class']) remember that you might have to itterate through your findAll with a for loop to do this.(if there's multiple class)

**row.text**


问:
Multiple threads accessing a collection
I have the following scenario.

I have a queue that I receive messages from. When a message comes in a new thread is created to deal with it.

This thread takes the message and adds it to a collection. It then checks if the collection contains 100 items and if it does it sends them elsewhere and clears the collection.

I can't use a regular list because I get collection is modified, enumeration can't continue errors. So I need to use a thread safe collection.

My worry here though is, one thread writes to it and its the 100th item, while it's sending them off elsewhere another thread adds to the collection. Making it 101 items, the thread that triggered the 100th then clears it and I lose an item.

I can't use a concurrent bag, because it has no clear, I can't iterate the bag and remove 1 by 1 as messages might be coming in and being added quicker than it can remove and it will never end.

ConcurrentStack has a clear, but would that work in this scenario?

Some code to demonstrate what I mean, HandleMeasurementMessage happens on a new thread for each message.

```<code>private static readonly ConcurrentStack<EventHubDatum> EventHubDataBatch = new ConcurrentStack<EventHubDatum>();

private static void HandleMeasurementMessage(IMessage<MessageEnvelope> msg)
{
    /* Do a bunch of stuff to msg */

   EventHubDataBatch.Push(eventHubDatum);

   if(EventHubDataBatch.Count == 100)
   {
      /* Send them off*/
      EventHubDatabatch.Clear();
   }
}
</code>```

Wierdly, the problem with the enumeration being modified only occurs if I'm not running it via the debugger in VS2015. The program runs for an hour or so just fine. If I turn off the debugger, I get these enumeration errors which is why I'm trying to switch to a threadsafe collection. I'm just not sure which one is appropriate.

Code that calls HandleMeasurementMessage

```<code>_busSingle.Consume<MessageEnvelope>(_queueMeasurement, (msg, MessageReceivedInfo) => Task.Factory.StartNew(() =>
            {
                try
                {
                    HandleMeasurementMessage(msg);
                }
                catch (Exception ex)
                {
                    /* Logging stuff*/
                }
            }));
</code>```

答:
I would just use simple lock like this:

```<code>private static readonly List<EventHubDatum> EventHubDataBatch = new List<EventHubDatum>();
private static void HandleMeasurementMessage(IMessage<MessageEnvelope> msg)
{
    /* Do a bunch of stuff to msg */

    EventHubDatum[] toSend = null;
    lock (EventHubDataBatch) {
        EventHubDataBatch.Add(eventHubDatum);

        if (EventHubDataBatch.Count == 100) {
            // copy to local
            toSend = EventHubDataBatch.ToArray();
            EventHubDataBatch.Clear();
        }
    }

    if (toSend != null) {
        /* Send them off*/
    }
}
</code>```

Locking here is very brief so it should not affect perfomance in your case in any noticeable way. Note that if there are 100 items - we copy them to local array and clear source list to not hold the lock for the duration of "send them off" operation, which potentially might take long time.

Title: Multiple threads accessing a collection

Body:
I have the following scenario.

I have a queue that I receive messages from. When a message comes in a new thread is created to deal with it.

This thread takes the message and adds it to a collection. It then checks if the collection contains 100 items and if it does it sends them elsewhere and clears the collection.

I can't use a regular list because I get collection is modified, enumeration can't continue errors. So I need to use a thread safe collection.

My worry here though is, one thread writes to it and its the 100th item, while it's sending them off elsewhere another thread adds to the collection. Making it 101 items, the thread that triggered the 100th then clears it and I lose an item.

I can't use a concurrent bag, because it has no clear, I can't iterate the bag and remove 1 by 1 as messages might be coming in and being added quicker than it can remove and it will never end.

ConcurrentStack has a clear, but would that work in this scenario?

Some code to demonstrate what I mean, HandleMeasurementMessage happens on a new thread for each message.

private static readonly ConcurrentStack<EventHubDatum> EventHubDataBatch = new ConcurrentStack<EventHubDatum>();

private static void HandleMeasurementMessage(IMessage<MessageEnvelope> msg)
{
    /* Do a bunch of stuff to msg */

   EventHubDataBatch.Push(eventHubDatum);

   if(EventHubDataBatch.Count == 100)
   {
      /* Send them off*/
      EventHubDatabatch.Clear();
   }
}

Wierdly, the problem with the enumeration being modified only occurs if I'm not running it via the debugger in VS2015. The program runs for an hour or so just fine. If I turn off the debugger, I get these enumeration errors which is why I'm trying to switch to a threadsafe collection. I'm just not sure which one is appropriate.

Code that calls HandleMeasurementMessage

_busSingle.Consume<MessageEnvelope>(_queueMeasurement, (msg, MessageReceivedInfo) => Task.Factory.StartNew(() =>
            {
                try
                {
                    HandleMeasurementMessage(msg);
                }
                catch (Exception ex)
                {
                    /* Logging stuff*/
                }
            }));

Body:
I would just use simple lock like this:

private static readonly List<EventHubDatum> EventHubDataBatch = new List<EventHubDatum>();
private static void HandleMeasurementMessage(IMessage<MessageEnvelope> msg)
{
    /* Do a bunch of stuff to msg */

    EventHubDatum[] toSend = null;
    lock (EventHubDataBatch) {
        EventHubDataBatch.Add(eventHubDatum);

        if (EventHubDataBatch.Count == 100) {
            // copy to local
            toSend = EventHubDataBatch.ToArray();
            EventHubDataBatch.Clear();
        }
    }

    if (toSend != null) {
        /* Send them off*/
    }
}

Locking here is very brief so it should not affect perfomance in your case in any noticeable way. Note that if there are 100 items - we copy them to local array and clear source list to not hold the lock for the duration of "send them off" operation, which potentially might take long time.


问:
why can't I get the string while scraping with python?
here is my code i want to scrape a list of words from a website,
but when i call the .string on the

```<code>import requests
from bs4 import BeautifulSoup

url = "https://www.merriam-webster.com/browse/thesaurus/a"
source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text, "html.parser")
entry_view = soup.find_all('div', {'class': 'entries'})
view = entry_view[0]
list = view.ul

for m in list:
    for x in m:
        title = x.string
        print(title)
</code>```

what I want is a list printing the text from the website but what I get is an error

```<code>Traceback (most recent call last):
  File "/home/vidu/PycharmProjects/untitled/hello.py", line 14, in <module>
    title = x.string
AttributeError: 'str' object has no attribute 'string'
Error in sys.excepthook:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 63, in apport_excepthook
    from apport.fileutils import likely_packaged, get_recent_crashes
  File "/usr/lib/python3/dist-packages/apport/__init__.py", line 5, in <module>
    from apport.report import Report
  File "/usr/lib/python3/dist-packages/apport/report.py", line 30, in <module>
    import apport.fileutils
  File "/usr/lib/python3/dist-packages/apport/fileutils.py", line 23, in <module>
    from apport.packaging_impl import impl as packaging
  File "/usr/lib/python3/dist-packages/apport/packaging_impl.py", line 23, in <module>
    import apt
  File "/usr/lib/python3/dist-packages/apt/__init__.py", line 23, in <module>
    import apt_pkg
ModuleNotFoundError: No module named 'apt_pkg'

Original exception was:
Traceback (most recent call last):
  File "/home/vidu/PycharmProjects/untitled/hello.py", line 14, in <module>
    title = x.string
AttributeError: 'str' object has no attribute 'string'
</code>```

答:
You can achieve what you want by using the following piece of code.

Code:

```<code>import requests
from bs4 import BeautifulSoup

url = "https://www.merriam-webster.com/browse/thesaurus/a"
html_source = requests.get(url).text
soup = BeautifulSoup(html_source, "html.parser")

entry_view = soup.find_all('div', {'class': 'entries'})

entries = []
for elem in entry_view:
    for e in elem.find_all('a'):
        entries.append(e.text)

#show only 5 elements and whole list length
print(entries[:5])
print(entries[-5:])
print(len(entries))
</code>```

Output:

```<code>['A1', 'aback', 'abaft', 'abandon', 'abandoned']
['absorbing', 'absorption', 'abstainer', 'abstain from', 'abstemious']
100
</code>```

In your code:

```<code>print(type(list))
<class 'bs4.element.Tag'>

print(type(m))
<class 'bs4.element.NavigableString'>

print(type(x))
<class 'str'>
</code>```

So, as you can see, the variable x is already a string, so it's non-sense to use the bs4 method .string().

p.s.: you shouldn't use a variable name like list, it's a reserved keyword.

Body:
here is my code i want to scrape a list of words from a website,
but when i call the .string on the

import requests
from bs4 import BeautifulSoup

url = "https://www.merriam-webster.com/browse/thesaurus/a"
source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text, "html.parser")
entry_view = soup.find_all('div', {'class': 'entries'})
view = entry_view[0]
list = view.ul

for m in list:
    for x in m:
        title = x.string
        print(title)

what I want is a list printing the text from the website but what I get is an error

Traceback (most recent call last):
  File "/home/vidu/PycharmProjects/untitled/hello.py", line 14, in <module>
    title = x.string
AttributeError: 'str' object has no attribute 'string'
Error in sys.excepthook:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 63, in apport_excepthook
    from apport.fileutils import likely_packaged, get_recent_crashes
  File "/usr/lib/python3/dist-packages/apport/__init__.py", line 5, in <module>
    from apport.report import Report
  File "/usr/lib/python3/dist-packages/apport/report.py", line 30, in <module>
    import apport.fileutils
  File "/usr/lib/python3/dist-packages/apport/fileutils.py", line 23, in <module>
    from apport.packaging_impl import impl as packaging
  File "/usr/lib/python3/dist-packages/apport/packaging_impl.py", line 23, in <module>
    import apt
  File "/usr/lib/python3/dist-packages/apt/__init__.py", line 23, in <module>
    import apt_pkg
ModuleNotFoundError: No module named 'apt_pkg'

Original exception was:
Traceback (most recent call last):
  File "/home/vidu/PycharmProjects/untitled/hello.py", line 14, in <module>
    title = x.string
AttributeError: 'str' object has no attribute 'string'

Body:
You can achieve what you want by using the following piece of code.

Code:

import requests
from bs4 import BeautifulSoup

url = "https://www.merriam-webster.com/browse/thesaurus/a"
html_source = requests.get(url).text
soup = BeautifulSoup(html_source, "html.parser")

entry_view = soup.find_all('div', {'class': 'entries'})

entries = []
for elem in entry_view:
    for e in elem.find_all('a'):
        entries.append(e.text)

#show only 5 elements and whole list length
print(entries[:5])
print(entries[-5:])
print(len(entries))

Output:

['A1', 'aback', 'abaft', 'abandon', 'abandoned']
['absorbing', 'absorption', 'abstainer', 'abstain from', 'abstemious']
100

In your code:

print(type(list))
<class 'bs4.element.Tag'>

print(type(m))
<class 'bs4.element.NavigableString'>

print(type(x))
<class 'str'>

So, as you can see, the variable x is already a string, so it's non-sense to use the bs4 method .string().

p.s.: you shouldn't use a variable name like list, it's a reserved keyword.


问:
how to parse simple json string array to object in java
I have a json array as a string in the following format:

```<code> [ "Ford", "BMW", "Fiat" ]
</code>```

which is a legal json string. How am I able to use Gson to save into an object?
When I am trying to use getAsJsonArray(), but I get an error:

```<code> java.lang.IllegalStateException: This is not a JSON Array.
</code>```

答:
You can use this to get value into arraylist using getAsJsonArray() Method</p>

```<code>    String jsonStr = "['Ford', 'BMW', 'Fiat' ]";
    JsonArray root = new JsonParser().parse(jsonStr).getAsJsonArray();
    Gson gson = new Gson();
    ArrayList<String> staff = new ArrayList<>() ;
    Type listType = new TypeToken<List<String>>() {}.getType();
    List<String> yourList = new Gson().fromJson(root, listType);

    System.out.println(yourList );
</code>```

Body:
I have a json array as a string in the following format:

 [ "Ford", "BMW", "Fiat" ]

which is a legal json string. How am I able to use Gson to save into an object?
When I am trying to use getAsJsonArray(), but I get an error:

 java.lang.IllegalStateException: This is not a JSON Array.

Body:
You can use this to get value into arraylist using getAsJsonArray() Method

    String jsonStr = "['Ford', 'BMW', 'Fiat' ]";
    JsonArray root = new JsonParser().parse(jsonStr).getAsJsonArray();
    Gson gson = new Gson();
    ArrayList<String> staff = new ArrayList<>() ;
    Type listType = new TypeToken<List<String>>() {}.getType();
    List<String> yourList = new Gson().fromJson(root, listType);

    System.out.println(yourList );


问:
html check if input is greater than other input after submit
I have two input fields and want to check if one field is greater than the other.
I want to check this before the submit-Button is clicked.

<input type="text" name = "minValue" pattern="(|-)?[0-9]{0,3}?" id="min_value" value="" required/>

<input type="text" name = "maxValue" pattern="(|-)?[0-9]{0,3}?" id="max_value" value="" required/>

<button type = "submit" name = "submitcheck" id = "submit_check"> Let´s Go </button>```

Do I need jquery? I want to do this check before checking the submt button.

答:
Try adding some JavaScript to your code! Maybe like such:</p>

```<code><input type="text" name = "minValue" pattern="(|-)?[0-9]{0,3}?" id="min_value" value="" required/>

<input type="text" name = "maxValue" pattern="(|-)?[0-9]{0,3}?" id="max_value" value="" required/>

<button type = "submit" name = "submitcheck" id = "submit_check"> Let´s Go </button>
<div id=log><div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script type="text/javascript">

$(document).ready(function () {
    $('#submit_check').on('submit', function (e) {
        if (parseInt($("#min_value").val()) > parseInt($("#max_value").val())) {
            document.getElementById('log').innerHTML = "min is larger than max";
        } else {
            document.getElementById('log').innerHTML = "max is larger than min";
        }
    }
);

</script>
</code>```

Body:
I have two input fields and want to check if one field is greater than the other.
I want to check this before the submit-Button is clicked.

<input type="text" name = "minValue" pattern="(|-)?[0-9]{0,3}?" id="min_value" value="" required/>

<input type="text" name = "maxValue" pattern="(|-)?[0-9]{0,3}?" id="max_value" value="" required/>

<button type = "submit" name = "submitcheck" id = "submit_check"> Let´s Go </button>

Do I need jquery? I want to do this check before checking the submt button.

Body:
Try adding some JavaScript to your code! Maybe like such:

<input type="text" name = "minValue" pattern="(|-)?[0-9]{0,3}?" id="min_value" value="" required/>

<input type="text" name = "maxValue" pattern="(|-)?[0-9]{0,3}?" id="max_value" value="" required/>

<button type = "submit" name = "submitcheck" id = "submit_check"> Let´s Go </button>
<div id=log><div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script type="text/javascript">

$(document).ready(function () {
    $('#submit_check').on('submit', function (e) {
        if (parseInt($("#min_value").val()) > parseInt($("#max_value").val())) {
            document.getElementById('log').innerHTML = "min is larger than max";
        } else {
            document.getElementById('log').innerHTML = "max is larger than min";
        }
    }
);

</script>


问:
Set selected item in Android BottomNavigationView
I am using the new android.support.design.widget.BottomNavigationView from the support library.
How can I set the current selection from code? I realized, that the selection is changed back to the first item, after rotating the screen. Of course it would also help, if someone could tell me, how to "save" the current state of the BottomNavigationView in the onPause function and how to restore it in onResume.

Thanks!

答:
From API 25.3.0 it was introduced the method setSelectedItemId(int id) which lets you mark an item as selected as if it was tapped.

From docs:

Set the selected menu item ID. This behaves the same as tapping on an item.

Code example:

```<code>BottomNavigationView bottomNavigationView;
bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomNavigationView);
bottomNavigationView.setOnNavigationItemSelectedListener(myNavigationItemListener);
bottomNavigationView.setSelectedItemId(R.id.my_menu_item_id);
</code>```

IMPORTANT

You MUST have already added all items to the menu (in case you do this programmatically) and set the Listener before calling setSelectedItemId(I believe you want the code in your listener to run when you call this method). If you call setSelectedItemId before adding the menu items and setting the listener nothing will happen.

Body:
From API 25.3.0 it was introduced the method setSelectedItemId(int id) which lets you mark an item as selected as if it was tapped.

From docs:

Set the selected menu item ID. This behaves the same as tapping on an item.

Code example:

BottomNavigationView bottomNavigationView;
bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomNavigationView);
bottomNavigationView.setOnNavigationItemSelectedListener(myNavigationItemListener);
bottomNavigationView.setSelectedItemId(R.id.my_menu_item_id);

IMPORTANT

You MUST have already added all items to the menu (in case you do this programmatically) and set the Listener before calling setSelectedItemId(I believe you want the code in your listener to run when you call this method). If you call setSelectedItemId before adding the menu items and setting the listener nothing will happen.


问:
Android - Changing notification's ContentText on a button click
I have a notification that contains a button, inside that notification .setContentText() there is a proverb shown from an array of strings containing numerous proverbs, what I'm trying to do is when I click that notification button a new proverb is assigned to .setContestText()

I tried looking for other solutions on SO but I got nothing similar

Current result : When I click the button nothing happens

Here is my code so far:

```<code>public void notif(){
    int icon = getRandomIc();
    String Prov = getRandomProverb();
    String newProverb = getRandomProverb();
    Intent reloadQ = new Intent(this, Splash.class);

    PendingIntent piReload = PendingIntent.getService(this, 0, reloadQ, 0);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
    Notification notification = mBuilder
            .setSmallIcon(icon)
            .setVibrate(new long[] { 1000, 1000 })
            .setLights(Color.BLUE, 700, 500)
            .setContentTitle("Notification title")
            .setStyle(new NotificationCompat.BigTextStyle().bigText(NorProv))
            .addAction(R.mipmap.ic_autorenew_black_24dp, "New quote", piReload)
            .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
            .setContentText(Prov)
            .build();

    NotificationManager nMN = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    nMN.notify(NOTIFICATION_ID, notification);
}
</code>```

答:
You can't do that, once a notification is sent you cannot change it's content
take a look at ANDROID NOTIFICATIONS</p>

Body:
I have a notification that contains a button, inside that notification .setContentText() there is a proverb shown from an array of strings containing numerous proverbs, what I'm trying to do is when I click that notification button a new proverb is assigned to .setContestText()

I tried looking for other solutions on SO but I got nothing similar

Current result : When I click the button nothing happens

Here is my code so far:

public void notif(){
    int icon = getRandomIc();
    String Prov = getRandomProverb();
    String newProverb = getRandomProverb();
    Intent reloadQ = new Intent(this, Splash.class);

    PendingIntent piReload = PendingIntent.getService(this, 0, reloadQ, 0);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
    Notification notification = mBuilder
            .setSmallIcon(icon)
            .setVibrate(new long[] { 1000, 1000 })
            .setLights(Color.BLUE, 700, 500)
            .setContentTitle("Notification title")
            .setStyle(new NotificationCompat.BigTextStyle().bigText(NorProv))
            .addAction(R.mipmap.ic_autorenew_black_24dp, "New quote", piReload)
            .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
            .setContentText(Prov)
            .build();

    NotificationManager nMN = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    nMN.notify(NOTIFICATION_ID, notification);
}


问:
Winforms RichTextBox: How can I determine how many lines of text are visible?
I have a Winforms app containing a RichTextBox.

How can I determine how many lines of text are displayed, currently visible?

Reason:  I want to scroll the caret to the middle of the RichTextBox. I can use RichTextBox.ScrollToCaret(), but that puts the caret at  the top of the RichTextBox.  I figure, If I know how many lines are displayed, I could move the caret "back" n/2 lines, then call ScrollToCaret(), then restore the original caret position.

EDIT:

I found EM_GETLINECOUNT, which I thought was the answer, except the doc says: The EM_GETLINECOUNT message retrieves the total number of text lines, not just the number of lines that are currently visible.

Tantalizingly, there is also EM_GETFIRSTVISIBLELINE, which gets the first visible line, but I couldn't find a GETLASTVISIBLELINE.  ??

Related:

How can I scroll the caret to the middle of the RichTextBox?

答:
To display the number of lines that a RichTextBox is capable of displaying, even if there is no text there currently, try:

```<code>Dim s As SizeF = TextRenderer.MeasureText("A", rtb.Font, rtb.Size, TextFormatFlags.WordBreak)
Dim letterHeight As Integer = CInt(s.Height)
Dim displayableLines As Integer = rtb.Height / letterHeight
</code>```

This uses the height of a test letter 'A' in the current font to find the line height in pixels.

Body:
To display the number of lines that a RichTextBox is capable of displaying, even if there is no text there currently, try:

Dim s As SizeF = TextRenderer.MeasureText("A", rtb.Font, rtb.Size, TextFormatFlags.WordBreak)
Dim letterHeight As Integer = CInt(s.Height)
Dim displayableLines As Integer = rtb.Height / letterHeight

This uses the height of a test letter 'A' in the current font to find the line height in pixels.


问:
Can I make a CSS grid with dynamic number of rows or columns?
What I wanna do is to make a CSS grid with a dynamic number of cells. For the sake of simplicity, let's assume there will always be four cells per row. Can I specify a grid with such a dynamic number of rows?

To make it easier, here's the Flexbox implementation:

const COLORS = [
  '#FE9',
  '#9AF',
  '#F9A',
  "#AFA",
  "#FA7"
];

function addItem(container, template) {
  let color = COLORS[_.random(COLORS.length - 1)];
  let num = _.random(10000);

  container.append(Mustache.render(template, { color, num }));
}

$(() => {
  const tmpl = $('#item_template').html()
  const container = $('#app');

  for(let i=0; i<5; i++) { addItem(container, tmpl); }

  $('#add_el').click(() => {
    addItem(container, tmpl);
  })

  container.on('click', '.del_el', (e) => {
    $(e.target).closest('.item').remove();
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  width: 100%;
  display: flex;
  flex-flow: row wrap;
  justify-content: flex-start;
}
.container .item {
  flex: 0 0 calc(25% - 1em);
  min-height: 120px;
  margin: 0.25em 0.5em;
}</code>```

<button id="add_el">Add element</button>

<template id="item_template">

{{ num }}

      <button class="del_el">Delete</button>

</template>```

P.S. Apparently, I wasn't clear enough the first time... I want to recreate this effect using the latest CSS Grid Layout.

答:
Okay, after reading the MDN reference, I found the answer! The key to dynamic rows (or columns) is the repeat property.

const COLORS = [
  '#FE9',
  '#9AF',
  '#F9A',
  "#AFA",
  "#FA7"
];

function addItem(container, template) {
  let color = COLORS[_.random(COLORS.length - 1)];
  let num = _.random(10000);

  container.append(Mustache.render(template, { color, num }));
}

$(() => {
  const tmpl = $('#item_template').html()
  const container = $('#app');

  for(let i=0; i<5; i++) { addItem(container, tmpl); }

  $('#add_el').click(() => {
    addItem(container, tmpl);
  })

  container.on('click', '.del_el', (e) => {
    $(e.target).closest('.item').remove();
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  width: 100%;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: repeat(auto-fill, 120px);
  grid-row-gap: .5em;
  grid-column-gap: 1em;
}

.container .item {
}</code>```

<button id="add_el">Add element</button>

<template id="item_template">

{{ num }}

      <button class="del_el">Delete</button>

</template>```

P.S. Or you can use grid-auto-rows in my particular example.

Body:
What I wanna do is to make a CSS grid with a dynamic number of cells. For the sake of simplicity, let's assume there will always be four cells per row. Can I specify a grid with such a dynamic number of rows?

To make it easier, here's the Flexbox implementation:

const COLORS = [
  '#FE9',
  '#9AF',
  '#F9A',
  "#AFA",
  "#FA7"
];

function addItem(container, template) {
  let color = COLORS[_.random(COLORS.length - 1)];
  let num = _.random(10000);

  container.append(Mustache.render(template, { color, num }));
}

$(() => {
  const tmpl = $('#item_template').html()
  const container = $('#app');

  for(let i=0; i<5; i++) { addItem(container, tmpl); }

  $('#add_el').click(() => {
    addItem(container, tmpl);
  })

  container.on('click', '.del_el', (e) => {
    $(e.target).closest('.item').remove();
  });
});

.container {
  width: 100%;
  display: flex;
  flex-flow: row wrap;
  justify-content: flex-start;
}
.container .item {
  flex: 0 0 calc(25% - 1em);
  min-height: 120px;
  margin: 0.25em 0.5em;
}

<button id="add_el">Add element</button>

<template id="item_template">

{{ num }}

      <button class="del_el">Delete</button>

</template>

P.S. Apparently, I wasn't clear enough the first time... I want to recreate this effect using the latest CSS Grid Layout.

Body:
Okay, after reading the MDN reference, I found the answer! The key to dynamic rows (or columns) is the repeat property.

const COLORS = [
  '#FE9',
  '#9AF',
  '#F9A',
  "#AFA",
  "#FA7"
];

function addItem(container, template) {
  let color = COLORS[_.random(COLORS.length - 1)];
  let num = _.random(10000);

  container.append(Mustache.render(template, { color, num }));
}

$(() => {
  const tmpl = $('#item_template').html()
  const container = $('#app');

  for(let i=0; i<5; i++) { addItem(container, tmpl); }

  $('#add_el').click(() => {
    addItem(container, tmpl);
  })

  container.on('click', '.del_el', (e) => {
    $(e.target).closest('.item').remove();
  });
});

.container {
  width: 100%;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: repeat(auto-fill, 120px);
  grid-row-gap: .5em;
  grid-column-gap: 1em;
}

.container .item {
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.3.0/mustache.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="app" class="container">
</div>

<button id="add_el">Add element</button>

<template id="item_template">
  <div class="item" style="background: {{color}}">
    <p>{{ num }}</p>
    <p>
      <button class="del_el">Delete</button>
    </p>
  </div>
</template>

P.S. Or you can use grid-auto-rows in my particular example.


问:
How do I link the correct library so __aeabi_idiv and __aeabi_idivmod work?
This is the question I'm following up on. I have the same problem as regomodo did in that thread way back in 2011:

I'm trying to run a little program on my Raspberry Pi, and I'm using operators that aren't natively supported by ARM:

```<code>hello.c:(.text+0x64): undefined reference to `__aeabi_idiv'
hello.c:(.text+0x7c): undefined reference to `__aeabi_idivmod'
</code>```

I understand that I need to link a library that knows about division and modding, but I can't quite get that to work (newbie to the Makefile life).

So I gave it a kind of pathetic stab and tried just adding the -lgcc:

```<code>LDFLAGS  = -L../lib -lgcc
</code>```

that wasn't super fruitful:

```<code>arm-none-eabi-ld: cannot find -lgcc
</code>```

any advice would be so appreciated.

[edit1] here's the start of my makefile:

```<code>ARMGNU ?= arm-none-eabi

CPPFLAGS = -I../include
CFLAGS = $(ARCHFLAGS) -Wall -O2 -nostdlib -nostartfiles -ffreestanding
LDFLAGS  = -L../lib -lgcc
LIBS = -lpi
</code>```

答:
I know is quite late, but I was having the same problem, I'm using ArchLinux and it turns out that the libgcc.a file was not located at

```<code>/usr/arm-none-eabi/lib/
</code>```

and/or its child folders which is the default installation directory for arm-none-eabi compiler in my system, instead, the libgcc.a library is located at

```<code>/usr/lib/gcc/arm-none-eabi/(version)
</code>```

So whatever system you're using, you should look for that library in your default lib directory.

Body:
This is the question I'm following up on. I have the same problem as regomodo did in that thread way back in 2011:

I'm trying to run a little program on my Raspberry Pi, and I'm using operators that aren't natively supported by ARM:

hello.c:(.text+0x64): undefined reference to `__aeabi_idiv'
hello.c:(.text+0x7c): undefined reference to `__aeabi_idivmod'

I understand that I need to link a library that knows about division and modding, but I can't quite get that to work (newbie to the Makefile life).

So I gave it a kind of pathetic stab and tried just adding the -lgcc:

LDFLAGS  = -L../lib -lgcc

that wasn't super fruitful:

arm-none-eabi-ld: cannot find -lgcc

any advice would be so appreciated.

[edit1] here's the start of my makefile:

ARMGNU ?= arm-none-eabi

CPPFLAGS = -I../include
CFLAGS = $(ARCHFLAGS) -Wall -O2 -nostdlib -nostartfiles -ffreestanding
LDFLAGS  = -L../lib -lgcc
LIBS = -lpi

Body:
I know is quite late, but I was having the same problem, I'm using ArchLinux and it turns out that the libgcc.a file was not located at

/usr/arm-none-eabi/lib/

and/or its child folders which is the default installation directory for arm-none-eabi compiler in my system, instead, the libgcc.a library is located at

/usr/lib/gcc/arm-none-eabi/(version)

So whatever system you're using, you should look for that library in your default lib directory.


问:
How to convert Php foreach to Twig?
I'm using CodeIgniter with Twig, i'm trying to integrate FullCalendar
I got the librerary form Here , my problem is with this line - in the Index.php file :

```<code>events: [
    <?php foreach($events as $event):
        $start = explode(" ", $event['start']);
        $end = explode(" ", $event['end']);
        if($start[1] == '00:00:00'){
            $start = $start[0];
        }else{
            $start = $event['start'];
        }
        if($end[1] == '00:00:00'){
            $end = $end[0];
        }else{
            $end = $event['end'];
        }
    ?>
        {
            id: '<?php echo $event['id']; ?>',
            title: '<?php echo $event['title']; ?>',
            start: '<?php echo $start; ?>',
            end: '<?php echo $end; ?>',
            color: '<?php echo $event['color']; ?>',
        },
    <?php endforeach; ?>
]
</code>```

Since i'm using Twig - i can't translate this part into twig, i've tried :

```<code>events: [
    {
        {% for res in events_from_db %}
        id : "{{ res.id}}",
        title : "{{ res.title}}",
        start : "{{ res.start}}",
        end : "{{ res.end}}",
        color : "{{ res.color}}",
        {% endfor %}
    }
]
</code>```

But it's getting only the last key of the Array.... So i figure - why not simply insert the array directly - So i did this:

```<code>var events_from_db = '{{ events_from_db|json_encode|raw }}';

var json_res = JSON.parse(events_from_db);
events_res = [];
$.each(json_res, function (k,v) {
    events_res.push(v);
});

events: [
    events_res
]
</code>```

But it didn't worked either...

答:
Your loop should be outside the JS brackets:</p>

```<code>{% for res in events_from_db %}
    {
        id : "{{ res.id}}",
        title : "{{ res.title}}",
        start : "{{ res.start}}",
        end : "{{ res.end}}",
        color : "{{ res.color}}",
    },
{% endfor %}
</code>```

Title: How to convert Php foreach to Twig?

Body:
I'm using CodeIgniter with Twig, i'm trying to integrate FullCalendar
I got the librerary form Here , my problem is with this line - in the Index.php file :

events: [
    <?php foreach($events as $event):
        $start = explode(" ", $event['start']);
        $end = explode(" ", $event['end']);
        if($start[1] == '00:00:00'){
            $start = $start[0];
        }else{
            $start = $event['start'];
        }
        if($end[1] == '00:00:00'){
            $end = $end[0];
        }else{
            $end = $event['end'];
        }
    ?>
        {
            id: '<?php echo $event['id']; ?>',
            title: '<?php echo $event['title']; ?>',
            start: '<?php echo $start; ?>',
            end: '<?php echo $end; ?>',
            color: '<?php echo $event['color']; ?>',
        },
    <?php endforeach; ?>
]

Since i'm using Twig - i can't translate this part into twig, i've tried :

events: [
    {
        {% for res in events_from_db %}
        id : "{{ res.id}}",
        title : "{{ res.title}}",
        start : "{{ res.start}}",
        end : "{{ res.end}}",
        color : "{{ res.color}}",
        {% endfor %}
    }
]

But it's getting only the last key of the Array.... So i figure - why not simply insert the array directly - So i did this:

var events_from_db = '{{ events_from_db|json_encode|raw }}';

var json_res = JSON.parse(events_from_db);
events_res = [];
$.each(json_res, function (k,v) {
    events_res.push(v);
});

events: [
    events_res
]

But it didn't worked either...

Body:
Your loop should be outside the JS brackets:

{% for res in events_from_db %}
    {
        id : "{{ res.id}}",
        title : "{{ res.title}}",
        start : "{{ res.start}}",
        end : "{{ res.end}}",
        color : "{{ res.color}}",
    },
{% endfor %}


问:
How to open window or whatever while my method is doing something in background WPF
as much as we know,
programs are executing line by line, and now I am facing issue, I have a method which is taking few seconds to execute,
I thought I could solve it by threads but I will speak about it later, now what I would like to do is next:

How could I open a window with message like "Still executing..." when that method start execution and when method is done window could close himself,
I need that because I Would like to avoid UI freezing because that long method is not in another task/thread.

Here is how it looks like:

```<code>if (e.Key == Key.Delete)
{
    //Could I show window here like like "Loading please wait.."
    ExecuteLongMethod();
    //When this is done close this method
}
</code>```

Thanks guys,
Cheers

答:
An example where a top window/control is displayed with progress information and the main window is disabled:

```<code>if (e.Key == Key.Delete)
{
    // create a window with a progress ring or progress bar
    var window = new Window();

    new Thread(() =>
    {
        // execute long method
        ExecuteLongMethod();

        // close the progress window - release control
        // ensure it is done on the UI thread
        System.Windows.Application.Current.Dispatcher.Invoke(() => window.Close());
    }).Start();

    // display progress window
    window.ShowDialog();
}
</code>```

Another approach would be to temporarily disable or hide any UI elements (buttons, tabs) that might interfere with the background thread and do not block the main window.

Body:
as much as we know,
programs are executing line by line, and now I am facing issue, I have a method which is taking few seconds to execute,
I thought I could solve it by threads but I will speak about it later, now what I would like to do is next:

How could I open a window with message like "Still executing..." when that method start execution and when method is done window could close himself,
I need that because I Would like to avoid UI freezing because that long method is not in another task/thread.

Here is how it looks like:

if (e.Key == Key.Delete)
{
    //Could I show window here like like "Loading please wait.."
    ExecuteLongMethod();
    //When this is done close this method
}

Thanks guys,
Cheers

Body:
An example where a top window/control is displayed with progress information and the main window is disabled:

if (e.Key == Key.Delete)
{
    // create a window with a progress ring or progress bar
    var window = new Window();

    new Thread(() =>
    {
        // execute long method
        ExecuteLongMethod();

        // close the progress window - release control
        // ensure it is done on the UI thread
        System.Windows.Application.Current.Dispatcher.Invoke(() => window.Close());
    }).Start();

    // display progress window
    window.ShowDialog();
}

Another approach would be to temporarily disable or hide any UI elements (buttons, tabs) that might interfere with the background thread and do not block the main window.


问:
Complex Function in ggplot in R
I have an expression

((cos(-0.2 * pi)*(y-1) - (sin(-0.2 * pi)*x))) = 0.2 * (abs( sin((10*pi*(sin(-0.2 * pi) * (y - 1) + cos(-0.2 * pi) * x))^1)))^6

that I want to draw in a ggplot with geom_point plotted points.
The function will look similar to this image when plotted:

The problem with the function is probably the overlapping values. I have tried to solve it by using a contour plot as described in this question. This solution produced the following result:

However, this plot seems imprecise, so I would like to find a better solution for plotting this kind of function in R with ggplot.

答:
Following the idea of the contour plot, you only have to increase the resolution in x and y.
Here you will find a script with your function. The lower the value of resolution here, the higher the precision. Be careful not to use a too high value that would create a very long calculation...

It starts to be good with 0.05:

```<code>library(ggplot2)
resolution <- 0.005
xy <- expand.grid(x = seq(0, 1, resolution), y = seq(0, 1, resolution))
z <- apply(xy, 1, function(xy) {
  x <- xy[1]
  y <- xy[2]
  0.2 * (abs( sin((10*pi*(sin(-0.2 * pi) * (y - 1) + cos(-0.2 * pi) * x))^1)))^6 -
  ((cos(-0.2 * pi)*(y-1) - (sin(-0.2 * pi)*x)))
})

xyz <- data.frame(xy, z)

ggplot() +
geom_contour(data=xyz,
             aes(x=x,y=y,z=z),breaks=0,
             colour="black")
</code>```

Title: Complex Function in ggplot in R

Body:
Following the idea of the contour plot, you only have to increase the resolution in x and y.
Here you will find a script with your function. The lower the value of resolution here, the higher the precision. Be careful not to use a too high value that would create a very long calculation...

It starts to be good with 0.05:

library(ggplot2)
resolution <- 0.005
xy <- expand.grid(x = seq(0, 1, resolution), y = seq(0, 1, resolution))
z <- apply(xy, 1, function(xy) {
  x <- xy[1]
  y <- xy[2]
  0.2 * (abs( sin((10*pi*(sin(-0.2 * pi) * (y - 1) + cos(-0.2 * pi) * x))^1)))^6 -
  ((cos(-0.2 * pi)*(y-1) - (sin(-0.2 * pi)*x)))
})

xyz <- data.frame(xy, z)

ggplot() +
geom_contour(data=xyz,
             aes(x=x,y=y,z=z),breaks=0,
             colour="black")


问:
split scala code into modules with one module for imports only
I have a main scala module with my main object with multiple function. I import many fundamental and necessary packages in order to run the code.

I have splitted the code into few modules and each module has got an object with some functions taken from original main module.

I do not know what to do about imports. I thought I can just create a separate module for imports and this is what I have tried but obviously it does not work.

is there a way to skip having imports in each module separately and just to have one module for all necessary imports?

答:
Some languages allow re-exporting imports, but Scala isn't one of them. You can do something like this:

```<code>object Imports {
  type Type1 = some.package.Type1
  // only if Type1 is a Scala type with a companion object
  val Type1 = some.package.Type1
  ...
  // you can also define methods here
}

// elsewhere
import Imports._
</code>```

In most circumstances this is a bad idea. It also doesn't help with static members of Java types.

Body:
Some languages allow re-exporting imports, but Scala isn't one of them. You can do something like this:

object Imports {
  type Type1 = some.package.Type1
  // only if Type1 is a Scala type with a companion object
  val Type1 = some.package.Type1
  ...
  // you can also define methods here
}

// elsewhere
import Imports._

In most circumstances this is a bad idea. It also doesn't help with static members of Java types.


问:
Memory Allocation Algorithm (non-contiguous)
Just a curious question though!

While going through various techniques of memory allocation and management, specially paging in which the fixed size block is assigned to a particular request, everything goes fine until when the process exits the memory leaving behind spaces for non-contiguous allocation for other processes. Now for that case the data structure Page Tables keeps a track of corresponding Page to Frame number.

Can an algorithm be designed in such a way that pages are always allocated after the last allocated page in the memory and dynamically shifting and covering the empty page space that is caused by the freeing process (from somewhere in the middle) at every minute intervals, maintaining a row of contiguous memory at any given time. This may preserve contiguous memory allocation for processes thus enabling quicker memory access.

For e.g:

```<code> ----------                                            ----------
|  Page 1  |   After Page 2 is deallocated            |  Page 1  |
 ----------        rather than assigning               ----------
|  Page 2  |    the space to some other process       |  Page 3  |
 ----------        in a non-contiguous fashion,        ----------
|  Page 3  |     there can be something               |  Page 4  |
 ----------            like this -->                   ----------
|  Page 4  |                                          |          |
 ----------                                            ----------
</code>```

The point is that the memory allocation can be continuous and always after the last allocated page.

I would appreciate if I am told about the design flaws or the parameters one has to take care of while thinking of any such algorithm.

答:
This is called 'compacting' garbage collection, usually part of a mark-compact garbage collection algorithm: https://en.wikipedia.org/wiki/Mark-compact_algorithm

As with any garbage collector, the collection/compaction is the easy part.  The hard part is letting the program that you're collecting for continue to work as you're moving its memory around.

Body:
Just a curious question though!

While going through various techniques of memory allocation and management, specially paging in which the fixed size block is assigned to a particular request, everything goes fine until when the process exits the memory leaving behind spaces for non-contiguous allocation for other processes. Now for that case the data structure Page Tables keeps a track of corresponding Page to Frame number.

Can an algorithm be designed in such a way that pages are always allocated after the last allocated page in the memory and dynamically shifting and covering the empty page space that is caused by the freeing process (from somewhere in the middle) at every minute intervals, maintaining a row of contiguous memory at any given time. This may preserve contiguous memory allocation for processes thus enabling quicker memory access.

For e.g:

 ----------                                            ----------
|  Page 1  |   After Page 2 is deallocated            |  Page 1  |
 ----------        rather than assigning               ----------
|  Page 2  |    the space to some other process       |  Page 3  |
 ----------        in a non-contiguous fashion,        ----------
|  Page 3  |     there can be something               |  Page 4  |
 ----------            like this -->                   ----------
|  Page 4  |                                          |          |
 ----------                                            ----------

The point is that the memory allocation can be continuous and always after the last allocated page.

I would appreciate if I am told about the design flaws or the parameters one has to take care of while thinking of any such algorithm.


问:
Windows service and permissions problem
I have written a windows service that needs to be installed on any flavor of windows from WinXP SP2 on up (client requirement).  I initially wrote the service to be started by the SCM during install, using the 'Network Service' account.  All testing took place on virtual box VM's in various locations at our site, with no problems during the install, and the service running as expected.

But at the customer site, using VPC's the install of this service fails with Error 1920- a permissions error.  It also fails for Virtual Box VM's- in fact it fails for pretty much -every- machine I (and my team) have tried it on but only at the customer QA site.

If the service is manually installed and a local user account is used to log on (a Workgroup account) the service starts fine- so unrealistic as this is, it at least shows the service can run, with the right log on configuration.

I set up a new user account, and went through permissions, local security policies, groups etc to make sure the account that worked and the new one matched exactly, but that new user account also could not start the service(!?).  Since the account that worked is a member of a workgroup rather than a domain, I dont think there is a domain policy messing with things, but Im not 100% about that.

Any ideas on what to look for or what I could be missing?

答:
You may want to add the login which is used for running the service to be part of Administrators Group.

Please refer to this Microsoft Support Article

Title: Windows service and permissions problem


问:
I want to create a log file where I can get INFO, DEBUG, ERROR, CRITICAL, WARNING details int that file. But My code is not giving me the exact output
```<code>import logging.handlers

LOG_FILENAME = 'logger.log'

logging.basicConfig(filename=LOG_FILENAME,
                    level=logging.DEBUG,
                    )

logging.info('In Log File...')
f = open(LOG_FILENAME, 'rt')

try:
    body = f.read()
finally:
    f.close()
print 'FILE:'
print body
def syslog (debug,info,warning,error,critical = "LEVELS"):
    str = "Debug: "+ debug+" Info: "+ info+" Waring: "+ warning+" Error: "+ error+" Critical: " +critical
    return str
my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.DEBUG)

handler = logging.handlers.SysLogHandler(address = ('localhost',514), facility=19)
my_logger.addHandler(handler)

my_logger.debug('this is debug')
my_logger.critical('this is critical')
my_logger.info('this is info')
my_logger.warn('this is critical')
</code>```

答:
```<code>import logging
import socket
import sys
from logging.handlers import SysLogHandler

#class ContextFilter(object):
    #pass
class ContextFilter(logging.Filter):
    hostname = socket.gethostname()

    def filter(self, record):
        record.hostname = ContextFilter.hostname
        return True

    try:
        syslog = SysLogHandler(address=('110.110.112.143', 514))
    # except (IOError,NameError) as e:
    #     print str(e)
    except Exception as e:
        logging.exception("message contextfilter")
    finally:
        pass

        #try:
            #handler = logging.handlers.SysLogHandler(address=('localhost', 514), facility=19)
            # except (IOError,NameError) as e:
            #     print str(e)
        #except Exception as e:
            #logging.exception("message contextfilter")
        #finally:
        #pass

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

f = ContextFilter()
logger.addFilter(f)

# syslog = SysLogHandler(address=('110.110.112.202', 514))
# handler = logging.handlers.SysLogHandler(address = '/dev/log')
# handler = logging.handlers.SysLogHandler(address=('localhost', 514), facility=19)
# logger.addHandler(handler)
# syslog = SysLogHandler(address=('192.168.56.102', 514))
formatter = logging.Formatter('%(hostname)s syslogs: [%(levelname)s] %(message)s', datefmt='%b %d %H:%M:%S')
# syslog.setFormatter(formatter)
# logger.addHandler(syslog)

#  NullHandler handler excepation
logging.getLogger('ContextFilter').addHandler(logging.NullHandler())
logging.debug("In Information's Log File... ")
logging.info("In Debug's Log File... ")
logging.warning("In Warning's Log File... ")
logging.error("In Critical's Log File... ")
logging.critical("In Error's Log File...")
print "These is loging INFO .... "
</code>```


问:
non-repeatable read vs. phantom read
I know that

```<code>A non-repeatable read occurs, when during the course of a transaction, a row is
retrieved twice and the values within the row differ between reads.
</code>```

and

```<code>A phantom read occurs when, in the course of a transaction, two identical queries are executed, and the collection of rows returned by the second query is different from the first.
</code>```

and I guess that this happens because in both causes we are in transaction A and transaction B just commit some changes.

So my question is... Is there another use case from both or 1 that the cause could be another than transaction B just commit some changes while we are in transaction A ? So basically these are 2 different consequences of the same problem, right ?

答:
The discrepancy in a non-repeatable read is always the result of an UPDATE statement, whereas in the case of phantom read, it could also be the result of an INSERT or a DELETE.
Also, the first case can be prevented by locking rows, not the second.</p>

Title: non-repeatable read vs. phantom read

Body:
I know that

A non-repeatable read occurs, when during the course of a transaction, a row is
retrieved twice and the values within the row differ between reads.

and

A phantom read occurs when, in the course of a transaction, two identical queries are executed, and the collection of rows returned by the second query is different from the first.

and I guess that this happens because in both causes we are in transaction A and transaction B just commit some changes.

So my question is... Is there another use case from both or 1 that the cause could be another than transaction B just commit some changes while we are in transaction A ? So basically these are 2 different consequences of the same problem, right ?


问:
Ember.js component rerender not rerendering
I'm trying to render some data into a table. The data is organized by years, and users can add years to the index.

When the user adds a year, the data for that year is loaded via AJAX and added to an Ember.Object info, like this:

```<code>var self=this;
Ember.$.getJSON('url'+year, function(data) {
  var info = self.get("info");
  info['total'][year] = data.total;
  info['commission'][year] = data.commission;
}
</code>```

In the template, the data is shown via each-in helpers:

```<code>{{#each-in info.total as |k t|}}
  {{t}}
{{/each-in}}
</code>```

Following the manual, here, since each-in is not bound to new properties, I added self.rerender(); after the ajax assigments in the component.

My issue is that the component is NOT rerendering. If I change routes and come back, the page is rerendered and the data shows, so the issue is clearly on the rerender() call.

PS: The code shown here is a simplified example; there is a reason why I must use each-in and any solution that necessitates changing the data structure won't help. I just need to know why rerender() is not rerendering and how to make it do so.

答:
Since glimmer 2 you don't need to call rerender for an each-in loop.

Now you could create new objects, however a faster solution is to just use Ember.set instead of the [] syntax. So replace this:

```<code>info['total'][year] = data.total;
</code>```

with this:

```<code>Ember.set(info, `total.${year}`, data.total);
</code>```

And it will work.

If you refuse to do that you should call notifyPropertyChange. However Ember.set is preferred.

Checkout this twiddle.

Body:
I'm trying to render some data into a table. The data is organized by years, and users can add years to the index.

When the user adds a year, the data for that year is loaded via AJAX and added to an Ember.Object info, like this:

var self=this;
Ember.$.getJSON('url'+year, function(data) {
  var info = self.get("info");
  info['total'][year] = data.total;
  info['commission'][year] = data.commission;
}

In the template, the data is shown via each-in helpers:

{{#each-in info.total as |k t|}}
  {{t}}
{{/each-in}}

Following the manual, here, since each-in is not bound to new properties, I added self.rerender(); after the ajax assigments in the component.

My issue is that the component is NOT rerendering. If I change routes and come back, the page is rerendered and the data shows, so the issue is clearly on the rerender() call.

PS: The code shown here is a simplified example; there is a reason why I must use each-in and any solution that necessitates changing the data structure won't help. I just need to know why rerender() is not rerendering and how to make it do so.

Body:
Since glimmer 2 you don't need to call rerender for an each-in loop.

Now you could create new objects, however a faster solution is to just use Ember.set instead of the [] syntax. So replace this:

info['total'][year] = data.total;

with this:

Ember.set(info, `total.${year}`, data.total);

And it will work.

If you refuse to do that you should call notifyPropertyChange. However Ember.set is preferred.

Checkout this twiddle.


问:
To push selected values from one dynamic table to another dynamic table
I have two tables named products and customers:-

```<code><table cellpadding="0" cellspacing="0">
     <thead>
        <tr>
           <th>Product Code</th>
        </tr>
       </thead>
    <tbody>
  <tr ng-repeat="row in service track by $index" ng-class="{'ISselected': isSelected(row, $index)}" ng-click="selectedRow(row, $index)">
        <td>{{row}}</td>
  </tr>
    </tbody>
</table>

<table cellpadding="0" cellspacing="0">
      <thead>
         <tr>
           <th>Customer Code</th>
         </tr>
      </thead>
       <tbody>
         <tr ng-repeat="row in customers track by $index">
            <td>{{row}}</td>
         </tr>
       </tbody>
   </table>
</code>```

And a button:-

```<code><button type="button" class="btn btn-info">Add</button>
</code>```

My directive code:-

```<code>scope.services = [];
 scope.customers = [];
  scope.selectedRowID = null;

            scope.selectedRow = function(rowID){
                    scope.selectedRowID = scope.selectedRowID == rowID ? null : rowID;
                }

            scope.isSelected = function(rowID){
                    return (scope.selectedRowID == rowID);
            }
</code>```

What I want here is when I select a particular row/value from the 'products' table and press 'add' button then that row/value gets pushed or added to my customers' table. The data inside from both tables are coming from the backend.

答:
What i understand is for every row you have ADD button so that you can transfer data from one table to another.

First add "ADD" button inside table for every row.

Then Add the ng-click directive to ADD button

```<code><button type="button" class="btn btn-info" ng-click="transferData($index)">Add</button>
</code>```

Then add this function to your Directive:

```<code>$scope.transferData=function(index){
$scope.customers.push($scope.services [index]);
};
</code>```

This will meet your requirements.

Body:
I have two tables named products and customers:-

           Product Code

        {{row}}

           Customer Code

            {{row}}

And a button:-

<button type="button" class="btn btn-info">Add</button>

My directive code:-

scope.services = [];
 scope.customers = [];
  scope.selectedRowID = null;

            scope.selectedRow = function(rowID){
                    scope.selectedRowID = scope.selectedRowID == rowID ? null : rowID;
                }

            scope.isSelected = function(rowID){
                    return (scope.selectedRowID == rowID);
            }

What I want here is when I select a particular row/value from the 'products' table and press 'add' button then that row/value gets pushed or added to my customers' table. The data inside from both tables are coming from the backend.

Body:
What i understand is for every row you have ADD button so that you can transfer data from one table to another.

First add "ADD" button inside table for every row.

Then Add the ng-click directive to ADD button

<button type="button" class="btn btn-info" ng-click="transferData($index)">Add</button>

Then add this function to your Directive:

$scope.transferData=function(index){
$scope.customers.push($scope.services [index]);
};

This will meet your requirements.


问:
Javascript clock - server time
I need to show the server time on a clock. Below is the code i currently have. I get the server time with Ajax call. The problem is that if the user changes it's local/computer clock it will also update the script's clock which is not ok - it should continue without changing and i'm stuck. I've tried passing the serverTime within the setTimeout so it get's used every time as a reference but no luck with that.

var serverTime  = 1490856278000;
var localTime   = +Date.now();
var timeDiff    = serverTime - localTime;
var realTime;
var date;
var hours;
var minutes;
var seconds;
setInterval(function () {
  realTime = +Date.now() + timeDiff;
  date     = new Date(realTime);
  hours    = date.getHours();
  minutes  = date.getMinutes();
  seconds  = date.getSeconds();
  document.getElementById('clock').innerHTML = hours + ':' + minutes + ':' + seconds;
}, 1000);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="clock"></div></code>```

答:
Using How to create an accurate timer in javascript? and Bergi's answer I prepared an another way. I think you don't have to use the local time at all:

var serverTime  = 1490856278000;
var expected = serverTime;
var date;
var hours;
var minutes;
var seconds;
var now = performance.now();
var then = now;
var dt = 0;
var nextInterval = interval = 1000; // ms

setTimeout(step, interval);
function step() {
    then = now;
    now = performance.now();
    dt = now - then - nextInterval; // the drift

    nextInterval = interval - dt;
    serverTime += interval;
    date     = new Date(serverTime);
    hours    = date.getUTCHours();
    minutes  = date.getUTCMinutes();
    seconds  = date.getUTCSeconds();
    document.getElementById('clock').innerHTML = hours + ':' + minutes + ':' + seconds;

    console.log(nextInterval, dt); //Click away to another tab and check the logs after a while
    now = performance.now();

    setTimeout(step, Math.max(0, nextInterval)); // take into account drift
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="clock"></div></code>```

Title: Javascript clock - server time

Body:
Using How to create an accurate timer in javascript? and Bergi's answer I prepared an another way. I think you don't have to use the local time at all:

var serverTime  = 1490856278000;
var expected = serverTime;
var date;
var hours;
var minutes;
var seconds;
var now = performance.now();
var then = now;
var dt = 0;
var nextInterval = interval = 1000; // ms

setTimeout(step, interval);
function step() {
    then = now;
    now = performance.now();
    dt = now - then - nextInterval; // the drift

    nextInterval = interval - dt;
    serverTime += interval;
    date     = new Date(serverTime);
    hours    = date.getUTCHours();
    minutes  = date.getUTCMinutes();
    seconds  = date.getUTCSeconds();
    document.getElementById('clock').innerHTML = hours + ':' + minutes + ':' + seconds;

    console.log(nextInterval, dt); //Click away to another tab and check the logs after a while
    now = performance.now();

    setTimeout(step, Math.max(0, nextInterval)); // take into account drift
}

<div id="clock"></div>


问:
String and StringBuilder return type in method
I have one doubt if I use return type as String then it stored in heap memory or not?

For example.

```<code>public String someName(){

return "Test String";

}

public StringBuilder someName(){
 StringBuilder sb = new StringBuilder("Hi from sb");
        return sb;

}
</code>```

On above example we create two method 1. return String 2. return StringBuilder.

So my question is 1st method string is stored in heap or not ?

答: Stack is a memory place where the methods and the local variables are stored. Heap is a memory place where the objects and its instance variable are stored.</p>

Body:
I have one doubt if I use return type as String then it stored in heap memory or not?

For example.

public String someName(){

return "Test String";

}

public StringBuilder someName(){
 StringBuilder sb = new StringBuilder("Hi from sb");
        return sb;

}

On above example we create two method 1. return String 2. return StringBuilder.

So my question is 1st method string is stored in heap or not ?


问:
How can we put the initial centroids in FCM function ( Matlab )
I am using fcm function in Matlab to clustering. However, the initial centroids are set randomly. I need to set the initial centroids values by myself. I am thinking to modify the stepfcm function in Matlab. Could anyone tell me how can I put the initial centroids by myself? </p>

答:
I did edit('fcm.m').

On line 84 (I use MATLAB R2016b) you have:

U = initfcm(cluster_n, data_n);            % Initial fuzzy partition

This is the initialization of clusters centroids.

If you replace it with your own you'll get what you want.

How To?

On MATLAB's command line run the command edit('fcm.m').

Save a copy of it with the name FcmInit.

Change the function signature from [center, U, obj_fcn] = fcm(data, cluster_n, options) To [center, obj_fcn] = FcmInit(data, cluster_n, U, options).

Delete the line U = initfcm(cluster_n, data_n); so it won't overwrite the input.


问:
Retrofit enqueue doesn't work but execute work
I'm using com.squareup.retrofit2:retrofit:2.2.0

```<code>    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.BODY);

    OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
    httpClient.addInterceptor(logging);

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://localhost:9000")
            .addConverterFactory(GsonConverterFactory.create())
            .client(httpClient.build())
            .build();

    final UserService service = retrofit.create(UserService.class);

    Call<User> userCall = service.createUser(user)
</code>```

Here is the problem: when I run the execute it make REST API request but when I use enqueue it does nothing (no exception, no log)

```<code>  userCall.execute(); //this work

  //this does not work
  userCall.enqueue(new Callback<User>() {
      @Override
      public void onResponse(Call<User> call, Response<User> response) {
          // no response
      }

      @Override
      public void onFailure(Call<User> call, Throwable t) {
          //nothing here
      }
  });
</code>```

答:
put your code as this:

```<code> userCall.enqueue(new Callback<User>() {
    @Override
    public void onResponse(Call<User> call, Response<User> response) {
        Toast.makeText(this, "in response", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onFailure(Call<User> call, Throwable t) {

        Toast.makeText(this, "in response", Toast.LENGTH_SHORT).show();
    }
});
</code>```

Now based on method call you will get toast if its in response toast will be "In response" don't forget write youractivity name before this  like :  MainActivity.this

Body:
I'm using com.squareup.retrofit2:retrofit:2.2.0

    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.BODY);

    OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
    httpClient.addInterceptor(logging);

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://localhost:9000")
            .addConverterFactory(GsonConverterFactory.create())
            .client(httpClient.build())
            .build();

    final UserService service = retrofit.create(UserService.class);

    Call<User> userCall = service.createUser(user)

Here is the problem: when I run the execute it make REST API request but when I use enqueue it does nothing (no exception, no log)

  userCall.execute(); //this work

  //this does not work
  userCall.enqueue(new Callback<User>() {
      @Override
      public void onResponse(Call<User> call, Response<User> response) {
          // no response
      }

      @Override
      public void onFailure(Call<User> call, Throwable t) {
          //nothing here
      }
  });

Body:
put your code as this:

 userCall.enqueue(new Callback<User>() {
    @Override
    public void onResponse(Call<User> call, Response<User> response) {
        Toast.makeText(this, "in response", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onFailure(Call<User> call, Throwable t) {

        Toast.makeText(this, "in response", Toast.LENGTH_SHORT).show();
    }
});

Now based on method call you will get toast if its in response toast will be "In response" don't forget write youractivity name before this  like :  MainActivity.this


问:
Exporting a subset of a out-of-proc COM server by using an in-proc-server
I implemented an out-of-proc COM server (implemented in a Service). I don't want other applications to access all the functionality in the COM server, so I developed an in-proc server (DLL) which would talk to the out-of-proc server.

Because I don't want the interfaces in the out-of-proc COM server to be accessed directly, I don't embed the type library with the Service so I thought I could use #import and have access to the COM server through the TLB. However, when I try in my in-proc-server to create an instance of a class implemented in the service, I get an E_NOINTERFACE back. I guess this is due to marshalling, but I couldn't figure out how to overcome this.

Any idea on how to communicate from the in-proc-server with my out-of-proc server without exposing the interface details of the out-of-proc server?

答: I'm not sure about how this will help to conseal the interfaces, but there're three ways to make marshalling working and typelib is one of them. The other quite easy way is a proxy/stub - a bunch of code in a separate in-proc COM server that will automagically do the marshalling once it has been registered in Windows registry. Again, I'm not sure how this will help conseal the interface, but it looks more covert then a type library that just exposes teh interface to anyone with OLEView.</p>


问:
Convert float64 column to datetime pandas
I have the following pandas DataFrame column dfA['TradeDate']:

```<code>0     20100329.0
1     20100328.0
2     20100329.0
...
</code>```

and I wish to transform it to a datetime.

Based on another tread on SO, I convert it first to a string and then apply the strptime function.

```<code>dfA['TradeDate'] = datetime.datetime.strptime( dfA['TradeDate'].astype('int').to_string() ,'%Y%m%d')
</code>```

However this returns the error that my format is incorrect (ValueError).

An issue that I spotted is that the column is not properly to string, but to an object.

When I try:

```<code>dfA['TradeDate'] = datetime.datetime.strptime( dfA['TradeDate'].astype(int).astype(str),'%Y%m%d')
</code>```

It returns: must be a Str and not Series.

答:
strptime function works on a single value, not on series. You need to apply that function to each element of the column

try pandas.to_datetime method

eg

```<code>dfA = pandas.DataFrame({"TradeDate" : [20100329.0,20100328.0]})
pandas.to_datetime(dfA['TradeDate'], format = "%Y%m%d")
</code>```

or

```<code>dfA['TradeDate'].astype(int).astype(str)\
    .apply(lambda x:datetime.datetime.strptime(x,'%Y%m%d'))
</code>```

Body:
I have the following pandas DataFrame column dfA['TradeDate']:

0     20100329.0
1     20100328.0
2     20100329.0
...

and I wish to transform it to a datetime.

Based on another tread on SO, I convert it first to a string and then apply the strptime function.

dfA['TradeDate'] = datetime.datetime.strptime( dfA['TradeDate'].astype('int').to_string() ,'%Y%m%d')

However this returns the error that my format is incorrect (ValueError).

An issue that I spotted is that the column is not properly to string, but to an object.

When I try:

dfA['TradeDate'] = datetime.datetime.strptime( dfA['TradeDate'].astype(int).astype(str),'%Y%m%d')

It returns: must be a Str and not Series.

Body:
strptime function works on a single value, not on series. You need to apply that function to each element of the column

try pandas.to_datetime method

eg

dfA = pandas.DataFrame({"TradeDate" : [20100329.0,20100328.0]})
pandas.to_datetime(dfA['TradeDate'], format = "%Y%m%d")

or

dfA['TradeDate'].astype(int).astype(str)\
    .apply(lambda x:datetime.datetime.strptime(x,'%Y%m%d'))


问:
How to detect input field value change in ng-repeat
I will have N number of input fields and every field will have a value CHANGE without getting in or out of focus. How can I detect value change of every input field.

I only found one question related and using that I tried following but it is not working. can Any one help further

for (var i=0;i<$scope.customers.product.length;i++)
{
//i m trying to get unique ids and bining input fields for change
$('#total-i').on('input', function() {
    alert($(this).val()); // get the current value of the input field.
});
}   ```
<pre class="snippet-code-html lang-html prettyprint-override"><code>//there will be multiple of input fields having unique ids
<input id="total-{{$index}}" value={{cust.price*cust.quantity}}"/></code>```

答:
It should be easy and possible with ng-change provided you have ng-model associated to input.

```<code><input id="total-{{$index}}" value={{cust.price*cust.quantity}}" ng-model="total" ng-change="updatemethod()"/>
</code>```

total and updatemethod() should be part of controller $scope.

Body:
I will have N number of input fields and every field will have a value CHANGE without getting in or out of focus. How can I detect value change of every input field.

I only found one question related and using that I tried following but it is not working. can Any one help further

for (var i=0;i<$scope.customers.product.length;i++)
{
//i m trying to get unique ids and bining input fields for change
$('#total-i').on('input', function() {
    alert($(this).val()); // get the current value of the input field.
});
}

//there will be multiple of input fields having unique ids
<input id="total-{{$index}}" value={{cust.price*cust.quantity}}"/>

Body:
It should be easy and possible with ng-change provided you have ng-model associated to input.

<input id="total-{{$index}}" value={{cust.price*cust.quantity}}" ng-model="total" ng-change="updatemethod()"/>

total and updatemethod() should be part of controller $scope.


问:
Go back to old revision in Bazaar
I want to go back in my bazaar history (change working tree) to find the commit that introduced a certain bug.

I do not want to delete any commits, just change my working tree until I found the bug, and then I want to go back to the latest revision to work on.

What are the two commands for that (going back to an earlier commit and afterwards checking out the latest revision again)?

Thanks in advance.

答:
you can use bzr log --forward to see your previous versions with DESC sorting

and you can use bzr revert -r for change your version to the

if you want to revert to the last version just do bzr revert

Title: Go back to old revision in Bazaar