问:
How to convert seconds to HH:mm to HH:mm:ss in moment.js
Suppose I have a time as 13:45.

Now I want to convert this into 13:45:00 using moment.js.

I am doing
moment('13:45').format('h:m:s'); but it is not working.

答:
You need to add second parameter to let moment know the format of your passed date

```<code>moment('13:45', 'HH:mm').format('h:m:s')
</code>```

or

```<code>moment('13:45', 'HH:mm').format('HH:mm:ss')
</code>```

Body:
You need to add second parameter to let moment know the format of your passed date

moment('13:45', 'HH:mm').format('h:m:s')

or

moment('13:45', 'HH:mm').format('HH:mm:ss')


来源: stackexchange

问:
Android Studio editor not opening
I installed Android studio, already have jdk 1.8 but when i click on finish during the creation of new project(Customize the Activity)  nothing happens, just nothing, what could be the problem.</p>

答: You could try and restart your computer. Your computer probably needs a restart to fully complete the java installation. You will face this when installing a lot of programming languages. Plus restarting always fixes a lot of things so it couldn't hurt to try. </p>

ContentLicense: CC BY-SA 3.0

Title: Android Studio editor not opening


问:
How to pass data through url of ionic-plugin-deeplinks
```<code>.state('profiledet', {
    url: '/profiledet',
    params: { 'profile_id': null},
    templateUrl: 'templates/profile-det.html',
    controller: 'profiledet'
})
</code>```

above is the route of my page.

```<code>$cordovaDeeplinks.route({
  '/profiledet': {
    target: 'profiledet',
    parent: 'profiledet'
  }
})
</code>```

this is the deep linking route, I can't pass data through this. Can anyone help me?

答:
I have got the answer, below is the code.

```<code>   $cordovaDeeplinks.route({'/profiledet:profile_id': {
target: 'profiledet',
parent: 'profiledet'
</code>```

}
})

Body:
.state('profiledet', {
    url: '/profiledet',
    params: { 'profile_id': null},
    templateUrl: 'templates/profile-det.html',
    controller: 'profiledet'
})

above is the route of my page.

$cordovaDeeplinks.route({
  '/profiledet': {
    target: 'profiledet',
    parent: 'profiledet'
  }
})

this is the deep linking route, I can't pass data through this. Can anyone help me?

Body:
I have got the answer, below is the code.

   $cordovaDeeplinks.route({'/profiledet:profile_id': {
target: 'profiledet',
parent: 'profiledet'

}
})


问:
Filtering two arrays returns blank array
I have these two arrays and have a simple method to filter the matching items from both the data array and the data2 array. But it returns empty array when it should return two items. What am i doing wrong?

var data =  [{ teamId: 74, teamName: 'Blah' },
 { teamId: 94, teamName: 'Panhi' },
 { teamId: 30, teamName: 'Writer' },
 { teamId: 121, teamName: 'People' },
 { teamId: 85, teamName: 'Perf' },
 { teamId: 31, teamName: 'Tell' },
 { teamId: 32, teamName: 'Gall' },
 { teamId: 137, teamName: 'Bird' },
 { teamId: 79, teamName: 'Blue' },
 { teamId: 119, teamName: 'Red' },
 { teamId: 66, teamName: 'Pluto' },
 { teamId: 56, teamName: 'PolarBear' },
 { teamId: 33, teamName: 'Praxis' },
 { teamId: 62, teamName: 'Purple' }
];

var data2 = [ { id: 1, reId: 52, teamId: 94 },
  { id: 2, reId: 52, teamId: 32 } ];

var found = data.filter(i => i.teamId === data2.teamId);
console.log(found);```

答:
A dynamic solution to your problem.

var data =  [{ teamId: 74, teamName: 'Blah' },
 { teamId: 94, teamName: 'Panhi' },
 { teamId: 30, teamName: 'Writer' },
 { teamId: 121, teamName: 'People' },
 { teamId: 85, teamName: 'Perf' },
 { teamId: 31, teamName: 'Tell' },
 { teamId: 32, teamName: 'Gall' },
 { teamId: 137, teamName: 'Bird' },
 { teamId: 79, teamName: 'Blue' },
 { teamId: 119, teamName: 'Red' },
 { teamId: 66, teamName: 'Pluto' },
 { teamId: 56, teamName: 'PolarBear' },
 { teamId: 33, teamName: 'Praxis' },
 { teamId: 62, teamName: 'Purple' }
];

var data2 = [ { id: 1, reId: 52, teamId: 94 },
  { id: 2, reId: 52, teamId: 32 } ];

var found = [];

found = data.filter(function(i) {
  return data2.find( d => d.teamId === i.teamId);
});
console.log(found);```


问:
What is the most common waste of computing power in Javascript?
We've all seen people who do this:

```<code>jQuery('a').each(function(){
    jQuery(this)[0].innerHTML += ' proccessed';
});

function letsPoluteNS() {
    polute = '';
    for (morePolution = 0; morePolution < arguments.length; morePolution++)
        polute.join(arguments[morePolution]);
    return polute;
}
</code>```

and so on. I was wondering what people have seen the most common JavaScript/jQuery technique that is slowing down the page and/or wasting time for the JavaScript engine.

I know that this question may not seem to fit into what's an accepted question, yet I'm asking "what is the most common accepted waste?"

答:
Anything that has do to with tracking users and heavy publicity. Thats wasted space for sure.

I guess wrong use of stuff like using classes instead ids as selector in very complex html would slow thing down.
And ie of course.

Body:
We've all seen people who do this:

jQuery('a').each(function(){
    jQuery(this)[0].innerHTML += ' proccessed';
});

function letsPoluteNS() {
    polute = '';
    for (morePolution = 0; morePolution < arguments.length; morePolution++)
        polute.join(arguments[morePolution]);
    return polute;
}

and so on. I was wondering what people have seen the most common JavaScript/jQuery technique that is slowing down the page and/or wasting time for the JavaScript engine.

I know that this question may not seem to fit into what's an accepted question, yet I'm asking "what is the most common accepted waste?"

ContentLicense: CC BY-SA 2.5


问:
AlarmManager not invoking the task?
I want to execute a auto-logout after 10 PM everyday in my application, for that that I have implemented a AlarmManager task but it is not invoking .For testing purpose I have given the other timing .(e.g

```<code>calendar.set(Calendar.HOUR_OF_DAY,15);
                    calendar.set(Calendar.MINUTE,59);
                    calendar.set(Calendar.SECOND,30);
</code>```

)
AlarmManager Code:

```<code> sign_in_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideKeyboard(LoginActivity.this);
                //implementation of auto logout
                checkSuiteSession = new CheckSuiteSession(getApplicationContext());
                checkSuiteSession.check_attendance_flag("true");
                Calendar calendar = Calendar.getInstance();
                calendar.set(Calendar.HOUR_OF_DAY,15);
                calendar.set(Calendar.MINUTE,59);
                calendar.set(Calendar.SECOND,30);
                Intent autoLogoutIntent = new Intent(getApplicationContext(),AutoLogoutRecevier.class);
                PendingIntent pendingIntent =
                        PendingIntent.getBroadcast(getApplicationContext(),100,autoLogoutIntent,PendingIntent.FLAG_UPDATE_CURRENT);

                AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
                alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);
</code>```

My broadcast receiver class :

```<code>public class AutoLogoutRecevier extends BroadcastReceiver {
    CheckSuiteSession checkSuiteSession;
    @Override
    public void onReceive(Context context, Intent intent) {
        checkSuiteSession = new CheckSuiteSession(context);
        //calling logout function
        checkSuiteSession.logoutUser();
        Log.d("LOGOUT","auto logout executed");
        checkSuiteSession.check_attendance_flag("false");

    }
}
</code>```

My manifest file (I have added the following permission) :

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.fresherguru.checksuite">

    <!-- To auto-complete the email text field in the login form with the user's emails -->
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.READ_PROFILE" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
    <uses-permission android:name="android.permission.WAKE_LOCK"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service
            android:name=".fcm.MyFirebaseMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            </intent-filter>
        </service>
        <service android:name=".fcm.MyFirebaseInstanceIDService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>

        <receiver android:name=".autoLogoutReceiver.AutoLogoutRecevier">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED"/>
        </intent-filter>
        </receiver>

        <receiver android:name=".autoLogoutReceiver.ActivateLogin">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
        </receiver>

        <receiver android:name=".autoLogoutReceiver.ChangeDialogStatus"
            android:process=":remote"/>
        <receiver android:name=".autoLogoutReceiver.ScreenUnlockReceiver">
            <intent-filter>
                <action android:name="android.intent.action.USER_PRESENT" />
                <!--<action android:name="android.intent.action.ACTION_SHUTDOWN" />-->
            </intent-filter>
            </receiver>

        <receiver android:name=".autoLogoutReceiver.DeviceBootReceiver"
            android:enabled="false">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
                <action android:name="android.intent.action.REBOOT"/>
            </intent-filter>
        </receiver>
        <service android:name=".service.CallHandleAlarmService"
            android:enabled="true"/>

        <activity
            android:name=".home.LoginActivity"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity
            android:name=".home.HomeActivity"
            android:theme="@style/AppTheme.NoActionBar" />

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <activity
            android:name=".home.CheckSuiteForm"
            />
    </application>

