问:
Using jQuery with Angular-CLI Project
I am using "@angular/cli": "1.0.2" and angular version 4.

For some reason I had to use jquery based plugin for select area because I couldn't found equivalent plugin in angular.

This is how my component looks like

```<code>declare var $ : any;
//adding only necessary code
export class SelectComponent implements OnInit {

    constructor(private _ngZone: NgZone) {}

    public rowData: any = [];

    ngOnInit() {
        $('img#example').selectAreas({
            minSize: [10, 10],
            onChanged: this.debugQtyAreas,
            width: 500,
            areas: [{
                x: 10,
                y: 20,
                width: 60,
                height: 100,
            }]
        });
    }
    debugQtyAreas(event, id, areas) {
        this.rowData = areas.map(function(obj) {
            return {
                left: obj.x,
                top: obj.y,
                id: obj.id
            };
        });
    };
}
</code>```

Some how this way my jquery thing is working I am able to select areas on a Image.

But the value I am pushing / assigning to array rowData are not updating in the view

I tried searching on internet and found this solution working for everyone but not for me

```<code>this._ngZone.run(() => {
      //running code inside this
})
</code>```

But I am getting error here as

Cannot read property 'run' of undefined

Same thing happening with rowData, when I tried to push data instead of assigning it from map like following

```<code>for(var i = 0; i < areas.length; i++){
    this.rowData.push({
        left: areas[i].x,
        top: areas[i].y,
        id: obj.id
    });
}
</code>```

It says Cannot read property 'push' of undefined

答:
this becomes reserved inside jQuery functions and is not referenced to the global scope as it usually is.

I always add this lines at the top of my function:

let scope = this;

And then use scope instead of this`, e.g.

```<code>scope._ngZone.run(() => {
  //running code inside this
})

...

for(var i = 0; i < areas.length; i++){
    scope.rowData.push({
        left: areas[i].x,
        top: areas[i].y,
        id: obj.id
    });
}
</code>```

Title: Using jQuery with Angular-CLI Project

Body:
I am using "@angular/cli": "1.0.2" and angular version 4.

For some reason I had to use jquery based plugin for select area because I couldn't found equivalent plugin in angular.

This is how my component looks like

declare var $ : any;
//adding only necessary code
export class SelectComponent implements OnInit {

    constructor(private _ngZone: NgZone) {}

    public rowData: any = [];

    ngOnInit() {
        $('img#example').selectAreas({
            minSize: [10, 10],
            onChanged: this.debugQtyAreas,
            width: 500,
            areas: [{
                x: 10,
                y: 20,
                width: 60,
                height: 100,
            }]
        });
    }
    debugQtyAreas(event, id, areas) {
        this.rowData = areas.map(function(obj) {
            return {
                left: obj.x,
                top: obj.y,
                id: obj.id
            };
        });
    };
}

Some how this way my jquery thing is working I am able to select areas on a Image.

But the value I am pushing / assigning to array rowData are not updating in the view

I tried searching on internet and found this solution working for everyone but not for me

this._ngZone.run(() => {
      //running code inside this
})

But I am getting error here as

Cannot read property 'run' of undefined

Same thing happening with rowData, when I tried to push data instead of assigning it from map like following

for(var i = 0; i < areas.length; i++){
    this.rowData.push({
        left: areas[i].x,
        top: areas[i].y,
        id: obj.id
    });
}

It says Cannot read property 'push' of undefined

Body:
this becomes reserved inside jQuery functions and is not referenced to the global scope as it usually is.

I always add this lines at the top of my function:

let scope = this;

And then use scope instead of this`, e.g.

scope._ngZone.run(() => {
  //running code inside this
})

...

for(var i = 0; i < areas.length; i++){
    scope.rowData.push({
        left: areas[i].x,
        top: areas[i].y,
        id: obj.id
    });
}


来源: stackexchange

问:
Java changing image color to represent day/night cycle
I'm currently working on a 2D game in Java and I'm having a little trouble implementing a day/night cycle. I've currently got a system in place that draws a semi-transparent rectangle over the whole screen. Depending on the time in game the rectangle becomes more or less transparent. The problem with this is frame rate takes a huge hit.

So now I'm trying to take the hex color value of the pixel currently being displayed, split it into separate RGB values, and reduce those values then return the number back as a hex in order to draw it to the screen.

This is my code currently. My issue is if the values are greater than 99 the the program crashes.

```<code>public int getRGB(String hex) {
    if (hex.length() > 1) {
        String temp;
        int colVal;
        temp = hex.substring(2, 4);
        red = Integer.parseInt(temp, 16);
        temp = hex.substring(4, 6);
        green = Integer.parseInt(temp, 16);
        temp = hex.substring(6, 8);
        blue = Integer.parseInt(temp, 16);
        colVal = darkenTile(red, green, blue);
        return colVal;
    } else {
        return 0;
    }
}

public int darkenTile(int r, int g, int b) {
    int col = 0;
    String red;
    String green;
    String blue;
    for (int i = 0; i < 20; i++) {
        if (r > 0) r--;
        if (g > 0) g--;
        if (b > 0) b--;
    }
    if (r == 0) red = "00";
    else red = Integer.toString(r);
    if (g == 0) green = "00";
    else green = Integer.toString(g);
    if (b == 0) blue = "00";
    else blue = Integer.toString(b);
    String hex = red + green + blue;
    System.out.println(hex);
    col = Integer.parseInt(hex, 16);
    return col;

}
</code>```

When I crash this is what I get.

```<code>Exception in thread "Display" java.lang.NumberFormatException: For input string: "110112129"
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at com.cousersoft.game.graphics.Screen.darkenTile(Screen.java:178)
    at com.cousersoft.game.graphics.Screen.getRGB(Screen.java:154)
    at com.cousersoft.game.graphics.Screen.renderTile(Screen.java:50)
    at com.cousersoft.game.level.tile.RockTile.render(RockTile.java:13)
    at com.cousersoft.game.level.Level.render(Level.java:84)
    at com.cousersoft.game.Game.render(Game.java:200)
    at com.cousersoft.game.Game.run(Game.java:163)
    at java.lang.Thread.run(Unknown Source)
</code>```

答:
The value 110112129 in hex which you're trying to convert to int is equal to 4,564,525,353 in decimal - it's larger than the maximum value an integer can store:

Integer.MAX_VALUE is 2,147,483,647

The cause of this is because you're converting the r,b,g values to a decimal string instead of a hex string.

Instead of

```<code>if (r == 0) red = "00";
else red = Integer.toString(r);
if (g == 0) green = "00";
else green = Integer.toString(g);
if (b == 0) blue = "00";
else blue = Integer.toString(b);
</code>```

try:

```<code>if (r == 0) red = "00";
else red = Integer.toHexString(r);
if (g == 0) green = "00";
else green = Integer.toHexString(g);
if (b == 0) blue = "00";
else blue = Integer.toHexString(b);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm currently working on a 2D game in Java and I'm having a little trouble implementing a day/night cycle. I've currently got a system in place that draws a semi-transparent rectangle over the whole screen. Depending on the time in game the rectangle becomes more or less transparent. The problem with this is frame rate takes a huge hit.

So now I'm trying to take the hex color value of the pixel currently being displayed, split it into separate RGB values, and reduce those values then return the number back as a hex in order to draw it to the screen.

This is my code currently. My issue is if the values are greater than 99 the the program crashes.

public int getRGB(String hex) {
    if (hex.length() > 1) {
        String temp;
        int colVal;
        temp = hex.substring(2, 4);
        red = Integer.parseInt(temp, 16);
        temp = hex.substring(4, 6);
        green = Integer.parseInt(temp, 16);
        temp = hex.substring(6, 8);
        blue = Integer.parseInt(temp, 16);
        colVal = darkenTile(red, green, blue);
        return colVal;
    } else {
        return 0;
    }
}

public int darkenTile(int r, int g, int b) {
    int col = 0;
    String red;
    String green;
    String blue;
    for (int i = 0; i < 20; i++) {
        if (r > 0) r--;
        if (g > 0) g--;
        if (b > 0) b--;
    }
    if (r == 0) red = "00";
    else red = Integer.toString(r);
    if (g == 0) green = "00";
    else green = Integer.toString(g);
    if (b == 0) blue = "00";
    else blue = Integer.toString(b);
    String hex = red + green + blue;
    System.out.println(hex);
    col = Integer.parseInt(hex, 16);
    return col;

}

When I crash this is what I get.

Exception in thread "Display" java.lang.NumberFormatException: For input string: "110112129"
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at com.cousersoft.game.graphics.Screen.darkenTile(Screen.java:178)
    at com.cousersoft.game.graphics.Screen.getRGB(Screen.java:154)
    at com.cousersoft.game.graphics.Screen.renderTile(Screen.java:50)
    at com.cousersoft.game.level.tile.RockTile.render(RockTile.java:13)
    at com.cousersoft.game.level.Level.render(Level.java:84)
    at com.cousersoft.game.Game.render(Game.java:200)
    at com.cousersoft.game.Game.run(Game.java:163)
    at java.lang.Thread.run(Unknown Source)

Body:
The value 110112129 in hex which you're trying to convert to int is equal to 4,564,525,353 in decimal - it's larger than the maximum value an integer can store:

Integer.MAX_VALUE is 2,147,483,647

The cause of this is because you're converting the r,b,g values to a decimal string instead of a hex string.

Instead of

if (r == 0) red = "00";
else red = Integer.toString(r);
if (g == 0) green = "00";
else green = Integer.toString(g);
if (b == 0) blue = "00";
else blue = Integer.toString(b);

try:

if (r == 0) red = "00";
else red = Integer.toHexString(r);
if (g == 0) green = "00";
else green = Integer.toHexString(g);
if (b == 0) blue = "00";
else blue = Integer.toHexString(b);


问:
How to update a variable outside a function in corona sdk?
How do I change the variable outside a function(in my case it is an eventListener)? I have a goal, which is a circle and I want its radius to change when the score is over 10. How do I update the variable to check what the radius is?</p>

```<code> local goal
 local goalRadius = 40

 local function checkScore()
   if(score>10)then
      goalRadius = 20
      --UPDATE THE VARIABLE?
 end

