问:
Geolocations with javascript
I'm working on a script to get the Geolocations (Lat, lon) that I can use to center my instance of google maps. For now i work with 2 possible technologies. One is the google.loader.ClientLocation object. I haven't tested this one yet because it returns null for me. I think because I'm not living on a regular location (Willemstad, Curacao using a wireless internet connection. So my modem is wireless.).

Therefore I made a backup plan using navigator.geolocation. This works great in Chrome, but firefox gives a timeout and it doesn't work at all in IE.

Does anyone know a good alternative method to get the users geolocation, or does anyone have recommendation on my code how it can become more stable.

I set a timeout for navigator.geolocation because I don't want my users to wait for more as 5 seconds. Increasing the timeout does not improve the reliability of firefox.

```<code>function init_tracker_map() {
 var latitude;
 var longitude;

 if(google.loader.ClientLocation) {
  latitude = (google.loader.ClientLocation.latitude);
  longitude = (google.loader.ClientLocation.longitude);
  buildMap(latitude, longitude);
 }
 else if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(
   function(position) {
    latitude = (position.coords.latitude);
    longitude = (position.coords.longitude);
    buildMap(latitude, longitude);
   },
   function errorCallback(error) {
    useDefaultLatLon();
   },
   {
    enableHighAccuracy:false,
    maximumAge:Infinity,
    timeout:5000
   }
  );
 }
 else {
  useDefaultLatLon();
 }
}

function useDefaultLatLon() {
 latitude = (51.81540697949437);
 longitude = (5.72113037109375);
 buildMap(latitude, longitude);
}
</code>```

ps. I'm aware there are more questions like this on SO but couldn't find a clear answer. I'm hoping that people made some new discovery's.

Update:
Tried google gears aswell. Succesfull in chrome again. Fails in FF and IE.

```<code>var geo = google.gears.factory.create('beta.geolocation');
if(geo) {
  function updatePosition(position) {
    alert('Current lat/lon is: ' + position.latitude + ',' + position.longitude);
  }

  function handleError(positionError) {
    alert('Attempt to get location failed: ' + positionError.message);
  }
  geo.getCurrentPosition(updatePosition, handleError);
}
</code>```

Update 2: navigator.geolocation works fine in FF from my work location.

Final Result

This works great. Get an api key from ipinfodb.org

```<code>var Geolocation = new geolocate(false, true);
Geolocation.checkcookie(function() {
    alert('Visitor latitude code : ' + Geolocation.getField('Latitude'));
    alert('Visitor Longitude code : ' + Geolocation.getField('Longitude'));
});

function geolocate(timezone, cityPrecision) {
    alert("Using IPInfoDB");
    var key = 'your api code';
    var api = (cityPrecision) ? "ip_query.php" : "ip_query_country.php";
    var domain = 'api.ipinfodb.com';
    var version = 'v2';
    var url = "http://" + domain + "/" + version + "/" + api + "?key=" + key + "&output=json" + ((timezone) ? "&timezone=true" : "&timezone=false" ) + "&callback=?";
    var geodata;
    var JSON = JSON || {};
    var callback =  function() {
        alert("lol");
    }

    // implement JSON.stringify serialization
    JSON.stringify = JSON.stringify || function (obj) {
        var t = typeof (obj);
        if (t != "object" || obj === null) {
            // simple data type
            if (t == "string") obj = '"'+obj+'"';
            return String(obj);
        }
        else {
            // recurse array or object
            var n, v, json = [], arr = (obj && obj.constructor == Array);
            for (n in obj) {
                v = obj[n]; t = typeof(v);
                if (t == "string") v = '"'+v+'"';
                else if (t == "object" && v !== null) v = JSON.stringify(v);
                json.push((arr ? "" : '"' + n + '":') + String(v));
            }
            return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
        }
    };

    // implement JSON.parse de-serialization
    JSON.parse = JSON.parse || function (str) {
        if (str === "") str = '""';
        eval("var p=" + str + ";");
        return p;
    };

    // Check if cookie already exist. If not, query IPInfoDB
    this.checkcookie = function(callback) {
        geolocationCookie = getCookie('geolocation');
        if (!geolocationCookie) {
            getGeolocation(callback);
        }
        else {
            geodata = JSON.parse(geolocationCookie);
            callback();
        }
    }

    // Return a geolocation field
    this.getField = function(field) {
        try {
            return geodata[field];
        } catch(err) {}
    }

    // Request to IPInfoDB
    function getGeolocation(callback) {
        try {
            $.getJSON(url,
                    function(data){
                if (data['Status'] == 'OK') {
                    geodata = data;
                    JSONString = JSON.stringify(geodata);
                    setCookie('geolocation', JSONString, 365);
                    callback();
                }
            });
        } catch(err) {}
    }

    // Set the cookie
    function setCookie(c_name, value, expire) {
        var exdate=new Date();
        exdate.setDate(exdate.getDate()+expire);
        document.cookie = c_name+ "=" +escape(value) + ((expire==null) ? "" : ";expires="+exdate.toGMTString());
    }

    // Get the cookie content
    function getCookie(c_name) {
        if (document.cookie.length > 0 ) {
            c_start=document.cookie.indexOf(c_name + "=");
            if (c_start != -1){
                c_start=c_start + c_name.length+1;
                c_end=document.cookie.indexOf(";",c_start);
                if (c_end == -1) {
                    c_end=document.cookie.length;
                }
                return unescape(document.cookie.substring(c_start,c_end));
            }
        }
        return '';
    }
}
</code>```

答:
I had a similar problem and, for browsers without geolocation, went with server-side location based on the user's IP.

Two free geolocation services are:

http://www.maxmind.com/app/geolitecity

http://www.hostip.info/

I found maxmind to me much more accurate.

If it's possible within your project you could query the location before rendering the page, or perform an ajax call to query the location.

ContentLicense: CC BY-SA 2.5

Title: Geolocations with javascript

Body:
I'm working on a script to get the Geolocations (Lat, lon) that I can use to center my instance of google maps. For now i work with 2 possible technologies. One is the google.loader.ClientLocation object. I haven't tested this one yet because it returns null for me. I think because I'm not living on a regular location (Willemstad, Curacao using a wireless internet connection. So my modem is wireless.).

Therefore I made a backup plan using navigator.geolocation. This works great in Chrome, but firefox gives a timeout and it doesn't work at all in IE.

Does anyone know a good alternative method to get the users geolocation, or does anyone have recommendation on my code how it can become more stable.

I set a timeout for navigator.geolocation because I don't want my users to wait for more as 5 seconds. Increasing the timeout does not improve the reliability of firefox.

function init_tracker_map() {
 var latitude;
 var longitude;

 if(google.loader.ClientLocation) {
  latitude = (google.loader.ClientLocation.latitude);
  longitude = (google.loader.ClientLocation.longitude);
  buildMap(latitude, longitude);
 }
 else if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(
   function(position) {
    latitude = (position.coords.latitude);
    longitude = (position.coords.longitude);
    buildMap(latitude, longitude);
   },
   function errorCallback(error) {
    useDefaultLatLon();
   },
   {
    enableHighAccuracy:false,
    maximumAge:Infinity,
    timeout:5000
   }
  );
 }
 else {
  useDefaultLatLon();
 }
}

function useDefaultLatLon() {
 latitude = (51.81540697949437);
 longitude = (5.72113037109375);
 buildMap(latitude, longitude);
}

ps. I'm aware there are more questions like this on SO but couldn't find a clear answer. I'm hoping that people made some new discovery's.

Update:
Tried google gears aswell. Succesfull in chrome again. Fails in FF and IE.

var geo = google.gears.factory.create('beta.geolocation');
if(geo) {
  function updatePosition(position) {
    alert('Current lat/lon is: ' + position.latitude + ',' + position.longitude);
  }

  function handleError(positionError) {
    alert('Attempt to get location failed: ' + positionError.message);
  }
  geo.getCurrentPosition(updatePosition, handleError);
}

Update 2: navigator.geolocation works fine in FF from my work location.

Final Result

This works great. Get an api key from ipinfodb.org

var Geolocation = new geolocate(false, true);
Geolocation.checkcookie(function() {
    alert('Visitor latitude code : ' + Geolocation.getField('Latitude'));
    alert('Visitor Longitude code : ' + Geolocation.getField('Longitude'));
});

function geolocate(timezone, cityPrecision) {
    alert("Using IPInfoDB");
    var key = 'your api code';
    var api = (cityPrecision) ? "ip_query.php" : "ip_query_country.php";
    var domain = 'api.ipinfodb.com';
    var version = 'v2';
    var url = "http://" + domain + "/" + version + "/" + api + "?key=" + key + "&output=json" + ((timezone) ? "&timezone=true" : "&timezone=false" ) + "&callback=?";
    var geodata;
    var JSON = JSON || {};
    var callback =  function() {
        alert("lol");
    }

    // implement JSON.stringify serialization
    JSON.stringify = JSON.stringify || function (obj) {
        var t = typeof (obj);
        if (t != "object" || obj === null) {
            // simple data type
            if (t == "string") obj = '"'+obj+'"';
            return String(obj);
        }
        else {
            // recurse array or object
            var n, v, json = [], arr = (obj && obj.constructor == Array);
            for (n in obj) {
                v = obj[n]; t = typeof(v);
                if (t == "string") v = '"'+v+'"';
                else if (t == "object" && v !== null) v = JSON.stringify(v);
                json.push((arr ? "" : '"' + n + '":') + String(v));
            }
            return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
        }
    };

    // implement JSON.parse de-serialization
    JSON.parse = JSON.parse || function (str) {
        if (str === "") str = '""';
        eval("var p=" + str + ";");
        return p;
    };

    // Check if cookie already exist. If not, query IPInfoDB
    this.checkcookie = function(callback) {
        geolocationCookie = getCookie('geolocation');
        if (!geolocationCookie) {
            getGeolocation(callback);
        }
        else {
            geodata = JSON.parse(geolocationCookie);
            callback();
        }
    }

    // Return a geolocation field
    this.getField = function(field) {
        try {
            return geodata[field];
        } catch(err) {}
    }

    // Request to IPInfoDB
    function getGeolocation(callback) {
        try {
            $.getJSON(url,
                    function(data){
                if (data['Status'] == 'OK') {
                    geodata = data;
                    JSONString = JSON.stringify(geodata);
                    setCookie('geolocation', JSONString, 365);
                    callback();
                }
            });
        } catch(err) {}
    }

    // Set the cookie
    function setCookie(c_name, value, expire) {
        var exdate=new Date();
        exdate.setDate(exdate.getDate()+expire);
        document.cookie = c_name+ "=" +escape(value) + ((expire==null) ? "" : ";expires="+exdate.toGMTString());
    }

    // Get the cookie content
    function getCookie(c_name) {
        if (document.cookie.length > 0 ) {
            c_start=document.cookie.indexOf(c_name + "=");
            if (c_start != -1){
                c_start=c_start + c_name.length+1;
                c_end=document.cookie.indexOf(";",c_start);
                if (c_end == -1) {
                    c_end=document.cookie.length;
                }
                return unescape(document.cookie.substring(c_start,c_end));
            }
        }
        return '';
    }
}


