问:
Generics without parameterless constructors
Can someone explain why in the code below, class1List does not require class1 to have a parameterless constructor, but class2list does require class 2 to have a parameterless constructor.

```<code>unit Unit11;

interface

uses
  System.Generics.Collections;

type
  class1 = class
  public
    constructor Create( const i : integer ); virtual;
  end;

  class1List<T : class1 > = class( TObjectList< T > )
  public
    function AddChild( const i : integer ) : T;
  end;

  class2 = class
  public
    constructor Create( const i : integer );
  end;

  class2List<T : class2 > = class( TObjectList< T > )
  public
    function AddChild( const i : integer ) : T;
  end;

implementation

{ class1List<T> }

function class1List<T>.AddChild(const i: integer): T;
begin
  Result := T.Create( i );
  inherited Add( Result );
end;

{ class2List<T> }

function class2List<T>.AddChild(const i: integer): T;
begin
  Result := T.Create( i );
  inherited Add( Result );
end;

{ class1 }

constructor class1.Create(const i: integer);
begin

end;

{ class2 }

constructor class2.Create(const i: integer);
begin

end;

end.
</code>```

答:
```<code>function class1List<T>.AddChild(const i: integer): T;
begin
  Result := T.Create( i );
  inherited Add( Result );
end;
</code>```

The constructor of class1 is declared virtual. Therefore the compiler knows that T.Create yields an instance of T whose intended constructor has been called. Hence the compiler accepts this code. Note that earlier versions of the compiler would reject this code and force you to use the following cast

```<code>Result := T(class1(T).Create( i ));
</code>```

But more recent versions of the compiler have removed the need for such trickery.

```<code>function class2List<T>.AddChild(const i: integer): T;
begin
  Result := T.Create( i );
  inherited Add( Result );
end;
</code>```

The constructor of class2 is not virtual and so the compiler knows that were it to call the constructor of class2, likely the class would not be properly initialised. It is prepared to call a parameterless constructor from the specialised type T if one exists, and you apply the constructor constraint when you declare the generic type. However, the language offers no way to apply a constructor constraint for constructors that accept parameters.

Now, you could apply the constructor constraint, but that would do no good. In order for the instance to be initialised properly, you need to call the constructor with the parameter. Which means, in practical terms, that you should use the first approach using a virtual constructor.

Don't be tempted to cast your way out of this hole. This code will compile

```<code>Result := T(class2(T).Create( i ));
</code>```

but will likely not do what you want. This will call the static constructor of class2 which is surely not what you want.

Body:
Can someone explain why in the code below, class1List does not require class1 to have a parameterless constructor, but class2list does require class 2 to have a parameterless constructor.

unit Unit11;

interface

uses
  System.Generics.Collections;

type
  class1 = class
  public
    constructor Create( const i : integer ); virtual;
  end;

  class1List<T : class1 > = class( TObjectList< T > )
  public
    function AddChild( const i : integer ) : T;
  end;

  class2 = class
  public
    constructor Create( const i : integer );
  end;

  class2List<T : class2 > = class( TObjectList< T > )
  public
    function AddChild( const i : integer ) : T;
  end;

implementation

{ class1List<T> }

function class1List<T>.AddChild(const i: integer): T;
begin
  Result := T.Create( i );
  inherited Add( Result );
end;

{ class2List<T> }

function class2List<T>.AddChild(const i: integer): T;
begin
  Result := T.Create( i );
  inherited Add( Result );
end;

{ class1 }

constructor class1.Create(const i: integer);
begin

end;

{ class2 }

constructor class2.Create(const i: integer);
begin

end;

end.

Body:
function class1List<T>.AddChild(const i: integer): T;
begin
  Result := T.Create( i );
  inherited Add( Result );
end;

The constructor of class1 is declared virtual. Therefore the compiler knows that T.Create yields an instance of T whose intended constructor has been called. Hence the compiler accepts this code. Note that earlier versions of the compiler would reject this code and force you to use the following cast

Result := T(class1(T).Create( i ));

But more recent versions of the compiler have removed the need for such trickery.

function class2List<T>.AddChild(const i: integer): T;
begin
  Result := T.Create( i );
  inherited Add( Result );
end;

The constructor of class2 is not virtual and so the compiler knows that were it to call the constructor of class2, likely the class would not be properly initialised. It is prepared to call a parameterless constructor from the specialised type T if one exists, and you apply the constructor constraint when you declare the generic type. However, the language offers no way to apply a constructor constraint for constructors that accept parameters.

Now, you could apply the constructor constraint, but that would do no good. In order for the instance to be initialised properly, you need to call the constructor with the parameter. Which means, in practical terms, that you should use the first approach using a virtual constructor.

Don't be tempted to cast your way out of this hole. This code will compile

Result := T(class2(T).Create( i ));

but will likely not do what you want. This will call the static constructor of class2 which is surely not what you want.


来源: stackexchange

问:
Is it possible to create new type variable without struct?
Here is what i got but when i check type it displays "struct MyVarName"

```<code>#include <iostream>
#include <typeinfo>
typedef struct { char text[15];} MyVarName;
int  g = 0;
int main(void) {
    MyVarName a = { "super" };
    std::cout << typeid(a).name() << '\n';
    std::cout << typeid(g).name() << '\n';
return 0;
}
</code>```

Is it possible to define your own variable type and then use it as any other variable?

Print, assign new value.. etc.

答:
in C:</p>

```<code>typedef char newtype[20];

void foo(void)
{
    newtype a;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Here is what i got but when i check type it displays "struct MyVarName"

#include <iostream>
#include <typeinfo>
typedef struct { char text[15];} MyVarName;
int  g = 0;
int main(void) {
    MyVarName a = { "super" };
    std::cout << typeid(a).name() << '\n';
    std::cout << typeid(g).name() << '\n';
return 0;
}

Is it possible to define your own variable type and then use it as any other variable?

Print, assign new value.. etc.

Body:
in C:

typedef char newtype[20];

void foo(void)
{
    newtype a;
}


问:
google sheet formula - get column letter by variable?
Given a formula, eg:

```<code>= FILTER(matrix!B3:B99, NOT(matrix!C3:C99 = "") )    )
</code>```

Is it possible to pass a variable in place of column B reference? Eg:

```<code>= FILTER(matrix!$requiredCol3:$requiredCol99, NOT(matrix!C3:C99 = "") )    )
</code>```

where $requiredCol is whatever value is always in A1 for example?

eg, A1=X
formula is now equivilent to:

```<code>= FILTER(matrix!$X3:$X99, NOT(matrix!C3:C99 = "") )    )
</code>```

Thanks

答:
You should be able to use INDIRECT(), which takes a cell reference as string as (first) parameter. See if this works:

```<code>= FILTER(INDIRECT("matrix!"&A1&"3:"&A1&"99"), NOT(matrix!C3:C99 = "") )
</code>```

EDIT: if you have the ranges in cells A1 and A2 try

```<code>=FILTER(INDIRECT(A1), INDIRECT(A2) <>"")
</code>```

Body:
Given a formula, eg:

= FILTER(matrix!B3:B99, NOT(matrix!C3:C99 = "") )    )

Is it possible to pass a variable in place of column B reference? Eg:

= FILTER(matrix!$requiredCol3:$requiredCol99, NOT(matrix!C3:C99 = "") )    )

where $requiredCol is whatever value is always in A1 for example?

eg, A1=X
formula is now equivilent to:

= FILTER(matrix!$X3:$X99, NOT(matrix!C3:C99 = "") )    )

Thanks

Body:
You should be able to use INDIRECT(), which takes a cell reference as string as (first) parameter. See if this works:

= FILTER(INDIRECT("matrix!"&A1&"3:"&A1&"99"), NOT(matrix!C3:C99 = "") )

EDIT: if you have the ranges in cells A1 and A2 try

=FILTER(INDIRECT(A1), INDIRECT(A2) <>"")


问:
Javascript sending data via POST in firefox addon
I have a mysql database, with a php form.  Normally, people use the php form on my website to add to the mysql database.  I have been building a firefox addon to let them use the form without visiting the site directly to add data to the mysql database.  Now I am stuck...

I have the form data I want to add to the mysql database, but how can I send it to the mysql database from the addon?  What's the best way to do this?  Would you send it to the php form first or is there a direct way?  Is it possible to go straight to mysql?  The firefox addon is coded in javascript.

Thanks!

答:
Jan Hančič is right : the best way is to use XMLHttpRequest.

Here's an example :

```<code>var xhr = new XMLHttpRequest();
xhr.open("post", "http://ex.ample.com/file.php", true);
xhr.onreadystatechange = function() {
    if(this.readyState == 4) {
        // Do something with this.responseText
    }
}
xhr.send("var1=val1&var2=val2");
</code>```

There are plenty of tutorials and references on the web about AJAX and the xhr object.

ContentLicense: CC BY-SA 2.5

Body:
Jan Hančič is right : the best way is to use XMLHttpRequest.

Here's an example :

var xhr = new XMLHttpRequest();
xhr.open("post", "http://ex.ample.com/file.php", true);
xhr.onreadystatechange = function() {
    if(this.readyState == 4) {
        // Do something with this.responseText
    }
}
xhr.send("var1=val1&var2=val2");

There are plenty of tutorials and references on the web about AJAX and the xhr object.


问:
Write a query that gives mutual friend names of user DDD and FFF. Also, note that if A is friend of B then B is also friend A
Create 2 tables that contains list of friends and users.

This is my query:

```<code>SELECT
  U.username "Mutual Friend"
FROM users U
LEFT OUTER JOIN friends F
  ON U.userid = F.friendid
WHERE f.userid = 6
AND f.friendid IN (SELECT
  friendid
FROM friends
WHERE userid = 4);
</code>```

friends: userid, friendid

```<code>1, 2
1, 3
1, 4
2, 4
2, 5
2, 7
3, 4
3, 6
4, 7
4, 8
4, 9
5, 6
5, 9
6, 7
7, 8
8, 9
</code>```

users: userid, username

```<code>1, AAA
2, BBB
3, CCC
4, DDD
5, EEE
6, FFF
7, GGG
8, HHH
9, III
</code>```

Desired Result:

```<code>Mutual Friends
-----------------
CCC
GGG
</code>```

答:
You could use having for that:

```<code>SELECT     u.username "Mutual Friend"
FROM       users u
INNER JOIN friends f
        ON u.userid IN (f.userid, f.friendid)
INNER JOIN users v
        ON v.userid IN (f.userid, f.friendid)
       AND v.userid <> u.userid
       AND v.username IN ('DDD', 'FFF')
