问:
Laravel 'with' and nested relation
I am retrieving some relationship:

```<code>$requirements = Requirement::with([
            'countryMatch',
            'applier',
            'doc' ])->get();
</code>```

and my model Requirements contains:

```<code>public function doc()
{
    return $this->belongsTo(Doc::class);
}
</code>```

Right now all fine.

Since my Doc model has its own relationship:

```<code>public function translation($language = null)
{
    if ($language == null) {
        $language = /*App::getLocale()*/'en';
    }
    return $this->hasMany('App\DocTranslation')->where('language', '=', $language);
}
</code>```

I would like to retrieve this relationship direct in the first 'with' statement, something like this:

```<code>$requirements = Requirement::with([
        'countryMatch',
        'applier',
        'doc->translation()' ])->get();
</code>```

but I receive error:

```<code>Call to undefined relationship [doc->translation()] on model [App\Requirement].
</code>```

That's because relation translation is in Doc model not in Requirement.

答:
for a nested relationship use dot like announcement.advertiser

$requirements = Requirement::with([
            'countryMatch',
            'applier',
            'doc',
            'doc.translation'])->get();

Title: Laravel 'with' and nested relation

Body:
I am retrieving some relationship:

$requirements = Requirement::with([
            'countryMatch',
            'applier',
            'doc' ])->get();

and my model Requirements contains:

public function doc()
{
    return $this->belongsTo(Doc::class);
}

Right now all fine.

Since my Doc model has its own relationship:

public function translation($language = null)
{
    if ($language == null) {
        $language = /*App::getLocale()*/'en';
    }
    return $this->hasMany('App\DocTranslation')->where('language', '=', $language);
}

I would like to retrieve this relationship direct in the first 'with' statement, something like this:

$requirements = Requirement::with([
        'countryMatch',
        'applier',
        'doc->translation()' ])->get();

but I receive error:

Call to undefined relationship [doc->translation()] on model [App\Requirement].

That's because relation translation is in Doc model not in Requirement.


来源: stackexchange

问:
fx:deploy with nativeBundles = image does not let me run the executable from folder containing special characters
On windows: I create a build with ant from IntelliJ and that when run from folder called "š" does not run anything. When I run directly the jar everything works fine.

On mac: The executable .app build can be run but System.getProperty("user.dir") returns the path wrongly (the special chars are wrong), again if the jar is run directly, the path is alright.

```<code><fx:application id="SId" name="s" mainClass="packageName"/>
      <fx:jar destfile="${artifact.temp.output.mainJar}/S.jar">
      <fx:application refid="SId"/>
      <fileset dir="${artifact.temp.output.mainJar}" excludes="**/*.jar"/>
      <fx:resources>
          <fx:fileset dir="${artifact.temp.output.mainJar}" includes="**/*.jar" />
      </fx:resources>
      <fx:platform javafx="2.1+">
          <fx:property name="file.encoding" value="UTF-8"/>
      </fx:platform>
    <manifest/>
  </fx:jar>

  <fx:deploy width="600" height="400" updatemode="background" outdir="${artifact.temp.output.mainJar}/deploy" outfile="S" nativeBundles="image">
      <fx:application refid="SId"/>
      <fx:resources>
          <fx:fileset dir="${artifact.temp.output.mainJar}" includes="**/*.jar"/>
      </fx:resources>
      <fx:info>
      <fx:icon href="${basedir}/build_scripts/${iconFileName}" />
      </fx:info>
      <fx:platform javafx="2.1+">
          <fx:property name="file.encoding" value="UTF-8"/>
      </fx:platform>
  </fx:deploy>
</code>```

答:
This is a known problem, which already got reported one the JDK.

JDK-8133034 launcher crashes if started with non english arguments

JDK-8138642 Generated bundle is not executable when main class contains unicode

Since this is a general problem with the native executables, and both issues being open for that long (because it involves C++ and unicode-problems), there is no quick solution for this.

Funny part: I was checking for this today as some issue-cleanup on the javafx-maven-plugin project: https://github.com/javafx-maven-plugin/javafx-maven-plugin/issues/209

ContentLicense: CC BY-SA 3.0

Body:
On windows: I create a build with ant from IntelliJ and that when run from folder called "š" does not run anything. When I run directly the jar everything works fine.

On mac: The executable .app build can be run but System.getProperty("user.dir") returns the path wrongly (the special chars are wrong), again if the jar is run directly, the path is alright.

<fx:application id="SId" name="s" mainClass="packageName"/>
      <fx:jar destfile="${artifact.temp.output.mainJar}/S.jar">
      <fx:application refid="SId"/>
      <fileset dir="${artifact.temp.output.mainJar}" excludes="**/*.jar"/>
      <fx:resources>
          <fx:fileset dir="${artifact.temp.output.mainJar}" includes="**/*.jar" />
      </fx:resources>
      <fx:platform javafx="2.1+">
          <fx:property name="file.encoding" value="UTF-8"/>
      </fx:platform>
    <manifest/>
  </fx:jar>

  <fx:deploy width="600" height="400" updatemode="background" outdir="${artifact.temp.output.mainJar}/deploy" outfile="S" nativeBundles="image">
      <fx:application refid="SId"/>
      <fx:resources>
          <fx:fileset dir="${artifact.temp.output.mainJar}" includes="**/*.jar"/>
      </fx:resources>
      <fx:info>
      <fx:icon href="${basedir}/build_scripts/${iconFileName}" />
      </fx:info>
      <fx:platform javafx="2.1+">
          <fx:property name="file.encoding" value="UTF-8"/>
      </fx:platform>
  </fx:deploy>


问:
Convert json_objects to array
I have this query

```<code>SELECT json_object('image_name', image_name, 'iid', iid)
FROM `posts_images`
WHERE `pid` = '62'
</code>```

That result in this

Image:

can I convert these result into one line JSON array in same query?

答:
```<code>var o = {"0":"1","1":"2","2":"3","3":"4"};

var arr = $.map(o, function(el) { return el; })

console.log(arr)
</code>```

Try this

ContentLicense: CC BY-SA 4.0

Title: Convert json_objects to array

Body:
I have this query

SELECT json_object('image_name', image_name, 'iid', iid)
FROM `posts_images`
WHERE `pid` = '62'

That result in this

Image:

can I convert these result into one line JSON array in same query?

Body:
var o = {"0":"1","1":"2","2":"3","3":"4"};

var arr = $.map(o, function(el) { return el; })

console.log(arr)

Try this


问:
Getting error in Firebase one to one chat app Notifications
I have made a one to one chat app and I have implemented chat notifications but when I am sending notifications from the user app to the doctor app but my doctor app crashes as soon as I am clicking on the chat notification

This is my Java class where I am handling the notification if my app is in foreground so this class will handle notifications so now in this class I am calling firebase database and taking some data from there and passing that data as an extra data with the resulting intent but when that resulting intent directs the app to the particular chat view that database  data is not there

This is the Log of my app

```<code>E/MyFirebaseMessaging: From:408315985482
07-05 16:19:33.803 4399-6278/com.tech.pritz.bemoprovider D/MyFirebaseMessaging: in between Firebase and auth
07-05 16:19:33.805 4399-6278/com.tech.pritz.bemoprovider D/MyFirebaseMessaging: Message data payload: {idRe, username=komal , message=hi}
07-05 16:19:33.805 4399-6278/com.tech.pritz.bemoprovider D/MyFirebaseMessaging: app in background
07-05 16:19:33.813 4399-6278/com.tech.pritz.bemoprovider E/MyFirebaseMessaging: image not found
07-05 16:19:33.825 4399-6278/com.tech.pritz.bemoprovider D/NotificationUtil: New Message

D/MyFirebaseMessaging: Entered into the database

07-05 16:19:34.359 4399-4399/com.tech.pritz.bemoprovider D/MyFirebaseMessaging: HKNi1sezUpbwJSeEGos44FtfUw43
</code>```

You can see here it is showing entered in the database also and it is getting that data also but when I pass it as an intent it is not found in another activity.

Crash log

Caused by: java.lang.NullPointerException: Attempt to invoke virtual
  method 'java.lang.String
  com.tech.pritz.bemoprovider.model.Provider.getId()' on a null object
  reference at
  com.tech.pritz.bemoprovider.bemo.ChatView.ini(ChatView.java:350) at
  com.tech.pritz.bemoprovider.bemo.ChatView.onCreate(ChatView.java:150)

