问:
DropDownListFor in an MVC ASP application
I have a view model which you see below

```<code>public class AssetCategoryViewModel : IEnumerable<AssetCategory>
{
    DataModelContext db = new DataModelContext();
    public AssetCategory AssetCategory { get; set; }
    public Guid Id { get; set; }
    public IList<AssetCategory> AssetCategoryList { get; set; }
    public IEnumerable<SelectListItem> AssetCategoryNames { get; set; }
    public AssetCategoryViewModel()
    {
        AssetCategoryList = (from x in db.AssetCategory
                             select x).ToList();
        AssetCategoryNames = (from x in db.AssetCategory
                              select new SelectListItem
                              {
                                  Text = x.Name,
                                  Value = x.Code
                              });
    }

    public IEnumerator<AssetCategory> GetEnumerator()
    {
        return AssetCategoryList.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        throw new NotImplementedException();
    }
}
</code>```

and I want to send  SelectlistItem to to view for using dropdownlist.

action method :

```<code>    public ActionResult AddNewCategory()
    {
        AssetCategoryViewModel acvm = new AssetCategoryViewModel();

        return View(acvm);
    }
</code>```

and div class (included dropdownlistfor helper method)

```<code>                <div class="form-group">
                    @Html.LabelFor(model => model.AssetCategory.MasterCategory, htmlAttributes: new { @class = "control-label" })
                    @Html.DropDownListFor(model => model.AssetCategoryNames, Model.AssetCategoryNames, "Seçim yapınız", htmlAttributes: new { @class = "form-control" })
                </div>
</code>```

and I got error

Server Error in '/' Application.
  Object reference not set to an instance of an object.
  Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
  Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

I am stuck on this.

答:
thank you very much.
I forgot to add new model to actionresult view.
I have changed the controller part as below and I worked

```<code>    public ActionResult AddNewCategory()
    {
        AssetCategoryViewModel acvm = new AssetCategoryViewModel();
        return View(acvm);
    }
</code>```

thanks.

Body:
I have a view model which you see below

public class AssetCategoryViewModel : IEnumerable<AssetCategory>
{
    DataModelContext db = new DataModelContext();
    public AssetCategory AssetCategory { get; set; }
    public Guid Id { get; set; }
    public IList<AssetCategory> AssetCategoryList { get; set; }
    public IEnumerable<SelectListItem> AssetCategoryNames { get; set; }
    public AssetCategoryViewModel()
    {
        AssetCategoryList = (from x in db.AssetCategory
                             select x).ToList();
        AssetCategoryNames = (from x in db.AssetCategory
                              select new SelectListItem
                              {
                                  Text = x.Name,
                                  Value = x.Code
                              });
    }

    public IEnumerator<AssetCategory> GetEnumerator()
    {
        return AssetCategoryList.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        throw new NotImplementedException();
    }
}

and I want to send  SelectlistItem to to view for using dropdownlist.

action method :

    public ActionResult AddNewCategory()
    {
        AssetCategoryViewModel acvm = new AssetCategoryViewModel();

        return View(acvm);
    }

and div class (included dropdownlistfor helper method)

                    @Html.LabelFor(model => model.AssetCategory.MasterCategory, htmlAttributes: new { @class = "control-label" })
                    @Html.DropDownListFor(model => model.AssetCategoryNames, Model.AssetCategoryNames, "Seçim yapınız", htmlAttributes: new { @class = "form-control" })

and I got error

Server Error in '/' Application.
  Object reference not set to an instance of an object.
  Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
  Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

I am stuck on this.

Body:
thank you very much.
I forgot to add new model to actionresult view.
I have changed the controller part as below and I worked

    public ActionResult AddNewCategory()
    {
        AssetCategoryViewModel acvm = new AssetCategoryViewModel();
        return View(acvm);
    }

thanks.


来源: stackexchange

问:
NSOpenPanel from C++ boost thread
I'm invoking a NSOpenPanel from a thread created by boost C++.

the panel behaves erratically and doesn't respond well to mouse, that is clicking on objects does nothing sometime when clicking on top level combo box does improve response.

do i've to run a separate runloop I'm doing a runModalForDirectory which should take care of running its own loop.

I've also created a separate objc class which does performSelectorOnMainThread to show panel in main thread but still the behavior is same.

```<code>[ps performSelectorOnMainThread:@selector(showOpenPanel) withObject:nil
                      waitUntilDone:YES
                      modes:[NSArray arrayWithObject:NSRunLoopCommonModes]];
</code>```

I've also tried with waitUntilDone:NO and running a CFRunLoopRunInMode which isn't helping either.

```<code>- (bool) showOpenPanel
{
    NSOpenPanel *op = [NSOpenPanel openPanel];
    [op setAllowsMultipleSelection:YES];
    [op setTitle:@"Choose File"];
    [op setMessage:@"Choose file for Importing."];
    [op setFloatingPanel:true];
    bool result =[op runModalForDirectory:NSHomeDirectory() file:nil types:self.fileTypes];
    if (result == NSOKButton) {
        [self setSelectedFiles:[op filenames]];
        [self setLastShowResult:true];
    }
    else {
        [self setLastShowResult:false];
    }

    [self setPanelIsDone:true];
    return self.lastShowResult;
}
</code>```

答:
NSOpenPanel is part of AppKit. AppKit functions and classes can only be safely used on the main thread.

Show us the code you used with performSelectorOnMainThread so we can help figure out why you might still be seeing problems. I suspect you're calling individual methods with it--don't; it won't work the way you expect. Call back to the main thread for the totality of your interaction with NSOpenPanel.

ContentLicense: CC BY-SA 2.5

Title: NSOpenPanel from C++ boost thread

Body:
I'm invoking a NSOpenPanel from a thread created by boost C++.

the panel behaves erratically and doesn't respond well to mouse, that is clicking on objects does nothing sometime when clicking on top level combo box does improve response.

do i've to run a separate runloop I'm doing a runModalForDirectory which should take care of running its own loop.

I've also created a separate objc class which does performSelectorOnMainThread to show panel in main thread but still the behavior is same.

[ps performSelectorOnMainThread:@selector(showOpenPanel) withObject:nil
                      waitUntilDone:YES
                      modes:[NSArray arrayWithObject:NSRunLoopCommonModes]];

I've also tried with waitUntilDone:NO and running a CFRunLoopRunInMode which isn't helping either.

- (bool) showOpenPanel
{
    NSOpenPanel *op = [NSOpenPanel openPanel];
    [op setAllowsMultipleSelection:YES];
    [op setTitle:@"Choose File"];
    [op setMessage:@"Choose file for Importing."];
    [op setFloatingPanel:true];
    bool result =[op runModalForDirectory:NSHomeDirectory() file:nil types:self.fileTypes];
    if (result == NSOKButton) {
        [self setSelectedFiles:[op filenames]];
        [self setLastShowResult:true];
    }
    else {
        [self setLastShowResult:false];
    }

    [self setPanelIsDone:true];
    return self.lastShowResult;
}


问:
PDFsharp Ximage does not contain a constructor that contains 1 argument
I am trying to write an XImage function that reads an image from a given URL and it looks like:

```<code>    public static XImage FromURI(string uri)
    {
        HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(uri);
        webRequest.AllowWriteStreamBuffering = true;
        WebResponse webResponse = webRequest.GetResponse();
        System.Drawing.Image image = System.Drawing.Image.FromStream(webResponse.GetResponseStream());
        webResponse.Close();
        PdfSharp.Drawing.XImage ximg = new PdfSharp.Drawing.XImage(image);
        return new PdfSharp.Drawing.XImage(image);
    }
</code>```

but I am getting an error on the line

```<code>        return new PdfSharp.Drawing.XImage(image);
</code>```

It says:

```<code>XImage does not contain a constructor that contains 1 argument.
</code>```

When I look at the XImage.cs file, it seems like it has a constructor that has 1 argument.

```<code>namespace PdfSharp.Drawing
{
    //
    // Summary:
    //     Defines an object used to draw image files (bmp, png, jpeg, gif) and PDF forms.
    //     An abstract base class that provides functionality for the Bitmap and Metafile
    //     descended classes.
    public class XImage : IDisposable
    {
        //
        // Summary:
        //     Initializes a new instance of the PdfSharp.Drawing.XImage class.
        protected XImage();

        //
        // Summary:
        //     Gets the vertical resolution of the image.
        public virtual double VerticalResolution { get; }
        //
        // Summary:
        //     Gets the horizontal resolution of the image.
        public virtual double HorizontalResolution { get; }
        //
        // Summary:
        //     Gets the size in point of the image.
        public virtual XSize Size { get; }
        //
        // Summary:
        //     Gets the height of the image in pixels.
        public virtual int PixelHeight { get; }
        //
        // Summary:
        //     Gets the width of the image in pixels.
        public virtual int PixelWidth { get; }
        //
        // Summary:
        //     Gets the height of the image in point.
        public virtual double PointHeight { get; }
        //
        // Summary:
        //     Gets the width of the image in point.
        public virtual double PointWidth { get; }
        //
        // Summary:
        //     Gets the height of the image.
        [Obsolete("Use either PixelHeight or PointHeight. Temporarily obsolete because of rearrangements for WPF. Currently same as PixelHeight, but will become PointHeight in future releases of PDFsharp.")]
        public virtual double Height { get; }
        //
        // Summary:
        //     Gets the width of the image.
        [Obsolete("Use either PixelWidth or PointWidth. Temporarily obsolete because of rearrangements for WPF. Currently same as PixelWidth, but will become PointWidth in future releases of PDFsharp.")]
        public virtual double Width { get; }
        //
        // Summary:
        //     Gets or sets a flag indicating whether image interpolation is to be performed.
        public virtual bool Interpolate { get; set; }
        //
        // Summary:
        //     Gets the format of the image.
        public XImageFormat Format { get; }

        //
        // Summary:
        //     Tests if a file exist. Supports PDF files with page number suffix.
        //
        // Parameters:
        //   path:
        //     The path to a BMP, PNG, GIF, JPEG, TIFF, or PDF file.
        public static bool ExistsFile(string path);
        //
        // Summary:
        //     Creates an image from the specified file.
        //
        // Parameters:
        //   path:
        //     The path to a BMP, PNG, GIF, JPEG, TIFF, or PDF file.
        public static XImage FromFile(string path);
        //
        // Summary:
        //     Conversion from Image to XImage.
        public static XImage FromGdiPlusImage(Image image);
        //
        // Summary:
        //     Under construction
        public void Dispose();
        //
        // Summary:
        //     Disposes underlying GDI+ object.
        protected virtual void Dispose(bool disposing);

        //
        // Summary:
        //     Implicit conversion from Image to XImage.
        public static implicit operator XImage(Image image);
    }
}
</code>```

And even if I try to fix this file, it cannot be fixed because it has a [from metadata] label.

答:
The best you can do: skip creating the Image and create the XImage directly from the stream.