GROUP BY   u.username
HAVING     count(distinct v.userid) = 2
</code>```

Body:
Create 2 tables that contains list of friends and users.

This is my query:

SELECT
  U.username "Mutual Friend"
FROM users U
LEFT OUTER JOIN friends F
  ON U.userid = F.friendid
WHERE f.userid = 6
AND f.friendid IN (SELECT
  friendid
FROM friends
WHERE userid = 4);

friends: userid, friendid

1, 2
1, 3
1, 4
2, 4
2, 5
2, 7
3, 4
3, 6
4, 7
4, 8
4, 9
5, 6
5, 9
6, 7
7, 8
8, 9

users: userid, username

1, AAA
2, BBB
3, CCC
4, DDD
5, EEE
6, FFF
7, GGG
8, HHH
9, III

Desired Result:

Mutual Friends
-----------------
CCC
GGG

Body:
You could use having for that:

SELECT     u.username "Mutual Friend"
FROM       users u
INNER JOIN friends f
        ON u.userid IN (f.userid, f.friendid)
INNER JOIN users v
        ON v.userid IN (f.userid, f.friendid)
       AND v.userid <> u.userid
       AND v.username IN ('DDD', 'FFF')
GROUP BY   u.username
HAVING     count(distinct v.userid) = 2


问:
Admob & ActionScript 3
I saw that Admob just released an SDK for Flash Lite (Action Script 2). I'm working on an AS3
project, and could not find anywhere on the internet an AS3 version of the SDK.

Does anyone have any knowledge of such an SDK for AS3 or using the AS2 SDK in AS3.

Thanks

Can

答: There is no as3 sdk. Also the as2 sdk does not work in as3. It needs to be rewritten in as3. I am not very talented with as3. Can someone rewrite the AdMobAd.as class to as3? </p>

Title: Admob & ActionScript 3


问:
How to correctly bind a DependencyProperty of a UserControl to a property of its own view model?
EDIT: Set the View Model as the DataContext

There are a lot of questions on SO here but they all revolve around doing some funky CodeBehind stuff. What I want is:

I have a view model like this:

```<code>public class FooViewModel : INotifyPropertyChanged {

    public Foo Foo {
        get { ...}
        set { ... }
    }
}
</code>```

And I define this in my UserControl like this:

```<code><UserControl.DataContext>
    <vm:FooViewModel />
