问:
Interpreting CISC as RISC
I'm preparing for a test in computer science and there's this question that keeps coming up in previous tests that I can't find an answer to.

Consider the execution of the two instructions below on a typical RISC architecture with only one addressing mode (Reg + Offset).

```<code>804836e:    40            inc    %eax
804836f:    89 04 91      mov    %eax,(%ecx,%edx,4)
</code>```

Explain, justifying, how these 2 IA-32 instructions would be compiled for this architecture, using IA-32 sintaxe to show that code.

Comment on the size of this piece of code on the RISC architecture versus the IA-32.

The C function is :

```<code>voidpara_par (int a[], int n) {
    int i;
    for (i=0 ; i<n ; i++) {
        if (a[i] & 0x01) {
            a[i] += 1;
        }
    }
}
</code>```

Which receives an array of ints and increments the value of the odd ones.

For reference:

```<code>%eax -> int i
(%ecx,%edx,4) -> int, part of the array "a" saved to %ecx
</code>```

I know this question feels vague to say the least but that's my problem, I don't really know how to begin "translating" from one architecture to the other.

答:
```<code>inc eax
mov [ecx+edx*4],eax
</code>```

is pretty much using trivial instructions, so why this is not actual answer also for RISC-like?

Because the constraint is "only one addressing mode (Reg + Offset)." (and also it's unlikely the RISC will have inc, but that can be "fixed" by simple add eax,1).

So you have to convert the addressing from the base_reg + index_reg*index_size_imm + ofs x86 addressing mode to reg + ofs. If you will think about it for a short while, there's no reasonable way to use the "ofs" part, unless you create self-modifying code, putting some nifty ofs into the instruction opcode before executing it.. so it's narrowed down to task "do it by (reg+0) addressing mode".

And so you do the address math "manually"

```<code>add  eax,1   ; inc eax
shl  edx,2   ; edx = edx*4
add  ecx,edx ; ecx = ecx + edx*4
mov  [ecx+0],eax
</code>```

Done. (Intel syntax used intentionally, because I don't think the GAS/AT&T is supposed to be used by humans).

all the explaining/reasoning about result left to the OP, because he should try. :) (let me know in comment if you get stuck)

BTW, if you would translate that whole C part, it would certainly lead to more optimal machine code, without the *4 multiplying in the first place, so both x86 and "RISC" machine code would look lot more similar, except the x86 can manipulate the array element directly in memory:

DANG, I managed to create "increase every element", missed the if part, sorry.... not going to fix, as this illustrates the looping vs indexing thing any way, which was my original intention to point out, that the original mov %eax,(%ecx, %edx, 4) is quite artificial and would be hardly found in optimized machine code.

```<code>    eax = array + n*4
    ecx = -n*4
loop:
    inc dword [eax+ecx]
    add ecx,4
    jnz loop
</code>```

RISC-like version:

```<code>    ebx = array
    ecx = n
loop:
    mov eax,[ebx]
    add eax,1
    mov [ebx],eax
    add ebx,4
    sub ecx,1
    jnz loop
</code>```

Again no index needed, that's high level stuff, which can be usually easily avoided in optimized machine code, with enough fixed constraints about data structure, like here each element is of fixed 4-byte size.

Title: Interpreting CISC as RISC

Body:
I'm preparing for a test in computer science and there's this question that keeps coming up in previous tests that I can't find an answer to.

Consider the execution of the two instructions below on a typical RISC architecture with only one addressing mode (Reg + Offset).

804836e:    40            inc    %eax
804836f:    89 04 91      mov    %eax,(%ecx,%edx,4)

Explain, justifying, how these 2 IA-32 instructions would be compiled for this architecture, using IA-32 sintaxe to show that code.

Comment on the size of this piece of code on the RISC architecture versus the IA-32.

The C function is :

voidpara_par (int a[], int n) {
    int i;
    for (i=0 ; i<n ; i++) {
        if (a[i] & 0x01) {
            a[i] += 1;
        }
    }
}

Which receives an array of ints and increments the value of the odd ones.

For reference:

%eax -> int i
(%ecx,%edx,4) -> int, part of the array "a" saved to %ecx

I know this question feels vague to say the least but that's my problem, I don't really know how to begin "translating" from one architecture to the other.

Body:
inc eax
mov [ecx+edx*4],eax

is pretty much using trivial instructions, so why this is not actual answer also for RISC-like?

Because the constraint is "only one addressing mode (Reg + Offset)." (and also it's unlikely the RISC will have inc, but that can be "fixed" by simple add eax,1).

So you have to convert the addressing from the base_reg + index_reg*index_size_imm + ofs x86 addressing mode to reg + ofs. If you will think about it for a short while, there's no reasonable way to use the "ofs" part, unless you create self-modifying code, putting some nifty ofs into the instruction opcode before executing it.. so it's narrowed down to task "do it by (reg+0) addressing mode".

And so you do the address math "manually"

add  eax,1   ; inc eax
shl  edx,2   ; edx = edx*4
add  ecx,edx ; ecx = ecx + edx*4
mov  [ecx+0],eax

Done. (Intel syntax used intentionally, because I don't think the GAS/AT&T is supposed to be used by humans).

all the explaining/reasoning about result left to the OP, because he should try. :) (let me know in comment if you get stuck)

BTW, if you would translate that whole C part, it would certainly lead to more optimal machine code, without the *4 multiplying in the first place, so both x86 and "RISC" machine code would look lot more similar, except the x86 can manipulate the array element directly in memory:

DANG, I managed to create "increase every element", missed the if part, sorry.... not going to fix, as this illustrates the looping vs indexing thing any way, which was my original intention to point out, that the original mov %eax,(%ecx, %edx, 4) is quite artificial and would be hardly found in optimized machine code.

    eax = array + n*4
    ecx = -n*4
loop:
    inc dword [eax+ecx]
    add ecx,4
    jnz loop

RISC-like version:

    ebx = array
    ecx = n
loop:
    mov eax,[ebx]
    add eax,1
    mov [ebx],eax
    add ebx,4
    sub ecx,1
    jnz loop

Again no index needed, that's high level stuff, which can be usually easily avoided in optimized machine code, with enough fixed constraints about data structure, like here each element is of fixed 4-byte size.


来源: stackexchange

问:
IoException error when save button is selected
Beloew is my code which i want to save some info the user key in to be saved to the file, how come i keep encountering Ioexception error after i debug and click on the save button..pls kindly adv..thks!!! i guess it has something to do with the filefolder but have absolutely no idea..</p>

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace ASSISNMENTTT
{
    public partial class Registeration : Form
    {
        public Registeration()
        {
            InitializeComponent();
        }

        private void Btn_Save_Click(object sender, EventArgs e)
        {
            // This is the button labeled "Save" in the program.
            //
            File.WriteAllText("C:\\demo.txt", Tb_Admin.Text);
            File.WriteAllText("C:\\demo.txt", Tb_Name.Text);
            File.WriteAllText("C:\\demo.txt", Tb_Gender.Text);
        }
    }
}
</code>```

答:
If your app does have access to the C:\ drive, demo.txt is likely marked read-only as WriteAllText will attempt to overwrite the file.

This code shows an UnauthorizedAccessException with the same error text as you are commenting on your question and on the other answer.

```<code>static void Main(string[] args)
{
    var demoTxt = new FileInfo("C:\\demo.txt");
    demoTxt.Attributes |= FileAttributes.ReadOnly;

    WriteAllText("should succeed");

    try
    {
        demoTxt.Attributes |= FileAttributes.ReadOnly;
        WriteAllText("should fail");
    }
    catch (UnauthorizedAccessException uae)
    {
        Debug.WriteLine(uae.ToString());
    }
}

static void WriteAllText(string text)
{
    // This is the button labeled "Save" in the program.
    //
    File.WriteAllText("C:\\demo.txt", text);
}
</code>```

For future reference, this may help you give more information for SO posts.

```<code>    private void Btn_Save_Click(object sender, EventArgs e)
    {
        try
        {
            // This is the button labeled "Save" in the program.
            //
            File.WriteAllText("C:\\demo.txt", Tb_Admin.Text);
            File.WriteAllText("C:\\demo.txt", Tb_Name.Text);
            File.WriteAllText("C:\\demo.txt", Tb_Gender.Text);
        }
        catch(IoException ex)
        {
            //View the Output Window, copy the text to your question
            System.Diagnostics.Debug.WriteLine(ex.ToString());
        }
    }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Beloew is my code which i want to save some info the user key in to be saved to the file, how come i keep encountering Ioexception error after i debug and click on the save button..pls kindly adv..thks!!! i guess it has something to do with the filefolder but have absolutely no idea..

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace ASSISNMENTTT
{
    public partial class Registeration : Form
    {
        public Registeration()
        {
            InitializeComponent();
        }

        private void Btn_Save_Click(object sender, EventArgs e)
        {
            // This is the button labeled "Save" in the program.
            //
            File.WriteAllText("C:\\demo.txt", Tb_Admin.Text);
            File.WriteAllText("C:\\demo.txt", Tb_Name.Text);
            File.WriteAllText("C:\\demo.txt", Tb_Gender.Text);
        }
    }
}

Body:
If your app does have access to the C:\ drive, demo.txt is likely marked read-only as WriteAllText will attempt to overwrite the file.

This code shows an UnauthorizedAccessException with the same error text as you are commenting on your question and on the other answer.

static void Main(string[] args)
{
    var demoTxt = new FileInfo("C:\\demo.txt");
    demoTxt.Attributes |= FileAttributes.ReadOnly;

    WriteAllText("should succeed");

    try
    {
        demoTxt.Attributes |= FileAttributes.ReadOnly;
        WriteAllText("should fail");
    }
    catch (UnauthorizedAccessException uae)
    {
        Debug.WriteLine(uae.ToString());
    }
}

static void WriteAllText(string text)
{
    // This is the button labeled "Save" in the program.
    //
    File.WriteAllText("C:\\demo.txt", text);
}

For future reference, this may help you give more information for SO posts.

    private void Btn_Save_Click(object sender, EventArgs e)
    {
        try
        {
            // This is the button labeled "Save" in the program.
            //
            File.WriteAllText("C:\\demo.txt", Tb_Admin.Text);
            File.WriteAllText("C:\\demo.txt", Tb_Name.Text);
            File.WriteAllText("C:\\demo.txt", Tb_Gender.Text);
        }
        catch(IoException ex)
        {
            //View the Output Window, copy the text to your question
            System.Diagnostics.Debug.WriteLine(ex.ToString());
        }
    }


问:
How to convert UInt16 to UInt8 in Swift 3?
I want to convert UInt16 to UInt8 array, but am getting the following error message:

'init' is unavailable: use 'withMemoryRebound(to:capacity:_)' to
  temporarily view memory as another layout-compatible type.

The code:

```<code>    let statusByte: UInt8 = UInt8(status)
    let lenghtByte: UInt16 = UInt16(passwordBytes.count)

    var bigEndian = lenghtByte.bigEndian

    let bytePtr = withUnsafePointer(to: &bigEndian) {
        UnsafeBufferPointer<UInt8>(start: UnsafePointer($0), count: MemoryLayout.size(ofValue: bigEndian))
    }
</code>```

答:
You can extend Numeric protocol and create a data property as follow:

Swift 4 or later

```<code>extension Numeric {
    var data: Data {
        var source = self
        return Data(bytes: &source, count: MemoryLayout<Self>.size)
    }
}
</code>```

Since Swift 3 Data conforms to RandomAccessCollection so you can just create an array of bytes from your UInt16 bigEndian data:

```<code>extension Data {
    var array: [UInt8] { return Array(self) }
}
</code>```

```<code>let lenghtByte = UInt16(8)
let bytePtr = lenghtByte.bigEndian.data.array   // [0, 8]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to convert UInt16 to UInt8 array, but am getting the following error message:

'init' is unavailable: use 'withMemoryRebound(to:capacity:_)' to
  temporarily view memory as another layout-compatible type.

The code:

    let statusByte: UInt8 = UInt8(status)
    let lenghtByte: UInt16 = UInt16(passwordBytes.count)

    var bigEndian = lenghtByte.bigEndian

    let bytePtr = withUnsafePointer(to: &bigEndian) {
        UnsafeBufferPointer<UInt8>(start: UnsafePointer($0), count: MemoryLayout.size(ofValue: bigEndian))
    }

Body:
You can extend Numeric protocol and create a data property as follow:

Swift 4 or later

extension Numeric {
    var data: Data {
        var source = self
        return Data(bytes: &source, count: MemoryLayout<Self>.size)
    }
}

Since Swift 3 Data conforms to RandomAccessCollection so you can just create an array of bytes from your UInt16 bigEndian data:

extension Data {
    var array: [UInt8] { return Array(self) }
}

let lenghtByte = UInt16(8)
let bytePtr = lenghtByte.bigEndian.data.array   // [0, 8]

ContentLicense: CC BY-SA 4.0


问:
How to add a window to apps I am observing using AccessibilityService?
I am developing a floating window, which will be shown on apps I am observing using AccessibilityService.
But I don't want the window shown on other apps.

So I firstly configure the android:packageNames property of <accessibility-service>. Then find some solutions to check whether user is using apps I configured, like getRunningTasks, getRunningAppProcesses and UsageStatsManager. But they all have some shortcomings.

The question is:

Is there any way to check whether apps I configured using Accessibility is foreground currently?

OR:

Is there any way to make the window shown on apps I configured using Accessiblity and not shown on other apps?

Thanks a lot!

答:
Thanks to idea of @ataulm !

I find a perfect way of checking whether my apps are in foreground:

set accessibility's packageName to all

set accessibility's EventTypes to typeAllMask

Java:

```<code>public void onAccessibilityEvent(AccessibilityEvent event) {
    if (event == null || event.getSource() == null) {
        return;
    }
    AccessibilityNodeInfo source = event.getSource();
    String className = source.getClassName().toString();
    switch (event.getEventType()) {
        case AccessibilityEvent.TYPE_VIEW_SCROLLED:
            Log.i(TAG, "onAccessibilityEvent: scrolled");
            break;
        case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED:
            setForegroundApp(event.getPackageName());
            break;
        }
}

public static String sForegroundPackageName;
static final List<String> supportedPackagesName = blablablabla;

public static void setForegroundApp(CharSequence packageName) {
    if (packageName != null) {
        sForegroundPackageName = packageName.toString();
    }
}

// use this to check.
public static boolean isForeground() {
    return supportedPackagesName.contains(sForegroundPackageName);
}
</code>```

Body:
Thanks to idea of @ataulm !

I find a perfect way of checking whether my apps are in foreground:

set accessibility's packageName to all

set accessibility's EventTypes to typeAllMask

Java:

public void onAccessibilityEvent(AccessibilityEvent event) {
    if (event == null || event.getSource() == null) {
        return;
    }
    AccessibilityNodeInfo source = event.getSource();
    String className = source.getClassName().toString();
    switch (event.getEventType()) {
        case AccessibilityEvent.TYPE_VIEW_SCROLLED:
            Log.i(TAG, "onAccessibilityEvent: scrolled");
            break;
        case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED:
            setForegroundApp(event.getPackageName());
            break;
        }
}

public static String sForegroundPackageName;
static final List<String> supportedPackagesName = blablablabla;

public static void setForegroundApp(CharSequence packageName) {
    if (packageName != null) {
        sForegroundPackageName = packageName.toString();
    }
}

// use this to check.
public static boolean isForeground() {
    return supportedPackagesName.contains(sForegroundPackageName);
}


问:
jQuery custom core : use just what you need
As you may have guessed, I'm trying to speed up page loading on my website.
So since I Don't use most of jQuery's functions, I thought that I could use a "lighter" version.

Is there an easy way to get your custom version of jQuery (like with jQuery UI)?

答: Probably you are looking at the wrong place to solve your problem. In most cases minified JQuery from a CDN like google doesn't take much of your time. I would look at other things that are taking up time onload.</p>


问:
Build .md vignette using devtools
I’m using knitr::rmarkdown (but knitr::knitr does the same) as my VignetteEngine. I then build my package vignette using devtools::build_vignettes().

This works, but only creates HTML and R output files in inst/doc. What I want is a Markdown output file, since only that can be displayed directly within the Github project pages (for HTML files, Github shows the source and for Rmd files it shows a rendered output but — obviously — without executing the R blocks).

I’ve tried finding out how to specify the output for custom VignetteEngines and I think that it should be possible (after all, other packages use this to build PDF vignettes, at a minimum) but I cannot find a way of doing this via devtools::build_vignettes. Is there no way around building the vignette manually (i.e. via knitr::knit or similar mechanisms that ignore the VignetteBuilder directives)?

I can’t find relevant information in the documentation/source either.

答:
The only output formats for vignettes are HTML and PDF (and LaTeX, but it is converted to PDF, not displayed).  Markdown isn't supported.

You can have arbitrary documentation files in your package (by convention you put them in inst/doc), but they aren't considered to be vignettes, so they won't be automatically built, functions like browseVignettes() will ignore them, etc.

To convert an Rmd file to md, just run knitr::knit on it.

Title: Build .md vignette using devtools


问:
Caliburn.Micro's OnUnhandledException not called
I have overridden the OnUnhandledException in my bootstrapper, but in the following scenario it is not called:

```<code>public class Foo : IHandle<Bar> {
    public void Handle(Bar message) {
        // Do something that requires UI thread
    }

    public void DoSomething() {
        eventAggregator.PublishOnBackgroundThread(new Bar());
    }
}
</code>```

When the handle method is called it will throw InvalidOperationException: The calling thread must be STA, because many UI components require this. because it is performed on the background thread instead of on the UI thread:

That exception is never caught by OnUnhandledException in my bootstrapper. Neither is it caught by the Application.DispatcherUnhandledException event handler.

How can I make a general exception handler that will also catch these types of exceptions, without having to implement try/catch everywhere?

答: As per the Caliburn.Micro GitHub it appears this is a known problem, and is something that they're actively working on solving. You may wish to join the conversation over there and see if there are any stop-gap solutions for the time being.</p>

Body:
I have overridden the OnUnhandledException in my bootstrapper, but in the following scenario it is not called:

public class Foo : IHandle<Bar> {
    public void Handle(Bar message) {
        // Do something that requires UI thread
    }

    public void DoSomething() {
        eventAggregator.PublishOnBackgroundThread(new Bar());
    }
}

When the handle method is called it will throw InvalidOperationException: The calling thread must be STA, because many UI components require this. because it is performed on the background thread instead of on the UI thread:

That exception is never caught by OnUnhandledException in my bootstrapper. Neither is it caught by the Application.DispatcherUnhandledException event handler.

How can I make a general exception handler that will also catch these types of exceptions, without having to implement try/catch everywhere?


问:
How to populate dropdown in thymeleaf with hashmap set from controller
I want the dropdown  in the view to be get filled with value set from the controller. In my controller using model attribute I have added the list limits

```<code> @RequestMapping(value = "/works", method = RequestMethod.GET)
  public String searchWorks(Model model){
     Map< Integer, String > limits = new HashMap<Integer, String>();
        limits.put(20, "20件");
        limits.put(25, "25件");
        limits.put(30, "30件");
        limits.put(35, "35件");
        limits.put(40, "40件");
        limits.put(45, "45件");
        limits.put(50, "50件");
    model.addAttribute("limits",limits);
    model.addAttribute("limit",limit);
    return "workSituation";
  }
</code>```

In view Page in order to populate the dropdown with the value set using model attribute I have used this code

```<code> <div class="col-sm-3">
                <select class="form-control" name = "limit" id="limit" onchange="getList(this.value)">
                  <option selected>-- select number of items--</option>

                  <option data-th-each="limit : ${limits}"
                                      data-th-value="${limt.getKey()}"
                                      data-th-text="${limt.getValue()}"  >

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

I am getting the error

```<code>caused by: org.attoparser.ParseException: Exception evaluating SpringEL expression: "limt.getKey()"

caused by: org.attoparser.ParseException: Exception evaluating SpringEL expression: "limt.getValue()"
</code>```

What will be the cause for this. Actually dropdown is iterating 7 times(the number of records in the limits list) but the key and value is not able to fetch with code.What is the correct way to get the dropdown filled with

```<code>          <option value="20">20件</option>
          <option value="25">25件</option>
          <option value="30">30件</option>
          <option value="35">35件</option>
          <option value="40">40件</option>
          <option value="45">45件</option>
          <option value="50">50件</option>
</code>```

答:
For thymeleaf try the following</p>

```<code><option th:each="limit : ${limits.entrySet()}" th:value="${limit.key}" th:text="${limit.value}"></option>
</code>```

Body:
I want the dropdown  in the view to be get filled with value set from the controller. In my controller using model attribute I have added the list limits

 @RequestMapping(value = "/works", method = RequestMethod.GET)
  public String searchWorks(Model model){
     Map< Integer, String > limits = new HashMap<Integer, String>();
        limits.put(20, "20件");
        limits.put(25, "25件");
        limits.put(30, "30件");
        limits.put(35, "35件");
        limits.put(40, "40件");
        limits.put(45, "45件");
        limits.put(50, "50件");
    model.addAttribute("limits",limits);
    model.addAttribute("limit",limit);
    return "workSituation";
  }

In view Page in order to populate the dropdown with the value set using model attribute I have used this code

                <select class="form-control" name = "limit" id="limit" onchange="getList(this.value)">
                  <option selected>-- select number of items--</option>

                  <option data-th-each="limit : ${limits}"
                                      data-th-value="${limt.getKey()}"
                                      data-th-text="${limt.getValue()}"  >

                   </select>

I am getting the error

caused by: org.attoparser.ParseException: Exception evaluating SpringEL expression: "limt.getKey()"

caused by: org.attoparser.ParseException: Exception evaluating SpringEL expression: "limt.getValue()"

What will be the cause for this. Actually dropdown is iterating 7 times(the number of records in the limits list) but the key and value is not able to fetch with code.What is the correct way to get the dropdown filled with

          <option value="20">20件</option>
          <option value="25">25件</option>
          <option value="30">30件</option>
          <option value="35">35件</option>
          <option value="40">40件</option>
          <option value="45">45件</option>
          <option value="50">50件</option>

Body:
For thymeleaf try the following

<option th:each="limit : ${limits.entrySet()}" th:value="${limit.key}" th:text="${limit.value}"></option>


问:
C# Discord Bot: How can I check if a user has said a specific phrase?
So I'm trying to create a bot that responds to a certain line of text in my discord server. I want to check if my friend says "no u" (he says that a lot, he has the mentality of a five year old) and I want my bot to respond to this statement. I'm still relatively new to C# and have looked desperately everywhere for this answer. If you can help, that would be greatly appreciated!  </p>

答: You should checkout this example from the Discord.Net GitHub. Essentially you need to subscribe to the MessageReceived event and then reply based on the message.


问:
Unable to remove white space from data frame and hence was not able to find mean
I need to find the mean of this value where
class(newtemp)
is character .The data was original 10.6 °C like this. i removed °C but space is there due to which as.numeric is not working.

```<code>newtemp

 [1] "-10.6 " "-10.6 " "-11.0 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 "

[12] "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-11.0 "

[23] "-10.6 " "-10.6 " "-10.6 " "-11.0 " "-10.6 " "-10.0 " "-10.0 " "-10.0 " "-10.0 " "-10.0 " "-9.4 "

[34] "-8.9 "  "-8.3 "  "-7.2 "  "-7.2 "  "-5.6 "  "-5.0 "  "-3.9 "  "-3.9 "  "-3.9 "  "-3.3 "  "-3.3 "

[45] "-3.9 "  "-6.1 "  "-8.3 "  "-7.8 "  "-8.9 "  "-10.0 " "-11.7 " "-12.8 "

#Tried this
library(stringr)
try=str_replace_all(newtemp, fixed(" "), "") but not able to remove
#Tried this also
trim <- function (x) gsub("^\\s+|\\s+$", "", x)
trim(x =newtemp)
# STill not removed

as.numeric(try)

 [1] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA

[36] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
#Warning message:
#NAs introduced by coercion
#Sill no output.
</code>```

The code i m using is :

```<code>    library(rvest)
linkurl="https://www.wunderground.com/history/airport/KVAY/2015/2/17/DailyHistory.html?req_city=Cherry+Hill&req_state=NJ&req_statename=New+Jersey&reqdb.zip=08002&reqdb.magic=1&reqdb.wmo=99999&MR=1"
weathertable=read_html(linkurl)%>%html_node("#obsTable")%>%html_table()
weathertable
newtemp=weathertable$Temp.

abc=(gsub("°C", "", newtemp))
abc
abc_new=(gsub("[[:space:]]", "", abc))
as.numeric(abc_new)
trimws(x=abc)
as.numeric(trimws(x=abc))
</code>```

Update

```<code>        > newtemp
     [1] "-10.6 °C" "-10.6 °C" "-11.0 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C"
    [10] "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C"
    [19] "-10.6 °C" "-10.6 °C" "-10.6 °C" "-11.0 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-11.0 °C" "-10.6 °C"
    [28] "-10.0 °C" "-10.0 °C" "-10.0 °C" "-10.0 °C" "-10.0 °C" "-9.4 °C"  "-8.9 °C"  "-8.3 °C"  "-7.2 °C"
    [37] "-7.2 °C"  "-5.6 °C"  "-5.0 °C"  "-3.9 °C"  "-3.9 °C"  "-3.9 °C"  "-3.3 °C"  "-3.3 °C"  "-3.9 °C"
    [46] "-6.1 °C"  "-8.3 °C"  "-7.8 °C"  "-8.9 °C"  "-10.0 °C" "-11.7 °C" "-12.8 °C"
    > abc=(gsub(" °C", "", newtemp))
    > abc
     [1] "-10.6 °C" "-10.6 °C" "-11.0 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C"
    [10] "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C"
    [19] "-10.6 °C" "-10.6 °C" "-10.6 °C" "-11.0 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-11.0 °C" "-10.6 °C"
    [28] "-10.0 °C" "-10.0 °C" "-10.0 °C" "-10.0 °C" "-10.0 °C" "-9.4 °C"  "-8.9 °C"  "-8.3 °C"  "-7.2 °C"
    [37] "-7.2 °C"  "-5.6 °C"  "-5.0 °C"  "-3.9 °C"  "-3.9 °C"  "-3.9 °C"  "-3.3 °C"  "-3.3 °C"  "-3.9 °C"
    [46] "-6.1 °C"  "-8.3 °C"  "-7.8 °C"  "-8.9 °C"  "-10.0 °C" "-11.7 °C" "-12.8 °C"
    > abc=(gsub("°C", "", newtemp))
> abc
 [1] "-10.6 " "-10.6 " "-11.0 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 "
[12] "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-11.0 "
[23] "-10.6 " "-10.6 " "-10.6 " "-11.0 " "-10.6 " "-10.0 " "-10.0 " "-10.0 " "-10.0 " "-10.0 " "-9.4 "
[34] "-8.9 "  "-8.3 "  "-7.2 "  "-7.2 "  "-5.6 "  "-5.0 "  "-3.9 "  "-3.9 "  "-3.9 "  "-3.3 "  "-3.3 "
[45] "-3.9 "  "-6.1 "  "-8.3 "  "-7.8 "  "-8.9 "  "-10.0 " "-11.7 " "-12.8 "
>
</code>```

答:
You could avoid the whole issue by using readr::parse_number:

library(rvest)
library(tidyverse)

url <- "https://www.wunderground.com/history/airport/KVAY/2015/2/17/DailyHistory.html?req_city=Cherry+Hill&req_state=NJ&req_statename=New+Jersey&reqdb.zip=08002&reqdb.magic=1&reqdb.wmo=99999&MR=1"

h <- url %>% read_html()

obs <- h %>%
    html_node('#obsTable') %>%
    html_table()

obs_clean <- obs %>%
    mutate(Temp. = parse_number(Temp.)) %>%
    tbl_df()   # for printing

obs_clean
#> # A tibble: 52 x 13
#>    `Time (EST)` Temp. Windchill `Dew Point` Humidity Pressure Visibility
#>           <chr> <dbl>     <chr>       <chr>    <chr>    <chr>      <chr>
#>  1     12:33 AM  12.9         -      8.1 °F      81% 30.08 in     2.0 mi
#>  2     12:45 AM  12.9         -      8.1 °F      81% 30.05 in     1.2 mi
#>  3     12:51 AM  12.2         -      8.6 °F      85% 30.05 in     0.8 mi
#>  4     12:54 AM  12.9         -      9.0 °F      84% 30.06 in     0.8 mi
#>  5      1:02 AM  12.9         -      9.0 °F      84% 30.05 in     0.5 mi
#>  6      1:25 AM  12.9         -      9.0 °F      84% 30.02 in     1.0 mi
#>  7      1:37 AM  12.9    6.9 °F      9.0 °F      84% 30.03 in     0.8 mi
#>  8      1:54 AM  12.9    6.9 °F      9.0 °F      84% 30.02 in     0.8 mi
#>  9      2:18 AM  12.9    5.2 °F      9.0 °F      84% 30.01 in     1.0 mi
#> 10      2:40 AM  12.9    5.2 °F      9.0 °F      84% 29.99 in     1.0 mi
#> # ... with 42 more rows, and 6 more variables: `Wind Dir` <chr>, `Wind
#> #   Speed` <chr>, `Gust Speed` <chr>, Precip <chr>, Events <chr>,
#> #   Conditions <chr>
```

<p>or with regex,</p>

<pre class="lang-r prettyprint-override"><code>obs %>% mutate(Temp. = as.numeric(gsub('[\\W°FC]', '', Temp.))) %>% tbl_df()
</code>```

which returns the same thing.

Body:
I need to find the mean of this value where
class(newtemp)
is character .The data was original 10.6 °C like this. i removed °C but space is there due to which as.numeric is not working.

newtemp

 [1] "-10.6 " "-10.6 " "-11.0 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 "

[12] "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-11.0 "

[23] "-10.6 " "-10.6 " "-10.6 " "-11.0 " "-10.6 " "-10.0 " "-10.0 " "-10.0 " "-10.0 " "-10.0 " "-9.4 "

[34] "-8.9 "  "-8.3 "  "-7.2 "  "-7.2 "  "-5.6 "  "-5.0 "  "-3.9 "  "-3.9 "  "-3.9 "  "-3.3 "  "-3.3 "

[45] "-3.9 "  "-6.1 "  "-8.3 "  "-7.8 "  "-8.9 "  "-10.0 " "-11.7 " "-12.8 "

#Tried this
library(stringr)
try=str_replace_all(newtemp, fixed(" "), "") but not able to remove
#Tried this also
trim <- function (x) gsub("^\\s+|\\s+$", "", x)
trim(x =newtemp)
# STill not removed

as.numeric(try)

 [1] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA

[36] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
#Warning message:
#NAs introduced by coercion
#Sill no output.

The code i m using is :

    library(rvest)
linkurl="https://www.wunderground.com/history/airport/KVAY/2015/2/17/DailyHistory.html?req_city=Cherry+Hill&req_state=NJ&req_statename=New+Jersey&reqdb.zip=08002&reqdb.magic=1&reqdb.wmo=99999&MR=1"
weathertable=read_html(linkurl)%>%html_node("#obsTable")%>%html_table()
weathertable
newtemp=weathertable$Temp.

abc=(gsub("°C", "", newtemp))
abc
abc_new=(gsub("[[:space:]]", "", abc))
as.numeric(abc_new)
trimws(x=abc)
as.numeric(trimws(x=abc))

Update

        > newtemp
     [1] "-10.6 °C" "-10.6 °C" "-11.0 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C"
    [10] "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C"
    [19] "-10.6 °C" "-10.6 °C" "-10.6 °C" "-11.0 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-11.0 °C" "-10.6 °C"
    [28] "-10.0 °C" "-10.0 °C" "-10.0 °C" "-10.0 °C" "-10.0 °C" "-9.4 °C"  "-8.9 °C"  "-8.3 °C"  "-7.2 °C"
    [37] "-7.2 °C"  "-5.6 °C"  "-5.0 °C"  "-3.9 °C"  "-3.9 °C"  "-3.9 °C"  "-3.3 °C"  "-3.3 °C"  "-3.9 °C"
    [46] "-6.1 °C"  "-8.3 °C"  "-7.8 °C"  "-8.9 °C"  "-10.0 °C" "-11.7 °C" "-12.8 °C"
    > abc=(gsub(" °C", "", newtemp))
    > abc
     [1] "-10.6 °C" "-10.6 °C" "-11.0 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C"
    [10] "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C"
    [19] "-10.6 °C" "-10.6 °C" "-10.6 °C" "-11.0 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-11.0 °C" "-10.6 °C"
    [28] "-10.0 °C" "-10.0 °C" "-10.0 °C" "-10.0 °C" "-10.0 °C" "-9.4 °C"  "-8.9 °C"  "-8.3 °C"  "-7.2 °C"
    [37] "-7.2 °C"  "-5.6 °C"  "-5.0 °C"  "-3.9 °C"  "-3.9 °C"  "-3.9 °C"  "-3.3 °C"  "-3.3 °C"  "-3.9 °C"
    [46] "-6.1 °C"  "-8.3 °C"  "-7.8 °C"  "-8.9 °C"  "-10.0 °C" "-11.7 °C" "-12.8 °C"
    > abc=(gsub("°C", "", newtemp))
> abc
 [1] "-10.6 " "-10.6 " "-11.0 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 "
[12] "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-11.0 "
[23] "-10.6 " "-10.6 " "-10.6 " "-11.0 " "-10.6 " "-10.0 " "-10.0 " "-10.0 " "-10.0 " "-10.0 " "-9.4 "
[34] "-8.9 "  "-8.3 "  "-7.2 "  "-7.2 "  "-5.6 "  "-5.0 "  "-3.9 "  "-3.9 "  "-3.9 "  "-3.3 "  "-3.3 "
[45] "-3.9 "  "-6.1 "  "-8.3 "  "-7.8 "  "-8.9 "  "-10.0 " "-11.7 " "-12.8 "
>

Body:
You could avoid the whole issue by using readr::parse_number:

library(rvest)
library(tidyverse)

url <- "https://www.wunderground.com/history/airport/KVAY/2015/2/17/DailyHistory.html?req_city=Cherry+Hill&req_state=NJ&req_statename=New+Jersey&reqdb.zip=08002&reqdb.magic=1&reqdb.wmo=99999&MR=1"

h <- url %>% read_html()

obs <- h %>%
    html_node('#obsTable') %>%
    html_table()

obs_clean <- obs %>%
    mutate(Temp. = parse_number(Temp.)) %>%
    tbl_df()   # for printing

obs_clean
#> # A tibble: 52 x 13
#>    `Time (EST)` Temp. Windchill `Dew Point` Humidity Pressure Visibility
#>           <chr> <dbl>     <chr>       <chr>    <chr>    <chr>      <chr>
#>  1     12:33 AM  12.9         -      8.1 °F      81% 30.08 in     2.0 mi
#>  2     12:45 AM  12.9         -      8.1 °F      81% 30.05 in     1.2 mi
#>  3     12:51 AM  12.2         -      8.6 °F      85% 30.05 in     0.8 mi
#>  4     12:54 AM  12.9         -      9.0 °F      84% 30.06 in     0.8 mi
#>  5      1:02 AM  12.9         -      9.0 °F      84% 30.05 in     0.5 mi
#>  6      1:25 AM  12.9         -      9.0 °F      84% 30.02 in     1.0 mi
#>  7      1:37 AM  12.9    6.9 °F      9.0 °F      84% 30.03 in     0.8 mi
#>  8      1:54 AM  12.9    6.9 °F      9.0 °F      84% 30.02 in     0.8 mi
#>  9      2:18 AM  12.9    5.2 °F      9.0 °F      84% 30.01 in     1.0 mi
#> 10      2:40 AM  12.9    5.2 °F      9.0 °F      84% 29.99 in     1.0 mi
#> # ... with 42 more rows, and 6 more variables: `Wind Dir` <chr>, `Wind
#> #   Speed` <chr>, `Gust Speed` <chr>, Precip <chr>, Events <chr>,
#> #   Conditions <chr>

or with regex,

obs %>% mutate(Temp. = as.numeric(gsub('[\\W°FC]', '', Temp.))) %>% tbl_df()

which returns the same thing.


问:
Nested NSArray into UITableView
i have looked everywhere for this, but i am unable to find the exact answer... all have slight variations.

Anyway, i call a json page that returns the following (from the NSLog):

```<code>{
    messages =         {
        1 =             {
            Body = "This is the body of message 1";
            Title = "Message 1";
        };
        2 =             {
            Body = "This is the body of message 2";
            Title = "Message 2";
        };
    };
}
</code>```

I then save the data into a NSDictionary (called messageArray). (the array is a NSMutableArray)

then i do:

```<code>// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }

    //put rowsarray into dictionary
    NSDictionary *dictionary = [messageArray objectAtIndex:indexPath.section];

    //new dictionary into array
    NSArray *messages = [dictionary objectForKey:@"messages"];

    NSLog(@"the message array = %@",messages );

    //this fails
    cell.textLabel.text = [messages objectAtIndex:indexPath.row];

return cell;
</code>```

the returned NSLog (so i am assuming my json array is working correctly):

```<code>the message array = {
1 =     {
    Body = "This is the body of message 1";
    Title = "Message 1";
};
2 =     {
    Body = "This is the body of message 2";
    Title = "Message 2";
};
</code>```

}

I understand that i am not labelling the textlabels.text correctly, but i am not sure how to go about looping through the "messages" array, to display all the "Title" values from the array, to display on my UITableView list.

i am certain i am missing something so simple... but it has eluded me until now. Any links welcome... i will keep searching myself....

答:
i have "semi" sorted the issue. I have removed the indexes from the json data so now it looks like:

```<code>messages =     (
            {
        Body = "This is the body of message 1";
        Title = "Message 1";
    },
            {
        Body = "This is the body of message 2";
        Title = "Message 2";
    }
);
</code>```

And have used this for the populating of the table:

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }

    //put rowsarray into dictionary
    NSDictionary *dictionary = [messageArray objectAtIndex:indexPath.section];

    NSLog(@"dictionary = %@", dictionary );

    //new dictionary into array
    NSArray *messages = [dictionary objectForKey:@"messages"];

    //NSArray *message=[[messages allKeys] sortedArrayUsingSelector:@selector(compare:)];
    NSLog(@"array messages = %@", messages );

    cell.textLabel.text = [[messages objectAtIndex:indexPath.row] objectForKey:@"Title"];

    return cell;
}
</code>```

i hope this helps someone.

Title: Nested NSArray into UITableView

Body:
i have looked everywhere for this, but i am unable to find the exact answer... all have slight variations.

Anyway, i call a json page that returns the following (from the NSLog):

{
    messages =         {
        1 =             {
            Body = "This is the body of message 1";
            Title = "Message 1";
        };
        2 =             {
            Body = "This is the body of message 2";
            Title = "Message 2";
        };
    };
}

I then save the data into a NSDictionary (called messageArray). (the array is a NSMutableArray)

then i do:

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }

    //put rowsarray into dictionary
    NSDictionary *dictionary = [messageArray objectAtIndex:indexPath.section];

    //new dictionary into array
    NSArray *messages = [dictionary objectForKey:@"messages"];

    NSLog(@"the message array = %@",messages );

    //this fails
    cell.textLabel.text = [messages objectAtIndex:indexPath.row];

return cell;

the returned NSLog (so i am assuming my json array is working correctly):

the message array = {
1 =     {
    Body = "This is the body of message 1";
    Title = "Message 1";
};
2 =     {
    Body = "This is the body of message 2";
    Title = "Message 2";
};

}

I understand that i am not labelling the textlabels.text correctly, but i am not sure how to go about looping through the "messages" array, to display all the "Title" values from the array, to display on my UITableView list.

i am certain i am missing something so simple... but it has eluded me until now. Any links welcome... i will keep searching myself....

Body:
i have "semi" sorted the issue. I have removed the indexes from the json data so now it looks like:

messages =     (
            {
        Body = "This is the body of message 1";
        Title = "Message 1";
    },
            {
        Body = "This is the body of message 2";
        Title = "Message 2";
    }
);

And have used this for the populating of the table:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }

    //put rowsarray into dictionary
    NSDictionary *dictionary = [messageArray objectAtIndex:indexPath.section];

    NSLog(@"dictionary = %@", dictionary );

    //new dictionary into array
    NSArray *messages = [dictionary objectForKey:@"messages"];

    //NSArray *message=[[messages allKeys] sortedArrayUsingSelector:@selector(compare:)];
    NSLog(@"array messages = %@", messages );

    cell.textLabel.text = [[messages objectAtIndex:indexPath.row] objectForKey:@"Title"];

    return cell;
}

i hope this helps someone.


问:
New project Error - Product Targets Turn Red
Every time I create a new project, all of the product targets turn red immediately. If I understand correctly, that means that it can't locate the folder it is in. I have tried restarting Xcode, clean, clean build, and restarting my computer. Is this just how its supposed to be or is there something wrong with my targets?

When I go and right click on the app target and "Show in Finder", it takes me to the Derived Data folder and not the actual app which is the picture above:

答:
It is not the targets but the products that are marked as red.

The products do not exist after creating a new project as they have not been build yet and thus they are marked red. Building means "creating a product".

After you build the project once, the product/artefact exists and is not marked red any more.


问:
Is it possible to read the Slog in android monitor?
In the android source code i see often line like Slog.v(WindowManagerService.TAG, "First window added to " + this + ", creating SurfaceSession"); How can i see those Slog under android monitor ? And what the difference between Slog and Log?

答:
Short answer

You get logs logged with Slog by default, but they are "hidden" between other log messages. In order to get just the ones logged with Slog use this command:

```<code>adb logcat -b system
</code>```

Long answer

I looked at source of Slog.java:

```<code>public static int v(String tag, String msg) {
    return Log.println_native(Log.LOG_ID_SYSTEM, Log.VERBOSE, tag, msg);
}
</code>```

Compared to Log.java:

```<code>public static int v(String tag, String msg) {
    return println_native(LOG_ID_MAIN, VERBOSE, tag, msg);
}
</code>```

As you can see, the difference is solely in LOG_ID parameter.

Then I looked at adb logcat -help:

```<code>  ...
  -b <buffer>     Request alternate ring buffer, 'main', 'system', 'radio',
                  'events', 'crash' or 'all'. Multiple -b parameters are
                  allowed and results are interleaved. The default is
                  -b main -b system -b crash.
  ...
