问:
How can I keep responsive image in container when resizing screen
I have an image inside a container, I have to use bottom in negative in order to keep the part of the image that I want, the problem is that when I resize the screen into a smaller one, the image just disappears, how can I fix this?

HTML:

```<code></section>
<section id="img">
   <div class="container-fluid">
   <div class="row content">
      <div id="imgcont">
        <img class="img-responsive" src="http://www.qygjxz.com/data/out/162/6155406-mountain-images.jpeg" />
         <div id="header">
            <div class="title">
               <h1>Title in image centered</h1>
            </div>
         </div>
      </div>
   </div>
   <div class="row content text-center">
      <h1>More content, same section </h1>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum consectetur adipiscing elit.</p>
   </div>
</section>
</code>```

CSS:

```<code>#imgcont {
       overflow: hidden;
       height: 400px;
       max-height: 400px;
       position: relative;
}

#imgcont .img-responsive {
          display: block;
        width: 100%;
        height: auto;
        position: absolute;
        bottom: -500px;
    }

.title {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    color: white;
    text-align: center;
}

.title h1 {
    text-transform: uppercase;
    margin: 0;
    font-size: 3rem;
    white-space: nowrap;
}
</code>```

Full code:

https://codepen.io/elunap/pen/Ebwwjv

Or is there another way around this? this is really bothering me, when I finnaly think I made it work, something new happens.

答:
I have made the changes to #imgcont .img-responsive class. Used display:flex to make the image flexible according to the browser size.

body {
 color: white;
}

.navbar {
 margin-bottom: 0;
 border-radius: 0;
  padding-bottom: 0;
}

.row.content {
 min-height: 450px
}

#about {
 background-color: red;
}

#img {
 background-color: gray;
 height 100%;
  object-fit: contain;
}

#howto {
 background-color: #003300;
}

#imgcont {

       overflow: hidden;
       height: 400px;
       max-height: 400px;
       position: relative;
}

#imgcont .img-responsive {
       display: flex;
        width: 100%;
        height: auto;
        position: absolute;
    }

.title {
 position: absolute;
 top: 50%;
 left: 50%;
 transform: translate(-50%, -50%);
 color: white;
 text-align: center;
}

.title h1 {
 text-transform: uppercase;
 margin: 0;
 font-size: 3rem;
 white-space: nowrap;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav class="navbar navbar-inverse">
   <div class="container-fluid">
      <div class="navbar-header">
         <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
         <span class="icon-bar"></span>
         <span class="icon-bar"></span>
         <span class="icon-bar"></span>
         </button>
         Logo
      </div>
      <div class="collapse navbar-collapse" id="myNavbar">
         <ul class="nav navbar-nav">
            <li class="active">Home</li>
            <li>About</li>
            <li>Projects</li>
            <li>Contact</li>
         </ul>
         <ul class="nav navbar-nav navbar-right">
            <li><span class="glyphicon glyphicon-log-in"></span> Login</li>
         </ul>
      </div>
   </div>
</nav>
<section id="about">
   <div class="container-fluid text-center">
      <div class="row content">
         <div class="col-lg-12">
            <h1>Welcome</h1>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
         </div>
      </div>
   </div>
</section>
<section id="img">
   <div class="container-fluid">
   <div class="row content">
      <div id="imgcont">
        <img class="img-responsive" src="http://www.qygjxz.com/data/out/162/6155406-mountain-images.jpeg" />
         <div id="header">
            <div class="title">
               <h1>Title in image centered</h1>
            </div>
         </div>
      </div>
   </div>
   <div class="row content text-center">
      <h1>More content, same section </h1>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum consectetur adipiscing elit.</p>
   </div>
</section>
<section id="howto">
   <div class="container-fluid">
      <div class="row content">
         <div class="col-lg-12">
            <h1>Welcome</h1>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
         </div>
      </div>
   </div>
</section></code>```

Body:
I have an image inside a container, I have to use bottom in negative in order to keep the part of the image that I want, the problem is that when I resize the screen into a smaller one, the image just disappears, how can I fix this?

HTML:

Title in image centered

More content, same section

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum consectetur adipiscing elit.

CSS:

#imgcont {
       overflow: hidden;
       height: 400px;
       max-height: 400px;
       position: relative;
}

#imgcont .img-responsive {
          display: block;
        width: 100%;
        height: auto;
        position: absolute;
        bottom: -500px;
    }

.title {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    color: white;
    text-align: center;
}

.title h1 {
    text-transform: uppercase;
    margin: 0;
    font-size: 3rem;
    white-space: nowrap;
}

Full code:

https://codepen.io/elunap/pen/Ebwwjv

Or is there another way around this? this is really bothering me, when I finnaly think I made it work, something new happens.

Body:
I have made the changes to #imgcont .img-responsive class. Used display:flex to make the image flexible according to the browser size.

body {
 color: white;
}

.navbar {
 margin-bottom: 0;
 border-radius: 0;
  padding-bottom: 0;
}

.row.content {
 min-height: 450px
}

#about {
 background-color: red;
}

#img {
 background-color: gray;
 height 100%;
  object-fit: contain;
}

#howto {
 background-color: #003300;
}

#imgcont {

       overflow: hidden;
       height: 400px;
       max-height: 400px;
       position: relative;
}

#imgcont .img-responsive {
       display: flex;
        width: 100%;
        height: auto;
        position: absolute;
    }

.title {
 position: absolute;
 top: 50%;
 left: 50%;
 transform: translate(-50%, -50%);
 color: white;
 text-align: center;
}

.title h1 {
 text-transform: uppercase;
 margin: 0;
 font-size: 3rem;
 white-space: nowrap;
}

<nav class="navbar navbar-inverse">
   <div class="container-fluid">
      <div class="navbar-header">
         <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
         <span class="icon-bar"></span>
         <span class="icon-bar"></span>
         <span class="icon-bar"></span>
         </button>
         <a class="navbar-brand" href="#">Logo</a>
      </div>
      <div class="collapse navbar-collapse" id="myNavbar">
         <ul class="nav navbar-nav">
            <li class="active"><a href="#">Home</a></li>
            <li><a href="#">About</a></li>
            <li><a href="#">Projects</a></li>
            <li><a href="#">Contact</a></li>
         </ul>
         <ul class="nav navbar-nav navbar-right">
            <li><a href="#"><span class="glyphicon glyphicon-log-in"></span> Login</a></li>
         </ul>
      </div>
   </div>
</nav>
<section id="about">
   <div class="container-fluid text-center">
      <div class="row content">
         <div class="col-lg-12">
            <h1>Welcome</h1>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
         </div>
      </div>
   </div>
</section>
<section id="img">
   <div class="container-fluid">
   <div class="row content">
      <div id="imgcont">
        <img class="img-responsive" src="http://www.qygjxz.com/data/out/162/6155406-mountain-images.jpeg" />
         <div id="header">
            <div class="title">
               <h1>Title in image centered</h1>
            </div>
         </div>
      </div>
   </div>
   <div class="row content text-center">
      <h1>More content, same section </h1>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum consectetur adipiscing elit.</p>
   </div>
</section>
<section id="howto">
   <div class="container-fluid">
      <div class="row content">
         <div class="col-lg-12">
            <h1>Welcome</h1>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
         </div>
      </div>
   </div>
</section>


来源: stackexchange

问:
programmatically add column & rows to WPF Datagrid
I want to know how should we add columns and rows programmatically to a DataGrid in WPF. The way we used to do it in windows forms. create table columns and rows, and bind it to DataGrid.

I have No. of rows and columns which I need to draw in DataGrid so that user can edit the data in the cells.

答:
I found a solution that adds columns at runtime, and binds to a DataTable.

How do I bind a WPF DataGrid to a variable number of columns?

Unfortunately, with 47 columns defined this way, it doesn't bind to the data fast enough for me.  Any suggestions?

xaml

```<code><DataGrid
  Name="dataGrid"
  AutoGenerateColumns="False"
  ItemsSource="{Binding}">
</DataGrid>
</code>```

xaml.cs
    using System.Windows.Data;

```<code>if (table != null) // table is a DataTable
{
  foreach (DataColumn col in table.Columns)
  {
    dataGrid.Columns.Add(
      new DataGridTextColumn
      {
        Header = col.ColumnName,
        Binding = new Binding(string.Format("[{0}]", col.ColumnName))
      });
  }

  dataGrid.DataContext = table;
}
</code>```

OwnerDisplayName: Andy

ContentLicense: CC BY-SA 4.0

Body:
I found a solution that adds columns at runtime, and binds to a DataTable.

How do I bind a WPF DataGrid to a variable number of columns?

Unfortunately, with 47 columns defined this way, it doesn't bind to the data fast enough for me.  Any suggestions?

xaml

<DataGrid
  Name="dataGrid"
  AutoGenerateColumns="False"
  ItemsSource="{Binding}">
</DataGrid>

xaml.cs
    using System.Windows.Data;

if (table != null) // table is a DataTable
{
  foreach (DataColumn col in table.Columns)
  {
    dataGrid.Columns.Add(
      new DataGridTextColumn
      {
        Header = col.ColumnName,
        Binding = new Binding(string.Format("[{0}]", col.ColumnName))
      });
  }

  dataGrid.DataContext = table;
}

ContentLicense: CC BY-SA 2.5


问:
"java(tm) binary has stopped working" error while running jmeter tests using ant via command prompt
I am getting following error while trying to run my jmeter tests using Ant via command prompt.

When I click on 'view problem details', I get following error.

```<code>*Problem signature:
  Problem Event Name:   APPCRASH
  Application Name: java.exe
  Application Version:  8.0.1210.13
  Application Timestamp:    584f5bdd
  Fault Module Name:    java.exe
  Fault Module Version: 8.0.1210.13
  Fault Module Timestamp:   584f5bdd
  Exception Code:   c0000005
  Exception Offset: 00009724
  OS Version:   6.1.7601.2.1.0.256.48
  Locale ID:    3081
  Additional Information 1: 0a9e
  Additional Information 2: 0a9e372d3b4ad19135b953a78882e789
  Additional Information 3: 0a9e
  Additional Information 4: 0a9e372d3b4ad19135b953a78882e789
Read our privacy statement online:
  http://go.microsoft.com/fwlink/?linkid=104288&clcid=0x0409
If the online privacy statement is not available, please read our privacy statement offline:
  C:\windows\system32\en-US\erofflps.txt*
</code>```

Can someone help please?

答:
Adding the <jvmarg value="-Xmx1024m"/> line under <jmeter> tag in build.xml works like Charm :)

Refer this for more details:-
Jmeter Java memory Issue

ContentLicense: CC BY-SA 3.0

Body:
I am getting following error while trying to run my jmeter tests using Ant via command prompt.

When I click on 'view problem details', I get following error.

*Problem signature:
  Problem Event Name:   APPCRASH
  Application Name: java.exe
  Application Version:  8.0.1210.13
  Application Timestamp:    584f5bdd
  Fault Module Name:    java.exe
  Fault Module Version: 8.0.1210.13
  Fault Module Timestamp:   584f5bdd
  Exception Code:   c0000005
  Exception Offset: 00009724
  OS Version:   6.1.7601.2.1.0.256.48
  Locale ID:    3081
  Additional Information 1: 0a9e
  Additional Information 2: 0a9e372d3b4ad19135b953a78882e789
  Additional Information 3: 0a9e
  Additional Information 4: 0a9e372d3b4ad19135b953a78882e789
Read our privacy statement online:
  http://go.microsoft.com/fwlink/?linkid=104288&clcid=0x0409
If the online privacy statement is not available, please read our privacy statement offline:
  C:\windows\system32\en-US\erofflps.txt*

Can someone help please?


问:
Single-responsability principle
Let's say you have abstract class A doing some stuff. Then you have abstract class B doing other stuff.

And lastly a few normal classes, let's say C ... Z.

Both A and B provide functionality that are used by class C .. Z classes. In my case mainly an observer pattern which is static, and some __get magic + lazy-loading for a certain type of properties - this is not static. I'm thinking to merge this into one class, but then I'm sure it violates SRP :)

So I am extending A, B in C, D etc... Essentially all C .. Z classes inherit the functionality of the A & B classes. So besides what they are supposed to do, they also do the observer stuff and so on

Does this violate the single-responsability principle?

答:
Multiple inheritance doesn't force this, but tends to lead to it. Your base interfaces are designed for a single purpose, inheriting both of them does create a class with multiple responsibilities.
You can partition your classes and interfaces into two major groups - the ones addressing the essential complexity of your system, and the ones addressing its accidental complexity. I think if you inherit from more than one "essential" classes, it is bad . But if you inherit from one "essential" and one or more "accidental" classes, it is normal.</p>

Title: Single-responsability principle


问:
PreferenceFragmentCompat not listening to first touch event
I created a PreferenceFragmentCompat settings everything is working fine but I noticed something odd, clicking on setting button first time when preference screen loaded and I touch on some preference it does not respond to my first touch but right after it works normally this is my code

```<code>public class SettingsFragment extends PreferenceFragmentCompat implements HomeActivity.Authentication, Preference.OnPreferenceClickListener, SharedPreferences.OnSharedPreferenceChangeListener, ConfirmAlertDialog.OnDialogClickInterface {
@Override
public boolean onPreferenceClick(final Preference preference) {
    final String key = preference.getKey();

    switch (key) {
        case "remove_ads":
            homeActivity.purchaseRemoveAds();
            break;
        case "hide_icon":
            try {
                homeActivity.loadFragment(new HideOptiosTutorial(), getParentFragment().getFragmentManager().beginTransaction());
            } catch (Exception e) {
                e.printStackTrace();
            }
            break;

        case "key_share_app_link":
            shareAppFile();

            break;

        case "move_to_sdcard":

            showMovetoSdDialog();

            break;
        case "button_internal":

            showMovetoInternalDialog();

            break;
        case "back_up_sdcard":
            if (isSDCardUnmounted()) {
                showSDCardMountError();
            } else {

                globalPasswords = getBackupPasswords();

                if (!FileUtilis.isSafAllowed(getActivity())) {
                    showSDCardNotAllowedDialog(983);
                    //
                    return false;
                }

                if (globalPasswords.size() == 0) {
                    showNoBackupFoundMsg();
                } else {
                    showDialogToBackupFromSDCard();
                }
            }
            break;
        case "change_password":
            showChangePinDialog();
            break;

        case "key_rate_us":
            rateApplication();
            break;
        case "app_link":
            SavedAlbumsFragment.showAppLockLink(getActivity());
            break;
        case "view_intruders":
            startActivity(new Intent(homeActivity, ViewIntruders.class));
            break;
        case "theme":
            showSelectTehmeDialog();
            break;

        case "enter_email":

            showChangeEmailDialog();
            break;
    }

    return false;
}
@Override
public void onCreatePreferences(Bundle bundle, String s) {
    addPreferencesFromResource(R.xml.pref_headers);
    Log.e("Mateen","onCreatePreferences");

    homeActivity = ((HomeActivity) getActivity());
    homeActivity.addAuthenticationListner(this);
    localDatabase = LocalDatabase.getInstance(getActivity());
    localPreferences = new LocalPreferences(getActivity());

    getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
    LocalBroadcastManager.getInstance(homeActivity).registerReceiver(broadcastReceiver,new IntentFilter("Remove_Is_Purchased"));

    removeAdsPref=findPreference("remove_ads");
    mCategory = (PreferenceCategory)findPreference("cat_remove_ads");

    if (localPreferences.IsRemovedAdsPurchased())
    {
        mCategory.removePreference(removeAdsPref);
        getPreferenceScreen().removePreference(mCategory);
    }
    else
    {
        removeAdsPref.setOnPreferenceClickListener(this);
    }

    findPreference("move_to_sdcard").setOnPreferenceClickListener(this);
    findPreference("view_intruders").setOnPreferenceClickListener(this);
    findPreference("button_internal").setOnPreferenceClickListener(this);
    findPreference("back_up_sdcard").setOnPreferenceClickListener(this);
    findPreference("change_password").setOnPreferenceClickListener(this);
    findPreference("key_rate_us").setOnPreferenceClickListener(this);
    findPreference("app_link").setOnPreferenceClickListener(this);
    findPreference("hide_icon").setOnPreferenceClickListener(this);
    findPreference("key_share_app_link").setOnPreferenceClickListener(this);
    findPreference("listPref_wrong_tries").setOnPreferenceClickListener(this);
    findPreference("theme").setOnPreferenceClickListener(this);
    findPreference("enter_email").setOnPreferenceClickListener(this);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        findPreference("key_cam_short").setVisible(false);
        findPreference("key_vid_short").setVisible(false);
    }

    if (!PreferenceManager.getDefaultSharedPreferences(homeActivity).getBoolean("key_intruder_detection",false))
    {
        findPreference("listPref_wrong_tries").setEnabled(false);
    }
    if (!Reprint.isHardwarePresent()) {
        findPreference("key_fingerprint").setEnabled(false);
    }

    if (!FileUtilis.isSdcardPresent(getActivity())) {
        findPreference("move_to_sdcard").setEnabled(false);
        findPreference("button_internal").setEnabled(false);
        findPreference("back_up_sdcard").setEnabled(false);

        //  findPreference("change_password").setEnabled(false);
        findPreference("always_save_to_sdcard").setEnabled(false);
    }
    //add xml

}
</code>```

and this is my preference xml:

```<code><android.support.v7.preference.PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.andr]oid.com/apk/res-auto"
app:key="preferenceScreen">

