问:
Dynamically inserting html5 video element doesn't work in Opera
I'm using JavaScript to insert video elements into the DOM but it doesn't work in Opera (v10.63). The element gets inserted but the video doesn't appear/play. Works in Firefox, Chrome and Safari. I'm still running some tests to see if I can get it to work but I just wondered whether anyone else had come across this issue.

On another note which might be helpful to others, it seems event delegation is only possible with Firefox and not Opera, Chrome or Safari. That's based on code tests I've done so it could be wrong but I can't get it to work.

Many thanks

答: You could try using the HTML5 Inner Shiv. I know it's more aimed at IE, but it might be worth a shot.</p>


来源: stackexchange

问:
expression has type 'a list -> 'b list but an expression was expected of type 'b list
This is my function

```<code>let rec helper inputList = function
  | [] -> []
  | a :: b :: hd ->
    if a = b then helper ([b::hd])
    else a :: helper (b::hd)
</code>```

It's not complete, however I can't see why I keep getting the error in the title at helper ([b::hd]). I've tried helper (b::hd) or helper (b::hd::[]) however all come up with errors. How do I make it so that it works?

答:
When you use function you are supplying a pattern for the parameter of the function. But you already have a parameter named inputList. So this function helper is expecting two parameters (but it ignores the first).

You can fix this by removing inputList.

You also have a problem in your first recursive call to helper. Your expression [b :: hd] is a list of lists. I suspect that you want something more like just b :: hd here.

There is at least one other problem, but I hope this helps get you started.

ContentLicense: CC BY-SA 4.0

Body:
This is my function

let rec helper inputList = function
  | [] -> []
  | a :: b :: hd ->
    if a = b then helper ([b::hd])
    else a :: helper (b::hd)

It's not complete, however I can't see why I keep getting the error in the title at helper ([b::hd]). I've tried helper (b::hd) or helper (b::hd::[]) however all come up with errors. How do I make it so that it works?

ContentLicense: CC BY-SA 3.0


问:
Avada portfolios
I am trying to find a way to static the size of the portfolios as they become uneven due to multiple categories. I am using the Avada theme and if you go to the portfolios page (https://www.socalip.com/professionals/) you will see how some of the lower portfolios float lower than others.

Does anyone know of any CSS that might make those a static size? I'd like to keep them all uniform if possible. Apologies if i missed any important details.

Thanks in advance!

答:
Your position absolute is throwing everything out of wack. This will help you go around it

```<code>.fusion-portfolio-post.fusion-col-spacing {
     position: static !important;
}
</code>```

I'm using both classes in the specificity in case the col-spacing class is also being used somewhere else, but to make it even better, add a hook class on your highest parent div that holds this component and add that to the specificity to make it even more specific and not mess up another component in your site.

For example

```<code><div class="hook-class">
  <my shortcode for this component here/>
</div>

//CSS
.hook-class > .fusion-portfolio-post.fusion-col-spacing {
     position: static !important;
}
</code>```

EDIT (Aditional code you may need...Optional)

The H4 tag will give you problems with longer names wrapping. I would ellipse those if I were you and keep font size for legibility purposes. But it's your choice nonetheless Notice Jeff in my screenshot

```<code>.fusion-portfolio-content h4 {
    width: 200px;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
}
</code>```

Use specificity here as well.

Here is the test at different responsive breakpoints

1024px

991px

768px

<500px

Title: Avada portfolios

Body:
Your position absolute is throwing everything out of wack. This will help you go around it

.fusion-portfolio-post.fusion-col-spacing {
     position: static !important;
}

I'm using both classes in the specificity in case the col-spacing class is also being used somewhere else, but to make it even better, add a hook class on your highest parent div that holds this component and add that to the specificity to make it even more specific and not mess up another component in your site.

For example

<div class="hook-class">
  <my shortcode for this component here/>
</div>

//CSS
.hook-class > .fusion-portfolio-post.fusion-col-spacing {
     position: static !important;
}

EDIT (Aditional code you may need...Optional)

The H4 tag will give you problems with longer names wrapping. I would ellipse those if I were you and keep font size for legibility purposes. But it's your choice nonetheless Notice Jeff in my screenshot

.fusion-portfolio-content h4 {
    width: 200px;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
}

Use specificity here as well.

Here is the test at different responsive breakpoints

1024px

991px

768px

<500px


问:
Select website and its language in AlertDialog and save it
I need to load and save a website and its language in sharedpreferences. When I exit and then open the app, saved website and language load. I have used various ways, but cant achieve it. There is String and int not compatible with each other.  My simple code like this:

```<code>      private SharedPreferences prefs;
      private static final String SELECTED_ITEM = "SelectedItem";
      private SharedPreferences.Editor sharedPrefEditor;

  @SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    else if (id == R.id.web)
    final CharSequence[] items={"English","Arabic","Russian"};

        AlertDialog.Builder builder = new AlertDialog.Builder(
                MainActivity.this);

        builder.setTitle("Choose Website");
        builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {}
        });

        builder.setSingleChoiceItems(items, getSelectedItem(), new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                webView = (WebView) findViewById(R.id.webView);
                int website=current_page;

                if("English".equals(items[which]))
                {
                    webView.loadUrl("https://english.com");
                    website=("https://english.com");
                }
                else if("Arabic".equals(items[which]))
                {
                    webView.loadUrl("https://arabic.com");
                    website=("https://arabic.com");
                }
                else if("Russian".equals(items[which]))
                {
                    webView.loadUrl("https://russian.com");
                    website=("https://russian.com");
                }

                saveSelectedItem(website);
            }
        });
        builder.show();
    }

 private int getSelectedItem() {
      if (prefs == null) {
        prefs = PreferenceManager
                .getDefaultSharedPreferences(this);
    }
    return prefs.getInt(SELECTED_ITEM, -1);
}

  private void saveSelectedItem(int which) {
    if (prefs == null) {
        prefs = PreferenceManager
                .getDefaultSharedPreferences(this);
    }
    sharedPrefEditor = prefs.edit();
    sharedPrefEditor.putInt(SELECTED_ITEM, which);
    sharedPrefEditor.commit();
}
</code>```

答:
Why are you setting a String to an int variable (website)

You should probably save the language as a preference (String). and then when you load up the app, read the language preference and determine the website from there.

something like below.

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

    SharedPreferences prefs;
    if (prefs == null) {
        prefs = PreferenceManager
            .getDefaultSharedPreferences(this);
    }

    String language = prefs.getString("Language", "English");

    String website = "";

    switch(language){
        case "Russian":
            website = "russian.com";
            break;
        default:
            website = "english.com";
    }

    return website;
}