```<code>  public class MyFirebaseMessaging extends FirebaseMessagingService
    {

        private  static  final String TAG=MyFirebaseMessaging.class.getSimpleName();
        private NotificationUtil notificationUtil;
        private DatabaseReference pathFirebase;
        private FirebaseAuth auth;
        private Provider mprovider;

        @Override
        public void onMessageReceived(RemoteMessage remoteMessage)
        {
            Log.e(TAG,"From:"+ remoteMessage.getFrom());
            pathFirebase = FirebaseDatabase.getInstance().getReference();
            Log.d(TAG,"in between Firebase and auth");
            auth = FirebaseAuth.getInstance();

            if(remoteMessage ==null )
            {
                return;

            }
            //check if message contains a notification payload
            if(remoteMessage.getNotification()!=null)
            {
                String tittle = remoteMessage.getNotification().getTitle();
                Log.e(TAG,"Notification Body:" + remoteMessage.getNotification().getBody());
                handleNotification(remoteMessage.getNotification().getBody(),tittle,null, mprovider);
            }
            //checks to see if message contains a data payload
            if(remoteMessage.getData().size() > 0)
            {
                Log.d(TAG, "Message data payload: " + remoteMessage.getData());
               String imageUrl = remoteMessage.getData().get("image");
              //  String message =  remoteMessage.getData().get("message");
               // String title = remoteMessage.getData().get("title");
               // String name = remoteMessage.getData().get("username");

               String message= remoteMessage.getData().get("message");
                String name= remoteMessage.getData().get("username");
                String title= "New Message";
                String iduser= remoteMessage.getData().get("iduser");
                String email=  remoteMessage.getData().get("email");
                String gcm_id=  remoteMessage.getData().get("idGCM");
                String conversation_id=remoteMessage.getData().get("conversation_id");

                Log.d(TAG,"app in background");

                pathFirebase.child("users").child(auth.getCurrentUser().getUid())
                        .addValueEventListener(
                                new ValueEventListener() {
                                    @Override
                                    public void onDataChange(DataSnapshot dataSnapshot) {

                                        if (dataSnapshot.exists()) {
                                            Log.d(TAG,"Entered into the database");
                                            mprovider = dataSnapshot.getValue(Provider.class);
                                            UserDataHolder.getInstance().setmName(mprovider.getName());
                                            // Intent intent = new Intent(MyFirebaseMessaging.this, ListPatients.class);
                                            mprovider.setId(auth.getCurrentUser().getUid());
                                            UserDataHolder.getInstance().setmUserId(mprovider.getId());
                                            // intent.putExtra("user", provider);
                                            //startActivity(intent);
                                            //finish();
                                            Log.d(TAG,mprovider.getId());
                                        }
                                    }
                                    @Override
                                    public void onCancelled(DatabaseError databaseError) {

                                        Toast.makeText(MyFirebaseMessaging.this, "Failed", Toast.LENGTH_SHORT).show();
                                    }
                                });

    //            Log.d(TAG,mprovider.getId());
                // app is in background, show the notification in notification tray
                Intent resultIntent = new Intent(getApplicationContext(),ChatView.class);
                resultIntent.putExtra("user_id", iduser);
                resultIntent.putExtra("email", email);
                resultIntent.putExtra("User_display_name",name);
                resultIntent.putExtra("user_gcm_id",gcm_id);
                resultIntent.putExtra("conversation_id",conversation_id);
               // resultIntent.putExtra("providerLocal",mprovider);

                resultIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                //  resultIntent.putExtra("message", message);

                // check for image attachment
                if (TextUtils.isEmpty(imageUrl))
                {
                    Log.e(TAG,"image not found");
                    showNotificationMessage(getApplicationContext(), title, message,name,resultIntent,mprovider);
                }
                else
                {
                    // image is present, show notification with image
                    Log.e(TAG,"image found");
                    showNotificationMessageWithBigImage(getApplicationContext(), title, message, resultIntent, imageUrl);
                }
            }

        }

        private void handleNotification(String message,String title,String name,Provider provider)
        {

            if(!NotificationUtil.isAppInBackground(getApplicationContext()))
            {
                Intent resultIntent = new Intent(getApplicationContext(), ChatView.class);
                showNotificationMessage(getApplicationContext(), title, message,null,resultIntent, provider);

            }
            else
            {
                Intent resultIntent = new Intent(getApplicationContext(), ChatView.class);
                showNotificationMessage(getApplicationContext(), title, message,null,resultIntent, mprovider);

            }
        }

        private void showNotificationMessageWithBigImage(Context applicationContext, String title, String message, Intent resultIntent, String imageUrl)
        {
            notificationUtil = new NotificationUtil(applicationContext);
            resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            notificationUtil.showNotificationMessage(title, message,null,resultIntent,imageUrl);

        }

        private void showNotificationMessage(Context applicationContext, String title, String message,String name, Intent resultIntent,Provider mprovider)
        {
           // Log.d(TAG,mprovider.getId());
            notificationUtil = new NotificationUtil(applicationContext);
            resultIntent.putExtra("providerLocal",mprovider);
            // resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            notificationUtil.showNotificationMessage(title, message,name,resultIntent);

        }

    }
</code>```

答:
the problem is in this line :

```<code>UserDataHolder.getInstance().setmUserId(mprovider.getId());
</code>```

the mprovider object is null

Body:
I have made a one to one chat app and I have implemented chat notifications but when I am sending notifications from the user app to the doctor app but my doctor app crashes as soon as I am clicking on the chat notification

This is my Java class where I am handling the notification if my app is in foreground so this class will handle notifications so now in this class I am calling firebase database and taking some data from there and passing that data as an extra data with the resulting intent but when that resulting intent directs the app to the particular chat view that database  data is not there

This is the Log of my app

E/MyFirebaseMessaging: From:408315985482
07-05 16:19:33.803 4399-6278/com.tech.pritz.bemoprovider D/MyFirebaseMessaging: in between Firebase and auth
07-05 16:19:33.805 4399-6278/com.tech.pritz.bemoprovider D/MyFirebaseMessaging: Message data payload: {idRe, username=komal , message=hi}
07-05 16:19:33.805 4399-6278/com.tech.pritz.bemoprovider D/MyFirebaseMessaging: app in background
07-05 16:19:33.813 4399-6278/com.tech.pritz.bemoprovider E/MyFirebaseMessaging: image not found
07-05 16:19:33.825 4399-6278/com.tech.pritz.bemoprovider D/NotificationUtil: New Message

D/MyFirebaseMessaging: Entered into the database

07-05 16:19:34.359 4399-4399/com.tech.pritz.bemoprovider D/MyFirebaseMessaging: HKNi1sezUpbwJSeEGos44FtfUw43

You can see here it is showing entered in the database also and it is getting that data also but when I pass it as an intent it is not found in another activity.

Crash log

Caused by: java.lang.NullPointerException: Attempt to invoke virtual
  method 'java.lang.String
  com.tech.pritz.bemoprovider.model.Provider.getId()' on a null object
  reference at
  com.tech.pritz.bemoprovider.bemo.ChatView.ini(ChatView.java:350) at
  com.tech.pritz.bemoprovider.bemo.ChatView.onCreate(ChatView.java:150)

  public class MyFirebaseMessaging extends FirebaseMessagingService
    {

        private  static  final String TAG=MyFirebaseMessaging.class.getSimpleName();
        private NotificationUtil notificationUtil;
        private DatabaseReference pathFirebase;
        private FirebaseAuth auth;
        private Provider mprovider;

        @Override
        public void onMessageReceived(RemoteMessage remoteMessage)
        {
            Log.e(TAG,"From:"+ remoteMessage.getFrom());
            pathFirebase = FirebaseDatabase.getInstance().getReference();
            Log.d(TAG,"in between Firebase and auth");
            auth = FirebaseAuth.getInstance();

            if(remoteMessage ==null )
            {
                return;

            }
            //check if message contains a notification payload
            if(remoteMessage.getNotification()!=null)
            {
                String tittle = remoteMessage.getNotification().getTitle();
                Log.e(TAG,"Notification Body:" + remoteMessage.getNotification().getBody());
                handleNotification(remoteMessage.getNotification().getBody(),tittle,null, mprovider);
            }
            //checks to see if message contains a data payload
            if(remoteMessage.getData().size() > 0)
            {
                Log.d(TAG, "Message data payload: " + remoteMessage.getData());
               String imageUrl = remoteMessage.getData().get("image");
              //  String message =  remoteMessage.getData().get("message");
               // String title = remoteMessage.getData().get("title");
               // String name = remoteMessage.getData().get("username");

               String message= remoteMessage.getData().get("message");
                String name= remoteMessage.getData().get("username");
                String title= "New Message";
                String iduser= remoteMessage.getData().get("iduser");
                String email=  remoteMessage.getData().get("email");
                String gcm_id=  remoteMessage.getData().get("idGCM");
                String conversation_id=remoteMessage.getData().get("conversation_id");

                Log.d(TAG,"app in background");

                pathFirebase.child("users").child(auth.getCurrentUser().getUid())
                        .addValueEventListener(
                                new ValueEventListener() {
                                    @Override
                                    public void onDataChange(DataSnapshot dataSnapshot) {

                                        if (dataSnapshot.exists()) {
                                            Log.d(TAG,"Entered into the database");
                                            mprovider = dataSnapshot.getValue(Provider.class);
                                            UserDataHolder.getInstance().setmName(mprovider.getName());
                                            // Intent intent = new Intent(MyFirebaseMessaging.this, ListPatients.class);
                                            mprovider.setId(auth.getCurrentUser().getUid());
                                            UserDataHolder.getInstance().setmUserId(mprovider.getId());
                                            // intent.putExtra("user", provider);
                                            //startActivity(intent);
                                            //finish();
                                            Log.d(TAG,mprovider.getId());
                                        }
                                    }
                                    @Override
                                    public void onCancelled(DatabaseError databaseError) {

                                        Toast.makeText(MyFirebaseMessaging.this, "Failed", Toast.LENGTH_SHORT).show();
                                    }
                                });

    //            Log.d(TAG,mprovider.getId());
                // app is in background, show the notification in notification tray
                Intent resultIntent = new Intent(getApplicationContext(),ChatView.class);
                resultIntent.putExtra("user_id", iduser);
                resultIntent.putExtra("email", email);
                resultIntent.putExtra("User_display_name",name);
                resultIntent.putExtra("user_gcm_id",gcm_id);
                resultIntent.putExtra("conversation_id",conversation_id);
               // resultIntent.putExtra("providerLocal",mprovider);

                resultIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                //  resultIntent.putExtra("message", message);

                // check for image attachment
                if (TextUtils.isEmpty(imageUrl))
                {
                    Log.e(TAG,"image not found");
                    showNotificationMessage(getApplicationContext(), title, message,name,resultIntent,mprovider);
                }
                else
                {
                    // image is present, show notification with image
                    Log.e(TAG,"image found");
                    showNotificationMessageWithBigImage(getApplicationContext(), title, message, resultIntent, imageUrl);
                }
            }

        }

        private void handleNotification(String message,String title,String name,Provider provider)
        {

            if(!NotificationUtil.isAppInBackground(getApplicationContext()))
            {
                Intent resultIntent = new Intent(getApplicationContext(), ChatView.class);
                showNotificationMessage(getApplicationContext(), title, message,null,resultIntent, provider);

            }
            else
            {
                Intent resultIntent = new Intent(getApplicationContext(), ChatView.class);
                showNotificationMessage(getApplicationContext(), title, message,null,resultIntent, mprovider);

            }
        }

        private void showNotificationMessageWithBigImage(Context applicationContext, String title, String message, Intent resultIntent, String imageUrl)
        {
            notificationUtil = new NotificationUtil(applicationContext);
            resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            notificationUtil.showNotificationMessage(title, message,null,resultIntent,imageUrl);

        }

        private void showNotificationMessage(Context applicationContext, String title, String message,String name, Intent resultIntent,Provider mprovider)
        {
           // Log.d(TAG,mprovider.getId());
            notificationUtil = new NotificationUtil(applicationContext);
            resultIntent.putExtra("providerLocal",mprovider);
            // resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            notificationUtil.showNotificationMessage(title, message,name,resultIntent);

        }

    }

Body:
the problem is in this line :

UserDataHolder.getInstance().setmUserId(mprovider.getId());

the mprovider object is null


问:
git clone all remote branches
I have a repository in github with X number of branches and a repository in a closed network.

I need to move all of the repository to the one on the closed network. How do I clone all the branches (not just the default master), so I could then push it to the closed-network one with all the branches existing.

Entering the repo binary is not the issue here.

I want the same result as if I cloned my repo and did git branch to each branch, so it would be initialized locally.

答:
There's a git-clone option --mirror which sets up all remotely tracked branches. But, --mirror also implies --bare option, ie. the clone will will not be created as a working copy and you cannot checkout the branches. Therefore the directory is changed to a working directory afterwards.