The XImage class has some static members. There is XImage.FromGdiImage that takes an Image (this would be the answer to your question) and there is XImage.FromStream that avoids creating the Image in the first place.

When your project references PDFsharp DLLs (e.g. from NuGet) then Visual Studio will show you decompiled meta data that cannot be changed. You can use the PDFsharp source code, add references to the .csproj files and make changes es needed.

The constructor that takes an Image as parameter is not public. No need to make it public as you can use XImage.FromGdiImage to access it. Note that only the GDI build of PDFsharp has this method. When using the WPF build, you can use XImage.FromStream.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to write an XImage function that reads an image from a given URL and it looks like:

    public static XImage FromURI(string uri)
    {
        HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(uri);
        webRequest.AllowWriteStreamBuffering = true;
        WebResponse webResponse = webRequest.GetResponse();
        System.Drawing.Image image = System.Drawing.Image.FromStream(webResponse.GetResponseStream());
        webResponse.Close();
        PdfSharp.Drawing.XImage ximg = new PdfSharp.Drawing.XImage(image);
        return new PdfSharp.Drawing.XImage(image);
    }

but I am getting an error on the line

        return new PdfSharp.Drawing.XImage(image);

It says:

XImage does not contain a constructor that contains 1 argument.

When I look at the XImage.cs file, it seems like it has a constructor that has 1 argument.

namespace PdfSharp.Drawing
{
    //
    // Summary:
    //     Defines an object used to draw image files (bmp, png, jpeg, gif) and PDF forms.
    //     An abstract base class that provides functionality for the Bitmap and Metafile
    //     descended classes.
    public class XImage : IDisposable
    {
        //
        // Summary:
        //     Initializes a new instance of the PdfSharp.Drawing.XImage class.
        protected XImage();

        //
        // Summary:
        //     Gets the vertical resolution of the image.
        public virtual double VerticalResolution { get; }
        //
        // Summary:
        //     Gets the horizontal resolution of the image.
        public virtual double HorizontalResolution { get; }
        //
        // Summary:
        //     Gets the size in point of the image.
        public virtual XSize Size { get; }
        //
        // Summary:
        //     Gets the height of the image in pixels.
        public virtual int PixelHeight { get; }
        //
        // Summary:
        //     Gets the width of the image in pixels.
        public virtual int PixelWidth { get; }
        //
        // Summary:
        //     Gets the height of the image in point.
        public virtual double PointHeight { get; }
        //
        // Summary:
        //     Gets the width of the image in point.
        public virtual double PointWidth { get; }
        //
        // Summary:
        //     Gets the height of the image.
        [Obsolete("Use either PixelHeight or PointHeight. Temporarily obsolete because of rearrangements for WPF. Currently same as PixelHeight, but will become PointHeight in future releases of PDFsharp.")]
        public virtual double Height { get; }
        //
        // Summary:
        //     Gets the width of the image.
        [Obsolete("Use either PixelWidth or PointWidth. Temporarily obsolete because of rearrangements for WPF. Currently same as PixelWidth, but will become PointWidth in future releases of PDFsharp.")]
        public virtual double Width { get; }
        //
        // Summary:
        //     Gets or sets a flag indicating whether image interpolation is to be performed.
        public virtual bool Interpolate { get; set; }
        //
        // Summary:
        //     Gets the format of the image.
        public XImageFormat Format { get; }

        //
        // Summary:
        //     Tests if a file exist. Supports PDF files with page number suffix.
        //
        // Parameters:
        //   path:
        //     The path to a BMP, PNG, GIF, JPEG, TIFF, or PDF file.
        public static bool ExistsFile(string path);
        //
        // Summary:
        //     Creates an image from the specified file.
        //
        // Parameters:
        //   path:
        //     The path to a BMP, PNG, GIF, JPEG, TIFF, or PDF file.
        public static XImage FromFile(string path);
        //
        // Summary:
        //     Conversion from Image to XImage.
        public static XImage FromGdiPlusImage(Image image);
        //
        // Summary:
        //     Under construction
        public void Dispose();
        //
        // Summary:
        //     Disposes underlying GDI+ object.
        protected virtual void Dispose(bool disposing);

        //
        // Summary:
        //     Implicit conversion from Image to XImage.
        public static implicit operator XImage(Image image);
    }
}

And even if I try to fix this file, it cannot be fixed because it has a [from metadata] label.

ContentLicense: CC BY-SA 4.0


问:
How to work with sqlite3 and Python
I was looking for any database solution with Python. And found the tutorial Python: A Simple Step-by-Step SQLite Tutorial. There I found a code example which shows how to create a database and INSERT some data:

```<code>import sqlite3

conn = sqlite3.connect("mydatabase.db") # or use :memory: to put it in RAM

cursor = conn.cursor()

# create a table
cursor.execute("""CREATE TABLE albums
                  (title text, artist text, release_date text,
                   publisher text, media_type text)
               """)
</code>```

I am totally new to sqlite3.

If I want to use sqlite3 do I need to install any particular Python modules?

In the above code I can see one database named mydatabase.db. How do I create that database?

If anyone help me to get these confusions cleared from my head, I can give these new module a good start.

Thanks

答:
Sqlite3 is the version commonly used with Python. If you are running Windows, you need to download sqlite download from official page. If you are using Ubuntu or Debian based system then it comes pre-installed.

Now coming to python, sqlite3 is the package name, it comes included with python, if you don't find it, then install it with the command apt-get install python-sqlite on Ubuntu system.

Considering you are using Ubuntu system, simply type sqlite3 test.db to create database name test.db.

As for your program:

```<code>import sqlite3

conn = sqlite3.connect("test.db") # connect to test.db
cursor = conn.cursor() # get a cursor to the sqlite database
# cursor is the object here, you can use any name

# create a table
cursor.execute("""CREATE TABLE albums
                  (title text, artist text, release_date text,
                   publisher text, media_type text)""")
# cursor.execute is used to execute any command to sqlite
</code>```

Few more function I would like to introduce is data = cursor.fetchone() to fetch one row, data = cursor.fetchall() to fetch many rows at once and store in tuple data.

Title: How to work with sqlite3 and Python

Body:
I was looking for any database solution with Python. And found the tutorial Python: A Simple Step-by-Step SQLite Tutorial. There I found a code example which shows how to create a database and INSERT some data:

import sqlite3

conn = sqlite3.connect("mydatabase.db") # or use :memory: to put it in RAM

cursor = conn.cursor()

# create a table
cursor.execute("""CREATE TABLE albums
                  (title text, artist text, release_date text,
                   publisher text, media_type text)
               """)

I am totally new to sqlite3.

If I want to use sqlite3 do I need to install any particular Python modules?

In the above code I can see one database named mydatabase.db. How do I create that database?

If anyone help me to get these confusions cleared from my head, I can give these new module a good start.

Thanks

Body:
Sqlite3 is the version commonly used with Python. If you are running Windows, you need to download sqlite download from official page. If you are using Ubuntu or Debian based system then it comes pre-installed.

Now coming to python, sqlite3 is the package name, it comes included with python, if you don't find it, then install it with the command apt-get install python-sqlite on Ubuntu system.

Considering you are using Ubuntu system, simply type sqlite3 test.db to create database name test.db.

As for your program:

import sqlite3

conn = sqlite3.connect("test.db") # connect to test.db
cursor = conn.cursor() # get a cursor to the sqlite database
# cursor is the object here, you can use any name

# create a table
cursor.execute("""CREATE TABLE albums
                  (title text, artist text, release_date text,
                   publisher text, media_type text)""")
# cursor.execute is used to execute any command to sqlite

Few more function I would like to introduce is data = cursor.fetchone() to fetch one row, data = cursor.fetchall() to fetch many rows at once and store in tuple data.


问:
How to apply function to many columns?
For the following dataset, I wrote a function,

```<code>expconvert <- function(a) {
     if(a=="h" || a=="H")
         return(100)
     if(a=="k" || a=="K")
         return(1000)
     if(a=="m" || a=="M")
         return(1000000)
     if(a=="b" || a=="B")
         return(1000000000)
     if(is.numeric(a))
         return(a)
     else
         return(0)
}
</code>```

The data set looks like following,

```<code>CROPDMGEXP CROPDMG PROPDMG PROPDMGEXP
   k         0       20        h
   H         23      41        B
   k         10      5         B
             2       3         k
             5       50
</code>```

The transformed data set should look like following,

```<code>CROPDMGEXP CROPDMG PROPDMG PROPDMGEXP
   1000        0       20        100
   100         23      41        1000000000
   1000        10      5         1000000000
   0           2       3         1000
   0           5       50        0
</code>```

I wish to apply the above function to the first and the last column. When I write the following code, consider df as the above data frame

df[c(1,4)] <- apply(df[c(1,4)], MARGIN = 1, FUN = expconvert)

I don't get the desired output that is the conversion of the letters in those columns to appropriate numerical weights.

But when I use apply for individual column it works fine as below,

df$CROPDMGEXP <- apply(df[1], MARGIN = 1, FUN = expconvert)

Please help me how do I apply it to both the columns at the same time.

There are many levels in the data set so setNames is cool when there are few. That is why I wrote the function. The question is the function works fine for single column with apply, but returns wrong values when used with multiple columns with apply.

答:
We can use lapply instead of apply as lapply keeps the same structure of the columns while apply will convert to a matrix and matrix can have only a single class.

```<code>df[c(1, 4)] <- lapply(df[c(1, 4)], expconvert)
</code>```

Also, instead of using the if/else, this can be done easily

```<code>v1 <- setNames(c(100, 1000, 1000000, 1000000000), c('h', 'k', 'm', 'b'))
df[c(1, 4)] <- lapply(df[c(1, 4)], function(x) v1[tolower(x)])
df[is.na(df)] <- 0
df
#   CROPDMGEXP CROPDMG PROPDMG PROPDMGEXP
#1       1000       0      20        100
#2        100      23      41 1000000000
#3       1000      10       5 1000000000
#4          0       2       3       1000
#5          0       5      50          0
</code>```

data

```<code>df <- structure(list(CROPDMGEXP = c("k", "H", "k", "", ""), CROPDMG = c(0L,
23L, 10L, 2L, 5L), PROPDMG = c(20L, 41L, 5L, 3L, 50L), PROPDMGEXP = c("h",
"B", "B", "k", "")), .Names = c("CROPDMGEXP", "CROPDMG", "PROPDMG",
"PROPDMGEXP"), class = "data.frame", row.names = c(NA, -5L))
</code>```

Title: How to apply function to many columns?

Body:
For the following dataset, I wrote a function,

expconvert <- function(a) {
     if(a=="h" || a=="H")
         return(100)
     if(a=="k" || a=="K")
         return(1000)
     if(a=="m" || a=="M")
         return(1000000)
     if(a=="b" || a=="B")
         return(1000000000)
     if(is.numeric(a))
         return(a)
     else
         return(0)
}