goal = display.newCircle(0,0,goalRadius)
goal:addEventListener("touch", checkScore)
</code>```

答: If you need change radius of circle use goal.width and goal.height. Just remember that goal.width == goal.height == two radii for circle.

Body:
How do I change the variable outside a function(in my case it is an eventListener)? I have a goal, which is a circle and I want its radius to change when the score is over 10. How do I update the variable to check what the radius is?

 local goal
 local goalRadius = 40

 local function checkScore()
   if(score>10)then
      goalRadius = 20
      --UPDATE THE VARIABLE?
 end

goal = display.newCircle(0,0,goalRadius)
goal:addEventListener("touch", checkScore)


问:
Add pause to Alexa without using SSML
Is there a way to add a pause (preferably 1 second) in Amazon Alexa without using SSML? Perhaps there is a trick I can do with the Outputspeech.Text and I just don't know it.

Below, I am saying "Here are works of art by {artist name}" but the name and the start of the works of art become mixed together - in spite of the period - so I end up with things like "Here are the works of art by Pablo Picasso Harlequin..."

I am using C# and my own https endpoint, not AWS Lambda.

Any suggestions? Otherwise I will add it as SSML. Thanks.

```<code>        var output = new StringBuilder();
        var outputCard = new StringBuilder();

        string m_location;
        string m_current_location;

        string m_artist = dt_artist.Rows[0]["DisplayName"].ToString();

        output.Append("here are works of art for " + m_artist + ". ");
        outputCard.Append("Here are works of art for " + m_artist + ".\n\n");

        foreach (DataRow dr in dt_artist_objs.Rows)
        {
            m_current_location = dr["CurrentLocation"].ToString();

            if (m_current_location == " ")
            {
                m_location = "The location is not available.";
            }
            else
            {
                m_location = "It is located on the " + m_current_location;
            }

            output.Append(dr["Title"].ToString() + " is a " + dr["Classification"].ToString() + ". The medium is " + dr["Medium"].ToString() + ". " + m_location);
            outputCard.Append(dr["Title"].ToString() + ", " + dr["Dated"].ToString() + " is a " + dr["Classification"].ToString() + ". The medium is " + dr["Medium"].ToString() + ". " + dr["Creditline"].ToString() + ". " + m_location + ".\n");  // It is located on the " + dr["CurrentLocation"].ToString());

        }

        sql_conn_data.Close();

        response.Response.OutputSpeech.Text = output.ToString();
        response.Response.Card.Title = "Art";
        response.Response.Card.Type = "Standard";
        response.Response.Card.Text = outputCard.ToString();
        response.Response.ShouldEndSession = true;

        return response;
</code>```

UPDATE

OK.  Ended up going the SSML route which looks like this:

```<code>        var output = new StringBuilder();
        var outputCard = new StringBuilder();

        string m_location;
        string m_current_location;
        string m_location_card;

        string m_artist = dt_artist.Rows[0]["DisplayName"].ToString();

        output.Append("<speak>");
        output.Append("here are works of art for " + m_artist + ". <break time='1s'/> ");
        outputCard.Append("Here are works of art for " + m_artist + ".\n\n");

        foreach (DataRow dr in dt_artist_objs.Rows)
        {
            m_current_location = dr["CurrentLocation"].ToString();

            if (m_current_location == " ")
            {
                m_location = "The location is not available. <break time='1s' />";
                m_location_card = "The location is not available. ";
            }
            else
            {
                m_location = "It is located on the " + m_current_location + "<break time = '1s' />";
                m_location_card = "It is located on the " + m_current_location;
            }

            output.Append(dr["Title"].ToString() + " is a " + dr["Classification"].ToString() + ". The medium is " + dr["Medium"].ToString() + ". " + m_location);
            outputCard.Append(dr["Title"].ToString() + ", " + dr["Dated"].ToString() + " is a " + dr["Classification"].ToString() + ". The medium is " + dr["Medium"].ToString() + ". " + dr["Creditline"].ToString() + ". " + m_location_card + ". \n");

        }

        output.Append("</speak>");

        sql_conn_data.Close();

        response.Response.OutputSpeech.Ssml = output.ToString();
        response.Response.OutputSpeech.Type = "SSML";
        response.Response.Card.Title = "Art";
        response.Response.Card.Type = "Standard";
        response.Response.Card.Text = outputCard.ToString();
        response.Response.ShouldEndSession = true;

        return response;
    }
</code>```

答: There is not a way to introduce a pause in Alexa without SSML. You will need to build the ssml string and return it back to Alexa using the pause, or the cadence strings.</p>

Title: Add pause to Alexa without using SSML

Body:
Is there a way to add a pause (preferably 1 second) in Amazon Alexa without using SSML? Perhaps there is a trick I can do with the Outputspeech.Text and I just don't know it.

Below, I am saying "Here are works of art by {artist name}" but the name and the start of the works of art become mixed together - in spite of the period - so I end up with things like "Here are the works of art by Pablo Picasso Harlequin..."

I am using C# and my own https endpoint, not AWS Lambda.

Any suggestions? Otherwise I will add it as SSML. Thanks.

        var output = new StringBuilder();
        var outputCard = new StringBuilder();

        string m_location;
        string m_current_location;

        string m_artist = dt_artist.Rows[0]["DisplayName"].ToString();

        output.Append("here are works of art for " + m_artist + ". ");
        outputCard.Append("Here are works of art for " + m_artist + ".\n\n");

        foreach (DataRow dr in dt_artist_objs.Rows)
        {
            m_current_location = dr["CurrentLocation"].ToString();

            if (m_current_location == " ")
            {
                m_location = "The location is not available.";
            }
            else
            {
                m_location = "It is located on the " + m_current_location;
            }

            output.Append(dr["Title"].ToString() + " is a " + dr["Classification"].ToString() + ". The medium is " + dr["Medium"].ToString() + ". " + m_location);
            outputCard.Append(dr["Title"].ToString() + ", " + dr["Dated"].ToString() + " is a " + dr["Classification"].ToString() + ". The medium is " + dr["Medium"].ToString() + ". " + dr["Creditline"].ToString() + ". " + m_location + ".\n");  // It is located on the " + dr["CurrentLocation"].ToString());

        }

        sql_conn_data.Close();

        response.Response.OutputSpeech.Text = output.ToString();
        response.Response.Card.Title = "Art";
        response.Response.Card.Type = "Standard";
        response.Response.Card.Text = outputCard.ToString();
        response.Response.ShouldEndSession = true;

        return response;

UPDATE

OK.  Ended up going the SSML route which looks like this:

        var output = new StringBuilder();
        var outputCard = new StringBuilder();

        string m_location;
        string m_current_location;
        string m_location_card;

        string m_artist = dt_artist.Rows[0]["DisplayName"].ToString();

        output.Append("<speak>");
        output.Append("here are works of art for " + m_artist + ". <break time='1s'/> ");
        outputCard.Append("Here are works of art for " + m_artist + ".\n\n");

        foreach (DataRow dr in dt_artist_objs.Rows)
        {
            m_current_location = dr["CurrentLocation"].ToString();

            if (m_current_location == " ")
            {
                m_location = "The location is not available. <break time='1s' />";
                m_location_card = "The location is not available. ";
            }
            else
            {
                m_location = "It is located on the " + m_current_location + "<break time = '1s' />";
                m_location_card = "It is located on the " + m_current_location;
            }

            output.Append(dr["Title"].ToString() + " is a " + dr["Classification"].ToString() + ". The medium is " + dr["Medium"].ToString() + ". " + m_location);
            outputCard.Append(dr["Title"].ToString() + ", " + dr["Dated"].ToString() + " is a " + dr["Classification"].ToString() + ". The medium is " + dr["Medium"].ToString() + ". " + dr["Creditline"].ToString() + ". " + m_location_card + ". \n");

        }

        output.Append("</speak>");

        sql_conn_data.Close();

        response.Response.OutputSpeech.Ssml = output.ToString();
        response.Response.OutputSpeech.Type = "SSML";
        response.Response.Card.Title = "Art";
        response.Response.Card.Type = "Standard";
        response.Response.Card.Text = outputCard.ToString();
        response.Response.ShouldEndSession = true;

        return response;
    }


问:
how to inject dependencies to a service with MacWire (play framework)
I have a service class, and the service have one method getSomethingFromApi , now , I want to have play Configuration instance so I can pull stuff from the application.conf, and a play WSClient so I can perform http calls.

this is how I want my service to look:

```<code>class MyApiService {

  def getSomethingFromApi(whichApi: String): Future[ApiRes] = {
    wsClient.url(configuration.getString(whichApi)).withHttpHeaders(("Content-Type", "application/json")).get.map { res =>
      response.status match {
        case Status.OK => // do something
        case _ => throw new Exception
      }
    }
  }

}
</code>```

and this is the ServicesModule that is wiring my services:

```<code>import com.softwaremill.macwire._

trait ServicesModule {

  lazy val myService: MyApiService = wire[MyApiService]

}
</code>```

my question now is what is the right way of using wiring play Configuration and WSClient instances..? cause currently i need those instances in my service but i dont have them, how should i do this the right way?
thanks

答:
With macwire it'll probably look like this

```<code>// MyApiService.scala
class MyApiService(wsClient: WSClient) { ... }