</code>```

I did not check any further - it looks like a safe bet that -b option corresponds to different LOG_ID params.

Body:
Short answer

You get logs logged with Slog by default, but they are "hidden" between other log messages. In order to get just the ones logged with Slog use this command:

adb logcat -b system

Long answer

I looked at source of Slog.java:

public static int v(String tag, String msg) {
    return Log.println_native(Log.LOG_ID_SYSTEM, Log.VERBOSE, tag, msg);
}

Compared to Log.java:

public static int v(String tag, String msg) {
    return println_native(LOG_ID_MAIN, VERBOSE, tag, msg);
}

As you can see, the difference is solely in LOG_ID parameter.

Then I looked at adb logcat -help:

  ...
  -b <buffer>     Request alternate ring buffer, 'main', 'system', 'radio',
                  'events', 'crash' or 'all'. Multiple -b parameters are
                  allowed and results are interleaved. The default is
                  -b main -b system -b crash.
  ...

I did not check any further - it looks like a safe bet that -b option corresponds to different LOG_ID params.


问:
Scatter plotting pandas DataFrame with categorically labeled rows/columns
I would like to produce a scatter plot of pandas DataFrame with categorical row and column labels using matplotlib. A sample DataFrame looks like this:

```<code>import pandas as pd
df = pd.DataFrame({"a": [1,2], "b": [3,4]}, index=["c","d"])
#   a  b
#c  1  2
#d  3  4
</code>```

The marker size is the function of the respective DataFrame values. So far, I came up with an awkward solution that essentially enumerates the rows and columns, plots the data, and then reconstructs the labels:

```<code>flat = df.reset_index(drop=True).T.reset_index(drop=True).T.stack().reset_index()
#   level_0  level_1  0
#0        0        0  1
#1        0        1  2
#2        1        0  3
#3        1        1  4

