Programs & Examples On #Remote forms

How to find char in string and get all the indexes?

x = "abcdabcdabcd"
print(x)
l = -1
while True:
    l = x.find("a", l+1)
    if l == -1:
        break
    print(l)

How to set margin of ImageView using code, not xml

If you want to change imageview margin but leave all other margins intact.

  1. Get MarginLayoutParameters of your image view in this case: myImageView

     MarginLayoutParams marginParams = (MarginLayoutParams) myImageView.getLayoutParams();
    
  2. Now just change the margin you want to change but leave the others as they are:

     marginParams.setMargins(marginParams.leftMargin, 
                             marginParams.topMargin, 
                             150, //notice only changing right margin
                             marginParams.bottomMargin); 
    

SSIS expression: convert date to string

@[User::path] ="MDS/Material/"+(DT_STR, 4, 1252) DATEPART("yy" , GETDATE())+ "/" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("mm" , GETDATE()), 2) + "/" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("dd" , GETDATE()), 2)

Passing on command line arguments to runnable JAR

You can also set a Java property, i.e. environment variable, on the command line and easily use it anywhere in your code.

The command line would be done this way:

c:/> java -jar -Dmyvar=enwiki-20111007-pages-articles.xml wiki2txt

and the java code accesses the value like this:

String context = System.getProperty("myvar"); 

See this question about argument passing in Java.

Where is JAVA_HOME on macOS Mojave (10.14) to Lion (10.7)?

For Mac OS X 10.9 I installed the latest version of JRE from Oracle and then reset the JAVA_HOME to /Library/Java/JavaVirtualMachines/jdk1.7.0_45.jdk/Contents/Home.

I am sure there is a better way but got me up and running.

hughsmac:~ hbrien$ echo $JAVA_HOME /Library/Java/JavaVirtualMachines/jdk1.7.0_45.jdk/Contents/Home

How to create a checkbox with a clickable label?

<label for="my_checkbox">Check me</label>
<input type="checkbox" name="my_checkbox" value="Car" />

Why does javascript map function return undefined?

var arr = ['a','b',1];
 var results = arr.filter(function(item){
                if(typeof item ==='string'){return item;}  
               });

Node.js version on the command line? (not the REPL)

open node.js command prompt
run this command

node -v

What operator is <> in VBA

It is the "not equal" operator, i.e. the equivalent of != in pretty much every other language.

JavaScript backslash (\) in variables is causing an error

You may want to try the following, which is more or less the standard way to escape user input:

function stringEscape(s) {
    return s ? s.replace(/\\/g,'\\\\').replace(/\n/g,'\\n').replace(/\t/g,'\\t').replace(/\v/g,'\\v').replace(/'/g,"\\'").replace(/"/g,'\\"').replace(/[\x00-\x1F\x80-\x9F]/g,hex) : s;
    function hex(c) { var v = '0'+c.charCodeAt(0).toString(16); return '\\x'+v.substr(v.length-2); }
}

This replaces all backslashes with an escaped backslash, and then proceeds to escape other non-printable characters to their escaped form. It also escapes single and double quotes, so you can use the output as a string constructor even in eval (which is a bad idea by itself, considering that you are using user input). But in any case, it should do the job you want.

How to fill color in a cell in VBA?

  1. Select all cells by left-top corner
  2. Choose [Home] >> [Conditional Formatting] >> [New Rule]
  3. Choose [Format only cells that contain]
  4. In [Format only cells with:], choose "Errors"
  5. Choose proper formats in [Format..] button

Parse String to Date with Different Format in Java

Simple way to format a date and convert into string

    Date date= new Date();

    String dateStr=String.format("%td/%tm/%tY", date,date,date);

    System.out.println("Date with format of dd/mm/dd: "+dateStr);

output:Date with format of dd/mm/dd: 21/10/2015

Escape Character in SQL Server

Escaping quotes in MSSQL is done by a double quote, so a '' or a "" will produce one escaped ' and ", respectively.

How can I replace every occurrence of a String in a file with PowerShell?

Use (V3 version):

(Get-Content c:\temp\test.txt).replace('[MYID]', 'MyValue') | Set-Content c:\temp\test.txt

Or for V2:

(Get-Content c:\temp\test.txt) -replace '\[MYID\]', 'MyValue' | Set-Content c:\temp\test.txt

Difference between id and name attributes in HTML

The id will give an element a id, so once you write real code, (like JavaScript) you can use the id to read elements. The name is just a name so the user can see the name of the element, I guess.

Example:

<h1 id="heading">text</h1>
<script>
  document.getElementById("heading"); //Reads the element that has the id "heading".
</script>
//You can also use something like this:
document.getElementById("heading").value; //Reads the value of the selected element.

Is it helpful? Let me know if there is some problems.

Go to first line in a file in vim?

In command mode (press Esc if you are not sure) you can use:

  • gg,
  • :1,
  • 1G,
  • or 1gg.

Access parent DataContext from DataTemplate

You can use RelativeSource to find the parent element, like this -

Binding="{Binding Path=DataContext.CurveSpeedMustBeSpecified, 
RelativeSource={RelativeSource AncestorType={x:Type local:YourParentElementType}}}"

See this SO question for more details about RelativeSource.

Generate Java classes from .XSD files...?

Talking about JAXB limitation, a solution when having the same name for different attributes is adding inline jaxb customizations to the xsd:

+

. . binding declarations . .

or external customizations...

You can see further informations on : http://jaxb.java.net/tutorial/section_5_3-Overriding-Names.html

How do you put an image file in a json object?

The JSON format can contain only those types of value:

  • string
  • number
  • object
  • array
  • true
  • false
  • null

An image is of the type "binary" which is none of those. So you can't directly insert an image into JSON. What you can do is convert the image to a textual representation which can then be used as a normal string.

The most common way to achieve that is with what's called base64. Basically, instead of encoding it as 1 and 0s, it uses a range of 64 characters which makes the textual representation of it more compact. So for example the number '64' in binary is represented as 1000000, while in base64 it's simply one character: =.

There are many ways to encode your image in base64 depending on if you want to do it in the browser or not.

Note that if you're developing a web application, it will be way more efficient to store images separately in binary form, and store paths to those images in your JSON or elsewhere. That also allows your client's browser to cache the images.

How to search for file names in Visual Studio?

The best option now is to install Microsoft Visual Studio add on called Productivity Power Tools (VS 2010 version, VS 2013 version).

With this comes "Solution Navigator" (alternative to Solution Explorer, with a lot of benefits).

search solution navigator

BTW, this feature is built-in into Visual Studio 2012.

I lose my data when the container exits

a brilliant answer here How to continue a docker which is exited from user kgs

docker start $(docker ps -a -q --filter "status=exited")
(or in this case just docker start $(docker ps -ql) 'cos you don't want to start all of them)

docker exec -it <container-id> /bin/bash

That second line is crucial. So exec is used in place of run, and not on an image but on a containerid. And you do it after the container has been started.

What is the proper REST response code for a valid request but an empty data?

What the existing answers do not elaborate on is that it makes a difference whether you use path parameters or query parameters.

  • In case of path parameters, the parameter is part of the resource path. In case of /users/9, the response should be 404 because that resource was not found. /users/9 is the resource, and the result is unary, or an error, it doesn't exist. This is not a monad.
  • In case of query parameters, the parameter is not part of the resource path. In case of /users?id=9, the response should be 204 because the resource /users was found but it could not return any data. The resource /users exists and the result is n-ary, it exists even if it is empty. If id is unique, this is a monad.

Whether to use path parameters or query parameters depends on the use case. I prefer path parameters for mandatory, normative, or identifying arguments and query parameters for optional, non-normative, or attributing arguments (like paging, collation locale and stuff). In a REST API, I would use /users/9 not /users?id=9 especially because of the possible nesting to get "child records" like /users/9/ssh-keys/0 to get the first public ssh key or /users/9/address/2 to get the third postal address.

I prefer using 404. Here's why:

  • Calls for unary (1 result) and n-ary (n results) methods should not vary for no good reason. I like to have the same response codes if possible. The number of expected results is of course a difference, say, you expect the body to be an object (unary) or an array of objects (n-ary).
  • For n-ary, I would return an array, and in case there are not results, I would not return no set (no document), I would return an empty set (empty document, like empty array in JSON or empty element in XML). That is, it's still 200 but with zero records. There's no reason to put this information on the wire other than in the body.
  • 204 is like a void method. I would not use it for GET, only for POST, PUT, and DELETE. I make an exception in case of GET where the identifiers are query parameters not path parameters.
  • Not finding the record is like NoSuchElementException, ArrayIndexOutOfBoundsException or something like that, caused by the client using an id that doesn't exist, so, it's a client error.
  • From a code perspective, getting 204 means an additional branch in the code that could be avoided. It complicates client code, and in some cases it also complicates server code (depending on whether you use entity/model monads or plain entities/models; and I strongly recommend staying away from entity/model monads, it can lead to nasty bugs where because of the monad you think an operation is successful and return 200 or 204 when you should actually have returned something else).
  • Client code is easier to write and understand if 2xx means the server did what the client requested, and 4xx means the server didn't do what the client requested and it's the client's fault. Not giving the client the record that the client requested by id is the client's fault, because the client requested an id that doesn't exist.

Last but not least: Consistency

  • GET /users/9
  • PUT /users/9 and DELETE /users/9

PUT /users/9 and DELETE /users/9 already have to return 204 in case of successful update or deletion. So what should they return in case user 9 didn't exist? It makes no sense having the same situation presented as different status codes depending on the HTTP method used.

Besides, not a normative, but a cultural reason: If 204 is used for GET /users/9 next thing that will happen in the project is that somebody thinks returning 204 is good for n-ary methods. And that complicates client code, because instead of just checking for 2xx and then decoding the body, the client now has to specifically check for 204 and in that case skip decoding the body. Bud what does the client do instead? Create an empty array? Why not have that on the wire, then? If the client creates the empty array, 204 is a form of stupid compression. If the client uses null instead, a whole different can of worms is opened.

Link entire table row?

Use the ::before pseudo element. This way only you don't have to deal with Javascript or creating links for each cell. Using the following table structure

<table>
  <tr>
    <td><a href="http://domain.tld" class="rowlink">Cell</a></td>
    <td>Cell</td>
    <td>Cell</td>
  </tr>
</table>

all we have to do is create a block element spanning the entire width of the table using ::before on the desired link (.rowlink) in this case.

table {
  position: relative;
}

.rowlink::before {
  content: "";
  display: block;
  position: absolute;
  left: 0;
  width: 100%;
  height: 1.5em; /* don't forget to set the height! */
}

demo

The ::before is highlighted in red in the demo so you can see what it's doing.

What is the "Upgrade-Insecure-Requests" HTTP header?

This explains the whole thing:

The HTTP Content-Security-Policy (CSP) upgrade-insecure-requests directive instructs user agents to treat all of a site's insecure URLs (those served over HTTP) as though they have been replaced with secure URLs (those served over HTTPS). This directive is intended for web sites with large numbers of insecure legacy URLs that need to be rewritten.

The upgrade-insecure-requests directive is evaluated before block-all-mixed-content and if it is set, the latter is effectively a no-op. It is recommended to set one directive or the other, but not both.

The upgrade-insecure-requests directive will not ensure that users visiting your site via links on third-party sites will be upgraded to HTTPS for the top-level navigation and thus does not replace the Strict-Transport-Security (HSTS) header, which should still be set with an appropriate max-age to ensure that users are not subject to SSL stripping attacks.

Source: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/upgrade-insecure-requests

orderBy multiple fields in Angular

If you wants to sort on mulitple fields inside controller use this

$filter('orderBy')($scope.property_list, ['firstProp', 'secondProp']);

See also https://docs.angularjs.org/api/ng/filter/orderBy

Rails 3.1 and Image Assets

In rails 4 you can now use a css and sass helper image-url:

div.logo {background-image: image-url("logo.png");}

If your background images aren't showing up consider looking at how you're referencing them in your stylesheets.

How to capitalize the first character of each word in a string

This is just another way of doing it:

private String capitalize(String line)
{
    StringTokenizer token =new StringTokenizer(line);
    String CapLine="";
    while(token.hasMoreTokens())
    {
        String tok = token.nextToken().toString();
        CapLine += Character.toUpperCase(tok.charAt(0))+ tok.substring(1)+" ";        
    }
    return CapLine.substring(0,CapLine.length()-1);
}

How to convert a factor to integer\numeric without loss of information?

Note: this particular answer is not for converting numeric-valued factors to numerics, it is for converting categorical factors to their corresponding level numbers.


Every answer in this post failed to generate results for me , NAs were getting generated.

y2<-factor(c("A","B","C","D","A")); 
as.numeric(levels(y2))[y2] 
[1] NA NA NA NA NA Warning message: NAs introduced by coercion

What worked for me is this -

as.integer(y2)
# [1] 1 2 3 4 1

How unique is UUID?

Here's a testing snippet for you to test it's uniquenes. inspired by @scalabl3's comment

Funny thing is, you could generate 2 in a row that were identical, of course at mind-boggling levels of coincidence, luck and divine intervention, yet despite the unfathomable odds, it's still possible! :D Yes, it won't happen. just saying for the amusement of thinking about that moment when you created a duplicate! Screenshot video! – scalabl3 Oct 20 '15 at 19:11

If you feel lucky, check the checkbox, it only checks the currently generated id's. If you wish a history check, leave it unchecked. Please note, you might run out of ram at some point if you leave it unchecked. I tried to make it cpu friendly so you can abort quickly when needed, just hit the run snippet button again or leave the page.