The data set looks like following,

CROPDMGEXP CROPDMG PROPDMG PROPDMGEXP
   k         0       20        h
   H         23      41        B
   k         10      5         B
             2       3         k
             5       50

The transformed data set should look like following,

CROPDMGEXP CROPDMG PROPDMG PROPDMGEXP
   1000        0       20        100
   100         23      41        1000000000
   1000        10      5         1000000000
   0           2       3         1000
   0           5       50        0

I wish to apply the above function to the first and the last column. When I write the following code, consider df as the above data frame

df[c(1,4)] <- apply(df[c(1,4)], MARGIN = 1, FUN = expconvert)

I don't get the desired output that is the conversion of the letters in those columns to appropriate numerical weights.

But when I use apply for individual column it works fine as below,

df$CROPDMGEXP <- apply(df[1], MARGIN = 1, FUN = expconvert)

Please help me how do I apply it to both the columns at the same time.

There are many levels in the data set so setNames is cool when there are few. That is why I wrote the function. The question is the function works fine for single column with apply, but returns wrong values when used with multiple columns with apply.

Body:
We can use lapply instead of apply as lapply keeps the same structure of the columns while apply will convert to a matrix and matrix can have only a single class.

df[c(1, 4)] <- lapply(df[c(1, 4)], expconvert)

Also, instead of using the if/else, this can be done easily

v1 <- setNames(c(100, 1000, 1000000, 1000000000), c('h', 'k', 'm', 'b'))
df[c(1, 4)] <- lapply(df[c(1, 4)], function(x) v1[tolower(x)])
df[is.na(df)] <- 0
df
#   CROPDMGEXP CROPDMG PROPDMG PROPDMGEXP
#1       1000       0      20        100
#2        100      23      41 1000000000
#3       1000      10       5 1000000000
#4          0       2       3       1000
#5          0       5      50          0

data

df <- structure(list(CROPDMGEXP = c("k", "H", "k", "", ""), CROPDMG = c(0L,
23L, 10L, 2L, 5L), PROPDMG = c(20L, 41L, 5L, 3L, 50L), PROPDMGEXP = c("h",
"B", "B", "k", "")), .Names = c("CROPDMGEXP", "CROPDMG", "PROPDMG",
"PROPDMGEXP"), class = "data.frame", row.names = c(NA, -5L))


答:
There is a glitch to the days column in Jaugar Chang's answer when the dates have the same day. I think the following corrects for this:

```<code>(SELECT CASE sign(day(now)-day(dob))
  WHEN 0 THEN 0
  WHEN 1 THEN day(now)-day(dob)
  ELSE (DAY(STR_TO_DATE(DATE_FORMAT(dob + INTERVAL 1 MONTH,'%Y-%m-01'),'%Y-%m-%d')-INTERVAL 1 DAY)-day(dob)+day(now)) END)
  as days
</code>```

For completeness the amended version of Jaugar's answer would follow:

```<code>SELECT
FLOOR(( DATE_FORMAT(NOW(),'%Y%m%d') - DATE_FORMAT(dob,'%Y%m%d'))/10000) as year,
FLOOR((1200 + DATE_FORMAT(NOW(),'%m%d')-DATE_FORMAT(dob,'%m%d'))/100) %12 as month,
CASE sign(day(NOW())-day(dob))
  WHEN 0 THEN 0
  WHEN 1 THEN day(NOW())-day(dob)
  ELSE (DAY(STR_TO_DATE(DATE_FORMAT(dob + INTERVAL 1 MONTH,'%Y-%m-01'),'%Y-%m-%d')-INTERVAL 1 DAY)-day(dob)+day(NOW())) END as day
FROM sampelaja
</code>```

Title: MySQL Calculate age by year month and day

Body:
I want to display data of patients age.

mysql> select nama,gender,dob,TIMESTAMPDIFF(YEAR,dob,now()) as age from sampelaja;
+------------------+--------+------------+------+
| nama             | gender | dob        | age  |
+------------------+--------+------------+------+
| Rizkiyandi       |      1 | 2010-05-21 |    4 |
| Siti Khodijah    |      0 | 1980-03-15 |   34 |
| Aisyah Az-zahra  |      0 | 1986-08-17 |   28 |
| Paritem          |      0 | 2005-12-13 |    8 |
| Ngadimin         |      1 | 2014-08-28 |    0 |
+------------------+--------+------------+------+

10 rows in set (0.00 sec)

Here there is a problem when there is a 4-day-old baby who is regarded as the age of 0 year
I want a result like this

+------------------+--------+------------+------+-------+------+
| nama             | gender | dob        | year | month | day  |
+------------------+--------+------------+------+-------+------+
| Rizkiyandi       |      1 | 2010-05-21 |    4 |     3 |   13 |
| Siti Khodijah    |      0 | 1980-03-15 |   34 |     5 |   18 |
| Aisyah Az-zahra  |      0 | 1986-08-17 |   28 |     0 |   16 |
| Paritem          |      0 | 2005-12-13 |    8 |     8 |   20 |
| Ngadimin         |      1 | 2014-08-28 |    0 |     0 |    6 |
+------------------+--------+------------+------+-------+------+

Body:
There is a glitch to the days column in Jaugar Chang's answer when the dates have the same day. I think the following corrects for this:

(SELECT CASE sign(day(now)-day(dob))
  WHEN 0 THEN 0
  WHEN 1 THEN day(now)-day(dob)
  ELSE (DAY(STR_TO_DATE(DATE_FORMAT(dob + INTERVAL 1 MONTH,'%Y-%m-01'),'%Y-%m-%d')-INTERVAL 1 DAY)-day(dob)+day(now)) END)
  as days

For completeness the amended version of Jaugar's answer would follow:

SELECT
FLOOR(( DATE_FORMAT(NOW(),'%Y%m%d') - DATE_FORMAT(dob,'%Y%m%d'))/10000) as year,
FLOOR((1200 + DATE_FORMAT(NOW(),'%m%d')-DATE_FORMAT(dob,'%m%d'))/100) %12 as month,
CASE sign(day(NOW())-day(dob))
  WHEN 0 THEN 0
  WHEN 1 THEN day(NOW())-day(dob)
  ELSE (DAY(STR_TO_DATE(DATE_FORMAT(dob + INTERVAL 1 MONTH,'%Y-%m-01'),'%Y-%m-%d')-INTERVAL 1 DAY)-day(dob)+day(NOW())) END as day
FROM sampelaja


问:
Convert Date string in NodeIS
I have a TranDate "2017/07/05 12:12:22", i want to convert it to this style : 20170705121222, can you help me what function of nodejs can I use to do this issue ? Thank you !</p>

答:
var df = require('date-format')
  df('yyyyMMddhhmmss', new Date('2017 07 05 12:12:22'))

Title: Convert Date string in NodeIS


问:
Calling a referenced dll from WebAPI works locally but not on server
I have a WebAPI that I have Cors enabled.

My webAPI references a Class library that I do a lot of the processing in.

calls between the WebAPI and Class library and also some calls inside the class library are

throwing this error...

```<code>{"Message":"An error has occurred.","ExceptionMessage":"Object reference not set to an instance of an object.",
"ExceptionType":"System.NullReferenceException","StackTrace":"
at RCIS.MappingServices.WebAPI.Utilities.SQL.SQLInsertObjects(Int32 TypeMapId, Int32 GrowerId, Int32 CropYear, String NAME, String SHAPE, String CREATED_BY, String CREATED_DATETIME, String MODIFIED_BY, String MODIFIED_DATETIME, String IsDELETED)\r\n
at RCIS.MappingServices.WebAPI.Controllers.PostObjectsController.GET(String TypeMapId, String GrowerId, String CropYear, String NAME, String SHAPE)\r\n
at lambda_method(Closure , Object , Object[] )\r\n
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)\r\n
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext,
IDictionary`2 arguments, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n
at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n
at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n
at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()"}
</code>```

This Only seems to be happening when calling the class library from the server (i.e.) I enter a URL into Chrome calling the WebAPI method and get this error back.

If I use all primitive types in the WebAPI and In the class library I get a success message back.

If you have any questions please let me know.
Any help on this would be greatly appreciated I have been trying to solve this for 2 days!!!

答:
Make an ErrorHelper:

```<code>public class ErrorHelper : IHttpActionResult
{
    private HttpRequestMessage Request { get; }
    private HttpStatusCode statusCode;
    private string message;

    public ErrorHelper(HttpRequestMessage request, HttpStatusCode statusCode, string message)
    {
        this.Request = request;
        this.statusCode = statusCode;
        this.message = message;
    }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        return Task.FromResult(Request.CreateErrorResponse(statusCode, message));
    }
}
</code>```

Then call it like this:

```<code>public IHttpActionResult Get(int id)
{
    try
    {
        var person = _repository.GetPersonId(id);
        if (person == null)
        {
            return NotFound();
        }
        return Ok(person);
    }
    catch (Exception ex)
    {
        return new ErrorHelper(Request, HttpStatusCode.InternalServerError, ex.ToString());
    }
}
</code>```

This will give you the Exception details. You probably haven't got a component installed on the Server, like a Database Driver or something like that.

Body:
I have a WebAPI that I have Cors enabled.

My webAPI references a Class library that I do a lot of the processing in.

calls between the WebAPI and Class library and also some calls inside the class library are

throwing this error...

{"Message":"An error has occurred.","ExceptionMessage":"Object reference not set to an instance of an object.",
"ExceptionType":"System.NullReferenceException","StackTrace":"
at RCIS.MappingServices.WebAPI.Utilities.SQL.SQLInsertObjects(Int32 TypeMapId, Int32 GrowerId, Int32 CropYear, String NAME, String SHAPE, String CREATED_BY, String CREATED_DATETIME, String MODIFIED_BY, String MODIFIED_DATETIME, String IsDELETED)\r\n
at RCIS.MappingServices.WebAPI.Controllers.PostObjectsController.GET(String TypeMapId, String GrowerId, String CropYear, String NAME, String SHAPE)\r\n
at lambda_method(Closure , Object , Object[] )\r\n
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)\r\n
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext,
IDictionary`2 arguments, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n
at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n
at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n
at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()"}

This Only seems to be happening when calling the class library from the server (i.e.) I enter a URL into Chrome calling the WebAPI method and get this error back.

If I use all primitive types in the WebAPI and In the class library I get a success message back.

If you have any questions please let me know.
Any help on this would be greatly appreciated I have been trying to solve this for 2 days!!!

Body:
Make an ErrorHelper:

public class ErrorHelper : IHttpActionResult
{
    private HttpRequestMessage Request { get; }
    private HttpStatusCode statusCode;
    private string message;

