Programs & Examples On #Undelete

Reload the page after ajax success

use this Reload page

success: function(data){
   if(data.success == true){ // if true (1)
      setTimeout(function(){// wait for 5 secs(2)
           location.reload(); // then reload the page.(3)
      }, 5000); 
   }
}

The Definitive C Book Guide and List

Warning!

This is a list of random books of diverse quality. In the view of some people (with some justification), it is no longer a list of recommended books. Some of the listed books contain blatantly incorrect statements or teach wrong/harmful practices. People who are aware of such books can edit this answer to help improve it. See The C book list has gone haywire. What to do with it?, and also Deleted question audit 2018.

Reference (All Levels)

  • The C Programming Language (2nd Edition) - Brian W. Kernighan and Dennis M. Ritchie (1988). Still a good, short but complete introduction to C (C90, not C99 or later versions), written by the inventor of C. However, the language has changed and good C style has developed in the last 25 years, and there are parts of the book that show its age.

  • C: A Reference Manual (5th Edition) - Samuel P. Harbison and Guy R. Steele (2002). An excellent reference book on C, up to and including C99. It is not a tutorial, and probably unfit for beginners. It's great if you need to write a compiler for C, as the authors had to do when they started.

  • C Pocket Reference (O'Reilly) - Peter Prinz and Ulla Kirch-Prinz (2002).

  • The comp.lang.c FAQ - Steve Summit. Web site with answers to many questions about C.

  • Various versions of the C language standards can be found here. There is an online version of the draft C11 standard.

  • The new C standard - an annotated reference (Free PDF) - Derek M. Jones (2009). The "new standard" referred to is the old C99 standard rather than C11.

  • Rationale for C99 Standard.


Beginner

  • C In Easy Steps (5th Edition) - Mike McGrath (2018). It is a good book for learning and referencing C.

  • Effective C - Robert C Seacord (2020). A good introduction to modern C, including chapters on dynamic memory allocation, on program structure, and on debugging, testing and analysis. It has some pointers toward probable C2x features.

Intermediate

  • Modern C — Jens Gustedt (2017 1st Edn; 2020 2nd Edn). Covers C in 5 levels (encounter, acquaintance, cognition, experience, ambition) from beginning C to advanced C. It covers C11 and C17, including threads and atomic access, which few other books do. Not all compilers recognize these features in all environments.

  • C Interfaces and Implementations - David R. Hanson (1997). Provides information on how to define a boundary between an interface and implementation in C in a generic and reusable fashion. It also demonstrates this principle by applying it to the implementation of common mechanisms and data structures in C, such as lists, sets, exceptions, string manipulation, memory allocators, and more. Basically, Hanson took all the code he'd written as part of building Icon and lcc and pulled out the best bits in a form that other people could reuse for their own projects. It's a model of good C programming using modern design techniques (including Liskov's data abstraction), showing how to organize a big C project as a bunch of useful libraries.

  • The C Puzzle Book - Alan R. Feuer (1998)

  • The Standard C Library - P.J. Plauger (1992). It contains the complete source code to an implementation of the C89 standard library, along with extensive discussions about the design and why the code is designed as shown.

  • 21st Century C: C Tips from the New School - Ben Klemens (2012). In addition to the C language, the book explains gdb, valgrind, autotools, and git. The comments on style are found in the last part (Chapter 6 and beyond).

  • Algorithms in C - Robert Sedgewick (1997). Gives you a real grasp of implementing algorithms in C. Very lucid and clear; will probably make you want to throw away all of your other algorithms books and keep this one.

  • Extreme C: Push the limits of what C and you can do - Kamran Amini (2019). This book builds on your existing C knowledge to help you become a more expert C programmer. You will gain insights into algorithm design, functions, and structures, and understand both multi-threading and multi-processing in a POSIX environment.

Expert


Uncategorized

  • Essential C (Free PDF) - Nick Parlante (2003). Note that this describes the C90 language at several points (e.g., in discussing // comments and placement of variable declarations at arbitrary points in the code), so it should be treated with some caution.

  • C Programming FAQs: Frequently Asked Questions - Steve Summit (1995). This is the book of the web site listed earlier. It doesn't cover C99 or the later standards.

  • C in a Nutshell - Peter Prinz and Tony Crawford (2005). Excellent book if you need a reference for C99.

  • Functional C - Pieter Hartel and Henk Muller (1997). Teaches modern practices that are invaluable for low-level programming, with concurrency and modularity in mind.

  • The Practice of Programming - Brian W. Kernighan and Rob Pike (1999). A very good book to accompany K&R. It uses C++ and Java too.

  • C Traps and Pitfalls by A. Koenig (1989). Very good, but the C style pre-dates standard C, which makes it less recommendable these days.

    Some have argued for the removal of 'Traps and Pitfalls' from this list because it has trapped some people into making mistakes; others continue to argue for its inclusion. Perhaps it should be regarded as an 'expert' book because it requires a moderately extensive knowledge of C to understand what's changed since it was published.

  • MISRA-C - industry standard published and maintained by the Motor Industry Software Reliability Association. Covers C89 and C99.

    Although this isn't a book as such, many programmers recommend reading and implementing as much of it as possible. MISRA-C was originally intended as guidelines for safety-critical applications in particular, but it applies to any area of application where stable, bug-free C code is desired (who doesn't want fewer bugs?). MISRA-C is becoming the de facto standard in the whole embedded industry and is getting increasingly popular even in other programming branches. There are (at least) three publications of the standard (1998, 2004, and the current version from 2012). There is also a MISRA Compliance Guidelines document from 2016, and MISRA C:2012 Amendment 1 — Additional Security Guidelines for MISRA C:2012 (published in April 2016).

    Note that some of the strictures in the MISRA rules are not appropriate to every context. For example, directive 4.12 states "Dynamic memory allocation shall not be used". This is appropriate in the embedded systems for which the MISRA rules are designed; it is not appropriate everywhere. (Compilers, for instance, generally use dynamic memory allocation for things like symbol tables, and to do without dynamic memory allocation would be difficult, if not preposterous.)

  • Archived lists of ACCU-reviewed books on Beginner's C (116 titles) from 2007 and Advanced C (76 titles) from 2008. Most of these don't look to be on the main site anymore, and you can't browse that by subject anyway.


Warnings

There is a list of books and tutorials to be cautious about at the ISO 9899 Wiki, which is not itself formally associated with ISO or the C standard, but contains information about the C standard (though it hails the release of ISO 9899:2011 and does not mention the release of ISO 9899:2018).

Be wary of books written by Herbert Schildt. In particular, you should stay away from C: The Complete Reference (4th Edition, 2000), known in some circles as C: The Complete Nonsense.

Also do not use the book Let Us C (16th Edition, 2017) by Yashwant Kanetkar. Many people view it as an outdated book that teaches Turbo C and has lots of obsolete, misleading and incorrect material. For example, page 137 discusses the expected output from printf("%d %d %d\n", a, ++a, a++) and does not categorize it as undefined behaviour as it should. It also consistently promotes unportable and buggy coding practices, such as using gets, %[\n]s in scanf, storing return value of getchar in a variable of type char or using fflush on stdin.

Learn C The Hard Way (2015) by Zed Shaw. A book with mixed reviews. A critique of this book by Tim Hentenaar:

To summarize my views, which are laid out below, the author presents the material in a greatly oversimplified and misleading way, the whole corpus is a bundled mess, and some of the opinions and analyses he offers are just plain wrong. I've tried to view this book through the eyes of a novice, but unfortunately I am biased by years of experience writing code in C. It's obvious to me that either the author has a flawed understanding of C, or he's deliberately oversimplifying to the point where he's actually misleading the reader (intentionally or otherwise).

"Learn C The Hard Way" is not a book that I could recommend to someone who is both learning to program and learning C. If you're already a competent programmer in some other related language, then it represents an interesting and unusual exposition on C, though I have reservations about parts of the book. Jonathan Leffler


Outdated


Other contributors, not necessarily credited in the revision history, include:
Alex Lockwood, Ben Jackson, Bubbles, claws, coledot, Dana Robinson, Daniel Holden, desbest, Dervin Thunk, dwc, Erci Hou, Garen, haziz, Johan Bezem, Jonathan Leffler, Joshua Partogi, Lucas, Lundin, Matt K., mossplix, Matthieu M., midor, Nietzche-jou, Norman Ramsey, r3st0r3, ridthyself, Robert S. Barnes, Steve Summit, Tim Ring, Tony Bai, VMAtm

Difference between static memory allocation and dynamic memory allocation

There are three types of allocation — static, automatic, and dynamic.

Static Allocation means, that the memory for your variables is allocated when the program starts. The size is fixed when the program is created. It applies to global variables, file scope variables, and variables qualified with static defined inside functions.

Automatic memory allocation occurs for (non-static) variables defined inside functions, and is usually stored on the stack (though the C standard doesn't mandate that a stack is used). You do not have to reserve extra memory using them, but on the other hand, have also limited control over the lifetime of this memory. E.g: automatic variables in a function are only there until the function finishes.

void func() {
    int i; /* `i` only exists during `func` */
}

Dynamic memory allocation is a bit different. You now control the exact size and the lifetime of these memory locations. If you don't free it, you'll run into memory leaks, which may cause your application to crash, since at some point of time, system cannot allocate more memory.

int* func() {
    int* mem = malloc(1024);
    return mem;
}

int* mem = func(); /* still accessible */

In the upper example, the allocated memory is still valid and accessible, even though the function terminated. When you are done with the memory, you have to free it:

free(mem);

JQuery: How to get selected radio button value?

You should really be using checkboxes if there will be an instance where something isn't selected.

according to the W3C

If no radio button in a set sharing the same control name is initially "on", user agent behavior for choosing which control is initially "on" is undefined. Note. Since existing implementations handle this case differently, the current specification differs from RFC 1866 ([RFC1866] section 8.1.2.4), which states:

At all times, exactly one of the radio buttons in a set is checked. If none of the elements of a set of radio buttons specifies `CHECKED', then the user agent must check the first radio button of the set initially.

Since user agent behavior differs, authors should ensure that in each set of radio buttons that one is initially "on".

How to process POST data in Node.js?

If you don't want to chunk your data together with the data callback you can always use the readable callback like this:

// Read Body when Available
request.on("readable", function(){
  request.body = '';
  while (null !== (request.body += request.read())){}
});

// Do something with it
request.on("end", function(){
  request.body //-> POST Parameters as String
});

This approach modifies the incoming request, but as soon as you finish your response the request will be garbage collected, so that should not be a problem.

An advanced approach would be to check the body size first, if you're afraid of huge bodies.

Find and replace string values in list

An example with for loop (I prefer List Comprehensions).

a, b = '[br]', '<br />'
for i, v in enumerate(words):
    if a in v:
        words[i] = v.replace(a, b)
print(words)
# ['how', 'much', 'is<br/>', 'the', 'fish<br/>', 'no', 'really']

Scrolling to an Anchor using Transition/CSS3

Using the scroll-behavior CSS property:

(which is supported in modern browsers but not Edge):

_x000D_
_x000D_
a {
  display: inline-block;
  padding: 5px 7%;
  text-decoration: none;
}

nav, section {
  display: block;
  margin: 0 auto;
  text-align: center;
}

nav {
  width: 350px;
  padding: 5px;
}

section {
  width: 350px;
  height: 130px;
  overflow-y: scroll;
  border: 1px solid black;
  font-size: 0; 
  scroll-behavior: smooth;    /* <----- THE SECRET ---- */
}

section div{
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  font-size: 8vw;
}
_x000D_
<nav>
  <a href="#page-1">1</a>
  <a href="#page-2">2</a>
  <a href="#page-3">3</a>
</nav>
<section>
  <div id="page-1">1</div>
  <div id="page-2">2</div>
  <div id="page-3">3</div>
</section>
_x000D_
_x000D_
_x000D_

Enable vertical scrolling on textarea

Try this: http://jsfiddle.net/8fv6e/8/

It is another version of the answers.

HTML:

<label for="aboutDescription" id="aboutHeading">About</label>
<textarea rows="15" cols="50" id="aboutDescription"
    style="max-height:100px;min-height:100px; resize: none"></textarea>
<a  id="imageURLId" target="_blank">Go to
    HomePage</a>

CSS:

#imageURLId{
font-size: 14px;
font-weight: normal;
resize: none;
overflow-y: scroll;

}

Why do we use __init__ in Python classes?

To contribute my 5 cents to the thorough explanation from Amadan.

Where classes are a description "of a type" in an abstract way. Objects are their realizations: the living breathing thing. In the object-orientated world there are principal ideas you can almost call the essence of everything. They are:

  1. encapsulation (won't elaborate on this)
  2. inheritance
  3. polymorphism

Objects have one, or more characteristics (= Attributes) and behaviors (= Methods). The behavior mostly depends on the characteristics. Classes define what the behavior should accomplish in a general way, but as long as the class is not realized (instantiated) as an object it remains an abstract concept of a possibility. Let me illustrate with the help of "inheritance" and "polymorphism".

    class Human:
        gender
        nationality
        favorite_drink
        core_characteristic
        favorite_beverage
        name
        age

        def love    
        def drink
        def laugh
        def do_your_special_thing                

    class Americans(Humans)
        def drink(beverage):
            if beverage != favorite_drink: print "You call that a drink?"
            else: print "Great!" 

    class French(Humans)
        def drink(beverage, cheese):
            if beverage == favourite_drink and cheese == None: print "No cheese?" 
            elif beverage != favourite_drink and cheese == None: print "Révolution!"

    class Brazilian(Humans)
        def do_your_special_thing
            win_every_football_world_cup()

    class Germans(Humans)
        def drink(beverage):
            if favorite_drink != beverage: print "I need more beer"
            else: print "Lecker!" 

    class HighSchoolStudent(Americans):
        def __init__(self, name, age):
             self.name = name
             self.age = age

jeff = HighSchoolStudent(name, age):
hans = Germans()
ronaldo = Brazilian()
amelie = French()

for friends in [jeff, hans, ronaldo]:
    friends.laugh()
    friends.drink("cola")
    friends.do_your_special_thing()

print amelie.love(jeff)
>>> True
print ronaldo.love(hans)
>>> False

Some characteristics define human beings. But every nationality differs somewhat. So "national-types" are kinda Humans with extras. "Americans" are a type of "Humans " and inherit some abstract characteristics and behavior from the human type (base-class) : that's inheritance. So all Humans can laugh and drink, therefore all child-classes can also! Inheritance (2).

But because they are all of the same kind (Type/base-class : Humans) you can exchange them sometimes: see the for-loop at the end. But they will expose an individual characteristic, and thats Polymorphism (3).

So each human has a favorite_drink, but every nationality tend towards a special kind of drink. If you subclass a nationality from the type of Humans you can overwrite the inherited behavior as I have demonstrated above with the drink() Method. But that's still at the class-level and because of this it's still a generalization.

hans = German(favorite_drink = "Cola")

instantiates the class German and I "changed" a default characteristic at the beginning. (But if you call hans.drink('Milk') he would still print "I need more beer" - an obvious bug ... or maybe that's what i would call a feature if i would be a Employee of a bigger Company. ;-)! )

The characteristic of a type e.g. Germans (hans) are usually defined through the constructor (in python : __init__) at the moment of the instantiation. This is the point where you define a class to become an object. You could say breath life into an abstract concept (class) by filling it with individual characteristics and becoming an object.

But because every object is an instance of a class they share all some basic characteristic-types and some behavior. This is a major advantage of the object-orientated concept.

To protect the characteristics of each object you encapsulate them - means you try to couple behavior and characteristic and make it hard to manipulate it from outside the object. That's Encapsulation (1)

Debian 8 (Live-CD) what is the standard login and password?

Although this is an old question, I had the same question when using the Standard console version. The answer can be found in the Debian Live manual under the section 10.1 Customizing the live user. It says:

It is also possible to change the default username "user" and the default password "live".

I tried the username user and password live and it did work. If you want to run commands as root you can preface each command with sudo

AngularJS: No "Access-Control-Allow-Origin" header is present on the requested resource

CORS is Cross Origin Resource Sharing, you get this error if you are trying to access from one domain to another domain.

Try using JSONP. In your case, JSONP should work fine because it only uses the GET method.

Try something like this:

var url = "https://api.getevents.co/event?&lat=41.904196&lng=12.465974";
$http({
    method: 'JSONP',
    url: url
}).
success(function(status) {
    //your code when success
}).
error(function(status) {
    //your code when fails
});

How to get access token from FB.login method in javascript SDK

response.session doesn't work anymore because response.authResponse is the new way to access the response content after the oauth migration.
Check this for details: SDKs & Tools › JavaScript SDK › FB.login

How do I find the difference between two values without knowing which is larger?

You can try: a=[0,1,2,3,4,5,6,7,8,9];

[abs(x[1]-x[0]) for x in zip(a[1:],a[:-1])]

How to write multiple conditions of if-statement in Robot Framework

Just make sure put single space before and after "and" Keyword..

Lookup City and State by Zip Google Geocode Api

I found a couple of ways to do this with web based APIs. I think the US Postal Service would be the most accurate, since Zip codes are their thing, but Ziptastic looks much easier.

Using the US Postal Service HTTP/XML API

According to this page on the US Postal Service website which documents their XML based web API, specifically Section 4.0 (page 22) of this PDF document, they have a URL where you can send an XML request containing a 5 digit Zip Code and they will respond with an XML document containing the corresponding City and State.

According to their documentation, here's what you would send:

http://SERVERNAME/ShippingAPITest.dll?API=CityStateLookup&XML=<CityStateLookupRequest%20USERID="xxxxxxx"><ZipCode ID= "0"><Zip5>90210</Zip5></ZipCode></CityStateLookupRequest>

And here's what you would receive back:

<?xml version="1.0"?> 
<CityStateLookupResponse> 
    <ZipCode ID="0"> 
        <Zip5>90210</Zip5> 
        <City>BEVERLY HILLS</City> 
        <State>CA</State> 
    </ZipCode> 
</CityStateLookupResponse>

USPS does require that you register with them before you can use the API, but, as far as I could tell, there is no charge for access. By the way, their API has some other features: you can do Address Standardization and Zip Code Lookup, as well as the whole suite of tracking, shipping, labels, etc.

Using the Ziptastic HTTP/JSON API (no longer supported)

Update: As of August 13, 2017, Ziptastic is now a paid API and can be found here

This is a pretty new service, but according to their documentation, it looks like all you need to do is send a GET request to http://ziptasticapi.com, like so:

GET http://ziptasticapi.com/48867

And they will return a JSON object along the lines of:

{"country": "US", "state": "MI", "city": "OWOSSO"}

Indeed, it works. You can test this from a command line by doing something like:

curl http://ziptasticapi.com/48867 

Display loading image while post with ajax

$.ajax(
{
    type: 'post',
    url: 'mail.php',
    data: form.serialize(),
    beforeSend: function()
    {
        $('.content').html('loading...');
    },
    success: function(data)
    {
        $('.content').html(data);
    },
    error: function()
    {
        $('.content').html('error');
    }
});

have fun playing arround!

if you should have quick loading times which prevent te loading showing, you can add a timeout of some sort.

AttributeError: 'datetime' module has no attribute 'strptime'

If I had to guess, you did this:

import datetime

at the top of your code. This means that you have to do this:

datetime.datetime.strptime(date, "%Y-%m-%d")

to access the strptime method. Or, you could change the import statement to this:

from datetime import datetime

and access it as you are.

The people who made the datetime module also named their class datetime:

#module  class    method
datetime.datetime.strptime(date, "%Y-%m-%d")

Ajax LARAVEL 419 POST error

419 error happens when you don`t post csrf_token. in your post method you must add this token along other variables.

How do I make a fully statically linked .exe with Visual Studio Express 2005?

My experience in Visual Studio 2010 is that there are two changes needed so as to not need DLL's. From the project property page (right click on the project name in the Solution Explorer window):

  1. Under Configuration Properties --> General, change the "Use of MFC" field to "Use MFC in a Static Library".

  2. Under Configuration Properties --> C/C++ --> Code Generation, change the "Runtime Library" field to "Multi-Threaded (/MT)"

Not sure why both were needed. I used this to remove a dependency on glut32.dll.

Added later: When making these changes to the configurations, you should make them to "All Configurations" --- you can select this at the top of the Properties window. If you make the change to just the Debug configuration, it won't apply to the Release configuration, and vice-versa.

how to draw smooth curve through N points using javascript HTML5 canvas?

To add to K3N's cardinal splines method and perhaps address T. J. Crowder's concerns about curves 'dipping' in misleading places, I inserted the following code in the getCurvePoints() function, just before res.push(x);

if ((y < _pts[i+1] && y < _pts[i+3]) || (y > _pts[i+1] && y > _pts[i+3])) {
    y = (_pts[i+1] + _pts[i+3]) / 2;
}
if ((x < _pts[i] && x < _pts[i+2]) || (x > _pts[i] && x > _pts[i+2])) {
    x = (_pts[i] + _pts[i+2]) / 2;
}

This effectively creates a (invisible) bounding box between each pair of successive points and ensures the curve stays within this bounding box - ie. if a point on the curve is above/below/left/right of both points, it alters its position to be within the box. Here the midpoint is used, but this could be improved upon, perhaps using linear interpolation.

Where can I read the Console output in Visual Studio 2015

The simple way is using System.Diagnostics.Debug.WriteLine()

Your can then read what you're writing to the output by clicking the menu "DEBUG" -> "Windows" -> "Output".

Error Installing Homebrew - Brew Command Not Found

This was just happening to me, but none of the suggestions above worked. I changed directories ("cd ~/tmp") and suddenly the command

ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)"

worked for me. Prior to changing directories I had been in a directory that is a Git repository. Perhaps that was interfering with the ruby and Git commands in the Brew install script.

How to create threads in nodejs

You can get multi-threading using Napa.js.

https://github.com/Microsoft/napajs

"Napa.js is a multi-threaded JavaScript runtime built on V8, which was originally designed to develop highly iterative services with non-compromised performance in Bing. As it evolves, we find it useful to complement Node.js in CPU-bound tasks, with the capability of executing JavaScript in multiple V8 isolates and communicating between them. Napa.js is exposed as a Node.js module, while it can also be embedded in a host process without Node.js dependency."

How to check whether the user uploaded a file in PHP?

<!DOCTYPE html>
<html>
<body>

<form action="#" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input name="my_files[]" type="file" multiple="multiple" />
    <input type="submit" value="Upload Image" name="submit">
</form>


<?php

 if (isset($_FILES['my_files']))
  {
    $myFile = $_FILES['my_files'];
    $fileCount = count($myFile["name"]);


        for ($i = 0; $i <$fileCount; $i++)
         {
           $error = $myFile["error"][$i]; 

            if ($error == '4')  // error 4 is for "no file selected"
             {
               echo "no file selected";
             }
            else
             {

               $name =  $myFile["name"][$i];
               echo $name; 
               echo "<br>"; 
               $temporary_file = $myFile["tmp_name"][$i];
               echo $temporary_file;
               echo "<br>";
               $type = $myFile["type"][$i];
               echo $type;
               echo "<br>";
               $size = $myFile["size"][$i];
               echo $size;
               echo "<br>";



               $target_path = "uploads/$name";   //first make a folder named "uploads" where you will upload files


                 if(move_uploaded_file($temporary_file,$target_path))
                  {
                   echo " uploaded";
                   echo "<br>";
                   echo "<br>";
                  }
                   else
                  {
                   echo "no upload ";
                  }




              }
        }  
}
        ?>


</body>
</html>

But be alert. User can upload any type of file and also can hack your server or system by uploading a malicious or php file. In this script there should be some validations. Thank you.

Enable IIS7 gzip

Configuration

You can enable GZIP compression entirely in your Web.config file. This is particularly useful if you're on shared hosting and can't configure IIS directly, or you want your config to carry between all environments you target.

<system.webServer>
  <httpCompression directory="%SystemDrive%\inetpub\temp\IIS Temporary Compressed Files">
    <scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll"/>
    <dynamicTypes>
      <add mimeType="text/*" enabled="true"/>
      <add mimeType="message/*" enabled="true"/>
      <add mimeType="application/javascript" enabled="true"/>
      <add mimeType="*/*" enabled="false"/>
    </dynamicTypes>
    <staticTypes>
      <add mimeType="text/*" enabled="true"/>
      <add mimeType="message/*" enabled="true"/>
      <add mimeType="application/javascript" enabled="true"/>
      <add mimeType="*/*" enabled="false"/>
    </staticTypes>
  </httpCompression>
  <urlCompression doStaticCompression="true" doDynamicCompression="true"/>
</system.webServer>

Testing

To test whether compression is working or not, use the developer tools in Chrome or Firebug for Firefox and ensure the HTTP response header is set:

Content-Encoding: gzip

Note that this header won't be present if the response code is 304 (Not Modified). If that's the case, do a full refresh (hold shift or control while you press the refresh button) and check again.

Model summary in pytorch

AFAK there is no model.summary() like equivalent in pytorch

Meanwhile you can refer script by szagoruyko, which gives a nice visualizaton like in resnet18-example

Cheers

Parse an HTML string with JS

const parse = Range.prototype.createContextualFragment.bind(document.createRange());

document.body.appendChild( parse('<p><strong>Today is:</strong></p>') ),
document.body.appendChild( parse(`<p style="background: #eee">${new Date()}</p>`) );


Only valid child Nodes within the parent Node (start of the Range) will be parsed. Otherwise, unexpected results may occur:

// <body> is "parent" Node, start of Range
const parseRange = document.createRange();
const parse = Range.prototype.createContextualFragment.bind(parseRange);

// Returns Text "1 2" because td, tr, tbody are not valid children of <body>
parse('<td>1</td> <td>2</td>');
parse('<tr><td>1</td> <td>2</td></tr>');
parse('<tbody><tr><td>1</td> <td>2</td></tr></tbody>');

// Returns <table>, which is a valid child of <body>
parse('<table> <td>1</td> <td>2</td> </table>');
parse('<table> <tr> <td>1</td> <td>2</td> </tr> </table>');
parse('<table> <tbody> <td>1</td> <td>2</td> </tbody> </table>');

// <tr> is parent Node, start of Range
parseRange.setStart(document.createElement('tr'), 0);

// Returns [<td>, <td>] element array
parse('<td>1</td> <td>2</td>');
parse('<tr> <td>1</td> <td>2</td> </tr>');
parse('<tbody> <td>1</td> <td>2</td> </tbody>');
parse('<table> <td>1</td> <td>2</td> </table>');

Write a number with two decimal places SQL Server

Try this:

 declare @MyFloatVal float;

    set @MyFloatVal=(select convert(decimal(10, 2), 10.254000))

    select  @MyFloatVal

    Convert(decimal(18,2),r.AdditionAmount) as AdditionAmount

Batch File: ( was unexpected at this time

You are getting that error because when the param1 if statements are evaluated, param is always null due to being scoped variables without delayed expansion.

When parentheses are used, all the commands and variables within those parentheses are expanded. And at that time, param1 has no value making the if statements invalid. When using delayed expansion, the variables are only expanded when the command is actually called.

Also I recommend using if not defined command to determine if a variable is set.

@echo off
setlocal EnableExtensions EnableDelayedExpansion
cls
title ~USB Wizard~
echo What do you want to do?
echo 1.Enable/Disable USB Storage Devices.
echo 2.Enable/Disable Writing Data onto USB Storage.
echo 3.~Yet to come~.

set "a=%globalparam1%"
goto :aCheck
:aPrompt
set /p "a=Enter Choice: "
:aCheck
if not defined a goto :aPrompt
echo %a%

IF "%a%"=="2" (
    title USB WRITE LOCK
    echo What do you want to do?
    echo 1.Apply USB Write Protection
    echo 2.Remove USB Write Protection

    ::param1
    set "param1=%globalparam2%"
    goto :param1Check
    :param1Prompt
    set /p "param1=Enter Choice: "
    :param1Check
    if not defined param1 goto :param1Prompt
    echo !param1!

    if "!param1!"=="1" (
        REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies\ /v WriteProtect /t REG_DWORD /d 00000001 
        echo USB Write is Locked!
    )
    if "!param1!"=="2" (
        REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies\ /v WriteProtect /t REG_DWORD /d 00000000
        echo USB Write is Unlocked! 
    )
)
pause
endlocal

Use of True, False, and None as return values in Python functions

If checking for truth:

if foo

For false:

if not foo

For none:

if foo is None

For non-none:

if foo is not None

For getattr() the correct behaviour is not to return None, but raise an AttributError error instead - unless your class is something like defaultdict.

Regular expression to validate US phone numbers?

The easiest way to match both

^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$

and

^[0-9]{3}-[0-9]{3}-[0-9]{4}$

is to use alternation ((...|...)): specify them as two mostly-separate options:

^(\([0-9]{3}\)|[0-9]{3}-)[0-9]{3}-[0-9]{4}$

By the way, when Americans put the area code in parentheses, we actually put a space after that; for example, I'd write (123) 123-1234, not (123)123-1234. So you might want to write:

^(\([0-9]{3}\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$

(Though it's probably best to explicitly demonstrate the format that you expect phone numbers to be in.)

How to use CMAKE_INSTALL_PREFIX

There are two ways to use this variable:

  • passing it as a command line argument just like Job mentioned:

    cmake -DCMAKE_INSTALL_PREFIX=< install_path > ..

  • assigning value to it in CMakeLists.txt:

    SET(CMAKE_INSTALL_PREFIX < install_path >)

    But do remember to place it BEFORE PROJECT(< project_name>) command, otherwise it will not work!

Reload a DIV without reloading the whole page

The code you're using is also going to include a fadeout effect. Is this what you want to achieve? If not, it might make more sense to just add the following INSIDE "Small.php".

<meta http-equiv="refresh" content="15" >

This adds a refresh every 15seconds to the small.php page which should mean if called by PHP into another page, only that "frame" will reload.

Let us know if it worked/solved your problem!?

-Brad

Fitting polynomial model to data in R

Which model is the "best fitting model" depends on what you mean by "best". R has tools to help, but you need to provide the definition for "best" to choose between them. Consider the following example data and code:

x <- 1:10
y <- x + c(-0.5,0.5)

plot(x,y, xlim=c(0,11), ylim=c(-1,12))

fit1 <- lm( y~offset(x) -1 )
fit2 <- lm( y~x )
fit3 <- lm( y~poly(x,3) )
fit4 <- lm( y~poly(x,9) )
library(splines)
fit5 <- lm( y~ns(x, 3) )
fit6 <- lm( y~ns(x, 9) )

fit7 <- lm( y ~ x + cos(x*pi) )

xx <- seq(0,11, length.out=250)
lines(xx, predict(fit1, data.frame(x=xx)), col='blue')
lines(xx, predict(fit2, data.frame(x=xx)), col='green')
lines(xx, predict(fit3, data.frame(x=xx)), col='red')
lines(xx, predict(fit4, data.frame(x=xx)), col='purple')
lines(xx, predict(fit5, data.frame(x=xx)), col='orange')
lines(xx, predict(fit6, data.frame(x=xx)), col='grey')
lines(xx, predict(fit7, data.frame(x=xx)), col='black')

Which of those models is the best? arguments could be made for any of them (but I for one would not want to use the purple one for interpolation).

Run Batch File On Start-up

There are a few ways to run a batch file on start up. The one I usually use is through task scheduler. If you press the windows key then type task scheduler it will come up as an option (or find through administerative tools).

When you create a new task you can chose from trigger options such as 'At log on' for a specific user, on workstation unlock etc. Then in actions you select start a program and put the full path to your batch script (there is also an option to put any command line args required).

Here is a an example script to launch Stack Overflow in Firefox:

@echo off

title Auto launch Stack Overflow


start firefox http://stackoverflow.com/questions/tagged/python+or+sql+or+sqlite+or+plsql+or+oracle+or+windows-7+or+cmd+or+excel+or+access+or+vba+or+excel-vba+or+access-vba?sort=newest

REM Optional - I tend to log these sorts of events so that you can see what has happened afterwards
echo %date% %time%, %computername% >> %logs%\StackOverflowAuto.csv

exit

Giving height to table and row in Bootstrap

For the <tr>'s just set

tr {
   line-height: 25px;
   min-height: 25px;
   height: 25px;
}

It works with bootstrap also. For the 100% height, 100% must be 100% of something. Therefore, you must define a fixed height for one of the containers, or the body. I guess you want the entire page to be 100%, so (example) :

body {
    height: 700px;
}
.table100, .row, .container, .table-responsive, .table-bordered  {
    height: 100%;
}

A workaround not to set a static height is by forcing the height in code according to the viewport :

$('body').height(document.documentElement.clientHeight);

all the above in this fiddle -> http://jsfiddle.net/LZuJt/

Note : I do not care that you have 25% height on #description, and 100% height on table. Guess it is just an example. And notice that clientHeight is not right since the documentElement is an iframe, but you'll get the picture in your own projekt :)

What does the "at" (@) symbol do in Python?

It indicates that you are using a decorator. Here is Bruce Eckel's example from 2008.

Using Mockito, how do I verify a method was a called with a certain argument?

First you need to create a mock m_contractsDao and set it up. Assuming that the class is ContractsDao:

ContractsDao mock_contractsDao = mock(ContractsDao.class);
when(mock_contractsDao.save(any(String.class))).thenReturn("Some result");

Then inject the mock into m_orderSvc and call your method.

m_orderSvc.m_contractsDao = mock_contractsDao;
m_prog = new ProcessOrdersWorker(m_orderSvc, m_opportunitySvc, m_myprojectOrgSvc);
m_prog.work(); 

Finally, verify that the mock was called properly:

verify(mock_contractsDao, times(1)).save("Parameter I'm expecting");

Adding a new line/break tag in XML

Without using CDATA, try

<xsl:value-of select="'&#xA;'" />

Note the double and single quotes.

That is particularly useful if you are not creating xml aka text. <xsl:output method="text" />

When should I use semicolons in SQL Server?

From a SQLServerCentral.Com article by Ken Powers:

The Semicolon

The semicolon character is a statement terminator. It is a part of the ANSI SQL-92 standard, but was never used within Transact-SQL. Indeed, it was possible to code T-SQL for years without ever encountering a semicolon.

Usage

There are two situations in which you must use the semicolon. The first situation is where you use a Common Table Expression (CTE), and the CTE is not the first statement in the batch. The second is where you issue a Service Broker statement and the Service Broker statement is not the first statement in the batch.

How/when to use ng-click to call a route?

Remember that if you use ng-click for routing you will not be able to right-click the element and choose 'open in new tab' or ctrl clicking the link. I try to use ng-href when in comes to navigation. ng-click is better to use on buttons for operations or visual effects like collapse. But About I would not recommend. If you change the route you might need to change in a lot of placed in the application. Have a method returning the link. ex: About. This method you place in a utility

Creating a ZIP archive in memory using System.IO.Compression

       private void button6_Click(object sender, EventArgs e)
    {

        //create With Input FileNames
        AddFileToArchive_InputByte(new ZipItem[]{ new ZipItem( @"E:\b\1.jpg",@"images\1.jpg"),
            new ZipItem(@"E:\b\2.txt",@"text\2.txt")}, @"C:\test.zip");

        //create with input stream
        AddFileToArchive_InputByte(new ZipItem[]{ new ZipItem(File.ReadAllBytes( @"E:\b\1.jpg"),@"images\1.jpg"),
            new ZipItem(File.ReadAllBytes(@"E:\b\2.txt"),@"text\2.txt")}, @"C:\test.zip");

        //Create Archive And Return StreamZipFile
        MemoryStream GetStreamZipFile = AddFileToArchive(new ZipItem[]{ new ZipItem( @"E:\b\1.jpg",@"images\1.jpg"),
            new ZipItem(@"E:\b\2.txt",@"text\2.txt")});


        //Extract in memory
        ZipItem[] ListitemsWithBytes = ExtractItems(@"C:\test.zip");

        //Choese Files For Extract To memory
        List<string> ListFileNameForExtract = new List<string>(new string[] { @"images\1.jpg", @"text\2.txt" });
        ListitemsWithBytes = ExtractItems(@"C:\test.zip", ListFileNameForExtract);


        // Choese Files For Extract To Directory
        ExtractItems(@"C:\test.zip", ListFileNameForExtract, "c:\\extractFiles");

    }

    public struct ZipItem
    {
        string _FileNameSource;
        string _PathinArchive;
        byte[] _Bytes;
        public ZipItem(string __FileNameSource, string __PathinArchive)
        {
            _Bytes=null ;
            _FileNameSource = __FileNameSource;
            _PathinArchive = __PathinArchive;
        }
        public ZipItem(byte[] __Bytes, string __PathinArchive)
        {
            _Bytes = __Bytes;
            _FileNameSource = "";
            _PathinArchive = __PathinArchive;

        }
        public string FileNameSource
        {
            set
            {
                FileNameSource = value;
            }
            get
            {
                return _FileNameSource;
            }
        }
        public string PathinArchive
        {
            set
            {
                _PathinArchive = value;
            }
            get
            {
                return _PathinArchive;
            }
        }
        public byte[] Bytes
        {
            set
            {
                _Bytes = value;
            }
            get
            {
                return _Bytes;
            }
        }
    }


     public void AddFileToArchive(ZipItem[] ZipItems, string SeveToFile)
    {

        MemoryStream memoryStream = new MemoryStream();

        //Create Empty Archive
        ZipArchive archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true);

        foreach (ZipItem item in ZipItems)
        {

            //Create Path File in Archive
            ZipArchiveEntry FileInArchive = archive.CreateEntry(item.PathinArchive);


            //Open File in Archive For Write
            var OpenFileInArchive = FileInArchive.Open();

            //Read Stream
            FileStream fsReader = new FileStream(item.FileNameSource, FileMode.Open, FileAccess.Read);

            byte[] ReadAllbytes = new byte[4096];//Capcity buffer
            int ReadByte = 0;
            while (fsReader.Position != fsReader.Length)
            {
                //Read Bytes
                ReadByte = fsReader.Read(ReadAllbytes, 0, ReadAllbytes.Length);

                //Write Bytes
                OpenFileInArchive.Write(ReadAllbytes, 0, ReadByte);
            }
            fsReader.Dispose();
            OpenFileInArchive.Close();


        }
        archive.Dispose();

        using (var fileStream = new FileStream(SeveToFile, FileMode.Create))
        {
            memoryStream.Seek(0, SeekOrigin.Begin);
            memoryStream.CopyTo(fileStream);
        }





    }
     public MemoryStream  AddFileToArchive(ZipItem[] ZipItems)
    {

        MemoryStream memoryStream = new MemoryStream();

        //Create Empty Archive
        ZipArchive archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true);

        foreach (ZipItem item in ZipItems)
        {

            //Create Path File in Archive
            ZipArchiveEntry FileInArchive = archive.CreateEntry(item.PathinArchive);


            //Open File in Archive For Write
            var OpenFileInArchive = FileInArchive.Open();

            //Read Stream
            FileStream fsReader = new FileStream(item.FileNameSource, FileMode.Open, FileAccess.Read);

            byte[] ReadAllbytes = new byte[4096];//Capcity buffer
            int ReadByte = 0;
            while (fsReader.Position != fsReader.Length)
            {
                //Read Bytes
                ReadByte = fsReader.Read(ReadAllbytes, 0, ReadAllbytes.Length);

                //Write Bytes
                OpenFileInArchive.Write(ReadAllbytes, 0, ReadByte);
            }
            fsReader.Dispose();
            OpenFileInArchive.Close();


        }
        archive.Dispose();




        return memoryStream;


    }

     public void AddFileToArchive_InputByte(ZipItem[] ZipItems, string SeveToFile)
    {

        MemoryStream memoryStream = new MemoryStream();

        //Create Empty Archive
        ZipArchive archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true);

        foreach (ZipItem item in ZipItems)
        {

            //Create Path File in Archive
            ZipArchiveEntry FileInArchive = archive.CreateEntry(item.PathinArchive);


            //Open File in Archive For Write
            var OpenFileInArchive = FileInArchive.Open();

            //Read Stream
          //  FileStream fsReader = new FileStream(item.FileNameSource, FileMode.Open, FileAccess.Read);

            byte[] ReadAllbytes = new byte[4096];//Capcity buffer
            int ReadByte = 4096 ;int  TotalWrite=0;
            while (TotalWrite != item.Bytes.Length)
            {

                if(TotalWrite+4096>item.Bytes.Length)
                 ReadByte=item.Bytes.Length-TotalWrite;



                Array.Copy(item.Bytes, TotalWrite, ReadAllbytes, 0, ReadByte);




                //Write Bytes
                OpenFileInArchive.Write(ReadAllbytes, 0, ReadByte);
                TotalWrite += ReadByte;
            }

            OpenFileInArchive.Close();


        }
        archive.Dispose();

        using (var fileStream = new FileStream(SeveToFile, FileMode.Create))
        {
            memoryStream.Seek(0, SeekOrigin.Begin);
            memoryStream.CopyTo(fileStream);
        }


    }
     public MemoryStream  AddFileToArchive_InputByte(ZipItem[] ZipItems)
    {

        MemoryStream memoryStream = new MemoryStream();

        //Create Empty Archive
        ZipArchive archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true);

        foreach (ZipItem item in ZipItems)
        {

            //Create Path File in Archive
            ZipArchiveEntry FileInArchive = archive.CreateEntry(item.PathinArchive);


            //Open File in Archive For Write
            var OpenFileInArchive = FileInArchive.Open();

            //Read Stream
          //  FileStream fsReader = new FileStream(item.FileNameSource, FileMode.Open, FileAccess.Read);

            byte[] ReadAllbytes = new byte[4096];//Capcity buffer
            int ReadByte = 4096 ;int  TotalWrite=0;
            while (TotalWrite != item.Bytes.Length)
            {

                if(TotalWrite+4096>item.Bytes.Length)
                 ReadByte=item.Bytes.Length-TotalWrite;



                Array.Copy(item.Bytes, TotalWrite, ReadAllbytes, 0, ReadByte);




                //Write Bytes
                OpenFileInArchive.Write(ReadAllbytes, 0, ReadByte);
                TotalWrite += ReadByte;
            }

            OpenFileInArchive.Close();


        }
        archive.Dispose();



        return memoryStream;
    }

     public void ExtractToDirectory(string sourceArchiveFileName, string destinationDirectoryName)
     {
         //Opens the zip file up to be read
         using (ZipArchive archive = ZipFile.OpenRead(sourceArchiveFileName))
         {
             if (Directory.Exists(destinationDirectoryName)==false )
                 Directory.CreateDirectory(destinationDirectoryName);

             //Loops through each file in the zip file
             archive.ExtractToDirectory(destinationDirectoryName);

         }
     }  
     public void   ExtractItems(string sourceArchiveFileName,List< string> _PathFilesinArchive, string destinationDirectoryName)
     {

         //Opens the zip file up to be read
         using (ZipArchive archive = ZipFile.OpenRead(sourceArchiveFileName))
         {


             //Loops through each file in the zip file
             foreach (ZipArchiveEntry file in archive.Entries)
             {
                 int PosResult = _PathFilesinArchive.IndexOf(file.FullName);
                 if (PosResult != -1)
                 {
                     //Create Folder
                     if (Directory.Exists( destinationDirectoryName + "\\" +Path.GetDirectoryName( _PathFilesinArchive[PosResult])) == false)
                         Directory.CreateDirectory(destinationDirectoryName + "\\" + Path.GetDirectoryName(_PathFilesinArchive[PosResult]));

                     Stream OpenFileGetBytes = file.Open();

                     FileStream   FileStreamOutput = new FileStream(destinationDirectoryName + "\\" + _PathFilesinArchive[PosResult], FileMode.Create);

                     byte[] ReadAllbytes = new byte[4096];//Capcity buffer
                     int ReadByte = 0; int TotalRead = 0; 
                     while (TotalRead != file.Length)
                     {
                         //Read Bytes
                         ReadByte = OpenFileGetBytes.Read(ReadAllbytes, 0, ReadAllbytes.Length);
                         TotalRead += ReadByte;

                         //Write Bytes
                         FileStreamOutput.Write(ReadAllbytes, 0, ReadByte);
                     }

                     FileStreamOutput.Close();
                     OpenFileGetBytes.Close();



                     _PathFilesinArchive.RemoveAt(PosResult);
                 }

                 if (_PathFilesinArchive.Count == 0)
                     break;
             }
         }


     }

     public ZipItem[] ExtractItems(string sourceArchiveFileName)
     {
       List<  ZipItem> ZipItemsReading = new List<ZipItem>();
         //Opens the zip file up to be read
         using (ZipArchive archive = ZipFile.OpenRead(sourceArchiveFileName))
         {


             //Loops through each file in the zip file
             foreach (ZipArchiveEntry file in archive.Entries)
             {
                 Stream OpenFileGetBytes = file.Open();

                 MemoryStream memstreams = new MemoryStream();
                 byte[] ReadAllbytes = new byte[4096];//Capcity buffer
                 int ReadByte = 0; int TotalRead = 0;
                 while (TotalRead != file.Length)
                 {
                     //Read Bytes
                     ReadByte = OpenFileGetBytes.Read(ReadAllbytes, 0, ReadAllbytes.Length);
                     TotalRead += ReadByte;

                     //Write Bytes
                     memstreams.Write(ReadAllbytes, 0, ReadByte);
                 }

                 memstreams.Position = 0;
                 OpenFileGetBytes.Close();
                 memstreams.Dispose();

                 ZipItemsReading.Add(new ZipItem(memstreams.ToArray(),file.FullName));


             }
         }

         return ZipItemsReading.ToArray();
     }
     public ZipItem[] ExtractItems(string sourceArchiveFileName,List< string> _PathFilesinArchive)
     {
       List<  ZipItem> ZipItemsReading = new List<ZipItem>();
         //Opens the zip file up to be read
         using (ZipArchive archive = ZipFile.OpenRead(sourceArchiveFileName))
         {

             //Loops through each file in the zip file
             foreach (ZipArchiveEntry file in archive.Entries)
             {
                 int PosResult = _PathFilesinArchive.IndexOf(file.FullName); 
                 if (PosResult!= -1)
                 {
                     Stream OpenFileGetBytes = file.Open();

                     MemoryStream memstreams = new MemoryStream();
                     byte[] ReadAllbytes = new byte[4096];//Capcity buffer
                     int ReadByte = 0; int TotalRead = 0;  
                     while (TotalRead != file.Length)
                     {
                         //Read Bytes
                         ReadByte = OpenFileGetBytes.Read(ReadAllbytes, 0, ReadAllbytes.Length);
                         TotalRead += ReadByte;

                         //Write Bytes
                         memstreams.Write(ReadAllbytes, 0, ReadByte);
                     }

                     //Create item
                     ZipItemsReading.Add(new ZipItem(memstreams.ToArray(),file.FullName));

                     OpenFileGetBytes.Close();
                     memstreams.Dispose();



                     _PathFilesinArchive.RemoveAt(PosResult);
                 }

                 if (_PathFilesinArchive.Count == 0)
                     break;


             }
         }

         return ZipItemsReading.ToArray();
     }

JavaScript - Hide a Div at startup (load)

I've had the same problem.

Use CSS to hide is not the best solution, because sometimes you want users without JS can see the div.. The cleanest solution is to hide the div with JQuery. But the div is visible about 0.5 seconde, which is problematic if the div is on the top of the page.

In these cases, I use an intermediate solution, without JQuery. This one works and is immediate :

<script>document.write('<style>.js_hidden { display: none; }</style>');</script>

<div class="js_hidden">This div will be hidden for JS users, and visible for non JS users.</div>

Of course, you can still add all the effects you want on the div, JQuery toggle() for example. And you will get the best behaviour possible (imho) :

  • for non JS users, the div is visible directly
  • for JS users, the div is hidden and has toggle effect.

Customizing Bootstrap CSS template

I recently wrote a post about how I've been doing it at Udacity for the last couple years. This method has meant we've been able to update Bootstrap whenever we wanted to without having merge conflicts, thrown out work, etc. etc.

The post goes more in depth with examples, but the basic idea is:

  • Keep a pristine copy of bootstrap and overwrite it externally.
  • Modify one file (bootstrap's variables.less) to include your own variables.
  • Make your site file @include bootstrap.less and then your overrides.

This does mean using LESS, and compiling it down to CSS before shipping it to the client (client-side LESS if finicky, and I generally avoid it) but it is EXTREMELY good for maintainability/upgradability, and getting LESS compilation is really really easy. The linked github code has an example using grunt, but there are many ways to achieve this -- even GUIs if that's your thing.

Using this solution, your example problem would look like:

  • Change the nav bar color with @navbar-inverse-bg in your variables.less (not bootstrap's)
  • Add your own nav bar styles to your bootstrap_overrides.less, overwriting anything you need to as you go.
  • Happiness.

When it comes time to upgrade your bootstrap, you just swap out the pristine bootstrap copy and everything will still work (if bootstrap makes breaking changes, you'll need to update your overrides, but you'd have to do that anyway)

Blog post with walk-through is here.

Code example on github is here.

How to add an image to an svg container using D3.js

In SVG (contrasted with HTML), you will want to use <image> instead of <img> for elements.

Try changing your last block with:

var imgs = svg.selectAll("image").data([0]);
            imgs.enter()
            .append("svg:image")
            ...

how to break the _.each function in underscore.js

It's also good to note that an each loop cannot be broken out of — to break, use _.find instead.

http://underscorejs.org/#each

Spring 3 RequestMapping: Get path value

This has been here quite a while but posting this. Might be useful for someone.

@RequestMapping( "/{id}/**" )
public void foo( @PathVariable String id, HttpServletRequest request ) {
    String urlTail = new AntPathMatcher()
            .extractPathWithinPattern( "/{id}/**", request.getRequestURI() );
}

Can't import database through phpmyadmin file size too large

Its due to PHP that has a file size restriction for uploads.

If you have terminal/shell access then the above answers @Kyotoweb will work.

one way to get it done is that you create an .htaccess/ini file file to change PHP settings to get the sql file uploaded through PHPmyAdmin.

php_value upload_max_filesize 120M //file size
php_value post_max_size 120M
php_value max_execution_time 200
php_value max_input_time 200

Note you should remove this file after upload.

Adding value labels on a matplotlib bar chart

If you only want to add Datapoints above the bars, you could easily do it with:

 for i in range(len(frequencies)): # your number of bars
    plt.text(x = x_values[i]-0.25, #takes your x values as horizontal positioning argument 
    y = y_values[i]+1, #takes your y values as vertical positioning argument 
    s = data_labels[i], # the labels you want to add to the data
    size = 9) # font size of datalabels

Display Yes and No buttons instead of OK and Cancel in Confirm box?

There is the Jquery alert plugin

$.alerts.okButton = ' Yes ';
$.alerts.cancelButton = ' No ';

putting datepicker() on dynamically created elements - JQuery/JQueryUI

Make sure your element with the .date-picker class does NOT already have a hasDatepicker class. If it does, even an attempt to re-initialize with $myDatepicker.datepicker(); will fail! Instead you need to do...

$myDatepicker.removeClass('hasDatepicker').datepicker();

How do I convert hex to decimal in Python?

You could use a literal eval:

>>> ast.literal_eval('0xdeadbeef')
3735928559

Or just specify the base as argument to int:

>>> int('deadbeef', 16)
3735928559

A trick that is not well known, if you specify the base 0 to int, then Python will attempt to determine the base from the string prefix:

>>> int("0xff", 0)
255
>>> int("0o644", 0)
420
>>> int("0b100", 0)
4
>>> int("100", 0)
100

Use Excel pivot table as data source for another Pivot Table

In a new sheet (where you want to create a new pivot table) press the key combination (Alt+D+P). In the list of data source options choose "Microsoft Excel list of database". Click Next and select the pivot table that you want to use as a source (select starting with the actual headers of the fields). I assume that this range is rather static and if you refresh the source pivot and it changes it's size you would have to re-size the range as well. Hope this helps.

Convert a SQL query result table to an HTML table for email

Here my common used script below. I use this for running scripts on two tables/views with SQL job and send results as two HTML tables via mail. Ofcourse you should create mail profile before run this.

DECLARE @mailfrom varchar(max)
DECLARE @subject varchar(100)
DECLARE @tableHTML NVARCHAR(MAX), @tableHTML1 NVARCHAR(MAX), @tableHTML2 NVARCHAR(MAX), @mailbody NVARCHAR(MAX)
DECLARE @Table1 NVARCHAR(MAX), @Table2 NVARCHAR(MAX)
DECLARE @jobName varchar(100)
SELECT @jobName = name from msdb..sysjobs where job_id = $(ESCAPE_NONE(JOBID))

-- If the result set is not empty then fill the Table1 HTML table
IF (SELECT COUNT(*) FROM [Database].[Schema].[Table1]) > 0
BEGIN
SET @Table1 = N''
SELECT @Table1 = @Table1 + '<tr style="font-size:13px;background-color:#FFFFFF">' + 
    '<td>' + ColumnText + '</td>' +
    '<td>' + CAST(ColumnNumber as nvarchar(30)) + '</td>' + '</tr>'  
FROM [Database].[Schema].[Table1]
ORDER BY ColumnText,ColumnNumber

SET @tableHTML1 = 
N'<table border="1" align="Left" cellpadding="2" cellspacing="0" style="color:black;font-family:arial,helvetica,sans-serif;text-align:left;" >' +
N'<tr style ="font-size:13px;font-weight: normal;background: #FFFFFF"> 
<th align=left>ColumnTextHeader1</th>
<th align=left>ColumnNumberHeader2</th> </tr>' + @Table1 + '</table>'
END
ELSE
BEGIN
SET @tableHTML1 = N''
SET @Table1 = N''
END


-- If the result set is not empty then fill the Table2 HTML table
IF (SELECT COUNT(*) FROM [Database].[Schema].[Table2]) > 0
BEGIN
SET @Table2 = N''
SELECT @Table2 = @Table2 + '<tr style="font-size:13px;background-color:#FFFFFF">' + 
    '<td>' + ColumnText + '</td>' +
    '<td>' + CAST(ColumnNumber as nvarchar(30)) + '</td>' + '</tr>'  
FROM [Database].[Schema].[Table2]
ORDER BY ColumnText,ColumnNumber

SET @tableHTML2 = 
N'<table border="1" align="Left" cellpadding="2" cellspacing="0" style="color:black;font-family:arial,helvetica,sans-serif;text-align:left;" >' +
N'<tr style ="font-size:13px;font-weight: normal;background: #FFFFFF"> 
<th align=left>ColumnTextHeader1</th>
<th align=left>ColumnNumberHeader2</th> </tr>' + @Table2 + '</table>'
END
ELSE
BEGIN
SET @tableHTML2 = N''
SET @Table2 = N''
END

SET @tableHTML = @tableHTML1 + @tableHTML2

-- If result sets from Table1 and Table2 are empty, then don't sent mail.
IF (SELECT @tableHTML) <> ''
BEGIN
SET @mailbody = N' Write mail text here<br><br>' + @tableHTML
SELECT @mailfrom = 'SQL Server <' + cast(SERVERPROPERTY('ComputerNamePhysicalNETBIOS') as varchar(50)) + '@domain.com>'
SELECT @subject = N'Mail Subject [Job: ' + @jobName + ']'
    EXEC msdb.dbo.sp_send_dbmail
    @profile_name= 'mailprofilename',
    @recipients= '<[email protected]>',
    @from_address = @mailfrom,
    @reply_to = '<[email protected]>',
    @subject = @subject,
    @body = @mailbody,
    @body_format = 'HTML'
--   ,@importance = 'HIGH'
END

#1071 - Specified key was too long; max key length is 767 bytes

Index Lengths & MySQL / MariaDB


Laravel uses the utf8mb4 character set by default, which includes support for storing "emojis" in the database. If you are running a version of MySQL older than the 5.7.7 release or MariaDB older than the 10.2.2 release, you may need to manually configure the default string length generated by migrations in order for MySQL to create indexes for them. You may configure this by calling the Schema::defaultStringLength method within your AppServiceProvider:

use Illuminate\Support\Facades\Schema;

/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{
    Schema::defaultStringLength(191);
}

Alternatively, you may enable the innodb_large_prefix option for your database. Refer to your database's documentation for instructions on how to properly enable this option.

Reference from blog : https://www.scratchcode.io/specified-key-too-long-error-in-laravel/

Reference from Official laravel documentation : https://laravel.com/docs/5.7/migrations

Client on Node.js: Uncaught ReferenceError: require is not defined

This is because require() does not exist in the browser/client-side JavaScript.

Now you're going to have to make some choices about your client-side JavaScript script management.

You have three options:

  1. Use the <script> tag.
  2. Use a CommonJS implementation. It has synchronous dependencies like Node.js
  3. Use an asynchronous module definition (AMD) implementation.

CommonJS client side-implementations include (most of them require a build step before you deploy):

  1. Browserify - You can use most Node.js modules in the browser. This is my personal favorite.
  2. Webpack - Does everything (bundles JavaScript code, CSS, etc.). It was made popular by the surge of React, but it is notorious for its difficult learning curve.
  3. Rollup - a new contender. It leverages ES6 modules and includes tree-shaking abilities (removes unused code).

You can read more about my comparison of Browserify vs (deprecated) Component.

AMD implementations include:

  1. RequireJS - Very popular amongst client-side JavaScript developers. It is not my taste because of its asynchronous nature.

Note, in your search for choosing which one to go with, you'll read about Bower. Bower is only for package dependencies and is unopinionated on module definitions like CommonJS and AMD.

Sort Java Collection

You should implement the Comparator interface.

example:

public class CustomComparator implements Comparator<CustomObject> 
{
    @Override
    public int compare(CustomObject o1, CustomObject o2) {
        return o1.getId().compareTo(o2.getId());
    }
}

Then you can use the Collections classes Collections.sort() method:

Collections.sort(list, new CustomComparator());

How to put a component inside another component in Angular2?

If you remove directives attribute it should work.

@Component({
    selector: 'parent',
    template: `
            <h1>Parent Component</h1>
            <child></child>
        `
    })
    export class ParentComponent{}


@Component({
    selector: 'child',    
    template: `
            <h4>Child Component</h4>
        `
    })
    export class ChildComponent{}

Directives are like components but they are used in attributes. They also have a declarator @Directive. You can read more about directives Structural Directives and Attribute Directives.

There are two other kinds of Angular directives, described extensively elsewhere: (1) components and (2) attribute directives.

A component manages a region of HTML in the manner of a native HTML element. Technically it's a directive with a template.


Also if you are open the glossary you can find that components are also directives.

Directives fall into one of the following categories:

  • Components combine application logic with an HTML template to render application views. Components are usually represented as HTML elements. They are the building blocks of an Angular application.

  • Attribute directives can listen to and modify the behavior of other HTML elements, attributes, properties, and components. They are usually represented as HTML attributes, hence the name.

  • Structural directives are responsible for shaping or reshaping HTML layout, typically by adding, removing, or manipulating elements and their children.


The difference that components have a template. See Angular Architecture overview.

A directive is a class with a @Directive decorator. A component is a directive-with-a-template; a @Component decorator is actually a @Directive decorator extended with template-oriented features.


The @Component metadata doesn't have directives attribute. See Component decorator.

How to get first and last day of week in Oracle?

SELECT NEXT_DAY (TO_DATE ('01/01/'||SUBSTR('201118',1,4),'MM/DD/YYYY')+(TO_NUMBER(SUBSTR('201118',5,2))*7)-3,'SUNDAY')-7 first_day_wk,
    NEXT_DAY (TO_DATE ('01/01/'||SUBSTR('201118',1,4),'MM/DD/YYYY')+(TO_NUMBER(SUBSTR('201118',5,2))*7)-3,'SATURDAY') last_day_wk FROM dual

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

In case this is useful to anyone I had this same issue. I was bringing in a footer into a web page via jQuery. Inside that footer were some Google scripts for ads and retargeting. I had to move those scripts from the footer and place them directly in the page and that eliminated the notice.

Sorting a vector of custom objects

In the interest of coverage. I put forward an implementation using lambda expressions.

C++11

#include <vector>
#include <algorithm>

using namespace std;

vector< MyStruct > values;

sort( values.begin( ), values.end( ), [ ]( const MyStruct& lhs, const MyStruct& rhs )
{
   return lhs.key < rhs.key;
});

C++14

#include <vector>
#include <algorithm>

using namespace std;

vector< MyStruct > values;

sort( values.begin( ), values.end( ), [ ]( const auto& lhs, const auto& rhs )
{
   return lhs.key < rhs.key;
});

Exact time measurement for performance testing

As others said, Stopwatch should be the right tool for this. There can be few improvements made to it though, see this thread specifically: Benchmarking small code samples in C#, can this implementation be improved?.

I have seen some useful tips by Thomas Maierhofer here

Basically his code looks like:

//prevent the JIT Compiler from optimizing Fkt calls away
long seed = Environment.TickCount;

//use the second Core/Processor for the test
Process.GetCurrentProcess().ProcessorAffinity = new IntPtr(2);

//prevent "Normal" Processes from interrupting Threads
Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High;

//prevent "Normal" Threads from interrupting this thread
Thread.CurrentThread.Priority = ThreadPriority.Highest;

//warm up
method();

var stopwatch = new Stopwatch()
for (int i = 0; i < repetitions; i++)
{
    stopwatch.Reset();
    stopwatch.Start();
    for (int j = 0; j < iterations; j++)
        method();
    stopwatch.Stop();
    print stopwatch.Elapsed.TotalMilliseconds;
}

Another approach is to rely on Process.TotalProcessTime to measure how long the CPU has been kept busy running the very code/process, as shown here This can reflect more real scenario since no other process affects the measurement. It does something like:

 var start = Process.GetCurrentProcess().TotalProcessorTime;
 method();
 var stop = Process.GetCurrentProcess().TotalProcessorTime;
 print (end - begin).TotalMilliseconds;

A naked, detailed implementation of the samething can be found here.

I wrote a helper class to perform both in an easy to use manner:

public class Clock
{
    interface IStopwatch
    {
        bool IsRunning { get; }
        TimeSpan Elapsed { get; }

        void Start();
        void Stop();
        void Reset();
    }



    class TimeWatch : IStopwatch
    {
        Stopwatch stopwatch = new Stopwatch();

        public TimeSpan Elapsed
        {
            get { return stopwatch.Elapsed; }
        }

        public bool IsRunning
        {
            get { return stopwatch.IsRunning; }
        }



        public TimeWatch()
        {
            if (!Stopwatch.IsHighResolution)
                throw new NotSupportedException("Your hardware doesn't support high resolution counter");

            //prevent the JIT Compiler from optimizing Fkt calls away
            long seed = Environment.TickCount;

            //use the second Core/Processor for the test
            Process.GetCurrentProcess().ProcessorAffinity = new IntPtr(2);

            //prevent "Normal" Processes from interrupting Threads
            Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High;

            //prevent "Normal" Threads from interrupting this thread
            Thread.CurrentThread.Priority = ThreadPriority.Highest;
        }



        public void Start()
        {
            stopwatch.Start();
        }

        public void Stop()
        {
            stopwatch.Stop();
        }

        public void Reset()
        {
            stopwatch.Reset();
        }
    }



    class CpuWatch : IStopwatch
    {
        TimeSpan startTime;
        TimeSpan endTime;
        bool isRunning;



        public TimeSpan Elapsed
        {
            get
            {
                if (IsRunning)
                    throw new NotImplementedException("Getting elapsed span while watch is running is not implemented");

                return endTime - startTime;
            }
        }

        public bool IsRunning
        {
            get { return isRunning; }
        }



        public void Start()
        {
            startTime = Process.GetCurrentProcess().TotalProcessorTime;
            isRunning = true;
        }

        public void Stop()
        {
            endTime = Process.GetCurrentProcess().TotalProcessorTime;
            isRunning = false;
        }

        public void Reset()
        {
            startTime = TimeSpan.Zero;
            endTime = TimeSpan.Zero;
        }
    }



    public static void BenchmarkTime(Action action, int iterations = 10000)
    {
        Benchmark<TimeWatch>(action, iterations);
    }

    static void Benchmark<T>(Action action, int iterations) where T : IStopwatch, new()
    {
        //clean Garbage
        GC.Collect();

        //wait for the finalizer queue to empty
        GC.WaitForPendingFinalizers();

        //clean Garbage
        GC.Collect();

        //warm up
        action();

        var stopwatch = new T();
        var timings = new double[5];
        for (int i = 0; i < timings.Length; i++)
        {
            stopwatch.Reset();
            stopwatch.Start();
            for (int j = 0; j < iterations; j++)
                action();
            stopwatch.Stop();
            timings[i] = stopwatch.Elapsed.TotalMilliseconds;
            print timings[i];
        }
        print "normalized mean: " + timings.NormalizedMean().ToString();
    }

    public static void BenchmarkCpu(Action action, int iterations = 10000)
    {
        Benchmark<CpuWatch>(action, iterations);
    }
}

Just call

Clock.BenchmarkTime(() =>
{
    //code

}, 10000000);

or

Clock.BenchmarkCpu(() =>
{
    //code

}, 10000000);

The last part of the Clock is the tricky part. If you want to display the final timing, its up to you to choose what sort of timing you want. I wrote an extension method NormalizedMean which gives you the mean of the read timings discarding the noise. I mean I calculate the the deviation of each timing from the actual mean, and then I discard the values which was farer (only the slower ones) from the mean of deviation (called absolute deviation; note that its not the often heard standard deviation), and finally return the mean of remaining values. This means, for instance, if timed values are { 1, 2, 3, 2, 100 } (in ms or whatever), it discards 100, and returns the mean of { 1, 2, 3, 2 } which is 2. Or if timings are { 240, 220, 200, 220, 220, 270 }, it discards 270, and returns the mean of { 240, 220, 200, 220, 220 } which is 220.

public static double NormalizedMean(this ICollection<double> values)
{
    if (values.Count == 0)
        return double.NaN;

    var deviations = values.Deviations().ToArray();
    var meanDeviation = deviations.Sum(t => Math.Abs(t.Item2)) / values.Count;
    return deviations.Where(t => t.Item2 > 0 || Math.Abs(t.Item2) <= meanDeviation).Average(t => t.Item1);
}

public static IEnumerable<Tuple<double, double>> Deviations(this ICollection<double> values)
{
    if (values.Count == 0)
        yield break;

    var avg = values.Average();
    foreach (var d in values)
        yield return Tuple.Create(d, avg - d);
}

How to free memory from char array in C

The memory associated with arr is freed automatically when arr goes out of scope. It is either a local variable, or allocated statically, but it is not dynamically allocated.

A simple rule for you to follow is that you must only every call free() on a pointer that was returned by a call to malloc, calloc or realloc.

Passing HTML to template using Flask/Jinja2

You can also declare it HTML safe from the code:

from flask import Markup
value = Markup('<strong>The HTML String</strong>')

Then pass that value to the templates and they don't have to |safe it.

How to delete all files from a specific folder?

System.IO.DirectoryInfo myDirInfo = new DirectoryInfo(myDirPath);

foreach (FileInfo file in myDirInfo.GetFiles())
{
    file.Delete(); 
}
foreach (DirectoryInfo dir in myDirInfo.GetDirectories())
{
    dir.Delete(true); 
}

Constants in Objective-C

If you like namespace constant, you can leverage struct, Friday Q&A 2011-08-19: Namespaced Constants and Functions

// in the header
extern const struct MANotifyingArrayNotificationsStruct
{
    NSString *didAddObject;
    NSString *didChangeObject;
    NSString *didRemoveObject;
} MANotifyingArrayNotifications;

// in the implementation
const struct MANotifyingArrayNotificationsStruct MANotifyingArrayNotifications = {
    .didAddObject = @"didAddObject",
    .didChangeObject = @"didChangeObject",
    .didRemoveObject = @"didRemoveObject"
};

How do I delete an item or object from an array using ng-click?

Here is another answer. I hope it will help.

<a class="btn" ng-click="delete(item)">Delete</a>

$scope.delete(item){
 var index = this.list.indexOf(item);
                this.list.splice(index, 1);   
}

array.splice(start)
array.splice(start, deleteCount)
array.splice(start, deleteCount, item1, item2, ...)

Full source is here
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

How can you remove all documents from a collection with Mongoose?

MongoDB shell version v4.2.6
Node v14.2.0

Assuming you have a Tour Model: tourModel.js

const mongoose = require('mongoose');

const tourSchema = new mongoose.Schema({
  name: {
    type: String,
    required: [true, 'A tour must have a name'],
    unique: true,
    trim: true,
  },
  createdAt: {
    type: Date,
    default: Date.now(),
  },
});
const Tour = mongoose.model('Tour', tourSchema);

module.exports = Tour;

Now you want to delete all tours at once from your MongoDB, I also providing connection code to connect with the remote cluster. I used deleteMany(), if you do not pass any args to deleteMany(), then it will delete all the documents in Tour collection.

const mongoose = require('mongoose');
const Tour = require('./../../models/tourModel');
const conStr = 'mongodb+srv://lord:<PASSWORD>@cluster0-eeev8.mongodb.net/tour-guide?retryWrites=true&w=majority';
const DB = conStr.replace('<PASSWORD>','ADUSsaZEKESKZX');
mongoose.connect(DB, {
    useNewUrlParser: true,
    useCreateIndex: true,
    useFindAndModify: false,
    useUnifiedTopology: true,
  })
  .then((con) => {
    console.log(`DB connection successful ${con.path}`);
  });

const deleteAllData = async () => {
  try {
    await Tour.deleteMany();
    console.log('All Data successfully deleted');
  } catch (err) {
    console.log(err);
  }
};

ImportError: No module named pip

In terminal try this:

ls -lA /usr/local/bin | grep pip

in my case i get:

-rwxr-xr-x 1 root  root      284 ??? 13 16:20 pip
-rwxr-xr-x 1 root  root      204 ??? 27 16:37 pip2
-rwxr-xr-x 1 root  root      204 ??? 27 16:37 pip2.7
-rwxr-xr-x 1 root  root      292 ??? 13 16:20 pip-3.4

So pip2 || pip2.7 in my case works, and pip

How to decode encrypted wordpress admin password?

MD5 encrypting is possible, but decrypting is still unknown (to me). However, there are many ways to compare these things.

  1. Using compare methods like so:

    <?php
      $db_pass = $P$BX5675uhhghfhgfhfhfgftut/0;
      $my_pass = "mypass";
      if ($db_pass === md5($my_pass)) {
        // password is matched
      } else {
        // password didn't match
      }
    
  2. Only for WordPress users. If you have access to your PHPMyAdmin, focus you have because you paste that hashing here: $P$BX5675uhhghfhgfhfhfgftut/0, WordPress user_pass is not only MD5 format it also uses utf8_mb4_cli charset so what to do?

    That's why I use another Approach if I forget my WordPress password I use

    I install other WordPress with new password :P, and I then go to PHPMyAdmin and copy that hashing from the database and paste that hashing to my current PHPMyAdmin password ( which I forget )

    EASY is use this :

    1. password = "ARJUNsingh@123"
    2. password_hasing = " $P$BDSdKx2nglM.5UErwjQGeVtVWvjEvD1 "
    3. Replace your $P$BX5675uhhghfhgfhfhfgftut/0 with my $P$BDSdKx2nglM.5UErwjQGeVtVWvjEvD1

I USE THIS APPROACH FOR MY SELF WHEN I DESIGN THEMES AND PLUGINS

WORDPRESS USE THIS

https://developer.wordpress.org/reference/functions/wp_hash_password/

How to find a number in a string using JavaScript?

// stringValue can be anything in which present any number
`const stringValue = 'last_15_days';
// /\d+/g is regex which is used for matching number in string
// match helps to find result according to regex from string and return match value
 const result = stringValue.match(/\d+/g);
 console.log(result);`

output will be 15

If You want to learn more about regex here are some links:

https://www.w3schools.com/jsref/jsref_obj_regexp.asp

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

https://www.tutorialspoint.com/javascript/javascript_regexp_object.htm

How to display activity indicator in middle of the iphone screen?

Try this way

UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    activityIndicator.frame = CGRectMake(10.0, 0.0, 40.0, 40.0);
    activityIndicator.center = super_view.center;
    [super_view addSubview: activityIndicator];

[activityIndicator startAnimating];

How to check file MIME type with javascript before upload?

Here is a Typescript implementation that supports webp. This is based on the JavaScript answer by Vitim.us.

interface Mime {
  mime: string;
  pattern: (number | undefined)[];
}

// tslint:disable number-literal-format
// tslint:disable no-magic-numbers
const imageMimes: Mime[] = [
  {
    mime: 'image/png',
    pattern: [0x89, 0x50, 0x4e, 0x47]
  },
  {
    mime: 'image/jpeg',
    pattern: [0xff, 0xd8, 0xff]
  },
  {
    mime: 'image/gif',
    pattern: [0x47, 0x49, 0x46, 0x38]
  },
  {
    mime: 'image/webp',
    pattern: [0x52, 0x49, 0x46, 0x46, undefined, undefined, undefined, undefined, 0x57, 0x45, 0x42, 0x50, 0x56, 0x50],
  }
  // You can expand this list @see https://mimesniff.spec.whatwg.org/#matching-an-image-type-pattern
];
// tslint:enable no-magic-numbers
// tslint:enable number-literal-format

function isMime(bytes: Uint8Array, mime: Mime): boolean {
  return mime.pattern.every((p, i) => !p || bytes[i] === p);
}

function validateImageMimeType(file: File, callback: (b: boolean) => void) {
  const numBytesNeeded = Math.max(...imageMimes.map(m => m.pattern.length));
  const blob = file.slice(0, numBytesNeeded); // Read the needed bytes of the file

  const fileReader = new FileReader();

  fileReader.onloadend = e => {
    if (!e || !fileReader.result) return;

    const bytes = new Uint8Array(fileReader.result as ArrayBuffer);

    const valid = imageMimes.some(mime => isMime(bytes, mime));

    callback(valid);
  };

  fileReader.readAsArrayBuffer(blob);
}

// When selecting a file on the input
fileInput.onchange = () => {
  const file = fileInput.files && fileInput.files[0];
  if (!file) return;

  validateImageMimeType(file, valid => {
    if (!valid) {
      alert('Not a valid image file.');
    }
  });
};

_x000D_
_x000D_
<input type="file" id="fileInput">
_x000D_
_x000D_
_x000D_

Using array map to filter results with if conditional

Here's some info if someone comes upon this in 2019.

I think reduce vs map + filter might be somewhat dependent on what you need to loop through. Not sure on this but reduce does seem to be slower.

One thing is for sure - if you're looking for performance improvements the way you write the code is extremely important!

Here a JS perf test that shows the massive improvements when typing out the code fully rather than checking for "falsey" values (e.g. if (string) {...}) or returning "falsey" values where a boolean is expected.

Hope this helps someone

Why is "cursor:pointer" effect in CSS not working

I have the same issue, when I close the chrome window popup browser inspector its working fine for me.

How to fix C++ error: expected unqualified-id

Get rid of the semicolon after WordGame.

You really should have discovered this problem when the class was a lot smaller. When you're writing code, you should be compiling about every time you add half a dozen lines.

The import android.support cannot be resolved

Please follow these Steps:

For Eclipse:

  • Go to your Project's Properties
  • Navigate to the Java Build Path
  • Then go to the Libraries tab. There click the Add External JARs Button on the Right pane.
  • Select the android-support-v4.jar file, usually the path for the Jar file is :
    YOUR_DRIVE\android-sdks\extras\android\support\v4\android-support-v4.jar
  • After adding android-support-v4.jar Library, navigate to the Order and Export tab and put check mark on the android-support-v4 Library file.
  • After doing the above, Clean the Project and Build it.
  • Problem Solved.

For Android Studio:

Short Version:

  • Add the following line to your build.gradle file:
    implementation 'com.android.support:support-v4:YOUR_TARGET_VERSION'

Long Version:

  • Go to File -> Project Structure

  • Go to "Dependencies" Tab -> Click on the Plus sign -> Go to "Library dependency"

  • Select the support library "support-v4 (com.android.support:support-v4:YOUR_TARGET_VERSION)"

  • Navigate to your "build.gradle" inside your App Directory and double check if your desired Android Support Library has been added to your dependencies.

  • Rebuild your project and now everything should work.

Further reading regarding this Question:

  1. Support Library - Android Dev
  2. Recent Support Library Revisions
  3. Support Library Packages
  4. What is an Android Support Library?
  5. How Android Support Library work?

I hope this helps.

How to copy a file along with directory structure/path using python?

take a look at shutil. shutil.copyfile(src, dst) will copy a file to another file.

Note that shutil.copyfile will not create directories that do not already exist. for that, use os.makedirs

Can I write into the console in a unit test? If yes, why doesn't the console window open?

As stated, unit tests are designed to run without interaction.

However, you can debug unit tests, just like any other code. The easiest way is to use the Debug button in the Test Results tab.

Being able to debug means being able to use breakpoints. Being able to use breakpoints, then, means being able to use Tracepoints, which I find extremely useful in every day debugging.

Essentially, Tracepoints allow you to write to the Output window (or, more accurately, to standard output). Optionally, you can continue to run, or you can stop like a regular breakpoint. This gives you the "functionality" you are asking for, without the need to rebuild your code, or fill it up with debug information.

Simply add a breakpoint, and then right-click on that breakpoint. Select the "When Hit..." option:

When hitting option

Which brings up the dialog:

When a breakpoint is hit

A few things to note:

  1. Notice that the breakpoint is now shown as a diamond, instead of a sphere, indicating a trace point
  2. You can output the value of a variable by enclosing it like {this}.
  3. Uncheck the "Continue Execution" checkbox to have the code break on this line, like any regular breakpoint
  4. You have the option of running a macro. Please be careful - you may cause harmful side effects.

See the documentation for more details.

How to join three table by laravel eloquent model

$articles =DB::table('articles')
                ->join('categories','articles.id', '=', 'categories.id')
                ->join('user', 'articles.user_id', '=', 'user.id')
                ->select('articles.id','articles.title','articles.body','user.user_name', 'categories.category_name')
                ->get();
return view('myarticlesview',['articles'=>$articles]);

Cannot serve WCF services in IIS on Windows 8

you can add this code to web.config in asp mvc

   <system.webServer>
    <staticContent>
      <remove fileExtension=".srt" />
      <mimeMap fileExtension=".srt" mimeType="text/srt" />
      <remove fileExtension=".vtt" />
      <mimeMap fileExtension=".vtt" mimeType="text/vtt" />
    </staticContent>
  </system.webServer>

you can change file extension with your file extension

Testing if a list of integer is odd or even

There's at least 7 different ways to test if a number is odd or even. But, if you read through these benchmarks, you'll find that as TGH mentioned above, the modulus operation is the fastest:

if (x % 2 == 0)
               //even number
        else
               //odd number

Here are a few other methods (from the website) :

//bitwise operation
if ((x & 1) == 0)
       //even number
else
      //odd number

//bit shifting
if (((x >> 1) << 1) == x)
       //even number
else
       //odd number

//using native library
System.Math.DivRem((long)x, (long)2, out outvalue);
if ( outvalue == 0)
       //even number
else
       //odd number

How do you right-justify text in an HTML textbox?

Using inline styles:

<input type="text" style="text-align: right"/>

or, put it in a style sheet, like so:

<style>
   .rightJustified {
        text-align: right;
    }
</style>

and reference the class:

<input type="text" class="rightJustified"/>

In Java 8 how do I transform a Map<K,V> to another Map<K,V> using a lambda?

If you don't mind using 3rd party libraries, my cyclops-react lib has extensions for all JDK Collection types, including Map. You can directly use the map or bimap methods to transform your Map. A MapX can be constructed from an existing Map eg.

  MapX<String, Column> y = MapX.fromMap(orgColumnMap)
                               .map(c->new Column(c.getValue());

If you also wish to change the key you can write

  MapX<String, Column> y = MapX.fromMap(orgColumnMap)
                               .bimap(this::newKey,c->new Column(c.getValue());

bimap can be used to transform the keys and values at the same time.

As MapX extends Map the generated map can also be defined as

  Map<String, Column> y

How to install requests module in Python 3.4, instead of 2.7

You can specify a Python version for pip to use:

pip3.4 install requests

Python 3.4 has pip support built-in, so you can also use:

python3.4 -m pip install

If you're running Ubuntu (or probably Debian as well), you'll need to install the system pip3 separately:

sudo apt-get install python3-pip

This will install the pip3 executable, so you can use it, as well as the earlier mentioned python3.4 -m pip:

pip3 install requests

How to pass dictionary items as function arguments in python?

*data interprets arguments as tuples, instead you have to pass **data which interprets the arguments as dictionary.

data = {'school':'DAV', 'class': '7', 'name': 'abc', 'city': 'pune'}


def my_function(**data):
    schoolname  = data['school']
    cityname = data['city']
    standard = data['class']
    studentname = data['name']

You can call the function like this:

my_function(**data)

Unable to resolve host "<insert URL here>" No address associated with hostname

Also, make sure that your device isn't on airplane mode and/or that data usage is enabled.

Error message Strict standards: Non-static method should not be called statically in php

Try this:

$r = Page()->getInstanceByName($page);

It worked for me in a similar case.

Hide "NFC Tag type not supported" error on Samsung Galaxy devices

Before Android 4.4

What you are trying to do is simply not possible from an app (at least not on a non-rooted/non-modified device). The message "NFC tag type not supported" is displayed by the Android system (or more specifically the NFC system service) before and instead of dispatching the tag to your app. This means that the NFC system service filters MIFARE Classic tags and never notifies any app about them. Consequently, your app can't detect MIFARE Classic tags or circumvent that popup message.

On a rooted device, you may be able to bypass the message using either

  1. Xposed to modify the behavior of the NFC service, or
  2. the CSC (Consumer Software Customization) feature configuration files on the system partition (see /system/csc/. The NFC system service disables the popup and dispatches MIFARE Classic tags to apps if the CSC feature <CscFeature_NFC_EnableSecurityPromptPopup> is set to any value but "mifareclassic" or "all". For instance, you could use:

    <CscFeature_NFC_EnableSecurityPromptPopup>NONE</CscFeature_NFC_EnableSecurityPromptPopup>
    

    You could add this entry to, for instance, the file "/system/csc/others.xml" (within the section <FeatureSet> ... </FeatureSet> that already exists in that file).

Since, you asked for the Galaxy S6 (the question that you linked) as well: I have tested this method on the S4 when it came out. I have not verified if this still works in the latest firmware or on other devices (e.g. the S6).

Since Android 4.4

This is pure guessing, but according to this (link no longer available), it seems that some apps (e.g. NXP TagInfo) are capable of detecting MIFARE Classic tags on affected Samsung devices since Android 4.4. This might mean that foreground apps are capable of bypassing that popup using the reader-mode API (see NfcAdapter.enableReaderMode) possibly in combination with NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK.

Reading data from DataGridView in C#

If you wish, you can also use the column names instead of column numbers.

For example, if you want to read data from DataGridView on the 4. row and the "Name" column. It provides me a better understanding for which variable I am dealing with.

dataGridView.Rows[4].Cells["Name"].Value.ToString();

Hope it helps.

Jasmine JavaScript Testing - toBe vs toEqual

To quote the jasmine github project,

expect(x).toEqual(y); compares objects or primitives x and y and passes if they are equivalent

expect(x).toBe(y); compares objects or primitives x and y and passes if they are the same object

Error inflating when extending a class

It's important to write full class path in the xml. I got 'Error inflating class' when only subclass's name was written in.

How to use breakpoints in Eclipse

Breakpoints are just used to check the execution of your code, wherever you will put breakpoints the execution will stop there, so you can just check that your project execution is going forward or not. To get more details follow link:-

http://javapapers.com/core-java/top-10-java-debugging-tips-with-eclipse/

Reading/parsing Excel (xls) files with Python

If you need old XLS format. Below code for ansii 'cp1251'.

import xlrd

file=u'C:/Landau/task/6200.xlsx'

try:
    book = xlrd.open_workbook(file,encoding_override="cp1251")  
except:
    book = xlrd.open_workbook(file)
print("The number of worksheets is {0}".format(book.nsheets))
print("Worksheet name(s): {0}".format(book.sheet_names()))
sh = book.sheet_by_index(0)
print("{0} {1} {2}".format(sh.name, sh.nrows, sh.ncols))
print("Cell D30 is {0}".format(sh.cell_value(rowx=29, colx=3)))
for rx in range(sh.nrows):
   print(sh.row(rx))

how to get the last part of a string before a certain character?

You are looking for str.rsplit(), with a limit:

print x.rsplit('-', 1)[0]

.rsplit() searches for the splitting string from the end of input string, and the second argument limits how many times it'll split to just once.

Another option is to use str.rpartition(), which will only ever split just once:

print x.rpartition('-')[0]

For splitting just once, str.rpartition() is the faster method as well; if you need to split more than once you can only use str.rsplit().

Demo:

>>> x = 'http://test.com/lalala-134'
>>> print x.rsplit('-', 1)[0]
http://test.com/lalala
>>> 'something-with-a-lot-of-dashes'.rsplit('-', 1)[0]
'something-with-a-lot-of'

and the same with str.rpartition()

>>> print x.rpartition('-')[0]
http://test.com/lalala
>>> 'something-with-a-lot-of-dashes'.rpartition('-')[0]
'something-with-a-lot-of'

Are there any SHA-256 javascript implementations that are generally considered trustworthy?

Forge's SHA-256 implementation is fast and reliable.

To run tests on several SHA-256 JavaScript implementations, go to http://brillout.github.io/test-javascript-hash-implementations/.

The results on my machine suggests forge to be the fastest implementation and also considerably faster than the Stanford Javascript Crypto Library (sjcl) mentioned in the accepted answer.

Forge is 256 KB big, but extracting the SHA-256 related code reduces the size to 4.5 KB, see https://github.com/brillout/forge-sha256

Merge or combine by rownames

cbind.fill <- function(x, y){
  xrn <- rownames(x)
  yrn <- rownames(y)
  rn <- union(xrn, yrn)
  xcn <- colnames(x)
  ycn <- colnames(y)
  if(is.null(xrn) | is.null(yrn) | is.null(xcn) | is.null(ycn)) 
    stop("NULL rownames or colnames")
  z <- matrix(NA, nrow=length(rn), ncol=length(xcn)+length(ycn))
  rownames(z) <- rn
  colnames(z) <- c(xcn, ycn)
  idx <- match(rn, xrn)
  z[!is.na(idx), 1:length(xcn)] <- x[na.omit(idx),]
  idy <- match(rn, yrn)
  z[!is.na(idy), length(xcn)+(1:length(ycn))] <- y[na.omit(idy),]
  return(z)
}

Copy data from one existing row to another existing row in SQL?

Maybe I read the problem wrong, but I believe you already have inserted the course 11 records and simply need to update those that meet the criteria you listed with course 6's data.

If this is the case, you'll want to use an UPDATE...FROM statement:

UPDATE MyTable
SET
    complete = 1,
    complete_date = newdata.complete_date,
    post_score = newdata.post_score
FROM
    (
    SELECT
        userID,
        complete_date,
        post_score
    FROM MyTable
    WHERE
        courseID = 6
        AND complete = 1
        AND complete_date > '8/1/2008'
    ) newdata
WHERE
    CourseID = 11
    AND userID = newdata.userID

See this related SO question for more info

Only on Firefox "Loading failed for the <script> with source"

I've just had the same issue - for me Privacy Badger on Firefox was the issue - not adblocker. Posting for posterity

Docker is installed but Docker Compose is not ? why?

I'm installing on a Raspberry Pi 3, with Raspbian 8. The curl method failed for me (got a line 1: Not: command not found error upon asking for docker-compose --version) and the solution of @sunapi386 seemed a little out-dated, so I tried this which worked:

First clean things up from previous efforts:

sudo rm /usr/local/bin/docker-compose
sudo pip uninstall docker-compose

Then follow this guidance re docker-compose on Rpi:

sudo apt-get -y install python-pip
sudo pip install docker-compose

For me (on 1 Nov 2017) this results in the following response to docker-compose --version:

docker-compose version 1.16.1, build 6d1ac219

XAMPP, Apache - Error: Apache shutdown unexpectedly

In my case this happened after installing sql server and the solution was as described in this answer

Xampp - Can't start Apache after install SQL Server and Visual Studio

so I had to just disable "SQL Server Reporting Services" service from Windows services

Cross-browser window resize event - JavaScript / jQuery

Since you are open to jQuery, this plugin seems to do the trick.

Error in plot.new() : figure margins too large in R

Check if your object is a list or a vector. To do this, type is.list(yourobject). If this is true, try renaming it x<-unlist(yourobject). This will make it into a vector you can plot.

Where is HttpContent.ReadAsAsync?

If you are already using Newtonsoft.Json and don't want to install Microsoft.AspNet.WebApi.Client:

 var myInstance = JsonConvert.DeserializeObject<MyClass>(
   await response.Content.ReadAsStringAsync());

Define: What is a HashSet?

A HashSet has an internal structure (hash), where items can be searched and identified quickly. The downside is that iterating through a HashSet (or getting an item by index) is rather slow.

So why would someone want be able to know if an entry already exists in a set?

One situation where a HashSet is useful is in getting distinct values from a list where duplicates may exist. Once an item is added to the HashSet it is quick to determine if the item exists (Contains operator).

Other advantages of the HashSet are the Set operations: IntersectWith, IsSubsetOf, IsSupersetOf, Overlaps, SymmetricExceptWith, UnionWith.

If you are familiar with the object constraint language then you will identify these set operations. You will also see that it is one step closer to an implementation of executable UML.

SQLSTATE[HY000] [2002] Connection refused within Laravel homestead

After you put all configuration on .env file, if you already run php artisan serve, RESTART IT.

How can I get just the first row in a result set AFTER ordering?

An alternative way:

SELECT ...
FROM bla
WHERE finalDate = (SELECT MAX(finalDate) FROM bla) AND
      rownum = 1

Classes vs. Functions

Before answering your question:

If you do not have a Person class, first you must consider whether you want to create a Person class. Do you plan to reuse the concept of a Person very often? If so, you should create a Person class. (You have access to this data in the form of a passed-in variable and you don't care about being messy and sloppy.)

To answer your question:

You have access to their birthyear, so in that case you likely have a Person class with a someperson.birthdate field. In that case, you have to ask yourself, is someperson.age a value that is reusable?

The answer is yes. We often care about age more than the birthdate, so if the birthdate is a field, age should definitely be a derived field. (A case where we would not do this: if we were calculating values like someperson.chanceIsFemale or someperson.positionToDisplayInGrid or other irrelevant values, we would not extend the Person class; you just ask yourself, "Would another program care about the fields I am thinking of extending the class with?" The answer to that question will determine if you extend the original class, or make a function (or your own class like PersonAnalysisData or something).)

multiple classes on single element html

Short Answer

Yes.


Explanation

It is a good practice since an element can be a part of different groups, and you may want specific elements to be a part of more than one group. The element can hold an infinite number of classes in HTML5, while in HTML4 you are limited by a specific length.

The following example will show you the use of multiple classes.

The first class makes the text color red.

The second class makes the background-color blue.

See how the DOM Element with multiple classes will behave, it will wear both CSS statements at the same time.

Result: multiple CSS statements in different classes will stack up.

You can read more about CSS Specificity.


CSS

.class1 {
    color:red;
}

.class2 {
    background-color:blue;
}

HTML

<div class="class1">text 1</div>
<div class="class2">text 2</div>
<div class="class1 class2">text 3</div>

Live demo

Traverse all the Nodes of a JSON Object Tree with JavaScript

function traverse(o) {
    for (var i in o) {
        if (!!o[i] && typeof(o[i])=="object") {
            console.log(i, o[i]);
            traverse(o[i]);
        } else {
            console.log(i, o[i]);
        }
    }
}

When to encode space to plus (+) or %20?

+ means a space only in application/x-www-form-urlencoded content, such as the query part of a URL:

http://www.example.com/path/foo+bar/path?query+name=query+value

In this URL, the parameter name is query name with a space and the value is query value with a space, but the folder name in the path is literally foo+bar, not foo bar.

%20 is a valid way to encode a space in either of these contexts. So if you need to URL-encode a string for inclusion in part of a URL, it is always safe to replace spaces with %20 and pluses with %2B. This is what eg. encodeURIComponent() does in JavaScript. Unfortunately it's not what urlencode does in PHP (rawurlencode is safer).

See Also HTML 4.01 Specification application/x-www-form-urlencoded

How to use a TRIM function in SQL Server

Example:

DECLARE @Str NVARCHAR(MAX) = N'
            foo   bar
        Foo           Bar        

'

PRINT '[' + @Str + ']'

DECLARE @StrPrv NVARCHAR(MAX) = N''

WHILE ((@StrPrv <> @Str) AND (@Str IS NOT NULL)) BEGIN
    SET @StrPrv = @Str

    -- Beginning
    IF EXISTS (SELECT 1 WHERE @Str LIKE '[' + CHAR(13) + CHAR(10) + CHAR(9) + ']%')
        SET @Str = LTRIM(RIGHT(@Str, LEN(@Str) - 1))

    -- Ending
    IF EXISTS (SELECT 1 WHERE @Str LIKE '%[' + CHAR(13) + CHAR(10) + CHAR(9) + ']')
        SET @Str = RTRIM(LEFT(@Str, LEN(@Str) - 1))
END

PRINT '[' + @Str + ']'

Result

[
            foo   bar
        Foo           Bar        

]
[foo   bar
        Foo           Bar]

Using fnTrim

Source: https://github.com/reduardo7/fnTrim

SELECT dbo.fnTrim(colName)

OSError: [Errno 8] Exec format error

I will hijack this thread to point out that this error may also happen when target of Popen is not executable. Learnt it hard way when by accident I have had override a perfectly executable binary file with zip file.

How to split a string in shell and get the last field

For those that comfortable with Python, https://github.com/Russell91/pythonpy is a nice choice to solve this problem.

$ echo "a:b:c:d:e" | py -x 'x.split(":")[-1]'

From the pythonpy help: -x treat each row of stdin as x.

With that tool, it is easy to write python code that gets applied to the input.

Edit (Dec 2020): Pythonpy is no longer online. Here is an alternative:

$ echo "a:b:c:d:e" | python -c 'import sys; sys.stdout.write(sys.stdin.read().split(":")[-1])'

it contains more boilerplate code (i.e. sys.stdout.read/write) but requires only std libraries from python.

Convert regular Python string to raw string

Raw strings are not a different kind of string. They are a different way of describing a string in your source code. Once the string is created, it is what it is.

getting only name of the class Class.getName()

Social.class.getSimpleName()

getSimpleName() : Returns the simple name of the underlying class as given in the source code. Returns an empty string if the underlying class is anonymous. The simple name of an array is the simple name of the component type with "[]" appended. In particular the simple name of an array whose component type is anonymous is "[]".

How to put more than 1000 values into an Oracle IN clause

Use ...from table(... :

create or replace type numbertype
as object
(nr number(20,10) )
/ 

create or replace type number_table
as table of numbertype
/ 

create or replace procedure tableselect
( p_numbers in number_table
, p_ref_result out sys_refcursor)
is
begin
  open p_ref_result for
    select *
    from employees , (select /*+ cardinality(tab 10) */ tab.nr from table(p_numbers) tab) tbnrs 
    where id = tbnrs.nr; 
end; 
/ 

This is one of the rare cases where you need a hint, else Oracle will not use the index on column id. One of the advantages of this approach is that Oracle doesn't need to hard parse the query again and again. Using a temporary table is most of the times slower.

edit 1 simplified the procedure (thanks to jimmyorr) + example

create or replace procedure tableselect
( p_numbers in number_table
, p_ref_result out sys_refcursor)
is
begin
  open p_ref_result for
    select /*+ cardinality(tab 10) */ emp.*
    from  employees emp
    ,     table(p_numbers) tab
    where tab.nr = id;
end;
/

Example:

set serveroutput on 

create table employees ( id number(10),name varchar2(100));
insert into employees values (3,'Raymond');
insert into employees values (4,'Hans');
commit;

declare
  l_number number_table := number_table();
  l_sys_refcursor sys_refcursor;
  l_employee employees%rowtype;
begin
  l_number.extend;
  l_number(1) := numbertype(3);
  l_number.extend;
  l_number(2) := numbertype(4);
  tableselect(l_number, l_sys_refcursor);
  loop
    fetch l_sys_refcursor into l_employee;
    exit when l_sys_refcursor%notfound;
    dbms_output.put_line(l_employee.name);
  end loop;
  close l_sys_refcursor;
end;
/

This will output:

Raymond
Hans

How to sort an array of integers correctly

If anyone doesn't understand how Array.sort() works with integers, read this answer.

Alphabetical order:

By default, the sort() method sorts the values as strings in alphabetical and ascending order.

const myArray = [104, 140000, 99];
myArray.sort();
console.log(myArray); // output is [104, 140000, 99]

Ascending order with array.sort(compareFunction):

const myArray = [104, 140000, 99];
myArray.sort(function(a, b){
  return a - b;
});
console.log(myArray); // output is [99, 104, 140000]

Explanation from w3schools:

compareFunction defines an alternative sort order. The function should return a negative, zero, or positive value, depending on the arguments, like: function(a, b){return a-b} When the sort() method compares two values, it sends the values to the compare function, and sorts the values according to the returned (negative, zero, positive) value.

Example:

When comparing 40 and 100, the sort() method calls the compare function(40,100).

The function calculates 40-100, and returns -60 (a negative value).

The sort function will sort 40 as a value lower than 100.

Descending order with array.sort(compareFunction):

const myArray = [104, 140000, 99];
myArray.sort(function(a, b){
  return b - a;
});
console.log(myArray); // output is [140000, 104, 99]

This time we calculated with b - a(i.e., 100-40) which returns a positive value.

How to save a plot as image on the disk?

In some cases one wants to both save and print a base r plot. I spent a bit of time and came up with this utility function:

x = 1:10

basesave = function(expr, filename, print=T) {
  #extension
  exten = stringr::str_match(filename, "\\.(\\w+)$")[, 2]

  switch(exten,
         png = {
           png(filename)
           eval(expr, envir = parent.frame())
           dev.off()
         },
         {stop("filetype not recognized")})


  #print?
  if (print) eval(expr, envir = parent.frame())

  invisible(NULL)
}

#plots, but doesn't save
plot(x)

#saves, but doesn't plot
png("test.png")
plot(x)
dev.off()

#both
basesave(quote(plot(x)), "test.png")

#works with pipe too
quote(plot(x)) %>% basesave("test.png")

Note that one must use quote, otherwise the plot(x) call is run in the global environment and NULL gets passed to basesave().

How to change color in markdown cells ipython/jupyter notebook?

<span style='color:blue '> your message/text </span>

So here it is a perfect html css style entry inside a notebook ipynb file.

Of course you can choose your favourite color here and then your text.

How to restart adb from root to user mode?

This is a very common issue.

One solution is to kill adb server and restart it through command prompt. Sometimes this may not help out.

Just go to Window Task Manager to kill adb process and restart Eclipse.

Will work perfect :)

Cannot find module '@angular/compiler'

In my case this was required:
npm install @angular/compiler --save
npm install @angular/cli --save-dev

Eclipse: "'Periodic workspace save.' has encountered a pro?blem."

I solved the problem switching the workspace.

  1. Go to File (Switch workspace)
  2. Select the destination and create a folder named Workspace
  3. Run a Hello World and close Eclipse (notice that Eclipse creates the folder RemoteSystemsTempFiles automatically)
  4. now copy all your projects into the new folder Workspace
  5. Open Eclipse and if necessary (sometimes Eclipse does not show the projects) import all of them (go to File/ Open projects from File System)

How do I evenly add space between a label and the input field regardless of length of text?

You can use a table

<table class="formcontrols" >   
    <tr>
        <td>
            <label for="firstName">FirstName:</label>
        </td>
        <td  style="padding-left:10px;">
            <input id="firstName" name="firstName" value="John">
        </td>
    </tr>
    <tr>
        <td>
            <label for="Test">Last name:</label>
        </td>
        <td  style="padding-left:10px;">
            <input id="lastName" name="lastName" value="Travolta">
        </td>
    </tr>
</table>

The result would be: ImageResult

what is right way to do API call in react js?

I would like you to have a look at redux http://redux.js.org/index.html

They have very well defined way of handling async calls ie API calls, and instead of using jQuery for API calls, I would like to recommend using fetch or request npm packages, fetch is currently supported by modern browsers, but a shim is also available for server side.

There is also this another amazing package superagent, which has alot many options when making an API request and its very easy to use.

Writing an mp4 video using python opencv

This worked for me.

self._name = name + '.mp4'
self._cap = VideoCapture(0)
self._fourcc = VideoWriter_fourcc(*'MP4V')
self._out = VideoWriter(self._name, self._fourcc, 20.0, (640,480))

How to put individual tags for a scatter plot

Perhaps use plt.annotate:

import numpy as np
import matplotlib.pyplot as plt

N = 10
data = np.random.random((N, 4))
labels = ['point{0}'.format(i) for i in range(N)]

plt.subplots_adjust(bottom = 0.1)
plt.scatter(
    data[:, 0], data[:, 1], marker='o', c=data[:, 2], s=data[:, 3] * 1500,
    cmap=plt.get_cmap('Spectral'))

for label, x, y in zip(labels, data[:, 0], data[:, 1]):
    plt.annotate(
        label,
        xy=(x, y), xytext=(-20, 20),
        textcoords='offset points', ha='right', va='bottom',
        bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
        arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))

plt.show()

enter image description here

500 internal server error, how to debug

You can turn on your PHP errors with error_reporting:

error_reporting(E_ALL);
ini_set('display_errors', 'on');

Edit: It's possible that even after putting this, errors still don't show up. This can be caused if there is a fatal error in the script. From PHP Runtime Configuration:

Although display_errors may be set at runtime (with ini_set()), it won't have any affect if the script has fatal errors. This is because the desired runtime action does not get executed.

You should set display_errors = 1 in your php.ini file and restart the server.

How can I convince IE to simply display application/json rather than offer to download it?

If you are okay with just having IE open the JSON into a notepad, you can change your system's default program for .json files to Notepad.

To do this, create or find a .json file, right mouse click, and select "Open With" or "Choose Default Program."

This might come in handy if you by chance want to use Internet Explorer but your IT company wont let you edit your registry. Otherwise, I recommend the above answers.

How can I show the table structure in SQL Server query?

For SQL Server, if using a newer version, you can use

select *
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME='tableName'

There are different ways to get the schema. Using ADO.NET, you can use the schema methods. Use the DbConnection's GetSchema method or the DataReader'sGetSchemaTable method.

Provided that you have a reader for the for the query, you can do something like this:

using(DbCommand cmd = ...)
using(var reader = cmd.ExecuteReader())
{
    var schema = reader.GetSchemaTable();
    foreach(DataRow row in schema.Rows)
    {
        Debug.WriteLine(row["ColumnName"] + " - " + row["DataTypeName"])
    }
}

See this article for further details.

How to get current page URL in MVC 3

The case (single page style) for browser history

HttpContext.Request.UrlReferrer

How to get diff between all files inside 2 folders that are on the web?

Once you have the source trees, e.g.

diff -ENwbur repos1/ repos2/ 

Even better

diff -ENwbur repos1/ repos2/  | kompare -o -

and have a crack at it in a good gui tool :)

  • -Ewb ignore the bulk of whitespace changes
  • -N detect new files
  • -u unified
  • -r recurse

Does Python's time.time() return the local or UTC timestamp?

Based on the answer from #squiguy, to get a true timestamp I would type cast it from float.

>>> import time
>>> ts = int(time.time())
>>> print(ts)
1389177318

At least that's the concept.

How do I get TimeSpan in minutes given two Dates?

TimeSpan span = end-start;
double totalMinutes = span.TotalMinutes;

Why do we have to normalize the input for an artificial neural network?

It's explained well here.

If the input variables are combined linearly, as in an MLP [multilayer perceptron], then it is rarely strictly necessary to standardize the inputs, at least in theory. The reason is that any rescaling of an input vector can be effectively undone by changing the corresponding weights and biases, leaving you with the exact same outputs as you had before. However, there are a variety of practical reasons why standardizing the inputs can make training faster and reduce the chances of getting stuck in local optima. Also, weight decay and Bayesian estimation can be done more conveniently with standardized inputs.

getting file size in javascript

You could probably try this to get file sizes in kB and MB Until the file size in bytes would be upto 7 digits, the outcome would be in kbs. 7 seems to be the magic number here. After which, if the bytes would have 7 to 10 digits, we would have to divide it by 10**3(n) where n is the appending action . This pattern would repeat for every 3 digits added.

let fileSize = myInp.files[0].size.toString();

if(fileSize.length < 7) return `${Math.round(+fileSize/1024).toFixed(2)}kb`
    return `${(Math.round(+fileSize/1024)/1000).toFixed(2)}MB`

Array Size (Length) in C#

it goes like this: 1D:

 type[] name=new type[size]  //or =new type[]{.....elements...}

2D:

 type[][]name=new type[size][] //second brackets are emtpy

then as you use this array :

 name[i]=new type[size_of_sec.Dim]

or You can declare something like a matrix

type[ , ] name=new type [size1,size2]

Input button target="_blank" isn't causing the link to load in a new window/tab

Instead of

onClick="parent.location='http://www.facebook.com/'"

try using

onClick="window.open='http://www.facebook.com/'" onClick="window.open('http://www.facebook.com/','facebook')"

How can I remove 3 characters at the end of a string in php?

<?php echo substr("abcabcabc", 0, -3); ?>

How to call a Parent Class's method from Child Class in Python?

Many answers have explained how to call a method from the parent which has been overridden in the child.

However

"how do you call a parent class's method from child class?"

could also just mean:

"how do you call inherited methods?"

You can call methods inherited from a parent class just as if they were methods of the child class, as long as they haven't been overwritten.

e.g. in python 3:

class A():
  def bar(self, string):
    print("Hi, I'm bar, inherited from A"+string)

class B(A):
  def baz(self):
    self.bar(" - called by baz in B")

B().baz() # prints out "Hi, I'm bar, inherited from A - called by baz in B"

yes, this may be fairly obvious, but I feel that without pointing this out people may leave this thread with the impression you have to jump through ridiculous hoops just to access inherited methods in python. Especially as this question rates highly in searches for "how to access a parent class's method in Python", and the OP is written from the perspective of someone new to python.

I found: https://docs.python.org/3/tutorial/classes.html#inheritance to be useful in understanding how you access inherited methods.

Automatically start a Windows Service on install

Despite following the accepted answer exactly, I was still unable to get the service to start-- I was instead given a failure message during installation stating that the service that was just installed could not be started, as it did not exist, despite using this.serviceInstaller.ServiceName rather than a literal...

I eventually found an alternative solution that makes use of the command line:

private void serviceInstaller_AfterInstall(object sender, InstallEventArgs e) {
        ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
        startInfo.FileName = "cmd.exe";
        startInfo.Arguments = "/C sc start " + this.serviceInstaller.ServiceName;

        Process process = new Process();
        process.StartInfo = startInfo;
        process.Start();
    }

No mapping found for HTTP request with URI.... in DispatcherServlet with name

I solved my issue with : Java Build Path -> JRE system library - > Edit -> Alternate JRE -> -> Finish

As it was configured to JDK folder so it was giving Exception

How to download a branch with git?

git checkout -b branch/name

git pull origin branch/name

How to run html file on localhost?

You can run your file in http-server.

1> Have Node.js installed in your system.

2> In CMD, run the command npm install http-server -g

3> Navigate to the specific path of your file folder in CMD and run the command http-server

4> Go to your browser and type localhost:8080. Your Application should run there.

Thanks:)

How to access elements of a JArray (or iterate over them)

There is a much simpler solution for that.
Actually treating the items of JArray as JObject works.
Here is an example:
Let's say we have such array of JSON objects:

JArray jArray = JArray.Parse(@"[
              {
                ""name"": ""Croke Park II"",
                ""url"": ""http://twitter.com/search?q=%22Croke+Park+II%22"",
                ""promoted_content"": null,
                ""query"": ""%22Croke+Park+II%22"",
                ""events"": null
              },
              {
                ""name"": ""Siptu"",
                ""url"": ""http://twitter.com/search?q=Siptu"",
                ""promoted_content"": null,
                ""query"": ""Siptu"",
                ""events"": null
              }]");

To get access each item we just do the following:

foreach (JObject item in jArray)
{
    string name = item.GetValue("name").ToString();
    string url = item.GetValue("url").ToString();
    // ...
}

JAVA_HOME and PATH are set but java -version still shows the old one

There is an easy way, just remove the symbolic link from "/usr/bin". It will work.

ASP.NET document.getElementById('<%=Control.ClientID%>'); returns null

Gotcha!

You have to use RegisterStartupScript instead of RegisterClientScriptBlock

Here My Example.

MasterPage:

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="MasterPage.master.cs"
    Inherits="prueba.MasterPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <script type="text/javascript">

        function confirmCallBack() {
            var a = document.getElementById('<%= Page.Master.FindControl("ContentPlaceHolder1").FindControl("Button1").ClientID %>');

            alert(a.value);

        }

    </script>

    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
        </asp:ContentPlaceHolder>
    </div>
    </form>
</body>
</html>

WebForm1.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.Master" AutoEventWireup="true"
    CodeBehind="WebForm1.aspx.cs" Inherits="prueba.WebForm1" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">

</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button" />
</asp:Content>

WebForm1.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace prueba
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "js", "confirmCallBack();", true);

        }
    }
}

How to print something when running Puppet client?

If, like me, you don't have access to the puppet master and need to print debug logs to inspect variables on your puppet client machine, you can try writing to a file from your puppet code itself:

file { '/tmp/puppet_debug.log':
  content => inline_template('<%= @variable_x.to_s %>'),
}

jQuery Set Select Index

Shortly:

$("#selectBox").attr("selectedIndex",index)

where index is the selected index as integer.

Find out time it took for a python script to complete execution

import time 

startTime = time.time()
# Your code here !
print ('The script took {0} second !'.format(time.time() - startTime))

The previous code works for me with no problem !

Java HashMap performance optimization / alternative

Another poster already pointed out that your hashcode implementation will result in a lot of collisions due to the way that you're adding values together. I'm willing to be that, if you look at the HashMap object in a debugger, you'll find that you have maybe 200 distinct hash values, with extremely long bucket chains.

If you always have values in the range 0..51, each of those values will take 6 bits to represent. If you always have 5 values, you can create a 30-bit hashcode with left-shifts and additions:

    int code = a[0];
    code = (code << 6) + a[1];
    code = (code << 6) + b[0];
    code = (code << 6) + b[1];
    code = (code << 6) + b[2];
    return code;

The left-shift is fast, but will leave you with hashcodes that aren't evenly distributed (because 6 bits implies a range 0..63). An alternative is to multiply the hash by 51 and add each value. This still won't be perfectly distributed (eg, {2,0} and {1,52} will collide), and will be slower than the shift.

    int code = a[0];
    code *= 51 + a[1];
    code *= 51 + b[0];
    code *= 51 + b[1];
    code *= 51 + b[2];
    return code;

MySQL error #1054 - Unknown column in 'Field List'

I had this error aswell.

I am working in mysql workbench. When giving the values they have to be inside "". That solved it for me.

Find closing HTML tag in Sublime Text

Try Emmet plug-in command Go To Matching Pair:

http://docs.emmet.io/actions/go-to-pair/

Shortcut (Mac): Shift + Control + T

Shortcut (PC): Control + Alt + J

https://github.com/sergeche/emmet-sublime#available-actions

Current user in Magento?

I don't know this off the top of my head, but look in the file which shows the user's name, etc in the header of the page after the user has logged in. It might help if you turned on template hints (see this tutorial.

When you find the line such as "Hello <? //code for showing username?>", just copy that line and show it where you need to

Python Requests package: Handling xml response

requests does not handle parsing XML responses, no. XML responses are much more complex in nature than JSON responses, how you'd serialize XML data into Python structures is not nearly as straightforward.

Python comes with built-in XML parsers. I recommend you use the ElementTree API:

import requests
from xml.etree import ElementTree

response = requests.get(url)

tree = ElementTree.fromstring(response.content)

or, if the response is particularly large, use an incremental approach:

    response = requests.get(url, stream=True)
    # if the server sent a Gzip or Deflate compressed response, decompress
    # as we read the raw stream:
    response.raw.decode_content = True

    events = ElementTree.iterparse(response.raw)
    for event, elem in events:
        # do something with `elem`

The external lxml project builds on the same API to give you more features and power still.

Disable all Database related auto configuration in Spring Boot

I had the same problem here, solved like this:

Just add another application-{yourprofile}.yml where "yourprofile" could be "client".

In my case I just wanted to remove Redis in a Dev profile, so I added a application-dev.yml next to the main application.yml and it did the job.

In this file I put:

spring.autoconfigure.exclude: org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration

this should work with properties files as well.

I like the fact that there is no need to change the application code to do that.

How to populate a dropdownlist with json data in jquery?

var listItems= "";
var jsonData = jsonObj.d;
    for (var i = 0; i < jsonData.Table.length; i++){
      listItems+= "<option value='" + jsonData.Table[i].stateid + "'>" + jsonData.Table[i].statename + "</option>";
    }
    $("#<%=DLState.ClientID%>").html(listItems);

Example

   <html>
    <head></head>
    <body>
      <select id="DLState">
      </select>
    </body>
    </html>

    /*javascript*/
    var jsonList = {"Table" : [{"stateid" : "2","statename" : "Tamilnadu"},
                {"stateid" : "3","statename" : "Karnataka"},
                {"stateid" : "4","statename" : "Andaman and Nicobar"},
                 {"stateid" : "5","statename" : "Andhra Pradesh"},
                 {"stateid" : "6","statename" : "Arunachal Pradesh"}]}

    $(document).ready(function(){
      var listItems= "";
      for (var i = 0; i < jsonList.Table.length; i++){
        listItems+= "<option value='" + jsonList.Table[i].stateid + "'>" + jsonList.Table[i].statename + "</option>";
      }
      $("#DLState").html(listItems);
    });    

Getting Spring Application Context

Even after adding @Autowire if your class is not a RestController or Configuration Class, the applicationContext object was coming as null. Tried Creating new class with below and it is working fine:

@Component
public class SpringContext implements ApplicationContextAware{

   private static ApplicationContext applicationContext;

   @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws 
     BeansException {
    this.applicationContext=applicationContext;
   }
 }

you can then implement a getter method in the same class as per your need like getting the Implemented class reference by:

    applicationContext.getBean(String serviceName,Interface.Class)

restrict edittext to single line

Use Below Code instead of your code

<EditText 
    android:id="@+id/searchbox"  
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:maxLines="1"
    android:inputType="text"
    android:scrollHorizontally="true"
    android:ellipsize="end"
    android:layout_weight="1"
    android:layout_marginTop="2dp"
    android:drawablePadding="10dp"
    android:background="@drawable/edittext"
    android:drawableLeft="@drawable/folder_full"
    android:drawableRight="@drawable/search"
    android:paddingLeft="15dp"
    android:hint="search..."/>

member names cannot be the same as their enclosing type C#

A constructor should no have a return type . remove void before each constructor .

Some very basic characteristic of a constructor :

a. Same name as class b. no return type. c. will be called every time an object is made with the class. for eg- in your program if u made two objects of Flow, Flow flow1=new Flow(); Flow flow2=new Flow(); then Flow constructor will be called for 2 times.

d. If you want to call the constructor just for once then declare that as static (static constructor) and dont forget to remove any access modifier from static constructor ..

Bad Gateway 502 error with Apache mod_proxy and Tomcat

Just to add some specific settings, I had a similar setup (with Apache 2.0.63 reverse proxying onto Tomcat 5.0.27).

For certain URLs the Tomcat server could take perhaps 20 minutes to return a page.

I ended up modifying the following settings in the Apache configuration file to prevent it from timing out with its proxy operation (with a large over-spill factor in case Tomcat took longer to return a page):

Timeout 5400
ProxyTimeout 5400

Some backgound

ProxyTimeout alone wasn't enough. Looking at the documentation for Timeout I'm guessing (I'm not sure) that this is because while Apache is waiting for a response from Tomcat, there is no traffic flowing between Apache and the Browser (or whatever http client) - and so Apache closes down the connection to the browser.

I found that if I left the Timeout setting at its default (300 seconds), then if the proxied request to Tomcat took longer than 300 seconds to get a response the browser would display a "502 Proxy Error" page. I believe this message is generated by Apache, in the knowledge that it's acting as a reverse proxy, before it closes down the connection to the browser (this is my current understanding - it may be flawed).

The proxy error page says:

Proxy Error

The proxy server received an invalid response from an upstream server. The proxy server could not handle the request GET.

Reason: Error reading from remote server

...which suggests that it's the ProxyTimeout setting that's too short, while investigation shows that Apache's Timeout setting (timeout between Apache and the client) that also influences this.

how to automatically scroll down a html page?

You can use two different techniques to achieve this.

The first one is with javascript: set the scrollTop property of the scrollable element (e.g. document.body.scrollTop = 1000;).

The second is setting the link to point to a specific id in the page e.g.

<a href="mypage.html#sectionOne">section one</a>

Then if in your target page you'll have that ID the page will be scrolled automatically.

C# Remove object from list of objects

You're removing and then incrementing, which means you'll be one ahead of yourself. Instead, remove in reverse so you never mess up your next item.

for (int i = ChunkList.Count-1; i >=0; i--)
{
    if (ChunkList[i].UniqueID == ChunkID)
    {
        ChunkList.RemoveAt(i);
    }
}

How to use <DllImport> in VB.NET?

You can also try this

Private Declare Function GetWindowText Lib "user32.dll" (ByVal hwnd As IntPtr, ByVal lpString As StringBuilder, ByVal cch As Integer) As Integer

I always use Declare Function instead of DllImport... Its more simply, its shorter and does the same

Pandas: Creating DataFrame from Series

I guess anther way, possibly faster, to achieve this is 1) Use dict comprehension to get desired dict (i.e., taking 2nd col of each array) 2) Then use pd.DataFrame to create an instance directly from the dict without loop over each col and concat.

Assuming your mat looks like this (you can ignore this since your mat is loaded from file):

In [135]: mat = {'a': np.random.randint(5, size=(4,2)),
   .....: 'b': np.random.randint(5, size=(4,2))}

In [136]: mat
Out[136]: 
{'a': array([[2, 0],
        [3, 4],
        [0, 1],
        [4, 2]]), 'b': array([[1, 0],
        [1, 1],
        [1, 0],
        [2, 1]])}

Then you can do:

In [137]: df = pd.DataFrame ({name:mat[name][:,1] for name in mat})

In [138]: df
Out[138]: 
   a  b
0  0  0
1  4  1
2  1  0
3  2  1

[4 rows x 2 columns]

SQLSTATE[HY000] [1698] Access denied for user 'root'@'localhost'

MySQL makes a difference between "localhost" and "127.0.0.1".

It might be possible that 'root'@'localhost' is not allowed because there is an entry in the user table that will only allow root login from 127.0.0.1.

This could also explain why some application on your server can connect to the database and some not because there are different ways of connecting to the database. And you currently do not allow it through "localhost".

Create a new cmd.exe window from within another cmd.exe prompt

Simply type start in the command prompt:

start

This will open up new cmd windows.

Grouping switch statement cases together?

No, unless you want to break compatibility and your compiler supports it.

How to count objects in PowerShell?

Just use parenthesis and 'count'. This applies to Powershell v3

(get-alias).count

DateTime.Now.ToShortDateString(); replace month and day

this.TextBox3.Text = DateTime.Now.ToString("MM.dd.yyyy");

How to get data by SqlDataReader.GetValue by column name

thisReader.GetString(int columnIndex)

How to encode a string in JavaScript for displaying in HTML?

If you want to use a library rather than doing it yourself:

The most commonly used way is using jQuery for this purpose:

var safestring = $('<div>').text(unsafestring).html();

If you want to to encode all the HTML entities you will have to use a library or write it yourself.

You can use a more compact library than jQuery, like HTML Encoder and Decode

Python Pandas Counting the Occurrences of a Specific value

Couple of ways using count or sum

In [338]: df
Out[338]:
  col1 education
0    a       9th
1    b       9th
2    c       8th

In [335]: df.loc[df.education == '9th', 'education'].count()
Out[335]: 2

In [336]: (df.education == '9th').sum()
Out[336]: 2

In [337]: df.query('education == "9th"').education.count()
Out[337]: 2

Count how many files in directory PHP

You can simply do the following :

$fi = new FilesystemIterator(__DIR__, FilesystemIterator::SKIP_DOTS);
printf("There were %d Files", iterator_count($fi));

Python socket connection timeout

For setting the Socket timeout, you need to follow these steps:

import socket
socks = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socks.settimeout(10.0) # settimeout is the attr of socks.

Limit the output of the TOP command to a specific process name

Using the approach mentioned in the answer by Rick Byers:

top -p `pgrep java | paste -sd "," -`

but I had more than 20 processes running so following command can be helpful for someone who encounter a similar situation.

top -p `pgrep java | head -n 20 | paste -sd "," -`

pgrep gets the list of processes with given name - java in this case. head is used to get first 20 pids because top cannot handle more than 20 pids when using -p argument. Finally paste joins the list of pids with ','.

You can control the process name you are looking for in the above command and the number of processes with that name you are interested to watch. You can ignore the head -n 20 part if the number of your processes with the given name is less than 20.

Remove the last chars of the Java String variable

import org.apache.commons.lang3.StringUtils;

// path = "http://cdn.gs.com/new/downloads/Q22010MVR_PressRelease.pdf.null"
StringUtils.removeEnd(path, ".null");
// path = "http://cdn.gs.com/new/downloads/Q22010MVR_PressRelease.pdf"

Limit the height of a responsive image with css

You can use inline styling to limit the height:

<img src="" class="img-responsive" alt="" style="max-height: 400px;">

mssql '5 (Access is denied.)' error during restoring database

I was getting the same error while trying to restore SQL 2008 R2 backup db in SQL 2012 DB. I guess the error is due to insufficient permissions to place .mdf and .ldf files in C drive. I tried one simple thing then I succeeded in restoring it successfully.

Try this:

In the Restore DB wizard windows, go to Files tab, change the restore destination from C: to some other drive. Then proceed with the regular restore process. It will definitely get restores successfully!

Hope this helps you too. Cheers :)

