问:
Cannot authorize to WCF Basic Authentication Web Service from JMeter
I am using JMeter to run tests to a WCF Web Service with Basic Auth, the service is working and credentials are correct (I run them successfully from SOAPUI).

From all my research I have configured both the 'HTTP Header Manager' and 'HTTP Basic Authentication' and I cannot see anything wrong with my actual HTTP header when submitting:

What I have done so far:

Verified that credentials are correct by decoding the base64 string

Enabled 'serviceSecurityAudit' on the service itself resulting in the following application error:

After some manipulation of the SOAPAction I aligned it to the SOAPUI that works but the JMeter basic auth still fails:

The HTTP response is below but it is standard (I get this from SOAPUI when I intentionally type in wrong credentials)

```<code><s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body><s:Fault><faultcode xmlns:a="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">a:InvalidSecurity</faultcode><faultstring xml:lang="en-ZA">An error occurred when verifying security for the message.</faultstring></s:Fault></s:Body></s:Envelope>
</code>```

I have include the binding configuration below it uses standard basicHttpsBinding's (not wsHttpBinding):

```<code><service name="PayM8.Axis.PaymentsService.V1.HyperLink.HyperLinkService">
        <endpoint address="" binding="basicHttpsBinding" bindingConfiguration="DefaultHttpsBinding"
          contract="PayM8.Axis.PaymentsService.V1.HyperLink.IHyperLinkService"/>
</service>

<basicHttpsBinding>
    <binding name="DefaultHttpsBinding" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647">
      <security mode="TransportWithMessageCredential">
        <transport clientCredentialType="Basic" />
      </security>
    </binding>
</basicHttpsBinding>
</code>```

Any idea's what might be wrong with my JMeter Basic Authentication HTTP request?

答:
Web Services may have different authentication types, the error you're getting is about missing or incorrect WS-Security header.

There are multiple ways of adding the header to the request, you could try using JMeterSoapPlugin which has some authentication types support.

You could also take a look at Take the Pain out of Load Testing Secure Web Services to see how to bypass different types of web service authentication.

Body:
I am using JMeter to run tests to a WCF Web Service with Basic Auth, the service is working and credentials are correct (I run them successfully from SOAPUI).

From all my research I have configured both the 'HTTP Header Manager' and 'HTTP Basic Authentication' and I cannot see anything wrong with my actual HTTP header when submitting:

What I have done so far:

Verified that credentials are correct by decoding the base64 string

Enabled 'serviceSecurityAudit' on the service itself resulting in the following application error:

After some manipulation of the SOAPAction I aligned it to the SOAPUI that works but the JMeter basic auth still fails:

The HTTP response is below but it is standard (I get this from SOAPUI when I intentionally type in wrong credentials)

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body><s:Fault><faultcode xmlns:a="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">a:InvalidSecurity</faultcode><faultstring xml:lang="en-ZA">An error occurred when verifying security for the message.</faultstring></s:Fault></s:Body></s:Envelope>

I have include the binding configuration below it uses standard basicHttpsBinding's (not wsHttpBinding):

<service name="PayM8.Axis.PaymentsService.V1.HyperLink.HyperLinkService">
        <endpoint address="" binding="basicHttpsBinding" bindingConfiguration="DefaultHttpsBinding"
          contract="PayM8.Axis.PaymentsService.V1.HyperLink.IHyperLinkService"/>
</service>

<basicHttpsBinding>
    <binding name="DefaultHttpsBinding" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647">
      <security mode="TransportWithMessageCredential">
        <transport clientCredentialType="Basic" />
      </security>
    </binding>
</basicHttpsBinding>

Any idea's what might be wrong with my JMeter Basic Authentication HTTP request?


来源: stackexchange

问:
Remove Titlebar but still be able to resize
I wanted to do a WPF Window and build a custom TitleBar without having to reimplement all the code and behaviour myself...
Only problem is that even setting the Borderthickness to "0" will leave a small
border on the top of the window.
Is there any way to get rid of that by not using WindowStyle = "None" ?

Thanks for you help!

答:
You don't have to implement the resizing functionality yourself if you use the WindowChrome class.

Please refer to the documenation and the following blog post for more information: https://blogs.msdn.microsoft.com/wpfsdk/2010/08/25/experiments-with-windowchrome/

ContentLicense: CC BY-SA 3.0


问:
How do I optimize filtering in AngularJS?
I have here a filter for AngularJS. Is there any better way for this?</p>

```<code> return function (data, selected) {
        var result = [];
        if (selected[0] == 'All Types') {
            result = data;
        }
        else {
            for (var i = 0; i < data.length; i++) {
                for (var j = 0; j < selected.length; j++) {
                    if (data[i].Type == selected[j]) {
                        result.push(data[i]);
                    }
                }
            }
        }

        return result;
    };
</code>```

答:
Obviously this is using lodash, but native methods can be substituted:</p>

```<code>return (data, selected) => {
  return
    _.first(selected) === 'All Types' ? data :
    _.reduce(data, (sum, value, key) => {
      if (_.includes(selected, value.Type)) {
        sum.push(value);
      }
      return sum;
    }, []);
}
</code>```

Body:
I have here a filter for AngularJS. Is there any better way for this?

 return function (data, selected) {
        var result = [];
        if (selected[0] == 'All Types') {
            result = data;
        }
        else {
            for (var i = 0; i < data.length; i++) {
                for (var j = 0; j < selected.length; j++) {
                    if (data[i].Type == selected[j]) {
                        result.push(data[i]);
                    }
                }
            }
        }

        return result;
    };

Body:
Obviously this is using lodash, but native methods can be substituted:

return (data, selected) => {
  return
    _.first(selected) === 'All Types' ? data :
    _.reduce(data, (sum, value, key) => {
      if (_.includes(selected, value.Type)) {
        sum.push(value);
      }
      return sum;
    }, []);
}


问:
How to expose functions globally through webpack in a web app?
I am trying to expose some functions which I have in my helpers.js file globally, so that I can directly call them without having to import them. Here is my javascript file:

```<code>function icon_string(num, white){
    return "https://flyhomes.imgix.net/icons/icons_" + (white ? "w" : "b") +"_v2-" + num.toString() + ".svg";
}

Number.prototype.format = function(decPlaces, thouSeparator, decSeparator) {
    var n = this,
        decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces,
        decSeparator = decSeparator == undefined ? "." : decSeparator,
        thouSeparator = thouSeparator == undefined ? "," : thouSeparator,
        sign = n < 0 ? "-" : "",
        i = parseInt(n = Math.abs(+n || 0).toFixed(decPlaces)) + "",
        j = (j = i.length) > 3 ? j % 3 : 0;
    return sign + (j ? i.substr(0, j) + thouSeparator : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thouSeparator) + (decPlaces ? decSeparator + Math.abs(n - i).toFixed(decPlaces).slice(2) : "");
};

Array.prototype.clean = function(deleteValue) {
  for (var i = 0; i < this.length; i++) {
    if (this[i] == deleteValue) {
      this.splice(i, 1);
      i--;
    }
  }
  return this;
};

Array.prototype.move = function (old_index, new_index) {
  if (new_index >= this.length) {
      var k = new_index - this.length;
      while ((k--) + 1) {
          this.push(undefined);
      }
  }
  this.splice(new_index, 0, this.splice(old_index, 1)[0]);
  return this; // for testing purposes
};

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
    }
    return "";
}

String.prototype.replaceAll = function(search, replacement) {
    var target = this;
    return target.replace(new RegExp(search, 'g'), replacement);
};

function containsObjectID(obj, list) {
    var i;
    for (i = 0; i < list.length; i++) {
        if (list[i].id === obj.id) {
            return true;
        }
    }
    return false;
}

function containsObjectIndex(obj, list) {
    var i;
    for (i = 0; i < list.length; i++) {
        if (list[i].id === obj.id) {
            return i;
        }
    }
    return -1;
}

function getParameterByName(name) {
    var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
    return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}

function updateQueryStringParameter(uri, key, value) {
  var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
  var separator = uri.indexOf('?') !== -1 ? "&" : "?";
  if (uri.match(re)) {
    return uri.replace(re, '$1' + key + "=" + value + '$2');
  }
  else {
    return uri + separator + key + "=" + value;
  }
}

function removeQueryStringParameter(url, parameter) {
    var urlparts= url.split('?');
    if (urlparts.length>=2) {

        var prefix= encodeURIComponent(parameter)+'=';
        var pars= urlparts[1].split(/[&;]/g);

        for (var i= pars.length; i-- > 0;) {
            if (pars[i].lastIndexOf(prefix, 0) !== -1) {
                pars.splice(i, 1);
            }
        }
        url= urlparts[0]+'?'+pars.join('&');
        return url;
    } else {
        return url;
    }
}

function paramsToObject(params){
    var query_string = {};
    var query = params;
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
      var pair = vars[i].split("=");
          // If first entry with this name
      if (typeof query_string[pair[0]] === "undefined") {
        query_string[pair[0]] = decodeURIComponent(pair[1]);
          // If second entry with this name
      } else if (typeof query_string[pair[0]] === "string") {
        var arr = [ query_string[pair[0]],decodeURIComponent(pair[1]) ];
        query_string[pair[0]] = arr;
          // If third or later entry with this name
      } else {
        query_string[pair[0]].push(decodeURIComponent(pair[1]));
      }
    }
      return query_string;
}

function humanize(str) {
  var frags = str.split('_');
  frags[0] = frags[0].charAt(0).toUpperCase() + frags[0].slice(1);
  return frags.join(' ');
}

String.prototype.capitalize = function() {
  return this.charAt(0).toUpperCase() + this.slice(1);
}

// Warn if overriding existing method
if(Array.prototype.equals)
  console.warn("Overriding existing Array.prototype.equals. Possible causes: New API defines the method, there's a framework conflict or you've got double inclusions in your code.");
// attach the .equals method to Array's prototype to call it on any array
Array.prototype.equals = function (array) {
  // if the other array is a falsy value, return
  if (!array)
      return false;

  // compare lengths - can save a lot of time
  if (this.length != array.length)
      return false;

  for (var i = 0, l=this.length; i < l; i++) {
      // Check if we have nested arrays
      if (this[i] instanceof Array && array[i] instanceof Array) {
          // recurse into the nested arrays
          if (!this[i].equals(array[i]))
              return false;
      }
      else if (this[i] != array[i]) {
          // Warning - two different object instances will never be equal: {x:20} != {x:20}
          return false;
      }
  }
  return true;
}
// Hide method from for-in loops
Object.defineProperty(Array.prototype, "equals", {enumerable: false});

exports.onMobile = function() {
  var check = false;
  (function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))) check = true;})(navigator.userAgent||navigator.vendor||window.opera);
  return check;
};
</code>```