```<code>$ git clone --mirror original-repo.git /path/cloned-directory/.git
$ cd /path/cloned-directory
$ git config --bool core.bare false
$ git checkout anybranch
</code>```

Git FAQ: How do I clone a repository with all remotely tracked branches?

Title: git clone all remote branches

Body:
There's a git-clone option --mirror which sets up all remotely tracked branches. But, --mirror also implies --bare option, ie. the clone will will not be created as a working copy and you cannot checkout the branches. Therefore the directory is changed to a working directory afterwards.

$ git clone --mirror original-repo.git /path/cloned-directory/.git
$ cd /path/cloned-directory
$ git config --bool core.bare false
$ git checkout anybranch

Git FAQ: How do I clone a repository with all remotely tracked branches?


问:
Extract given columns from a matrix based on a vector in Matlab
I have this matrix:

```<code>A = [2 3 5; 1 7 8; 4 9 1; 6 2 6]
</code>```

and this vector:

```<code>b = [1 0 1 0]
</code>```

And I would like to get this matrix:

```<code>C = [2 3 5; 4 9 1]
</code>```

Thanks for your answers.

答:
you can do the following using find method</p>

```<code>C = A(:,find(b))
</code>```

Body:
I have this matrix:

A = [2 3 5; 1 7 8; 4 9 1; 6 2 6]

and this vector:

b = [1 0 1 0]

And I would like to get this matrix:

C = [2 3 5; 4 9 1]

Thanks for your answers.

Body:
you can do the following using find method

C = A(:,find(b))


问:
Boolean false echoes an empty string
I've tried everything! I'm trying to find if the user "sales administrator" is allowed in the string. I've tried exploding the string & putting it in an array, i've tried strpos (in code below), preg match and even if (strpos($userAllowedString, $userRole) > -1). The result is always empty. The result should be false, but it's not giving back anything.

```<code>$userAllowedString = "Sales Manager,Sales Director,Project Manager,Developer";
$userRole = "Sales Administrator";

if(strpos($userAllowedString,$userRole) !== false) {
     $userAllowed= true;
} else {
     $userAllowed = false;
}
</code>```

Any advice?

答:
Try to use the value like 'true' or 'false' not the true or false. Because true or false without the quote itself represent empty string.

```<code>$userAllowedString = "Sales Manager,Sales Director,Project Manager,Developer";
$userRole = "Sales Administrator";
$userAllowedString = explode(',', $userAllowedString);

if(in_array($userRole, $userAllowedString)) {
     $userAllowed= 'true';
} else {
     $userAllowed = 'false';
}
echo $userAllowed; //false
</code>```

Working example: https://3v4l.org/Zkg9b

Title: Boolean false echoes an empty string

Body:
I've tried everything! I'm trying to find if the user "sales administrator" is allowed in the string. I've tried exploding the string & putting it in an array, i've tried strpos (in code below), preg match and even if (strpos($userAllowedString, $userRole) > -1). The result is always empty. The result should be false, but it's not giving back anything.

$userAllowedString = "Sales Manager,Sales Director,Project Manager,Developer";
$userRole = "Sales Administrator";

if(strpos($userAllowedString,$userRole) !== false) {
     $userAllowed= true;
} else {
     $userAllowed = false;
}

Any advice?

Body:
Try to use the value like 'true' or 'false' not the true or false. Because true or false without the quote itself represent empty string.

$userAllowedString = "Sales Manager,Sales Director,Project Manager,Developer";
$userRole = "Sales Administrator";
$userAllowedString = explode(',', $userAllowedString);

if(in_array($userRole, $userAllowedString)) {
     $userAllowed= 'true';
} else {
     $userAllowed = 'false';
}
echo $userAllowed; //false

Working example: https://3v4l.org/Zkg9b


问:
separating number from date in Pandas columns
I have a column in pandas that include 100 rows like the following:

```<code>timeseries

2000-05-01 10:00:00+00:00   0.9
</code>```

it's only the index and I want to separate datetime with the number, and have two columns like:

```<code>time                                        number

2000-05-01 10:00:00+00:00                    0.9
</code>```

I tried :

```<code>df['start'] = mydata.str.split(' ').str.get(0)
df['end'] =   mydata.str.split(' ').str.get(1)
</code>```

but the answer is like:

```<code>                         timeseries     start  end
2017-05-01 10:00:00+00:00   0.9          0.9    NaN
</code>```

How can I separate the index as date and the number columns?

答:
In the example you have posted, there are three spaces between time and number part. In that case,

```<code>df[['timeseries', 'number']] = df.timeseries.str.extract('(.*)\s{3}(.*)')
</code>```

If you know that there are two or more spaces between time and number,

```<code>df[['timeseries', 'number']] = df.timeseries.str.extract('(.*)\s\s+(.*)')
</code>```

For a more generic case,

```<code>df['number'] = df.timeseries.str.split('\s+').str[-1]
df['timeseries'] = df.timeseries.str.split('\s+').str[:-1].apply(' '.join)
</code>```

In all the cases you get,

```<code>    timeseries                  number
0   2000-05-01 10:00:00+00:00   0.9
</code>```

Body:
I have a column in pandas that include 100 rows like the following:

timeseries

2000-05-01 10:00:00+00:00   0.9

it's only the index and I want to separate datetime with the number, and have two columns like:

time                                        number

2000-05-01 10:00:00+00:00                    0.9

I tried :

df['start'] = mydata.str.split(' ').str.get(0)
df['end'] =   mydata.str.split(' ').str.get(1)

but the answer is like:

                         timeseries     start  end
2017-05-01 10:00:00+00:00   0.9          0.9    NaN

How can I separate the index as date and the number columns?

Body:
In the example you have posted, there are three spaces between time and number part. In that case,

df[['timeseries', 'number']] = df.timeseries.str.extract('(.*)\s{3}(.*)')

If you know that there are two or more spaces between time and number,

df[['timeseries', 'number']] = df.timeseries.str.extract('(.*)\s\s+(.*)')

For a more generic case,

df['number'] = df.timeseries.str.split('\s+').str[-1]
df['timeseries'] = df.timeseries.str.split('\s+').str[:-1].apply(' '.join)

In all the cases you get,

    timeseries                  number
0   2000-05-01 10:00:00+00:00   0.9


问:
Does upgrading jQuery UI 1.7.2 to 1.8.7 result in a performance improvement?
My site is only using dialogs and buttons from jQuery UI. In general things are working fine, but from time to time some users are facing light performance issues; the system is not as responsive as it should be in their opinion.

Upgrading from jQuery 1.4.2 to 1.4.4 really did a good job, because there are lots of find()/filter() calls in my code. Should I expect some performance benefits from upgrading jQuery UI?

答:
There are a couple things to think about with respect to upgrading a library.

How difficult is it going to be to do so. Many times, if it is a minor release upgrade, you're not going to see any API changes or anything of that nature. It should be a fairly smooth process to perform the upgrade. In this case, I don't see any reason why you wouldn't perform the upgrade.

In the case of going to a more major release, you need to consider the API changes that could cause the upgrade to a new version of a library to take longer. It may not be just a simple idea of "drop in the new library and you're good to go." With that said, I typically try to keep my libraries as up-to-date as possible. Yeah, it may be slightly more work now, but, in the long run, it is easier to upgrade a library on a continual basis than do it once every 5 years.

As for the type of performance improvements you'll see if you upgrade to 1.8.7, check out the release notes. Not only t should you see improvements, you should also have more feature availability as well.

With all this said...

Many times, performance improvements are better affected if the code using the libraries is improved. Better algorithms, better use of structures, etc can show MUCH better improvements than just upgrading a library. I would look into this along with looking at upgrading the jQueryUI library.

ContentLicense: CC BY-SA 2.5


问:
QnAMaker QnA format support
I have not been able to use the auto import for QnAMaker successfully for several, differently-formatted, docx and sharepoint-based web faqs.

I see support for TSV called out in several places and wonder if there are examples of working docx formatted documents or web page formats that work?

The help content provided with qnamkaer states that markdown is supported. I am also seeking a guide to specific syntax supported.

答:
The QnAMaker FAQ states that it should work with this format:

```<code>.txt, .docx, .pdf: QnA contained as regular FAQ content, i.e. sequence of questions and answers.
</code>```

I got it to work with a .txt file; Just start with a question followed by the answer. Seperate them with a comma and a space, just like a normal sentence (i.e. as shown in the above example). Start a new question on a new line. Easy as that.

Title: QnAMaker QnA format support

Body:
The QnAMaker FAQ states that it should work with this format:

.txt, .docx, .pdf: QnA contained as regular FAQ content, i.e. sequence of questions and answers.

I got it to work with a .txt file; Just start with a question followed by the answer. Seperate them with a comma and a space, just like a normal sentence (i.e. as shown in the above example). Start a new question on a new line. Easy as that.


问:
What are these various settings in Charles proxy?
Screenshot of Charles proxy throttle setting

Can anyone describe them in layman terms?

答:
I've never used this option in Charles Proxy, but I did on Chrome.
"Throttling" has to do with regulating network speed, so by this feature you can simulate poorer connection speed, as if connecting with 2G, 3G or so.
This is useful to detect problems that only arise when timeouts occur, for example.
(please note that, obviously, you will not be able to simulate higher speeds than the one provided by your ISP)</p>


问:
overlap not working using JavaScript in Phaser
I am making a game and in this game I want when the player overlaps with the coin, the coin disappears, but its not for some reason and I don't why. I have tried a lot of ways even putting the coin into a tile when I made the map but even then it still doesn't work.

Can anyone help me out please?