<!-- These settings headers are only used on tablets. -->z
<android.support.v7.preference.PreferenceCategory  android:title="@string/cate_remove_ads"
    android:key="cat_remove_ads">
    <Preference
        android:key="remove_ads"
        android:summary="@string/txt_remove_ads"
        android:title="@string/remove_ads" />
</android.support.v7.preference.PreferenceCategory>

<android.support.v7.preference.PreferenceCategory android:title="@string/storage">

    <Preference
        android:key="move_to_sdcard"
        android:summary="@string/export_sdcard_summary"
        android:title="@string/txt_move_to_external" />

    <Preference
        android:key="button_internal"
        android:summary="@string/export_internal_summary"
        android:title="@string/txt_move_too_internal" />

    <Preference
        android:key="back_up_sdcard"
        android:summary="@string/backup_summary"
        android:title="@string/back_from_sdcard" />

    <android.support.v7.preference.SwitchPreferenceCompat
        android:defaultValue="false"
        android:key="always_save_to_sdcard"
        android:summary="@string/always_on_sd_card"
        android:title="@string/sav_loc" />

</android.support.v7.preference.PreferenceCategory>

<android.support.v7.preference.PreferenceCategory android:title="@string/cate_security">

    <Preference
        android:key="hide_icon"
        android:title="@string/hide_icon" />

    <Preference
        android:key="app_link"
        android:summary="@string/app_link_title"
        android:title="@string/app_link_detail" />

    <Preference
        android:key="change_password"
        android:title="@string/chagne_password" />

    <Preference
        android:key="enter_email"
        android:title="@string/forgot_email_title"
        android:summary="@string/enter_email_to_recover" />

    <android.support.v7.preference.SwitchPreferenceCompat
        android:defaultValue="false"
        android:key="shuffle_pin"
        android:summary="@string/shuffle_summary"
        android:title="@string/shuffle_title" />

    <android.support.v7.preference.SwitchPreferenceCompat
        android:defaultValue="false"
        android:key="key_fingerprint"
        android:summary="@string/summary_fingerprint"
        android:title="@string/fingerprint_auth" />
</android.support.v7.preference.PreferenceCategory>

<android.support.v7.preference.PreferenceCategory android:title="@string/cate_intruder">
    <android.support.v7.preference.SwitchPreferenceCompat
        android:defaultValue="false"
        android:key="key_intruder_detection"
        android:summary="@string/take_intruder_picture_summary"
        android:title="@string/take_intruder_picture" />

    <android.support.v7.preference.ListPreference
        android:defaultValue="3"
        android:entries="@array/wrong_tries"
        android:entryValues="@array/wrong_tries"
        android:summary="%s"
        android:title="@string/wrong_tries"
        android:key="listPref_wrong_tries" />
    <Preference
        android:key="view_intruders"
        android:summary="@string/show_intruder_pic"
        android:title="@string/show_intruder_pic_summary" />
</android.support.v7.preference.PreferenceCategory>

<android.support.v7.preference.PreferenceCategory android:title="@string/cate_others">
    <Preference
        android:key="theme"
        android:summary="@string/chose_theme"
        android:title="@string/select_theme" />

    <android.support.v7.preference.SwitchPreferenceCompat
        android:defaultValue="false"
        android:key="key_cam_short"
        android:summary="@string/cam_short_detail"
        android:title="@string/sec_selfi_shortcut" />

    <android.support.v7.preference.SwitchPreferenceCompat
        android:defaultValue="false"
        android:key="key_vid_short"
        android:summary="@string/vid_short_detail"
        android:title="@string/sec_vid_shortcut" />

    <Preference
        android:key="key_share_app_link"
        android:summary="@string/share_app_link_detail"
        android:title="@string/share_app_link_title" />

    <Preference
        android:key="key_rate_us"
        android:summary="@string/rate_detail"
        android:title="@string/rate_us" />