</UserControl.DataContext>
</code>```

In my CodeBehind file I defined a DependencyProperty:

```<code>    public Foo Foo {
        get { return (Foo)GetValue(FooProperty); }
        set { SetValue(FooProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Foo.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty FooProperty =
        DependencyProperty.Register("Foo", typeof(Foo), typeof(FooControl), new PropertyMetadata(null));
</code>```

So I now can bind the Foo property when I use the control elsewhere.

The missing link is: How do I bind the UserControl's Foo to the ViewModel's Foo?

Currently, I am using some elaborate event handling in the CodeBehind to synchronize these, but I reckon there must be a way to do this in XAML, or is there not?

答:
If you really want to do that - you can use a style (I'm using your original code when view model was in resources):

```<code><UserControl.Resources>
    <local:ViewModel x:Key="ViewModel" />
    <Style TargetType="local:MyUserControl">
        <Setter Property="Foo"
                Value="{Binding Source={StaticResource ViewModel}, Path=Foo}" />
    </Style>
</UserControl.Resources>
</code>```

However having view model for a UserControl is not a good idea. Use dependency properties and bind to them directly from controls inside your UserControl. Then when you use UserControl - you will be able to bind its dependency properties from outside. However binding them from the inside (to separate view model) is usually not a good idea.

Body:
EDIT: Set the View Model as the DataContext

There are a lot of questions on SO here but they all revolve around doing some funky CodeBehind stuff. What I want is:

I have a view model like this:

public class FooViewModel : INotifyPropertyChanged {

    public Foo Foo {
        get { ...}
        set { ... }
    }
}

And I define this in my UserControl like this:

<UserControl.DataContext>
    <vm:FooViewModel />
</UserControl.DataContext>

In my CodeBehind file I defined a DependencyProperty:

    public Foo Foo {
        get { return (Foo)GetValue(FooProperty); }
        set { SetValue(FooProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Foo.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty FooProperty =
        DependencyProperty.Register("Foo", typeof(Foo), typeof(FooControl), new PropertyMetadata(null));

So I now can bind the Foo property when I use the control elsewhere.

The missing link is: How do I bind the UserControl's Foo to the ViewModel's Foo?

Currently, I am using some elaborate event handling in the CodeBehind to synchronize these, but I reckon there must be a way to do this in XAML, or is there not?

Body:
If you really want to do that - you can use a style (I'm using your original code when view model was in resources):

<UserControl.Resources>
    <local:ViewModel x:Key="ViewModel" />
    <Style TargetType="local:MyUserControl">
        <Setter Property="Foo"
                Value="{Binding Source={StaticResource ViewModel}, Path=Foo}" />
    </Style>
</UserControl.Resources>

However having view model for a UserControl is not a good idea. Use dependency properties and bind to them directly from controls inside your UserControl. Then when you use UserControl - you will be able to bind its dependency properties from outside. However binding them from the inside (to separate view model) is usually not a good idea.


问:
how to align login form wp_login_form()
I'd like to customize my WordPress Login form. I am a newbie in WP and strictly follows procedure described here:https://themetrust.com/build-custom-wordpress-login-page/.  But I made additional small customization:

```<code>require_once( explode( "wp-content" , __FILE__ )[0] . "wp-load.php" );

get_header(); ?>
<?php the_content(); ?>

<style>
.right{
position: absolute;
right: 532px;
width: 480px;
border: 3px solid #73AD21;
padding: 10px;
}
</style>
<?php
$args = array(
'echo'           => true,
'redirect'       => site_url( $_SERVER['REQUEST_URI'] ),
'form_id'        => 'loginform',
'label_username' => 'Username',
'label_password' => 'Password',
'label_remember' => 'Remember Me',
'label_log_in'   => 'Log In',
'id_username'    => 'user_login',
'id_password'    => 'user_pass',
'id_remember'    => 'rememberme',
'id_submit'      => 'wp-submit',
'remember'       => true,
'value_username' => NULL,
'value_remember' => false
);
?>
 <div>
<table class = "right" bgcolor="#cccccc">
<tr>
 <td <p><a href="<?php  get_template_directory_uri() .'/page-not-
member.php'; ?>">Not member yet</a></p></td><td></td><td></td>
</tr>
<tr>
 <td colspan="2">Login:</td>
 </tr>
 <tr>
  <td> <?php wp_login_form( array('redirect' => home_url()) ); ?> </td>
 </tr>
<tr>
  <td colspan="2"><a href="<?php get_template_directory_uri()
.'/zapomnij_formularz.php'; ?>">Forgot password?</a></td>
</tr>
</tr>
</table>
</div>
</code>```

... and I got Login page like this:
http://ipic.su/img/img7/fs/image1.1499330136.jpg

How can i get page formatted like that(login/password input fields aligned ): http://ipic.su/img/img7/fs/image2.1499330556.jpg?

```<code>Thank you in advance.
</code>```

答:
You can use css.Below css are login form css.

Here's some helpful, highly specifc CSS selectors for the login page:

```<code>body.login {}
body.login div#login {}
body.login div#login h1 {}
body.login div#login h1 a {}
body.login div#login form#loginform {}
body.login div#login form#loginform p {}
body.login div#login form#loginform p label {}
body.login div#login form#loginform input {}
body.login div#login form#loginform input#user_login {}
body.login div#login form#loginform input#user_pass {}
body.login div#login form#loginform p.forgetmenot {}
body.login div#login form#loginform p.forgetmenot input#rememberme {}
body.login div#login form#loginform p.submit {}
body.login div#login form#loginform p.submit input#wp-submit {}
body.login div#login p#nav {}
body.login div#login p#nav a {}
body.login div#login p#backtoblog {}
body.login div#login p#backtoblog a {}
</code>```

for you i think thione css is needed

```<code>body.login div#login form#loginform input#user_pass {}
</code>```

Hopes this helps you

Title: how to align login form wp_login_form()

Body:
I'd like to customize my WordPress Login form. I am a newbie in WP and strictly follows procedure described here:https://themetrust.com/build-custom-wordpress-login-page/.  But I made additional small customization:

require_once( explode( "wp-content" , __FILE__ )[0] . "wp-load.php" );

get_header(); ?>
<?php the_content(); ?>

<?php
$args = array(
'echo'           => true,
'redirect'       => site_url( $_SERVER['REQUEST_URI'] ),
'form_id'        => 'loginform',
'label_username' => 'Username',
'label_password' => 'Password',
'label_remember' => 'Remember Me',
'label_log_in'   => 'Log In',
'id_username'    => 'user_login',
'id_password'    => 'user_pass',
'id_remember'    => 'rememberme',
'id_submit'      => 'wp-submit',
'remember'       => true,
'value_username' => NULL,
'value_remember' => false
);
?>

 <td
<a href="<?php  get_template_directory_uri() .'/page-not-
member.php'; ?>">Not member yet

 Login:

   <?php wp_login_form( array('redirect' => home_url()) ); ?>

  <a href="<?php get_template_directory_uri()
.'/zapomnij_formularz.php'; ?>">Forgot password?

... and I got Login page like this:
http://ipic.su/img/img7/fs/image1.1499330136.jpg

How can i get page formatted like that(login/password input fields aligned ): http://ipic.su/img/img7/fs/image2.1499330556.jpg?

Thank you in advance.

Body:
You can use css.Below css are login form css.

Here's some helpful, highly specifc CSS selectors for the login page:

body.login {}
body.login div#login {}
body.login div#login h1 {}
body.login div#login h1 a {}
body.login div#login form#loginform {}
body.login div#login form#loginform p {}
body.login div#login form#loginform p label {}
body.login div#login form#loginform input {}
body.login div#login form#loginform input#user_login {}
body.login div#login form#loginform input#user_pass {}
body.login div#login form#loginform p.forgetmenot {}
body.login div#login form#loginform p.forgetmenot input#rememberme {}
body.login div#login form#loginform p.submit {}
body.login div#login form#loginform p.submit input#wp-submit {}
body.login div#login p#nav {}
body.login div#login p#nav a {}
body.login div#login p#backtoblog {}
body.login div#login p#backtoblog a {}

for you i think thione css is needed

body.login div#login form#loginform input#user_pass {}

Hopes this helps you


问:
Button color change when untouched

<!DOCTYPE html>

 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Dummy form

<form name="myForm">
<input name="myInput" ng-model="myInput" required />

<input  type="button" ng-click="deleteRow($event,name)" value="Remove" class="btn" >

<input type="button"  ng-click="deleteRow($event,name)" value="Remove" class="btn btn-primary" >
</form>

```

When the inputs are touched I'm trying the change the remove button color.I tried with if else,it was not working.So, used ng-show where I'm getting two buttons and the one button with changed color is working only when I click outside the form.Can anyone help?

答:
Try this with only a single button and change class by ngclass

<input ng-class="{'btn-primary':myForm.myInput.$valid}" type="button"  ng-click="deleteRow($event,name)" value="Remove" class="btn btn-primary" >
```

Title: Button color change when untouched

Body:
<!DOCTYPE html>

 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Dummy form

<form name="myForm">
<input name="myInput" ng-model="myInput" required />

<input  type="button" ng-click="deleteRow($event,name)" value="Remove" class="btn" >

<input type="button"  ng-click="deleteRow($event,name)" value="Remove" class="btn btn-primary" >
</form>

When the inputs are touched I'm trying the change the remove button color.I tried with if else,it was not working.So, used ng-show where I'm getting two buttons and the one button with changed color is working only when I click outside the form.Can anyone help?

Body:
Try this with only a single button and change class by ngclass

<div>
<input ng-class="{'btn-primary':myForm.myInput.$valid}" type="button"  ng-click="deleteRow($event,name)" value="Remove" class="btn btn-primary" ></div>


问:
How to read Adb Dumpsys alarm output
I'm setting multiple alarms on repeat through alarm manager, they are working fine on the day they got set but not repeating at all. I have updated my code but I can't wait all day to check if the code is even working or not so I have tried adb shell dumpsys alarm command but I don't know how to read the output properly and how to extract the times of alarms being set. I have followed some links to understand the output but none is specifiying how to check the exact time of the alarm being set.
here is my output

my main code where i'm setting the alarm

```<code> final int _id = (int) System.currentTimeMillis();

        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

   //  alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,AllTime[i],AlarmManager.INTERVAL_DAY,
        //        PendingIntent.getBroadcast(this, _id, alertIntent, PendingIntent.FLAG_UPDATE_CURRENT));
        alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP,AllTime[i],AlarmManager.INTERVAL_DAY,
                PendingIntent.getBroadcast(this, _id, alertIntent, PendingIntent.FLAG_UPDATE_CURRENT));
</code>```

and this this the broadcast receiver

```<code>public void onReceive(Context context, Intent intent) {

    String[] myStrings = intent.getStringArrayExtra("strings");
    Log.i("okk", "cathing intent values through break" + Arrays.toString(myStrings));

    createNotification(context, "Time is here baby", "this is the notification text", "Alert");
    Log.i("okk", "cathing intent values through break" + Arrays.toString(myStrings));

}

public void createNotification(Context context, String msg, String msgText, String msgAlert) {
    final int _id = (int) System.currentTimeMillis();  // unique request code

    // will open mainActivity on notification click, can change it
 //   PendingIntent notificationIntent = PendingIntent.getActivity(context, _id, new Intent(context, MainActivity.class), 0);  // changed from 0 to _id

    PendingIntent notificationIntent = PendingIntent.getActivity(context,0, new Intent(context,MainActivity.class),0);
    NotificationCompat.Builder mbuilder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.cast_ic_notification_play)
            .setContentTitle(msg)
            .setTicker(msgAlert)
            .setContentText(msgText);

    // now intent we want to fire when noti is clicked

    mbuilder.setContentIntent(notificationIntent);

    // how person is notified

    mbuilder.setDefaults(NotificationCompat.DEFAULT_SOUND);

    mbuilder.setAutoCancel(true); // noti dismisble when user swipe it away

    NotificationManager notificationManager = (NotificationManager)
            context.getSystemService((Context.NOTIFICATION_SERVICE));

    //    Log.i("okk", "NOTIFIED " + intent.getExtras());

    notificationManager.notify(1, mbuilder.build());  // changes from 1 to _id
       }
</code>```

答:
maybe it can help you, I've created an opensource project with a GUI version of the "adb shell dumpsys alarms" command. You can find it here:

https://github.com/Dottorhouse/DumpsysAlarm

Hopefully it will help you figure out what's wrong

Title: How to read Adb Dumpsys alarm output

Body:
I'm setting multiple alarms on repeat through alarm manager, they are working fine on the day they got set but not repeating at all. I have updated my code but I can't wait all day to check if the code is even working or not so I have tried adb shell dumpsys alarm command but I don't know how to read the output properly and how to extract the times of alarms being set. I have followed some links to understand the output but none is specifiying how to check the exact time of the alarm being set.
here is my output

my main code where i'm setting the alarm

 final int _id = (int) System.currentTimeMillis();

        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

   //  alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,AllTime[i],AlarmManager.INTERVAL_DAY,
        //        PendingIntent.getBroadcast(this, _id, alertIntent, PendingIntent.FLAG_UPDATE_CURRENT));
        alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP,AllTime[i],AlarmManager.INTERVAL_DAY,
                PendingIntent.getBroadcast(this, _id, alertIntent, PendingIntent.FLAG_UPDATE_CURRENT));

and this this the broadcast receiver

public void onReceive(Context context, Intent intent) {

    String[] myStrings = intent.getStringArrayExtra("strings");
    Log.i("okk", "cathing intent values through break" + Arrays.toString(myStrings));

    createNotification(context, "Time is here baby", "this is the notification text", "Alert");
    Log.i("okk", "cathing intent values through break" + Arrays.toString(myStrings));

}

public void createNotification(Context context, String msg, String msgText, String msgAlert) {
    final int _id = (int) System.currentTimeMillis();  // unique request code

    // will open mainActivity on notification click, can change it
 //   PendingIntent notificationIntent = PendingIntent.getActivity(context, _id, new Intent(context, MainActivity.class), 0);  // changed from 0 to _id

    PendingIntent notificationIntent = PendingIntent.getActivity(context,0, new Intent(context,MainActivity.class),0);
    NotificationCompat.Builder mbuilder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.cast_ic_notification_play)
            .setContentTitle(msg)
            .setTicker(msgAlert)
            .setContentText(msgText);

    // now intent we want to fire when noti is clicked

    mbuilder.setContentIntent(notificationIntent);

    // how person is notified

    mbuilder.setDefaults(NotificationCompat.DEFAULT_SOUND);

    mbuilder.setAutoCancel(true); // noti dismisble when user swipe it away

    NotificationManager notificationManager = (NotificationManager)
            context.getSystemService((Context.NOTIFICATION_SERVICE));

    //    Log.i("okk", "NOTIFIED " + intent.getExtras());

    notificationManager.notify(1, mbuilder.build());  // changes from 1 to _id
       }


问:
Arabic text to speech in Xamarin not working
Hi I'm trying to develop an application that will talk to the user via text to speech. I have used the tutorials available on Xamarin website and the plugin created by James Montemagno and I can output English text to speech but whenever I ask the app to say Arabic words it goes silent.

Is Arabic TTS supported on Xamarin in either Forms, Android, or iOS?

Thanks

答: After too many searches I found that android devices not supporting Arabic TTS and you have to use paid third party to do that. </p>


问:
When to create .exe file using Java? Why it is needed?
I am looking for answers for the questions Can a java developer create an executable jar as in ".exe" file? Why it to be created and where it is used? Please brothers help me with these questions. Interviewer has asked me this questions because of these questions I got rejected. So please help me to know better about this.</p>

答:
Yeah you can transform a jar -> exe and it is mostly used to make a jar run easily on windows. If you double click a jar file it doesn't mean it has to be executed as well, but using an exe ensures this. Also you secure your jar a bit from decompiling.

But I really don't believe that such a question rejects you from a job offer ^^


问:
Why does my list reduction over gamepad timestamps result in NaN?
I have a simple reduction in JavaScript:

```<code>navigator.getGamepads().reduce((i, j) => i.timestamp * j.timestamp, 1)
</code>```

When there are no gamepads, the result is 1.

When there is one gamepad, the result is NaN.

However, the list is of number values:

```<code>navigator.getGamepads().map(x => x.timestamp)
Array [ 280868.92 ]

navigator.getGamepads().map(x => typeof x.timestamp)
Array [ "number" ]
</code>```

Why is this?

I am using Firefox 54.0 64-bit

答:
Reduce function in navigator.getGamepads().reduce((i, j) => i.timestamp * j.timestamp, 1) gets 1 as the first argument for the first iteration. timestamp property of 1 is undefined, this is why you get NaN.

You may try something like this:

navigator.getGamepads().reduce((i, j) => i.timestamp * j.timestamp, {timestamp: 1})

Body:
I have a simple reduction in JavaScript:

navigator.getGamepads().reduce((i, j) => i.timestamp * j.timestamp, 1)

When there are no gamepads, the result is 1.

When there is one gamepad, the result is NaN.

However, the list is of number values:

navigator.getGamepads().map(x => x.timestamp)
Array [ 280868.92 ]

navigator.getGamepads().map(x => typeof x.timestamp)
Array [ "number" ]

Why is this?

I am using Firefox 54.0 64-bit


问:
Webpack not recognising values defined by DefinePlugin
When webpack bundles and I launch the website, I get the following error:

*** process.env.ENV is not defined, assuming 'prod' env

However, if I log my process.env

Object {NODE_ENV: "development", ENV: "development", HOST: "localhost"}

My webpack configuration:

```<code>/*  Main */
const webpackConfig = {
  entry: [
    project.app.entry,
  ],
  output: {
    path: project.path.out,
    filename: 'bundle.js',
    publicPath: '/',
  },
  module: {
      rules: [{
        test: /\.js$/,
        include: project.path.app,
        exclude: /node_modules/,
        use: [
          { loader: 'babel-loader' },
          { loader: 'eslint-loader' },
        ],
      }],
  },
  plugins: [
    new webpack.NoEmitOnErrorsPlugin(),
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify(process.env.NODE_ENV),
        ENV: JSON.stringify(process.env.NODE_ENV),// Added because webpack bundle complains
        HOST: JSON.stringify(process.env.HOST),
      },
    }),
  ],
  devtool: DEV ? 'source-map' : false,
  resolve: {
    modules: ["src", "node_modules"],
    alias: {}
  }
};
</code>```

Is this a bug in webpack, or am I missing something? Thank you.

答:
Some people are having the same issue because of the Grammarly extension.

If you are using it, disable it and the error will be gone.

Related:

How to define process.env.ENV in create-react-app?

*** process.env.ENV is not defined, assuming 'prod' env

https://github.com/facebookincubator/create-react-app/issues/2722

Body:
When webpack bundles and I launch the website, I get the following error:

*** process.env.ENV is not defined, assuming 'prod' env

However, if I log my process.env

Object {NODE_ENV: "development", ENV: "development", HOST: "localhost"}

My webpack configuration:

/*  Main */
const webpackConfig = {
  entry: [
    project.app.entry,
  ],
  output: {
    path: project.path.out,
    filename: 'bundle.js',
    publicPath: '/',
  },
  module: {
      rules: [{
        test: /\.js$/,
        include: project.path.app,
        exclude: /node_modules/,
        use: [
          { loader: 'babel-loader' },
          { loader: 'eslint-loader' },
        ],
      }],
  },
  plugins: [
    new webpack.NoEmitOnErrorsPlugin(),
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify(process.env.NODE_ENV),
        ENV: JSON.stringify(process.env.NODE_ENV),// Added because webpack bundle complains
        HOST: JSON.stringify(process.env.HOST),
      },
    }),
  ],
  devtool: DEV ? 'source-map' : false,
  resolve: {
    modules: ["src", "node_modules"],
    alias: {}
  }
};

Is this a bug in webpack, or am I missing something? Thank you.


问:
@include a view with controller functionality - Laravel 5.4
I am working on a profile page for my web application. Within this view profile.blade.php I would like to include the view progress/index.blade.php. I have the following structure:

profile.blade.php

```<code><div class="panel panel-default">
        <div class="panel-heading clearfix">
            <h1 class="panel-title pull-left">{{ $user->name }} Progress</h1>
        </div>
        <div class="panel-body">
            @include('client.progress.index')
        </div>
</div>
</code>```

web.php

```<code>Route::group(['middleware' => ['auth', 'client'], 'prefix' => 'client', 'as' => 'client.'], function () {
    Route::get('home', 'Client\HomeController@index')->name('home');
    Route::get('profile', 'Client\UserController@profile')->name('profile');
    Route::get('progress', 'Client\UserController@progress')->name('progress.index');
});
</code>```

UserController@progress

```<code>public function progress(){

        $auth = Auth::user();
        $progressPictures = Picture::select('*')
            ->where('user_id', $auth->id)
            ->get();

        return view('client.progress.index', ['progressPictures' => $progressPictures]);
    }