```<code> var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', {
 preload: preload, create: create, update: update, render: render });

 function preload() {
game.load.tilemap('level12', 'res/level12.json', null,
Phaser.Tilemap.TILED_JSON);
game.load.image('sprite12', 'res/sprite12.png');
game.load.spritesheet('dude', 'res/player.png', 64, 64);
game.load.spritesheet('droid', 'res/droid.png', 32, 32);
game.load.image('starSmall', 'res/star.png');
game.load.spritesheet('coin', 'res/coin.png',32,32 );
game.load.image('background', 'res/sprite3.png');

}

var map;
var tileset;
var layer;
var player;
var facing = 'left';
var jumpTimer = 0;
var cursors;
var jumpButton;
var bg;
var coin;

function create() {
game.physics.startSystem(Phaser.Physics.ARCADE);
game.stage.backgroundColor = '#000000';

bg = game.add.tileSprite(0, 0, 800, 600, 'background');
bg.fixedToCamera = true;

map = game.add.tilemap('level12');
map.addTilesetImage('sprite12');
map.addTilesetImage('coin');
map.setCollisionBetween(1, 12);
map.setCollisionByExclusion([ 13, 14, 15, 16, 46, 47, 48, 49, 50, 51 ]);

layer = map.createLayer('Tile Layer 1');
layer.resizeWorld();

coin = game.add.group();
coin.enableBody = true;
coin.physicsBodyType = Phaser.Physics.ARCADE;
createcoin();

game.physics.arcade.gravity.y = 200;

player = game.add.sprite(150, 900, 'dude');

game.physics.enable(player, Phaser.Physics.ARCADE);

player.body.bounce.y = 0.2;

player.body.collideWorldBounds = true;

player.animations.add('left', [3,2,1,0], 10, true);
player.animations.add('right', [4,5,6,7], 10, true);

game.camera.follow(player);

cursors = game.input.keyboard.createCursorKeys();
jumpButton = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);

game.physics.arcade.overlap(coin, player, killcoin(), null, this);

}
function killcoin(coin,player) {

coin.kill();
}

function  createcoin() {
coin = game.add.sprite(50,700, 'coin');
}

function update() {

game.physics.arcade.collide(player, layer);

player.body.velocity.x = 0;

if (cursors.left.isDown) {
    player.body.velocity.x = -150;

    if (facing != 'left') {
        player.animations.play('left');
        facing = 'left';
    }
}
else if (cursors.right.isDown) {
    player.body.velocity.x = 150;

    if (facing != 'right') {
        player.animations.play('right');
        facing = 'right';
    }
}
else {
    if (facing != 'idle') {
        player.animations.stop();

        if (facing == 'left') {
            player.frame = 0;
        }
        else {
            player.frame = 5;
        }

        facing = 'idle';
    }
}

if (jumpButton.isDown && player.body.onFloor() && game.time.now > jumpTimer) {
    player.body.velocity.y = -250;
    jumpTimer = game.time.now + 750;
}
}

function render () {

}
</code>```

答:
There are three problems in your code. First of all the naming of the variables is confusing. You're creating a group and assigning it to coin but you're also adding new sprites and assigning them to coin. So then what is the value of coin when calling the overlap function? Maybe this works correctly on a technical level, but just to avoid any confusion I would use different variable names for different things. If nothing else it makes your code more readable.

Secondly, the coin sprites that are added to the game in createcoin() aren't added to the group. And because it is not added to the group, the physics body of the sprite is never enabled.

Finally, the arcade.overlap function is called only once in create(). I think it should be called in the update() function. The update() function in Phaser.js is kind of the main game loop. It is called for every frame update.

So put those three fixes all together and I would try something like this:

```<code>grpcoins = game.add.group();
grpcoins.enableBody = true;
grpcoins.physicsBodyType = Phaser.Physics.ARCADE;
//..

function  createcoin() {
    var c = game.add.sprite(50,700, 'coin');
    grpcoins.add(c);
}

function update() {
   //..
   game.physics.arcade.overlap(player, grpcoins, killcoin, null, this);
   //..
}

function killcoin(pl, cn) {
    cn.kill();
}
</code>```

Body:
I am making a game and in this game I want when the player overlaps with the coin, the coin disappears, but its not for some reason and I don't why. I have tried a lot of ways even putting the coin into a tile when I made the map but even then it still doesn't work.

Can anyone help me out please?

 var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', {
 preload: preload, create: create, update: update, render: render });

 function preload() {
game.load.tilemap('level12', 'res/level12.json', null,
Phaser.Tilemap.TILED_JSON);
game.load.image('sprite12', 'res/sprite12.png');
game.load.spritesheet('dude', 'res/player.png', 64, 64);
game.load.spritesheet('droid', 'res/droid.png', 32, 32);
game.load.image('starSmall', 'res/star.png');
game.load.spritesheet('coin', 'res/coin.png',32,32 );
game.load.image('background', 'res/sprite3.png');

}

var map;
var tileset;
var layer;
var player;
var facing = 'left';
var jumpTimer = 0;
var cursors;
var jumpButton;
var bg;
var coin;

function create() {
game.physics.startSystem(Phaser.Physics.ARCADE);
game.stage.backgroundColor = '#000000';

bg = game.add.tileSprite(0, 0, 800, 600, 'background');
bg.fixedToCamera = true;

map = game.add.tilemap('level12');
map.addTilesetImage('sprite12');
map.addTilesetImage('coin');
map.setCollisionBetween(1, 12);
map.setCollisionByExclusion([ 13, 14, 15, 16, 46, 47, 48, 49, 50, 51 ]);

layer = map.createLayer('Tile Layer 1');
layer.resizeWorld();

coin = game.add.group();
coin.enableBody = true;
coin.physicsBodyType = Phaser.Physics.ARCADE;
createcoin();

game.physics.arcade.gravity.y = 200;

player = game.add.sprite(150, 900, 'dude');

game.physics.enable(player, Phaser.Physics.ARCADE);

player.body.bounce.y = 0.2;

player.body.collideWorldBounds = true;

player.animations.add('left', [3,2,1,0], 10, true);
player.animations.add('right', [4,5,6,7], 10, true);

game.camera.follow(player);

cursors = game.input.keyboard.createCursorKeys();
jumpButton = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);

game.physics.arcade.overlap(coin, player, killcoin(), null, this);

}
function killcoin(coin,player) {

coin.kill();
}

function  createcoin() {
coin = game.add.sprite(50,700, 'coin');
}

function update() {

game.physics.arcade.collide(player, layer);

player.body.velocity.x = 0;

if (cursors.left.isDown) {
    player.body.velocity.x = -150;

    if (facing != 'left') {
        player.animations.play('left');
        facing = 'left';
    }
}
else if (cursors.right.isDown) {
    player.body.velocity.x = 150;

    if (facing != 'right') {
        player.animations.play('right');
        facing = 'right';
    }
}
else {
    if (facing != 'idle') {
        player.animations.stop();

        if (facing == 'left') {
            player.frame = 0;
        }
        else {
            player.frame = 5;
        }

        facing = 'idle';
    }
}

if (jumpButton.isDown && player.body.onFloor() && game.time.now > jumpTimer) {
    player.body.velocity.y = -250;
    jumpTimer = game.time.now + 750;
}
}

function render () {

}

Body:
There are three problems in your code. First of all the naming of the variables is confusing. You're creating a group and assigning it to coin but you're also adding new sprites and assigning them to coin. So then what is the value of coin when calling the overlap function? Maybe this works correctly on a technical level, but just to avoid any confusion I would use different variable names for different things. If nothing else it makes your code more readable.

Secondly, the coin sprites that are added to the game in createcoin() aren't added to the group. And because it is not added to the group, the physics body of the sprite is never enabled.

Finally, the arcade.overlap function is called only once in create(). I think it should be called in the update() function. The update() function in Phaser.js is kind of the main game loop. It is called for every frame update.

So put those three fixes all together and I would try something like this:

grpcoins = game.add.group();
grpcoins.enableBody = true;
grpcoins.physicsBodyType = Phaser.Physics.ARCADE;
//..

function  createcoin() {
    var c = game.add.sprite(50,700, 'coin');
    grpcoins.add(c);
}

function update() {
   //..
   game.physics.arcade.overlap(player, grpcoins, killcoin, null, this);
   //..
}

function killcoin(pl, cn) {
    cn.kill();
}


问:
How to maintain login session in ios?
I would like to know where I need to change the root view controller in the app programming. Below is my code

```<code>class NavigationViewController: UINavigationController {

var window: UIWindow?

override func viewDidLoad() {
    super.viewDidLoad()

    let storyBoard = UIStoryboard(name: "Main", bundle: nil)
    let newRootView = storyBoard.instantiateViewController(withIdentifier: "WelcomeViewController") as! WelcomeViewController
    let userStatus = UserDefaults.standard.bool(forKey: "isLoggedIn")
    if userStatus {
        self.window?.rootViewController = newRootView
    }

  }
}
</code>```

I am setting the value for isLoggedIn key as true when user logged in and false when the user logged out so that I can retrieve the value in this navigation controller subclass, based on that I can choose the root view controller. But its not working fine it remains the same whenever I am launching the app I am getting the login page only though I already logged in, also please don't suggest me to change the root view controller inside of didfinishlaunchingwithoptions method. Could someone help me to solve it? Thanks in advance.

答:
If I understand correctly the goal of your code, you want to boot directly on WelcomeViewController if the user is already logged in.

You could try to create a custom segue called ReplaceSegue and set this ReplaceSegue to the segue linking the NavigationViewController and the ViewController.

And then you can change the destination of your segue.

```<code>class ReplaceSegue: UIStoryboardSegue {

    override func perform() {
        let storyBoard = UIStoryboard(name: "Main", bundle: nil)
        let newRootView = storyBoard.instantiateViewController(withIdentifier: "WelcomeViewController") as! WelcomeViewController
        sourceViewController.navigationController?.setViewControllers([newRootView], animated: true)
    }
}
</code>```

Title: How to maintain login session in ios?

Body:
I would like to know where I need to change the root view controller in the app programming. Below is my code

class NavigationViewController: UINavigationController {

var window: UIWindow?

override func viewDidLoad() {
    super.viewDidLoad()

    let storyBoard = UIStoryboard(name: "Main", bundle: nil)
    let newRootView = storyBoard.instantiateViewController(withIdentifier: "WelcomeViewController") as! WelcomeViewController
    let userStatus = UserDefaults.standard.bool(forKey: "isLoggedIn")
    if userStatus {
        self.window?.rootViewController = newRootView
    }

  }
}

I am setting the value for isLoggedIn key as true when user logged in and false when the user logged out so that I can retrieve the value in this navigation controller subclass, based on that I can choose the root view controller. But its not working fine it remains the same whenever I am launching the app I am getting the login page only though I already logged in, also please don't suggest me to change the root view controller inside of didfinishlaunchingwithoptions method. Could someone help me to solve it? Thanks in advance.

Body:
If I understand correctly the goal of your code, you want to boot directly on WelcomeViewController if the user is already logged in.

You could try to create a custom segue called ReplaceSegue and set this ReplaceSegue to the segue linking the NavigationViewController and the ViewController.

And then you can change the destination of your segue.

class ReplaceSegue: UIStoryboardSegue {

    override func perform() {
        let storyBoard = UIStoryboard(name: "Main", bundle: nil)
        let newRootView = storyBoard.instantiateViewController(withIdentifier: "WelcomeViewController") as! WelcomeViewController
        sourceViewController.navigationController?.setViewControllers([newRootView], animated: true)
    }
}


问:
Horizontal scroller in CSS
I have been trying to add a scroller to my context section that will only allow the box to scroll horizontally within the visible of the viewer's screen, not vertical.