</android.support.v7.preference.PreferenceCategory>
</code>```

Please guide me what am I doing wrong?
Is it support libs issue or I am doing something wrong?

答:
Appears to be support library bug. It works as expected after updating app gradle dependencies to support library 27.0.0</p>

```<code>implementation 'com.android.support:appcompat-v7:27.0.0'
implementation 'com.android.support:preference-v14:27.0.0'
implementation 'com.android.support:support-v13:27.0.0'
</code>```

Body:
I created a PreferenceFragmentCompat settings everything is working fine but I noticed something odd, clicking on setting button first time when preference screen loaded and I touch on some preference it does not respond to my first touch but right after it works normally this is my code

public class SettingsFragment extends PreferenceFragmentCompat implements HomeActivity.Authentication, Preference.OnPreferenceClickListener, SharedPreferences.OnSharedPreferenceChangeListener, ConfirmAlertDialog.OnDialogClickInterface {
@Override
public boolean onPreferenceClick(final Preference preference) {
    final String key = preference.getKey();

    switch (key) {
        case "remove_ads":
            homeActivity.purchaseRemoveAds();
            break;
        case "hide_icon":
            try {
                homeActivity.loadFragment(new HideOptiosTutorial(), getParentFragment().getFragmentManager().beginTransaction());
            } catch (Exception e) {
                e.printStackTrace();
            }
            break;

        case "key_share_app_link":
            shareAppFile();

            break;

        case "move_to_sdcard":

            showMovetoSdDialog();

            break;
        case "button_internal":

            showMovetoInternalDialog();

            break;
        case "back_up_sdcard":
            if (isSDCardUnmounted()) {
                showSDCardMountError();
            } else {

                globalPasswords = getBackupPasswords();

                if (!FileUtilis.isSafAllowed(getActivity())) {
                    showSDCardNotAllowedDialog(983);
                    //
                    return false;
                }

                if (globalPasswords.size() == 0) {
                    showNoBackupFoundMsg();
                } else {
                    showDialogToBackupFromSDCard();
                }
            }
            break;
        case "change_password":
            showChangePinDialog();
            break;

        case "key_rate_us":
            rateApplication();
            break;
        case "app_link":
            SavedAlbumsFragment.showAppLockLink(getActivity());
            break;
        case "view_intruders":
            startActivity(new Intent(homeActivity, ViewIntruders.class));
            break;
        case "theme":
            showSelectTehmeDialog();
            break;

        case "enter_email":

            showChangeEmailDialog();
            break;
    }

    return false;
}
@Override
public void onCreatePreferences(Bundle bundle, String s) {
    addPreferencesFromResource(R.xml.pref_headers);
    Log.e("Mateen","onCreatePreferences");

    homeActivity = ((HomeActivity) getActivity());
    homeActivity.addAuthenticationListner(this);
    localDatabase = LocalDatabase.getInstance(getActivity());
    localPreferences = new LocalPreferences(getActivity());

    getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
    LocalBroadcastManager.getInstance(homeActivity).registerReceiver(broadcastReceiver,new IntentFilter("Remove_Is_Purchased"));

    removeAdsPref=findPreference("remove_ads");
    mCategory = (PreferenceCategory)findPreference("cat_remove_ads");

    if (localPreferences.IsRemovedAdsPurchased())
    {
        mCategory.removePreference(removeAdsPref);
        getPreferenceScreen().removePreference(mCategory);
    }
    else
    {
        removeAdsPref.setOnPreferenceClickListener(this);
    }

    findPreference("move_to_sdcard").setOnPreferenceClickListener(this);
    findPreference("view_intruders").setOnPreferenceClickListener(this);
    findPreference("button_internal").setOnPreferenceClickListener(this);
    findPreference("back_up_sdcard").setOnPreferenceClickListener(this);
    findPreference("change_password").setOnPreferenceClickListener(this);
    findPreference("key_rate_us").setOnPreferenceClickListener(this);
    findPreference("app_link").setOnPreferenceClickListener(this);
    findPreference("hide_icon").setOnPreferenceClickListener(this);
    findPreference("key_share_app_link").setOnPreferenceClickListener(this);
    findPreference("listPref_wrong_tries").setOnPreferenceClickListener(this);
    findPreference("theme").setOnPreferenceClickListener(this);
    findPreference("enter_email").setOnPreferenceClickListener(this);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        findPreference("key_cam_short").setVisible(false);
        findPreference("key_vid_short").setVisible(false);
    }

    if (!PreferenceManager.getDefaultSharedPreferences(homeActivity).getBoolean("key_intruder_detection",false))
    {
        findPreference("listPref_wrong_tries").setEnabled(false);
    }
    if (!Reprint.isHardwarePresent()) {
        findPreference("key_fingerprint").setEnabled(false);
    }

    if (!FileUtilis.isSdcardPresent(getActivity())) {
        findPreference("move_to_sdcard").setEnabled(false);
        findPreference("button_internal").setEnabled(false);
        findPreference("back_up_sdcard").setEnabled(false);

        //  findPreference("change_password").setEnabled(false);
        findPreference("always_save_to_sdcard").setEnabled(false);
    }
    //add xml

}

and this is my preference xml:

<android.support.v7.preference.PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.andr]oid.com/apk/res-auto"
app:key="preferenceScreen">

z
<android.support.v7.preference.PreferenceCategory  android:title="@string/cate_remove_ads"
    android:key="cat_remove_ads">
    <Preference
        android:key="remove_ads"
        android:summary="@string/txt_remove_ads"
        android:title="@string/remove_ads" />
</android.support.v7.preference.PreferenceCategory>

<android.support.v7.preference.PreferenceCategory android:title="@string/storage">

    <Preference
        android:key="move_to_sdcard"
        android:summary="@string/export_sdcard_summary"
        android:title="@string/txt_move_to_external" />

    <Preference
        android:key="button_internal"
        android:summary="@string/export_internal_summary"
        android:title="@string/txt_move_too_internal" />

    <Preference
        android:key="back_up_sdcard"
        android:summary="@string/backup_summary"
        android:title="@string/back_from_sdcard" />

    <android.support.v7.preference.SwitchPreferenceCompat
        android:defaultValue="false"
        android:key="always_save_to_sdcard"
        android:summary="@string/always_on_sd_card"
        android:title="@string/sav_loc" />

</android.support.v7.preference.PreferenceCategory>

<android.support.v7.preference.PreferenceCategory android:title="@string/cate_security">

    <Preference
        android:key="hide_icon"
        android:title="@string/hide_icon" />

    <Preference
        android:key="app_link"
        android:summary="@string/app_link_title"
        android:title="@string/app_link_detail" />

    <Preference
        android:key="change_password"
        android:title="@string/chagne_password" />

    <Preference
        android:key="enter_email"
        android:title="@string/forgot_email_title"
        android:summary="@string/enter_email_to_recover" />

    <android.support.v7.preference.SwitchPreferenceCompat
        android:defaultValue="false"
        android:key="shuffle_pin"
        android:summary="@string/shuffle_summary"
        android:title="@string/shuffle_title" />

    <android.support.v7.preference.SwitchPreferenceCompat
        android:defaultValue="false"
        android:key="key_fingerprint"
        android:summary="@string/summary_fingerprint"
        android:title="@string/fingerprint_auth" />
</android.support.v7.preference.PreferenceCategory>

<android.support.v7.preference.PreferenceCategory android:title="@string/cate_intruder">
    <android.support.v7.preference.SwitchPreferenceCompat
        android:defaultValue="false"
        android:key="key_intruder_detection"
        android:summary="@string/take_intruder_picture_summary"
        android:title="@string/take_intruder_picture" />

    <android.support.v7.preference.ListPreference
        android:defaultValue="3"
        android:entries="@array/wrong_tries"
        android:entryValues="@array/wrong_tries"
        android:summary="%s"
        android:title="@string/wrong_tries"
        android:key="listPref_wrong_tries" />
    <Preference
        android:key="view_intruders"
        android:summary="@string/show_intruder_pic"
        android:title="@string/show_intruder_pic_summary" />
</android.support.v7.preference.PreferenceCategory>

<android.support.v7.preference.PreferenceCategory android:title="@string/cate_others">
    <Preference
        android:key="theme"
        android:summary="@string/chose_theme"
        android:title="@string/select_theme" />

    <android.support.v7.preference.SwitchPreferenceCompat
        android:defaultValue="false"
        android:key="key_cam_short"
        android:summary="@string/cam_short_detail"
        android:title="@string/sec_selfi_shortcut" />

    <android.support.v7.preference.SwitchPreferenceCompat
        android:defaultValue="false"
        android:key="key_vid_short"
        android:summary="@string/vid_short_detail"
        android:title="@string/sec_vid_shortcut" />

    <Preference
        android:key="key_share_app_link"
        android:summary="@string/share_app_link_detail"
        android:title="@string/share_app_link_title" />

    <Preference
        android:key="key_rate_us"
        android:summary="@string/rate_detail"
        android:title="@string/rate_us" />
</android.support.v7.preference.PreferenceCategory>

Please guide me what am I doing wrong?
Is it support libs issue or I am doing something wrong?

Body:
Appears to be support library bug. It works as expected after updating app gradle dependencies to support library 27.0.0

implementation 'com.android.support:appcompat-v7:27.0.0'
implementation 'com.android.support:preference-v14:27.0.0'
implementation 'com.android.support:support-v13:27.0.0'


答:
Not happy with the solution but this I think gives the answer. There is still scope of improvement :

```<code>unique(sapply(lst, function(x)
       unique(unlist(lst[sapply(lst, function(y)
                         any(x %in% y))]))))

#[[1]]
#[1] 7

#[[2]]
#[1]  10  11  12 211 446 469  13 215

#[[3]]
#[1]  15  16  17 216 225
</code>```

This is basically double loop to check if any of the list element is present in any another list. If you find any such element then merge them together taking only unique values out of them.

data

```<code>lst <- list(7, c(10 ,11 ,12, 211, 446, 469), c(10, 11, 12, 13),c(11 ,12, 13 ,215),
               c(15, 16), c(15, 17 ,216 ,225))
</code>```

Title: Merging list with common elements

Body:
I have a list

[[1]]
[1] 7

[[2]]
[1] 10 11 12 211 446 469

[[3]]
[1] 10 11 12 13

[[4]]
[1] 11 12 13 215

[[5]]
[1] 15 16

[[6]]
[1] 15 17 216 225

I want to merge list slices that have common elements, and index which list slices have been merged. My desired output is below.

$`1`
[1] 7

$`2`, `3`, `4`
[1] 10 11 12 13 211 215 446 469

$`5`,`6`
[1] 15 16 17 216 225

(I've put the original list slice indices as new list names, but any form of output is fine.)

Reproducible data:

mylist <- list(7, c(10, 11, 12, 211, 446, 469), c(10, 11, 12, 13), c(11,
12, 13, 215), c(15, 16), c(15, 17, 216, 225))

Body:
Not happy with the solution but this I think gives the answer. There is still scope of improvement :

unique(sapply(lst, function(x)
       unique(unlist(lst[sapply(lst, function(y)
                         any(x %in% y))]))))

#[[1]]
#[1] 7

#[[2]]
#[1]  10  11  12 211 446 469  13 215

#[[3]]
#[1]  15  16  17 216 225

This is basically double loop to check if any of the list element is present in any another list. If you find any such element then merge them together taking only unique values out of them.

data

lst <- list(7, c(10 ,11 ,12, 211, 446, 469), c(10, 11, 12, 13),c(11 ,12, 13 ,215),
               c(15, 16), c(15, 17 ,216 ,225))


问:
Missing HttpOnly Attribute for Session Identifier with HTTP protocol
Earlier I was getting HttpOnly for both HTTP/HTTPS protocol, but missing secure attribute.

In order to add "Secure" attribute, I added secure="true" in server.xml ’s Connector port syntax as below –

```<code><Connector address="10.23.17.69" port="8000" maxHttpHeaderSize="8192"
           maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
           enableLookups="false" redirectPort="8443" acceptCount="100"
           connectionTimeout="60000" disableUploadTimeout="true" URIEncoding="UTF-8"  server="Dev" secure="true" />