</manifest>
</code>```

答:
Change and set right time for 10 PM in your Calendar object:

```<code>Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY,21);
calendar.set(Calendar.MINUTE,59);
calendar.set(Calendar.SECOND,59);
</code>```

Title: AlarmManager not invoking the task?

Body:
I want to execute a auto-logout after 10 PM everyday in my application, for that that I have implemented a AlarmManager task but it is not invoking .For testing purpose I have given the other timing .(e.g

calendar.set(Calendar.HOUR_OF_DAY,15);
                    calendar.set(Calendar.MINUTE,59);
                    calendar.set(Calendar.SECOND,30);

)
AlarmManager Code:

 sign_in_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideKeyboard(LoginActivity.this);
                //implementation of auto logout
                checkSuiteSession = new CheckSuiteSession(getApplicationContext());
                checkSuiteSession.check_attendance_flag("true");
                Calendar calendar = Calendar.getInstance();
                calendar.set(Calendar.HOUR_OF_DAY,15);
                calendar.set(Calendar.MINUTE,59);
                calendar.set(Calendar.SECOND,30);
                Intent autoLogoutIntent = new Intent(getApplicationContext(),AutoLogoutRecevier.class);
                PendingIntent pendingIntent =
                        PendingIntent.getBroadcast(getApplicationContext(),100,autoLogoutIntent,PendingIntent.FLAG_UPDATE_CURRENT);

                AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
                alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);

My broadcast receiver class :

public class AutoLogoutRecevier extends BroadcastReceiver {
    CheckSuiteSession checkSuiteSession;
    @Override
    public void onReceive(Context context, Intent intent) {
        checkSuiteSession = new CheckSuiteSession(context);
        //calling logout function
        checkSuiteSession.logoutUser();
        Log.d("LOGOUT","auto logout executed");
        checkSuiteSession.check_attendance_flag("false");

    }
}

My manifest file (I have added the following permission) :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.fresherguru.checksuite">

    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.READ_PROFILE" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
    <uses-permission android:name="android.permission.WAKE_LOCK"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service
            android:name=".fcm.MyFirebaseMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            </intent-filter>
        </service>
        <service android:name=".fcm.MyFirebaseInstanceIDService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>

        <receiver android:name=".autoLogoutReceiver.AutoLogoutRecevier">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED"/>
        </intent-filter>
        </receiver>

        <receiver android:name=".autoLogoutReceiver.ActivateLogin">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
        </receiver>

        <receiver android:name=".autoLogoutReceiver.ChangeDialogStatus"
            android:process=":remote"/>
        <receiver android:name=".autoLogoutReceiver.ScreenUnlockReceiver">
            <intent-filter>
                <action android:name="android.intent.action.USER_PRESENT" />

            </intent-filter>
            </receiver>

        <receiver android:name=".autoLogoutReceiver.DeviceBootReceiver"
            android:enabled="false">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
                <action android:name="android.intent.action.REBOOT"/>
            </intent-filter>
        </receiver>
        <service android:name=".service.CallHandleAlarmService"
            android:enabled="true"/>

        <activity
            android:name=".home.LoginActivity"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity
            android:name=".home.HomeActivity"
            android:theme="@style/AppTheme.NoActionBar" />

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <activity
            android:name=".home.CheckSuiteForm"
            />
    </application>

</manifest>

Body:
Change and set right time for 10 PM in your Calendar object:

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY,21);
calendar.set(Calendar.MINUTE,59);
calendar.set(Calendar.SECOND,59);


问:
Is it possible to group a set of html elements so that they move together?
When the browser size is changed/on different sized devices, I need a set of html elements that are all semantically related to remain together and move in a block. That is, if one of the elements move to the next "row" due to their not being enough width to contain the whole grouping, ALL of it should move down.

IOW, this is sort of like the "keep together" attribute that some groupings of items in a word processing document have.

To be a little more specific, say that I have collections of the following elements:

```<code>1) an anchor tag, filling out a first "column"
2) a collection of tags, to the right of the anchor tag, consisting of:
(a) a div, followed by a <br/>
(b) a cite, followed by a <br/>
(c) another div, followed by a <br/>
(d) two or three anchor tags that are aligned side-by-side at the bottom of the second "column"
</code>```

So to sum up, if there is not enough room for the second "column" in a "row," rather than keep the  in the first "column" and moving the elements in the second column down to the next "row," the  in the first column should adhere to its siblings and always remain on the same "row" with them (I'm putting "row" and "column" in quotes because I'm not using an html table, and those exist only in a virtual sense).

If you're finding this a little hard to visualize (I don't blame you), check out the fiddle: http://jsfiddle.net/W7CYC/8/

Note: wrapping the groupings into html5 s did not help.

Here's the code:

HTML:

```<code><div class="yearBanner">2013</div>
<section>
<a id="mainImage" class="floatLeft" href="https://rads.stackoverflow.com/amzn/click/com/0299186342" rel="nofollow noreferrer"><img height="240" width="160" src="http://ecx.images-amazon.com/images/I/51usxIl4vML._SY346_.jpg"></a>

    <div id="prizeCategory" class="category">BIOGRAPHY</div>
    <br/>
<cite id="prizeTitle" class="title">Son of the Wilderness: The Life of John Muir</cite>

    <br/>
    <div id="prizeArtist" class="author">Linnie Marsh Wolfe</div>
    <br/>
    <img class="floatLeft" height="60" width="40" src="http://ecx.images-amazon.com/images/I/51usxIl4vML._SY346_.jpg">
    <img class="floatLeft" height="60" width="40" src="http://ecx.images-amazon.com/images/I/51usxIl4vML._SY346_.jpg">
    <img class="floatLeft" height="60" width="40" src="http://ecx.images-amazon.com/images/I/51usxIl4vML._SY346_.jpg">
</section>
<section>
<a class="floatLeft" href="https://rads.stackoverflow.com/amzn/click/com/0299186342" rel="nofollow noreferrer"><img height="240" width="160" src="http://ecx.images-amazon.com/images/I/51usxIl4vML._SY346_.jpg"></a>

    <div class="category">BIOGRAPHY</div>
    <br/>
<cite class="title">Son of the Wilderness: The Life of John Muir</cite>

    <br/>
    <div class="author">Linnie Marsh Wolfe</div>
    <br/>
    <img height="60" width="40" src="http://ecx.images-amazon.com/images/I/51usxIl4vML._SY346_.jpg">
    <img height="60" width="40" src="http://ecx.images-amazon.com/images/I/51usxIl4vML._SY346_.jpg">
    <img height="60" width="40" src="http://ecx.images-amazon.com/images/I/51usxIl4vML._SY346_.jpg">
</section>
</code>```

CSS:

```<code>body {
    background-color: black;
}
.floatLeft {
    float: left;
    padding-right: 20px;
    padding-left: 5px;
}
.yearBanner {
    font-size: 3em;
    color: white;
    font-family: Verdana, Arial, Helvetica, sans-serif;
    float: left;
    padding-top: 64px;
}
.category {
    display: inline-block;
    font-family: Consolas, sans-serif;
    font-size: 2em;
    color: Orange;
    width: 160px;
}
.title {
    display: inline-block;
    font-family: Calibri, Candara, serif;
    color: Yellow;
    width: 160px;
}
.author {
    display: inline-block;
    font-family: Courier, sans-serif;
    font-size: 0.8em;
    color: White;
    width: 160px;
}
</code>```

jQuery:

```<code>$('#prizeCategory').text("Changed Category");
$('#prizeTitle').text("Changed Title that spans two rows");
$('#prizeArtist').text("Changed Author and co-author");
$('#mainImage img').attr("src", "http://ecx.images-amazon.com/images/I/61l0rZz6mdL._SY300_.jpg");
$('#mainImage img').attr("height", "200");
</code>```

答:
Bootstrap grids

Bootstrap includes a powerful mobile-first flexbox grid system for
  building layouts of all shapes and sizes. It’s based on a 12 column
  layout and has multiple tiers, one for each media query range. You can
  use it with Sass mixins or our predefined classes.

code example :

```<code>  <div class="row">
    <div class="col-4">.col-4</div>
    <div class="col-4">.col-4</div>
    <div class="col-4">.col-4</div>
  </div>

  <div class="row">
    <div class="col-sm-4">.col-sm-4</div>
    <div class="col-sm-4">.col-sm-4</div>
    <div class="col-sm-4">.col-sm-4</div>
  </div>

  <div class="row">
    <div class="col-md-4">.col-md-4</div>
    <div class="col-md-4">.col-md-4</div>
    <div class="col-md-4">.col-md-4</div>
  </div>

  <div class="row">
    <div class="col-lg-4">.col-lg-4</div>
    <div class="col-lg-4">.col-lg-4</div>
    <div class="col-lg-4">.col-lg-4</div>
  </div>

  <div class="row">
    <div class="col-xl-4">.col-xl-4</div>
    <div class="col-xl-4">.col-xl-4</div>
    <div class="col-xl-4">.col-xl-4</div>
  </div>
</code>```

Output:
This is default output:

and when size of my browser reduce to less than 1200px

Here we have four row and the first row coumns will always at the same tow.

the second row will remain when max width is >=768px

the third row will remain when max width is >=992px and so on.I have inserted this details in G rids options

Here is a gif demo of output

you can mix this classes together.for example

```<code>  <div class="row">
    <div class="col-sm-4 col-xs-6">first-col</div>
    <div class="col-sm-4 col-xs-3">second-col</div>
    <div class="col-sm-4 col-xs-3">third-col</div>
  </div>
</code>```

mean if small devices I want three column with same with but in very small device I want to first-col be half of space and every two other column be 25% of with.

Now as you can see in every size you can set what behavior every row and every column should do and if you want to always move together you can use col-* classes without any prefix.
Grids Options

```<code>                (<768px)   (≥768px)   (≥992px)      (≥1200px)
Grid behavior   Horizontal at all times Collapsed to start, horizontal above breakpoints
Container width None (auto) 750px      970px          1170px
Class prefix    .col-xs-   .col-sm-    .col-md-       .col-lg-
# of columns    12
Column width    Auto       ~62px     ~81px  ~97px
Gutter width    30px (15px on each side of a column)
Nestable        Yes
Offsets         Yes
Column ordering Yes
</code>```

Here is more detail if you need

Body:
When the browser size is changed/on different sized devices, I need a set of html elements that are all semantically related to remain together and move in a block. That is, if one of the elements move to the next "row" due to their not being enough width to contain the whole grouping, ALL of it should move down.

IOW, this is sort of like the "keep together" attribute that some groupings of items in a word processing document have.

To be a little more specific, say that I have collections of the following elements:

1) an anchor tag, filling out a first "column"
2) a collection of tags, to the right of the anchor tag, consisting of:
(a) a div, followed by a

(b) a cite, followed by a

(c) another div, followed by a

(d) two or three anchor tags that are aligned side-by-side at the bottom of the second "column"

So to sum up, if there is not enough room for the second "column" in a "row," rather than keep the  in the first "column" and moving the elements in the second column down to the next "row," the  in the first column should adhere to its siblings and always remain on the same "row" with them (I'm putting "row" and "column" in quotes because I'm not using an html table, and those exist only in a virtual sense).

If you're finding this a little hard to visualize (I don't blame you), check out the fiddle: http://jsfiddle.net/W7CYC/8/

Note: wrapping the groupings into html5 s did not help.

Here's the code:

HTML:

2013

BIOGRAPHY

Son of the Wilderness: The Life of John Muir

Linnie Marsh Wolfe

BIOGRAPHY

Son of the Wilderness: The Life of John Muir

Linnie Marsh Wolfe

CSS:

body {
    background-color: black;
}
.floatLeft {
    float: left;
    padding-right: 20px;
    padding-left: 5px;
}
.yearBanner {
    font-size: 3em;
    color: white;
    font-family: Verdana, Arial, Helvetica, sans-serif;
    float: left;
    padding-top: 64px;
}
.category {
    display: inline-block;
    font-family: Consolas, sans-serif;
    font-size: 2em;
    color: Orange;
    width: 160px;
}
.title {
    display: inline-block;
    font-family: Calibri, Candara, serif;
    color: Yellow;
    width: 160px;
}
.author {
    display: inline-block;
    font-family: Courier, sans-serif;
    font-size: 0.8em;
    color: White;
    width: 160px;
}

jQuery:

$('#prizeCategory').text("Changed Category");
$('#prizeTitle').text("Changed Title that spans two rows");
$('#prizeArtist').text("Changed Author and co-author");
$('#mainImage img').attr("src", "http://ecx.images-amazon.com/images/I/61l0rZz6mdL._SY300_.jpg");
$('#mainImage img').attr("height", "200");

Body:
Bootstrap grids

Bootstrap includes a powerful mobile-first flexbox grid system for
  building layouts of all shapes and sizes. It’s based on a 12 column
  layout and has multiple tiers, one for each media query range. You can
  use it with Sass mixins or our predefined classes.

code example :

  <div class="row">
    <div class="col-4">.col-4</div>
    <div class="col-4">.col-4</div>
    <div class="col-4">.col-4</div>
  </div>

  <div class="row">
    <div class="col-sm-4">.col-sm-4</div>
    <div class="col-sm-4">.col-sm-4</div>
    <div class="col-sm-4">.col-sm-4</div>
  </div>

  <div class="row">
    <div class="col-md-4">.col-md-4</div>
    <div class="col-md-4">.col-md-4</div>
    <div class="col-md-4">.col-md-4</div>
  </div>

  <div class="row">
    <div class="col-lg-4">.col-lg-4</div>
    <div class="col-lg-4">.col-lg-4</div>
    <div class="col-lg-4">.col-lg-4</div>
  </div>

  <div class="row">
    <div class="col-xl-4">.col-xl-4</div>
    <div class="col-xl-4">.col-xl-4</div>
    <div class="col-xl-4">.col-xl-4</div>
  </div>

Output:
This is default output:

and when size of my browser reduce to less than 1200px

Here we have four row and the first row coumns will always at the same tow.

the second row will remain when max width is >=768px

the third row will remain when max width is >=992px and so on.I have inserted this details in G rids options

Here is a gif demo of output

you can mix this classes together.for example

  <div class="row">
    <div class="col-sm-4 col-xs-6">first-col</div>
    <div class="col-sm-4 col-xs-3">second-col</div>
    <div class="col-sm-4 col-xs-3">third-col</div>
  </div>

mean if small devices I want three column with same with but in very small device I want to first-col be half of space and every two other column be 25% of with.

Now as you can see in every size you can set what behavior every row and every column should do and if you want to always move together you can use col-* classes without any prefix.
Grids Options

                (<768px)   (≥768px)   (≥992px)      (≥1200px)
Grid behavior   Horizontal at all times Collapsed to start, horizontal above breakpoints
Container width None (auto) 750px      970px          1170px
Class prefix    .col-xs-   .col-sm-    .col-md-       .col-lg-
# of columns    12
Column width    Auto       ~62px     ~81px  ~97px
Gutter width    30px (15px on each side of a column)
Nestable        Yes
Offsets         Yes
Column ordering Yes

Here is more detail if you need


问:
pyGame in a thread
I want to use a pyGame program as a part of another process. Using the following code, pyGame doesn't seem to be processing events; it doesn't respond to the 'q' key nor does it draw the titlebar for the window. If go() is not run as a thread, it works fine. This is under OSX; I'm unsure if that's the problem or not.

```<code>import pygame, threading, random