</code>```

client.progress.index

```<code><p>Progress pictures</p>

@foreach($progressPictures as $progressPicture)
    <img src="/storage/uploads/progress/{{ $progressPicture }}" style="width:150px; height:150px; float:left; border-radius:50%; margin-right:25px;">
@endforeach
</code>```

When I remove the php part from the index.blade.php, the site works. but when i add the foreach loop, $progressPictures is undefined. I am not calling the UserController@progress in some way. Could some one help me with this?

答:
Change this to

```<code>return view('client.progress.index', ['progressPictures' => $progressPictures]);
</code>```

to this

```<code>return view('client.progress.index')-> with('progressPictures', $progressPictures);
</code>```

Body:
I am working on a profile page for my web application. Within this view profile.blade.php I would like to include the view progress/index.blade.php. I have the following structure:

profile.blade.php

{{ $user->name }} Progress

            @include('client.progress.index')

web.php

Route::group(['middleware' => ['auth', 'client'], 'prefix' => 'client', 'as' => 'client.'], function () {
    Route::get('home', 'Client\HomeController@index')->name('home');
    Route::get('profile', 'Client\UserController@profile')->name('profile');
    Route::get('progress', 'Client\UserController@progress')->name('progress.index');
});

UserController@progress

public function progress(){

        $auth = Auth::user();
        $progressPictures = Picture::select('*')
            ->where('user_id', $auth->id)
            ->get();

        return view('client.progress.index', ['progressPictures' => $progressPictures]);
    }

client.progress.index

Progress pictures

@foreach($progressPictures as $progressPicture)

@endforeach

When I remove the php part from the index.blade.php, the site works. but when i add the foreach loop, $progressPictures is undefined. I am not calling the UserController@progress in some way. Could some one help me with this?

Body:
Change this to

return view('client.progress.index', ['progressPictures' => $progressPictures]);

to this

return view('client.progress.index')-> with('progressPictures', $progressPictures);


问:
How to display a JSON representation and not [Object Object] on the screen
I am making an AngularJS 2 application with the beta version. I want to show a JSON representation of an object in my page, but it shows [Object Object] and not  {key1:value1 ....}

From the component I can use:

```<code>get example() {return JSON.stringify(this.myObject)};
</code>```

and then in the template:

```<code>{{example}}
</code>```

but if I have an array of objects and would like to print a list of these objects, how I can do it?

Using:

```<code><ul>
   <li *ngFor="#obj of myArray">{{obj}}</li>