Sorry for adding the whole file, but I would like to draw attention to some of the functions which are applied to base classes themselves (such as Number, String etc), while others are declared as is.

To expose them, I tried adding alias in webpack.config.js as follows:

```<code>module.exports = {
  ...
  resolve: {
    extensions: ['.json', '.jsx', '.js'],
    alias: {
      'helpers': path.resolve(__dirname, './vendor/assets/javascripts/helpers.js')
    }
  },
  plugins: [
    new webpack.ProvidePlugin({
      helpers: 'helpers'
    })
  ],
  ...
};
</code>```

But as I was skeptical, it didn't work. I copied this idea from the instance when we need a specific library globally and we have it's javascript file, we follow the above approach. But obviously, that's related to importing a specific file and not a file containing such functions and exporting them globally at once. Can you help me how to do it through webpack or where am I going wrong?

答:
That alias just holds the value of the location of your helpers.js file.
Referencing it within other files just means the alias is replaced with the helpers file String and not its contents.

I'd also think quite carefully about not polluting the global scope with your helper functions.  If anything you can just use a namespace variable that will hold your functions as methods of the name space.  Think lodash's '_'  or even more simply vanilla JS's Math object.

BTW: Augmenting or extending the native JavaScript object is highly
 discouraged.

Body:
I am trying to expose some functions which I have in my helpers.js file globally, so that I can directly call them without having to import them. Here is my javascript file:

function icon_string(num, white){
    return "https://flyhomes.imgix.net/icons/icons_" + (white ? "w" : "b") +"_v2-" + num.toString() + ".svg";
}

Number.prototype.format = function(decPlaces, thouSeparator, decSeparator) {
    var n = this,
        decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces,
        decSeparator = decSeparator == undefined ? "." : decSeparator,
        thouSeparator = thouSeparator == undefined ? "," : thouSeparator,
        sign = n < 0 ? "-" : "",
        i = parseInt(n = Math.abs(+n || 0).toFixed(decPlaces)) + "",
        j = (j = i.length) > 3 ? j % 3 : 0;
    return sign + (j ? i.substr(0, j) + thouSeparator : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thouSeparator) + (decPlaces ? decSeparator + Math.abs(n - i).toFixed(decPlaces).slice(2) : "");
};

Array.prototype.clean = function(deleteValue) {
  for (var i = 0; i < this.length; i++) {
    if (this[i] == deleteValue) {
      this.splice(i, 1);
      i--;
    }
  }
  return this;
};

Array.prototype.move = function (old_index, new_index) {
  if (new_index >= this.length) {
      var k = new_index - this.length;
      while ((k--) + 1) {
          this.push(undefined);
      }
  }
  this.splice(new_index, 0, this.splice(old_index, 1)[0]);
  return this; // for testing purposes
};

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
    }
    return "";
}

String.prototype.replaceAll = function(search, replacement) {
    var target = this;
    return target.replace(new RegExp(search, 'g'), replacement);
};

function containsObjectID(obj, list) {
    var i;
    for (i = 0; i < list.length; i++) {
        if (list[i].id === obj.id) {
            return true;
        }
    }
    return false;
}

function containsObjectIndex(obj, list) {
    var i;
    for (i = 0; i < list.length; i++) {
        if (list[i].id === obj.id) {
            return i;
        }
    }
    return -1;
}

function getParameterByName(name) {
    var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
    return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}

function updateQueryStringParameter(uri, key, value) {
  var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
  var separator = uri.indexOf('?') !== -1 ? "&" : "?";
  if (uri.match(re)) {
    return uri.replace(re, '$1' + key + "=" + value + '$2');
  }
  else {
    return uri + separator + key + "=" + value;
  }
}

function removeQueryStringParameter(url, parameter) {
    var urlparts= url.split('?');
    if (urlparts.length>=2) {

        var prefix= encodeURIComponent(parameter)+'=';
        var pars= urlparts[1].split(/[&;]/g);

        for (var i= pars.length; i-- > 0;) {
            if (pars[i].lastIndexOf(prefix, 0) !== -1) {
                pars.splice(i, 1);
            }
        }
        url= urlparts[0]+'?'+pars.join('&');
        return url;
    } else {
        return url;
    }
}

function paramsToObject(params){
    var query_string = {};
    var query = params;
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
      var pair = vars[i].split("=");
          // If first entry with this name
      if (typeof query_string[pair[0]] === "undefined") {
        query_string[pair[0]] = decodeURIComponent(pair[1]);
          // If second entry with this name
      } else if (typeof query_string[pair[0]] === "string") {
        var arr = [ query_string[pair[0]],decodeURIComponent(pair[1]) ];
        query_string[pair[0]] = arr;
          // If third or later entry with this name
      } else {
        query_string[pair[0]].push(decodeURIComponent(pair[1]));
      }
    }
      return query_string;
}

function humanize(str) {
  var frags = str.split('_');
  frags[0] = frags[0].charAt(0).toUpperCase() + frags[0].slice(1);
  return frags.join(' ');
}

String.prototype.capitalize = function() {
  return this.charAt(0).toUpperCase() + this.slice(1);
}

// Warn if overriding existing method
if(Array.prototype.equals)
  console.warn("Overriding existing Array.prototype.equals. Possible causes: New API defines the method, there's a framework conflict or you've got double inclusions in your code.");
// attach the .equals method to Array's prototype to call it on any array
Array.prototype.equals = function (array) {
  // if the other array is a falsy value, return
  if (!array)
      return false;

  // compare lengths - can save a lot of time
  if (this.length != array.length)
      return false;

  for (var i = 0, l=this.length; i < l; i++) {
      // Check if we have nested arrays
      if (this[i] instanceof Array && array[i] instanceof Array) {
          // recurse into the nested arrays
          if (!this[i].equals(array[i]))
              return false;
      }
      else if (this[i] != array[i]) {
          // Warning - two different object instances will never be equal: {x:20} != {x:20}
          return false;
      }
  }
  return true;
}
// Hide method from for-in loops
Object.defineProperty(Array.prototype, "equals", {enumerable: false});

exports.onMobile = function() {
  var check = false;
  (function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))) check = true;})(navigator.userAgent||navigator.vendor||window.opera);
  return check;
};

Sorry for adding the whole file, but I would like to draw attention to some of the functions which are applied to base classes themselves (such as Number, String etc), while others are declared as is.

To expose them, I tried adding alias in webpack.config.js as follows:

module.exports = {
  ...
  resolve: {
    extensions: ['.json', '.jsx', '.js'],
    alias: {
      'helpers': path.resolve(__dirname, './vendor/assets/javascripts/helpers.js')
    }
  },
  plugins: [
    new webpack.ProvidePlugin({
      helpers: 'helpers'
    })
  ],
  ...
};

But as I was skeptical, it didn't work. I copied this idea from the instance when we need a specific library globally and we have it's javascript file, we follow the above approach. But obviously, that's related to importing a specific file and not a file containing such functions and exporting them globally at once. Can you help me how to do it through webpack or where am I going wrong?


问:
Removing the second "|" on the last position
Here are some examples from my data:

```<code>a <-c("sp|Q9Y6W5|","sp|Q9HB90|,sp|Q9NQL2|","orf|NCBIAAYI_c_1_1023|",
     "orf|NCBIACEN_c_10_906|,orf|NCBIACEO_c_5_1142|",
      "orf|NCBIAAYI_c_258|,orf|aot172_c_6_302|,orf|aot180_c_2_405|")
</code>```

For a: The individual strings can contain even more entries of "sp|" and "orf"

The results have to be like this:

```<code>[1] "sp|Q9Y6W5" "sp|Q9HB90,sp|Q9NQL2" "orf|NCBIAAYI_c_1_1023"
   "orf|NCBIACEN_c_10_906,orf|NCBIACEO_c_5_1142"
   "orf|NCBIAAYI_c_258,orf|aot172_c_6_302,orf|aot180_c_2_405"
</code>```

So the aim is to remove the last "|" for each "sp|" and "orf|" entry. It seems that "|" is a special challenge because it is a metacharacter in regular expressions. Furthermore, the length and composition of the "orf|" entries varying a lot. The only things they have in common is "orf|" or "sp|" at the beginning and that "|" is on the last position. I tried different things with gsub() but also with the stringr package or regexpr() or [:punct:], but nothing really worked. Maybe it was just the wrong combination.

答:
We can use gsub to match the | that is followed by a , or is at the end ($) of the string and replace with blank ("")