def go():
  pygame.init()
  surf = pygame.display.set_mode((640,480))
  pygame.fastevent.init()

  while True:
    e = pygame.fastevent.poll()
    if e.type == pygame.KEYDOWN and e.unicode == 'q':
      return

    surf.set_at((random.randint(0,640), random.randint(0,480)), (255,255,255))
    pygame.display.flip()

t = threading.Thread(target=go)
t.start()
t.join()
</code>```

答:
Not really an answer, just an affirmation of the fact that this problem does indeed occur on Mac OS X and not on Linux. I developed my program on Ubuntu and this sort of code worked fine there, but it failed as you described when I tried to run it on a Mac. Running the drawing code in the main thread instead works fine.

If this is really a limitation of either the threading module or pygame (on Mac), then I guess the only way is to restructure your program so that all drawing is handled by the main thread. Alternatively, file a bug report and see what happens.

EDIT: Another, much better, option would be to use the multiprocessing module. You could spawn a separate python process just for rendering to screen. Processes can then communicate information to each other. I'm looking into using this myself.

Title: pyGame in a thread

Body:
I want to use a pyGame program as a part of another process. Using the following code, pyGame doesn't seem to be processing events; it doesn't respond to the 'q' key nor does it draw the titlebar for the window. If go() is not run as a thread, it works fine. This is under OSX; I'm unsure if that's the problem or not.

import pygame, threading, random

def go():
  pygame.init()
  surf = pygame.display.set_mode((640,480))
  pygame.fastevent.init()

  while True:
    e = pygame.fastevent.poll()
    if e.type == pygame.KEYDOWN and e.unicode == 'q':
      return

    surf.set_at((random.randint(0,640), random.randint(0,480)), (255,255,255))
    pygame.display.flip()

t = threading.Thread(target=go)
t.start()
t.join()


问:
Unix Shell Sed Pattern March with Space
I want to grep the data after the "DA":

```<code>BSSID:Broadcast DA:Broadcast SA:da:a1:19:dd:aa:92 (oui Unknown) Probe Request
</code>```

the output should be

```<code>Broadcast
</code>```

And the data

```<code>BSSID:d8:49:2f:74:dc:cf (oui Unknown) DA:d8:49:2f:74:dc:cf (oui Unknown) SA:d8:49:2f:74:dc:cf (oui Unknown) Probe Request
</code>```

Should be

```<code>d8:49:2f:74:dc:cf
</code>```

I use the command

```<code>echo " -90dB signal [bit 29] BSSID:Broadcast DA:Broadcast SA:f4:9f:f3:d6:68:bc (oui Unknown) Probe Request (PremiumOutletsJP) [1.0 2.0 5.5 11.0 Mbit]" |
sed -rn 's/.*DA:(.*)[:space:]/\1/p'
#it is echo "$DATA"|sed -rn 's/.*DA:(.*)[:space:]/\1/p'
</code>```

But the output is:

```<code> Broadcast SA:f4:9f:f3:d6:68:bc (oui Unknown) Probe Request (PremiumOutletJP) [1.0 2.0 5.5 11.0 Mbit]
</code>```

Or I try the command:

```<code>echo "$DATA" | sed -rn 's/ DA:(.*) /\1/p'
</code>```

Those are wrong.
Could anyone guide me to fix the error and tell me how to learn pattern match of regular-expression ? thank you.

答:
grep solution: Using look around.

```<code>echo "$DATA"|grep -oP 'DA:\K[^ ]+'
Broadcast
echo "$DATA"|grep -oP 'BSSID:\K[^ ]+'
d8:49:2f:74:dc:cf
</code>```

Using sed:

```<code>echo "$DATA"| sed -r 's/BSSID:([^ ]+).*/\1/g'
d8:49:2f:74:dc:cf

echo "$DATA"| sed -r 's/.*DA:([^ ]+).*/\1/g'
Broadcast
</code>```

Here required string is captured inside ( and ) and later called using \1. ([^ ]+) means capture anything till space character is seen.

Title: Unix Shell Sed Pattern March with Space

Body:
I want to grep the data after the "DA":

BSSID:Broadcast DA:Broadcast SA:da:a1:19:dd:aa:92 (oui Unknown) Probe Request

the output should be

Broadcast

And the data

BSSID:d8:49:2f:74:dc:cf (oui Unknown) DA:d8:49:2f:74:dc:cf (oui Unknown) SA:d8:49:2f:74:dc:cf (oui Unknown) Probe Request

Should be

d8:49:2f:74:dc:cf

I use the command

echo " -90dB signal [bit 29] BSSID:Broadcast DA:Broadcast SA:f4:9f:f3:d6:68:bc (oui Unknown) Probe Request (PremiumOutletsJP) [1.0 2.0 5.5 11.0 Mbit]" |
sed -rn 's/.*DA:(.*)[:space:]/\1/p'
#it is echo "$DATA"|sed -rn 's/.*DA:(.*)[:space:]/\1/p'

But the output is:

 Broadcast SA:f4:9f:f3:d6:68:bc (oui Unknown) Probe Request (PremiumOutletJP) [1.0 2.0 5.5 11.0 Mbit]

Or I try the command:

echo "$DATA" | sed -rn 's/ DA:(.*) /\1/p'

Those are wrong.
Could anyone guide me to fix the error and tell me how to learn pattern match of regular-expression ? thank you.

Body:
grep solution: Using look around.

echo "$DATA"|grep -oP 'DA:\K[^ ]+'
Broadcast
echo "$DATA"|grep -oP 'BSSID:\K[^ ]+'
d8:49:2f:74:dc:cf

Using sed:

echo "$DATA"| sed -r 's/BSSID:([^ ]+).*/\1/g'
d8:49:2f:74:dc:cf

echo "$DATA"| sed -r 's/.*DA:([^ ]+).*/\1/g'
Broadcast

Here required string is captured inside ( and ) and later called using \1. ([^ ]+) means capture anything till space character is seen.


问:
How do I concatenate 2 resource strings together in an aspx page
I have a localised ASP.net application (.net 2.0). I wish to concatenate 2 strings retrieved from the resource file together into one element, something like this.

```<code>Text="<%$ Resources:Resource, lw_name %>" + <%$ Resources:Resource, lw_required %>"
</code>```

I have tried using Eval without success. Is what I am trying to do the "correct" approach or can I store strings with placeholders in the resource file and interpolate them "on the fly".

I am trying to do this in the aspx file rather than in code-behind.

答:
Use this method to append 2 strings in ASPX.</p>

```<code>Text='<%# String.Format("{0} {1}",
      Resources.file01.string1,Resources.file01.string2)%>'
