问:
Prediction using random-forest model in python
I have this three column dataset formatted as in the following

```<code>t_stamp,Xval,Ytval
0.000543,0,10
0.000575,0,10
0.041324,1,10
0.041331,2,10
0.041336,3,10
0.04134,4,10
0.041345,5,10
0.04135,6,10
0.041354,7,10
</code>```

How can we predict the current value of Y (the true value) using the last 5 data points of Xval using random forest classifier model of sklearn in Python? Meaning taking [0,0,1,2,3] of Xval column as an input - i want to predict the 5th row value of Ytval. Using a simple rolling OLS regression model, we can do it as in the following but I wanted to do it using random forest model.

```<code>import pandas as pd

df = pd.read_csv('data_pred.csv')
model = pd.stats.ols.MovingOLS(y=df.Ytval, x=df[['Xval']],
                               window_type='rolling', window=5, intercept=True)
</code>```

答:
You can realize the rolling input data on your own by reforming your data so that each of the last 5 values of X becomes it's own feature:

```<code>import pandas as pd
from io import StringIO
from sklearn.ensemble import RandomForestRegressor

data = StringIO("""t_stamp,Xval,Ytval
0.000543,0,10
0.000575,0,10
0.041324,1,10
0.041331,2,10
0.041336,3,10
0.04134,4,10
0.041345,5,10
0.04135,6,10
0.041354,7,10""")

df = pd.read_csv(data)

for i in range(1,6):
    df['Xval_t'+str(i)] = df['Xval'].shift(i)
</code>```

Which yields df:

```<code>t_stamp    Xval Ytval   Xval_t1 Xval_t2 Xval_t3 Xval_t4 Xval_t5
0.000543    0   10      NaN     NaN     NaN     NaN     NaN
0.000575    0   10      0.0     NaN     NaN     NaN     NaN
0.041324    1   10      0.0     0.0     NaN     NaN     NaN
0.041331    2   10      1.0     0.0     0.0     NaN     NaN
0.041336    3   10      2.0     1.0     0.0     0.0     NaN
0.041340    4   10      3.0     2.0     1.0     0.0     0.0
0.041345    5   10      4.0     3.0     2.0     1.0     0.0
0.041350    6   10      5.0     4.0     3.0     2.0     1.0
0.041354    7   10      6.0     5.0     4.0     3.0     2.0
</code>```

Of course, you need to decide on how to handle the NaNs. I just drop them for demonstration purposes.

```<code>df.dropna(inplace=True)

X = df[['Xval', 'Xval_t1', 'Xval_t2', 'Xval_t3', 'Xval_t4', 'Xval_t5']].values
y = df['Ytval'].values

reg = RandomForestRegressor()
reg.fit(X,y)
print(reg.predict(X))
</code>```

Result:

```<code>[ 10.  10.  10.  10.]
</code>```

Body:
I have this three column dataset formatted as in the following

t_stamp,Xval,Ytval
0.000543,0,10
0.000575,0,10
0.041324,1,10
0.041331,2,10
0.041336,3,10
0.04134,4,10
0.041345,5,10
0.04135,6,10
0.041354,7,10

How can we predict the current value of Y (the true value) using the last 5 data points of Xval using random forest classifier model of sklearn in Python? Meaning taking [0,0,1,2,3] of Xval column as an input - i want to predict the 5th row value of Ytval. Using a simple rolling OLS regression model, we can do it as in the following but I wanted to do it using random forest model.

import pandas as pd

df = pd.read_csv('data_pred.csv')
model = pd.stats.ols.MovingOLS(y=df.Ytval, x=df[['Xval']],
                               window_type='rolling', window=5, intercept=True)

Body:
You can realize the rolling input data on your own by reforming your data so that each of the last 5 values of X becomes it's own feature:

import pandas as pd
from io import StringIO
from sklearn.ensemble import RandomForestRegressor

data = StringIO("""t_stamp,Xval,Ytval
0.000543,0,10
0.000575,0,10
0.041324,1,10
0.041331,2,10
0.041336,3,10
0.04134,4,10
0.041345,5,10
0.04135,6,10
0.041354,7,10""")

df = pd.read_csv(data)

for i in range(1,6):
    df['Xval_t'+str(i)] = df['Xval'].shift(i)

Which yields df:

t_stamp    Xval Ytval   Xval_t1 Xval_t2 Xval_t3 Xval_t4 Xval_t5
0.000543    0   10      NaN     NaN     NaN     NaN     NaN
0.000575    0   10      0.0     NaN     NaN     NaN     NaN
0.041324    1   10      0.0     0.0     NaN     NaN     NaN
0.041331    2   10      1.0     0.0     0.0     NaN     NaN
0.041336    3   10      2.0     1.0     0.0     0.0     NaN
0.041340    4   10      3.0     2.0     1.0     0.0     0.0
0.041345    5   10      4.0     3.0     2.0     1.0     0.0
0.041350    6   10      5.0     4.0     3.0     2.0     1.0
0.041354    7   10      6.0     5.0     4.0     3.0     2.0

Of course, you need to decide on how to handle the NaNs. I just drop them for demonstration purposes.

df.dropna(inplace=True)

X = df[['Xval', 'Xval_t1', 'Xval_t2', 'Xval_t3', 'Xval_t4', 'Xval_t5']].values
y = df['Ytval'].values

reg = RandomForestRegressor()
reg.fit(X,y)
print(reg.predict(X))

Result:

[ 10.  10.  10.  10.]


来源: stackexchange

问:
Getting error in sqlite like query in ionic1
I am using sqlite select query to retrieve the name from a list in which I have used the following select query with like but it gives me an error as NaN can anyone tell me what's wrong in this query.

```<code>var query = 'SELECT DISTINCT * FROM ' + tblName + ' WHERE name LIKE ' % '' + name + '' % ' ORDER BY name COLLATE NOCASE ASC';
</code>```

Error:

getAllSearchQuery:  SELECT DISTINCT * FROM phonebookNaNViNaN

答:
I suppose the problem is with quotes absence. Try to use the combination of ' and " if it's possible in the programming language you use, something like this would probably work:

```<code>var query = 'SELECT DISTINCT * FROM ' + tblName + ' WHERE name LIKE "%' + name + '%" ORDER BY name COLLATE NOCASE ASC';
</code>```

or reverse:

```<code>var query = 'SELECT DISTINCT * FROM ' + tblName + ' WHERE name LIKE '%" + name + "%' ORDER BY name COLLATE NOCASE ASC';
</code>```

The point in combination of quotes is that this allows to include one quoted part of code into another.

ContentLicense: CC BY-SA 3.0

Body:
I am using sqlite select query to retrieve the name from a list in which I have used the following select query with like but it gives me an error as NaN can anyone tell me what's wrong in this query.

var query = 'SELECT DISTINCT * FROM ' + tblName + ' WHERE name LIKE ' % '' + name + '' % ' ORDER BY name COLLATE NOCASE ASC';

Error:

getAllSearchQuery:  SELECT DISTINCT * FROM phonebookNaNViNaN

Body:
I suppose the problem is with quotes absence. Try to use the combination of ' and " if it's possible in the programming language you use, something like this would probably work:

var query = 'SELECT DISTINCT * FROM ' + tblName + ' WHERE name LIKE "%' + name + '%" ORDER BY name COLLATE NOCASE ASC';

or reverse:

var query = 'SELECT DISTINCT * FROM ' + tblName + ' WHERE name LIKE '%" + name + "%' ORDER BY name COLLATE NOCASE ASC';

The point in combination of quotes is that this allows to include one quoted part of code into another.


问:
php - regex exclude word between quotes
I want to match all words with \w and excluding some specific word and numbers.
but I want to exclude also words between double and single quotes with something like this (?!"\w+") but seems doesn't work.

How can I do? Here's what am using

```<code>/(?!return|if|floor|else|elseif|NULL|null|pow|function|\d+)\b(\w+)/
</code>```

答:
You can use (*SKIP)(*F) predicated in PCRE to match and skip certain substrings like this:

```<code>/(['"])\w+\1(*SKIP)(*F)|\b(?!return|elseif|else|if|floor|NULL|pow|function|\d+)\w+/i
</code>```

RegEx Demo