flat.plot(kind='scatter', x='level_0', y='level_1', s=100*flat[0])
plt.xticks(range(df.shape[1]), df.columns)
plt.yticks(range(df.shape[0]), df.index)
plt.show()
</code>```

Which kind of works.

Now, question: Is there a more intuitive, more integrated way to produce this scatter plot, ideally without splitting the data and the metadata?

答:
Maybe not the entire answer you're looking for, but an idea to help save time and readability with the flat= line of code.

Pandas unstack method will produce a Series with a MultiIndex.

```<code>dfu = df.unstack()

print(dfu.index)
MultiIndex(levels=[[u'a', u'b'], [u'c', u'd']],
           labels=[[0, 0, 1, 1], [0, 1, 0, 1]])
</code>```

The MultiIndex contains contains the necessary x and y points to construct the plot (in labels).  Here, I assign levels and labels to more informative variable names better suited for plotting.

```<code>xlabels, ylabels = dfu.index.levels
xs, ys = dfu.index.labels
</code>```

Plotting is pretty straight-forward from here.

```<code>plt.scatter(xs, ys, s=dfu*100)
plt.xticks(range(len(xlabels)), xlabels)
plt.yticks(range(len(ylabels)), ylabels)
plt.show()
</code>```

I tried this on a few different DataFrame shapes and it seemed to hold up.

Body:
I would like to produce a scatter plot of pandas DataFrame with categorical row and column labels using matplotlib. A sample DataFrame looks like this:

import pandas as pd
df = pd.DataFrame({"a": [1,2], "b": [3,4]}, index=["c","d"])
#   a  b
#c  1  2
#d  3  4

The marker size is the function of the respective DataFrame values. So far, I came up with an awkward solution that essentially enumerates the rows and columns, plots the data, and then reconstructs the labels:

flat = df.reset_index(drop=True).T.reset_index(drop=True).T.stack().reset_index()
#   level_0  level_1  0
#0        0        0  1
#1        0        1  2
#2        1        0  3
#3        1        1  4

flat.plot(kind='scatter', x='level_0', y='level_1', s=100*flat[0])
plt.xticks(range(df.shape[1]), df.columns)
plt.yticks(range(df.shape[0]), df.index)
plt.show()

Which kind of works.

Now, question: Is there a more intuitive, more integrated way to produce this scatter plot, ideally without splitting the data and the metadata?

Body:
Maybe not the entire answer you're looking for, but an idea to help save time and readability with the flat= line of code.

Pandas unstack method will produce a Series with a MultiIndex.

dfu = df.unstack()

print(dfu.index)
MultiIndex(levels=[[u'a', u'b'], [u'c', u'd']],
           labels=[[0, 0, 1, 1], [0, 1, 0, 1]])

The MultiIndex contains contains the necessary x and y points to construct the plot (in labels).  Here, I assign levels and labels to more informative variable names better suited for plotting.

xlabels, ylabels = dfu.index.levels
xs, ys = dfu.index.labels

Plotting is pretty straight-forward from here.

plt.scatter(xs, ys, s=dfu*100)
plt.xticks(range(len(xlabels)), xlabels)
plt.yticks(range(len(ylabels)), ylabels)
plt.show()

I tried this on a few different DataFrame shapes and it seemed to hold up.


问:
python csv to dictionary using csv or pandas module
I am using Python's csv.DictReader to read in values from a CSV file to create a dictionary where keys are first row or headers in the CSV and other rows are values. It works perfectly as expected and I am able to get a dictionary, but I only want certain keys to be in the dictionary rather than all of the column values. What is the best way to do this? I tried using csv.reader but I don't think it has this functionality. Maybe this can be achieved using pandas?

Here is the code I was using with CSV module where Fieldnames was the keys that I wanted to retain in my dict. I realized it isn't used for what I described above.

```<code>import csv
with open(target_path+target_file) as csvfile:
    reader = csv.DictReader(csvfile,fieldnames=Fieldnames)
    for i in reader:
        print i