</code>```

Also added "cookie-config" in web.xml as below –

```<code><session-config>
    <session-timeout>120</session-timeout>
    <cookie-config>
        <secure>true</secure>
        <http-only>true</http-only>
    </cookie-config>
</session-config>
</code>```

Now for HTTPS protocol, I’m getting ‘Secure’ and ‘HttpOnly’ flags as true for Session cookie as below.

But for HTTP protocol, I'm not getting HttpOnly attribute. I need "HttpOnly=true" in case of HTTP protocol.

Please note, my context.xml's "Context" element already contains useHttpOnly attribute as following -

```<code><Context useHttpOnly="true">
 ....
</Context>
</code>```

Any suggestion is much appreciated.

答:
Read this article I think you have incorrectly set the session cookies attribute.

It should be:

```<code><Context cookies="true" crossContext="true">
  <SessionCookie secure="true" httpOnly="true" />
</code>```

Body:
Earlier I was getting HttpOnly for both HTTP/HTTPS protocol, but missing secure attribute.

In order to add "Secure" attribute, I added secure="true" in server.xml ’s Connector port syntax as below –

<Connector address="10.23.17.69" port="8000" maxHttpHeaderSize="8192"
           maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
           enableLookups="false" redirectPort="8443" acceptCount="100"
           connectionTimeout="60000" disableUploadTimeout="true" URIEncoding="UTF-8"  server="Dev" secure="true" />

Also added "cookie-config" in web.xml as below –

<session-config>
    <session-timeout>120</session-timeout>
    <cookie-config>
        <secure>true</secure>
        <http-only>true</http-only>
    </cookie-config>
</session-config>

Now for HTTPS protocol, I’m getting ‘Secure’ and ‘HttpOnly’ flags as true for Session cookie as below.

But for HTTP protocol, I'm not getting HttpOnly attribute. I need "HttpOnly=true" in case of HTTP protocol.

Please note, my context.xml's "Context" element already contains useHttpOnly attribute as following -

<Context useHttpOnly="true">
 ....
</Context>

Any suggestion is much appreciated.

Body:
Read this article I think you have incorrectly set the session cookies attribute.

It should be:

<Context cookies="true" crossContext="true">
  <SessionCookie secure="true" httpOnly="true" />


问:
OnBackButton pressed Issue
I have 3 Activities A, B, and C.

A is the home activity and B is its child and C is its child.

When I go to Activity C and return to A by pressing back button it gets proper navigation. But after this, if I press back button again to exit the app, it goes back to Activity B instead of exiting the app.

I have finished the Activity B onBackpressed override.

And I have implemented dynamic fragments on Activity B is that causes this problem.

I can't find out why this happens. Does Anyone have an answer?

答:
```<code>B.b.finish();
</code>```

Explanation :
Declare this in B Activity :

```<code>private static B(classname) b(some name);
</code>```

Call this in which class do you  finish B Activity :

```<code>B.b.finish();
</code>```

Title: OnBackButton pressed Issue

Body:
B.b.finish();

Explanation :
Declare this in B Activity :

private static B(classname) b(some name);

Call this in which class do you  finish B Activity :

B.b.finish();


问:
output parameter
how to get output parameter from stored procedure of one table and by using that value how to insert data in another table which is in realation with that table? </p>

答:
You can use something like this:

```<code>CREATE PROCEDURE dbo.InsertNewImage
 @ImageTitle nvarchar(30),
 @ImageDescription nvarchar(100),
 @ImageFilename nvarchar(50),
 @ImageThumbnail image,
 @AlbumID int
AS
 Begin

  Set Nocount On

  DECLARE @ImageID int

  INSERT INTO Images(ImageTitle, ImageDescription, ImageFilename, ImageThumbnail)
  VALUES (@ImageTitle, @ImageDescription, @ImageFilename, @ImageThumbnail)

  SELECT @ImageID=@@IDENTITY

  INSERT INTO ImageInAlbum(ImageId, AlbumId)
  VALUES (@ImageID, @AlbumID)

 End
</code>```

Note: Use SCOPE_IDENTITY() instead of @@IDENTITY if you're using SQL Server 2005 + (I think)

OwnerDisplayName: Amit

Title: output parameter

Body:
You can use something like this:

CREATE PROCEDURE dbo.InsertNewImage
 @ImageTitle nvarchar(30),
 @ImageDescription nvarchar(100),
 @ImageFilename nvarchar(50),
 @ImageThumbnail image,
 @AlbumID int
AS
 Begin

  Set Nocount On

  DECLARE @ImageID int

  INSERT INTO Images(ImageTitle, ImageDescription, ImageFilename, ImageThumbnail)
  VALUES (@ImageTitle, @ImageDescription, @ImageFilename, @ImageThumbnail)

  SELECT @ImageID=@@IDENTITY

  INSERT INTO ImageInAlbum(ImageId, AlbumId)
  VALUES (@ImageID, @AlbumID)

 End

Note: Use SCOPE_IDENTITY() instead of @@IDENTITY if you're using SQL Server 2005 + (I think)

OwnerDisplayName: Galwegian


问:
How to fix unwanted new line in java?
I am trying to figure why my code is creating a new line every time a return method called is within a for-loop. The if statement within the main for-loop checks every Student Object inside the array list named list. After it is done comparing Student i to Student j (Student j being the second for-loop). Once Student i have found the best match, it is supposed to print out a statement saying either he/she has matched with someone.

Here is what it is supposed to return:

```<code>Abey matches with Melissa with score 60
John matches with Jeff with score 100
Craig has no matches.
</code>```

Instead, it returns this:

```<code>Abey matches with
Melissa with score 60

John matches with
Jeff with score 100

Craig has no matches.
</code>```

Here is the code:

```<code>    for (int i = 0; i < list.size(); i++) {
    int maxScore = 0;
    int currentScore = 0;
    int bestMatchScore = 0;
    int bestMatchStudent = 0;
    if (!list.get(i).isMatched()) {
        for (int j = i; j < list.size(); j++) {
            if (!list.get(j).isMatched()) {
                if (j != i) {
                currentScore = list.get(i).compare(list.get(j));
                if (currentScore > maxScore) {
                    maxScore = currentScore;
                    bestMatchStudent = j;
                    bestMatchScore = maxScore;
                }
                }
            }
        }
            if(bestMatchScore == 0) {
                System.out.println(list.get(i).getName() + " has no matches.");
                }
            else {
                list.get(i).setMatched(list.get(bestMatchStudent));

                System.out.println(list.get(i).getName() + " matches with " + list.get(bestMatchStudent).getName() + " with score " + maxScore);
            }
        }
    }
</code>```

If I were to remove all of the getName() inside the if-else statement, I get an output that is sort of what I desire:

```<code>Student@6d3552ed matches with Student@47d77d9e with score 60
Student@147834eb matches with Student@5fda3acc with score 100
Student@704a583d has no matches.
</code>```

I suspect that it has to do something with calling the getName method. All it is is an accessor method...

Here is all the code to reproduce the problem:

Student Class

```<code>public class Student {
    private String name;
    private char gender;
    private Date birthdate;
    private Preference pref;
    private boolean matched;

public Student(String name, char gender, Date birthdate, Preference pref) {
    this.name = name;
    this.gender = gender;
    this.birthdate = birthdate;
    this.pref = pref;
}

public String getName() {
    return name;
}

public char getGender() {
    return gender;
}

public Date getBirthdate() {
    return birthdate;
}

public Preference getPref() {
    return pref;
}

public boolean isMatched() {
    return matched;
}

public void setMatched() {
    this.matched = true;
}

public void setMatched(Student roommate) {
    setMatched();
    roommate.setMatched();
}

public int compare(Student st) {
    if (st.getGender() != gender)
        return 0;
    return Math.abs((40 - pref.compare(st.getPref())) + (60 - birthdate.compare(st.getBirthdate())));
}

}
</code>```

Match Class

```<code>import java.io.*;
import java.util.Scanner;
import java.util.*;
public class Match {

public static void main(String[] args) throws FileNotFoundException {
    //Student[] fullRoster = new Student[5]; converted to ArrayList
    ArrayList<Student> list = new ArrayList<Student>();
    String fileName = "Students.txt";
    Scanner input = new Scanner(new FileReader(fileName));
    input.useDelimiter("[\t\r-]");
    //int studentIndex = 0; converted to ArrayList
    while(input.hasNext()) {
        String name = input.next();
        //System.out.println(name);
        char gender = input.next().charAt(0);
        //System.out.println(gender);
        int month = Integer.parseInt(input.next());
        //System.out.println(month);
        int day = Integer.parseInt(input.next());
        //System.out.println(day);
        int year = Integer.parseInt(input.next());
        //System.out.println(year);
        Date birthday = new Date(year, month, day);
        //System.out.println(birthday); //Printed out birthday
        int pref1 = Integer.parseInt(input.next());
        //System.out.println(pref1);
        int pref2 = Integer.parseInt(input.next());
        //System.out.println(pref2);
        int pref3 = Integer.parseInt(input.next());
        //System.out.println(pref3);
        int pref4 = Integer.parseInt(input.next());
        //System.out.println(pref4);
        Preference pref = new Preference(pref1, pref2, pref3, pref4);
        //System.out.println(pref); //Printed out pref
        //fullRoster[studentIndex] = new Student(name, gender, birthday, pref); converted to ArrayList
        list.add(new Student(name, gender, birthday, pref));
        //studentIndex++; converted to ArrayList
    }

    input.close();

    for (int i = 0; i < list.size(); i++) {
    int maxScore = 0;
    int currentScore = 0;
    int bestMatchScore = 0;
    int bestMatchStudent = 0;
    if (!list.get(i).isMatched()) {
        for (int j = i; j < list.size(); j++) {
            if (!list.get(j).isMatched()) {
                if (j != i) {
                currentScore = list.get(i).compare(list.get(j));
                if (currentScore > maxScore) {
                    maxScore = currentScore;
                    bestMatchStudent = j;
                    bestMatchScore = maxScore;
                }
                }
            }
        }
            if(bestMatchScore == 0) {
                System.out.println(list.get(i) + " has no matches.");
                }
            else {
                list.get(i).setMatched(list.get(bestMatchStudent));

                System.out.println(list.get(i).getName() + " matches with " + list.get(bestMatchStudent) + " with score " + maxScore);
            }
        }
    }
}
}
</code>```

Preference Class

```<code>public class Preference {
private int quietTime, music, reading, chatting;

public Preference(int quietTime, int music, int reading, int chatting) {
    this.quietTime = quietTime;
    this.music = music;
    this.reading = reading;
    this.chatting = chatting;
}

public int getQuietTime() {
    return quietTime;
}

public int getMusic() {
    return music;
}

public int getReading() {
    return reading;
}

public int getChatting() {
    return chatting;
}

public int compare(Preference pref) {
    int difference = 0;
    difference += Math.abs(pref.getQuietTime() - this.getQuietTime());
    difference += Math.abs(pref.getMusic() - this.getMusic());
    difference += Math.abs(pref.getReading() - this.getReading());
    difference += Math.abs(pref.getChatting() - this.getChatting());
    return difference;
}

}
</code>```

Date Class

```<code>public class Date {
int year, month, day;

public Date(int year, int month, int day) {
    this.year = year;
    this.month = month;
    this.day = day;
}

public int getYear() {
    return year;
}

public int getMonth() {
    return month;
}

public int getDay() {
    return day;
}

public int compare(Date dt) {
    int yearsDifferenceInDays = (Math.abs(year - dt.getYear())) * 365;
    int daysDifference = Math.abs(dt.dayOfYear() - this.dayOfYear());
    int totalDifference = Math.abs(yearsDifferenceInDays - daysDifference);
    int monthsDifference = totalDifference / 30;
    if(monthsDifference > 60)
        return 60;
    return monthsDifference;
}

public int dayOfYear() {
    int totalDays = 0;
    switch (month) {
    case 12: totalDays += 30;
    case 11: totalDays += 31;
    case 10: totalDays += 30;
    case 9 : totalDays += 31;
    case 8 : totalDays += 31;
    case 7 : totalDays += 30;
    case 6 : totalDays += 31;
    case 5 : totalDays += 30;
    case 4 : totalDays += 31;
    case 3 : totalDays += 28;
    case 2 : totalDays += 31;
    }
    totalDays += day;
    return totalDays;
    }
}
</code>```

Match Class

```<code>import java.io.*;
import java.util.Scanner;
import java.util.*;

