问:
angular2 style guide - property with dollar sign?
Parent and children communicate via a service example from the official guide on Angular.io makes use of dollar signs in Observable stream names.

Notice missionAnnounced$ and missionConfirmed$ in the following example:

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable()
export class MissionService {

  // Observable string sources
  private missionAnnouncedSource = new Subject<string>();
  private missionConfirmedSource = new Subject<string>();

  // Observable string streams
  missionAnnounced$ = this.missionAnnouncedSource.asObservable();
  missionConfirmed$ = this.missionConfirmedSource.asObservable();

  // Service message commands
  announceMission(mission: string) {
    this.missionAnnouncedSource.next(mission);
  }

  confirmMission(astronaut: string) {
    this.missionConfirmedSource.next(astronaut);
  }
}
```

Can anyone explain:

why $ is used? What's the reason behind this notation? Do I always need to use this for public properties?

public properties are used but not methods (e.g. missionAnnouncements(), missionConfirmations()) - again, is this a convention for Angular2 apps?

答:
Update:
https://angular.io/guide/rx-library#naming-conventions-for-observables

Because Angular applications are mostly written in TypeScript, you will typically know when a variable is an observable. Although the Angular framework does not enforce a naming convention for observables, you will often see observables named with a trailing “$” sign.

This can be useful when scanning through code and looking for observable values. Also, if you want a property to store the most recent value from an observable, it can be convenient to simply use the same name with or without the “$”.

Original:

I saw variables end with $ when reading the official hero tutorial:

```<code><div id="search-component">
  <h4>Hero Search</h4>

  <input #searchBox id="search-box" (keyup)="search(searchBox.value)" />

  <ul class="search-result">
    <li *ngFor="let hero of heroes$ | async" >
      <a routerLink="/detail/{{hero.id}}">
        {{hero.name}}
      </a>
    </li>
  </ul>
</div>
</code>```

Look closely and you'll see that the *ngFor iterates over a list called heroes$, not heroes.

```<code><li *ngFor="let hero of heroes$ | async" >
</code>```

The $ is a convention that indicates heroes$ is an Observable, not an array.

Most cases are that we do not subscribe to those Observable variables in component. We usually use AsyncPipe to subscribe to the Observable variables automatically

I haven't found it in Style Guide since Angular5.1 has released yesterday(December 6th, 2017).

Body:
Parent and children communicate via a service example from the official guide on Angular.io makes use of dollar signs in Observable stream names.

Notice missionAnnounced$ and missionConfirmed$ in the following example:

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable()
export class MissionService {

  // Observable string sources
  private missionAnnouncedSource = new Subject<string>();
  private missionConfirmedSource = new Subject<string>();

  // Observable string streams
  missionAnnounced$ = this.missionAnnouncedSource.asObservable();
  missionConfirmed$ = this.missionConfirmedSource.asObservable();

  // Service message commands
  announceMission(mission: string) {
    this.missionAnnouncedSource.next(mission);
  }

  confirmMission(astronaut: string) {
    this.missionConfirmedSource.next(astronaut);
  }
}

Can anyone explain:

why $ is used? What's the reason behind this notation? Do I always need to use this for public properties?

public properties are used but not methods (e.g. missionAnnouncements(), missionConfirmations()) - again, is this a convention for Angular2 apps?

Body:
Update:
https://angular.io/guide/rx-library#naming-conventions-for-observables

Because Angular applications are mostly written in TypeScript, you will typically know when a variable is an observable. Although the Angular framework does not enforce a naming convention for observables, you will often see observables named with a trailing “$” sign.

This can be useful when scanning through code and looking for observable values. Also, if you want a property to store the most recent value from an observable, it can be convenient to simply use the same name with or without the “$”.

Original:

I saw variables end with $ when reading the official hero tutorial:

<div id="search-component">
  <h4>Hero Search</h4>

  <input #searchBox id="search-box" (keyup)="search(searchBox.value)" />

  <ul class="search-result">
    <li *ngFor="let hero of heroes$ | async" >
      <a routerLink="/detail/{{hero.id}}">
        {{hero.name}}
      </a>
    </li>
  </ul>
</div>

Look closely and you'll see that the *ngFor iterates over a list called heroes$, not heroes.

<li *ngFor="let hero of heroes$ | async" >

The $ is a convention that indicates heroes$ is an Observable, not an array.

Most cases are that we do not subscribe to those Observable variables in component. We usually use AsyncPipe to subscribe to the Observable variables automatically

I haven't found it in Style Guide since Angular5.1 has released yesterday(December 6th, 2017).


来源: stackexchange

问:
Merge collections in different databases in MongoDB
I have simple ranking system written in nodejs which is based on mongodb database. For each month system creates different database: ranking-1 for Janurary, ranking-2 for February etc.
Now I need to sum each user points from six months. From July to December.

In each database I have collection named users which contains user model which looks like this:

```<code>var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var UserSchema = new Schema({
    id: Number,
    name: String,
    points: Number,
    avatar: String,
    rank: String
});

module.exports = mongoose.model('User', UserSchema);
</code>```

Now I would like to find user by id and sum his points from six months and export this data to another database or collection.

Ranking for december is still updating so I need to process this task every 15 minutes.

I know there is map and reduce but if I understand it well it is working on collections at the same database?

Is there a way to merge this data or I need to rebuild whole system?

答:
There is no way using MongoDB to query data across databases.

And, frankly, unless you have really good reasons to go with that custom "by month" partitioning, I would not recommend doing so. So if you can change your system to keep everything in one database (and probably even one collection) then that's certainly the way to go.

However, I can think of a bunch of workarounds:

If it's really just a single sum that you need to calculate then you could write a small application that simply accesses all relevant 6 databases in a row to calculate the partial sums and then sums up the 6 return values into the final result. That should be trivial and would probably be the way to go (unless you can merge your databases)

You create some script that calls mongodump (probably with the query parameter to limit your data to what's really needed) to extract the information from your relevant databases/collections and mongorestore to restore them into a common database (ideally even into the same target collection). Then you can run normal queries against that new collection.

You could get Apache Spark, set up all your data sources and have Spark do the heavy lifting: https://databricks.com/blog/2015/03/20/using-mongodb-with-spark.html. That would be majorly over-complicating things unless you have Spark running anyway.

ContentLicense: CC BY-SA 3.0

Body:
I have simple ranking system written in nodejs which is based on mongodb database. For each month system creates different database: ranking-1 for Janurary, ranking-2 for February etc.
Now I need to sum each user points from six months. From July to December.

In each database I have collection named users which contains user model which looks like this:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var UserSchema = new Schema({
    id: Number,
    name: String,
    points: Number,
    avatar: String,
    rank: String
});

module.exports = mongoose.model('User', UserSchema);

Now I would like to find user by id and sum his points from six months and export this data to another database or collection.

Ranking for december is still updating so I need to process this task every 15 minutes.

I know there is map and reduce but if I understand it well it is working on collections at the same database?

Is there a way to merge this data or I need to rebuild whole system?


问:
Getting error while executing AsyncTask in Android App
I am Getting an error  java.lang.RuntimeException: An error occurred while executing doInBackground()  while executing

here is my doInBackground() method

```<code> @Override
    protected String doInBackground(String... strings) {

            AlertDialog.Builder rewardedAdvert = new AlertDialog.Builder(PlayGame.this);
            View rView = getLayoutInflater().inflate(R.layout.rewardedads, null);
            homeButton = (Button) rView.findViewById(R.id.homebutton);

            homeButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    gameOver();
                }
            });
            rewardedAdvert.setView(rView);

            AlertDialog dialog = rewardedAdvert.create();
          dialog.getWindow().setLayout(700, 700);

        return null;
    }