</code>```

答:
You can do this very simply using pandas.

```<code>import pandas as pd

# get only the columns you want from the csv file
df = pd.read_csv(target_path + target_file, usecols=['Column Name1', 'Column Name2'])
result = df.to_dict(orient='records')
</code>```

Sources:

pandas.read_csv

pandas.DataFrame.to_dict

Body:
I am using Python's csv.DictReader to read in values from a CSV file to create a dictionary where keys are first row or headers in the CSV and other rows are values. It works perfectly as expected and I am able to get a dictionary, but I only want certain keys to be in the dictionary rather than all of the column values. What is the best way to do this? I tried using csv.reader but I don't think it has this functionality. Maybe this can be achieved using pandas?

Here is the code I was using with CSV module where Fieldnames was the keys that I wanted to retain in my dict. I realized it isn't used for what I described above.

import csv
with open(target_path+target_file) as csvfile:
    reader = csv.DictReader(csvfile,fieldnames=Fieldnames)
    for i in reader:
        print i

Body:
You can do this very simply using pandas.

import pandas as pd

# get only the columns you want from the csv file
df = pd.read_csv(target_path + target_file, usecols=['Column Name1', 'Column Name2'])
result = df.to_dict(orient='records')

Sources:

pandas.read_csv

pandas.DataFrame.to_dict


问:
InvocationException: GraphViz's executables not found (Python)
Getting error calling pydotplus.graph_from_dot_data in code below:

```<code>from IPython.display import Image