// ServicesModule.scala
trait ServicesModule with NingWSComponents {
    lazy val wsClient = wire[WSClient]
    lazy val apiService = wire[MyApiService]
}
</code>```

I haven't tried using macwire with play myself, so I have relatively low confidence that it'll work on the first try, but macwire play example suggests mixing in certain Play modules to provide values needed for WSClient. Most likely not all of them are needed, but some might be - soo I'd suggest starting with just NingWSComponents and gradually adding more until it works.

Body:
I have a service class, and the service have one method getSomethingFromApi , now , I want to have play Configuration instance so I can pull stuff from the application.conf, and a play WSClient so I can perform http calls.

this is how I want my service to look:

class MyApiService {

  def getSomethingFromApi(whichApi: String): Future[ApiRes] = {
    wsClient.url(configuration.getString(whichApi)).withHttpHeaders(("Content-Type", "application/json")).get.map { res =>
      response.status match {
        case Status.OK => // do something
        case _ => throw new Exception
      }
    }
  }

}

and this is the ServicesModule that is wiring my services:

import com.softwaremill.macwire._

trait ServicesModule {

  lazy val myService: MyApiService = wire[MyApiService]

}

my question now is what is the right way of using wiring play Configuration and WSClient instances..? cause currently i need those instances in my service but i dont have them, how should i do this the right way?
thanks

Body:
With macwire it'll probably look like this

// MyApiService.scala
class MyApiService(wsClient: WSClient) { ... }

// ServicesModule.scala
trait ServicesModule with NingWSComponents {
    lazy val wsClient = wire[WSClient]
    lazy val apiService = wire[MyApiService]
}

I haven't tried using macwire with play myself, so I have relatively low confidence that it'll work on the first try, but macwire play example suggests mixing in certain Play modules to provide values needed for WSClient. Most likely not all of them are needed, but some might be - soo I'd suggest starting with just NingWSComponents and gradually adding more until it works.


问:
settiing a txt file as an output and and input
what I'm trying to do with this code is to create a bot that automatically downloads a file when it read a discord message (that part is not done yet) but I want to save the download button position variable (mouse down position) into a text file and make it read but I don't know how to create an input/output text file from c++

bonus: if you want could you tell me how to make c++ read a discord message from a specified user

答: though your question is not clear, but if you want to run your file as a cpp file then you could save your file with .cpp extension.


问:
Is complex formatting inside label of tab in Tkinter Notebook widget possible?
I've just finished adding some nice formatting to my logging console where based on the message type the prefix of the message is coloured differently:

In order to do that I used tags (tag_config()) along with Font() to make things bold:

```<code>from tkinter import font, Tk, END
from tkinter.scrolledtext import ScrolledText

def log_info(msg, widget):
  log(msg, "info", widget)

def log_error(msg, widget):
  log(msg, "error", widget)

def log_warn(msg, widget):
  log(msg, "warn", widget)

def log(msg, type, widget):
  msg_prefix = font.Font(widget, widget.cget("font"))
  msg_prefix.configure(weight="bold")
  if type == "info":
    widget.insert(END, "INFO: ", "info")
    widget.insert(END, msg + "\n")
  elif type == "error":
    widget.insert(END, "ERROR: ", "error")
    widget.insert(END, msg + "\n")
  elif type == "warn":
    widget.insert(END, "WARNING: ", "warn")
    widget.insert(END, msg + "\n")
  else:
    print("Unknown type of log message. Available types are 'info', 'error' and 'warn'")

  widget.tag_config("info", font=msg_prefix)
  widget.tag_config("error", foreground="red", font=msg_prefix)
  widget.tag_config("warn", foreground="orange", font=msg_prefix)

window = Tk()
window.geometry('970x45')
box = ScrolledText(window, width=70, height=7)
box.pack()
log_info("This is an information log message", box)
log_error("This is an error log message", box)
log_warn("This is a warning log message", box)

window.mainloop()
</code>```

However I am struggling to add a similar feature to the tab where this console is. Every time an error log message is logged in the console the tab where it is located gets updated to show the number of errors that are currently logged:

However I would like to make the (4) (from the screenshot above) coloured with red. I was unable to find font formatting for the tab label:

Reason: I've discovered that the logging console gets ignored quite often since the other tab in my widget is where the interaction happens. Since I want to keep things separated in order to prevent clustering too many things on the screen at the same time I'm trying to notify the user in an non-intrusive way that an error has occurred (other types of log messages are not that important).

答:
I would declare your log windows as instances of a LogWindow class. This may not quite be perfect Python but you get the idea. You can probably move the tag_config commands too. __log becomes a private method and thus doesn't need as strict data checking.

class LogWindow:
  def __init__(self):
    window = Tk()
    window.geometry('970x45')
    self.widget = ScrolledText(window, width=70, height=7)
    self.widget.pack()

  def info(msg):
    self.widget.insert(END, "INFO: ", "info")
    __log(msg, "info")

  def error(msg, widget):
    self.widget.insert(END, "ERROR: ", "error")
    __log(msg, "error")

  def warn(msg):
    self.widget.insert(END, "WARNING: ", "warn")
    __log(msg, "warn")

  def __log(msg, type):
    msg_prefix = font.Font(self.widget, widget.cget("font"))
    msg_prefix.configure(weight="bold")
    self.widget.insert(END, msg + "\n")
    self.widget.tag_config("info", font=msg_prefix)
    self.widget.tag_config("error", foreground="red", font=msg_prefix)
    self.widget.tag_config("warn", foreground="orange", font=msg_prefix)

log = LogWindow();

log.info("This is an information log message")
log.error("This is an error log message")
```

Body:
I've just finished adding some nice formatting to my logging console where based on the message type the prefix of the message is coloured differently:

In order to do that I used tags (tag_config()) along with Font() to make things bold:

from tkinter import font, Tk, END
from tkinter.scrolledtext import ScrolledText

def log_info(msg, widget):
  log(msg, "info", widget)

def log_error(msg, widget):
  log(msg, "error", widget)

def log_warn(msg, widget):
  log(msg, "warn", widget)

def log(msg, type, widget):
  msg_prefix = font.Font(widget, widget.cget("font"))
  msg_prefix.configure(weight="bold")
  if type == "info":
    widget.insert(END, "INFO: ", "info")
    widget.insert(END, msg + "\n")
  elif type == "error":
    widget.insert(END, "ERROR: ", "error")
    widget.insert(END, msg + "\n")
  elif type == "warn":
    widget.insert(END, "WARNING: ", "warn")
    widget.insert(END, msg + "\n")
  else:
    print("Unknown type of log message. Available types are 'info', 'error' and 'warn'")

  widget.tag_config("info", font=msg_prefix)
  widget.tag_config("error", foreground="red", font=msg_prefix)
  widget.tag_config("warn", foreground="orange", font=msg_prefix)

window = Tk()
window.geometry('970x45')
box = ScrolledText(window, width=70, height=7)
box.pack()
log_info("This is an information log message", box)
log_error("This is an error log message", box)
log_warn("This is a warning log message", box)

window.mainloop()

However I am struggling to add a similar feature to the tab where this console is. Every time an error log message is logged in the console the tab where it is located gets updated to show the number of errors that are currently logged:

However I would like to make the (4) (from the screenshot above) coloured with red. I was unable to find font formatting for the tab label:

Reason: I've discovered that the logging console gets ignored quite often since the other tab in my widget is where the interaction happens. Since I want to keep things separated in order to prevent clustering too many things on the screen at the same time I'm trying to notify the user in an non-intrusive way that an error has occurred (other types of log messages are not that important).


问:
Button added to custom section header view disappears when row is deleted
Just came across some very strange behavior in my app. I've recreated the problem in a simplest-case scenario:

```<code>NSMutableArray *data;

- (void)viewDidLoad {
    [super viewDidLoad];
    data = [[NSMutableArray arrayWithObjects:@"1", @"2", @"3", nil] retain];
}

- (UIView *)tableView:(UITableView *)aTableView viewForHeaderInSection:(NSInteger)section {
    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, self.view.frame.size.width, 32.0)];
    header.backgroundColor = [UIColor lightGrayColor];
    [header addSubview:self.button];
    return header;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [data removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationTop];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return data.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil] autorelease];
    cell.textLabel.text = [data objectAtIndex:indexPath.row];
    return cell;
}

- (void)dealloc {
    [super dealloc];
}
</code>```

Every time I delete a row; the button in my header disappears! This happens no matter what type of rowAnimation I use. If I scroll the table up so that the header scrolls off; the button returns when the header returns. The button is created in the xib file.

I can work around it in one of 2 ways:

Reloading the tableView data after the delete; with a delay so that the deletion animation completes first.

Creating the button in viewForHeaderInSection instead of in the interfaceBuilder.

I'd really like to understand what's going on here. Where is the button going? I've confirmed that viewForHeaderInSection is called when I delete a row.

Edit I tried changing it so that the button is created in viewForHeader, instead of in the xib, but it's causing other strange issues... when I create or delete the button, I am setting certain properties such as the title and enabled depending on how many items there are in the table. When I delete the last row in the table, I don't see the update in text and enabled status until I scroll the button off the screen and back on again.

答:
Because you only have one instance of your button, if the table view decides to create a new header view then the button will be removed from its current parent and moved to the new one. Even if you only have one section in your table, the table view may be doing some strange things internally and recreating header views off-screen so you can't rely on just one being in existence at any one time.

You should create the button in viewForHeaderInSection: and work around your other problems. Rather than only updating the button properties in viewForHeaderInSection you should handle any delete events so that deleting a row will also update the button.

ContentLicense: CC BY-SA 2.5

Body:
Just came across some very strange behavior in my app. I've recreated the problem in a simplest-case scenario:

NSMutableArray *data;

- (void)viewDidLoad {
    [super viewDidLoad];
    data = [[NSMutableArray arrayWithObjects:@"1", @"2", @"3", nil] retain];
}

- (UIView *)tableView:(UITableView *)aTableView viewForHeaderInSection:(NSInteger)section {
    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, self.view.frame.size.width, 32.0)];
    header.backgroundColor = [UIColor lightGrayColor];
    [header addSubview:self.button];
    return header;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [data removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationTop];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return data.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil] autorelease];
    cell.textLabel.text = [data objectAtIndex:indexPath.row];
    return cell;
}

- (void)dealloc {
    [super dealloc];
}

Every time I delete a row; the button in my header disappears! This happens no matter what type of rowAnimation I use. If I scroll the table up so that the header scrolls off; the button returns when the header returns. The button is created in the xib file.

I can work around it in one of 2 ways:

Reloading the tableView data after the delete; with a delay so that the deletion animation completes first.

Creating the button in viewForHeaderInSection instead of in the interfaceBuilder.

I'd really like to understand what's going on here. Where is the button going? I've confirmed that viewForHeaderInSection is called when I delete a row.

Edit I tried changing it so that the button is created in viewForHeader, instead of in the xib, but it's causing other strange issues... when I create or delete the button, I am setting certain properties such as the title and enabled depending on how many items there are in the table. When I delete the last row in the table, I don't see the update in text and enabled status until I scroll the button off the screen and back on again.


问:
Bukkit/Spigot MySQL Syntax Error
first of all, I searched a lot about this issue tried a lot of solutions and it didn't work.

It seems to be it's on creating table and I don't know why it's not working, it worked before but now I did no change anything and it's not working

I have this error: "com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1"