</ul>
</code>```

results in something like:

```
- [Object Object]
- [Object Object]
- [Object Object]
- [Object Object]
```

and so on. Is there a way to display those as JSON?

答:
We can use angular pipe json

```<code>{{ jsonObject | json }}
</code>```

Body:
I am making an AngularJS 2 application with the beta version. I want to show a JSON representation of an object in my page, but it shows [Object Object] and not  {key1:value1 ....}

From the component I can use:

get example() {return JSON.stringify(this.myObject)};

and then in the template:

{{example}}

but if I have an array of objects and would like to print a list of these objects, how I can do it?

Using:

{{obj}}

results in something like:

- [Object Object]
- [Object Object]
- [Object Object]
- [Object Object]

and so on. Is there a way to display those as JSON?

Body:
We can use angular pipe json

{{ jsonObject | json }}


问:
WebAPI to SOAP call impersonation
We are currently working on an extension service which is used to extend SharePoint functionalities.

At the moment we do have problems on impersonation the user. We provide a REST service which calls some SharePoint SOAP methods.

Basicly UI calls the REST Service (WebAPI) which uses Windows authentication / WebAPI code then runs impersonated and then should call the SOAP (WCF) API as the impersonated user.

What we did in code is this

```<code>using (((WindowsIdentity)HttpContext.Current.User.Identity).Impersonate())
                {
                    SoapClient service = new SoapClient ();
                    service.ClientCredentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation;

....
</code>```

Currently we receive the following error :

The HTTP request is unauthorized with client authentication scheme
  'Negotiate'. The authentication header received from the server was
  'Negotiate,NTLM

Is there a trick to fix this in web.config ?

Hope you can help me out ;-) Thanks in forcast.

Kind regards.
Iki

答:
We did a lot of research and it was actually an infrastructural issue.
Due to the connection between the services “hoping” through multiple forest the impersonation fails. </p>

Title: WebAPI to SOAP call impersonation

Body:
We are currently working on an extension service which is used to extend SharePoint functionalities.

At the moment we do have problems on impersonation the user. We provide a REST service which calls some SharePoint SOAP methods.

Basicly UI calls the REST Service (WebAPI) which uses Windows authentication / WebAPI code then runs impersonated and then should call the SOAP (WCF) API as the impersonated user.

What we did in code is this

using (((WindowsIdentity)HttpContext.Current.User.Identity).Impersonate())
                {
                    SoapClient service = new SoapClient ();
                    service.ClientCredentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation;

....

Currently we receive the following error :

The HTTP request is unauthorized with client authentication scheme
  'Negotiate'. The authentication header received from the server was
  'Negotiate,NTLM

Is there a trick to fix this in web.config ?

Hope you can help me out ;-) Thanks in forcast.

Kind regards.
Iki


问:
JApplet/JPanel not receiving KeyListener events!
I cannot get my JPanel within my JApplet to receive keyboard events. I CANNOT FATHOM why!

Note that...

Clicking the panel (with mouse) before typing makes no difference. This is by far the most common advice I see given on the Net.

I have tried using the 'low-level' java.awt.KeyEventDispatcher interface. That makes no different either!

However, if I use Applet instead of JApplet, then the Applet DOES receive keyboard events. But even here, the moment I add a Panel to this Applet (the Panel is really where all my app/painting logic is), I once again stop receiving kb events (in my Panel)!

Now, I cannot simply use Applet (instead of JApplet) because, among other things, its onPaint gets a Graphics (instead of a Graphics2D object). So, #3 is NOT a solution for me.

Things work like a charm in AppletViewer that comes with JDK.

I desperately need someone's help here. Spent last 2-3 days trying all kinds of permutations I don't even recall now.

My platform details:

Firefox 3.5.3

Fedora 11 on x86 (with latest updates/patches)

Java Plugin: tried both of these, made no difference.

3.1 IcedTea Java Web Browser Plugin 1.6 (fedora-29.b16.fc11-i386)

3.2 jdk1.6.0_16/jre/plugin/i386/ns7/libjavaplugin_oji.so

Used the above jdk1.6.0_16 to compile my applet source.

Here's my code. Will greatly appreciate to hear from my fellow programmers... as I'm completely stuck!

Thanks,

/SD

```<code>import java.awt.event.*;
import java.awt.*;

import javax.swing.*;
import javax.swing.event.*;

class MyAppletKeyListener implements KeyListener, MouseListener {

  public void keyPressed(KeyEvent e) {
    System.out.println("panel:keyPressed" + e.getKeyChar());
  }
  public void keyReleased(KeyEvent e) {
  }
  public void keyTyped(KeyEvent e) {
    System.out.println("panel:keyTyped" + e.getKeyChar());
  }

  public void mouseClicked(MouseEvent e) {
    System.out.println("panel:mouseClicked");
  }
  public void mouseEntered(MouseEvent e) { }
  public void mouseExited(MouseEvent e) { }
  public void mousePressed(MouseEvent e) { }
  public void mouseReleased(MouseEvent e) { }
}

public class TestApplet extends JApplet implements MouseListener {
  public void init() {
    System.out.println("applet:init");

    MyAppletKeyListener listener = new MyAppletKeyListener();

    // Panel related
    // Note: I'd like this red panel to handle
    // all my keyboard and mouse events.
    JPanel panel = new JPanel();
    panel.setLayout(new FlowLayout());
    panel.add(new JButton("test"));
    panel.add(new JButton("test2"));
    panel.setFocusable(true);
    panel.requestFocus();
    panel.setBackground(new Color(200, 0, 0));
    panel.addKeyListener(listener);
    panel.addMouseListener(listener);

    // applet related
    // Note: Added this only for debugging. I do NOT want
    // to handle my mouse/kb events in the applet.
    addMouseListener(this);
    getContentPane().setLayout(new FlowLayout());
    getContentPane().add(panel);

  }

  public void mouseClicked(MouseEvent e) {
    System.out.println("applet:mouseClicked");
  }
  public void mouseEntered(MouseEvent e) { }
  public void mouseExited(MouseEvent e) { }
  public void mousePressed(MouseEvent e) { }
  public void mouseReleased(MouseEvent e) { }
}
</code>```

The HTML:

```<code><html>
  <head>
  </head>
  <body>
    <applet id="myApplet" code="TestApplet.class"
        width="425"
        height="150" >
    </applet>
  </body>
</html>
</code>```

答:
I found this on the net, and it solves the issue for me:

As for the fact that KeyListener does
  not work for JApplet as it does for
  Applet you should use the
  KeyEventDispatcher interface.

```<code>public class AppletMain extends JApplet implements
</code>```

java.awt.KeyEventDispatcher

Furthermore you have to set the
  KeyboardFocusManager to the Panel

```<code>KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(this);
</code>```

Afterwards override the
  dispatchKeyEvent function of the
  interface:

```<code>@Override
public boolean dispatchKeyEvent(KeyEvent e);
</code>```

This allows you to catch the KeyEvents
  as it is done with KeyListener.

Body:
I cannot get my JPanel within my JApplet to receive keyboard events. I CANNOT FATHOM why!

Note that...

Clicking the panel (with mouse) before typing makes no difference. This is by far the most common advice I see given on the Net.

I have tried using the 'low-level' java.awt.KeyEventDispatcher interface. That makes no different either!

However, if I use Applet instead of JApplet, then the Applet DOES receive keyboard events. But even here, the moment I add a Panel to this Applet (the Panel is really where all my app/painting logic is), I once again stop receiving kb events (in my Panel)!

Now, I cannot simply use Applet (instead of JApplet) because, among other things, its onPaint gets a Graphics (instead of a Graphics2D object). So, #3 is NOT a solution for me.

Things work like a charm in AppletViewer that comes with JDK.

I desperately need someone's help here. Spent last 2-3 days trying all kinds of permutations I don't even recall now.

My platform details:

Firefox 3.5.3

Fedora 11 on x86 (with latest updates/patches)

Java Plugin: tried both of these, made no difference.

3.1 IcedTea Java Web Browser Plugin 1.6 (fedora-29.b16.fc11-i386)

3.2 jdk1.6.0_16/jre/plugin/i386/ns7/libjavaplugin_oji.so

Used the above jdk1.6.0_16 to compile my applet source.

Here's my code. Will greatly appreciate to hear from my fellow programmers... as I'm completely stuck!

Thanks,

/SD

import java.awt.event.*;
import java.awt.*;

import javax.swing.*;
import javax.swing.event.*;

class MyAppletKeyListener implements KeyListener, MouseListener {

  public void keyPressed(KeyEvent e) {
    System.out.println("panel:keyPressed" + e.getKeyChar());
  }
  public void keyReleased(KeyEvent e) {
  }
  public void keyTyped(KeyEvent e) {
    System.out.println("panel:keyTyped" + e.getKeyChar());
  }

  public void mouseClicked(MouseEvent e) {
    System.out.println("panel:mouseClicked");
  }
  public void mouseEntered(MouseEvent e) { }
  public void mouseExited(MouseEvent e) { }
  public void mousePressed(MouseEvent e) { }
  public void mouseReleased(MouseEvent e) { }
}

public class TestApplet extends JApplet implements MouseListener {
  public void init() {
    System.out.println("applet:init");

    MyAppletKeyListener listener = new MyAppletKeyListener();

    // Panel related
    // Note: I'd like this red panel to handle
    // all my keyboard and mouse events.
    JPanel panel = new JPanel();
    panel.setLayout(new FlowLayout());
    panel.add(new JButton("test"));
    panel.add(new JButton("test2"));
    panel.setFocusable(true);
    panel.requestFocus();
    panel.setBackground(new Color(200, 0, 0));
    panel.addKeyListener(listener);
    panel.addMouseListener(listener);

    // applet related
    // Note: Added this only for debugging. I do NOT want
    // to handle my mouse/kb events in the applet.
    addMouseListener(this);
    getContentPane().setLayout(new FlowLayout());
    getContentPane().add(panel);

  }

  public void mouseClicked(MouseEvent e) {
    System.out.println("applet:mouseClicked");
  }
  public void mouseEntered(MouseEvent e) { }
  public void mouseExited(MouseEvent e) { }
  public void mousePressed(MouseEvent e) { }
  public void mouseReleased(MouseEvent e) { }
}

The HTML:

    <applet id="myApplet" code="TestApplet.class"
        width="425"
        height="150" >
    </applet>

Body:
I found this on the net, and it solves the issue for me:

As for the fact that KeyListener does
  not work for JApplet as it does for
  Applet you should use the
  KeyEventDispatcher interface.

public class AppletMain extends JApplet implements

java.awt.KeyEventDispatcher

Furthermore you have to set the
  KeyboardFocusManager to the Panel

KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(this);

Afterwards override the
  dispatchKeyEvent function of the
  interface:

@Override
public boolean dispatchKeyEvent(KeyEvent e);

This allows you to catch the KeyEvents
  as it is done with KeyListener.


问:
IOS8 - Calculate visible screen height when keyboard open or close
I need to calculate the visible screen height on ios8.
Means when the keyboard is open, calculate the screen height minus the keyboard height. minus the status bar, etc.

help?

答: maybe the document.documentElement.clientHeight is changed.


问:
operator precedence: ! and await
In JavaScript, how is the following statement to be interpreted:

```<code>cond1 && !await f()
</code>```

This is an excerpt from the line

```<code>if(cond1 && !await f()){
    do_stuff();
}
</code>```

inside a production application. chrome seems to be fine with it, but on ios this causes an error reading

```<code>unexpected identifier 'f'. Expected ')' to end an if condition.
</code>```

It looks as if ios turns !await f() into (!await)(f()) instead of !(await f()).

Now to my question: According to ECMA-262 what is the correct interpretation of the above line?

p.s.: We have fixed the code for ios by changing it to

```<code>var f_result = await f();
if(cond1 && !f_result){
    do_stuff();
}
</code>```

答: This has nothing to do with operator precedence. Since both are unary prefix operators, there's only a single way this expression can be interpreted - all of delete, void, typeof, +, -, ~, ! and await are parsed with the same production goal and can be arbitrarily nested. And yes, it's valid syntax in ES2017.

Title: operator precedence: ! and await

Body:
In JavaScript, how is the following statement to be interpreted:

cond1 && !await f()

This is an excerpt from the line

if(cond1 && !await f()){
    do_stuff();
}

inside a production application. chrome seems to be fine with it, but on ios this causes an error reading

unexpected identifier 'f'. Expected ')' to end an if condition.

It looks as if ios turns !await f() into (!await)(f()) instead of !(await f()).

Now to my question: According to ECMA-262 what is the correct interpretation of the above line?

p.s.: We have fixed the code for ios by changing it to

var f_result = await f();
if(cond1 && !f_result){
    do_stuff();
}


问:
How to have this kind of JSON Response formatting?
Good day. I have json response and I want to have this json format below so that I can parse it and stored it into a database. My current json response is invalid. hope you can correct my code so that I can have this kind of json response.

Expected JSON response

```<code>  {
      "login": {
          "error": false,
          "user": {
              "br_code": 12,
              "mem_id": 13,
              "username": "novalyn",
              "email": "gsac_tabaco@yahoo.com",
              "created_at": "2016-07-22 09:05:21"
          }
      },
      "accounts": {
          "error": false,
          "sl_summ": [{
                  "sl_desc": "PA : Savings Account",
                  "tr_date": "2015-08-17",
                  "actual_balance": "483.67",
                  "available_balance": "483.67"
              },
              {
                  "sl_desc": "PA : Savings - Cash Bond",
                  "tr_date": "2015-08-28",
                  "actual_balance": "10129.43",
                  "available_balance": "10129.43"
              }
          ]
      }
  }
</code>```

My current JSON format

```<code>{
    "error": false,
    "user": {
        "br_code": 12,
        "mem_id": 13,
        "username": "novalyn",
        "email": "gsac_tabaco@yahoo.com",
        "created_at": "2016-07-22 09:05:21"
    }
} {
    "error": false,
    "sl_summ": [{
        "sl_desc": "PA : Savings Account",
        "tr_date": "2015-08-17",
        "actual_balance": "483.67",
        "available_balance": "483.67"
    }, {
        "sl_desc": "PA : Savings - Cash Bond",
        "tr_date": "2015-08-28",
        "actual_balance": "10129.43",
        "available_balance": "10129.43"
    }]
}
</code>```

PHP code

```<code>$response = array("error" => FALSE);
$sl_response["error"] = FALSE;
$sl_response["sl_summ"] = array();
$user = $db->getUserByUsernameAndPassword($username, $password);

if ($user != null) {
    // user is found
    $response["error"] = FALSE;
    $response["user"]["br_code"] = $user["MEMBER_ID_BRCODE"];
    $response["user"]["mem_id"] = $user["MEMBER_ID"];
    $response["user"]["username"] = $user["USERNAME"];
    $response["user"]["email"] = $user["EMAIL"];
    $response["user"]["created_at"] = $user["REG_DATE"];
    json_encode($response, true);
    //Displaying json value
    echo json_encode($response, true);

     // FOR SL SUMM
     $user_sldtl = $db->getUserSLsummary($arclass, $loanclass, $accintreceivable, $date, $year, $month, $br_code, $clientid);

        If($user_sldtl != null) {
             for($i = 0; $i < count($user_sldtl); $i++){
                $item = array();
                    $item["sl_desc"] = $user_sldtl[$i][7];
                    $item["tr_date"] = $user_sldtl[$i][10];
                    $item["actual_balance"] = $user_sldtl[$i][14];
                    $item["available_balance"] = $user_sldtl[$i][14];

                    $response = array("error" => FALSE);
                    $sl_response["sl_summ"][] = $item;
                }
                json_encode($sl_response);
                echo json_encode($sl_response, true);
         }
         else {
             $sl_response["error"] = TRUE;
             $sl_response["error_msg"] = "NO SL Details found!";
             echo json_encode($sl_response);
         }
}
else {
    // user is not found with the credentials
    $response["error"] = TRUE;
    $response["error_msg"] = "Login credentials are wrong. Please try again!";
    json_encode($response);
    echo json_encode($response);
    // echo "<br />" .$username. "<br />";
    // echo $password;
}
</code>```

答:
I am just covering the good path use case which will generate the expected response as sample JSON payload. You would need to add similar structure for all the error scenarios.</p>

```<code>$response = array("error" => FALSE);
$sl_response["error"] = FALSE;
$sl_response["sl_summ"] = array();
$user = $db->getUserByUsernameAndPassword($username, $password);

if ($user != null) {
    // user is found
    $response["login"]["error"] = FALSE;
    $response["login"]["user"]["br_code"] = $user["MEMBER_ID_BRCODE"];
    $response["login"]["user"]["mem_id"] = $user["MEMBER_ID"];
    $response["login"]["user"]["username"] = $user["USERNAME"];
    $response["login"]["user"]["email"] = $user["EMAIL"];
    $response["login"]["user"]["created_at"] = $user["REG_DATE"];
    json_encode($response, true);
    //Displaying json value
    echo json_encode($response, true);

     // FOR SL SUMM
     $user_sldtl = $db->getUserSLsummary($arclass, $loanclass, $accintreceivable, $date, $year, $month, $br_code, $clientid);

        If($user_sldtl != null) {
             for($i = 0; $i < count($user_sldtl); $i++){
                $item = array();
                    $item["sl_desc"] = $user_sldtl[$i][7];
                    $item["tr_date"] = $user_sldtl[$i][10];
                    $item["actual_balance"] = $user_sldtl[$i][14];
                    $item["available_balance"] = $user_sldtl[$i][14];
                    $sl_response["sl_summ"][] = $item;
                }
                $response["accounts"] = $sl_response;
                json_encode(response);
                echo json_encode($response, true);
         }
         else {
             $sl_response["error"] = TRUE;
             $sl_response["error_msg"] = "NO SL Details found!";
             echo json_encode($sl_response);
         }
}
else {
    // user is not found with the credentials
    $response["error"] = TRUE;
    $response["error_msg"] = "Login credentials are wrong. Please try again!";
    json_encode($response);
    echo json_encode($response);
    // echo "<br />" .$username. "<br />";
    // echo $password;
}
</code>```

Body:
Good day. I have json response and I want to have this json format below so that I can parse it and stored it into a database. My current json response is invalid. hope you can correct my code so that I can have this kind of json response.

Expected JSON response

  {
      "login": {
          "error": false,
          "user": {
              "br_code": 12,
              "mem_id": 13,
              "username": "novalyn",
              "email": "gsac_tabaco@yahoo.com",
              "created_at": "2016-07-22 09:05:21"
          }
      },
      "accounts": {
          "error": false,
          "sl_summ": [{
                  "sl_desc": "PA : Savings Account",
                  "tr_date": "2015-08-17",
                  "actual_balance": "483.67",
                  "available_balance": "483.67"
              },
              {
                  "sl_desc": "PA : Savings - Cash Bond",
                  "tr_date": "2015-08-28",
                  "actual_balance": "10129.43",
                  "available_balance": "10129.43"
              }
          ]
      }
  }

My current JSON format

{
    "error": false,
    "user": {
        "br_code": 12,
        "mem_id": 13,
        "username": "novalyn",
        "email": "gsac_tabaco@yahoo.com",
        "created_at": "2016-07-22 09:05:21"
    }
} {
    "error": false,
    "sl_summ": [{
        "sl_desc": "PA : Savings Account",
        "tr_date": "2015-08-17",
        "actual_balance": "483.67",
        "available_balance": "483.67"
    }, {
        "sl_desc": "PA : Savings - Cash Bond",
        "tr_date": "2015-08-28",
        "actual_balance": "10129.43",
        "available_balance": "10129.43"
    }]
}

PHP code

$response = array("error" => FALSE);
$sl_response["error"] = FALSE;
$sl_response["sl_summ"] = array();
$user = $db->getUserByUsernameAndPassword($username, $password);

if ($user != null) {
    // user is found
    $response["error"] = FALSE;
    $response["user"]["br_code"] = $user["MEMBER_ID_BRCODE"];
    $response["user"]["mem_id"] = $user["MEMBER_ID"];
    $response["user"]["username"] = $user["USERNAME"];
    $response["user"]["email"] = $user["EMAIL"];
    $response["user"]["created_at"] = $user["REG_DATE"];
    json_encode($response, true);
    //Displaying json value
    echo json_encode($response, true);

     // FOR SL SUMM
     $user_sldtl = $db->getUserSLsummary($arclass, $loanclass, $accintreceivable, $date, $year, $month, $br_code, $clientid);

        If($user_sldtl != null) {
             for($i = 0; $i < count($user_sldtl); $i++){
                $item = array();
                    $item["sl_desc"] = $user_sldtl[$i][7];
                    $item["tr_date"] = $user_sldtl[$i][10];
                    $item["actual_balance"] = $user_sldtl[$i][14];
                    $item["available_balance"] = $user_sldtl[$i][14];

                    $response = array("error" => FALSE);
                    $sl_response["sl_summ"][] = $item;
                }
                json_encode($sl_response);
                echo json_encode($sl_response, true);
         }
         else {
             $sl_response["error"] = TRUE;
             $sl_response["error_msg"] = "NO SL Details found!";
             echo json_encode($sl_response);
         }
}
else {
    // user is not found with the credentials
    $response["error"] = TRUE;
    $response["error_msg"] = "Login credentials are wrong. Please try again!";
    json_encode($response);
    echo json_encode($response);
    // echo "
" .$username. "
";
    // echo $password;
}

Body:
I am just covering the good path use case which will generate the expected response as sample JSON payload. You would need to add similar structure for all the error scenarios.

$response = array("error" => FALSE);
$sl_response["error"] = FALSE;
$sl_response["sl_summ"] = array();
$user = $db->getUserByUsernameAndPassword($username, $password);

if ($user != null) {
    // user is found
    $response["login"]["error"] = FALSE;
    $response["login"]["user"]["br_code"] = $user["MEMBER_ID_BRCODE"];
    $response["login"]["user"]["mem_id"] = $user["MEMBER_ID"];
    $response["login"]["user"]["username"] = $user["USERNAME"];
    $response["login"]["user"]["email"] = $user["EMAIL"];
    $response["login"]["user"]["created_at"] = $user["REG_DATE"];
    json_encode($response, true);
    //Displaying json value
    echo json_encode($response, true);

     // FOR SL SUMM
     $user_sldtl = $db->getUserSLsummary($arclass, $loanclass, $accintreceivable, $date, $year, $month, $br_code, $clientid);

        If($user_sldtl != null) {
             for($i = 0; $i < count($user_sldtl); $i++){
                $item = array();
                    $item["sl_desc"] = $user_sldtl[$i][7];
                    $item["tr_date"] = $user_sldtl[$i][10];
                    $item["actual_balance"] = $user_sldtl[$i][14];
                    $item["available_balance"] = $user_sldtl[$i][14];
                    $sl_response["sl_summ"][] = $item;
                }
                $response["accounts"] = $sl_response;
                json_encode(response);
                echo json_encode($response, true);
         }
         else {
             $sl_response["error"] = TRUE;
             $sl_response["error_msg"] = "NO SL Details found!";
             echo json_encode($sl_response);
         }
}
else {
    // user is not found with the credentials
    $response["error"] = TRUE;
    $response["error_msg"] = "Login credentials are wrong. Please try again!";
    json_encode($response);
    echo json_encode($response);
    // echo "<br />" .$username. "<br />";
    // echo $password;
}


问:
How to for loop in userDefaults swift
I am saving data into userDeafults using 2 textfield as String, String but I want to know how to retrieve all the data to display either using loop or function </p>

```<code>    let save = UserDefaults.standard

    let heading = headingText.text
    let description = desxriptionTexr.text
    save.set(description, forKey: heading!)
</code>```

答:
Here you are setting the key as heading and the value as description.
You can retrieve the value from userDefaults using UserDefaults.standard.object(forKey:),  UserDefaults.standard.string(forKey: ),UserDefaults.standard.value(forKey: ) etc functions.

So its better to save heading and description for 2 different keys may be like

```<code>let save = UserDefaults.standard
let heading = headingText.text
let description = desxriptionTexr.text
save.set(description, forKey: "description")
save.set(heading, forKey: "heading")
</code>```

And you could retrieve like

```<code> let description = UserDefaults.standard.string(forKey:"description")
 let heading = UserDefaults.standard.string(forKey:"heading")
</code>```

Title: How to for loop in userDefaults swift

Body:
I am saving data into userDeafults using 2 textfield as String, String but I want to know how to retrieve all the data to display either using loop or function

    let save = UserDefaults.standard

    let heading = headingText.text
    let description = desxriptionTexr.text
    save.set(description, forKey: heading!)

Body:
Here you are setting the key as heading and the value as description.
You can retrieve the value from userDefaults using UserDefaults.standard.object(forKey:),  UserDefaults.standard.string(forKey: ),UserDefaults.standard.value(forKey: ) etc functions.

So its better to save heading and description for 2 different keys may be like

let save = UserDefaults.standard
let heading = headingText.text
let description = desxriptionTexr.text
save.set(description, forKey: "description")
save.set(heading, forKey: "heading")

And you could retrieve like

 let description = UserDefaults.standard.string(forKey:"description")
 let heading = UserDefaults.standard.string(forKey:"heading")


问:
What does f+++++++++ mean in rsync logs?
I'm using rsync to make a backup of my server files, and I have two questions:

In the middle of the process I need to stop and start rsync again.

Will rsync start from the point where it stopped or it will restart from the beginning?

In the log files I see "f+++++++++". What does it mean?

e.g.:

```<code>2010/12/21 08:28:37 [4537] >f.st...... iddd/logs/website-production-access_log
2010/12/21 08:29:11 [4537] >f.st...... iddd/web/website/production/shared/log/production.log
2010/12/21 08:29:14 [4537] .d..t...... iddd/web/website/production/shared/sessions/
2010/12/21 08:29:14 [4537] >f+++++++++ iddd/web/website/production/shared/sessions/ruby_sess.017a771cc19b18cd
2010/12/21 08:29:14 [4537] >f+++++++++ iddd/web/website/production/shared/sessions/ruby_sess.01eade9d317ca79a
</code>```

答:
1.) It will "restart the sync", but it will not transfer files that are the same size and timestamp etc.  It first builds up a list of files to transfer and during this stage it will see that it has already transferred some files and will skip them.  You should tell rsync to preserve the timestamps etc. (e.g. using rsync -a ...)

While rsync is transferring a file, it will call it something like .filename.XYZABC instead of filename.  Then when it has finished transferring that file it will rename it.  So, if you kill rsync while it is transferring a large file, you will have to use the --partial option to continue the transfer instead of starting from scratch.

2.) I don't know what that is.  Can you paste some examples?

EDIT: As per http://ubuntuforums.org/showthread.php?t=1342171 those codes are defined in the rsync man page in section for the the -i, --itemize-changes option.

Fixed part if my answer based on Joao's

ContentLicense: CC BY-SA 4.0

Body:
I'm using rsync to make a backup of my server files, and I have two questions:

In the middle of the process I need to stop and start rsync again.

Will rsync start from the point where it stopped or it will restart from the beginning?

In the log files I see "f+++++++++". What does it mean?

e.g.:

2010/12/21 08:28:37 [4537] >f.st...... iddd/logs/website-production-access_log
2010/12/21 08:29:11 [4537] >f.st...... iddd/web/website/production/shared/log/production.log
2010/12/21 08:29:14 [4537] .d..t...... iddd/web/website/production/shared/sessions/
2010/12/21 08:29:14 [4537] >f+++++++++ iddd/web/website/production/shared/sessions/ruby_sess.017a771cc19b18cd
2010/12/21 08:29:14 [4537] >f+++++++++ iddd/web/website/production/shared/sessions/ruby_sess.01eade9d317ca79a


问:
Java Collections by user input
In java collections
I should get user input as integers and sort it in Ascending order.</p>

```<code>import java.util.*;
import java.io.*;
class ArrayToCollection{

 public static void main(String args[]) throws IOException{

      BufferedReader in = new BufferedReader
      (new InputStreamReader(System.in));
      System.out.println("How many elements you want to add to the array: ");
      int n = Integer.parseInt(in.readLine());
      int[] num = new int[n];
      for(int i = 0; i < n; i++){
         num[i] = in.readLine();
      }
     TreeSet<String> setA =new TreeSet<String>();
     setA.add(num);
     System.out.println(setA.contains(num));
    }
}
</code>```

答:
```<code>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.TreeSet;

class ArrayToCollection{

public static void main(String args[]) throws IOException{

 BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
 System.out.println("How many elements you want to add to the array: ");
 int n = Integer.parseInt(in.readLine());
 System.out.println("enter numbers : ");
 TreeSet<Integer> setA = new TreeSet<Integer>();
 for (int i = 0; i < n; i++) {
     setA.add(Integer.parseInt(in.readLine()));
 }

 System.out.println(setA.toString());
}
}
</code>```

Title: Java Collections by user input

Body:
In java collections
I should get user input as integers and sort it in Ascending order.

import java.util.*;
import java.io.*;
class ArrayToCollection{

 public static void main(String args[]) throws IOException{

      BufferedReader in = new BufferedReader
      (new InputStreamReader(System.in));
      System.out.println("How many elements you want to add to the array: ");
      int n = Integer.parseInt(in.readLine());
      int[] num = new int[n];
      for(int i = 0; i < n; i++){
         num[i] = in.readLine();
      }
     TreeSet<String> setA =new TreeSet<String>();
     setA.add(num);
     System.out.println(setA.contains(num));
    }
}


问:
(click)="foo()" is not working in data table
Here is my following code of datatable

```<code>datatable [options]="{
   colReorder: true,
   ajax: 'assets/api/tables/admin-list.json',
   columns: [
      {data: 'id'},
      {data: 'name'},
      {data: 'username'},
      {data: 'adminRole'},
      {data: 'siteId'},
      {defaultContent: '<button **(click)=\'foo()\'**>Edit</button>'},
      {defaultContent: '<button>Delete</button>'}
  ]}"
  paginationLength="true"
  tableClass="table table-striped table-bordered table-hover"
  width="100%">