_x000D_
_x000D_
Math.log2 = Math.log2 || function(n){ return Math.log(n) / Math.log(2); }_x000D_
  Math.trueRandom = (function() {_x000D_
  var crypt = window.crypto || window.msCrypto;_x000D_
_x000D_
  if (crypt && crypt.getRandomValues) {_x000D_
      // if we have a crypto library, use it_x000D_
      var random = function(min, max) {_x000D_
          var rval = 0;_x000D_
          var range = max - min;_x000D_
          if (range < 2) {_x000D_
              return min;_x000D_
          }_x000D_
_x000D_
          var bits_needed = Math.ceil(Math.log2(range));_x000D_
          if (bits_needed > 53) {_x000D_
            throw new Exception("We cannot generate numbers larger than 53 bits.");_x000D_
          }_x000D_
          var bytes_needed = Math.ceil(bits_needed / 8);_x000D_
          var mask = Math.pow(2, bits_needed) - 1;_x000D_
          // 7776 -> (2^13 = 8192) -1 == 8191 or 0x00001111 11111111_x000D_
_x000D_
          // Create byte array and fill with N random numbers_x000D_
          var byteArray = new Uint8Array(bytes_needed);_x000D_
          crypt.getRandomValues(byteArray);_x000D_
_x000D_
          var p = (bytes_needed - 1) * 8;_x000D_
          for(var i = 0; i < bytes_needed; i++ ) {_x000D_
              rval += byteArray[i] * Math.pow(2, p);_x000D_
              p -= 8;_x000D_
          }_x000D_
_x000D_
          // Use & to apply the mask and reduce the number of recursive lookups_x000D_
          rval = rval & mask;_x000D_
_x000D_
          if (rval >= range) {_x000D_
              // Integer out of acceptable range_x000D_
              return random(min, max);_x000D_
          }_x000D_
          // Return an integer that falls within the range_x000D_
          return min + rval;_x000D_
      }_x000D_
      return function() {_x000D_
          var r = random(0, 1000000000) / 1000000000;_x000D_
          return r;_x000D_
      };_x000D_
  } else {_x000D_
      // From http://baagoe.com/en/RandomMusings/javascript/_x000D_
      // Johannes Baagøe <[email protected]>, 2010_x000D_
      function Mash() {_x000D_
          var n = 0xefc8249d;_x000D_
_x000D_
          var mash = function(data) {_x000D_
              data = data.toString();_x000D_
              for (var i = 0; i < data.length; i++) {_x000D_
                  n += data.charCodeAt(i);_x000D_
                  var h = 0.02519603282416938 * n;_x000D_
                  n = h >>> 0;_x000D_
                  h -= n;_x000D_
                  h *= n;_x000D_
                  n = h >>> 0;_x000D_
                  h -= n;_x000D_
                  n += h * 0x100000000; // 2^32_x000D_
              }_x000D_
              return (n >>> 0) * 2.3283064365386963e-10; // 2^-32_x000D_
          };_x000D_
_x000D_
          mash.version = 'Mash 0.9';_x000D_
          return mash;_x000D_
      }_x000D_
_x000D_
      // From http://baagoe.com/en/RandomMusings/javascript/_x000D_
      function Alea() {_x000D_
          return (function(args) {_x000D_
              // Johannes Baagøe <[email protected]>, 2010_x000D_
              var s0 = 0;_x000D_
              var s1 = 0;_x000D_
              var s2 = 0;_x000D_
              var c = 1;_x000D_
_x000D_
              if (args.length == 0) {_x000D_
                  args = [+new Date()];_x000D_
              }_x000D_
              var mash = Mash();_x000D_
              s0 = mash(' ');_x000D_
              s1 = mash(' ');_x000D_
              s2 = mash(' ');_x000D_
_x000D_
              for (var i = 0; i < args.length; i++) {_x000D_
                  s0 -= mash(args[i]);_x000D_
                  if (s0 < 0) {_x000D_
                      s0 += 1;_x000D_
                  }_x000D_
                  s1 -= mash(args[i]);_x000D_
                  if (s1 < 0) {_x000D_
                      s1 += 1;_x000D_
                  }_x000D_
                  s2 -= mash(args[i]);_x000D_
                  if (s2 < 0) {_x000D_
                      s2 += 1;_x000D_
                  }_x000D_
              }_x000D_
              mash = null;_x000D_
_x000D_
              var random = function() {_x000D_
                  var t = 2091639 * s0 + c * 2.3283064365386963e-10; // 2^-32_x000D_
                  s0 = s1;_x000D_
                  s1 = s2;_x000D_
                  return s2 = t - (c = t | 0);_x000D_
              };_x000D_
              random.uint32 = function() {_x000D_
                  return random() * 0x100000000; // 2^32_x000D_
              };_x000D_
              random.fract53 = function() {_x000D_
                  return random() +_x000D_
                      (random() * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53_x000D_
              };_x000D_
              random.version = 'Alea 0.9';_x000D_
              random.args = args;_x000D_
              return random;_x000D_
_x000D_
          }(Array.prototype.slice.call(arguments)));_x000D_
      };_x000D_
      return Alea();_x000D_
  }_x000D_
}());_x000D_
_x000D_
Math.guid = function() {_x000D_
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c)    {_x000D_
      var r = Math.trueRandom() * 16 | 0,_x000D_
          v = c == 'x' ? r : (r & 0x3 | 0x8);_x000D_
      return v.toString(16);_x000D_
  });_x000D_
};_x000D_
function logit(item1, item2) {_x000D_
    console.log("Do "+item1+" and "+item2+" equal? "+(item1 == item2 ? "OMG! take a screenshot and you'll be epic on the world of cryptography, buy a lottery ticket now!":"No they do not. shame. no fame")+ ", runs: "+window.numberofRuns);_x000D_
}_x000D_
numberofRuns = 0;_x000D_
function test() {_x000D_
   window.numberofRuns++;_x000D_
   var x = Math.guid();_x000D_
   var y = Math.guid();_x000D_
   var test = x == y || historyTest(x,y);_x000D_
_x000D_
   logit(x,y);_x000D_
   return test;_x000D_
_x000D_
}_x000D_
historyArr = [];_x000D_
historyCount = 0;_x000D_
function historyTest(item1, item2) {_x000D_
    if(window.luckyDog) {_x000D_
       return false;_x000D_
    }_x000D_
    for(var i = historyCount; i > -1; i--) {_x000D_
        logit(item1,window.historyArr[i]);_x000D_
        if(item1 == history[i]) {_x000D_
            _x000D_
            return true;_x000D_
        }_x000D_
        logit(item2,window.historyArr[i]);_x000D_
        if(item2 == history[i]) {_x000D_
            _x000D_
            return true;_x000D_
        }_x000D_
_x000D_
    }_x000D_
    window.historyArr.push(item1);_x000D_
    window.historyArr.push(item2);_x000D_
    window.historyCount+=2;_x000D_
    return false;_x000D_
}_x000D_
luckyDog = false;_x000D_
document.body.onload = function() {_x000D_
document.getElementById('runit').onclick  = function() {_x000D_
window.luckyDog = document.getElementById('lucky').checked;_x000D_
var val = document.getElementById('input').value_x000D_
if(val.trim() == '0') {_x000D_
    var intervaltimer = window.setInterval(function() {_x000D_
         var test = window.test();_x000D_
         if(test) {_x000D_
            window.clearInterval(intervaltimer);_x000D_
         }_x000D_
    },0);_x000D_
}_x000D_
else {_x000D_
   var num = parseInt(val);_x000D_
   if(num > 0) {_x000D_
        var intervaltimer = window.setInterval(function() {_x000D_
         var test = window.test();_x000D_
         num--;_x000D_
         if(num < 0 || test) {_x000D_
    _x000D_
         window.clearInterval(intervaltimer);_x000D_
         }_x000D_
    },0);_x000D_
   }_x000D_
}_x000D_
};_x000D_
};
_x000D_
Please input how often the calulation should run. set to 0 for forever. Check the checkbox if you feel lucky.<BR/>_x000D_
<input type="text" value="0" id="input"><input type="checkbox" id="lucky"><button id="runit">Run</button><BR/>
_x000D_
_x000D_
_x000D_

Alter column in SQL Server

I think you want this syntax:

ALTER TABLE tb_TableName  
add constraint cnt_Record_Status Default '' for Record_Status

Based on some of your comments, I am going to guess that you might already have null values in your table which is causing the alter of the column to not null to fail. If that is the case, then you should run an UPDATE first. Your script will be:

update tb_TableName
set Record_Status  = ''
where Record_Status is null

ALTER TABLE tb_TableName
ALTER COLUMN Record_Status VARCHAR(20) NOT NULL

ALTER TABLE tb_TableName
ADD CONSTRAINT DEF_Name DEFAULT '' FOR Record_Status

See SQL Fiddle with demo

What are the new features in C++17?

Language features:

Templates and Generic Code

Lambda

Attributes

Syntax cleanup

Cleaner multi-return and flow control

  • Structured bindings

    • Basically, first-class std::tie with auto
    • Example:
      • const auto [it, inserted] = map.insert( {"foo", bar} );
      • Creates variables it and inserted with deduced type from the pair that map::insert returns.
    • Works with tuple/pair-likes & std::arrays and relatively flat structs
    • Actually named structured bindings in standard
  • if (init; condition) and switch (init; condition)

    • if (const auto [it, inserted] = map.insert( {"foo", bar} ); inserted)
    • Extends the if(decl) to cases where decl isn't convertible-to-bool sensibly.
  • Generalizing range-based for loops

    • Appears to be mostly support for sentinels, or end iterators that are not the same type as begin iterators, which helps with null-terminated loops and the like.
  • if constexpr

    • Much requested feature to simplify almost-generic code.

Misc

Library additions:

Data types

Invoke stuff

File System TS v1

New algorithms

  • for_each_n

  • reduce

  • transform_reduce

  • exclusive_scan

  • inclusive_scan

  • transform_exclusive_scan

  • transform_inclusive_scan

  • Added for threading purposes, exposed even if you aren't using them threaded

Threading

(parts of) Library Fundamentals TS v1 not covered above or below

Container Improvements

Smart pointer changes

Other std datatype improvements:

Misc

Traits

Deprecated

Isocpp.org has has an independent list of changes since C++14; it has been partly pillaged.

Naturally TS work continues in parallel, so there are some TS that are not-quite-ripe that will have to wait for the next iteration. The target for the next iteration is C++20 as previously planned, not C++19 as some rumors implied. C++1O has been avoided.

Initial list taken from this reddit post and this reddit post, with links added via googling or from the above isocpp.org page.

Additional entries pillaged from SD-6 feature-test list.

clang's feature list and library feature list are next to be pillaged. This doesn't seem to be reliable, as it is C++1z, not C++17.

these slides had some features missing elsewhere.

While "what was removed" was not asked, here is a short list of a few things ((mostly?) previous deprecated) that are removed in C++17 from C++:

Removed:

There were rewordings. I am unsure if these have any impact on code, or if they are just cleanups in the standard:

Papers not yet integrated into above:

  • P0505R0 (constexpr chrono)

  • P0418R2 (atomic tweaks)

  • P0512R0 (template argument deduction tweaks)

  • P0490R0 (structured binding tweaks)

  • P0513R0 (changes to std::hash)

  • P0502R0 (parallel exceptions)

  • P0509R1 (updating restrictions on exception handling)

  • P0012R1 (make exception specifications be part of the type system)

  • P0510R0 (restrictions on variants)

  • P0504R0 (tags for optional/variant/any)

  • P0497R0 (shared ptr tweaks)

  • P0508R0 (structured bindings node handles)

  • P0521R0 (shared pointer use count and unique changes?)

Spec changes:

Further reference:

MySQL duplicate entry error even though there is no duplicate entry

This problem is often created when adding a column or using an existing column as a primary key. It is not created due to a primary key existing that was never actually created or due to damage to the table.

What the error actually denotes is that a pending key value is blank.

The solution is to populate the column with unique values and then try to create the primary key again. There can be no blank, null or duplicate values, or this misleading error will appear.

PHP Warning: POST Content-Length of 8978294 bytes exceeds the limit of 8388608 bytes in Unknown on line 0

Using wamp do the following and hopefully, it will resolve an issue

Make these changes in PHP Options to correct:

max_execution_time   180

memory_limit   512M or your highest available

post_max_size  32M

upload_max_filesize   64M

How to view files in binary from bash?

hexdump -C yourfile.bin

unless you want to edit it of course. Most linux distros have hexdump by default (but obviously not all).

ASP.NET strange compilation error

Cause: I have noticed that when I clean my project or clean one of the dependent projects and then hit refresh a few times on the page showing the site then it causes this error. It seems like it tries to load/run a broken/missing DLL project somehow.

Rename the project’s IIS directory to something different and with new name it loads fine (again providing project is built first OK then run otherwise it causes the same issue)

Python - Get path of root project structure

I've recently been trying to do something similar and I have found these answers inadequate for my use cases (a distributed library that needs to detect project root). Mainly I've been battling different environments and platforms, and still haven't found something perfectly universal.

Code local to project

I've seen this example mentioned and used in a few places, Django, etc.

import os
print(os.path.dirname(os.path.abspath(__file__)))

Simple as this is, it only works when the file that the snippet is in is actually part of the project. We do not retrieve the project directory, but instead the snippet's directory

Similarly, the sys.modules approach breaks down when called from outside the entrypoint of the application, specifically I've observed a child thread cannot determine this without relation back to the 'main' module. I've explicitly put the import inside a function to demonstrate an import from a child thread, moving it to top level of app.py would fix it.