```<code>package me.joseph.murder.sql;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.bukkit.plugin.Plugin;
import org.bukkit.scheduler.BukkitRunnable;

import me.joseph.murder.Main;

public class SQLConnection {
    public SQLDatabase MySQL;
    public static Connection c;

    public SQLConnection(Plugin plugin, String host, String port, String database, String username, String password) {
        this.MySQL = new SQLDatabase(plugin, host, port, database, username, password);
    }

    public void openConnection() {
        if (isConnected()) {
            closeConnection();
        }
        try {
            c = this.MySQL.openConnection();

            executeUpdate(
                    "CREATE TABLE IF NOT EXISTS Account (playername VARCHAR(16), wins INT(10), loses INT(10), deaths INT(10), kills INT(10), coins INT(10);");
            new BukkitRunnable() {
                @Override
                public void run() {
                    SQLConnection.this.openConnection();
                }
            }.runTaskLater(Main.getInstance(), 100L);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public boolean isConnected() {
        try {
            if (c.isClosed()) {
                return false;
            }
            return true;
        } catch (Exception e) {
        }
        return false;
    }

    public void closeConnection() {
        if (isConnected()) {
            try {
                c.close();
            } catch (SQLException localSQLException) {
            }
        }
    }

    public ResultSet executeQuery(String statement, boolean next) {
        if (isConnected()) {
            try {
                Statement s = c.createStatement();
                ResultSet res = s.executeQuery(statement);
                if (next) {
                    res.next();
                }
                return res;
            } catch (SQLException e) {
                return null;
            }
        }
        return null;
    }

    public boolean executeUpdate(String statement) {
        if (isConnected()) {
            try {
                Statement s = c.createStatement();
                s.executeUpdate(statement);
                return true;
            } catch (SQLException e) {
                e.printStackTrace();
                return false;
            }
        }
        return false;
    }
}
</code>```

答:
Missing parenthese ;) </p>

```<code>CREATE TABLE IF NOT EXISTS
Account (
    playername VARCHAR(16),
    wins INT(10),
    loses INT(10),
    deaths INT(10),
    kills INT(10),
    coins INT(10)
);
</code>```

Title: Bukkit/Spigot MySQL Syntax Error

Body:
first of all, I searched a lot about this issue tried a lot of solutions and it didn't work.

It seems to be it's on creating table and I don't know why it's not working, it worked before but now I did no change anything and it's not working

I have this error: "com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1"

package me.joseph.murder.sql;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.bukkit.plugin.Plugin;
import org.bukkit.scheduler.BukkitRunnable;

import me.joseph.murder.Main;

public class SQLConnection {
    public SQLDatabase MySQL;
    public static Connection c;

    public SQLConnection(Plugin plugin, String host, String port, String database, String username, String password) {
        this.MySQL = new SQLDatabase(plugin, host, port, database, username, password);
    }

    public void openConnection() {
        if (isConnected()) {
            closeConnection();
        }
        try {
            c = this.MySQL.openConnection();

            executeUpdate(
                    "CREATE TABLE IF NOT EXISTS Account (playername VARCHAR(16), wins INT(10), loses INT(10), deaths INT(10), kills INT(10), coins INT(10);");
            new BukkitRunnable() {
                @Override
                public void run() {
                    SQLConnection.this.openConnection();
                }
            }.runTaskLater(Main.getInstance(), 100L);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public boolean isConnected() {
        try {
            if (c.isClosed()) {
                return false;
            }
            return true;
        } catch (Exception e) {
        }
        return false;
    }

    public void closeConnection() {
        if (isConnected()) {
            try {
                c.close();
            } catch (SQLException localSQLException) {
            }
        }
    }

    public ResultSet executeQuery(String statement, boolean next) {
        if (isConnected()) {
            try {
                Statement s = c.createStatement();
                ResultSet res = s.executeQuery(statement);
                if (next) {
                    res.next();
                }
                return res;
            } catch (SQLException e) {
                return null;
            }
        }
        return null;
    }

    public boolean executeUpdate(String statement) {
        if (isConnected()) {
            try {
                Statement s = c.createStatement();
                s.executeUpdate(statement);
                return true;
            } catch (SQLException e) {
                e.printStackTrace();
                return false;
            }
        }
        return false;
    }
}

Body:
Missing parenthese ;)

CREATE TABLE IF NOT EXISTS
Account (
    playername VARCHAR(16),
    wins INT(10),
    loses INT(10),
    deaths INT(10),
    kills INT(10),
    coins INT(10)
);


问:
fortran read statement not stopping
program not stopping to read "ar". help please. even after allocating that it has definite number of elements. what may be the reason? is there something a could have missed?</p>

```<code>program summer_a39
    implicit none
    integer:: n, i, l, k
    integer, allocatable, dimension(:)::ar
    print*, 'Enter size of array:'
    read*, n
    allocate (ar(n))
    print*, 'Enter values:'
    read*, ar
    l=1
    3 do i=l,n-1
        if (l==n) then
        goto 4
        end if
        if (ar(i)<=ar(i+1)) then
        goto 1
        else
        goto 2
        end if
    end do
    1 do i=l,n-1
        do while (ar(i)<=ar(i+1))
        k=k+1
        end do
        l=k
    end do
    print*, 'Increases to', l
    goto 3
    2 do i=l,n
        do while (ar(i)>=ar(i+1))
        k=k+1
        end do
        l=k
    end do
    print*, 'Decreases to', l
    goto 3
    4 print*, 'The End'
    deallocate(ar)
    end program
</code>```

答:
Uhm... Wow... Well...

That code makes no sense at all.

I hate to say it, but you still have a lot of learning and understanding to do.

First of all: STOP USING GOTO. It breaks the code flow and makes reading it a mess.1)

Secondly: Even without checking, I'm confident that the read statement is not the reason your program hangs. It hangs between the various loops.

Even without the goto statements, this snippet alone is a surefire way to get the program to hang:

```<code>do while (ar(i)>=ar(i+1))
    k=k+1
end do
</code>```

This loop keeps repeating for as long as ar(i) is larger or equal to ar(i+1) -- but in the body of the loop, neither value changes (only k, but k is not part of the condition). So if the condition is true once, it will stay true forever, and the loop will never ever terminate.

Then you keep jumping back to the beginning of a loop. Each time you do that, the loop starts again from scratch. Again, you never come to a conclusion.

I contemplated showing how to use subroutines to do what I think you want to do, but I thought better of it. You need a lot more time to understand what's going on, and I suggest you find some dedicated resources that teach programming.
It doesn't have to be Fortran specific, any tutorial for any procedural language will help you understand program flow, which is what you need to analyse this mess.

1) a good programmer might know when to use goto. You are not a good programmer yet.

Title: fortran read statement not stopping

Body:
program not stopping to read "ar". help please. even after allocating that it has definite number of elements. what may be the reason? is there something a could have missed?

program summer_a39
    implicit none
    integer:: n, i, l, k
    integer, allocatable, dimension(:)::ar
    print*, 'Enter size of array:'
    read*, n
    allocate (ar(n))
    print*, 'Enter values:'
    read*, ar
    l=1
    3 do i=l,n-1
        if (l==n) then
        goto 4
        end if
        if (ar(i)<=ar(i+1)) then
        goto 1
        else
        goto 2
        end if
    end do
    1 do i=l,n-1
        do while (ar(i)<=ar(i+1))
        k=k+1
        end do
        l=k
    end do
    print*, 'Increases to', l
    goto 3
    2 do i=l,n
        do while (ar(i)>=ar(i+1))
        k=k+1
        end do
        l=k
    end do
    print*, 'Decreases to', l
    goto 3
    4 print*, 'The End'
    deallocate(ar)
    end program

Body:
Uhm... Wow... Well...

That code makes no sense at all.

I hate to say it, but you still have a lot of learning and understanding to do.

First of all: STOP USING GOTO. It breaks the code flow and makes reading it a mess.1)

Secondly: Even without checking, I'm confident that the read statement is not the reason your program hangs. It hangs between the various loops.

Even without the goto statements, this snippet alone is a surefire way to get the program to hang:

do while (ar(i)>=ar(i+1))
    k=k+1
end do

This loop keeps repeating for as long as ar(i) is larger or equal to ar(i+1) -- but in the body of the loop, neither value changes (only k, but k is not part of the condition). So if the condition is true once, it will stay true forever, and the loop will never ever terminate.

Then you keep jumping back to the beginning of a loop. Each time you do that, the loop starts again from scratch. Again, you never come to a conclusion.

I contemplated showing how to use subroutines to do what I think you want to do, but I thought better of it. You need a lot more time to understand what's going on, and I suggest you find some dedicated resources that teach programming.
It doesn't have to be Fortran specific, any tutorial for any procedural language will help you understand program flow, which is what you need to analyse this mess.

1) a good programmer might know when to use goto. You are not a good programmer yet.


问:
scikit-learn:ImportError: cannot import name atleast2d_or_csr
When I am working with ELM(extreme learning machine) in python, I came into this problem:ImportError: cannot import name atleast2d_or_csr.The details of error is listed as follows:

```<code>C:\Users\sherlock\Anaconda2\lib\site-packages\sklearn\cross_validation.py:44: DeprecationWarning: This module was deprecated in version 0.18 in favor of the model_selection module into which all the refactored classes and functions are moved. Also note that the interface of the new CV iterators are different from that of this module. This module will be removed in 0.20.
"This module will be removed in 0.20.", DeprecationWarning)
Traceback (most recent call last):

File "<ipython-input-50-dad0703e9d35>", line 1, in <module>
runfile('C:/Users/sherlock/Desktop/Ensemble Learnig/Python-ELM-master
/plot_elm_comparison.py', wdir='C:/Users/sherlock/Desktop/EnsembleLearnig
/Python-ELM-master')

File "C:\Users\sherlock\Anaconda2\lib\site-packages\spyder\utils
\site\sitecustomize.py", line 866, in runfile
execfile(filename, namespace)

File "C:\Users\sherlock\Anaconda2\lib\site-packages\spyder\utils
\site\sitecustomize.py", line 87, in execfile
exec(compile(scripttext, filename, 'exec'), glob, loc)

File "C:/Users/sherlock/Desktop/Ensemble Learnig/Python-ELM-master
/plot_elm_comparison.py", line 75, in <module>
from elm import ELMClassifier

File "elm.py", line 34, in <module>
from random_hidden_layer import SimpleRandomHiddenLayer

File "random_hidden_layer.py", line 27, in <module>
from sklearn.utils import check_random_state, atleast2d_or_csr

ImportError: cannot import name atleast2d_or_csr
</code>```