</code>```

here is the method where i am calling AsyncTask

```<code>  private void wrongAnswer() {
    correctImg.setVisibility(View.INVISIBLE);
    wrongImg.setVisibility(View.VISIBLE);
    ((LightQuiz) this.getApplicationContext()).soundHandler.playWrongSound();
    lives--;
    if (lives == 0) {

       new GameOverRewardedAds().execute();

      //  gameOver();

    }
</code>```

here is the logcat:

```<code>Java.lang.RuntimeException: An error occurred while executing doInBackground()
                                                                            at android.os.AsyncTask$3.done(AsyncTask.java:309)
                                                                            at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
                                                                            at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
                                                                            at java.util.concurrent.FutureTask.run(FutureTask.java:242)
                                                                            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
                                                                            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                                            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                                            at java.lang.Thread.run(Thread.java:818)
                                                                         Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
                                                                            at android.os.Handler.<init>(Handler.java:200)
                                                                            at android.os.Handler.<init>(Handler.java:114)
                                                                            at android.app.Dialog.<init>(Dialog.java:119)
                                                                            at android.app.AlertDialog.<init>(AlertDialog.java:200)
                                                                            at android.app.AlertDialog$Builder.create(AlertDialog.java:1086)
                                                                            at com.awwalsoft.javaplay.PlayGame$GameOverRewardedAds.doInBackground(PlayGame.java:429)
                                                                            at com.awwalsoft.javaplay.PlayGame$GameOverRewardedAds.doInBackground(PlayGame.java:387)
                                                                            at android.os.AsyncTask$2.call(AsyncTask.java:295)
                                                                            at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
                                                                            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                                            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                                            at java.lang.Thread.run(Thread.java:818)
</code>```

答:
Your doInBackground is not executing on the UI thread but on the different thread and you can't touch views created on UI thread  from background thread. Also, in your AsyncTask you are not doing anything that needs to be done in the background, so you can move all the stuff to your activity which runs on the UI thread.

Main reason for using AsyncTask is some lengthy job that would freeze your UI if it's done on the main thread. If you are just dealing with your views and performing short tasks then leave it on the main thread.

Body:
I am Getting an error  java.lang.RuntimeException: An error occurred while executing doInBackground()  while executing

here is my doInBackground() method

 @Override
    protected String doInBackground(String... strings) {

            AlertDialog.Builder rewardedAdvert = new AlertDialog.Builder(PlayGame.this);
            View rView = getLayoutInflater().inflate(R.layout.rewardedads, null);
            homeButton = (Button) rView.findViewById(R.id.homebutton);

            homeButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    gameOver();
                }
            });
            rewardedAdvert.setView(rView);

            AlertDialog dialog = rewardedAdvert.create();
          dialog.getWindow().setLayout(700, 700);

        return null;
    }

here is the method where i am calling AsyncTask

  private void wrongAnswer() {
    correctImg.setVisibility(View.INVISIBLE);
    wrongImg.setVisibility(View.VISIBLE);
    ((LightQuiz) this.getApplicationContext()).soundHandler.playWrongSound();
    lives--;
    if (lives == 0) {

       new GameOverRewardedAds().execute();

      //  gameOver();

    }

here is the logcat:

Java.lang.RuntimeException: An error occurred while executing doInBackground()
                                                                            at android.os.AsyncTask$3.done(AsyncTask.java:309)
                                                                            at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
                                                                            at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
                                                                            at java.util.concurrent.FutureTask.run(FutureTask.java:242)
                                                                            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
                                                                            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                                            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                                            at java.lang.Thread.run(Thread.java:818)
                                                                         Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
                                                                            at android.os.Handler.<init>(Handler.java:200)
                                                                            at android.os.Handler.<init>(Handler.java:114)
                                                                            at android.app.Dialog.<init>(Dialog.java:119)
                                                                            at android.app.AlertDialog.<init>(AlertDialog.java:200)
                                                                            at android.app.AlertDialog$Builder.create(AlertDialog.java:1086)
                                                                            at com.awwalsoft.javaplay.PlayGame$GameOverRewardedAds.doInBackground(PlayGame.java:429)
                                                                            at com.awwalsoft.javaplay.PlayGame$GameOverRewardedAds.doInBackground(PlayGame.java:387)
                                                                            at android.os.AsyncTask$2.call(AsyncTask.java:295)
                                                                            at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
                                                                            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                                            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                                            at java.lang.Thread.run(Thread.java:818)


问:
Does local method call wait for remote return value in java RMI?
I have a question about how local and remote methods cooperate in Java RMI.
Here's the ideal situation:

```<code>localClass.setValue(server.getValue());
</code>```

Does localClass.setValue(..) awaits for the return value from the server or do I have to make sure of it using some sort of synchronization in local?
What happens if the server needs like 5 seconds to execute getValue()?

答:
Not quite.

Arguments are evaluated left to right before the method is called.

So localClass.setValue() isn't even called until the parameter value returned by server.getValue() is available. So the client waits as long as that takes, and then calls localClass.setValue(). It isn't setValue() that does the waiting, it is the stub's call to server.getValue().

You don't have to do anything about it yourself.

Body:
I have a question about how local and remote methods cooperate in Java RMI.
Here's the ideal situation:

localClass.setValue(server.getValue());

Does localClass.setValue(..) awaits for the return value from the server or do I have to make sure of it using some sort of synchronization in local?
What happens if the server needs like 5 seconds to execute getValue()?

ContentLicense: CC BY-SA 4.0


问:
is it possible to retrieve all userID from firebase at one time?
I have a sets of data in firebase database and I wanted to retrieve all the userID, but not its content, just a list of userID will do. Anyone has done it before?</p>

答:
In what platform are you referring to? Assuming you are talking about java you can do something like that: </p>

```<code>     usersDatabaseRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for(Datasnapshot snap2 : dataSnapshot.getChildren()){
                   String userId = snap2.getKey();
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
</code>```

Body:
In what platform are you referring to? Assuming you are talking about java you can do something like that:

     usersDatabaseRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for(Datasnapshot snap2 : dataSnapshot.getChildren()){
                   String userId = snap2.getKey();
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });


问:
Selenium can not click on one element
I am using Selenium Chromedriver and my problem looks like this:

My program is clicking element on website and a list of elements appear.

Than it is choosing one of element from list using checkbox.

Nextly it is trying to click other element but the program crashes.

When the mentioned list appear if I am clicking anywhere on website using inspect option the code of inspected element looking like this:

```<code><div id="__selectOverlay" style="display: block;"></div>
</code>```

how can I click any element from website after the list appear?

答:
looking at the html snippet shared, "__selectOverlay" might be the overlay which comes on top of the web page(like a loading spinwheel/panel) .

To get rid of the error, you can try the following
 * Wait for panel/overlay to disappear
 * Close the panel , if there is a panel close button.

And then click on any element on the web page

Title: Selenium can not click on one element

Body:
I am using Selenium Chromedriver and my problem looks like this:

My program is clicking element on website and a list of elements appear.

Than it is choosing one of element from list using checkbox.

Nextly it is trying to click other element but the program crashes.

When the mentioned list appear if I am clicking anywhere on website using inspect option the code of inspected element looking like this:

how can I click any element from website after the list appear?


问:
Tkinter Grid Dynamic Layout
I am wanting to create a grid layout, with a grid that fills the first row until it runs out of space in the window, and will dynamically move items to the row below (like text line-wrapping).  As the window width is adjusted, the grid adjusts to fit.  The boxes resizing is not desired. I intend to maintain each small box's size, but change where the layout puts each box.

I imagine this functionality is possible by measuring the width of the frame, and if the (number of boxes)*(width of each box) exceeds the width, move to the next row.  I was just wondering if there was a better way built in that I'm not understanding.

If the above is the only option, what is the best way to update that? Do I have to set an event on window resize or something?  It seems like I shouldn't have to rework a layout manager, which is what that feels like.  I just want to check if similar functionality is already built in. Grid seems like a powerful layout manager, but I have not been able to find that option.

The below pics describes the behavior I want using the same set of 6 boxes on a single frame using grid layout.

Window is wide enough to hold all 6 boxes, so they all fit on row 1. They then adjust as window size changes.

答:
Here's a working example: </p>

```<code>import Tkinter as tk

class AutoGrid(tk.Frame):
    def __init__(self, master=None, **kwargs):
        tk.Frame.__init__(self, master, **kwargs)
        self.columns = None
        self.bind('<Configure>', self.regrid)

    def regrid(self, event=None):
        width = self.winfo_width()
        slaves = self.grid_slaves()
        max_width = max(slave.winfo_width() for slave in slaves)
        cols = width // max_width
        if cols == self.columns: # if the column number has not changed, abort
            return
        for i, slave in enumerate(slaves):
            slave.grid_forget()
            slave.grid(row=i//cols, column=i%cols)
        self.columns = cols

class TestFrame(tk.Frame):
    def __init__(self, master=None, **kwargs):
        tk.Frame.__init__(self, master, bd=5, relief=tk.RAISED, **kwargs)

        tk.Label(self, text="name").pack(pady=10)
        tk.Label(self, text=" info ........ info ").pack(pady=10)
        tk.Label(self, text="data\n"*5).pack(pady=10)

def main():
    root = tk.Tk()
    frame = AutoGrid(root)
    frame.pack(fill=tk.BOTH, expand=True)

    TestFrame(frame).grid() # use normal grid parameters to set up initial layout
    TestFrame(frame).grid(column=1)
    TestFrame(frame).grid(column=2)
    TestFrame(frame).grid()
    TestFrame(frame).grid()
    TestFrame(frame).grid()
    root.mainloop()

if __name__ == '__main__':
    main()
</code>```

<p>Note this will ruin the rowspan and columnspan features of the grid manager. </p>

Title: Tkinter Grid Dynamic Layout

Body:
Here's a working example:

import Tkinter as tk

class AutoGrid(tk.Frame):
    def __init__(self, master=None, **kwargs):
        tk.Frame.__init__(self, master, **kwargs)
        self.columns = None
        self.bind('<Configure>', self.regrid)

    def regrid(self, event=None):
        width = self.winfo_width()
        slaves = self.grid_slaves()
        max_width = max(slave.winfo_width() for slave in slaves)
        cols = width // max_width
        if cols == self.columns: # if the column number has not changed, abort
            return
        for i, slave in enumerate(slaves):
            slave.grid_forget()
            slave.grid(row=i//cols, column=i%cols)
        self.columns = cols

class TestFrame(tk.Frame):
    def __init__(self, master=None, **kwargs):
        tk.Frame.__init__(self, master, bd=5, relief=tk.RAISED, **kwargs)

        tk.Label(self, text="name").pack(pady=10)
        tk.Label(self, text=" info ........ info ").pack(pady=10)
        tk.Label(self, text="data\n"*5).pack(pady=10)

def main():
    root = tk.Tk()
    frame = AutoGrid(root)
    frame.pack(fill=tk.BOTH, expand=True)

    TestFrame(frame).grid() # use normal grid parameters to set up initial layout
    TestFrame(frame).grid(column=1)
    TestFrame(frame).grid(column=2)
    TestFrame(frame).grid()
    TestFrame(frame).grid()
    TestFrame(frame).grid()
    root.mainloop()

if __name__ == '__main__':
    main()

Note this will ruin the rowspan and columnspan features of the grid manager.


问:
Laravel says file does not exist but it does
I have this line:

```<code>$local_document_path = storage_path() . "/app/file/myfile.pdf";

$myfile = Storage::get($local_document_path);
</code>```

And I get a FileNotFoundException error.

Now I checked the variable and seems correct, and I double checked again by copying the path to clipboard and pasting it:

```<code>dd($local_document_path == $copypasted_path)
</code>```

It returns true. This means that the path is 100% correct, yet it does not work with storage. I have also tried by removing storage_path(); and it does not work either.

Any help?

Thanks in advance.

答: Your Storage::get calls should use a path relative to the root of the storage disk. The default storage disk is configured to be storage_path('app'), so you'll need Storage::get('file/myfile.pdf').

Body:
I have this line:

$local_document_path = storage_path() . "/app/file/myfile.pdf";

$myfile = Storage::get($local_document_path);

And I get a FileNotFoundException error.

Now I checked the variable and seems correct, and I double checked again by copying the path to clipboard and pasting it:

dd($local_document_path == $copypasted_path)

It returns true. This means that the path is 100% correct, yet it does not work with storage. I have also tried by removing storage_path(); and it does not work either.

Any help?

Thanks in advance.


问:
Exception during generic container clearing, C++
I am having problems with clearing of the generic container. In carrying out the function clear() the program fails.

Base class:

```<code>//Generic container
template <class Item>
struct TList
{
    typedef std::vector <Item> Type;
};

template <class Item>
class GContainer
{
protected:
            typename TList <Item>::Type items;

public:
            GContainer() : items (0) {}
    virtual ~GContainer() = 0;

public:
            typename TList <Item>::Type ::iterator begin() { return items.begin(); }
            typename TList <Item>::Type ::iterator end() { return items.end(); }
...
};
</code>```

Derived class:

```<code>//Generic container for points
template <class Point>
class ContPoints : public GContainer <Point>
{
public:
    void clear();
            ...
};

//Specialization
template <class Point>
class ContPoints <Point *> : public GContainer <Point>
{
public:
    void clear();
            ...
};
</code>```

Implementation of the method clear()

```<code>template <class Point>
void ContPoints <Point *>::clear()
{
        for ( typename TItemsList <Point>::Type ::iterator i_items = items.begin(); i_items != items.end(); ++i_items )
        {
                //Delete each node
                if ( &(i_items) != NULL )
                {
                          delete * i_items //Compile error, not usable, why ???
                          delete &*i_items; //Usable, but exception
                  *i_items) = 0; //Than exception
                }
        }
        items.clear(); //vector clear
}
</code>```

Suprisingly:

A] I am not able to delete *i_items...

```<code>delete *i_items; //Error C2440: 'delete' : cannot convert from 'Point<T>' to 'void *
</code>```

B] I am able to delete only &*i_items...

```<code>int _tmain(int argc, _TCHAR* argv[])
{
  ContPoints <Point<double> *> pll;
  pll.push_back (new Point <double>(0,0));
  pll.push_back (new Point <double>(10,10));
  pll.clear(); //Exception
  return 0;
}
</code>```

Thanks for your help...

答:
delete &*i_items; should be delete *i_items;. You don't want to delete the address of the pointer, you want to delete the pointer! I don't see a reason for the following line (*i_items) = 0; //Exception) at all.

Finally, why insert points by pointer? Just insert the actual points and use std::vector instead. If you want containers which automatically delete their contents, consider boost pointer containers.

ContentLicense: CC BY-SA 2.5

Body:
I am having problems with clearing of the generic container. In carrying out the function clear() the program fails.

Base class:

//Generic container
template <class Item>
struct TList
{
    typedef std::vector <Item> Type;
};

template <class Item>
class GContainer
{
protected:
            typename TList <Item>::Type items;

public:
            GContainer() : items (0) {}
    virtual ~GContainer() = 0;

public:
            typename TList <Item>::Type ::iterator begin() { return items.begin(); }
            typename TList <Item>::Type ::iterator end() { return items.end(); }
...
};

Derived class:

//Generic container for points
template <class Point>
class ContPoints : public GContainer <Point>
{
public:
    void clear();
            ...
};

//Specialization
template <class Point>
class ContPoints <Point *> : public GContainer <Point>
{
public:
    void clear();
            ...
};

Implementation of the method clear()

template <class Point>
void ContPoints <Point *>::clear()
{
        for ( typename TItemsList <Point>::Type ::iterator i_items = items.begin(); i_items != items.end(); ++i_items )
        {
                //Delete each node
                if ( &(i_items) != NULL )
                {
                          delete * i_items //Compile error, not usable, why ???
                          delete &*i_items; //Usable, but exception
                  *i_items) = 0; //Than exception
                }
        }
        items.clear(); //vector clear
}

Suprisingly:

A] I am not able to delete *i_items...

delete *i_items; //Error C2440: 'delete' : cannot convert from 'Point<T>' to 'void *

B] I am able to delete only &*i_items...

int _tmain(int argc, _TCHAR* argv[])
{
  ContPoints <Point<double> *> pll;
  pll.push_back (new Point <double>(0,0));
  pll.push_back (new Point <double>(10,10));
  pll.clear(); //Exception
  return 0;
}

Thanks for your help...


问:
Constantly Updating JavaFX GUI
I'm currently working on a project where I convert the time into base 10 time (essentially it will end up displaying a percentage of the day that has passed. ex: 12:00 noon would be displayed as 50.00 in base 10 time). Currently, I know my algorithm is correct since it prints out correctly if I print it to the console, but for some reason, I can't get my GUI to display. If I get rid of the part where I attempt to constantly update the GUI to display the correct numbers, the GUI displays fine, but with no numbers. My code is as follows:

```<code>package ClockPackage;

import java.util.Calendar;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class ClockView extends Application {
    Pane background;
    static Text firstDigit;
    static Text secondDigit;
    static Text thirdDigit;
    static Text fourthDigit;
    Text middleDecimal;

    /* Sets the first digit of the base 10 time to the passed through char. */
    static void setFirstDigit(char x1) {
        String digitString = "";
        digitString += x1;
        firstDigit.setText(digitString);
    }

    /* Sets the second digit of the base 10 time to the passed through char. */
    static void setSecondDigit(char x2) {
        String digitString = "";
        digitString += x2;
        secondDigit.setText(digitString);
    }

    /* Sets the third digit of the base 10 time to the passed through char. */
    static void setThirdDigit(char y1) {
        String digitString = "";
        digitString += y1;
        thirdDigit.setText(digitString);
    }

    /* Sets the fourth digit of the base 10 time to the passed through char. */
    static void setFourthDigit(char y2) {
        String digitString = "";
        digitString += y2;
        fourthDigit.setText(digitString);
    }

    /* Main Method that Launches the GUI */
    public static void main(String[] args) {
        Application.launch(args);

    }

    @Override
    public void start(Stage primaryStage) throws Exception {
            final double TEXTFIELD_LAYOUT_Y = 200;

            //Background Pane
            background = new Pane();

            //First digit textField
            firstDigit = new Text();
            firstDigit.setLayoutX(17);
            firstDigit.setLayoutY(TEXTFIELD_LAYOUT_Y);
            firstDigit.setStyle("-fx-font-size: 96pt;");

            //Second digit textField
            secondDigit = new Text();
            secondDigit.setLayoutX(117);
            secondDigit.setLayoutY(TEXTFIELD_LAYOUT_Y);
            secondDigit.setStyle("-fx-font-size: 96pt;");

            //Middle decimal
            middleDecimal = new Text(".");
            middleDecimal.setLayoutX(219);
            middleDecimal.setLayoutY(210);
            middleDecimal.setStyle("-fx-font-size: 72pt;");

            //Third digit textField
            thirdDigit = new Text();
            thirdDigit.setLayoutX(250);
            thirdDigit.setLayoutY(TEXTFIELD_LAYOUT_Y);
            thirdDigit.setStyle("-fx-font-size: 96pt;");

            //Fourth digit textField
            fourthDigit = new Text();
            fourthDigit.setLayoutX(362);
            fourthDigit.setLayoutY(TEXTFIELD_LAYOUT_Y);
            fourthDigit.setStyle("-fx-font-size: 96pt;");

            /* Adding the Nodes to the Pane */
            background.getChildren().addAll(firstDigit, secondDigit, middleDecimal, thirdDigit, fourthDigit);

            /* Setting the Scene */
            Scene scene = new Scene(background, 470, 258);
            primaryStage.setTitle("Base 10 Clock");
            primaryStage.setScene(scene);
            primaryStage.show();

            /*
             * Calculates the time in base 10 time and calls the 4 methods
             * to set the GUI display.
             *
             * In a constant while loop in order to continuously update
             * the GUI.
             */
            Calendar now;
            double currentTime;
            String timeString;
            long timestamp;
            while(true) {
                /* Sleep for 8.64 seconds since that is how long it is between
                increments of 0.01 in base 10 time. */
                Thread.sleep(8640);
                now = Calendar.getInstance();
                timestamp = now.get(Calendar.HOUR_OF_DAY)*60*60 + now.get(Calendar.MINUTE)*60 + now.get(Calendar.SECOND);
                currentTime = timestamp/86400.0;
                timeString = "" + currentTime;
                setFirstDigit(timeString.charAt(2));
                setSecondDigit(timeString.charAt(3));
                setThirdDigit(timeString.charAt(4));
                setFourthDigit(timeString.charAt(5));
            }
    }
}
</code>```

Does anyone have any idea how I would go about making the GUI both show up and update the numbers constantly? I can't figure out how to get it to do both. I've seen where people use buttons to update data, but I haven't seen where the display is constantly automatically updated.

Thanks!

答:
You should replace the while(true) loop with a new thread or a service call with another thread.  The main thread is already responsible for updating the UI, so when you have some kind of blocking (IO, loops that take a long time, etc...), it will prevent the UI thread from updating.

Link to the Service interface

Create a service:

```<code>public static class TimeService extends Service<String> {

    protected Task createTask() {
        return new Task<String>() {
            protected String call() throws Exception {
                // TODO: Do work - return the date/time as a String
                // If you need a Thread.sleep, use a spawn a new thread
            }
        };
    }
}
</code>```

Then in your controller:

```<code>TimeService timeService = new TimeService();
timeService.restart();
</code>```

You could also do all sorts of things like binding UI elements to properties in the TimeService (that way the UI will "just update" as the service is running).

Title: Constantly Updating JavaFX GUI

Body:
I'm currently working on a project where I convert the time into base 10 time (essentially it will end up displaying a percentage of the day that has passed. ex: 12:00 noon would be displayed as 50.00 in base 10 time). Currently, I know my algorithm is correct since it prints out correctly if I print it to the console, but for some reason, I can't get my GUI to display. If I get rid of the part where I attempt to constantly update the GUI to display the correct numbers, the GUI displays fine, but with no numbers. My code is as follows:

package ClockPackage;

import java.util.Calendar;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class ClockView extends Application {
    Pane background;
    static Text firstDigit;
    static Text secondDigit;
    static Text thirdDigit;
    static Text fourthDigit;
    Text middleDecimal;

    /* Sets the first digit of the base 10 time to the passed through char. */
    static void setFirstDigit(char x1) {
        String digitString = "";
        digitString += x1;
        firstDigit.setText(digitString);
    }

    /* Sets the second digit of the base 10 time to the passed through char. */
    static void setSecondDigit(char x2) {
        String digitString = "";
        digitString += x2;
        secondDigit.setText(digitString);
    }

    /* Sets the third digit of the base 10 time to the passed through char. */
    static void setThirdDigit(char y1) {
        String digitString = "";
        digitString += y1;
        thirdDigit.setText(digitString);
    }

    /* Sets the fourth digit of the base 10 time to the passed through char. */
    static void setFourthDigit(char y2) {
        String digitString = "";
        digitString += y2;
        fourthDigit.setText(digitString);
    }

    /* Main Method that Launches the GUI */
    public static void main(String[] args) {
        Application.launch(args);

    }

    @Override
    public void start(Stage primaryStage) throws Exception {
            final double TEXTFIELD_LAYOUT_Y = 200;

            //Background Pane
            background = new Pane();

            //First digit textField
            firstDigit = new Text();
            firstDigit.setLayoutX(17);
            firstDigit.setLayoutY(TEXTFIELD_LAYOUT_Y);
            firstDigit.setStyle("-fx-font-size: 96pt;");

            //Second digit textField
            secondDigit = new Text();
            secondDigit.setLayoutX(117);
            secondDigit.setLayoutY(TEXTFIELD_LAYOUT_Y);
            secondDigit.setStyle("-fx-font-size: 96pt;");

            //Middle decimal
            middleDecimal = new Text(".");
            middleDecimal.setLayoutX(219);
            middleDecimal.setLayoutY(210);
            middleDecimal.setStyle("-fx-font-size: 72pt;");

            //Third digit textField
            thirdDigit = new Text();
            thirdDigit.setLayoutX(250);
            thirdDigit.setLayoutY(TEXTFIELD_LAYOUT_Y);
            thirdDigit.setStyle("-fx-font-size: 96pt;");

            //Fourth digit textField
            fourthDigit = new Text();
            fourthDigit.setLayoutX(362);
            fourthDigit.setLayoutY(TEXTFIELD_LAYOUT_Y);
            fourthDigit.setStyle("-fx-font-size: 96pt;");

            /* Adding the Nodes to the Pane */
            background.getChildren().addAll(firstDigit, secondDigit, middleDecimal, thirdDigit, fourthDigit);

            /* Setting the Scene */
            Scene scene = new Scene(background, 470, 258);
            primaryStage.setTitle("Base 10 Clock");
            primaryStage.setScene(scene);
            primaryStage.show();

            /*
             * Calculates the time in base 10 time and calls the 4 methods
             * to set the GUI display.
             *
             * In a constant while loop in order to continuously update
             * the GUI.
             */
            Calendar now;
            double currentTime;
            String timeString;
            long timestamp;
            while(true) {
                /* Sleep for 8.64 seconds since that is how long it is between
                increments of 0.01 in base 10 time. */
                Thread.sleep(8640);
                now = Calendar.getInstance();
                timestamp = now.get(Calendar.HOUR_OF_DAY)*60*60 + now.get(Calendar.MINUTE)*60 + now.get(Calendar.SECOND);
                currentTime = timestamp/86400.0;
                timeString = "" + currentTime;
                setFirstDigit(timeString.charAt(2));
                setSecondDigit(timeString.charAt(3));
                setThirdDigit(timeString.charAt(4));
                setFourthDigit(timeString.charAt(5));
            }
    }
}

Does anyone have any idea how I would go about making the GUI both show up and update the numbers constantly? I can't figure out how to get it to do both. I've seen where people use buttons to update data, but I haven't seen where the display is constantly automatically updated.

Thanks!

Body:
You should replace the while(true) loop with a new thread or a service call with another thread.  The main thread is already responsible for updating the UI, so when you have some kind of blocking (IO, loops that take a long time, etc...), it will prevent the UI thread from updating.

Link to the Service interface

Create a service:

public static class TimeService extends Service<String> {

    protected Task createTask() {
        return new Task<String>() {
            protected String call() throws Exception {
                // TODO: Do work - return the date/time as a String
                // If you need a Thread.sleep, use a spawn a new thread
            }
        };
    }
}

Then in your controller:

TimeService timeService = new TimeService();
timeService.restart();

You could also do all sorts of things like binding UI elements to properties in the TimeService (that way the UI will "just update" as the service is running).


问:
Gensim Library not recognized in Jupyter notebook
I have a bIg data platform. On that I install Anaconda. When I ssh to my account on the platform and open up a Python interpreter in terminal it works fine when I import the gensim library. I had earlier installed this library using

```<code>Conda install gensim

$ python
Python 2.7.12 |Anaconda 2.5.0 (64-bit)| (default, Jul  2 2016, 17:42:40)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
Anaconda is brought to you by Continuum Analytics.
Please check out: http://continuum.io/thanks and https://anaconda.org
>>> import gensim
/home/anaconda2/lib/python2.7/site-packages/gensim/utils.py:1015: UserWarning: Pattern library is not installed, lemmatization won't be available.
  warnings.warn("Pattern library is not installed, lemmatization won't be available.")
</code>```

If you see it does import the library (just gives some warning for Pattern library). However when I open up Jupyter notebook and try to import the same library there it gives the following:

```<code>In [11]:

import gensim
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-11-0539d76422c6> in <module>()
----> 1 import gensim

ImportError: No module named gensim
</code>```

Am not sure why the same library which is installed is not working in Jupyter. Please note that when I do

```<code>pip list
</code>```

it shows me all the libraries and it has gensim there.

答:
pip list will not show you conda modules
try conda list to ensure you have the gensim module installed

EDIT:

Also ensure your kernelspec and the python interpreter are pointing to the same enviroment

http://jupyter-client.readthedocs.io/en/stable/api/kernelspec.html

Body:
I have a bIg data platform. On that I install Anaconda. When I ssh to my account on the platform and open up a Python interpreter in terminal it works fine when I import the gensim library. I had earlier installed this library using

Conda install gensim

$ python
Python 2.7.12 |Anaconda 2.5.0 (64-bit)| (default, Jul  2 2016, 17:42:40)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
Anaconda is brought to you by Continuum Analytics.
Please check out: http://continuum.io/thanks and https://anaconda.org
>>> import gensim
/home/anaconda2/lib/python2.7/site-packages/gensim/utils.py:1015: UserWarning: Pattern library is not installed, lemmatization won't be available.
  warnings.warn("Pattern library is not installed, lemmatization won't be available.")

If you see it does import the library (just gives some warning for Pattern library). However when I open up Jupyter notebook and try to import the same library there it gives the following:

In [11]:

import gensim
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-11-0539d76422c6> in <module>()
----> 1 import gensim

ImportError: No module named gensim

Am not sure why the same library which is installed is not working in Jupyter. Please note that when I do

pip list

it shows me all the libraries and it has gensim there.


问:
Fastest way to zero out a range of positions of an array?
I have an array which I wish to assign zeros to all positions in a given range (positions 10 to 24, in this case). I'm doing this:

```<code>ulong st[25];
...
for(int i = 10; i < 25; ++i) st[i] = 0x00UL;
</code>```

Is this the fastest way to do that? It seems that there should be a faster way without a loop, given that it's a contiguous position in memory, but I don't know what that would be (perhaps XORing that memory space with itself? If so, how would I do that?)

Any ideas?

答:
You could use memset()for that: http://man7.org/linux/man-pages/man3/memset.3.html

Might be the same thing under the covers though.

Body:
I have an array which I wish to assign zeros to all positions in a given range (positions 10 to 24, in this case). I'm doing this:

ulong st[25];
...
for(int i = 10; i < 25; ++i) st[i] = 0x00UL;

Is this the fastest way to do that? It seems that there should be a faster way without a loop, given that it's a contiguous position in memory, but I don't know what that would be (perhaps XORing that memory space with itself? If so, how would I do that?)

Any ideas?


问:
Displaying Hexadecimal numbers
We would display Hexadecimals in A03Eh format which A=10 & E=14, and A is a nibble. But I have seen another display like this : 0x002314A8 , How can we convert the above number into this format ? what is this format ?</p>

答:
Write a function that takes an integer and returns a string in that format.  Then call it like this:

```<code>std::cout << toHex(0xA03E);
</code>```

It shouldn't be that difficult a function to write.  Using the ios::hex manipulator will display your number in the 0x format.  Is that what you wanted?

Title: Displaying Hexadecimal numbers

Body:
Write a function that takes an integer and returns a string in that format.  Then call it like this:

std::cout << toHex(0xA03E);

It shouldn't be that difficult a function to write.  Using the ios::hex manipulator will display your number in the 0x format.  Is that what you wanted?


问:
javascript replace text inside of parenthases
I'm trying to replace text inside of parenthases with the same text surrounded by my text between parenthases

```<code>text.replace(/\[([^\][]+)]/g, "<span class='font-weight-bold underline'>$1</span>")
</code>```

so If I have this is my [name]
It replaces it to this is my name

I need something similar for parentheses.

How can I replace text globally between parentheses? It's not a simple as I thought it would be.

答: Replace your regex with text.replace(/\(([^\][]+)\) */g, "$1");

Body:
I'm trying to replace text inside of parenthases with the same text surrounded by my text between parenthases

text.replace(/\[([^\][]+)]/g, "$1")

so If I have this is my [name]
It replaces it to this is my name

I need something similar for parentheses.

How can I replace text globally between parentheses? It's not a simple as I thought it would be.

Body: Replace your regex with text.replace(/\(([^\][]+)\) */g, "<span class='font-weight-bold underline'>$1</span>");


问:
How to format time intervals for user display (social network like) in swift?
I have a time interval, say, 12600, which is equivalent to 3 hours 30 minutes. How could I format any such time interval so that only the highest part of the interval (for example in this case figure, the hours) is kept and have the correct locale abbreviation be appended to the number. For example 10m (10 minutes), 3d (3 days), 1y (1 years).

EDIT: Here are some examples:

```
Time interval in: 90000    Whole string: 1d      String out: 1d
Time interval in: 900      Whole string: 15m     String out: 15m
Time interval in: 13500    Whole String: 3h 45m  String out: 4h
```

As a general rule, apply the normal rounding rules (3.4 rounds down, 3.6 rounds up).

答:
Just in case anyone wants it.. Swift 4

```<code>extension TimeInterval {
    func format(using units: NSCalendar.Unit) -> String? {
        let formatter = DateComponentsFormatter()
        formatter.allowedUnits = units
        formatter.unitsStyle = .abbreviated
        formatter.zeroFormattingBehavior = .pad

        return formatter.string(from: self)
    }
}
</code>```

Example usage:

```<code>let value:TimeInterval =  12600.0
print("\(value.format(using: [.hour, .minute, .second])!)")
</code>```

and the result will be:

```<code>3h 30m 0s
</code>```

Body:
I have a time interval, say, 12600, which is equivalent to 3 hours 30 minutes. How could I format any such time interval so that only the highest part of the interval (for example in this case figure, the hours) is kept and have the correct locale abbreviation be appended to the number. For example 10m (10 minutes), 3d (3 days), 1y (1 years).

EDIT: Here are some examples:

Time interval in: 90000    Whole string: 1d      String out: 1d
Time interval in: 900      Whole string: 15m     String out: 15m
Time interval in: 13500    Whole String: 3h 45m  String out: 4h

As a general rule, apply the normal rounding rules (3.4 rounds down, 3.6 rounds up).

Body:
Just in case anyone wants it.. Swift 4

extension TimeInterval {
    func format(using units: NSCalendar.Unit) -> String? {
        let formatter = DateComponentsFormatter()
        formatter.allowedUnits = units
        formatter.unitsStyle = .abbreviated
        formatter.zeroFormattingBehavior = .pad

        return formatter.string(from: self)
    }
}

Example usage:

let value:TimeInterval =  12600.0
print("\(value.format(using: [.hour, .minute, .second])!)")

and the result will be:

3h 30m 0s


问:
Datagridview Invisible Columns - accessing data
Having set up a datagridview, bound to a bindingsource, I have to use the cellformatting to paint the cells various colours.

Since you cannot access a field or record via bindingsource on a cellformatting event, the only way I could access the data, is through a column such as the primary ID for example. (this is only for cellformatting, i have no problem accessing the ID through the bindignsource.current object).

So, once I have finished designing and testing my datagridview, I then switch various columns (ID) for this example, to visible=false to make the column invisible.

I now cannot access the column data through cellformatting. I have read on a number of pages listed by google that since datagridview doesnt render the columns, the values are unobtainable aside from a couple of alternatives such as :
.TAG
and datakeynames

I cannot find datakeynames under datagridview for winforms for some reason.
.tag doesnt seem to do anything as far as I can tell.

Since trying to use this from the cell formatting, I am unable to use

```<code>Select Case .Columns(e.ColumnIndex).DataPropertyName.ToLower
</code>```

or

```<code>If Datagridview1.columns(e.columnindex).datapropertyname.tolower='id' Then
</code>```

as the column is invisible...

Shame I cannot access the bindingsource through cellformatting, but there must be a way and there must be others who have had this issue.

答:
Use DataBoundItem:

```<code>Dim drw As DataRow = DirectCast(DataGridView1.Rows(i).DataBoundItem, DataRowView).Row
</code>```

(Assuming you've bound to a DataTable)

Body:
Having set up a datagridview, bound to a bindingsource, I have to use the cellformatting to paint the cells various colours.

Since you cannot access a field or record via bindingsource on a cellformatting event, the only way I could access the data, is through a column such as the primary ID for example. (this is only for cellformatting, i have no problem accessing the ID through the bindignsource.current object).

So, once I have finished designing and testing my datagridview, I then switch various columns (ID) for this example, to visible=false to make the column invisible.

I now cannot access the column data through cellformatting. I have read on a number of pages listed by google that since datagridview doesnt render the columns, the values are unobtainable aside from a couple of alternatives such as :
.TAG
and datakeynames

I cannot find datakeynames under datagridview for winforms for some reason.
.tag doesnt seem to do anything as far as I can tell.

Since trying to use this from the cell formatting, I am unable to use

Select Case .Columns(e.ColumnIndex).DataPropertyName.ToLower

or

If Datagridview1.columns(e.columnindex).datapropertyname.tolower='id' Then

as the column is invisible...

Shame I cannot access the bindingsource through cellformatting, but there must be a way and there must be others who have had this issue.

Body:
Use DataBoundItem:

Dim drw As DataRow = DirectCast(DataGridView1.Rows(i).DataBoundItem, DataRowView).Row

(Assuming you've bound to a DataTable)


问:
Is there any purpose to `bind()` unix domain socket client processes?
When using AF_UNIX (unix domain sockets), is there any application to calling bind() in a process that never calls listen()?

In my systems programming lecture and lab, we are instructed to callbind() on a unix domain socket client processes. Is there any documented, undocumented, or practical application to calling bind on a client-only unix domain socket  process? From my understanding bind() creates the special socket file, which is a responsibility a server process would undertake. Is this correct?

Here is an example code based off of what concepts discussed in class:

server.c

```<code>#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>

int main() {
    int s0, s1;
    struct sockaddr sa0 = {AF_UNIX, "a"};

    s0 = socket(AF_UNIX, SOCK_STREAM, 0);

    bind(s0, &sa0, sizeof(sa0) + sizeof("a"));
    listen(s0, 1);
    for (;;) {
        s1 = accept(s0, NULL, NULL);
        puts("connected!");
        for (;;) {
            char text[1];
            ssize_t n = read(s1, &text, sizeof(text));
            if (n < 1) {
                break;
            }
            putchar(text[0]);
        }
        close(s1);
    }
    close(s0);
    unlink("a");
    return 0;
}
</code>```

client.c

```<code>#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>

int main() {
    int s0;
    struct sockaddr sa0 = {AF_UNIX, "b"};
    struct sockaddr sa1 = {AF_UNIX, "a"};
    socklen_t sa1_len;

    s0 = socket(AF_UNIX, SOCK_STREAM, 0);
    bind(s0, &sa0, sizeof(sa0) + sizeof("b")); // What does this do??
    connect(s0, &sa1, sizeof(sa1) + sizeof("b"));
    for (;;) {
        int c = fgetc(stdin);
        if (c == EOF) {
            break;
        }
        write(s0, &c, sizeof(c));
    }
    close(s0);
    unlink("b");
    return 0;
}
</code>```

答:
Calling bind() on a Unix-domain socket, with no intention of ever calling accept(), is a very useful way of assuring only one copy of a process is running.  It's a lot more robust than relying on a process name, as binaries can be copied and run under another name.

Cleanup on abnormal termination (SIGSEGV, being the target of kill -9 ...) is a problem, though. as the socket won't be removed unless your application does it in a signal handler.

Body:
When using AF_UNIX (unix domain sockets), is there any application to calling bind() in a process that never calls listen()?

In my systems programming lecture and lab, we are instructed to callbind() on a unix domain socket client processes. Is there any documented, undocumented, or practical application to calling bind on a client-only unix domain socket  process? From my understanding bind() creates the special socket file, which is a responsibility a server process would undertake. Is this correct?

Here is an example code based off of what concepts discussed in class:

server.c

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>

int main() {
    int s0, s1;
    struct sockaddr sa0 = {AF_UNIX, "a"};

    s0 = socket(AF_UNIX, SOCK_STREAM, 0);

    bind(s0, &sa0, sizeof(sa0) + sizeof("a"));
    listen(s0, 1);
    for (;;) {
        s1 = accept(s0, NULL, NULL);
        puts("connected!");
        for (;;) {
            char text[1];
            ssize_t n = read(s1, &text, sizeof(text));
            if (n < 1) {
                break;
            }
            putchar(text[0]);
        }
        close(s1);
    }
    close(s0);
    unlink("a");
    return 0;
}

client.c

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>

int main() {
    int s0;
    struct sockaddr sa0 = {AF_UNIX, "b"};
    struct sockaddr sa1 = {AF_UNIX, "a"};
    socklen_t sa1_len;

    s0 = socket(AF_UNIX, SOCK_STREAM, 0);
    bind(s0, &sa0, sizeof(sa0) + sizeof("b")); // What does this do??
    connect(s0, &sa1, sizeof(sa1) + sizeof("b"));
    for (;;) {
        int c = fgetc(stdin);
        if (c == EOF) {
            break;
        }
        write(s0, &c, sizeof(c));
    }
    close(s0);
    unlink("b");
    return 0;
}


问:
Oauth: Redirect url has https, but original website is on http
Here is the issue:

Website(Some clients login as http and some as https) = http://www.example.com

Dropbox redirect needs to be https://www.example.com (Dropbox does not allow redirect urls to be http)

If my website is https://www.example.com it all works great. But for some clients it is http. I am okay with redirect = https, but it should come back to my http page after user logs in via popup window.

Any suggestions how to do this?

Here is my code:

```<code>this._oauthSignIn(url, dropboxRedirect).then(
    lang.hitch(this, function (oauthSignInUrl) {
      this._getTokenValue(oauthSignInUrl, 'access_token').then(
        lang.hitch(this, function (accessToken) {
          dfd.resolve(accessToken);
        })
      );
    })
  );

_oauthSignIn: function (url, redirect_uri) {
  var dfd = new Deferred();
  var win = window.open(url, "_blank", 'width=800, height=600');
  win.focus();
  var pollTimer = window.setInterval(function () {
    try {
      if (win.document.URL.indexOf(redirect_uri) != -1) {
        window.clearInterval(pollTimer);
        win.close();
        dfd.resolve(win.document.URL);
      }
    } catch(e) {
    }
  },100);
  return dfd;
},

_getTokenValue: function (url, name) {
  var dfd = new Deferred();
  name = name.replace(/[[]/,"\[").replace(/[]]/,"\]");
  var regexS = "[\?&#]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( url );
  if( results == null )
      dfd.resolve("");
  else
      dfd.resolve(results[1]);
  return dfd;
},
</code>```

答:
Got this to work, so posting the workaround for this use case.

Using this example:
Customer page: www.abc.example.com/something.html

Oauth redirect page = www.example.com/oauthTest.html

Hidden Iframe = www.example.com/iframe.html

Create a hidden iframe on the customer page. This hidden iframe when called, starts popup.
When user clicks on login with dropbox, the hidden iframe opens the oauth popup. Since hidden iframe and oauth popup are on same domain this works fine, and they can cross communicate.
Once you get token on the hidden iframe, send it to customer page via postmessage.
Now you have the token to work with in your application.
Add protection around iframe, so only your application can call it.

Body:
Here is the issue:

Website(Some clients login as http and some as https) = http://www.example.com

Dropbox redirect needs to be https://www.example.com (Dropbox does not allow redirect urls to be http)

If my website is https://www.example.com it all works great. But for some clients it is http. I am okay with redirect = https, but it should come back to my http page after user logs in via popup window.

Any suggestions how to do this?

Here is my code:

this._oauthSignIn(url, dropboxRedirect).then(
    lang.hitch(this, function (oauthSignInUrl) {
      this._getTokenValue(oauthSignInUrl, 'access_token').then(
        lang.hitch(this, function (accessToken) {
          dfd.resolve(accessToken);
        })
      );
    })
  );

_oauthSignIn: function (url, redirect_uri) {
  var dfd = new Deferred();
  var win = window.open(url, "_blank", 'width=800, height=600');
  win.focus();
  var pollTimer = window.setInterval(function () {
    try {
      if (win.document.URL.indexOf(redirect_uri) != -1) {
        window.clearInterval(pollTimer);
        win.close();
        dfd.resolve(win.document.URL);
      }
    } catch(e) {
    }
  },100);
  return dfd;
},

_getTokenValue: function (url, name) {
  var dfd = new Deferred();
  name = name.replace(/[[]/,"\[").replace(/[]]/,"\]");
  var regexS = "[\?&#]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( url );
  if( results == null )
      dfd.resolve("");
  else
      dfd.resolve(results[1]);
  return dfd;
},


问:
Testing if a Type has been registered in Unity
Can I test if a type has been registered in a Unity container without calling for a Resolve and trapping the exception?</p>

答: Your only other option (currently) is to use ResolveAll<T>() and enumerate the results.

OwnerDisplayName: lagerdalek

OwnerDisplayName: Mitch Wheat


问:
C string arrays
I just wrote a string splitting function:

```<code>typedef enum {
    strspl_allocation_error = 1
} strspl_error;

int strspl(const char *string, const char separator, char ***result) {

    const int stringLength = strlen(string);
    int lastSplit = 0;
    int numberOfComponents = 1;

    // Compute the number of components
    for (int i = 0; i <= stringLength; i++) {
        if (string[i] == separator)
            numberOfComponents++;
    }

    // Allocate space to hold pointers to each component
    *result = (char **) malloc(numberOfComponents * sizeof(char *));
    if (result == NULL)
        return strspl_allocation_error;

    numberOfComponents = 0;

    for (int i = 0; i <= stringLength; i++) {
        char c = string[i];
        if (c == separator || i == stringLength) {

            const int componentLength = i - lastSplit;

            // Allocate space to hold the component
            char *component = (char *) malloc(componentLength * sizeof(char));
            if (component == NULL)
                return strspl_allocation_error;

            // Copy the characters from the string into the component
            for (int j = 0; j < componentLength; j++)
                component[j] = string[lastSplit + j];
            component[componentLength] = '\0';

            // Put the component into the array
            *result[numberOfComponents] = component;

            lastSplit = i + 1;
            numberOfComponents++;
        }
    }

    return numberOfComponents;
}
</code>```

Example:

```<code>char **result;
int r = strspl("aaaBcBddddeeBk", 'B', result);

for (int i = 0; i < r; i++)
    printf("component: %s\n", result[i]);
</code>```

should output:

```<code>component: aaa
component: c
component: ddddee
component: k
</code>```

But when I run it, it either crashes or returns garbage values. I don't understand where I'm making a mistake...

Update: here's a hopefully bugfree version:

```<code>int strspl(const char *string, const char separator, char ***results) {

    const char *separatorString = (char[]){separator, '\0'};
    int numberOfComponents = 0;
    int stringLength = strlen(string);

    int lastCharacterWasSeparator = 1;

    // Compute the number of components
    for (int i = 0; i < stringLength; i++) {
        if (string[i] != separator) {
            if (lastCharacterWasSeparator)
                numberOfComponents++;
            lastCharacterWasSeparator = 0;
        }
        else
            lastCharacterWasSeparator = 1;
    }

    // Allocate space to hold pointers to components
    *results = malloc(numberOfComponents * sizeof(**results));

    char *stringCopy = strdup(string); // A reference to the copy of the string to modify it and to free() it later.
    char *strptr = stringCopy; // This will be used to iterate through the string.
    int componentLength = 0;
    int component = 0;

    while (component < numberOfComponents) {

        // Move to the startpoint of the next component.
        while (componentLength == 0) {
            componentLength = strcspn(strptr, separatorString);

            // Break out the while loop if we found an actual component.
            if (componentLength != 0)
                break;

            // If we found two adjacent separators, we just "silently" move over them.
            strptr += componentLength + 1;
        }

        // Replace the terminating separator character with a NULL character.
        strptr[componentLength] = '\0';

        // Copy the new component into the array.
        (*results)[component++] = strdup(strptr);

        // Move the string pointer ahead so we can work on the next component.
        strptr += componentLength + 1;

        componentLength = 0;
    }

    // Free the copy of the string.
    free(stringCopy);

    return numberOfComponents;
}
</code>```

答:
Sorry about that, all of what we suggested for you to do to fix it combined together and broke it again! From your original code, here are the adjustments you need:

The signature of the function needs to be char ***result instead of char **result.

The array allocation should be *result = malloc(...) instead of result = malloc(...).

The component pointer was never being stored in the results array, a line reading: (*result)[numberOfComponents] = component; should be put after component[componentLength] = '\0'; (the parenthesis are needed because the result parameter was changed to char***).

And finally, the call to the function should be something like this: strspl(..., &result); instead of strspl(..., result);

Pointers have always been one of the more difficult things to understand when working in C/C++... Let me see if I can explain this:

Let's say we have the caller with a stack like this:

```<code>Address     -  Data        -  Description
0x99887760  -  0xbaadbeef  -  caller-result variable (uninitialized garbage)
</code>```

When the call is made like this: strspl(..., result);, the compiler copies the local pointer (0xbaadbeef) onto the stack of strspl:

```<code>Address     -  Data        -  Description
0x99887750  -  0xbaadbeef  -  strspl-result variable (copy of uninitialized garbage)
...
0x99887760  -  0xbaadbeef  -  caller-result variable (uninitialized garbage)
</code>```

Now when we call result = malloc(...) and copy the result into the local strspl-result variable, we get:

```<code>Address     -  Data        -  Description
0x99887750  -  0x01000100  -  strspl-result variable (new array)
...
0x99887760  -  0xbaadbeef  -  caller-result variable (uninitialized garbage)
</code>```

Obviously not updating the caller's result variable.

If instead we call with the address of the result variable: strspl(..., &result); we get this:

```<code>Address     -  Data        -  Description
0x99887750  -  0x99887760  -  strspl-result variable (pointer to the caller's result)
...
0x99887760  -  0xbaadbeef  -  caller-result variable (uninitialized garbage)
</code>```

And then when we call result = malloc(...) we get this:

```<code>Address     -  Data        -  Description
0x99887750  -  0x01000100  -  strspl-result variable (new array)
...
0x99887760  -  0xbaadbeef  -  caller-result variable (uninitialized garbage)
</code>```

Still not quite what we want, because the caller never gets the pointer to the array.

If instead we call *result = malloc(...) we get this:

```<code>Address     -  Data        -  Description
0x99887750  -  0x99887760  -  strspl-result variable (pointer to the caller's result)
...
0x99887760  -  0x01000100  -  caller-result variable (new array)
</code>```

This way, when we return, we've overwritten the caller's garbage with our newly malloc'd array.

As you can see, the compiler is copying the address of the caller's variable onto the stack of the function being called. Because it's copied, the function cannot modify it unless the caller passes a pointer to it's variable (this is why it needed to be char*** not char**).

I hope that clears things up without making it harder to understand! :-P

Title: C string arrays

Body:
I just wrote a string splitting function:

typedef enum {
    strspl_allocation_error = 1
} strspl_error;

int strspl(const char *string, const char separator, char ***result) {

    const int stringLength = strlen(string);
    int lastSplit = 0;
    int numberOfComponents = 1;

    // Compute the number of components
    for (int i = 0; i <= stringLength; i++) {
        if (string[i] == separator)
            numberOfComponents++;
    }

    // Allocate space to hold pointers to each component
    *result = (char **) malloc(numberOfComponents * sizeof(char *));
    if (result == NULL)
        return strspl_allocation_error;

    numberOfComponents = 0;

    for (int i = 0; i <= stringLength; i++) {
        char c = string[i];
        if (c == separator || i == stringLength) {

            const int componentLength = i - lastSplit;

            // Allocate space to hold the component
            char *component = (char *) malloc(componentLength * sizeof(char));
            if (component == NULL)
                return strspl_allocation_error;

            // Copy the characters from the string into the component
            for (int j = 0; j < componentLength; j++)
                component[j] = string[lastSplit + j];
            component[componentLength] = '\0';

            // Put the component into the array
            *result[numberOfComponents] = component;

            lastSplit = i + 1;
            numberOfComponents++;
        }
    }

    return numberOfComponents;
}

Example:

char **result;
int r = strspl("aaaBcBddddeeBk", 'B', result);

for (int i = 0; i < r; i++)
    printf("component: %s\n", result[i]);

should output:

component: aaa
component: c
component: ddddee
component: k

But when I run it, it either crashes or returns garbage values. I don't understand where I'm making a mistake...

Update: here's a hopefully bugfree version:

int strspl(const char *string, const char separator, char ***results) {

    const char *separatorString = (char[]){separator, '\0'};
    int numberOfComponents = 0;
    int stringLength = strlen(string);

    int lastCharacterWasSeparator = 1;

    // Compute the number of components
    for (int i = 0; i < stringLength; i++) {
        if (string[i] != separator) {
            if (lastCharacterWasSeparator)
                numberOfComponents++;
            lastCharacterWasSeparator = 0;
        }
        else
            lastCharacterWasSeparator = 1;
    }

    // Allocate space to hold pointers to components
    *results = malloc(numberOfComponents * sizeof(**results));

    char *stringCopy = strdup(string); // A reference to the copy of the string to modify it and to free() it later.
    char *strptr = stringCopy; // This will be used to iterate through the string.
    int componentLength = 0;
    int component = 0;

    while (component < numberOfComponents) {

        // Move to the startpoint of the next component.
        while (componentLength == 0) {
            componentLength = strcspn(strptr, separatorString);

            // Break out the while loop if we found an actual component.
            if (componentLength != 0)
                break;

            // If we found two adjacent separators, we just "silently" move over them.
            strptr += componentLength + 1;
        }

        // Replace the terminating separator character with a NULL character.
        strptr[componentLength] = '\0';

        // Copy the new component into the array.
        (*results)[component++] = strdup(strptr);

        // Move the string pointer ahead so we can work on the next component.
        strptr += componentLength + 1;

        componentLength = 0;
    }

    // Free the copy of the string.
    free(stringCopy);

    return numberOfComponents;
}

Body:
Sorry about that, all of what we suggested for you to do to fix it combined together and broke it again! From your original code, here are the adjustments you need:

The signature of the function needs to be char ***result instead of char **result.

The array allocation should be *result = malloc(...) instead of result = malloc(...).

The component pointer was never being stored in the results array, a line reading: (*result)[numberOfComponents] = component; should be put after component[componentLength] = '\0'; (the parenthesis are needed because the result parameter was changed to char***).

And finally, the call to the function should be something like this: strspl(..., &result); instead of strspl(..., result);

Pointers have always been one of the more difficult things to understand when working in C/C++... Let me see if I can explain this:

Let's say we have the caller with a stack like this:

Address     -  Data        -  Description
0x99887760  -  0xbaadbeef  -  caller-result variable (uninitialized garbage)

When the call is made like this: strspl(..., result);, the compiler copies the local pointer (0xbaadbeef) onto the stack of strspl:

Address     -  Data        -  Description
0x99887750  -  0xbaadbeef  -  strspl-result variable (copy of uninitialized garbage)
...
0x99887760  -  0xbaadbeef  -  caller-result variable (uninitialized garbage)

Now when we call result = malloc(...) and copy the result into the local strspl-result variable, we get:

Address     -  Data        -  Description
0x99887750  -  0x01000100  -  strspl-result variable (new array)
...
0x99887760  -  0xbaadbeef  -  caller-result variable (uninitialized garbage)

Obviously not updating the caller's result variable.

If instead we call with the address of the result variable: strspl(..., &result); we get this:

Address     -  Data        -  Description
0x99887750  -  0x99887760  -  strspl-result variable (pointer to the caller's result)
...
0x99887760  -  0xbaadbeef  -  caller-result variable (uninitialized garbage)

And then when we call result = malloc(...) we get this:

Address     -  Data        -  Description
0x99887750  -  0x01000100  -  strspl-result variable (new array)
...
0x99887760  -  0xbaadbeef  -  caller-result variable (uninitialized garbage)

Still not quite what we want, because the caller never gets the pointer to the array.

If instead we call *result = malloc(...) we get this:

Address     -  Data        -  Description
0x99887750  -  0x99887760  -  strspl-result variable (pointer to the caller's result)
...
0x99887760  -  0x01000100  -  caller-result variable (new array)

This way, when we return, we've overwritten the caller's garbage with our newly malloc'd array.

As you can see, the compiler is copying the address of the caller's variable onto the stack of the function being called. Because it's copied, the function cannot modify it unless the caller passes a pointer to it's variable (this is why it needed to be char*** not char**).

I hope that clears things up without making it harder to understand! :-P


问:
NetLogo: How to make a turtle recognise any shade of one color?
I'm using NetLogo for the first time and need to lay out a simple programme where i have one light source that diffuses light out beyond its source patch and one turtle that will avoid the light.

I can achieve this by using basic 'set pcolor yellow' and then use 'if patch-ahead [pcolor] = yellow [right 45][fd speed]' type command. However this doesn't give me diffused light.

By adapting the HeatBugs code, i can diffuse the color out past the source patch, however the roaming turtle no longer recognises the color as yellow, i think, as it is a scale-color. I tried setting the code to != black but this also doesn't work. I'm assuming it's because the patches are being recolored after each tick.

Is there a way to make the turtle recognise the patches of diffused color so as to avoid them? Or a simpler way to diffuse the light out. (i want a variable intensity so using neighbors and yellow -1 won't do it.)

Here's the code i have so far: (this is a condensed version as i have other things happening in the main body, so i apologise if it isn't clear)

```<code>globals [ color-by-unhappiness? ]

turtles-own[
  speed
  speed-limit
  speed-min
  ideal-temp       ;; The temperature I want to be at
  output-heat      ;; How much heat I emit per time step
  unhappiness      ;; The magnitude of the difference between my ideal
               ;;   temperature and the actual current temperature here
]

patches-own[
  temp
]

to setup
  clear-all
  setup-turtles
  ;;creating diffused light
  set color-by-unhappiness? false ;; button
  ask n-of number-of-lights patches [
    sprout 1 [
      set color white
      set shape "circle"
      set ideal-temp  min-ideal-temp  + random (max-ideal-temp  - min-    ideal-temp) ;;these are all sliders
      set output-heat min-output-heat + random (max-output-heat - min-  output-heat) ;;these are all sliders
      set unhappiness abs (ideal-temp - temp) ;;ideal-temp is a button
      color-by-ideal-temp
      set size 2
    ]
  ]
  reset-ticks
end

to setup-turtles
  create-fears number-of-fears [
    set color violet
    set shape "circle"
    setxy random-xcor random-ycor
    set speed 0.1 + random-float 0.9
    set speed-limit 1
    set speed-min 0.00
  ]
end

to go
  ask turtles [
    if speed > speed-limit [set speed speed-limit]
    fd speed
  ask fears[
    if patch-ahead 1 = nobody [rt 135]
    if patch-right-and-ahead 45 1 != nobody and [pcolor] of patch-right-and-ahead 45 1 != black[left 45]
    if patch-left-and-ahead 45 1 != nobody and [pcolor] of patch-left-and-ahead 45 1 != black[right 45]
    ifelse [pcolor] of patch-here = yellow [set speed speed-min][fd speed]
  ]
  if not any? turtles [ stop ]
  ;; diffuse heat through world
  diffuse temp diffusion-rate
  ask patches [ set temp temp * (1 - evaporation-rate) ]
  ask turtles [ set temp temp + output-heat ask bugs [bug-move patch-here]]
  recolor-turtles
  recolor-patches
  tick
end

to recolor-patches
  ask patches [ set pcolor scale-color yellow temp 0 150 ]
]
end
</code>```

答:
I can't use your code as-is; check out the MCVE guidelines for some tips on reducing your code to just the necessary parts.

Color in Netlogo can given as a string, but it's also just a range of numbers. If you look at Tools > Color Swatches, you will see that the range of "Yellow" colors corresponds roughly to 40 ~ 50. So if you want to, you can just have them evaluate patch color using a numerical range rather than the color name. So, using this unnecessarily complicated example setup:

```<code>patches-own [ light? temp]

to setup
  ca
  ask patches [
    set light? false
  ]
  ask n-of 5 patches [
    set light? true
    set temp 150
  ]
  recolor-patches
  crt 10 [
    move-to one-of patches with [ not ( pcolor > 40 and pcolor < 49 ) ]
  ]
  reset-ticks
end

to recolor-patches
  ask n-of 3 patches with [ light? ] [
    if temp < 20 [
      set temp temp + random 20
    ]
  ]
  repeat 5 [
    diffuse temp 0.1
  ]
  ask patches [
    ifelse temp > 0.25 [
      set temp temp - 0.005
    ] [
      set temp 0
    ]
    set pcolor scale-color yellow temp 0 15
  ]
end
</code>```

You can ask your turtles to move and just avoid patches that fall in that numerical range:

```<code>to go
  recolor-patches
  ask turtles [
    ifelse [pcolor] of patch-ahead 1 > 40 and [pcolor] of patch-ahead 1 < 49 [
      let target min-one-of neighbors [pcolor]
      if target != nobody [
        face target
        fd 1
      ]
    ] [
      rt random 60 - 30
      fd 1
    ]
  ]
  tick
end
</code>```

EDIT

As Seth Tisue pointed out, the shade-of? primitive can accomplish what the greater than / less than logical statement does:

```<code>to go
  recolor-patches
  ask turtles [
    ifelse shade-of? ( [pcolor] of patch-ahead 1 ) yellow [
      let target min-one-of neighbors [pcolor]
      if target != nobody [
        face target
        fd 1
      ]
    ] [
      rt random 60 - 30
      fd 1
    ]
  ]
  tick
end
</code>```

However, this does require a slight modification to the recolor-patches procedure, as scale-color sets the base color to 40 (in the case of 'yellow'); just ask patches with that pcolor to set their color to black (0) so that movement works as expected here:

```<code>to recolor-patches
  ask n-of 3 patches with [ light? ] [
    if temp < 20 [
      set temp temp + random 20
    ]
  ]
  repeat 5 [
    diffuse temp 0.1
  ]
  ask patches [
    ifelse temp > 0.25 [
      set temp temp - 0.005
    ] [
      set temp 0
    ]
    set pcolor scale-color yellow temp 0 15
    if pcolor = 40 [
      set pcolor black
    ]
  ]
end
</code>```

Body:
I'm using NetLogo for the first time and need to lay out a simple programme where i have one light source that diffuses light out beyond its source patch and one turtle that will avoid the light.

I can achieve this by using basic 'set pcolor yellow' and then use 'if patch-ahead [pcolor] = yellow [right 45][fd speed]' type command. However this doesn't give me diffused light.

By adapting the HeatBugs code, i can diffuse the color out past the source patch, however the roaming turtle no longer recognises the color as yellow, i think, as it is a scale-color. I tried setting the code to != black but this also doesn't work. I'm assuming it's because the patches are being recolored after each tick.

Is there a way to make the turtle recognise the patches of diffused color so as to avoid them? Or a simpler way to diffuse the light out. (i want a variable intensity so using neighbors and yellow -1 won't do it.)

Here's the code i have so far: (this is a condensed version as i have other things happening in the main body, so i apologise if it isn't clear)

globals [ color-by-unhappiness? ]

turtles-own[
  speed
  speed-limit
  speed-min
  ideal-temp       ;; The temperature I want to be at
  output-heat      ;; How much heat I emit per time step
  unhappiness      ;; The magnitude of the difference between my ideal
               ;;   temperature and the actual current temperature here
]

patches-own[
  temp
]

to setup
  clear-all
  setup-turtles
  ;;creating diffused light
  set color-by-unhappiness? false ;; button
  ask n-of number-of-lights patches [
    sprout 1 [
      set color white
      set shape "circle"
      set ideal-temp  min-ideal-temp  + random (max-ideal-temp  - min-    ideal-temp) ;;these are all sliders
      set output-heat min-output-heat + random (max-output-heat - min-  output-heat) ;;these are all sliders
      set unhappiness abs (ideal-temp - temp) ;;ideal-temp is a button
      color-by-ideal-temp
      set size 2
    ]
  ]
  reset-ticks
end

to setup-turtles
  create-fears number-of-fears [
    set color violet
    set shape "circle"
    setxy random-xcor random-ycor
    set speed 0.1 + random-float 0.9
    set speed-limit 1
    set speed-min 0.00
  ]
end

to go
  ask turtles [
    if speed > speed-limit [set speed speed-limit]
    fd speed
  ask fears[
    if patch-ahead 1 = nobody [rt 135]
    if patch-right-and-ahead 45 1 != nobody and [pcolor] of patch-right-and-ahead 45 1 != black[left 45]
    if patch-left-and-ahead 45 1 != nobody and [pcolor] of patch-left-and-ahead 45 1 != black[right 45]
    ifelse [pcolor] of patch-here = yellow [set speed speed-min][fd speed]
  ]
  if not any? turtles [ stop ]
  ;; diffuse heat through world
  diffuse temp diffusion-rate
  ask patches [ set temp temp * (1 - evaporation-rate) ]
  ask turtles [ set temp temp + output-heat ask bugs [bug-move patch-here]]
  recolor-turtles
  recolor-patches
  tick
end

to recolor-patches
  ask patches [ set pcolor scale-color yellow temp 0 150 ]
]
end

Body:
I can't use your code as-is; check out the MCVE guidelines for some tips on reducing your code to just the necessary parts.

Color in Netlogo can given as a string, but it's also just a range of numbers. If you look at Tools > Color Swatches, you will see that the range of "Yellow" colors corresponds roughly to 40 ~ 50. So if you want to, you can just have them evaluate patch color using a numerical range rather than the color name. So, using this unnecessarily complicated example setup:

patches-own [ light? temp]

to setup
  ca
  ask patches [
    set light? false
  ]
  ask n-of 5 patches [
    set light? true
    set temp 150
  ]
  recolor-patches
  crt 10 [
    move-to one-of patches with [ not ( pcolor > 40 and pcolor < 49 ) ]
  ]
  reset-ticks
end

to recolor-patches
  ask n-of 3 patches with [ light? ] [
    if temp < 20 [
      set temp temp + random 20
    ]
  ]
  repeat 5 [
    diffuse temp 0.1
  ]
  ask patches [
    ifelse temp > 0.25 [
      set temp temp - 0.005
    ] [
      set temp 0
    ]
    set pcolor scale-color yellow temp 0 15
  ]
end

You can ask your turtles to move and just avoid patches that fall in that numerical range:

to go
  recolor-patches
  ask turtles [
    ifelse [pcolor] of patch-ahead 1 > 40 and [pcolor] of patch-ahead 1 < 49 [
      let target min-one-of neighbors [pcolor]
      if target != nobody [
        face target
        fd 1
      ]
    ] [
      rt random 60 - 30
      fd 1
    ]
  ]
  tick
end

EDIT

As Seth Tisue pointed out, the shade-of? primitive can accomplish what the greater than / less than logical statement does:

to go
  recolor-patches
  ask turtles [
    ifelse shade-of? ( [pcolor] of patch-ahead 1 ) yellow [
      let target min-one-of neighbors [pcolor]
      if target != nobody [
        face target
        fd 1
      ]
    ] [
      rt random 60 - 30
      fd 1
    ]
  ]
  tick
end

However, this does require a slight modification to the recolor-patches procedure, as scale-color sets the base color to 40 (in the case of 'yellow'); just ask patches with that pcolor to set their color to black (0) so that movement works as expected here:

to recolor-patches
  ask n-of 3 patches with [ light? ] [
    if temp < 20 [
      set temp temp + random 20
    ]
  ]
  repeat 5 [
    diffuse temp 0.1
  ]
  ask patches [
    ifelse temp > 0.25 [
      set temp temp - 0.005
    ] [
      set temp 0
    ]
    set pcolor scale-color yellow temp 0 15
    if pcolor = 40 [
      set pcolor black
    ]
  ]
end


问:
python sys.stdin.read() from tail -f
How come sys.stdin.read() doesn't read the piped input from tail -f?

```<code>#!/usr/bin/env python
import sys
from geoip import geolite2
def iplookup(srcip):
        for ip in srcip.split("\n"):
                try:
                        print(geolite2.lookup(ip))
                except:
                        pass
source = sys.stdin.read()
iplookup(source)
</code>```

tail -f /var/log/bleh.log | grep -oE '((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])' | python mygeoip.py

答:
None of the other answers (even fileinput) fully addresses the issue of buffering, and so will not work for small outputs of tail -f.

From the python man page:

Note that there is internal buffering in xreadlines(), readlines() and
  file-object iterators ("for line in sys.stdin") which is not
  influenced by this option. To work around this, you will want to use
  "sys.stdin.readline()" inside a "while 1:" loop.

In other words what you want is:

```<code>while True:
    line = sys.stdin.readline()
    iplookup(line)
</code>```

Title: python sys.stdin.read() from tail -f

Body:
How come sys.stdin.read() doesn't read the piped input from tail -f?

#!/usr/bin/env python
import sys
from geoip import geolite2
def iplookup(srcip):
        for ip in srcip.split("\n"):
                try:
                        print(geolite2.lookup(ip))
                except:
                        pass
source = sys.stdin.read()
iplookup(source)

tail -f /var/log/bleh.log | grep -oE '((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])' | python mygeoip.py

Body:
None of the other answers (even fileinput) fully addresses the issue of buffering, and so will not work for small outputs of tail -f.

From the python man page:

Note that there is internal buffering in xreadlines(), readlines() and
  file-object iterators ("for line in sys.stdin") which is not
  influenced by this option. To work around this, you will want to use
  "sys.stdin.readline()" inside a "while 1:" loop.

In other words what you want is:

while True:
    line = sys.stdin.readline()
    iplookup(line)


问:
Display API data using Axios and a list in React
I'm attempting to make a request to this https://www.themoviedb.org/documentation/api API in a React project and then display JSON data on my site.

I'm using Axios to make the request and I have been able to make the request and get the appropriate JSON data and console.log it or view it in the React tools in Firefox. However, I am having difficulty displaying the data in a ul. Initially I had an error pertaining to having a unique key for each list item, and I have since resolved that (or so I believe).

Here's my request and how I am attempting to render the data:

```<code>import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import axios from "axios";

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      posts: []
    }
  }

  componentDidMount() {
    axios.get(`https://api.themoviedb.org/3/movie/now_playing?api_key=*apikeyhere*&language=en-US&page=1`)
      .then(res => {
        const posts = res.data.results.map(obj => [obj.title, obj.overview]);
        this.setState({ posts });
      });
  }

/*  render() {
    return (
      <div>
        <h1>Movie API data</h1>
        <ul>
          {this.state.posts.map(post =>
              <li key={post.toString()}>{post.title}</li>
            )}
        </ul>
      </div>
    );
  }
}
*/

  render() {
    return (
      <ul>
        {this.state.posts.map(function(post, index){
          return (
              <div key={index}>
                <h1>{post.title}</h1>
                <p>{post.overview}</p>
              </div>
            )
          }
        )}
      </ul>
    );

  }

}
</code>```

As you can see I attempted multile approaches to rendering this. What's wrong with my code and why isn't the JSON data rendering in the ul on my site?

答:
I think, you have an error inside success fuction ({title: obj.title, overview: obj.overview})

```<code>componentDidMount() {
    axios.get(`https://api.themoviedb.org/3/movie/now_playing?api_key=*apikeyhere*&language=en-US&page=1`)
      .then(res => {
        const posts = res.data.results.map(obj => ({title: obj.title, overview: obj.overview}));
        this.setState({ posts });
      });
  }
</code>```

Body:
I'm attempting to make a request to this https://www.themoviedb.org/documentation/api API in a React project and then display JSON data on my site.

I'm using Axios to make the request and I have been able to make the request and get the appropriate JSON data and console.log it or view it in the React tools in Firefox. However, I am having difficulty displaying the data in a ul. Initially I had an error pertaining to having a unique key for each list item, and I have since resolved that (or so I believe).

Here's my request and how I am attempting to render the data:

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import axios from "axios";

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      posts: []
    }
  }

  componentDidMount() {
    axios.get(`https://api.themoviedb.org/3/movie/now_playing?api_key=*apikeyhere*&language=en-US&page=1`)
      .then(res => {
        const posts = res.data.results.map(obj => [obj.title, obj.overview]);
        this.setState({ posts });
      });
  }

/*  render() {
    return (

Movie API data

          {this.state.posts.map(post =>

{post.title}

            )}

    );
  }
}
*/

  render() {
    return (

        {this.state.posts.map(function(post, index){
          return (

{post.title}

{post.overview}

            )
          }
        )}

    );

  }

}

As you can see I attempted multile approaches to rendering this. What's wrong with my code and why isn't the JSON data rendering in the ul on my site?

Body:
I think, you have an error inside success fuction ({title: obj.title, overview: obj.overview})

componentDidMount() {
    axios.get(`https://api.themoviedb.org/3/movie/now_playing?api_key=*apikeyhere*&language=en-US&page=1`)
      .then(res => {
        const posts = res.data.results.map(obj => ({title: obj.title, overview: obj.overview}));
        this.setState({ posts });
      });
  }