</code>```

In this code, angular click event is not bind

I am stuck in this part
Any solution ..?

答:
That won't work because angular cannot bound to click because the code is being generated on the fly and Angular's compiler doesn't compile it as a Angular component , it would become normal html (string).

Your best solution would be to use <button onCLick="foo()"> in a normal javascript way.

Or you could assign a class to them and then use addEventListener to those classes.

```<code> <button class="myButtons">
</code>```

Inside your component class :

```<code>ngAfterViewInit(){

   document.getElementsBytClassName('myButtons').addEventListener('click',foo)
}
</code>```

Otherwise you must go in the direction of using viewContainer and loading the buttons as a template dynamically and that can be really painful.

Body:
Here is my following code of datatable

datatable [options]="{
   colReorder: true,
   ajax: 'assets/api/tables/admin-list.json',
   columns: [
      {data: 'id'},
      {data: 'name'},
      {data: 'username'},
      {data: 'adminRole'},
      {data: 'siteId'},
      {defaultContent: '<button **(click)=\'foo()\'**>Edit</button>'},
      {defaultContent: '<button>Delete</button>'}
  ]}"
  paginationLength="true"
  tableClass="table table-striped table-bordered table-hover"
  width="100%">

In this code, angular click event is not bind

I am stuck in this part
Any solution ..?

Body:
That won't work because angular cannot bound to click because the code is being generated on the fly and Angular's compiler doesn't compile it as a Angular component , it would become normal html (string).

Your best solution would be to use <button onCLick="foo()"> in a normal javascript way.

Or you could assign a class to them and then use addEventListener to those classes.

 <button class="myButtons">

Inside your component class :

ngAfterViewInit(){

   document.getElementsBytClassName('myButtons').addEventListener('click',foo)
}

Otherwise you must go in the direction of using viewContainer and loading the buttons as a template dynamically and that can be really painful.


问:
My devise User model custom field username always nil. I have tried all the other solutions on stack overflow
My application controller file

```<code>  class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
  before_action :configure_permitted_parameters, if: :devise_controller?

  protected
  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up)  {|u| u.permit(:username, :email, :password, :password_confirmation, :remember_me)}
    devise_parameter_sanitizer.permit(:sign_in)  {|u| u.permit(:username, :email, :password, :password_confirmation, :remember_me)}
    devise_parameter_sanitizer.permit(:account_update) {|u| u.permit(:email, :password, :password_confirmation, :remember_me)}
  end