The concerned statement may be:

```<code>from sklearn.utils import check_random_state, atleast2d_or_csr
</code>```

答:
Replace the following:

```<code>from sklearn.utils import check_random_state, atleast2d_or_csr
</code>```

with this:

```<code>from sklearn.utils import check_random_state, check_array
</code>```

Reference: link

Body:
When I am working with ELM(extreme learning machine) in python, I came into this problem:ImportError: cannot import name atleast2d_or_csr.The details of error is listed as follows:

C:\Users\sherlock\Anaconda2\lib\site-packages\sklearn\cross_validation.py:44: DeprecationWarning: This module was deprecated in version 0.18 in favor of the model_selection module into which all the refactored classes and functions are moved. Also note that the interface of the new CV iterators are different from that of this module. This module will be removed in 0.20.
"This module will be removed in 0.20.", DeprecationWarning)
Traceback (most recent call last):

File "<ipython-input-50-dad0703e9d35>", line 1, in <module>
runfile('C:/Users/sherlock/Desktop/Ensemble Learnig/Python-ELM-master
/plot_elm_comparison.py', wdir='C:/Users/sherlock/Desktop/EnsembleLearnig
/Python-ELM-master')

File "C:\Users\sherlock\Anaconda2\lib\site-packages\spyder\utils
\site\sitecustomize.py", line 866, in runfile
execfile(filename, namespace)

File "C:\Users\sherlock\Anaconda2\lib\site-packages\spyder\utils
\site\sitecustomize.py", line 87, in execfile
exec(compile(scripttext, filename, 'exec'), glob, loc)

File "C:/Users/sherlock/Desktop/Ensemble Learnig/Python-ELM-master
/plot_elm_comparison.py", line 75, in <module>
from elm import ELMClassifier

File "elm.py", line 34, in <module>
from random_hidden_layer import SimpleRandomHiddenLayer

File "random_hidden_layer.py", line 27, in <module>
from sklearn.utils import check_random_state, atleast2d_or_csr

ImportError: cannot import name atleast2d_or_csr

The concerned statement may be:

from sklearn.utils import check_random_state, atleast2d_or_csr

Body:
Replace the following:

from sklearn.utils import check_random_state, atleast2d_or_csr

with this:

from sklearn.utils import check_random_state, check_array

Reference: link


问:
Increment a counter based on number of elements
I have a below snippet for showing TABS which is static HTML. But each item would get shown on UI based on some business logic. Based on the number of tabs I need to set a width. For e.g if two tabs are shown then I need to equally divide tabs i.e 50%. when three, it will be 33.3%.

```<code> <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
 </ul>
</code>```

Using 'ng-class' I can add runtime classes to apply the width but its increasing the complexity and killing the page as I need to apply the same business logic in ng-class.

Rather, I was trying to use ng-init to get the count to check how many tabs are formed.

```<code> <ul ng-init="totalTabs=0">
    <li ng-init="totalTabs=totalTabs+1">1</li>
    <li ng-init="totalTabs=totalTabs+1">2</li>
    <li ng-init="totalTabs=totalTabs+1">3</li>
    <li ng-init="totalTabs=totalTabs+1">4</li>
</ul>
</code>```

This doesn't give me the expected count. Do you have any clue or  suggestions ?

答:
It's time to use some new features of CSS3. In case you don't know it, there's a new display called flex. It allows a lot of things, and one of them is to give elements the same width, based on their parent's width.

You can find a quick tutorial here, or if you want to be fast :

```<code>ul {
    display: flex;
    flex-flow: row wrap;
    justify-content: center;
    align-items: center;
    align-content: flex-start;
    li {
        flex: 1 1 auto;
    }
}
</code>```

Body:
I have a below snippet for showing TABS which is static HTML. But each item would get shown on UI based on some business logic. Based on the number of tabs I need to set a width. For e.g if two tabs are shown then I need to equally divide tabs i.e 50%. when three, it will be 33.3%.

1

2

3

4

Using 'ng-class' I can add runtime classes to apply the width but its increasing the complexity and killing the page as I need to apply the same business logic in ng-class.

Rather, I was trying to use ng-init to get the count to check how many tabs are formed.

1

2

3

4

This doesn't give me the expected count. Do you have any clue or  suggestions ?

Body:
It's time to use some new features of CSS3. In case you don't know it, there's a new display called flex. It allows a lot of things, and one of them is to give elements the same width, based on their parent's width.

You can find a quick tutorial here, or if you want to be fast :

ul {
    display: flex;
    flex-flow: row wrap;
    justify-content: center;
    align-items: center;
    align-content: flex-start;
    li {
        flex: 1 1 auto;
    }
}


问:
Ways of managing the data in a database
I'm new to databases and web servers and that kind of thing. So I am looking for information so I can begin to figure out a starting point and options open to me.

I need to have a database that can be accessed by an iPhone app. So logically it will be hosted on a webserver somewhere.

To get/insert the data from/into the database the app would make a HTTP connection to a php file on the same server as the DB which would then insert/return the relevant data. To stop random hackers messing with the DB the app would have some validation code inside it to send to the php file to check that its not a hacker trying to mess with the database. This all making sense or will that not be secure enough.

Now the most confusing part to get my head around is :
I need check every minute has any data in the database become to old and remove it if so. So something needs to be running on the server constantly checking/manageing the database. What would this be? What is commonly used to do this kinda of thing? Is there somekey word for it that i can start searching and reading about to see what options there are?

Thanks for your advise,
-Code

答:
One way to do this is to have a purge script run via crontab. The script can run every minute and check for old data and remove it.

MySQL version greater than 5.1.6 has inbuilt event scheduler which can be used to schedule periodic jobs inside mysql server itself.
http://dev.mysql.com/doc/refman/5.1/en/events.html

Title: Ways of managing the data in a database


问:
Twilio stop recording of a call
We are currently developing an autodialler using twilio - we are using conferences. The call center operator will be sitting in a conference room and then calls are initiated via twilios rest api and then moved into the conference. We are not wanting to record the entire conference but just the calls within the conference. We will be transferring calls as part of this but when we transfer to a third party we want to ensure this isn't recorded. Is there a way to stop recording with Twilio.</p>

答:
Twilio developer evangelist here.

There isn't an API native way to stop the recording of a conference part way through. What I'd recommend here is that, when you want to initiate the call to the third party to bring them into the conference, also initiate a couple of requests the use the Twilio API to redirect the current calls into a new, non-recording conference and direct the third party into that conference instead.

Let me know if that helps at all.

Title: Twilio stop recording of a call


问:
How can i display animated svg file in iOS without using UIWebView
Currently i am using UIWebView to display animated svg file in my native iOS application.

This works fine except the CPU usage is constantly being on higher side as long as app is in foreground.

Is there any better way to display svg file without using UIwebView

I have already tried many third party libraries but all works only with static svg file not animated svgs

I have tried following

https://github.com/mchoe/SwiftSVG

https://github.com/exyte/Macaw

https://github.com/onmyway133/Snowflake

https://github.com/SVGKit/SVGKit

My app supports iOS 9 and above , My code is in Swift3

Here is the link of on of the svg file that i am trying to display

http://www.mediafire.com/file/04ojy6t4e3c41lv/03d.svg

答:
You should take look at SVGKit !

This library is based on core animation.

Refer this tutorial,

First install pod or manually install SVGKit into your project.

Then drag and drop your svg file in to your project.

Then you can do something like,

```<code>  UIView *myView = [[UIView alloc]initWithFrame:CGRectMake(20, 70, 300, 300)];

myView.backgroundColor = [UIColor yellowColor];

[self.view addSubview:myView];

 // SVGKImage *image = [SVGKImage imageWithContentsOfFile:@"animated-svg-icon"];

SVGKImage *image = [SVGKImage imageNamed:@"cd-icon.svg"];

[self animateCALayer:image.CALayerTree duration:2.0];
[myView.layer addSublayer:image.CALayerTree];
</code>```

here cd-icon.svg is the svg image. Put all the html,js and css files with it in your bundle! (put whole folder of svg in your project)

If you get any error related CocoaLumberjack then install pod 'CocoaLumberjack' in your project and replace @import CocoaLumberjack; with #import "CocoaLumberjack.h" in SVGKit-prefix.pch

Follow everything step by step as I mentioned. And you are done. You will displaying svg in UIView instead of webview.

Body:
You should take look at SVGKit !

This library is based on core animation.

Refer this tutorial,

First install pod or manually install SVGKit into your project.

Then drag and drop your svg file in to your project.

Then you can do something like,

  UIView *myView = [[UIView alloc]initWithFrame:CGRectMake(20, 70, 300, 300)];

myView.backgroundColor = [UIColor yellowColor];

[self.view addSubview:myView];

 // SVGKImage *image = [SVGKImage imageWithContentsOfFile:@"animated-svg-icon"];

SVGKImage *image = [SVGKImage imageNamed:@"cd-icon.svg"];

[self animateCALayer:image.CALayerTree duration:2.0];
[myView.layer addSublayer:image.CALayerTree];

here cd-icon.svg is the svg image. Put all the html,js and css files with it in your bundle! (put whole folder of svg in your project)

If you get any error related CocoaLumberjack then install pod 'CocoaLumberjack' in your project and replace @import CocoaLumberjack; with #import "CocoaLumberjack.h" in SVGKit-prefix.pch

Follow everything step by step as I mentioned. And you are done. You will displaying svg in UIView instead of webview.


问:
Webdriver getText not returning any meaningful value
I have the following html in a page

```<code><div class="mst_updt" style=""> 27/06/2017 12:02:31 </div>
</code>```

I am trying to extract the dynamic date value between the divs :

```<code> WebElement webElement =driver.findElement(By.cssSelector(".mst_updt"));

 String text = webElement.getText();
 System.out.println("i am text : " + text);

 System.out.println("Most read 1 : " +   webElement.getText());

 String a = driver.findElement(By.cssSelector(".mst_updt")).getText();
 System.out.println("Most read 2 : " + a);
 System.out.println(webElement);

 Boolean isTheTextPresent =  driver.getPageSource().contains("mst_updt");
 System.out.println("And did we find the string ? : " + isTheTextPresent);
</code>```

you will see i am trying various methods , here are the results i am getting, why cant i extract the date and time ??

i am text :

Most read 1 :

Most read 2 :

[[FirefoxDriver: firefox on ANY (e4a9c548-6146-4685-9944-6b5d51308bff)] -> css selector: .mst_updt]

And did we find the string ? : true

Full Code which should help..

```<code><div class="content">
    <div role="main" class="content-inner content-full-width">
        <div class="main-content">
          <section class="component-list">
             <div class="section group">
                <div class="col-lrg span-lrg_1_of_3">
    <div class="component-weekly-wrap">
        <header class="header-weekly-wrap">
            <h4 itemprop="name">
                <a class="section-title-link" href="example.com/static/survey-panel">Computer Survey Panel</a>
            </h4>
        </header>
        <article>
            <a href="example.com/static/survey-panel"><img alt="" src="/w-images/fa8edbd1-2c78-4415-9abf-334f7087ff8b/2/CTGRS17OA344213-370x229.jpg" /></a>
            <div class="col-inner weekly-wrap-details">
                    <p><p>Join our <a href="example.com/static/survey-panel" target="_blank"><strong>Research Survey Panel</strong></a> and earn an Amazon voucher for each survey you complete!</p>
<p><strong><a href="example.com/static/survey-panel">Find out more</a></strong></p></p>
            <!--<a class="btn download" href="#">More information</a> -->

            </div>
            </article>
    </div>
</div>
                <!--most read homepage updated START-->
<div class= "mst_updt" style="display:none;">
28/06/2017 12:38:15
</div>
<!--most read homepage updated END-->
<div class="col-lrg component-list-most-read span-lrg_2_of_3">
    <div class="col-inner component-most-read">
        <header class="header-most-read">
            <h4 itemprop="name">Most read</h4>
        </header>
        <div class="ol">
            <ol>
                <li>

                </li>
                <li>

                </li>
                <li>

                </li>
                <li>

                </li>
                <li>

                </li>
            </ol>
        </div>
    </div>
</div>

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

答:
Try this xpath, if that's working, it means the identifier you are using is giving you wrong element. </p>

```<code>//*[contains(text(),'27/06/2017')]
</code>```

Body:
I have the following html in a page

 27/06/2017 12:02:31

I am trying to extract the dynamic date value between the divs :

 WebElement webElement =driver.findElement(By.cssSelector(".mst_updt"));

 String text = webElement.getText();
 System.out.println("i am text : " + text);

 System.out.println("Most read 1 : " +   webElement.getText());

 String a = driver.findElement(By.cssSelector(".mst_updt")).getText();
 System.out.println("Most read 2 : " + a);
 System.out.println(webElement);

 Boolean isTheTextPresent =  driver.getPageSource().contains("mst_updt");
 System.out.println("And did we find the string ? : " + isTheTextPresent);

you will see i am trying various methods , here are the results i am getting, why cant i extract the date and time ??

i am text :

Most read 1 :

Most read 2 :

[[FirefoxDriver: firefox on ANY (e4a9c548-6146-4685-9944-6b5d51308bff)] -> css selector: .mst_updt]

And did we find the string ? : true

Full Code which should help..

                Computer Survey Panel

Join our Research Survey Panel and earn an Amazon voucher for each survey you complete!

Find out more

28/06/2017 12:38:15

Most read

Body:
Try this xpath, if that's working, it means the identifier you are using is giving you wrong element.

//*[contains(text(),'27/06/2017')]


问:
Backup and Restore option not available in pgAdmin III
I have to take backup of my database but when I right click DB and then backup  The button for backup is disabled. Similarly in existing database ,not able to restore because the Restore button too disabled.
I was working fine till the time I created a new database.

How do they get enabled?

答:
There is no need for reinstall,
just open File->Options->Binary paths and add set "PG bin path" to path where pg_dump/pg_restore is located.


问:
Promise rejected or fulfilled confusion
I have a promise function

```<code>create(data) {
        return new Promise((resolve, reject) => {
            const datetime = Date.parse(new Date());
            data.createdAt = datetime;
            data.updatedAt = datetime;
            this._db.collection(this._table).insertOne(data, (err) => {
                if (err) {
                    this._logger.error(err);
                    reject(err);
                } else {
                    resolve(data);
                }
            });
        });
    }
</code>```

And write unit test for it

```<code>it('should reject insertion', () => {
    const promise = Agent.create(data).then(() => (Agent.create(data)));
    return expect(promise).to.be.rejected;
});
</code>```

This assertion passes. But if the unit test is:

```<code>it('should reject insertion', () => {
    const promise = Agent.create(data).then(Agent.create(data));
    return expect(promise).to.be.rejected;
});
</code>```

It fails. The error is AssertionError: expected promise to be rejected but it was fulfilled with { Object (_id, role, ...) }

Where is the difference between these two practices? I haven't gotten it.

答: As many in comments have indicated, You're passing a function in the first case and the return value in the other case, which is a promise. That's the reason you're seeing the differences in outcomes.</p>

Title: Promise rejected or fulfilled confusion

Body:
I have a promise function

create(data) {
        return new Promise((resolve, reject) => {
            const datetime = Date.parse(new Date());
            data.createdAt = datetime;
            data.updatedAt = datetime;
            this._db.collection(this._table).insertOne(data, (err) => {
                if (err) {
                    this._logger.error(err);
                    reject(err);
                } else {
                    resolve(data);
                }
            });
        });
    }

And write unit test for it

it('should reject insertion', () => {
    const promise = Agent.create(data).then(() => (Agent.create(data)));
    return expect(promise).to.be.rejected;
});

This assertion passes. But if the unit test is:

it('should reject insertion', () => {
    const promise = Agent.create(data).then(Agent.create(data));
    return expect(promise).to.be.rejected;
});

It fails. The error is AssertionError: expected promise to be rejected but it was fulfilled with { Object (_id, role, ...) }

Where is the difference between these two practices? I haven't gotten it.


问:
Using semantic-ui in webpack project
I'm trying to use the semantic-ui-less package, but whenever I try to import one of the .less files, I get an error saying that ../../theme.config can't be found. Of course, I have a theme.config, but it can't find it.

The .less file that's importing theme.config is located in node_modules/semantic-ui-less/src/definitions/modules/checkbox.less. With a relative path of ../.., I would expect it to want themes.config to be in node_modules/semantic-ui-less/src, but obviously I can't put my own theme.config inside of an installed node module directory - so where can I locate it so that less will be able to find it? Or is there some configuration I can pass to less-loader that will tell it how to find it?

答:
I use the solution provided in Artem Butusov's tutorial.

It solves the problem by running a postinstall script that fixes the wrong references in the semantic-ui-less package by overwriting the theme.config in node_modules with the one you provide.

It also fixes the wrong font paths in the themes.

(I came across this solution in an issue of semantic-ui-less when I was trying to solve this same problem.)

Title: Using semantic-ui in webpack project


问:
Caching Systems - Redis vs Geode/GemFire
We are considering to use a caching system to our application to do data lookup. This data will change very infrequently. My findings came out with Redis, GemFire/Geode, VoltDB, Aerospike, Hazlecast and few others. I shortlisted Geode and Redis. Both are key-value in-memory stores.

Redis (C based) seems to be easier to use and supports data types such as lists, hashes, sets, sorted sets, etc. It also has some good client available in Java, NodeJS, C#, etc. It supports multiple nodes (master-slave).

Geode (Java based) seems to have more features considering its existence dates a long back. It has concepts of regions in which stores the data. It has clients available in Java, C#, C++. It has locator(s) and server(s) which make the system. It supports distributed servers/nodes (non-shared/no single point of failure).

I searched internet but could not find any comparison between these two in terms of Read/write speed, Memory usage, Disk I/O dumping, Scaling, Security. Has anyone come across such situation before ?

答:
I'm working primarily with Redis but got to know Geode (Open-Source variant of Pivotal Gemfire) throughout the last year as I work for Pivotal. Might be biased, though.

Redis is primarily a standalone Key-Value store, driven by Salvatore Sanfilippo, HA and sharding options (Sentinel, Cluster) were built at a much later time. Redis is blazing fast, and if you favor performance over consistency, Redis is a good choice. Redis only security feature is password-based authentication, but you would rather secure it on transport-level which requires additional effort. There's no support besides the community or if you opt for a commercial Redis product (such as RedisLabs).

Geode (Open-Sourced Pivotal GemFire about a year ago, nowadays GemFire is based on Geode) is a product driven by Pivotal for many years. It's built with consistency, HA, and data distribution in mind – call it an in-memory data grid. The security layer of Geode is extensible and pluggable so you can tailor it to your needs. If you want to get commercial support, then Pivotal can serve you with your needs.

Geode features a Redis protocol adapter which allows you to connect with Redis clients to Geode and to use a subset of Redis data structures and commands. It's not complete from a Redis 3.2 perspective but still a good choice if you want to integrate with a single key-value store product, and you don't want to use Redis and Geode.


问:
Hibernate Index Query Slow
My question is similar to the one posed in this thread:
How to avoid this very heavy query that slows down the application?

We checked for missing indexes on foreign keys and found some. Adding the missing indexes actually had the opposite effect in that it slowed the query even more. One important piece of information is that our customer has a single Oracle install with our schema replicated on it 21 times. Each schema has just shy of 1,000 tables in it. Are we asking too much of Oracle with such a large number of tables (and of course indexes)? I don't know what their hardware is but my question is whether this is a reasonable approach or would it be be better to break up the users to different SIDs?

Below is the query that is being executed by Hibernate. The customer is telling us that this query is consuming about 45% of the processor when it is being executed (though I don't know for how long).

Any suggestions are appreciated,
Steve

```<code>SELECT NULL AS table_cat,
       owner AS table_schem,
       table_name,
       0 AS non_unique,
       NULL AS index_qualifier,
       NULL AS index_name,
       0 AS TYPE,
       0 AS ordinal_position,
       NULL AS column_name,
       NULL AS asc_or_desc,
       num_rows AS CARDINALITY,
       blocks AS pages,
       NULL AS filter_condition
  FROM all_tables
 WHERE table_name = 'BOOKING'
       AND owner = 'FORWARD_TN'
UNION
SELECT NULL AS table_cat,
       i.owner AS table_schem,
       i.table_name,
       DECODE (i.uniqueness, 'UNIQUE', 0, 1),
       NULL AS index_qualifier,
       i.index_name,
       1 AS TYPE,
       c.column_position AS ordinal_position,
       c.column_name,
       NULL AS asc_or_desc,
       i.distinct_keys AS CARDINALITY,
       i.leaf_blocks AS pages,
       NULL AS filter_condition
  FROM all_indexes i,
       all_ind_columns c
 WHERE     i.table_name = 'BOOKING'
       AND i.owner = 'FORWARD_TN'
       AND i.index_name = c.index_name
       AND i.table_owner = c.table_owner
       AND i.table_name = c.table_name
       AND i.owner = c.index_owner
ORDER BY non_unique,
         TYPE,
         index_name,
         ordinal_position
</code>```

答:
Our customer reviewed their Oracle configuration and changed the configuration to the following values:
optimizer_index_caching=90
optimizer_index_cost_adj=15
optimizer_mode='CHOOSE'

They report that this seems to have fixed their speed issue.

Title: Hibernate Index Query Slow

Body:
My question is similar to the one posed in this thread:
How to avoid this very heavy query that slows down the application?

We checked for missing indexes on foreign keys and found some. Adding the missing indexes actually had the opposite effect in that it slowed the query even more. One important piece of information is that our customer has a single Oracle install with our schema replicated on it 21 times. Each schema has just shy of 1,000 tables in it. Are we asking too much of Oracle with such a large number of tables (and of course indexes)? I don't know what their hardware is but my question is whether this is a reasonable approach or would it be be better to break up the users to different SIDs?

Below is the query that is being executed by Hibernate. The customer is telling us that this query is consuming about 45% of the processor when it is being executed (though I don't know for how long).

Any suggestions are appreciated,
Steve

SELECT NULL AS table_cat,
       owner AS table_schem,
       table_name,
       0 AS non_unique,
       NULL AS index_qualifier,
       NULL AS index_name,
       0 AS TYPE,
       0 AS ordinal_position,
       NULL AS column_name,
       NULL AS asc_or_desc,
       num_rows AS CARDINALITY,
       blocks AS pages,
       NULL AS filter_condition
  FROM all_tables
 WHERE table_name = 'BOOKING'
       AND owner = 'FORWARD_TN'
UNION
SELECT NULL AS table_cat,
       i.owner AS table_schem,
       i.table_name,
       DECODE (i.uniqueness, 'UNIQUE', 0, 1),
       NULL AS index_qualifier,
       i.index_name,
       1 AS TYPE,
       c.column_position AS ordinal_position,
       c.column_name,
       NULL AS asc_or_desc,
       i.distinct_keys AS CARDINALITY,
       i.leaf_blocks AS pages,
       NULL AS filter_condition
  FROM all_indexes i,
       all_ind_columns c
 WHERE     i.table_name = 'BOOKING'
       AND i.owner = 'FORWARD_TN'
       AND i.index_name = c.index_name
       AND i.table_owner = c.table_owner
       AND i.table_name = c.table_name
       AND i.owner = c.index_owner
ORDER BY non_unique,
         TYPE,
         index_name,
         ordinal_position


问:
override django admin change_list_results.html per model
I'm trying to override change_list_results.html only for a particular model. I tried copying the file as with the other templates in the corresponding tree directory ( templates/admin/APP/MODEL ), but this method didn't work. I see in the documentation that overriding per app/model is possible, but it is not described the special method to achieve this. I found some related answer about overriding change_list.html, but I want to override only change_list_results.html and I can't understand how to accomplish just that. What is the way to do this override?

答: This may have changed since freethinker6's answer: change_list_results.html is currently hardcoded.</p>


问:
Python selenium unable to click field
I'm trying to request data that I can later scrap. I write the dates in the text field but when I send the request, it does not update according to the dates. I'm trying to click the date field, but I don't see the calendar pop up as it should. How can i go about this? </p>

```<code>from selenium import webdriver
driver = webdriver.Firefox()
driver.get('https://www.fxstreet.com/economic-calendar')

time.sleep(10)

#close popup
driver.find_element_by_xpath('//button[@aria-label="Close Modal"]').click()
driver.find_element_by_id('fxit-advlink').click()

#click filter options
driver.find_element_by_id('fxit-advlink').click()

#set start and end time
driver.find_element_by_xpath("//input[contains(@id,'fxit-start-advance')]").click()
driver.find_element_by_xpath("//input[contains(@id,'fxit-start-advance')]").send_keys("01/01/2017")

driver.find_element_by_xpath("//input[contains(@id,'fxit-end-advance')]").click()
driver.find_element_by_xpath("//input[contains(@id,'fxit-end-advance')]").send_keys("06/01/2017")

#select countries

#select data type
driver.find_element_by_xpath('//a[@class="fxst-selectall" and @data-name="fxst-category"]').click()

#refresh your results
driver.find_element_by_id('fxit-filterbutton').click()
</code>```

答:
I'd double check that you are correctly selecting the elements you want. This might not be the case as you mentioned not seeing the date-time picker.

I'd recommend using the Selenium IDE (download link on their website here). It's a plugin for Firefox which allows you to record actions against a page. That way you could compare against what you have.

Title: Python selenium unable to click field

Body:
I'm trying to request data that I can later scrap. I write the dates in the text field but when I send the request, it does not update according to the dates. I'm trying to click the date field, but I don't see the calendar pop up as it should. How can i go about this?

from selenium import webdriver
driver = webdriver.Firefox()
driver.get('https://www.fxstreet.com/economic-calendar')

time.sleep(10)

#close popup
driver.find_element_by_xpath('//button[@aria-label="Close Modal"]').click()
driver.find_element_by_id('fxit-advlink').click()

#click filter options
driver.find_element_by_id('fxit-advlink').click()

#set start and end time
driver.find_element_by_xpath("//input[contains(@id,'fxit-start-advance')]").click()
driver.find_element_by_xpath("//input[contains(@id,'fxit-start-advance')]").send_keys("01/01/2017")

driver.find_element_by_xpath("//input[contains(@id,'fxit-end-advance')]").click()
driver.find_element_by_xpath("//input[contains(@id,'fxit-end-advance')]").send_keys("06/01/2017")

#select countries

#select data type
driver.find_element_by_xpath('//a[@class="fxst-selectall" and @data-name="fxst-category"]').click()

#refresh your results
driver.find_element_by_id('fxit-filterbutton').click()


问:
Unable to load div using ajax
I am using a select box to navigate to a new page but the table div data will be received from another data based on the select box. Here is my code

html page

```<code><select id="works" class="btn btn-default" style="text-align:left; background-color:#FFF" onchange="getboq(this)">
<option value=""> Select Work Name</option>
<option value="1" style="text-align:left"><?= 1 ?>
<option value="2" style="text-align:left"><?= 2 ?>
</option>
</select>
</code>```

Js file

```<code>function getboq(work)
{
var boq = work.value;
$.ajax({
            url: 'data/cont_boq.php',
            type: 'post',
            dataType: 'json',
            data: {
                boq:boq,
            },
            success: function (data) {
            window.location = 'boq.php'
                $('#boq').html(data);
            },
            error: function(){
                alert('error');
            }
        });
}
</code>```

Cont.php

Its a normal table based on select box value, How ever even i made a simple table as well to check if it works but my efforts bore no fruit

boq.php

is a simple php page having the required div

```<code><div id="boq"></div>
</code>```

Interestingly i can see the response on firebug but getting alert "error"

答:
You are wrongly using the ajax functionality.
In the success callback you are doing two things that are not compatible between them.

Choose your action:

Redirect to another page that already contains all the data that you need

Render a new element div#boq based on your ajax returned data

If you are getting the alert with "error" message add an argument to your error callback, that will contains the return data, with the error.

error: function(data) { console.log(data); }

You are parsing the return data as JSON string, this means the return data is a broken, unparsable, json string ;)

Title: Unable to load div using ajax

Body:
I am using a select box to navigate to a new page but the table div data will be received from another data based on the select box. Here is my code

html page

<select id="works" class="btn btn-default" style="text-align:left; background-color:#FFF" onchange="getboq(this)">
<option value=""> Select Work Name</option>
<option value="1" style="text-align:left"><?= 1 ?>
<option value="2" style="text-align:left"><?= 2 ?>
</option>
</select>

Js file

function getboq(work)
{
var boq = work.value;
$.ajax({
            url: 'data/cont_boq.php',
            type: 'post',
            dataType: 'json',
            data: {
                boq:boq,
            },
            success: function (data) {
            window.location = 'boq.php'
                $('#boq').html(data);
            },
            error: function(){
                alert('error');
            }
        });
}

Cont.php

Its a normal table based on select box value, How ever even i made a simple table as well to check if it works but my efforts bore no fruit

boq.php

is a simple php page having the required div

Interestingly i can see the response on firebug but getting alert "error"


问:
How to query Healthkit for average heart rate with Swift
I need to query HKStatistics for average heart rate, with Swift 2.2. I've learned from research the parameter I need is HKStatisticsOptionDiscreteAverage

I have code for the workout session. How can I add the function to this code below measuring heart-rate to return the heart rate average of the workout session with HKStatisticsOptionDiscreteAverage?

```<code>func createHeartRateStreamingQuery(workoutStartDate: NSDate) -> HKQuery? {
    // adding predicate will not work
    // let predicate = HKQuery.predicateForSamplesWithStartDate(workoutStartDate, endDate: nil, options: HKQueryOptions.None)

    guard let quantityType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate) else { return nil }

    let heartRateQuery = HKAnchoredObjectQuery(type: quantityType, predicate: nil, anchor: anchor, limit: Int(HKObjectQueryNoLimit)) { (query, sampleObjects, deletedObjects, newAnchor, error) -> Void in
        guard let newAnchor = newAnchor else {return}
        self.anchor = newAnchor
        self.updateHeartRate(sampleObjects)
    }

    heartRateQuery.updateHandler = {(query, samples, deleteObjects, newAnchor, error) -> Void in
        self.anchor = newAnchor!
        self.updateHeartRate(samples)
    }
    return heartRateQuery
}