```<code>gsub("[|](?=(,|$))", "", a, perl = TRUE)
#[1] "sp|Q9Y6W5"
#[2] "sp|Q9HB90,sp|Q9NQL2"
#[3] "orf|NCBIAAYI_c_1_1023"
#[4] "orf|NCBIACEN_c_10_906,orf|NCBIACEO_c_5_1142"
#[5] "orf|NCBIAAYI_c_258,orf|aot172_c_6_302,orf|aot180_c_2_405"
</code>```

Or we split by ,', remove the last character withsubstr, andpastethelist` elements together

```<code>sapply(strsplit(a, ","), function(x) paste(substr(x, 1, nchar(x)-1), collapse=","))
</code>```

Body:
Here are some examples from my data:

a <-c("sp|Q9Y6W5|","sp|Q9HB90|,sp|Q9NQL2|","orf|NCBIAAYI_c_1_1023|",
     "orf|NCBIACEN_c_10_906|,orf|NCBIACEO_c_5_1142|",
      "orf|NCBIAAYI_c_258|,orf|aot172_c_6_302|,orf|aot180_c_2_405|")

For a: The individual strings can contain even more entries of "sp|" and "orf"

The results have to be like this:

[1] "sp|Q9Y6W5" "sp|Q9HB90,sp|Q9NQL2" "orf|NCBIAAYI_c_1_1023"
   "orf|NCBIACEN_c_10_906,orf|NCBIACEO_c_5_1142"
   "orf|NCBIAAYI_c_258,orf|aot172_c_6_302,orf|aot180_c_2_405"

So the aim is to remove the last "|" for each "sp|" and "orf|" entry. It seems that "|" is a special challenge because it is a metacharacter in regular expressions. Furthermore, the length and composition of the "orf|" entries varying a lot. The only things they have in common is "orf|" or "sp|" at the beginning and that "|" is on the last position. I tried different things with gsub() but also with the stringr package or regexpr() or [:punct:], but nothing really worked. Maybe it was just the wrong combination.

Body:
We can use gsub to match the | that is followed by a , or is at the end ($) of the string and replace with blank ("")

gsub("[|](?=(,|$))", "", a, perl = TRUE)
#[1] "sp|Q9Y6W5"
#[2] "sp|Q9HB90,sp|Q9NQL2"
#[3] "orf|NCBIAAYI_c_1_1023"
#[4] "orf|NCBIACEN_c_10_906,orf|NCBIACEO_c_5_1142"
#[5] "orf|NCBIAAYI_c_258,orf|aot172_c_6_302,orf|aot180_c_2_405"

Or we split by ,', remove the last character withsubstr, andpastethelist` elements together

sapply(strsplit(a, ","), function(x) paste(substr(x, 1, nchar(x)-1), collapse=","))


问:
Reading positional parameters using PHP
I am using a .php page just like a shell script. The only problem is that I do not know how to pass the positional parameters to PHP page.

```<code>#!/usr/bin/php
<?php

$myfile="balexp.xml";
</code>```

The following does not work in this php page and does work in the shell script.

```<code>myvar=$1
</code>```

How do I pass variables to a php page?

答: You pass positional parameters via the $argv convention. See http://php.net/manual/en/features.commandline.usage.php.</p>

ContentLicense: CC BY-SA 2.5

Title: Reading positional parameters using PHP

Body:
I am using a .php page just like a shell script. The only problem is that I do not know how to pass the positional parameters to PHP page.

#!/usr/bin/php
<?php

$myfile="balexp.xml";

The following does not work in this php page and does work in the shell script.

myvar=$1

How do I pass variables to a php page?


问:
Change color of Back button in navigation bar
I am trying to change the color of the Settings button to white, but can't get it to change.

I've tried both of these:

```<code>navigationItem.leftBarButtonItem?.tintColor = UIColor.whiteColor()
navigationItem.backBarButtonItem?.tintColor = UIColor.whiteColor()
</code>```

but no change, it still looks like this:

How do I make that button white?

答:
If you already have the back button in your "Settings" view controller and you want to change the back button color on the "Payment Information" view controller to something else, you can do it inside "Settings" view controller's prepare for segue like this:</p>

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "YourPaymentInformationSegue"
    {
        //Make the back button for "Payment Information" gray:
        self.navigationItem.backBarButtonItem?.tintColor = UIColor.gray
    }
}
</code>```

Body:
I am trying to change the color of the Settings button to white, but can't get it to change.

I've tried both of these:

navigationItem.leftBarButtonItem?.tintColor = UIColor.whiteColor()
navigationItem.backBarButtonItem?.tintColor = UIColor.whiteColor()

but no change, it still looks like this:

How do I make that button white?

Body:
If you already have the back button in your "Settings" view controller and you want to change the back button color on the "Payment Information" view controller to something else, you can do it inside "Settings" view controller's prepare for segue like this:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "YourPaymentInformationSegue"
    {
        //Make the back button for "Payment Information" gray:
        self.navigationItem.backBarButtonItem?.tintColor = UIColor.gray
    }
}


问:
location finder in php with latitude and longitude with google api
I'm trying to get location from google map with the geocode api. But after some usage the api is not working.

Here is the my code, I don't know what is happening, I have changed api_key and tried, there also nothing get from the api

```<code>    function addressPicker($latitude, $longitude){
        /*$latitude = '9.537086';
        $longitude = '76.886407';*/
        $geolocation = $latitude.','.$longitude;

        $API_KEY = 'AIzaSyCV1OstieLoQIssF0tBwB6jYYz_I7w1FRA';
        $request = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='.$geolocation.'&sensor=false&key='.$API_KEY;

        $file_contents = file_get_contents($request);
        $json_decode = json_decode($file_contents);
        $place_name = '';
        if(isset($json_decode->results[0])) {
            $response = array();
            $j = 0;
            foreach($json_decode->results[0]->address_components as $addressComponet) {
                $response2[] = $addressComponet->long_name;

                switch ($json_decode->results[0]->address_components[$j]->types[0]) {
                    case 'street_number':
                        $place_name .= $json_decode->results[0]->address_components[$j]->long_name . ', ';
                        break;
                    case 'route':
                        $place_name .= $json_decode->results[0]->address_components[$j]->long_name . ', ';
                        break;
                    case 'political':
                        $place_name .= $json_decode->results[0]->address_components[$j]->long_name . ', ';
                        break;
                    case 'locality':
                        $place_name .= $json_decode->results[0]->address_components[$j]->long_name . ', ';
                        break;
                }
                $j++;
            }
            return $place_name;
        }
    }
</code>```

答:
Indeed your Google URL is not correct. This URL seems to be good:

https://maps.googleapis.com/maps/api/geocode/json?latlng=9.537086,76.886407&key=AIzaSyCV1OstieLoQIssF0tBwB6jYYz_I7w1FRA

```<code>function addressPicker($latitude, $longitude){
        /*$latitude = '9.537086';
        $longitude = '76.886407';*/
        $geolocation = $latitude.','.$longitude;

        $API_KEY = 'AIzaSyCV1OstieLoQIssF0tBwB6jYYz_I7w1FRA';
        $request = 'https://maps.googleapis.com/maps/api/geocode/json?latlng='.$geolocation.'&sensor=false&key='.$API_KEY;

        $file_contents = file_get_contents($request);
        $json_decode = json_decode($file_contents);
        $place_name = '';
        if(isset($json_decode->results[0])) {
            $response = array();
            $j = 0;
            foreach($json_decode->results[0]->address_components as $addressComponet) {
                $response2[] = $addressComponet->long_name;

                switch ($json_decode->results[0]->address_components[$j]->types[0]) {
                    case 'street_number':
                        $place_name .= $json_decode->results[0]->address_components[$j]->long_name . ', ';
                        break;
                    case 'route':
                        $place_name .= $json_decode->results[0]->address_components[$j]->long_name . ', ';
                        break;
                    case 'political':
                        $place_name .= $json_decode->results[0]->address_components[$j]->long_name . ', ';
                        break;
                    case 'locality':
                        $place_name .= $json_decode->results[0]->address_components[$j]->long_name . ', ';
                        break;
                }
                $j++;
            }
            return $place_name;
        }
    }