Does anyone know any code to have scrollable content in a div in a fluid css layout design?

Also, here is a link to a website that has the exact scroll effect I am trying to recreate: http://patrickhoelck.com/home.html

答:
You probably want to take a look at overflow-x: scroll, which, along with setting a fixed size on the parent, will force a horizontal scrollbar if the content is too wide.

Some example html:

```<code><div style="width: 50px; overflow-x: scroll">
    <p>Hello world!</p>
    <p>Here is a div with a horizontal scrollbar!</p>
</div>
</code>```

OwnerDisplayName: R Herod

Title: Horizontal scroller in CSS

LastEditorDisplayName: R Herod

Body:
You probably want to take a look at overflow-x: scroll, which, along with setting a fixed size on the parent, will force a horizontal scrollbar if the content is too wide.

Some example html:

<div style="width: 50px; overflow-x: scroll">
    <p>Hello world!</p>
    <p>Here is a div with a horizontal scrollbar!</p>
</div>

OwnerDisplayName: Matt Hamilton

LastEditorDisplayName: Matt Hamilton


问:
DotNetNuke redirects site root example.com/ to example.com/Default.aspx - why?
After moving a DNN 4.3.7 website from a Windows 2003 to a Windows 2008 server (IIS 7), entering the URL automatically results in a redirect to Default.aspx. When you create a Google sitemap, the root node is named "Object moved" which is ugly.

There are no HTTP Redirects added to IIS 7. We are using Helicon ISAPI rewrite, but there are no relating settings either.

It probably has to do with IIS 7 because we did not have this problem on IIS 6. On the other hand, other non-DNN sites on the same server do not have that problem, neither do other DNN-sites on other IIS 7 servers.

I am overlooking something obvious. But what?

答:
Hopefully, you checked the Documents tab on the site in IIS. The "Enable default content page" might be it.

In Host Settings, there is a Friendly URLs section, which might also be the culprit.


问:
Fit gaussians (or other distributions) on my data using python
I have a database of features, a 2D np.array (2000 samples and each sample contains 100 features, 2000 X 100). I want to fit gaussian distributions to my database using python. My code is the following:

```<code>data = load_my_data() # loads a np.array with size 2000x200
clf = mixture.GaussianMixture(n_components= 50, covariance_type='full')
clf.fit(data)
</code>```

I am not sure about the parameters for example the covariance_type and how can I investigate whether the fit was occured succesfully or not.

EDIT: I debug the code to investigate what is happening with the clf.means_ and appartently it produced a matrix n_components X size_of_features 50 X 20). Is there a way that i can check that the fitting was successful, or to plot data? What are the alternatives to Gaussian mixtures (mixtures of exponential for example, I cannot find any available implementation)?

答:
I understand, you may like to do regression of two different distributions, more than fitting them to an arithmetic curve. If this is the case, you may be interested in plotting one against the other one, and make a linear (or polynomial) regression, checking the coefficients
If this is the case, linear regression of two distributions, may tell you if there linear dependent or not.
Linear Regression using Scipy documentation </p>

Body:
I have a database of features, a 2D np.array (2000 samples and each sample contains 100 features, 2000 X 100). I want to fit gaussian distributions to my database using python. My code is the following:

data = load_my_data() # loads a np.array with size 2000x200
clf = mixture.GaussianMixture(n_components= 50, covariance_type='full')
clf.fit(data)

I am not sure about the parameters for example the covariance_type and how can I investigate whether the fit was occured succesfully or not.

EDIT: I debug the code to investigate what is happening with the clf.means_ and appartently it produced a matrix n_components X size_of_features 50 X 20). Is there a way that i can check that the fitting was successful, or to plot data? What are the alternatives to Gaussian mixtures (mixtures of exponential for example, I cannot find any available implementation)?


答:
You could just use in_array():

```<code>$userAllowedString = "Sales Manager,Sales Director,Project Manager,Developer";
$userRole = "Sales Administrator";
$userAllowed = in_array($userRole, explode(',', $userAllowedString));
</code>```

Title: Boolean false echoes an empty string

Body:
You could just use in_array():

$userAllowedString = "Sales Manager,Sales Director,Project Manager,Developer";
$userRole = "Sales Administrator";
$userAllowed = in_array($userRole, explode(',', $userAllowedString));


问:
Should I decouple the repository interface from the domain model
Let’s say I have some DDD service that requires some IEnumerable<Foo> to perform some calculations. I came up with two designs:

Abstract the data access with an IFooRepository interface, which is quite typical

```<code>public class FooService
{
    private readonly IFooRepository _fooRepository;

    public FooService(IFooRepository fooRepository)
        => _fooRepository = fooRepository;

    public int Calculate()
    {
        var fooModels = _fooRepository.GetAll();
        return fooModels.Sum(f => f.Bar);
    }
}
</code>```

Do not rely on the IFooRepository abstraction and inject IEnumerable<Foo> directly

```<code>public class FooService
{
    private readonly IEnumerable<Foo> _foos;

    public FooService(IEnumerable<Foo> foos)
        => _foos = foos;

    public int Calculate()
        => _foos.Sum(f => f.Bar);
}
</code>```

This second design seems better in my opinion as FooService now does not care where the data is coming from and Calculate becomes pure domain logic (ignoring the fact that IEnumerable may come from an impure source).

Another argument for using the second design is that when IFooRepository performs asynchronous IO over the network, usually it will be desirable to use async-await like:

```<code>public class AsyncDbFooRepository : IFooRepository
{
    public async Task<IEnumerable<Foo>> GetAll()
    {
        // Asynchronously fetch results from database
    }
}
</code>```

But as you need to async all the way down, FooService is now forced to change its signature to async Task<int> Calculate(). This seems to violate the dependency inversion principle.

However, there are also issues with the second design. First of all, you have to rely on the DI container (using Simple Injector as an example here) or the composition root to resolve the data access code like:

```<code>public class CompositionRoot
{
    public void ComposeDependencies()
    {
        container.Register<IFooRepository, AsyncDbFooRepository>(Lifestyle.Scoped);

        // Not sure if the syntax is right, but it demonstrates the concept
        container.Register<FooService>(async () => new FooService(await GetFoos(container)));
    }

    private async Task<IEnumerable<Foo>> GetFoos(Container container)
    {
        var fooRepository = container.GetInstance<IFooRepository>();
        return await fooRepository.GetAll();
    }
}
</code>```

Also in my specific scenario, AsyncDbFooRepository requires some sort of runtime parameter to construct, and that means you need an abstract factory to construct AsyncDbFooRepository.

With the abstract factory, now I have to manage the life cycles of all dependencies under AsyncDbFooRepository (the object graph under AsyncDbFooRepository is not trivial). I have a hunch that I am using DI incorrectly if I opt for the second design.

In summary, my questions are:

Am I using DI incorrectly in my second design?

How can I compose my dependencies satisfactorily for my second design?

答:
One aspect of async/await is that it by definition needs to applied "all the way down" as you rightfully state. You however can't prevent the use of Task<T> when injecting an IEnumerable<T>, as you suggest in your second option. You will have to inject a Task<IEnumerable<T>> into constructors to ensure data is retrieved asynchronously. When injecting an IEnumerable<T> it either means that your thread gets blocked when the collection is enumerated -or- all data must be loaded during object graph construction.

Loading data during object graph construction however is problematic, because of the reasons I explained here. Besides that, since we're dealing with collections of data here, it means that all data must be fetched from the database on each request, even though not all data might be required or even used. This might cause quite a performance penalty.

Am I using DI incorrectly in my second design?

That's hard to say. An IEnumerable<T> is a stream, so you could consider it a factory, which means that injecting an IEnumerable<T> does not require the runtime data to be loaded during object construction. As long as that condition is met, injecting an IEnumerable<T> could be fine, but still makes it impossible to make the system asynchronous.

However, when injecting an IEnumerable<T> you might end up with ambiguity, because it might not be very clear what it means to be injecting an IEnumerable<T>. Is that collection a stream that is lazily evaluated or not? Does it contain all elements of T. Is T runtime data or a service?

To prevent this confusion, moving the loading of this runtime information behind an abstraction is typically the best thing to do. To make your life easier, you could make the repository abstraction generic as well:

```<code>public interface IRepository<T> where T : Entity
{
    Task<IEnumerable<T>> GetAll();
}
</code>```

This allows you to have one generic implementation and make one single registration for all entities in the system.

How can I compose my dependencies satisfactorily for my second design?

You can't. To be able to do this, your DI container must be able to resolve object graphs asynchronously. For instance, it requires the following API:

```<code>Task<T> GetInstanceAsync<T>()
</code>```

But Simple Injection doesn't have such API, and neither does any other existing DI Container and that's for good reason. The reason is that object construction must be simple, fast and reliable and you lose that when doing I/O during object graph construction.

So not only is your second design undesirable, it is impossible to do so when data is loaded during object construction, without breaking the asynchonicity of the system and causing threads to block while using a DI container.

Body:
Let’s say I have some DDD service that requires some IEnumerable<Foo> to perform some calculations. I came up with two designs:

Abstract the data access with an IFooRepository interface, which is quite typical

public class FooService
{
    private readonly IFooRepository _fooRepository;

    public FooService(IFooRepository fooRepository)
        => _fooRepository = fooRepository;

    public int Calculate()
    {
        var fooModels = _fooRepository.GetAll();
        return fooModels.Sum(f => f.Bar);
    }
}

Do not rely on the IFooRepository abstraction and inject IEnumerable<Foo> directly

public class FooService
{
    private readonly IEnumerable<Foo> _foos;

    public FooService(IEnumerable<Foo> foos)
        => _foos = foos;

    public int Calculate()
        => _foos.Sum(f => f.Bar);
}

This second design seems better in my opinion as FooService now does not care where the data is coming from and Calculate becomes pure domain logic (ignoring the fact that IEnumerable may come from an impure source).

Another argument for using the second design is that when IFooRepository performs asynchronous IO over the network, usually it will be desirable to use async-await like:

public class AsyncDbFooRepository : IFooRepository
{
    public async Task<IEnumerable<Foo>> GetAll()
    {
        // Asynchronously fetch results from database
    }
}

But as you need to async all the way down, FooService is now forced to change its signature to async Task<int> Calculate(). This seems to violate the dependency inversion principle.

However, there are also issues with the second design. First of all, you have to rely on the DI container (using Simple Injector as an example here) or the composition root to resolve the data access code like:

public class CompositionRoot
{
    public void ComposeDependencies()
    {
        container.Register<IFooRepository, AsyncDbFooRepository>(Lifestyle.Scoped);

        // Not sure if the syntax is right, but it demonstrates the concept
        container.Register<FooService>(async () => new FooService(await GetFoos(container)));
    }