func updateHeartRate(samples: [HKSample]?) {
    guard let heartRateSamples = samples as? [HKQuantitySample] else {return}

    dispatch_async(dispatch_get_main_queue()) {
        guard let sample = heartRateSamples.first else{return}
        let value = sample.quantity.doubleValueForUnit(self.heartRateUnit)
        self.label.setText(String(UInt16(value)))

        // retrieve source from sample
        let name = sample.sourceRevision.source.name
        self.updateDeviceName(name)
        self.animateHeart()
    }
}
</code>```

答:
```<code>    func getAVGHeartRate() {

    var typeHeart = HKQuantityType.quantityType(forIdentifier: .heartRate)
    var startDate = Date() - 7 * 24 * 60 * 60 // start date is a week
    var predicate: NSPredicate? = HKQuery.predicateForSamples(withStart: startDate, end: Date(), options: HKQueryOptions.strictEndDate)

    var squery = HKStatisticsQuery(quantityType: typeHeart!, quantitySamplePredicate: predicate, options: .discreteAverage, completionHandler: {(query: HKStatisticsQuery,result: HKStatistics?, error: Error?) -> Void in
        DispatchQueue.main.async(execute: {() -> Void in
            var quantity: HKQuantity? = result?.averageQuantity()
            var beats: Double? = quantity?.doubleValue(for: HKUnit.count().unitDivided(by: HKUnit.minute()))
            print("got: \(String(format: "%.f", beats!))")
        })
        })
    healthStore.execute(squery)
}
</code>```

<p>This is the Swift 3 version :) </p>

Body:
I need to query HKStatistics for average heart rate, with Swift 2.2. I've learned from research the parameter I need is HKStatisticsOptionDiscreteAverage

I have code for the workout session. How can I add the function to this code below measuring heart-rate to return the heart rate average of the workout session with HKStatisticsOptionDiscreteAverage?

func createHeartRateStreamingQuery(workoutStartDate: NSDate) -> HKQuery? {
    // adding predicate will not work
    // let predicate = HKQuery.predicateForSamplesWithStartDate(workoutStartDate, endDate: nil, options: HKQueryOptions.None)

    guard let quantityType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate) else { return nil }

    let heartRateQuery = HKAnchoredObjectQuery(type: quantityType, predicate: nil, anchor: anchor, limit: Int(HKObjectQueryNoLimit)) { (query, sampleObjects, deletedObjects, newAnchor, error) -> Void in
        guard let newAnchor = newAnchor else {return}
        self.anchor = newAnchor
        self.updateHeartRate(sampleObjects)
    }

    heartRateQuery.updateHandler = {(query, samples, deleteObjects, newAnchor, error) -> Void in
        self.anchor = newAnchor!
        self.updateHeartRate(samples)
    }
    return heartRateQuery
}

func updateHeartRate(samples: [HKSample]?) {
    guard let heartRateSamples = samples as? [HKQuantitySample] else {return}

    dispatch_async(dispatch_get_main_queue()) {
        guard let sample = heartRateSamples.first else{return}
        let value = sample.quantity.doubleValueForUnit(self.heartRateUnit)
        self.label.setText(String(UInt16(value)))

        // retrieve source from sample
        let name = sample.sourceRevision.source.name
        self.updateDeviceName(name)
        self.animateHeart()
    }
}

Body:
    func getAVGHeartRate() {

    var typeHeart = HKQuantityType.quantityType(forIdentifier: .heartRate)
    var startDate = Date() - 7 * 24 * 60 * 60 // start date is a week
    var predicate: NSPredicate? = HKQuery.predicateForSamples(withStart: startDate, end: Date(), options: HKQueryOptions.strictEndDate)

    var squery = HKStatisticsQuery(quantityType: typeHeart!, quantitySamplePredicate: predicate, options: .discreteAverage, completionHandler: {(query: HKStatisticsQuery,result: HKStatistics?, error: Error?) -> Void in
        DispatchQueue.main.async(execute: {() -> Void in
            var quantity: HKQuantity? = result?.averageQuantity()
            var beats: Double? = quantity?.doubleValue(for: HKUnit.count().unitDivided(by: HKUnit.minute()))
            print("got: \(String(format: "%.f", beats!))")
        })
        })
    healthStore.execute(squery)
}

This is the Swift 3 version :)


问:
Performance of Java enums
I was thinking about using enum type to manage i18n in a Java game I'm developing but I was curious about performance issues that can occur when working with enums that have lots of elements (thousands I think).

Actually I'm trying something like:

```<code>public enum Text {
  STRING1,
  STRING2,
  STRING3;

  public String text() {
    return text;
  }

  public String setText() {
    this.text = text;
  }
}
</code>```

Then to load them I can just fill the fields:

```<code>static
{
  Text.STRING1.setText("My localized string1");
  Text.STRING2.setText("My localized string2");
  Text.STRING3.setText("My localized string3");
}
</code>```

Of course when I'll have to manage many languages I'll load them from a file.

What I'm asking is

is an obect allocated (in addition to the string) for every element? (I guess yes, since enums are implemented with objects)

how is the right element retrieved from the enum? is it static at compile time? (I mean when somewhere I use Text.STRING1.text()). So it should be constant complexity or maybe they are just replaced during the compiling phase..

in general, is it a good approach or should I look forward something else?

Thanks

答:
You're probably better off using the java.util.ResourceBundle class. It is designed to solve exactly this problem.

To answer your questions:

Yes, there is exactly one instance of each enum value.

Yes, constant complexity for looking up an Enum value.

Not really. Changing the content/behaviour of the enum kinda defeats the purpose of having enums in the first place. They're supposed to represent fixed-range constants with type safety. You can do this kind of thing but that's not what they were designed for.

Title: Performance of Java enums

Body:
I was thinking about using enum type to manage i18n in a Java game I'm developing but I was curious about performance issues that can occur when working with enums that have lots of elements (thousands I think).

Actually I'm trying something like:

public enum Text {
  STRING1,
  STRING2,
  STRING3;

  public String text() {
    return text;
  }

  public String setText() {
    this.text = text;
  }
}

Then to load them I can just fill the fields:

static
{
  Text.STRING1.setText("My localized string1");
  Text.STRING2.setText("My localized string2");
  Text.STRING3.setText("My localized string3");
}

Of course when I'll have to manage many languages I'll load them from a file.

What I'm asking is

is an obect allocated (in addition to the string) for every element? (I guess yes, since enums are implemented with objects)

how is the right element retrieved from the enum? is it static at compile time? (I mean when somewhere I use Text.STRING1.text()). So it should be constant complexity or maybe they are just replaced during the compiling phase..

in general, is it a good approach or should I look forward something else?

Thanks


问:
Pandas: Delete row based on a condition of more than one column
I have a DataFrame "df" with three columns named: "Particle", "Frequency1", "Frequency2" and a lot of rows.

I want to delete the rows where Frequency1 and Frequency2 are simoustaneously equal to 0.

What is the sintax for doing this?

答:
You can also use: df = (df[df.Frequency1 == 0] & df[df.Frequency2 == 0]).

This will delete the row which has 0 in both columns of 'Frequency1andFrequency2`.