REST response code for invalid data

If the request could not be correctly parsed (including the request entity/body) the appropriate response is 400 Bad Request [1].

RFC 4918 states that 422 Unprocessable Entity is applicable when the request entity is syntactically well-formed, but semantically erroneous. So if the request entity is garbled (like a bad email format) use 400; but if it just doesn't make sense (like @example.com) use 422.

If the issue is that, as stated in the question, user name/email already exists, you could use 409 Conflict [2] with a description of the conflict, and a hint about how to fix it (in this case, "pick a different user name/email"). However in the spec as written, 403 Forbidden [3] can also be used in this case, arguments about HTTP Authorization notwithstanding.

412 Precondition Failed [4] is used when a precondition request header (e.g. If-Match) that was supplied by the client evaluates to false. That is, the client requested something and supplied preconditions, knowing full well that those preconditions might fail. 412 should never be sprung on the client out of the blue, and shouldn't be related to the request entity per se.

Difference between .keystore file and .jks file

Ultimately, .keystore and .jks are just file extensions: it's up to you to name your files sensibly. Some application use a keystore file stored in $HOME/.keystore: it's usually implied that it's a JKS file, since JKS is the default keystore type in the Sun/Oracle Java security provider. Not everyone uses the .jks extension for JKS files, because it's implied as the default. I'd recommend using the extension, just to remember which type to specify (if you need).