app/
|-- config
|   `-- __init__.py
|   `-- settings.py
`-- app.py

app.py

#!/usr/bin/env python
import threading


def background_setup():
    # Explicitly importing this from the context of the child thread
    from config import settings
    print(settings.ROOT_DIR)


# Spawn a thread to background preparation tasks
t = threading.Thread(target=background_setup)
t.start()

# Do other things during initialization

t.join()

# Ready to take traffic

settings.py

import os
import sys


ROOT_DIR = None


def setup():
    global ROOT_DIR
    ROOT_DIR = os.path.dirname(sys.modules['__main__'].__file__)
    # Do something slow

Running this program produces an attribute error:

>>> import main
>>> Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\Python2714\lib\threading.py", line 801, in __bootstrap_inner
    self.run()
  File "C:\Python2714\lib\threading.py", line 754, in run
    self.__target(*self.__args, **self.__kwargs)
  File "main.py", line 6, in background_setup
    from config import settings
  File "config\settings.py", line 34, in <module>
    ROOT_DIR = get_root()
  File "config\settings.py", line 31, in get_root
    return os.path.dirname(sys.modules['__main__'].__file__)
AttributeError: 'module' object has no attribute '__file__'

...hence a threading-based solution

Location independent

Using the same application structure as before but modifying settings.py

import os
import sys
import inspect
import platform
import threading


ROOT_DIR = None


def setup():
    main_id = None
    for t in threading.enumerate():
        if t.name == 'MainThread':
            main_id = t.ident
            break

    if not main_id:
        raise RuntimeError("Main thread exited before execution")

    current_main_frame = sys._current_frames()[main_id]
    base_frame = inspect.getouterframes(current_main_frame)[-1]

    if platform.system() == 'Windows':
        filename = base_frame.filename
    else:
        filename = base_frame[0].f_code.co_filename

    global ROOT_DIR
    ROOT_DIR = os.path.dirname(os.path.abspath(filename))

Breaking this down: First we want to accurately find the thread ID of the main thread. In Python3.4+ the threading library has threading.main_thread() however, everybody doesn't use 3.4+ so we search through all threads looking for the main thread save it's ID. If the main thread has already exited, it won't be listed in the threading.enumerate(). We raise a RuntimeError() in this case until I find a better solution.

main_id = None
for t in threading.enumerate():
    if t.name == 'MainThread':
        main_id = t.ident
        break

if not main_id:
    raise RuntimeError("Main thread exited before execution")

Next we find the very first stack frame of the main thread. Using the cPython specific function sys._current_frames() we get a dictionary of every thread's current stack frame. Then utilizing inspect.getouterframes() we can retrieve the entire stack for the main thread and the very first frame. current_main_frame = sys._current_frames()[main_id] base_frame = inspect.getouterframes(current_main_frame)[-1] Finally, the differences between Windows and Linux implementations of inspect.getouterframes() need to be handled. Using the cleaned up filename, os.path.abspath() and os.path.dirname() clean things up.

if platform.system() == 'Windows':
    filename = base_frame.filename
else:
    filename = base_frame[0].f_code.co_filename

global ROOT_DIR
ROOT_DIR = os.path.dirname(os.path.abspath(filename))

So far I've tested this on Python2.7 and 3.6 on Windows as well as Python3.4 on WSL

avrdude: stk500v2_ReceiveMessage(): timeout

I've connected to USB port directly in my laptop and timeout issue has been resolved.

Previously tried by port replicator, but it did not even recognized arduino, thus I chosen wrong port - resulting in timeout message.

So make sure that it is visible by your OS.

bootstrap 3 - how do I place the brand in the center of the navbar?

I used two classes to achieve this and maintain responsiveness navbar-brand-left and navbar-brand-center. Keep in mind it utilises Sass / Less Bootstrap for line height, otherwise specify a hardcode px / rem height.

HTML

<nav class="navbar navbar-default">
  <div class="container-fluid">

    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a href="#" class="navbar-brand-left visible-xs visible-sm">Brand</a>
    </div>

    <div class="collapse navbar-collapse text-center" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav">
        <li><a href="#">About</a></li>
        <li><a href="#">How it works</a></li>
      </ul>
      <a href="#" class="navbar-brand-center hidden-xs hidden-sm">Brand</a>
      <ul class="nav navbar-nav navbar-right">
        <li><a href="#">Log in</a></li>
        <li><a href="#">Start now</a></li>
      </ul>
    </div><!-- /.navbar-collapse -->
  </div><!-- /.container-fluid -->
</nav>

CSS

.navbar-brand-left {
    display: inline-block;
    margin: 0;
    padding: 0;
    line-height: @navbar-height;
}

.navbar-brand-center {
    display: inline-block;
    margin: 0 auto;
    padding: 0;
    line-height: @navbar-height;
}

Laravel - Eloquent or Fluent random row

This works just fine,

$model=Model::all()->random(1)->first();

you can also change argument in random function to get more than one record.

Note: not recommended if you have huge data as this will fetch all rows first and then returns random value.

How can I escape double quotes in XML attributes values?

From the XML specification:

To allow attribute values to contain both single and double quotes, the apostrophe or single-quote character (') may be represented as "&apos;", and the double-quote character (") as "&quot;".

Javascript negative number

If you really want to dive into it and even need to distinguish between -0 and 0, here's a way to do it.

function negative(number) {
  return !Object.is(Math.abs(number), +number);
}

console.log(negative(-1));  // true
console.log(negative(1));   // false
console.log(negative(0));   // false
console.log(negative(-0));  // true

git returns http error 407 from proxy after CONNECT

Maybe you are already using the system proxy setting - in this case unset all git proxies will work:

git config --global --unset http.proxy
git config --global --unset https.proxy

Mysql: Setup the format of DATETIME to 'DD-MM-YYYY HH:MM:SS' when creating a table

This cannot be done for the table; besides, you even cannot change this default value at all.

The answer is a server variable datetime_format, it is unused.

How can I find the location of origin/master in git, and how do I change it?

I had the problem "Your branch is ahead of 'origin/master' by nn commits." when i pushed to a remote repository with:

git push ssh://[email protected]/yyy/zzz.git

When i found that my remote adress was in the file .git/FETCH_HEAD and used:

git push

the problem disappeared.

Get the data received in a Flask request

To post JSON with jQuery in JavaScript, use JSON.stringify to dump the data, and set the content type to application/json.

var value_data = [1, 2, 3, 4];

$.ajax({
    type: 'POST',
    url: '/process',
    data: JSON.stringify(value_data),
    contentType: 'application/json',
    success: function (response_data) {
        alert("success");
    }   
});

Parse it in Flask with request.get_json().

data = request.get_json()

How to programmatically set the SSLContext of a JAX-WS client?

I tried the steps here:

http://jyotirbhandari.blogspot.com/2011/09/java-error-invalidalgorithmparameterexc.html

And, that fixed the issue. I made some minor tweaks - I set the two parameters using System.getProperty...

What's the difference between __PRETTY_FUNCTION__, __FUNCTION__, __func__?

__func__ is documented in the C++0x standard at section 8.4.1. In this case it's a predefined function local variable of the form:

static const char __func__[] = "function-name ";

where "function name" is implementation specfic. This means that whenever you declare a function, the compiler will add this variable implicitly to your function. The same is true of __FUNCTION__ and __PRETTY_FUNCTION__. Despite their uppercasing, they aren't macros. Although __func__ is an addition to C++0x

g++ -std=c++98 ....

will still compile code using __func__.

__PRETTY_FUNCTION__ and __FUNCTION__ are documented here http://gcc.gnu.org/onlinedocs/gcc-4.5.1/gcc/Function-Names.html#Function-Names. __FUNCTION__ is just another name for __func__. __PRETTY_FUNCTION__ is the same as __func__ in C but in C++ it contains the type signature as well.

What is VanillaJS?

This word, hence, VanillaJS is a just damn joke that changed my life. I had gone to a German company for an interview, I was very poor in JavaScript and CSS, very poor, so the Interviewer said to me: We're working here with VanillaJs, So you should know this framework.

Definitely, I understood that I'was rejected, but for one week I seek for VanillaJS, After all, I found THIS LINK.

What I am just was because of that joke.

VanillaJS === plain `JavaScript`

Print the stack trace of an exception

The Throwable class provides two methods named printStackTrace, one that accepts a PrintWriter and one that takes in a PrintStream, that outputs the stack trace to the given stream. Consider using one of these.

How to display count of notifications in app launcher icon

This is sample and best way for showing badge on notification launcher icon.

Add This Class in your application

public class BadgeUtils {

    public static void setBadge(Context context, int count) {
        setBadgeSamsung(context, count);
        setBadgeSony(context, count);
    }

    public static void clearBadge(Context context) {
        setBadgeSamsung(context, 0);
        clearBadgeSony(context);
    }


    private static void setBadgeSamsung(Context context, int count) {
        String launcherClassName = getLauncherClassName(context);
        if (launcherClassName == null) {
            return;
        }
        Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
        intent.putExtra("badge_count", count);
        intent.putExtra("badge_count_package_name", context.getPackageName());
        intent.putExtra("badge_count_class_name", launcherClassName);
        context.sendBroadcast(intent);
    }

    private static void setBadgeSony(Context context, int count) {
        String launcherClassName = getLauncherClassName(context);
        if (launcherClassName == null) {
            return;
        }

        Intent intent = new Intent();
        intent.setAction("com.sonyericsson.home.action.UPDATE_BADGE");
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.ACTIVITY_NAME", launcherClassName);
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.SHOW_MESSAGE", true);
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.MESSAGE", String.valueOf(count));
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.PACKAGE_NAME", context.getPackageName());

        context.sendBroadcast(intent);
    }


    private static void clearBadgeSony(Context context) {
        String launcherClassName = getLauncherClassName(context);
        if (launcherClassName == null) {
            return;
        }

        Intent intent = new Intent();
        intent.setAction("com.sonyericsson.home.action.UPDATE_BADGE");
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.ACTIVITY_NAME", launcherClassName);
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.SHOW_MESSAGE", false);
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.MESSAGE", String.valueOf(0));
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.PACKAGE_NAME", context.getPackageName());

        context.sendBroadcast(intent);
    }

    private static String getLauncherClassName(Context context) {

        PackageManager pm = context.getPackageManager();

        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);

        List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
        for (ResolveInfo resolveInfo : resolveInfos) {
            String pkgName = resolveInfo.activityInfo.applicationInfo.packageName;
            if (pkgName.equalsIgnoreCase(context.getPackageName())) {
                String className = resolveInfo.activityInfo.name;
                return className;
            }
        }
        return null;
    }


}

==> MyGcmListenerService.java Use BadgeUtils class when notification comes.

public class MyGcmListenerService extends GcmListenerService { 

    private static final String TAG = "MyGcmListenerService"; 
    @Override
    public void onMessageReceived(String from, Bundle data) {

            String message = data.getString("Msg");
            String Type = data.getString("Type"); 
            Intent intent = new Intent(this, SplashActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                    PendingIntent.FLAG_ONE_SHOT);

            Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

            NotificationCompat.BigTextStyle bigTextStyle= new NotificationCompat.BigTextStyle();

            bigTextStyle .setBigContentTitle(getString(R.string.app_name))
                    .bigText(message);
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                    .setSmallIcon(getNotificationIcon())
                    .setContentTitle(getString(R.string.app_name))
                    .setContentText(message)
                    .setStyle(bigTextStyle) 
                    .setAutoCancel(true)
                    .setSound(defaultSoundUri)
                    .setContentIntent(pendingIntent);

            int color = getResources().getColor(R.color.appColor);
            notificationBuilder.setColor(color);
            NotificationManager notificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);


            int unOpenCount=AppUtill.getPreferenceInt("NOTICOUNT",this);
            unOpenCount=unOpenCount+1;

            AppUtill.savePreferenceLong("NOTICOUNT",unOpenCount,this);  
            notificationManager.notify(unOpenCount /* ID of notification */, notificationBuilder.build()); 

// This is for bladge on home icon          
        BadgeUtils.setBadge(MyGcmListenerService.this,(int)unOpenCount);

    }


    private int getNotificationIcon() {
        boolean useWhiteIcon = (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP);
        return useWhiteIcon ? R.drawable.notification_small_icon : R.drawable.icon_launcher;
    }
}

And clear notification from preference and also with badge count

 public class SplashActivity extends AppCompatActivity { 
                @Override
                protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_splash);

                    AppUtill.savePreferenceLong("NOTICOUNT",0,this);
                    BadgeUtils.clearBadge(this);
            }
    }
<uses-permission android:name="com.sonyericsson.home.permission.BROADCAST_BADGE" />

CSS - Make divs align horizontally

you can use the clip property:

#container {
  position: absolute;
  clip: rect(0px,200px,100px,0px);
  overflow: hidden;
  background: red;
}

note the position: absolute and overflow: hidden needed in order to get clip to work.

How do I combine two data-frames based on two columns?

See the documentation on ?merge, which states:

By default the data frames are merged on the columns with names they both have, 
 but separate specifications of the columns can be given by by.x and by.y.

This clearly implies that merge will merge data frames based on more than one column. From the final example given in the documentation:

x <- data.frame(k1=c(NA,NA,3,4,5), k2=c(1,NA,NA,4,5), data=1:5)
y <- data.frame(k1=c(NA,2,NA,4,5), k2=c(NA,NA,3,4,5), data=1:5)
merge(x, y, by=c("k1","k2")) # NA's match

This example was meant to demonstrate the use of incomparables, but it illustrates merging using multiple columns as well. You can also specify separate columns in each of x and y using by.x and by.y.

TypeError: $.browser is undefined

Just include this script

http://code.jquery.com/jquery-migrate-1.0.0.js

after you include your jquery javascript file.

How to solve SQL Server Error 1222 i.e Unlock a SQL Server table

I had these SQL behavior settings enabled on options query execution: ANSI SET IMPLICIT_TRANSACTIONS checked. On execution of your query e.g create, alter table or stored procedure, you have to COMMIT it.

Just type COMMIT and execute it F5

Eclipse "Server Locations" section disabled and need to change to use Tomcat installation

Starting server and publishing without any projects helped me to modify the "Server Locations".

How can I convert byte size into a human-readable format in Java?

Create an interface:

public interface IUnits {
    public String format(long size, String pattern);
    public long getUnitSize();
}

Create the StorageUnits class:

import java.text.DecimalFormat;

public class StorageUnits {

    private static final long K = 1024;
    private static final long M = K * K;
    private static final long G = M * K;
    private static final long T = G * K;

    enum Unit implements IUnits {

        TERA_BYTE {
            @Override
            public String format(long size, String pattern) {
                return format(size, getUnitSize(), "TB", pattern);
            }
            @Override
            public long getUnitSize() {
                return T;
            }
            @Override
            public String toString() {
                return "Terabytes";
            }
        },
        GIGA_BYTE {
            @Override
            public String format(long size, String pattern) {
                return format(size, getUnitSize(), "GB", pattern);
            }
            @Override
            public long getUnitSize() {
                return G;
            }
            @Override
            public String toString() {
                return "Gigabytes";
            }
        },
        MEGA_BYTE {
            @Override
            public String format(long size, String pattern) {
                return format(size, getUnitSize(), "MB", pattern);
            }
            @Override
            public long getUnitSize() {
                return M;
            }
            @Override
            public String toString() {
                return "Megabytes";
            }
        },
        KILO_BYTE {
            @Override
            public String format(long size, String pattern) {
                return format(size, getUnitSize(), "kB", pattern);
            }
            @Override
            public long getUnitSize() {
                return K;
            }
            @Override
            public String toString() {
                return "Kilobytes";
            }

        };

        String format(long size, long base, String unit, String pattern) {
            return new DecimalFormat(pattern).format(
                           Long.valueOf(size).doubleValue() /
                           Long.valueOf(base).doubleValue()
            ) + unit;
        }
    }

    public static String format(long size, String pattern) {
        for(Unit unit : Unit.values()) {
            if(size >= unit.getUnitSize()) {
                return unit.format(size, pattern);
            }
        }
        return ("???(" + size + ")???");
    }

    public static String format(long size) {
        return format(size, "#,##0.#");
    }
}

Call it:

class Main {
    public static void main(String... args) {
        System.out.println(StorageUnits.format(21885));
        System.out.println(StorageUnits.format(2188121545L));
    }
}

Output:

21.4kB
2GB

How to call a function from another controller in angularjs?

Communication between controllers is done though $emit + $on / $broadcast + $on methods.

So in your case you want to call a method of Controller "One" inside Controller "Two", the correct way to do this is:

app.controller('One', ['$scope', '$rootScope'
    function($scope) {
        $rootScope.$on("CallParentMethod", function(){
           $scope.parentmethod();
        });

        $scope.parentmethod = function() {
            // task
        }
    }
]);
app.controller('two', ['$scope', '$rootScope'
    function($scope) {
        $scope.childmethod = function() {
            $rootScope.$emit("CallParentMethod", {});
        }
    }
]);

While $rootScope.$emit is called, you can send any data as second parameter.

Why is the default value of the string type null instead of an empty string?

A String is an immutable object which means when given a value, the old value doesn't get wiped out of memory, but remains in the old location, and the new value is put in a new location. So if the default value of String a was String.Empty, it would waste the String.Empty block in memory when it was given its first value.

Although it seems minuscule, it could turn into a problem when initializing a large array of strings with default values of String.Empty. Of course, you could always use the mutable StringBuilder class if this was going to be a problem.

Required request body content is missing: org.springframework.web.method.HandlerMethod$HandlerMethodParameter

I also had the same problem. I use "Postman" for JSON request. The code itself is not wrong. I simply set the content type to JSON (application/json) and it worked, as you can see on the image below

My Code

LINQ Orderby Descending Query

I think this first failed because you are ordering value which is null. If Delivery is a foreign key associated table then you should include this table first, example below:

var itemList = from t in ctn.Items.Include(x=>x.Delivery)
                    where !t.Items && t.DeliverySelection
                    orderby t.Delivery.SubmissionDate descending
                    select t;

Pure CSS to make font-size responsive based on dynamic amount of characters

Note: This solution changes based on viewport size and not the amount of content

I just found out that this is possible using VW units. They're the units associated with setting the viewport width. There are some drawbacks, such as lack of legacy browser support, but this is definitely something to seriously consider using. Plus you can still provide fallbacks for older browsers like so:

p {
    font-size: 30px;
    font-size: 3.5vw;
}

http://css-tricks.com/viewport-sized-typography/ and https://medium.com/design-ux/66bddb327bb1

.net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible

That particular package does not include assemblies for dotnet core, at least not at present. You may be able to build it for core yourself with a few tweaks to the project file, but I can't say for sure without diving into the source myself.

Unix command-line JSON parser?

Checkout TickTick.

It's a true Bash JSON parser.

#!/bin/bash
. /path/to/ticktick.sh

# File
DATA=`cat data.json`
# cURL
#DATA=`curl http://foobar3000.com/echo/request.json`

tickParse "$DATA"

echo ``pathname``
echo ``headers["user-agent"]``

Append a dictionary to a dictionary

Assuming that you do not want to change orig, you can either do a copy and update like the other answers, or you can create a new dictionary in one step by passing all items from both dictionaries into the dict constructor:

from itertools import chain
dest = dict(chain(orig.items(), extra.items()))

Or without itertools:

dest = dict(list(orig.items()) + list(extra.items()))

Note that you only need to pass the result of items() into list() on Python 3, on 2.x dict.items() already returns a list so you can just do dict(orig.items() + extra.items()).

As a more general use case, say you have a larger list of dicts that you want to combine into a single dict, you could do something like this:

from itertools import chain
dest = dict(chain.from_iterable(map(dict.items, list_of_dicts)))

What is the best IDE for C Development / Why use Emacs over an IDE?

I've moved from a terminal text-editor+make environment to Eclipse for most of my projects. Spanning from C and C++, to Java and Python to name few languages I am currently working with.

The reason was simply productivity. I could not afford spending time and effort on keeping all projects "in my head" as other things got more important.

There are benefits of using the "hardcore" approach (terminal) - such as that you have a much thinner layer between yourself and the code which allows you to be a bit more productive when you're all "inside" the project and everything is on the top of your head. But I don't think it is possible to defend that way of working just for it's own sake when your mind is needed elsewhere.

Usually when you work with command line tools you will frequently have to solve a lot of boilerplate problems that will keep you from being productive. You will need to know the tools in detail to fully leverage their potentials. Also maintaining a project will take a lot more effort. Refactoring will lead to updates in make-files, etc.

To summarize: If you only work on one or two projects, preferably full-time without too much distractions, "terminal based coding" can be more productive than a full blown IDE. However, if you need to spend your thinking energy on something more important an IDE is definitely the way to go in order to keep productivity.

Make your choice accordingly.

Lazy Method for Reading Big File in Python?

i am not allowed to comment due to my low reputation, but SilentGhosts solution should be much easier with file.readlines([sizehint])

python file methods

edit: SilentGhost is right, but this should be better than:

s = "" 
for i in xrange(100): 
   s += file.next()

How to link html pages in same or different folders?

For ASP.NET, this worked for me on development and deployment:

<a runat="server" href="~/Subfolder/TargetPage">TargetPage</a>

Using runat="server" and the href="~/" are the keys for going to the root.