    public ErrorHelper(HttpRequestMessage request, HttpStatusCode statusCode, string message)
    {
        this.Request = request;
        this.statusCode = statusCode;
        this.message = message;
    }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        return Task.FromResult(Request.CreateErrorResponse(statusCode, message));
    }
}

Then call it like this:

public IHttpActionResult Get(int id)
{
    try
    {
        var person = _repository.GetPersonId(id);
        if (person == null)
        {
            return NotFound();
        }
        return Ok(person);
    }
    catch (Exception ex)
    {
        return new ErrorHelper(Request, HttpStatusCode.InternalServerError, ex.ToString());
    }
}

This will give you the Exception details. You probably haven't got a component installed on the Server, like a Database Driver or something like that.


问:
How can I unit test an MVC Action that returns a PartialViewResult?
I have an Action as follows:

```<code>public PartialViewResult MyActionIWantToTest(string someParameter)
{
    // ... A bunch of logic
    return PartialView("ViewName", viewModel);
}
</code>```

When I inspect the result, It has a few properties, but they are either null, or empty.
The only property that has anything is the ViewEngineCollection which doesn't contain anything specific to my method.

Does anyone have some example code that tests a PartialViewResult?

答:
Say you have an Action that looks something like this:

```<code>public PartialViewResult MyActionIWantToTest(string someParameter)
{
   var viewModel = new MyPartialViewModel { SomeValue = someParameter };
   return PartialView("MyPartialView", viewModel);
}
</code>```

Note: MyPartialViewModel is a simple class with only one property - SomeValue.

An NUnit example may look like this:

```<code>[Test]
public void MyActionIWantToTestReturnsPartialViewResult()
{
    // Arrange
    const string myTestValue = "Some value";
    var ctrl = new StringController();

    // Act
    var result = ctrl.MyActionIWantToTest(myTestValue);

    // Assert
    Assert.AreEqual("MyPartialView", result.ViewName);
    Assert.IsInstanceOf<MyPartialViewModel>(result.ViewData.Model);
    Assert.AreEqual(myTestValue, ((MyPartialViewModel)result.ViewData.Model).SomeValue);
}
</code>```

Body:
I have an Action as follows:

public PartialViewResult MyActionIWantToTest(string someParameter)
{
    // ... A bunch of logic
    return PartialView("ViewName", viewModel);
}

When I inspect the result, It has a few properties, but they are either null, or empty.
The only property that has anything is the ViewEngineCollection which doesn't contain anything specific to my method.

Does anyone have some example code that tests a PartialViewResult?

Body:
Say you have an Action that looks something like this:

public PartialViewResult MyActionIWantToTest(string someParameter)
{
   var viewModel = new MyPartialViewModel { SomeValue = someParameter };
   return PartialView("MyPartialView", viewModel);
}

Note: MyPartialViewModel is a simple class with only one property - SomeValue.

An NUnit example may look like this:

[Test]
public void MyActionIWantToTestReturnsPartialViewResult()
{
    // Arrange
    const string myTestValue = "Some value";
    var ctrl = new StringController();

    // Act
    var result = ctrl.MyActionIWantToTest(myTestValue);

    // Assert
    Assert.AreEqual("MyPartialView", result.ViewName);
    Assert.IsInstanceOf<MyPartialViewModel>(result.ViewData.Model);
    Assert.AreEqual(myTestValue, ((MyPartialViewModel)result.ViewData.Model).SomeValue);
}


问:
File Browser Window on Android>=6 with PhoneGap/Cordova
I'm having trouble opening a file browser window on Android6+. I'm using latest Cordova/PhoneGap with Visual Studio 2017. When I click the desired button, nothing happens. When I deploy my source code on a webserver and access this site on my tablet, everything works fine. A live example can be seen at:
http://gipong.github.io/shp2geojson.js/. "Upload zip file" won't open a file browser.

```<code><div class="ui teal fluid labeled icon button upload" id="zipfile" data-content="Mandatory files : SHP , DBF" data-variation="inverted large">
                    Upload zip file
                    <i class="file archive outline icon"></i>
                    <input type="file" id="file" accept=".zip">
            </div>
</code>```