</code>```

Body:
I'm trying to get location from google map with the geocode api. But after some usage the api is not working.

Here is the my code, I don't know what is happening, I have changed api_key and tried, there also nothing get from the api

    function addressPicker($latitude, $longitude){
        /*$latitude = '9.537086';
        $longitude = '76.886407';*/
        $geolocation = $latitude.','.$longitude;

        $API_KEY = 'AIzaSyCV1OstieLoQIssF0tBwB6jYYz_I7w1FRA';
        $request = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='.$geolocation.'&sensor=false&key='.$API_KEY;

        $file_contents = file_get_contents($request);
        $json_decode = json_decode($file_contents);
        $place_name = '';
        if(isset($json_decode->results[0])) {
            $response = array();
            $j = 0;
            foreach($json_decode->results[0]->address_components as $addressComponet) {
                $response2[] = $addressComponet->long_name;

                switch ($json_decode->results[0]->address_components[$j]->types[0]) {
                    case 'street_number':
                        $place_name .= $json_decode->results[0]->address_components[$j]->long_name . ', ';
                        break;
                    case 'route':
                        $place_name .= $json_decode->results[0]->address_components[$j]->long_name . ', ';
                        break;
                    case 'political':
                        $place_name .= $json_decode->results[0]->address_components[$j]->long_name . ', ';
                        break;
                    case 'locality':
                        $place_name .= $json_decode->results[0]->address_components[$j]->long_name . ', ';
                        break;
                }
                $j++;
            }
            return $place_name;
        }
    }

Body:
Indeed your Google URL is not correct. This URL seems to be good:

https://maps.googleapis.com/maps/api/geocode/json?latlng=9.537086,76.886407&key=AIzaSyCV1OstieLoQIssF0tBwB6jYYz_I7w1FRA

function addressPicker($latitude, $longitude){
        /*$latitude = '9.537086';
        $longitude = '76.886407';*/
        $geolocation = $latitude.','.$longitude;

        $API_KEY = 'AIzaSyCV1OstieLoQIssF0tBwB6jYYz_I7w1FRA';
        $request = 'https://maps.googleapis.com/maps/api/geocode/json?latlng='.$geolocation.'&sensor=false&key='.$API_KEY;

        $file_contents = file_get_contents($request);
        $json_decode = json_decode($file_contents);
        $place_name = '';
        if(isset($json_decode->results[0])) {
            $response = array();
            $j = 0;
            foreach($json_decode->results[0]->address_components as $addressComponet) {
                $response2[] = $addressComponet->long_name;

                switch ($json_decode->results[0]->address_components[$j]->types[0]) {
                    case 'street_number':
                        $place_name .= $json_decode->results[0]->address_components[$j]->long_name . ', ';
                        break;
                    case 'route':
                        $place_name .= $json_decode->results[0]->address_components[$j]->long_name . ', ';
                        break;
                    case 'political':
                        $place_name .= $json_decode->results[0]->address_components[$j]->long_name . ', ';
                        break;
                    case 'locality':
                        $place_name .= $json_decode->results[0]->address_components[$j]->long_name . ', ';
                        break;
                }
                $j++;
            }
            return $place_name;
        }
    }


问:
Why can't I directly assign an int to an int pointer like this: int *p = 6;?
error: invalid conversion from 'int' to 'int*'

int *q = 8;

Works fine.

*q = 6;

Why can't I directly assign an int to an int pointer like this: int *q = 6; and I can assign it safely in the next line?

答:
Here, assign the value 8 to an object of type int*. It means q points on address 8 on memory.

```<code> int *q = 8;
</code>```

Is equivalent to:

```<code>int *q;
q = 8;
</code>```

Is Not equivalent to:

```<code>int *q;
*q = 8;
</code>```

is illegal, as it involves constraint violation.

Related stack overflow question: Is it possible to initialize a C pointer to NULL?

Body:
Here, assign the value 8 to an object of type int*. It means q points on address 8 on memory.

 int *q = 8;

Is equivalent to:

int *q;
q = 8;

Is Not equivalent to:

int *q;
*q = 8;

is illegal, as it involves constraint violation.

Related stack overflow question: Is it possible to initialize a C pointer to NULL?


问:
Add ONLY checked items from a checklistbox to a listView control
My situation:

I have a populated checklistbox control on Form1.
Then I have a listView control on Form2.

I would like for the user to be able to check items on the checklistbox on Form1, then click on a button on Form1 to open Form2.

Form2 contains the listView control, that I want to populate with only the checked items from checklistbox on Form1.

I tried

```<code>namespace Boodschappenlijst
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

    public static string[] strKruideniersw = new string[] { Boodschappenlijst.producten[0], Boodschappenlijst.producten[1], Boodschappenlijst.producten[2] };
    public static string[] strVerswaren = new string[] { Boodschappenlijst.producten[3], Boodschappenlijst.producten[4], Boodschappenlijst.producten[5] };
    public static string[] strVerzorgingspr = new string[] { Boodschappenlijst.producten[6], Boodschappenlijst.producten[7], Boodschappenlijst.producten[8], Boodschappenlijst.producten[9] };

    public static List<string> kruidenierswList = new List<string>(strKruideniersw);
    public static List<string> verswarenList = new List<string>(strVerswaren);
    public static List<string> verzproductenList = new List<string>(strVerzorgingspr);

    public static string[] strKruidenierswCh;

    public void Form1_Load(object sender, EventArgs e)
    {
        clbKruidenierswaren.Items.AddRange(strKruideniersw);
        clbVerswaren.Items.AddRange(strVerswaren);
        clbVerzproducten.Items.AddRange(strVerzorgingspr);
        strKruidenierswCh = clbKruidenierswaren.CheckedItems;
    }

    // TODO
    // public string kruidenierswChecked = clbKruidenierswaren.CheckedItems;

    private void button1_Click(object sender, EventArgs e)
    {
        // Create a new instance of the Form2 class
        Form2 form2 = new Form2();

        // Show the settings form
        form2.Show();
    }
}

public abstract class Boodschappenlijst : Form1
{
    public static string[] producten = new string[] { "Peper", "Zout", "Kruidnagel", "Sla", "Komkommer", "Tomaten", "Tandpasta", "Shampoo", "Wax", "Deodorant" };

    // Not working.. clbKruidenierswaren is not static.
    List<string> items = clbKruidenierswaren.CheckedItems.Cast<string>().ToList();

    // Make form1 controls accessible for other classes?
    // Form1 form1 = Application.OpenForms.OfType<Form1>().FirstOrDefault();

}
}
</code>```

but the I get the error

A field initializer cannot reference the non-static field, method, or property 'Form1.clbKruidenierswaren'.

Can you please direct me to a solution that works?

答:
```<code>public partial class Form1 : Form
{
    // Todo declare the variables
    private List<string> kruidenierswList;
    private List<string> verswarenList;
    private List<string> verzproductenList;

    public Form1()
    {
        InitializeComponent();

        // call the instance once and add that to the variable lijst
        Boodschappenlijst lijst = Boodschappenlijst.Instance; // <- @ others on S/O this is just used as information I know I could do a new as well.

        // initialize the variables
        kruidenierswList = new List<string>() { lijst.Products[0], lijst.Products[1], lijst.Products[2] };
        verswarenList = new List<string>() { lijst.Products[3], lijst.Products[4], lijst.Products[5] };
        verzproductenList = new List<string>() { lijst.Products[6], lijst.Products[7], lijst.Products[8], lijst.Products[9] };
    }

    public void Form1_Load(object sender, EventArgs e)
    {
        // populate the checklist boxes
        clbKruidenierswaren.Items.AddRange(kruidenierswList.ToArray());
        clbVerswaren.Items.AddRange(verswarenList.ToArray());
        clbVerzproducten.Items.AddRange(verzproductenList.ToArray());
    }

    private void button1_Click(object sender, EventArgs e)
    {
        // Create a new instance of the Form2 class
        Form2 form2 = new Form2();

        // Show the settings form
        form2.Show();
    }
}

public class Boodschappenlijst
{
    private static Boodschappenlijst instance;

    public string[] Products
    {
        get;
        private set;
    }

    private Boodschappenlijst()
    {
        Products = new string[] { "Peper", "Zout", "Kruidnagel", "Sla", "Komkommer", "Tomaten", "Tandpasta", "Shampoo", "Wax", "Deodorant" };
    }

    public static Boodschappenlijst Instance
    {
        get
        {
            // singleton initialization => look for design pattern - singleton  <- Design patterns can brighten your day.
            //
            return instance == null ? instance = new Boodschappenlijst() : instance;
        }
    }
}
</code>```

Body:
My situation:

I have a populated checklistbox control on Form1.
Then I have a listView control on Form2.

I would like for the user to be able to check items on the checklistbox on Form1, then click on a button on Form1 to open Form2.

Form2 contains the listView control, that I want to populate with only the checked items from checklistbox on Form1.

I tried

namespace Boodschappenlijst
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

    public static string[] strKruideniersw = new string[] { Boodschappenlijst.producten[0], Boodschappenlijst.producten[1], Boodschappenlijst.producten[2] };
    public static string[] strVerswaren = new string[] { Boodschappenlijst.producten[3], Boodschappenlijst.producten[4], Boodschappenlijst.producten[5] };
    public static string[] strVerzorgingspr = new string[] { Boodschappenlijst.producten[6], Boodschappenlijst.producten[7], Boodschappenlijst.producten[8], Boodschappenlijst.producten[9] };

    public static List<string> kruidenierswList = new List<string>(strKruideniersw);
    public static List<string> verswarenList = new List<string>(strVerswaren);
    public static List<string> verzproductenList = new List<string>(strVerzorgingspr);

    public static string[] strKruidenierswCh;

    public void Form1_Load(object sender, EventArgs e)
    {
        clbKruidenierswaren.Items.AddRange(strKruideniersw);
        clbVerswaren.Items.AddRange(strVerswaren);
        clbVerzproducten.Items.AddRange(strVerzorgingspr);
        strKruidenierswCh = clbKruidenierswaren.CheckedItems;
    }

    // TODO
    // public string kruidenierswChecked = clbKruidenierswaren.CheckedItems;

    private void button1_Click(object sender, EventArgs e)
    {
        // Create a new instance of the Form2 class
        Form2 form2 = new Form2();

        // Show the settings form
        form2.Show();
    }
}

public abstract class Boodschappenlijst : Form1
{
    public static string[] producten = new string[] { "Peper", "Zout", "Kruidnagel", "Sla", "Komkommer", "Tomaten", "Tandpasta", "Shampoo", "Wax", "Deodorant" };

    // Not working.. clbKruidenierswaren is not static.
    List<string> items = clbKruidenierswaren.CheckedItems.Cast<string>().ToList();

    // Make form1 controls accessible for other classes?
    // Form1 form1 = Application.OpenForms.OfType<Form1>().FirstOrDefault();

}
}

but the I get the error

A field initializer cannot reference the non-static field, method, or property 'Form1.clbKruidenierswaren'.

Can you please direct me to a solution that works?


问:
StreamWriter Only Works on Some Workstations
I have a page on an intraweb (that I didn't create) which allows a user to specify a .txt file and then it writes the results of a SQL stored procedure to the file using StreamWriter.

It apparently stopped working for some of my workstations several months ago, so I can't trace it to any specific changes (However, I know the code itself didn't change).

If I access & use the page on the server (where the wwwroot and applicable database are located), it successfully writes the .txt, whether I specified a local file or on a workstation on the network. Users on some workstations,though, are no longer able to write to a file.
(It is also not just writing a blank file. The "Date Modified" remains unchanged.)

The problem seems to be machine-related rather than user-related, as I can login as the same user on different workstations with different results.

I still think it may have something to do with permissions, so I created a .txt on a problem workstation with every possible account having full permissions, but no luck. Permissions on the database, stored procedure, and folder destination seem correct.

Any suggestions welcome, Thanks.

答:
You mean to tell us that the page completes with success, your calls to StreamWriter all succeed, and yet in the end there is no file? I find that really hard to digest. A much more likely hypothesis is that the page fails and exception is thrown. Such an exception would be logged normally in the system event log.

From the description of your symptoms the issue could be a constrained delegation scenario: the page is impersonating the IE user and it cannot flow the credentials to whe accessing the network resource.


问:
Overlapping border div
i want to create a table just with div tag. I use only two class and it works well.

The only problem is the border of cell inside the table have double width of the table border and it looks ugly. I know the reason is all cell have border around but i can not fix it. I've try some solution in other post but it does not work in this case.

Can some one please help me? Thanks a lot. Note that i don't want to add more class.

.row {
  height: 100%;
  display: flex;
  width: 100%;
  flex-wrap: wrap;
}

.col {
  border: solid 2px blue;
  padding: 5px;
  margin: 0;
  min-height: 1px;
  flex-grow: 1;
  max-width: 100%;
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
  <div class="col">x</div>
  <div class="col">x</div>
</div>
<div class="row">
  <div class="col">x</div>
</div>
<div class="row">
  <div class="col">x</div>
  <div class="col">x</div>
  <div class="col">x</div>
</div>
<div class="row">
  <div class="row">
    <div class="col">x</div>
    <div class="col">x</div>
  </div>
  <div class="row">
    <div class="col">x</div>
    <div class="col">x</div>
  </div>
</div></code>```