private void saveSelectedItem(String language) {
    if (prefs == null) {
        prefs = PreferenceManager
            .getDefaultSharedPreferences(this);
    }
    sharedPrefEditor = prefs.edit();
    sharedPrefEditor.putInt("language", language);
    sharedPrefEditor.commit();
}
</code>```

when you call save selected item, just pass in items[which] instead of which

Body:
I need to load and save a website and its language in sharedpreferences. When I exit and then open the app, saved website and language load. I have used various ways, but cant achieve it. There is String and int not compatible with each other.  My simple code like this:

      private SharedPreferences prefs;
      private static final String SELECTED_ITEM = "SelectedItem";
      private SharedPreferences.Editor sharedPrefEditor;

  @SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    else if (id == R.id.web)
    final CharSequence[] items={"English","Arabic","Russian"};

        AlertDialog.Builder builder = new AlertDialog.Builder(
                MainActivity.this);

        builder.setTitle("Choose Website");
        builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {}
        });

        builder.setSingleChoiceItems(items, getSelectedItem(), new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                webView = (WebView) findViewById(R.id.webView);
                int website=current_page;

                if("English".equals(items[which]))
                {
                    webView.loadUrl("https://english.com");
                    website=("https://english.com");
                }
                else if("Arabic".equals(items[which]))
                {
                    webView.loadUrl("https://arabic.com");
                    website=("https://arabic.com");
                }
                else if("Russian".equals(items[which]))
                {
                    webView.loadUrl("https://russian.com");
                    website=("https://russian.com");
                }

                saveSelectedItem(website);
            }
        });
        builder.show();
    }

 private int getSelectedItem() {
      if (prefs == null) {
        prefs = PreferenceManager
                .getDefaultSharedPreferences(this);
    }
    return prefs.getInt(SELECTED_ITEM, -1);
}

  private void saveSelectedItem(int which) {
    if (prefs == null) {
        prefs = PreferenceManager
                .getDefaultSharedPreferences(this);
    }
    sharedPrefEditor = prefs.edit();
    sharedPrefEditor.putInt(SELECTED_ITEM, which);
    sharedPrefEditor.commit();
}

Body:
Why are you setting a String to an int variable (website)

You should probably save the language as a preference (String). and then when you load up the app, read the language preference and determine the website from there.

something like below.

public String getWebsite(){

    SharedPreferences prefs;
    if (prefs == null) {
        prefs = PreferenceManager
            .getDefaultSharedPreferences(this);
    }

    String language = prefs.getString("Language", "English");

    String website = "";

    switch(language){
        case "Russian":
            website = "russian.com";
            break;
        default:
            website = "english.com";
    }

    return website;
}

private void saveSelectedItem(String language) {
    if (prefs == null) {
        prefs = PreferenceManager
            .getDefaultSharedPreferences(this);
    }
    sharedPrefEditor = prefs.edit();
    sharedPrefEditor.putInt("language", language);
    sharedPrefEditor.commit();
}

when you call save selected item, just pass in items[which] instead of which


问:
When to use Variable classes? (BooleanVar, DoubleVar, IntVar, StringVar)
Can't tkinter.widget.configure(text="our text") be used for all widgets? What is the advantage, or the main purpose of using:

```<code>var_cls = tkinter.StringVar()
tkinter.widget.configure(textvariable=var_cls)
</code>```

Is it that var_cls can be more easily shared among methods/classes etc?

Example with a Variable class:

```<code>import tkinter as tk
root = tk.Tk()
var = tk.StringVar(value="This will be on the label.")
tk.Label(root, textvariable=var).pack()
root.mainloop()
</code>```

Example without a Variable class:

```<code>import tkinter as tk
root = tk.Tk()
tk.Label(root, text="This will be on the label.").pack()
root.mainloop()
</code>```

答: StringVar can be bound to a widget, so you just need to have a handle on the StringVar and you can modify its value and it will update automatically. Otherwise, you would need to keep a handle on the widget itself and handle the event loop stuff etc. Basically you should use StringVar etc. when the value could change. If it's going to be static for certain, you don't need it.

Body:
Can't tkinter.widget.configure(text="our text") be used for all widgets? What is the advantage, or the main purpose of using:

var_cls = tkinter.StringVar()
tkinter.widget.configure(textvariable=var_cls)

Is it that var_cls can be more easily shared among methods/classes etc?

Example with a Variable class:

import tkinter as tk
root = tk.Tk()
var = tk.StringVar(value="This will be on the label.")
tk.Label(root, textvariable=var).pack()
root.mainloop()

Example without a Variable class:

import tkinter as tk
root = tk.Tk()
tk.Label(root, text="This will be on the label.").pack()
root.mainloop()


问:
InvalidOperationException when calling SaveChanges in .NET Entity framework
I'm trying to learn how to use the Entity framework but I've hit an issue I can't solve.
What I'm doing is that I'm walking through a list of Movies that I have and inserts each one into a simple database.

This is the code I'm using

```<code>private void AddMovies(DirectoryInfo dir)
{
    MovieEntities db = new MovieEntities();
    foreach (DirectoryInfo d in dir.GetDirectories())
    {
        Movie m = new Movie { Name = d.Name, Path = dir.FullName };
        db.AddToMovies(movie);
    }
    db.SaveChanges();
}
</code>```

When I do this I get an exception at db.SaveChanges() that read.

The changes to the database were
  committed successfully, but an error
  occurred while updating the object
  context. The ObjectContext might be in
  an inconsistent state. Inner exception
  message: AcceptChanges cannot continue
  because the object's key values
  conflict with another object in the
  ObjectStateManager. Make sure that the
  key values are unique before calling
  AcceptChanges.

I haven't been able to find out what's causing this issue.
My database table contains three columns

Id int autoincrement

Name nchar(255)

Path nchar(255)

Update:
I Checked my edmx file and the SSDL section have the StoreGeneratedPattern="Identity" as suggested. I also followed the blog post and tried to add ClientAutoGenerated="true" and StoreGenerated="true" in the CSDL as suggested there. This resulted in compile errors ( Error 5: The 'ClientAutoGenerated' attribute is not allowed.). Since the blog post is from 2006 and it has a link to a follow up post I assume it's been changed.

However, I cannot read the followup post since it seems to require an msdn account.

答:
```<code>System.Data.Objects.SaveOptions.None
</code>```

This solves the problem but I'm wondering what's the difference between uning none or the other options.

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to learn how to use the Entity framework but I've hit an issue I can't solve.
What I'm doing is that I'm walking through a list of Movies that I have and inserts each one into a simple database.

This is the code I'm using

private void AddMovies(DirectoryInfo dir)
{
    MovieEntities db = new MovieEntities();
    foreach (DirectoryInfo d in dir.GetDirectories())
    {
        Movie m = new Movie { Name = d.Name, Path = dir.FullName };
        db.AddToMovies(movie);
    }
    db.SaveChanges();
}

When I do this I get an exception at db.SaveChanges() that read.

The changes to the database were
  committed successfully, but an error
  occurred while updating the object
  context. The ObjectContext might be in
  an inconsistent state. Inner exception
  message: AcceptChanges cannot continue
  because the object's key values
  conflict with another object in the
  ObjectStateManager. Make sure that the
  key values are unique before calling
  AcceptChanges.

I haven't been able to find out what's causing this issue.
My database table contains three columns

Id int autoincrement

Name nchar(255)

Path nchar(255)

Update:
I Checked my edmx file and the SSDL section have the StoreGeneratedPattern="Identity" as suggested. I also followed the blog post and tried to add ClientAutoGenerated="true" and StoreGenerated="true" in the CSDL as suggested there. This resulted in compile errors ( Error 5: The 'ClientAutoGenerated' attribute is not allowed.). Since the blog post is from 2006 and it has a link to a follow up post I assume it's been changed.

However, I cannot read the followup post since it seems to require an msdn account.

Body:
System.Data.Objects.SaveOptions.None

This solves the problem but I'm wondering what's the difference between uning none or the other options.


问:
Rails 3: Where are Javascript :defaults defined after running "rails g jquery:install"?
I just installed jQuery 1.4.4 with Rails 3 as described here.

I do have the following line in views/layouts/application.html.erb:

```<code><%= javascript_include_tag :defaults %>
</code>```

However, in config/application.rb the following line is still commented:

```<code># config.action_view.javascript_expansions[:defaults] = ...
</code>```

If so, where does Rails defines what :defaults means in javascript_include_tag :defaults ?

(My application works fine. I just want to understand where :defaults is defined.)

答:
I installed jQuery support using the gem as described here, and ran the jquery:install generator.  That installed the necessary .js files, but it did -not- automatically cause them to be included in the HTML generated by

```<code><%= javascript_include_tag :defaults %>
</code>```

To get that to generate the correct HTML, I had to follow the last instruction in the Manual Installation section and manually change "%w()" to "%w(jquery rails)" on the

```<code>config.action_view.javascript_expansions[:defaults] = %w()
</code>```

line in my config/application.rb file, after which, everything began working properly.

If it makes any difference, I had created my application using the --skip-prototype option in anticipation of using jQuery instead of Prototype.

Body:
I just installed jQuery 1.4.4 with Rails 3 as described here.

I do have the following line in views/layouts/application.html.erb:

<%= javascript_include_tag :defaults %>

However, in config/application.rb the following line is still commented:

# config.action_view.javascript_expansions[:defaults] = ...

If so, where does Rails defines what :defaults means in javascript_include_tag :defaults ?

(My application works fine. I just want to understand where :defaults is defined.)

Body:
I installed jQuery support using the gem as described here, and ran the jquery:install generator.  That installed the necessary .js files, but it did -not- automatically cause them to be included in the HTML generated by

<%= javascript_include_tag :defaults %>

To get that to generate the correct HTML, I had to follow the last instruction in the Manual Installation section and manually change "%w()" to "%w(jquery rails)" on the

config.action_view.javascript_expansions[:defaults] = %w()

line in my config/application.rb file, after which, everything began working properly.

If it makes any difference, I had created my application using the --skip-prototype option in anticipation of using jQuery instead of Prototype.


问:
How to exclude whole word only in negative lookahead
I have the following regex:

```<code>^(?!FIT|FAT|FUTURE)[F-I].*
</code>```

[F-I] shows that any words starting with F to I should match apart from the given list of words that shouldn't match.

Currently, it doesn't match a word like FITTER, but I only want the regex to not match if it's a whole word such as FIT, FAT and FUTURE.

These are following scenarios I want it to work for:

Matches

```<code>FUTURE-YES
FITTER
GOOD
ITCHY
</code>```

Non Matches

```<code>FIT
FAT
FUTURE
</code>```

答:
Brief

Usually, you would use word boundaries \b to ensure the edge of a word. In your case, however, you have some words that use hyphens -, thus, this is likely the solution you're looking for.

Code

See regex in use here

```<code>^(?!(?:FIT|FAT|FUTURE)(?![\w-]))[F-I][\w-]*$
</code>```

Results

Input

```<code>FUTURE-YES
FITTER
GOOD
ITCHY

FIT
FAT
FUTURE
</code>```

Output

Note: Shown below are matches

```<code>FUTURE-YES
FITTER
GOOD
ITCHY
</code>```

Explanation

^ Assert position at the start of the line

(?!(?:FIT|FAT|FUTURE)(?![\w-])) Negative lookahead ensuring what follows does not match

(?:FIT|FAT|FUTURE) Match either FIT, FAT or FUTURE literally

(?![\w-]) Negative lookahead ensuring what follows does not match a word character or hyphen -

[F-I] Match a character between F and I (FGHI)

[\w-]* Match any word character or hyphen - character any number of times

$ Assert position at the end of the line

Body:
I have the following regex:

^(?!FIT|FAT|FUTURE)[F-I].*

[F-I] shows that any words starting with F to I should match apart from the given list of words that shouldn't match.

Currently, it doesn't match a word like FITTER, but I only want the regex to not match if it's a whole word such as FIT, FAT and FUTURE.

These are following scenarios I want it to work for:

Matches

FUTURE-YES
FITTER
GOOD
ITCHY

Non Matches

FIT
FAT
FUTURE

Body:
Brief

Usually, you would use word boundaries \b to ensure the edge of a word. In your case, however, you have some words that use hyphens -, thus, this is likely the solution you're looking for.

Code

See regex in use here

^(?!(?:FIT|FAT|FUTURE)(?![\w-]))[F-I][\w-]*$

Results

Input

FUTURE-YES
FITTER
GOOD
ITCHY

FIT
FAT
FUTURE

Output

Note: Shown below are matches

FUTURE-YES
FITTER
GOOD
ITCHY

Explanation

^ Assert position at the start of the line

(?!(?:FIT|FAT|FUTURE)(?![\w-])) Negative lookahead ensuring what follows does not match

(?:FIT|FAT|FUTURE) Match either FIT, FAT or FUTURE literally

(?![\w-]) Negative lookahead ensuring what follows does not match a word character or hyphen -

[F-I] Match a character between F and I (FGHI)

[\w-]* Match any word character or hyphen - character any number of times

$ Assert position at the end of the line


问:
Convert UTC into Local Time on Android
In my project, I have get the API response in json format. I get a string value of time in UTC time format like this Jul 16, 2013 12:08:59 AM.

I need to change this into Local time.
That is where ever we use this the app needs to show the local time. How to I do this?

Here is some Code I have tried:

```<code>String aDate = getValue("dateTime", aEventJson);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss z");
simpleDateFormat.setTimeZone(TimeZone.getDefault());
String formattedDate = simpleDateFormat.format(aDate);
</code>```

Assume aDate contains Jul 16, 2013 12:08:59 AM

答:
I should like to contribute the modern answer. While SimpleDateFormat was the class we had for parsing and formatting date-times in 2013 (apart from Joda-Time), it is now long outdated, and we have so much better in java.time or JSR-310, the modern Java date and time API that came out with Java 8 in 2014.

But most Android devices still don’t run Java 8, I hear you say. Fortunately you can still use the modern Java date and time API on them through the ThreeTenABP, the backport of JSR-310 to Android Java 7. Details are in this question: How to use ThreeTenABP in Android Project.

Now the code is:

```<code>    DateTimeFormatter formatter
            = DateTimeFormatter.ofPattern("MMM dd, uuuu hh:mm:ss a", Locale.ENGLISH);
    String aDate = "Jul 16, 2013 12:08:59 AM";
    String formattedDate = LocalDateTime.parse(aDate, formatter)
            .atOffset(ZoneOffset.UTC)
            .atZoneSameInstant(ZoneId.systemDefault())
            .format(formatter);
    System.out.println(formattedDate);