My code (from https://github.com/gipong/shp2geojson.js)

```<code> function loadShpZip() {
            var epsg = ($('#epsg').val() == '') ? 4326 : $('#epsg').val(),
                encoding = ($('#encoding').val() == '') ? 'UTF-8' : $('#encoding').val();
            if (file.name.split('.')[1] == 'zip') {
                if (file) $('.dimmer').addClass('active');
                loadshp({
                    url: file,
                    encoding: encoding,
                    EPSG: epsg
                }, function (data) {
                    var URL = window.URL || window.webkitURL || window.mozURL || window.msURL,
                        url = URL.createObjectURL(new Blob([JSON.stringify(data)], { type: "application/json" }));

                    $('#link').attr('href', url);
                    $('#link').html(file.name + '.geojson' + '<i class="download icon"></i>').attr('download', file.name + '.geojson');

                    $('#downloadLink').slideDown(400);

                    $('.shp-modal').toggleClass('effect');
                    $('.overlay').toggleClass('effect');
                    $('#wrap').toggleClass('blur');

                    vector.addData(data);
                    map.fitBounds([
                        [data.bbox[1], data.bbox[0]], [data.bbox[3], data.bbox[2]]
                    ]);
                    $('.dimmer').removeClass('active');
                    $('#preview').addClass('disabled');
                    $('#epsg').val('');
                    $('#encoding').val('');
                    $('#info').addClass('picInfo');
                    $('#option').slideUp(500);

                    newData = data;

                    for (var i = 0; i < newData.features.length; i++) {
                        var c1 = newData.features[i].geometry.coordinates;

                        for (var u = 0; u < c1.length; u++) {
                            var c2 = c1[u];

                            for (var o = 0; o < c2.length; o++) {
                                var oldCoordinate = c2[o];
                                var newCoordinate = [oldCoordinate[1], oldCoordinate[0]];
                                c2[o] = newCoordinate;
                            }
                        }
                    }

                    globaljson = $.parseJSON(JSON.stringify(data));

                });
            } else {
                $('.modal').modal('show');
            }
        }
        initVector();

        $("#file").change(function (evt) {
            file = evt.target.files[0];
            if (file.size > 0) {
                $('#dataInfo').text(' ').append(file.name + ' , ' + file.size + ' kb');
                $('#option').slideDown(500);
                $('#preview').removeClass('disabled');
            }
        });

        $('#preview').click(function () {
            loadShpZip();
        });

        $('.button').popup({
            //inline: true,
            position: 'bottom left'
        });
        $('.tips').popup({
            target: '#addZipfile',
            position: 'top center'
            //variation: 'huge'
        });
        $('#entireLayer').click(function () {
            map.fitBounds(vector.getBounds());
            chrome.storage.local.set({ 'key': 'value' });
            chrome.storage.local.get('key', function (obj) {
                alert(obj.key);
            });

        });
        $('#addZipfile').click(function () {
            $('.shp-modal').toggleClass('effect');
            $('.overlay').toggleClass('effect');
            $('#wrap').toggleClass('blur');
        });
        $('#cancel').click(function () {
            $('.shp-modal').toggleClass('effect');
            $('.overlay').toggleClass('effect');
            $('#wrap').toggleClass('blur');
        });
        $('#removeLayer').click(function () {
            $('#attr').fadeOut(300);
            window.location.reload();
        });
        $('#encoding').dropdown();
        $('.v').change(function () {
            var msg = '<div class="msg" id="msg" style="display: none;"><div class="ui primary inverted red segment">' +
                '<p>You can find the EPSG Code of your Shapefile on <strong>spatialreference.org</strong></p></div><br /></div>';
            if ($('#epsg').val().match(/^\d{4}$/) != null) {
                $('#zipfile').removeClass('disabled');
                $('.msg').slideUp(750);
            } else {
                if ($('.msg')[0] == undefined) {
                    $('#epsgField').after(msg);
                    $('.msg').slideDown(1500);
                }
            }
        });

        $("#attr").draggable({ containment: $(this).parent().parent(), scroll: false, cursor: "move" });
        $('#cancelAttr').click(function () { $('#attr').hide()
});
</code>```

I've set my permissions in config.xml like this:

```<code>     <platform name="android">
       <config-file target="AndroidManifest.xml" parent="/*">
         android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
         android:name="android.permission.READ_EXTERNAL_STORAGE" />
       </config-file>
     </platform>
</code>```

When I check my app for requested permissions, none show up tho.

This Problem does not exist on a tablet with Android 4.4.

edit: a few logs, which I don't really understand.

```<code>07-04 12:10:20.471 18340 18340 W CordovaInterfaceImpl: Got an activity result, but no plugin was registered to receive it.
07-04 12:10:20.471 18340 18340 D WebView : resumeTimers
07-04 12:10:20.471 18340 18340 D WebView : setNetworkAvailable=true
07-04 12:10:20.472 18340 18340 D ActivityThread: SEND_RESULT handled : 0 / ResultData{token=android.os.BinderProxy@7c8f400 results[ResultInfo{who=null, request=5173, result=0, data=null}]}
07-04 12:10:20.482   202  2362 I BufferQueueProducer: [io.cordova.myappac1b3c/io.cordova.myappac1b3c.MainActivity](this:0x7f9222e400,id:306,api:1,p:18340,c:202) queueBuffer: fps=6.96 dur=1149.87 max=176.61 min=134.62
07-04 12:10:20.530   783  1018 D InputReader: AP_PROF:AppLaunch_dispatchPtr:Down:71182195, ID:0, Index:1969346496
07-04 12:10:20.530   783  1018 I PerfService: PerfServiceNative_boostEnableAsync:3
07-04 12:10:20.611   783  1018 D InputReader: AP_PROF:AppLaunch_dispatchPtr:Up:71182277, ID:0, Index:1969349888
07-04 12:10:20.611   783  1018 I PerfService: PerfServiceNative_boostEnableTimeoutMsAsync:3, 100
07-04 12:10:20.696   783  1018 D InputReader: AP_PROF:AppLaunch_dispatchPtr:Down:71182362, ID:0, Index:1969346496
07-04 12:10:20.696   783  1018 I PerfService: PerfServiceNative_boostEnableAsync:3
07-04 12:10:20.766   783  1018 D InputReader: AP_PROF:AppLaunch_dispatchPtr:Up:71182431, ID:0, Index:1969349888
07-04 12:10:20.766   783  1018 I PerfService: PerfServiceNative_boostEnableTimeoutMsAsync:3, 100
07-04 12:10:20.838   783  1018 D InputReader: AP_PROF:AppLaunch_dispatchPtr:Down:71182504, ID:0, Index:1969346496
07-04 12:10:20.838   783  1018 I PerfService: PerfServiceNative_boostEnableAsync:3
07-04 12:10:20.886   783  1017 D PowerManagerService: userActivityFromNative
07-04 12:10:20.887   783  1017 D PowerManagerService: userActivityNoUpdateLocked: eventTime=71182552, event=2, flags=0x0, uid=1000
07-04 12:10:20.887   783  1017 D PowerManagerNotifier: onUserActivity: event=2, uid=1000
07-04 12:10:20.887   783  1017 D PowerManagerService: updateUserActivitySummaryLocked: mWakefulness=Awake, mUserActivitySummary=0x1, nextTimeout=72975552 (in 1792999 ms)
07-04 12:10:20.887   783  1017 D DisplayPowerController: requestPowerState: policy=BRIGHT, useProximitySensor=false, screenBrightness=102, screenAutoBrightnessAdjustment=1.0, brightnessSetByUser=true, useAutoBrightness=true, blockScreenOn=false, lowPowerMode=false, boostScreenBrightness=false, dozeScreenBrightness=-1, dozeScreenState=UNKNOWN, waitForNegativeProximity=false
07-04 12:10:20.887   783  1017 I PowerManagerService: setBrightness mButtonLight 0.
07-04 12:10:20.887   783  1017 D PowerManagerService: updateDisplayPowerStateLocked: mDisplayReady=true, policy=3, mWakefulness=1, mWakeLockSummary=0x23, mUserActivitySummary=0x1, mBootCompleted=true, mScreenBrightnessBoostInProgress=false
07-04 12:10:20.908   783  1018 D InputReader: AP_PROF:AppLaunch_dispatchPtr:Up:71182574, ID:0, Index:1969349888
07-04 12:10:20.908   783  1018 I PerfService: PerfServiceNative_boostEnableTimeoutMsAsync:3, 100
07-04 12:10:20.957   783  1018 D InputReader: AP_PROF:AppLaunch_dispatchPtr:Down:71182623, ID:0, Index:1969346496
07-04 12:10:20.957   783  1018 I PerfService: PerfServiceNative_boostEnableAsync:3
07-04 12:10:21.039   783  1018 D InputReader: AP_PROF:AppLaunch_dispatchPtr:Up:71182705, ID:0, Index:1969349888
07-04 12:10:21.039   783  1018 I PerfService: PerfServiceNative_boostEnableTimeoutMsAsync:3, 100
07-04 12:10:21.080   783  2792 I ActivityManager: START u0 {act=android.intent.action.GET_CONTENT cat=[android.intent.category.OPENABLE] typ=.zip} from uid 10111 from pid 18340 on display 0
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.: android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.GET_CONTENT cat=[android.intent.category.OPENABLE] typ=.zip }
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1809)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at android.app.Instrumentation.execStartActivity(Instrumentation.java:1523)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at android.app.Activity.startActivityForResult(Activity.java:3968)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at org.apache.cordova.CordovaActivity.startActivityForResult(CordovaActivity.java:332)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at android.app.Activity.startActivityForResult(Activity.java:3920)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at org.apache.cordova.CordovaInterfaceImpl.startActivityForResult(CordovaInterfaceImpl.java:67)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at org.apache.cordova.engine.SystemWebChromeClient.onShowFileChooser(SystemWebChromeClient.java:268)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at com.android.webview.chromium.WebViewContentsClientAdapter.showFileChooser(WebViewContentsClientAdapter.java:481)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at org.chromium.android_webview.AwWebContentsDelegateAdapter.runFileChooser(AwWebContentsDelegateAdapter.java:70)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at org.chromium.base.SystemMessageHandler.nativeDoRunLoopOnce(Native Method)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at org.chromium.base.SystemMessageHandler.handleMessage(SystemMessageHandler.java:7)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at android.os.Handler.dispatchMessage(Handler.java:111)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at android.os.Looper.loop(Looper.java:207)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at android.app.ActivityThread.main(ActivityThread.java:5728)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at java.lang.reflect.Method.invoke(Native Method)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
07-04 12:10:21.083 18340 18340 D WebView : setNetworkAvailable=false
</code>```

答:
I fixed it by changing input type into

```<code><input type="file" id="file" name="files[]" multiple />
</code>```

Seems like something in the compile process or Android 6 processing doesn't quite like the accept=.zip parameter on input fields.

Body:
I'm having trouble opening a file browser window on Android6+. I'm using latest Cordova/PhoneGap with Visual Studio 2017. When I click the desired button, nothing happens. When I deploy my source code on a webserver and access this site on my tablet, everything works fine. A live example can be seen at:
http://gipong.github.io/shp2geojson.js/. "Upload zip file" won't open a file browser.

                    Upload zip file

                    <input type="file" id="file" accept=".zip">

My code (from https://github.com/gipong/shp2geojson.js)

 function loadShpZip() {
            var epsg = ($('#epsg').val() == '') ? 4326 : $('#epsg').val(),
                encoding = ($('#encoding').val() == '') ? 'UTF-8' : $('#encoding').val();
            if (file.name.split('.')[1] == 'zip') {
                if (file) $('.dimmer').addClass('active');
                loadshp({
                    url: file,
                    encoding: encoding,
                    EPSG: epsg
                }, function (data) {
                    var URL = window.URL || window.webkitURL || window.mozURL || window.msURL,
                        url = URL.createObjectURL(new Blob([JSON.stringify(data)], { type: "application/json" }));

                    $('#link').attr('href', url);
                    $('#link').html(file.name + '.geojson' + '').attr('download', file.name + '.geojson');

                    $('#downloadLink').slideDown(400);

                    $('.shp-modal').toggleClass('effect');
                    $('.overlay').toggleClass('effect');
                    $('#wrap').toggleClass('blur');

                    vector.addData(data);
                    map.fitBounds([
                        [data.bbox[1], data.bbox[0]], [data.bbox[3], data.bbox[2]]
                    ]);
                    $('.dimmer').removeClass('active');
                    $('#preview').addClass('disabled');
                    $('#epsg').val('');
                    $('#encoding').val('');
                    $('#info').addClass('picInfo');
                    $('#option').slideUp(500);

                    newData = data;

                    for (var i = 0; i < newData.features.length; i++) {
                        var c1 = newData.features[i].geometry.coordinates;

                        for (var u = 0; u < c1.length; u++) {
                            var c2 = c1[u];

                            for (var o = 0; o < c2.length; o++) {
                                var oldCoordinate = c2[o];
                                var newCoordinate = [oldCoordinate[1], oldCoordinate[0]];
                                c2[o] = newCoordinate;
                            }
                        }
                    }

                    globaljson = $.parseJSON(JSON.stringify(data));

                });
            } else {
                $('.modal').modal('show');
            }
        }
        initVector();

        $("#file").change(function (evt) {
            file = evt.target.files[0];
            if (file.size > 0) {
                $('#dataInfo').text(' ').append(file.name + ' , ' + file.size + ' kb');
                $('#option').slideDown(500);
                $('#preview').removeClass('disabled');
            }
        });

        $('#preview').click(function () {
            loadShpZip();
        });

        $('.button').popup({
            //inline: true,
            position: 'bottom left'
        });
        $('.tips').popup({
            target: '#addZipfile',
            position: 'top center'
            //variation: 'huge'
        });
        $('#entireLayer').click(function () {
            map.fitBounds(vector.getBounds());
            chrome.storage.local.set({ 'key': 'value' });
            chrome.storage.local.get('key', function (obj) {
                alert(obj.key);
            });

        });
        $('#addZipfile').click(function () {
            $('.shp-modal').toggleClass('effect');
            $('.overlay').toggleClass('effect');
            $('#wrap').toggleClass('blur');
        });
        $('#cancel').click(function () {
            $('.shp-modal').toggleClass('effect');
            $('.overlay').toggleClass('effect');
            $('#wrap').toggleClass('blur');
        });
        $('#removeLayer').click(function () {
            $('#attr').fadeOut(300);
            window.location.reload();
        });
        $('#encoding').dropdown();
        $('.v').change(function () {
            var msg = '

' +
                '
You can find the EPSG Code of your Shapefile on spatialreference.org

';
            if ($('#epsg').val().match(/^\d{4}$/) != null) {
                $('#zipfile').removeClass('disabled');
                $('.msg').slideUp(750);
            } else {
                if ($('.msg')[0] == undefined) {
                    $('#epsgField').after(msg);
                    $('.msg').slideDown(1500);
                }
            }
        });

        $("#attr").draggable({ containment: $(this).parent().parent(), scroll: false, cursor: "move" });
        $('#cancelAttr').click(function () { $('#attr').hide()
});

I've set my permissions in config.xml like this:

     <platform name="android">
       <config-file target="AndroidManifest.xml" parent="/*">
         android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
         android:name="android.permission.READ_EXTERNAL_STORAGE" />
       </config-file>
     </platform>

When I check my app for requested permissions, none show up tho.

This Problem does not exist on a tablet with Android 4.4.

edit: a few logs, which I don't really understand.

07-04 12:10:20.471 18340 18340 W CordovaInterfaceImpl: Got an activity result, but no plugin was registered to receive it.
07-04 12:10:20.471 18340 18340 D WebView : resumeTimers
07-04 12:10:20.471 18340 18340 D WebView : setNetworkAvailable=true
07-04 12:10:20.472 18340 18340 D ActivityThread: SEND_RESULT handled : 0 / ResultData{token=android.os.BinderProxy@7c8f400 results[ResultInfo{who=null, request=5173, result=0, data=null}]}
07-04 12:10:20.482   202  2362 I BufferQueueProducer: [io.cordova.myappac1b3c/io.cordova.myappac1b3c.MainActivity](this:0x7f9222e400,id:306,api:1,p:18340,c:202) queueBuffer: fps=6.96 dur=1149.87 max=176.61 min=134.62
07-04 12:10:20.530   783  1018 D InputReader: AP_PROF:AppLaunch_dispatchPtr:Down:71182195, ID:0, Index:1969346496
07-04 12:10:20.530   783  1018 I PerfService: PerfServiceNative_boostEnableAsync:3
07-04 12:10:20.611   783  1018 D InputReader: AP_PROF:AppLaunch_dispatchPtr:Up:71182277, ID:0, Index:1969349888
07-04 12:10:20.611   783  1018 I PerfService: PerfServiceNative_boostEnableTimeoutMsAsync:3, 100
07-04 12:10:20.696   783  1018 D InputReader: AP_PROF:AppLaunch_dispatchPtr:Down:71182362, ID:0, Index:1969346496
07-04 12:10:20.696   783  1018 I PerfService: PerfServiceNative_boostEnableAsync:3
07-04 12:10:20.766   783  1018 D InputReader: AP_PROF:AppLaunch_dispatchPtr:Up:71182431, ID:0, Index:1969349888
07-04 12:10:20.766   783  1018 I PerfService: PerfServiceNative_boostEnableTimeoutMsAsync:3, 100
07-04 12:10:20.838   783  1018 D InputReader: AP_PROF:AppLaunch_dispatchPtr:Down:71182504, ID:0, Index:1969346496
07-04 12:10:20.838   783  1018 I PerfService: PerfServiceNative_boostEnableAsync:3
07-04 12:10:20.886   783  1017 D PowerManagerService: userActivityFromNative
07-04 12:10:20.887   783  1017 D PowerManagerService: userActivityNoUpdateLocked: eventTime=71182552, event=2, flags=0x0, uid=1000
07-04 12:10:20.887   783  1017 D PowerManagerNotifier: onUserActivity: event=2, uid=1000
07-04 12:10:20.887   783  1017 D PowerManagerService: updateUserActivitySummaryLocked: mWakefulness=Awake, mUserActivitySummary=0x1, nextTimeout=72975552 (in 1792999 ms)
07-04 12:10:20.887   783  1017 D DisplayPowerController: requestPowerState: policy=BRIGHT, useProximitySensor=false, screenBrightness=102, screenAutoBrightnessAdjustment=1.0, brightnessSetByUser=true, useAutoBrightness=true, blockScreenOn=false, lowPowerMode=false, boostScreenBrightness=false, dozeScreenBrightness=-1, dozeScreenState=UNKNOWN, waitForNegativeProximity=false
07-04 12:10:20.887   783  1017 I PowerManagerService: setBrightness mButtonLight 0.
07-04 12:10:20.887   783  1017 D PowerManagerService: updateDisplayPowerStateLocked: mDisplayReady=true, policy=3, mWakefulness=1, mWakeLockSummary=0x23, mUserActivitySummary=0x1, mBootCompleted=true, mScreenBrightnessBoostInProgress=false
07-04 12:10:20.908   783  1018 D InputReader: AP_PROF:AppLaunch_dispatchPtr:Up:71182574, ID:0, Index:1969349888
07-04 12:10:20.908   783  1018 I PerfService: PerfServiceNative_boostEnableTimeoutMsAsync:3, 100
07-04 12:10:20.957   783  1018 D InputReader: AP_PROF:AppLaunch_dispatchPtr:Down:71182623, ID:0, Index:1969346496
07-04 12:10:20.957   783  1018 I PerfService: PerfServiceNative_boostEnableAsync:3
07-04 12:10:21.039   783  1018 D InputReader: AP_PROF:AppLaunch_dispatchPtr:Up:71182705, ID:0, Index:1969349888
07-04 12:10:21.039   783  1018 I PerfService: PerfServiceNative_boostEnableTimeoutMsAsync:3, 100
07-04 12:10:21.080   783  2792 I ActivityManager: START u0 {act=android.intent.action.GET_CONTENT cat=[android.intent.category.OPENABLE] typ=.zip} from uid 10111 from pid 18340 on display 0
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.: android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.GET_CONTENT cat=[android.intent.category.OPENABLE] typ=.zip }
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1809)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at android.app.Instrumentation.execStartActivity(Instrumentation.java:1523)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at android.app.Activity.startActivityForResult(Activity.java:3968)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at org.apache.cordova.CordovaActivity.startActivityForResult(CordovaActivity.java:332)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at android.app.Activity.startActivityForResult(Activity.java:3920)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at org.apache.cordova.CordovaInterfaceImpl.startActivityForResult(CordovaInterfaceImpl.java:67)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at org.apache.cordova.engine.SystemWebChromeClient.onShowFileChooser(SystemWebChromeClient.java:268)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at com.android.webview.chromium.WebViewContentsClientAdapter.showFileChooser(WebViewContentsClientAdapter.java:481)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at org.chromium.android_webview.AwWebContentsDelegateAdapter.runFileChooser(AwWebContentsDelegateAdapter.java:70)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at org.chromium.base.SystemMessageHandler.nativeDoRunLoopOnce(Native Method)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at org.chromium.base.SystemMessageHandler.handleMessage(SystemMessageHandler.java:7)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at android.os.Handler.dispatchMessage(Handler.java:111)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at android.os.Looper.loop(Looper.java:207)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at android.app.ActivityThread.main(ActivityThread.java:5728)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at java.lang.reflect.Method.invoke(Native Method)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
07-04 12:10:21.082 18340 18340 W No activity found to handle file chooser intent.:  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
07-04 12:10:21.083 18340 18340 D WebView : setNetworkAvailable=false