答:
You can add CSS to override the border in certain conditions...

.row {
  height: 100%;
  display: flex;
  width: 100%;
  flex-wrap: wrap;
}

.col {
  border: solid 2px blue;
  border-top: none;
  padding: 5px;
  margin: 0;
  min-height: 1px;
  flex-grow: 1;
  max-width: 100%;
  text-align: center;
}

.col+.col {
  border-left: none;
}

.row:first-of-type .col {
  border-top: solid 2px blue;
}

.row .row .col {
  border-top: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
  <div class="col">x</div>
  <div class="col">x</div>
</div>
<div class="row">
  <div class="col">x</div>
</div>
<div class="row">
  <div class="col">x</div>
  <div class="col">x</div>
  <div class="col">x</div>
</div>
<div class="row">
  <div class="row">
    <div class="col">x</div>
    <div class="col">x</div>
  </div>
  <div class="row">
    <div class="col">x</div>
    <div class="col">x</div>
  </div>
</div></code>```

Title: Overlapping border div

Body:
i want to create a table just with div tag. I use only two class and it works well.

The only problem is the border of cell inside the table have double width of the table border and it looks ugly. I know the reason is all cell have border around but i can not fix it. I've try some solution in other post but it does not work in this case.

Can some one please help me? Thanks a lot. Note that i don't want to add more class.

.row {
  height: 100%;
  display: flex;
  width: 100%;
  flex-wrap: wrap;
}

.col {
  border: solid 2px blue;
  padding: 5px;
  margin: 0;
  min-height: 1px;
  flex-grow: 1;
  max-width: 100%;
  text-align: center;
}

x

x

x

x

x

x

x

x

x

x

Body:
You can add CSS to override the border in certain conditions...

.row {
  height: 100%;
  display: flex;
  width: 100%;
  flex-wrap: wrap;
}

.col {
  border: solid 2px blue;
  border-top: none;
  padding: 5px;
  margin: 0;
  min-height: 1px;
  flex-grow: 1;
  max-width: 100%;
  text-align: center;
}

.col+.col {
  border-left: none;
}

.row:first-of-type .col {
  border-top: solid 2px blue;
}

.row .row .col {
  border-top: none;
}

<div class="row">
  <div class="col">x</div>
  <div class="col">x</div>
</div>
<div class="row">
  <div class="col">x</div>
</div>
<div class="row">
  <div class="col">x</div>
  <div class="col">x</div>
  <div class="col">x</div>
</div>
<div class="row">
  <div class="row">
    <div class="col">x</div>
    <div class="col">x</div>
  </div>
  <div class="row">
    <div class="col">x</div>
    <div class="col">x</div>
  </div>
</div>


答:
you can add a class to wrap the content and add some style like:

    .table{
      border: 2px solid blue;
     }
    .row {
      height: 100%;
      display: flex;
      width: 100%;
      flex-wrap: wrap;
    }

    .col {
      border: solid 2px blue;
      padding: 5px;
      margin: 0;
      min-height: 1px;
      flex-grow: 1;
      max-width: 100%;
      text-align: center;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <div class="table">
    <div class="row">
      <div class="col">x</div>
      <div class="col">x</div>
    </div>
    <div class="row">
      <div class="col">x</div>
    </div>
    <div class="row">
      <div class="col">x</div>
      <div class="col">x</div>
      <div class="col">x</div>
    </div>
    <div class="row">
      <div class="row">
        <div class="col">x</div>
        <div class="col">x</div>
      </div>
      <div class="row">
        <div class="col">x</div>
        <div class="col">x</div>
      </div>
    </div>
    </div></code>```

Title: Overlapping border div

Body:
you can add a class to wrap the content and add some style like:

    .table{
      border: 2px solid blue;
     }
    .row {
      height: 100%;
      display: flex;
      width: 100%;
      flex-wrap: wrap;
    }

    .col {
      border: solid 2px blue;
      padding: 5px;
      margin: 0;
      min-height: 1px;
      flex-grow: 1;
      max-width: 100%;
      text-align: center;
    }

    <div class="table">
    <div class="row">
      <div class="col">x</div>
      <div class="col">x</div>
    </div>
    <div class="row">
      <div class="col">x</div>
    </div>
    <div class="row">
      <div class="col">x</div>
      <div class="col">x</div>
      <div class="col">x</div>
    </div>
    <div class="row">
      <div class="row">
        <div class="col">x</div>
        <div class="col">x</div>
      </div>
      <div class="row">
        <div class="col">x</div>
        <div class="col">x</div>
      </div>
    </div>
    </div>


问:
Conditional Spinner
I've one problem. I've created spinner, and everything app runs without crashing, but it won't change value of int price, neither setText doesn't work

```<code>public class MainActivity extends AppCompatActivity implements View.OnClickListener {

Button calculateBtn;
EditText userEcts;
TextView ectsPrice;
TextView summary;
Spinner courses;
String cors;
int price = 200;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    userEcts = (EditText) findViewById(R.id.ects_input);
    summary = (TextView) findViewById(R.id.text_summary);
    courses = (Spinner) findViewById(R.id.course_spinner);

    calculateBtn = (Button) findViewById(R.id.calculate);
    calculateBtn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            //When the button is clicked, call the calculate method.
            calculate();
        }
    });

    final String[] courseArray = new String[4];
    {
        courseArray[0] = "Preddiplomski studij Menadžment";
        courseArray[1] = "Preddiplomski studij Promet";
        courseArray[2] = "Preddiplomski Upravni studij";
        courseArray[3] = "Specijalistički studij Menadžment";
    }

    ArrayAdapter courseAdapter = new ArrayAdapter(this,
            android.R.layout.simple_spinner_item, courseArray);
    courseAdapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice);
    courses.setAdapter(courseAdapter);

    courses.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){

        public void onItemSelected(AdapterView<?> parent,
                                   View view, int pos, long id) {

            //Get item from Spinner and store in string conductorSize........
            cors = parent.getItemAtPosition(pos).toString();
            if (cors.equals(0)) {
                ectsPrice.setText("200");
                price = 200;
            } else if (cors.equals(1)) {
                ectsPrice.setText("250");
                price = 250;
            } else if (cors.equals(2)) {
                ectsPrice.setText("300");
                price = 300;
            } else if (cors.equals(3)) {
                ectsPrice.setText("350");
                price = 350;
            } else {
                //Do nothing
            }
        }

        public void onNothingSelected(AdapterView parent) {
            // Do nothing.
        }
    });
}

public void calculate() {
    //gets entered text from the EditText,and convert to integers.
    if (!TextUtils.isEmpty(userEcts.getText().toString())) {
        Double ects = Double.parseDouble(userEcts.getText().toString());
        //do the calculation
        Double calculatedPrice = ects * price;
        //set the value to the TextView, to display on screen.
        summary.setText("Ukupno za platit: " + Double.toString(calculatedPrice) + "kn");
    } else {
        Toast.makeText(this, "Niste unijeli broj bodova", Toast.LENGTH_SHORT).show();
    }
}

@Override
public void onClick(View v) {
    calculate();
}
</code>```

}

So, on selecting item on position 0, I want to setText to specific text, and change price. Can anyone help?

答:
Use the position number to check the condition.</p>

```<code>String[] courseArray = new String[4];
    {
        courseArray[0] = "Preddiplomski studij Menadžment";
        courseArray[1] = "Preddiplomski studij Promet";
        courseArray[2] = "Preddiplomski Upravni studij";
        courseArray[3] = "Specijalistički studij Menadžment";
    }

    ArrayAdapter courseAdapter = new ArrayAdapter(this,
            android.R.layout.simple_spinner_item, courseArray);
    courseAdapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice);
    courses.setAdapter(courseAdapter);

    courses.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){

        public void onItemSelected(AdapterView<?> parent,
                                   View view, int pos, long id) {

            //Get item from Spinner and store in string conductorSize........
            cors = parent.getItemAtPosition(pos).toString();
            if (cors.equals(courseArray[0])) {
                ectsPrice.setText("200");
                price = 200;
            } else if (cors.equals(courseArray[1])) {
                ectsPrice.setText("250");
                price = 250;
            } else if (cors.equals(courseArray[2])) {
                ectsPrice.setText("300");
                price = 300;
            } else if (cors.equals(courseArray[3])) {
                ectsPrice.setText("350");
                price = 350;
            } else {
                //Do nothing
            }
        }

        public void onNothingSelected(AdapterView parent) {
            // Do nothing.
        }
    });
}
</code>```