In Java, the word keystore can have either of the following meanings, depending on the context:

When talking about the file and storage, this is not really a storage facility for key/value pairs (there are plenty or other formats for this). Rather, it's a container to store cryptographic keys and certificates (I believe some of them can also store passwords). Generally, these files are encrypted and password-protected so as not to let this data available to unauthorized parties.

Java uses its KeyStore class and related API to make use of a keystore (whether it's file based or not). JKS is a Java-specific file format, but the API can also be used with other file types, typically PKCS#12. When you want to load a keystore, you must specify its keystore type. The conventional extensions would be:

  • .jks for type "JKS",
  • .p12 or .pfx for type "PKCS12" (the specification name is PKCS#12, but the # is not used in the Java keystore type name).

In addition, BouncyCastle also provides its implementations, in particular BKS (typically using the .bks extension), which is frequently used for Android applications.

Add property to an array of objects

I came up against this problem too, and in trying to solve it I kept crashing the chrome tab that was running my app. It looks like the spread operator for objects was the culprit.

With a little help from adrianolsk’s comment and sidonaldson's answer above, I used Object.assign() the output of the spread operator from babel, like so:

this.options.map(option => {
  // New properties to be added
  const newPropsObj = {
    newkey1:value1,
    newkey2:value2
  };

  // Assign new properties and return
  return Object.assign(option, newPropsObj);
});

How can I access a hover state in reactjs?

React components expose all the standard Javascript mouse events in their top-level interface. Of course, you can still use :hover in your CSS, and that may be adequate for some of your needs, but for the more advanced behaviors triggered by a hover you'll need to use the Javascript. So to manage hover interactions, you'll want to use onMouseEnter and onMouseLeave. You then attach them to handlers in your component like so:

<ReactComponent
    onMouseEnter={() => this.someHandler}
    onMouseLeave={() => this.someOtherHandler}
/>

You'll then use some combination of state/props to pass changed state or properties down to your child React components.

How can I detect the touch event of an UIImageView?

For those of you looking for a Swift 4 solution to this answer, you can use the following to detect a touch event on a UIImageView.

let gestureRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageViewTapped))
imageView.addGestureRecognizer(gestureRecognizer)
imageView.isUserInteractionEnabled = true