来源: stackexchange

问:
Dynamically add element to DOM in angular
This is how my page looks like on initial load

```<code><body>
 <div class="col-md-12" id="dataPanes">
   <div class="row dataPane"> Chunk of html elements </div>
 </div>

 <div class"col-md-12 text-right">
   <input type="button" class="btn btn-primary" value="Add dynamic row" ng-click="addElementChunk()" />
</body>
</code>```

I am in need to add rows to div#dataPanes on button click

If I was using jQuery,addElementChunk() function would have looked as below

```<code>var addElementChunk = function()
{
   var html = "<div class='row dataPane'> Chunk of html elements </div>";
   $("#dataPanes").append(html);
}
</code>```

but how do I implement the same in angular??

答:
You need to use $compile

Compiles an HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together.

and $sce

Strict Contextual Escaping (SCE) is a mode in which AngularJS constrains bindings to only render trusted values. Its goal is to assist in writing code in a way that (a) is secure by default, and (b) makes auditing for security vulnerabilities such as XSS, clickjacking, etc. a lot easier.

```<code>addElementChunk = function(){
    var html = '<div class="row dataPane"> Chunk of html elements </div>';
    var trustedHtml = $sce.trustAsHtml(html);
    var compiledHtml = $compile(trustedHtml)($scope);
    angular.element(document.getElementById('dataPanes')).append(compiledHtml);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This is how my page looks like on initial load

 Chunk of html elements

   <input type="button" class="btn btn-primary" value="Add dynamic row" ng-click="addElementChunk()" />

I am in need to add rows to div#dataPanes on button click

If I was using jQuery,addElementChunk() function would have looked as below

var addElementChunk = function()
{
   var html = "
 Chunk of html elements
";
   $("#dataPanes").append(html);
}

but how do I implement the same in angular??

Body:
You need to use $compile

Compiles an HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together.

and $sce

Strict Contextual Escaping (SCE) is a mode in which AngularJS constrains bindings to only render trusted values. Its goal is to assist in writing code in a way that (a) is secure by default, and (b) makes auditing for security vulnerabilities such as XSS, clickjacking, etc. a lot easier.

addElementChunk = function(){
    var html = '<div class="row dataPane"> Chunk of html elements </div>';
    var trustedHtml = $sce.trustAsHtml(html);
    var compiledHtml = $compile(trustedHtml)($scope);
    angular.element(document.getElementById('dataPanes')).append(compiledHtml);
}


问:
SonarQube 5.6 LDAP (FreeIPA) authenticated users have no groups
I saw some posts on stackoverflow, like this one and this, but problem still exists. I updated sonarqube from 5.3 to 5.6. Here's example of my config:

```<code>sonar.security.realm=LDAP
sonar.security.savePassword=false
sonar.security.localUsers=admin
ldap.authentication=simple
ldap.url=ldap://ipa.company.com
ldap.bindDn=uid=ldap_search,cn=users,cn=accounts,dc=company,dc=com
ldap.bindPassword=*************

ldap.user.baseDn=cn=users,cn=accounts,dc=company,dc=com
ldap.user.request=(&(objectClass=inetOrgPerson)(uid={login}))
ldap.user.realNameAttribute=cn
ldap.user.emailAttribute=mail

ldap.group.baseDn=cn=groups,cn=accounts,dc=company,dc=com
ldap.group.request=(&(objectClass=posixGroup)(memberUid={uid}))
ldap.group.idAttribute=cn
</code>```

The problem is in authentication. If i create local user, then i can't authenticate using same LDAP (FreeIPA) account, according to this docs (Local users block). If i authenticate first time with FreeIPA account i see newly created sonar user, but it has no groups (sonar-users for example, but he is actually a member of sonar-users in FreeIPA groups)

Here's example of test account in sonarqube - http://joxi.ru/zAN46EXcb9gem9, and test account in FreeIPA - http://joxi.ru/VrwnzgDcBeGxAX.
Even, when i login with admin and add groups to test user, they disappear after next login.

Here's example from mysql sonar.users db:

```<code>| id | login                    | updated_at    | external_identity        | external_identity_provider | user_local |
| 32 | test                     | 1494580874688 | test                     | sonarqube                  |          0 |
</code>```

Please help me to find a solution.

答:
After a couple of weeks i finally found right solution! I realized that problem was in group synchronization, so right config for group sync must looks like next one for your FreeIPA configuration:

```<code>ldap.group.baseDn=cn=groups,cn=compat,dc=company,dc=com
ldap.group.request=(&(objectClass=posixGroup)(memberUid={uid}))
ldap.group.idAttribute=cn
</code>```

Difference is in cn=groups,cn=compat,dc=company,dc=com.
You can't use memberUid filter with cn=accounts.

Body:
I saw some posts on stackoverflow, like this one and this, but problem still exists. I updated sonarqube from 5.3 to 5.6. Here's example of my config:

sonar.security.realm=LDAP
sonar.security.savePassword=false
sonar.security.localUsers=admin
ldap.authentication=simple
ldap.url=ldap://ipa.company.com
ldap.bindDn=uid=ldap_search,cn=users,cn=accounts,dc=company,dc=com
ldap.bindPassword=*************

ldap.user.baseDn=cn=users,cn=accounts,dc=company,dc=com
ldap.user.request=(&(objectClass=inetOrgPerson)(uid={login}))
ldap.user.realNameAttribute=cn
ldap.user.emailAttribute=mail

ldap.group.baseDn=cn=groups,cn=accounts,dc=company,dc=com
ldap.group.request=(&(objectClass=posixGroup)(memberUid={uid}))
ldap.group.idAttribute=cn

The problem is in authentication. If i create local user, then i can't authenticate using same LDAP (FreeIPA) account, according to this docs (Local users block). If i authenticate first time with FreeIPA account i see newly created sonar user, but it has no groups (sonar-users for example, but he is actually a member of sonar-users in FreeIPA groups)

Here's example of test account in sonarqube - http://joxi.ru/zAN46EXcb9gem9, and test account in FreeIPA - http://joxi.ru/VrwnzgDcBeGxAX.
Even, when i login with admin and add groups to test user, they disappear after next login.

Here's example from mysql sonar.users db:

| id | login                    | updated_at    | external_identity        | external_identity_provider | user_local |
| 32 | test                     | 1494580874688 | test                     | sonarqube                  |          0 |

Please help me to find a solution.

Body:
After a couple of weeks i finally found right solution! I realized that problem was in group synchronization, so right config for group sync must looks like next one for your FreeIPA configuration:

ldap.group.baseDn=cn=groups,cn=compat,dc=company,dc=com
ldap.group.request=(&(objectClass=posixGroup)(memberUid={uid}))
ldap.group.idAttribute=cn

Difference is in cn=groups,cn=compat,dc=company,dc=com.
You can't use memberUid filter with cn=accounts.


问:
How to prevent Soft Keyboard hiding button in custom dialog?
I have a custom dialog like following

When soft keyboard comes it hides the Button like below.

my code

https://mcaf.ee/9qhnef

How to avoid Submit button being hide?  i have added autoresize and auto pan but no luck so far.

答:
Update your Linked Xml with below xml its working, i have tested.

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#1260C5"
    android:orientation="vertical">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:alpha=".85">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:alpha=".5"
                android:gravity="center"
                android:orientation="vertical">

                <ImageButton
                    android:id="@+id/imgNotificationClose"
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:background="#00000000"
                    android:scaleType="fitCenter"
                    android:src="@mipmap/ic_launcher" />

                <TextView
                    android:id="@+id/txtNotification"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:text="CHANGE PASSWORD"
                    android:textAppearance="@style/TextAppearance.AppCompat.Large"
                    android:textSize="36sp"
                    android:visibility="gone" />

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="5dp"
                android:gravity="top"
                android:orientation="vertical">

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"

                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="20dp"
                    android:gravity="left|center"
                    android:text="Email"
                    android:textStyle="bold" />

                <EditText
                    android:id="@+id/old_email"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="15dp"
                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="20dp"
                    android:background="#FFFFFF"
                    android:focusable="false"
                    android:padding="10dip"
                    android:paddingLeft="30dp"
                    android:paddingRight="30dp"
                    android:textColor="#000000"
                    android:textSize="14sp" />

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"

                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="20dp"
                    android:gravity="left|center"
                    android:text="Old Password"
                    android:textStyle="bold" />

                <EditText
                    android:id="@+id/password_change_edit_password_current_pass"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="15dp"
                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="20dp"
                    android:background="#FFFFFF"
                    android:inputType="textPassword"
                    android:padding="10dip"
                    android:paddingLeft="30dp"
                    android:paddingRight="30dp"
                    android:textColor="#000000"
                    android:textSize="14sp" />

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"

                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="20dp"
                    android:gravity="left|center"
                    android:text="New Password"
                    android:textStyle="bold" />

                <EditText
                    android:id="@+id/password_change_edit_password_new_pass"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="15dp"
                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="20dp"
                    android:background="#FFFFFF"
                    android:ems="10"
                    android:inputType="textPassword"

                    android:padding="10dip"
                    android:paddingLeft="30dp"
                    android:paddingRight="30dp"
                    android:textColor="#000000"
                    android:textSize="14sp" />

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"

                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="20dp"
                    android:gravity="left|center"
                    android:text="Confirm New Password"
                    android:textSize="14sp"
                    android:textStyle="bold" />

                <EditText
                    android:id="@+id/password_change_edit_password_confirm_pass"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="15dp"
                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="20dp"
                    android:background="#FFFFFF"
                    android:ems="10"
                    android:inputType="textPassword"

                    android:padding="10dip"
                    android:paddingLeft="30dp"
                    android:paddingRight="30dp"
                    android:textColor="#000000"
                    android:textSize="14sp" />

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal"
                    android:layout_marginTop="10dp"
                    android:orientation="horizontal">

                    <ImageView
                        android:id="@+id/img_alert"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:src="@mipmap/ic_launcher"
                        android:visibility="invisible" />

                    <TextView
                        android:id="@+id/password_change_validation_status"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center"
                        android:gravity="center"
                        android:text=""
                        android:textColor="#BEB2D1"
                        android:textSize="14sp"
                        android:textStyle="bold" />

                </LinearLayout>

            </LinearLayout>

        </LinearLayout>
    </ScrollView>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0">

        <Button
            android:id="@+id/password_change_btn_password_submit"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="15dp"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:layout_marginTop="20dp"
            android:paddingLeft="30dp"
            android:paddingRight="30dp"
            android:text="Submit"
            android:textColor="#FFFFFF"
            android:textSize="18sp" />

    </RelativeLayout>

</LinearLayout>
</code>```