dot_data = tree.export_graphviz(clf,
                                out_file=None,
                                feature_names=iris.feature_names,
                                class_names=iris.target_names,
                                filled=True,
                                rounded=True,
                                special_characters=True)
graph = pydotplus.graph_from_dot_data(dot_data)
Image(graph.create_png())
</code>```

The error output:

```<code>File "C:\Users\ss\Anaconda3\lib\site-packages\pydotplus\graphviz.py", line 1960, in create 'GraphViz\'s executables not found')
InvocationException: GraphViz's executables not found
</code>```

答: As pydotplus states in its requirements, you need GraphViz installed in your system.</p>

Body:
Getting error calling pydotplus.graph_from_dot_data in code below:

from IPython.display import Image

dot_data = tree.export_graphviz(clf,
                                out_file=None,
                                feature_names=iris.feature_names,
                                class_names=iris.target_names,
                                filled=True,
                                rounded=True,
                                special_characters=True)
graph = pydotplus.graph_from_dot_data(dot_data)
Image(graph.create_png())

The error output:

File "C:\Users\ss\Anaconda3\lib\site-packages\pydotplus\graphviz.py", line 1960, in create 'GraphViz\'s executables not found')
InvocationException: GraphViz's executables not found


问:
Regex to find a string between two special known characters
I'm trying to parse messages transmited over TCP for my own network protocol using regex without success.

My commands start with ! followed by COMMAND_NAME and a list of arguments in the format or ARGUMENT_NAME=ARGUMENT_VALUE enclosed in <>

for example:

```<code>!LOGIN?<USERNAME='user'><PASSWORD='password'>;
</code>```

my code :

```<code>public class CommandParser
{
    private Dictionary<string, string> arguments = new Dictionary<string, string>();

    public CommandParser(string input)
    {
        Match commandMatch = Regex.Match(input, @"\!([^)]*)\&");

        if (commandMatch.Success)
        {
            CommandName = commandMatch.Groups[1].Value;
        }

        // Here we call Regex.Match.
        MatchCollection matches = Regex.Matches(input,"(?<!\\S)<([a-z0-9]+)=(\'[a-z0-9]+\')>(?!\\S)",
            RegexOptions.IgnoreCase);

        //
        foreach (Match argumentMatch in matches)
        {
            arguments.Add(
                argumentMatch.Groups[1].Value,
                argumentMatch.Groups[2].Value);
        }
    }

    public string CommandName { get; set; }

    public Dictionary<string, string> Arguments
    {
        get { return arguments; }
    }

    /// <summary>
    ///
    /// </summary>
    public int ArgumentCount
    {
        get { return arguments.Count; }
    }
}
</code>```

答:
To find the command name, finding the first word after the "!" should be enough:

```<code>/\!\w*/g
</code>```

To match the key/value pairs in groups, you could try something like:

```<code>(\w+)='([a-zA-Z_]*)'
</code>```

An example of the above regex can be found here.

Body:
I'm trying to parse messages transmited over TCP for my own network protocol using regex without success.

My commands start with ! followed by COMMAND_NAME and a list of arguments in the format or ARGUMENT_NAME=ARGUMENT_VALUE enclosed in <>

for example:

!LOGIN?<USERNAME='user'><PASSWORD='password'>;

my code :

public class CommandParser
{
    private Dictionary<string, string> arguments = new Dictionary<string, string>();

    public CommandParser(string input)
    {
        Match commandMatch = Regex.Match(input, @"\!([^)]*)\&");

        if (commandMatch.Success)
        {
            CommandName = commandMatch.Groups[1].Value;
        }

        // Here we call Regex.Match.
        MatchCollection matches = Regex.Matches(input,"(?<!\\S)<([a-z0-9]+)=(\'[a-z0-9]+\')>(?!\\S)",
            RegexOptions.IgnoreCase);

        //
        foreach (Match argumentMatch in matches)
        {
            arguments.Add(
                argumentMatch.Groups[1].Value,
                argumentMatch.Groups[2].Value);
        }
    }

    public string CommandName { get; set; }

    public Dictionary<string, string> Arguments
    {
        get { return arguments; }
    }

    ///
    ///
    ///
    public int ArgumentCount
    {
        get { return arguments.Count; }
    }
}

Body:
To find the command name, finding the first word after the "!" should be enough:

/\!\w*/g

To match the key/value pairs in groups, you could try something like:

(\w+)='([a-zA-Z_]*)'

An example of the above regex can be found here.


问:
Rewrite the algorithm in java stream with less effort?
I was learning about Streams in Java 8.

For example, If I have to double a number:

```<code>Arrays.stream(intArray).map(e->e*2).forEach(System.out::println);
</code>```

If I have to square a number, then I can use below:

```<code>Arrays.stream(intArray).map(e->e*e).forEach(System.out::println);
</code>```

But If I have to apply both functions on same Integer array using "andThen" method java.util.function.Function, I am doing it via:

```<code>  Function<Integer, Integer> times2 = e -> e * 2;

  Function<Integer, Integer> squared = e -> e * e;

 Arrays.stream(intArray).map(times2.andThen(squared)).forEach(System.out::println);