public class Match {

public static void main(String[] args) throws FileNotFoundException {
    //Student[] fullRoster = new Student[5]; converted to ArrayList
    ArrayList<Student> list = new ArrayList<Student>();
    String fileName = "Students.txt";
    Scanner input = new Scanner(new FileReader(fileName));
    input.useDelimiter("[\t\r-]");
    //int studentIndex = 0; converted to ArrayList
    while(input.hasNext()) {
        String name = input.next();
        //System.out.println(name);
        char gender = input.next().charAt(0);
        //System.out.println(gender);
        int month = Integer.parseInt(input.next());
        //System.out.println(month);
        int day = Integer.parseInt(input.next());
        //System.out.println(day);
        int year = Integer.parseInt(input.next());
        //System.out.println(year);
        Date birthday = new Date(year, month, day);
        //System.out.println(birthday); //Printed out birthday
        int pref1 = Integer.parseInt(input.next());
        //System.out.println(pref1);
        int pref2 = Integer.parseInt(input.next());
        //System.out.println(pref2);
        int pref3 = Integer.parseInt(input.next());
        //System.out.println(pref3);
        int pref4 = Integer.parseInt(input.next());
        //System.out.println(pref4);
        Preference pref = new Preference(pref1, pref2, pref3, pref4);
        //System.out.println(pref); //Printed out pref
        //fullRoster[studentIndex] = new Student(name, gender, birthday, pref); converted to ArrayList
        list.add(new Student(name, gender, birthday, pref));
        //studentIndex++; converted to ArrayList
    }

    input.close();

    for (int i = 0; i < list.size(); i++) {
    int maxScore = 0;
    int currentScore = 0;
    int bestMatchScore = 0;
    int bestMatchStudent = 0;
    if (!list.get(i).isMatched()) {
        for (int j = i; j < list.size(); j++) {
            if (!list.get(j).isMatched()) {
                if (j != i) {
                currentScore = list.get(i).compare(list.get(j));
                if (currentScore > maxScore) {
                    maxScore = currentScore;
                    bestMatchStudent = j;
                    bestMatchScore = maxScore;
                }
                }
            }
        }
            if(bestMatchScore == 0) {
                System.out.println(list.get(i) + " has no matches.");
                }
            else {
                list.get(i).setMatched(list.get(bestMatchStudent));

                System.out.println(list.get(i).getName() + " matches with " + list.get(bestMatchStudent) + " with score " + maxScore);
            }
        }
    }
}
}
</code>```

Students.txt

```<code>Abey    F   5-5-1996    0   0   0   0
John    M   5-5-1997    10  10  10  10
Melissa F   5-5-1996    10  10  10  10
Craig   M   5-5-1998    5   5   5   5
Jeff    M   5-5-1997    10  10  10  10
</code>```

答:
If I were to remove all of the getName() inside the if-else statement, I get an output that is sort of what I desire:

```<code>Student@6d3552ed matches with Student@47d77d9e with score 60
Student@147834eb matches with Student@5fda3acc with score 100
Student@704a583d has no matches.
</code>```

That output is explained here How do I print my Java object without getting "SomeType@2f92e0f4"?

Seems like you just need to trim() the name.

Depending on where you want your "input validation" to be oerformed, you could do that at input.

```<code>String name = input.next().trim();
</code>```

Or in the constuctor

```<code>public Student(String name, char gender, Date birthdate, Preference pref) {
    this.name = name.trim();
    this.gender = gender;
    this.birthdate = birthdate;
    this.pref = pref;
}
</code>```

Or in the getter

```<code>public String getName() {
    return name.trim();
}
</code>```

Or when you actually display the value in the println

Or define toString(), as explained in the other post to return name.trim();, and just print list.get(i), as you had done.

The root issue may be that you haven't defined LF (\n) or CRLF (\r\n) as a delimiter.

```<code>input.useDelimiter("[\t\r-]");
</code>```

Try

```<code>input.useDelimiter("\r\n|[\t\r\n-]");
</code>```

Title: How to fix unwanted new line in java?

Body:
I am trying to figure why my code is creating a new line every time a return method called is within a for-loop. The if statement within the main for-loop checks every Student Object inside the array list named list. After it is done comparing Student i to Student j (Student j being the second for-loop). Once Student i have found the best match, it is supposed to print out a statement saying either he/she has matched with someone.

Here is what it is supposed to return:

Abey matches with Melissa with score 60
John matches with Jeff with score 100
Craig has no matches.

Instead, it returns this:

Abey matches with
Melissa with score 60

John matches with
Jeff with score 100

Craig has no matches.

Here is the code:

    for (int i = 0; i < list.size(); i++) {
    int maxScore = 0;
    int currentScore = 0;
    int bestMatchScore = 0;
    int bestMatchStudent = 0;
    if (!list.get(i).isMatched()) {
        for (int j = i; j < list.size(); j++) {
            if (!list.get(j).isMatched()) {
                if (j != i) {
                currentScore = list.get(i).compare(list.get(j));
                if (currentScore > maxScore) {
                    maxScore = currentScore;
                    bestMatchStudent = j;
                    bestMatchScore = maxScore;
                }
                }
            }
        }
            if(bestMatchScore == 0) {
                System.out.println(list.get(i).getName() + " has no matches.");
                }
            else {
                list.get(i).setMatched(list.get(bestMatchStudent));

                System.out.println(list.get(i).getName() + " matches with " + list.get(bestMatchStudent).getName() + " with score " + maxScore);
            }
        }
    }

If I were to remove all of the getName() inside the if-else statement, I get an output that is sort of what I desire:

Student@6d3552ed matches with Student@47d77d9e with score 60
Student@147834eb matches with Student@5fda3acc with score 100
Student@704a583d has no matches.

I suspect that it has to do something with calling the getName method. All it is is an accessor method...

Here is all the code to reproduce the problem:

Student Class

public class Student {
    private String name;
    private char gender;
    private Date birthdate;
    private Preference pref;
    private boolean matched;

public Student(String name, char gender, Date birthdate, Preference pref) {
    this.name = name;
    this.gender = gender;
    this.birthdate = birthdate;
    this.pref = pref;
}

public String getName() {
    return name;
}

public char getGender() {
    return gender;
}

public Date getBirthdate() {
    return birthdate;
}

public Preference getPref() {
    return pref;
}

public boolean isMatched() {
    return matched;
}

public void setMatched() {
    this.matched = true;
}

public void setMatched(Student roommate) {
    setMatched();
    roommate.setMatched();
}

public int compare(Student st) {
    if (st.getGender() != gender)
        return 0;
    return Math.abs((40 - pref.compare(st.getPref())) + (60 - birthdate.compare(st.getBirthdate())));
}

}

Match Class

import java.io.*;
import java.util.Scanner;
import java.util.*;
public class Match {

public static void main(String[] args) throws FileNotFoundException {
    //Student[] fullRoster = new Student[5]; converted to ArrayList
    ArrayList<Student> list = new ArrayList<Student>();
    String fileName = "Students.txt";
    Scanner input = new Scanner(new FileReader(fileName));
    input.useDelimiter("[\t\r-]");
    //int studentIndex = 0; converted to ArrayList
    while(input.hasNext()) {
        String name = input.next();
        //System.out.println(name);
        char gender = input.next().charAt(0);
        //System.out.println(gender);
        int month = Integer.parseInt(input.next());
        //System.out.println(month);
        int day = Integer.parseInt(input.next());
        //System.out.println(day);
        int year = Integer.parseInt(input.next());
        //System.out.println(year);
        Date birthday = new Date(year, month, day);
        //System.out.println(birthday); //Printed out birthday
        int pref1 = Integer.parseInt(input.next());
        //System.out.println(pref1);
        int pref2 = Integer.parseInt(input.next());
        //System.out.println(pref2);
        int pref3 = Integer.parseInt(input.next());
        //System.out.println(pref3);
        int pref4 = Integer.parseInt(input.next());
        //System.out.println(pref4);
        Preference pref = new Preference(pref1, pref2, pref3, pref4);
        //System.out.println(pref); //Printed out pref
        //fullRoster[studentIndex] = new Student(name, gender, birthday, pref); converted to ArrayList
        list.add(new Student(name, gender, birthday, pref));
        //studentIndex++; converted to ArrayList
    }

    input.close();

    for (int i = 0; i < list.size(); i++) {
    int maxScore = 0;
    int currentScore = 0;
    int bestMatchScore = 0;
    int bestMatchStudent = 0;
    if (!list.get(i).isMatched()) {
        for (int j = i; j < list.size(); j++) {
            if (!list.get(j).isMatched()) {
                if (j != i) {
                currentScore = list.get(i).compare(list.get(j));
                if (currentScore > maxScore) {
                    maxScore = currentScore;
                    bestMatchStudent = j;
                    bestMatchScore = maxScore;
                }
                }
            }
        }
            if(bestMatchScore == 0) {
                System.out.println(list.get(i) + " has no matches.");
                }
            else {
                list.get(i).setMatched(list.get(bestMatchStudent));

                System.out.println(list.get(i).getName() + " matches with " + list.get(bestMatchStudent) + " with score " + maxScore);
            }
        }
    }
}
}

Preference Class

public class Preference {
private int quietTime, music, reading, chatting;

public Preference(int quietTime, int music, int reading, int chatting) {
    this.quietTime = quietTime;
    this.music = music;
    this.reading = reading;
    this.chatting = chatting;
}

public int getQuietTime() {
    return quietTime;
}

public int getMusic() {
    return music;
}

public int getReading() {
    return reading;
}

public int getChatting() {
    return chatting;
}

public int compare(Preference pref) {
    int difference = 0;
    difference += Math.abs(pref.getQuietTime() - this.getQuietTime());
    difference += Math.abs(pref.getMusic() - this.getMusic());
    difference += Math.abs(pref.getReading() - this.getReading());
    difference += Math.abs(pref.getChatting() - this.getChatting());
    return difference;
}

}

Date Class

public class Date {
int year, month, day;

public Date(int year, int month, int day) {
    this.year = year;
    this.month = month;
    this.day = day;
}

public int getYear() {
    return year;
}

public int getMonth() {
    return month;
}

public int getDay() {
    return day;
}

public int compare(Date dt) {
    int yearsDifferenceInDays = (Math.abs(year - dt.getYear())) * 365;
    int daysDifference = Math.abs(dt.dayOfYear() - this.dayOfYear());
    int totalDifference = Math.abs(yearsDifferenceInDays - daysDifference);
    int monthsDifference = totalDifference / 30;
    if(monthsDifference > 60)
        return 60;
    return monthsDifference;
}

public int dayOfYear() {
    int totalDays = 0;
    switch (month) {
    case 12: totalDays += 30;
    case 11: totalDays += 31;
    case 10: totalDays += 30;
    case 9 : totalDays += 31;
    case 8 : totalDays += 31;
    case 7 : totalDays += 30;
    case 6 : totalDays += 31;
    case 5 : totalDays += 30;
    case 4 : totalDays += 31;
    case 3 : totalDays += 28;
    case 2 : totalDays += 31;
    }
    totalDays += day;
    return totalDays;
    }
}

Match Class

import java.io.*;
import java.util.Scanner;
import java.util.*;

public class Match {

public static void main(String[] args) throws FileNotFoundException {
    //Student[] fullRoster = new Student[5]; converted to ArrayList
    ArrayList<Student> list = new ArrayList<Student>();
    String fileName = "Students.txt";
    Scanner input = new Scanner(new FileReader(fileName));
    input.useDelimiter("[\t\r-]");
    //int studentIndex = 0; converted to ArrayList
    while(input.hasNext()) {
        String name = input.next();
        //System.out.println(name);
        char gender = input.next().charAt(0);
        //System.out.println(gender);
        int month = Integer.parseInt(input.next());
        //System.out.println(month);
        int day = Integer.parseInt(input.next());
        //System.out.println(day);
        int year = Integer.parseInt(input.next());
        //System.out.println(year);
        Date birthday = new Date(year, month, day);
        //System.out.println(birthday); //Printed out birthday
        int pref1 = Integer.parseInt(input.next());
        //System.out.println(pref1);
        int pref2 = Integer.parseInt(input.next());
        //System.out.println(pref2);
        int pref3 = Integer.parseInt(input.next());
        //System.out.println(pref3);
        int pref4 = Integer.parseInt(input.next());
        //System.out.println(pref4);
        Preference pref = new Preference(pref1, pref2, pref3, pref4);
        //System.out.println(pref); //Printed out pref
        //fullRoster[studentIndex] = new Student(name, gender, birthday, pref); converted to ArrayList
        list.add(new Student(name, gender, birthday, pref));
        //studentIndex++; converted to ArrayList
    }

    input.close();

    for (int i = 0; i < list.size(); i++) {
    int maxScore = 0;
    int currentScore = 0;
    int bestMatchScore = 0;
    int bestMatchStudent = 0;
    if (!list.get(i).isMatched()) {
        for (int j = i; j < list.size(); j++) {
            if (!list.get(j).isMatched()) {
                if (j != i) {
                currentScore = list.get(i).compare(list.get(j));
                if (currentScore > maxScore) {
                    maxScore = currentScore;
                    bestMatchStudent = j;
                    bestMatchScore = maxScore;
                }
                }
            }
        }
            if(bestMatchScore == 0) {
                System.out.println(list.get(i) + " has no matches.");
                }
            else {
                list.get(i).setMatched(list.get(bestMatchStudent));

                System.out.println(list.get(i).getName() + " matches with " + list.get(bestMatchStudent) + " with score " + maxScore);
            }
        }
    }
}
}

Students.txt

Abey    F   5-5-1996    0   0   0   0
John    M   5-5-1997    10  10  10  10
Melissa F   5-5-1996    10  10  10  10
Craig   M   5-5-1998    5   5   5   5
Jeff    M   5-5-1997    10  10  10  10

Body:
If I were to remove all of the getName() inside the if-else statement, I get an output that is sort of what I desire:

Student@6d3552ed matches with Student@47d77d9e with score 60
Student@147834eb matches with Student@5fda3acc with score 100
Student@704a583d has no matches.

That output is explained here How do I print my Java object without getting "SomeType@2f92e0f4"?

Seems like you just need to trim() the name.

Depending on where you want your "input validation" to be oerformed, you could do that at input.

String name = input.next().trim();

Or in the constuctor

public Student(String name, char gender, Date birthdate, Preference pref) {
    this.name = name.trim();
    this.gender = gender;
    this.birthdate = birthdate;
    this.pref = pref;
}

Or in the getter

public String getName() {
    return name.trim();
}

Or when you actually display the value in the println

Or define toString(), as explained in the other post to return name.trim();, and just print list.get(i), as you had done.

The root issue may be that you haven't defined LF (\n) or CRLF (\r\n) as a delimiter.

input.useDelimiter("[\t\r-]");

Try

input.useDelimiter("\r\n|[\t\r\n-]");


问:
How to load Gist code without getting async error
I am currently working with angular and rails on a new blog for myself and I am stuck. I used ng-bind-html for injecting the code from my backend.

Now I fixed it using my own directive.

I am currently getting the following error when I am trying to import a code example from Github's Gist service:

```<code>Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.
</code>```

What is the reason and how to fix this? Thanks in advance!

答:
The question is quite old but I stumbled across it while searching for the error. You can include https://github.com/blairvanderhoof/gist-embed/ in your project and then write a directive to apply the change:

```<code>yourApp.directive('gistDirective', function() {
    return function(scope, element, attrs) {
        scope.$watch('someAngularVariable', function(){
            angular.element('[data-gist-id]').gist();
        });

    }
});
</code>```

Then

```<code><section gist-directive>
                <article>
                    <div ng-bind-html="trustHtml(someAngularVariable.body)"></div>
                </article>
    </section>