Body:
Update your Linked Xml with below xml its working, i have tested.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#1260C5"
    android:orientation="vertical">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:alpha=".85">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:alpha=".5"
                android:gravity="center"
                android:orientation="vertical">

                <ImageButton
                    android:id="@+id/imgNotificationClose"
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:background="#00000000"
                    android:scaleType="fitCenter"
                    android:src="@mipmap/ic_launcher" />

                <TextView
                    android:id="@+id/txtNotification"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:text="CHANGE PASSWORD"
                    android:textAppearance="@style/TextAppearance.AppCompat.Large"
                    android:textSize="36sp"
                    android:visibility="gone" />

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="5dp"
                android:gravity="top"
                android:orientation="vertical">

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"

                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="20dp"
                    android:gravity="left|center"
                    android:text="Email"
                    android:textStyle="bold" />

                <EditText
                    android:id="@+id/old_email"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="15dp"
                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="20dp"
                    android:background="#FFFFFF"
                    android:focusable="false"
                    android:padding="10dip"
                    android:paddingLeft="30dp"
                    android:paddingRight="30dp"
                    android:textColor="#000000"
                    android:textSize="14sp" />

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"

                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="20dp"
                    android:gravity="left|center"
                    android:text="Old Password"
                    android:textStyle="bold" />

                <EditText
                    android:id="@+id/password_change_edit_password_current_pass"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="15dp"
                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="20dp"
                    android:background="#FFFFFF"
                    android:inputType="textPassword"
                    android:padding="10dip"
                    android:paddingLeft="30dp"
                    android:paddingRight="30dp"
                    android:textColor="#000000"
                    android:textSize="14sp" />

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"

                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="20dp"
                    android:gravity="left|center"
                    android:text="New Password"
                    android:textStyle="bold" />

                <EditText
                    android:id="@+id/password_change_edit_password_new_pass"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="15dp"
                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="20dp"
                    android:background="#FFFFFF"
                    android:ems="10"
                    android:inputType="textPassword"

                    android:padding="10dip"
                    android:paddingLeft="30dp"
                    android:paddingRight="30dp"
                    android:textColor="#000000"
                    android:textSize="14sp" />

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"

                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="20dp"
                    android:gravity="left|center"
                    android:text="Confirm New Password"
                    android:textSize="14sp"
                    android:textStyle="bold" />

                <EditText
                    android:id="@+id/password_change_edit_password_confirm_pass"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="15dp"
                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="20dp"
                    android:background="#FFFFFF"
                    android:ems="10"
                    android:inputType="textPassword"

                    android:padding="10dip"
                    android:paddingLeft="30dp"
                    android:paddingRight="30dp"
                    android:textColor="#000000"
                    android:textSize="14sp" />

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal"
                    android:layout_marginTop="10dp"
                    android:orientation="horizontal">

                    <ImageView
                        android:id="@+id/img_alert"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:src="@mipmap/ic_launcher"
                        android:visibility="invisible" />

                    <TextView
                        android:id="@+id/password_change_validation_status"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center"
                        android:gravity="center"
                        android:text=""
                        android:textColor="#BEB2D1"
                        android:textSize="14sp"
                        android:textStyle="bold" />

                </LinearLayout>

            </LinearLayout>

        </LinearLayout>
    </ScrollView>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0">

        <Button
            android:id="@+id/password_change_btn_password_submit"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="15dp"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:layout_marginTop="20dp"
            android:paddingLeft="30dp"
            android:paddingRight="30dp"
            android:text="Submit"
            android:textColor="#FFFFFF"
            android:textSize="18sp" />

    </RelativeLayout>

</LinearLayout>


答:
```<code>;WITH Preprocessed AS (
    SELECT STORE_ID, INDEX_ID, START_DATE, END_DATE,
        NEXT_START_DATE = FIRST_VALUE(START_DATE) OVER (PARTITION BY STORE_ID, INDEX_ID ORDER BY START_DATE ROWS BETWEEN 1 FOLLOWING AND 1 FOLLOWING),
        MAX_END_DATE    = MAX(END_DATE) OVER(PARTITION BY STORE_ID, INDEX_ID ORDER BY START_DATE ROWS UNBOUNDED PRECEDING)
    FROM @t
)
SELECT
    STORE_ID, INDEX_ID, START_DATE,
    END_DATE_NEW = IIF(NEXT_START_DATE IS NOT NULL AND NEXT_START_DATE < END_DATE, DATEADD(SECOND, -1, NEXT_START_DATE), END_DATE)
FROM Preprocessed

UNION ALL

SELECT STORE_ID, INDEX_ID,
    START_DATE  = DATEADD(SECOND, 1, END_DATE),
    END_DATE    = IIF(NEXT_START_DATE < MAX_END_DATE, DATEADD(SECOND, -1, NEXT_START_DATE), MAX_END_DATE)
FROM Preprocessed
WHERE (NEXT_START_DATE IS NULL OR NEXT_START_DATE > DATEADD(SECOND, 1, END_DATE))   -- End of the range
    AND (END_DATE < MAX_END_DATE)                                                   -- Check if need to add new record after range
ORDER BY 1, 2, 3
</code>```

Title: Divide rows by date and by group SQL

Body:
I have a problem with SQL. I found similar one TOPIC, but not exactly the same. I would like to separate the dates which overlaps. For example I have in the first row START_DATE 2014-08-06 and END_DATE 2014-10-06. We can see that the dates from the second and the third row are inside this period of time from first row but I have to do it separately on STORE_ID and INDEX_ID. The price should be taken from inner period. I can't modify this code. Can you help me?

My table looks like this:

declare @t table  (STORE_ID INT,
                  INDEX_ID INT,
                  START_DATE datetime,
                  END_DATE datetime,
                  GROSS_SALES_PRICE decimal(10,2)
             );

 insert into @t
 values (1,20,'2014-08-06 00:00:00.000', '2014-10-06 23:59:59.000', 29.99),
 (1,20,'2014-09-06 00:00:00.000', '2014-09-09 23:59:59.000', 32.99),
 (1,20,'2014-09-10 00:00:00.000', '2014-09-30 23:59:59.000', 32.99),
 (1,20,'2014-10-07 00:00:00.000', '2049-12-31 23:59:59.000', 34.99),
 (1,22,'2014-08-06 00:00:00.000', '2014-10-06 23:59:59.000', 29.99),
 (1,22,'2014-09-06 00:00:00.000', '2014-09-09 23:59:59.000', 32.99),
 (1,22,'2014-09-10 00:00:00.000', '2014-09-30 23:59:59.000', 32.99),
 (1,22,'2014-10-07 00:00:00.000', '2049-12-31 23:59:59.000', 34.99),
 (2,20,'2014-08-06 00:00:00.000', '2014-10-06 23:59:59.000', 29.99),
 (2,20,'2014-09-06 00:00:00.000', '2014-09-09 23:59:59.000', 32.99),
 (2,20,'2014-09-10 00:00:00.000', '2014-09-30 23:59:59.000', 32.99),
 (2,20,'2014-10-07 00:00:00.000', '2049-12-31 23:59:59.000', 34.99)

And the desired output:

  declare @t2 table (STORE_ID INT,
                    INDEX_ID INT,
                    START_DATE datetime,
                    END_DATE datetime,
                    GROSS_SALES_PRICE decimal(10,2)
                   );

 insert into @t2
 values (1,20,'2014-08-06 00:00:00.000', '2014-09-05 23:59:59.000', 29.99),
   (1,20,'2014-09-06 00:00:00.000', '2014-09-09 23:59:59.000', 32.99),
   (1,20,'2014-09-10 00:00:00.000', '2014-09-30 23:59:59.000', 32.99),
   (1,20,'2014-10-01 00:00:00.000', '2014-10-06 23:59:59.000', 29.99),
   (1,20,'2014-10-07 00:00:00.000', '2049-12-31 23:59:59.000', 34.99),
   (1,22,'2014-08-06 00:00:00.000', '2014-09-05 23:59:59.000', 29.99),
   (1,22,'2014-09-06 00:00:00.000', '2014-09-09 23:59:59.000', 32.99),
   (1,22,'2014-09-10 00:00:00.000', '2014-09-30 23:59:59.000', 32.99),
   (1,22,'2014-10-01 00:00:00.000', '2014-10-06 23:59:59.000', 29.99),
   (1,22,'2014-10-07 00:00:00.000', '2049-12-31 23:59:59.000', 34.99),
   (2,20,'2014-08-06 00:00:00.000', '2014-09-05 23:59:59.000', 29.99),
   (2,20,'2014-09-06 00:00:00.000', '2014-09-09 23:59:59.000', 32.99),
   (2,20,'2014-09-10 00:00:00.000', '2014-09-30 23:59:59.000', 32.99),
   (2,20,'2014-10-01 00:00:00.000', '2014-10-06 23:59:59.000', 29.99),
   (2,20,'2014-10-07 00:00:00.000', '2049-12-31 23:59:59.000', 34.99)