You will then need to define your selector as follows:

@objc func imageViewTapped() {
    // Image has been tapped
}

Extract a page from a pdf as a jpeg

One problem,everyone will face that is to Install Poppler.My way is a tricky way,but will work efficiently.1st download Poppler here.Then Extract it add In the code section just add poppler_path=r'C:\Program Files\poppler-0.68.0\bin'(for eg.) like below

from pdf2image import convert_from_path
images = convert_from_path("mypdf.pdf", 500,poppler_path=r'C:\Program Files\poppler-0.68.0\bin')
for i, image in enumerate(images):
    fname = 'image'+str(i)+'.png'
    image.save(fname, "PNG")

How to create a file in Android?

From here: http://www.anddev.org/working_with_files-t115.html

//Writing a file...  



try { 
       // catches IOException below
       final String TESTSTRING = new String("Hello Android");

       /* We have to use the openFileOutput()-method
       * the ActivityContext provides, to
       * protect your file from others and
       * This is done for security-reasons.
       * We chose MODE_WORLD_READABLE, because
       *  we have nothing to hide in our file */             
       FileOutputStream fOut = openFileOutput("samplefile.txt",
                                                            MODE_PRIVATE);
       OutputStreamWriter osw = new OutputStreamWriter(fOut); 

       // Write the string to the file
       osw.write(TESTSTRING);

       /* ensure that everything is
        * really written out and close */
       osw.flush();
       osw.close();

//Reading the file back...

       /* We have to use the openFileInput()-method
        * the ActivityContext provides.
        * Again for security reasons with
        * openFileInput(...) */

        FileInputStream fIn = openFileInput("samplefile.txt");
        InputStreamReader isr = new InputStreamReader(fIn);

        /* Prepare a char-Array that will
         * hold the chars we read back in. */
        char[] inputBuffer = new char[TESTSTRING.length()];

        // Fill the Buffer with data from the file
        isr.read(inputBuffer);

        // Transform the chars to a String
        String readString = new String(inputBuffer);

        // Check if we read back the same chars that we had written out
        boolean isTheSame = TESTSTRING.equals(readString);

        Log.i("File Reading stuff", "success = " + isTheSame);

    } catch (IOException ioe) 
      {ioe.printStackTrace();}