</code>```

Since my computer is running Europe/Copenhagen time zone, which in July is 2 hours ahead of UTC, this prints

```<code>Jul 16, 2013 02:08:59 AM
</code>```

Further points:

Since you have AM in your string, I assumed your hours are within AM, from 1 through 12. To parse and format them correctly you need lowercase h in the format pattern string. Uppercase H is for hour-of-day from 0 through 23.

Prefer to give an explcit locale to the formatter (whether SimpleDateFormat or DateTimeFormatter). If no locale is given, the formatter will use the device’s default locale. “Jul” and “AM” are in English, and your code may run nicely on many devices until one day it runs on a device with non-English locale and crashes, and you have a hard time figuring out why.

If you can, give the desired time zone explictly, for example as ZoneId.of("Asia/Kolkata"). The JVM’s default time zone may be changed by other parts of your program or other programs running in the same JVM, so is not reliable.

Title: Convert UTC into Local Time on Android

Body:
In my project, I have get the API response in json format. I get a string value of time in UTC time format like this Jul 16, 2013 12:08:59 AM.

I need to change this into Local time.
That is where ever we use this the app needs to show the local time. How to I do this?

Here is some Code I have tried:

String aDate = getValue("dateTime", aEventJson);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss z");
simpleDateFormat.setTimeZone(TimeZone.getDefault());
String formattedDate = simpleDateFormat.format(aDate);

Assume aDate contains Jul 16, 2013 12:08:59 AM

Body:
I should like to contribute the modern answer. While SimpleDateFormat was the class we had for parsing and formatting date-times in 2013 (apart from Joda-Time), it is now long outdated, and we have so much better in java.time or JSR-310, the modern Java date and time API that came out with Java 8 in 2014.

But most Android devices still don’t run Java 8, I hear you say. Fortunately you can still use the modern Java date and time API on them through the ThreeTenABP, the backport of JSR-310 to Android Java 7. Details are in this question: How to use ThreeTenABP in Android Project.

Now the code is:

    DateTimeFormatter formatter
            = DateTimeFormatter.ofPattern("MMM dd, uuuu hh:mm:ss a", Locale.ENGLISH);
    String aDate = "Jul 16, 2013 12:08:59 AM";
    String formattedDate = LocalDateTime.parse(aDate, formatter)
            .atOffset(ZoneOffset.UTC)
            .atZoneSameInstant(ZoneId.systemDefault())
            .format(formatter);
    System.out.println(formattedDate);

Since my computer is running Europe/Copenhagen time zone, which in July is 2 hours ahead of UTC, this prints

Jul 16, 2013 02:08:59 AM

Further points:

Since you have AM in your string, I assumed your hours are within AM, from 1 through 12. To parse and format them correctly you need lowercase h in the format pattern string. Uppercase H is for hour-of-day from 0 through 23.

Prefer to give an explcit locale to the formatter (whether SimpleDateFormat or DateTimeFormatter). If no locale is given, the formatter will use the device’s default locale. “Jul” and “AM” are in English, and your code may run nicely on many devices until one day it runs on a device with non-English locale and crashes, and you have a hard time figuring out why.

If you can, give the desired time zone explictly, for example as ZoneId.of("Asia/Kolkata"). The JVM’s default time zone may be changed by other parts of your program or other programs running in the same JVM, so is not reliable.


问:
Can't get rid of non-unicode characters in numpy array
I have a table:
vals = table.iloc[sum(which(pa_i),[1]),1:]
content:

```<code>Out[249]:
                      1         2       3
2  NA [1] (16.0 to N/A)  12.0 [2]  NA [1]
</code>```

When I write vals.values I get:
vals

```<code>Out[250]: array([['NA\xa0[1] (16.0\xa0to\xa0N/A)', '12.0\xa0[2]', 'NA\xa0[1]']], dtype=object)
</code>```

I simply want to get this table to an array or list but earlier want to replace \xa0 values. When I apply:
v = print(map(lambda s: s.replace('\xa0' , ' '), vals)) I don't know how to read this object or when
np.char.replace(vals[0],'\xa0' , ' ') I get error "TypeError: string operation on non-string array".

What is the easiest way to convert the content to array or to replace unwanted chars??

EDIT

I've got a solution: v = vals.astype('str') and v = np.char.replace(v,'\xa0' , ' ').

```<code>Out[306]: array([['NA [1] (16.0 to N/A)', '12.0 [2]', 'NA [1]']], dtype='<U20')
</code>```

But I'm not fully satisfied of this answer. I need something to work directly on vals variable - for example by doing this:
a = vals[1:].toarray(?)
expected result:

```<code>a
Out[318]: ['(16.0 to N/A)', '12.0 [2]', 'NA [1]]']
</code>```

答:
Well, its because it contains int elements and not str

Do this:

```<code>table.values = [str(v) for v in table.values]
</code>```

Body:
I have a table:
vals = table.iloc[sum(which(pa_i),[1]),1:]
content:

Out[249]:
                      1         2       3
2  NA [1] (16.0 to N/A)  12.0 [2]  NA [1]

When I write vals.values I get:
vals

Out[250]: array([['NA\xa0[1] (16.0\xa0to\xa0N/A)', '12.0\xa0[2]', 'NA\xa0[1]']], dtype=object)

I simply want to get this table to an array or list but earlier want to replace \xa0 values. When I apply:
v = print(map(lambda s: s.replace('\xa0' , ' '), vals)) I don't know how to read this object or when
np.char.replace(vals[0],'\xa0' , ' ') I get error "TypeError: string operation on non-string array".

What is the easiest way to convert the content to array or to replace unwanted chars??

EDIT

I've got a solution: v = vals.astype('str') and v = np.char.replace(v,'\xa0' , ' ').

Out[306]: array([['NA [1] (16.0 to N/A)', '12.0 [2]', 'NA [1]']], dtype='<U20')

But I'm not fully satisfied of this answer. I need something to work directly on vals variable - for example by doing this:
a = vals[1:].toarray(?)
expected result:

a
Out[318]: ['(16.0 to N/A)', '12.0 [2]', 'NA [1]]']

Body:
Well, its because it contains int elements and not str

Do this:

table.values = [str(v) for v in table.values]


问:
randomizing a sequence in a 1d array in c
**This is not generating a number, it is rearranging the number in 1d array
Need help in randomizing the sequence of 0,1,2,3 number in rbox array. however when random, it shows 1,1,1,1 or 2,2,2,2 etc. anyone have idea how to randomize the sequence into 0,3,2,1 or 2,0,1,3 etc?</p>

```<code>srand(time(NULL));
int randomm = rand()%4;
int rbox[4];
int x;

for(x=0;x<4;x++)
{
    rbox[x] = 0;
}
for(x=0;x<4;x++)
{
    rbox[x] = randomm;
}
for(x=0;x<4;x++)
{
    printf("%i", rbox[x]);
}
</code>```

答:
```<code>for(x=0;x<4;x++)
{
    rbox[x] = rand()%4;
}
</code>```

Assign each element of array to a different output of rand().

Here you are assigning every element of array rbox to same value (random) - that explains why you are getting same value.

Shuffle of the array:

As from user's comment it seems that OP wants to create shuffle of the array.

Now to do that either you can initialize the whole array with values 0,1,2,3 and then apply this algorithm

```<code>-- To shuffle an array a of n elements (indices 0..n-1):
for i from n−1 downto 1 do
     j ← random integer such that 0 ≤ j ≤ i
     exchange a[j] and a[i]
</code>```

This is known as Fisher Yates Shuffle.

Also other ways...

Another way would be to follow this algorithm :-

Keep track of the range of numbers (this is basically highestNumInRange - iteration Number).

And then keep track of the number of elements you need to generate.

3.1. If the ratio of 2 multiplied with rand() is less than 1 then put the number of iteration in the array.

3.2. Else increase the iteration.

Body:
**This is not generating a number, it is rearranging the number in 1d array
Need help in randomizing the sequence of 0,1,2,3 number in rbox array. however when random, it shows 1,1,1,1 or 2,2,2,2 etc. anyone have idea how to randomize the sequence into 0,3,2,1 or 2,0,1,3 etc?

srand(time(NULL));
int randomm = rand()%4;
int rbox[4];
int x;

for(x=0;x<4;x++)
{
    rbox[x] = 0;
}
for(x=0;x<4;x++)
{
    rbox[x] = randomm;
}
for(x=0;x<4;x++)
{
    printf("%i", rbox[x]);
}

Body:
for(x=0;x<4;x++)
{
    rbox[x] = rand()%4;
}

Assign each element of array to a different output of rand().

Here you are assigning every element of array rbox to same value (random) - that explains why you are getting same value.

Shuffle of the array:

As from user's comment it seems that OP wants to create shuffle of the array.

Now to do that either you can initialize the whole array with values 0,1,2,3 and then apply this algorithm

-- To shuffle an array a of n elements (indices 0..n-1):
for i from n−1 downto 1 do
     j ← random integer such that 0 ≤ j ≤ i
     exchange a[j] and a[i]

This is known as Fisher Yates Shuffle.

Also other ways...

Another way would be to follow this algorithm :-

Keep track of the range of numbers (this is basically highestNumInRange - iteration Number).

And then keep track of the number of elements you need to generate.

3.1. If the ratio of 2 multiplied with rand() is less than 1 then put the number of iteration in the array.

3.2. Else increase the iteration.


问:
Update wizard not responding
Every time I need to update my emdx from database, the update wizard takes an incredible amount of time to do so rendering itself as not responding once you hit the finish (as finish the update) button.

I use Visual Studio 2015 and LocalDb SQL Server 2014. Some people suggested to install the Service Pack 1 to address the issue. I have installed the SP1 for LocalDb, but it has not helped. My installation of VS2015 is also rather new.

I have the latest Entity Framework 6 version (from nuget).

答: I still had to do this with Microsoft SQL Server 2014 (SP2-GDR) (KB4019093) - 12.0.5207.0 (X64)   Jul  3 2017 02:25:44   Copyright (c) Microsoft Corporation  Standard Edition (64-bit) on Windows NT 6.3 <X64> (Build 9600: ) (Hypervisor) using Entity Framework 6.2.0.  How in the world has this not yet been solved?!

Title: Update wizard not responding


问:
Calling a Variable from another Class
How can I access a variable in one public class from another public class in C#?

I have:

```<code>public class Variables
{
   static string name = "";
}
</code>```

I need to call it from:

```<code>public class Main
{
}
</code>```

I am working in a Console App.

答:
```<code>class Program
{
    Variable va = new Variable();
    static void Main(string[] args)
    {
        va.name = "Stackoverflow";
    }
}
</code>```

Title: Calling a Variable from another Class

Body:
How can I access a variable in one public class from another public class in C#?

I have:

public class Variables
{
   static string name = "";
}

I need to call it from:

public class Main
{
}

I am working in a Console App.


问:
How to replace all elements in vector by the sum of element digits?
I have trouble understanding how to replace all elements in vector by the sum of element digits. For example if i have sequence of such digits 9 22 54 981 my output has to be 9 4 9 18.I know how to count the sum. I have this vector called file_numbers .But I am stuck at this point. Thanks for the help.

```<code>   int SumOfDigits(int digit)
{

    int sum = 0;
    while (digit > 0)
    {
        sum += digit % 10;
        digit /= 10;
    }
    return sum;
}
void FourthTask(vector<int>& file_numbers)
{
    std::transform(file_numbers.begin(),
        file_numbers.end(),
        file_numbers.begin(),SumOfDigits);
}
</code>```

答:
You might need to #include <algorithm>

```<code>int SumOfDigits(int digit)
{
    int sum = 0;
    while (digit > 0)
    {
        sum += digit % 10;
        digit /= 10;
    }
    return sum;
}