</code>```

Body:
I have a localised ASP.net application (.net 2.0). I wish to concatenate 2 strings retrieved from the resource file together into one element, something like this.

Text="<%$ Resources:Resource, lw_name %>" + <%$ Resources:Resource, lw_required %>"

I have tried using Eval without success. Is what I am trying to do the "correct" approach or can I store strings with placeholders in the resource file and interpolate them "on the fly".

I am trying to do this in the aspx file rather than in code-behind.

Body:
Use this method to append 2 strings in ASPX.

Text='<%# String.Format("{0} {1}",
      Resources.file01.string1,Resources.file01.string2)%>'


问:
DataBinding templates for Android Studio?
I've decided to use DataBinding library for my Android project. Are there any plugins/code templates available to install into Android Studio to get new Activity / Fragment etc added using Android Studio's wizard auto generated code compatible with DataBinding? I need to create models/presenters/variables in xml every time, can I get them to be generated automatically?</p>

答:
Well,it's not fully what am I looking for, but this looks promising: https://plugins.jetbrains.com/plugin/9271-databinding-support - int theory, it should able to convert standard layouts to data binding:

It basically intended to add all mising DataBinding integration to Android Studio.
Shame Google is still not going to add any databinding integration to Android Studio and we need 3rd party plugins for that.


问:
SOAP vs REST, when to use one and not the other?
I'm really confused everytime I come around this question, what characteristics would help one choosing SOAP over REST or the other way around?

I mean, besides the fact that REST has a compact format compared to SOAP, and the other "minor" or "technical" differences, what are the "obvious" differences that make one of them more suitable for a project and not the other?

Just for the record, I have read all of the other questions (1|2|3|4) regarding this matter on Stack Overflow, and not one of them answered my question.

答:
If you just want a simple, visual guide to help you measure SOAP and REST against your applications requirements...

Vijay Prasad Gupta has put together a simple, helpful flow-chart.

Direct link to flow chart:
https://drive.google.com/file/d/0B3zMtAq1Rf-sdVFNdThvNmZWRGc/edit

Link to article:
https://www.linkedin.com/pulse/20140818062318-7933571-soap-vs-rest-flowchart-to-determine-the-right-web-services-protocol-for-your-needs


问:
Can HttpServerUtility.Execute get binary data?
This is how I normally execute an aspx web form and get a string from the output:

```<code>public static string GetAspPageOutput(string page)
{
  string html;

  using (var sw = new StringWriter())
  {
    HttpContext.Current.Server.Execute(page, sw);

    html = sw.ToString();
  }

  return html;
}
</code>```

How do I instead get a byte array?

答:
The suggestion is from this post https://stackoverflow.com/a/1745456/3646986. Use the StreamWriter instead of the StringWriter</p>

```<code>MemoryStream ms = new MemoryStream();
StreamWriter writer = new StreamWriter(ms);
context.Server.Execute(virtualpath, writer);
var bytes = ms.toArray()
return bytes
</code>```

Body:
This is how I normally execute an aspx web form and get a string from the output:

public static string GetAspPageOutput(string page)
{
  string html;

  using (var sw = new StringWriter())
  {
    HttpContext.Current.Server.Execute(page, sw);

    html = sw.ToString();
  }

  return html;
}

How do I instead get a byte array?

Body:
The suggestion is from this post https://stackoverflow.com/a/1745456/3646986. Use the StreamWriter instead of the StringWriter

MemoryStream ms = new MemoryStream();
StreamWriter writer = new StreamWriter(ms);
context.Server.Execute(virtualpath, writer);
var bytes = ms.toArray()
return bytes


问:
why this query not working
```<code>select ROW_NUMBER() over(PARTITION by number order by number) as rn
from (select t1.id as number,
             t1.name as name from #a as T1
      join #a T2 on T1.id=T2.id)
</code>```

why this query not working

it show error.....

Msg 102, Level 15, State 1, Line 6
  Incorrect syntax near ')'.

答:
MSSQL requires that a derived table (subselect in the from clause) be named. Simply changing your query to:

```<code>select ROW_NUMBER() over(PARTITION by number order by number)as rn
from
(
select t1.id as number,t1.name as name from  #a as T1  join #a T2 on T1.id=T2.id
) subquery1
</code>```

should solve your problem.

Title: why this query not working

Body:
select ROW_NUMBER() over(PARTITION by number order by number) as rn
from (select t1.id as number,
             t1.name as name from #a as T1
      join #a T2 on T1.id=T2.id)

why this query not working

it show error.....

Msg 102, Level 15, State 1, Line 6
  Incorrect syntax near ')'.

Body:
MSSQL requires that a derived table (subselect in the from clause) be named. Simply changing your query to:

select ROW_NUMBER() over(PARTITION by number order by number)as rn
from
(
select t1.id as number,t1.name as name from  #a as T1  join #a T2 on T1.id=T2.id
) subquery1

should solve your problem.


问:
Group values of keys in ruby hash in one hash and print specific value
This is my hash:

```<code>{"Specialty"=>"Other (note in description);Medical;Dental;Vision", "Value"=>"https://www.example.com/ca"}
{"Value"=>"P.O. BOX 60007 LOS ANGELES, CA 90060"}
{"Specialty"=>"Pharmacy;Medical", "Value"=>"800-824-0898"}
{"Specialty"=>"Urgent Care;Medical", "Value"=>"800-700-9186"}
{"Specialty"=>"Urgent Care;Emergency Care;Medical;Chiropractor;Acupuncture", "Value"=>"800-677-6669"}
{"Specialty"=>"Pharmacy;Medical", "Value"=>"https://www.example.com"}
{"Specialty"=>"Claims", "Value"=>"https://www.example.com/consumer/claims/claimsoverview"}
{"Specialty"=>"Urgent Care;Emergency Care;Medical;Chiropractor;Acupuncture", "Value"=>"https://example/example/apps/services/www/ABCBS/mobilewebapp/default/index.html#/providers/search"}
{""Specialty"=>"Claims;Customer Service;Medical", "Value"=>"800-888-8288"}
</code>```

You can see from this that the key value has differed values in each hash table, and I would like to print only one specific value, that is P.O. BOX 60007 LOS ANGELES, CA 90060

I tried printing the values of the hash by hash["value"] and it prints all the contents of the values. I tried loading them into an array[] by using to_s function to print the value I want, but one array is loaded with all these values or I may be loading the array wrong.

```<code>array = []
array = medical.split("\n")
text = array.to_s
text1 = array.index{|s| s.include?("P.O.")}
puts text1
</code>```

Can someone help me with how do I print that specific hash value inspite of various values existing in the key named value

答:
If that's the pattern of the hash specifically, uniqueness I can figure out is that all hashes have multiple keys except the one you are looking for..considering it as an array of hashes

```<code>hashes.each{ |hash| break hash['Value'] if hash.keys == ['Value'] }
</code>```

UPDATE

From the comments, instead of printing the hashes individually you can check and print the required value directly..

```<code>results1.map{ |result1| (value = result1['Value']).include?('P.O. BOX') ? value : nil }.compact
</code>```

It will return array of strings having substring P.O. BOX

Body:
This is my hash:

{"Specialty"=>"Other (note in description);Medical;Dental;Vision", "Value"=>"https://www.example.com/ca"}
{"Value"=>"P.O. BOX 60007 LOS ANGELES, CA 90060"}
{"Specialty"=>"Pharmacy;Medical", "Value"=>"800-824-0898"}
{"Specialty"=>"Urgent Care;Medical", "Value"=>"800-700-9186"}
{"Specialty"=>"Urgent Care;Emergency Care;Medical;Chiropractor;Acupuncture", "Value"=>"800-677-6669"}
{"Specialty"=>"Pharmacy;Medical", "Value"=>"https://www.example.com"}
{"Specialty"=>"Claims", "Value"=>"https://www.example.com/consumer/claims/claimsoverview"}
{"Specialty"=>"Urgent Care;Emergency Care;Medical;Chiropractor;Acupuncture", "Value"=>"https://example/example/apps/services/www/ABCBS/mobilewebapp/default/index.html#/providers/search"}
{""Specialty"=>"Claims;Customer Service;Medical", "Value"=>"800-888-8288"}

You can see from this that the key value has differed values in each hash table, and I would like to print only one specific value, that is P.O. BOX 60007 LOS ANGELES, CA 90060

I tried printing the values of the hash by hash["value"] and it prints all the contents of the values. I tried loading them into an array[] by using to_s function to print the value I want, but one array is loaded with all these values or I may be loading the array wrong.

array = []
array = medical.split("\n")
text = array.to_s
text1 = array.index{|s| s.include?("P.O.")}
puts text1

Can someone help me with how do I print that specific hash value inspite of various values existing in the key named value

Body:
If that's the pattern of the hash specifically, uniqueness I can figure out is that all hashes have multiple keys except the one you are looking for..considering it as an array of hashes

hashes.each{ |hash| break hash['Value'] if hash.keys == ['Value'] }

UPDATE

From the comments, instead of printing the hashes individually you can check and print the required value directly..

results1.map{ |result1| (value = result1['Value']).include?('P.O. BOX') ? value : nil }.compact

It will return array of strings having substring P.O. BOX


问:
Deploy Angular 2 to Apache Server
I want to deploy an Angular 2 application on an Apache server. I've read various guides like this and this but none of them is working. I have npm and ng installed on the server.

In a nutshell, here's what I did:

Cloned complete project repository on my server.

Installed dependencies using npm install.

Used ng build --prod command and it created a dist directory.

Changed apache root to /var/www/html/dist directory.

Enabled mod_rewrite, restarted apache and added this .htaccess in my dist directory.

```<code><IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.html$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.html [L]
</IfModule>
</code>```

But only my home page domain.com works, other pages like domain.com/login, domain.com/register etc. throw 404 error. Even domain.com/index.html/login doesn't work.

The application works fine on my local system where I'm developing it using ng serve. What am i missing?

答:
Change base tag in index.html file

<base href="./">

Create a build after that

ng build --prod

Now you will have a new folder dist, deploy dist folder now. It should work.

ContentLicense: CC BY-SA 4.0

Title: Deploy Angular 2 to Apache Server

Body:
I want to deploy an Angular 2 application on an Apache server. I've read various guides like this and this but none of them is working. I have npm and ng installed on the server.

In a nutshell, here's what I did:

Cloned complete project repository on my server.

Installed dependencies using npm install.

Used ng build --prod command and it created a dist directory.

Changed apache root to /var/www/html/dist directory.

Enabled mod_rewrite, restarted apache and added this .htaccess in my dist directory.

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.html$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.html [L]
</IfModule>

But only my home page domain.com works, other pages like domain.com/login, domain.com/register etc. throw 404 error. Even domain.com/index.html/login doesn't work.

The application works fine on my local system where I'm developing it using ng serve. What am i missing?


问:
Changing the height of a html div down to top without using transition
I need to do tank animation, where according to the liquid level, the height of the tank(image) changes. For this I have written HTML code as below:

```<code><div>
<img id='T1' style="height:0px;position:absolute">
</div>
</code>```

Now I am obtaining the level information from database using ajax and trying to change the height of the image according to the value of the level parameter using JavaScript.

```<code>  var level=response;
 document.getElementById('T1').height=level."px";
</code>```

This is changing the height from top to down, but I want down to top.
Inverting the div using transform is not working. Also transition is not working as transition-time cannot be specified in this case.
Please provide me some suggestions.

答:
Position the image absolute to the bottom of the container with bottom: 0 so that it always starts at the bottom and extends from there.

To demonstrate:

var level=14;
document.getElementById('T1').style.height = level+"px";

var changeLevel = function() {
    var level = document.getElementById('level').value;
    document.getElementById('T1').style.height = level+"px";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
    margin-top: 20px;
    position: relative;
    height: 50px;
    background-color: #eee;
}
#T1 {
    height: 0px;
    background-color: #909;
    width: 100%;
    position: absolute;
    bottom: 0;
}</code>```

<input id="level" type="text" placeholder="Level" />
<input type="button" value="Change Level" onclick="changeLevel()"/>

```

Body:
I need to do tank animation, where according to the liquid level, the height of the tank(image) changes. For this I have written HTML code as below:

Now I am obtaining the level information from database using ajax and trying to change the height of the image according to the value of the level parameter using JavaScript.

  var level=response;
 document.getElementById('T1').height=level."px";

This is changing the height from top to down, but I want down to top.
Inverting the div using transform is not working. Also transition is not working as transition-time cannot be specified in this case.
Please provide me some suggestions.

Body:
Position the image absolute to the bottom of the container with bottom: 0 so that it always starts at the bottom and extends from there.

To demonstrate:

var level=14;
document.getElementById('T1').style.height = level+"px";

var changeLevel = function() {
    var level = document.getElementById('level').value;
    document.getElementById('T1').style.height = level+"px";
}

div {
    margin-top: 20px;
    position: relative;
    height: 50px;
    background-color: #eee;
}
#T1 {
    height: 0px;
    background-color: #909;
    width: 100%;
    position: absolute;
    bottom: 0;
}

<input id="level" type="text" placeholder="Level" />
<input type="button" value="Change Level" onclick="changeLevel()"/>

<div>
    <div id='T1'></div>
</div>


问:
Display the image used as launch image fullscreend as background
I am trying to show the image that is used as launch image as background and as fade between launch and first view.
I "select" the image I want to use as follows:

```<code>NSString *defaultImageName = @"Default.png";
CGFloat imageScale = [[UIScreen mainScreen] scale];
CGSize imageSize = [[UIScreen mainScreen] applicationFrame].size;
if (imageScale > 1) {
    if (imageSize.height < 500) {
        defaultImageName = @"Default@2x.png";
    } else {
        defaultImageName = @"Default-568h@2x.png";
    }
}
backimg = [UIImage imageNamed:defaultImageName];
UIImageView *backgroundImage = [[UIImageView alloc] initWithImage: backimg];
[self.view addSubview:backgroundImage];
[self.view sendSubviewToBack:backgroundImage];
</code>```

Sadly the image isn´t shown fullscreen, it is display scaled:

instead of

Can anyone help with that?

Update #1:

solved using [backgroundImage setFrame:CGRectMake(0, 0,self.view.frame.size.width , self.view.frame.size.height)];

答:
Get Image use

```<code>[[UIImage alloc]initWithContentsOfFile:[[NSBundle mainBundle]
                           pathForResource:@"xxx" ofType:@"png"]]
</code>```

Instead of

```<code>[UIImage imageNamed: @"xxx"]
</code>```

Body:
I am trying to show the image that is used as launch image as background and as fade between launch and first view.
I "select" the image I want to use as follows:

NSString *defaultImageName = @"Default.png";
CGFloat imageScale = [[UIScreen mainScreen] scale];
CGSize imageSize = [[UIScreen mainScreen] applicationFrame].size;
if (imageScale > 1) {
    if (imageSize.height < 500) {
        defaultImageName = @"Default@2x.png";
    } else {
        defaultImageName = @"Default-568h@2x.png";
    }
}
backimg = [UIImage imageNamed:defaultImageName];
UIImageView *backgroundImage = [[UIImageView alloc] initWithImage: backimg];
[self.view addSubview:backgroundImage];
[self.view sendSubviewToBack:backgroundImage];

Sadly the image isn´t shown fullscreen, it is display scaled:

instead of

Can anyone help with that?

Update #1:

solved using [backgroundImage setFrame:CGRectMake(0, 0,self.view.frame.size.width , self.view.frame.size.height)];

Body:
Get Image use

[[UIImage alloc]initWithContentsOfFile:[[NSBundle mainBundle]
                           pathForResource:@"xxx" ofType:@"png"]]

Instead of

[UIImage imageNamed: @"xxx"]


问:
Convert a post-order binary tree traversal index to an level-order (breadth-first) index
Assuming a complete binary tree, each node can be adressed with the position it appears in a given tree traversal algorithm.

For example, the node indices of a simple complete tree with height 3 would look like this:

breadth first (aka level-order):

```<code>     0
   /   \
  1     2
 /  \  /  \
3   4  5  6
</code>```

post-order dept first:

```<code>     6
   /   \
  2     5
 /  \  /  \
0   1  3  4
</code>```

The height of the tree and an index in the post-order traversal is given.

How can i calculate the breadth first index from this information?

答:
I think it has to be computed iteratively/recursively.  Having said that, someone will come along in 37 seconds with a simple single-line computation and downvote me.  Nonetheless, it can be solved by thinking of it recursively.  Consider the simple tree (1-based) of a depth-first post-order traversal:

```<code>   3
  / \
 1   2
</code>```

From a recursive standpoint, that's all you have to think about.  You are either at the root of the subtree (3), in the left part of the subtree (1) or in the right part (2).  If you are at the root, then you are done.  Otherwise, the left and right subtrees are identical and the post-order traversal index in the right subtree is equal to the corresponding left subtree index + the number of nodes in the subtree.

The following code performs this computation in O(log n). For a tree with depth 10 (1023 nodes), it computes the index value in a maximum of 10 iterations (recursions).

It tracks the depth of the given node and computes the breadth-first row position based on whether it is dealing with the left or right subtree.  Note that this uses 1-based index values.  I found it simpler to think of it in those terms (a tree of depth 2 has 3 nodes in it and the top-most node in a post-order traversal is 3).  Also note that it considers a tree depth of 1 to have one node (I'm not sure if that is the typical convention or not).

```<code>// Recursively compute the given post-order traversal index's position
// in the tree:  Its position in the given level and its depth in the tree.
void ComputePos( int treedepth, int poindex, int *levelposition, int *nodedepth )
{
    int nodes;
    int half;

    // compute number of nodes for this depth.
    assert( treedepth > 0 );
    nodes = ( 1 << ( treedepth )) - 1;
    half = nodes / 2;   // e.g., 7 / 2 = 3

    //printf( "poindex = %3d, Depth = %3d, node count = %3d", poindex, treedepth, nodes );

    (*nodedepth)++;

    if ( poindex == nodes ) {
        // This post-order index value is the root of this subtree
        //printf( "  Root\n" );
        return;
    }
    else if ( poindex > half ) {
        // This index is in the right subtree
        //printf( "  Right\n" );
        poindex -= half;
        *levelposition = 2 * *levelposition + 1;
    }
    else {
        // Otherwise it must be in the left subtree
        //printf( "  Left\n" );
        *levelposition = 2 * *levelposition;
    }

    treedepth -= 1;
    ComputePos( treedepth, poindex, levelposition, nodedepth );
}

int main( int argc, char* argv[] )
{
    int levelposition = 0;   // the 0-based index from the left in a given level
    int nodedepth = 0;  // the depth of the node in the tree
    int bfindex;
    int treedepth = atoi( argv[1] );   // full depth of the tree (depth=1 means 1 node)
    int poindex = atoi( argv[2] ); // 1-based post-order traversal index

    ComputePos( treedepth, poindex, &levelposition, &nodedepth );

    //printf( "ComputePos( %d, %d ) = %d, %d\n", treedepth, poindex, levelposition, nodedepth );

    // Compute the breadth-first index as its position in its current
    // level plus the count of nodex in all the levels above it.
    bfindex = levelposition + ( 1 << ( nodedepth - 1 ));
    printf( "Post-Order index %3d = breadth-first index %3d\n", poindex, bfindex );

    return 0;
}
</code>```

Here are the values computed for the following tree (depth 4), which shows the post-order traversal index values (1-based).

```<code>            15
          /    \
         /      \
        /        \
       /          \
      /            \
     7             14
    / \            / \
   /   \          /   \
  3     6       10    13
 /\    / \      /\    / \
1  2  4   5    8  9  11  12

[C:\tmp]for /l %i in (1,1,15) do po2bf 4 %i
Post-Order index   1 = breadth-first index   8
Post-Order index   2 = breadth-first index   9
Post-Order index   3 = breadth-first index   4
Post-Order index   4 = breadth-first index  10
Post-Order index   5 = breadth-first index  11
Post-Order index   6 = breadth-first index   5
Post-Order index   7 = breadth-first index   2
Post-Order index   8 = breadth-first index  12
Post-Order index   9 = breadth-first index  13
Post-Order index  10 = breadth-first index   6
Post-Order index  11 = breadth-first index  14
Post-Order index  12 = breadth-first index  15
Post-Order index  13 = breadth-first index   7
Post-Order index  14 = breadth-first index   3
Post-Order index  15 = breadth-first index   1
</code>```

Body:
Assuming a complete binary tree, each node can be adressed with the position it appears in a given tree traversal algorithm.

For example, the node indices of a simple complete tree with height 3 would look like this:

breadth first (aka level-order):

     0
   /   \
  1     2
 /  \  /  \
3   4  5  6

post-order dept first:

     6
   /   \
  2     5
 /  \  /  \
0   1  3  4

The height of the tree and an index in the post-order traversal is given.

How can i calculate the breadth first index from this information?

Body:
I think it has to be computed iteratively/recursively.  Having said that, someone will come along in 37 seconds with a simple single-line computation and downvote me.  Nonetheless, it can be solved by thinking of it recursively.  Consider the simple tree (1-based) of a depth-first post-order traversal:

   3
  / \
 1   2

From a recursive standpoint, that's all you have to think about.  You are either at the root of the subtree (3), in the left part of the subtree (1) or in the right part (2).  If you are at the root, then you are done.  Otherwise, the left and right subtrees are identical and the post-order traversal index in the right subtree is equal to the corresponding left subtree index + the number of nodes in the subtree.

The following code performs this computation in O(log n). For a tree with depth 10 (1023 nodes), it computes the index value in a maximum of 10 iterations (recursions).

It tracks the depth of the given node and computes the breadth-first row position based on whether it is dealing with the left or right subtree.  Note that this uses 1-based index values.  I found it simpler to think of it in those terms (a tree of depth 2 has 3 nodes in it and the top-most node in a post-order traversal is 3).  Also note that it considers a tree depth of 1 to have one node (I'm not sure if that is the typical convention or not).

// Recursively compute the given post-order traversal index's position
// in the tree:  Its position in the given level and its depth in the tree.
void ComputePos( int treedepth, int poindex, int *levelposition, int *nodedepth )
{
    int nodes;
    int half;

    // compute number of nodes for this depth.
    assert( treedepth > 0 );
    nodes = ( 1 << ( treedepth )) - 1;
    half = nodes / 2;   // e.g., 7 / 2 = 3

    //printf( "poindex = %3d, Depth = %3d, node count = %3d", poindex, treedepth, nodes );

    (*nodedepth)++;

    if ( poindex == nodes ) {
        // This post-order index value is the root of this subtree
        //printf( "  Root\n" );
        return;
    }
    else if ( poindex > half ) {
        // This index is in the right subtree
        //printf( "  Right\n" );
        poindex -= half;
        *levelposition = 2 * *levelposition + 1;
    }
    else {
        // Otherwise it must be in the left subtree
        //printf( "  Left\n" );
        *levelposition = 2 * *levelposition;
    }

    treedepth -= 1;
    ComputePos( treedepth, poindex, levelposition, nodedepth );
}

int main( int argc, char* argv[] )
{
    int levelposition = 0;   // the 0-based index from the left in a given level
    int nodedepth = 0;  // the depth of the node in the tree
    int bfindex;
    int treedepth = atoi( argv[1] );   // full depth of the tree (depth=1 means 1 node)
    int poindex = atoi( argv[2] ); // 1-based post-order traversal index

    ComputePos( treedepth, poindex, &levelposition, &nodedepth );

    //printf( "ComputePos( %d, %d ) = %d, %d\n", treedepth, poindex, levelposition, nodedepth );

    // Compute the breadth-first index as its position in its current
    // level plus the count of nodex in all the levels above it.
    bfindex = levelposition + ( 1 << ( nodedepth - 1 ));
    printf( "Post-Order index %3d = breadth-first index %3d\n", poindex, bfindex );

    return 0;
}

Here are the values computed for the following tree (depth 4), which shows the post-order traversal index values (1-based).

            15
          /    \
         /      \
        /        \
       /          \
      /            \
     7             14
    / \            / \
   /   \          /   \
  3     6       10    13
 /\    / \      /\    / \
1  2  4   5    8  9  11  12

[C:\tmp]for /l %i in (1,1,15) do po2bf 4 %i
Post-Order index   1 = breadth-first index   8
Post-Order index   2 = breadth-first index   9
Post-Order index   3 = breadth-first index   4
Post-Order index   4 = breadth-first index  10
Post-Order index   5 = breadth-first index  11
Post-Order index   6 = breadth-first index   5
Post-Order index   7 = breadth-first index   2
Post-Order index   8 = breadth-first index  12
Post-Order index   9 = breadth-first index  13
Post-Order index  10 = breadth-first index   6
Post-Order index  11 = breadth-first index  14
Post-Order index  12 = breadth-first index  15
Post-Order index  13 = breadth-first index   7
Post-Order index  14 = breadth-first index   3
Post-Order index  15 = breadth-first index   1


问:
Jest Mock - inserting values into tested file
I'm having trouble inserting values into the file under test:

```<code>import device from '../device'

let execute = () => {
  if (device.isAndroid()) {
    return true
  else {
    return false
  }
}
</code>```

Now for the test file:

```<code>jest.mock('../device')
import device from '../device'

describe('when the device is Android', () => {
  let device

  beforeEach(() => {
    device = jest.fn().mockImplementation(() => {
      return {
        isAndroid: () => { return true }
      }
    })
  })

  it('returns true', () => {
    let results = execute()
    expect(result).toEqual(true)
  })
})
</code>```

The test fails and returns false. What am I doing wrong?

答:
You need to mock '../device' with a jest spy and the mock implementation on that:

```<code>jest.mock('../device', ()=>{return {isAndroid: jest.fn()}})
import device from '../device'

describe('when the device is Android', () => {

  beforeEach(() => {
    device.isAndroid.mockImplementation(() => true)
  })

  it('returns true', () => {
    let results = execute()
    expect(result).toEqual(true)
  })
})
</code>```

Body:
I'm having trouble inserting values into the file under test:

import device from '../device'

let execute = () => {
  if (device.isAndroid()) {
    return true
  else {
    return false
  }
}

Now for the test file:

jest.mock('../device')
import device from '../device'

describe('when the device is Android', () => {
  let device

  beforeEach(() => {
    device = jest.fn().mockImplementation(() => {
      return {
        isAndroid: () => { return true }
      }
    })
  })

  it('returns true', () => {
    let results = execute()
    expect(result).toEqual(true)
  })
})

The test fails and returns false. What am I doing wrong?

Body:
You need to mock '../device' with a jest spy and the mock implementation on that:

jest.mock('../device', ()=>{return {isAndroid: jest.fn()}})
import device from '../device'

describe('when the device is Android', () => {

  beforeEach(() => {
    device.isAndroid.mockImplementation(() => true)
  })

  it('returns true', () => {
    let results = execute()
    expect(result).toEqual(true)
  })
})


问:
Async load multiple images to single cell
I have a problem with loading of 5 images to each cell of TableView. I use AFNetworking for download and setImageWithUrl method for imageView:

```<code>for (int i = 0; i < urls.count; i++) {
    [self.photoImageView[i] setImageWithURL:urls[i]];
}
</code>```

TableView very brakes when I scroll it. But when i try to load 1 or 2  no brakes when scrolling.

How to correct download images without brakes?

答:
For downloading the Asynchronous image from url, use any of these library for improving the scroll performance

SDWebImage - Asynchronous image downloader with cache support as a UIImageView category.

```<code>#import <SDWebImage/UIImageView+WebCache.h>
...
[imageView sd_setImageWithURL:URL
             placeholderImage:[UIImage imageNamed:@"placeholder.png"]
];
</code>```

PINRemoteImage - It download a progressive jpeg and get attractive blurred updates.

For in your case, you can go for SDWebImage.

```<code>For Advance Concept, you could look into this one.
</code>```

AsyncDisplayKit  - Smooth asynchronous user interfaces for iOS apps

Even recently, Pinterest was built on top of AsyncDisplayKit to Keeps UIs smooth and responsive.
Read this article for more info: https://medium.com/@Pinterest_Engineering/re-architecting-pinterest-039-s-ios-app-e0a2d34a6ac2

Body:
I have a problem with loading of 5 images to each cell of TableView. I use AFNetworking for download and setImageWithUrl method for imageView:

for (int i = 0; i < urls.count; i++) {
    [self.photoImageView[i] setImageWithURL:urls[i]];
}

TableView very brakes when I scroll it. But when i try to load 1 or 2  no brakes when scrolling.

How to correct download images without brakes?

Body:
For downloading the Asynchronous image from url, use any of these library for improving the scroll performance

SDWebImage - Asynchronous image downloader with cache support as a UIImageView category.

#import <SDWebImage/UIImageView+WebCache.h>
...
[imageView sd_setImageWithURL:URL
             placeholderImage:[UIImage imageNamed:@"placeholder.png"]
];

PINRemoteImage - It download a progressive jpeg and get attractive blurred updates.

For in your case, you can go for SDWebImage.

For Advance Concept, you could look into this one.

AsyncDisplayKit  - Smooth asynchronous user interfaces for iOS apps

Even recently, Pinterest was built on top of AsyncDisplayKit to Keeps UIs smooth and responsive.
Read this article for more info: https://medium.com/@Pinterest_Engineering/re-architecting-pinterest-039-s-ios-app-e0a2d34a6ac2


问:
How to center image in attributed string?
I have an image that I want to center alongside a bunch of text but even when I set the NSMutableParagraphStyle alignment to center, the line with the image does not center

If anyone could please help me center the line with the image (i.e. first line) that would be great!

Code

```<code>let text = " text next to image is not centered \n\n centered text \n more centered text"
let iconAttachment = textAttachment(fontSize: 14, image: #imageLiteral(resourceName: "icon"))
        let iconString = NSAttributedString(attachment: iconAttachment)
let style = NSMutableParagraphStyle()
        style.alignment = .center
        style.minimumLineHeight = 20

        let attributedText = NSMutableAttributedString()
        attributedText.append(iconString)
        let fullText = NSAttributedString(string: text, attributes: [NSParagraphStyleAttributeName : style])
        attributedText.append(fullText)

private func textAttachment(fontSize: CGFloat, image: UIImage) -> NSTextAttachment {
        let font = UIFont.systemFont(ofSize: fontSize) //set accordingly to your font, you might pass it in the function
        let textAttachment = NSTextAttachment()
            textAttachment.image = image
        let mid = font.descender + font.capHeight
        textAttachment.bounds = CGRect(x: 0, y: font.descender - image.size.height / 2 + mid + 2, width: image.size.width, height: image.size.height).integral
        return textAttachment
    }
</code>```

答:
You just need to Alignment your lebel text to center and it will work :

```<code> label.textAlignment = .center
</code>```

Body:
I have an image that I want to center alongside a bunch of text but even when I set the NSMutableParagraphStyle alignment to center, the line with the image does not center

If anyone could please help me center the line with the image (i.e. first line) that would be great!

Code

let text = " text next to image is not centered \n\n centered text \n more centered text"
let iconAttachment = textAttachment(fontSize: 14, image: #imageLiteral(resourceName: "icon"))
        let iconString = NSAttributedString(attachment: iconAttachment)
let style = NSMutableParagraphStyle()
        style.alignment = .center
        style.minimumLineHeight = 20

        let attributedText = NSMutableAttributedString()
        attributedText.append(iconString)
        let fullText = NSAttributedString(string: text, attributes: [NSParagraphStyleAttributeName : style])
        attributedText.append(fullText)

private func textAttachment(fontSize: CGFloat, image: UIImage) -> NSTextAttachment {
        let font = UIFont.systemFont(ofSize: fontSize) //set accordingly to your font, you might pass it in the function
        let textAttachment = NSTextAttachment()
            textAttachment.image = image
        let mid = font.descender + font.capHeight
        textAttachment.bounds = CGRect(x: 0, y: font.descender - image.size.height / 2 + mid + 2, width: image.size.width, height: image.size.height).integral
        return textAttachment
    }

Body:
You just need to Alignment your lebel text to center and it will work :

 label.textAlignment = .center


问:
Drawing Cylinder Model as thick 3d line
I am working on an application that has to render a graph 3-dimensionally.
Nodes are represented by spheres and in my first draft I just draw glLines as edges.

Now the lines need to be

a) thick lines and

b) as it is a 3d application, they basically must have an cylindrical shape (It would look very weird otherwise).

After reading up on thick lines in OpenGL, I figured that this is relatively complicated, especially given my additional cylindrical shape in 3d requirement.

So I thought "Why not just take a cylinder model, and translate/rotate/scale it in place to represent the edge".

It works fine for me, and also achieves the look I am going for.

As I never saw anything similar online when researching "thick lines in OpenGL" I was wondering if there are any major drawback with my approach?

答:
I would use GLSL

pass interpolation polynomial/control points of rendered part of your curve plot

so divide your plot to chunks, fit polynomial or use cubic interpolation.

render rectangle covering your actually rendered chunk

in fragment

compute distance of fragment to your curve and either render it (color based on distance) or discard it if more distant then cylinder radius.

Here some related QAs that can help you with your task:

How can i produce multi point linear interpolation?

Draw Quadratic Curve on GPU

How can i make gradient sphere on glsl?

complete GL+GLSL+VAO/VBO C++ example

Morph a tube to coil in three js

Title: Drawing Cylinder Model as thick 3d line


问:
SQL Server simple Insert statement times out
I have a simple table with 6 columns. Most of the time any insert statements to it works just fine, but once in a while I'm getting a DB Timeout exception:
Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. The statement has been terminated.

Timeout is set to 10 seconds.

I should mention that I'm using NHibernate and that the statement also include a "select SCOPE_IDENTITY()" right after the insert itself.

My thought was that the table was locked or something, but there were no other statements running on that table at that time.

All the inserts are very simple, everything looks normal in sql profiler, the table has no indices but the PK (Page fullness: 98.57 %).

Any ideas on what should I look for?

Thanks.

答:
Could be that the table is taking a long time to grow.

If you have the table set to grow by a large amount, and don't have instant file initialization enabled, then the query could certainly timeout every once in a while.

Check this mess out: MSDN

OwnerDisplayName: Meidan Alon

LastEditorDisplayName: Ishmaeel

OwnerDisplayName: Eam


问:
What is the most common waste of computing power in Javascript?
We've all seen people who do this:

```<code>jQuery('a').each(function(){
    jQuery(this)[0].innerHTML += ' proccessed';
});

function letsPoluteNS() {
    polute = '';
    for (morePolution = 0; morePolution < arguments.length; morePolution++)
        polute.join(arguments[morePolution]);
    return polute;
}
</code>```

and so on. I was wondering what people have seen the most common JavaScript/jQuery technique that is slowing down the page and/or wasting time for the JavaScript engine.

I know that this question may not seem to fit into what's an accepted question, yet I'm asking "what is the most common accepted waste?"

答:
I'm guilt of this. Basically using only the element's class in a jQuery selector. Instead of combining the class selector with the elements tag name.

```<code><div></div>
<div class="hide"></div>
<div class="show"></div>
<div class="hide"></div>
<div class="hide again"></div>
</code>```

```<code>$(".hide").hide();
</code>```

Instead of the quicker

```<code>$("div.hide").hide()
</code>```

Also this is inefficient, many people don't make use of the context parameter for selectors

$( selector, [ context ] )

```<code>   $("#mydiv").click(function () {
      $("#mydiv span").show();
   }
</code>```

Which can be handled better like this:

```<code>   $("#mydiv").click(function () {
      $("span", this).show();
   }
</code>```

Body:
We've all seen people who do this:

jQuery('a').each(function(){
    jQuery(this)[0].innerHTML += ' proccessed';
});

function letsPoluteNS() {
    polute = '';
    for (morePolution = 0; morePolution < arguments.length; morePolution++)
        polute.join(arguments[morePolution]);
    return polute;
}

and so on. I was wondering what people have seen the most common JavaScript/jQuery technique that is slowing down the page and/or wasting time for the JavaScript engine.

I know that this question may not seem to fit into what's an accepted question, yet I'm asking "what is the most common accepted waste?"

Body:
I'm guilt of this. Basically using only the element's class in a jQuery selector. Instead of combining the class selector with the elements tag name.

<div></div>
<div class="hide"></div>
<div class="show"></div>
<div class="hide"></div>
<div class="hide again"></div>

$(".hide").hide();

Instead of the quicker

$("div.hide").hide()

Also this is inefficient, many people don't make use of the context parameter for selectors

$( selector, [ context ] )

   $("#mydiv").click(function () {
      $("#mydiv span").show();
   }

Which can be handled better like this:

   $("#mydiv").click(function () {
      $("span", this).show();
   }


问:
Selenium Loop Through Table Until Td Contains "x"
I wanted to loop through the table until Td text is "Dispatched Export To Shipper". I don't want it to check for below nodes.Only first 8 rows. But the condition should be td text. Any ideas?

Table Sample:

```<code><table role="grid" data-role="selectable" class="k-selectable">
<colgroup>
    <col style="width:115px">
    <col>
    <col>
    <col>
    <col>
    <col style="width:70px">
    <col style="width:50px">
    <col>
</colgroup>
<thead class="k-grid-header" role="rowgroup">
    <tr role="row">
        <th class="k-header" data-field="XNS_DTTM" data-index="0" data-title="Date" scope="col">
            <span class="k-link">Date</span>
        </th>
        <th class="k-header" data-field="ATLOC_NAME" data-index="1" data-title="Location" scope="col">
            <span class="k-link">Location</span>
        </th>
        <th class="k-header" data-field="TOLOC_NAME" data-index="2" data-title="To Location" scope="col">
            <span class="k-link">To Location</span>
        </th>
        <th class="k-header" data-field="BL_OR_BKG_NO" data-index="3" data-title="BL/BKG" scope="col">
            <span class="k-link">BL/BKG</span>
        </th>
        <th class="k-header" data-field="VSL_NAME" data-index="4" data-title="Vessel" scope="col">
            <span class="k-link">Vessel</span>
        </th>
        <th class="k-header" data-field="VOY_CODE" data-index="5" data-title="Voy" scope="col">
            <span class="k-link">Voy</span>
        </th>
        <th class="k-header" data-field="LINE_CODE" data-index="6" data-title="Line" scope="col">
            <span class="k-link">Line</span>
        </th>
        <th class="k-header" data-field="XNS_DSCR" data-index="7" data-title="Description" scope="col">
            <span class="k-link">Description</span>
        </th>
    </tr>
</thead>
<tbody role="rowgroup">
    <tr data-uid="affa9830-8556-4dcd-bcbc-4f54f0a56cc6" role="row">
        <td style="vertical-align:top;" role="gridcell">28-JUN-2017 09:30</td>
        <td style="vertical-align:top;" role="gridcell">COLOMBO - SOUTH ASIA GATEWAY TERMINAL</td>
        <td style="vertical-align:top;" role="gridcell"></td>
        <td style="vertical-align:top;" role="gridcell">
            <span title="Login into MOLPOWER to see the Container details.">--</span>
        </td>
        <td style="vertical-align:top;" role="gridcell">BELLAVIA/BLV</td>
        <td style="vertical-align:top;" role="gridcell">0034E</td>
        <td style="vertical-align:top;" role="gridcell">HSX</td>
        <td style="vertical-align:top;" role="gridcell">Landed Transshipment</td>
    </tr>
    <tr class="k-alt" data-uid="634db05f-8f85-49e4-b143-13971126591f" role="row">
        <td style="vertical-align:top;" role="gridcell">28-JUN-2017 08:42</td>
        <td style="vertical-align:top;" role="gridcell">COLOMBO - SOUTH ASIA GATEWAY TERMINAL</td>
        <td style="vertical-align:top;" role="gridcell"></td>
        <td style="vertical-align:top;" role="gridcell">
            <span title="Login into MOLPOWER to see the Container details.">--</span>
        </td>
        <td style="vertical-align:top;" role="gridcell">BELLAVIA/BLV</td>
        <td style="vertical-align:top;" role="gridcell">0034E</td>
        <td style="vertical-align:top;" role="gridcell">HSX</td>
        <td style="vertical-align:top;" role="gridcell">Vessel arrived at port</td>
    </tr>
    <tr data-uid="bdac4da1-ef1e-49f8-bb85-ff8bda21ff65" role="row">
        <td style="vertical-align:top;" role="gridcell">25-JUN-2017 18:18</td>
        <td style="vertical-align:top;" role="gridcell">PIPAVAV-APM TERMINALS</td>
        <td style="vertical-align:top;" role="gridcell">COLOMBO - SOUTH ASIA GATEWAY TERMINAL</td>
        <td style="vertical-align:top;" role="gridcell">
            <span title="Login into MOLPOWER to see the Container details.">--</span>
        </td>
        <td style="vertical-align:top;" role="gridcell">BELLAVIA/BLV</td>
        <td style="vertical-align:top;" role="gridcell">0034E</td>
        <td style="vertical-align:top;" role="gridcell">HSX</td>
        <td style="vertical-align:top;" role="gridcell">Vessel depart from the port</td>
    </tr>
    <tr class="k-alt" data-uid="403e9c6a-aec8-4124-b74b-749a98b52675" role="row">
        <td style="vertical-align:top;" role="gridcell">25-JUN-2017 13:57</td>
        <td style="vertical-align:top;" role="gridcell">PIPAVAV-APM TERMINALS</td>
        <td style="vertical-align:top;" role="gridcell">COLOMBO - SOUTH ASIA GATEWAY TERMINAL</td>
        <td style="vertical-align:top;" role="gridcell">
            <span title="Login into MOLPOWER to see the Container details.">--</span>
        </td>
        <td style="vertical-align:top;" role="gridcell">BELLAVIA/BLV</td>
        <td style="vertical-align:top;" role="gridcell">0034E</td>
        <td style="vertical-align:top;" role="gridcell">HSX</td>
        <td style="vertical-align:top;" role="gridcell">Loaded on Vessel</td>
    </tr>
    <tr data-uid="8e7c6913-a4a4-4ef9-a6a1-d16b9a3b7d30" role="row">
        <td style="vertical-align:top;" role="gridcell">20-JUN-2017 20:27</td>
        <td style="vertical-align:top;" role="gridcell">PIPAVAV-APM TERMINALS</td>
        <td style="vertical-align:top;" role="gridcell"></td>
        <td style="vertical-align:top;" role="gridcell">
            <span title="Login into MOLPOWER to see the Container details.">--</span>
        </td>
        <td style="vertical-align:top;" role="gridcell">BELLAVIA/BLV</td>
        <td style="vertical-align:top;" role="gridcell">0034E</td>
        <td style="vertical-align:top;" role="gridcell">HSX</td>
        <td style="vertical-align:top;" role="gridcell">In-Gate Export At Final Facility at LP</td>
    </tr>
    <tr class="k-alt" data-uid="e5b3a2a2-4ead-4480-a088-5d0bc5c2bfa6" role="row">
        <td style="vertical-align:top;" role="gridcell">20-JUN-2017 07:15</td>
        <td style="vertical-align:top;" role="gridcell">AHMEDABAD - ICD AHMEDABAD/ ICD KHODIYAR</td>
        <td style="vertical-align:top;" role="gridcell">PIPAVAV-APM TERMINALS</td>
        <td style="vertical-align:top;" role="gridcell">
            <span title="Login into MOLPOWER to see the Container details.">--</span>
        </td>
        <td style="vertical-align:top;" role="gridcell">BELLAVIA/BLV</td>
        <td style="vertical-align:top;" role="gridcell">0034E</td>
        <td style="vertical-align:top;" role="gridcell">HSX</td>
        <td style="vertical-align:top;" role="gridcell">Transit Export</td>
    </tr>
    <tr data-uid="c4d7f433-3cb2-4a2f-b0e8-19eae9545cd3" role="row">
        <td style="vertical-align:top;" role="gridcell">16-JUN-2017 21:16</td>
        <td style="vertical-align:top;" role="gridcell">AHMEDABAD - ICD AHMEDABAD/ ICD KHODIYAR</td>
        <td style="vertical-align:top;" role="gridcell"></td>
        <td style="vertical-align:top;" role="gridcell">
            <span title="Login into MOLPOWER to see the Container details.">--</span>
        </td>
        <td style="vertical-align:top;" role="gridcell">BELLAVIA/BLV</td>
        <td style="vertical-align:top;" role="gridcell">0034E</td>
        <td style="vertical-align:top;" role="gridcell">HSX</td>
        <td style="vertical-align:top;" role="gridcell">Received Export</td>
    </tr>
    <tr class="k-alt" data-uid="a8593a5d-4bd6-4714-80c8-04e55a3140a9" role="row">
        <td style="vertical-align:top;" role="gridcell">15-JUN-2017 17:00</td>
        <td style="vertical-align:top;" role="gridcell">AHMADABAD - QUEST CONTAINER DEPO</td>
        <td style="vertical-align:top;" role="gridcell">AHMADABAD - QUEST CONTAINER DEPO</td>
        <td style="vertical-align:top;" role="gridcell">
            <span title="Login into MOLPOWER to see the Container details.">--</span>
        </td>
        <td style="vertical-align:top;" role="gridcell">BELLAVIA/BLV</td>
        <td style="vertical-align:top;" role="gridcell">0034E</td>
        <td style="vertical-align:top;" role="gridcell">HSX</td>
        <td style="vertical-align:top;" role="gridcell">Dispatched Export To Shipper</td>
    </tr>
    <tr data-uid="cbdc7f97-5e8d-48c9-900b-8031ee6a6fe5" role="row">
        <td style="vertical-align:top;" role="gridcell">03-JUN-2017 11:00</td>
        <td style="vertical-align:top;" role="gridcell">AHMADABAD - QUEST CONTAINER DEPO</td>
        <td style="vertical-align:top;" role="gridcell"></td>
        <td style="vertical-align:top;" role="gridcell">
            <span title="Login into MOLPOWER to see the Container details.">--</span>
        </td>
        <td style="vertical-align:top;" role="gridcell"></td>
        <td style="vertical-align:top;" role="gridcell"></td>
        <td style="vertical-align:top;" role="gridcell"></td>
        <td style="vertical-align:top;" role="gridcell">In Empty And Available</td>
    </tr>
    <tr class="k-alt" data-uid="6c033a15-a900-47aa-8f26-642e012a97b0" role="row">
        <td style="vertical-align:top;" role="gridcell">03-JUN-2017 01:38</td>
        <td style="vertical-align:top;" role="gridcell">AHMEDABAD - ICD AHMEDABAD/ ICD KHODIYAR</td>
        <td style="vertical-align:top;" role="gridcell">AHMEDABAD - ICD AHMEDABAD/ ICD KHODIYAR</td>
        <td style="vertical-align:top;" role="gridcell">
            <span title="Login into MOLPOWER to see the Container details.">--</span>
        </td>
        <td style="vertical-align:top;" role="gridcell">WAN HAI 501/W501</td>
        <td style="vertical-align:top;" role="gridcell">0117W</td>
        <td style="vertical-align:top;" role="gridcell">HSX</td>
        <td style="vertical-align:top;" role="gridcell">Out-Gate Import To Consignee</td>
    </tr>
</tbody>
</code>```

Controller Sample:

```<code>foreach (var eachNode in driver.FindElements(By.XPath("//*[@id=\"gridEqpHistory\"]/table/tbody/tr")))
                {
                    var cells = eachNode.FindElements(By.TagName("td"));
                    cd = new ContainerDetail();

                    for (int i = 0; i < cells.Count(); i++)
                    {
                        cd.ContainerNo = containerNo;
                        cd.Location = cells[1].Text.Trim();
                        cd.ActionType = cells[7].Text.Trim();
                        string s = cells[0].Text;
                        DateTime dt = Convert.ToDateTime(s);
                        if (_minDate > dt) _minDate = dt;
                        cd.ActionDate = dt;
                        cd.Vessel = cells[4].Text.Split('/').First().Trim();
                        cd.Voyage = cells[5].Text.Trim();

                    }
</code>```

答:
If you want to get only first 8 tr elements with required data you can try to use below XPath expression

```<code>//tr[not(preceding-sibling::tr[td="Dispatched Export To Shipper"]) and not(th)]
</code>```

Body:
I wanted to loop through the table until Td text is "Dispatched Export To Shipper". I don't want it to check for below nodes.Only first 8 rows. But the condition should be td text. Any ideas?

Table Sample:

<colgroup>
    <col style="width:115px">
    <col>
    <col>
    <col>
    <col>
    <col style="width:70px">
    <col style="width:50px">
    <col>
</colgroup>

            Date

            Location

            To Location

            BL/BKG

            Vessel

            Voy

            Line

            Description

        28-JUN-2017 09:30
        COLOMBO - SOUTH ASIA GATEWAY TERMINAL

            --

        BELLAVIA/BLV
        0034E
        HSX
        Landed Transshipment

        28-JUN-2017 08:42
        COLOMBO - SOUTH ASIA GATEWAY TERMINAL

            --

        BELLAVIA/BLV
        0034E
        HSX
        Vessel arrived at port

        25-JUN-2017 18:18
        PIPAVAV-APM TERMINALS
        COLOMBO - SOUTH ASIA GATEWAY TERMINAL

            --

        BELLAVIA/BLV
        0034E
        HSX
        Vessel depart from the port

        25-JUN-2017 13:57
        PIPAVAV-APM TERMINALS
        COLOMBO - SOUTH ASIA GATEWAY TERMINAL

            --

        BELLAVIA/BLV
        0034E
        HSX
        Loaded on Vessel

        20-JUN-2017 20:27
        PIPAVAV-APM TERMINALS

            --

        BELLAVIA/BLV
        0034E
        HSX
        In-Gate Export At Final Facility at LP

        20-JUN-2017 07:15
        AHMEDABAD - ICD AHMEDABAD/ ICD KHODIYAR
        PIPAVAV-APM TERMINALS

            --

        BELLAVIA/BLV
        0034E
        HSX
        Transit Export

        16-JUN-2017 21:16
        AHMEDABAD - ICD AHMEDABAD/ ICD KHODIYAR

            --

        BELLAVIA/BLV
        0034E
        HSX
        Received Export

        15-JUN-2017 17:00
        AHMADABAD - QUEST CONTAINER DEPO
        AHMADABAD - QUEST CONTAINER DEPO

            --

        BELLAVIA/BLV
        0034E
        HSX
        Dispatched Export To Shipper

        03-JUN-2017 11:00
        AHMADABAD - QUEST CONTAINER DEPO

            --

        In Empty And Available

        03-JUN-2017 01:38
        AHMEDABAD - ICD AHMEDABAD/ ICD KHODIYAR
        AHMEDABAD - ICD AHMEDABAD/ ICD KHODIYAR

            --

        WAN HAI 501/W501
        0117W
        HSX
        Out-Gate Import To Consignee

Controller Sample:

foreach (var eachNode in driver.FindElements(By.XPath("//*[@id=\"gridEqpHistory\"]/table/tbody/tr")))
                {
                    var cells = eachNode.FindElements(By.TagName("td"));
                    cd = new ContainerDetail();

                    for (int i = 0; i < cells.Count(); i++)
                    {
                        cd.ContainerNo = containerNo;
                        cd.Location = cells[1].Text.Trim();
                        cd.ActionType = cells[7].Text.Trim();
                        string s = cells[0].Text;
                        DateTime dt = Convert.ToDateTime(s);
                        if (_minDate > dt) _minDate = dt;
                        cd.ActionDate = dt;
                        cd.Vessel = cells[4].Text.Split('/').First().Trim();
                        cd.Voyage = cells[5].Text.Trim();

                    }

Body:
If you want to get only first 8 tr elements with required data you can try to use below XPath expression

//tr[not(preceding-sibling::tr[td="Dispatched Export To Shipper"]) and not(th)]


答:
Assuming your have an array of hashes and you want to search for 'P.O.' strings then you can do this:</p>

```<code>arr.select { |hash| hash["Value"][/P\.O\./] }.flat_map(&:values)
#=> ["P.O. BOX 60007 LOS ANGELES, CA 90060"]
</code>```

Title: Group values of keys in ruby hash in one hash and print specific value

Body:
This is my hash:

{"Specialty"=>"Other (note in description);Medical;Dental;Vision", "Value"=>"https://www.example.com/ca"}
{"Value"=>"P.O. BOX 60007 LOS ANGELES, CA 90060"}
{"Specialty"=>"Pharmacy;Medical", "Value"=>"800-824-0898"}
{"Specialty"=>"Urgent Care;Medical", "Value"=>"800-700-9186"}
{"Specialty"=>"Urgent Care;Emergency Care;Medical;Chiropractor;Acupuncture", "Value"=>"800-677-6669"}
{"Specialty"=>"Pharmacy;Medical", "Value"=>"https://www.example.com"}
{"Specialty"=>"Claims", "Value"=>"https://www.example.com/consumer/claims/claimsoverview"}
{"Specialty"=>"Urgent Care;Emergency Care;Medical;Chiropractor;Acupuncture", "Value"=>"https://example/example/apps/services/www/ABCBS/mobilewebapp/default/index.html#/providers/search"}
{""Specialty"=>"Claims;Customer Service;Medical", "Value"=>"800-888-8288"}

You can see from this that the key value has differed values in each hash table, and I would like to print only one specific value, that is P.O. BOX 60007 LOS ANGELES, CA 90060

I tried printing the values of the hash by hash["value"] and it prints all the contents of the values. I tried loading them into an array[] by using to_s function to print the value I want, but one array is loaded with all these values or I may be loading the array wrong.

array = []
array = medical.split("\n")
text = array.to_s
text1 = array.index{|s| s.include?("P.O.")}
puts text1

Can someone help me with how do I print that specific hash value inspite of various values existing in the key named value

Body:
Assuming your have an array of hashes and you want to search for 'P.O.' strings then you can do this:

arr.select { |hash| hash["Value"][/P\.O\./] }.flat_map(&:values)
#=> ["P.O. BOX 60007 LOS ANGELES, CA 90060"]


问:
NavigableMap throwing unwanted exception
From java docs of NavigableMap :firstKey() of Navigable map

Returns a key-value mapping associated with the least key in this map, or null if the map is empty.

However, when i run the following program i am getting NoSuchElementException

```<code> public class Test1 {
        public static void main(String a[]) {
            NavigableMap<Object, Object> map = new TreeMap<>();
            Object obj = map.firstKey();
        }
    }
</code>```

I am not sure if i am missing something here, Please let me know why it is behaving like this?

答:
As pointed out by @Gilad Green, the firstKey API is behaving as per documentation.

But I think you are probably looking for below method -

```<code>firstEntry()
Returns a key-value mapping associated with the least key in this map, or null if the map is empty.
</code>```

This will give you Map.Entry object. And in your case it would return null as the map does not have any entry yet.

Body:
From java docs of NavigableMap :firstKey() of Navigable map

Returns a key-value mapping associated with the least key in this map, or null if the map is empty.

However, when i run the following program i am getting NoSuchElementException

 public class Test1 {
        public static void main(String a[]) {
            NavigableMap<Object, Object> map = new TreeMap<>();
            Object obj = map.firstKey();
        }
    }

I am not sure if i am missing something here, Please let me know why it is behaving like this?

Body:
As pointed out by @Gilad Green, the firstKey API is behaving as per documentation.

But I think you are probably looking for below method -

firstEntry()
Returns a key-value mapping associated with the least key in this map, or null if the map is empty.

This will give you Map.Entry object. And in your case it would return null as the map does not have any entry yet.