Lightweight Javascript DB for use in Node.js

NeDB seems to be what you are looking for. From the blurb:

Embedded persistent database for Node.js, written in Javascript, with no dependency (except npm modules of course). You can think of it as a SQLite for Node.js projects, which can be used with a simple require statement. The API is a subset of MongoDB's. You can use it as a persistent or an in-memory only datastore.

Meaning of tilde in Linux bash (not home directory)

Those are users. Check your /etc/passwd.

cd ~username takes you to that user's home directory.

How can I get Android Wifi Scan Results into a list?

Wrap an ArrayAdapter around your List<ScanResult>. Override getView() to populate your rows with the ScanResult data. Here is a free excerpt from one of my books that covers how to create custom ArrayAdapters like this.

"if not exist" command in batch file

When testing for directories remember that every directory contains two special files.

One is called '.' and the other '..'

. is the directory's own name while .. is the name of it's parent directory.

To avoid trailing backslash problems just test to see if the directory knows it's own name.

eg:

if not exist %temp%\buffer\. mkdir %temp%\buffer

Error: Configuration with name 'default' not found in Android Studio

This is probably a rare case, but for me a library that was included in the settings.gradle was not there.

E.g. I had: include ':libraries:Android-RateThisApp:library' in my settings.gradle

but the folder Android-RateThisApp was empty. As soon as I checked out this submodule the gradle sync succeed.