void FourthTask(vector<int>& file_numbers)
{
    std::transform(file_numbers.begin(),
                   file_numbers.end(),
                   file_numbers.begin(),
                   SumOfDigits);
}
</code>```

Body:
I have trouble understanding how to replace all elements in vector by the sum of element digits. For example if i have sequence of such digits 9 22 54 981 my output has to be 9 4 9 18.I know how to count the sum. I have this vector called file_numbers .But I am stuck at this point. Thanks for the help.

   int SumOfDigits(int digit)
{

    int sum = 0;
    while (digit > 0)
    {
        sum += digit % 10;
        digit /= 10;
    }
    return sum;
}
void FourthTask(vector<int>& file_numbers)
{
    std::transform(file_numbers.begin(),
        file_numbers.end(),
        file_numbers.begin(),SumOfDigits);
}

Body:
You might need to #include <algorithm>

int SumOfDigits(int digit)
{
    int sum = 0;
    while (digit > 0)
    {
        sum += digit % 10;
        digit /= 10;
    }
    return sum;
}

void FourthTask(vector<int>& file_numbers)
{
    std::transform(file_numbers.begin(),
                   file_numbers.end(),
                   file_numbers.begin(),
                   SumOfDigits);
}


问:
Create list of integers that correspond to a matched date between 2 different lengthed date objects
I have 2 date objects: a list of 73 dates which correspond to the start dates of 73 files which each have 5 days worth of data in them like so:

```<code>> head(fd)
[1] "1993-01-01" "1993-01-06" "1993-01-11" "1993-01-16" "1993-01-21" "1993-01-26"
</code>```

I then have a large list of 110k+ dates which correspond to observations which are at irregular, non-linear intervals but are classed as a date object like so:

```<code>> head(dd)
[1] "1993-01-04" "1993-01-10" "1993-01-05" "1993-01-15" "1993-01-18" "1993-01-03"
</code>```

I am trying to create a new list of values which link each of the values in dd to a value of fd such that if a date in dd is between 1993-01-01 and 1993-01-05 it gets a value of 1 and so on. It is far to inefficient both to code and compute, to use a loop. I tried to do this using the which function:

```<code>i <- which(dd >= fd[-length(fd)] & dd < fd[-1])
</code>```

but this returns a warning:

```<code>Warning messages:
1: In `>=.default`(dd, fd[-length(fd)]) :
  longer object length is not a multiple of shorter object length
2: In `<.default`(dd, fd[-1]) :
  longer object length is not a multiple of shorter object length
</code>```

and does not return the required output. It merely returns a list of integers which correspond to values in dd which it believes to be matched that don't apear to follow a logical order. Any suggestions?

For the above summarised data sets I would require a result of

```<code>>i
[1] 1 2 1 3 4 1
</code>```

as each date in dd would correspond to the 1st, 2nd, 1st, 3rd, 4th and 1st date in fd respectively.

The match function, as far as I'm aware cannot accomplish this as if you simply use:

```<code>i <- match(dd, fd)
</code>```

You are returned with a list of mostly NAs where the dates do not exactly match and roughly 365/5 numbers that do correspond to one of the dates in fd

答:
I think which.min is what you are after.  Try:

```<code>i <- sapply(dd, function(x)which.min(x > fd) - 1)
</code>```

If a date in dd is less than the smallest date in df, it will return 0. This does assume that df is sorted in ascending order.  I tried it with the following values:

```<code>fd <- seq.Date(as.Date("1993-01-01"), by="5 days", length=74)
dd <- sample(seq.Date(from = min(fd), to = max(fd) - 1, by="1 day"),
             size = 1E5, replace = TRUE)
</code>```

On my rather modest laptop, that took 64 seconds.
BTW, "which" (and which.min) is base R.

Edit- the inequality should of course be > not >=.

Also, in this case where fd is a simple sequence, there is obviously a much simpler solution:

```<code>startDate <- min(fd)
i2 <- as.integer((testSeq-startDate)/5) + 1
</code>```

Dealing with dates earlier than startDate would require some minor refinements.

Body:
I have 2 date objects: a list of 73 dates which correspond to the start dates of 73 files which each have 5 days worth of data in them like so:

> head(fd)
[1] "1993-01-01" "1993-01-06" "1993-01-11" "1993-01-16" "1993-01-21" "1993-01-26"

I then have a large list of 110k+ dates which correspond to observations which are at irregular, non-linear intervals but are classed as a date object like so:

> head(dd)
[1] "1993-01-04" "1993-01-10" "1993-01-05" "1993-01-15" "1993-01-18" "1993-01-03"

I am trying to create a new list of values which link each of the values in dd to a value of fd such that if a date in dd is between 1993-01-01 and 1993-01-05 it gets a value of 1 and so on. It is far to inefficient both to code and compute, to use a loop. I tried to do this using the which function:

i <- which(dd >= fd[-length(fd)] & dd < fd[-1])

but this returns a warning:

Warning messages:
1: In `>=.default`(dd, fd[-length(fd)]) :
  longer object length is not a multiple of shorter object length
2: In `<.default`(dd, fd[-1]) :
  longer object length is not a multiple of shorter object length

and does not return the required output. It merely returns a list of integers which correspond to values in dd which it believes to be matched that don't apear to follow a logical order. Any suggestions?

For the above summarised data sets I would require a result of

>i
[1] 1 2 1 3 4 1

as each date in dd would correspond to the 1st, 2nd, 1st, 3rd, 4th and 1st date in fd respectively.

The match function, as far as I'm aware cannot accomplish this as if you simply use:

i <- match(dd, fd)

You are returned with a list of mostly NAs where the dates do not exactly match and roughly 365/5 numbers that do correspond to one of the dates in fd

Body:
I think which.min is what you are after.  Try:

i <- sapply(dd, function(x)which.min(x > fd) - 1)

If a date in dd is less than the smallest date in df, it will return 0. This does assume that df is sorted in ascending order.  I tried it with the following values:

fd <- seq.Date(as.Date("1993-01-01"), by="5 days", length=74)
dd <- sample(seq.Date(from = min(fd), to = max(fd) - 1, by="1 day"),
             size = 1E5, replace = TRUE)

On my rather modest laptop, that took 64 seconds.
BTW, "which" (and which.min) is base R.

Edit- the inequality should of course be > not >=.

Also, in this case where fd is a simple sequence, there is obviously a much simpler solution:

startDate <- min(fd)
i2 <- as.integer((testSeq-startDate)/5) + 1

Dealing with dates earlier than startDate would require some minor refinements.


问:
Check if a column exists in SQLite
I need to check to see if a column exists and if it doesn't exist add it.  From my research it looks like sqlite doesn't support IF statements and case statement should be used instead.

Here is what I have so far:

```<code>SELECT CASE WHEN exists(select * from qaqc.columns where Name = "arg" and Object_ID = Object_ID("QAQC_Tasks")) = 0 THEN ALTER TABLE QAQC_Tasks ADD arg INT DEFAULT(0);
</code>```

But I get the error: Near "ALTER": Syntax error.

Any ideas?

答:
Some of these examples didn't worked for me. I'm trying to check whether my table already contains a column or not.

I'm using this snippet:

```<code>public boolean tableHasColumn(SQLiteDatabase db, String tableName, String columnName) {
    boolean isExist = false;
    Cursor cursor = db.rawQuery("PRAGMA table_info("+tableName+")",null);
    int cursorCount = cursor.getCount();
    for (int i = 1; i < cursorCount; i++ ) {
        cursor.moveToPosition(i);
        String storedSqlColumnName = cursor.getString(cursor.getColumnIndex("name"));
        if (columnName.equals(storedSqlColumnName)) {
            isExist = true;
        }
    }
    return isExist;
}
</code>```

The examples above are querying the pragma table which is a metadata table and not the actual data, each column indicates the names, type and some other stuff about the table's columns. So the actual column names are within the rows.

Hope that this helps someone else.

Title: Check if a column exists in SQLite

Body:
I need to check to see if a column exists and if it doesn't exist add it.  From my research it looks like sqlite doesn't support IF statements and case statement should be used instead.

Here is what I have so far:

SELECT CASE WHEN exists(select * from qaqc.columns where Name = "arg" and Object_ID = Object_ID("QAQC_Tasks")) = 0 THEN ALTER TABLE QAQC_Tasks ADD arg INT DEFAULT(0);

But I get the error: Near "ALTER": Syntax error.

Any ideas?

Body:
Some of these examples didn't worked for me. I'm trying to check whether my table already contains a column or not.

I'm using this snippet:

public boolean tableHasColumn(SQLiteDatabase db, String tableName, String columnName) {
    boolean isExist = false;
    Cursor cursor = db.rawQuery("PRAGMA table_info("+tableName+")",null);
    int cursorCount = cursor.getCount();
    for (int i = 1; i < cursorCount; i++ ) {
        cursor.moveToPosition(i);
        String storedSqlColumnName = cursor.getString(cursor.getColumnIndex("name"));
        if (columnName.equals(storedSqlColumnName)) {
            isExist = true;
        }
    }
    return isExist;
}

The examples above are querying the pragma table which is a metadata table and not the actual data, each column indicates the names, type and some other stuff about the table's columns. So the actual column names are within the rows.

Hope that this helps someone else.


问:
When do you use POST and when do you use GET?
From what I can gather, there are three categories:

Never use GET and use POST

Never use POST and use GET

It doesn't matter which one you use.

Am I correct in assuming those three cases? If so, what are some examples from each case?

答:
Because GETs are purely URLs, they can be cached by the web browser and may be better used for things like consistently generated images. (Set an Expiry time)

One example from the gravatar page: http://www.gravatar.com/avatar/4c3be63a4c2f539b013787725dfce802?d=monsterid

GET may yeild marginally better performance, some webservers write POST contents to a temporary file before invoking the handler.

Another thing to consider is the size limit. GETs are capped by the size of the URL, 1024 bytes by the standard, though browsers may support more.

Transferring more data than that should use a POST to get better browser compatibility.

Even less than that limit is a problem, as another poster wrote, anything in the URL could end up in other parts of the brower's UI, like history.

OwnerDisplayName: Thomas Owens

LastEditorDisplayName: RoBorg

OwnerDisplayName: davenpcj


问:
How do I print an IFrame from javascript in Safari/Chrome
Can someone please help me out with printing the contents of an IFrame via a javascript call in Safari/Chrome.

This works in firefox:

```<code>$('#' + id)[0].focus();
$('#' + id)[0].contentWindow.print();
</code>```

this works in IE:

```<code>window.frames[id].focus();
window.frames[id].print();
</code>```

But I can't get anything to work in Safari/Chrome.

Thanks

Andrew

答:
Here is my complete, cross browser solution:

In the iframe page:

```<code>function printPage() { print(); }
</code>```

In the main page

```<code>function printIframe(id)
{
    var iframe = document.frames
        ? document.frames[id]
        : document.getElementById(id);
    var ifWin = iframe.contentWindow || iframe;

    iframe.focus();
    ifWin.printPage();
    return false;
}
</code>```

Update: Many people seem to be having problems with this in versions of IE released since I had this problem. I do not have the time to re-investigate this right now, but, if you are stuck I suggest you read all the comments in this entire thread!

OwnerDisplayName: Andrew Bullock

Body:
Can someone please help me out with printing the contents of an IFrame via a javascript call in Safari/Chrome.

This works in firefox:

$('#' + id)[0].focus();
$('#' + id)[0].contentWindow.print();

this works in IE:

window.frames[id].focus();
window.frames[id].print();

But I can't get anything to work in Safari/Chrome.

Thanks

Andrew

Body:
Here is my complete, cross browser solution:

In the iframe page:

function printPage() { print(); }

In the main page

function printIframe(id)
{
    var iframe = document.frames
        ? document.frames[id]
        : document.getElementById(id);
    var ifWin = iframe.contentWindow || iframe;

    iframe.focus();
    ifWin.printPage();
    return false;
}

Update: Many people seem to be having problems with this in versions of IE released since I had this problem. I do not have the time to re-investigate this right now, but, if you are stuck I suggest you read all the comments in this entire thread!


问:
How can i use iPhone's accelerometer in our project?
I want to create simple application on iphone. For this purpose i use accelerometer, my object is on the track and whenever it will go outside the track, it will detect if i moved iphone</p>

答:
copy and pasting directly from this stackoverflow answer

The APIs you are looking for are in UIResponder:

```<code>- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event;
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event;
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event;
</code>```

Generally you just implement this:

```<code>- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
  if (event.type == UIEventSubtypeMotionShake) {
    //Your code here
  }
}
</code>```

in your UIViewController subclass (UIViewController is a subclass of UIResponder). Also, you want to handle it in motionEnded:withEvent:, not motionBegan:withEvent:. motionBegan:withEvent: is called when the phone suspects shaking is happening, but the OS can determine the difference between a user purposefully shaking, and incidental shaking (like walking up the stairs). If the OS decides it was not a real shake after motionBegan:withEvent: is called it will call motionCancelled: instead of motionEnded:withEvent:.

Body:
copy and pasting directly from this stackoverflow answer

The APIs you are looking for are in UIResponder:

- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event;
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event;
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event;

Generally you just implement this:

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
  if (event.type == UIEventSubtypeMotionShake) {
    //Your code here
  }
}

in your UIViewController subclass (UIViewController is a subclass of UIResponder). Also, you want to handle it in motionEnded:withEvent:, not motionBegan:withEvent:. motionBegan:withEvent: is called when the phone suspects shaking is happening, but the OS can determine the difference between a user purposefully shaking, and incidental shaking (like walking up the stairs). If the OS decides it was not a real shake after motionBegan:withEvent: is called it will call motionCancelled: instead of motionEnded:withEvent:.


问:
Angular 4: deleteRow in table, splice error
I have a quick question regarding Angular 4 and splicing.

Below is my Typescript code:

delete(appIndex: number): void {
    this.apps.splice(appIndex, 1);
  }

Below is my HTML Code:

```<code><tr  *ngFor="let app of apps; let i = index">
      <td><input type="text" [(contenteditableModel)]="text1"  tabindex="1"> {{ text1 }}</td>
      <td><input type="text"  [(contenteditableModel)]="text2" tabindex="2">{{ text2 }}</td>
      <td><input type="text"  [(contenteditableModel)]="text2" tabindex="3">{{ text3 }}</td>
      <td class="actions">
        <input type="button" value="Delete" (click)="delete(i)">
      </td>
    </tr>