</code>```

Is it possible to rewrite this (3 statements) in single line like :

```<code>Arrays.stream(intArray).map(e->e*2.andThen(f->f*f)).forEach(System.out::println);
</code>```

This is giving me a compiler error. Is it possible to do it?

答:
@tsolakp's answer shows how to create an inlined lambda of a specific type by casting the lambda expression to the desired functional type.

As to why you can't do:

```<code>Arrays.stream(intArray)
    .boxed()
    .map(e -> e * 2.andThen(e -> e * e)) // wrong! does not compile!
    .forEach(System.out::println);
</code>```

The reason is that in Java, lambdas and method references must have a target type, because they are not first citizens of the language. In fact, a lambda must be of a specific SAM type (single abstract method type). A SAM type is represented by a functional interface, i.e. an interface that has only one abstract method. Examples of functional interfaces are Function, Predicate, Consumer, Supplier, Runnable, etc., or any SAM type declared by yourself, such as:

```<code>@FunctionalInterface
public interface Whatever<T, R> {

    R thisIsMySingleAbstractMethod(T argument);
}
</code>```

A lambda expression that matches the Whatever functional type can be:

```<code>Whatever<Integer, String> whatever = number -> number.toString();
</code>```

But the same lambda expression could have been used to declare a Function<Integer, String>:

```<code>Function<Integer, String> whatever = number -> number.toString();
</code>```

This example shows that lambdas have no type of their own until they are targeted to a SAM type. Only after this point, the methods of the type are available for chaining.

In a stream, the map method expects a Function as an argument. If you can express such function with an inlined lambda expression, then this lambda expression will be automatically inferred to be of the type of the argument of the map method. This will happen (at least conceptually) after the lambda expression has been evaluated by the compiler.

However, if you want to use a method of the lambda expression's target type, (this would be andThen in your example), it is not possible, because the compiler hasn't figured out the target type yet.

That's why casting the lambda expression works: it tells the compiler in advance what the target type of the lambda expression will be.

Body:
I was learning about Streams in Java 8.

For example, If I have to double a number:

Arrays.stream(intArray).map(e->e*2).forEach(System.out::println);

If I have to square a number, then I can use below:

Arrays.stream(intArray).map(e->e*e).forEach(System.out::println);

But If I have to apply both functions on same Integer array using "andThen" method java.util.function.Function, I am doing it via:

  Function<Integer, Integer> times2 = e -> e * 2;

  Function<Integer, Integer> squared = e -> e * e;

 Arrays.stream(intArray).map(times2.andThen(squared)).forEach(System.out::println);

Is it possible to rewrite this (3 statements) in single line like :

Arrays.stream(intArray).map(e->e*2.andThen(f->f*f)).forEach(System.out::println);

This is giving me a compiler error. Is it possible to do it?

Body:
@tsolakp's answer shows how to create an inlined lambda of a specific type by casting the lambda expression to the desired functional type.

As to why you can't do:

Arrays.stream(intArray)
    .boxed()
    .map(e -> e * 2.andThen(e -> e * e)) // wrong! does not compile!
    .forEach(System.out::println);

The reason is that in Java, lambdas and method references must have a target type, because they are not first citizens of the language. In fact, a lambda must be of a specific SAM type (single abstract method type). A SAM type is represented by a functional interface, i.e. an interface that has only one abstract method. Examples of functional interfaces are Function, Predicate, Consumer, Supplier, Runnable, etc., or any SAM type declared by yourself, such as:

@FunctionalInterface
public interface Whatever<T, R> {

    R thisIsMySingleAbstractMethod(T argument);
}

A lambda expression that matches the Whatever functional type can be:

Whatever<Integer, String> whatever = number -> number.toString();

But the same lambda expression could have been used to declare a Function<Integer, String>:

Function<Integer, String> whatever = number -> number.toString();

This example shows that lambdas have no type of their own until they are targeted to a SAM type. Only after this point, the methods of the type are available for chaining.

In a stream, the map method expects a Function as an argument. If you can express such function with an inlined lambda expression, then this lambda expression will be automatically inferred to be of the type of the argument of the map method. This will happen (at least conceptually) after the lambda expression has been evaluated by the compiler.

However, if you want to use a method of the lambda expression's target type, (this would be andThen in your example), it is not possible, because the compiler hasn't figured out the target type yet.

That's why casting the lambda expression works: it tells the compiler in advance what the target type of the lambda expression will be.


问:
Convert Non-List Type to List Directly
I have a list of items that I need to actually be a list of lists. All the conversion methods I have seen convert the non-list items to lists of individual characters ["12", "cat", 87] to [['1', '2'], ['c', 'a', 't'], ['8', '7']] instead of [['12'], ['cat'], [87]]. The following works,

```<code>v_Data = ["12", "cat", 87]
for index, i in enumerate(v_Data):
    if type(i) != list:
        v_Data[index] = [i]
print(v_Data) ## [['12'], ['cat'], [87]]
</code>```

Is there a better way to do this?

Using Python 2.7

答:
You can use a list comprehension:

```<code>v_Data = ["12", "cat", 87]

new = [[x] for x in v_Data]
</code>```

Similar to:

```<code>v_Data = ["12", "cat", 87]

new = []
for x in v_Data:
    new.append([x])
</code>```

Title: Convert Non-List Type to List Directly

Body:
I have a list of items that I need to actually be a list of lists. All the conversion methods I have seen convert the non-list items to lists of individual characters ["12", "cat", 87] to [['1', '2'], ['c', 'a', 't'], ['8', '7']] instead of [['12'], ['cat'], [87]]. The following works,

v_Data = ["12", "cat", 87]
for index, i in enumerate(v_Data):
    if type(i) != list:
        v_Data[index] = [i]
print(v_Data) ## [['12'], ['cat'], [87]]

Is there a better way to do this?

Using Python 2.7

Body:
You can use a list comprehension:

v_Data = ["12", "cat", 87]

new = [[x] for x in v_Data]

Similar to:

v_Data = ["12", "cat", 87]

new = []
for x in v_Data:
    new.append([x])


问:
push file by ssh but error
```<code>> ! [rejected]        master -> master (non-fast-forward)
> error: failed to push some refs to 'git@github.com:wiwj1987ww/es6.git'
> hint: Updates were rejected because the tip of your current branch is
> behind
> hint: its remote counterpart. Integrate the remote changes (e.g.
> hint: 'git pull ...') before pushing again.
> hint: See the 'Note about fast-forwards' in 'git push --help' for
> details.
</code>```

when I push file by ssh ,it`s not work.

答:
Your question and the problem is not addressing the real problem.

This clearly explains what is the problem is.

```<code>error: failed to push some refs to 'git@github.com:wiwj1987ww/es6.git'
hint: Updates were rejected because the tip of your current branch is
behind
</code>```

What you need to do is check your branch and see have you modified any files. If you don't need those changes,

you can do git stash or do git reset --hard, caution needs to take while you reset hard and make sure what your deleting is not needed.

or do git pull --rebase. This will place all your local commits on top of newly pulled changes.

Already Tim Biegeleisen pointed out this has nothing do with the SSH.

Title: push file by ssh but error

Body:
> ! [rejected]        master -> master (non-fast-forward)
> error: failed to push some refs to 'git@github.com:wiwj1987ww/es6.git'
> hint: Updates were rejected because the tip of your current branch is
> behind
> hint: its remote counterpart. Integrate the remote changes (e.g.
> hint: 'git pull ...') before pushing again.
> hint: See the 'Note about fast-forwards' in 'git push --help' for
> details.

when I push file by ssh ,it`s not work.

Body:
Your question and the problem is not addressing the real problem.

This clearly explains what is the problem is.

error: failed to push some refs to 'git@github.com:wiwj1987ww/es6.git'
hint: Updates were rejected because the tip of your current branch is
behind

What you need to do is check your branch and see have you modified any files. If you don't need those changes,

you can do git stash or do git reset --hard, caution needs to take while you reset hard and make sure what your deleting is not needed.

or do git pull --rebase. This will place all your local commits on top of newly pulled changes.

Already Tim Biegeleisen pointed out this has nothing do with the SSH.


问:
How does dlmalloc coalesce chunks?
Here is a detailed description of the dlmalloc algorithm: http://g.oswego.edu/dl/html/malloc.html

A dlmalloc chunk is bookended by some metadata, which includes information about the amount of space in the chunk. Two contiguous free chunks might look like

```<code>[metadata | X bytes free space | metadata ][metadata | X bytes free space | metadata]
                Block A                                     Block B
</code>```

In that case we want to coalesce block B into block A. Now how many bytes of free space should block A report?

I think it should be 2X + 2 size(metadata) bytes, since now the coalesced block looks like:

```<code>[metadata | X bytes free space   metadata  metadata   X bytes free space  | metadata]
</code>```

But I'm wondering if this is correct, because I have a textbook that says the metadata will report 2X bytes without including the extra space we get from being able to write over the metadata.

答:
You can see the answer yourself by looking at the source. Begin with line 1876 to verify your diagram. The metadata is just two size_t unsigned integers, accessed by aliasing a struct malloc_chunk (line 1847). Field  prev_size is the size of the previous chunk, and size is the size of this one. Both include the size of the struct malloc_chunk itself. This will be 8 or 16 bytes on nearly all machines depending on whether the code is compiled for 32- or 64-bit addressing.

The "normal case" coalescing code starts at line 3766.  You can see that the size variable it's using to track coalescing is chunk size.

So - yeah - in the code blocks marked /* consolidate backward */ and /* consolidate forward */, when he adds the size of the preceding and succeeding chunks, he's implicitly adding the size of the struct malloc_chunk as you suspected.

This shows that your interpretation is correct.  My expectation is that the textbook author just got sloppy about the difference between chunk size (which includes metadata) and the size of the memory block allocated to the user.  Incidentally, malloc takes care of this difference at line 3397.

Perhaps the bigger lesson here is that - when you're trying to learn anything - you should never skip an opportunity to go straight to the first-hand source and figure stuff out for yourself.

Title: How does dlmalloc coalesce chunks?

Body:
Here is a detailed description of the dlmalloc algorithm: http://g.oswego.edu/dl/html/malloc.html

A dlmalloc chunk is bookended by some metadata, which includes information about the amount of space in the chunk. Two contiguous free chunks might look like

[metadata | X bytes free space | metadata ][metadata | X bytes free space | metadata]
                Block A                                     Block B

In that case we want to coalesce block B into block A. Now how many bytes of free space should block A report?

I think it should be 2X + 2 size(metadata) bytes, since now the coalesced block looks like:

[metadata | X bytes free space   metadata  metadata   X bytes free space  | metadata]

But I'm wondering if this is correct, because I have a textbook that says the metadata will report 2X bytes without including the extra space we get from being able to write over the metadata.


问:
InProc distributed cache in .Net 4.0
How does InProc distributed cache in .Net 4.0 deal with serialisation? </p>

<p>Is there any plugins or  thirdparty frameworks that support it out of the box? </p>

答:
Windows Server AppFabric cache supports serialization of any CLR object out of the box.

And you can have an InProc cache that is synchronized with distributed cache, so he is not necessarily wrong.

Title: InProc distributed cache in .Net 4.0

Body:
How does InProc distributed cache in .Net 4.0 deal with serialisation?

Is there any plugins or  thirdparty frameworks that support it out of the box?


问:
Angular 2 Routing with parameter undefined
I'm trying to create a route in Angular 2 that takes me to data of a json file, depending on the id. For instance I have 10001.json, 10002.json, 10003.json, etc...

People should be able to get to their patientfile by typing in that particular id as an url, but so far that's not working. I'm actually getting :

GET http://localhost:4200/assets/backend/patienten/undefined.json 404 (Not Found)

This is my patientcomponent:

```<code>import { Component, OnInit } from '@angular/core';
import {PatientService} from "../patient.service";
import {Patient} from "../models";
import {ActivatedRoute, Params} from "@angular/router";
import 'rxjs/add/operator/switchMap';