TypeError: method() takes 1 positional argument but 2 were given

In simple words.

In Python you should add self argument as the first argument to all defined methods in classes:

class MyClass:
  def method(self, arg):
    print(arg)

Then you can use your method according to your intuition:

>>> my_object = MyClass()
>>> my_object.method("foo")
foo

This should solve your problem :)

For a better understanding, you can also read the answers to this question: What is the purpose of self?

How can I do a BEFORE UPDATED trigger with sql server?

It is true that there aren't "before triggers" in MSSQL. However, you could still track the changes that were made on the table, by using the "inserted" and "deleted" tables together. When an update causes the trigger to fire, the "inserted" table stores the new values and the "deleted" table stores the old values. Once having this info, you could relatively easy simulate the "before trigger" behaviour.

Python - Check If Word Is In A String

What about to split the string and strip words punctuation?

w in [ws.strip(',.?!') for ws in p.split()]

Or working the case:

w.lower() in [ws.strip(',.?!') for ws in p.lower().split()]

Maybe that way:

def wsearch(word, phrase):
    # Attention about punctuation and about split characters
    punctuation = ',.?!'
    return word.lower() in [words.strip(punctuation) for words in phrase.lower().split()]

Sample:

print(wsearch('CAr', 'I own a caR.'))

I didn't check performance...

What's the bad magic number error?

Loading a python3 generated *.pyc file with python2 also causes this error.