</code>```

The issue I am running into is 'Cannot read property 'splice' of undefined. When I further researched into this, I found that in Angular 1, '$scope' was used in order to access within the DOM. How do I replicate this in Angular 4?

UPDATE:

I have edited my code to read like:

Typescript:

```<code> delete(appIndex: number) {
this.apps.splice(appIndex, 1);
this.changeDetectorRef.detectChanges();
</code>```

}

HTML:

```<code>  <tr class="odd">
      <td class="status"><img src="../../../assets/images/Red_Circle_1.png" class="redcircle"></td>
      <td><input type="text" [(contenteditableModel)]="text4"> {{ text4 }}</td>
      <td><input type="text" [(contenteditableModel)]="text5">{{ text5 }}</td>
      <td><input type="text" [(contenteditableModel)]="text6">{{ text6 }}</td>
      <td class="actions">
          <input type="button" value="Delete" *ngFor="let app of apps; let i = index" (click)="delete(i)">
      </td>
    </tr>
</code>```

Here is the  plunker: http://plnkr.co/edit/2KaXodEe2CbQdLXZtVaC?p=preview

I'm not getting any errors now, but the delete button is not displaying at all.
Any suggestions would be appreciated.

Thank you.

答:
Your code should work without problem so long as you are executing delete from the component whose template you called it from.

Here is basically the same code working: Live demo

Body:
I have a quick question regarding Angular 4 and splicing.

Below is my Typescript code:

delete(appIndex: number): void {
    this.apps.splice(appIndex, 1);
  }

Below is my HTML Code:

      <input type="text" [(contenteditableModel)]="text1"  tabindex="1"> {{ text1 }}
      <input type="text"  [(contenteditableModel)]="text2" tabindex="2">{{ text2 }}
      <input type="text"  [(contenteditableModel)]="text2" tabindex="3">{{ text3 }}

        <input type="button" value="Delete" (click)="delete(i)">

The issue I am running into is 'Cannot read property 'splice' of undefined. When I further researched into this, I found that in Angular 1, '$scope' was used in order to access within the DOM. How do I replicate this in Angular 4?

UPDATE:

I have edited my code to read like:

Typescript:

 delete(appIndex: number) {
this.apps.splice(appIndex, 1);
this.changeDetectorRef.detectChanges();

}

HTML:

      <input type="text" [(contenteditableModel)]="text4"> {{ text4 }}
      <input type="text" [(contenteditableModel)]="text5">{{ text5 }}
      <input type="text" [(contenteditableModel)]="text6">{{ text6 }}

          <input type="button" value="Delete" *ngFor="let app of apps; let i = index" (click)="delete(i)">

Here is the  plunker: http://plnkr.co/edit/2KaXodEe2CbQdLXZtVaC?p=preview

I'm not getting any errors now, but the delete button is not displaying at all.
Any suggestions would be appreciated.

Thank you.


问:
how to separating a nested list python
I am trying to create a new list build from the items inside the list
for example list = [[math,chemistery],biology]

I would like to create the new list

```<code>new_list = [math, chemistery, biology]
</code>```

thanks for the help

答:
You can use numpy hstack.</p>

```<code>import numpy as np
my_list = [['math', 'chemistery'], 'biology']
list(np.hstack(my_list)) # returns ['math', 'chemistery', 'biology']
</code>```

Title: how to separating a nested list python

Body:
I am trying to create a new list build from the items inside the list
for example list = [[math,chemistery],biology]

I would like to create the new list

new_list = [math, chemistery, biology]

thanks for the help

Body:
You can use numpy hstack.

import numpy as np
my_list = [['math', 'chemistery'], 'biology']
list(np.hstack(my_list)) # returns ['math', 'chemistery', 'biology']


问:
Android-How Can I grant Runtime Permission with NO user interaction?
I made an app for testing various phone functions with no user interaction, but it was not working on some devices, even though it worked fine before.  My theory was that it needed runt-time permissions and I was right.  When I put the run-time permission in the activity, it works perfectly.  The problem is that it requests the permissions from the user and I can't have user interaction.  Is there a way to grant permissions to the activity without user interaction?

I will include an activity where I got the recorder activity to work, but is dependent on the user granting permission. Please help!!

```<code>    public static final int RECORD_AUDIO_PERMISSION_REQUEST = 3;

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
                /*
         * API's to launch the application when the tablet is locked or
         * display is turned off
         */
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
        setContentView(R.layout.activity_recorder);

        //Check to see if the device has a microphone
        PackageManager pm = getPackageManager();
        boolean micPresent = pm.hasSystemFeature(PackageManager.FEATURE_MICROPHONE);
        if (!micPresent) {
            Log.i(log_tag, "There is no microphone present in this device.");
            exit_function();
        } else {
            createTempFile(status_tag, "INPROGRESS");

            //Create the file to write the recording
            try {
                FileOutputStream fOut = openFileOutput("audio_test.3gp", MODE_WORLD_READABLE);
            } catch (IOException e) {
                e.printStackTrace();
                Log.e(log_tag, "FAILED TO CREATE THE FILE OUTPUT STREAM");
                exit_function();
            }

//            if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, RECORD_AUDIO_PERMISSION_REQUEST);

            //start_recording();
        }
    }

    //Start the Recording
    private void start_recording() {
        if (recorder != null) {
            recorder.stop();
            recorder.reset();
            recorder.release();
            recorder = null;
        }
        //Setting for the Recorder
        try {
            Log.i(log_tag, "Setting the recorder");
            //This is the path that the file will be saved
            path = getFilesDir().getAbsolutePath() + "/audio_test.3gp";
            recorder = new MediaRecorder();
            recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
            recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            recorder.setOutputFile(path);

        } catch (Exception e) {
            Log.e(log_tag, "Recording Settings Failed");
            exit_function();
        }
        //Prepare the Recorder
        try {
            Log.i(log_tag, "Preparing the Recorder");
            recorder.prepare();
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(log_tag, "Recording failed");
            exit_function();
        }

        //Start the Recorder
        try {
            Log.i(log_tag, "Starting the recorder");
            title_text = ((TextView) findViewById(R.id.textView));
            title_text.setTextColor(Color.RED);
            title_text.setText("RECORDING");
            recorder.start();

            //The recording lasts as long as he timer and then stops
            mHandler.postDelayed(new Runnable() {
                public void run() {
                    if (recorder != null) {
                        recorder.stop();
                        recorder.reset();
                        recorder.release();
                        recorder = null;
                    }
                    Log.e(log_tag, "First Delay");
                    exit_function();
                }
            }, timer);
            createTempFile(status_tag, "Complete");

        } catch (Exception e) {
            e.printStackTrace();
            Log.e(log_tag, "Recorder start failed");
            exit_function();
        }
    }
        @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case  RECORD_AUDIO_PERMISSION_REQUEST:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    start_recording();
                } else {
                    onDestroy();
                }
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
</code>```

答:
Yea it is possible but its have a some limitations .

1) You have to use sdk 22 or below , if you use sdk above 22 than it will ask you
     run time permission.

go to app level gradle and put targetSdkVersion 22 .

i tried this method its works !

here sample project link :-https://github.com/kdblue/PermissionGranted

Body:
I made an app for testing various phone functions with no user interaction, but it was not working on some devices, even though it worked fine before.  My theory was that it needed runt-time permissions and I was right.  When I put the run-time permission in the activity, it works perfectly.  The problem is that it requests the permissions from the user and I can't have user interaction.  Is there a way to grant permissions to the activity without user interaction?

I will include an activity where I got the recorder activity to work, but is dependent on the user granting permission. Please help!!

    public static final int RECORD_AUDIO_PERMISSION_REQUEST = 3;

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
                /*
         * API's to launch the application when the tablet is locked or
         * display is turned off
         */
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
        setContentView(R.layout.activity_recorder);

        //Check to see if the device has a microphone
        PackageManager pm = getPackageManager();
        boolean micPresent = pm.hasSystemFeature(PackageManager.FEATURE_MICROPHONE);
        if (!micPresent) {
            Log.i(log_tag, "There is no microphone present in this device.");
            exit_function();
        } else {
            createTempFile(status_tag, "INPROGRESS");

            //Create the file to write the recording
            try {
                FileOutputStream fOut = openFileOutput("audio_test.3gp", MODE_WORLD_READABLE);
            } catch (IOException e) {
                e.printStackTrace();
                Log.e(log_tag, "FAILED TO CREATE THE FILE OUTPUT STREAM");
                exit_function();
            }

//            if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, RECORD_AUDIO_PERMISSION_REQUEST);

            //start_recording();
        }
    }

    //Start the Recording
    private void start_recording() {
        if (recorder != null) {
            recorder.stop();
            recorder.reset();
            recorder.release();
            recorder = null;
        }
        //Setting for the Recorder
        try {
            Log.i(log_tag, "Setting the recorder");
            //This is the path that the file will be saved
            path = getFilesDir().getAbsolutePath() + "/audio_test.3gp";
            recorder = new MediaRecorder();
            recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
            recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            recorder.setOutputFile(path);

        } catch (Exception e) {
            Log.e(log_tag, "Recording Settings Failed");
            exit_function();
        }
        //Prepare the Recorder
        try {
            Log.i(log_tag, "Preparing the Recorder");
            recorder.prepare();
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(log_tag, "Recording failed");
            exit_function();
        }

        //Start the Recorder
        try {
            Log.i(log_tag, "Starting the recorder");
            title_text = ((TextView) findViewById(R.id.textView));
            title_text.setTextColor(Color.RED);
            title_text.setText("RECORDING");
            recorder.start();

            //The recording lasts as long as he timer and then stops
            mHandler.postDelayed(new Runnable() {
                public void run() {
                    if (recorder != null) {
                        recorder.stop();
                        recorder.reset();
                        recorder.release();
                        recorder = null;
                    }
                    Log.e(log_tag, "First Delay");
                    exit_function();
                }
            }, timer);
            createTempFile(status_tag, "Complete");

        } catch (Exception e) {
            e.printStackTrace();
            Log.e(log_tag, "Recorder start failed");
            exit_function();
        }
    }
        @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case  RECORD_AUDIO_PERMISSION_REQUEST:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    start_recording();
                } else {
                    onDestroy();
                }
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }


问:
Including a header file in a .S to get some struct size
I am trying to compile a mixed C-code and an assembly-code project, while trying to share information between .S file and some header file, I ran into a problem.

I have created two files, as follows:

asm.S:

```<code>#include "common.h"