Body:
I fixed it by changing input type into

<input type="file" id="file" name="files[]" multiple />

Seems like something in the compile process or Android 6 processing doesn't quite like the accept=.zip parameter on input fields.


问:
python numpy: iterate for different conditions without using a loop
I am trying to iterate over numpy arrays and generate an output, which has conditions similar to that described below:

```<code>min1 = 3
max1 = 1
a1 = np.array([1, 2, 5, 3, 4])
a2 = np.array([5, 2, 6, 2, 1])
output = np.zeros(5)
for i in range(0, 5):
  if((a1[i] - a2[i]) > min1):
    output[i] = 3 * (a1[i] - a2[i])

  if((a1[i] - a2[i]) < max1):
    output = 5 * (a1[i] - a2[i])
</code>```

I need to optimize the above code, so that I utilize the numpy functionalities as the best and also avoid using a loop. How should I do it?

答:
Welcome to SO!  First, a tip for questions:

Even your current loopy code doesn't work, as you're assigning values to output instead of output[i].  Try to make sure that if you're asking for a code refactor your original code works (and other than numpy tags, asking for code refactoring on SO will normally get you downvoted).

You're going to want a nested np.where statement like this

```<code>output = np.where((a1 - a2) > min1, 3 * (a1 - a2), (np.where((a1 - a2) < max1, 5 * (a1 - a2), 0)))
</code>```

This way you don't need to initialize output, and no more loopy code.

If you have lots of conditions, you can also use np.select

```<code>d = a1 - a2
condlist = [d > min1, d < max1]
choicelist = [3 * d, 5 * d]
output = np.select(condlist, choicelist)
</code>```

Body:
I am trying to iterate over numpy arrays and generate an output, which has conditions similar to that described below:

min1 = 3
max1 = 1
a1 = np.array([1, 2, 5, 3, 4])
a2 = np.array([5, 2, 6, 2, 1])
output = np.zeros(5)
for i in range(0, 5):
  if((a1[i] - a2[i]) > min1):
    output[i] = 3 * (a1[i] - a2[i])

  if((a1[i] - a2[i]) < max1):
    output = 5 * (a1[i] - a2[i])

I need to optimize the above code, so that I utilize the numpy functionalities as the best and also avoid using a loop. How should I do it?

Body:
Welcome to SO!  First, a tip for questions:

Even your current loopy code doesn't work, as you're assigning values to output instead of output[i].  Try to make sure that if you're asking for a code refactor your original code works (and other than numpy tags, asking for code refactoring on SO will normally get you downvoted).

You're going to want a nested np.where statement like this

output = np.where((a1 - a2) > min1, 3 * (a1 - a2), (np.where((a1 - a2) < max1, 5 * (a1 - a2), 0)))

This way you don't need to initialize output, and no more loopy code.

If you have lots of conditions, you can also use np.select

d = a1 - a2
condlist = [d > min1, d < max1]
choicelist = [3 * d, 5 * d]
output = np.select(condlist, choicelist)


问:
how to get selected id inside interval using jquery
Having this piece of code and i want to get selected element id (popup_w) but this.id or $(this).attr('id') or $this returning undefined...

Is there any problem with interval? How i will get the selected element id?