Title: Conditional Spinner

Body:
I've one problem. I've created spinner, and everything app runs without crashing, but it won't change value of int price, neither setText doesn't work

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

Button calculateBtn;
EditText userEcts;
TextView ectsPrice;
TextView summary;
Spinner courses;
String cors;
int price = 200;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    userEcts = (EditText) findViewById(R.id.ects_input);
    summary = (TextView) findViewById(R.id.text_summary);
    courses = (Spinner) findViewById(R.id.course_spinner);

    calculateBtn = (Button) findViewById(R.id.calculate);
    calculateBtn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            //When the button is clicked, call the calculate method.
            calculate();
        }
    });

    final String[] courseArray = new String[4];
    {
        courseArray[0] = "Preddiplomski studij Menadžment";
        courseArray[1] = "Preddiplomski studij Promet";
        courseArray[2] = "Preddiplomski Upravni studij";
        courseArray[3] = "Specijalistički studij Menadžment";
    }

    ArrayAdapter courseAdapter = new ArrayAdapter(this,
            android.R.layout.simple_spinner_item, courseArray);
    courseAdapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice);
    courses.setAdapter(courseAdapter);

    courses.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){

        public void onItemSelected(AdapterView<?> parent,
                                   View view, int pos, long id) {

            //Get item from Spinner and store in string conductorSize........
            cors = parent.getItemAtPosition(pos).toString();
            if (cors.equals(0)) {
                ectsPrice.setText("200");
                price = 200;
            } else if (cors.equals(1)) {
                ectsPrice.setText("250");
                price = 250;
            } else if (cors.equals(2)) {
                ectsPrice.setText("300");
                price = 300;
            } else if (cors.equals(3)) {
                ectsPrice.setText("350");
                price = 350;
            } else {
                //Do nothing
            }
        }

        public void onNothingSelected(AdapterView parent) {
            // Do nothing.
        }
    });
}

public void calculate() {
    //gets entered text from the EditText,and convert to integers.
    if (!TextUtils.isEmpty(userEcts.getText().toString())) {
        Double ects = Double.parseDouble(userEcts.getText().toString());
        //do the calculation
        Double calculatedPrice = ects * price;
        //set the value to the TextView, to display on screen.
        summary.setText("Ukupno za platit: " + Double.toString(calculatedPrice) + "kn");
    } else {
        Toast.makeText(this, "Niste unijeli broj bodova", Toast.LENGTH_SHORT).show();
    }
}

@Override
public void onClick(View v) {
    calculate();
}

}

So, on selecting item on position 0, I want to setText to specific text, and change price. Can anyone help?

Body:
Use the position number to check the condition.

String[] courseArray = new String[4];
    {
        courseArray[0] = "Preddiplomski studij Menadžment";
        courseArray[1] = "Preddiplomski studij Promet";
        courseArray[2] = "Preddiplomski Upravni studij";
        courseArray[3] = "Specijalistički studij Menadžment";
    }

    ArrayAdapter courseAdapter = new ArrayAdapter(this,
            android.R.layout.simple_spinner_item, courseArray);
    courseAdapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice);
    courses.setAdapter(courseAdapter);

    courses.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){

        public void onItemSelected(AdapterView<?> parent,
                                   View view, int pos, long id) {

            //Get item from Spinner and store in string conductorSize........
            cors = parent.getItemAtPosition(pos).toString();
            if (cors.equals(courseArray[0])) {
                ectsPrice.setText("200");
                price = 200;
            } else if (cors.equals(courseArray[1])) {
                ectsPrice.setText("250");
                price = 250;
            } else if (cors.equals(courseArray[2])) {
                ectsPrice.setText("300");
                price = 300;
            } else if (cors.equals(courseArray[3])) {
                ectsPrice.setText("350");
                price = 350;
            } else {
                //Do nothing
            }
        }

        public void onNothingSelected(AdapterView parent) {
            // Do nothing.
        }
    });
}


问:
SQL UPDATE not working and no error is thrown
I'm coding a program in Visual studio windows forms, and my SQL UPDATEstatement isn't working, and there are no errors thrown. Here are my codes:

```<code>  string strConnection = ConfigurationManager.ConnectionStrings
         ["Brownie.Properties.Settings.BrownieDB2ConnectionString"].ConnectionString;

        SqlConnection sqlconnect = new SqlConnection(strConnection);

        string strSQL = "UPDATE Cargo SET Jobdone = 'Yes' WHERE (DriverID IN (SELECT DriverID FROM Driver WHERE (CardID = @a)))";

        SqlCommand cmd = new SqlCommand(strSQL, sqlconnect);

        cmd.Parameters.AddWithValue("@a", momentcardid);

        try
        {
            //step 3: open connection
            sqlconnect.Open();
            //step 4: execute command
            int result = cmd.ExecuteNonQuery();

            if (result > 0)
                MessageBox.Show("Job has been successfully updated");
            else
                MessageBox.Show("Job update is unsuccessful");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            //step 5: close connection
            sqlconnect.Close();
        }
</code>```

I tested out this code on the Query Testing function provided by Visual studio under Server Explorer (Right click database > Right click table name > New Query), placed the value momentcardid for testing and it was able to update successfully into the database.

However when I tried to run the codes on winform, it does not update into the database. There is no error thrown as well. It even displays the message box Job has been updated successfully

I'm really not sure what is wrong, I hope someone can help me figure out!

答:
There are two possible things going on here:

the values of @a and CardId simply aren't matching, due to not being quite what you expect; common reasons:

case sensitivity

whitespace

fixed width (char/nchar) vs dynamic width (varchar/nvarchar)

invisible characters (unicode characters or escape characters) in one of the two values

there simply isn't matching data for that value!

it is working, but you're looking in the wrong place

this is common when using file-based databases rather than dedicated servers - you need to be sure to look in the database file in the executing folder (often /bin/debug etc) rather than the source folder

To determine which, you might add select @@rowcount; after the update statement and use var rowsUpdated = cmd.ExecuteScalar. By reading this value, you can see how many rows were updated. If it is zero, then the first bullet applies; if it is non-zero, then the second bullet applies.

Assuming it is the first bullet, you'll need to look very carefully at the value of momentcardid, including any whitespace and hidden characters. momentcardid.Length would be a good place to start, but momentcardid.ToCharArray() would be the next step (and look carefully at every character)

Body:
I'm coding a program in Visual studio windows forms, and my SQL UPDATEstatement isn't working, and there are no errors thrown. Here are my codes:

  string strConnection = ConfigurationManager.ConnectionStrings
         ["Brownie.Properties.Settings.BrownieDB2ConnectionString"].ConnectionString;

        SqlConnection sqlconnect = new SqlConnection(strConnection);

        string strSQL = "UPDATE Cargo SET Jobdone = 'Yes' WHERE (DriverID IN (SELECT DriverID FROM Driver WHERE (CardID = @a)))";

        SqlCommand cmd = new SqlCommand(strSQL, sqlconnect);

        cmd.Parameters.AddWithValue("@a", momentcardid);

        try
        {
            //step 3: open connection
            sqlconnect.Open();
            //step 4: execute command
            int result = cmd.ExecuteNonQuery();

            if (result > 0)
                MessageBox.Show("Job has been successfully updated");
            else
                MessageBox.Show("Job update is unsuccessful");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            //step 5: close connection
            sqlconnect.Close();
        }

I tested out this code on the Query Testing function provided by Visual studio under Server Explorer (Right click database > Right click table name > New Query), placed the value momentcardid for testing and it was able to update successfully into the database.

However when I tried to run the codes on winform, it does not update into the database. There is no error thrown as well. It even displays the message box Job has been updated successfully

I'm really not sure what is wrong, I hope someone can help me figure out!


问:
How to create a copy of a file having length more than 260 characters
How to create a copy of a file having length more than 260 characters including file name using vb.net

When we are trying to create a copy using File.Copy method it throws exception as follows:

"The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters."

Is it possible, then please help...

答: There are tips for shortening the name ... see the section titled "Cause 4: Files exist in paths that are deeper than MAX_PATH characters" at http://support.microsoft.com/?kbid=320081#

OwnerDisplayName: Sugam

LastEditorDisplayName: CodeSlave

OwnerDisplayName: ChrisW


答:
@Midhun Please Use This Code.
i just check in Your Code its Return ERROR:

LIKE  [error_message] => Requests to this API must be over SSL. Load the API with "https://" instead of "http://".

```<code> /*$latitude = '9.537086';
    $longitude = '76.886407';*/
    $geolocation = $latitude.','.$longitude;

    $API_KEY = 'AIzaSyCV1OstieLoQIssF0tBwB6jYYz_I7w1FRA';
    $request = 'https://maps.googleapis.com/maps/api/geocode/json?latlng='.$geolocation.'&sensor=false&key='.$API_KEY;

    $file_contents = file_get_contents($request);
    $json_decode = json_decode($file_contents);
    $place_name = '';
    if(isset($json_decode->results[0])) {
        $response = array();
        $j = 0;
        foreach($json_decode->results[0]->address_components as $addressComponet) {
            $response2[] = $addressComponet->long_name;

            switch ($json_decode->results[0]->address_components[$j]->types[0]) {
                case 'street_number':
                    $place_name .= $json_decode->results[0]->address_components[$j]->long_name . ', ';
                    break;
                case 'route':
                    $place_name .= $json_decode->results[0]->address_components[$j]->long_name . ', ';
                    break;
                case 'political':
                    $place_name .= $json_decode->results[0]->address_components[$j]->long_name . ', ';
                    break;
                case 'locality':
                    $place_name .= $json_decode->results[0]->address_components[$j]->long_name . ', ';
                    break;
            }
            $j++;
        }
        return $place_name;
    }
}
</code>```