.space SOME_STRUCT_SIZE
.word SOME_MAGIC

.globl main
b start

start:
   ; ... code here
</code>```

common.h:

```<code>struct someStruct {
    int data;
};

#define SOME_STRUCT_SIZE sizeof(struct someStruct)
#define SOME_MAGIC 0x12345678
</code>```

When trying to compile the .S file (arm-linux-gnueabi-gcc -o asm asm.S), I get error messages indicating the assembler is trying to assemble the .h file, and obviously fails on the struct definition.

```<code>common.h: Assembler messages:
common.h:2: Error: bad instruction 'int data'
</code>```

Is it possible to force the pre-processor to statically create both defines and insert them in a way that the assembly code can use?

答:
I implemented what @pm100 suggested, and it worked out just fine.

common_bare_gen.c:

```<code>#include "common.h"
#include <stdio.h>

void main(void){
    FILE *common_bare_fp;
    common_bare_fp = fopen("common_bare.h", "w");

    fprintf(common_bare_fp, "#define SOME_STRUCT_SIZE 0x%08x\n", SOME_STRUCT_SIZE);
    fprintf(common_bare_fp, "#define SOME_MAGIC 0x%08x\n", SOME_MAGIC);
    fclose(common_bare_fp);
}
</code>```

In asm.S I changed:

```<code>#include "common_bare.h"
</code>```

And added two commands to compile and execute common_bare_gen in my Makefile.

Thanks a lot for your help!

Body:
I am trying to compile a mixed C-code and an assembly-code project, while trying to share information between .S file and some header file, I ran into a problem.

I have created two files, as follows:

asm.S:

#include "common.h"

.space SOME_STRUCT_SIZE
.word SOME_MAGIC

.globl main
b start

start:
   ; ... code here

common.h:

struct someStruct {
    int data;
};

#define SOME_STRUCT_SIZE sizeof(struct someStruct)
#define SOME_MAGIC 0x12345678

When trying to compile the .S file (arm-linux-gnueabi-gcc -o asm asm.S), I get error messages indicating the assembler is trying to assemble the .h file, and obviously fails on the struct definition.

common.h: Assembler messages:
common.h:2: Error: bad instruction 'int data'

Is it possible to force the pre-processor to statically create both defines and insert them in a way that the assembly code can use?

Body:
I implemented what @pm100 suggested, and it worked out just fine.

common_bare_gen.c:

#include "common.h"
#include <stdio.h>

void main(void){
    FILE *common_bare_fp;
    common_bare_fp = fopen("common_bare.h", "w");

    fprintf(common_bare_fp, "#define SOME_STRUCT_SIZE 0x%08x\n", SOME_STRUCT_SIZE);
    fprintf(common_bare_fp, "#define SOME_MAGIC 0x%08x\n", SOME_MAGIC);
    fclose(common_bare_fp);
}

In asm.S I changed:

#include "common_bare.h"

And added two commands to compile and execute common_bare_gen in my Makefile.

Thanks a lot for your help!


问:
how to Filter Place Picker's results by PlaceType?
At the moment the Place Picker shows the map with all of the Places marked on the map. The list of places is at the bottom of the screen.

It would be great if I could filter the places by Place Type.

For example, the map and list would only show Taxis stands nearby.

My java code:

```<code>import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.widget.Toast;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlacePicker;

public class PlacesAPIActivity extends AppCompatActivity {

    private int PLACE_PICKER_REQUEST = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_places_api);

                PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
                Intent intent;
                try {
                    intent = builder.build(getApplicationContext());
                    startActivityForResult(intent, PLACE_PICKER_REQUEST);
                } catch (GooglePlayServicesRepairableException e) {
                    e.printStackTrace();
                } catch (GooglePlayServicesNotAvailableException e) {
                    e.printStackTrace();
                }

            }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_place_api, menu);

        return true;
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == PLACE_PICKER_REQUEST) {
            if (resultCode == RESULT_OK) {

                Place place = PlacePicker.getPlace(data , this) ;

                String toastMsg = String.format("Place: %s %s", place.getName(), place.getPhoneNumber());
                Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();
            }
        }
    }

}
</code>```

My XML:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:background="@drawable/bg_gradient">
</code>```

答:
a Workaround could be to check the PlaceType and take action accordingly:</p>

```<code>if (!place.getPlaceTypes().contains(1013)){ // 1013 = point of interest
 // Do action if Selected place not a point of interest
}
</code>```

Body:
At the moment the Place Picker shows the map with all of the Places marked on the map. The list of places is at the bottom of the screen.

It would be great if I could filter the places by Place Type.

For example, the map and list would only show Taxis stands nearby.

My java code:

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.widget.Toast;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlacePicker;

public class PlacesAPIActivity extends AppCompatActivity {

    private int PLACE_PICKER_REQUEST = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_places_api);

                PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
                Intent intent;
                try {
                    intent = builder.build(getApplicationContext());
                    startActivityForResult(intent, PLACE_PICKER_REQUEST);
                } catch (GooglePlayServicesRepairableException e) {
                    e.printStackTrace();
                } catch (GooglePlayServicesNotAvailableException e) {
                    e.printStackTrace();
                }

            }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_place_api, menu);

        return true;
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == PLACE_PICKER_REQUEST) {
            if (resultCode == RESULT_OK) {

                Place place = PlacePicker.getPlace(data , this) ;

                String toastMsg = String.format("Place: %s %s", place.getName(), place.getPhoneNumber());
                Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();
            }
        }
    }

}

My XML:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:background="@drawable/bg_gradient">

Body:
a Workaround could be to check the PlaceType and take action accordingly:

if (!place.getPlaceTypes().contains(1013)){ // 1013 = point of interest
 // Do action if Selected place not a point of interest
}


问:
IIS error, Unable to start debugging on the webserver
I want to run my application from IIS on my local machine. I created the virtual directory and added the application to it and in the properties folder of the application I checked the radio button 'Use Local IIS Webserver'. I then started running my application but I'm getting the following error:

Unable to start debugging on the webserver.see help for common configuration errors.Running the webpage outside of the debugger may provide further information.

Make sure the server in operating correctly.Verify there are no syntax errors in web.config by doing a debug.Start Without Debugging.You may also want to refer to the ASP.NET and ATL Server debugging topic in the online documentation.

How do I get rid of this error?

I'm using Visual Studio 2010 on Windows 7 and IIS 7.5.