    private async Task<IEnumerable<Foo>> GetFoos(Container container)
    {
        var fooRepository = container.GetInstance<IFooRepository>();
        return await fooRepository.GetAll();
    }
}

Also in my specific scenario, AsyncDbFooRepository requires some sort of runtime parameter to construct, and that means you need an abstract factory to construct AsyncDbFooRepository.

With the abstract factory, now I have to manage the life cycles of all dependencies under AsyncDbFooRepository (the object graph under AsyncDbFooRepository is not trivial). I have a hunch that I am using DI incorrectly if I opt for the second design.

In summary, my questions are:

Am I using DI incorrectly in my second design?

How can I compose my dependencies satisfactorily for my second design?

Body:
One aspect of async/await is that it by definition needs to applied "all the way down" as you rightfully state. You however can't prevent the use of Task<T> when injecting an IEnumerable<T>, as you suggest in your second option. You will have to inject a Task<IEnumerable<T>> into constructors to ensure data is retrieved asynchronously. When injecting an IEnumerable<T> it either means that your thread gets blocked when the collection is enumerated -or- all data must be loaded during object graph construction.

Loading data during object graph construction however is problematic, because of the reasons I explained here. Besides that, since we're dealing with collections of data here, it means that all data must be fetched from the database on each request, even though not all data might be required or even used. This might cause quite a performance penalty.

Am I using DI incorrectly in my second design?

That's hard to say. An IEnumerable<T> is a stream, so you could consider it a factory, which means that injecting an IEnumerable<T> does not require the runtime data to be loaded during object construction. As long as that condition is met, injecting an IEnumerable<T> could be fine, but still makes it impossible to make the system asynchronous.

However, when injecting an IEnumerable<T> you might end up with ambiguity, because it might not be very clear what it means to be injecting an IEnumerable<T>. Is that collection a stream that is lazily evaluated or not? Does it contain all elements of T. Is T runtime data or a service?

To prevent this confusion, moving the loading of this runtime information behind an abstraction is typically the best thing to do. To make your life easier, you could make the repository abstraction generic as well:

public interface IRepository<T> where T : Entity
{
    Task<IEnumerable<T>> GetAll();
}

This allows you to have one generic implementation and make one single registration for all entities in the system.

How can I compose my dependencies satisfactorily for my second design?

You can't. To be able to do this, your DI container must be able to resolve object graphs asynchronously. For instance, it requires the following API:

Task<T> GetInstanceAsync<T>()

But Simple Injection doesn't have such API, and neither does any other existing DI Container and that's for good reason. The reason is that object construction must be simple, fast and reliable and you lose that when doing I/O during object graph construction.

So not only is your second design undesirable, it is impossible to do so when data is loaded during object construction, without breaking the asynchonicity of the system and causing threads to block while using a DI container.


问:
Hide "Add to cart" button when the product price is zero
I have an event based WordPress website on that I sell tickets using WooCommerce. Is there any way to hide the "add to cart" button for the product having cost zero?

Thanks.

答:
This code work like charm in function.php using this two filter.</p>

```<code>add_filter('remove_add_to_cart', 'my_woocommerce_is_purchasable', 10, 2);
function remove_add_to_cart($is_purchasable, $product) {
        if( $product->get_price() == 0 )
            $is_purchasable = false;
            return $purchasable;
}

function remove_add_to_cart_on_0 ( $purchasable, $product ){
        if( $product->get_price() == 0 )
            $purchasable = false;
        return $purchasable;
    }
add_filter( 'woocommerce_is_purchasable', 'remove_add_to_cart_on_0', 10, 2 );
</code>```

Body:
This code work like charm in function.php using this two filter.

add_filter('remove_add_to_cart', 'my_woocommerce_is_purchasable', 10, 2);
function remove_add_to_cart($is_purchasable, $product) {
        if( $product->get_price() == 0 )
            $is_purchasable = false;
            return $purchasable;
}

function remove_add_to_cart_on_0 ( $purchasable, $product ){
        if( $product->get_price() == 0 )
            $purchasable = false;
        return $purchasable;
    }
add_filter( 'woocommerce_is_purchasable', 'remove_add_to_cart_on_0', 10, 2 );


问:
How to get height of LinearLayout
I have a LinearLayout set height as match_parent as below:

```<code><LinearLayout
    android:id="@+id/list_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
</code>```

I want to get the height of this LinearLayout.

I used the code below:

```<code>LinearLayout ll_list = (LinearLayout)findViewById(R.id.list_layout);
int h = ll_list.getHeight();
</code>```

But it return null.

How can I do?

答:
You need to wait View to be initialized first use View Tree Observer it waits until the view is created check out this

get layout height and width at run time android

Title: How to get height of LinearLayout

Body:
I have a LinearLayout set height as match_parent as below:

<LinearLayout
    android:id="@+id/list_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

I want to get the height of this LinearLayout.

I used the code below:

LinearLayout ll_list = (LinearLayout)findViewById(R.id.list_layout);
int h = ll_list.getHeight();

But it return null.

How can I do?


问:
When programming for Mac OS X, is there an equivalent to viewDidLoad?

Possible Duplicate:

  viewDidLoad in NSViewController?

I started development on iOS apps and am now moving to Mac OS X apps. I was wondering if there's an equivalent method in Mac OS X that is like iOS's viewDidLoad to run code after a View Controller launches.

Thank you!

答:
From the Apple Release Notes:

Advice for People who Are Looking for
  -viewWillLoad and -viewDidLoad Methods in NSViewController

Even though NSWindowController has
  -windowWillLoad and -windowDidLoad methods for you to override the
  NSViewController class introduced in
  Mac OS 10.5 does not have
  corresponding -viewWillLoad and
  -viewDidLoad methods. You can override -[NSViewController loadView] to customize what happens immediately
  before or immediately after nib
  loading done by a view controller.


问:
JavaFX unfilter FilteredList
I have got a ObservableList and I linked it to multiple CheckMenuItem it's shown in a TableView and I can filter out one predicate.

I did that by using .filter(Predicate p) and updated my TableView to it's return value. When I wanted to unfilter, I simply set it back on my ObservableList.

But I can't wrap my head around on how to remove multiple filteres to my ObservableList. I can apply them if i just keep using .filter(Predicate p) with different predicates on the returned lists, but how to I remove a spcific filter?

Greets

答:
The code

```<code>ObservableList<DataType> data = FXCollections.observableArrayList();
table.setItems(data.filter(predicate));
</code>```

is equivalent to

```<code>ObservableList<DataType> data = FXCollections.observableArrayList();
table.setItems(new FilteredList<DataType>(data, predicate));
</code>```

and the code

```<code>ObservableList<DataType> data = FXCollections.observableArrayList();
table.setItems(data.filter(predicate1).filter(predicate2));
</code>```

is logically equivalent to

```<code>ObservableList<DataType> data = FXCollections.observableArrayList();
table.setItems(new FilteredList<DataType>(data, predicate1.and(predicate2)));
</code>```

So you can achieve what you need by keeping a reference to the filtered list and updating its predicate:

```<code>ObservableList<DataType> data = FXCollections.observableArrayList();
FilteredList<DataType> filteredData = new FilteredList<>(data, x -> true);
table.setItems(filteredData);
</code>```

Now you can use predicate1 only with:

```<code>filteredData.setPredicate(predicate1);
</code>```

add predicate2:

```<code>filteredData.setPredicate(predicate1.and(predicate2));
</code>```

remove predicate1:

```<code>filteredData.setPredicate(predicate2);
</code>```

remove all filters:

```<code>filteredData.setPredicate(x -> true);
</code>```

If you wanted a really esoteric solution (which is almost certainly overkill), you could keep an ObservableList<Predicate<DataType>>:

```<code>ObservableList<Predicate<DataType>> filters = FXCollections.observableArrayList();
</code>```

and then bind the predicate of the filtered list to combining all filters with a logical and:

```<code>filteredList.predicateProperty().bind(Bindings.createObjectBinding(() ->
    filters.stream().reduce(x -> true, Predicate::and),
    filters));
</code>```

Then you can just add and remove predicates to the filters list, e.g.

```<code>filters.add(predicate1);
filters.add(predicate2);
filters.remove(predicate1);
</code>```

and the table data will automatically update.

Title: JavaFX unfilter FilteredList

Body:
The code

ObservableList<DataType> data = FXCollections.observableArrayList();
table.setItems(data.filter(predicate));

is equivalent to

ObservableList<DataType> data = FXCollections.observableArrayList();
table.setItems(new FilteredList<DataType>(data, predicate));

and the code

ObservableList<DataType> data = FXCollections.observableArrayList();
table.setItems(data.filter(predicate1).filter(predicate2));

is logically equivalent to

ObservableList<DataType> data = FXCollections.observableArrayList();
table.setItems(new FilteredList<DataType>(data, predicate1.and(predicate2)));

So you can achieve what you need by keeping a reference to the filtered list and updating its predicate:

ObservableList<DataType> data = FXCollections.observableArrayList();
FilteredList<DataType> filteredData = new FilteredList<>(data, x -> true);
table.setItems(filteredData);

Now you can use predicate1 only with:

filteredData.setPredicate(predicate1);

add predicate2:

filteredData.setPredicate(predicate1.and(predicate2));

remove predicate1:

filteredData.setPredicate(predicate2);

remove all filters:

filteredData.setPredicate(x -> true);

If you wanted a really esoteric solution (which is almost certainly overkill), you could keep an ObservableList<Predicate<DataType>>:

ObservableList<Predicate<DataType>> filters = FXCollections.observableArrayList();

and then bind the predicate of the filtered list to combining all filters with a logical and:

filteredList.predicateProperty().bind(Bindings.createObjectBinding(() ->
    filters.stream().reduce(x -> true, Predicate::and),
    filters));

Then you can just add and remove predicates to the filters list, e.g.

filters.add(predicate1);
filters.add(predicate2);
filters.remove(predicate1);

and the table data will automatically update.


问:
how to check mysql for duplicates with php
I need a way to check a database if a word is in it already if so then it doesn't have to be pushed to the database if the word isn't in it yet then it has to be  pushed into it.

It's a MYSQL database and I have to do it in PHP this is what I got so far.

```<code>$result = array_count_values(explode(" ", $filter));
arsort($result);
foreach ($result as $word => $frequency)
{
    if (!in_array($word, [" ", ""]))
        query("words", "INSERT INTO Woord (woord) VALUE (?)",[$word], false);
}
query("words" "SELECT WHERE")
</code>```