overlay opaque div over youtube iframe

Hmm... what's different this time? http://jsfiddle.net/fdsaP/2/

Renders in Chrome fine. Do you need it cross-browser? It really helps being specific.

EDIT: Youtube renders the object and embed with no explicit wmode set, meaning it defaults to "window" which means it overlays everything. You need to either:


a) Host the page that contains the object/embed code yourself and add wmode="transparent" param element to object and attribute to embed if you choose to serve both elements

b) Find a way for youtube to specify those.


Getting Class type from String

It should be:

Class.forName(String classname)

How do I declare an array variable in VBA?

You have to declare the array variable as an array:

Dim test(10) As Variant

<script> tag vs <script type = 'text/javascript'> tag

In HTML 4, the type attribute is required. In my experience, all browsers will default to text/javascript if it is absent, but that behaviour is not defined anywhere. While you can in theory leave it out and assume it will be interpreted as JavaScript, it's invalid HTML, so why not add it.

In HTML 5, the type attribute is optional and defaults to text/javascript

Use <script type="text/javascript"> or simply <script> (if omitted, the type is the same). Do not use <script language="JavaScript">; the language attribute is deprecated

Ref :
http://social.msdn.microsoft.com/Forums/vstudio/en-US/65aaf5f3-09db-4f7e-a32d-d53e9720ad4c/script-languagejavascript-or-script-typetextjavascript-?forum=netfxjscript
and
Difference between <script> tag with type and <script> without type?

Do you need type attribute at all?

I am using HTML5- No

I am not using HTML5 - Yes

Why use #ifndef CLASS_H and #define CLASS_H in .h file but not in .cpp?

The CLASS_H is an include guard; it's used to avoid the same header file being included multiple times (via different routes) within the same CPP file (or, more accurately, the same translation unit), which would lead to multiple-definition errors.

Include guards aren't needed on CPP files because, by definition, the contents of the CPP file are only read once.

You seem to have interpreted the include guards as having the same function as import statements in other languages (such as Java); that's not the case, however. The #include itself is roughly equivalent to the import in other languages.

Git remote branch deleted, but still it appears in 'branch -a'

In our particular case, we use Stash as our remote Git repository. We tried all the previous answers and nothing was working. We ended up having to do the following:

git branch –D branch-name (delete from local)
git push origin :branch-name (delete from remote)

Then when users went to pull changes, they needed to do the following:

git fetch -p

How do I manage MongoDB connections in a Node.js web application?

Here is some code that will manage your MongoDB connections.

var MongoClient = require('mongodb').MongoClient;
var url = require("../config.json")["MongoDBURL"]

var option = {
  db:{
    numberOfRetries : 5
  },
  server: {
    auto_reconnect: true,
    poolSize : 40,
    socketOptions: {
        connectTimeoutMS: 500
    }
  },
  replSet: {},
  mongos: {}
};

function MongoPool(){}

var p_db;

function initPool(cb){
  MongoClient.connect(url, option, function(err, db) {
    if (err) throw err;

    p_db = db;
    if(cb && typeof(cb) == 'function')
        cb(p_db);
  });
  return MongoPool;
}

MongoPool.initPool = initPool;

function getInstance(cb){
  if(!p_db){
    initPool(cb)
  }
  else{
    if(cb && typeof(cb) == 'function')
      cb(p_db);
  }
}
MongoPool.getInstance = getInstance;

module.exports = MongoPool;

When you start the server, call initPool

require("mongo-pool").initPool();

Then in any other module you can do the following:

var MongoPool = require("mongo-pool");
MongoPool.getInstance(function (db){
    // Query your MongoDB database.
});

This is based on MongoDB documentation. Take a look at it.

psql: could not connect to server: No such file or directory (Mac OS X)

Maybe this is unrelated but a similar error appears when you upgrade postgres to a major version using brew; using brew info postgresql found out this that helped:

To migrate existing data from a previous major version of PostgreSQL run:
brew postgresql-upgrade-database

How to handle an IF STATEMENT in a Mustache template?

Just took a look over the mustache docs and they support "inverted sections" in which they state

they (inverted sections) will be rendered if the key doesn't exist, is false, or is an empty list

http://mustache.github.io/mustache.5.html#Inverted-Sections

{{#value}}
  value is true
{{/value}}
{{^value}}
  value is false
{{/value}}

How to remove last n characters from every element in the R vector

Similar to @Matthew_Plourde using gsub

However, using a pattern that will trim to zero characters i.e. return "" if the original string is shorter than the number of characters to cut:

cs <- c("foo_bar","bar_foo","apple","beer","so","a")
gsub('.{0,3}$', '', cs)
# [1] "foo_" "bar_" "ap"   "b"    ""    ""

Difference is, {0,3} quantifier indicates 0 to 3 matches, whereas {3} requires exactly 3 matches otherwise no match is found in which case gsub returns the original, unmodified string.

N.B. using {,3} would be equivalent to {0,3}, I simply prefer the latter notation.

See here for more information on regex quantifiers: https://www.regular-expressions.info/refrepeat.html

Convert a row of a data frame to vector

Note that you have to be careful if your row contains a factor. Here is an example:

df_1 = data.frame(V1 = factor(11:15),
                  V2 = 21:25)
df_1[1,] %>% as.numeric() # you expect 11 21 but it returns 
[1] 1 21

Here is another example (by default data.frame() converts characters to factors)

df_2 = data.frame(V1 = letters[1:5],
                  V2 = 1:5)
df_2[3,] %>% as.numeric() # you expect to obtain c 3 but it returns
[1] 3 3
df_2[3,] %>% as.character() # this won't work neither
[1] "3" "3"

To prevent this behavior, you need to take care of the factor, before extracting it:

df_1$V1 = df_1$V1 %>% as.character() %>% as.numeric()
df_2$V1 = df_2$V1 %>% as.character()
df_1[1,] %>% as.numeric()
[1] 11  21
df_2[3,] %>% as.character()
[1] "c" "3"

How to clean old dependencies from maven repositories?

I came up with a utility and hosted on GitHub to clean old versions of libraries in the local Maven repository. The utility, on its default execution removes all older versions of artifacts leaving only the latest ones. Optionally, it can remove all snapshots, sources, javadocs, and also groups or artifacts can be forced / excluded in this process. This cross platform also supports date based removal based on last access / download dates.

https://github.com/techpavan/mvn-repo-cleaner

How to load an ImageView by URL in Android?

Try this way,hope this will help you to solve your problem.

Here I explain about how to use "AndroidQuery" external library for load image from url/server in asyncTask manner with also cache loaded image to device file or cache area.

  • Download "AndroidQuery" library from here
  • Copy/Paste this jar to project lib folder and add this library to project build-path
  • Now I show demo to how to use it.

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center">

        <FrameLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <ImageView
                android:id="@+id/imageFromUrl"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:adjustViewBounds="true"/>
            <ProgressBar
                android:id="@+id/pbrLoadImage"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"/>

        </FrameLayout>
    </LinearLayout>

MainActivity.java

public class MainActivity extends Activity {

private AQuery aQuery;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    aQuery = new AQuery(this);
    aQuery.id(R.id.imageFromUrl).progress(R.id.pbrLoadImage).image("http://itechthereforeiam.com/wp-content/uploads/2013/11/android-gone-packing.jpg",true,true);
 }
}

Note : Here I just implemented common method to load image from url/server but you can use various types of method which can be provided by "AndroidQuery"to load your image easily.

X close button only using css

Main point you are looking for is:

.tag-remove::before {
  content: 'x'; // here is your X(cross) sign.
  color: #fff;
  font-weight: 300;
  font-family: Arial, sans-serif;
}

FYI, you can make a close button by yourself very easily:

_x000D_
_x000D_
#mdiv {_x000D_
  width: 25px;_x000D_
  height: 25px;_x000D_
  background-color: red;_x000D_
  border: 1px solid black;_x000D_
}_x000D_
_x000D_
.mdiv {_x000D_
  height: 25px;_x000D_
  width: 2px;_x000D_
  margin-left: 12px;_x000D_
  background-color: black;_x000D_
  transform: rotate(45deg);_x000D_
  Z-index: 1;_x000D_
}_x000D_
_x000D_
.md {_x000D_
  height: 25px;_x000D_
  width: 2px;_x000D_
  background-color: black;_x000D_
  transform: rotate(90deg);_x000D_
  Z-index: 2;_x000D_
}
_x000D_
<div id="mdiv">_x000D_
  <div class="mdiv">_x000D_
    <div class="md"></div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

java.security.cert.CertificateException: Certificates does not conform to algorithm constraints

Since this result is the first that Google returns for this error, I'll just add that if anyone looks for way do change java security settings without changing the global file java.security (for example you need to run some tests), you can just provide an overriding security file by JVM parameter -Djava.security.properties=your/file/path in which you can enable the necessary algorithms by overriding the disablements.

How to get current available GPUs in tensorflow?

In TensorFlow 2.0, you can use tf.config.experimental.list_physical_devices('GPU'):

import tensorflow as tf
gpus = tf.config.experimental.list_physical_devices('GPU')
for gpu in gpus:
    print("Name:", gpu.name, "  Type:", gpu.device_type)

If you have two GPUs installed, it outputs this:

Name: /physical_device:GPU:0   Type: GPU
Name: /physical_device:GPU:1   Type: GPU

From 2.1, you can drop experimental:

gpus = tf.config.list_physical_devices('GPU')

See:

Dynamically create an array of strings with malloc

char **orderIds;

orderIds = malloc(variableNumberOfElements * sizeof(char*));

for(int i = 0; i < variableNumberOfElements; i++) {
  orderIds[i] = malloc((ID_LEN + 1) * sizeof(char));
  strcpy(orderIds[i], your_string[i]);
}

How do I create a MessageBox in C#?

This is some of the things you can put into a message box. Enjoy
MessageBox.Show("Enter the text for the message box",
"Enter the name of the message box",
(Enter the button names e.g. MessageBoxButtons.YesNo),
(Enter the icon e.g. MessageBoxIcon.Question),
(Enter the default button e.g. MessageBoxDefaultButton.Button1)

More information can be found here

Best Practice for Forcing Garbage Collection in C#

Suppose your program doesn't have memory leakage, objects accumulates and cannot be GC-ed in Gen 0 because: 1) They are referenced for long time so get into Gen1 & Gen2; 2) They are large objects (>80K) so get into LOH (Large Object Heap). And LOH doesn't do compacting as in Gen0, Gen1 & Gen2.

Check the performance counter of ".NET Memory" can you can see that the 1) problem is really not a problem. Generally, every 10 Gen0 GC will trigger 1 Gen1 GC, and every 10 Gen1 GC will trigger 1 Gen2 GC. Theoretically, GC1 & GC2 can never be GC-ed if there is no pressure on GC0 (if the program memory usage is really wired). It never happens to me.

For problem 2), you can check ".NET Memory" performance counter to verify whether LOH is getting bloated. If it is really a issue to your problem, perhaps you can create a large-object-pool as this blog suggests http://blogs.msdn.com/yunjin/archive/2004/01/27/63642.aspx.

What are the true benefits of ExpandoObject?

There are some cases where this is handy. I'll use it for a Modularized shell for instance. Each module defines it's own Configuration Dialog databinded to it's settings. I provide it with an ExpandoObject as it's Datacontext and save the values in my configuration Storage. This way the Configuration Dialog writer just has to Bind to a Value and it's automatically created and saved. (And provided to the module for using these settings of course)

It' simply easier to use than an Dictionary. But everyone should be aware that internally it is just a Dictionary.

It's like LINQ just syntactic sugar, but it makes things easier sometimes.

So to answer your question directly: It's easier to write and easier to read. But technically it essentially is a Dictionary<string,object> (You can even cast it into one to list the values).

submitting a GET form with query string params and hidden params disappear

<form ... action="http:/www.blabla.com?a=1&b=2" method ="POST">
<input type="hidden" name="c" value="3" /> 
</form>

change the request method to' POST' instead of 'GET'.

C++ program converts fahrenheit to celsius

The answer has already been found although I would also like to share my answer:

int main(void)
{
using namespace std;

short tempC;
cout << "Please enter a Celsius value: ";
cin >> tempC;
double tempF = convert(tempC);
cout << tempC << " degrees Celsius is " << tempF << " degrees Fahrenheit." << endl;
cin.get();
cin.get();
return 0;

}

int convert(short nT)
{
return nT * 1.8 + 32;
}

This is a more proper way to do this; however, it is slightly more complex then what you were going for.

Where is NuGet.Config file located in Visual Studio project?

There are multiple nuget packages read in the following order:

  1. First the NuGetDefaults.Config file. You will find this in %ProgramFiles(x86)%\NuGet\Config.
  2. The computer-level file.
  3. The user-level file. You will find this in %APPDATA%\NuGet\nuget.config.
  4. Any file named nuget.config beginning from the root of your drive up to the directory where nuget.exe is called.
  5. The config file you specify in the -configfile option when calling nuget.exe

You can find more information here.

How to query nested objects?

db.messages.find( { headers : { From: "[email protected]" } } )

This queries for documents where headers equals { From: ... }, i.e. contains no other fields.


db.messages.find( { 'headers.From': "[email protected]" } )

This only looks at the headers.From field, not affected by other fields contained in, or missing from, headers.


Dot-notation docs

Android Reading from an Input stream efficiently

Another possibility with Guava:

dependency: compile 'com.google.guava:guava:11.0.2'

import com.google.common.io.ByteStreams;
...

String total = new String(ByteStreams.toByteArray(inputStream ));

How to use a jQuery plugin inside Vue

First install jquery using npm,

npm install jquery --save

I use:

global.jQuery = require('jquery');
var $ = global.jQuery;
window.$ = $;

Inline list initialization in VB.NET

Collection initializers are only available in VB.NET 2010, released 2010-04-12:

Dim theVar = New List(Of String) From { "one", "two", "three" }

How can I change the language (to english) in Oracle SQL Developer?

With SQL Developer 4.x, the language option is to be added to ..\sqldeveloper\bin\sqldeveloper.conf, rather than ..\sqldeveloper\bin\ide.conf:

# ----- MODIFICATION BEGIN -----
AddVMOption -Duser.language=en
# ----- MODIFICATION END -----

Android: How to programmatically access the device serial number shown in the AVD manager (API Version 8)

From Android P, defining the READ_PHONE_STATE permission in AndroidManifest only, will not work. We have to actually request for the permission. Below code works for me:

@RequiresApi(api = Build.VERSION_CODES.P)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, 101);
    }
}

@RequiresApi(api = Build.VERSION_CODES.O)
@Override
protected void onResume() {
    super.onResume();
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    Log.d(TAG,Build.getSerial());
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    switch (requestCode) {
        case 101:
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
        } else {
            //not granted
        }
        break;
        default:
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}

Add this permissions in AndroidManifest.xml

<uses-permission android:name = "android.permission.INTERNET"/>
<uses-permission android:name = "android.permission.READ_PHONE_STATE" />

Hope this helps.

Thank You, MJ

Hibernate error: ids for this class must be manually assigned before calling save():

Your @Entity class has a String type for its @Id field, so it can't generate ids for you.

If you change it to an auto increment in the DB and a Long in java, and add the @GeneratedValue annotation:

@Id
@Column(name="U_id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long U_id;

it will handle incrementing id generation for you.

How to open a Bootstrap modal window using jQuery?

I tried several methods which failed, but the below worked for me like a charm:

$('#myModal').appendTo("body").modal('show');

Create SQLite database in android

    public class MyDatabaseHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "MyDb.db";

    private static final int DATABASE_VERSION = 1;

    // Database creation sql statement
    private static final String DATABASE_CREATE_FRIDGE_ITEM = "create table FridgeItem(id integer primary key autoincrement,f_id text not null,food_item text not null,quantity text not null,measurement text not null,expiration_date text not null,current_date text not null,flag text not null,location text not null);";

    public MyDatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Method is called during creation of the database
    @Override
    public void onCreate(SQLiteDatabase database) {
        database.execSQL(DATABASE_CREATE_FRIDGE_ITEM);
    }

    // Method is called during an upgrade of the database,
    @Override
    public void onUpgrade(SQLiteDatabase database,int oldVersion,int newVersion){
        Log.w(MyDatabaseHelper.class.getName(),"Upgrading database from version " + oldVersion + " to "
                         + newVersion + ", which will destroy all old data");
        database.execSQL("DROP TABLE IF EXISTS FridgeItem");
        onCreate(database);
    }
}



    public class CommentsDataSource {

    private MyDatabaseHelper dbHelper;

    private SQLiteDatabase database;

    public String stringArray[];

    public final static String FOOD_TABLE = "FridgeItem"; // name of table
    public final static String FOOD_ITEMS_DETAILS = "FoodDetails"; // name of table

    public final static String P_ID = "id"; // pid
    public final static String FOOD_ID = "f_id"; // id value for food item
    public final static String FOOD_NAME = "food_item"; // name of food
    public final static String FOOD_QUANTITY = "quantity"; // quantity of food item
    public final static String FOOD_MEASUREMENT = "measurement"; // measurement of food item
    public final static String FOOD_EXPIRATION = "expiration_date"; // expiration date of food item
    public final static String FOOD_CURRENTDATE = "current_date"; //  date of food item added
    public final static String FLAG = "flag"; 
    public final static String LOCATION = "location";
    /**
     * 
     * @param context
     */
    public CommentsDataSource(Context context) {
        dbHelper = new MyDatabaseHelper(context);
        database = dbHelper.getWritableDatabase();
    }

    public long insertFoodItem(String id, String name,String quantity, String measurement, String currrentDate,String expiration,String flag,String location) {
        ContentValues values = new ContentValues();
        values.put(FOOD_ID, id);
        values.put(FOOD_NAME, name);
        values.put(FOOD_QUANTITY, quantity);
        values.put(FOOD_MEASUREMENT, measurement);
        values.put(FOOD_CURRENTDATE, currrentDate);
        values.put(FOOD_EXPIRATION, expiration);
        values.put(FLAG, flag);
        values.put(LOCATION, location);
        return database.insert(FOOD_TABLE, null, values);
    }

    public long insertFoodItemsDetails(String id, String name,String quantity, String measurement, String currrentDate,String expiration) {
        ContentValues values = new ContentValues();
        values.put(FOOD_ID, id);
        values.put(FOOD_NAME, name);
        values.put(FOOD_QUANTITY, quantity);
        values.put(FOOD_MEASUREMENT, measurement);
        values.put(FOOD_CURRENTDATE, currrentDate);
        values.put(FOOD_EXPIRATION, expiration);
        return database.insert(FOOD_ITEMS_DETAILS, null, values);

    }

    public Cursor selectRecords(String id) {
        String[] cols = new String[] { FOOD_ID, FOOD_NAME, FOOD_QUANTITY, FOOD_MEASUREMENT, FOOD_EXPIRATION,FLAG,LOCATION,P_ID};
        Cursor mCursor = database.query(true, FOOD_TABLE, cols, P_ID+"=?", new String[]{id}, null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor; // iterate to get each value.
    }

    public Cursor selectAllName() {
        String[] cols = new String[] { FOOD_NAME};
        Cursor mCursor = database.query(true, FOOD_TABLE, cols, null, null, null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor; // iterate to get each value.
    }

    public Cursor selectAllRecords(String loc) {
        String[] cols = new String[] { FOOD_ID, FOOD_NAME, FOOD_QUANTITY, FOOD_MEASUREMENT, FOOD_EXPIRATION,FLAG,LOCATION,P_ID};
        Cursor mCursor = database.query(true, FOOD_TABLE, cols, LOCATION+"=?", new String[]{loc}, null, null, null, null);
        int size=mCursor.getCount();
        stringArray = new String[size];
        int i=0;
        if (mCursor != null) {
            mCursor.moveToFirst();
            FoodInfo.arrayList.clear();
                while (!mCursor.isAfterLast()) {
                    String name=mCursor.getString(1);
                    stringArray[i]=name;
                    String quant=mCursor.getString(2);
                    String measure=mCursor.getString(3);
                    String expir=mCursor.getString(4);
                    String id=mCursor.getString(7);
                    FoodInfo fooditem=new FoodInfo();
                    fooditem.setName(name);
                    fooditem.setQuantity(quant);
                    fooditem.setMesure(measure);
                    fooditem.setExpirationDate(expir);
                    fooditem.setid(id);
                    FoodInfo.arrayList.add(fooditem);
                    mCursor.moveToNext();
                    i++;
                }
        }
        return mCursor; // iterate to get each value.
    }

    public Cursor selectExpDate() {
        String[] cols = new String[] {FOOD_NAME, FOOD_QUANTITY, FOOD_MEASUREMENT, FOOD_EXPIRATION};
        Cursor mCursor = database.query(true, FOOD_TABLE, cols, null, null, null, null,  FOOD_EXPIRATION, null);
        int size=mCursor.getCount();
        stringArray = new String[size];
        if (mCursor != null) {
            mCursor.moveToFirst();
            FoodInfo.arrayList.clear();
                while (!mCursor.isAfterLast()) {
                    String name=mCursor.getString(0);
                    String quant=mCursor.getString(1);
                    String measure=mCursor.getString(2);
                    String expir=mCursor.getString(3);
                    FoodInfo fooditem=new FoodInfo();
                    fooditem.setName(name);
                    fooditem.setQuantity(quant);
                    fooditem.setMesure(measure);
                    fooditem.setExpirationDate(expir);
                    FoodInfo.arrayList.add(fooditem);
                    mCursor.moveToNext();
                }
        }
        return mCursor; // iterate to get each value.
    }

    public int UpdateFoodItem(String id, String quantity, String expiration){
       ContentValues values=new ContentValues();
       values.put(FOOD_QUANTITY, quantity);
       values.put(FOOD_EXPIRATION, expiration);
       return database.update(FOOD_TABLE, values, P_ID+"=?", new String[]{id});   
      }

    public void deleteComment(String id) {
        System.out.println("Comment deleted with id: " + id);
        database.delete(FOOD_TABLE, P_ID+"=?", new String[]{id});
        }

}

HttpRequest maximum allowable size in tomcat?

The connector section has the parameter

maxPostSize

The maximum size in bytes of the POST which will be handled by the container FORM URL parameter parsing. The limit can be disabled by setting this attribute to a value less than or equal to 0. If not specified, this attribute is set to 2097152 (2 megabytes).

Another Limit is:

maxHttpHeaderSize The maximum size of the request and response HTTP header, specified in bytes. If not specified, this attribute is set to 4096 (4 KB).

You find them in

$TOMCAT_HOME/conf/server.xml

PHP: if !empty & empty

For several cases, or even just a few cases involving a lot of criteria, consider using a switch.

switch( true ){

    case ( !empty($youtube) && !empty($link) ):{
        // Nothing is empty...
        break;
    }

    case ( !empty($youtube) && empty($link) ):{
        // One is empty...
        break;
    }

    case ( empty($youtube) && !empty($link) ):{
        // The other is empty...
        break;
    }

    case ( empty($youtube) && empty($link) ):{
        // Everything is empty
        break;
    }

    default:{
        // Even if you don't expect ever to use it, it's a good idea to ALWAYS have a default.
        // That way if you change it, or miss a case, you have some default handler.
        break;
    }

}

If you have multiple cases that require the same action, you can stack them and omit the break; to flowthrough. Just maybe put a comment like /*Flowing through*/ so you're explicit about doing it on purpose.

Note that the { } around the cases aren't required, but they are nice for readability and code folding.

More about switch: http://php.net/manual/en/control-structures.switch.php

In git, what is the difference between merge --squash and rebase?

Merge squash merges a tree (a sequence of commits) into a single commit. That is, it squashes all changes made in n commits into a single commit.

Rebasing is re-basing, that is, choosing a new base (parent commit) for a tree. Maybe the mercurial term for this is more clear: they call it transplant because it's just that: picking a new ground (parent commit, root) for a tree.

When doing an interactive rebase, you're given the option to either squash, pick, edit or skip the commits you are going to rebase.

Hope that was clear!

Insert string in beginning of another string

private static void appendZeroAtStart() {
        String strObj = "11";
        int maxLegth = 5;

        StringBuilder sb = new StringBuilder(strObj);
        if (sb.length() <= maxLegth) {
            while (sb.length() < maxLegth) {
                sb.insert(0, '0');
            }
        } else {
            System.out.println("error");
        }

        System.out.println("result: " + sb);

    }

Simple file write function in C++

This is a place in which C++ has a strange rule. Before being able to compile a call to a function the compiler must know the function name, return value and all parameters. This can be done by adding a "prototype". In your case this simply means adding before main the following line:

int writeFile();

this tells the compiler that there exist a function named writeFile that will be defined somewhere, that returns an int and that accepts no parameters.

Alternatively you can define first the function writeFile and then main because in this case when the compiler gets to main already knows your function.

Note that this requirement of knowing in advance the functions being called is not always applied. For example for class members defined inline it's not required...

struct Foo {
    void bar() {
        if (baz() != 99) {
            std::cout << "Hey!";
        }
    }

    int baz() {
        return 42;
    }
};

In this case the compiler has no problem analyzing the definition of bar even if it depends on a function baz that is declared later in the source code.

Use jQuery to get the file input's selected filename without the path

This alternative seems the most appropriate.

$('input[type="file"]').change(function(e){
        var fileName = e.target.files[0].name;
        alert('The file "' + fileName +  '" has been selected.');
});

Pretty printing XML in Python

As others pointed out, lxml has a pretty printer built in.

Be aware though that by default it changes CDATA sections to normal text, which can have nasty results.

Here's a Python function that preserves the input file and only changes the indentation (notice the strip_cdata=False). Furthermore it makes sure the output uses UTF-8 as encoding instead of the default ASCII (notice the encoding='utf-8'):

from lxml import etree

def prettyPrintXml(xmlFilePathToPrettyPrint):
    assert xmlFilePathToPrettyPrint is not None
    parser = etree.XMLParser(resolve_entities=False, strip_cdata=False)
    document = etree.parse(xmlFilePathToPrettyPrint, parser)
    document.write(xmlFilePathToPrettyPrint, pretty_print=True, encoding='utf-8')

Example usage:

prettyPrintXml('some_folder/some_file.xml')

Using Mockito to stub and execute methods for testing

SHORT ANSWER

How to do in your case:

int argument = 5; // example with int but could be another type
Mockito.when(mockMyAgent.otherMethod(Mockito.anyInt()).thenReturn(requiredReturnArg(argument));

LONG ANSWER

Actually what you want to do is possible, at least in Java 8. Maybe you didn't get this answer by other people because I am using Java 8 that allows that and this question is before release of Java 8 (that allows to pass functions, not only values to other functions).

Let's simulate a call to a DataBase query. This query returns all the rows of HotelTable that have FreeRoms = X and StarNumber = Y. What I expect during testing, is that this query will give back a List of different hotel: every returned hotel has the same value X and Y, while the other values and I will decide them according to my needs. The following example is simple but of course you can make it more complex.

So I create a function that will give back different results but all of them have FreeRoms = X and StarNumber = Y.

static List<Hotel> simulateQueryOnHotels(int availableRoomNumber, int starNumber) {
    ArrayList<Hotel> HotelArrayList = new ArrayList<>();
    HotelArrayList.add(new Hotel(availableRoomNumber, starNumber, Rome, 1, 1));
    HotelArrayList.add(new Hotel(availableRoomNumber, starNumber, Krakow, 7, 15));
    HotelArrayList.add(new Hotel(availableRoomNumber, starNumber, Madrid, 1, 1));
    HotelArrayList.add(new Hotel(availableRoomNumber, starNumber, Athens, 4, 1));

    return HotelArrayList;
}

Maybe Spy is better (please try), but I did this on a mocked class. Here how I do (notice the anyInt() values):

//somewhere at the beginning of your file with tests...
@Mock
private DatabaseManager mockedDatabaseManager;

//in the same file, somewhere in a test...
int availableRoomNumber = 3;
int starNumber = 4;
// in this way, the mocked queryOnHotels will return a different result according to the passed parameters
when(mockedDatabaseManager.queryOnHotels(anyInt(), anyInt())).thenReturn(simulateQueryOnHotels(availableRoomNumber, starNumber));

How to remove list elements in a for loop in Python?

You are not permitted to remove elements from the list while iterating over it using a for loop.

The best way to rewrite the code depends on what it is you're trying to do.

For example, your code is equivalent to:

for item in a:
  print item
a[:] = []

Alternatively, you could use a while loop:

while a:
  print a.pop(0)

I'm trying to remove items if they match a condition. Then I go to next item.

You could copy every element that doesn't match the condition into a second list:

result = []
for item in a:
  if condition is False:
    result.append(item)
a = result

Alternatively, you could use filter or a list comprehension and assign the result back to a:

a = filter(lambda item:... , a)

or

a = [item for item in a if ...]

where ... stands for the condition that you need to check.

Deserialize JSON with Jackson into Polymorphic Types - A Complete Example is giving me a compile error

A simple way to enable polymorphic serialization / deserialization via Jackson library is to globally configure the Jackson object mapper (jackson.databind.ObjectMapper) to add information, such as the concrete class type, for certain kinds of classes, such as abstract classes.

To do that, just make sure your mapper is configured correctly. For example:

Option 1: Support polymorphic serialization / deserialization for abstract classes (and Object typed classes)

jacksonObjectMapper.enableDefaultTyping(
    ObjectMapper.DefaultTyping.OBJECT_AND_NON_CONCRETE); 

Option 2: Support polymorphic serialization / deserialization for abstract classes (and Object typed classes), and arrays of those types.

jacksonObjectMapper.enableDefaultTyping(
    ObjectMapper.DefaultTyping.NON_CONCRETE_AND_ARRAYS); 

Reference: https://github.com/FasterXML/jackson-docs/wiki/JacksonPolymorphicDeserialization

JQuery - File attributes

Just try

var file = $("#uploadedfile").prop("files")[0];
var fileName = file.name;
var fileSize = file.size;
alert("Uploading: "+fileName+" @ "+fileSize+"bytes");

It worked for me

How to force HTTPS using a web.config file

To augment LazyOne's answer, here is an annotated version of the answer.

<rewrite>
  <rules>
     <clear />
     <rule name="Redirect all requests to https" stopProcessing="true">
       <match url="(.*)" />
         <conditions logicalGrouping="MatchAll">
           <add input="{HTTPS}" pattern="off" ignoreCase="true" />
         </conditions>
         <action 
            type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" 
            redirectType="Permanent" appendQueryString="false" />
     </rule>
  </rules>
</rewrite>

Clear all the other rules that might already been defined on this server. Create a new rule, that we will name "Redirect all requests to https". After processing this rule, do not process any more rules! Match all incoming URLs. Then check whether all of these other conditions are true: HTTPS is turned OFF. Well, that's only one condition (but make sure it's true). If it is, send a 301 Permanent redirect back to the client at http://www.foobar.com/whatever?else=the#url-contains. Don't add the query string at the end of that, because it would duplicate the query string!

This is what the properties, attributes, and some of the values mean.

  • clear removes all server rules that we might otherwise inherit.
  • rule defines a rule.
    • name an arbitrary (though unique) name for the rule.
    • stopProcessing whether to forward the request immediately to the IIS request pipeline or first to process additional rules.
  • match when to run this rule.
    • url a pattern against which to evaluate the URL
  • conditions additional conditions about when to run this rule; conditions are processed only if there is first a match.
    • logicalGrouping whether all the conditions must be true (MatchAll) or any of the conditions must be true (MatchAny); similar to AND vs OR.
  • add adds a condition that must be met.
    • input the input that a condition is evaluating; input can be server variables.
    • pattern the standard against which to evaluate the input.
    • ignoreCase whether capitalization matters or not.
  • action what to do if the match and its conditions are all true.
    • type can generally be redirect (client-side) or rewrite (server-side).
    • url what to produce as a result of this rule; in this case, concatenate https:// with two server variables.
    • redirectType what HTTP redirect to use; this one is a 301 Permanent.
    • appendQueryString whether to add the query string at the end of the resultant url or not; in this case, we are setting it to false, because the {REQUEST_URI} already includes it.

The server variables are

  • {HTTPS} which is either OFF or ON.
  • {HTTP_HOST} is www.mysite.com, and
  • {REQUEST_URI} includes the rest of the URI, e.g. /home?key=value
    • the browser handles the #fragment (see comment from LazyOne).

See also: https://www.iis.net/learn/extensions/url-rewrite-module/url-rewrite-module-configuration-reference

How to export a Hive table into a CSV file?

I have used simple linux shell piping + perl to convert hive generated output from tsv to csv.

hive -e "SELECT col1, col2, … FROM table_name" | perl -lpe 's/"/\\"/g; s/^|$/"/g; s/\t/","/g' > output_file.csv

(I got the updated perl regex from someone in stackoverflow some time ago)

The result will be like regular csv:

"col1","col2","col3"... and so on

"replace" function examples

Here's two simple examples

> x <- letters[1:4]
> replace(x, 3, 'Z') #replacing 'c' by 'Z'
[1] "a" "b" "Z" "d"
> 
> y <- 1:10
> replace(y, c(4,5), c(20,30)) # replacing 4th and 5th elements by 20 and 30
 [1]  1  2  3 20 30  6  7  8  9 10

RuntimeWarning: invalid value encountered in divide

I think your code is trying to "divide by zero" or "divide by NaN". If you are aware of that and don't want it to bother you, then you can try:

import numpy as np
np.seterr(divide='ignore', invalid='ignore')

For more details see:

Laravel eloquent update record without loading from database

You can also use firstOrCreate OR firstOrNew

// Retrieve the Post by the attributes, or create it if it doesn't exist...
$post = Post::firstOrCreate(['id' => 3]);
// OR
// Retrieve the Post by the attributes, or instantiate a new instance...
$post = Post::firstOrNew(['id' => 3]); 

// update record
$post->title = "Updated title";
$post->save();

Hope it will help you :)

Is optimisation level -O3 dangerous in g++?

-O3 option turns on more expensive optimizations, such as function inlining, in addition to all the optimizations of the lower levels ‘-O2’ and ‘-O1’. The ‘-O3’ optimization level may increase the speed of the resulting executable, but can also increase its size. Under some circumstances where these optimizations are not favorable, this option might actually make a program slower.

How to build and fill pandas dataframe from for loop?

I may be wrong, but I think the accepted answer by @amit has a bug.

from pandas import DataFrame as df
x = [1,2,3]
y = [7,8,9,10]

# this gives me a syntax error at 'for' (Python 3.7)
d1 = df[[a, "A", b, "B"] for a in x for b in y]

# this works
d2 = df([a, "A", b, "B"] for a in x for b in y)

# and if you want to add the column names on the fly
# note the additional parentheses
d3 = df(([a, "A", b, "B"] for a in x for b in y), columns = ("l","m","n","o"))

How to generate a Makefile with source in sub-directories using just one makefile

This will do it without painful manipulation or multiple command sequences:

build/%.o: src/%.cpp
src/%.o: src/%.cpp
%.o:
    $(CC) -c $< -o $@

build/test.exe: build/widgets/apple.o build/widgets/knob.o build/tests/blend.o src/ui/flash.o
    $(LD) $^ -o $@

JasperE has explained why "%.o: %.cpp" won't work; this version has one pattern rule (%.o:) with commands and no prereqs, and two pattern rules (build/%.o: and src/%.o:) with prereqs and no commands. (Note that I put in the src/%.o rule to deal with src/ui/flash.o, assuming that wasn't a typo for build/ui/flash.o, so if you don't need it you can leave it out.)

build/test.exe needs build/widgets/apple.o,
build/widgets/apple.o looks like build/%.o, so it needs src/%.cpp (in this case src/widgets/apple.cpp),
build/widgets/apple.o also looks like %.o, so it executes the CC command and uses the prereqs it just found (namely src/widgets/apple.cpp) to build the target (build/widgets/apple.o)

Using OpenSSL what does "unable to write 'random state'" mean?

Apparently, I needed to run OpenSSL as root in order for it to have permission to the seeding file.

jQuery checkbox change and click event

simply just use click event my check box id is CheckAll

     $('#CheckAll').click(function () {

        if ($('#CheckAll').is(':checked') == true) {

             alert(";)");
      }
    }

Using $setValidity inside a Controller

$setValidity needs to be called on the ngModelController. Inside the controller, I think that means $scope.myForm.file.$setValidity().

See also section "Custom Validation" on the Forms page, if you haven't already.

Also, for the first argument to $setValidity, use just 'filetype' and 'size'.

Converting a value to 2 decimal places within jQuery

Try to use this

parseFloat().toFixed(2)

How do I change Bootstrap 3's glyphicons to white?

You can just create your own .white class and add it to the glyphicon element.

.white, .white a {
  color: #fff;
}
<i class="glyphicon glyphicon-home white"></i>

How to pass a querystring or route parameter to AWS Lambda from Amazon API Gateway

As part of trying to answer one of my own questions here, I came across this trick.

In the API Gateway mapping template, use the following to give you the complete query string as sent by the HTTP client:

{
    "querystring": "$input.params().querystring"
}

The advantage is that you don't have to limit yourself to a set of predefined mapped keys in your query string. Now you can accept any key-value pairs in the query string, if this is how you want to handle.

Note: According to this, only $input.params(x) is listed as a variable made available for the VTL template. It is possible that the internals might change and querystring may no longer be available.

<xsl:variable> Print out value of XSL variable using <xsl:value-of>

Your main problem is thinking that the variable you declared outside of the template is the same variable being "set" inside the choose statement. This is not how XSLT works, the variable cannot be reassigned. This is something more like what you want:

<xsl:template match="class">
  <xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy>
  <xsl:variable name="subexists">
    <xsl:choose>
      <xsl:when test="joined-subclass">true</xsl:when>
      <xsl:otherwise>false</xsl:otherwise>
    </xsl:choose>
  </xsl:variable>
  subexists:      <xsl:value-of select="$subexists" />
</xsl:template>

And if you need the variable to have "global" scope then declare it outside of the template:

<xsl:variable name="subexists">
  <xsl:choose>
     <xsl:when test="/path/to/node/joined-subclass">true</xsl:when>
     <xsl:otherwise>false</xsl:otherwise>
  </xsl:choose>
</xsl:variable>

<xsl:template match="class">
   subexists:      <xsl:value-of select="$subexists" />
</xsl:template>

How to convert C++ Code to C

While you can do OO in C (e.g. by adding a theType *this first parameter to methods, and manually handling something like vtables for polymorphism) this is never particularly satisfactory as a design, and will look ugly (even with some pre-processor hacks).

I would suggest at least looking at a re-design to compare how this would work out.

Overall a lot depends on the answer to the key question: if you have working C++ code, why do you want C instead?

select count(*) from table of mysql in php

here is the code for showing no of rows in the table with PHP

$sql="select count(*) as total from student_table";
$result=mysqli_query($con,$sql);
$data=mysqli_fetch_assoc($result);
echo $data['total'];

What is perm space?

What exists under PremGen : Class Area comes under PremGen area. Static fields are also developed at class loading time, so they also exist in PremGen. Constant Pool area having all immutable fields that are pooled like String are kept here. In addition to that, class data loaded by class loaders, Object arrays, internal objects used by jvm are also located.

Unsafe JavaScript attempt to access frame with URL

From a child document of different origin you are not allowed access to the top window's location.hash property, but you are allowed to set the location property itself.

This means that given that the top windows location is http://example.com/page/, instead of doing

parent.location.hash = "#foobar";

you do need to know the parents location and do

parent.location = "http://example.com/page/#foobar";

Since the resource is not navigated this will work as expected, only changing the hash part of the url.

If you are using this for cross-domain communication, then I would recommend using easyXDM instead.

What does 'COLLATE SQL_Latin1_General_CP1_CI_AS' do?

It sets how the database server sorts (compares pieces of text). in this case:

SQL_Latin1_General_CP1_CI_AS

breaks up into interesting parts:

  1. latin1 makes the server treat strings using charset latin 1, basically ascii
  2. CP1 stands for Code Page 1252
  3. CI case insensitive comparisons so 'ABC' would equal 'abc'
  4. AS accent sensitive, so 'ü' does not equal 'u'

P.S. For more detailed information be sure to read @solomon-rutzky's answer.

Error: Module not specified (IntelliJ IDEA)

Faced the same issue. To solve it,

How to run a program in Atom Editor?

If you know how to launch your program from the command line then you can run it from the platformio-ide-terminal package's terminal. See platformio-ide-terminal provides an embedded terminal within the Atom text editor. So you can issue commands, including commands to run your Java program, from within it. To install this package you can use APM with the command:

$ apm install platformio-ide-terminal --no-confirm

Alternatively, you can install it from the command palette with:

  • Pressing Ctrl+Shift+P. I am assuming this is the appropriate keyboard shortcut for your platform, as you have dealt ith questions about Ubuntu in the past.
  • Type Install Packages and Themes.
  • Search for the platformio-ide-terminal.
  • Install it.

inline conditionals in angular.js

EDIT: 2Toad's answer below is what you're looking for! Upvote that thing

If you're using Angular <= 1.1.4 then this answer will do:

One more answer for this. I'm posting a separate answer, because it's more of an "exact" attempt at a solution than a list of possible solutions:

Here's a filter that will do an "immediate if" (aka iif):

app.filter('iif', function () {
   return function(input, trueValue, falseValue) {
        return input ? trueValue : falseValue;
   };
});

and can be used like this:

{{foo == "bar" | iif : "it's true" : "no, it's not"}}

Binding Combobox Using Dictionary as the Datasource

I used Sorin Comanescu's solution, but hit a problem when trying to get the selected value. My combobox was a toolstrip combobox. I used the "combobox" property, which exposes a normal combobox.

I had a

 Dictionary<Control, string> controls = new Dictionary<Control, string>();

Binding code (Sorin Comanescu's solution - worked like a charm):

 controls.Add(pictureBox1, "Image");
 controls.Add(dgvText, "Text");
 cbFocusedControl.ComboBox.DataSource = new BindingSource(controls, null);
 cbFocusedControl.ComboBox.ValueMember = "Key";
 cbFocusedControl.ComboBox.DisplayMember = "Value";

The problem was that when I tried to get the selected value, I didn't realize how to retrieve it. After several attempts I got this:

 var control = ((KeyValuePair<Control, string>) cbFocusedControl.ComboBox.SelectedItem).Key

Hope it helps someone else!

Multi-key dictionary in c#?

Here's my implementation. I wanted something to hide the implementation of the Tuple concept.

  public class TwoKeyDictionary<TKey1, TKey2, TValue> : Dictionary<TwoKey<TKey1, TKey2>, TValue>
  {
    public static TwoKey<TKey1, TKey2> Key(TKey1 key1, TKey2 key2)
    {
      return new TwoKey<TKey1, TKey2>(key1, key2);
    }

    public TValue this[TKey1 key1, TKey2 key2]
    {
      get { return this[Key(key1, key2)]; }
      set { this[Key(key1, key2)] = value; }
    }

    public void Add(TKey1 key1, TKey2 key2, TValue value)
    {
      Add(Key(key1, key2), value);
    }

    public bool ContainsKey(TKey1 key1, TKey2 key2)
    {
      return ContainsKey(Key(key1, key2));
    }
  }

  public class TwoKey<TKey1, TKey2> : Tuple<TKey1, TKey2>
  {
    public TwoKey(TKey1 item1, TKey2 item2) : base(item1, item2) { }

    public override string ToString()
    {
      return string.Format("({0},{1})", Item1, Item2);
    }
  }

It helps keeps the usage looking like a Dictionary

item.Add(1, "D", 5.6);

value = item[1, "D"];

rand() between 0 and 1

It doesn't. It makes 0 <= r < 1, but your original is 0 <= r <= 1.

Note that this can lead to undefined behavior if RAND_MAX + 1 overflows.

Change Tomcat Server's timeout in Eclipse

SOLVED: That's it!!!! For me was compiling with JDK6 but running Tomcat with JDK7, WST uses the system properties and not the eclipse settings. I also configure the same JDK Version in eclipse and in System (check it with java -version in cmd line)

Details: I try to configure eclipse like describe here, but it didn´t solve the problem, then I notice in eclipse´s error log that tomcat was started with jre 1.7. in spite of my configurations.

I also try, in cmd line, 'java -version' and obtained '1.7' instead of expected '1.6'.

I also decide to configure java 1.6 (like in eclipse) in system panel but it didn´t solve the problem. I also desinstall jre 1.7 restart eclipse AND IT SUCCESS!.. It was a very usefull clue, thank you.

How to read a value from the Windows registry

#include <windows.h>
#include <map>
#include <string>
#include <stdio.h>
#include <string.h>
#include <tr1/stdint.h>

using namespace std;

void printerr(DWORD dwerror) {
    LPVOID lpMsgBuf;
    FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER |
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        dwerror,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
        (LPTSTR) &lpMsgBuf,
        0,
        NULL
    );
    // Process any inserts in lpMsgBuf.
    // ...
    // Display the string.
    if (isOut) {
        fprintf(fout, "%s\n", lpMsgBuf);
    } else {
        printf("%s\n", lpMsgBuf);
    }
    // Free the buffer.
    LocalFree(lpMsgBuf);
}



bool regreadSZ(string& hkey, string& subkey, string& value, string& returnvalue, string& regValueType) {
    char s[128000];
    map<string,HKEY> keys;
    keys["HKEY_CLASSES_ROOT"]=HKEY_CLASSES_ROOT;
    keys["HKEY_CURRENT_CONFIG"]=HKEY_CURRENT_CONFIG; //DID NOT SURVIVE?
    keys["HKEY_CURRENT_USER"]=HKEY_CURRENT_USER;
    keys["HKEY_LOCAL_MACHINE"]=HKEY_LOCAL_MACHINE;
    keys["HKEY_USERS"]=HKEY_USERS;
    HKEY mykey;

    map<string,DWORD> valuetypes;
    valuetypes["REG_SZ"]=REG_SZ;
    valuetypes["REG_EXPAND_SZ"]=REG_EXPAND_SZ;
    valuetypes["REG_MULTI_SZ"]=REG_MULTI_SZ; //probably can't use this.

    LONG retval=RegOpenKeyEx(
        keys[hkey],         // handle to open key
        subkey.c_str(),  // subkey name
        0,   // reserved
        KEY_READ, // security access mask
        &mykey    // handle to open key
    );
    if (ERROR_SUCCESS != retval) {printerr(retval); return false;}
    DWORD slen=128000;
    DWORD valuetype = valuetypes[regValueType];
    retval=RegQueryValueEx(
      mykey,            // handle to key
      value.c_str(),  // value name
      NULL,   // reserved
      (LPDWORD) &valuetype,       // type buffer
      (LPBYTE)s,        // data buffer
      (LPDWORD) &slen      // size of data buffer
    );
    switch(retval) {
        case ERROR_SUCCESS:
            //if (isOut) {
            //    fprintf(fout,"RegQueryValueEx():ERROR_SUCCESS:succeeded.\n");
            //} else {
            //    printf("RegQueryValueEx():ERROR_SUCCESS:succeeded.\n");
            //}
            break;
        case ERROR_MORE_DATA:
            //what do I do now?  data buffer is too small.
            if (isOut) {
                fprintf(fout,"RegQueryValueEx():ERROR_MORE_DATA: need bigger buffer.\n");
            } else {
                printf("RegQueryValueEx():ERROR_MORE_DATA: need bigger buffer.\n");
            }
            return false;
        case ERROR_FILE_NOT_FOUND:
            if (isOut) {
                fprintf(fout,"RegQueryValueEx():ERROR_FILE_NOT_FOUND: registry value does not exist.\n");
            } else {
                printf("RegQueryValueEx():ERROR_FILE_NOT_FOUND: registry value does not exist.\n");
            }
            return false;
        default:
            if (isOut) {
                fprintf(fout,"RegQueryValueEx():unknown error type 0x%lx.\n", retval);
            } else {
                printf("RegQueryValueEx():unknown error type 0x%lx.\n", retval);
            }
            return false;

    }
    retval=RegCloseKey(mykey);
    if (ERROR_SUCCESS != retval) {printerr(retval); return false;}

    returnvalue = s;
    return true;
}

Update select2 data without rebuilding the control

select2 v3.x

If you have local array with options (received by ajax call), i think you should use data parameter as function returning results for select box:

var pills = [{id:0, text: "red"}, {id:1, text: "blue"}]; 

$('#selectpill').select2({
    placeholder: "Select a pill",
    data: function() { return {results: pills}; }
});

$('#uppercase').click(function() {
    $.each(pills, function(idx, val) {
        pills[idx].text = val.text.toUpperCase();
    });
});
$('#newresults').click(function() {
    pills = [{id:0, text: "white"}, {id:1, text: "black"}];
});

FIDDLE: http://jsfiddle.net/RVnfn/576/

In case if you customize select2 interface with buttons, just call updateResults (this method not allowed to call from outsite of select2 object but you can add it to allowedMethods array in select2 if you need to) method after updateting data array(pills in example).


select2 v4: custom data adapter

Custom data adapter with additional updateOptions (its unclear why original ArrayAdapter lacks this functionality) method can be used to dynamically update options list (all options in this example):

$.fn.select2.amd.define('select2/data/customAdapter',
    ['select2/data/array', 'select2/utils'],
    function (ArrayAdapter, Utils) {
        function CustomDataAdapter ($element, options) {
            CustomDataAdapter.__super__.constructor.call(this, $element, options);
        }
        Utils.Extend(CustomDataAdapter, ArrayAdapter);
        CustomDataAdapter.prototype.updateOptions = function (data) {
            this.$element.find('option').remove(); // remove all options
            this.addOptions(this.convertToOptions(data));
        }        
        return CustomDataAdapter;
    }
);

var customAdapter = $.fn.select2.amd.require('select2/data/customAdapter');

var sel = $('select').select2({
    dataAdapter: customAdapter,
    data: pills
});

$('#uppercase').click(function() {
    $.each(pills, function(idx, val) {
        pills[idx].text = val.text.toUpperCase();
    });
    sel.data('select2').dataAdapter.updateOptions(pills);
});

FIDDLE: https://jsfiddle.net/xu48n36c/1/


select2 v4: ajax transport function

in v4 you can define custom transport method that can work with local data array (thx @Caleb_Kiage for example, i've played with it without succes)

docs: https://select2.github.io/options.html#can-an-ajax-plugin-other-than-jqueryajax-be-used

Select2 uses the transport method defined in ajax.transport to send requests to your API. By default, this transport method is jQuery.ajax but this can be changed.

$('select').select2({
    ajax: {
        transport: function(params, success, failure) {
            var items = pills;
            // fitering if params.data.q available
            if (params.data && params.data.q) {
                items = items.filter(function(item) {
                    return new RegExp(params.data.q).test(item.text);
                });
            }
            var promise = new Promise(function(resolve, reject) {
                resolve({results: items});
            });
            promise.then(success);
            promise.catch(failure);
        }
    }
});

BUT with this method you need to change ids of options if text of option in array changes - internal select2 dom option element list did not modified. If id of option in array stay same - previous saved option will be displayed instead of updated from array! That is not problem if array modified only by adding new items to it - ok for most common cases.

FIDDLE: https://jsfiddle.net/xu48n36c/3/

What is the convention in JSON for empty vs. null?

It is good programming practice to return an empty array [] if the expected return type is an array. This makes sure that the receiver of the json can treat the value as an array immediately without having to first check for null. It's the same way with empty objects using open-closed braces {}.

Strings, Booleans and integers do not have an 'empty' form, so there it is okay to use null values.

This is also addressed in Joshua Blochs excellent book "Effective Java". There he describes some very good generic programming practices (often applicable to other programming langages as well). Returning empty collections instead of nulls is one of them.

Here's a link to that part of his book:

http://jtechies.blogspot.nl/2012/07/item-43-return-empty-arrays-or.html

Prepend text to beginning of string

EcmaScript 2017 added special functions to string prototype for that. padStart and padEnd are two new methods available in JavaScript string prototype object. As their name implies, they allow for formatting a string by adding padding characters at the start or the end. (Not supported by IE11 and lower)

var mystr = "Doe";
mystr = mystr.padStart('John ');

generate model using user:references vs user_id:integer

Both will generate the same columns when you run the migration. In rails console, you can see that this is the case:

:001 > Micropost
=> Micropost(id: integer, user_id: integer, created_at: datetime, updated_at: datetime)

The second command adds a belongs_to :user relationship in your Micropost model whereas the first does not. When this relationship is specified, ActiveRecord will assume that the foreign key is kept in the user_id column and it will use a model named User to instantiate the specific user.

The second command also adds an index on the new user_id column.

Tensorflow set CUDA_VISIBLE_DEVICES within jupyter

You can do it faster without any imports just by using magics:

%env CUDA_DEVICE_ORDER=PCI_BUS_ID
%env CUDA_VISIBLE_DEVICES=0

Notice that all env variable are strings, so no need to use ". You can verify that env-variable is set up by running: %env <name_of_var>. Or check all of them with %env.

Setting DEBUG = False causes 500 Error

Complementing the main answer
It is annoying to change the ALLOWED_HOSTS and DEBUG global constants in settings.py when switching between development and production. I am using this code to set these setting automatically:

import socket

if socket.gethostname() == "server_name":
    DEBUG = False
    ALLOWED_HOSTS = [".your_domain_name.com",]
    ...
else:
    DEBUG = True
    ALLOWED_HOSTS = ["localhost", "127.0.0.1",]
    ...

If you use macOS you could write a more generic code:

if socket.gethostname().endswith(".local"): # True in your local computer
    DEBUG = True
    ALLOWED_HOSTS = ["localhost", "127.0.0.1",]
else:
    ...

How do I extract data from a DataTable?

  var table = Tables[0]; //get first table from Dataset
  foreach (DataRow row in table.Rows)
     {
       foreach (var item in row.ItemArray)
         {
            console.Write("Value:"+item);
         }
     }

YAML equivalent of array of objects in JSON

Great answer above. Another way is to use the great yaml jq wrapper tool, yq at https://github.com/kislyuk/yq

Save your JSON example to a file, say ex.json and then

yq -y '.' ex.json

AAPL:
- shares: -75.088
  date: 11/27/2015
- shares: 75.088
  date: 11/26/2015

Can you get the column names from a SqlDataReader?

var reader = cmd.ExecuteReader();

var columns = new List<string>();

for(int i=0;i<reader.FieldCount;i++)
{
   columns.Add(reader.GetName(i));
}

or

var columns = Enumerable.Range(0, reader.FieldCount).Select(reader.GetName).ToList();

How to rename files and folder in Amazon S3?

This works for renaming the file in the same folder

aws s3  mv s3://bucketname/folder_name1/test_original.csv s3://bucket/folder_name1/test_renamed.csv

Adding a Method to an Existing Object Instance

This is actually an addon to the answer of "Jason Pratt"

Although Jasons answer works, it does only work if one wants to add a function to a class. It did not work for me when I tried to reload an already existing method from the .py source code file.

It took me for ages to find a workaround, but the trick seems simple... 1.st import the code from the source code file 2.nd force a reload 3.rd use types.FunctionType(...) to convert the imported and bound method to a function you can also pass on the current global variables, as the reloaded method would be in a different namespace 4.th now you can continue as suggested by "Jason Pratt" using the types.MethodType(...)

Example:

# this class resides inside ReloadCodeDemo.py
class A:
    def bar( self ):
        print "bar1"
        
    def reloadCode(self, methodName):
        ''' use this function to reload any function of class A'''
        import types
        import ReloadCodeDemo as ReloadMod # import the code as module
        reload (ReloadMod) # force a reload of the module
        myM = getattr(ReloadMod.A,methodName) #get reloaded Method
        myTempFunc = types.FunctionType(# convert the method to a simple function
                                myM.im_func.func_code, #the methods code
                                globals(), # globals to use
                                argdefs=myM.im_func.func_defaults # default values for variables if any
                                ) 
        myNewM = types.MethodType(myTempFunc,self,self.__class__) #convert the function to a method
        setattr(self,methodName,myNewM) # add the method to the function

if __name__ == '__main__':
    a = A()
    a.bar()
    # now change your code and save the file
    a.reloadCode('bar') # reloads the file
    a.bar() # now executes the reloaded code

How to connect HTML Divs with Lines?

Definitely possible with any number of libraries and/or HTML5 technologies. You could possible hack something together in pure CSS by using something like the border-bottom property, but it would probably be horribly hacky.

If you're serious about this, you should take a look at a JS library for canvas drawing or SVG. For example, something like http://www.graphjs.org/ or http://jsdraw2dx.jsfiction.com/

What is the difference between fastcgi and fpm?

Running PHP as a CGI means that you basically tell your web server the location of the PHP executable file, and the server runs that executable

whereas

PHP FastCGI Process Manager (PHP-FPM) is an alternative FastCGI daemon for PHP that allows a website to handle strenuous loads. PHP-FPM maintains pools (workers that can respond to PHP requests) to accomplish this. PHP-FPM is faster than traditional CGI-based methods, such as SUPHP, for multi-user PHP environments

However, there are pros and cons to both and one should choose as per their specific use case.

I found info on this link for fastcgi vs fpm quite helpful in choosing which handler to use in my scenario.

Bootstrap 3: Offset isn't working?

Which version of bootstrap are you using? The early versions of Bootstrap 3 (3.0, 3.0.1) didn't work with this functionality.

col-md-offset-0 should be working as seen in this bootstrap example found here (http://getbootstrap.com/css/#grid-responsive-resets):

<div class="row">
   <div class="col-sm-5 col-md-6">.col-sm-5 .col-md-6</div>
   <div class="col-sm-5 col-sm-offset-2 col-md-6 col-md-offset-0">.col-sm-5 .col-sm-offset-2 .col-md-6 .col-md-offset-0</div>
</div>

Assert an object is a specific type

Solution for JUnit 5

The documentation says:

However, JUnit Jupiter’s org.junit.jupiter.Assertions class does not provide an assertThat() method like the one found in JUnit 4’s org.junit.Assert class which accepts a Hamcrest Matcher. Instead, developers are encouraged to use the built-in support for matchers provided by third-party assertion libraries.

Example for Hamcrest:

import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;

import org.junit.jupiter.api.Test;

class HamcrestAssertionDemo {

    @Test
    void assertWithHamcrestMatcher() {
        SubClass subClass = new SubClass();
        assertThat(subClass, instanceOf(BaseClass.class));
    }

}

Example for AssertJ:

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.jupiter.api.Test;

class AssertJDemo {

    @Test
    void assertWithAssertJ() {
        SubClass subClass = new SubClass();
        assertThat(subClass).isInstanceOf(BaseClass.class);
    }

}

Note that this assumes you want to test behaviors similar to instanceof (which accepts subclasses). If you want exact equal type, I don’t see a better way than asserting the two class to be equal like you mentioned in the question.

How to compare values which may both be null in T-SQL

Use ISNULL:

ISNULL(MY_FIELD1, 'NULL') = ISNULL(@IN_MY_FIELD1, 'NULL')

You can change 'NULL' to something like 'All Values' if it makes more sense to do so.

It should be noted that with two arguments, ISNULL works the same as COALESCE, which you could use if you have a few values to test (i.e.-COALESCE(@IN_MY_FIELD1, @OtherVal, 'NULL')). COALESCE also returns after the first non-null, which means it's (marginally) faster if you expect MY_FIELD1 to be blank. However, I find ISNULL much more readable, so that's why I used it, here.

Troubleshooting "Warning: session_start(): Cannot send session cache limiter - headers already sent"

For others who may run across this - it can also occur if someone carelessly leaves trailing spaces from a php include file. Example:

 <?php 
    require_once('mylib.php');
    session_start();
 ?>

In the case above, if the mylib.php has blank spaces after its closing ?> tag, this will cause an error. This obviously can get annoying if you've included/required many files. Luckily the error tells you which file is offending.

HTH

Detecting iOS orientation change instantly

Try making your changes in:

- (void) viewWillLayoutSubviews {}

The code will run at every orientation change as the subviews get laid out again.

Python: Fetch first 10 results from a list

list[:10]

will give you the first 10 elements of this list using slicing.

However, note, it's best not to use list as a variable identifier as it's already used by Python: list()

To find out more about these type of operations you might find this tutorial on lists helpful and the link @DarenThomas provided Explain Python's slice notation - thanks Daren)

Proper way to concatenate variable strings

Good question. But I think there is no good answer which fits your criteria. The best I can think of is to use an extra vars file.

A task like this:

- include_vars: concat.yml

And in concat.yml you have your definition:

newvar: "{{ var1 }}-{{ var2 }}-{{ var3 }}"

Cache an HTTP 'Get' service response in AngularJS?

angularBlogServices.factory('BlogPost', ['$resource',
    function($resource) {
        return $resource("./Post/:id", {}, {
            get:    {method: 'GET',    cache: true,  isArray: false},
            save:   {method: 'POST',   cache: false, isArray: false},
            update: {method: 'PUT',    cache: false, isArray: false},
            delete: {method: 'DELETE', cache: false, isArray: false}
        });
    }]);

set cache to be true.

How to get the clicked link's href with jquery?

You're looking for $(this).attr("href");

How to check the version before installing a package using apt-get?

Also, according to the man page:

apt-cache showpkg <package_name>

can also be used to:

...display information about the packages listed on the command line. Remaining arguments are package names. The available versions and reverse dependencies of each package listed are listed, as well as forward dependencies for each version. Forward (normal) dependencies are those packages upon which the package in question depends; reverse dependencies are those packages that depend upon the package in question. Thus, forward dependencies must be satisfied for a package, but reverse dependencies need not be.

Ex:

apt-cache policy conky

conky:
  Installed: (none)
  Candidate: 1.10.3-1
  Version table:
     1.10.3-1 500
        500 http://us.archive.ubuntu.com/ubuntu yakkety/universe amd64 Packages
        500 http://us.archive.ubuntu.com/ubuntu yakkety/universe i386 Packages

How to initialize a private static const map in C++?

I did it! :)

Works fine without C++11

class MyClass {
    typedef std::map<std::string, int> MyMap;

    struct T {
        const char* Name;
        int Num;

        operator MyMap::value_type() const {
            return std::pair<std::string, int>(Name, Num);
        }
    };

    static const T MapPairs[];
    static const MyMap TheMap;
};

const MyClass::T MyClass::MapPairs[] = {
    { "Jan", 1 }, { "Feb", 2 }, { "Mar", 3 }
};

const MyClass::MyMap MyClass::TheMap(MapPairs, MapPairs + 3);

How to create web service (server & Client) in Visual Studio 2012?

WCF is a newer technology that is a viable alternative in many instances. ASP is great and works well, but I personally prefer WCF. And you can do it in .Net 4.5.

WCF Project

enter image description here

Create a new project. enter image description here Right-Click on the project in solution explorer, select "Add Service Reference" enter image description here

Create a textbox and button in the new application. Below is my click event for the button:

private void btnGo_Click(object sender, EventArgs e)
    {
        ServiceReference1.Service1Client testClient = new ServiceReference1.Service1Client();
        //Add error handling, null checks, etc...
        int iValue = int.Parse(txtInput.Text);
        string sResult = testClient.GetData(iValue).ToString();
        MessageBox.Show(sResult);
    }

And you're done. enter image description here

Call int() function on every list element?

Thought I'd consolidate the answers and show some timeit results.

Python 2 sucks pretty bad at this, but map is a bit faster than comprehension.

Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:42:59) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import timeit
>>> setup = """import random
random.seed(10)
l = [str(random.randint(0, 99)) for i in range(100)]"""
>>> timeit.timeit('[int(v) for v in l]', setup)
116.25092001434314
>>> timeit.timeit('map(int, l)', setup)
106.66044823117454

Python 3 is over 4x faster by itself, but converting the map generator object to a list is still faster than comprehension, and creating the list by unpacking the map generator (thanks Artem!) is slightly faster still.

Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 17:54:52) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import timeit
>>> setup = """import random
random.seed(10)
l = [str(random.randint(0, 99)) for i in range(100)]"""
>>> timeit.timeit('[int(v) for v in l]', setup)
25.133059591551955
>>> timeit.timeit('list(map(int, l))', setup)
19.705547827217515
>>> timeit.timeit('[*map(int, l)]', setup)
19.45838406513076

Note: In Python 3, 4 elements seems to be the crossover point (3 in Python 2) where comprehension is slightly faster, though unpacking the generator is still faster than either for lists with more than 1 element.

Free Online Team Foundation Server

VSO is now Azure DevOps https://visualstudio.microsoft.com/vso

Recently Microsoft Visual Studio Online (VSO) is now Azure DevOps

How to convert an integer (time) to HH:MM:SS::00 in SQL Server 2008?

CREATE FUNCTION [dbo].[_ICAN_FN_IntToTime](@Num INT)
  RETURNS NVARCHAR(13)
AS
-------------------------------------------------------------------------------------------------------------------
--INVENTIVE:Keyvan ARYAEE-MOEEN
-------------------------------------------------------------------------------------------------------------------
  BEGIN
    DECLARE @Hour VARCHAR(10)=CAST(@Num/3600 AS  VARCHAR(2))
    DECLARE @Minute VARCHAR(10)=CAST((@Num-@Hour*3600)/60 AS  VARCHAR(2))
    DECLARE @Time VARCHAR(13)=CASE WHEN @Hour<10 THEN '0'+@Hour ELSE @Hour END+':'+CASE WHEN @Minute<10 THEN '0'+@Minute ELSE @Minute END+':00.000'
    RETURN @Time
  END
-------------------------------------------------------------------------------------------------------------------
--SELECT dbo._ICAN_FN_IntToTime(25500)
-------------------------------------------------------------------------------------------------------------------

pip install from git repo branch

Instructions to install from private repo using ssh credentials:

$ pip install git+ssh://[email protected]/myuser/foo.git@my_version

How do I solve this "Cannot read property 'appendChild' of null" error?

The element hasn't been appended yet, therefore it is equal to null. The Id will never = 0. When you call getElementById(id), it is null since it is not a part of the dom yet unless your static id is already on the DOM. Do a call through the console to see what it returns.

Converting between java.time.LocalDateTime and java.util.Date

Everything is here : http://blog.progs.be/542/date-to-java-time

The answer with "round-tripping" is not exact : when you do

LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneOffset.UTC);