答:
Just one of the 10 sites configured on my Local IIS was giving this error, so I had a feeling that it wasn't anything from the other answers that were machine-wide things, like Turning Windows Features On or Off, or running VS2015 as admin (the other 9 sites worked ok, in the same VS).

The specific error for me was:

Unable to start debugging on the webserver. Operation not supported. Unknown error:0x80004005

The problem turned out to be the web config having a URL Rewrite rule to rewrite HTTP -> HTTPS. Commenting this out resolved the problem

TL;DR - try disabling all your web.config URL rewrite rules, if you have them (then add them back in gradually, if it helps)


问:
PHP/Javascript - Instant search, but different?
I have a page with a blank search bar, and then a bunch on contacts below it in a table. Each contact is one div.

I want to be able to filter the contact table as text is entered into the search bar. (So, for instance, if "Fran" was typed in to the search bar, you'd only see contacts with "Fran" in their name. And then all would go back to default if "Fran" was deleted.)

Is this possible? How? (I found an instant search diy guide, but it only worked the way Google does, with a dropdown beneath the search bar.)

答:
Here is some example Javascript for you:</p>

```<code><script type="text/javascript">
$(document).ready(function() {
    $("#search").keyup(function() {
        // Get the search value
        var searchValue = $(this).val();

        // If no value exists then show all divs
        if(searchValue === "") {
            $(".your_div").show();
            return;
        }

        // Initially hide all divs
        $(".your_div").hide();

        // Now show any that contain the search value
        $(".your_div:contains('" + searchValue + "').show();
    });
});
</script>
</code>```

Body:
Here is some example Javascript for you:

<script type="text/javascript">
$(document).ready(function() {
    $("#search").keyup(function() {
        // Get the search value
        var searchValue = $(this).val();

        // If no value exists then show all divs
        if(searchValue === "") {
            $(".your_div").show();
            return;
        }

        // Initially hide all divs
        $(".your_div").hide();

        // Now show any that contain the search value
        $(".your_div:contains('" + searchValue + "').show();
    });
});
</script>


问:
Converting an array of wrappers to an array of primitives
If I have an array of instances of primitive wrapper classes, how can I obtain an array of their respective primitives?

```<code>Object toPrimitiveArray(Object[] wrappedArray) {
    return ?;
}

Object primitiveArray = toPrimitiveArray(new Integer[] { 1, 2, 3 });
</code>```

In the above example, I'd like toPrimitiveArray() to return an int[] containing the int values 1, 2, and 3.

答:
This answer is quite late, but hopefully it helps future visitors to this questions.
My take on a reflective solution can be improved but the basic idea is this:

```<code>@SuppressWarnings("unchecked")
private static <TArray, TElement> TArray toArray(final Object elements, final Class<TElement> elementType)
{
  final int length = java.lang.reflect.Array.getLength(elements);
  final Object resultArray = java.lang.reflect.Array.newInstance(elementType, length);

  for (int i = 0; i < length; ++i)
  {
    final Object value = java.lang.reflect.Array.get(elements, i);

    java.lang.reflect.Array.set(resultArray, i, value);
  }

  return (TArray)resultArray;
}
</code>```

Then use as following:

```<code>final Boolean[] booleans = new Boolean[] { true, false, true, true, false };
final boolean[] primitives = toArray(booleans, boolean.class);

System.out.println(Arrays.asList(booleans));

for (boolean b : primitives)
{
  System.out.print(b);
  System.out.print(", ");
}
</code>```

This prints out:

```<code>[true, false, true, true, false]
true, false, true, true, false,
</code>```

This utility helps us pull arrays out of java.sql.Array, because java.sql.Array only gives us an Object for the array.

Body:
If I have an array of instances of primitive wrapper classes, how can I obtain an array of their respective primitives?

Object toPrimitiveArray(Object[] wrappedArray) {
    return ?;
}

Object primitiveArray = toPrimitiveArray(new Integer[] { 1, 2, 3 });

In the above example, I'd like toPrimitiveArray() to return an int[] containing the int values 1, 2, and 3.

Body:
This answer is quite late, but hopefully it helps future visitors to this questions.
My take on a reflective solution can be improved but the basic idea is this:

@SuppressWarnings("unchecked")
private static <TArray, TElement> TArray toArray(final Object elements, final Class<TElement> elementType)
{
  final int length = java.lang.reflect.Array.getLength(elements);
  final Object resultArray = java.lang.reflect.Array.newInstance(elementType, length);

  for (int i = 0; i < length; ++i)
  {
    final Object value = java.lang.reflect.Array.get(elements, i);

    java.lang.reflect.Array.set(resultArray, i, value);
  }

  return (TArray)resultArray;
}

Then use as following:

final Boolean[] booleans = new Boolean[] { true, false, true, true, false };
final boolean[] primitives = toArray(booleans, boolean.class);

System.out.println(Arrays.asList(booleans));

for (boolean b : primitives)
{
  System.out.print(b);
  System.out.print(", ");
}

This prints out:

[true, false, true, true, false]
true, false, true, true, false,

This utility helps us pull arrays out of java.sql.Array, because java.sql.Array only gives us an Object for the array.


问:
Rails includes with multiple conditions
Let's say I've got this relation:

```<code>Users has_many Orders, Visits
</code>```

For each user, I want to compose an object like so:

```<code>{Name: user.name, Orders: user.orders, Visits: user.visits}
</code>```

And I want to restrict visits to those occurring in the past year, and orders to those occurring in the past month. Right now I'm trying to use this query:

```<code>Users.includes(:Visits, :Orders).where('Visit.occurred_on > ?', 1.year.ago)
                                .where('Order.date > ?', 1.month.ago)
                                .references(:Visits, :Orders)
</code>```

The problem is, this returns only those users where both where conditions are met because the conditions are applied after the outer joins. Is there a way to only include the records I'm looking for?

答:
You can alter your query like this:

```<code>Users.includes(:Visits, :Orders).where('Visit.occurred_on > ? AND Order.date > ?', 1.year.ago, 1.month.ago)
</code>```

Let me know this is worked for you or not.

Note: Query didn't tested

Title: Rails includes with multiple conditions

Body:
Let's say I've got this relation:

Users has_many Orders, Visits

For each user, I want to compose an object like so:

{Name: user.name, Orders: user.orders, Visits: user.visits}

And I want to restrict visits to those occurring in the past year, and orders to those occurring in the past month. Right now I'm trying to use this query:

Users.includes(:Visits, :Orders).where('Visit.occurred_on > ?', 1.year.ago)
                                .where('Order.date > ?', 1.month.ago)
                                .references(:Visits, :Orders)

The problem is, this returns only those users where both where conditions are met because the conditions are applied after the outer joins. Is there a way to only include the records I'm looking for?

Body:
You can alter your query like this:

Users.includes(:Visits, :Orders).where('Visit.occurred_on > ? AND Order.date > ?', 1.year.ago, 1.month.ago)

Let me know this is worked for you or not.

Note: Query didn't tested


问:
Why and how the new keyword is being used with the already existing object of a class?
I'm using PHP 7.1.11

Consider below code :

```<code><?php
  class Test {
    static public function getNew() {
      return new static;
    }
  }

  class Child extends Test {}

  $obj1 = new Test();
  $obj2 = new $obj1;
?>
</code>```

Above code snippet has been taken from the PHP Manual.

From the above code I'm not able to understand why and how the new keyword is being used with the existing object of a class Test?

What's the intention behind doing like this?

Is this kind of usage of new keyword recommended?

If you really want to assign an already existing object of a class to some variable then can't it be done by simply writing the statement $obj2 = $obj1;?

What's the difference between below two statements? Which one is better and should be preferred?

```<code>$obj2 = new $obj1;
$obj2 = $obj1;
</code>```

答:
The new operator always creates a new instance of an object. It takes one argument, which can be a hard-coded class name:

```<code>$newObject = new MyClass();
</code>```

Or a variable that contains a class name:

```<code>$className = 'MyClass';
$newObject = new $className();
</code>```

Or an existing instance of an object of the type you want to create:

```<code>$oldObject = new MyClass();
$newObject = new $oldObject(); // Same as using "new MyClass();"
</code>```

You'll probably never use the third case.

Body:
I'm using PHP 7.1.11

Consider below code :

<?php
  class Test {
    static public function getNew() {
      return new static;
    }
  }

  class Child extends Test {}

  $obj1 = new Test();
  $obj2 = new $obj1;
?>

Above code snippet has been taken from the PHP Manual.

From the above code I'm not able to understand why and how the new keyword is being used with the existing object of a class Test?

What's the intention behind doing like this?

Is this kind of usage of new keyword recommended?

If you really want to assign an already existing object of a class to some variable then can't it be done by simply writing the statement $obj2 = $obj1;?

What's the difference between below two statements? Which one is better and should be preferred?

$obj2 = new $obj1;
$obj2 = $obj1;

Body:
The new operator always creates a new instance of an object. It takes one argument, which can be a hard-coded class name:

$newObject = new MyClass();

Or a variable that contains a class name:

$className = 'MyClass';
$newObject = new $className();

Or an existing instance of an object of the type you want to create:

$oldObject = new MyClass();
$newObject = new $oldObject(); // Same as using "new MyClass();"

You'll probably never use the third case.


问:
can't organise my data in my tableau
I'm using php and Angular JS and this is my code :

```<code> <table  class="table table-bordered">
                        <thead>
                        <tr>
                            <th><Bold>Participation fille-société</Bold></th>
                            <th><Bold>Secteur d'activité</Bold></th>
                            <th><Bold>Date d'acquisition</Bold></th>
                            <th><Bold>Prix d'acquisition</Bold></th>
                            <th><Bold>Tri actualisé</Bold></th>
                            <th><Bold>Type d'operation</Bold></th>
                            <th><Bold>Participations meres</Bold></th>
                            <th><Bold>Action<Bold></th>
                        </tr>
                        </thead>
                        </tbody>
                        <tr >
                            <td><Bold><a href="consultationPFS.php?id_participationfilleS={{ps.id_participationfilleS}}">{{ps.nomParticipationFilleS}}</Bold></td>
                            <td><Bold>{{ps.secteurActivite}}</Bold></td>
                            <td><Bold>{{ps.date_aquisition}}</Bold></td>
                            <td><Bold>{{ps.Prix_acquisition}}</Bold></td>
                            <td><Bold>{{ps.tri_actualise}}</Bold></td>
                            <td><Bold>{{ps.tri_actualise}}</Bold></td>
                            <td  ng-repeat="ac in DataPmers"><Bold>{{ac.nom_participation}} {{ac.pourcentage}}%</Bold></td>
                            <td><a type="submit" class="edit-row" href="UpdatePFS.php?id_participationfilleS={{ps.id_participationfilleS}}" title="Modifier" ><i class="fa fa-pencil"></i></a> |  <a type="submit" class="delet-row" title="Supprimer" ng-click="supp(ps)"><i class="fa fa-trash"</i></button></a> | <a type="submit" class="edit-row" href="EtatPFS.php?id_participationfilleS={{ps.id_participationfilleS}}" title="Modifier" ><i class="fa fa-pencil"></i></a></td>

                        </tr>
                        </tbody>
                    </table><div class="box-footer clearfix">
</code>```

And the result like in the picture below :

As u can see in Participations meres it give me only one data and other line of data in other column

How can I get all data of participation mere in the same column ?

答:
Would this work for you - new row of the table for each DataPmers?</p>

```<code><table  class="table table-bordered">
                 <thead>
                    <tr>
                        <th><Bold>Participation fille-société</Bold></th>
                        <th><Bold>Secteur d'activité</Bold></th>
                        <th><Bold>Date d'acquisition</Bold></th>
                        <th><Bold>Prix d'acquisition</Bold></th>
                        <th><Bold>Tri actualisé</Bold></th>
                        <th><Bold>Type d'operation</Bold></th>
                        <th><Bold>Participations meres</Bold></th>
                        <th><Bold>Action<Bold></th>
                    </tr>
                 </thead>
                 </tbody>
                    <tr ng-repeat="ac in DataPmers">
                        <td><Bold><a href="consultationPFS.php?id_participationfilleS={{ps.id_participationfilleS}}">{{ps.nomParticipationFilleS}}</Bold></td>
                        <td><Bold>{{ps.secteurActivite}}</Bold></td>
                        <td><Bold>{{ps.date_aquisition}}</Bold></td>
                        <td><Bold>{{ps.Prix_acquisition}}</Bold></td>
                        <td><Bold>{{ps.tri_actualise}}</Bold></td>
                        <td><Bold>{{ps.tri_actualise}}</Bold></td>
                        <td><Bold>{{ac.nom_participation}} {{ac.pourcentage}}%</Bold></td>
                        <td><a type="submit" class="edit-row" href="UpdatePFS.php?id_participationfilleS={{ps.id_participationfilleS}}" title="Modifier" ><i class="fa fa-pencil"></i></a> |  <a type="submit" class="delet-row" title="Supprimer" ng-click="supp(ps)"><i class="fa fa-trash"</i></button></a> | <a type="submit" class="edit-row" href="EtatPFS.php?id_participationfilleS={{ps.id_participationfilleS}}" title="Modifier" ><i class="fa fa-pencil"></i></a></td>

                    </tr>
                 </tbody>
</table>
</code>```

Title: can't organise my data in my tableau

Body:
I'm using php and Angular JS and this is my code :

                            <Bold>Participation fille-société</Bold>
                            <Bold>Secteur d'activité</Bold>
                            <Bold>Date d'acquisition</Bold>
                            <Bold>Prix d'acquisition</Bold>
                            <Bold>Tri actualisé</Bold>
                            <Bold>Type d'operation</Bold>
                            <Bold>Participations meres</Bold>
                            <Bold>Action<Bold>

                            <Bold>{{ps.nomParticipationFilleS}}</Bold>
                            <Bold>{{ps.secteurActivite}}</Bold>
                            <Bold>{{ps.date_aquisition}}</Bold>
                            <Bold>{{ps.Prix_acquisition}}</Bold>
                            <Bold>{{ps.tri_actualise}}</Bold>
                            <Bold>{{ps.tri_actualise}}</Bold>
                            <Bold>{{ac.nom_participation}} {{ac.pourcentage}}%</Bold>
                             |  <i class="fa fa-trash"</button> |

And the result like in the picture below :

As u can see in Participations meres it give me only one data and other line of data in other column

How can I get all data of participation mere in the same column ?

Body:
Would this work for you - new row of the table for each DataPmers?

<table  class="table table-bordered">
                 <thead>
                    <tr>
                        <th><Bold>Participation fille-société</Bold></th>
                        <th><Bold>Secteur d'activité</Bold></th>
                        <th><Bold>Date d'acquisition</Bold></th>
                        <th><Bold>Prix d'acquisition</Bold></th>
                        <th><Bold>Tri actualisé</Bold></th>
                        <th><Bold>Type d'operation</Bold></th>
                        <th><Bold>Participations meres</Bold></th>
                        <th><Bold>Action<Bold></th>
                    </tr>
                 </thead>
                 </tbody>
                    <tr ng-repeat="ac in DataPmers">
                        <td><Bold><a href="consultationPFS.php?id_participationfilleS={{ps.id_participationfilleS}}">{{ps.nomParticipationFilleS}}</Bold></td>
                        <td><Bold>{{ps.secteurActivite}}</Bold></td>
                        <td><Bold>{{ps.date_aquisition}}</Bold></td>
                        <td><Bold>{{ps.Prix_acquisition}}</Bold></td>
                        <td><Bold>{{ps.tri_actualise}}</Bold></td>
                        <td><Bold>{{ps.tri_actualise}}</Bold></td>
                        <td><Bold>{{ac.nom_participation}} {{ac.pourcentage}}%</Bold></td>
                        <td><a type="submit" class="edit-row" href="UpdatePFS.php?id_participationfilleS={{ps.id_participationfilleS}}" title="Modifier" ><i class="fa fa-pencil"></i></a> |  <a type="submit" class="delet-row" title="Supprimer" ng-click="supp(ps)"><i class="fa fa-trash"</i></button></a> | <a type="submit" class="edit-row" href="EtatPFS.php?id_participationfilleS={{ps.id_participationfilleS}}" title="Modifier" ><i class="fa fa-pencil"></i></a></td>

                    </tr>
                 </tbody>
</table>


问:
Nested comments with Classic ASP and MySQL
The idea behind what I'm trying to achieve is similar to a forum / commenting system I guess. There will be a main topic, then people can reply to that topic and to each other.

As replies are going to be in a completely different order in the database to how they will be displayed the way I thought best to achieve this is to have a parent_id col in the table, parent_id = 0 for a topic message, then replies have the relevant id's for the reply they correspond to.

Then I could use a recursive function to get the data in the right order and display like so e.g.:

Parent Topic

reply

reply

    reply to reply

reply

   reply to reply

       reply to reply to reply

reply

However this is where I am stuck. I'm quite new to VBScript, so it could be something really simple to do, but I just can't see it.

Anyone help it's driving me nuts.

答:
I guess you ask for help with the code required to get this from the database?

Here is the code required to show all the "parent" topics:

```<code>Sub ShowParentTopics()
    Dim strSQL, objRS, objConn
    objConn.Open "connection string here"
    strSQL = "Select * From Topics Where parent_id=0"
    Set objRS = objConn.Execute(strSQL)
    Do Until objRS.EOF
        Response.Write("Title: " & objRS("Title") & "<br />")
        Response.Write("<a href=""?topic=" & objRS("ID") & """>Expand</a><hr />")
        objRS.MoveNext
    Loop
    objRS.Close
    Set objRS = Nothing
    objConn.Close
    Set objConn = Nothing
End Sub
</code>```

And to show specific topic with all its replies you need recursive method, here is one that should work:

```<code>Sub ShowOneTopic(nTopicID)
    '//validation might be here.... make sure topic ID is numeric!//'
    Call RecursiveShowTopic nTopicID, 0
End Sub

Sub RecursiveShowTopic(nTopicID, nLevel)
    Dim strSQL, objRS, objConn
    Dim x, nChildID
    objConn.Open "connection string here"
    strSQL = "Select * From Topics Where ID=" & nTopicID
    Set objRS = objConn.Execute(strSQL)
    If Not(objRS.EOF) Then
        For x=1 To nLevel
            Response.Write("    ")
        Next
        If nLevel<1 Then
            Response.Write("Parent ")
        Else
            Response.Write("Child topic level " & nLevel & " ")
        End If
        Response.Write("Title: " & objRS("Title") & "<br />")
    End If
    objRS.Close

    nChildID = 0
    strSQL = "Select ID From Topics Where parent_id=" & nTopicID
    Set objRS = objConn.Execute(strSQL)
    If Not(objRS.EOF) Then
        nChildID = CLng(objRS("ID"))
    End If
    objRS.Close
    Set objRS = Nothing
    objConn.Close
    Set objConn = Nothing

    If nChildID>0 Then
        Call RecursiveShowTopic nChildID, nLevel + 1
    End If
End Sub
</code>```

Call ShowOneTopic with the ID from querystring that will be present when clicking "expand" link on some parent topic.

Of course you'll have to change the connection string, field names and the formatting but this should at least give you something to work with. :)

Body:
I guess you ask for help with the code required to get this from the database?

Here is the code required to show all the "parent" topics:

Sub ShowParentTopics()
    Dim strSQL, objRS, objConn
    objConn.Open "connection string here"
    strSQL = "Select * From Topics Where parent_id=0"
    Set objRS = objConn.Execute(strSQL)
    Do Until objRS.EOF
        Response.Write("Title: " & objRS("Title") & "<br />")
        Response.Write("<a href=""?topic=" & objRS("ID") & """>Expand</a><hr />")
        objRS.MoveNext
    Loop
    objRS.Close
    Set objRS = Nothing
    objConn.Close
    Set objConn = Nothing
End Sub

And to show specific topic with all its replies you need recursive method, here is one that should work:

Sub ShowOneTopic(nTopicID)
    '//validation might be here.... make sure topic ID is numeric!//'
    Call RecursiveShowTopic nTopicID, 0
End Sub

Sub RecursiveShowTopic(nTopicID, nLevel)
    Dim strSQL, objRS, objConn
    Dim x, nChildID
    objConn.Open "connection string here"
    strSQL = "Select * From Topics Where ID=" & nTopicID
    Set objRS = objConn.Execute(strSQL)
    If Not(objRS.EOF) Then
        For x=1 To nLevel
            Response.Write("&nbsp;&nbsp;&nbsp;&nbsp;")
        Next
        If nLevel<1 Then
            Response.Write("Parent ")
        Else
            Response.Write("Child topic level " & nLevel & " ")
        End If
        Response.Write("Title: " & objRS("Title") & "<br />")
    End If
    objRS.Close

    nChildID = 0
    strSQL = "Select ID From Topics Where parent_id=" & nTopicID
    Set objRS = objConn.Execute(strSQL)
    If Not(objRS.EOF) Then
        nChildID = CLng(objRS("ID"))
    End If
    objRS.Close
    Set objRS = Nothing
    objConn.Close
    Set objConn = Nothing

    If nChildID>0 Then
        Call RecursiveShowTopic nChildID, nLevel + 1
    End If
End Sub

Call ShowOneTopic with the ID from querystring that will be present when clicking "expand" link on some parent topic.

Of course you'll have to change the connection string, field names and the formatting but this should at least give you something to work with. :)