@Component({
  selector: 'app-patient',
  templateUrl: './patient.component.html',
  styleUrls: ['./patient.component.sass']
})
export class PatientComponent implements OnInit {

  patient:Patient[];
  id:any;

  errorMessage:string;

  constructor(private patientService:PatientService, private route: ActivatedRoute) { }

  ngOnInit():void {
    this.getData();
    this.id = this.route.params['id'];
    this.patientService.getPatient(this.id)
      .subscribe(patient => this.patient = patient);

  }

  getData() {
    this.patientService.getPatient(this.id)
      .subscribe(
        data => {
          this.patient = data;
          console.log(this.patient);
        }, error => this.errorMessage = <any> error);

  }
}
</code>```

This is the routing, very basic:

```<code>import {Routes} from "@angular/router";
import {AfdelingComponent} from "./afdeling/afdeling.component";
import {PatientComponent} from "./patient/patient.component";

export const routes: Routes = [
  {path: '', component: AfdelingComponent},
  {path: 'patient/:id', component: PatientComponent}

];
</code>```

And the service:

```<code>import { Injectable } from '@angular/core';
import {Http, RequestOptions, Response, Headers} from '@angular/http';
import {Observable} from "rxjs";
import {Patient} from "./models";

@Injectable()
export class PatientService {
  private patientUrl = "/assets/backend/patienten/";
  constructor(private http: Http) { }

  getPatient(id:any): Observable<Patient[]>{
    return this.http.get(this.patientUrl + id + '.json' )
        .map(this.extractData)
        .catch(this.handleError);
  }

  private extractData(res: Response) {
    let body = res.json();
    return body || { };
  }

  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error);
    return Promise.reject(error.message || error);
  }

  addPatient(afdelingsNaam: string, afdeling: any): Observable<Patient> {
    let body = JSON.stringify({"afdelingsNaam": afdelingsNaam, afdeling: afdeling});
    let headers = new Headers({'Content-Type': 'application/json'});
    let options = new RequestOptions({headers: headers});
    return this.http.post(this.patientUrl, body, options)
      .map(res => <Patient> res.json())
      .catch(this.handleError)
  }
}
</code>```

答:
The problem is that you call getData before this.id is populated.
Just change places

```<code>ngOnInit():void {
  this.id = this.route.params['id'];
  this.getData();
  this.patientService.getPatient(this.id)
    .subscribe(patient => this.patient = patient);

  }
</code>```

Edited:
route.params is an Observable, so you need to use it like:

```<code>this.sub = this.route.params.subscribe(params => {
   this.id = +params['id']; // (+) converts string 'id' to a number

   // In a real app: dispatch action to load the details here.
});
</code>```

Body:
I'm trying to create a route in Angular 2 that takes me to data of a json file, depending on the id. For instance I have 10001.json, 10002.json, 10003.json, etc...

People should be able to get to their patientfile by typing in that particular id as an url, but so far that's not working. I'm actually getting :

GET http://localhost:4200/assets/backend/patienten/undefined.json 404 (Not Found)

This is my patientcomponent:

import { Component, OnInit } from '@angular/core';
import {PatientService} from "../patient.service";
import {Patient} from "../models";
import {ActivatedRoute, Params} from "@angular/router";
import 'rxjs/add/operator/switchMap';

@Component({
  selector: 'app-patient',
  templateUrl: './patient.component.html',
  styleUrls: ['./patient.component.sass']
})
export class PatientComponent implements OnInit {

  patient:Patient[];
  id:any;

  errorMessage:string;

  constructor(private patientService:PatientService, private route: ActivatedRoute) { }

  ngOnInit():void {
    this.getData();
    this.id = this.route.params['id'];
    this.patientService.getPatient(this.id)
      .subscribe(patient => this.patient = patient);

  }

  getData() {
    this.patientService.getPatient(this.id)
      .subscribe(
        data => {
          this.patient = data;
          console.log(this.patient);
        }, error => this.errorMessage = <any> error);

  }
}

This is the routing, very basic:

import {Routes} from "@angular/router";
import {AfdelingComponent} from "./afdeling/afdeling.component";
import {PatientComponent} from "./patient/patient.component";

export const routes: Routes = [
  {path: '', component: AfdelingComponent},
  {path: 'patient/:id', component: PatientComponent}

];

And the service:

import { Injectable } from '@angular/core';
import {Http, RequestOptions, Response, Headers} from '@angular/http';
import {Observable} from "rxjs";
import {Patient} from "./models";

@Injectable()
export class PatientService {
  private patientUrl = "/assets/backend/patienten/";
  constructor(private http: Http) { }

  getPatient(id:any): Observable<Patient[]>{
    return this.http.get(this.patientUrl + id + '.json' )
        .map(this.extractData)
        .catch(this.handleError);
  }

  private extractData(res: Response) {
    let body = res.json();
    return body || { };
  }

  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error);
    return Promise.reject(error.message || error);
  }

  addPatient(afdelingsNaam: string, afdeling: any): Observable<Patient> {
    let body = JSON.stringify({"afdelingsNaam": afdelingsNaam, afdeling: afdeling});
    let headers = new Headers({'Content-Type': 'application/json'});
    let options = new RequestOptions({headers: headers});
    return this.http.post(this.patientUrl, body, options)
      .map(res => <Patient> res.json())
      .catch(this.handleError)
  }
}

Body:
The problem is that you call getData before this.id is populated.
Just change places

ngOnInit():void {
  this.id = this.route.params['id'];
  this.getData();
  this.patientService.getPatient(this.id)
    .subscribe(patient => this.patient = patient);

  }

Edited:
route.params is an Observable, so you need to use it like:

this.sub = this.route.params.subscribe(params => {
   this.id = +params['id']; // (+) converts string 'id' to a number

   // In a real app: dispatch action to load the details here.
});


问:
Cannot find module '@tridnguyen/config' | Install npm grunt
Getting error while running grunt after installing npm.</p>

```<code>C:\Users\XXXX\git\projectname\cartridges>grunt
Loading "Gruntfile.js" tasks...ERROR
>> Error: Cannot find module '@tridnguyen/config'
Warning: Task "default" not found. Use --force to continue.

Aborted due to warnings.
</code>```

答:
It is hard to tell as you do not show us your package.json nor your Gruntfile.js.

But as the error says, the module @tridnguyen/config was not found.

So you should start by install dependencies:

```<code>npm install
</code>```

or, if this is a new project:

```<code>npm install --save @tridnguyen/config
</code>```

Also there is a grunt warning because there is no registered default task in your Gruntfile.js file.

You may want to add one if you want to use grunt command:

```<code>grunt.registerTask('default', ["your_default_task"]);
</code>```

You should also take a look at the Grunt documentation to become more familiar with that.

Body:
Getting error while running grunt after installing npm.

C:\Users\XXXX\git\projectname\cartridges>grunt
Loading "Gruntfile.js" tasks...ERROR
>> Error: Cannot find module '@tridnguyen/config'
Warning: Task "default" not found. Use --force to continue.

Aborted due to warnings.

Body:
It is hard to tell as you do not show us your package.json nor your Gruntfile.js.

But as the error says, the module @tridnguyen/config was not found.

So you should start by install dependencies:

npm install

or, if this is a new project:

npm install --save @tridnguyen/config

Also there is a grunt warning because there is no registered default task in your Gruntfile.js file.

You may want to add one if you want to use grunt command:

grunt.registerTask('default', ["your_default_task"]);

You should also take a look at the Grunt documentation to become more familiar with that.


问:
values a re not being displayed in TextBox
in this program, when the Recall button (recallBtn_Click()) is clicked, it calls a method (that calculates directions) from another class which should then call the showPath() method. the show path method should then display its output in a textBox. But the values don't show even though i can see from debugging that the values are being sent to the text box. can anybody tell me where i went wrong?

```<code>public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        storeRetSelect.SelectedIndex = 0;
        PrioritySelect.SelectedIndex = 0;

    }

    public void showPath(List<PathFinderNode> mPath)
    {
        var T = new Form1().directionsTextBox;

        foreach (PathFinderNode node in mPath)
        {
            if ((node.X - node.PX) > 0) { T.Text += "Right" + System.Environment.NewLine ; }
            if ((node.X - node.PX) < 0) { T.Text += "Left" + System.Environment.NewLine; }
            if ((node.Y - node.PY) > 0) { T.Text += "UP" + System.Environment.NewLine; }
            if ((node.Y - node.PY) < 0) { T.Text += "Down" + System.Environment.NewLine; }
        }
    }

    private void recallBtn_Click(object sender, EventArgs e)
    {
        var path = new pathPlan();
        string desigString = inputTextBox.Text;
        int[] desig = new int[3];

        for (int i = 0; i < desigString.Length; i++) { desig[i] = (int)char.GetNumericValue(desigString[i]); }
        path.Recall(desig[1], desig[2], (-1) * desig[0]);
    }
}
</code>```

答:
With this line you are initialising a new object and get the reference of the textbox there.

```<code>var T = new Form1().directionsTextBox;
</code>```

But I assume you want to use the textbox of the form which is allready open. Change the line to the following to access the textbox of the current object.

```<code>var T = this.directionsTextBox;
</code>```

Body:
in this program, when the Recall button (recallBtn_Click()) is clicked, it calls a method (that calculates directions) from another class which should then call the showPath() method. the show path method should then display its output in a textBox. But the values don't show even though i can see from debugging that the values are being sent to the text box. can anybody tell me where i went wrong?

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        storeRetSelect.SelectedIndex = 0;
        PrioritySelect.SelectedIndex = 0;

    }

    public void showPath(List<PathFinderNode> mPath)
    {
        var T = new Form1().directionsTextBox;

        foreach (PathFinderNode node in mPath)
        {
            if ((node.X - node.PX) > 0) { T.Text += "Right" + System.Environment.NewLine ; }
            if ((node.X - node.PX) < 0) { T.Text += "Left" + System.Environment.NewLine; }
            if ((node.Y - node.PY) > 0) { T.Text += "UP" + System.Environment.NewLine; }
            if ((node.Y - node.PY) < 0) { T.Text += "Down" + System.Environment.NewLine; }
        }
    }

    private void recallBtn_Click(object sender, EventArgs e)
    {
        var path = new pathPlan();
        string desigString = inputTextBox.Text;
        int[] desig = new int[3];

        for (int i = 0; i < desigString.Length; i++) { desig[i] = (int)char.GetNumericValue(desigString[i]); }
        path.Recall(desig[1], desig[2], (-1) * desig[0]);
    }
}

Body:
With this line you are initialising a new object and get the reference of the textbox there.

var T = new Form1().directionsTextBox;

But I assume you want to use the textbox of the form which is allready open. Change the line to the following to access the textbox of the current object.

var T = this.directionsTextBox;


问:
Store words in char array C language
I have this code:

```<code>char *pch;
pch = strtok(texto," ");