if your system timezone is not UTC/GMT, you change the time !

Is it possible to change the package name of an Android app on Google Play?

If you are referring to com.example.app, no I understand you can't it would be considered a new app

Using filesystem in node.js with async / await

Native support for async await fs functions since Node 11

Since Node.JS 11.0.0 (stable), and version 10.0.0 (experimental), you have access to file system methods that are already promisify'd and you can use them with try catch exception handling rather than checking if the callback's returned value contains an error.

The API is very clean and elegant! Simply use .promises member of fs object:

import fs from 'fs';
const fsPromises = fs.promises;

async function listDir() {
  try {
    return fsPromises.readdir('path/to/dir');
  } catch (err) {
    console.error('Error occured while reading directory!', err);
  }
}

listDir();

Open a workbook using FileDialog and manipulate it in Excel VBA

Thankyou Frank.i got the idea. Here is the working code.

Option Explicit
Private Sub CommandButton1_Click()

  Dim directory As String, fileName As String, sheet As Worksheet, total As Integer
  Dim fd As Office.FileDialog

  Set fd = Application.FileDialog(msoFileDialogFilePicker)

  With fd
    .AllowMultiSelect = False
    .Title = "Please select the file."
    .Filters.Clear
    .Filters.Add "Excel 2003", "*.xls?"

    If .Show = True Then
      fileName = Dir(.SelectedItems(1))

    End If
  End With

  Application.ScreenUpdating = False
  Application.DisplayAlerts = False

  Workbooks.Open (fileName)

  For Each sheet In Workbooks(fileName).Worksheets
    total = Workbooks("import-sheets.xlsm").Worksheets.Count
    Workbooks(fileName).Worksheets(sheet.Name).Copy _
        after:=Workbooks("import-sheets.xlsm").Worksheets(total)
  Next sheet

  Workbooks(fileName).Close

  Application.ScreenUpdating = True
  Application.DisplayAlerts = True