</code>```

Body:
I am currently working with angular and rails on a new blog for myself and I am stuck. I used ng-bind-html for injecting the code from my backend.

Now I fixed it using my own directive.

I am currently getting the following error when I am trying to import a code example from Github's Gist service:

Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.

What is the reason and how to fix this? Thanks in advance!

Body:
The question is quite old but I stumbled across it while searching for the error. You can include https://github.com/blairvanderhoof/gist-embed/ in your project and then write a directive to apply the change:

yourApp.directive('gistDirective', function() {
    return function(scope, element, attrs) {
        scope.$watch('someAngularVariable', function(){
            angular.element('[data-gist-id]').gist();
        });

    }
});

Then

<section gist-directive>
                <article>
                    <div ng-bind-html="trustHtml(someAngularVariable.body)"></div>
                </article>
    </section>


问:
Android button onClick unknown event issue
When i am pressing the button in some devices it's showing `E/Sensors: ProximitySensor: unknown event (type=1, code=330, value=1), And here i given my code.

XML

```<code><Button
        android:id="@+id/button_done"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="@drawable/button_clcik_efferct_blue_white_no_round"
        android:text="DONE"
        android:textColor="@drawable/button_clcik_efferct_text_white_blue"
        android:textStyle="bold"/>
</code>```

JAVA

```<code>@BindView(R.id.button_done) Button buttonDone;

@OnClick(R.id.button_done)
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.button_done:
                try {
                  PreferenceManager.getInstance().setLocationName(localityName);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }
</code>```

答:
Try to use butterknife injection library and add the plugin to your android studio.

Plugin - File --> Settings --> Plugin --> Browse Repositories --> Search butterknife and Install.

Body:
When i am pressing the button in some devices it's showing `E/Sensors: ProximitySensor: unknown event (type=1, code=330, value=1), And here i given my code.

XML

<Button
        android:id="@+id/button_done"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="@drawable/button_clcik_efferct_blue_white_no_round"
        android:text="DONE"
        android:textColor="@drawable/button_clcik_efferct_text_white_blue"
        android:textStyle="bold"/>

JAVA

@BindView(R.id.button_done) Button buttonDone;

@OnClick(R.id.button_done)
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.button_done:
                try {
                  PreferenceManager.getInstance().setLocationName(localityName);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }


问:
vba - new sheets from columns, paste column A if X in column X to new sheet
Looking to generate a new sheet for each column in a workbook. (done, pasted below). Next step is to paste the value of Column A if a value is in column 'X'.

```<code>Name | Email | Course 101 | Course 203 |
John | john @|      X     |      X     |
Jane |Jane@  |      X     |            |
</code>```

Result would be two sheets, (Course 101, Course 203) controlled with a 'Range' function during the sheet generation code.

Part I'm stuck on, is how to paste John's name on the Course 101 and Course 203 sheet and Jane only on the Course 101 sheet.

Here's the code that works for the sheet generation (I think found on here :) )

```<code>Sub AddSheets()
Dim cell As Excel.Range
Dim wsWithSheetNames As Excel.Worksheet
Dim wbToAddSheetsTo As Excel.Workbook

    Set wsWithSheetNames = ActiveSheet
Set wbToAddSheetsTo = ActiveWorkbook
For Each cell In wsWithSheetNames.Range("A1:d1")
    With wbToAddSheetsTo
        .Sheets.Add after:=.Sheets(.Sheets.Count)
        On Error Resume Next
        ActiveSheet.Name = cell.Value
        If Err.Number = 1004 Then
          Debug.Print cell.Value & " already used as a sheet name"
        End If
        On Error GoTo 0
        End With
    Next cell
    End Sub
</code>```

答:
The code above will work to insert the worksheets but it does not do anything after that. Based off the script above I wrote up something similar that does what you want but with slightly easier to understand variables and terms.
The code pasted below requires you to enter the main worksheet name or just set the main worksheet's name to "Main".

This code should be a lot easier to understand since it breaks the process up into 2 blocks.