答:
You have 2 options:

REPLACE

```<code>REPLACE INTO table
SET column = 'example'
</code>```

This will overwrite if the record exists and if not it will create it.

INSERT IGNORE

```<code>INSERT IGNORE INTO table
SET column = 'example'
</code>```

This will ignore the query if already exists and if not it will create it.

Your php query should look like this:

"INSERT IGNORE INTO ID142118_ascii.Woord (woord) VALUES (".$word.")"

Body:
I need a way to check a database if a word is in it already if so then it doesn't have to be pushed to the database if the word isn't in it yet then it has to be  pushed into it.

It's a MYSQL database and I have to do it in PHP this is what I got so far.

$result = array_count_values(explode(" ", $filter));
arsort($result);
foreach ($result as $word => $frequency)
{
    if (!in_array($word, [" ", ""]))
        query("words", "INSERT INTO Woord (woord) VALUE (?)",[$word], false);
}
query("words" "SELECT WHERE")

Body:
You have 2 options:

REPLACE

REPLACE INTO table
SET column = 'example'

This will overwrite if the record exists and if not it will create it.

INSERT IGNORE

INSERT IGNORE INTO table
SET column = 'example'

This will ignore the query if already exists and if not it will create it.

Your php query should look like this:

"INSERT IGNORE INTO ID142118_ascii.Woord (woord) VALUES (".$word.")"


问:
Single dictionary initialization with different types of keys
Has anyone used class initialization like this:

```<code>var dictionary = new Dictionary {
    [address] = address,
    [person] = person,
    [biz] = biz
};
</code>```

How do I declare such class Dictionary which initializes using above line,
Never used [] in dictionary initialization which takes different types as key

address, person, biz are objects off different classes Address, Person and Biz

reference: problem I am solving

Updates

```<code>public class BaseEntity
{
    public string Id { get; set; }

    public bool Save()
    {
        return true;
    }

    public bool Delete()
    {
        return true;
    }
}

public class Address : BaseEntity
{
    public Address() { }

    public Address(string addressLine1, string addressLine2, string state, string zip)
    {
        this.AddressLine1 = addressLine1;
        this.AddressLine2 = addressLine2;
        this.State = state;
        this.ZipCode = zip;
    }

    public string AddressLine1 { get; set; }
    public string AddressLine2 { get; set; }
    public string State { get; set; }
    public string ZipCode { get; set; }

    public static Address Find(string id)
    {
        return null;
    }
}

public class Business : BaseEntity
{
    public Business() { }

    public Business(string businessName, Address address)
    {
        this.Name = businessName;
        this.Address = address;
    }

    public string Name { get; set; }
    public Address Address { get; set; }

    public static Business Find(string id)
    {
        return null;
    }
}

public class Person : BaseEntity
{
    public Person() { }

    public Person(string fname, string lname, Address address)
    {
        this.FirstName = fname;
        this.LastName = lname;
        this.Address = address;
    }

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Address Address { get; set; }

    public static Person Find(string id)
    {
        return null;
    }
}
</code>```

答:
Address, Person,Biz classes must implement common base class or interface say BaseX. The key shall be a string which is the name of the derived class. And:

```<code>var dictionary<string, BaseX> dict = new Dictionary<string, BaseX>();
dict.Add("address", new address());
dict.Add("person", new person());
dict.Add("biz", new biz());
</code>```

Thanks

Body:
Has anyone used class initialization like this:

var dictionary = new Dictionary {
    [address] = address,
    [person] = person,
    [biz] = biz
};

How do I declare such class Dictionary which initializes using above line,
Never used [] in dictionary initialization which takes different types as key

address, person, biz are objects off different classes Address, Person and Biz

reference: problem I am solving

Updates

public class BaseEntity
{
    public string Id { get; set; }

    public bool Save()
    {
        return true;
    }

    public bool Delete()
    {
        return true;
    }
}

public class Address : BaseEntity
{
    public Address() { }

    public Address(string addressLine1, string addressLine2, string state, string zip)
    {
        this.AddressLine1 = addressLine1;
        this.AddressLine2 = addressLine2;
        this.State = state;
        this.ZipCode = zip;
    }

    public string AddressLine1 { get; set; }
    public string AddressLine2 { get; set; }
    public string State { get; set; }
    public string ZipCode { get; set; }

    public static Address Find(string id)
    {
        return null;
    }
}

public class Business : BaseEntity
{
    public Business() { }

    public Business(string businessName, Address address)
    {
        this.Name = businessName;
        this.Address = address;
    }

    public string Name { get; set; }
    public Address Address { get; set; }

    public static Business Find(string id)
    {
        return null;
    }
}

public class Person : BaseEntity
{
    public Person() { }

    public Person(string fname, string lname, Address address)
    {
        this.FirstName = fname;
        this.LastName = lname;
        this.Address = address;
    }

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Address Address { get; set; }

    public static Person Find(string id)
    {
        return null;
    }
}

Body:
Address, Person,Biz classes must implement common base class or interface say BaseX. The key shall be a string which is the name of the derived class. And:

var dictionary<string, BaseX> dict = new Dictionary<string, BaseX>();
dict.Add("address", new address());
dict.Add("person", new person());
dict.Add("biz", new biz());

Thanks


问:
Spring boot app works when I run it, but falls when I test it
I have a simple spring app with one controller

```<code>@RestController
public class UserController {

//  @Autowired
//  UserServiceImpl userService;

  @RequestMapping(value="/getUser", method = RequestMethod.GET)
  public String getUser(){
//    return userService.greetUser();
    return "Hello user";
  }
</code>```

It works when I start it. If I uncomment @Autowired and run with the first return statement using UserService it also works.

My Service interface

```<code>@Service
public interface UserService {
  String greetUser();
  void insertUsers(List<User> users);
}
</code>```

and implementation

```<code>@Service
public class UserServiceImpl implements UserService{

  @Override
  public String greetUser() {
    return "Hello user";
  }
}
</code>```

But when I test it, the app falls with the following errors

```<code>java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userController': Unsatisfied dependency expressed through field 'userService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.demo.service.UserServiceImpl' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.demo.service.UserServiceImpl' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
</code>```

The test class

```<code>@RunWith(SpringRunner.class)
@WebMvcTest
public class DemoApplicationTests {

  @Autowired
  private MockMvc mockMvc;

    @Test
  public void shouldReturnHelloString() throws Exception{
      this.mockMvc
      .perform(get("/getUser"))
      .andDo(print())
      .andExpect(status().isOk())
      .andExpect(content().string("Hello user"));
  }
}
</code>```

Also, if I remove

```<code>//  @Autowired
//  UserServiceImpl userService;
</code>```

and run test with second return statement, the test execute without error. I understand that the problem is in the UserServiceImpl, but I don't know what it is. What do I need to correct?

答:
You should try to autowire your bean by an interface, not implementation

```<code>@Autowired
UserService userService;
</code>```

And also you should remove @Service from UserService interface

Body:
I have a simple spring app with one controller

@RestController
public class UserController {

//  @Autowired
//  UserServiceImpl userService;

  @RequestMapping(value="/getUser", method = RequestMethod.GET)
  public String getUser(){
//    return userService.greetUser();
    return "Hello user";
  }

It works when I start it. If I uncomment @Autowired and run with the first return statement using UserService it also works.

My Service interface

@Service
public interface UserService {
  String greetUser();
  void insertUsers(List<User> users);
}

and implementation

@Service
public class UserServiceImpl implements UserService{

  @Override
  public String greetUser() {
    return "Hello user";
  }
}

But when I test it, the app falls with the following errors

java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userController': Unsatisfied dependency expressed through field 'userService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.demo.service.UserServiceImpl' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.demo.service.UserServiceImpl' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

The test class

@RunWith(SpringRunner.class)
@WebMvcTest
public class DemoApplicationTests {

  @Autowired
  private MockMvc mockMvc;