while (pch != NULL)
{
  pch = strtok (NULL, " ");
}
</code>```

My "texto" variable have something like "This is my text example".

And i need to store each value comming from pch in while, in an array of characteres, but i really dont know how to do it.

I need something like that, each value in array will have a word, so:

"This is my text example".

```<code>Array[0][20] = This;

Array[1][20] = is;

Array[2][20] = my;

Array[3][20] = text;

Array[4][20] = example;
</code>```

The pch in while having all these words already split, but I don't know how to add into a char array, or how I will declare him too.

答:
This should work. Use strcpy to copy pch to character array.

```<code>char str[] ="This is my text example";
char *pch;
int i = 0;
pch = strtok (str," ");
char a[10][20];
while (pch != NULL)
{
  strcpy(a[i++], pch);
  pch = strtok (NULL, " ");
}
</code>```

And as @stackptr has suggested dont use strtok and instead use strtok_r . For more info on this.

Title: Store words in char array C language

Body:
I have this code:

char *pch;
pch = strtok(texto," ");

while (pch != NULL)
{
  pch = strtok (NULL, " ");
}

My "texto" variable have something like "This is my text example".

And i need to store each value comming from pch in while, in an array of characteres, but i really dont know how to do it.

I need something like that, each value in array will have a word, so:

"This is my text example".

Array[0][20] = This;

Array[1][20] = is;

Array[2][20] = my;

Array[3][20] = text;

Array[4][20] = example;

The pch in while having all these words already split, but I don't know how to add into a char array, or how I will declare him too.

Body:
This should work. Use strcpy to copy pch to character array.

char str[] ="This is my text example";
char *pch;
int i = 0;
pch = strtok (str," ");
char a[10][20];
while (pch != NULL)
{
  strcpy(a[i++], pch);
  pch = strtok (NULL, " ");
}

And as @stackptr has suggested dont use strtok and instead use strtok_r . For more info on this.


问:
time pass algorithm in python
```<code>import time
import random
info = """welcome to contest!..
pls answer question as quick as possible you can
pls enter small letter...\n"""
print(info)
questions = {"2 * 2 ?":"4",
"what is the capital city of turkey?":"ankara",
"what is the king of jungle?":"lion",
"what is the meaning of book in turkish language?":"kitap",
"who is the foundation of turkish government":"atatürk",
"what is the most popular drink in turkey?":"raki",
"pls tell us a hero as comic":"temel"}
correct = 0
wrong = 0
blank = 0
current_time = time.time() #system time
allowed_time = 25 #total time to reply the question

for i in random.sample(list(questions), 5):
     question = questions[i]
     if time.time() < current_time+allowed_time:
         answer = input("1. soru --> {} : ".format(i))
     if answer == question:
         correct += 1
     elif answer == "":
         blank += 1
     else:
         wrong += 1
print()
print("right answer  :", correct)
print("wrong answer :", wrong)
print("blank answer :", blank)
</code>```

Please see my survey code above. It's selecting random 5 question in total time 25 seconds. But, I'd like to make it time option for every single question.
For example, questions must be replied with in ten seconds otherwise change question automatically.

Could you help on how to do that?

答:
here's the steps to proceed(algorithm):

Add a timer to each question.

Run a counter or a timer inside the for loop, then, for every iteration passed, store the time in a variable x, check if x is less than 10.

Check whether it is answered within 10 seconds.

Iterate to the Next question, this i+1.

If NOT, jump to the next question.

Title: time pass algorithm in python

Body:
import time
import random
info = """welcome to contest!..
pls answer question as quick as possible you can
pls enter small letter...\n"""
print(info)
questions = {"2 * 2 ?":"4",
"what is the capital city of turkey?":"ankara",
"what is the king of jungle?":"lion",
"what is the meaning of book in turkish language?":"kitap",
"who is the foundation of turkish government":"atatürk",
"what is the most popular drink in turkey?":"raki",
"pls tell us a hero as comic":"temel"}
correct = 0
wrong = 0
blank = 0
current_time = time.time() #system time
allowed_time = 25 #total time to reply the question

for i in random.sample(list(questions), 5):
     question = questions[i]
     if time.time() < current_time+allowed_time:
         answer = input("1. soru --> {} : ".format(i))
     if answer == question:
         correct += 1
     elif answer == "":
         blank += 1
     else:
         wrong += 1
print()
print("right answer  :", correct)
print("wrong answer :", wrong)
print("blank answer :", blank)

Please see my survey code above. It's selecting random 5 question in total time 25 seconds. But, I'd like to make it time option for every single question.
For example, questions must be replied with in ten seconds otherwise change question automatically.

Could you help on how to do that?


问:
combining 2 activities together
ok so I'm making an app where I use an edit text to write anything and when I press a button it adds whatever I wrote in the edit to a listView, and it works, but I want the List to be in a different activity than the button and edit text, so I moved it without changing the code.can anyone figure this out,

BTW all the variables are public.

```<code>public class MainActivity extends AppCompatActivity {
    public ArrayList<String> arrayList2;
    public ArrayAdapter<String> adapter,adapter2;
    public EditText editText,editText2;
    public ArrayList<String> itemList,itemList2;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String[] items = {};
        itemList = new ArrayList<String>(Arrays.asList(items));
        adapter = new ArrayAdapter<String>(this, R.layout.activity_list_layout,R.id.txtItem,itemList);
        ListView listV = (ListView)findViewById(R.id.list_layout);
        listV.setAdapter(adapter);
        editText = (EditText)findViewById(R.id.thingadd);
        Button btAdd = (Button)findViewById(R.id.add);

        String[] age = {};
        arrayList2 = new ArrayList<String>(Arrays.asList(age));
        itemList2 = new ArrayList<String>(Arrays.asList(age));
        adapter2 = new ArrayAdapter<String>(this, R.layout.activity_list__layout2,R.id.txtage,itemList2);
        ListView listV2 = (ListView)findViewById(R.id.Age);
        listV2.setAdapter(adapter2);
        editText2 = (EditText)findViewById(R.id.agetxt);

        btAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String newItem=editText.getText().toString();
                String newItem2=editText2.getText().toString();

                itemList.add(newItem);
                itemList2.add(newItem2);

                adapter.notifyDataSetChanged();
                adapter2.notifyDataSetChanged();
            }
        });
    }
}
</code>```

答:
You have 2 options to do so.

You can use any database service. Store the values and display them in the next activity. But this needs Internet service to be enabled in the phone.

You can use intent. Convert those input to string type and pass them to next activity and display them using ids. This type do not require Internet service. To know more about this, Visit this link

Title: combining 2 activities together

Body:
ok so I'm making an app where I use an edit text to write anything and when I press a button it adds whatever I wrote in the edit to a listView, and it works, but I want the List to be in a different activity than the button and edit text, so I moved it without changing the code.can anyone figure this out,

BTW all the variables are public.

public class MainActivity extends AppCompatActivity {
    public ArrayList<String> arrayList2;
    public ArrayAdapter<String> adapter,adapter2;
    public EditText editText,editText2;
    public ArrayList<String> itemList,itemList2;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String[] items = {};
        itemList = new ArrayList<String>(Arrays.asList(items));
        adapter = new ArrayAdapter<String>(this, R.layout.activity_list_layout,R.id.txtItem,itemList);
        ListView listV = (ListView)findViewById(R.id.list_layout);
        listV.setAdapter(adapter);
        editText = (EditText)findViewById(R.id.thingadd);
        Button btAdd = (Button)findViewById(R.id.add);

        String[] age = {};
        arrayList2 = new ArrayList<String>(Arrays.asList(age));
        itemList2 = new ArrayList<String>(Arrays.asList(age));
        adapter2 = new ArrayAdapter<String>(this, R.layout.activity_list__layout2,R.id.txtage,itemList2);
        ListView listV2 = (ListView)findViewById(R.id.Age);
        listV2.setAdapter(adapter2);
        editText2 = (EditText)findViewById(R.id.agetxt);

        btAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String newItem=editText.getText().toString();
                String newItem2=editText2.getText().toString();

                itemList.add(newItem);
                itemList2.add(newItem2);

                adapter.notifyDataSetChanged();
                adapter2.notifyDataSetChanged();
            }
        });
    }
}


问:
attr new onclick function not working
I am replacing an onclick attr as so....

```<code>$('#divName').attr('onclick','newFunction()');

function newFunction(){
    alert('New Function Success');
}
</code>```

My current html is

```<code><div id="divName" onclick="oldFunction()">
</code>```

and after i insert the new attr , inspecting element shows this

```<code><div id="divName" onclick="newFunction()">
</code>```

but when i click , no alert msg is displayed, so new function is not being applied on click event , any ideas why ?

答:
Since jQuery provides .click() function, you can user this instead.
Please try the below solution.
Remove the onlick and attach click() to div</p>

```<code>$("#divName").attr("onclick","").click(newFunction);

function newFunction(){
    alert('New Function Success');
}
</code>```

Title: attr new onclick function not working

Body:
I am replacing an onclick attr as so....

$('#divName').attr('onclick','newFunction()');

function newFunction(){
    alert('New Function Success');
}

My current html is

and after i insert the new attr , inspecting element shows this

but when i click , no alert msg is displayed, so new function is not being applied on click event , any ideas why ?

Body:
Since jQuery provides .click() function, you can user this instead.
Please try the below solution.
Remove the onlick and attach click() to div

$("#divName").attr("onclick","").click(newFunction);

function newFunction(){
    alert('New Function Success');
}


问:
how to create password to folder Or secure folder using c#
I am working on a windows form application using c#. There are some important files near my project that I do not want anyone to have access them but my application needs files.
The first solution was using DotNetZip library with password.
But when the application want to use these files the zip file must unzipped and all files copy in hard disk.
Is there a solution without direct access to the files to use them?
Or is there a solution that can be secured folders?</p>

答: You could consider encrypting the passwords and not worry about people accessing it. If this does not work then you could also consider using a database to store your passwords.</p>