问:
Vuejs extending a parent component from child
I'm trying to put HTML from a child component in a parent component.

ChildComponent.vue

```<code><template>
  <parent>
    <h3>test</h3>
  </parent>
</template>
</code>```

Much like Laravel's @yield and @section

In my scenario, I have the menubars for my app in the parent <template> and want to fill the space beneath it via the child component.

Does anyone know whether and/or how it's possible to do this?

答: If you are just looking to extend without the use of VueRouter, take a look at the slots docs: https://v2.vuejs.org/v2/guide/components.html#Single-Slot</p>

Body:
I'm trying to put HTML from a child component in a parent component.

ChildComponent.vue

<template>
  <parent>

test

  </parent>
</template>

Much like Laravel's @yield and @section

In my scenario, I have the menubars for my app in the parent <template> and want to fill the space beneath it via the child component.

Does anyone know whether and/or how it's possible to do this?

ContentLicense: CC BY-SA 4.0


问:
How do the different compression levels of gzip differ?
I am trying to better understand how different compression levels  (1-9) of gzip differ in the way that encoding is implemented.

I've looked the zlib C source code and it seems that it has to do with how exhaustive the search for the longest matching string is, but looking for more specific information.

For example, do the levels yield any differences in the assignment of Huffman codes?

答:
The levels differ only in how hard deflate looks for matching strings, as you observed. The Huffman coding is done on a chosen fixed number of symbols (literals and length/distance pairs), producing a "block", where that number is defined by the memory level, not the compression level. The Huffman codes generated will necessarily differ, since the symbols being coded will differ.