```<code>Sub FillCourseWorksheets()
  Dim wb As Workbook, cws As Worksheet, ws As Worksheet, found As Boolean
  Dim crw As Long, rw As Long, col As Integer, wsName As String
  Dim CheckString As String, student As String, lastRow As Long
  Dim lastCol As Integer, courseName As String, resultRow As Long

  'this code depends on the main sheet to have the headers in row 1

  '----------------------------------------------------------
  wsName = "Main" 'set this to the name of your main worksheet
  '----------------------------------------------------------

  'set up
  Set wb = ThisWorkbook
  'if you get an error here set the sheet name to main
  Set cws = wb.Worksheets(wsName)
  'use the .end to find the last column and row similar to CTRL + Right/Down
  lastRow = cws.Range("A1").End(xlDown).Row
  lastCol = cws.Range("A1").End(xlToRight).Column

  'go through each column and add a worksheet if needed

  For col = 3 To lastCol
    CheckString = cws.Cells(1, col).Value
    'check if the worksheet already exists
     found = False
    For Each ws In wb.Worksheets
      If ws.Name = CheckString Then
        found = True
        Exit For
      End If
    Next ws
    If found = False Then 'didnt find the sheet. Add it to the workbook
      Set ws = wb.Worksheets.Add(after:=wb.Worksheets(wb.Worksheets.Count)) 'add the worksheet
      ws.Name = CheckString 'name it
      ws.Range("A1").Value = "Name"
      cws.Activate 'activate the main page after insert
    End If
  Next col

  'all worksheets added go through columns again and add data to each worksheet
  For col = 3 To lastCol
    courseName = cws.Cells(1, col).Value
    Set ws = wb.Worksheets(courseName) 'identify the worksheet to use
    For checkrow = 2 To lastRow
      If cws.Cells(checkrow, col).Value <> "" Then
        student = cws.Range("A" & checkrow).Value
        'set the resultrow and check if there is no data
        If ws.Range("A2").Value = "" Then
          resultRow = 2
        Else
          resultRow = ws.Range("A1").End(xlDown).Row + 1
        End If
        ws.Range("A" & resultRow).Value = student 'print out the student
      End If
    Next checkrow
  Next col

  MsgBox "done"

End Sub
</code>```

Save your workbook before running this and let me know if you have any trouble.

Body:
Looking to generate a new sheet for each column in a workbook. (done, pasted below). Next step is to paste the value of Column A if a value is in column 'X'.

Name | Email | Course 101 | Course 203 |
John | john @|      X     |      X     |
Jane |Jane@  |      X     |            |

Result would be two sheets, (Course 101, Course 203) controlled with a 'Range' function during the sheet generation code.

Part I'm stuck on, is how to paste John's name on the Course 101 and Course 203 sheet and Jane only on the Course 101 sheet.

Here's the code that works for the sheet generation (I think found on here :) )

Sub AddSheets()
Dim cell As Excel.Range
Dim wsWithSheetNames As Excel.Worksheet
Dim wbToAddSheetsTo As Excel.Workbook

    Set wsWithSheetNames = ActiveSheet
Set wbToAddSheetsTo = ActiveWorkbook
For Each cell In wsWithSheetNames.Range("A1:d1")
    With wbToAddSheetsTo
        .Sheets.Add after:=.Sheets(.Sheets.Count)
        On Error Resume Next
        ActiveSheet.Name = cell.Value
        If Err.Number = 1004 Then
          Debug.Print cell.Value & " already used as a sheet name"
        End If
        On Error GoTo 0
        End With
    Next cell
    End Sub

Body:
The code above will work to insert the worksheets but it does not do anything after that. Based off the script above I wrote up something similar that does what you want but with slightly easier to understand variables and terms.
The code pasted below requires you to enter the main worksheet name or just set the main worksheet's name to "Main".

This code should be a lot easier to understand since it breaks the process up into 2 blocks.

Sub FillCourseWorksheets()
  Dim wb As Workbook, cws As Worksheet, ws As Worksheet, found As Boolean
  Dim crw As Long, rw As Long, col As Integer, wsName As String
  Dim CheckString As String, student As String, lastRow As Long
  Dim lastCol As Integer, courseName As String, resultRow As Long

  'this code depends on the main sheet to have the headers in row 1

  '----------------------------------------------------------
  wsName = "Main" 'set this to the name of your main worksheet
  '----------------------------------------------------------

  'set up
  Set wb = ThisWorkbook
  'if you get an error here set the sheet name to main
  Set cws = wb.Worksheets(wsName)
  'use the .end to find the last column and row similar to CTRL + Right/Down
  lastRow = cws.Range("A1").End(xlDown).Row
  lastCol = cws.Range("A1").End(xlToRight).Column

  'go through each column and add a worksheet if needed

  For col = 3 To lastCol
    CheckString = cws.Cells(1, col).Value
    'check if the worksheet already exists
     found = False
    For Each ws In wb.Worksheets
      If ws.Name = CheckString Then
        found = True
        Exit For
      End If
    Next ws
    If found = False Then 'didnt find the sheet. Add it to the workbook
      Set ws = wb.Worksheets.Add(after:=wb.Worksheets(wb.Worksheets.Count)) 'add the worksheet
      ws.Name = CheckString 'name it
      ws.Range("A1").Value = "Name"
      cws.Activate 'activate the main page after insert
    End If
  Next col

  'all worksheets added go through columns again and add data to each worksheet
  For col = 3 To lastCol
    courseName = cws.Cells(1, col).Value
    Set ws = wb.Worksheets(courseName) 'identify the worksheet to use
    For checkrow = 2 To lastRow
      If cws.Cells(checkrow, col).Value <> "" Then
        student = cws.Range("A" & checkrow).Value
        'set the resultrow and check if there is no data
        If ws.Range("A2").Value = "" Then
          resultRow = 2
        Else
          resultRow = ws.Range("A1").End(xlDown).Row + 1
        End If
        ws.Range("A" & resultRow).Value = student 'print out the student
      End If
    Next checkrow
  Next col

  MsgBox "done"

End Sub

Save your workbook before running this and let me know if you have any trouble.


问:
How to query vsts artifacts with tags
we would like to query artefacts with tags to trigger parallel deployments. How should we do that? Is there an UI or do we have to use the API ?</p>

答:
Refer to these steps below:

Add a PowerShell or other (e.g. Command) task to call Logging Commands to add build tag (e.g. Write-Host "##vso[build.addbuildtag]tagTest")

Specify conditions for that PowerShell task

Open release definition

Specify the Artifact filters with build tags (You also can specify the filter for Continuous deployment)

After that, the environments that meet the filters will be running

Title: How to query vsts artifacts with tags


问:
Yammer REST API > Retain authentication details
I have created a Yammer app wherein the user is able to make posts and obtain messages using an open graph feed. The user is asked to authorize the Yammer app the first time he/she logs in, in order to obtain an access token. My question is, is it possible that the user does not have to login every time he/she uses the app, in order to obtain this token?

Currently, the container where the feed is supposed to show, shows a "Login to Yammer" button. Only after the login, is the feed visible.

Is there a way to automatically login the user in the background without using impersonation? (If an encrypted version of the username and password is stored in the system.)

Thank you!

答: You can't log in the user without either the user interacting to authorize the app, or the authorization being performed through impersonation. You can use the setAuthToken() method from the JavaScript SDK for Yammer to inject an existing token, even if you are doing the full impersonation laid out in the linked article.</p>


问:
SVN Tags based on a DATE
Can someone pls let me know how to make a tag or branch based on a certain date in SVN?</p>

答:
One way is from your working copy, from command line, is as follows:

svn copy -r {date-in-iso-format} destination

For example,

```<code>svn copy -r {2011-01-18} http://myserver/svn/project/trunk \
           http://myserver/svn/project/tags/tag-2011-01-18 \
           -m "Tagging project on 18th Jan 2011"
</code>```

Title: SVN Tags based on a DATE

Body:
One way is from your working copy, from command line, is as follows:

svn copy -r {date-in-iso-format} destination

For example,

svn copy -r {2011-01-18} http://myserver/svn/project/trunk \
           http://myserver/svn/project/tags/tag-2011-01-18 \
           -m "Tagging project on 18th Jan 2011"


问:
How to delete file from public folder in laravel 5.1
I want to delete a News from database and when I hit the delete button all data from database deleted but the image is remains in upload folder.
So, how do I this to work.
thanks

This is my function again but does not delete the image from images/news folder of public directory>

```<code> public function destroy($id) {
    $news = News::findOrFail($id);
    $image_path = app_path("images/news/{$news->photo}");

    if (File::exists($image_path)) {
        //File::delete($image_path);
        unlink($image_path);
    }
    $news->delete();
    return redirect('admin/dashboard')->with('message','خبر موفقانه حذف  شد');
}
</code>```

答:
Try it :Laravel 5.5  </p>

```<code>public function destroy($id){
      $data = User::FindOrFail($id);
      if(file_exists('backend_assets/uploads/userPhoto/'.$data->photo) AND !empty($data->photo)){
            unlink('backend_assets/uploads/userPhoto/'.$data->photo);
         }
            try{

                $data->delete();
                $bug = 0;
            }
            catch(\Exception $e){
                $bug = $e->errorInfo[1];
            }
            if($bug==0){
                echo "success";
            }else{
                echo 'error';
            }
        }
</code>```

Body:
I want to delete a News from database and when I hit the delete button all data from database deleted but the image is remains in upload folder.
So, how do I this to work.
thanks

This is my function again but does not delete the image from images/news folder of public directory>

 public function destroy($id) {
    $news = News::findOrFail($id);
    $image_path = app_path("images/news/{$news->photo}");

    if (File::exists($image_path)) {
        //File::delete($image_path);
        unlink($image_path);
    }
    $news->delete();
    return redirect('admin/dashboard')->with('message','خبر موفقانه حذف  شد');
}

Body:
Try it :Laravel 5.5

public function destroy($id){
      $data = User::FindOrFail($id);
      if(file_exists('backend_assets/uploads/userPhoto/'.$data->photo) AND !empty($data->photo)){
            unlink('backend_assets/uploads/userPhoto/'.$data->photo);
         }
            try{

                $data->delete();
                $bug = 0;
            }
            catch(\Exception $e){
                $bug = $e->errorInfo[1];
            }
            if($bug==0){
                echo "success";
            }else{
                echo 'error';
            }
        }


问:
How can I run git commands on Windows with SSH verbose mode?
This is the Windows version of How can I run git push/pull commands with SSH verbose mode?

There are times where you just need to debug git's usage of SSH.

OpenSSH has a -v flag for verbose output, but how do you get git to use it?

How can I run git commands on Windows with SSH verbose mode?

答:
If your PATH is correctly set:

you don't need OpenSSH-Win64 (ssh is already included in Git)

you don't need to specify the full path for SSH

You need:

```<code>set GH=C:\path\to\git
set PATH=%GH%\bin;%GH%\usr\bin;%GH%\mingw64\bin;%PATH%
</code>```

Then

```<code>set GIT_SSH_COMMAND=ssh -vvv
</code>```