End Sub

How can I delete a query string parameter in JavaScript?

Assuming you want to remove key=val parameter from URI:

function removeParam(uri) {
   return uri.replace(/([&\?]key=val*$|key=val&|[?&]key=val(?=#))/, '');
}

How can I truncate a string to the first 20 words in PHP?

This worked me for UNICODE (UTF8) sentences too:

function myUTF8truncate($string, $width){
    if (mb_str_word_count($string) > $width) {
        $string= preg_replace('/((\w+\W*|| [\p{L}]+\W*){'.($width-1).'}(\w+))(.*)/', '${1}', $string);
    }
    return $string;
}

Difference between break and continue in PHP?

break will exit the loop, while continue will start the next cycle of the loop immediately.

With android studio no jvm found, JAVA_HOME has been set

For me the case was completely different. I had created a studio64.exe.vmoptions file in C:\Users\YourUserName\.AndroidStudio3.4\config. In that folder, I had a typo of extra spaces. Due to that I was getting the same error.

I replaced the studio64.exe.vmoptions with the following code.

# custom Android Studio VM options, see https://developer.android.com/studio/intro/studio-config.html

-server
-Xms1G
-Xmx8G
# I have 8GB RAM so it is 8G. Replace it with your RAM size.
-XX:MaxPermSize=1G
-XX:ReservedCodeCacheSize=512m
-XX:+UseCompressedOops
-XX:+UseConcMarkSweepGC
-XX:SoftRefLRUPolicyMSPerMB=50
-da
-Djna.nosys=true
-Djna.boot.library.path=

-Djna.debug_load=true
-Djna.debug_load.jna=true
-Dsun.io.useCanonCaches=false
-Djava.net.preferIPv4Stack=true
-XX:+HeapDumpOnOutOfMemoryError
-Didea.paths.selector=AndroidStudio2.1
-Didea.platform.prefix=AndroidStudio

How to change the size of the radio button using CSS?

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
  <title>Bootstrap Example</title>_x000D_
  <meta charset="utf-8">_x000D_
  <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
  <style>_x000D_
input[type="radio"] {_x000D_
    -ms-transform: scale(1.5); /* IE 9 */_x000D_
    -webkit-transform: scale(1.5); /* Chrome, Safari, Opera */_x000D_
    transform: scale(1.5);_x000D_
}_x000D_
  </style>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div class="container">_x000D_
  <h2>Form control: inline radio buttons</h2>_x000D_
  <p>The form below contains three inline radio buttons:</p>_x000D_
  <form>_x000D_
    <label class="radio-inline">_x000D_
      <input type="radio" name="optradio">Option 1_x000D_
    </label>_x000D_
    <label class="radio-inline">_x000D_
      <input type="radio" name="optradio">Option 2_x000D_
    </label>_x000D_
    <label class="radio-inline">_x000D_
      <input type="radio" name="optradio">Option 3_x000D_
    </label>_x000D_
  </form>_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Mysql - delete from multiple tables with one query

You can use following query to delete rows from multiple tables,

DELETE table1, table2, table3 FROM table1 INNER JOIN table2 INNER JOIN table3 WHERE table1.userid = table2.userid AND table2.userid = table3.userid AND table1.userid=3

Laravel 5 error SQLSTATE[HY000] [1045] Access denied for user 'homestead'@'localhost' (using password: YES)

I had the same problem, so I realized that the .env file does not accept special characters, as my password has these characters, I added the password in the config/database.php file.

Why my regexp for hyphenated words doesn't work?

You can use this:

r'[a-z]+(?:-[a-z]+)*' 

Dark Theme for Visual Studio 2010 With Productivity Power Tools

  1. Install the Visual Studio Color Theme Editor extension:
  2. Make your own color scheme or try: The Dark Expression Blend Color Theme (preview below)
  3. Once you have that, you'll want schemes for the text editor as well. This site has several, including the VS2012 "dark" theme implemented for VS2010.

Visual Studio 2010 with Dark Theme

Short description of the scoping rules?

In Python,

any variable that is assigned a value is local to the block in which the assignment appears.

If a variable can't be found in the current scope, please refer to the LEGB order.

Count Vowels in String Python

For anyone who looking the most simple solution, here's the one

vowel = ['a', 'e', 'i', 'o', 'u']
Sentence = input("Enter a phrase: ")
count = 0
for letter in Sentence:
    if letter in vowel:
        count += 1
print(count)

Is it safe to use Project Lombok?

Lombok is great, but...

Lombok breaks the rules of annotation processing, in that it doesn't generate new source files. This means it cant be used with another annotation processors if they expect the getters/setters or whatever else to exist.

Annotation processing runs in a series of rounds. In each round, each one gets a turn to run. If any new java files are found after the round is completed, another round begins. In this way, the order of annotation processors doesn't matter if they only generate new files. Since lombok doesn't generate any new files, no new rounds are started so some AP that relies on lombok code don't run as expected. This was a huge source of pain for me while using mapstruct, and delombok-ing isn't a useful option since it destroys your line numbers in logs.

I eventually hacked a build script to work with both lombok and mapstruct. But I want to drop lombok due to how hacky it is -- in this project at least. I use lombok all the time in other stuff.

Allow scroll but hide scrollbar

I know this is an oldie but here is a quick way to hide the scroll bar with pure CSS.

Just add

::-webkit-scrollbar {display:none;}

To your id or class of the div you're using the scroll bar with.

Here is a helpful link Custom Scroll Bar in Webkit

Angular 2 Scroll to bottom (Chat style)

Sharing my solution, because I was not completely satisfied with the rest. My problem with AfterViewChecked is that sometimes I'm scrolling up, and for some reason, this life hook gets called and it scrolls me down even if there were no new messages. I tried using OnChanges but this was an issue, which lead me to this solution. Unfortunately, using only DoCheck, it was scrolling down before the messages were rendered, which was not useful either, so I combined them so that DoCheck is basically indicating AfterViewChecked if it should call scrollToBottom.

Happy to receive feedback.

export class ChatComponent implements DoCheck, AfterViewChecked {

    @Input() public messages: Message[] = [];
    @ViewChild('scrollable') private scrollable: ElementRef;

    private shouldScrollDown: boolean;
    private iterableDiffer;

    constructor(private iterableDiffers: IterableDiffers) {
        this.iterableDiffer = this.iterableDiffers.find([]).create(null);
    }

    ngDoCheck(): void {
        if (this.iterableDiffer.diff(this.messages)) {
            this.numberOfMessagesChanged = true;
        }
    }

    ngAfterViewChecked(): void {
        const isScrolledDown = Math.abs(this.scrollable.nativeElement.scrollHeight - this.scrollable.nativeElement.scrollTop - this.scrollable.nativeElement.clientHeight) <= 3.0;

        if (this.numberOfMessagesChanged && !isScrolledDown) {
            this.scrollToBottom();
            this.numberOfMessagesChanged = false;
        }
    }

    scrollToBottom() {
        try {
            this.scrollable.nativeElement.scrollTop = this.scrollable.nativeElement.scrollHeight;
        } catch (e) {
            console.error(e);
        }
    }

}

chat.component.html

<div class="chat-wrapper">

    <div class="chat-messages-holder" #scrollable>

        <app-chat-message *ngFor="let message of messages" [message]="message">
        </app-chat-message>

    </div>

    <div class="chat-input-holder">
        <app-chat-input (send)="onSend($event)"></app-chat-input>
    </div>

</div>

chat.component.sass

.chat-wrapper
  display: flex
  justify-content: center
  align-items: center
  flex-direction: column
  height: 100%

  .chat-messages-holder
    overflow-y: scroll !important
    overflow-x: hidden
    width: 100%
    height: 100%

How to purge tomcat's cache when deploying a new .war file? Is there a config setting?

Sounds like your class loader is not loading the servlet classes once they are updated. This might be fixed if you change your web.xml file which should prompt the server/container to re-deploy and reload the servlet classes. I guess add an empty line at the end of your web.xml and save it and then see if that fixes it. As i said this might fix it or might not.

Good luck!

how to compare the Java Byte[] array?

Cause they're not equal, ie: they're different arrays with equal elements inside.

Try using Arrays.equals() or Arrays.deepEquals().

Convert floating point number to a certain precision, and then copy to string

Python 3.6

Just to make it clear, you can use f-string formatting. This has almost the same syntax as the format method, but make it a bit nicer.

Example:

print(f'{numvar:.9f}')

More reading about the new f string:

Here is a diagram of the execution times of the various tested methods (from last link above):

execution times

How to fix Python Numpy/Pandas installation?

Don't know if you solved the problem but if anyone has this problem in future.

$python
>>import numpy
>>print(numpy)

Go to the location printed and delete the numpy installation found there. You can then use pip or easy_install

PDF to byte array and vice versa

This works for me:

try(InputStream pdfin = new FileInputStream("input.pdf");OutputStream pdfout = new FileOutputStream("output.pdf")){
    byte[] buffer = new byte[1024];
    int bytesRead;
    while((bytesRead = pdfin.read(buffer))!=-1){
        pdfout.write(buffer,0,bytesRead);
    }
}

But Jon's answer doesn't work for me if used in the following way:

try(InputStream pdfin = new FileInputStream("input.pdf");OutputStream pdfout = new FileOutputStream("output.pdf")){

    int k = readFully(pdfin).length;
    System.out.println(k);
}

Outputs zero as length. Why is that ?

C++ "was not declared in this scope" compile error

fix function declaration on

int nonrecursivecountcells(color grid[ROW_SIZE][COL_SIZE], int row, int column)

How to build and run Maven projects after importing into Eclipse IDE

  1. Right Click on your project
  2. Go to Maven>Update Project
  3. Check the Force Update of Snapshots/Releases Checkbox
  4. Click Ok

That's all. You can see progression of build in left below corner.

What's is the difference between train, validation and test set, in neural networks?

We create a validation set to

  • Measure how well a model generalizes, during training
  • Tell us when to stop training a model;When the validation loss stops decreasing (and especially when the validation loss starts increasing and the training loss is still decreasing)

Why validation set used:

Why validation set used

Convert UTC date time to local date time

For the TypeScript users, here is a helper function:

// Typescript Type: Date Options
interface DateOptions {
  day: 'numeric' | 'short' | 'long',
  month: 'numeric',
  year: 'numeric',
  timeZone: 'UTC',
};

// Helper Function: Convert UTC Date To Local Date
export const convertUTCDateToLocalDate = (date: Date) => {
  // Date Options
  const dateOptions: DateOptions = {
    day: 'numeric',
    month: 'numeric',
    year: 'numeric',
    timeZone: 'UTC',
  };

  // Formatted Date (4/20/2020)
  const formattedDate = new Date(date.getTime() - date.getTimezoneOffset() * 60 * 1000).toLocaleString('en-US', dateOptions);
  return formattedDate;
};

Global variables in Javascript across multiple files

//Javascript file 1

localStorage.setItem('Data',10);

//Javascript file 2

var number=localStorage.getItem('Data');

Don't forget to link your JS files in html :)

Fatal Error: Allowed Memory Size of 134217728 Bytes Exhausted (CodeIgniter + XML-RPC)

In Drupal 7, you can modify the memory limit in the settings.php file located in your sites/default folder. Around line 260, you'll see this:

ini_set('memory_limit', '128M');

Even if your php.ini settings are high enough, you won't be able to consume more than 128 MB if this isn't set in your Drupal settings.php file.

PHP: Calling another class' method

You would need to have an instance of ClassA within ClassB or have ClassB inherit ClassA

class ClassA {
    public function getName() {
      echo $this->name;
    }
}

class ClassB extends ClassA {
    public function getName() {
      parent::getName();
    }
}

Without inheritance or an instance method, you'd need ClassA to have a static method

class ClassA {
  public static function getName() {
    echo "Rawkode";
  }
}

--- other file ---

echo ClassA::getName();

If you're just looking to call the method from an instance of the class:

class ClassA {
  public function getName() {
    echo "Rawkode";
  }
}

--- other file ---

$a = new ClassA();
echo $a->getName();

Regardless of the solution you choose, require 'ClassA.php is needed.