end
</code>```

My routes.rb file

```<code>Rails.application.routes.draw do
  devise_for :users

  root 'pages#index'

  get 'home' => 'pages#home'

  get 'profile' => 'pages#profile'

  get 'explore' => 'pages#explore'

end
</code>```

My migration files

```<code>class DeviseCreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      ## Database authenticatable
      t.string :email,              null: false, default: ""
      t.string :encrypted_password, null: false, default: ""

      ## Recoverable
      t.string   :reset_password_token
      t.datetime :reset_password_sent_at

      ## Rememberable
      t.datetime :remember_created_at

      ## Trackable
      t.integer  :sign_in_count, default: 0, null: false
      t.datetime :current_sign_in_at
      t.datetime :last_sign_in_at
      t.string   :current_sign_in_ip
      t.string   :last_sign_in_ip

      ## Confirmable
      # t.string   :confirmation_token
      # t.datetime :confirmed_at
      # t.datetime :confirmation_sent_at
      # t.string   :unconfirmed_email # Only if using reconfirmable

      ## Lockable
      # t.integer  :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
      # t.string   :unlock_token # Only if unlock strategy is :email or :both
      # t.datetime :locked_at

      t.timestamps null: false
    end

    add_index :users, :email,                unique: true
    add_index :users, :reset_password_token, unique: true
    # add_index :users, :confirmation_token,   unique: true
    # add_index :users, :unlock_token,         unique: true
  end
end
</code>```

My add username column migration

```<code>class AddUsernameToUsers < ActiveRecord::Migration
  def change
    add_column :users, :username, :string
    add_index :users, :username, unique: true
  end
end
</code>```

My views/devise/registrations/new.html.erb

```<code><%= bootstrap_devise_error_messages! %>
<div class="panel panel-default devise-bs">
  <div class="panel-heading">
    <h4><%= t('.sign_up', default: 'Sign up') %></h4>
  </div>
  <div class="panel-body">
    <%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { role: 'form' }) do |f| %>
      <div class="form-group">
        <%= f.label :username %>
        <%= f.text_field :email, autofocus: true, class: 'form-control' %>
      </div>
      <div class="form-group">
        <%= f.label :email %>
        <%= f.email_field :email, class: 'form-control' %>
      </div>
      <div class="form-group">
        <%= f.label :password %>
        <%= f.password_field :password, class: 'form-control' %>
      </div>
      <div class="form-group">
        <%= f.label :password_confirmation %>
        <%= f.password_field :password_confirmation, class: 'form-control' %>
      </div>
      <%= f.submit t('.sign_up', default: 'Sign up'), class: 'btn btn-primary' %>
    <% end %>
  </div>
</div>
<%= render 'devise/shared/links' %>
</code>```

So even after using strong parameters when the usernames being added through browser are not reflected back in the database.

It gives this result

```<code>irb(main):001:0> u = User.all
  User Load (20.0ms)  SELECT "users".* FROM "users"
=> #<ActiveRecord::Relation [#<User id: 1, email: "testuser@test.com", created_at: "2017-07-05 19:42:19", updated_at: "2017-07-05 21:11:38", username: nil>, #<User id: 2, email: "ajha@test.com", created_at: "2017-07-06 08:45:18", updated_at: "2017-07-06 08:45:18", username: nil>, #<User id: 3, email: "akasd@test.com", created_at: "2017-07-06 08:56:15", updated_at: "2017-07-06 08:56:15", username: nil>, #<User id: 4, email: "rcontest@test.com", created_at: "2017-07-06 09:23:55", updated_at: "2017-07-06 09:23:55", username: nil>]>
</code>```

Any help will be appreciated. Also tell me if you need to see any other files.

答:
you did not specify username attribute in the form

add username in the form

```<code>    <div class="form-group">
    <%= f.label :username %>
    <%= f.text_field :username, autofocus: true, class: 'form-control' %>
  </div>
  <div class="form-group">
    <%= f.label :email %>
    <%= f.email_field :email, class: 'form-control' %>
  </div>