The choice of memory level also has some effect on compression, as a larger number of symbols spreads the cost of the code description for a block over more symbols, but too many symbols may prevent adaptation of the Huffman codes to local changes in the statistics of the symbols. The default memory level is 8 (resulting in 16,383 symbols per block), since testing indicated that that gave better compression than level 9 (32,767 symbols per block). However your mileage may vary.


问:
Intellij error=2 No such file or directory
Installed intellij and added sdk path to project structure, but when i try to run i get:

```<code>Error: Cannot run program "/home/$USER/java/jdk1.8.0_121/bin/java"
(in directory"/home/$USER/.intelliJIdea2016.3/system/compile-server"):
error=2, No such file or directory
</code>```

Both files (/home/$USER/java/jdk1.8.0_121/bin/java and /home/$USER/.intelliJIdea2016.3/system/compile-server) exists.

I am using Ubuntu 16.10

答:
The answer from here Change jdk path in IntelliJ 13 when compiling from 32 bit program file folder to 64 bit one worked for me

From the menu: File -> Project Structure....

On the left, below "Platform Settings", you have "SDKs": click on it; you can add your new JDK here.

Always in the same window, below "Project Settings", select "Project": you have the option to select the JDK which you just added.

Body:
Installed intellij and added sdk path to project structure, but when i try to run i get:

Error: Cannot run program "/home/$USER/java/jdk1.8.0_121/bin/java"
(in directory"/home/$USER/.intelliJIdea2016.3/system/compile-server"):
error=2, No such file or directory

Both files (/home/$USER/java/jdk1.8.0_121/bin/java and /home/$USER/.intelliJIdea2016.3/system/compile-server) exists.

I am using Ubuntu 16.10