console.clear();
$('#btn').on('click', function(){
   $("body").prepend('
A new popup div added
');
});

var found = false;
var checkDiv = setInterval( function() {

  if ( $("div[id$='_w']").length && !found) {
    found = true;
    console.log( this.id );
  };

}, 1000);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="click" id="btn"></code>```

答:
Use this to get Id $("div[id$='_w']")[0].id

EDIT: You can use $("div[id$='_w']").attr('id'). Thanks satpal for suggestion.

console.clear();
$('#btn').on('click', function(){
   $("body").prepend('
A new popup div added
');
});

var found = false;
var checkDiv = setInterval( function() {

  if ( $("div[id$='_w']").length && !found) {
    found = true;
    console.log( $("div[id$='_w']")[0].id );
    console.log( $("div[id$='_w']").attr('id'));
  };

}, 1000);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="click" id="btn"></code>```

Body:
Having this piece of code and i want to get selected element id (popup_w) but this.id or $(this).attr('id') or $this returning undefined...

Is there any problem with interval? How i will get the selected element id?

console.clear();
$('#btn').on('click', function(){
   $("body").prepend('
A new popup div added
');
});

var found = false;
var checkDiv = setInterval( function() {

  if ( $("div[id$='_w']").length && !found) {
    found = true;
    console.log( this.id );
  };

}, 1000);

<input type="button" value="click" id="btn">

Body:
Use this to get Id $("div[id$='_w']")[0].id

EDIT: You can use $("div[id$='_w']").attr('id'). Thanks satpal for suggestion.

console.clear();
$('#btn').on('click', function(){
   $("body").prepend('<div id="popup_w">A new popup div added</div>');
});

var found = false;
var checkDiv = setInterval( function() {

  if ( $("div[id$='_w']").length && !found) {
    found = true;
    console.log( $("div[id$='_w']")[0].id );
    console.log( $("div[id$='_w']").attr('id'));
  };

}, 1000);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="click" id="btn">


问:
How to Split a Column in Data-frame and add the split values
I have a Data-frame with column "age" of type String,I want to change values in following form.

null to  999

NaN  to  0

Age greater than 200 to 999

Range(val1-val2) to  (val1 + val 2) / 2

Keeping other value same.

Input Values for example

Age
=====
0
null
NaN
999
200
35
25-30
45
null
NaN
35-40
======
```

<p><strong>Output Required</strong></p>

<pre class="lang-none prettyprint-override"><code>Age
=====
0
999
0
999
999
35
27
45
999
0
37
======
</code>```

Code I have tried until now

```<code>val formatted_df1 = df.withColumn("age", regexp_replace(col("age"), "null", "999")) -- This will change the value from null to 999
val formatted_df2 = formatted_df1.withColumn("age", regexp_replace(col("age"), "NaN", "0")) -- This will change the value from NaN to 0
</code>```

答:
You can write a simple UDF function to get the result

```<code>val scrubUdf = udf((value : String ) => {
  value match {
    case "NaN"  => 0
    case "null" => 999
    case null   => 999
    case x if x.contains("-") => {
      //          (value.split("-")(0).toInt + value.split("-")(1).toInt) / 2
      x.split("-").map(x=> x.toInt).sum / 2
    }
    case x if x.toInt >= 200 => 999
    case _ => value.toInt
  }
})
</code>```

You can call the udf as

```<code>   df.withColumn("newAge", scrubUdf($"Age"))
</code>```

Hope this helps!

Body:
I have a Data-frame with column "age" of type String,I want to change values in following form.

null to  999

NaN  to  0

Age greater than 200 to 999

Range(val1-val2) to  (val1 + val 2) / 2

Keeping other value same.

Input Values for example

Age
=====
0
null
NaN
999
200
35
25-30
45
null
NaN
35-40
======

Output Required

Age
=====
0
999
0
999
999
35
27
45
999
0
37
======

Code I have tried until now

val formatted_df1 = df.withColumn("age", regexp_replace(col("age"), "null", "999")) -- This will change the value from null to 999
val formatted_df2 = formatted_df1.withColumn("age", regexp_replace(col("age"), "NaN", "0")) -- This will change the value from NaN to 0

Body:
You can write a simple UDF function to get the result

val scrubUdf = udf((value : String ) => {
  value match {
    case "NaN"  => 0
    case "null" => 999
    case null   => 999
    case x if x.contains("-") => {
      //          (value.split("-")(0).toInt + value.split("-")(1).toInt) / 2
      x.split("-").map(x=> x.toInt).sum / 2
    }
    case x if x.toInt >= 200 => 999
    case _ => value.toInt
  }
})

You can call the udf as

   df.withColumn("newAge", scrubUdf($"Age"))

Hope this helps!


问:
c++ how to read and store values from a sentence
So there is an input file that contains something like

```
name1 arrival 20 service 20
name2 arrival 22 service 11
name3 arrival 23 service 40
```

and I'm trying to store name1, name2, name3 in string name,
arrivals (20, 22, 23) in int arrival, and service (20, 11 ,40) in int service.
I know I would have to use while loop and getline, but Im not really sure what to do. Thanks

答:
Threw together a quick example program for you. Basically, you'll want to use stringstream to store into whatever data structure you need. There may be special solutions based on what architecture you're working with, but hopefully this will get you started.</p>

```<code>  std::string str = "name1 arrival 20 service 20\nname2 arrival 22 service 11\nname3 arrival 23 service 40";
  std::stringstream iss(str);

  // Create temporary variable to store each line
  std::string line;

  // Data to hold each item
  std::string name[3];
  int arrival[3];
  int service[3];
  std::string trash; // For throwing out data

  // Read stream line by line
  int index = 0;
  while (getline(iss, line))
  {
    // Parse the line
    std::stringstream lineStream(line);

    // Read each attribute into the appropriate data structure
    lineStream >> name[index];
    lineStream >> trash;
    lineStream >> arrival[index];
    lineStream >> trash;
    lineStream >> service[index];

    // Increment index
    ++index;
  }

  // Print out the results
  for (int i = 0; i < 3; ++i)
  {
    std::cout << "Index[" << i << "]: " << name[i]
              << ", " << arrival[i] << ", " << service[i]
              << std::endl;
  }
</code>```

Body:
So there is an input file that contains something like

name1 arrival 20 service 20
name2 arrival 22 service 11
name3 arrival 23 service 40

and I'm trying to store name1, name2, name3 in string name,
arrivals (20, 22, 23) in int arrival, and service (20, 11 ,40) in int service.
I know I would have to use while loop and getline, but Im not really sure what to do. Thanks

Body:
Threw together a quick example program for you. Basically, you'll want to use stringstream to store into whatever data structure you need. There may be special solutions based on what architecture you're working with, but hopefully this will get you started.

  std::string str = "name1 arrival 20 service 20\nname2 arrival 22 service 11\nname3 arrival 23 service 40";
  std::stringstream iss(str);

  // Create temporary variable to store each line
  std::string line;

  // Data to hold each item
  std::string name[3];
  int arrival[3];
  int service[3];
  std::string trash; // For throwing out data

  // Read stream line by line
  int index = 0;
  while (getline(iss, line))
  {
    // Parse the line
    std::stringstream lineStream(line);

    // Read each attribute into the appropriate data structure
    lineStream >> name[index];
    lineStream >> trash;
    lineStream >> arrival[index];
    lineStream >> trash;
    lineStream >> service[index];

    // Increment index
    ++index;
  }

  // Print out the results
  for (int i = 0; i < 3; ++i)
  {
    std::cout << "Index[" << i << "]: " << name[i]
              << ", " << arrival[i] << ", " << service[i]
              << std::endl;
  }


答:
You can do something like this

$(document).ready(function(){

console.clear();
$('#btn').on('click', function(){
    $("body").prepend('
A new popup div added
');
    $("body").prepend('
A new popup div added
');
});

var found = false;
var checkDiv = setInterval( function() {
  if ( $("div[id$='_w']").length && !found) {
    found = true;
     $("div[id$='_w']").each(function(){
        console.log( $(this).attr('id') );
     })

  };

}, 1000);

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="click" id="btn"></code>```

Notice that each loop which is very useful if you are expecting to get the id of several div that has _w as a part of the id attribute.

Title: how to get selected id inside interval using jquery

Body:
You can do something like this

$(document).ready(function(){

console.clear();
$('#btn').on('click', function(){
    $("body").prepend('<div id="popup_w">A new popup div added</div>');
    $("body").prepend('<div id="popup2_w">A new popup div added</div>');
});

var found = false;
var checkDiv = setInterval( function() {
  if ( $("div[id$='_w']").length && !found) {
    found = true;
     $("div[id$='_w']").each(function(){
        console.log( $(this).attr('id') );
     })

  };

}, 1000);

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="click" id="btn">

Notice that each loop which is very useful if you are expecting to get the id of several div that has _w as a part of the id attribute.


问:
Ruby RegEx to locate image assets in an html/erb file
My end goal is to write a script that will loop through all my app/views folders and find any image assets being used within them (jpg, png, svg, gifs) and I can't quite get it but I feel I am close but need a little assistance.

This is how I am getting all my assets

```<code>assets_in_assets = []
# I searched for image asset names in this folder
image_asset_path = './app/assets/images'
# I haven't made use the below global variables yet
assets_in_use = []
# I plan to loop through the below folders to see if and where the image
# assets are being used
public_folder = './public'
app_folder = './app'

Find.find(image_asset_path) do |path|
# returns path and file names of all files extensions recursively
  if !File.directory?(path) && path =~ /.*[\.jpg$ | \.png$ | .svg$ | \.gif$]/
   && !(path =~ /\.DS_Store/)
    new_path = File.basename(path) # equiv to path.to_s.split('/').last
    assets_in_assets << new_path
  end
end
# The above seems to work, it gives me all the asset image names in an array.
</code>```

This is how i am trying read a html.erb file to find if and where images are being used.

Here is a sample of part of the page:

```<code><div class="wrapper">
  <div class="content-wrapper pull-center center-text">
    <img class="pattern-stars" src="<%= image_path('v3/super/pattern-
     stars.png') %>" aria-hidden="true">

    <h2 class="pull-center uppercase">Built by the Obsessed People at the
     Company</h2>
    <p class="top-mini">Our pets needed a challenge.</p>
    <p class="italicize">So we made one.</p>
    <img class="stroke" src="<%= image_path('v3/super/stroke.png') %>"
     aria-hidden="true">
  </div>
</div>

# The assets I am  expecting to find, in this small section,  are:
 #- pattern-stars.png
 #- stroke.png
</code>```

And my code (I tried two different ways, here is the first):

```<code># My plan is start with one specific file, then expand it once the code works
lines = File.open('./app/views/pages/chewer.html.erb', 'r')
lines.each do |f|
  if f =~ / [\w]+\.(jpe?g | png | gif | svg) /xi
    puts 'match: ' + f # just wanted to see what's being returned
  end
end

# This is what gets returned
# match: <img class="pattern-stars" src="<%= image_path('v3/super
# /pattern-stars.png') %>" aria-hidden="true">
# match: <img class="stroke" src="<%= image_path('v3/super/stroke.png')
# %>" aria-hidden="true">
</code>```

Not what I was hoping for. I also tried the following:

```<code>lines = File.open('./app/views/pages/chewer.html.erb', 'r')
 lines.each do |f|
  new_f = File.basename(f)
  puts 'after split' + new_f # I wanted to see what was being returned
  if new_f =~ / [\w]+\.(jpe?g | png | gif | svg) /xi
    puts 'match: ' + new_f
  end
end

# This is what gets returned
# after split: pattern-stars.png') %>" aria-hidden="true">
# match: pattern-stars.png') %>" aria-hidden="true">
# after split: stroke.png') %>" aria-hidden="true">
# match: stroke.png') %>" aria-hidden="true">
</code>```

And here I remain blocked. I have searched through S.O. and tried a few things but nothing I have found has helped but it could be that I implemented the solutions incorrectly. I also tried look-behind (using the single ' as a end point) and look-ahead (using a / as a starting point)

If this is a dup or similar to another question, please let me know. I'd appreciate the help (plus an brief explanation, I really want to get a better understanding to improve my skills.

答: (?:['"])([^'"]+\.(?:png|jpe?g|gif|svg)) seems to work in the one test case you supplied us. It relies on the image paths always being within a string as the 'this is the start of the image path' delimiter and terminates at the extension so even if the string is unclosed should stop at an appropriate place.

Body:
My end goal is to write a script that will loop through all my app/views folders and find any image assets being used within them (jpg, png, svg, gifs) and I can't quite get it but I feel I am close but need a little assistance.

This is how I am getting all my assets

assets_in_assets = []
# I searched for image asset names in this folder
image_asset_path = './app/assets/images'
# I haven't made use the below global variables yet
assets_in_use = []
# I plan to loop through the below folders to see if and where the image
# assets are being used
public_folder = './public'
app_folder = './app'

Find.find(image_asset_path) do |path|
# returns path and file names of all files extensions recursively
  if !File.directory?(path) && path =~ /.*[\.jpg$ | \.png$ | .svg$ | \.gif$]/
   && !(path =~ /\.DS_Store/)
    new_path = File.basename(path) # equiv to path.to_s.split('/').last
    assets_in_assets << new_path
  end
end
# The above seems to work, it gives me all the asset image names in an array.

This is how i am trying read a html.erb file to find if and where images are being used.

Here is a sample of part of the page:

    <img class="pattern-stars" src="<%= image_path('v3/super/pattern-
     stars.png') %>" aria-hidden="true">

Built by the Obsessed People at the
     Company

Our pets needed a challenge.

So we made one.

    <img class="stroke" src="<%= image_path('v3/super/stroke.png') %>"
     aria-hidden="true">

# The assets I am  expecting to find, in this small section,  are:
 #- pattern-stars.png
 #- stroke.png

And my code (I tried two different ways, here is the first):

# My plan is start with one specific file, then expand it once the code works
lines = File.open('./app/views/pages/chewer.html.erb', 'r')
lines.each do |f|
  if f =~ / [\w]+\.(jpe?g | png | gif | svg) /xi
    puts 'match: ' + f # just wanted to see what's being returned
  end
end

# This is what gets returned
# match: <img class="pattern-stars" src="<%= image_path('v3/super
# /pattern-stars.png') %>" aria-hidden="true">
# match: <img class="stroke" src="<%= image_path('v3/super/stroke.png')
# %>" aria-hidden="true">

Not what I was hoping for. I also tried the following:

lines = File.open('./app/views/pages/chewer.html.erb', 'r')
 lines.each do |f|
  new_f = File.basename(f)
  puts 'after split' + new_f # I wanted to see what was being returned
  if new_f =~ / [\w]+\.(jpe?g | png | gif | svg) /xi
    puts 'match: ' + new_f
  end
end

# This is what gets returned
# after split: pattern-stars.png') %>" aria-hidden="true">
# match: pattern-stars.png') %>" aria-hidden="true">
# after split: stroke.png') %>" aria-hidden="true">
# match: stroke.png') %>" aria-hidden="true">

And here I remain blocked. I have searched through S.O. and tried a few things but nothing I have found has helped but it could be that I implemented the solutions incorrectly. I also tried look-behind (using the single ' as a end point) and look-ahead (using a / as a starting point)

If this is a dup or similar to another question, please let me know. I'd appreciate the help (plus an brief explanation, I really want to get a better understanding to improve my skills.


问:
Django: standard location/conventions for data import scripts?
I'm working on a number of Django projects, and in most of them, I have initial data to import.

This data isn't neat JSON, as shown in the fixture examples in the Django docs - it tends to be messy Excel or CSV files. The scripts tend to look like the following snippet, and I just run them as standalone Python, because I don't know any better:

```<code>import sys
from django.core.management import setup_environ
sys.path.append(LOCATION OF YOUR DJANGO PROJECTS, EX: 'C:\django')
from mysite import settings
setup_environ(settings)

from PROJECT_NAME.APP_NAME.models import MODEL_NAME

import csv
reader = csv.reader(open(COMPLETE PATH TO YOUR DATA, EX: "C:/django/mysite/restaurants.csv"), dialect='excel')

for row in reader:
   COLUMN_ONE_TITLE = row[0]
   COLUMN_TWO_TITLE = row[1]

   MODEL_NAME.objects.get_or_create(MY_FIRST_COLUMN=COLUMN_ONE_TITLE, MY_SECOND_COLUMN=COLUMN_TWO_TITLE)
</code>```

I feel that when I commit these projects to GitHub or send them to the client or whatever, I should include the import scripts. They're an important part of the project.

Is there a standard way, in Django, to store the import scripts  that I've written to import this data?

Where in the project should they sit? Should I be using management commands?

Thanks!

答: I like putting them in management commands - that way when someone else works on the project, the commands are where they're expected to be by someone who wasn't familiar with the choices being made during initial development.</p>

Body:
I'm working on a number of Django projects, and in most of them, I have initial data to import.

This data isn't neat JSON, as shown in the fixture examples in the Django docs - it tends to be messy Excel or CSV files. The scripts tend to look like the following snippet, and I just run them as standalone Python, because I don't know any better:

import sys
from django.core.management import setup_environ
sys.path.append(LOCATION OF YOUR DJANGO PROJECTS, EX: 'C:\django')
from mysite import settings
setup_environ(settings)

from PROJECT_NAME.APP_NAME.models import MODEL_NAME

import csv
reader = csv.reader(open(COMPLETE PATH TO YOUR DATA, EX: "C:/django/mysite/restaurants.csv"), dialect='excel')

for row in reader:
   COLUMN_ONE_TITLE = row[0]
   COLUMN_TWO_TITLE = row[1]

   MODEL_NAME.objects.get_or_create(MY_FIRST_COLUMN=COLUMN_ONE_TITLE, MY_SECOND_COLUMN=COLUMN_TWO_TITLE)

I feel that when I commit these projects to GitHub or send them to the client or whatever, I should include the import scripts. They're an important part of the project.

Is there a standard way, in Django, to store the import scripts  that I've written to import this data?

Where in the project should they sit? Should I be using management commands?

Thanks!


问:
Django Url unknown space
My urls.py is

```<code>   urlpatterns = [
         url(r'^admin/', admin.site.urls),
         url(r'^chat/', include('chat.urls'))
  ]
</code>```

And My chat/urls.py is

```<code>   urlpatterns = [
          #url(r'^$', views.index, name="index"),
          url(r'input/$', views.input , name='input'),

        ]
</code>```

Now when I try to hit the link http://127.0.0.1:8000/chat/input/ i got the error page not found 404.

It seems like there is an unknown space are after chat/  input.
The Question why these spaces are there and how to remove them
Screen shot of error message is here

View Code in as following

```<code>  def input(request):
       input = request.POST.get('msg', None)
      data ={
           'output': 'hi',
       }
     return JsonResponse(data)
</code>```

答:
add the caret ^ sign before the url start or else it wont work

```<code>url(r'^input/$', views.input , name='input'),
</code>```

or else

change this line

```<code>url(r'^chat/', include('chat.urls'))
</code>```

to

```<code>url(r'^chat/$', include('chat.urls'))
</code>```

Title: Django Url unknown space

Body:
My urls.py is

   urlpatterns = [
         url(r'^admin/', admin.site.urls),
         url(r'^chat/', include('chat.urls'))
  ]

And My chat/urls.py is

   urlpatterns = [
          #url(r'^$', views.index, name="index"),
          url(r'input/$', views.input , name='input'),

        ]

Now when I try to hit the link http://127.0.0.1:8000/chat/input/ i got the error page not found 404.

It seems like there is an unknown space are after chat/  input.
The Question why these spaces are there and how to remove them
Screen shot of error message is here

View Code in as following

  def input(request):
       input = request.POST.get('msg', None)
      data ={
           'output': 'hi',
       }
     return JsonResponse(data)

Body:
add the caret ^ sign before the url start or else it wont work

url(r'^input/$', views.input , name='input'),

or else

change this line

url(r'^chat/', include('chat.urls'))

to

url(r'^chat/$', include('chat.urls'))


问:
Change Toggle Switch status dynamically
I am trying to figure out how to set toggle switch button base on a value. I am using bootstrap for the button. Anyone please tell me what is wrong? </p>

<p>*user.isActive only have two value either true or false.</p>

```<code><td><input id="activeSwitch" data-toggle="toggle" data-on="Active" data-off="InActive" data-onstyle="danger" data-width="90" data-height="30" style="font-size:38px" type="checkbox">
<input type="hidden" id="activeStatus" value='${user.isActive}'/></td>

<script>
 $(document).ready(function() {

                if($('#activeStatus').val() == 'true'){
                      $("#activeSwitch").attr("checked", "checked");
                }

                else if($('#activeStatus').val() == 'false'){
                     ...
                }
            });
</script>
</code>```

答:
Try like this prop() instead of attr => prop('checked',true). use Boolean value instead of string

updated

Do with trim() its remove the unwanted space

$(document).ready(function() {

  if ($('#activeStatus').val().trim() == 'true') {
    $("#activeSwitch").prop("checked", true);
  } else if ($('#activeStatus').val().trim() == 'false') {
        $("#activeSwitch").prop("checked", false);
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td><input id="activeSwitch" data-toggle="toggle" data-on="Active" data-off="InActive" data-onstyle="danger" data-width="90" data-height="30" style="font-size:38px" type="checkbox">
  <input type="hidden" id="activeStatus" value='true' /></td></code>```

or single line code

```<code>$(document).ready(function() {
 $("#activeSwitch").prop("checked" , $('#activeStatus').val().trim() == 'true')
 })
</code>```

Title: Change Toggle Switch status dynamically

Body:
I am trying to figure out how to set toggle switch button base on a value. I am using bootstrap for the button. Anyone please tell me what is wrong?

*user.isActive only have two value either true or false.

<input id="activeSwitch" data-toggle="toggle" data-on="Active" data-off="InActive" data-onstyle="danger" data-width="90" data-height="30" style="font-size:38px" type="checkbox">
<input type="hidden" id="activeStatus" value='${user.isActive}'/>

Body:
Try like this prop() instead of attr => prop('checked',true). use Boolean value instead of string

updated

Do with trim() its remove the unwanted space

$(document).ready(function() {

  if ($('#activeStatus').val().trim() == 'true') {
    $("#activeSwitch").prop("checked", true);
  } else if ($('#activeStatus').val().trim() == 'false') {
        $("#activeSwitch").prop("checked", false);
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td><input id="activeSwitch" data-toggle="toggle" data-on="Active" data-off="InActive" data-onstyle="danger" data-width="90" data-height="30" style="font-size:38px" type="checkbox">
  <input type="hidden" id="activeStatus" value='true' /></td>

or single line code

$(document).ready(function() {
 $("#activeSwitch").prop("checked" , $('#activeStatus').val().trim() == 'true')
 })


问:
How to make chart with two data axis in different sytle
How to apply different styles on characters X1 (bold and center/left position) and show asdasd (rightposition) in Y-axis of a table??

reality

edit in paint :)

答:
You can use a multi-level axis for the category axis.

If Excel does not recognize the multi-levels, then you can fix that in the data source dialog.

There is, however, no way to format the axis labels to have different fonts and font sizes for the different levels. Excel simply does not support that.

Edit: there is also no setting to turn the outer level label around. Excel will determine how to show it and there is nothing the user can do to change that.

Don't shoot the messenger.


答:
You should use MutationObserver instead of setInterval for listening changes to DOM

$('#btn').on('click', function(){
   $(".container").prepend('
A new popup div added
');
});

var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;

var element = document.querySelector('.container');
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    if (mutation.type == "childList") {
      console.log("New Node inserted with ID", mutation.addedNodes[0].id);
    }
  });
});

observer.observe(element, {
  childList: true //configure it to listen to attribute changes
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="click" id="btn">
<div class="container"></div></code>```

Body:
You should use MutationObserver instead of setInterval for listening changes to DOM

$('#btn').on('click', function(){
   $(".container").prepend('<div id="popup_w">A new popup div added</div>');
});

var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;

var element = document.querySelector('.container');
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    if (mutation.type == "childList") {
      console.log("New Node inserted with ID", mutation.addedNodes[0].id);
    }
  });
});

observer.observe(element, {
  childList: true //configure it to listen to attribute changes
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="click" id="btn">
<div class="container"></div>


问:
Why constraints is always Zero,is Storyboard preventing from edges?
Let me trying to explain my question.I have noted from long time during app designing in Storyboard/Xib. In all cases for eg while dragging some controls into storyboard obviously it shows the blue lines helps to us place controls correctly.But it's seems prevent controls from UIView(main view) layout to place edges on controller.

When we trying to place controls the blue lines prevents us from edges.see below image

But why constraints always zero  even we are not placed at edges..it should be approximately 10,10,10..,

So my Qus is

Is Storyboard/Autolayout preventing to place controls at edges?

If yes.Then why all constraints is Zero ?

If No.Then what is the use of corner blue lines(eg:first image)?

答: They are the content margins of each view which are 8 points away from its actual borders. Please check this answer, which is explained it in details. Also you can place controls in the edges, just unchecking the constrain to margins will do that