Body:
If your PATH is correctly set:

you don't need OpenSSH-Win64 (ssh is already included in Git)

you don't need to specify the full path for SSH

You need:

set GH=C:\path\to\git
set PATH=%GH%\bin;%GH%\usr\bin;%GH%\mingw64\bin;%PATH%

Then

set GIT_SSH_COMMAND=ssh -vvv


问:
(TypeError: Cannot read property 'length' of null at HttpHeaders.applyUpdate) Angular 5, Http Client
I'm getting this reponse when making an http request in service.

Here's the Login component

```<code>export class LoginComponent {
  credentials: Credentials;

  constructor(
    private auth: AuthService,
    @Inject(UserService) private userService: UserService,
    @Inject(HttpClient) private http: HttpClient,
    private auth0: Auth0Service
  ) {}

  onLogin(credentials) {
    const sendReq = this.userService.login(credentials);
}
</code>```

I've added UserService in providers in App.module

Here's the UserService

```<code>@Injectable()
export class UserService {
  constructor(
    @Inject(Auth0Service) private authService: Auth0Service,
    protected http: HttpClient // @Inject(HttpClient) protected http: HttpClient
  ) {}
  login(credentials): Observable<any> {
    console.log(credentials);
    console.log(credentials.username);
    this.http
      .post("http://localhost:3000/api/Users/login", {
        username: credentials.username,
        password: credentials.password
      })
      .subscribe(
        data => {
          console.log(data);
        },
        err => {
          console.log("Something went wrong!");
          console.log(err);
        }
      );
    return credentials;
    // this.auth.login(credentials);
  }
}
</code>```

Here's the console

```<code>    at MergeMapSubscriber._innerSub (mergeMap.js:138)
    user.service.ts:14
{username: "hamzakpt", password: "hamza"}
    user.service.ts:15
 hamzakpt
    user.service.ts:26 Something went wrong!

    user.service.ts:27
 TypeError: Cannot read property 'length' of null
        at HttpHeaders.applyUpdate (http.js:308)
        at eval (http.js:255)
        at Array.forEach (<anonymous>)
        at HttpHeaders.init (http.js:255)
        at HttpHeaders.forEach (http.js:354)
        at Observable.eval [as _subscribe] (http.js:2153)
        at Observable._trySubscribe (Observable.js:172)
        at Observable.subscribe (Observable.js:160)
        at subscribeToResult (subscribeToResult.js:23)
        at MergeMapSubscriber._innerSub (mergeMap.js:138)
</code>```

The same get request works in LoginComponent but not in UserService. UserService is global service while Login is in a different module.

I've also added HTTPClientModule in app.module and Login Module.

答:
try like this :

service.ts

```<code>login(credentials): Observable<any> {
    return this.http.post("http://localhost:3000/api/Users/login", {
        username: credentials.username,
        password: credentials.password
    }).map(data => data.json())
}
</code>```

component.ts

```<code>onLogin(credentials) {
    this.userService.login(credentials)
        .subscribe(data => {
            console.log('data', data);
        }, (error) => {
            console.log('error', error);
        })
}
</code>```

Body:
I'm getting this reponse when making an http request in service.

Here's the Login component

export class LoginComponent {
  credentials: Credentials;

  constructor(
    private auth: AuthService,
    @Inject(UserService) private userService: UserService,
    @Inject(HttpClient) private http: HttpClient,
    private auth0: Auth0Service
  ) {}

  onLogin(credentials) {
    const sendReq = this.userService.login(credentials);
}

I've added UserService in providers in App.module

Here's the UserService

@Injectable()
export class UserService {
  constructor(
    @Inject(Auth0Service) private authService: Auth0Service,
    protected http: HttpClient // @Inject(HttpClient) protected http: HttpClient
  ) {}
  login(credentials): Observable<any> {
    console.log(credentials);
    console.log(credentials.username);
    this.http
      .post("http://localhost:3000/api/Users/login", {
        username: credentials.username,
        password: credentials.password
      })
      .subscribe(
        data => {
          console.log(data);
        },
        err => {
          console.log("Something went wrong!");
          console.log(err);
        }
      );
    return credentials;
    // this.auth.login(credentials);
  }
}

Here's the console

    at MergeMapSubscriber._innerSub (mergeMap.js:138)
    user.service.ts:14
{username: "hamzakpt", password: "hamza"}
    user.service.ts:15
 hamzakpt
    user.service.ts:26 Something went wrong!

    user.service.ts:27
 TypeError: Cannot read property 'length' of null
        at HttpHeaders.applyUpdate (http.js:308)
        at eval (http.js:255)
        at Array.forEach (<anonymous>)
        at HttpHeaders.init (http.js:255)
        at HttpHeaders.forEach (http.js:354)
        at Observable.eval [as _subscribe] (http.js:2153)
        at Observable._trySubscribe (Observable.js:172)
        at Observable.subscribe (Observable.js:160)
        at subscribeToResult (subscribeToResult.js:23)
        at MergeMapSubscriber._innerSub (mergeMap.js:138)

The same get request works in LoginComponent but not in UserService. UserService is global service while Login is in a different module.

I've also added HTTPClientModule in app.module and Login Module.

Body:
try like this :

service.ts

login(credentials): Observable<any> {
    return this.http.post("http://localhost:3000/api/Users/login", {
        username: credentials.username,
        password: credentials.password
    }).map(data => data.json())
}

component.ts

onLogin(credentials) {
    this.userService.login(credentials)
        .subscribe(data => {
            console.log('data', data);
        }, (error) => {
            console.log('error', error);
        })
}


问:
Minimal Permissions for Packer remote VMware-iso builder
I'm trying to use Packer to build images from iso on a remote VMware cluster, and there are security concerns with allowing direct access to the host. What are the minimal permissions required for an account on the esxi host to successfully complete the build?</p>

答:
The user needs to be able to run the following commands:

vmkfstools

vim-cmd

test

sh

ls

rm

esxcli

stat

mkdir

shaXsum

md5sum

For vim-cmd it must be allowed to run:

vmsvc/power.getstate

vmsvc/reload

vmsvc/power.on

vmsvc/power.off

solo/registervm

vmsvc/unregister

vmsvc/destroy

vmsvc/tools.install

And for esxcli:

network ip connection list

network vm list

network vm port list

system version get

system settings advanced list -o /Net/GuestIPHack

If security is I high concern I would recommend to look into running a dedicated ESXi host for Packer builds or use nested virtualisation to run a ESXi on top of vSphere just as a build host.


问:
Authentication and Roles in WPF
I am doing a project in WPF. I got a requirement to authenticate a user and providing accessibilty for the modules based on the role. Do i have a better way to achieve this in WPF.</p>

答:
It will depend in part on how secure you need the code to be.

For all your use cases, though, use a Model-View-ViewModel pattern. In each ViewModel, perhaps best placed in a base class for all your ViewModel classes, include a state variable which returns a string and raises the PropertyChanged event whenever the security state changes.

Base your presentation for each View class on the value of that string, following a pattern similar to the accepted answer to this SO question:

https://stackoverflow.com/questions/3868164/

The answer describes how to do this with boolean values, but you can use any string value other than "True" or "False" if your ViewModel state variable needs more than two states.

All .NET code, including WPF, can be easily reverse-engineered. If your code needs to be more secure than that, that is, if your use case assumes that your users will hack your WPF program, then you will want to obfuscate and/or encrypt much of the ViewModel code, using commercially available products like InishTech's SLPS or Dotfuscator or whatever.

Alternatively, you could use the same MVVM pattern and write a Silverlight application, but I'm not sure if a Silverlight user has access to the binary files the way a desktop WPF user would.

Title: Authentication and Roles in WPF


问:
Missing HttpOnly Attribute in Session Cookie
in sign.jsp, I have written the following so that, if a user is already logged in then immediately he would be forwarded to his home page

```<code><%
try{

HttpSession session1 = request.getSession(false);

if(session1.getAttribute("authenticated")!=null &&
 session1.getAttribute("authenticated").equals(true))
{
response.sendRedirect("userhome.jsp");
}
else{

// users have to login here
}
%>
</code>```

Security scan is telling that Missing HttpOnly Attribute in Session Cookie in sign.jsp.

If i will set:  <Context useHttpOnly="true">
                    ...
                </Context>

in : C:\Program Files\Apache Software Foundation\Apache Tomcat 6.0.20\conf

then will my problem be solved or what else i have to do? Any suggestion is much appreciated

答:
Read this article https://access.redhat.com/solutions/338313

I think you have to set

```<code><Context cookies="true" crossContext="true">
  <SessionCookie secure="true" httpOnly="true" />
</code>```

attributes in "$PROFILE\deploy\jbossweb.sar\context.xml"

Body:
in sign.jsp, I have written the following so that, if a user is already logged in then immediately he would be forwarded to his home page

<%
try{

HttpSession session1 = request.getSession(false);

if(session1.getAttribute("authenticated")!=null &&
 session1.getAttribute("authenticated").equals(true))
{
response.sendRedirect("userhome.jsp");
}
else{

// users have to login here
}
%>

Security scan is telling that Missing HttpOnly Attribute in Session Cookie in sign.jsp.

If i will set:  <Context useHttpOnly="true">
                    ...
                </Context>

in : C:\Program Files\Apache Software Foundation\Apache Tomcat 6.0.20\conf

then will my problem be solved or what else i have to do? Any suggestion is much appreciated

Body:
Read this article https://access.redhat.com/solutions/338313

I think you have to set

<Context cookies="true" crossContext="true">
  <SessionCookie secure="true" httpOnly="true" />

attributes in "$PROFILE\deploy\jbossweb.sar\context.xml"


问:
Processing Custom Alexa Skill Cards in AVS-SDK
I am building some simple custom skills with card like this:

this.response.cardRenderer(skillName,textCard);
this.emit(':responseReady');

I have AVS SDK installed on a Raspberry Pi, but I can't see where the card info ends up. The service simulator has the following info in the service response:

```<code>  "card": {
    "content": "hum, I can't sense any fan here.",
    "title": "FanControlIntent on"
  },
</code>```

Is there anyway I can extract the card info so I can process it in the SDK on my raspberry pi? My first guess is this will be in the payload of the directive but is not.

答:
Based on amazon developer forum, Card data is not exposed in any API at the moment. See the following ref.

https://forums.developer.amazon.com/questions/67919/how-do-i-access-the-alexa-card-responses-on-my-ras.html

https://forums.developer.amazon.com/questions/63071/display-alexa-card-information.html

Body:
I am building some simple custom skills with card like this:

this.response.cardRenderer(skillName,textCard);
this.emit(':responseReady');

I have AVS SDK installed on a Raspberry Pi, but I can't see where the card info ends up. The service simulator has the following info in the service response:

  "card": {
    "content": "hum, I can't sense any fan here.",
    "title": "FanControlIntent on"
  },

Is there anyway I can extract the card info so I can process it in the SDK on my raspberry pi? My first guess is this will be in the payload of the directive but is not.