</code>```

Body:
My application controller file

  class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
  before_action :configure_permitted_parameters, if: :devise_controller?

  protected
  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up)  {|u| u.permit(:username, :email, :password, :password_confirmation, :remember_me)}
    devise_parameter_sanitizer.permit(:sign_in)  {|u| u.permit(:username, :email, :password, :password_confirmation, :remember_me)}
    devise_parameter_sanitizer.permit(:account_update) {|u| u.permit(:email, :password, :password_confirmation, :remember_me)}
  end
end

My routes.rb file

Rails.application.routes.draw do
  devise_for :users

  root 'pages#index'

  get 'home' => 'pages#home'

  get 'profile' => 'pages#profile'

  get 'explore' => 'pages#explore'

end

My migration files

class DeviseCreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      ## Database authenticatable
      t.string :email,              null: false, default: ""
      t.string :encrypted_password, null: false, default: ""

      ## Recoverable
      t.string   :reset_password_token
      t.datetime :reset_password_sent_at

      ## Rememberable
      t.datetime :remember_created_at

      ## Trackable
      t.integer  :sign_in_count, default: 0, null: false
      t.datetime :current_sign_in_at
      t.datetime :last_sign_in_at
      t.string   :current_sign_in_ip
      t.string   :last_sign_in_ip

      ## Confirmable
      # t.string   :confirmation_token
      # t.datetime :confirmed_at
      # t.datetime :confirmation_sent_at
      # t.string   :unconfirmed_email # Only if using reconfirmable

      ## Lockable
      # t.integer  :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
      # t.string   :unlock_token # Only if unlock strategy is :email or :both
      # t.datetime :locked_at

      t.timestamps null: false
    end

    add_index :users, :email,                unique: true
    add_index :users, :reset_password_token, unique: true
    # add_index :users, :confirmation_token,   unique: true
    # add_index :users, :unlock_token,         unique: true
  end
end

My add username column migration

class AddUsernameToUsers < ActiveRecord::Migration
  def change
    add_column :users, :username, :string
    add_index :users, :username, unique: true
  end
end

My views/devise/registrations/new.html.erb

<%= bootstrap_devise_error_messages! %>

<%= t('.sign_up', default: 'Sign up') %>

    <%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { role: 'form' }) do |f| %>

        <%= f.label :username %>
        <%= f.text_field :email, autofocus: true, class: 'form-control' %>

        <%= f.label :email %>
        <%= f.email_field :email, class: 'form-control' %>

        <%= f.label :password %>
        <%= f.password_field :password, class: 'form-control' %>

        <%= f.label :password_confirmation %>
        <%= f.password_field :password_confirmation, class: 'form-control' %>

      <%= f.submit t('.sign_up', default: 'Sign up'), class: 'btn btn-primary' %>
    <% end %>

<%= render 'devise/shared/links' %>

So even after using strong parameters when the usernames being added through browser are not reflected back in the database.

It gives this result

irb(main):001:0> u = User.all
  User Load (20.0ms)  SELECT "users".* FROM "users"
=> #<ActiveRecord::Relation [#<User id: 1, email: "testuser@test.com", created_at: "2017-07-05 19:42:19", updated_at: "2017-07-05 21:11:38", username: nil>, #<User id: 2, email: "ajha@test.com", created_at: "2017-07-06 08:45:18", updated_at: "2017-07-06 08:45:18", username: nil>, #<User id: 3, email: "akasd@test.com", created_at: "2017-07-06 08:56:15", updated_at: "2017-07-06 08:56:15", username: nil>, #<User id: 4, email: "rcontest@test.com", created_at: "2017-07-06 09:23:55", updated_at: "2017-07-06 09:23:55", username: nil>]>

Any help will be appreciated. Also tell me if you need to see any other files.

Body:
you did not specify username attribute in the form

add username in the form

    <div class="form-group">
    <%= f.label :username %>
    <%= f.text_field :username, autofocus: true, class: 'form-control' %>
  </div>
  <div class="form-group">
    <%= f.label :email %>
    <%= f.email_field :email, class: 'form-control' %>
  </div>


问:
Spring Security hasPermission for Collection<Object>
I have working application secured with method-level security:

RestController:

```<code>@PreAuthorize("hasPermission(#product, 'WRITE')")
@RequestMapping(value = "/save", method = RequestMethod.POST)
public Product save(@RequestBody Product product) {
    return productService.save(product);
}
</code>```

PermissionEvaluator:

```<code>public class SecurityPermissionEvaluator implements PermissionEvaluator {

    private Logger log = LoggerFactory.getLogger(SecurityPermissionEvaluator.class);

    private final PermissionService permissionService;

    public SecurityPermissionEvaluator(PermissionService permissionService) {
        this.permissionService = permissionService;
    }

    @Override
    public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
        CustomUserDetails userDetails = (CustomUserDetails) authentication.getPrincipal();
        return permissionService.isAuthorized(userDetails.getUser(), targetDomainObject, permission.toString());
    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) {
        // almost the same implementation
    }
}
</code>```

And everything works fine until I implemented API which saves collection of objects. The logic of this service is to update existing entities and/or create new entities.

```<code>@PreAuthorize("hasPermission(#products, 'WRITE')")
@RequestMapping(value = "/saveCollection", method = RequestMethod.POST)
public Collection<Product> save(@RequestBody Collection<Product> products) {
    return productService.save(products);
}
</code>```

After this my permission service handles the collection object and looks like this now:

PemissionService:

```<code>public class PermissionService {

    public boolean isAuthorized(User user, Object targetDomainObject, String permission) {
        if (targetDomainObject instanceof TopAppEntity) {
            if (((TopAppEntity) targetDomainObject).getId() == null) {
                // check authorities and give response
            } else {
                // check ACL and give response
            }
        } else if(targetDomainObject instanceof Collection) {
            boolean isAuthorized = false;
            Collection targetDomainObjects = (Collection) targetDomainObject;
            for (Object targetObject : targetDomainObjects) {
                isAuthorized = isAuthorized(user, targetObject, permission);
                if (!isAuthorized) break;
            }
            return isAuthorized;
        }
    }
}
</code>```

My question is:

How I can handle collections using @PreAuthorize("hasPermission(#object, '...')") more elegant way? Is there some implementations in Spring Security for handling collections? At least, how can I optimize PemissionService for handling Collections?

答:
You can use the @PreFilter annotation.

So @PreFilter("hasPermission(filterTarget, '...')") will call your PermissionService for each element of the Collection.

```<code>public class PermissionService() {

    public boolean isAuthorized(User user, Object targetDomainObject, String permission) {
        if (targetDomainObject instanceof TopAppEntity) {
            if (((TopAppEntity) targetDomainObject).getId() == null) {
                // check authorities and give response
            } else {
                // check ACL and give response
            }
        }
    }
}
</code>```

Note: this will not prevent a call of your controller method. It only gets an empty Collection.

Body:
I have working application secured with method-level security:

RestController:

@PreAuthorize("hasPermission(#product, 'WRITE')")
@RequestMapping(value = "/save", method = RequestMethod.POST)
public Product save(@RequestBody Product product) {
    return productService.save(product);
}

PermissionEvaluator:

public class SecurityPermissionEvaluator implements PermissionEvaluator {

    private Logger log = LoggerFactory.getLogger(SecurityPermissionEvaluator.class);

    private final PermissionService permissionService;

    public SecurityPermissionEvaluator(PermissionService permissionService) {
        this.permissionService = permissionService;
    }

    @Override
    public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
        CustomUserDetails userDetails = (CustomUserDetails) authentication.getPrincipal();
        return permissionService.isAuthorized(userDetails.getUser(), targetDomainObject, permission.toString());
    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) {
        // almost the same implementation
    }
}

And everything works fine until I implemented API which saves collection of objects. The logic of this service is to update existing entities and/or create new entities.

@PreAuthorize("hasPermission(#products, 'WRITE')")
@RequestMapping(value = "/saveCollection", method = RequestMethod.POST)
public Collection<Product> save(@RequestBody Collection<Product> products) {
    return productService.save(products);
}

After this my permission service handles the collection object and looks like this now:

PemissionService:

public class PermissionService {

    public boolean isAuthorized(User user, Object targetDomainObject, String permission) {
        if (targetDomainObject instanceof TopAppEntity) {
            if (((TopAppEntity) targetDomainObject).getId() == null) {
                // check authorities and give response
            } else {
                // check ACL and give response
            }
        } else if(targetDomainObject instanceof Collection) {
            boolean isAuthorized = false;
            Collection targetDomainObjects = (Collection) targetDomainObject;
            for (Object targetObject : targetDomainObjects) {
                isAuthorized = isAuthorized(user, targetObject, permission);
                if (!isAuthorized) break;
            }
            return isAuthorized;
        }
    }
}

My question is:

How I can handle collections using @PreAuthorize("hasPermission(#object, '...')") more elegant way? Is there some implementations in Spring Security for handling collections? At least, how can I optimize PemissionService for handling Collections?

Body:
You can use the @PreFilter annotation.

So @PreFilter("hasPermission(filterTarget, '...')") will call your PermissionService for each element of the Collection.

public class PermissionService() {

    public boolean isAuthorized(User user, Object targetDomainObject, String permission) {
        if (targetDomainObject instanceof TopAppEntity) {
            if (((TopAppEntity) targetDomainObject).getId() == null) {
                // check authorities and give response
            } else {
                // check ACL and give response
            }
        }
    }
}

Note: this will not prevent a call of your controller method. It only gets an empty Collection.


问:
Are the attribution requirements for the premium version of the Google Places API different?
Are the attribution requirements for the premium version of the Google Places API different from the free one?

Specifically, does the premium version of the autocomplete version of the Places API require an attribution to Google to be shown ?

答:
This question can probably only be answered by Google Maps API Sales, best to ask them.

From what I could find, I suspect the answer will be Yes. See the Google Maps API - Purchase Agreement which apply on top of the more general Google Maps APIs Terms of Service.


问:
Getting Information from Req.User() into Req.params() in ExpressJS
After people log into my Express app, I'd like to redirect them to a url that reads:

```<code>www.mysite.com/:user
</code>```

What I'm having trouble with is that my req.params object is coming up as an empty object literal when people get re-directed after logging in.

Ideally what I'd like to do is to somehow take the information stored in req.user and pass some of that information into the URL.

So basically I'd like to get from here:

```<code>router.post('/login',
passport.authenticate('local', {successRedirect:'/', failureRedirect: '/login', failureFlash: true}));
</code>```

To here:

```<code>router.get('/:user', function(req, res) {
    //stuff
}
</code>```

After logging in the req.user object reads like this:

```<code>{
  username: joesmith@mail.com,
  name: Joe Smith,
  password:  dkei348#$kDL^583L,
  formulas: []
}
</code>```

And the code I'm attempting to use is as follows:

```<code>router.get('/:user', function(req, res) {
var user = req.user.name;
req.params = {
  "user": user
}
</code>```

But this doesn't work because initially req.user.name is undefined if someone isn't already logged in, so I can't get past the console error.

Apparently I don't understand how req.params is generated in enough detail to get around this problem.

Thank you.

答:
If you want to have username in parameters you shoud redirect to '/' + req.user.name); because '/' doesn't have any params. That's why it is undefined. (additionaly you shoud check if parameter is defined and handle the error, so instead of console error you get error 404 or get to next, proper routing path).

Passport Documentation privides examples of doiung it:

```<code>app.post('/login',
  passport.authenticate('local'),
  function(req, res) {
    // If this function gets called, authentication was successful.
    // `req.user` contains the authenticated user.
    res.redirect('/' + req.username);
  });
</code>```

or more complex custom callback :

```<code>app.get('/login', function(req, res, next) {
  passport.authenticate('local', function(err, user, info) {
    if (err) { return next(err); }
    if (!user) { return res.redirect('/login'); }
    req.logIn(user, function(err) {
      if (err) { return next(err); }
      return res.redirect('/' + user.name);
    });
  })(req, res, next);
});
</code>```

But I think it is not a good practice and safer would be to redirect to the proper page/content by req.user value without putting it to URL, for example setting req.auth. and then using next(); instead of res.redirect('/' + user.name); to get to the next middleware. There username would be taken from req.auth.username, not from /:username.

How does the structure of your routing looks? You shoud make sure router.get('/:user' .. is not before router.get('/login'...

Body:
After people log into my Express app, I'd like to redirect them to a url that reads:

www.mysite.com/:user

What I'm having trouble with is that my req.params object is coming up as an empty object literal when people get re-directed after logging in.

Ideally what I'd like to do is to somehow take the information stored in req.user and pass some of that information into the URL.

So basically I'd like to get from here:

router.post('/login',
passport.authenticate('local', {successRedirect:'/', failureRedirect: '/login', failureFlash: true}));

To here:

router.get('/:user', function(req, res) {
    //stuff
}

After logging in the req.user object reads like this:

{
  username: joesmith@mail.com,
  name: Joe Smith,
  password:  dkei348#$kDL^583L,
  formulas: []
}

And the code I'm attempting to use is as follows:

router.get('/:user', function(req, res) {
var user = req.user.name;
req.params = {
  "user": user
}

But this doesn't work because initially req.user.name is undefined if someone isn't already logged in, so I can't get past the console error.

Apparently I don't understand how req.params is generated in enough detail to get around this problem.

Thank you.

Body:
If you want to have username in parameters you shoud redirect to '/' + req.user.name); because '/' doesn't have any params. That's why it is undefined. (additionaly you shoud check if parameter is defined and handle the error, so instead of console error you get error 404 or get to next, proper routing path).

Passport Documentation privides examples of doiung it:

app.post('/login',
  passport.authenticate('local'),
  function(req, res) {
    // If this function gets called, authentication was successful.
    // `req.user` contains the authenticated user.
    res.redirect('/' + req.username);
  });

or more complex custom callback :

app.get('/login', function(req, res, next) {
  passport.authenticate('local', function(err, user, info) {
    if (err) { return next(err); }
    if (!user) { return res.redirect('/login'); }
    req.logIn(user, function(err) {
      if (err) { return next(err); }
      return res.redirect('/' + user.name);
    });
  })(req, res, next);
});

But I think it is not a good practice and safer would be to redirect to the proper page/content by req.user value without putting it to URL, for example setting req.auth. and then using next(); instead of res.redirect('/' + user.name); to get to the next middleware. There username would be taken from req.auth.username, not from /:username.

How does the structure of your routing looks? You shoud make sure router.get('/:user' .. is not before router.get('/login'...


问:
How do I embed javascript in clojure Hiccup?
I'm writing a webserver app in clojure with Hiccup (and other things).
I'm trying to have a check-box enable and disable two drop-down fields with a little JS but I can't make it work.</p>

```<code>[:head
[:script "function toggleText(cb, t1, t2) {
    document.getElementById(t1).disabled = !cb.checked;
    document.getElementById(t2).disabled = !cb.checked;
}"]]

[:td (hf/check-box {:on-change (str "toggleText(" (name endtag) "," (name tytag) "," (name tmtag) ")")} endtag)]
[:td (hf/drop-down tytag (range 2013 2031) 2017)]
[:td (hf/drop-down tmtag (range 1 13) 6)]
</code>```

答:
Thanks Aleph, your fix together with adding getElementById for the cb parameter in the function did the trick!

The function now looks like this

```<code>[:script "function toggleText(cb, t1, t2) {
    document.getElementById(t1).disabled = !document.getElementById(cb).checked;
    document.getElementById(t2).disabled = !document.getElementById(cb).checked;}"]
</code>```

And I simplified the Hiccup code too (not passing the tags as parameters) so it looks like this

```<code>[:td (hf/check-box {:onclick (str "toggleText('endtag','toyear','tomonth')")} :endtag (some? (:toyear m)))]
[:td (hf/drop-down :toyear (range 2013 2031))]
[:td (hf/drop-down :tomonth (range 1 13))]
</code>```

Body:
I'm writing a webserver app in clojure with Hiccup (and other things).
I'm trying to have a check-box enable and disable two drop-down fields with a little JS but I can't make it work.

[:head
[:script "function toggleText(cb, t1, t2) {
    document.getElementById(t1).disabled = !cb.checked;
    document.getElementById(t2).disabled = !cb.checked;
}"]]

[:td (hf/check-box {:on-change (str "toggleText(" (name endtag) "," (name tytag) "," (name tmtag) ")")} endtag)]
[:td (hf/drop-down tytag (range 2013 2031) 2017)]
[:td (hf/drop-down tmtag (range 1 13) 6)]

Body:
Thanks Aleph, your fix together with adding getElementById for the cb parameter in the function did the trick!

The function now looks like this

[:script "function toggleText(cb, t1, t2) {
    document.getElementById(t1).disabled = !document.getElementById(cb).checked;
    document.getElementById(t2).disabled = !document.getElementById(cb).checked;}"]

And I simplified the Hiccup code too (not passing the tags as parameters) so it looks like this

[:td (hf/check-box {:onclick (str "toggleText('endtag','toyear','tomonth')")} :endtag (some? (:toyear m)))]
[:td (hf/drop-down :toyear (range 2013 2031))]
[:td (hf/drop-down :tomonth (range 1 13))]


问:
Looking for a solution to add Video/Voice call for my cordova app?
I need to do Video/Voice call over my app if users connect with same WiFi?</p>

答:
Here the link for reference :

https://quickblox.com/blog/quickblox-unveils-apache-cordova-phonegap-chat-and-video-calling-webrtc-code-samples/