(['"]) matches single or double quote and captures it in group #1

\w+ matches a single word

\1 backrefrence to group #1 to ensure we have same closing quote as in group #1

(*SKIP)(*F) will skip this match

Title: php - regex exclude word between quotes

Body:
I want to match all words with \w and excluding some specific word and numbers.
but I want to exclude also words between double and single quotes with something like this (?!"\w+") but seems doesn't work.

How can I do? Here's what am using

/(?!return|if|floor|else|elseif|NULL|null|pow|function|\d+)\b(\w+)/

Body:
You can use (*SKIP)(*F) predicated in PCRE to match and skip certain substrings like this:

/(['"])\w+\1(*SKIP)(*F)|\b(?!return|elseif|else|if|floor|NULL|pow|function|\d+)\w+/i

RegEx Demo

(['"]) matches single or double quote and captures it in group #1

\w+ matches a single word

\1 backrefrence to group #1 to ensure we have same closing quote as in group #1

(*SKIP)(*F) will skip this match


问:
Establishing database Connection in php where mysql is in program files not in xampp
When I am installing XAMPP I have not installed MySQL where I have already using this database so I have not installed using xampp but in my PHP code when I am establishing connection I wrote

```<code>$conn = mysqli_connect($servername, $username, $password, $dbname);
</code>```

At $servername, everyone is keeping localhost and explaining PHPMyAdmin examples where MySQL is installed in xampp

In my case MySQL is at c:/programfiles/MySQL what I have to give at my $servername

Please help me, I am new to programming

答:
localhost isn't the name of your MySQL server's install directory. It's a reference to your local machine aka 127.0.0.1. Your server name is still localhost.

The only time you'll change this is if you host the database on a different machine.

Body:
When I am installing XAMPP I have not installed MySQL where I have already using this database so I have not installed using xampp but in my PHP code when I am establishing connection I wrote

$conn = mysqli_connect($servername, $username, $password, $dbname);

At $servername, everyone is keeping localhost and explaining PHPMyAdmin examples where MySQL is installed in xampp

In my case MySQL is at c:/programfiles/MySQL what I have to give at my $servername

Please help me, I am new to programming


问:
SDWebImage Library getting error with swift 3 Xcode 8.0
My Project was Developed with Xcode 7, Yesterday I have updated it with Xcode 8 and convert swift coding with latest swift version swift 3.0. Now it gives me error on some place all most I have solved all but not getting ID for ambiguous use of sd_setImage(with: ,placeholderImage: ,completed) line. can any one help me to solve this? I am using SDWebimage Library to load image in my application.

Thanks

Already checked this link but not getting what to do.
Ambiguous use of 'sd_setImage(with:placeholderImage:completed:)' with Swift 3

答:
Hey i think this will resolve your problem

```<code>YOURIMAGEVIEW.sd_setImage(with: URL(string: IMAGEURL),
placeholderImage: UIImage(named:"PLACEHOLDER"), options: [], completed: {
(image, error, cache, url) in
   DispatchQueue.main.async {
      YOURIMAGEVIEW.image = image
   }
})
</code>```

from that https://stackoverflow.com/a/39024894/4720374

Body:
Hey i think this will resolve your problem

YOURIMAGEVIEW.sd_setImage(with: URL(string: IMAGEURL),
placeholderImage: UIImage(named:"PLACEHOLDER"), options: [], completed: {
(image, error, cache, url) in
   DispatchQueue.main.async {
      YOURIMAGEVIEW.image = image
   }
})

from that https://stackoverflow.com/a/39024894/4720374


问:
ASP.NET: Can GridView be used to create a hierarchy?
We are using the GridView controls in some pages of our project which we dont want to change drastically, would it be possible to create a hierarchy in a gridview? Can this be achieved by using a GridView inside a Gridview to get the parent - child relation? </p>

答: GridView's are quite static.  We use XSLT if the tables are going to be more complex so we have ultimate control over it.  Otherwise Microsoft provide other ASP.NET controls such as the DataRepeater.</p>

OwnerDisplayName: Anthraxer

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Kezzer


问:
CSS/Jquery to show hide submenu
still trying to figure out jQuery and I need some help with a sidebar list.

I am editing this after trying some stuff.

I am trying to have the submenu hidden until a specific list item is moused over, then another menu appears to the side of the sidebar and you are able to mouse over those selections.  I am halfway there but when you mouseout it disappears before you can mouseover any of the items.  I will add hoverIntent but I do not think that is the problem as I need that whole hidden block to also be a trigger to show that element.  I tried Steerpikes solution below but it caused the entire main list to disappear after mouse out.

Here is the structure now:

```<code><ul>
<li>Always Showing Element</li>
<li class="trigger">Title that triggers Submenu
<ul>
<li>
Hidden Menu
</li>
</ul>
</li>
</ul>
</code>```

and the script

```<code>$('li.trigger ul').hide();
 $('li.trigger').hover(function() {
$('li.trigger ul').show();
},
function() {
      $('li.trigger ul').hide();
});
</code>```

So how can I keep it showing while my mouse are over the li.trigger ul li elementes?

Thanks for the help with this!

Nevermind... this works now, I just had the positioning off but now it overlaps a bit and with hoverintent adding a little delay there is no problem.

答:
For those who use class instead of using id, this is the code it works for me:</p>

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<div id='menu_box'>
<ul class='menu'>
<li><a href="">Always showing</a></li>
<li><a href="">Always showing Title of Submenu</a>
<ul>
<li><a href="">Hidden until hover over Title </a></li>
</ul>
</li>
</ul>
</div>
<script>
$('#menu_box ul li ul').hide();
$('#menu_box ul li').hover(function() {
        $(this).find('ul').show();
    },
    function() {
      $(this).find('ul').hide();
});
</script>
</code>```

Title: CSS/Jquery to show hide submenu

Body:
still trying to figure out jQuery and I need some help with a sidebar list.

I am editing this after trying some stuff.

I am trying to have the submenu hidden until a specific list item is moused over, then another menu appears to the side of the sidebar and you are able to mouse over those selections.  I am halfway there but when you mouseout it disappears before you can mouseover any of the items.  I will add hoverIntent but I do not think that is the problem as I need that whole hidden block to also be a trigger to show that element.  I tried Steerpikes solution below but it caused the entire main list to disappear after mouse out.

Here is the structure now:

Always Showing Element

Title that triggers Submenu

Hidden Menu

and the script

$('li.trigger ul').hide();
 $('li.trigger').hover(function() {
$('li.trigger ul').show();
},
function() {
      $('li.trigger ul').hide();
});

So how can I keep it showing while my mouse are over the li.trigger ul li elementes?

Thanks for the help with this!

Nevermind... this works now, I just had the positioning off but now it overlaps a bit and with hoverintent adding a little delay there is no problem.

Body:
For those who use class instead of using id, this is the code it works for me:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<div id='menu_box'>
<ul class='menu'>
<li><a href="">Always showing</a></li>
<li><a href="">Always showing Title of Submenu</a>
<ul>
<li><a href="">Hidden until hover over Title </a></li>
</ul>
</li>
</ul>
</div>
<script>
$('#menu_box ul li ul').hide();
$('#menu_box ul li').hover(function() {
        $(this).find('ul').show();
    },
    function() {
      $(this).find('ul').hide();
});
</script>


问:
How to upload .sql type of files in laravel?
View code:

```<code><input type="file" name="queryfile" id="queryfile" required>
</code>```

Here I am trying to upload the file with .sql extension.

Controller code:

```<code> public function debinsert1(Request $request)
  {

           $validator = Validator::make(Input::all(),
    array(
         'devicemodel' => 'exists:addProduct,productId',

        'debfile'                => 'mimes:deb',
         'basefile'                  => 'mimes:deb',
         'versions' => 'unique:MainHaghway',
          **'queryfile'                  => 'mimes:sql',**
    ));

if ($validator->fails()) {
    return redirect()->back()
        ->withErrors($validator)
        ->withInput();
}
else{
            $temp = new debModel;
 if(Input::hasFile('queryfile')){

            $file=$request->file('queryfile');
            $file->move(public_path().'/downloads',$file-
            >getClientOriginalName());

            $temp->queryfile=$file->getClientOriginalName();

            }
            $temp->save();
</code>```

In this controller code, I am trying to validate with the sql extension and if it succeeds need to insert into db. Validations for other files were working here but, .sql file is not passing with the validation.

Same view code(ie.,mentioned above):

```<code>@if (count($errors) > 0)
     <div class = "alert alert-danger">
        <ul>
           @foreach ($errors->all() as $error)
              <li>{{ $error }}</li>
           @endforeach
        </ul>
     </div>
  @endif
</code>```

Here ,I am throwing the errors incase of failing validations.

答:
This will not validate the sql file as laravel MIME type check here but .sql file don't have MIME type that why its not working but you can do this with manual check by use of php function pathinfo().

Just like this

```<code>if(pathinfo($request->queryfile->getClientOriginalName(), PATHINFO_EXTENSION)!=='sql'){
    echo 'invalid sql file';
}
</code>```

I thing it will help you.

Body:
View code:

<input type="file" name="queryfile" id="queryfile" required>

Here I am trying to upload the file with .sql extension.

Controller code:

 public function debinsert1(Request $request)
  {

           $validator = Validator::make(Input::all(),
    array(
         'devicemodel' => 'exists:addProduct,productId',

        'debfile'                => 'mimes:deb',
         'basefile'                  => 'mimes:deb',
         'versions' => 'unique:MainHaghway',
          **'queryfile'                  => 'mimes:sql',**
    ));

if ($validator->fails()) {
    return redirect()->back()
        ->withErrors($validator)
        ->withInput();
}
else{
            $temp = new debModel;
 if(Input::hasFile('queryfile')){

            $file=$request->file('queryfile');
            $file->move(public_path().'/downloads',$file-
            >getClientOriginalName());

            $temp->queryfile=$file->getClientOriginalName();

            }
            $temp->save();

In this controller code, I am trying to validate with the sql extension and if it succeeds need to insert into db. Validations for other files were working here but, .sql file is not passing with the validation.

Same view code(ie.,mentioned above):

@if (count($errors) > 0)

           @foreach ($errors->all() as $error)

{{ $error }}

           @endforeach

  @endif

Here ,I am throwing the errors incase of failing validations.

Body:
This will not validate the sql file as laravel MIME type check here but .sql file don't have MIME type that why its not working but you can do this with manual check by use of php function pathinfo().

Just like this

if(pathinfo($request->queryfile->getClientOriginalName(), PATHINFO_EXTENSION)!=='sql'){
    echo 'invalid sql file';
}

I thing it will help you.


问:
Reverse a C-style string
Write code to reverse a C-style string. (C-style string means that “abcd” is represented as five characters, including the null character.)
Nothing is printed out. Why?  </p>

```<code>void ReverseString(char *p){
    int length = strlen(p);
    for (int i = 0, j = length; i < j; i++, j--){
        swap(p[i], p[j]);
    }

}

int main()
{
    char a[] = "12345";
    ReverseString(a);
    cout << a;
    system("pause");
    return 0;
}
</code>```

答:
```<code>public class Reverse {
  public static void main(String[] args) {
    StringBuffer s = new StringBuffer("Xmen Logan");
    s.append('\0');

    System.out.println("C-style string---" + s);

    reverse(s);

  }

  public static void reverse(StringBuffer s) {
  int length = s.length();
  char[] chars = new char[length];

  int j = 0;
  for(int i = length-1; i>=0; i--) {
    chars[j++] = s.charAt(i);

  }

  String reverseString = new String(chars);

  System.out.println("Reverse String ------" + reverseString);

}
}
</code>```

Title: Reverse a C-style string

Body:
Write code to reverse a C-style string. (C-style string means that “abcd” is represented as five characters, including the null character.)
Nothing is printed out. Why?

void ReverseString(char *p){
    int length = strlen(p);
    for (int i = 0, j = length; i < j; i++, j--){
        swap(p[i], p[j]);
    }

}

int main()
{
    char a[] = "12345";
    ReverseString(a);
    cout << a;
    system("pause");
    return 0;
}


问:
What type of View is that slim bar on the right side in Xcode?

Can anyone tell me how is it called, what is its purpose and how to hide it, please?

答: Finally I got that. This is related to test coverage functionality and as you write unit/ui tests the right side with that red part appears. This has nothing to do with the vcs.</p>


问:
How do I catch Exception in SML from another function?
I believe I have some basic misunderstanding about catching exceptions in SML.

I wrote the following code:

```<code>    fun my_g acc p =
    let
    val r =  my_g acc
    in
    case p of
        Wildcard          => acc
      | Variable x        =>    if List.exists (fn y => y = x) acc then raise NoAnswer else x::acc
      | TupleP ps         => List.foldl (fn (p,i) => (my_g i p)) acc  ps
      | ConstructorP(_,p) => r p
      | _                 => acc
    end

(* val check_pat = fn : pattern -> bool *)
 fun check_pat p =
   if my_g []  p <> [] then
            true
else
    true
 handle NoAnswer => false
</code>```

I'm happy to explain the code in gory detail, but basically I'm looking to see if strings are repeated in a list.  If I find a string repeated, I raise an exception.  Notice I'm handling the exception in function check_pat, which calls function my_g.  However, when I run the code with some test methods, I get uncaught exception NoAnswer

Can I catch an exception thrown in one function in another (calling) function?
What am I doing wrong?

Thanks, Dave

Additional details for Andreas and future viewers.  The original hints were to first unfold  the structure and get a list of strings and only then go through and look for duplicates.  I felt that was inefficient and it would be best to look for duplicates as you unfolded.  Unfortunately, my SML knowledge is not good enough to come up with a super clean solution.  Really, I don't care about the return value of my_g.  If it doesn't throw an exception, then there are no duplicates.  As simple as that.  But it seemed the syntax rules were forcing me to check the return value.  Now that you've solved the "handle" issue for me, I might revisit the problem.  I was hoping to just write:

```<code>(my_g [] p
true)
handle NoAnswer => false
</code>```

but that didn't seem to work.  More broadly, although I think my solution is more efficient than first unfolding the entire list just to then look for duplicates, I suspect the idea of using an exception like I did is not good style.  In languages I'm familiar with (C++, C#), an exception means some exceptional or unexpected occurred.  Finding a duplicate string is certainly not exceptional.  Again, I'm sure there is another way to stop at the first duplicate without using exceptions.  I'm just not proficient enough in SML to know it. Thanks!

答:
This is simply a matter of parenthesization: handle binds tighter than if, so you have effectively written

```<code>if ... then ... else (... handle ...)
</code>```

Instead you want

```<code>(if ... then ... else ...) handle ...
</code>```

so you need to put in parentheses.

BTW, I can't make sense of your use of if -- why a conditional when both branches produce the same result? Also, if A then true else B is a verbose way of saying A orelse B.

Edit in reply to edit in the question: If you want to ignore the result of an expression and return something else instead then you can use the semicolon operator:

```<code>(my_g [] p; true)
</code>```

However, in general, using exceptions for non-exceptional control flow is not recommended. There is a cleaner way to write this function:

```<code>fun ids (Variable x)       = [x]
  | ids (Tuple ps)         = List.concat (List.map ids ps)
  | ids (Constructor(_,p)) = ids p
  | ids _                  = []

fun hasDups []      = false
  | hasDups (x::xs) = List.exists (fn y => y = x) xs orelse hasDups xs

fun checkPat p = not (hasDups (ids p))
</code>```

Edit 2: In the normal case (where there are no duplicates), this solution isn't slower than the other. So it's not necessarily worth taking the shortcut. If you insist, though, there are various options that don't require exceptions. For example:

```<code>fun checkPat'(_, NONE)               = NONE
  | checkPat'(Variable x, SOME xs)   = if List.exists (fn y => y = x) xs then NONE else SOME (x::xs)
  | checkPat'(Tuple ps, xso)         = List.foldl checkPat' xso ps
  | checkPat'(Constructor(_,p), xso) = checkPat'(p, xso)
  | checkPat'(_, xso)                = xso

fun checkPat p = isSome (checkPat'(p, SOME []))
</code>```

Or, if you are willing to use a bit of mutable state:

```<code>fun checkPat' xs (Variable x)       = List.exists (fn y => y = x) (!xs) before (xs := x :: !xs)
  | checkPat' xs (Tuple ps)         = List.all (checkPat' xs) ps
  | checkPat' xs (Constructor(_,p)) = checkPat' xs p
  | checkPat' xs _                  = true

fun checkPat p = checkPat' (ref []) p
</code>```

Body:
I believe I have some basic misunderstanding about catching exceptions in SML.

I wrote the following code:

    fun my_g acc p =
    let
    val r =  my_g acc
    in
    case p of
        Wildcard          => acc
      | Variable x        =>    if List.exists (fn y => y = x) acc then raise NoAnswer else x::acc
      | TupleP ps         => List.foldl (fn (p,i) => (my_g i p)) acc  ps
      | ConstructorP(_,p) => r p
      | _                 => acc
    end

(* val check_pat = fn : pattern -> bool *)
 fun check_pat p =
   if my_g []  p <> [] then
            true
else
    true
 handle NoAnswer => false

I'm happy to explain the code in gory detail, but basically I'm looking to see if strings are repeated in a list.  If I find a string repeated, I raise an exception.  Notice I'm handling the exception in function check_pat, which calls function my_g.  However, when I run the code with some test methods, I get uncaught exception NoAnswer

Can I catch an exception thrown in one function in another (calling) function?
What am I doing wrong?

Thanks, Dave

Additional details for Andreas and future viewers.  The original hints were to first unfold  the structure and get a list of strings and only then go through and look for duplicates.  I felt that was inefficient and it would be best to look for duplicates as you unfolded.  Unfortunately, my SML knowledge is not good enough to come up with a super clean solution.  Really, I don't care about the return value of my_g.  If it doesn't throw an exception, then there are no duplicates.  As simple as that.  But it seemed the syntax rules were forcing me to check the return value.  Now that you've solved the "handle" issue for me, I might revisit the problem.  I was hoping to just write:

(my_g [] p
true)
handle NoAnswer => false

but that didn't seem to work.  More broadly, although I think my solution is more efficient than first unfolding the entire list just to then look for duplicates, I suspect the idea of using an exception like I did is not good style.  In languages I'm familiar with (C++, C#), an exception means some exceptional or unexpected occurred.  Finding a duplicate string is certainly not exceptional.  Again, I'm sure there is another way to stop at the first duplicate without using exceptions.  I'm just not proficient enough in SML to know it. Thanks!

Body:
This is simply a matter of parenthesization: handle binds tighter than if, so you have effectively written

if ... then ... else (... handle ...)

Instead you want

(if ... then ... else ...) handle ...

so you need to put in parentheses.

BTW, I can't make sense of your use of if -- why a conditional when both branches produce the same result? Also, if A then true else B is a verbose way of saying A orelse B.

Edit in reply to edit in the question: If you want to ignore the result of an expression and return something else instead then you can use the semicolon operator:

(my_g [] p; true)

However, in general, using exceptions for non-exceptional control flow is not recommended. There is a cleaner way to write this function:

fun ids (Variable x)       = [x]
  | ids (Tuple ps)         = List.concat (List.map ids ps)
  | ids (Constructor(_,p)) = ids p
  | ids _                  = []

fun hasDups []      = false
  | hasDups (x::xs) = List.exists (fn y => y = x) xs orelse hasDups xs

fun checkPat p = not (hasDups (ids p))

Edit 2: In the normal case (where there are no duplicates), this solution isn't slower than the other. So it's not necessarily worth taking the shortcut. If you insist, though, there are various options that don't require exceptions. For example:

fun checkPat'(_, NONE)               = NONE
  | checkPat'(Variable x, SOME xs)   = if List.exists (fn y => y = x) xs then NONE else SOME (x::xs)
  | checkPat'(Tuple ps, xso)         = List.foldl checkPat' xso ps
  | checkPat'(Constructor(_,p), xso) = checkPat'(p, xso)
  | checkPat'(_, xso)                = xso

fun checkPat p = isSome (checkPat'(p, SOME []))

Or, if you are willing to use a bit of mutable state:

fun checkPat' xs (Variable x)       = List.exists (fn y => y = x) (!xs) before (xs := x :: !xs)
  | checkPat' xs (Tuple ps)         = List.all (checkPat' xs) ps
  | checkPat' xs (Constructor(_,p)) = checkPat' xs p
  | checkPat' xs _                  = true

fun checkPat p = checkPat' (ref []) p


问:
Polymer updating javascript array from firebase realtime database
I have a vaadin-grid and I want to show a list of data from firebase database. I know that based from the docs, this structure is ugly and I should create another subtree for this but and just want to make a proof of concept. So here is the code:

```<code>ready() {
    var items = [];
    if (this.locationKey) {
      var territoryRef = firebase.database().ref('Territories').child(this.locationKey);
      var householdRef = firebase.database().ref('Households');
      var contactsRef = firebase.database().ref('Contacts');

      territoryRef.once('value').then((terrSnap) => {
        terrSnap.forEach((terrChildSnap) => {
          var territoryName = terrChildSnap.val().name;
          var territoryKey = terrChildSnap.key;

          householdRef.child(territoryKey).once('value').then((householdSnap) => {
            if (householdSnap.val()) {
              householdSnap.forEach((householdChildSnap) => {
                var household = householdChildSnap.val();
                var householdName = household.name;
                var householdKey = householdChildSnap.key;

                contactsRef.child(householdKey).once('value').then((contactsSnap) => {
                  if (contactsSnap.val()) {
                    contactsSnap.forEach((contactsChildSnap) => {
                      var contacts = contactsChildSnap.val();
                      var contactsName = contacts.name;
                      var contactsKey = contactsChildSnap.key;

                      items.push({ territory: territoryName, name: contactsName, household: householdName, nationality: contacts.nationality, language: contacts.language || "" });

                    })
                  }
                })
              })
            }
          })
        })
        this.items = items;
      }).catch((err) => {
        console.error(err)
      });

    }
  }
</code>```

And I just put the items array in the grid

```<code><vaadin-grid id="grid" aria-label="Contacts Summary" items="[[items]]">
  <vaadin-grid-column width="50px" flex-grow="0">
    <template class="header">#</template>
    <template>[[index]]</template>
  </vaadin-grid-column>...
</code>```

The grid loads fine but it doesn't show the data. I can confirm though that that this.items is populated. Though not being shown in the grid. Please let me know what I'm doing wrong. Thank you

答:
this.items just sets the value, but if you want it to actually notify the dom-repeat about a change (or any kind of polymer element) you must use this.set('items', items). This.set() sends out an event to all polymer elements, such as dom-repeat, that the variable has changed.

I'm not familiar with firebase.database() but if it updates automatically, then you need to use this.push('items', item) instead. The dom-repeat usually only updates if you change the length of the array used to populate the dom-repeat.

If you want to see updates of specific properties within already existing elements, then you need to use this.set() but make sure to remove any references to the original array (this.items), before replacing the changed element. I usually do it with var items = JSON.parse(JSON.stringify(this.items)); instead of just var items = this.items. Otherwise, Polymer will make a dirty check against the new updated array and find no values has updated (because items is a reference to this.items), and therefor not update the DOM.

Also, ready() should be ready: function()

Body:
I have a vaadin-grid and I want to show a list of data from firebase database. I know that based from the docs, this structure is ugly and I should create another subtree for this but and just want to make a proof of concept. So here is the code:

ready() {
    var items = [];
    if (this.locationKey) {
      var territoryRef = firebase.database().ref('Territories').child(this.locationKey);
      var householdRef = firebase.database().ref('Households');
      var contactsRef = firebase.database().ref('Contacts');

      territoryRef.once('value').then((terrSnap) => {
        terrSnap.forEach((terrChildSnap) => {
          var territoryName = terrChildSnap.val().name;
          var territoryKey = terrChildSnap.key;

          householdRef.child(territoryKey).once('value').then((householdSnap) => {
            if (householdSnap.val()) {
              householdSnap.forEach((householdChildSnap) => {
                var household = householdChildSnap.val();
                var householdName = household.name;
                var householdKey = householdChildSnap.key;

                contactsRef.child(householdKey).once('value').then((contactsSnap) => {
                  if (contactsSnap.val()) {
                    contactsSnap.forEach((contactsChildSnap) => {
                      var contacts = contactsChildSnap.val();
                      var contactsName = contacts.name;
                      var contactsKey = contactsChildSnap.key;

                      items.push({ territory: territoryName, name: contactsName, household: householdName, nationality: contacts.nationality, language: contacts.language || "" });

                    })
                  }
                })
              })
            }
          })
        })
        this.items = items;
      }).catch((err) => {
        console.error(err)
      });

    }
  }

And I just put the items array in the grid

<vaadin-grid id="grid" aria-label="Contacts Summary" items="[[items]]">
  <vaadin-grid-column width="50px" flex-grow="0">
    <template class="header">#</template>
    <template>[[index]]</template>
  </vaadin-grid-column>...

The grid loads fine but it doesn't show the data. I can confirm though that that this.items is populated. Though not being shown in the grid. Please let me know what I'm doing wrong. Thank you


问:
The "GenerateJavaStubs" task failed unexpectedly
I have created one new project in Visual studio and only che in .xml file (put two frame layouts) and when i debug the code i have one error, please told me the solution

```<code>Error   1   The "GenerateJavaStubs" task failed unexpectedly.
System.InvalidOperationException: Sequence contains no elements
at System.Linq.Enumerable.Max(IEnumerable`1 source)
at Xamarin.Android.Tools.TypeNameMapGenerator.WriteBinaryMapping(Stream o, Dictionary`2 mapping)
at Xamarin.Android.Tools.TypeNameMapGenerator.WriteJavaToManaged(Stream output)
at Xamarin.Android.Tasks.GenerateJavaStubs.UpdateWhenChanged(String path, Action`1 generator)
at Xamarin.Android.Tasks.GenerateJavaStubs.WriteTypeMappings(List`1 types)
at Xamarin.Android.Tasks.GenerateJavaStubs.Run()
at Xamarin.Android.Tasks.GenerateJavaStubs.Execute()
at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
at Microsoft.Build.BackEnd.TaskBuilder.<ExecuteInstantiatedTask>d__20.MoveNext()    TMS_TabletView.Droid
</code>```

答:
I had this issue because for some reason my Android Class library got changed into an Android Application type - so VS was looking for Application class in the project.

Solution was to create a blank android class library, and compare project files.
I removed any xml tags from the broken project that were "application" specific.
like [<]AndroidApplication>true[<]/AndroidApplication>

Body:
I have created one new project in Visual studio and only che in .xml file (put two frame layouts) and when i debug the code i have one error, please told me the solution

Error   1   The "GenerateJavaStubs" task failed unexpectedly.
System.InvalidOperationException: Sequence contains no elements
at System.Linq.Enumerable.Max(IEnumerable`1 source)
at Xamarin.Android.Tools.TypeNameMapGenerator.WriteBinaryMapping(Stream o, Dictionary`2 mapping)
at Xamarin.Android.Tools.TypeNameMapGenerator.WriteJavaToManaged(Stream output)
at Xamarin.Android.Tasks.GenerateJavaStubs.UpdateWhenChanged(String path, Action`1 generator)
at Xamarin.Android.Tasks.GenerateJavaStubs.WriteTypeMappings(List`1 types)
at Xamarin.Android.Tasks.GenerateJavaStubs.Run()
at Xamarin.Android.Tasks.GenerateJavaStubs.Execute()
at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
at Microsoft.Build.BackEnd.TaskBuilder.<ExecuteInstantiatedTask>d__20.MoveNext()    TMS_TabletView.Droid


问:
Update react state after a certain interval
```<code>constructor(){
    super();
    this.state={
        data : [1,2,3,4,1,2,3,4,1,3,1,4,12,2,3,2]
    };

}
componentDidMount(){setInterval(this.updateCanvas(),5000);}

updateCanvas() {
    console.log(this.props.newData);
    let data = this.state.data.slice();
    let length = data.length;
    console.log(length);
    data.push(20);
    this.setState({data:data},()=>{console.log(this.state.data);});
}
</code>```

I am trying to push a new value to the state every 5s, but the state changes immediately. How can I achieve the effect I want?

答:
The state changes immediate because you are invoking the callback method you pass to setInterval immediately on this line by adding parenthesis to it:

```<code>setInterval(this.updateCanvas(),5000);
//---------------------------^
// Adding these to function will invoke it
</code>```

The solution is to pass the reference to the function without the parenthesis (and they're not invoking it immediately)

```<code>setInterval(this.updateCanvas,5000);
</code>```

Body:
constructor(){
    super();
    this.state={
        data : [1,2,3,4,1,2,3,4,1,3,1,4,12,2,3,2]
    };

}
componentDidMount(){setInterval(this.updateCanvas(),5000);}

updateCanvas() {
    console.log(this.props.newData);
    let data = this.state.data.slice();
    let length = data.length;
    console.log(length);
    data.push(20);
    this.setState({data:data},()=>{console.log(this.state.data);});
}

I am trying to push a new value to the state every 5s, but the state changes immediately. How can I achieve the effect I want?

Body:
The state changes immediate because you are invoking the callback method you pass to setInterval immediately on this line by adding parenthesis to it:

setInterval(this.updateCanvas(),5000);
//---------------------------^
// Adding these to function will invoke it

The solution is to pass the reference to the function without the parenthesis (and they're not invoking it immediately)

setInterval(this.updateCanvas,5000);


答:
Remove that bracket from this.updateCanvas().
Ie
setInterval(this.updateCanvas, 5000);}

The first will execute the function immediately whilst the second passes it in as a function for set interval

Title: Update react state after a certain interval


问:
post data on WebAPI after save in php Using ajax
I have created the code for save data in my custom table using Ajax which is working fine.

After that I want to post these data on the asp.Net API using js/jQuery. How I can post same data on the aps.net.

Here is my HTML form and JS code:

```<code><div id="inline1" class="audit-form" style="display: none;">
  <form class="infusion-form" id="infusion-form">
  <h3 style="color: #002046;">Sign Up For a Free Capability Audit </h3>
  <div class="dis_block clearfix">
    <div class="form-group">
      <label>First Name *</label>
      <input required class="form-control" id="inf_field_FirstName" name="inf_field_FirstName" type="text" />
    </div>
    <div class="form-group">
      <label>Last Name *</label>
      <input required id="inf_field_LastName" name="inf_field_LastName" type="text" class="form-control" />
    </div>
    <div class="form-group">
      <label>Email *</label>
      <input required id="inf_field_Email" name="inf_field_Email" type="email" class="form-control" />
    </div>
    <div class="form-group">
      <label>Confirm Email *</label>
      <input required id="inf_field_Phone1" name="inf_field_Phone1" type="email" class="form-control" />
    </div>
    <div class="form-group" style="text-align: center;">
      <input type="hidden" name="action" value ="save_procurement_data" />
      <input type="submit" id="frm_basic_info" class="btn custom-btn" value="NEXT" />

    </div>
  </div>
  </form>
  </div>
</code>```

JS Code is here

```<code><script type = "text/javascript">
jQuery(document).ready(function() {

    jQuery(document).on('click', '#frm_basic_info', function(e){
    jQuery("#infusion-form").validate({
      rules: {
        inf_field_FirstName: "required",
        inf_field_LastName: "required",
        inf_field_Email: "required",
        inf_field_Phone1: {
          equalTo: inf_field_Email
        }
      },
      messages: {
        inf_field_FirstName: "Please enter your firstname",
        inf_field_LastName: "Please enter your lastname",
        inf_field_Email: "Please enter your email",
        inf_field_Phone1: "Please enter your confirm email correct",
      },
        submitHandler: function (form) {

        e.preventDefault();
        var frmd = new FormData();

        var save_data = jQuery('form').serializeArray();
        jQuery.each(save_data,function(key,input){
          frmd.append(input.name,input.value);
        });
         jQuery.ajax({
           url: '<?php echo admin_url( 'admin-ajax.php' ); ?>',
           data: frmd,
           contentType: false,
           processData: false,
           type: 'POST',
           success: function(data){
            alert(data);
            return false;
           //window.location.href = "<?php echo site_url(); ?>/about-your-organization";
           }
         });
        }
      });
  });

});
</script>
</code>```

In the alert I getting alert data saved success fully.

答:
Simply add one more ajax method after saving in your php Url.

See, in your above ajax success method, check the status then post to Asp.Net Web Api, just like my bellow code,

```<code> success: function(data){
      //Here you can check the data and call your Web Api. For example
      if(data == "data saved success fully")
       {
        //Write an ajax method to post data to Web Api
        $.ajax({
          url: 'YourWebApiUrlHere',
          data: frmd,
          type:'Post',
          success: function (data) {
            //Show an alert message here that data saved in Web Api blah blah
            if(data == "Your response from Web Api goes here")//Edit this message
               alert("Data saved using Web Api");
            else
               alert("Failed to save data using Web Api");
           }
          error: function(xhr, status, error) {
            alert(xhr.responseText); //This is the exception if any issue with server
           }
          })
        }
       else
          alert("Your data haven't saved in Php Url. Check with server");
       return false;
       }
</code>```

Hope it helps!

Body:
I have created the code for save data in my custom table using Ajax which is working fine.

After that I want to post these data on the asp.Net API using js/jQuery. How I can post same data on the aps.net.

Here is my HTML form and JS code:

  <form class="infusion-form" id="infusion-form">

Sign Up For a Free Capability Audit

      First Name *
      <input required class="form-control" id="inf_field_FirstName" name="inf_field_FirstName" type="text" />

      Last Name *
      <input required id="inf_field_LastName" name="inf_field_LastName" type="text" class="form-control" />

      Email *
      <input required id="inf_field_Email" name="inf_field_Email" type="email" class="form-control" />

      Confirm Email *
      <input required id="inf_field_Phone1" name="inf_field_Phone1" type="email" class="form-control" />

      <input type="hidden" name="action" value ="save_procurement_data" />
      <input type="submit" id="frm_basic_info" class="btn custom-btn" value="NEXT" />

  </form>

JS Code is here

In the alert I getting alert data saved success fully.

Body:
Simply add one more ajax method after saving in your php Url.

See, in your above ajax success method, check the status then post to Asp.Net Web Api, just like my bellow code,

 success: function(data){
      //Here you can check the data and call your Web Api. For example
      if(data == "data saved success fully")
       {
        //Write an ajax method to post data to Web Api
        $.ajax({
          url: 'YourWebApiUrlHere',
          data: frmd,
          type:'Post',
          success: function (data) {
            //Show an alert message here that data saved in Web Api blah blah
            if(data == "Your response from Web Api goes here")//Edit this message
               alert("Data saved using Web Api");
            else
               alert("Failed to save data using Web Api");
           }
          error: function(xhr, status, error) {
            alert(xhr.responseText); //This is the exception if any issue with server
           }
          })
        }
       else
          alert("Your data haven't saved in Php Url. Check with server");
       return false;
       }

Hope it helps!


问:
How to navigate up/down using keyboard home keys in Eclipse's suggestions pop up window?
When Eclipse shows a popup for code completion, how do you change the highlighted option using the keyboard home keys? Currently, if the thing I want is third or fourth on the list of suggestions, I have to use the mouse to select it, or use the arrow keys. Is there a way to use the keyboard home keys/ shortcuts with ctrl/alt to do this?</p>

答:
Arrow keys always work for me. Can you be little more specific as to what perspective, editor, etc?

I get a code completion popup when I press Ctrl + 1 in the Java editor. From then on, I can use the arrow keys to navigate.


问:
how to get the value of the hovered time on input range
my question may have been a bit vague so ill explain it in detail here. im trying to develop a simple video player on a page. im using input range to display the file duration and current time like any standard player. here is my script.

```<code><script>
        var vid, playbtn, seekslider, curtimeText, durtimeText, mutebtn, volumeslider, fullscreenbtn;
        function initializePlayer() {

            //creating global object
            vid = document.getElementById('my_video');
            playbtn = document.getElementById('playpausebtn');
            seekslider = document.getElementById('seekslider');
            curtimeText = document.getElementById('curtimeText');
            durtimeText = document.getElementById('durtimeText');
            mutebtn = document.getElementById('mutebtn');
            volumeslider = document.getElementById('volumeslider');
            fullscreenbtn = document.getElementById('fullscreenbtn');

            //creating event for objects
            playbtn.addEventListener("click", playPause, false);
            seekslider.addEventListener("change", vidSeek, false);
            vid.addEventListener("timeupdate", seektimeupdate, false);
            mutebtn.addEventListener("click", vidmute, false);
            volumeslider.addEventListener("change", setvolume, false);
            fullscreenbtn.addEventListener("click", toggleFullScreen, false);
        }

        window.onload = initializePlayer;

        function playPause() {
            if (vid.paused) {
                vid.play();
                playbtn.innerHTML = "Pause";
            } else {
                vid.pause();
                playbtn.innerHTML = "Play";
            }

        }
        function vidSeek() {
            var seekto = vid.duration * (seekslider.value / 100);
            vid.currentTime = seekto;
        }
        function seektimeupdate() {
            var nt = vid.currentTime * (100 / vid.duration);
            seekslider.value = nt;
            var curmins = Math.floor(vid.currentTime / 60);
            var cursecs = Math.floor(vid.currentTime - curmins * 60);
            var durmins = Math.floor(vid.duration / 60);
            var dursecs = Math.floor(vid.duration - durmins * 60);
            if (cursecs < 10) {
                cursecs = "0" + cursecs;
            }
            if (dursecs < 10) {
                dursecs = "0" + dursecs;
            }
            if (curmins < 10) {
                curmins = "0" + curmins;
            }
            if (durmins < 10) {
                durmins = "0" + durmins;
            }
            curtimeText.innerHTML = curmins + ":" + cursecs;
            durtimeText.innerHTML = durmins + ":" + dursecs;
        }
        function vidmute() {

            if (vid.muted) {
                vid.muted = false;
                mutebtn.innerHTML = "Mute";
            } else {
                vid.muted = true;
                mutebtn.innerHTML = "Unmute";
            }
        }
        function setvolume() {
            vid.volume = volumeslider.value / 100;
        }
        function toggleFullScreen() {
            if (vid.requestFullScreen) {
                vid.requestFullScreen();
            } else if (vid.webkitRequestFullScreen) {
                vid.webkitRequestFullScreen();
            } else if (vid.mozRequestFullScreen) {
                vid.mozRequestFullScreen();
            }
        }
</script>
</code>```

and my HTML code:

```<code><div id="Video_player_box">
    <video id="my_video">
        <source src="Videos/cowhand.mp4" type="video/mp4">
        <!-- Your browser does not support HTML5 video.-->
    </video>
    <div id="Video_controls_bar">
        <button id="playpausebtn">Play</button>
        <span id="curtimeText"></span>
        <input id="seekslider" type="range" min="0" max="100" value="0" step="0.1">
        <span id="durtimeText"></span>
        <button id="mutebtn">Mute</button>
        <input id="volumeslider" type="range" min="0" max="100" value="50" step="1">
        <button id="fullscreenbtn">[  ]</button>
    </div>
</div>
</code>```

now what i want to do is to display the time of wherever the user is pointing at seekslider on a small tooltip. like if the video is 10min long, and the user is point at the middle of the rangebar (seekslider) i want a small tooltip to shows that the user is pointing at i.e 5:01  but i really have no idea on how to code that! i would appreciate any kind of help on how to implement this function.

答:
Hi there i was working on this tooltip of current Time project and i got a script that i made myself that actually works just awesome it is the mixture of every code i have seen for this project

 var video = $('video')[0];
 $('input').mousemove(function(e){
        var progress = $("input");
        var maxduration = video.duration;
        var position = e.pageX - progress.offset().left;
        var tooltip = $("span")[0];
        var percentage = 100 * position / progress.width();
        if (percentage > 100) {
            percentage = 100;
        }
        if (percentage < 0) {
            percentage = 0;
        }
        var min = Math.floor((percentage / 100 * video.duration) / 60);
        var sec = Math.floor((percentage / 100 * video.duration) - min * 60);
        if(min < 10){
            min = "0" + min;
        }
        if(sec < 10){
            sec = "0" + sec;
        }
        $("span").html(min + ":" + sec);
  //You can use this code below to align your tooltip when you have completed styling it
  /*tooltip.style.top = -progress[0].offsetTop+(-10) + "px";
         console.log(progress.offset().top);
         tooltip.style.marginLeft = (e.pageX - 25) + "px";
  //Note: You may have to edit this code according to your styling
*/
});
//Just for testing
var timeDrag = false;
$('input').on('mousedown', function(e) {
        timeDrag = true;
        video.pause();
        updatebar(e.pageX);
 });
   var updatebar = function(x) {
        var progress = $('input');

        //calculate drag position
        //and update video currenttime
        //as well as progress bar
        var maxduration = video.duration;
        var position = x - progress.offset().left;
        var percentage = 100 * position / progress.width();
        if (percentage > 100) {
            percentage = 100;
        }
        if (percentage < 0) {
            percentage = 0;
        }
        video.currentTime = maxduration * percentage / 100;
    };
 ```
<pre class="snippet-code-css lang-css prettyprint-override"><code>input{
  width:400px; /*Just for demonstration that this code does not depend on width of the slider*/
}</code>```

<video src="https://givemesomething.000webhostapp.com/video.mp4" height="280" width="100%" controls></video>
<input type="range" min="0" max="100" value="0">
```

That's All it will work surely work thanks

Body:
my question may have been a bit vague so ill explain it in detail here. im trying to develop a simple video player on a page. im using input range to display the file duration and current time like any standard player. here is my script.

and my HTML code:

    <video id="my_video">
        <source src="Videos/cowhand.mp4" type="video/mp4">

    </video>

        <button id="playpausebtn">Play</button>

        <input id="seekslider" type="range" min="0" max="100" value="0" step="0.1">

        <button id="mutebtn">Mute</button>
        <input id="volumeslider" type="range" min="0" max="100" value="50" step="1">
        <button id="fullscreenbtn">[  ]</button>

now what i want to do is to display the time of wherever the user is pointing at seekslider on a small tooltip. like if the video is 10min long, and the user is point at the middle of the rangebar (seekslider) i want a small tooltip to shows that the user is pointing at i.e 5:01  but i really have no idea on how to code that! i would appreciate any kind of help on how to implement this function.

Body:
Hi there i was working on this tooltip of current Time project and i got a script that i made myself that actually works just awesome it is the mixture of every code i have seen for this project

 var video = $('video')[0];
 $('input').mousemove(function(e){
        var progress = $("input");
        var maxduration = video.duration;
        var position = e.pageX - progress.offset().left;
        var tooltip = $("span")[0];
        var percentage = 100 * position / progress.width();
        if (percentage > 100) {
            percentage = 100;
        }
        if (percentage < 0) {
            percentage = 0;
        }
        var min = Math.floor((percentage / 100 * video.duration) / 60);
        var sec = Math.floor((percentage / 100 * video.duration) - min * 60);
        if(min < 10){
            min = "0" + min;
        }
        if(sec < 10){
            sec = "0" + sec;
        }
        $("span").html(min + ":" + sec);
  //You can use this code below to align your tooltip when you have completed styling it
  /*tooltip.style.top = -progress[0].offsetTop+(-10) + "px";
         console.log(progress.offset().top);
         tooltip.style.marginLeft = (e.pageX - 25) + "px";
  //Note: You may have to edit this code according to your styling
*/
});
//Just for testing
var timeDrag = false;
$('input').on('mousedown', function(e) {
        timeDrag = true;
        video.pause();
        updatebar(e.pageX);
 });
   var updatebar = function(x) {
        var progress = $('input');

        //calculate drag position
        //and update video currenttime
        //as well as progress bar
        var maxduration = video.duration;
        var position = x - progress.offset().left;
        var percentage = 100 * position / progress.width();
        if (percentage > 100) {
            percentage = 100;
        }
        if (percentage < 0) {
            percentage = 0;
        }
        video.currentTime = maxduration * percentage / 100;
    };

input{
  width:400px; /*Just for demonstration that this code does not depend on width of the slider*/
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<video src="https://givemesomething.000webhostapp.com/video.mp4" height="280" width="100%" controls></video>
<input type="range" min="0" max="100" value="0">
<span></span>

That's All it will work surely work thanks


问:
value head is not a member of org.apache.spark.sql.Row
I am executing twitter sample code, while i am getting error for value head is not a member of org.apache.spark.sql.Row, can someone please explain little bit more on this error.</p>

```<code>val tweets = sc.textFile(tweetInput)
    println("------------Sample JSON Tweets-------")
    for (tweet <- tweets.take(5)) {
      println(gson.toJson(jsonParser.parse(tweet)))
    }

    val tweetTable = sqlContext.jsonFile(tweetInput).cache()
    tweetTable.registerTempTable("tweetTable")

    println("------Tweet table Schema---")
    tweetTable.printSchema()

    println("----Sample Tweet Text-----")
    sqlContext.sql("SELECT text FROM tweetTable LIMIT 10").collect().foreach(println)

    println("------Sample Lang, Name, text---")
    sqlContext.sql("SELECT user.lang, user.name, text FROM tweetTable LIMIT 1000").collect().foreach(println)

    println("------Total count by languages Lang, count(*)---")
    sqlContext.sql("SELECT user.lang, COUNT(*) as cnt FROM tweetTable GROUP BY user.lang ORDER BY cnt DESC LIMIT 25").collect.foreach(println)

    println("--- Training the model and persist it")
    val texts = sqlContext.sql("SELECT text from tweetTable").map(_.head.toString)
    // Cache the vectors RDD since it will be used for all the KMeans iterations.
    val vectors = texts.map(Utils.featurize).cache()
</code>```

答:
I think your problem is that the sql method returns a DataSet of Rows. Therefore the _ represents a Row and Row doesn't have a head method (which explains the error message).

To access items in a Row you can do one of the following:

```<code>// get the first element in the Row
val texts = sqlContext.sql("...").map(_.get(0))

// get the first element as an Int
val texts = sqlContext.sql("...").map(_.getInt(0))
</code>```

See here for more info: https://spark.apache.org/docs/2.1.0/api/java/org/apache/spark/sql/Row.html

Body:
I am executing twitter sample code, while i am getting error for value head is not a member of org.apache.spark.sql.Row, can someone please explain little bit more on this error.

val tweets = sc.textFile(tweetInput)
    println("------------Sample JSON Tweets-------")
    for (tweet <- tweets.take(5)) {
      println(gson.toJson(jsonParser.parse(tweet)))
    }

    val tweetTable = sqlContext.jsonFile(tweetInput).cache()
    tweetTable.registerTempTable("tweetTable")

    println("------Tweet table Schema---")
    tweetTable.printSchema()

    println("----Sample Tweet Text-----")
    sqlContext.sql("SELECT text FROM tweetTable LIMIT 10").collect().foreach(println)

    println("------Sample Lang, Name, text---")
    sqlContext.sql("SELECT user.lang, user.name, text FROM tweetTable LIMIT 1000").collect().foreach(println)

    println("------Total count by languages Lang, count(*)---")
    sqlContext.sql("SELECT user.lang, COUNT(*) as cnt FROM tweetTable GROUP BY user.lang ORDER BY cnt DESC LIMIT 25").collect.foreach(println)

    println("--- Training the model and persist it")
    val texts = sqlContext.sql("SELECT text from tweetTable").map(_.head.toString)
    // Cache the vectors RDD since it will be used for all the KMeans iterations.
    val vectors = texts.map(Utils.featurize).cache()

Body:
I think your problem is that the sql method returns a DataSet of Rows. Therefore the _ represents a Row and Row doesn't have a head method (which explains the error message).

To access items in a Row you can do one of the following:

// get the first element in the Row
val texts = sqlContext.sql("...").map(_.get(0))

// get the first element as an Int
val texts = sqlContext.sql("...").map(_.getInt(0))

See here for more info: https://spark.apache.org/docs/2.1.0/api/java/org/apache/spark/sql/Row.html


问:
How to set a function into a variable and call from it?
I wonder if it is possible to do this in C ++?

e.g:

```<code>varFunction = void TestFunction();
RunCode(varFunction);
</code>```

答:
C++ provides several ways to do it.

For example, you can use std::function template: include <functional> and use the following syntax (demo):

```<code>std::function<void()> varFunction(TestFunction);
varFunction();
</code>```

You can also use function pointers (Q&A on the topic).

Body:
I wonder if it is possible to do this in C ++?

e.g:

varFunction = void TestFunction();
RunCode(varFunction);

Body:
C++ provides several ways to do it.

For example, you can use std::function template: include <functional> and use the following syntax (demo):

std::function<void()> varFunction(TestFunction);
varFunction();

You can also use function pointers (Q&A on the topic).


答:
With C++11 and higher, you can use the std::function to store function pointers and function objects.

But storing function pointers was available in C++ from the start. This means you can store the address of a function and call it later.

BTW, lambda expressions are also very useful (and the closure they are denoting could be assigned or passed as std::function-s)

Here is an example showing three different ways to achieve what did you asked for:

```<code>#include <iostream>
#include <functional>

void RunCode(const std::function<void()>& callable) {
    callable();
}

void TestFunction() {
    std::cout << "TestFunction is called..." << std::endl;
}

int main() {
    std::function<void()> varFunction_1 = TestFunction;
    void (*varFunction_2)() = TestFunction;

    RunCode(varFunction_1);
    RunCode(varFunction_2);
    RunCode([]() { std::cout << "TestLambda is called..." << std::endl; });

    return 0;
}
</code>```

But this is just the tip of the iceberg, passing function pointers and function objects as parameters is very common in the algorithms library.

Title: How to set a function into a variable and call from it?

Body:
With C++11 and higher, you can use the std::function to store function pointers and function objects.

But storing function pointers was available in C++ from the start. This means you can store the address of a function and call it later.

BTW, lambda expressions are also very useful (and the closure they are denoting could be assigned or passed as std::function-s)

Here is an example showing three different ways to achieve what did you asked for:

#include <iostream>
#include <functional>

void RunCode(const std::function<void()>& callable) {
    callable();
}

void TestFunction() {
    std::cout << "TestFunction is called..." << std::endl;
}

int main() {
    std::function<void()> varFunction_1 = TestFunction;
    void (*varFunction_2)() = TestFunction;

    RunCode(varFunction_1);
    RunCode(varFunction_2);
    RunCode([]() { std::cout << "TestLambda is called..." << std::endl; });

    return 0;
}

But this is just the tip of the iceberg, passing function pointers and function objects as parameters is very common in the algorithms library.


问:
how to use a project as module in another project in android studio
I've two android projects project:Main and project:Sub. When I am using Project:Main there is a Button, if i click That Button Project:Sub have to be Run in Same App. for that how i've to import project:Sub into project:Main like module, library,...etc any help how to import one project into another project?

答:
You need to Import Project as a Module

From menu File -> New -> Import Project /Import Module. Depending on what you are importing.

Then you need to check the dependency in the Project Structure Settings.


问:
PHP if statment for boolean/tinyint(1) type
What is the best way for boolen statement to know it is true or false?

In MYSQL database after select boolean it is showing tinyint(1) but the issue is when in database the value is 1,

I use if($var == 1) result is false and if($var == "1") is true.

But in my localhost (WAMP Server)

if($var == 1) is true

I am very confused the MYSQL version issue?
By the way I am using laravel framework...

答:
Type cast $var to int when you are assigning $var and then do the comparison. Example below:

```<code>$var = (int) $result['db_field_name'] // $result indicates the database value
if($var == 1) {

}
</code>```

I am sure, this will work on every machine.

Body:
Type cast $var to int when you are assigning $var and then do the comparison. Example below:

$var = (int) $result['db_field_name'] // $result indicates the database value
if($var == 1) {

}

I am sure, this will work on every machine.


问:
RegEx for the

 tags
i am working on the C# WinForm application. In that application, i have snippet like this:

```<code><ul>
<li>abc
<li>bbc
<li>xyz
<li>pqr </li></li></li></li>
</ul>
</code>```

but, i want to get output like..

```<code><ul>
<li>abc</li>
<li>bbc</li>
<li>xyz</li>
<li>pqr</li>
</ul>
</code>```

Is there any method using which this thing can be done?

Can anybody suggest me any RegEx for this problem?

Thanks. Regards.

答:
Its simple without using any fancy regex

Try below, you can implement your own code

```<code>   1. first Remove all </li>'s from the snippet
          line.replace("</li>","")
   2. Read each line starts with <li>
          if (line.startswith("<li">)
   3. and append the </li> at the end
          line+ ="</li>"
   4. combine all the line
           resString += line;
</code>```

Title:
RegEx for the

 tags

Body:
i am working on the C# WinForm application. In that application, i have snippet like this:

abc

bbc

xyz

pqr

but, i want to get output like..

abc

bbc

xyz

pqr

Is there any method using which this thing can be done?

Can anybody suggest me any RegEx for this problem?

Thanks. Regards.

Body:
Its simple without using any fancy regex

Try below, you can implement your own code

   1. first Remove all </li>'s from the snippet
          line.replace("</li>","")
   2. Read each line starts with <li>
          if (line.startswith("<li">)
   3. and append the </li> at the end
          line+ ="</li>"
   4. combine all the line
           resString += line;


问:
How would I normalize dates in a csv file? python
I have a CSV file with a field named  start_date that contains data in a variety of formats.

Some of the formats include e.g., June 23, 1912 or 5/11/1930 (month, day, year). But not all values are valid dates.

I want to add a start_date_description field adjacent to the start_date column to filter invalid date values into. Lastly, normalize all valid date values in start_date to ISO 8601 (i.e., YYYY-MM-DD).

So far I was only able to load the start_date into my file, I am stuck and would appreciate ant help. Please, any solution especially without using a library would be great!

```<code>import csv

date_column = ("start_date")
f = open("test.csv","r")
csv_reader = csv.reader(f)

headers = None
results = []
for row in csv_reader:
    if not headers:
        headers = []
        for i, col in enumerate(row):
           if col in date_column:
            headers.append(i)
    else:
        results.append(([row[i] for i in headers]))

print results
</code>```

答:
One way is to use dateutil module, you can parse data as follows:

```<code>from dateutil import parser
parser.parse('3/16/78')
parser.parse('4-Apr') # this will give current year i.e. 2017
</code>```

Then parsing to your format can be done by

```<code>dt = parser.parse('3/16/78')
dt.strftime('%Y-%m-%d')
</code>```

Suppose you have table in dataframe format, you can now define parsing function and apply to column as follows:

```<code>def parse_date(start_time):
    try:
        return parser.parse(x).strftime('%Y-%m-%d')
    except:
        return ''
df['parse_date'] = df.start_date.map(lambda x: parse_date(x))
</code>```

Body:
I have a CSV file with a field named  start_date that contains data in a variety of formats.

Some of the formats include e.g., June 23, 1912 or 5/11/1930 (month, day, year). But not all values are valid dates.

I want to add a start_date_description field adjacent to the start_date column to filter invalid date values into. Lastly, normalize all valid date values in start_date to ISO 8601 (i.e., YYYY-MM-DD).

So far I was only able to load the start_date into my file, I am stuck and would appreciate ant help. Please, any solution especially without using a library would be great!

import csv

date_column = ("start_date")
f = open("test.csv","r")
csv_reader = csv.reader(f)

headers = None
results = []
for row in csv_reader:
    if not headers:
        headers = []
        for i, col in enumerate(row):
           if col in date_column:
            headers.append(i)
    else:
        results.append(([row[i] for i in headers]))

print results

Body:
One way is to use dateutil module, you can parse data as follows:

from dateutil import parser
parser.parse('3/16/78')
parser.parse('4-Apr') # this will give current year i.e. 2017

Then parsing to your format can be done by

dt = parser.parse('3/16/78')
dt.strftime('%Y-%m-%d')

Suppose you have table in dataframe format, you can now define parsing function and apply to column as follows:

def parse_date(start_time):
    try:
        return parser.parse(x).strftime('%Y-%m-%d')
    except:
        return ''
df['parse_date'] = df.start_date.map(lambda x: parse_date(x))


问:
How to convert JSON array to use in RecyclerView
I have a news API JSON link which I want to convert to string array so that I can use them in recycled view.

I am a new to Java, kindly help me to know the way to do it.

I am trying to use Android Networking Library and GSON for this purpose.

```<code>package in.apptonic.lalit.newsapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.androidnetworking.AndroidNetworking;
import com.androidnetworking.error.ANError;
import com.androidnetworking.interfaces.JSONArrayRequestListener;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import in.apptonic.lalit.newsapplication.model.News;

public class MainActivity extends AppCompatActivity {

    RecyclerView recyclerView;
    RecyclerView.LayoutManager layoutManager;
    RecyclerView.Adapter adapter;
    List<News> newsList = new ArrayList<>();
    private Gson gson;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        GsonBuilder gsonbuilder = new GsonBuilder();
        gsonbuilder.setDateFormat("M/d/yy hh:mm a");
        gson = gsonbuilder.create();

        AndroidNetworking.initialize(getApplicationContext());

        recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new AdapterNews(newsList);
        recyclerView.setAdapter(adapter);
        downloadNews();
    }

    private void downloadNews() {

        AndroidNetworking.get("https://newsapi.org/v1/articles?source=the-next-web&sortBy=latest&apiKey=hidden")
                .build()
                .getAsJSONArray(new JSONArrayRequestListener() {
                    @Override
                    public void onResponse(JSONArray response) {

                        List<News> news = Arrays.asList(gson.fromJson(String.valueOf(response), News[].class));

                        //TODO How to convert JSON values n String so that I can send them in adapter for recycler view
                    }

                    @Override
                    public void onError(ANError anError) {

                    }
                });

    }
}
</code>```

答:
First create a list:

```<code>List<String> list = new ArrayList<String>();
</code>```

Then you can add the string values from the JSONArray to the list like this:

```<code>for (int i = 0; i < response.length(); i++) {
    list.add(response.getJSONObject(i).getString("name"));
}
</code>```

Then pass this list variable to your adapter.

Body:
I have a news API JSON link which I want to convert to string array so that I can use them in recycled view.

I am a new to Java, kindly help me to know the way to do it.

I am trying to use Android Networking Library and GSON for this purpose.

package in.apptonic.lalit.newsapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.androidnetworking.AndroidNetworking;
import com.androidnetworking.error.ANError;
import com.androidnetworking.interfaces.JSONArrayRequestListener;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import in.apptonic.lalit.newsapplication.model.News;

public class MainActivity extends AppCompatActivity {

    RecyclerView recyclerView;
    RecyclerView.LayoutManager layoutManager;
    RecyclerView.Adapter adapter;
    List<News> newsList = new ArrayList<>();
    private Gson gson;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        GsonBuilder gsonbuilder = new GsonBuilder();
        gsonbuilder.setDateFormat("M/d/yy hh:mm a");
        gson = gsonbuilder.create();

        AndroidNetworking.initialize(getApplicationContext());

        recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new AdapterNews(newsList);
        recyclerView.setAdapter(adapter);
        downloadNews();
    }

    private void downloadNews() {

        AndroidNetworking.get("https://newsapi.org/v1/articles?source=the-next-web&sortBy=latest&apiKey=hidden")
                .build()
                .getAsJSONArray(new JSONArrayRequestListener() {
                    @Override
                    public void onResponse(JSONArray response) {

                        List<News> news = Arrays.asList(gson.fromJson(String.valueOf(response), News[].class));

                        //TODO How to convert JSON values n String so that I can send them in adapter for recycler view
                    }

                    @Override
                    public void onError(ANError anError) {

                    }
                });

    }
}

Body:
First create a list:

List<String> list = new ArrayList<String>();

Then you can add the string values from the JSONArray to the list like this:

for (int i = 0; i < response.length(); i++) {
    list.add(response.getJSONObject(i).getString("name"));
}

Then pass this list variable to your adapter.

ContentLicense: CC BY-SA 4.0


问:
Text classification with LSTM Network and Keras
I'm currently using a Naive Bayes algorithm to do my text classification.

My end goal is to be able to highlight parts of a big text document if the algorithm has decided the sentence belonged to a category.

Naive Bayes results are good, but I would like to train a NN for this problem, so I've followed this tutorial:
http://machinelearningmastery.com/sequence-classification-lstm-recurrent-neural-networks-python-keras/ to build my LSTM network on Keras.

All these notions are quite difficult for me to understand right now, so excuse me if you see some really stupid things in my code.

1/ Preparation of the training data

I have 155 sentences of different sizes that have been tagged to a label.

All these tagged sentences are in a training.csv file:

```<code>8,9,1,2,3,4,5,6,7
16,15,4,6,10,11,12,13,14
17,18
22,19,20,21
24,20,21,23
</code>```

(each integer representing a word)

And all the results are in another label.csv file:

```<code>6,7,17,15,16,18,4,27,30,30,29,14,16,20,21 ...
</code>```

I have 155 lines in trainings.csv, and of course 155 integers in label.csv

My dictionnary has 1038 words.

2/ The code

Here is my current code:

```<code>total_words = 1039

## fix random seed for reproducibility
numpy.random.seed(7)

datafile = open('training.csv', 'r')
datareader = csv.reader(datafile)
data = []
for row in datareader:
    data.append(row)

X = data;
Y = numpy.genfromtxt("labels.csv", dtype="int", delimiter=",")

max_sentence_length = 500

X_train = sequence.pad_sequences(X, maxlen=max_sentence_length)
X_test = sequence.pad_sequences(X, maxlen=max_sentence_length)

# create the model
embedding_vecor_length = 32
model = Sequential()
model.add(Embedding(total_words, embedding_vecor_length, input_length=max_sentence_length))
model.add(LSTM(100, dropout=0.2, recurrent_dropout=0.2))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
print(model.summary())
model.fit(X_train, Y, epochs=3, batch_size=64)
# Final evaluation of the model
scores = model.evaluate(X_train, Y, verbose=0)
print("Accuracy: %.2f%%" % (scores[1]*100))
</code>```

This model is never converging:

```<code>155/155 [==============================] - 4s - loss: 0.5694 - acc: 0.0000e+00
Epoch 2/3
155/155 [==============================] - 3s - loss: -0.2561 - acc: 0.0000e+00
Epoch 3/3
155/155 [==============================] - 3s - loss: -1.7268 - acc: 0.0000e+00
</code>```

I would like to have one of the 24 labels as a result, or a list of probabilities for each label.

What am I doing wrong here?

Thanks for your help!

答:
I've updated my code thanks to the great comments posted to my question.

```<code>Y_train = numpy.genfromtxt("labels.csv", dtype="int", delimiter=",")
Y_test = numpy.genfromtxt("labels_test.csv", dtype="int", delimiter=",")
Y_train =  np_utils.to_categorical(Y_train)
Y_test = np_utils.to_categorical(Y_test)
max_review_length = 50

X_train = sequence.pad_sequences(X_train, maxlen=max_review_length)
X_test = sequence.pad_sequences(X_test, maxlen=max_review_length)

model = Sequential()
model.add(Embedding(top_words, 32, input_length=max_review_length))
model.add(LSTM(10, dropout=0.2, recurrent_dropout=0.2))
model.add(Dense(31, activation="softmax"))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=["accuracy"])

model.fit(X_train, Y_train, epochs=100, batch_size=30)
</code>```

I think I can play with LSTM size (10 or 100), number of epochs and batch size.

Model has a very poor accuracy (40%). But currently I think it's because I don't have enough data (150 sentences for 24 labels).

I will put this project in standby mode until I get more data.

If someone has some ideas to improve this code, feel free to comment!

Body:
I'm currently using a Naive Bayes algorithm to do my text classification.

My end goal is to be able to highlight parts of a big text document if the algorithm has decided the sentence belonged to a category.

Naive Bayes results are good, but I would like to train a NN for this problem, so I've followed this tutorial:
http://machinelearningmastery.com/sequence-classification-lstm-recurrent-neural-networks-python-keras/ to build my LSTM network on Keras.

All these notions are quite difficult for me to understand right now, so excuse me if you see some really stupid things in my code.

1/ Preparation of the training data

I have 155 sentences of different sizes that have been tagged to a label.

All these tagged sentences are in a training.csv file:

8,9,1,2,3,4,5,6,7
16,15,4,6,10,11,12,13,14
17,18
22,19,20,21
24,20,21,23

(each integer representing a word)

And all the results are in another label.csv file:

6,7,17,15,16,18,4,27,30,30,29,14,16,20,21 ...

I have 155 lines in trainings.csv, and of course 155 integers in label.csv

My dictionnary has 1038 words.

2/ The code

Here is my current code:

total_words = 1039

## fix random seed for reproducibility
numpy.random.seed(7)

datafile = open('training.csv', 'r')
datareader = csv.reader(datafile)
data = []
for row in datareader:
    data.append(row)

X = data;
Y = numpy.genfromtxt("labels.csv", dtype="int", delimiter=",")

max_sentence_length = 500

X_train = sequence.pad_sequences(X, maxlen=max_sentence_length)
X_test = sequence.pad_sequences(X, maxlen=max_sentence_length)

# create the model
embedding_vecor_length = 32
model = Sequential()
model.add(Embedding(total_words, embedding_vecor_length, input_length=max_sentence_length))
model.add(LSTM(100, dropout=0.2, recurrent_dropout=0.2))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
print(model.summary())
model.fit(X_train, Y, epochs=3, batch_size=64)
# Final evaluation of the model
scores = model.evaluate(X_train, Y, verbose=0)
print("Accuracy: %.2f%%" % (scores[1]*100))

This model is never converging:

155/155 [==============================] - 4s - loss: 0.5694 - acc: 0.0000e+00
Epoch 2/3
155/155 [==============================] - 3s - loss: -0.2561 - acc: 0.0000e+00
Epoch 3/3
155/155 [==============================] - 3s - loss: -1.7268 - acc: 0.0000e+00

I would like to have one of the 24 labels as a result, or a list of probabilities for each label.

What am I doing wrong here?

Thanks for your help!

Body:
I've updated my code thanks to the great comments posted to my question.

Y_train = numpy.genfromtxt("labels.csv", dtype="int", delimiter=",")
Y_test = numpy.genfromtxt("labels_test.csv", dtype="int", delimiter=",")
Y_train =  np_utils.to_categorical(Y_train)
Y_test = np_utils.to_categorical(Y_test)
max_review_length = 50

X_train = sequence.pad_sequences(X_train, maxlen=max_review_length)
X_test = sequence.pad_sequences(X_test, maxlen=max_review_length)

model = Sequential()
model.add(Embedding(top_words, 32, input_length=max_review_length))
model.add(LSTM(10, dropout=0.2, recurrent_dropout=0.2))
model.add(Dense(31, activation="softmax"))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=["accuracy"])

model.fit(X_train, Y_train, epochs=100, batch_size=30)

I think I can play with LSTM size (10 or 100), number of epochs and batch size.

Model has a very poor accuracy (40%). But currently I think it's because I don't have enough data (150 sentences for 24 labels).

I will put this project in standby mode until I get more data.

If someone has some ideas to improve this code, feel free to comment!


问:
Extract JSON value to shell variable using jq
I have a json response as shown below :

```<code>[
 {"id":10,
 "list_file":["/var/a.txt",
             "/dev/b.txt"]}
]
</code>```

I need to extract values of list_file and store it shell variable as an array. I tried doing it looping through and reading the values.

```<code>#!/bin/bash
x=()
while read -r value
do
  #echo "$value"
  x+=("$value")
done < <(jq -r '.[] | .list_file' input.json)
</code>```

But the extracted values in the array contains quotes, brackets and comma too.

```<code>[
    "/var/a.txt",
    "/dev/b.txt"
]
</code>```

Could you please help me modify the code so that the array contains only the entries /var/a.txt and /dev/b.txt. Also, I tried readarray and map, but they won't work on Mac Osx. Any help would be really appreciated.

答:
On a Mac, it's easy enough to install a bash with readarray (e.g. using homebrew: brew install bash), so in the following I'll assume it's available, but you could just as well use the while read -r value technique to read values on a line-by-line basis.  (One advantage of these line-oriented methods is that there's no need to fiddle with IFS.)

For the problem at hand, there may be situations in which it would be better to retain the JSON representation of special characters, e.g "\n" for NEWLINE, "\u0000" for NUL, etc.  At any rate, a generic alternative to using -r is to use the -c command-line option instead, as illustrated below:

```<code>$ readarray -t x < <(jq -n -c '("\u0001\nb", "c\td", "e\u0000f")'
  | sed -e 's/^\"//' -e 's/\"$//' )
$ printf ":%s:\n" "${x[@]}"
:\u0001\nb:
:c\td:
:e\u0000f:
</code>```

Body:
I have a json response as shown below :

[
 {"id":10,
 "list_file":["/var/a.txt",
             "/dev/b.txt"]}
]

I need to extract values of list_file and store it shell variable as an array. I tried doing it looping through and reading the values.

#!/bin/bash
x=()
while read -r value
do
  #echo "$value"
  x+=("$value")
done < <(jq -r '.[] | .list_file' input.json)

But the extracted values in the array contains quotes, brackets and comma too.

[
    "/var/a.txt",
    "/dev/b.txt"
]

Could you please help me modify the code so that the array contains only the entries /var/a.txt and /dev/b.txt. Also, I tried readarray and map, but they won't work on Mac Osx. Any help would be really appreciated.

Body:
On a Mac, it's easy enough to install a bash with readarray (e.g. using homebrew: brew install bash), so in the following I'll assume it's available, but you could just as well use the while read -r value technique to read values on a line-by-line basis.  (One advantage of these line-oriented methods is that there's no need to fiddle with IFS.)

For the problem at hand, there may be situations in which it would be better to retain the JSON representation of special characters, e.g "\n" for NEWLINE, "\u0000" for NUL, etc.  At any rate, a generic alternative to using -r is to use the -c command-line option instead, as illustrated below:

$ readarray -t x < <(jq -n -c '("\u0001\nb", "c\td", "e\u0000f")'
  | sed -e 's/^\"//' -e 's/\"$//' )
$ printf ":%s:\n" "${x[@]}"
:\u0001\nb:
:c\td:
:e\u0000f:


问:
Custom underline effect, other than creating a background image for it
is there a better way to create this style of "underline" through CSS, other than creating a background image for it?

To be clear, I'm only interested in the "duplicated line" effect, a thicker and shorter line sitting directly atop a thinner and longer line of a different color. Thanks!

答:
I always create "divider", like:

```<code><div class='divider'>
    <div class='divi-1'></div>
    <div class='divi-2'></div>
    <div class='divi-3'></div>
</div>
</code>```

CSS:

```<code>.divider{
    padding-top:15px; //or other
    text-align:center;
    display:block; // or column in bootstrap like col-md-12
}

.divider .divi-1{
    display:inline-block;
    height:2px; //or other
    width:50px; // or other
    background:#e5e5e5;
.

.divider .divi-2{
    display:inline-block;
    height:2px;
    width:50px;
    background:#000000;
}
.divider .divi-1{
    display:inline-block;
    height:2px; //or other
    width:50px; // or other
    background:#e5e5e5;
}
</code>```

And that's it. You can also use vertical-align for inline-block so You have some more options to move lines verticaly ... and also it's in the flow so You know what size it have and can be sure that other elements won't overlap it.

Body:
I always create "divider", like:

<div class='divider'>
    <div class='divi-1'></div>
    <div class='divi-2'></div>
    <div class='divi-3'></div>
</div>

CSS:

.divider{
    padding-top:15px; //or other
    text-align:center;
    display:block; // or column in bootstrap like col-md-12
}

.divider .divi-1{
    display:inline-block;
    height:2px; //or other
    width:50px; // or other
    background:#e5e5e5;
.

.divider .divi-2{
    display:inline-block;
    height:2px;
    width:50px;
    background:#000000;
}
.divider .divi-1{
    display:inline-block;
    height:2px; //or other
    width:50px; // or other
    background:#e5e5e5;
}

And that's it. You can also use vertical-align for inline-block so You have some more options to move lines verticaly ... and also it's in the flow so You know what size it have and can be sure that other elements won't overlap it.


问:
How can you adjust chromeOptions zoom levels without worrying about this id needing to be passed in?
I am trying to set chrome's zoom level upon opening. I realize there are ways to send keys to zoom, change viewport, and change browser size, but with the machine running our tests, the browser is not in the foreground to receive the keys, and the browser and viewport sizes are limited by the machines resolution. I also realize this breaks clicks, as webdriver cannot find the correct coordinates. With that in mind, proceeding!

My solution has been to change the browsers per_host_zoom_levels. To find this example, I checked my own chrome preferences here:
C:\Users\\AppData\Local\Google\Chrome\User Data\Default\Preferences

I found that passing in the per_host_zoom_levels does in fact work like so:

```<code>capabilities: {
    'browserName': 'chrome',

    'chromeOptions':{
        prefs:{
            "partition": {
                "per_host_zoom_levels": {
                    "14692111032568906945": {
                        "localhost":-3
                    }
                }
            }
        }
    }
},
</code>```

This gets the browser to use a different zoom level on any localhost addresses, which is exactly what I need for the test.

The issue is the 'id' of sorts that is directly under the per_host_zoom_levels. It is different for each machine, and in fact mine even has three different ids of sorts.

Is there a way to make this generic so it sets the zoom level no matter what the 'id' is?

答: You need to  retrieve the "id" from the machine's chrome preferences before executing the tests.</p>

Body:
I am trying to set chrome's zoom level upon opening. I realize there are ways to send keys to zoom, change viewport, and change browser size, but with the machine running our tests, the browser is not in the foreground to receive the keys, and the browser and viewport sizes are limited by the machines resolution. I also realize this breaks clicks, as webdriver cannot find the correct coordinates. With that in mind, proceeding!

My solution has been to change the browsers per_host_zoom_levels. To find this example, I checked my own chrome preferences here:
C:\Users\\AppData\Local\Google\Chrome\User Data\Default\Preferences

I found that passing in the per_host_zoom_levels does in fact work like so:

capabilities: {
    'browserName': 'chrome',

    'chromeOptions':{
        prefs:{
            "partition": {
                "per_host_zoom_levels": {
                    "14692111032568906945": {
                        "localhost":-3
                    }
                }
            }
        }
    }
},

This gets the browser to use a different zoom level on any localhost addresses, which is exactly what I need for the test.

The issue is the 'id' of sorts that is directly under the per_host_zoom_levels. It is different for each machine, and in fact mine even has three different ids of sorts.

Is there a way to make this generic so it sets the zoom level no matter what the 'id' is?


问:
Show "duplicate Number" when number is not found in range
```<code>If MoneyTextBox.Value = range("H:H").Find(MoneyTextBox.Value) Then
    MsgBox "Duplicate number"
EndIf
</code>```

答:
Or simply this...</p>

```<code>If Application.CountIf(Range("H:H"), MoneyTextBox.Value) > 0 Then
    MsgBox "Duplicate number"
End If
</code>```

Body:
Or simply this...

If Application.CountIf(Range("H:H"), MoneyTextBox.Value) > 0 Then
    MsgBox "Duplicate number"
End If


问:
CSS Affecting inner elements
I have a font awesome arrow icon inside a link tag. On mouse hover,I want the arrow to move slightly to the right like this:       http://mo-de.com/#contacts
My css :

```<code> a:hover{
  transform:translateX(2px);
 }
</code>```

But it moves the whole link. How can I access the specific tag I want or the icon to move it independently?

答:
Just give the id to the fa-icon example id="icon" and then have pseudo class as

```<code>#a:hover ~ #icon {
     transform: translateX(2px);
}
</code>```

This will work

Let me know if you require any further help

Title: CSS Affecting inner elements

Body:
I have a font awesome arrow icon inside a link tag. On mouse hover,I want the arrow to move slightly to the right like this:       http://mo-de.com/#contacts
My css :

 a:hover{
  transform:translateX(2px);
 }

But it moves the whole link. How can I access the specific tag I want or the icon to move it independently?

Body:
Just give the id to the fa-icon example id="icon" and then have pseudo class as

#a:hover ~ #icon {
     transform: translateX(2px);
}

This will work

Let me know if you require any further help


问:
Why isn't move_upload_file is always returning false in the given code?
I am trying to upload an image using php and mysql and below is the code used..

index.php

```<code><form action="submit.php" enctype="multipart/form-data" method="post">

<table style="border-collapse: collapse; font: 12px Tahoma;" border="1" cellspacing="5" cellpadding="5">
<tbody><tr>
<td>
<input name="uploadedimage" type="file">
</td>

</tr>

<tr>
<td>
<input name="Upload Now" type="submit" value="Upload Image">
</td>
</tr>

</tbody></table>

</form>
</code>```

submit.php

```<code><?php

include("mysqlconnect.php");

function GetImageExtension($imagetype) {
    if (empty($imagetype))
        return false;
    switch ($imagetype) {
        case 'image/bmp': return '.bmp';
        case 'image/gif': return '.gif';
        case 'image/jpeg': return '.jpg';
        case 'image/png': return '.png';
        default: return false;
    }
}

if (!empty($_FILES["uploadedimage"]["name"])) {

    $file_name = $_FILES["uploadedimage"]["name"];
    $temp_name = $_FILES["uploadedimage"]["tmp_name"];
    $imgtype = $_FILES["uploadedimage"]["type"];
    $ext = GetImageExtension($imgtype);
    $imagename = date("d-m-Y") . "-" . time() . $ext;
    $target_path = "images/" . $imagename;

    if (move_uploaded_file($_FILES['uploadedimage']['tmp_name'], $target_path)) {
        $detail = date("Y-m-d");
        $sql = "INSERT INTO `image_upload`(`id`, `image`, `detail`) VALUES (NULL,'$target_path','$detail')";
        if (!$conn->query($sql)) {
            echo $conn->error;
        } else {
            echo "Successfully inserted. ";
        }
    } else {

        exit("Error While uploading image on the server");
    }
}
?>
</code>```

Table structure:

```<code>#   Name        Type    Collation     Attributes    Null Default  Extra
1   id(Primary) int(11)                              No   None    AUTO_INCREMENT
2   image       blob                                 Yes  NULL
3   detail     varchar(500) utf8_general_ci          Yes  NULL
</code>```

Every time I execute this it always shows me "Error While uploading image on the server" I don't understand why. Can someone let me know where am I going wrong and how can I improve my implementation?
Thanks in advance.

答: Alter your table structure for image as varchar(255) and check if that works</p>

Body:
I am trying to upload an image using php and mysql and below is the code used..

index.php

<form action="submit.php" enctype="multipart/form-data" method="post">

<input name="uploadedimage" type="file">

<input name="Upload Now" type="submit" value="Upload Image">

</form>

submit.php

<?php

include("mysqlconnect.php");

function GetImageExtension($imagetype) {
    if (empty($imagetype))
        return false;
    switch ($imagetype) {
        case 'image/bmp': return '.bmp';
        case 'image/gif': return '.gif';
        case 'image/jpeg': return '.jpg';
        case 'image/png': return '.png';
        default: return false;
    }
}

if (!empty($_FILES["uploadedimage"]["name"])) {

    $file_name = $_FILES["uploadedimage"]["name"];
    $temp_name = $_FILES["uploadedimage"]["tmp_name"];
    $imgtype = $_FILES["uploadedimage"]["type"];
    $ext = GetImageExtension($imgtype);
    $imagename = date("d-m-Y") . "-" . time() . $ext;
    $target_path = "images/" . $imagename;

    if (move_uploaded_file($_FILES['uploadedimage']['tmp_name'], $target_path)) {
        $detail = date("Y-m-d");
        $sql = "INSERT INTO `image_upload`(`id`, `image`, `detail`) VALUES (NULL,'$target_path','$detail')";
        if (!$conn->query($sql)) {
            echo $conn->error;
        } else {
            echo "Successfully inserted. ";
        }
    } else {

        exit("Error While uploading image on the server");
    }
}
?>

Table structure:

#   Name        Type    Collation     Attributes    Null Default  Extra
1   id(Primary) int(11)                              No   None    AUTO_INCREMENT
2   image       blob                                 Yes  NULL
3   detail     varchar(500) utf8_general_ci          Yes  NULL

Every time I execute this it always shows me "Error While uploading image on the server" I don't understand why. Can someone let me know where am I going wrong and how can I improve my implementation?
Thanks in advance.