So i just set https in https://maps.googleapis.com/maps/api/geocode/json?latlng='.$geolocation.'&sensor=false&key='.$API_KEY;

Title: location finder in php with latitude and longitude with google api

Body:
@Midhun Please Use This Code.
i just check in Your Code its Return ERROR:

LIKE  [error_message] => Requests to this API must be over SSL. Load the API with "https://" instead of "http://".

 /*$latitude = '9.537086';
    $longitude = '76.886407';*/
    $geolocation = $latitude.','.$longitude;

    $API_KEY = 'AIzaSyCV1OstieLoQIssF0tBwB6jYYz_I7w1FRA';
    $request = 'https://maps.googleapis.com/maps/api/geocode/json?latlng='.$geolocation.'&sensor=false&key='.$API_KEY;

    $file_contents = file_get_contents($request);
    $json_decode = json_decode($file_contents);
    $place_name = '';
    if(isset($json_decode->results[0])) {
        $response = array();
        $j = 0;
        foreach($json_decode->results[0]->address_components as $addressComponet) {
            $response2[] = $addressComponet->long_name;

            switch ($json_decode->results[0]->address_components[$j]->types[0]) {
                case 'street_number':
                    $place_name .= $json_decode->results[0]->address_components[$j]->long_name . ', ';
                    break;
                case 'route':
                    $place_name .= $json_decode->results[0]->address_components[$j]->long_name . ', ';
                    break;
                case 'political':
                    $place_name .= $json_decode->results[0]->address_components[$j]->long_name . ', ';
                    break;
                case 'locality':
                    $place_name .= $json_decode->results[0]->address_components[$j]->long_name . ', ';
                    break;
            }
            $j++;
        }
        return $place_name;
    }
}

So i just set https in https://maps.googleapis.com/maps/api/geocode/json?latlng='.$geolocation.'&sensor=false&key='.$API_KEY;


问:
AWS ELB HealthCheck Improvements
All,

We recently had an issue with ELB HealthCheck in covering up a certain use-case or scenario which caused an application impact.

Can anyone suggest a fault-tolerant approach to handle this?

We have a nodeJS app running in a port - 80

We have 3 instances in the Target Group & that is enrolled in ELB.

ELB HealthCheck was configured to hit root path on port 80 and return success if it gets HTTP 200

Recently one of the node had 100% disk filled on application mount and root mount was still having space.

Though the HealthCheck was succeeding as per ELB the server didn't respond for any other services and it was ideally unhealthy. This means that there are some requests that got
succeeded but some of them failed (that was routed to this disk-filled server).

We did received notifications from other monitoring systems on disk filling but due to overwhelming emails & limited resources it got missed out.

Is there any other way we can improvise the HealthCheck strategy to just have these scenarios intimated to AutoScaling Group or ELB
so that we can target these nodes to be removed and replace them automatically?

答:
Rather than just checking that the index.htm page is returning a 200 response, you can configure Elastic Load Balancing to point to a customer Health Check page (eg healthcheck.php).

You could run some code on that page to test the general health of the application (database connectivity, disk space, free memory). If everything checks out OK, return a 200 response. If something is wrong, return a 500 response. This will cause the Load Balancer to treat the instance as Unhealthy and it will stop serving traffic to the instance.

If Auto Scaling is configured to use the ELB Health Check, then Auto Scaling will terminate the unhealthy instance and automatically replace it with a new instance.

Title: AWS ELB HealthCheck Improvements


问:
Android: can´t properly set build.gradle
I have this bulild.gradle

```<code> apply plugin: 'com.android.application'

 android {
compileSdkVersion 23
buildToolsVersion "23.0.2"

defaultConfig {
    applicationId "my.package"
    minSdkVersion 15
    targetSdkVersion 23
    versionCode 2
    versionName "2.0"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

 repositories {
mavenCentral()
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:design:23.1.1'
compile 'me.dm7.barcodescanner:zxing:1.8.4'
compile 'com.google.firebase:firebase-messaging:9.0.0'
compile 'com.squareup.okhttp3:okhttp:3.2.0'
compile files('libs/urlimageviewhelper-1.0.4.jar')
compile 'com.mcxiaoke.volley:library:1.0.19'
compile 'com.squareup.picasso:picasso:2.3.2'
compile 'com.nineoldandroids:library:2.4.0'
compile 'com.daimajia.slider:library:1.1.5@aar'
compile 'com.github.ksoichiro:android-observablescrollview:1.6.0'
compile 'com.makeramen:roundedimageview:2.2.1'
compile 'com.github.JakeWharton:ViewPagerIndicator:2.4.1'
debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5'
releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
compile 'it.sephiroth.android.library.horizontallistview:hlistview:1.2.2'
compile 'com.facebook.android:facebook-android-sdk:[4,5)'

}

apply plugin: 'com.google.gms.google-services'
</code>```

and I am getting this error.

```<code>  Error:(3) Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Borderless.Colored'.
</code>```

Found out that I have to change versions of android support, so I did it

```<code>apply plugin: 'com.android.application'

android {
compileSdkVersion 25
buildToolsVersion "23.0.2"

defaultConfig {
    applicationId "sk.weyou.matej_kosut.sowosk"
    minSdkVersion 15
    targetSdkVersion 23
    versionCode 2
    versionName "2.0"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

repositories {
mavenCentral()
}

 dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:design:25.3.1'
compile 'me.dm7.barcodescanner:zxing:1.8.4'
compile 'com.google.firebase:firebase-messaging:9.0.0'
compile 'com.squareup.okhttp3:okhttp:3.2.0'
compile files('libs/urlimageviewhelper-1.0.4.jar')
compile 'com.mcxiaoke.volley:library:1.0.19'
compile 'com.squareup.picasso:picasso:2.3.2'
compile 'com.nineoldandroids:library:2.4.0'
compile 'com.daimajia.slider:library:1.1.5@aar'
compile 'com.github.ksoichiro:android-observablescrollview:1.6.0'
compile 'com.makeramen:roundedimageview:2.2.1'
compile 'com.github.JakeWharton:ViewPagerIndicator:2.4.1'
debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5'
releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
compile 'it.sephiroth.android.library.horizontallistview:hlistview:1.2.2'
compile 'com.facebook.android:facebook-android-sdk:[4,5)'

 }

  apply plugin: 'com.google.gms.google-services'
</code>```

and now I am getting another error

```<code>FATAL EXCEPTION: main
                                                                         Process: sk.weyou.matej_kosut.sowosk, PID: 14788
                                                                         java.lang.IllegalAccessError: Method 'void android.support.v4.content.ContextCompat.<init>()' is inaccessible to class 'com.google.firebase.iid.zzg' (declaration of 'com.google.firebase.iid.zzg' appears in /data/app/sk.weyou.matej_kosut.sowosk-1/base.apk)
                                                                             at com.google.firebase.iid.zzg.zzeC(Unknown Source)
                                                                             at com.google.firebase.iid.zzg.<init>(Unknown Source)
                                                                             at com.google.firebase.iid.zzg.<init>(Unknown Source)
                                                                             at com.google.firebase.iid.zzd.zzb(Unknown Source)
                                                                             at com.google.firebase.iid.FirebaseInstanceId.getInstance(Unknown Source)
                                                                             at com.google.firebase.iid.FirebaseInstanceId.getInstance(Unknown Source)
                                                                             at com.google.firebase.messaging.FirebaseMessaging.getInstance(Unknown Source)
                                                                             at sk.weyou.matej_kosut.sowosk.login_reg.LoginService.onPostExecute(LoginService.java:148)
                                                                             at sk.weyou.matej_kosut.sowosk.login_reg.LoginService.onPostExecute(LoginService.java:37)
                                                                             at android.os.AsyncTask.finish(AsyncTask.java:632)
                                                                             at android.os.AsyncTask.access$600(AsyncTask.java:177)
                                                                             at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
                                                                             at android.os.Handler.dispatchMessage(Handler.java:111)
                                                                             at android.os.Looper.loop(Looper.java:194)
                                                                             at android.app.ActivityThread.main(ActivityThread.java:5550)
                                                                             at java.lang.reflect.Method.invoke(Native Method)
                                                                             at java.lang.reflect.Method.invoke(Method.java:372)
                                                                             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:955)
                                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:750)
</code>```

when using firebase at line

```<code> FirebaseMessaging.getInstance().subscribeToTopic(" ");
</code>```

which probably want those old versions back, I guess.

Or what am I supposed to change? I am trying to figure it out from monday.

答:
Your compile SDK version must match the support library , try this
change

```<code>buildToolsVersion "23.0.2"
</code>```

to

```<code>buildToolsVersion "25.0.2"
</code>```