So the code should work like in the topic I attached, but it should do it separately on every STORE_ID and INDEX_ID.


问:
Python and C++ modulus
I am learning c++ and in trying to code a little program i found something strange. It is about modulus :
c++ code

```<code>cout << -325 - (-325 % 100) << endl;
// -300
cout << 325 - (325 % 100);
// 300
</code>```

and python code

```<code>print(-325 - (-325 % 100))
# -400
print(325 - (325 % 100))
# 300
</code>```

Can someone explain me that pls ? Thq

答:
This is a bit out of my expertise but its likely python follows the Donald Knuth remainder calculation which is: a + b*[a/b] being [] the floor operation. As so:

```<code>a = -325
b = 100
print(a - b*math.floor(a/b))
print(math.floor(-3.25))
print(-325 -(a - b*math.floor(a/b)))
</code>```

results in:

```<code>75
-4
-400
</code>```

I'm a bit surprised C++ does not return the same (but I'm also not knowledgeable enough about the subject).

EDIT: Made a quick search for this topic and learncpp mentions the reason why C++, specifically C++ 11, standardized the floor operation always towards 0. I quote:

Prior to C++11, if either of the operands of integer division are
  negative, the compiler is free to round up or down! For example, -5 /
  2 can evaluate to either -3 or -2, depending on which way the compiler
  rounds. However, most modern compilers truncate towards 0 (so -5 / 2
  would equal -2). The C++11 specification changed this to explicitly
  define that integer division should always truncate towards 0 (or put
  more simply, the fractional component is dropped).

Also prior to C++11, if either operand of the modulus operator is
  negative, the results of the modulus can be either negative or
  positive! For example, -5 % 2 can evaluate to either 1 or -1. The
  C++11 specification tightens this up so that a % b always resolves to
  the sign of a.

Regarding Python you can take a look at the documentation for divmod which states:

Take two (non complex) numbers as arguments and return a pair of
  numbers consisting of their quotient and remainder when using integer
  division. With mixed operand types, the rules for binary arithmetic
  operators apply. For integers, the result is the same as (a // b, a %
  b). For floating point numbers the result is (q, a % b), where q is
  usually math.floor(a / b) but may be 1 less than that. In any case q *
  b + a % b is very close to a, if a % b is non-zero it has the same
  sign as b, and 0 <= abs(a % b) < abs(b)

EDIT2: Even more information on the Python Programming FAQ regarding this subject.

Why does -22 // 10 return -3?

It’s primarily driven by the desire that
  i % j have the same sign as j. If you want that, and also want:

i == (i // j) * j + (i % j)

then integer division has to return the
  floor. C also requires that identity to hold, and then compilers that
  truncate i // j need to make i % j have the same sign as i.

There are few real use cases for i % j when j is negative. When j is
  positive, there are many, and in virtually all of them it’s more
  useful for i % j to be >= 0. If the clock says 10 now, what did it say
  200 hours ago? -190 % 12 == 2 is useful; -190 % 12 == -10 is a bug
  waiting to bite.

Title: Python and C++ modulus

Body:
I am learning c++ and in trying to code a little program i found something strange. It is about modulus :
c++ code

cout << -325 - (-325 % 100) << endl;
// -300
cout << 325 - (325 % 100);
// 300

and python code

print(-325 - (-325 % 100))
# -400
print(325 - (325 % 100))
# 300

Can someone explain me that pls ? Thq

Body:
This is a bit out of my expertise but its likely python follows the Donald Knuth remainder calculation which is: a + b*[a/b] being [] the floor operation. As so:

a = -325
b = 100
print(a - b*math.floor(a/b))
print(math.floor(-3.25))
print(-325 -(a - b*math.floor(a/b)))

results in:

75
-4
-400

I'm a bit surprised C++ does not return the same (but I'm also not knowledgeable enough about the subject).

EDIT: Made a quick search for this topic and learncpp mentions the reason why C++, specifically C++ 11, standardized the floor operation always towards 0. I quote:

Prior to C++11, if either of the operands of integer division are
  negative, the compiler is free to round up or down! For example, -5 /
  2 can evaluate to either -3 or -2, depending on which way the compiler
  rounds. However, most modern compilers truncate towards 0 (so -5 / 2
  would equal -2). The C++11 specification changed this to explicitly
  define that integer division should always truncate towards 0 (or put
  more simply, the fractional component is dropped).

Also prior to C++11, if either operand of the modulus operator is
  negative, the results of the modulus can be either negative or
  positive! For example, -5 % 2 can evaluate to either 1 or -1. The
  C++11 specification tightens this up so that a % b always resolves to
  the sign of a.

Regarding Python you can take a look at the documentation for divmod which states:

Take two (non complex) numbers as arguments and return a pair of
  numbers consisting of their quotient and remainder when using integer
  division. With mixed operand types, the rules for binary arithmetic
  operators apply. For integers, the result is the same as (a // b, a %
  b). For floating point numbers the result is (q, a % b), where q is
  usually math.floor(a / b) but may be 1 less than that. In any case q *
  b + a % b is very close to a, if a % b is non-zero it has the same
  sign as b, and 0 <= abs(a % b) < abs(b)

EDIT2: Even more information on the Python Programming FAQ regarding this subject.

Why does -22 // 10 return -3?

It’s primarily driven by the desire that
  i % j have the same sign as j. If you want that, and also want:

i == (i // j) * j + (i % j)

then integer division has to return the
  floor. C also requires that identity to hold, and then compilers that
  truncate i // j need to make i % j have the same sign as i.

There are few real use cases for i % j when j is negative. When j is
  positive, there are many, and in virtually all of them it’s more
  useful for i % j to be >= 0. If the clock says 10 now, what did it say
  200 hours ago? -190 % 12 == 2 is useful; -190 % 12 == -10 is a bug
  waiting to bite.


问:
Randomize images on imageview with "if" function working strange
I'm trying to randomize images when a button is clicked and if the image is what I want it to be, randomize again, but if it's not, close the activity.

I cant randomize in my code, it closes always, but if I delete the call to the finish() function, it will randomize normally.

I just want that imageview to recognize the image without a sqlite DB

```<code>@Override
            public void onClick(View v) {
                int[] cards={R.drawable.bg,R.drawable.bg1};
                Random r = new Random();
                int n = r.nextInt(2);
                ImageView imgview1 = (ImageView) findViewById(R.id.imgv1);
                imgview1.setImageResource(cards[n]);

                if (imgview1.equals(R.drawable.bg){
                    imgview1.setImageResource(cards[n]);
                }
                else  {
                    finish();
                }
            }
</code>```

答:
You if-condition is always false because you are comparing an Object to an int which will never be true.

Unfortunately there is no ImageView#getDrawableId so you have to use a work around with Imageview#setTag e.g.

```<code>@Override
public void onClick(View v) {
    int[] cards = {
        R.drawable.bg,
        R.drawable.bg1
    };
    int id = cards[new Random().nextInt(2)];
    ImageView imgview1 = (ImageView) findViewById(R.id.imgv1);
    imgview1.setImageResource(id);
    imgview1.setTag(id);

    if (imgview1.getTag() == R.drawable.bg) {
        imgview1.setImageResource(id);
    } else {
        finish();
    }
}
</code>```

Body:
I'm trying to randomize images when a button is clicked and if the image is what I want it to be, randomize again, but if it's not, close the activity.

I cant randomize in my code, it closes always, but if I delete the call to the finish() function, it will randomize normally.

I just want that imageview to recognize the image without a sqlite DB

@Override
            public void onClick(View v) {
                int[] cards={R.drawable.bg,R.drawable.bg1};
                Random r = new Random();
                int n = r.nextInt(2);
                ImageView imgview1 = (ImageView) findViewById(R.id.imgv1);
                imgview1.setImageResource(cards[n]);

                if (imgview1.equals(R.drawable.bg){
                    imgview1.setImageResource(cards[n]);
                }
                else  {
                    finish();
                }
            }

Body:
You if-condition is always false because you are comparing an Object to an int which will never be true.

Unfortunately there is no ImageView#getDrawableId so you have to use a work around with Imageview#setTag e.g.

@Override
public void onClick(View v) {
    int[] cards = {
        R.drawable.bg,
        R.drawable.bg1
    };
    int id = cards[new Random().nextInt(2)];
    ImageView imgview1 = (ImageView) findViewById(R.id.imgv1);
    imgview1.setImageResource(id);
    imgview1.setTag(id);

    if (imgview1.getTag() == R.drawable.bg) {
        imgview1.setImageResource(id);
    } else {
        finish();
    }
}


问:
Angular2,Typescript:How to insert a key:value pair at a PARTICULAR index in an array?
I want to insert a key value pair at a particular index in an array.How do I do that ?

this is my code so far:

```<code>  this.quiz.push(
{
  "question-no":this.no,
  "Ans":this.ans
}
</code>```

I need it in that way because this is to store the choice selected by the user against the particular question. So if the user changes the choice then that has to get replaced at that particular position(index of the array). But now a new element is being created.But I want it to replace the existing one.
But I don't know how to insert it at a particular index.Can anyone help me please ?

Thanks in advance.

答:
You need to use splice function to insert at specific index.

```<code>this.quiz.splice(insertIndex, 0, newItem);
</code>```

Hope it helps!!

Body:
I want to insert a key value pair at a particular index in an array.How do I do that ?

this is my code so far:

  this.quiz.push(
{
  "question-no":this.no,
  "Ans":this.ans
}

I need it in that way because this is to store the choice selected by the user against the particular question. So if the user changes the choice then that has to get replaced at that particular position(index of the array). But now a new element is being created.But I want it to replace the existing one.
But I don't know how to insert it at a particular index.Can anyone help me please ?

Thanks in advance.

Body:
You need to use splice function to insert at specific index.

this.quiz.splice(insertIndex, 0, newItem);

Hope it helps!!


问:
UnitTests and iOS : viewDidLoad triggered twice
I am testing the viewDidLoad event on one of my UIViewController.

```<code>- (void)testMyView
{
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
    MyViewController *vc = [storyboard instantiateViewControllerWithIdentifier:MYID];
    [vc viewDidLoad];

    STAssertNotNil(vc, @"MyViewController should not be nil");
}
</code>```

If I remove the line [vc viewDidLoad];, the viewDidLoad is never triggered.

If I let [vc viewDidLoad]; in place, the viewDidLoad is triggered twice.

I understand that views are lazy loaded, but how can I avoid that behavior?

Is there any best practice regarding View testing?

答:
Read my note https://github.com/onmyway133/blog/issues/52

Suppose we have the following view controller

```<code>class ListController: UIViewController {
  override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = .white
  }
}
</code>```

Get to know viewDidLoad

We know that viewDidLoad is called when view is created the first time. So in the the Unit Test, if you use viewDidLoad to trigger, you will fall into a trap

```<code>func testSetup() {
  let controller = ListController()
  controller.viewDidLoad()
}
</code>```

Why is viewDidLoad called twice?

It is called once in your test
And in your viewDidLoad method, you access view, which is created the first time, hence it will trigger viewDidLoad again

The correct way

The best practice is not to trigger events yourself, but do something to make event happen. In Unit Test, we just access view to trigger viewDidLoad

```<code>func testSetup() {
  let controller = ListController()
  let _ = controller.view
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am testing the viewDidLoad event on one of my UIViewController.

- (void)testMyView
{
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
    MyViewController *vc = [storyboard instantiateViewControllerWithIdentifier:MYID];
    [vc viewDidLoad];

    STAssertNotNil(vc, @"MyViewController should not be nil");
}

If I remove the line [vc viewDidLoad];, the viewDidLoad is never triggered.

If I let [vc viewDidLoad]; in place, the viewDidLoad is triggered twice.

I understand that views are lazy loaded, but how can I avoid that behavior?

Is there any best practice regarding View testing?

Body:
Read my note https://github.com/onmyway133/blog/issues/52

Suppose we have the following view controller

class ListController: UIViewController {
  override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = .white
  }
}

Get to know viewDidLoad

We know that viewDidLoad is called when view is created the first time. So in the the Unit Test, if you use viewDidLoad to trigger, you will fall into a trap

func testSetup() {
  let controller = ListController()
  controller.viewDidLoad()
}

Why is viewDidLoad called twice?

It is called once in your test
And in your viewDidLoad method, you access view, which is created the first time, hence it will trigger viewDidLoad again

The correct way

The best practice is not to trigger events yourself, but do something to make event happen. In Unit Test, we just access view to trigger viewDidLoad

func testSetup() {
  let controller = ListController()
  let _ = controller.view
}


问:
JQuery change inner text but preserve html
I would like to change the text of a HTML element but preserve the rest of the inner html with jQuery.

For instance:

```<code><a href="link.html">Some text <img src="image.jpg" /></a>
</code>```

replace "Some text" with "Other text", and the result should look like:

```<code><a href="link.html">Other text <img src="image.jpg" /></a>
</code>```

EDIT:
My current solution is following:

```<code>var aElem = $('a');
var children = aElem.children();

aElem.text("NEW TEXT");
aElem.append(children);
</code>```

But there must be some more elegant way of doing this.

答:
I added a jQuery function for that need.

you may need to convert the html-entities to text representation, so i added decodeEntities function.

```<code>function decodeEntities(encodedString) {
 if (typeof encodedString != "string") return encodedString;
 if (!encodedString) return "";
 var textArea = document.createElement('textarea');
 textArea.innerHTML = encodedString;
 return textArea.value;
}
jQuery.fn.textOnly = function(n) {
  if (this.length > 0)
   $(this).html(decodeEntities($(this).html()).replace($(this).text(), n));
  return $(this);
 }
</code>```

Usage example
  $('selector').textOnly('some text')

Body:
I would like to change the text of a HTML element but preserve the rest of the inner html with jQuery.

For instance:

Some text

replace "Some text" with "Other text", and the result should look like:

Other text

EDIT:
My current solution is following:

var aElem = $('a');
var children = aElem.children();

aElem.text("NEW TEXT");
aElem.append(children);

But there must be some more elegant way of doing this.

Body:
I added a jQuery function for that need.

you may need to convert the html-entities to text representation, so i added decodeEntities function.

function decodeEntities(encodedString) {
 if (typeof encodedString != "string") return encodedString;
 if (!encodedString) return "";
 var textArea = document.createElement('textarea');
 textArea.innerHTML = encodedString;
 return textArea.value;
}
jQuery.fn.textOnly = function(n) {
  if (this.length > 0)
   $(this).html(decodeEntities($(this).html()).replace($(this).text(), n));
  return $(this);
 }

Usage example
  $('selector').textOnly('some text')


问:
PHP if statement inside HTML attribute
I was wondering something. I'm looking at code from other trainees (who left, so I can't ask anything). I see the following:

```<code><input type="text"
name="name"
class="form-control"
placeholder="name"
value="<?php if (isset($something)): echo 'bla';
             else: if(!empty($somethingelse)): echo 'bla2'; endif;"
>
</code>```

This actually does look pretty ugly if I say so myself. I was wondering: is this actually a "good"/okay way to do it or is it really as bad as I think?

答:
Try this -

```<code><?php
    if (isset($something)){
        $value = 'bla';
    }
    else if(!empty($somethingelse)){
       $value = 'bla2';
    }
?>

<input type="text" name="name" class="form-control" placeholder="name"
value="<?php echo $value ?>" >
</code>```

First I'm setting the value in $value based on a condition and then I'm echoing that value in value attribute.

Title: PHP if statement inside HTML attribute

Body:
I was wondering something. I'm looking at code from other trainees (who left, so I can't ask anything). I see the following:

<input type="text"
name="name"
class="form-control"
placeholder="name"
value="<?php if (isset($something)): echo 'bla';
             else: if(!empty($somethingelse)): echo 'bla2'; endif;"
>

This actually does look pretty ugly if I say so myself. I was wondering: is this actually a "good"/okay way to do it or is it really as bad as I think?

Body:
Try this -

<?php
    if (isset($something)){
        $value = 'bla';
    }
    else if(!empty($somethingelse)){
       $value = 'bla2';
    }
?>

<input type="text" name="name" class="form-control" placeholder="name"
value="<?php echo $value ?>" >

First I'm setting the value in $value based on a condition and then I'm echoing that value in value attribute.


问:
How to set time on load in ajax
Here is my code customize.js:

```<code>$(document).on('click','#savescore',function(e){

    var x = document.getElementsByTagName('input');

    $('input[name="name[]"]').each(function(){

        var values = ($(this).val());

        var a = $(this).attr('data');

        $.ajax({

                 url:"http://www.csscorecard.com/wp-content/themes/twentyseventeen/ajax/submit.php?function=updateScore",

                 type:"post",

                 data:{ score:values , id:a },
                 success:function(data){
                }

            });

           })
           $('#alert-success').addClass('show-alert-csp');
           $(this).disabled = true;

           document.getElementById('editscore').disabled = false;

})
</code>```

My problem is there are 50 data to loop in my input type,
I want to set a time into 5sec before the $('#alert-success').addClass('show-alert-csp'); appear to make all data save in database because everytime I update the data after I refresh the content not all data are updated. And i want to disable the cursor when time > 5sec.

Any suggestion.

答:
you can use setTimeout

Example

```<code>setTimeout(function(){
 $('#alert-success').addClass('show-alert-csp');
},5000);  // 1 second = 1000
</code>```

OR you can do it in after success ajax.

Example

```<code>success:function(data){
  $('#alert-success').addClass('show-alert-csp');
}
</code>```

Title: How to set time on load in ajax

Body:
Here is my code customize.js:

$(document).on('click','#savescore',function(e){

    var x = document.getElementsByTagName('input');

    $('input[name="name[]"]').each(function(){

        var values = ($(this).val());

        var a = $(this).attr('data');

        $.ajax({

                 url:"http://www.csscorecard.com/wp-content/themes/twentyseventeen/ajax/submit.php?function=updateScore",

                 type:"post",

                 data:{ score:values , id:a },
                 success:function(data){
                }

            });

           })
           $('#alert-success').addClass('show-alert-csp');
           $(this).disabled = true;

           document.getElementById('editscore').disabled = false;

})

My problem is there are 50 data to loop in my input type,
I want to set a time into 5sec before the $('#alert-success').addClass('show-alert-csp'); appear to make all data save in database because everytime I update the data after I refresh the content not all data are updated. And i want to disable the cursor when time > 5sec.

Any suggestion.

Body:
you can use setTimeout

Example

setTimeout(function(){
 $('#alert-success').addClass('show-alert-csp');
},5000);  // 1 second = 1000

OR you can do it in after success ajax.

Example

success:function(data){
  $('#alert-success').addClass('show-alert-csp');
}


问:
Use Laravel routeNotifcationForMail() to send to multiple emails addresses?
I'm using the Notifiable trait on my Model.

User has comma-separated list of subscribed emails (string).

The documentation and my background reading suggests that this will only route to a single email address.

```<code><?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * Route notifications for the mail channel.
     *
     * @return string
     */
    public function routeNotificationForMail()
    {
        return $this->email_address;
    }
}
</code>```

Laravel 5.3 Notifications

I've also read Matt Stauffer on Notifications but can't see an answer there.

My NotificationClass->toMail() is as follows.

```<code>/**
 * Get the mail representation of the notification.
 *
 * @param Store $store
 * @return mixed
 * @throws Exception
 */
public function toMail(User $user)
{
    return (new MailMessage)->view('notifications.emails.activity-roundup', compact('user'));
}
</code>```

答:
I guess you want code below since you can send array (see here):</p>

```<code>/**
 * Route notifications for the mail channel.
 *
 * @return string
 */
public function routeNotificationForMail()
{
    return $this->emailsToArray();
}

private function emailsToArray() {
    if (is_null($this->email_addresses)) {
        return $this->email; //default email
    }
    //perform more checks that you need
    return array_map('trim', explode(',', $this->email_addresses))
}
</code>```

Body:
I'm using the Notifiable trait on my Model.

User has comma-separated list of subscribed emails (string).

The documentation and my background reading suggests that this will only route to a single email address.

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * Route notifications for the mail channel.
     *
     * @return string
     */
    public function routeNotificationForMail()
    {
        return $this->email_address;
    }
}

Laravel 5.3 Notifications

I've also read Matt Stauffer on Notifications but can't see an answer there.

My NotificationClass->toMail() is as follows.

/**
 * Get the mail representation of the notification.
 *
 * @param Store $store
 * @return mixed
 * @throws Exception
 */
public function toMail(User $user)
{
    return (new MailMessage)->view('notifications.emails.activity-roundup', compact('user'));
}

Body:
I guess you want code below since you can send array (see here):

/**
 * Route notifications for the mail channel.
 *
 * @return string
 */
public function routeNotificationForMail()
{
    return $this->emailsToArray();
}

private function emailsToArray() {
    if (is_null($this->email_addresses)) {
        return $this->email; //default email
    }
    //perform more checks that you need
    return array_map('trim', explode(',', $this->email_addresses))
}


问:
HTML5 canvas drawImage, how to preserve image source size
```<code>function getImageBase64Data(_id)
{
    var c = document.createElement('CANVAS');
    var ctx = c.getContext("2d");
    var img = document.getElementById(_id);
    ctx.drawImage(img, 0, 0);
    var dataURL = c.toDataURL();
    return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
</code>```

I'm using HTML5 canvas to obtain base64-encoded image data. However, the resulting base64 encoded string is different and smaller than encoding the original image file with external software.

I suspect what is drawn on the canvas is the the resized/compressed image data rendered on the page, not the original source data. Is this the case, and how could I obtain the original bytes of the image? It is essential, that original bytes aren't manipulated in any way.

答:
To make it shown without compress, change the height/width for canvas itself:</p>

```<code>var img = new Image(); // var img = document.getElementById(_id);
img.onload = function() {
    var c = document.createElement('canvas');
    c.width = img.width;
    c.height = img.height;
    // ... other stuff
};
</code>```

Body:
function getImageBase64Data(_id)
{
    var c = document.createElement('CANVAS');
    var ctx = c.getContext("2d");
    var img = document.getElementById(_id);
    ctx.drawImage(img, 0, 0);
    var dataURL = c.toDataURL();
    return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}

I'm using HTML5 canvas to obtain base64-encoded image data. However, the resulting base64 encoded string is different and smaller than encoding the original image file with external software.

I suspect what is drawn on the canvas is the the resized/compressed image data rendered on the page, not the original source data. Is this the case, and how could I obtain the original bytes of the image? It is essential, that original bytes aren't manipulated in any way.

Body:
To make it shown without compress, change the height/width for canvas itself:

var img = new Image(); // var img = document.getElementById(_id);
img.onload = function() {
    var c = document.createElement('canvas');
    c.width = img.width;
    c.height = img.height;
    // ... other stuff
};


问:
Why does a function parameter call a constructor with an argument?
I have this code(stolen from cplusplus.com):

```<code>// explicit:
#include <iostream>
using namespace std;

class A {};

class B {
public:
  explicit B (const A& x) {}
  B& operator= (const A& x) {return *this;}
  operator A() {return A();}
};

void fn (B x) {}

int main ()
{
  A foo;
  B bar (foo);
  bar = foo;
  foo = bar;

//  fn (foo);  // not allowed for explicit ctor.
  fn (bar);

  return 0;
}
</code>```

So apparently the statement fn (foo); would call the constructor defined in class B, and I do not really get why. Why would that call a constructor with an argument, I mean aren't things simply copied to the function parameters when not using a reference? If fn (foo); calls the constructor B (const A& x) {}, shouldn't fn (bar); generate an error since there is no constructor defined for an argument of type B, such as B (const B& x) {}?

答:
Well ... B(const B&) although not explicitly declared, is there.  That's because it is one of the special functions for which the compiler has a default:

```<code>B()
B(const B&)
B(B&&)
B& operator=(const B&)
B& operator==(B&&)
~B()
</code>```

So, B can copy itself.

It cannot convert implicitly form A being such a conversion is declared as explicit.

fn(B(foo)) would have worked.

Body:
I have this code(stolen from cplusplus.com):

// explicit:
#include <iostream>
using namespace std;

class A {};

class B {
public:
  explicit B (const A& x) {}
  B& operator= (const A& x) {return *this;}
  operator A() {return A();}
};

void fn (B x) {}

int main ()
{
  A foo;
  B bar (foo);
  bar = foo;
  foo = bar;

//  fn (foo);  // not allowed for explicit ctor.
  fn (bar);

  return 0;
}

So apparently the statement fn (foo); would call the constructor defined in class B, and I do not really get why. Why would that call a constructor with an argument, I mean aren't things simply copied to the function parameters when not using a reference? If fn (foo); calls the constructor B (const A& x) {}, shouldn't fn (bar); generate an error since there is no constructor defined for an argument of type B, such as B (const B& x) {}?

Body:
Well ... B(const B&) although not explicitly declared, is there.  That's because it is one of the special functions for which the compiler has a default:

B()
B(const B&)
B(B&&)
B& operator=(const B&)
B& operator==(B&&)
~B()

So, B can copy itself.

It cannot convert implicitly form A being such a conversion is declared as explicit.

fn(B(foo)) would have worked.


问:
add typings for missing method (from a npm package)
I'm using the package @types/cropperjs
unfortunately it is behind the current cropper.js versions and lacks the method scale.
So far I just manually added the missing method to the d.ts file under node_modules (this is obviously a bad idea, so don't do that! it was just a temp. fix)

I tried to merge the definitions from node_modules with my own declaration.

```<code>declare class cropperjs {

  /**
   * Scale the image.
   *
   * @param scaleX The scaling factor to apply on the abscissa of the image.
   * When equal to 1 it does nothing. Default is 1
   * @param scaleY The scaling factor to apply on the ordinate of the image.
   * If not present, its default value is scaleX.
   */
   scale(scaleX: number, scaleY?: number): void;
}

export = cropperjs;
export as namespace Cropper;
</code>```

the typings from the DefinitlyTyped Repo can be found on github (it looks similar but is too big to display here)

Here's how I import cropper in an angular component.

import * as Cropper from 'cropperjs';

Here's my tsconfig.json (parts of it)

```<code> "typeRoots": [
  "node_modules/@types",
  "node_modules/@angular",
  "src/typings"
],
"types": [
  "jasmine",
  "node",
  "karma",
  "webpack",
   "cropperjs"
]
</code>```

I tried it with my custom typings folder an with the tripple slash reference notation.
But I can't figure out how I can successfully merge my and DefinitlyTyped's definitions so I can use cropperjs without having to fiddle around in node_module

P.S.
I already opened an issue with the updated definitions on github (no pull request, because at the time had almost no knowledge of git).

答:
Just wanted to add another possible "solution". I say "solution" because it's in my opinion quite ugly but then again it's a workaround.

After seeing and reading (see Aviad Hadad's answer) that class merging is not possible and read about typescripts node module resolution
Basically if you import an non-relative path like import * as Cropper from 'cropperjs typescript will look for the appropriate files in a folder named node_modules and it starts in the directory in which the file with the import statement resides. It then traverses up (example taken from the typescript documentation)

/root/src/node_modules/moduleB.ts

/root/node_modules/moduleB.ts

/node_modules/moduleB.ts (I assume that's the global node_modules directory)

Since typescript will also look for d.ts files I copied the whole index.d.ts from the @types/cropperjs package, renamed it to cropperjs.d.ts and put it in a folder named /root/src/node_modules. (and added the missing method)

if you trace the resolution with tsc --traceResolution you'll see that typescript will take the d.ts file from the custom node_modules directory.

The advantage with this solution is that you don't have to touch your code. As soon as @types/cropperjs has updated the missing method you can just delete your custom node_modules directory and everything will still work.
Disadvantage is you have to copy and paste code around.

Body:
I'm using the package @types/cropperjs
unfortunately it is behind the current cropper.js versions and lacks the method scale.
So far I just manually added the missing method to the d.ts file under node_modules (this is obviously a bad idea, so don't do that! it was just a temp. fix)

I tried to merge the definitions from node_modules with my own declaration.

declare class cropperjs {

  /**
   * Scale the image.
   *
   * @param scaleX The scaling factor to apply on the abscissa of the image.
   * When equal to 1 it does nothing. Default is 1
   * @param scaleY The scaling factor to apply on the ordinate of the image.
   * If not present, its default value is scaleX.
   */
   scale(scaleX: number, scaleY?: number): void;
}

export = cropperjs;
export as namespace Cropper;

the typings from the DefinitlyTyped Repo can be found on github (it looks similar but is too big to display here)

Here's how I import cropper in an angular component.

import * as Cropper from 'cropperjs';

Here's my tsconfig.json (parts of it)

 "typeRoots": [
  "node_modules/@types",
  "node_modules/@angular",
  "src/typings"
],
"types": [
  "jasmine",
  "node",
  "karma",
  "webpack",
   "cropperjs"
]

I tried it with my custom typings folder an with the tripple slash reference notation.
But I can't figure out how I can successfully merge my and DefinitlyTyped's definitions so I can use cropperjs without having to fiddle around in node_module

P.S.
I already opened an issue with the updated definitions on github (no pull request, because at the time had almost no knowledge of git).


问:
Reduce spacing between columns in table created with kable(, format = 'markdown')
I try to create a table using the format "markdown" of the function kable(), but the spaces between the columns are so wide that the table extends over the page. Is there anyway to adjust the cell size so that a table in markdown format does not extend over the page? In latex format it stays within the page, but I do not want this format nor do I want html. I want the output file to be .pdf.
I know that a similar question has been asked here, but my question is specific to the format markdown. If you feel this is a duplicate, please merge the questions.

Reproducible example:

```<code>---
title: "Example"
author: "JAQuent"
date: "7 Juni 2017"
output: pdf_document
---

\tiny

```{r results='asis', echo = FALSE, warning = FALSE}
library(knitr)

table1 <- data.frame(Factor1 = c('level 1', 'level 1', 'level 2', 'level 2'),
                     Factor2 = c('level 1', 'level 2', 'level 1', 'level 2'),
                     Parameter1 = sample(1000000:9999999, 2),
                     Parameter2 = sample(1000000:9999999, 2),
                     Parameter3 = sample(1000000:9999999, 2),
                     Parameter4 = sample(1000000:9999999, 2),
                     Parameter5 = sample(1000000:9999999, 2),
                     Parameter6 = sample(1000000:9999999, 2),
                     Parameter7 = sample(1000000:9999999, 2))

names(table1) <- c('Factor1', 'Factor2', 'Parameter1', 'Parameter2', 'Parameter3', 'Parameter4', 'Parameter5', 'Parameter6', 'Parameter7')

kable(table1, format = 'markdown')
kable(table1, format = 'latex')
```
</code>```

答:
A couple of the examples in ?kable contain a padding argument. Feeding it 0L gets you closer, but it turns out that this argument will take negative integers, so

```<code>kable(table1, format = 'markdown', padding=-1L)
</code>```

will produce something closer to what your are looking for.

Body:
I try to create a table using the format "markdown" of the function kable(), but the spaces between the columns are so wide that the table extends over the page. Is there anyway to adjust the cell size so that a table in markdown format does not extend over the page? In latex format it stays within the page, but I do not want this format nor do I want html. I want the output file to be .pdf.
I know that a similar question has been asked here, but my question is specific to the format markdown. If you feel this is a duplicate, please merge the questions.

Reproducible example:

---
title: "Example"
author: "JAQuent"
date: "7 Juni 2017"
output: pdf_document
---

\tiny

```{r results='asis', echo = FALSE, warning = FALSE}
library(knitr)

table1 <- data.frame(Factor1 = c('level 1', 'level 1', 'level 2', 'level 2'),
                     Factor2 = c('level 1', 'level 2', 'level 1', 'level 2'),
                     Parameter1 = sample(1000000:9999999, 2),
                     Parameter2 = sample(1000000:9999999, 2),
                     Parameter3 = sample(1000000:9999999, 2),
                     Parameter4 = sample(1000000:9999999, 2),
                     Parameter5 = sample(1000000:9999999, 2),
                     Parameter6 = sample(1000000:9999999, 2),
                     Parameter7 = sample(1000000:9999999, 2))

names(table1) <- c('Factor1', 'Factor2', 'Parameter1', 'Parameter2', 'Parameter3', 'Parameter4', 'Parameter5', 'Parameter6', 'Parameter7')

kable(table1, format = 'markdown')
kable(table1, format = 'latex')
```

Body:
A couple of the examples in ?kable contain a padding argument. Feeding it 0L gets you closer, but it turns out that this argument will take negative integers, so

kable(table1, format = 'markdown', padding=-1L)

will produce something closer to what your are looking for.


答:
Setting a fixed time would not be a good solution. We are not sure if the process will indeed complete within the time you have set (what if the server fails, what if the server is slow). Instead, your AJAX request should return a response (upon successful insertion into the database, or failure to do so). Once the response is received, a callback function should be called on the client side to display the appropriate success / error message.

Assuming the server returns the appropriate response, you can have something like:

```<code>$.ajax({

                    url:"http://www.csscorecard.com/wp-content/themes/twentyseventeen/ajax/submit.php?function=updateScore",

                    type:"post",

                    data:{ score:values , id:a },
                    success:function(data){
                        $('#alert-success').addClass('show-alert-csp');
                    }

                });
</code>```

Title: How to set time on load in ajax

Body:
Setting a fixed time would not be a good solution. We are not sure if the process will indeed complete within the time you have set (what if the server fails, what if the server is slow). Instead, your AJAX request should return a response (upon successful insertion into the database, or failure to do so). Once the response is received, a callback function should be called on the client side to display the appropriate success / error message.

Assuming the server returns the appropriate response, you can have something like:

$.ajax({

                    url:"http://www.csscorecard.com/wp-content/themes/twentyseventeen/ajax/submit.php?function=updateScore",

                    type:"post",

                    data:{ score:values , id:a },
                    success:function(data){
                        $('#alert-success').addClass('show-alert-csp');
                    }

                });


问:
OLEDB date(time) issue asp.net c#
I have written a little excel helper which works fine. It uses this connection string:

```<code>"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=<FILENAME>;Extended Properties=\"Excel 12.0;HDR=Yes;\";";
</code>```

Unfortunately when I deploy the code, cells, which contains a date string like this: 28/12/2008 are returned as: 12/25/2008 12:00:00 AM rather than 25/12/2008 00:00:00 after using ToString. I adjusted the time zone etc. of the machine (all machines are now UK time zones) but this hasn't changed anything. I am just curious what determines how OLEDB 'behaves'. The aim would be to get 25/12/2008 00:00:00 on both machines.

Thanks!

Christian

答: You have American datetime settings, either change this or use the numberformat to show it in the format you want, see http://www.mvps.org/dmcritchie/excel/datetime.htm</p>

Title: OLEDB date(time) issue asp.net c#

Body:
I have written a little excel helper which works fine. It uses this connection string:

"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=<FILENAME>;Extended Properties=\"Excel 12.0;HDR=Yes;\";";

Unfortunately when I deploy the code, cells, which contains a date string like this: 28/12/2008 are returned as: 12/25/2008 12:00:00 AM rather than 25/12/2008 00:00:00 after using ToString. I adjusted the time zone etc. of the machine (all machines are now UK time zones) but this hasn't changed anything. I am just curious what determines how OLEDB 'behaves'. The aim would be to get 25/12/2008 00:00:00 on both machines.

Thanks!

Christian


问:
Do we need to explicitly ask for the permission other than AndroidManifest.xml in Marshmallow?
In the Android versions lower than the marshmallow, i can run my application that writes a file to the External storage. And in those system the permission is granted at the time of installation of the app. But when i tried to run my application in marshmallow, it says "the app need no permissions" at the time of installation. And the app unexpectedly exits at the time i execute the write function.

Usually the device asks to grant permissions on every app at the time when it is opened for the first time. but in my app this too doesn't happens.

答: You have to provide the runtime permission handling for Android 6.0+ (Marshmallow) yourself. See here for more information.</p>


问:
card flipping front flips in different direction opposite of whats declared in the css why?
I have a parent div with a class of .card and it has to children div, that rotates in opposite directions when their parent is hovered over to create a flipping card. If you hover over it and wait until the transition finishes it works fine, however if you hover over it then move the mouse of before the animation finishes the div with a class of .front rotates in the opposite direction, why and is there a way to fix this? In addition if you move the mouse on and off multiple times both children start turning at different times even though they have the same trigger- why?

https://jsfiddle.net/8pktgqpu/15/

```<code>  .card,.front,.back{
    width: 100px;
    height: 160px;
    margin: 1px;
  }
  .card{
    position: relative;
  }
  .front{
    background-color: red;
    transform: perspective(400px) rotatey(0deg);
    backface-visibility: hidden;
    transition: transform 1s ease-in-out 0s;
  }
  .back{
    backface-visibility: hidden;
    transform: perspective(400px) rotatey(180deg);
    background-color: blue;
    transition: transform 1s ease-in-out 0s;
    position: absolute;
    top: 0;
  }

  .card:hover .front{
    transform: rotatey(-180deg);
  }
  .card:hover .back{
    transform: rotatey(0deg);
  }
</code>```

答:
Add a div and use perspective and transform-style: preserve-3d; to get it
below an example

        .flip {
            width: 300px;
            height: 500px;
            perspective: 1000px;
        }
        .flip_box {
            width: 300px;
            height: 500px;
            position: relative;
            transition: all 0.4s linear;
            -webkit-transition: all 0.4s linear;
            transform-style: preserve-3d;
            -webkit-transform-style: preserve-3d
        }
        .front, .back {
            position: absolute;
            width: 300px;
            height: 500px;
            top: 0px;
            left: 0px;
            border: 1px solid #666;
            backface-visibility: hidden;
            -webkit-backface-visibility: hidden;
        }
        .front {
            color: red;
            font-size: 16px;
        }
        .back {
            color: blue;
            font-size: 18px;
            transform: rotateY(180deg);
            -webkit-transform: rotateY(180deg);
        }
        .flip:hover .flip_box {
            transform: rotateY(180deg);
            -webkit-transform: rotateY(180deg);
        }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="flip">
    <div class="flip_box">
        <div class="front">
            Hello
        </div>
        <div class="back">
            Bye
        </div>
    </div>
</div></code>```

Body:
I have a parent div with a class of .card and it has to children div, that rotates in opposite directions when their parent is hovered over to create a flipping card. If you hover over it and wait until the transition finishes it works fine, however if you hover over it then move the mouse of before the animation finishes the div with a class of .front rotates in the opposite direction, why and is there a way to fix this? In addition if you move the mouse on and off multiple times both children start turning at different times even though they have the same trigger- why?

https://jsfiddle.net/8pktgqpu/15/

  .card,.front,.back{
    width: 100px;
    height: 160px;
    margin: 1px;
  }
  .card{
    position: relative;
  }
  .front{
    background-color: red;
    transform: perspective(400px) rotatey(0deg);
    backface-visibility: hidden;
    transition: transform 1s ease-in-out 0s;
  }
  .back{
    backface-visibility: hidden;
    transform: perspective(400px) rotatey(180deg);
    background-color: blue;
    transition: transform 1s ease-in-out 0s;
    position: absolute;
    top: 0;
  }

  .card:hover .front{
    transform: rotatey(-180deg);
  }
  .card:hover .back{
    transform: rotatey(0deg);
  }

Body:
Add a div and use perspective and transform-style: preserve-3d; to get it
below an example

        .flip {
            width: 300px;
            height: 500px;
            perspective: 1000px;
        }
        .flip_box {
            width: 300px;
            height: 500px;
            position: relative;
            transition: all 0.4s linear;
            -webkit-transition: all 0.4s linear;
            transform-style: preserve-3d;
            -webkit-transform-style: preserve-3d
        }
        .front, .back {
            position: absolute;
            width: 300px;
            height: 500px;
            top: 0px;
            left: 0px;
            border: 1px solid #666;
            backface-visibility: hidden;
            -webkit-backface-visibility: hidden;
        }
        .front {
            color: red;
            font-size: 16px;
        }
        .back {
            color: blue;
            font-size: 18px;
            transform: rotateY(180deg);
            -webkit-transform: rotateY(180deg);
        }
        .flip:hover .flip_box {
            transform: rotateY(180deg);
            -webkit-transform: rotateY(180deg);
        }

<div class="flip">
    <div class="flip_box">
        <div class="front">
            Hello
        </div>
        <div class="back">
            Bye
        </div>
    </div>
</div>


问:
How to display a property from a class in a ListBox?
In my class Student I have a property studentName which I want to be displayed on each line of my ListBox.

My ListBox is bound to a List<Students> studentList

How do I display the name of each student in the list onto the ListBox ?

e.g

```<code>foreach(Student s in studentList){
    ListBox.DisplayOnNewLine(s.studentName);
}
</code>```

答:
set DisplayMember to property you want to display
e.g.

```<code>listBox1.DisplayMember = "studentName";
</code>```

this way you do not have to override ToString()

Body:
In my class Student I have a property studentName which I want to be displayed on each line of my ListBox.

My ListBox is bound to a List<Students> studentList

How do I display the name of each student in the list onto the ListBox ?

e.g

foreach(Student s in studentList){
    ListBox.DisplayOnNewLine(s.studentName);
}

Body:
set DisplayMember to property you want to display
e.g.

listBox1.DisplayMember = "studentName";

this way you do not have to override ToString()


问:
Razor View throwing "The name 'model' does not exist in the current context"
After significant refactoring in my MVC 4 application, and Razor shows this error while debugging Views:

The name 'model' does not exist in the current context.

This is the offending line of code:

```<code>@model ICollection<DataSourceByActive>
</code>```

I know that the usage of @model is correct.

Why is this happening? How can I fix it?

答:
I've found a solution.
If you want to update razor version or mvc 4 to 5, change some lines.

Old code in Views/web.config

```<code><sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
  <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
  <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
</sectionGroup>
</code>```

Replaced with

```<code><sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
    <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
    <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
</sectionGroup>
</code>```

sectionGroup must be change, too.

Body:
After significant refactoring in my MVC 4 application, and Razor shows this error while debugging Views:

The name 'model' does not exist in the current context.

This is the offending line of code:

@model ICollection<DataSourceByActive>

I know that the usage of @model is correct.

Why is this happening? How can I fix it?

Body:
I've found a solution.
If you want to update razor version or mvc 4 to 5, change some lines.

Old code in Views/web.config

<sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
  <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
  <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
</sectionGroup>

Replaced with

<sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
    <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
    <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
</sectionGroup>

sectionGroup must be change, too.


问:
How to get all possible subsets of a set
Can someone explain to me how to generate all subsets of a set using an algorithm which has complexity lower or equal to the following?

```<code>#include <stdio.h>
#include <math.h>

void printPowerSet(char *set, int set_size)
{
    /*set_size of power set of a set with set_size
      n is (2**n -1)*/
    unsigned int pow_set_size = pow(2, set_size);
    int counter, j;

    /*Run from counter 000..0 to 111..1*/
    for(counter = 0; counter < pow_set_size; counter++)
    {
      for(j = 0; j < set_size; j++)
       {
          /* Check if jth bit in the counter is set
             If set then pront jth element from set */
          if(counter & (1<<j))
            printf("%c", set[j]);
       }
       printf("\n");
    }
}

/*Driver program to test printPowerSet*/
int main()
{
    char set[] = {'a','b','c'};
    printPowerSet(set, 3);

    getchar();
    return 0;
}
</code>```

For example if my input is

```<code>3
2 3 4
</code>```

I should get my output as

```<code>{2} {3} {4} {2,3} {2,4} {3,4} {2,3,4}
</code>```

答:
Disclaimer: the following is intended for showing the concept of generating the powerset of a set.

starts with the empty set and add it to the powerset sets:

for each element el[i]  of your set el

for each subset add already present in sets

augment add by pushing_back el[i] to it

push the augmented set to sets

Here is a proof of concept in c++

```<code>void generateSubset(vector<int>& el) {
    vector<vector<int>> sets;
    sets.push_back(vector<int>());
    for (int i = 0; i < el.size() ; i++) {
        vector<vector<int>> ssets;
        for (int j = 0 ; j < sets.size() ; j++ ) {
            vector<int> add(sets[j]);
            add.push_back(el[i]);
            ssets.push_back(add);
        }
        sets.insert(sets.end(), begin(ssets), end(ssets));
    }

//print the subsets
    for (int j = 0 ; j < sets.size() ; j++ ) {
        auto v = sets[j];
        for (auto a : v) {
            cout << a << " ";
        }
        cout << endl;
    }
    cout << "#subsets "<<sets.size() << endl;
}

int main() {
    vector<int> a = {1, 2, 3};
    generateSubset(a);
}
</code>```

Hope this helps understanding how to generate the powerset.

Body:
Can someone explain to me how to generate all subsets of a set using an algorithm which has complexity lower or equal to the following?

#include <stdio.h>
#include <math.h>

void printPowerSet(char *set, int set_size)
{
    /*set_size of power set of a set with set_size
      n is (2**n -1)*/
    unsigned int pow_set_size = pow(2, set_size);
    int counter, j;

    /*Run from counter 000..0 to 111..1*/
    for(counter = 0; counter < pow_set_size; counter++)
    {
      for(j = 0; j < set_size; j++)
       {
          /* Check if jth bit in the counter is set
             If set then pront jth element from set */
          if(counter & (1<<j))
            printf("%c", set[j]);
       }
       printf("\n");
    }
}

/*Driver program to test printPowerSet*/
int main()
{
    char set[] = {'a','b','c'};
    printPowerSet(set, 3);

    getchar();
    return 0;
}

For example if my input is

3
2 3 4

I should get my output as

{2} {3} {4} {2,3} {2,4} {3,4} {2,3,4}

Body:
Disclaimer: the following is intended for showing the concept of generating the powerset of a set.

starts with the empty set and add it to the powerset sets:

for each element el[i]  of your set el

for each subset add already present in sets

augment add by pushing_back el[i] to it

push the augmented set to sets

Here is a proof of concept in c++

void generateSubset(vector<int>& el) {
    vector<vector<int>> sets;
    sets.push_back(vector<int>());
    for (int i = 0; i < el.size() ; i++) {
        vector<vector<int>> ssets;
        for (int j = 0 ; j < sets.size() ; j++ ) {
            vector<int> add(sets[j]);
            add.push_back(el[i]);
            ssets.push_back(add);
        }
        sets.insert(sets.end(), begin(ssets), end(ssets));
    }

//print the subsets
    for (int j = 0 ; j < sets.size() ; j++ ) {
        auto v = sets[j];
        for (auto a : v) {
            cout << a << " ";
        }
        cout << endl;
    }
    cout << "#subsets "<<sets.size() << endl;
}

int main() {
    vector<int> a = {1, 2, 3};
    generateSubset(a);
}

Hope this helps understanding how to generate the powerset.


答:
Alternatively, you could make use of data binding as follows:</p>

```<code>ListBox.DisplayMember = "studentName";
ListBox.DataSource = studentList;
</code>```

Title: How to display a property from a class in a ListBox?

Body:
Alternatively, you could make use of data binding as follows:

ListBox.DisplayMember = "studentName";
ListBox.DataSource = studentList;


问:
Using StatusStrip in C#
Consider System.Windows.Forms.StatusStrip. I have added a StatusStrip to my Windows Forms application, but I am having a few problems.

I would like to have a label anchored at the left and a progressbar anchored on the right in the StatusStrip, but I can't find a way to set these properties.

I then thought that I may need to create two StatusStrips and anchor them on either side of the bottom of the form... That didn't pan out; besides that, it just doesn't feel right.

答: This can be achieved with the default table layout for the statusStrip by simply putting another label between your current label and your progressBar and set the Spring property to true.</p>

OwnerDisplayName: Brad

Title: Using StatusStrip in C#


问:
Bundle Identifer & all Certificates exist in Xcode, in Developer Account the Bundle Identifer is missing
i just created a new app. In Xcode everything like Team, Provisioning Profile and Signing Certificate is registered and i can build my app successfully. I enabled the automatically signing so Xcode should register  the bundle identifier in my developer account. But this isn't happen. In my developer account i see all my other bundle identifiers, where i used the same Signing Certificate. Now im confused, cause normally Xcode should register the bundle identifier in my developer account right? I don't want to create the bundle identifier in my developer account manually, cause i enabled that Xcode should do it.

So maybe you have some tips for me how to handle the problem.

答: i just changed my app-id and now everything is working. Don't know what the problem was.</p>