    @Test
  public void shouldReturnHelloString() throws Exception{
      this.mockMvc
      .perform(get("/getUser"))
      .andDo(print())
      .andExpect(status().isOk())
      .andExpect(content().string("Hello user"));
  }
}

Also, if I remove

//  @Autowired
//  UserServiceImpl userService;

and run test with second return statement, the test execute without error. I understand that the problem is in the UserServiceImpl, but I don't know what it is. What do I need to correct?

Body:
You should try to autowire your bean by an interface, not implementation

@Autowired
UserService userService;

And also you should remove @Service from UserService interface


问:
What version of TLS is used in a .NET application installed on different operating systems
Say I have a standard .NET (4.5) web application that needs to connect to a secure server using TLS.

I want to stop supporting unused or weak protocols and cipher suites in my server and support only the ones which the client also supports (preferably TLS 1.2)

Does the version of TLS (1.0, 1.1 or 1.2) and/or cipher suites in use depend on the operation system or the .NET version?

In other words, will my .NET application use a different cipher suite or TLS version when installed on machines with different Operating systems / updates? Or does the usage of .NET 4.5 ensures that the protocols on every client-server communication will be identical?

答:
Starting with .NET 4.7, .NET uses the operating system's default.

The TLS stack, which is used by System.Net.Security.SslStream and up-stack components such as HTTP, FTP, and SMTP, allows developers to use the default TLS protocols supported by the operating system. Developers need no longer hard-code a TLS version.

Before 4.7, you had to specify the TLS version to use explicitly with

```<code>ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
</code>```

For .NET 4.7, ServicePointManager.SecurityProtocol (if not explicitly set) now returns SystemDefault.

BTW the earliest supported .NET version is 4.5.2. Most systems will have a newer version though, installed by other applications or Windows Update. Every version since 4.0 is a binary replacement of the previous.

Body:
Starting with .NET 4.7, .NET uses the operating system's default.

The TLS stack, which is used by System.Net.Security.SslStream and up-stack components such as HTTP, FTP, and SMTP, allows developers to use the default TLS protocols supported by the operating system. Developers need no longer hard-code a TLS version.

Before 4.7, you had to specify the TLS version to use explicitly with

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12

For .NET 4.7, ServicePointManager.SecurityProtocol (if not explicitly set) now returns SystemDefault.

BTW the earliest supported .NET version is 4.5.2. Most systems will have a newer version though, installed by other applications or Windows Update. Every version since 4.0 is a binary replacement of the previous.


问:
The SMTP server requires a secure connection or the client was not authenticated
I am getting this error

```<code>The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Must issue a STARTTLS command first. e17sm974159fak.34
</code>```

Web.config

```<code><mailSettings>
    <smtp deliveryMethod="Network"
                from="emailaccount@gmail.com">
        <network defaultCredentials="false" host="smtp.gmail.com" port="587"
                    userName="emailaccount@gmail.com"  password="12345678" />
    </smtp>
</mailSettings>
</code>```

Code file

```<code>public void Submit()
        {
            EnsureCurrentlyValid();
            // Send via email
            var message = new StringBuilder();
            message.AppendFormat("Date: {0:yyyy-MM-dd hh:mm}\n", DateTime.Now);
            message.AppendFormat("Email from: {0}\n", Name);
            message.AppendFormat("Email: {0}\n", Email);
            message.AppendFormat("Message: {0}\n", Message);
            SmtpClient smtpClient = new SmtpClient();
            MailMessage m = new MailMessage(
                "visitor@mydomain.com", // From
                "emailaccount@gmail.com", // To
                "Suggestion/Comments", // Subject
                message.ToString()); // Body

            smtpClient.Send(m);
        }
</code>```

答:
Try setting the EnableSsl property to true:

```<code>smtpClient.EnableSsl = true;
</code>```

AFAIK this property can only be set in code and cannot be specified in the config file.

Body:
I am getting this error

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Must issue a STARTTLS command first. e17sm974159fak.34

Web.config

<mailSettings>
    <smtp deliveryMethod="Network"
                from="emailaccount@gmail.com">
        <network defaultCredentials="false" host="smtp.gmail.com" port="587"
                    userName="emailaccount@gmail.com"  password="12345678" />
    </smtp>
</mailSettings>

Code file

public void Submit()
        {
            EnsureCurrentlyValid();
            // Send via email
            var message = new StringBuilder();
            message.AppendFormat("Date: {0:yyyy-MM-dd hh:mm}\n", DateTime.Now);
            message.AppendFormat("Email from: {0}\n", Name);
            message.AppendFormat("Email: {0}\n", Email);
            message.AppendFormat("Message: {0}\n", Message);
            SmtpClient smtpClient = new SmtpClient();
            MailMessage m = new MailMessage(
                "visitor@mydomain.com", // From
                "emailaccount@gmail.com", // To
                "Suggestion/Comments", // Subject
                message.ToString()); // Body

            smtpClient.Send(m);
        }

Body:
Try setting the EnableSsl property to true:

smtpClient.EnableSsl = true;

AFAIK this property can only be set in code and cannot be specified in the config file.


问:
Protractor Single Page application test
In Angular JS Single Page Application, ui router is configured to change the view content (<ui-view></ui-view>) based on the state of the application.

How do we test the changed view content (pages) in protractor? The view content is not displayed while doing page source view. Page is loaded correctly, but the protractor cannot find the page elements.

```<code><head>
    <title> Test Application</title>
</head>
<body>
    <div class="wrapper">
        <div class="container">
            <ui-view></ui-view>
        </div>
    <div>
<body>
</code>```

Snippet code that goes inside <ui-view></ui-view>

```<code><div class="form-group">
<label for="firstName" class="ng-scope">First Name</label>
<input type="text" id="firstName" name="firstName"  ng-model="customer.firstName">
</div>
</code>```

Protractor cannot find the elements by.model.

```<code>describe('Protractor Demo App', function() {
        browser.get('http://example.com');//url
        it("Test..", function() {
        element(by.model('customer.firstName')).sendKeys('FIRSTNAME');
        element(by.model('customer.lastName')).sendKeys('LASTNAME');
       });
    });
</code>```

答:
Possible that it's looking for the elements before they've been loaded in and is therefore missing them. Try using protractor.ExpectedConditions. For example:

```<code>describe('Protractor Demo App', function() {
    browser.get('http://example.com');
    it("Test..", function() {
        var el = element(by.css('.form-group'));
        var EC = protractor.ExpectedConditions;
        browser.wait(EC.presenceOf(el), 10000).then(function(){
            element(by.model('customer.firstName')).sendKeys('FIRSTNAME');
            element(by.model('customer.lastName')).sendKeys('LASTNAME');
        });
    });
});
</code>```

Here it will wait a maximum of 10 seconds for the .form-group div to be present on the page before attempting to fill in the inputs.

Title: Protractor Single Page application test

Body:
In Angular JS Single Page Application, ui router is configured to change the view content (<ui-view></ui-view>) based on the state of the application.

How do we test the changed view content (pages) in protractor? The view content is not displayed while doing page source view. Page is loaded correctly, but the protractor cannot find the page elements.

    <title> Test Application</title>

            <ui-view></ui-view>

Snippet code that goes inside <ui-view></ui-view>

First Name
<input type="text" id="firstName" name="firstName"  ng-model="customer.firstName">

Protractor cannot find the elements by.model.

describe('Protractor Demo App', function() {
        browser.get('http://example.com');//url
        it("Test..", function() {
        element(by.model('customer.firstName')).sendKeys('FIRSTNAME');
        element(by.model('customer.lastName')).sendKeys('LASTNAME');
       });
    });

Body:
Possible that it's looking for the elements before they've been loaded in and is therefore missing them. Try using protractor.ExpectedConditions. For example:

describe('Protractor Demo App', function() {
    browser.get('http://example.com');
    it("Test..", function() {
        var el = element(by.css('.form-group'));
        var EC = protractor.ExpectedConditions;
        browser.wait(EC.presenceOf(el), 10000).then(function(){
            element(by.model('customer.firstName')).sendKeys('FIRSTNAME');
            element(by.model('customer.lastName')).sendKeys('LASTNAME');
        });
    });
});

Here it will wait a maximum of 10 seconds for the .form-group div to be present on the page before attempting to fill in the inputs.


问:
Gradle does not download complete dependencies
Im trying to download and build spring-data-hadoop 2.4.0.RELEASE using the following decleration in my dependencies.gradle:

```<code>dependencies {
    ...
//    compile('org.springframework.data:spring-data_hadoop:2.4.0.RELEASE')
    compile group: 'org.springframework.data', name: 'spring-data-hadoop', version: '2.4.0.RELEASE'

    ...
}
</code>```

Refreshing gradle now results in downloading the newly added dependency BUT the data is not consistend. I got the following external dependencies after the download:

I thought everything is fine now... but I am wrong. Lets open up one of those and look depper into the packages:

If you compare the content of org.springframework.data.hadoop.config with the official API you will notice, that in this package, there should be much more content. The annotations package for example.

How can it be that gradle is not downloading the complete source?

答: There is a separate spring-data-hadoop-config with the description "Spring for Apache Hadoop Annotation Configuration", so that's probably where annotations would be.

Body:
Im trying to download and build spring-data-hadoop 2.4.0.RELEASE using the following decleration in my dependencies.gradle:

dependencies {
    ...
//    compile('org.springframework.data:spring-data_hadoop:2.4.0.RELEASE')
    compile group: 'org.springframework.data', name: 'spring-data-hadoop', version: '2.4.0.RELEASE'

    ...
}

Refreshing gradle now results in downloading the newly added dependency BUT the data is not consistend. I got the following external dependencies after the download:

I thought everything is fine now... but I am wrong. Lets open up one of those and look depper into the packages:

If you compare the content of org.springframework.data.hadoop.config with the official API you will notice, that in this package, there should be much more content. The annotations package for example.

How can it be that gradle is not downloading the complete source?


问:
How do I remove role="search" from the form-tag in drupal?
I am new to Drupal. I have developed one site . But in WCAG 2.0 testing I was getting following problem: Element 'form' does not need a 'role' attribute. How do I achive this ? Please Help...

Thanks.

Here is my source code:
enter image description here

答:
You can do that by using hook_form_alter. You need to try this code with your custom module.

```<code>function hook_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_block_form') {
    $form["#attributes"]["role"] = "";
    //Or
    unset($form["#attributes"]["role"]);
  }
}
</code>```

You need to create a custom module at 'sites/all/modules' directory and in the .module file you need to write this function replacing the hook with module name.

For example, create a custom module with the name custom. See this article if needs help. In the modules's custom.module file write the following function:

```<code>function custom_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_block_form') {
    $form["#attributes"]["role"] = "";
    //Or
    unset($form["#attributes"]["role"]);
  }
}
</code>```

Hope that helps!

Body:
You can do that by using hook_form_alter. You need to try this code with your custom module.

function hook_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_block_form') {
    $form["#attributes"]["role"] = "";
    //Or
    unset($form["#attributes"]["role"]);
  }
}

You need to create a custom module at 'sites/all/modules' directory and in the .module file you need to write this function replacing the hook with module name.

For example, create a custom module with the name custom. See this article if needs help. In the modules's custom.module file write the following function:

function custom_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_block_form') {
    $form["#attributes"]["role"] = "";
    //Or
    unset($form["#attributes"]["role"]);
  }
}

Hope that helps!


问:
How do I pass a poco to azure webjob from azure app service (azure website)?
I have an asp.net mvc 5 website running in an azure app service. My site allows customers to communicate via email uploading documents if required.

I modeled this as sending email with attachments (max 4mb) using sendgrid with azure webjob.

I cannot use an azure queue since the message size is way too small.

Therefore I have to communicate with a triggered webjob via kudu. I've read the docs and the argument seems to be a simple string which I can either read it off of the arguments or WEBJOBS_COMMAND_ARGUMENTS environment variable.

My poco class to send email has customer properties (mostly string) + the file the user uploads is of type HttpPostedFileBase.

How do I pass this poco class to the triggered webjob via kudu?

Should I json serialize it and pass it as a string?

Any other options?

I need help.

答:
I cannot use an azure queue since the message size is way too small.

That's not a limitation on Azure Queues.

Should I json serialize it and pass it as a string?

That's basically what the azure queues is doing.

My suggestion is if you want to use Azure WebJobs to send an email, you can just send a message to a queue with the appropriate payload. When you listen to the queue you can get the attachment (maybe store it as a blob?) and send it using SendGrid.

When you listen to the message you can either get a string or POCO object. If you're going to get a POCO, I suggest not to send the HttpPostedFileBase property since that can make the message too large (that is a limitation on the message).

Hope this helps


问:
CompositionTarget.Rendering event for Windows Form?
This code is in WPF:

```
<code>
CompositionTarget.Rendering += new EventHandler(Update);
CompositionTarget.Rendering += new EventHandler(Draw);
</code>
```

I would like to translate do Windows Form. Can I do this?
Thank you.

答: The closest equivalent is the Form.Paint event.  It isn't exactly a very good match, each control in Winforms gets its own event.  A fundamental difference between WPF and Winforms.  A child control may need to paint itself (compare Control.Invalidate) without the parent ever getting the event.</p>

Body:
This code is in WPF:

CompositionTarget.Rendering += new EventHandler(Update);
CompositionTarget.Rendering += new EventHandler(Draw);

I would like to translate do Windows Form. Can I do this?
Thank you.