Body:
I have this bulild.gradle

 apply plugin: 'com.android.application'

 android {
compileSdkVersion 23
buildToolsVersion "23.0.2"

defaultConfig {
    applicationId "my.package"
    minSdkVersion 15
    targetSdkVersion 23
    versionCode 2
    versionName "2.0"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

 repositories {
mavenCentral()
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:design:23.1.1'
compile 'me.dm7.barcodescanner:zxing:1.8.4'
compile 'com.google.firebase:firebase-messaging:9.0.0'
compile 'com.squareup.okhttp3:okhttp:3.2.0'
compile files('libs/urlimageviewhelper-1.0.4.jar')
compile 'com.mcxiaoke.volley:library:1.0.19'
compile 'com.squareup.picasso:picasso:2.3.2'
compile 'com.nineoldandroids:library:2.4.0'
compile 'com.daimajia.slider:library:1.1.5@aar'
compile 'com.github.ksoichiro:android-observablescrollview:1.6.0'
compile 'com.makeramen:roundedimageview:2.2.1'
compile 'com.github.JakeWharton:ViewPagerIndicator:2.4.1'
debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5'
releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
compile 'it.sephiroth.android.library.horizontallistview:hlistview:1.2.2'
compile 'com.facebook.android:facebook-android-sdk:[4,5)'

}

apply plugin: 'com.google.gms.google-services'

and I am getting this error.

  Error:(3) Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Borderless.Colored'.

Found out that I have to change versions of android support, so I did it

apply plugin: 'com.android.application'

android {
compileSdkVersion 25
buildToolsVersion "23.0.2"

defaultConfig {
    applicationId "sk.weyou.matej_kosut.sowosk"
    minSdkVersion 15
    targetSdkVersion 23
    versionCode 2
    versionName "2.0"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

repositories {
mavenCentral()
}

 dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:design:25.3.1'
compile 'me.dm7.barcodescanner:zxing:1.8.4'
compile 'com.google.firebase:firebase-messaging:9.0.0'
compile 'com.squareup.okhttp3:okhttp:3.2.0'
compile files('libs/urlimageviewhelper-1.0.4.jar')
compile 'com.mcxiaoke.volley:library:1.0.19'
compile 'com.squareup.picasso:picasso:2.3.2'
compile 'com.nineoldandroids:library:2.4.0'
compile 'com.daimajia.slider:library:1.1.5@aar'
compile 'com.github.ksoichiro:android-observablescrollview:1.6.0'
compile 'com.makeramen:roundedimageview:2.2.1'
compile 'com.github.JakeWharton:ViewPagerIndicator:2.4.1'
debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5'
releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
compile 'it.sephiroth.android.library.horizontallistview:hlistview:1.2.2'
compile 'com.facebook.android:facebook-android-sdk:[4,5)'

 }

  apply plugin: 'com.google.gms.google-services'

and now I am getting another error

FATAL EXCEPTION: main
                                                                         Process: sk.weyou.matej_kosut.sowosk, PID: 14788
                                                                         java.lang.IllegalAccessError: Method 'void android.support.v4.content.ContextCompat.<init>()' is inaccessible to class 'com.google.firebase.iid.zzg' (declaration of 'com.google.firebase.iid.zzg' appears in /data/app/sk.weyou.matej_kosut.sowosk-1/base.apk)
                                                                             at com.google.firebase.iid.zzg.zzeC(Unknown Source)
                                                                             at com.google.firebase.iid.zzg.<init>(Unknown Source)
                                                                             at com.google.firebase.iid.zzg.<init>(Unknown Source)
                                                                             at com.google.firebase.iid.zzd.zzb(Unknown Source)
                                                                             at com.google.firebase.iid.FirebaseInstanceId.getInstance(Unknown Source)
                                                                             at com.google.firebase.iid.FirebaseInstanceId.getInstance(Unknown Source)
                                                                             at com.google.firebase.messaging.FirebaseMessaging.getInstance(Unknown Source)
                                                                             at sk.weyou.matej_kosut.sowosk.login_reg.LoginService.onPostExecute(LoginService.java:148)
                                                                             at sk.weyou.matej_kosut.sowosk.login_reg.LoginService.onPostExecute(LoginService.java:37)
                                                                             at android.os.AsyncTask.finish(AsyncTask.java:632)
                                                                             at android.os.AsyncTask.access$600(AsyncTask.java:177)
                                                                             at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
                                                                             at android.os.Handler.dispatchMessage(Handler.java:111)
                                                                             at android.os.Looper.loop(Looper.java:194)
                                                                             at android.app.ActivityThread.main(ActivityThread.java:5550)
                                                                             at java.lang.reflect.Method.invoke(Native Method)
                                                                             at java.lang.reflect.Method.invoke(Method.java:372)
                                                                             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:955)
                                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:750)

when using firebase at line

 FirebaseMessaging.getInstance().subscribeToTopic(" ");

which probably want those old versions back, I guess.

Or what am I supposed to change? I am trying to figure it out from monday.

Body:
Your compile SDK version must match the support library , try this
change

buildToolsVersion "23.0.2"

to

buildToolsVersion "25.0.2"


问:
How to determine postback with javascript and asp.net mvc?
I am currently using ASP.NET MVC2 and I have a ActionController that allows me to save only if the form content is valid, something like

```<code>public ActionResult Edit(Guid id)
{
    //....
    return View();
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Guid id, DTOUserEdit dto)
{
    if ( ModelState.IsValid) Save(user);
    return ModelState.IsValid ? RedirectToAction("Index") : (ActionResult)View(dto);
}
</code>```

This occasion that, if I'm completing incorrectly the editing form it shows again repeatedly.

My question is if I can trust in the following piece of javascript code to determine whether a call is a PostBack, in other words if it helps me to know it's not the first time that I'm visiting that page. I read somewhere that I should not trust in document.referrer because some proxies delete it, then what code should I use?

```<code>function isPostBack() {
    if (document.referrer != null && document.referrer == window.location.href)
        return true;
    return false;
}
</code>```

答:
This code could be easily hacked by malicious user or Javascript could be disabled at all.

I don't know exactly your requirements, but I would probably prefer server side check during view rendering. So instead of

```<code><script type="text/javascript">
    if (isPostBack())
    {
        alert("Check your data!");
    }
</script>
</code>```

I would use

```<code><%
    if (Request.HttpMethod == "POST")
    {
%>
    <script type="text/javascript">
        alert("Check your data!");
    </script>
<%
    }
%>
</code>```

Body:
I am currently using ASP.NET MVC2 and I have a ActionController that allows me to save only if the form content is valid, something like

public ActionResult Edit(Guid id)
{
    //....
    return View();
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Guid id, DTOUserEdit dto)
{
    if ( ModelState.IsValid) Save(user);
    return ModelState.IsValid ? RedirectToAction("Index") : (ActionResult)View(dto);
}

This occasion that, if I'm completing incorrectly the editing form it shows again repeatedly.

My question is if I can trust in the following piece of javascript code to determine whether a call is a PostBack, in other words if it helps me to know it's not the first time that I'm visiting that page. I read somewhere that I should not trust in document.referrer because some proxies delete it, then what code should I use?

function isPostBack() {
    if (document.referrer != null && document.referrer == window.location.href)
        return true;
    return false;
}

Body:
This code could be easily hacked by malicious user or Javascript could be disabled at all.

I don't know exactly your requirements, but I would probably prefer server side check during view rendering. So instead of

<script type="text/javascript">
    if (isPostBack())
    {
        alert("Check your data!");
    }
</script>

I would use

<%
    if (Request.HttpMethod == "POST")
    {
%>
    <script type="text/javascript">
        alert("Check your data!");
    </script>
<%
    }
%>


问:
Split text into two sentences in C#
I want to divide a text into sentences.the sentence contains whitespace characters

For example:

```<code>Orginal sentence: 100 10 20 13
the result:
first sentence:100 10 20
second sentence:13
</code>```

I tried split but the result was :

```<code>first:100
second:10
third:20
fourth:13
</code>```

How can I do that?

答:
You want all before the last space and the rest? You can use String.LastIndexOf and Substring:

```<code>string text = "100 10 20 13";
string firstPart = text;
string lastPart;

int lastSpaceIndex =  text.LastIndexOf(' ');
if(lastSpaceIndex >= 0)
{
    firstPart = text.Substring(0, lastSpaceIndex);
    lastPart = text.Substring(lastSpaceIndex).TrimStart();
}
</code>```

Title: Split text into two sentences in C#

Body:
I want to divide a text into sentences.the sentence contains whitespace characters

For example:

Orginal sentence: 100 10 20 13
the result:
first sentence:100 10 20
second sentence:13

I tried split but the result was :

first:100
second:10
third:20
fourth:13

How can I do that?

Body:
You want all before the last space and the rest? You can use String.LastIndexOf and Substring:

string text = "100 10 20 13";
string firstPart = text;
string lastPart;

int lastSpaceIndex =  text.LastIndexOf(' ');
if(lastSpaceIndex >= 0)
{
    firstPart = text.Substring(0, lastSpaceIndex);
    lastPart = text.Substring(lastSpaceIndex).TrimStart();
}


问:
Recent methods for finding semantic similarity between two short sentences or articles (on a concept level)
I'm working on finding similarities between short sentences and articles. I used many existing methods such as tf-idf, word2vec etc but the results are just okay. The most relevant measure which I found was word moving distance, however, its results are not that better than the other measures. I know it's a challenging problem, however, I am wondering if there are any new methods to find an approximate similarity more on a higher or concept level than just matching words.  Especially, any alternative new methods like word moving distance which looks at slightly higher semantic of a sentence or article?</p>

答:
To be honest the best thing I know to use for this at the moment is AMR:

About AMR here: https://amr.isi.edu/

Documentation here: https://github.com/amrisi/amr-guidelines/blob/master/amr.md

You can use a system like JAMR (see here: https://github.com/jflanigan/jamr) to generate AMRs for your sentence and then you can use Smatch (see here: https://amr.isi.edu/eval/smatch/tutorial.html) to compare the similarity of the two generated AMRs.

What you are trying to do is very difficult and is an active ongoing area of research.