Programs & Examples On #Triangle count

Using If else in SQL Select statement

You can also use a union construct. I'm not sure if CASE is a common SQL construct ...

SELECT ID FROM tabName WHERE IDParent<1 OR IDParent IS NULL
UNION 
SELECT IDParent FROM tabName WHERE IDParent>1

Extracting Ajax return data in jQuery

You may also use the jQuery context parameter. Link to docs

Selector Context

By default, selectors perform their searches within the DOM starting at the document root. However, an alternate context can be given for the search by using the optional second parameter to the $() function

Therefore you could also have:

success: function(data){
    var oneval = $('#one',data).text();
    var subval = $('#sub',data).text();
}

How to align a div inside td element using CSS class

I cannot help you much without a small (possibly reduced) snippit of the problem. If the problem is what I think it is then it's because a div by default takes up 100% width, and as such cannot be aligned.

What you may be after is to align the inline elements inside the div (such as text) with text-align:center; otherwise you may consider setting the div to display:inline-block;

If you do go down the inline-block route then you may have to consider my favorite IE hack.

width:100px;
display:inline-block;
zoom:1; //IE only
*display:inline; //IE only

Happy Coding :)

PHP PDO: charset, set names?

This is probably the most elegant way to do it.
Right in the PDO constructor call, but avoiding the buggy charset option (as mentioned above):

$connect = new PDO(
  "mysql:host=$host;dbname=$db", 
  $user, 
  $pass, 
  array(
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"
  )
);

Works great for me.

Cannot use string offset as an array in php

I just want to explain my solving for the same problem.

my code before(given same error):

$arr2= ""; // this is the problem and solve by replace this $arr2 = array();
for($i=2;$i<count($arrdata);$i++){
    $rowx = explode(" ",$arrdata[$i]);
    $arr1= ""; // and this is too
    for($x=0;$x<count($rowx);$x++){
        if($rowx[$x]!=""){
            $arr1[] = $rowx[$x];
        }
    }
    $arr2[] = $arr1;
}
for($i=0;$i<count($arr2);$i++){
    $td .="<tr>";
    for($j=0;$j<count($hcol)-1;$j++){
        $td .= "<td style='border-right:0px solid #000'>".$arr2[$i][$j]."</td>"; //and it's($arr2[$i][$j]) give an error: Cannot use string offset as an array
    }
    $td .="</tr>";
}

my code after and solved it:

$arr2= array(); //change this from $arr2="";
for($i=2;$i<count($arrdata);$i++){
    $rowx = explode(" ",$arrdata[$i]);
    $arr1=array(); //and this
    for($x=0;$x<count($rowx);$x++){
        if($rowx[$x]!=""){
            $arr1[] = $rowx[$x];
        }
    }
    $arr2[] = $arr1;
}
for($i=0;$i<count($arr2);$i++){
    $td .="<tr>";
    for($j=0;$j<count($hcol)-1;$j++){
        $td .= "<td style='border-right:0px solid #000'>".$arr2[$i][$j]."</td>";
    }
    $td .="</tr>";
}

Thank's. Hope it's helped, and sorry if my english mess like boy's room :D

What is the difference between public, private, and protected?

PHP manual has a good read on the question here.

The visibility of a property or method can be defined by prefixing the declaration with the keywords public, protected or private. Class members declared public can be accessed everywhere. Members declared protected can be accessed only within the class itself and by inherited and parent classes. Members declared as private may only be accessed by the class that defines the member.

How to check if a variable is not null?

if myVar is null then if block not execute other-wise it will execute.

if (myVar != null) {...}

Hash Map in Python

Python dictionary is a built-in type that supports key-value pairs.

streetno = {"1": "Sachin Tendulkar", "2": "Dravid", "3": "Sehwag", "4": "Laxman", "5": "Kohli"}

as well as using the dict keyword:

streetno = dict({"1": "Sachin Tendulkar", "2": "Dravid"}) 

or:

streetno = {}
streetno["1"] = "Sachin Tendulkar" 

MySQL, update multiple tables with one query

Let's say I have Table1 with primary key _id and a boolean column doc_availability; Table2 with foreign key _id and DateTime column last_update and I want to change the availability of a document with _id 14 in Table1 to 0 i.e unavailable and update Table2 with the timestamp when the document was last updated. The following query would do the task:

UPDATE Table1, Table2 
SET doc_availability = 0, last_update = NOW() 
WHERE Table1._id = Table2._id AND Table1._id = 14

jQuery .live() vs .on() method for adding a click event after loading dynamic html

Try this:

$('#parent').on('click', '#child', function() {
    // Code
});

From the $.on() documentation:

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on().

Your #child element doesn't exist when you call $.on() on it, so the event isn't bound (unlike $.live()). #parent, however, does exist, so binding the event to that is fine.

The second argument in my code above acts as a 'filter' to only trigger if the event bubbled up to #parent from #child.

How can I fill a column with random numbers in SQL? I get the same value in every row

If you are on SQL Server 2008 you can also use

 CRYPT_GEN_RANDOM(2) % 10000

Which seems somewhat simpler (it is also evaluated once per row as newid is - shown below)

DECLARE @foo TABLE (col1 FLOAT)

INSERT INTO @foo SELECT 1 UNION SELECT 2

UPDATE @foo
SET col1 =  CRYPT_GEN_RANDOM(2) % 10000

SELECT *  FROM @foo

Returns (2 random probably different numbers)

col1
----------------------
9693
8573

Mulling the unexplained downvote the only legitimate reason I can think of is that because the random number generated is between 0-65535 which is not evenly divisible by 10,000 some numbers will be slightly over represented. A way around this would be to wrap it in a scalar UDF that throws away any number over 60,000 and calls itself recursively to get a replacement number.

CREATE FUNCTION dbo.RandomNumber()
RETURNS INT
AS
  BEGIN
      DECLARE @Result INT

      SET @Result = CRYPT_GEN_RANDOM(2)

      RETURN CASE
               WHEN @Result < 60000
                     OR @@NESTLEVEL = 32 THEN @Result % 10000
               ELSE dbo.RandomNumber()
             END
  END  

Email validation using jQuery

Another simple and complete option:

<input type="text" id="Email"/>
<div id="ClasSpan"></div>   
<input id="ValidMail" type="submit"  value="Valid"/>  


function IsEmail(email) {
    var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    return regex.test(email);
}

$("#ValidMail").click(function () {
    $('span', '#ClasSpan').empty().remove();
    if (IsEmail($("#Email").val())) {
        //aqui mi sentencia        
    }
    else {
        $('#ClasSpan').append('<span>Please enter a valid email</span>');
        $('#Email').keypress(function () {
            $('span', '#itemspan').empty().remove();
        });
    }
});

Run a vbscript from another vbscript

See if the following works

Dim objShell
Set objShell = Wscript.CreateObject("WScript.Shell")

objShell.Run "TestScript.vbs" 

' Using Set is mandatory
Set objShell = Nothing

Strange Jackson exception being thrown when serializing Hibernate object

I had the same problem. See if you are using hibernatesession.load(). If so, try converting to hibernatesession.get(). This solved my problem.

jQuery - If element has class do this

First, you're missing some parentheses in your conditional:

if ($("#about").hasClass("opened")) {
  $("#about").animate({right: "-700px"}, 2000);
}

But you can also simplify this to:

$('#about.opened').animate(...);

If #about doesn't have the opened class, it won't animate.

If the problem is with the animation itself, we'd need to know more about your element positioning (absolute? absolute inside relative parent? does the parent have layout?)

How to overload functions in javascript?

For this you need to create a function that adds the function to an object, then it will execute depending on the amount of arguments you send to the function:

<script > 
//Main function to add the methods
function addMethod(object, name, fn) {
  var old = object[name];
  object[name] = function(){
    if (fn.length == arguments.length)
      return fn.apply(this, arguments)
    else if (typeof old == 'function')
      return old.apply(this, arguments);
  };
}


?  var ninjas = {
   values: ["Dean Edwards", "Sam Stephenson", "Alex Russell"]
};

//Here we declare the first function with no arguments passed
  addMethod(ninjas, "find", function(){
    return this.values;
});

//Second function with one argument
  addMethod(ninjas, "find", function(name){
    var ret = [];
    for (var i = 0; i < this.values.length; i++)
      if (this.values[i].indexOf(name) == 0)
        ret.push(this.values[i]);
    return ret;
  });

//Third function with two arguments
  addMethod(ninjas, "find", function(first, last){
    var ret = [];
    for (var i = 0; i < this.values.length; i++)
      if (this.values[i] == (first + " " + last))
        ret.push(this.values[i]);
    return ret;
  });


//Now you can do:
ninjas.find();
ninjas.find("Sam");
ninjas.find("Dean", "Edwards")
</script>

(Built-in) way in JavaScript to check if a string is a valid number

Save yourself the headache of trying to find a "built-in" solution.

There isn't a good answer, and the hugely upvoted answer in this thread is wrong.

npm install is-number

In JavaScript, it's not always as straightforward as it should be to reliably check if a value is a number. It's common for devs to use +, -, or Number() to cast a string value to a number (for example, when values are returned from user input, regex matches, parsers, etc). But there are many non-intuitive edge cases that yield unexpected results:

console.log(+[]); //=> 0
console.log(+''); //=> 0
console.log(+'   '); //=> 0
console.log(typeof NaN); //=> 'number'

Artisan migrate could not find driver

If you are matching with sqlite database:
In your php folder open php.ini file, go to:

;extension=pdo_sqlite

Just remove the semicolon and it will work.

When to use RDLC over RDL reports?

If we have fewer number of reports which are less complex and consumed by asp.net web pages. It's better to go with rdlc,reason is we can avoid maintaing reports on RS instance. but we have to fetch the data from DB manually and bind it to rdlc.

Cons:designing rdlc in visual studio is little difficult compared to SSrs designer.

Pro:Maintenance is easy. while exporting the report from we page,observed that performance gain compared to server side reports.

How to access the GET parameters after "?" in Express?

In my case with the given code, I was able to parse the value of the passed parameter in this way.

_x000D_
_x000D_
const express = require('express');
const bodyParser = require('body-parser');

const app = express(); 
app.use(bodyParser.urlencoded({ extended: false }));
//url/par1=val1&par2=val2 
let val1= req.body.par1;
let val2 = req.body.par2;
_x000D_
_x000D_
_x000D_

Is it possible to use raw SQL within a Spring Repository

It is possible to use raw query within a Spring Repository.

      @Query(value = "SELECT A.IS_MUTUAL_AID FROM planex AS A 
             INNER JOIN planex_rel AS B ON A.PLANEX_ID=B.PLANEX_ID  
             WHERE B.GOOD_ID = :goodId",nativeQuery = true)

      Boolean mutualAidFlag(@Param("goodId")Integer goodId);

Compilation error: stray ‘\302’ in program etc

Invalid character on your code. A common copy paste error specially when code is copied from Word Documents or PDF files.

List of lists into numpy array

>>> numpy.array([[1, 2], [3, 4]]) 
array([[1, 2], [3, 4]])

How do I get the difference between two Dates in JavaScript?

function compare()
{
  var end_actual_time    = $('#date3').val();

  start_actual_time = new Date();
  end_actual_time = new Date(end_actual_time);

  var diff = end_actual_time-start_actual_time;

  var diffSeconds = diff/1000;
  var HH = Math.floor(diffSeconds/3600);
  var MM = Math.floor(diffSeconds%3600)/60;

  var formatted = ((HH < 10)?("0" + HH):HH) + ":" + ((MM < 10)?("0" + MM):MM)
  getTime(diffSeconds);
}
function getTime(seconds) {
  var days = Math.floor(leftover / 86400);

  //how many seconds are left
  leftover = leftover - (days * 86400);

  //how many full hours fits in the amount of leftover seconds
  var hours = Math.floor(leftover / 3600);

  //how many seconds are left
  leftover = leftover - (hours * 3600);

  //how many minutes fits in the amount of leftover seconds
  var minutes = leftover / 60;

  //how many seconds are left
  //leftover = leftover - (minutes * 60);
  alert(days + ':' + hours + ':' + minutes);
}

Raise to power in R

1: No difference. It is kept around to allow old S-code to continue to function. This is documented a "Note" in ?Math

2: Yes: But you already know it:

`^`(x,y)
#[1] 1024

In R the mathematical operators are really functions that the parser takes care of rearranging arguments and function names for you to simulate ordinary mathematical infix notation. Also documented at ?Math.

Edit: Let me add that knowing how R handles infix operators (i.e. two argument functions) is very important in understanding the use of the foundational infix "[[" and "["-functions as (functional) second arguments to lapply and sapply:

> sapply( list( list(1,2,3), list(4,3,6) ), "[[", 1)
[1] 1 4
> firsts <- function(lis) sapply(lis, "[[", 1)
> firsts( list( list(1,2,3), list(4,3,6) ) )
[1] 1 4

Installing NumPy via Anaconda in Windows

Move path\to\anaconda in the PATH above path\to\python

Append a single character to a string or char array in java?

public class lab {
public static void main(String args[]){
   Scanner input = new Scanner(System.in);
   System.out.println("Enter a string:");
   String s1;
   s1 = input.nextLine();
   int k = s1.length();
   char s2;
   s2=s1.charAt(k-1);
   s1=s2+s1+s2;
   System.out.println("The new string is\n" +s1);
   }
  }

Here's the output you'll get.

* Enter a string CAT The new string is TCATT *

It prints the the last character of the string to the first and last place. You can do it with any character of the String.

Encoding Javascript Object to Json string

You can use JSON.stringify like:

JSON.stringify(new_tweets);

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured

If you are using YAML for configuration, then it might be indentation problem. Thoroughly check the YAML files.

How to change text color of cmd with windows batch script every 1 second

on particular computer color codes can be assigned to different RGB color by editing color values in cmd window properties. Easy click color on color palete and change their rgb values.

Unicode character as bullet for list-item in CSS

A more complete example of 222's answer:

ul {
    list-style:none;
    padding: 0 0 0 2em;     /* padding includes space for character and its margin */

    /* IE7 and lower use default */
    *list-style: disc;
    *padding: 0 0 0 1em;
}
ul li:before {
    content: '\25BA';
    font-family: "Courier New", courier, "Lucida Sans Typewriter", "Lucida Typewriter", monospace;
    margin: 0 1em 0 -1em;   /* right margin defines spacing between bullet and text. negative left margin pushes back to the edge of the parent <ul> */

    /* IE7 and lower use default */
    *content: none;
    *margin: 0;
}
ul li {
    text-indent: -1em;      /* negative text indent brings first line back inline with the others */

    /* IE7 and lower use default */
    *text-indent: 0;
}

I have included star-hack properties to restore the default list styles in older IE versions. You could pull these out and include them in a conditional include if desired, or replace with a background-image based solution. My humble opinion is that special bullet styles implemented in this manner should degrade gracefully on the few browsers that don't support pseudoselectors.

Tested in Firefox, Chrome, Safari and IE8-10 and renders correctly in all.

getting " (1) no such column: _id10 " error

I think you missed a equal sign at:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);  

Change to:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null); 

Post-increment and Pre-increment concept?

The difference between the postfix increment, x++, and the prefix increment, ++x, is precisely in how the two operators evaluate their operands. The postfix increment conceptually copies the operand in memory, increments the original operand and finally yields the value of the copy. I think this is best illustrated by implementing the operator in code:

int operator ++ (int& n)  // postfix increment
{
    int tmp = n;
    n = n + 1;
    return tmp;
}

The above code will not compile because you can't re-define operators for primitive types. The compiler also can't tell here we're defining a postfix operator rather than prefix, but let's pretend this is correct and valid C++. You can see that the postfix operator indeed acts on its operand, but it returns the old value prior to the increment, so the result of the expression x++ is the value prior to the increment. x, however, is incremented.

The prefix increment increments its operand as well, but it yields the value of the operand after the increment:

int& operator ++ (int& n)
{
    n = n + 1;
    return n;
}

This means that the expression ++x evaluates to the value of x after the increment.

It's easy to think that the expression ++x is therefore equivalent to the assignmnet (x=x+1). This is not precisely so, however, because an increment is an operation that can mean different things in different contexts. In the case of a simple primitive integer, indeed ++x is substitutable for (x=x+1). But in the case of a class-type, such as an iterator of a linked list, a prefix increment of the iterator most definitely does not mean "adding one to the object".

Split string into array

Use the .split() method. When specifying an empty string as the separator, the split() method will return an array with one element per character.

entry = prompt("Enter your name")
entryArray = entry.split("");

Create Elasticsearch curl query for not null and not empty("")

You can use a bool combination query with must/must_not which gives great performance and returns all records where the field is not null and not empty.

bool must_not is like "NOT AND" which means field!="", bool must exist means its !=null.

so effectively enabling: where field1!=null and field1!=""

GET  IndexName/IndexType/_search
{
    "query": {
        "bool": {
            "must": [{
                "bool": {
                    "must_not": [{
                        "term": { "YourFieldName": ""}
                    }]
                }
            }, {
                "bool": {
                    "must": [{
                      "exists" : { "field" : "YourFieldName" }
                    }]
                }
            }]
        }   
    }
}

ElasticSearch Version:

  "version": {
    "number": "5.6.10",
    "lucene_version": "6.6.1"
  }

What is the C# equivalent of friend?

Take a very common pattern. Class Factory makes Widgets. The Factory class needs to muck about with the internals, because, it is the Factory. Both are implemented in the same file and are, by design and desire and nature, tightly coupled classes -- in fact, Widget is really just an output type from factory.

In C++, make the Factory a friend of Widget class.

In C#, what can we do? The only decent solution that has occurred to me is to invent an interface, IWidget, which only exposes the public methods, and have the Factory return IWidget interfaces.

This involves a fair amount of tedium - exposing all the naturally public properties again in the interface.

Spring MVC UTF-8 Encoding

In addition to Benjamin's answer (which I've only skimmed), you need to make sure that your files are actually stored using the proper encoding (that would be UTF-8 for source code, JSPs etc., but note that Java Properties files must be encoded as ISO 8859-1 by definition).

The problem with this is that it's not possible to tell what encoding has been used to store a file. Your only option is to open the file using a specific encoding, and checking whether or not the content makes sense. You can also try to convert the file from the assumed encoding to the desired encoding using iconv - if that produces an error, your assumption was incorrect. So if you assume that hello.jsp is encoded as UTF-8, run "iconv -f UTF-16 -t UTF-8 hello.jsp" and check for errors.

If you should find out that your files are not properly encoded, you need to find out why. It's probably the editor or IDE you used to create the file. In case of Eclipse (and STS), make sure the Text File Encoding (Preferences / General / Workspace) is set to UTF-8 (it unfortunately defaults to your system's platform encoding).

What makes encoding problems so difficult to debug is that there's so many components involved (text editor, borwser, plus each and every software component in between, in some cases including a database), and each of them has the potential to introduce an error.

how to specify local modules as npm package dependencies

npm install now supports this

npm install --save ../path/to/mymodule

For this to work mymodule must be configured as a module with its own package.json. See Creating NodeJS modules.

As of npm 2.0, local dependencies are supported natively. See danilopopeye's answer to a similar question. I've copied his response here as this question ranks very high in web search results.

This feature was implemented in the version 2.0.0 of npm. For example:

{
  "name": "baz",
  "dependencies": {
    "bar": "file:../foo/bar"
  }
}

Any of the following paths are also valid:

../foo/bar
~/foo/bar
./foo/bar
/foo/bar

syncing updates

Since npm install copies mymodule into node_modules, changes in mymodule's source will not automatically be seen by the dependent project.

There are two ways to update the dependent project with

  • Update the version of mymodule and then use npm update: As you can see above, the package.json "dependencies" entry does not include a version specifier as you would see for normal dependencies. Instead, for local dependencies, npm update just tries to make sure the latest version is installed, as determined by mymodule's package.json. See chriskelly's answer to this specific problem.

  • Reinstall using npm install. This will install whatever is at mymodule's source path, even if it is older, or has an alternate branch checked out, whatever.

How do I make an attributed string using Swift?

The attributes can be setting directly in swift 3...

    let attributes = NSAttributedString(string: "String", attributes: [NSFontAttributeName : UIFont(name: "AvenirNext-Medium", size: 30)!,
         NSForegroundColorAttributeName : UIColor .white,
         NSTextEffectAttributeName : NSTextEffectLetterpressStyle])

Then use the variable in any class with attributes

What does "ulimit -s unlimited" do?

stack size can indeed be unlimited. _STK_LIM is the default, _STK_LIM_MAX is something that differs per architecture, as can be seen from include/asm-generic/resource.h:

/*
 * RLIMIT_STACK default maximum - some architectures override it:
 */
#ifndef _STK_LIM_MAX
# define _STK_LIM_MAX           RLIM_INFINITY
#endif

As can be seen from this example generic value is infinite, where RLIM_INFINITY is, again, in generic case defined as:

/*
 * SuS says limits have to be unsigned.
 * Which makes a ton more sense anyway.
 *
 * Some architectures override this (for compatibility reasons):
 */
#ifndef RLIM_INFINITY
# define RLIM_INFINITY          (~0UL)
#endif

So I guess the real answer is - stack size CAN be limited by some architecture, then unlimited stack trace will mean whatever _STK_LIM_MAX is defined to, and in case it's infinity - it is infinite. For details on what it means to set it to infinite and what implications it might have, refer to the other answer, it's way better than mine.

Regex: ignore case sensitivity

Just for the sake of completeness I wanted to add the solution for regular expressions in C++ with Unicode:

std::tr1::wregex pattern(szPattern, std::tr1::regex_constants::icase);

if (std::tr1::regex_match(szString, pattern))
{
...
}

Why is processing a sorted array faster than processing an unsorted array?

An official answer would be from

  1. Intel - Avoiding the Cost of Branch Misprediction
  2. Intel - Branch and Loop Reorganization to Prevent Mispredicts
  3. Scientific papers - branch prediction computer architecture
  4. Books: J.L. Hennessy, D.A. Patterson: Computer architecture: a quantitative approach
  5. Articles in scientific publications: T.Y. Yeh, Y.N. Patt made a lot of these on branch predictions.

You can also see from this lovely diagram why the branch predictor gets confused.

2-bit state diagram

Each element in the original code is a random value

data[c] = std::rand() % 256;

so the predictor will change sides as the std::rand() blow.

On the other hand, once it's sorted, the predictor will first move into a state of strongly not taken and when the values change to the high value the predictor will in three runs through change all the way from strongly not taken to strongly taken.


How can I convert uppercase letters to lowercase in Notepad++

Ctrl+A , Ctrl+Shift+U

should do the trick!

Edit: Ctrl+U is the shortcut to be used to convert capital letters to lowercase (reverse scenario)

Using SHA1 and RSA with java.security.Signature vs. MessageDigest and Cipher

A slightly more efficient version of the bytes2String method is

private static final char[] hex = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
private static String byteArray2Hex(byte[] bytes) {
    StringBuilder sb = new StringBuilder(bytes.length * 2);
    for (final byte b : bytes) {
        sb.append(hex[(b & 0xF0) >> 4]);
        sb.append(hex[b & 0x0F]);
    }
    return sb.toString();
}

Including external HTML file to another HTML file

You're looking for the <iframe> tag, or, better yet, a server-side templating language.

Where does Android emulator store SQLite database?

The filesystem of the emulator doesn't map to a directory on your hard drive. The emulator's disk image is stored as an image file, which you can manage through either Eclipse (look for the G1-looking icon in the toolbar), or through the emulator binary itself (run "emulator -help" for a description of options).

You're best off using adb from the command line to jack into a running emulator. If you can get the specific directory and filename, you can do an "adb pull" to get the database file off of the emulator and onto your regular hard drive.

Edit: Removed suggestion that this works for unrooted devices too - it only works for emulators, and devices where you are operating adb as root.

Undefined symbols for architecture x86_64 on Xcode 6.1

Check if that file is included in Build Phases -> Compiled Sources

How to scan a folder in Java?

In JDK7, "more NIO features" should have methods to apply the visitor pattern over a file tree or just the immediate contents of a directory - no need to find all the files in a potentially huge directory before iterating over them.

How to change the remote repository for a git submodule?

Just edit your .git/config file. For example; if you have a "common" submodule you can do this in the super-module:

git config submodule.common.url /data/my_local_common

401 Unauthorized: Access is denied due to invalid credentials

I had a permissions issue to a website and just couldn't get Windows authentication to work. It was a folder permissions rather than ASP.NET configuration issue in the end and once the Everyone user was granted permissions it started working.

Jboss server error : Failed to start service jboss.deployment.unit."jbpm-console.war"

I had a similar issue, my error was:

Caused by: org.jboss.as.server.deployment.DeploymentUnitProcessingException: java.lang.ClassNotFoundException:org.glassfish.jersey.servlet.ServletContainer from [Module "deployment.RESTful_Services_CRUD.war:main" from Service Module Loader]

I use jboss and glassfish so I changed the web.xml to the following:

<servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>

Instead of:

<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>

Hope this work for you.

How do I decompile a .NET EXE into readable C# source code?

Reflector is no longer free in general, but they do offer it for free to open source developers: http://reflectorblog.red-gate.com/2013/07/open-source/

But a few companies like DevExtras and JetBrains have created free alternatives:

DevExtras CodeReflect

JetBrains DotPeek

How can I pass data from Flask to JavaScript in a template?

Some js files come from the web or library, they are not written by yourself. The code they get variable like this:

var queryString = document.location.search.substring(1);
var params = PDFViewerApplication.parseQueryString(queryString);
var file = 'file' in params ? params.file : DEFAULT_URL;

This method makes js files unchanged(keep independence), and pass variable correctly!

python-pandas and databases like mysql

For recent readers of this question: pandas have the following warning in their docs for version 14.0:

Warning: Some of the existing functions or function aliases have been deprecated and will be removed in future versions. This includes: tquery, uquery, read_frame, frame_query, write_frame.

And:

Warning: The support for the ‘mysql’ flavor when using DBAPI connection objects has been deprecated. MySQL will be further supported with SQLAlchemy engines (GH6900).

This makes many of the answers here outdated. You should use sqlalchemy:

from sqlalchemy import create_engine
import pandas as pd
engine = create_engine('dialect://user:pass@host:port/schema', echo=False)
f = pd.read_sql_query('SELECT * FROM mytable', engine, index_col = 'ID')

Efficient way to remove keys with empty strings from a dict

If you have a nested dictionary, and you want this to work even for empty sub-elements, you can use a recursive variant of BrenBarn's suggestion:

def scrub_dict(d):
    if type(d) is dict:
        return dict((k, scrub_dict(v)) for k, v in d.iteritems() if v and scrub_dict(v))
    else:
        return d

How can I convert a string to boolean in JavaScript?

I'm a little late, but I have a little snippet to do this, it essentially maintains all of JScripts truthey/falsey/filthy-ness but includes "false" as an acceptible value for false.

I prefer this method to the ones mentioned because it doesn't rely on a 3rd party to parse the code (i.e: eval/JSON.parse), which is overkill in my mind, it's short enough to not require a utility function and maintains other truthey/falsey conventions.

var value = "false";
var result = (value == "false") != Boolean(value);

// value = "true"  => result = true
// value = "false" => result = false
// value = true    => result = true
// value = false   => result = false
// value = null    => result = false
// value = []      => result = true
// etc..

_csv.Error: field larger than field limit (131072)

The csv file might contain very huge fields, therefore increase the field_size_limit:

import sys
import csv

csv.field_size_limit(sys.maxsize)

sys.maxsize works for Python 2.x and 3.x. sys.maxint would only work with Python 2.x (SO: what-is-sys-maxint-in-python-3)

Update

As Geoff pointed out, the code above might result in the following error: OverflowError: Python int too large to convert to C long. To circumvent this, you could use the following quick and dirty code (which should work on every system with Python 2 and Python 3):

import sys
import csv
maxInt = sys.maxsize

while True:
    # decrease the maxInt value by factor 10 
    # as long as the OverflowError occurs.

    try:
        csv.field_size_limit(maxInt)
        break
    except OverflowError:
        maxInt = int(maxInt/10)

Get a UTC timestamp

You can use Date.UTC method to get the time stamp at the UTC timezone.

Usage:

var now = new Date;
var utc_timestamp = Date.UTC(now.getUTCFullYear(),now.getUTCMonth(), now.getUTCDate() , 
      now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds(), now.getUTCMilliseconds());

Live demo here http://jsfiddle.net/naryad/uU7FH/1/

Passing a variable from node.js to html

What you can utilize is some sort of templating engine like pug (formerly jade). To enable it you should do the following:

  1. npm install --save pug - to add it to the project and package.json file
  2. app.set('view engine', 'pug'); - register it as a view engine in express
  3. create a ./views folder and add a simple .pug file like so:
html
  head
    title= title
  body
    h1= message

note that the spacing is very important!

  1. create a route that returns the processed html:
app.get('/', function (req, res) {
  res.render('index', { title: 'Hey', message: 'Hello there!'});
});

This will render an index.html page with the variables passed in node.js changed to the values you have provided. This has been taken directly from the expressjs templating engine page: http://expressjs.com/en/guide/using-template-engines.html

For more info on pug you can also check: https://github.com/pugjs/pug

How to send a stacktrace to log4j?

this would be good log4j error/exception logging - readable by splunk/other logging/monitoring s/w. everything is form of key-value pair. log4j would get the stack trace from Exception obj e

    try {
          ---
          ---
    } catch (Exception e) {
        log.error("api_name={} method={} _message=\"error description.\" msg={}", 
                  new Object[]{"api_name", "method_name", e.getMessage(), e});
    }

How to link to a <div> on another page?

Create an anchor:

<a name="anchor" id="anchor"></a> 

then link to it:

<a href="http://server/page.html#anchor">Link text</a>

"Cannot instantiate the type..."

I had the very same issue, not being able to instantiate the type of a class which I was absolutely sure was not abstract. Turns out I was implementing an abstract class from Java.util instead of implementing my own class.

So if the previous answers did not help you, please check that you import the class you actually wanted to import, and not something else with the same name that you IDE might have hinted you.

For example, if you were trying to instantiate the class Queue from the package myCollections which you coded yourself :

import java.util.*; // replace this line
import myCollections.Queue; // by this line

     Queue<Edge> theQueue = new Queue<Edge>();

SyntaxError: multiple statements found while compiling a single statement

In the shell, you can't execute more than one statement at a time:

>>> x = 5
y = 6
SyntaxError: multiple statements found while compiling a single statement

You need to execute them one by one:

>>> x = 5
>>> y = 6
>>>

When you see multiple statements are being declared, that means you're seeing a script, which will be executed later. But in the interactive interpreter, you can't do more than one statement at a time.

Access elements of parent window from iframe

I think the problem may be that you are not finding your element because of the "#" in your call to get it:

window.parent.document.getElementById('#target'); 

You only need the # if you are using jquery. Here it should be:

window.parent.document.getElementById('target'); 

Check if not nil and not empty in Rails shortcut?

There's a method that does this for you:

def show
  @city = @user.city.present?
end

The present? method tests for not-nil plus has content. Empty strings, strings consisting of spaces or tabs, are considered not present.

Since this pattern is so common there's even a shortcut in ActiveRecord:

def show
  @city = @user.city?
end

This is roughly equivalent.

As a note, testing vs nil is almost always redundant. There are only two logically false values in Ruby: nil and false. Unless it's possible for a variable to be literal false, this would be sufficient:

if (variable)
  # ...
end

This is preferable to the usual if (!variable.nil?) or if (variable != nil) stuff that shows up occasionally. Ruby tends to wards a more reductionist type of expression.

One reason you'd want to compare vs. nil is if you have a tri-state variable that can be true, false or nil and you need to distinguish between the last two states.

How to format strings in Java

This solution worked for me. I needed to create urls for a REST client dynamically so I created this method, so you just have to pass the restURL like this

/customer/{0}/user/{1}/order

and add as many params as you need:

public String createURL (String restURL, Object ... params) {       
    return new MessageFormat(restURL).format(params);
}

You just have to call this method like this:

createURL("/customer/{0}/user/{1}/order", 123, 321);

The output

"/customer/123/user/321/order"

Multiple HttpPost method in Web API controller

public class Journal : ApiController
{
    public MyResult Get(journal id)
    {
        return null;
    }
}

public class Journal : ApiController
{

    public MyResult Get(journal id, publication id)
    {
        return null;
    }
}

I am not sure whether overloading get/post method violates the concept of restfull api,but it workds. If anyone could've enlighten on this matter. What if I have a uri as

uri:/api/journal/journalid
uri:/api/journal/journalid/publicationid

so as you might seen my journal sort of aggregateroot, though i can define another controller for publication solely and pass id number of publication in my url however this gives much more sense. since my publication would not exist without journal itself.

Is it possible to use Java 8 for Android development?

Yes. We will use Java 8 soon!

We've decided to add support for Java 8 language features directly into the current javac and dx set of tools, and deprecate the Jack toolchain. With this new direction, existing tools and plugins dependent on the Java class file format should continue to work. Moving forward, Java 8 language features will be natively supported by the Android build system. We're aiming to launch this as part of Android Studio in the coming weeks, and we wanted to share this decision early with you.

https://android-developers.googleblog.com/2017/03/future-of-java-8-language-feature.html

While variable is not defined - wait

Shorter way:

   var queue = function (args){
      typeof variableToCheck !== "undefined"? doSomething(args) : setTimeout(function () {queue(args)}, 2000);
};

You can also pass arguments

Where do you include the jQuery library from? Google JSAPI? CDN?

In head:

  (function() {
    var jsapi = document.createElement('script'); jsapi.type = 'text/javascript'; jsapi.async = true;
    jsapi.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'www.google.com/jsapi?key=YOUR KEY';
    (document.getElementsByTagName('head')[0] || document.getElementsByTagName('head')[0]).appendChild(jsapi);
  })();

End of Body:

<script type="text/javascript">
google.load("jquery", "version");
</script>

Find a pair of elements from an array whose sum equals a given number

A simple python version of the code that find a pair sum of zero and can be modify to find k:

def sumToK(lst):
    k = 0  # <- define the k here
    d = {} # build a dictionary 

# build the hashmap key = val of lst, value = i
for index, val in enumerate(lst):
    d[val] = index

# find the key; if a key is in the dict, and not the same index as the current key
for i, val in enumerate(lst):
    if (k-val) in d and d[k-val] != i:
        return True

return False

The run time complexity of the function is O(n) and Space: O(n) as well.

Using Bootstrap Tooltip with AngularJS

I wrote a simple Angular Directive that's been working well for us.

Here's a demo: http://jsbin.com/tesido/edit?html,js,output

Directive (for Bootstrap 3):

// registers native Twitter Bootstrap 3 tooltips
app.directive('bootstrapTooltip', function() {
  return function(scope, element, attrs) {
    attrs.$observe('title',function(title){
      // Destroy any existing tooltips (otherwise new ones won't get initialized)
      element.tooltip('destroy');
      // Only initialize the tooltip if there's text (prevents empty tooltips)
      if (jQuery.trim(title)) element.tooltip();
    })
    element.on('$destroy', function() {
      element.tooltip('destroy');
      delete attrs.$$observers['title'];
    });
  }
});

Note: If you're using Bootstrap 4, on lines 6 & 11 above you'll need to replace tooltip('destroy') with tooltip('dispose') (Thanks to user1191559 for this upadate)

Simply add bootstrap-tooltip as an attribute to any element with a title. Angular will monitor for changes to the title but otherwise pass the tooltip handling over to Bootstrap.

This also allows you to use any of the native Bootstrap Tooltip Options as data- attributes in the normal Bootstrap way.

Markup:

<div bootstrap-tooltip data-placement="left" title="Tooltip on left">
        Tooltip on left
</div>

Clearly this doesn't have all the elaborate bindings & advanced integration that AngularStrap and UI Bootstrap offer, but it's a good solution if you're already using Bootstrap's JS in your Angular app and you just need a basic tooltip bridge across your entire app without modifying controllers or managing mouse events.

Having issues with a MySQL Join that needs to meet multiple conditions

If you join the facilities table twice you will get what you are after:

select u.* 
from room u 
  JOIN facilities_r fu1 on fu1.id_uc = u.id_uc and fu1.id_fu = '4'
  JOIN facilities_r fu2 on fu2.id_uc = u.id_uc and fu2.id_fu = '3' 
where 1 and vizibility='1' 
group by id_uc 
order by u_premium desc, id_uc desc

tkinter: Open a new window with a button prompt

Here's the nearly shortest possible solution to your question. The solution works in python 3.x. For python 2.x change the import to Tkinter rather than tkinter (the difference being the capitalization):

import tkinter as tk
#import Tkinter as tk  # for python 2
    
def create_window():
    window = tk.Toplevel(root)

root = tk.Tk()
b = tk.Button(root, text="Create new window", command=create_window)
b.pack()

root.mainloop()

This is definitely not what I recommend as an example of good coding style, but it illustrates the basic concepts: a button with a command, and a function that creates a window.

Adb over wireless without usb cable at all for not rooted phones

Had same issue, however I'm using Macbook Pro (2016) which has USB-c only and I forgot my adapter at home.

Since unable to run adb at all on my development machine, I found a different approach.

Connecting phone with USB cable to another computer (in same WiFi) and enable run adb tcpip from there.

Master-machine : computer where development goes on, with only USB-C connectors

Slave-machine: another computer with USB and in same WiFi

Steps:

  1. Connect the phone to a different computer (slave-machine)
  2. Run adb usb && adb tcpip 5555 from there
  3. On master machine

    deko$: adb devices
    List of devices attached
    
    deko$: adb connect 10.0.20.153:5555
    connected to 10.0.20.153:5555
    
  4. Now Android Studio or Xamarin can install and run app on the phone


Sidenote:

I also tested Bluetooth tethering from the Phone to Master-machine and successfully connected to phone. Both Android Studio and Xamarin worked well, however the upload process, from Xamarin was taking long time. But it works.

How can strip whitespaces in PHP's variable?

To strip any whitespace, you can use a regular expression

$str=preg_replace('/\s+/', '', $str);

See also this answer for something which can handle whitespace in UTF-8 strings.

What is `related_name` used for in Django?

The essentials of your question are as follows.

Since you have Map and User models and you have defined ManyToManyField in Map model, if you want to get access to members of the Map then you have the option of map_instance.members.all() since you have defined members field. However, say you want to access all maps a user is a part of then what option do you have.

By default, Django provided you with user_instance.modelname_set.all() and this will translate to the user.map_set.all() in this case.

maps is much better than map_set.

related_name provides you an ability to let Django know how you are going to access Map from User model or in general how you can access reverse models which is the whole point in creating ManyToMany fields and using ORM in that sense.

How can I convert a Unix timestamp to DateTime and vice versa?

A Unix tick is 1 second (if I remember well), and a .NET tick is 100 nanoseconds.

If you've been encountering problems with nanoseconds, you might want to try using AddTick(10000000 * value).

What is resource-ref in web.xml used for?

You can always refer to resources in your application directly by their JNDI name as configured in the container, but if you do so, essentially you are wiring the container-specific name into your code. This has some disadvantages, for example, if you'll ever want to change the name later for some reason, you'll need to update all the references in all your applications, and then rebuild and redeploy them.

<resource-ref> introduces another layer of indirection: you specify the name you want to use in the web.xml, and, depending on the container, provide a binding in a container-specific configuration file.

So here's what happens: let's say you want to lookup the java:comp/env/jdbc/primaryDB name. The container finds that web.xml has a <resource-ref> element for jdbc/primaryDB, so it will look into the container-specific configuration, that contains something similar to the following:

<resource-ref>
  <res-ref-name>jdbc/primaryDB</res-ref-name>
  <jndi-name>jdbc/PrimaryDBInTheContainer</jndi-name>
</resource-ref>

Finally, it returns the object registered under the name of jdbc/PrimaryDBInTheContainer.

The idea is that specifying resources in the web.xml has the advantage of separating the developer role from the deployer role. In other words, as a developer, you don't have to know what your required resources are actually called in production, and as the guy deploying the application, you will have a nice list of names to map to real resources.

Comparing arrays for equality in C++

When we use an array, we are really using a pointer to the first element in the array. Hence, this condition if( iar1 == iar2 ) actually compares two addresses. Those pointers do not address the same object.

How to add to the end of lines containing a pattern with sed or awk?

Solution with awk:

awk '{if ($1 ~ /^all/) print $0, "anotherthing"; else print $0}' file

Simply: if the row starts with all print the row plus "anotherthing", else print just the row.

SQL multiple columns in IN clause

It often ends up being easier to load your data into the database, even if it is only to run a quick query. Hard-coded data seems quick to enter, but it quickly becomes a pain if you start having to make changes.

However, if you want to code the names directly into your query, here is a cleaner way to do it:

with names (fname,lname) as (
    values
        ('John','Smith'),
        ('Mary','Jones')
)
select city from user
    inner join names on
        fname=firstName and
        lname=lastName;

The advantage of this is that it separates your data out of the query somewhat.

(This is DB2 syntax; it may need a bit of tweaking on your system).

Pull new updates from original GitHub repository into forked GitHub repository

If you want to do it without cli, you can do it fully on Github website.

  1. Go to your fork repository.
  2. Click on New pull request.
  3. Make sure to set your fork as the base repository, and the original (upstream) repository as head repository. Usually you only want to sync the master branch.
  4. Create new pull request.
  5. Select the arrow to the right of the merging button, and make sure to choose rebase instead of merge. Then click the button. This way, it will not produce unnecessary merge commit.
  6. Done.

Catching errors in Angular HttpClient

With the arrival of the HTTPClient API, not only was the Http API replaced, but a new one was added, the HttpInterceptor API.

AFAIK one of its goals is to add default behavior to all the HTTP outgoing requests and incoming responses.

So assumming that you want to add a default error handling behavior, adding .catch() to all of your possible http.get/post/etc methods is ridiculously hard to maintain.

This could be done in the following way as example using a HttpInterceptor:

import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse, HTTP_INTERCEPTORS } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { _throw } from 'rxjs/observable/throw';
import 'rxjs/add/operator/catch';

/**
 * Intercepts the HTTP responses, and in case that an error/exception is thrown, handles it
 * and extract the relevant information of it.
 */
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
    /**
     * Intercepts an outgoing HTTP request, executes it and handles any error that could be triggered in execution.
     * @see HttpInterceptor
     * @param req the outgoing HTTP request
     * @param next a HTTP request handler
     */
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(req)
            .catch(errorResponse => {
                let errMsg: string;
                if (errorResponse instanceof HttpErrorResponse) {
                    const err = errorResponse.message || JSON.stringify(errorResponse.error);
                    errMsg = `${errorResponse.status} - ${errorResponse.statusText || ''} Details: ${err}`;
                } else {
                    errMsg = errorResponse.message ? errorResponse.message : errorResponse.toString();
                }
                return _throw(errMsg);
            });
    }
}

/**
 * Provider POJO for the interceptor
 */
export const ErrorInterceptorProvider = {
    provide: HTTP_INTERCEPTORS,
    useClass: ErrorInterceptor,
    multi: true,
};

// app.module.ts

import { ErrorInterceptorProvider } from 'somewhere/in/your/src/folder';

@NgModule({
   ...
   providers: [
    ...
    ErrorInterceptorProvider,
    ....
   ],
   ...
})
export class AppModule {}

Some extra info for OP: Calling http.get/post/etc without a strong type isn't an optimal use of the API. Your service should look like this:

// These interfaces could be somewhere else in your src folder, not necessarily in your service file
export interface FooPost {
 // Define the form of the object in JSON format that your 
 // expect from the backend on post
}

export interface FooPatch {
 // Define the form of the object in JSON format that your 
 // expect from the backend on patch
}

export interface FooGet {
 // Define the form of the object in JSON format that your 
 // expect from the backend on get
}

@Injectable()
export class DataService {
    baseUrl = 'http://localhost'
    constructor(
        private http: HttpClient) {
    }

    get(url, params): Observable<FooGet> {

        return this.http.get<FooGet>(this.baseUrl + url, params);
    }

    post(url, body): Observable<FooPost> {
        return this.http.post<FooPost>(this.baseUrl + url, body);
    }

    patch(url, body): Observable<FooPatch> {
        return this.http.patch<FooPatch>(this.baseUrl + url, body);
    }
}

Returning Promises from your service methods instead of Observables is another bad decision.

And an extra piece of advice: if you are using TYPEscript, then start using the type part of it. You lose one of the biggest advantages of the language: to know the type of the value that you are dealing with.

If you want a, in my opinion, good example of an angular service, take a look at the following gist.

Diff files present in two different directories

If it's GNU diff then you should just be able to point it at the two directories and use the -r option.

Otherwise, try using

for i in $(\ls -d ./dir1/*); do diff ${i} dir2; done

N.B. As pointed out by Dennis in the comments section, you don't actually need to do the command substitution on the ls. I've been doing this for so long that I'm pretty much doing this on autopilot and substituting the command I need to get my list of files for comparison.

Also I forgot to add that I do '\ls' to temporarily disable my alias of ls to GNU ls so that I lose the colour formatting info from the listing returned by GNU ls.

PHP session lost after redirect

I've been struggling with this for days, checking/trying all the solutions, but my problem was I didn't call session_start(); again after the redirect. I just assumed the session was 'still alive'.

So don't forget that!

Initialize a string in C to empty string

You want to set the first character of the string to zero, like this:

char myString[10];
myString[0] = '\0';

(Or myString[0] = 0;)

Or, actually, on initialisation, you can do:

char myString[10] = "";

But that's not a general way to set a string to zero length once it's been defined.

Cannot resolve the collation conflict between "SQL_Latin1_General_CP1_CI_AS" and "Latin1_General_CI_AS" in the equal to operation

Identify the fields for which it is throwing this error and add following to them: COLLATE DATABASE_DEFAULT

There are two tables joined on Code field:

...
and table1.Code = table2.Code
...

Update your query to:

...
and table1.Code COLLATE DATABASE_DEFAULT = table2.Code COLLATE DATABASE_DEFAULT
...

How to enable NSZombie in Xcode?

in ur XCODE (4.3) next the play button :) (run)

select : edit scheme

the scheme management window will open

click on the Arguments tab

you should see : 1- Arguments passed on launch 2- environment variables

inside the the (2- environment variables) place Name: NSZombieEnabled
Value: YES

And its done....

How to hide a div element depending on Model value? MVC

Your code isn't working, because the hidden attibute is not supported in versions of IE before v11

If you need to support IE before version 11, add a CSS style to hide when the hidden attribute is present:

*[hidden] { display: none; }

How can I view live MySQL queries?

You can log every query to a log file really easily:

mysql> SHOW VARIABLES LIKE "general_log%";

+------------------+----------------------------+
| Variable_name    | Value                      |
+------------------+----------------------------+
| general_log      | OFF                        |
| general_log_file | /var/run/mysqld/mysqld.log |
+------------------+----------------------------+

mysql> SET GLOBAL general_log = 'ON';

Do your queries (on any db). Grep or otherwise examine /var/run/mysqld/mysqld.log

Then don't forget to

mysql> SET GLOBAL general_log = 'OFF';

or the performance will plummet and your disk will fill!

AJAX reload page with POST

By using jquery ajax you can reload your page

$.ajax({
    type: "POST",
    url: "packtypeAdd.php",
    data: infoPO,
    success: function() {   
        location.reload();  
    }
});

How to find a value in an excel column by vba code Cells.Find

I'd prefer to use the .Find method directly on a range object containing the range of cells to be searched. For original poster's code it might look like:

Set cell = ActiveSheet.Columns("B:B").Find( _
    What:=celda, _
    After:=ActiveCell _
    LookIn:=xlFormulas, _
    LookAt:=xlWhole, _
    SearchOrder:=xlByRows, _
    SearchDirection:=xlNext, _
    MatchCase:=False, _
    SearchFormat:=False _
)

If cell Is Nothing Then
    'do something
Else
    'do something else
End If

I'd prefer to use more variables (and be sure to declare them) and let a lot of optional arguments use their default values:

Dim rng as Range
Dim cell as Range
Dim search as String

Set rng = ActiveSheet.Columns("B:B")
search = "String to Find"
Set cell = rng.Find(What:=search, LookIn:=xlFormulas, LookAt:=xlWhole, MatchCase:=False)

If cell Is Nothing Then
    'do something
Else
    'do something else
End If

I kept LookIn:=, LookAt::=, and MatchCase:= to be explicit about what is being matched. The other optional parameters control the order matches are returned in - I'd only specify those if the order is important to my application.

What does a Status of "Suspended" and high DiskIO means from sp_who2?

This is a very broad question, so I am going to give a broad answer.

  1. A query gets suspended when it is requesting access to a resource that is currently not available. This can be a logical resource like a locked row or a physical resource like a memory data page. The query starts running again, once the resource becomes available. 
  2. High disk IO means that a lot of data pages need to be accessed to fulfill the request.

That is all that I can tell from the above screenshot. However, if I were to speculate, you probably have an IO subsystem that is too slow to keep up with the demand. This could be caused by missing indexes or an actually too slow disk. Keep in mind, that 15000 reads for a single OLTP query is slightly high but not uncommon.

Using :before and :after CSS selector to insert Html

content doesn't support HTML, only text. You should probably use javascript, jQuery or something like that.

Another problem with your code is " inside a " block. You should mix ' and " (class='headingDetail').

If content did support HTML you could end up in an infinite loop where content is added inside content.

Get single row result with Doctrine NativeQuery

You can use $query->getSingleResult(), which will throw an exception if more than one result are found, or if no result is found. (see the related phpdoc here https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/AbstractQuery.php#L791)

There's also the less famous $query->getOneOrNullResult() which will throw an exception if more than one result are found, and return null if no result is found. (see the related phpdoc here https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/AbstractQuery.php#L752)

Command line to remove an environment variable from the OS level configuration

To remove the variable from the current command session without removing it permanently, use the regular built-in set command - just put nothing after the equals sign:

set FOOBAR=

To confirm, run set with no arguments and check the current environment. The variable should be missing from the list entirely.

Note: this will only remove the variable from the current environment - it will not persist the change to the registry. When a new command process is started, the variable will be back.

Dealing with multiple Python versions and PIP?

for Blender:

/usr/bin $ python3.7 -m pip install irc

URL encoding the space character: + or %20?

This confusion is because URLs are still 'broken' to this day.

Take "http://www.google.com" for instance. This is a URL. A URL is a Uniform Resource Locator and is really a pointer to a web page (in most cases). URLs actually have a very well-defined structure since the first specification in 1994.

We can extract detailed information about the "http://www.google.com" URL:

+---------------+-------------------+
|      Part     |      Data         |
+---------------+-------------------+
|  Scheme       | http              |
|  Host         | www.google.com    |
+---------------+-------------------+

If we look at a more complex URL such as:

"https://bob:[email protected]:8080/file;p=1?q=2#third"

we can extract the following information:

+-------------------+---------------------+
|        Part       |       Data          |
+-------------------+---------------------+
|  Scheme           | https               |
|  User             | bob                 |
|  Password         | bobby               |
|  Host             | www.lunatech.com    |
|  Port             | 8080                |
|  Path             | /file;p=1           |
|  Path parameter   | p=1                 |
|  Query            | q=2                 |
|  Fragment         | third               |
+-------------------+---------------------+

https://bob:[email protected]:8080/file;p=1?q=2#third
\___/   \_/ \___/ \______________/ \__/\_______/ \_/ \___/
  |      |    |          |          |      | \_/  |    |
Scheme User Password    Host       Port  Path |   | Fragment
        \_____________________________/       | Query
                       |               Path parameter
                   Authority

The reserved characters are different for each part.

For HTTP URLs, a space in a path fragment part has to be encoded to "%20" (not, absolutely not "+"), while the "+" character in the path fragment part can be left unencoded.

Now in the query part, spaces may be encoded to either "+" (for backwards compatibility: do not try to search for it in the URI standard) or "%20" while the "+" character (as a result of this ambiguity) has to be escaped to "%2B".

This means that the "blue+light blue" string has to be encoded differently in the path and query parts:

"http://example.com/blue+light%20blue?blue%2Blight+blue".

From there you can deduce that encoding a fully constructed URL is impossible without a syntactical awareness of the URL structure.

This boils down to:

You should have %20 before the ? and + after.

Source

Init method in Spring Controller (annotation version)

Alternatively you can have your class implement the InitializingBean interface to provide a callback function (afterPropertiesSet()) which the ApplicationContext will invoke when the bean is constructed.

Sending multipart/formdata with jQuery.ajax

Nowadays you don't even need jQuery:) fetch API support table

let result = fetch('url', {method: 'POST', body: new FormData(document.querySelector("#form"))})

How to sort an object array by date property?

I'm going to add this here, as some uses may not be able to work out how to invert this sorting method.

To sort by 'coming up', we can simply swap a & b, like so:

your_array.sort ( (a, b) => {
      return new Date(a.DateTime) - new Date(b.DateTime);
});

Notice that a is now on the left hand side, and b is on the right, :D!

Using CSS how to change only the 2nd column of a table

You can use the :nth-child pseudo class like this:

.countTable table table td:nth-child(2)

Note though, this won't work in older browsers (or IE), you'll need to give the cells a class or use javascript in that case.

Tkinter understanding mainloop

while 1:
    root.update()

... is (very!) roughly similar to:

root.mainloop()

The difference is, mainloop is the correct way to code and the infinite loop is subtly incorrect. I suspect, though, that the vast majority of the time, either will work. It's just that mainloop is a much cleaner solution. After all, calling mainloop is essentially this under the covers:

while the_window_has_not_been_destroyed():
    wait_until_the_event_queue_is_not_empty()
    event = event_queue.pop()
    event.handle()

... which, as you can see, isn't much different than your own while loop. So, why create your own infinite loop when tkinter already has one you can use?

Put in the simplest terms possible: always call mainloop as the last logical line of code in your program. That's how Tkinter was designed to be used.

How to use if statements in underscore.js templates?

If you prefer shorter if else statement, you can use this shorthand:

<%= typeof(id)!== 'undefined' ?  id : '' %>

It means display the id if is valid and blank if it wasn't.

How to find the minimum value of a column in R?

If you need minimal value for particular column

min(data[,2])

Note: R considers NA both the minimum and maximum value so if you have NA's in your column, they return: NA. To remedy, use:

min(data[,2], na.rm=T)

C++ convert string to hexadecimal and vice versa

You can try this. It's Working...

#include <algorithm>
#include <sstream>
#include <iostream>
#include <iterator>
#include <iomanip>

namespace {
   const std::string test="hello world";
}

int main() {
   std::ostringstream result;
   result << std::setw(2) << std::setfill('0') << std::hex << std::uppercase;
   std::copy(test.begin(), test.end(), std::ostream_iterator<unsigned int>(result, " "));
   std::cout << test << ":" << result.str() << std::endl;
}

CSS list item width/height does not work

Remove the <br> from the .navcontainer-top li styles.

Get loop count inside a Python FOR loop

Agree with Nick. Here is more elaborated code.

#count=0
for idx, item in enumerate(list):
    print item
    #count +=1
    #if count % 10 == 0:
    if (idx+1) % 10 == 0:
        print 'did ten'

I have commented out the count variable in your code.

How to loop through each and every row, column and cells in a GridView and get its value

foreach (DataGridViewRow row in GridView2.Rows)
            {
                if ( ! row.IsNewRow)
                {
                    for (int i = 0; i < GridView2.Columns.Count; i++)
                    {
                        String header = GridView2.Columns[i].HeaderText;
                        String cellText = Convert.ToString(row.Cells[i].Value);
                    }
                }
            }

Here Before Iterating for cell Values need to check for NewRow.

What is for Python what 'explode' is for PHP?

The alternative for explode in php is split.

The first parameter is the delimiter, the second parameter the maximum number splits. The parts are returned without the delimiter present (except possibly the last part). When the delimiter is None, all whitespace is matched. This is the default.

>>> "Rajasekar SP".split()
['Rajasekar', 'SP']

>>> "Rajasekar SP".split('a',2)
['R','j','sekar SP']

What does the "@" symbol do in SQL?

The @CustID means it's a parameter that you will supply a value for later in your code. This is the best way of protecting against SQL injection. Create your query using parameters, rather than concatenating strings and variables. The database engine puts the parameter value into where the placeholder is, and there is zero chance for SQL injection.

What is the difference between exit(0) and exit(1) in C?

The difference is the value returned to the environment is 0 in the former case and 1 in the latter case:

$ ./prog_with_exit_0
$ echo $?
0
$

and

$ ./prog_with_exit_1
$ echo $?
1
$

Also note that the macros value EXIT_SUCCESS and EXIT_FAILURE used as an argument to exit function are implementation defined but are usually set to respectively 0 and a non-zero number. (POSIX requires EXIT_SUCCESS to be 0). So usually exit(0) means a success and exit(1) a failure.

An exit function call with an argument in main function is equivalent to the statement return with the same argument.

How, in general, does Node.js handle 10,000 concurrent requests?

I understand that Node.js uses a single-thread and an event loop to process requests only processing one at a time (which is non-blocking).

I could be misunderstanding what you've said here, but "one at a time" sounds like you may not be fully understanding the event-based architecture.

In a "conventional" (non event-driven) application architecture, the process spends a lot of time sitting around waiting for something to happen. In an event-based architecture such as Node.js the process doesn't just wait, it can get on with other work.

For example: you get a connection from a client, you accept it, you read the request headers (in the case of http), then you start to act on the request. You might read the request body, you will generally end up sending some data back to the client (this is a deliberate simplification of the procedure, just to demonstrate the point).

At each of these stages, most of the time is spent waiting for some data to arrive from the other end - the actual time spent processing in the main JS thread is usually fairly minimal.

When the state of an I/O object (such as a network connection) changes such that it needs processing (e.g. data is received on a socket, a socket becomes writable, etc) the main Node.js JS thread is woken with a list of items needing to be processed.

It finds the relevant data structure and emits some event on that structure which causes callbacks to be run, which process the incoming data, or write more data to a socket, etc. Once all of the I/O objects in need of processing have been processed, the main Node.js JS thread will wait again until it's told that more data is available (or some other operation has completed or timed out).

The next time that it is woken, it could well be due to a different I/O object needing to be processed - for example a different network connection. Each time, the relevant callbacks are run and then it goes back to sleep waiting for something else to happen.

The important point is that the processing of different requests is interleaved, it doesn't process one request from start to end and then move onto the next.

To my mind, the main advantage of this is that a slow request (e.g. you're trying to send 1MB of response data to a mobile phone device over a 2G data connection, or you're doing a really slow database query) won't block faster ones.

In a conventional multi-threaded web server, you will typically have a thread for each request being handled, and it will process ONLY that request until it's finished. What happens if you have a lot of slow requests? You end up with a lot of your threads hanging around processing these requests, and other requests (which might be very simple requests that could be handled very quickly) get queued behind them.

There are plenty of others event-based systems apart from Node.js, and they tend to have similar advantages and disadvantages compared with the conventional model.

I wouldn't claim that event-based systems are faster in every situation or with every workload - they tend to work well for I/O-bound workloads, not so well for CPU-bound ones.

How to run docker-compose up -d at system start up?

You should be able to add:

restart: always 

to every service you want to restart in the docker-compose.yml file.

See: https://github.com/compose-spec/compose-spec/blob/master/spec.md#restart

Access an arbitrary element in a dictionary in Python

No external libraries, works on both Python 2.7 and 3.x:

>>> list(set({"a":1, "b": 2}.values()))[0]
1

For aribtrary key just leave out .values()

>>> list(set({"a":1, "b": 2}))[0]
'a'

How do I center list items inside a UL element?

write display:inline-block instead of float:left.

li {
        display:inline-block;
        *display:inline; /*IE7*/
        *zoom:1; /*IE7*/
        background:blue;
        color:white;
        margin-right:10px;
}

http://jsfiddle.net/3Ezx2/3/

How to access Anaconda command prompt in Windows 10 (64-bit)

I added "\Anaconda3_64\" and "\Anaconda3_64\Scripts\" to the PATH variable. Then I can use conda from powershell or command prompt.

How to read text file in JavaScript

Yeah it is possible with FileReader, I have already done an example of this, here's the code:

<!DOCTYPE html>
<html>
  <head>
    <title>Read File (via User Input selection)</title>
    <script type="text/javascript">
    var reader; //GLOBAL File Reader object for demo purpose only

    /**
     * Check for the various File API support.
     */
    function checkFileAPI() {
        if (window.File && window.FileReader && window.FileList && window.Blob) {
            reader = new FileReader();
            return true; 
        } else {
            alert('The File APIs are not fully supported by your browser. Fallback required.');
            return false;
        }
    }

    /**
     * read text input
     */
    function readText(filePath) {
        var output = ""; //placeholder for text output
        if(filePath.files && filePath.files[0]) {           
            reader.onload = function (e) {
                output = e.target.result;
                displayContents(output);
            };//end onload()
            reader.readAsText(filePath.files[0]);
        }//end if html5 filelist support
        else if(ActiveXObject && filePath) { //fallback to IE 6-8 support via ActiveX
            try {
                reader = new ActiveXObject("Scripting.FileSystemObject");
                var file = reader.OpenTextFile(filePath, 1); //ActiveX File Object
                output = file.ReadAll(); //text contents of file
                file.Close(); //close file "input stream"
                displayContents(output);
            } catch (e) {
                if (e.number == -2146827859) {
                    alert('Unable to access local files due to browser security settings. ' + 
                     'To overcome this, go to Tools->Internet Options->Security->Custom Level. ' + 
                     'Find the setting for "Initialize and script ActiveX controls not marked as safe" and change it to "Enable" or "Prompt"'); 
                }
            }       
        }
        else { //this is where you could fallback to Java Applet, Flash or similar
            return false;
        }       
        return true;
    }   

    /**
     * display content using a basic HTML replacement
     */
    function displayContents(txt) {
        var el = document.getElementById('main'); 
        el.innerHTML = txt; //display output in DOM
    }   
</script>
</head>
<body onload="checkFileAPI();">
    <div id="container">    
        <input type="file" onchange='readText(this)' />
        <br/>
        <hr/>   
        <h3>Contents of the Text file:</h3>
        <div id="main">
            ...
        </div>
    </div>
</body>
</html>

It's also possible to do the same thing to support some older versions of IE (I think 6-8) using the ActiveX Object, I had some old code which does that too but its been a while so I'll have to dig it up I've found a solution similar to the one I used courtesy of Jacky Cui's blog and edited this answer (also cleaned up code a bit). Hope it helps.

Lastly, I just read some other answers that beat me to the draw, but as they suggest, you might be looking for code that lets you load a text file from the server (or device) where the JavaScript file is sitting. If that's the case then you want AJAX code to load the document dynamically which would be something as follows:

<!DOCTYPE html>
<html>
<head><meta charset="utf-8" />
<title>Read File (via AJAX)</title>
<script type="text/javascript">
var reader = new XMLHttpRequest() || new ActiveXObject('MSXML2.XMLHTTP');

function loadFile() {
    reader.open('get', 'test.txt', true); 
    reader.onreadystatechange = displayContents;
    reader.send(null);
}

function displayContents() {
    if(reader.readyState==4) {
        var el = document.getElementById('main');
        el.innerHTML = reader.responseText;
    }
}

</script>
</head>
<body>
<div id="container">
    <input type="button" value="test.txt"  onclick="loadFile()" />
    <div id="main">
    </div>
</div>
</body>
</html>

How Long Does it Take to Learn Java for a Complete Newbie?

I teach Java Programming at a high school, and our course runs 14 weeks. This is enough time to give students a solid foundation in object oriented programming, but students are not experienced enough to develop and large projects or anything too complicated.

Many schools use the textbook by Lambert & Osbborne:

Lambert, K. & Osborne, M. Fundamentals of Java: AP Computer Science Essentials for the AP Exam. 3rd ed. 2006. Thomson Course Technology.

Find an element in a list of tuples

>>> [i for i in a if 1 in i]

[(1, 2), (1, 4)]

How to calculate an angle from three points?

It gets very simple if you think it as two vectors, one from point P1 to P2 and one from P1 to P3

so:
a = (p1.x - p2.x, p1.y - p2.y)
b = (p1.x - p3.x, p1.y - p3.y)

You can then invert the dot product formula:
dot product
to get the angle:
angle between two vectors

Remember that dot product just means: a1*b1 + a2*b2 (just 2 dimensions here...)

How can I check if a user is logged-in in php?

See this script for registering. It is simple and very easy to understand.

<?php
    define('DB_HOST', 'Your Host[Could be localhost or also a website]');
    define('DB_NAME', 'database name');
    define('DB_USERNAME', 'Username[In many cases root, but some sites offer a MySQL page where the username might be different]');
    define('DB_PASSWORD', 'whatever you keep[if username is root then 99% of the password is blank]');

    $link = mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD);

    if (!$link) {
        die('Could not connect line 9');
    }

    $DB_SELECT = mysql_select_db(DB_NAME, $link);

    if (!$DB_SELECT) {
        die('Could not connect line 15');
    }

    $valueone = $_POST['name'];
    $valuetwo = $_POST['last_name'];
    $valuethree = $_POST['email'];
    $valuefour = $_POST['password'];
    $valuefive = $_POST['age'];

    $sqlone = "INSERT INTO user (name, last_name, email, password, age) VALUES ('$valueone','$valuetwo','$valuethree','$valuefour','$valuefive')";

    if (!mysql_query($sqlone)) {
        die('Could not connect name line 33');
    }

    mysql_close();
?>

Make sure you make all the database stuff using phpMyAdmin. It's a very easy tool to work with. You can find it here: phpMyAdmin

Get a JSON object from a HTTP response

This is not the exact answer for your question, but this may help you

public class JsonParser {

    private static DefaultHttpClient httpClient = ConnectionManager.getClient();

    public static List<Club> getNearestClubs(double lat, double lon) {
        // YOUR URL GOES HERE
        String getUrl = Constants.BASE_URL + String.format("getClosestClubs?lat=%f&lon=%f", lat, lon);

        List<Club> ret = new ArrayList<Club>();

        HttpResponse response = null;
        HttpGet getMethod = new HttpGet(getUrl);
        try {
            response = httpClient.execute(getMethod);

            // CONVERT RESPONSE TO STRING
            String result = EntityUtils.toString(response.getEntity());

            // CONVERT RESPONSE STRING TO JSON ARRAY
            JSONArray ja = new JSONArray(result);

            // ITERATE THROUGH AND RETRIEVE CLUB FIELDS
            int n = ja.length();
            for (int i = 0; i < n; i++) {
                // GET INDIVIDUAL JSON OBJECT FROM JSON ARRAY
                JSONObject jo = ja.getJSONObject(i);

                // RETRIEVE EACH JSON OBJECT'S FIELDS
                long id = jo.getLong("id");
                String name = jo.getString("name");
                String address = jo.getString("address");
                String country = jo.getString("country");
                String zip = jo.getString("zip");
                double clat = jo.getDouble("lat");
                double clon = jo.getDouble("lon");
                String url = jo.getString("url");
                String number = jo.getString("number");

                // CONVERT DATA FIELDS TO CLUB OBJECT
                Club c = new Club(id, name, address, country, zip, clat, clon, url, number);
                ret.add(c);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // RETURN LIST OF CLUBS
        return ret;
    }

}
Again, it’s relatively straight forward, but the methods I’ll make special note of are:

JSONArray ja = new JSONArray(result);
JSONObject jo = ja.getJSONObject(i);
long id = jo.getLong("id");
String name = jo.getString("name");
double clat = jo.getDouble("lat");

How do I correct "Commit Failed. File xxx is out of date. xxx path not found."

I've had the same issue today and I've not done any intermediate merges so from your opening post only #1 might apply - however i have made commits both from an svn client in ubuntu as well as tortoisesvn in windows. Luckily in my case no changes to the trunk were made so I could just replace the trunk with the branch. Possibly different svn versions then? That's quite worrying.

If you use the svn move / copy /delete functions though no history is lost in my case - i svn moved the trunk and then svn moved the branch to trunk.

Cannot use mkdir in home directory: permission denied (Linux Lubuntu)

As @kirbyfan64sos notes in a comment, /home is NOT your home directory (a.k.a. home folder):

The fact that /home is an absolute, literal path that has no user-specific component provides a clue.

While /home happens to be the parent directory of all user-specific home directories on Linux-based systems, you shouldn't even rely on that, given that this differs across platforms: for instance, the equivalent directory on macOS is /Users.

What all Unix platforms DO have in common are the following ways to navigate to / refer to your home directory:

  • Using cd with NO argument changes to your home dir., i.e., makes your home dir. the working directory.
    • e.g.: cd # changes to home dir; e.g., '/home/jdoe'
  • Unquoted ~ by itself / unquoted ~/ at the start of a path string represents your home dir. / a path starting at your home dir.; this is referred to as tilde expansion (see man bash)
    • e.g.: echo ~ # outputs, e.g., '/home/jdoe'
  • $HOME - as part of either unquoted or preferably a double-quoted string - refers to your home dir. HOME is a predefined, user-specific environment variable:
    • e.g.: cd "$HOME/tmp" # changes to your personal folder for temp. files

Thus, to create the desired folder, you could use:

mkdir "$HOME/bin"  # same as: mkdir ~/bin

Note that most locations outside your home dir. require superuser (root user) privileges in order to create files or directories - that's why you ran into the Permission denied error.

Datatables: Cannot read property 'mData' of undefined

I had encountered the same issue but I was generating table Dynamically. In my case, my table had missing <thead> and <tbody> tags.

here is my code snippet if it helped somebody

   //table string
   var strDiv = '<table id="tbl" class="striped center responsive-table">';

   //add headers
   var strTable = ' <thead><tr id="tableHeader"><th>Customer Name</th><th>Customer Designation</th><th>Customer Email</th><th>Customer Organization</th><th>Customer Department</th><th>Customer ContactNo</th><th>Customer Mobile</th><th>Cluster Name</th><th>Product Name</th><th> Installed Version</th><th>Requirements</th><th>Challenges</th><th>Future Expansion</th><th>Comments</th></tr> </thead> <tbody>';


  //add data
  $.each(data, function (key, GetCustomerFeedbackBE) {
                            strTable = strTable + '<tr><td>' + GetCustomerFeedbackBE.StrCustName + '</td><td>' + GetCustomerFeedbackBE.StrCustDesignation + '</td><td>' + GetCustomerFeedbackBE.StrCustEmail + '</td><td>' + GetCustomerFeedbackBE.StrCustOrganization + '</td><td>' + GetCustomerFeedbackBE.StrCustDepartment + '</td><td>' + GetCustomerFeedbackBE.StrCustContactNo + '</td><td>' + GetCustomerFeedbackBE.StrCustMobile + '</td><td>' + GetCustomerFeedbackBE.StrClusterName + '</td><td>' + GetCustomerFeedbackBE.StrProductName + '</td><td>' + GetCustomerFeedbackBE.StrInstalledVersion + '</td><td>' + GetCustomerFeedbackBE.StrRequirements + '</td><td>' + GetCustomerFeedbackBE.StrChallenges + '</td><td>' + GetCustomerFeedbackBE.StrFutureExpansion + '</td><td>' + GetCustomerFeedbackBE.StrComments + '</td></tr>';
                        });

//add end of tbody
 strTable = strTable + '</tbody></table>';

//insert table into a div                 
   $('#divCFB_D').html(strDiv);
   $('#tbl').html(strTable);


    //finally add export buttons 
   $('#tbl').DataTable({
                            dom: 'Bfrtip',
                            buttons: [
                                'copy', 'csv', 'excel', 'pdf', 'print'
                            ]
                        });

Understanding passport serialize deserialize

For anyone using Koa and koa-passport:

Know that the key for the user set in the serializeUser method (often a unique id for that user) will be stored in:

this.session.passport.user

When you set in done(null, user) in deserializeUser where 'user' is some user object from your database:

this.req.user OR this.passport.user

for some reason this.user Koa context never gets set when you call done(null, user) in your deserializeUser method.

So you can write your own middleware after the call to app.use(passport.session()) to put it in this.user like so:

app.use(function * setUserInContext (next) {
  this.user = this.req.user
  yield next
})

If you're unclear on how serializeUser and deserializeUser work, just hit me up on twitter. @yvanscher

How can I use Guzzle to send a POST request in JSON?

This worked for me (using Guzzle 6)

$client = new Client(); 
$result = $client->post('http://api.example.com', [
            'json' => [
                'value_1' => 'number1',
                'Value_group' =>  
                             array("value_2" => "number2",
                                    "value_3" => "number3")
                    ]
                ]);

echo($result->getBody()->getContents());

PHP : send mail in localhost

You will need to install a local mailserver in order to do this. If you want to send it to external e-mail addresses, it might end up in unwanted e-mails or it may not arrive at all.

A good mailserver which I use (I use it on Linux, but it's also available for Windows) is Axigen: http://www.axigen.com/mail-server/download/

You might need some experience with mailservers to install it, but once it works, you can do anything you want with it.

What is the correct XPath for choosing attributes that contain "foo"?

For the code above... //*[contains(@prop,'foo')]

Getting data posted in between two dates

if you want to force using BETWEEN keyword on Codeigniter query helper. You can use where without escape false like this code. Works well on CI version 3.1.5. Hope its help someone.

if(!empty($tglmin) && !empty($tglmax)){
        $this->db->group_start();
        $this->db->where('DATE(create_date) BETWEEN "'.$tglmin.'" AND "'.$tglmax.'"', '',false);
        $this->db->group_end();
    }

Node.js/Express.js App Only Works on Port 3000

The default way to change the listening port on The Express framework is to modify the file named www in the bin folder.

There, you will find a line such as the following

var port = normalizePort(process.env.PORT || '3000');

Change the value 3000 to any port you wish.

This is valid for Express version 4.13.1

Where is my .vimrc file?

I'd like to share how I set showing the line number as the default on Mac.

  1. In a terminal, type cd. This will help you go to the home folder.
  2. In the terminal, type vi .vimrc. This will create an empty vimrc system file which you want to use.
  3. In the file, type set number, and then hit Esc on the keyboard and type in :wq. This will set the line number shown in the default setting file vimrc and save it.
  4. vi something to see if this works. If not, try to restart the terminal completely.

If in a terminal, type in cd /usr/share/vim/, go to that folder, and type in ls. You can directly see a file named vimrc. But it's a system file that says read only. I feel it's not a good idea to try modify it. So following the above steps to create a vimrc by yourself is better. It worked for me.

Get File Path (ends with folder)

Use the Application.FileDialog object

Sub SelectFolder()
    Dim diaFolder As FileDialog
    Dim selected As Boolean

    ' Open the file dialog
    Set diaFolder = Application.FileDialog(msoFileDialogFolderPicker)
    diaFolder.AllowMultiSelect = False
    selected = diaFolder.Show

    If selected Then
        MsgBox diaFolder.SelectedItems(1)
    End If

    Set diaFolder = Nothing
End Sub

SQL how to check that two tables has exactly the same data?

Enhancement to dietbuddha's answer...

select * from
(
    select * from tableA
    minus
    select * from tableB
)
union all
select * from
(
    select * from tableB
    minus
    select * from tableA
)

How can I divide two integers stored in variables in Python?

Multiply by 1.

result = 1. * a / b

or, using the float function

result = float(a) / b

Android Debug Bridge (adb) device - no permissions

...the OP’s own answer is wrong in so far, that there are no “special system permissions”. – The “no permission” problem boils down to ... no permissions.

Unfortunately it is not easy to debug, because adb makes it a secret which device it tries to access! On Linux, it tries to open the “USB serial converter” device of the phone, which is e.g. /dev/bus/usb/001/115 (your bus number and device address will vary). This is sometimes linked and used from /dev/android_adb.

lsusb will help to find bus number and device address. Beware that the device address will change for sure if you re-plug, as might the bus number if the port gets confused about which speed to use (e.g. one physical port ends up on one logical bus or another).

An lsusb-line looks similar to this: Bus 001 Device 115: ID 4321:fedc bla bla bla

lsusb -v might help you to find the device if the “bla bla bla” is not hint enough (sometimes it does neither contain the manufacturer, nor the model of the phone).

Once you know the device, check with your own eyes that ls -a /dev/bus/usb/001/115 is really accessible for the user in question! Then check that it works with chmod and fix your udev setup.

PS1: /dev/android_adb can only point to one device, so make sure it does what you want.

PS2: Unrelated to this question, but less well known: adb has a fixed list of vendor ids it goes through. This list can be extended from ~/.android/adb_usb.ini, which should contain 0x4321 (if we follow my example lsusb line from above). – Not needed here, as you don’t even get a “no permissions” if the vendor id is not known.

How to convert string to Title Case in Python?

just use .title(), and it will convert first letter of every word in capital, rest in small:

>>> a='mohs shahid ss'
>>> a.title()
'Mohs Shahid Ss'
>>> a='TRUE'
>>> b=a.title()
>>> b
'True'
>>> eval(b)
True

Refresh Excel VBA Function Results

If you include ALL references to the spreadsheet data in the UDF parameter list, Excel will recalculate your function whenever the referenced data changes:

Public Function doubleMe(d As Variant)
    doubleMe = d * 2
End Function

You can also use Application.Volatile, but this has the disadvantage of making your UDF always recalculate - even when it does not need to because the referenced data has not changed.

Public Function doubleMe()
    Application.Volatile
    doubleMe = Worksheets("Fred").Range("A1") * 2
End Function

how to get the selected index of a drop down

If you are actually looking for the index number (and not the value) of the selected option then it would be

document.forms[0].elements["CCards"].selectedIndex 
/* You may need to change document.forms[0] to reference the correct form */

or using jQuery

$('select[name="CCards"]')[0].selectedIndex 

How to create an array from a CSV file using PHP and the fgetcsv function

This function will return array with Header values as array keys.

function csv_to_array($file_name) {
        $data =  $header = array();
        $i = 0;
        $file = fopen($file_name, 'r');
        while (($line = fgetcsv($file)) !== FALSE) {
            if( $i==0 ) {
                $header = $line;
            } else {
                $data[] = $line;        
            }
            $i++;
        }
        fclose($file);
        foreach ($data as $key => $_value) {
            $new_item = array();
            foreach ($_value as $key => $value) {
                $new_item[ $header[$key] ] =$value;
            }
            $_data[] = $new_item;
        }
        return $_data;
    }

How to allocate aligned memory only using the standard library?

If there are constraints that, you cannot waste a single byte, then this solution works: Note: There is a case where this may be executed infinitely :D

   void *mem;  
   void *ptr;
try:
   mem =  malloc(1024);  
   if (mem % 16 != 0) {  
       free(mem);  
       goto try;
   }  
   ptr = mem;  
   memset_16aligned(ptr, 0, 1024);

How to get the body's content of an iframe in Javascript?

AFAIK, an Iframe cannot be used that way. You need to point its src attribute to another page.

Here's how to get its body content using plane old javascript. This works with both IE and Firefox.

function getFrameContents(){
   var iFrame =  document.getElementById('id_description_iframe');
   var iFrameBody;
   if ( iFrame.contentDocument ) 
   { // FF
     iFrameBody = iFrame.contentDocument.getElementsByTagName('body')[0];
   }
   else if ( iFrame.contentWindow ) 
   { // IE
     iFrameBody = iFrame.contentWindow.document.getElementsByTagName('body')[0];
   }
    alert(iFrameBody.innerHTML);
 }

useState set method not reflecting change immediately

Additional details to the previous answer:

While React's setState is asynchronous (both classes and hooks), and it's tempting to use that fact to explain the observed behavior, it is not the reason why it happens.

TLDR: The reason is a closure scope around an immutable const value.


Solutions:

  • read the value in render function (not inside nested functions):

      useEffect(() => { setMovies(result) }, [])
      console.log(movies)
    
  • add the variable into dependencies (and use the react-hooks/exhaustive-deps eslint rule):

      useEffect(() => { setMovies(result) }, [])
      useEffect(() => { console.log(movies) }, [movies])
    
  • use a mutable reference (when the above is not possible):

      const moviesRef = useRef(initialValue)
      useEffect(() => {
        moviesRef.current = result
        console.log(moviesRef.current)
      }, [])
    

Explanation why it happens:

If async was the only reason, it would be possible to await setState().

However, both props and state are assumed to be unchanging during 1 render.

Treat this.state as if it were immutable.

With hooks, this assumption is enhanced by using constant values with the const keyword:

const [state, setState] = useState('initial')

The value might be different between 2 renders, but remains a constant inside the render itself and inside any closures (functions that live longer even after render is finished, e.g. useEffect, event handlers, inside any Promise or setTimeout).

Consider following fake, but synchronous, React-like implementation:

_x000D_
_x000D_
// sync implementation:

let internalState
let renderAgain

const setState = (updateFn) => {
  internalState = updateFn(internalState)
  renderAgain()
}

const useState = (defaultState) => {
  if (!internalState) {
    internalState = defaultState
  }
  return [internalState, setState]
}

const render = (component, node) => {
  const {html, handleClick} = component()
  node.innerHTML = html
  renderAgain = () => render(component, node)
  return handleClick
}

// test:

const MyComponent = () => {
  const [x, setX] = useState(1)
  console.log('in render:', x) // ?
  
  const handleClick = () => {
    setX(current => current + 1)
    console.log('in handler/effect/Promise/setTimeout:', x) // ? NOT updated
  }
  
  return {
    html: `<button>${x}</button>`,
    handleClick
  }
}

const triggerClick = render(MyComponent, document.getElementById('root'))
triggerClick()
triggerClick()
triggerClick()
_x000D_
<div id="root"></div>
_x000D_
_x000D_
_x000D_

*.h or *.hpp for your class definitions

I'm answering this as an reminder, to give point to my comment(s) on "user1949346" answer to this same OP.


So as many already answered: either way is fine. Followed by emphasizes of their own impressions.

Introductory, as also in the previous named comments stated, my opinion is C++ header extensions are proposed to be .h if there is actually no reason against it.

Since the ISO/IEC documents use this notation of header files and no string matching to .hpp even occurs in their language documentations about C++.

But I'm now aiming for an approvable reason WHY either way is ok, and especially why it's not subject of the language it self.

So here we go.

The C++ documentation (I'm actually taking reference from the version N3690) defines that a header has to conform to the following syntax:

2.9 Header names

header-name:
    < h-char-sequence >
    " q-char-sequence "
h-char-sequence:
    h-char
    h-char-sequence h-char
h-char:
    any member of the source character set except new-line and >
q-char-sequence:
    q-char
    q-char-sequence q-char
q-char:
    any member of the source character set except new-line and "

So as we can extract from this part, the header file name may be anything that is valid in the source code, too. Except containing '\n' characters and depending on if it is to be included by <> it is not allowed to contain a >. Or the other way if it is included by ""-include it is not allowed to contain a ".

In other words: if you had a environment supporting filenames like prettyStupidIdea.>, an include like:

#include "prettyStupidIdea.>"

would be valid, but:

#include <prettyStupidIdea.>>

would be invalid. The other way around the same.

And even

#include <<.<>

would be a valid includable header file name.

Even this would conform to C++, it would be a pretty pretty stupid idea, tho.

And that's why .hpp is valid, too.

But it's not an outcome of the committees designing decisions for the language!

So discussing about to use .hpp is same as doing it about .cc, .mm or what ever else I read in other posts on this topic.

I have to admit I have no clue where .hpp came from1, but I would bet an inventor of some parsing tool, IDE or something else concerned with C++ came to this idea to optimize some internal processes or just to invent some (probably even for them necessarily) new naming conventions.

But it is not part of the language.

And whenever one decides to use it this way. May it be because he likes it most or because some applications of the workflow require it, it never2 is a requirement of the language. So whoever says "the pp is because it is used with C++", simply is wrong in regards of the languages definition.

C++ allows anything respecting the previous paragraph. And if there is anything the committee proposed to use, then it is using .h since this is the extension sued in all examples of the ISO document.

Conclusion:

As long you don't see/feel any need of using .h over .hpp or vise versa, you shouldn't bother. Because both would be form a valid header name of same quality in respect to the standard. And therefore anything that REQUIRES you to use .h or .hpp is an additional restriction of the standard which could even be contradicting with other additional restrictions not conform with each other. But as OP doesn't mention any additional language restriction, this is the only correct and approvable answer to the question

"*.h or *.hpp for your class definitions" is:

Both are equally correct and applicable as long as no external restrictions are present.


1From what I know, apparently, it is the boost framework that came up with that .hpp extension.

2Of course I can't say what some future versions will bring with it!

Compress images on client side before uploading

If you are looking for a library to carry out client-side image compression, you can check this out:compress.js. This will basically help you compress multiple images purely with JavaScript and convert them to base64 string. You can optionally set the maximum size in MB and also the preferred image quality.

Slick.js: Get current and total slides (ie. 3/5)

This might help:

  • You don't need to enable dots or customPaging.
  • Position .slick-counter with CSS.

CSS

.slick-counter{
  position:absolute;
  top:5px;
  left:5px;
  background:yellow;
  padding:5px;
  opacity:0.8;
  border-radius:5px;
}

JavaScript

var $el = $('.slideshow');

$el.slick({
  slide: 'img',
  autoplay: true,
  onInit: function(e){
    $el.append('<div class="slick-counter">'+ parseInt(e.currentSlide + 1, 10) +' / '+ e.slideCount +'</div>');
  },
  onAfterChange: function(e){
    $el.find('.slick-counter').html(e.currentSlide + 1 +' / '+e.slideCount);
  }
});

http://jsfiddle.net/cpdqhdwy/6/

Cross browser JavaScript (not jQuery...) scroll to top animation

PURE JAVASCRIPT SCROLLER CLASS

This is an old question but I thought I could answer with some fancy stuff and some more options to play with if you want to have a bit more control over the animation.

  • Cross-browser
  • Copy/Paste ready solution (You only need CSS and JS)
  • 3 animate modes: ["normal"|"linear"|false]
  • Customize your animation with available settings - make it snappy or fluent
  • Double click to skip animation
  • Every next single click adds initial speed
  • Stop scroll animation by draging down the scroll bar
  • Stop scroll animation by mouse wheel down
  • Animated button fade-in-out on scroll
  • Here it is a pure JS Class to take care of the scrolling for you:

    SEE DEMO AT CODEPEN OR GO TO THE BOTTOM AND RUN THE SINPET

    // ------------------- USE EXAMPLE ---------------------
    // *Set options
    var options = {
      'showButtonAfter': 200, // show button after scroling down this amount of px
      'animate': "linear", // [false|normal|linear] - for false no aditional settings are needed
    
      'normal': { // applys only if [animate: normal] - set scroll loop distanceLeft/steps|ms
        'steps': 20, // the more steps per loop the slower animation gets
        'ms': 10 // the less ms the quicker your animation gets
      }, 
      'linear': { // applys only if [animate: linear] - set scroll px|ms
        'px': 30, // the more px the quicker your animation gets
        'ms': 10 // the less ms the quicker your animation gets
      }, 
    };
    
    
    // *Create new Scroller and run it.
    var scroll = new Scroller(options);
    scroll.init();
    

    FULL CLASS SCRIPT + USE EXAMPLE:

    _x000D_
    _x000D_
    // PURE JAVASCRIPT (OOP)_x000D_
    _x000D_
    function Scroller(options) {_x000D_
      this.options = options;_x000D_
      this.button = null;_x000D_
      this.stop = false;_x000D_
    }_x000D_
    _x000D_
    Scroller.prototype.constructor = Scroller;_x000D_
    _x000D_
    Scroller.prototype.createButton = function() {_x000D_
    _x000D_
      this.button = document.createElement('button');_x000D_
      this.button.classList.add('scroll-button');_x000D_
      this.button.classList.add('scroll-button--hidden');_x000D_
      this.button.textContent = "^";_x000D_
      document.body.appendChild(this.button);_x000D_
    }_x000D_
    _x000D_
    Scroller.prototype.init = function() {_x000D_
      this.createButton();_x000D_
      this.checkPosition();_x000D_
      this.click();_x000D_
      this.stopListener();_x000D_
    }_x000D_
    _x000D_
    Scroller.prototype.scroll = function() {_x000D_
      if (this.options.animate == false || this.options.animate == "false") {_x000D_
        this.scrollNoAnimate();_x000D_
        return;_x000D_
      }_x000D_
      if (this.options.animate == "normal") {_x000D_
        this.scrollAnimate();_x000D_
        return;_x000D_
      }_x000D_
      if (this.options.animate == "linear") {_x000D_
        this.scrollAnimateLinear();_x000D_
        return;_x000D_
      }_x000D_
    }_x000D_
    Scroller.prototype.scrollNoAnimate = function() {_x000D_
      document.body.scrollTop = 0;_x000D_
      document.documentElement.scrollTop = 0;_x000D_
    }_x000D_
    Scroller.prototype.scrollAnimate = function() {_x000D_
      if (this.scrollTop() > 0 && this.stop == false) {_x000D_
        setTimeout(function() {_x000D_
          this.scrollAnimate();_x000D_
          window.scrollBy(0, (-Math.abs(this.scrollTop()) / this.options.normal['steps']));_x000D_
        }.bind(this), (this.options.normal['ms']));_x000D_
      }_x000D_
    }_x000D_
    Scroller.prototype.scrollAnimateLinear = function() {_x000D_
      if (this.scrollTop() > 0 && this.stop == false) {_x000D_
        setTimeout(function() {_x000D_
          this.scrollAnimateLinear();_x000D_
          window.scrollBy(0, -Math.abs(this.options.linear['px']));_x000D_
        }.bind(this), this.options.linear['ms']);_x000D_
      }_x000D_
    }_x000D_
    _x000D_
    Scroller.prototype.click = function() {_x000D_
    _x000D_
      this.button.addEventListener("click", function(e) {_x000D_
        e.stopPropagation();_x000D_
        this.scroll();_x000D_
      }.bind(this), false);_x000D_
    _x000D_
      this.button.addEventListener("dblclick", function(e) {_x000D_
        e.stopPropagation();_x000D_
        this.scrollNoAnimate();_x000D_
      }.bind(this), false);_x000D_
    _x000D_
    }_x000D_
    _x000D_
    Scroller.prototype.hide = function() {_x000D_
      this.button.classList.add("scroll-button--hidden");_x000D_
    }_x000D_
    _x000D_
    Scroller.prototype.show = function() {_x000D_
      this.button.classList.remove("scroll-button--hidden");_x000D_
    }_x000D_
    _x000D_
    Scroller.prototype.checkPosition = function() {_x000D_
      window.addEventListener("scroll", function(e) {_x000D_
        if (this.scrollTop() > this.options.showButtonAfter) {_x000D_
          this.show();_x000D_
        } else {_x000D_
          this.hide();_x000D_
        }_x000D_
      }.bind(this), false);_x000D_
    }_x000D_
    _x000D_
    Scroller.prototype.stopListener = function() {_x000D_
    _x000D_
      // stop animation on slider drag_x000D_
      var position = this.scrollTop();_x000D_
      window.addEventListener("scroll", function(e) {_x000D_
        if (this.scrollTop() > position) {_x000D_
          this.stopTimeout(200);_x000D_
        } else {_x000D_
          //..._x000D_
        }_x000D_
        position = this.scrollTop();_x000D_
      }.bind(this, position), false);_x000D_
    _x000D_
      // stop animation on wheel scroll down_x000D_
      window.addEventListener("wheel", function(e) {_x000D_
        if (e.deltaY > 0) this.stopTimeout(200);_x000D_
      }.bind(this), false);_x000D_
    }_x000D_
    _x000D_
    Scroller.prototype.stopTimeout = function(ms) {_x000D_
      this.stop = true;_x000D_
      // console.log(this.stop); //_x000D_
      setTimeout(function() {_x000D_
        this.stop = false;_x000D_
        console.log(this.stop); //_x000D_
      }.bind(this), ms);_x000D_
    }_x000D_
    _x000D_
    Scroller.prototype.scrollTop = function() {_x000D_
      var curentScrollTop = document.documentElement.scrollTop || document.body.scrollTop;_x000D_
      return curentScrollTop;_x000D_
    }_x000D_
    _x000D_
    _x000D_
    _x000D_
    // ------------------- USE EXAMPLE ---------------------_x000D_
    // *Set options_x000D_
    var options = {_x000D_
      'showButtonAfter': 200, // show button after scroling down this amount of px_x000D_
      'animate': "normal", // [false|normal|linear] - for false no aditional settings are needed_x000D_
    _x000D_
      'normal': { // applys only if [animate: normal] - set scroll loop distanceLeft/steps|ms_x000D_
        'steps': 20, // the more steps per loop the slower animation gets_x000D_
        'ms': 10 // the less ms the quicker your animation gets_x000D_
      },_x000D_
      'linear': { // applys only if [animate: linear] - set scroll px|ms_x000D_
        'px': 30, // the more px the quicker your animation gets_x000D_
        'ms': 10 // the less ms the quicker your animation gets_x000D_
      },_x000D_
    };_x000D_
    // *Create new Scroller and run it._x000D_
    var scroll = new Scroller(options);_x000D_
    scroll.init();
    _x000D_
    /* CSS */_x000D_
    _x000D_
    @import url(https://fonts.googleapis.com/css?family=Open+Sans);_x000D_
     body {_x000D_
      font-family: 'Open Sans', sans-serif;_x000D_
      font-size: 1.2rem;_x000D_
      line-height: 2rem;_x000D_
      height: 100%;_x000D_
      position: relative;_x000D_
      padding: 0 25%;_x000D_
    }_x000D_
    .scroll-button {_x000D_
      font-size: 1.2rem;_x000D_
      line-height: 2rem;_x000D_
      padding: 10px;_x000D_
      width: 50px;_x000D_
      height: 50px;_x000D_
      background: black;_x000D_
      color: white;_x000D_
      border-radius: 50%;_x000D_
      position: fixed;_x000D_
      right: 20px;_x000D_
      bottom: 20px;_x000D_
      visibility: visible;_x000D_
      filter: alpha(opacity=50);_x000D_
      filter: progid: DXImageTransform.Microsoft.Alpha(Opacity=50);_x000D_
      opacity: 0.5;_x000D_
      cursor: pointer;_x000D_
      transition: all 1.2s;_x000D_
      -webkit-transition: all 1.2s;_x000D_
      -moz-transition: all 1.2s;_x000D_
      -ms-transition: all 1.2s;_x000D_
      -o-transition: all 1.2s;_x000D_
    }_x000D_
    .scroll-button:hover {_x000D_
      filter: alpha(opacity=100);_x000D_
      filter: progid: DXImageTransform.Microsoft.Alpha(Opacity=100);_x000D_
      opacity: 1;_x000D_
    }_x000D_
    .scroll-button--hidden {_x000D_
      filter: alpha(opacity=0);_x000D_
      filter: progid: DXImageTransform.Microsoft.Alpha(Opacity=0);_x000D_
      opacity: 0;_x000D_
      visibility: hidden;_x000D_
    }
    _x000D_
    <!-- HTML -->_x000D_
    _x000D_
    <h1>Scroll down by 200px for button to appear</h1>_x000D_
    <ul>_x000D_
      <li>Cross-browser</li>_x000D_
      <li>Copy/Paste solution</li>_x000D_
      <li>3 animate modes: <b>["normal"|"linear"|false]</b></li>_x000D_
      <li>Customize your aniamtion with aveilable settings - make it snapy or fluent</li>_x000D_
      <li>Double click to skip animation</li>_x000D_
      <li>Every next single click adds initial speed</li>_x000D_
      <li>Stop scroll animation by draging down the scroll bar</li>_x000D_
      <li>Stop scroll animation by mouse wheel down</li>_x000D_
      <li>Animated button fade-in-out on scroll</li>_x000D_
    </ul>_x000D_
    _x000D_
    <br />_x000D_
    <br />_x000D_
    <pre>_x000D_
    // ------------------- USE EXAMPLE ---------------------_x000D_
    // *Set options_x000D_
    var options = {_x000D_
      'showButtonAfter': 200, // show button after scroling down this amount of px_x000D_
      'animate': "normal", // [false|normal|linear] - for false no aditional settings are needed_x000D_
      _x000D_
      'normal': { // applys only if [animate: normal] - set scroll loop distanceLeft/steps|ms_x000D_
        'steps': 20, // the more steps the slower animation gets_x000D_
        'ms': 20 // the less ms the quicker your animation gets_x000D_
      }, _x000D_
      'linear': { // applys only if [animate: linear] - set scroll px|ms_x000D_
        'px': 55, // the more px the quicker your animation gets_x000D_
        'ms': 10 // the less ms the quicker your animation gets_x000D_
      }, _x000D_
    };_x000D_
    _x000D_
    // *Create new Scroller and run it._x000D_
    var scroll = new Scroller(options);_x000D_
    scroll.init();_x000D_
    </pre>_x000D_
    <br />_x000D_
    <br />_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quae molestiae illo nobis quo autem molestias voluptatum quam, amet ipsum debitis, iure animi illum soluta eaque qui perspiciatis harum, sequi nesciunt.</span><span>Quisquam nesciunt aspernatur a possimus pariatur enim architecto. Hic aperiam sit repellat doloremque vel est soluta et assumenda dolore, sint sapiente porro, quam impedit. Sint praesentium quas excepturi, voluptatem dicta!</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptate, porro nisi molestias minima corrupti tempore, dolorum fugiat ipsam dicta doloremque accusamus atque consequatur iusto natus, mollitia distinctio odit dolor tempora.</span><span>Perferendis a in laudantium accusantium, dolorum eius placeat velit porro similique, eum cumque veniam neque aspernatur architecto suscipit rem laboriosam voluptates laborum? Voluptates tempora necessitatibus animi nostrum quod, maxime odio.</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nihil accusantium, itaque corporis repellat pariatur soluta officia perspiciatis in reprehenderit facere, incidunt saepe excepturi. Inventore atque ex illo, ipsam at deserunt.</span><span>Laborum inventore officia, perspiciatis cumque magni consequatur iste accusantium soluta, nesciunt blanditiis voluptatibus adipisci laudantium mollitia minus quia necessitatibus voluptates. Minima unde quos impedit necessitatibus aspernatur minus maiores ipsa eligendi!</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptate nesciunt, explicabo similique, quo maxime modi, aliquid, voluptatibus repellendus dolorum placeat mollitia ea dicta quia laboriosam alias dignissimos ipsam tenetur. Nulla.</span><span>Vel maiores necessitatibus odio voluptate debitis, error in accusamus nulla, eum, nemo et ea commodi. Autem numquam at, consequatur temporibus. Mollitia placeat nobis blanditiis impedit distinctio! Ad, incidunt fugiat sed.</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsam voluptatum, odio quam omnis iste laudantium, itaque architecto, eos ullam debitis delectus sapiente nemo autem reprehenderit. Dolorem quidem facere ipsam! Nisi.</span><span>Vitae quaerat modi voluptatibus ratione numquam? Sapiente aliquid officia pariatur quibusdam aliquam id expedita non recusandae, cumque deserunt asperiores. Corrupti et doloribus aspernatur ipsum asperiores, ipsa unde corporis commodi reiciendis?</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima adipisci minus iste, nesciunt itaque quisquam quidem voluptatum assumenda rerum aliquid, excepturi voluptatem tempora. Possimus ratione alias a error vel, rem.</span><span>Officia esse error accusantium veritatis ad, et sit animi? Recusandae mollitia odit tenetur ad cumque maiores eligendi blanditiis nobis hic tempora obcaecati consequatur commodi totam, debitis, veniam, ducimus molestias ut.</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Obcaecati quibusdam, tempora cupiditate quaerat tempore ullam delectus voluptates optio eum placeat provident consequatur iure reprehenderit vero quae sapiente architecto earum nemo.</span><span>Quis molestias sint fuga doloribus, necessitatibus nulla. Esse ipsa, itaque asperiores. Tempora a sequi nobis cumque incidunt aspernatur, pariatur rem voluptatibus. Atque veniam magnam, ea laudantium ipsum reprehenderit sapiente repellendus.</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima, pariatur at explicabo aliquid repudiandae vero eum quasi totam voluptates iusto unde ad repellendus ipsam et voluptatem hic adipisci! Vero, nobis!</span><span>Consequatur eligendi quo quas omnis architecto dolorum aperiam doloremque labore, explicabo enim incidunt vitae saepe, quod soluta illo odit provident amet beatae quasi animi. Similique nostrum molestiae animi corrupti qui?</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestias quis, tempora laborum incidunt qui fuga adipisci doloremque iusto commodi vitae est, nemo iure placeat ut sit optio, consequuntur voluptas impedit.</span><span>Eos officiis, hic esse unde eaque, aut tenetur voluptate quam sint vel exercitationem totam dolor odio soluta illo praesentium non corrupti! Consequuntur velit, mollitia excepturi. Minus, veniam accusantium! Aliquam, ea!</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reprehenderit quis reiciendis veritatis expedita velit vitae amet magni sunt rerum in blanditiis aut tempore quia fugiat, voluptates officia quaerat quam id.</span><span>Sapiente tempore repudiandae, quae doloremque ullam odio quia ea! Impedit atque, ipsa consequatur quis obcaecati voluptas necessitatibus, cupiditate sunt amet ab modi illum inventore, a dolor enim similique architecto est!</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque non aliquam, sit illo quas deserunt esse nobis reprehenderit quidem fuga beatae eligendi reiciendis omnis qui repellat velit earum blanditiis possimus.</span><span>Provident aspernatur ducimus, illum beatae debitis vitae non dolorum rem officia nostrum natus accusantium perspiciatis ad soluta maiores praesentium eveniet qui hic quis at quaerat ea perferendis. Ut, aut, natus.</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ratione corrupti quibusdam, sed hic veniam. Perspiciatis ex, quod architecto natus autem totam at commodi excepturi maxime pariatur corporis, veritatis vero, praesentium.</span><span>Nesciunt suscipit, nobis eos perferendis ex quaerat inventore nihil qui magnam saepe rerum velit reiciendis ipsam deleniti ducimus eligendi odio eius minima vero, nisi voluptates amet eaque, iste, labore laudantium.</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illo, voluptas accusantium ad omnis velit distinctio! Adipisci magnam nihil nostrum molestiae rem dolores, ut ad nemo, dolor quos itaque maiores quaerat!</span><span>Quia ad suscipit reprehenderit vitae inventore eius non culpa maiores omnis sit obcaecati vel placeat quibusdam, ipsa exercitationem nam odit, magni nobis. Quam quas, accusamus expedita molestiae asperiores eaque ex?</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Rerum explicabo doloribus nihil iusto quasi vel expedita dignissimos amet mollitia, temporibus aut atque architecto assumenda dolorum nam velit deserunt totam numquam.</span><span>Ab perferendis labore, quae. Quidem architecto quo officia deserunt ea doloribus libero molestias id nisi perferendis eum porro, quibusdam! Odit aliquid placeat rem aut officia minus sit esse eos obcaecati!</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eligendi nostrum repellendus placeat, unde aperiam. Fuga, voluptas, minima. Debitis nemo ducimus itaque laboriosam error quaerat reprehenderit quo animi incidunt. Nulla, quis!</span><span>Explicabo assumenda dicta ratione? Tempora commodi asperiores, explicabo doloremque eius quia impedit possimus architecto sit nemo odio eum fuga minima dolor iste mollitia sequi dolorem perspiciatis unde quisquam laborum soluta.</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Veniam officia corporis, reiciendis laudantium, voluptate voluptates necessitatibus assumenda, delectus quisquam velit deserunt! Reprehenderit, vel quaerat accusantium nesciunt libero animi. Sequi, eveniet?</span><span>Animi natus pariatur porro, alias, veniam aut est tempora adipisci molestias harum modi cumque assumenda enim! Expedita eveniet autem illum rerum nostrum ipsum alias neque aut, dolorum impedit pariatur non?</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quis aliquid rerum, odio veniam ipsam ad officia quos repellat ex aperiam voluptatum optio est animi possimus minus. Sapiente voluptates amet dolorem.</span><span>Illo necessitatibus similique asperiores inventore ut cumque nihil assumenda debitis explicabo rerum, dolorum molestiae culpa accusantium. Nisi doloremque optio provident blanditiis, eum ipsam asperiores, consequatur aliquam vel sit mollitia sunt.</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Enim, totam harum perferendis. Minus ea perferendis laboriosam, iste, qui corrupti, quas veritatis omnis officiis animi fuga perspiciatis impedit! Error, harum, voluptas.</span><span>Omnis laborum, cum mollitia facilis ipsa unde distinctio maxime nesciunt illum perspiciatis ut officiis, eligendi numquam dolorem quod modi ipsam est rerum perferendis repellendus totam. Maxime excepturi culpa alias labore.</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Impedit deleniti, odit sit consequatur dolorum omnis repellendus, alias vel ullam numquam. Nostrum obcaecati hic, possimus delectus nam atque aliquid explicabo cum.</span><span>Explicabo tenetur minima consequatur, aliquam, laudantium non consequuntur facilis sint, suscipit debitis ex atque mollitia magni quod repellat ratione dolorum excepturi molestiae cumque iusto eos unde? Voluptatum dolores, porro provident!</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. At laboriosam fuga aperiam eveniet, obcaecati esse, nulla porro iure molestiae praesentium sint fugiat ea voluptate suscipit voluptates mollitia, voluptatibus. Autem, non.</span><span>Numquam velit culpa tempora ratione ipsum minus modi in? Nisi reiciendis, voluptate voluptatem maxime repellat quae odio, repellendus aliquid laborum dolorem. Labore, fuga ea minima explicabo quae voluptatum necessitatibus, similique.</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quasi, rerum dolorum nemo error fugiat ut, modi, architecto libero maxime laborum repellendus doloribus neque aperiam adipisci quaerat obcaecati deserunt consequuntur amet!</span><span>Sint, assumenda nisi obcaecati doloremque iste. Perspiciatis accusantium, distinctio impedit cum esse recusandae sunt. Officiis culpa dolore eius, doloribus natus, dolorum excepturi vitae fugiat ullam provident harum! Suscipit, assumenda, harum.</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odit, nihil tenetur tempore eligendi qui nesciunt consequatur delectus accusantium consectetur ipsa, nulla doloribus dolores rerum corporis, laborum, laboriosam hic mollitia repellat.</span><span>Ab deleniti vitae blanditiis quod tenetur! Voluptatem temporibus ab eaque quis? Quis odio aliquid harum temporibus totam, ipsa eius iusto fugiat enim in, quibusdam molestiae aliquam consequatur nulla, consequuntur sint.</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illum odit praesentium quos, earum nesciunt laudantium illo tempora eligendi, porro doloremque mollitia neque aperiam inventore nam maxime dolor labore aspernatur molestias.</span><span>Voluptatibus provident hic cupiditate placeat, ut reprehenderit nisi eum, dolores ad sed quis. Doloribus molestiae, quae rem odit expedita soluta, facilis animi corporis velit ut in, recusandae harum laboriosam veritatis.</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Incidunt repudiandae molestias magnam delectus veritatis labore, corporis dicta officia quos, ad corrupti odit! Ad hic officia maxime eveniet consectetur similique adipisci!</span><span>Quia at, nesciunt aliquid delectus ex alias voluptas maxime hic esse. Incidunt, laborum quos mollitia dolores et! Voluptas commodi asperiores, fugit quidem quis corporis, a eaque, animi, autem deserunt repellendus.</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sequi quas, voluptas hic minima inventore optio, id quidem placeat necessitatibus omnis voluptatibus vitae mollitia tempora consequuntur consequatur, illo facilis accusamus illum.</span><span>Voluptates consequuntur ipsam odit. Eius quis ipsam vitae, nihil molestias perferendis corporis recusandae consequatur vero iure blanditiis quas adipisci quos voluptatem rem illo voluptate. Eveniet officiis iure sit laborum veniam.</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Suscipit a quis cumque nostrum quisquam molestiae pariatur, asperiores natus necessitatibus adipisci illum cupiditate nam vero, tempora excepturi laborum, earum. Voluptates, nobis.</span><span>Pariatur suscipit, hic blanditiis libero, iusto, quam cupiditate nam error id asperiores repellat ab consequatur vitae ipsa voluptatem totam magni reiciendis expedita maxime dolor! Minus explicabo quas, laborum ab omnis!</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Labore qui ad assumenda placeat optio illo molestias corporis dolorum cum. Doloribus eius autem obcaecati minima, asperiores iure dignissimos ducimus suscipit dolorem.</span><span>Blanditiis earum accusamus eaque temporibus necessitatibus voluptatum dolorem enim debitis inventore assumenda quae error perspiciatis aut, nulla delectus quam ipsa sapiente ea aliquam laboriosam repudiandae. Nesciunt praesentium, beatae eos quasi!</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Cupiditate dicta voluptate impedit? Ad voluptatum dicta earum perferendis asperiores. Dolore distinctio modi expedita consequatur provident perspiciatis neque totam rerum placeat quas.</span><span>Eveniet optio est possimus iste accusantium ipsum illum. Maiores saepe repudiandae facere, delectus iure dolorem vitae nihil pariatur minima, reprehenderit eligendi dolore impedit, nisi doloribus quidem similique. Optio, delectus, minus.</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iste ex molestiae architecto enim nihil tempore, atque consequuntur doloribus recusandae sed consequatur veniam quos, in consectetur perspiciatis magni nostrum ab voluptates.</span><span>Nisi quos mollitia quis in maiores asperiores labore deserunt! Voluptate voluptas adipisci qui hic officia molestias, laborum necessitatibus sint nam vel minus incidunt perspiciatis recusandae sunt, rerum suscipit doloremque possimus!</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. At nihil perferendis quae quidem facilis aliquid pariatur possimus hic asperiores, recusandae exercitationem adipisci atque laborum, delectus, odit ab reprehenderit distinctio dolor.</span><span>Non excepturi quos aspernatur repudiandae laboriosam, unde molestias, totam, sapiente harum accusamus delectus laborum ipsam velit amet nisi! Consectetur aliquam provident voluptatibus saepe repudiandae eveniet laborum beatae, animi, voluptate dolores.</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Cumque magni, eum ipsa, veritatis facere voluptatem dolorum nobis neque minus debitis asperiores iste. Pariatur sequi quam, tempora. Dignissimos, esse similique tempora.</span><span>Ex delectus excepturi autem sunt, nemo repudiandae, recusandae nostrum accusantium nobis temporibus magnam eligendi similique veritatis deleniti, eaque blanditiis possimus at! Repellat alias laboriosam ipsum commodi dolorem, corporis dolore suscipit!</span></p>
    _x000D_
    _x000D_
    _x000D_

    Regex for Mobile Number Validation

    Try this regex:

    ^(\+?\d{1,4}[\s-])?(?!0+\s+,?$)\d{10}\s*,?$
    

    Explanation of the regex using Perl's YAPE is as below:

    NODE                     EXPLANATION
    ----------------------------------------------------------------------
    (?-imsx:                 group, but do not capture (case-sensitive)
                             (with ^ and $ matching normally) (with . not
                             matching \n) (matching whitespace and #
                             normally):
    ----------------------------------------------------------------------
      ^                        the beginning of the string
    ----------------------------------------------------------------------
      (                        group and capture to \1 (optional
                               (matching the most amount possible)):
    ----------------------------------------------------------------------
        \+?                      '+' (optional (matching the most amount
                                 possible))
    ----------------------------------------------------------------------
        \d{1,4}                  digits (0-9) (between 1 and 4 times
                                 (matching the most amount possible))
    ----------------------------------------------------------------------
        [\s-]                    any character of: whitespace (\n, \r,
                                 \t, \f, and " "), '-'
    ----------------------------------------------------------------------
      )?                       end of \1 (NOTE: because you are using a
                               quantifier on this capture, only the LAST
                               repetition of the captured pattern will be
                               stored in \1)
    ----------------------------------------------------------------------
      (?!                      look ahead to see if there is not:
    ----------------------------------------------------------------------
        0+                       '0' (1 or more times (matching the most
                                 amount possible))
    ----------------------------------------------------------------------
        \s+                      whitespace (\n, \r, \t, \f, and " ") (1
                                 or more times (matching the most amount
                                 possible))
    ----------------------------------------------------------------------
        ,?                       ',' (optional (matching the most amount
                                 possible))
    ----------------------------------------------------------------------
        $                        before an optional \n, and the end of
                                 the string
    ----------------------------------------------------------------------
      )                        end of look-ahead
    ----------------------------------------------------------------------
      \d{10}                   digits (0-9) (10 times)
    ----------------------------------------------------------------------
      \s*                      whitespace (\n, \r, \t, \f, and " ") (0 or
                               more times (matching the most amount
                               possible))
    ----------------------------------------------------------------------
      ,?                       ',' (optional (matching the most amount
                               possible))
    ----------------------------------------------------------------------
      $                        before an optional \n, and the end of the
                               string
    ----------------------------------------------------------------------
    )                        end of grouping
    ----------------------------------------------------------------------
    

    How to trigger the window resize event in JavaScript?

    With jQuery, you can try to call trigger:

    $(window).trigger('resize');
    

    Proper way of checking if row exists in table in PL/SQL block

    I wouldn't push regular code into an exception block. Just check whether any rows exist that meet your condition, and proceed from there:

    declare
      any_rows_found number;
    begin
      select count(*)
      into   any_rows_found
      from   my_table
      where  rownum = 1 and
             ... other conditions ...
    
      if any_rows_found = 1 then
        ...
      else
        ...
      end if;
    

    Sleep function in Windows, using C

    Use:

    #include <windows.h>
    
    Sleep(sometime_in_millisecs); // Note uppercase S
    

    And here's a small example that compiles with MinGW and does what it says on the tin:

    #include <windows.h>
    #include <stdio.h>
    
    int main() {
        printf( "starting to sleep...\n" );
        Sleep(3000); // Sleep three seconds
        printf("sleep ended\n");
    }
    

    Equivalent of waitForVisible/waitForElementPresent in Selenium WebDriver tests using Java?

    Another way to wait for maximum of certain amount say 10 seconds of time for the element to be displayed as below:

    (new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
                public Boolean apply(WebDriver d) {
                    return d.findElement(By.id("<name>")).isDisplayed();
    
                }
            });
    

    Visual Studio Code Automatic Imports

    Fill the include property in the first level of the JSON-object in the tsconfig.editor.json like here:

    "include": [
      "src/**/*.ts"
    ]
    

    It works for me well.

    Also you can add another Typescript file extensions if it's needed, like here:

    "include": [
      "src/**/*.ts",
      "src/**/*.spec.ts",
      "src/**/*.d.ts"
    ]
    

    Double free or corruption after queue::push

    Let's talk about copying objects in C++.

    Test t;, calls the default constructor, which allocates a new array of integers. This is fine, and your expected behavior.

    Trouble comes when you push t into your queue using q.push(t). If you're familiar with Java, C#, or almost any other object-oriented language, you might expect the object you created earler to be added to the queue, but C++ doesn't work that way.

    When we take a look at std::queue::push method, we see that the element that gets added to the queue is "initialized to a copy of x." It's actually a brand new object that uses the copy constructor to duplicate every member of your original Test object to make a new Test.

    Your C++ compiler generates a copy constructor for you by default! That's pretty handy, but causes problems with pointer members. In your example, remember that int *myArray is just a memory address; when the value of myArray is copied from the old object to the new one, you'll now have two objects pointing to the same array in memory. This isn't intrinsically bad, but the destructor will then try to delete the same array twice, hence the "double free or corruption" runtime error.

    How do I fix it?

    The first step is to implement a copy constructor, which can safely copy the data from one object to another. For simplicity, it could look something like this:

    Test(const Test& other){
        myArray = new int[10];
        memcpy( myArray, other.myArray, 10 );
    }
    

    Now when you're copying Test objects, a new array will be allocated for the new object, and the values of the array will be copied as well.

    We're not completely out trouble yet, though. There's another method that the compiler generates for you that could lead to similar problems - assignment. The difference is that with assignment, we already have an existing object whose memory needs to be managed appropriately. Here's a basic assignment operator implementation:

    Test& operator= (const Test& other){
        if (this != &other) {
            memcpy( myArray, other.myArray, 10 );
        }
        return *this;
    }
    

    The important part here is that we're copying the data from the other array into this object's array, keeping each object's memory separate. We also have a check for self-assignment; otherwise, we'd be copying from ourselves to ourselves, which may throw an error (not sure what it's supposed to do). If we were deleting and allocating more memory, the self-assignment check prevents us from deleting memory from which we need to copy.

    Will Google Android ever support .NET?

    .NET compact framework has been ported to Symbian OS (http://www.redfivelabs.com/). If .NET as a 'closed' platform can be ported to this platform, I can't see any reason why it cannot be done for Android.

    How to print matched regex pattern using awk?

    If Perl is an option, you can try this:

    perl -lne 'print $1 if /(regex)/' file
    

    To implement case-insensitive matching, add the i modifier

    perl -lne 'print $1 if /(regex)/i' file
    

    To print everything AFTER the match:

    perl -lne 'if ($found){print} else{if (/regex(.*)/){print $1; $found++}}' textfile
    

    To print the match and everything after the match:

    perl -lne 'if ($found){print} else{if (/(regex.*)/){print $1; $found++}}' textfile
    

    What are the differences between type() and isinstance()?

    For the real differences, we can find it in code, but I can't find the implement of the default behavior of the isinstance().

    However we can get the similar one abc.__instancecheck__ according to __instancecheck__.

    From above abc.__instancecheck__, after using test below:

    # file tree
    # /test/__init__.py
    # /test/aaa/__init__.py
    # /test/aaa/aa.py
    class b():
    pass
    
    # /test/aaa/a.py
    import sys
    sys.path.append('/test')
    
    from aaa.aa import b
    from aa import b as c
    
    d = b()
    
    print(b, c, d.__class__)
    for i in [b, c, object]:
        print(i, '__subclasses__',  i.__subclasses__())
        print(i, '__mro__', i.__mro__)
        print(i, '__subclasshook__', i.__subclasshook__(d.__class__))
        print(i, '__subclasshook__', i.__subclasshook__(type(d)))
    print(isinstance(d, b))
    print(isinstance(d, c))
    
    <class 'aaa.aa.b'> <class 'aa.b'> <class 'aaa.aa.b'>
    <class 'aaa.aa.b'> __subclasses__ []
    <class 'aaa.aa.b'> __mro__ (<class 'aaa.aa.b'>, <class 'object'>)
    <class 'aaa.aa.b'> __subclasshook__ NotImplemented
    <class 'aaa.aa.b'> __subclasshook__ NotImplemented
    <class 'aa.b'> __subclasses__ []
    <class 'aa.b'> __mro__ (<class 'aa.b'>, <class 'object'>)
    <class 'aa.b'> __subclasshook__ NotImplemented
    <class 'aa.b'> __subclasshook__ NotImplemented
    <class 'object'> __subclasses__ [..., <class 'aaa.aa.b'>, <class 'aa.b'>]
    <class 'object'> __mro__ (<class 'object'>,)
    <class 'object'> __subclasshook__ NotImplemented
    <class 'object'> __subclasshook__ NotImplemented
    True
    False
    

    I get this conclusion, For type:

    # according to `abc.__instancecheck__`, they are maybe different! I have not found negative one 
    type(INSTANCE) ~= INSTANCE.__class__
    type(CLASS) ~= CLASS.__class__
    

    For isinstance:

    # guess from `abc.__instancecheck__`
    return any(c in cls.__mro__ or c in cls.__subclasses__ or cls.__subclasshook__(c) for c in {INSTANCE.__class__, type(INSTANCE)})
    

    BTW: better not to mix use relative and absolutely import, use absolutely import from project_dir( added by sys.path)

    How to remove/ignore :hover css style on touch devices

    This is also a possible workaround, but you will have to go through your css and add a .no-touch class before your hover styles.

    Javascript:

    if (!("ontouchstart" in document.documentElement)) {
    document.documentElement.className += " no-touch";
    }
    

    CSS Example:

    <style>
    p span {
        display: none;
    }
    
    .no-touch p:hover span {
        display: inline;
    }
    </style>
    <p><a href="/">Tap me</a><span>You tapped!</span></p>
    

    Source

    P.s. But we should remember, there are coming more and more touch-devices to the market, which are also supporting mouse input at the same time.

    What are the pros and cons of parquet format compared to other formats?

    Choosing the right file format is important to building performant data applications. The concepts outlined in this post carry over to Pandas, Dask, Spark, and Presto / AWS Athena.

    Column pruning

    Column pruning is a big performance improvement that's possible for column-based file formats (Parquet, ORC) and not possible for row-based file formats (CSV, Avro).

    Suppose you have a dataset with 100 columns and want to read two of them into a DataFrame. Here's how you can perform this with Pandas if the data is stored in a Parquet file.

    import pandas as pd
    
    pd.read_parquet('some_file.parquet', columns = ['id', 'firstname'])
    

    Parquet is a columnar file format, so Pandas can grab the columns relevant for the query and can skip the other columns. This is a massive performance improvement.

    If the data is stored in a CSV file, you can read it like this:

    import pandas as pd
    
    pd.read_csv('some_file.csv', usecols = ['id', 'firstname'])
    

    usecols can't skip over entire columns because of the row nature of the CSV file format.

    Spark doesn't require users to explicitly list the columns that'll be used in a query. Spark builds up an execution plan and will automatically leverage column pruning whenever possible. Of course, column pruning is only possible when the underlying file format is column oriented.

    Popularity

    Spark and Pandas have built-in readers writers for CSV, JSON, ORC, Parquet, and text files. They don't have built-in readers for Avro.

    Avro is popular within the Hadoop ecosystem. Parquet has gained significant traction outside of the Hadoop ecosystem. For example, the Delta Lake project is being built on Parquet files.

    Arrow is an important project that makes it easy to work with Parquet files with a variety of different languages (C, C++, Go, Java, JavaScript, MATLAB, Python, R, Ruby, Rust), but doesn't support Avro. Parquet files are easier to work with because they are supported by so many different projects.

    Schema

    Parquet stores the file schema in the file metadata. CSV files don't store file metadata, so readers need to either be supplied with the schema or the schema needs to be inferred. Supplying a schema is tedious and inferring a schema is error prone / expensive.

    Avro also stores the data schema in the file itself. Having schema in the files is a huge advantage and is one of the reasons why a modern data project should not rely on JSON or CSV.

    Column metadata

    Parquet stores metadata statistics for each column and lets users add their own column metadata as well.

    The min / max column value metadata allows for Parquet predicate pushdown filtering that's supported by the Dask & Spark cluster computing frameworks.

    Here's how to fetch the column statistics with PyArrow.

    import pyarrow.parquet as pq
    
    parquet_file = pq.ParquetFile('some_file.parquet')
    print(parquet_file.metadata.row_group(0).column(1).statistics)
    
    <pyarrow._parquet.Statistics object at 0x11ac17eb0>
      has_min_max: True
      min: 1
      max: 9
      null_count: 0
      distinct_count: 0
      num_values: 3
      physical_type: INT64
      logical_type: None
      converted_type (legacy): NONE
    

    Complex column types

    Parquet allows for complex column types like arrays, dictionaries, and nested schemas. There isn't a reliable method to store complex types in simple file formats like CSVs.

    Compression

    Columnar file formats store related types in rows, so they're easier to compress. This CSV file is relatively hard to compress.

    first_name,age
    ken,30
    felicia,36
    mia,2
    

    This data is easier to compress when the related types are stored in the same row:

    ken,felicia,mia
    30,36,2
    

    Parquet files are most commonly compressed with the Snappy compression algorithm. Snappy compressed files are splittable and quick to inflate. Big data systems want to reduce file size on disk, but also want to make it quick to inflate the flies and run analytical queries.

    Mutable nature of file

    Parquet files are immutable, as described here. CSV files are mutable.

    Adding a row to a CSV file is easy. You can't easily add a row to a Parquet file.

    Data lakes

    In a big data environment, you'll be working with hundreds or thousands of Parquet files. Disk partitioning of the files, avoiding big files, and compacting small files is important. The optimal disk layout of data depends on your query patterns.

    Spark RDD to DataFrame python

    See,

    There are two ways to convert an RDD to DF in Spark.

    toDF() and createDataFrame(rdd, schema)

    I will show you how you can do that dynamically.

    toDF()

    The toDF() command gives you the way to convert an RDD[Row] to a Dataframe. The point is, the object Row() can receive a **kwargs argument. So, there is an easy way to do that.

    from pyspark.sql.types import Row
    
    #here you are going to create a function
    def f(x):
        d = {}
        for i in range(len(x)):
            d[str(i)] = x[i]
        return d
    
    #Now populate that
    df = rdd.map(lambda x: Row(**f(x))).toDF()
    

    This way you are going to be able to create a dataframe dynamically.

    createDataFrame(rdd, schema)

    Other way to do that is creating a dynamic schema. How?

    This way:

    from pyspark.sql.types import StructType
    from pyspark.sql.types import StructField
    from pyspark.sql.types import StringType
    
    schema = StructType([StructField(str(i), StringType(), True) for i in range(32)])
    
    df = sqlContext.createDataFrame(rdd, schema)
    

    This second way is cleaner to do that...

    So this is how you can create dataframes dynamically.

    "Large data" workflows using pandas

    I know this is an old thread but I think the Blaze library is worth checking out. It's built for these types of situations.

    From the docs:

    Blaze extends the usability of NumPy and Pandas to distributed and out-of-core computing. Blaze provides an interface similar to that of the NumPy ND-Array or Pandas DataFrame but maps these familiar interfaces onto a variety of other computational engines like Postgres or Spark.

    Edit: By the way, it's supported by ContinuumIO and Travis Oliphant, author of NumPy.

    window.onload vs <body onload=""/>

    There is no difference ...

    So principially you could use both (one at a time !-)

    But for the sake of readability and for the cleanliness of the html-code I always prefer the window.onload !o]

    How can I create a unique constraint on my column (SQL Server 2008 R2)?

    Set column as unique in SQL Server from the GUI:

    They really make you run around the barn to do it with the GUI:

    Make sure your column does not violate the unique constraint before you begin.

    1. Open SQL Server Management Studio.
    2. Right click your Table, click "Design".
    3. Right click the column you want to edit, a popup menu appears, click Indexes/Keys.
    4. Click the "Add" Button.
    5. Expand the "General" tab.
    6. Make sure you have the column you want to make unique selected in the "columns" box.
    7. Change the "Type" box to "Unique Key".
    8. Click "Close".
    9. You see a little asterisk in the file window, this means changes are not yet saved.
    10. Press Save or hit Ctrl+s. It should save, and your column should be unique.

    Or set column as unique from the SQL Query window:

    alter table location_key drop constraint pinky;
    alter table your_table add constraint pinky unique(yourcolumn);
    

    Changes take effect immediately:

    Command(s) completed successfully.
    

    Composer - the requested PHP extension mbstring is missing from your system

    1. find your php.ini
    2. make sure the directive extension_dir=C:\path\to\server\php\ext is set and adjust the path (set your PHP extension dir)
    3. make sure the directive extension=php_mbstring.dll is set (uncommented)

    If this doesn't work and the php_mbstring.dll file is missing, then the PHP installation of this stack is simply broken.

    Sending HTML Code Through JSON

    Do Like this

    1st put all your HTML content to array, then do json_encode

    $html_content="<p>hello this is sample text";
    $json_array=array(
    
    'content'=>50,
    'html_content'=>$html_content
    );
    echo json_encode($json_array);
    

    X11/Xlib.h not found in Ubuntu

    Presume he's using the tutorial from http://www.arcsynthesis.org/gltut/ along with premake4.3 :-)

    sudo apt-get install libx11-dev ................. for X11/Xlib.h
    sudo apt-get install mesa-common-dev........ for GL/glx.h
    sudo apt-get install libglu1-mesa-dev ..... for GL/glu.h
    sudo apt-get install libxrandr-dev ........... for X11/extensions/Xrandr.h
    sudo apt-get install libxi-dev ................... for X11/extensions/XInput.h

    After which I could build glsdk_0.4.4 and examples without further issue.

    Convert unix time to readable date in pandas dataframe

    If you try using:

    df[DATE_FIELD]=(pd.to_datetime(df[DATE_FIELD],***unit='s'***))
    

    and receive an error :

    "pandas.tslib.OutOfBoundsDatetime: cannot convert input with unit 's'"

    This means the DATE_FIELD is not specified in seconds.

    In my case, it was milli seconds - EPOCH time.

    The conversion worked using below:

    df[DATE_FIELD]=(pd.to_datetime(df[DATE_FIELD],unit='ms')) 
    

    Python logging not outputting anything

    For anyone here that wants a super-simple answer: just set the level you want displayed. At the top of all my scripts I just put:

    import logging
    logging.basicConfig(level = logging.INFO)
    

    Then to display anything at or above that level:

    logging.info("Hi you just set your fleeb to level plumbus")
    

    It is a hierarchical set of five levels so that logs will display at the level you set, or higher. So if you want to display an error you could use logging.error("The plumbus is broken").

    The levels, in increasing order of severity, are DEBUG, INFO, WARNING, ERROR, and CRITICAL. The default setting is WARNING.

    This is a good article containing this information expressed better than my answer:
    https://www.digitalocean.com/community/tutorials/how-to-use-logging-in-python-3

    hasNext in Python iterators?

    The way I solved my problem is to keep the count of the number of objects iterated over, so far. I wanted to iterate over a set using calls to an instance method. Since I knew the length of the set, and the number of items counted so far, I effectively had an hasNext method.

    A simple version of my code:

    class Iterator:
        # s is a string, say
        def __init__(self, s):
            self.s = set(list(s))
            self.done = False
            self.iter = iter(s)
            self.charCount = 0
    
        def next(self):
            if self.done:
                return None
            self.char = next(self.iter)
            self.charCount += 1
            self.done = (self.charCount < len(self.s))
            return self.char
    
        def hasMore(self):
            return not self.done
    

    Of course, the example is a toy one, but you get the idea. This won't work in cases where there is no way to get the length of the iterable, like a generator etc.

    Microsoft.WebApplication.targets was not found, on the build server. What's your solution?

    • After installation of MSBuild tools from Microsoft, define the MSBuild path in the environment variable, so that it can be run from any path.
    • Edit the .csproj file in any notepad editor such as notepad++, and comment the
    • Check for the following elements, -->
      • Make sure you use import only once, choose whichever works.
      • Make sure you have the following folder exists on the drive, "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v14.0" or whichever version is referenced by MSBuild target at "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v14.0\WebApplications\Microsoft.WebApplication.targets"
      • From the command prompt, run the following command, to check

    C:>msbuild "C:\\DotnetCi.sln" /p:Configuration=Release /p:UseWPP_CopyWebApplication=true /p:PipelineDependsOnBuild=false

    How to get longitude and latitude of any address?

    Use the following code for getting lat and long using php. Here are two methods:

    Type-1:

        <?php
         // Get lat and long by address         
            $address = $dlocation; // Google HQ
            $prepAddr = str_replace(' ','+',$address);
            $geocode=file_get_contents('https://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&sensor=false');
            $output= json_decode($geocode);
            $latitude = $output->results[0]->geometry->location->lat;
            $longitude = $output->results[0]->geometry->location->lng;
    
    ?>
    

    edit - Google Maps requests must be over https

    Type-2:

    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
         <script>
          var geocoder;
          var map;
          function initialize() {
            geocoder = new google.maps.Geocoder();
             var latlng = new google.maps.LatLng(50.804400, -1.147250);
            var mapOptions = {
             zoom: 6,
             center: latlng
            }
             map = new google.maps.Map(document.getElementById('map-canvas12'), mapOptions);
            }
    
           function codeAddress(address,tutorname,url,distance,prise,postcode) {
           var address = address;
    
            geocoder.geocode( { 'address': address}, function(results, status) {
             if (status == google.maps.GeocoderStatus.OK) {
              map.setCenter(results[0].geometry.location);
               var marker = new google.maps.Marker({
              map: map,
              position: results[0].geometry.location
          });
    
          var infowindow = new google.maps.InfoWindow({
             content: 'Tutor Name: '+tutorname+'<br>Price Guide: '+prise+'<br>Distance: '+distance+' Miles from you('+postcode+')<br> <a href="'+url+'" target="blank">View Tutor profile</a> '
           });
            infowindow.open(map,marker);
    
              } /*else {
              alert('Geocode was not successful for the following reason: ' + status);
            }*/
           });
         }
    
    
          google.maps.event.addDomListener(window, 'load', initialize);
    
         window.onload = function(){
          initialize();
          // your code here
          <?php foreach($addr as $add) { 
    
          ?>
          codeAddress('<?php echo $add['address']; ?>','<?php echo $add['tutorname']; ?>','<?php echo $add['url']; ?>','<?php echo $add['distance']; ?>','<?php echo $add['prise']; ?>','<?php echo substr( $postcode1,0,4); ?>');
          <?php } ?>
        };
          </script>
    
         <div id="map-canvas12"></div>
    

    Inline functions in C#?

    No, there is no such construct in C#, but the .NET JIT compiler could decide to do inline function calls on JIT time. But i actually don't know if it is really doing such optimizations.
    (I think it should :-))

    Spring @Transactional - isolation, propagation

    PROPAGATION_REQUIRED = 0; If DataSourceTransactionObject T1 is already started for Method M1. If for another Method M2 Transaction object is required, no new Transaction object is created. Same object T1 is used for M2.

    PROPAGATION_MANDATORY = 2; method must run within a transaction. If no existing transaction is in progress, an exception will be thrown.

    PROPAGATION_REQUIRES_NEW = 3; If DataSourceTransactionObject T1 is already started for Method M1 and it is in progress (executing method M1). If another method M2 start executing then T1 is suspended for the duration of method M2 with new DataSourceTransactionObject T2 for M2. M2 run within its own transaction context.

    PROPAGATION_NOT_SUPPORTED = 4; If DataSourceTransactionObject T1 is already started for Method M1. If another method M2 is run concurrently. Then M2 should not run within transaction context. T1 is suspended till M2 is finished.

    PROPAGATION_NEVER = 5; None of the methods run in transaction context.


    An isolation level: It is about how much a transaction may be impacted by the activities of other concurrent transactions. It a supports consistency leaving the data across many tables in a consistent state. It involves locking rows and/or tables in a database.

    The problem with multiple transaction

    Scenario 1. If T1 transaction reads data from table A1 that was written by another concurrent transaction T2. If on the way T2 is rollback, the data obtained by T1 is invalid one. E.g. a=2 is original data. If T1 read a=1 that was written by T2. If T2 rollback then a=1 will be rollback to a=2 in DB. But, now, T1 has a=1 but in DB table it is changed to a=2.

    Scenario2. If T1 transaction reads data from table A1. If another concurrent transaction (T2) update data on table A1. Then the data that T1 has read is different from table A1. Because T2 has updated the data on table A1. E.g. if T1 read a=1 and T2 updated a=2. Then a!=b.

    Scenario 3. If T1 transaction reads data from table A1 with certain number of rows. If another concurrent transaction (T2) inserts more rows on table A1. The number of rows read by T1 is different from rows on table A1.

    Scenario 1 is called Dirty reads.

    Scenario 2 is called Non-repeatable reads.

    Scenario 3 is called Phantom reads.

    So, isolation level is the extend to which Scenario 1, Scenario 2, Scenario 3 can be prevented. You can obtain complete isolation level by implementing locking. That is preventing concurrent reads and writes to the same data from occurring. But it affects performance. The level of isolation depends upon application to application how much isolation is required.

    ISOLATION_READ_UNCOMMITTED: Allows to read changes that haven’t yet been committed. It suffer from Scenario 1, Scenario 2, Scenario 3.

    ISOLATION_READ_COMMITTED: Allows reads from concurrent transactions that have been committed. It may suffer from Scenario 2 and Scenario 3. Because other transactions may be updating the data.

    ISOLATION_REPEATABLE_READ: Multiple reads of the same field will yield the same results untill it is changed by itself. It may suffer from Scenario 3. Because other transactions may be inserting the data.

    ISOLATION_SERIALIZABLE: Scenario 1, Scenario 2, Scenario 3 never happen. It is complete isolation. It involves full locking. It affects performace because of locking.

    You can test using:

    public class TransactionBehaviour {
       // set is either using xml Or annotation
        DataSourceTransactionManager manager=new DataSourceTransactionManager();
        SimpleTransactionStatus status=new SimpleTransactionStatus();
       ;
      
        
        public void beginTransaction()
        {
            DefaultTransactionDefinition Def = new DefaultTransactionDefinition();
            // overwrite default PROPAGATION_REQUIRED and ISOLATION_DEFAULT
            // set is either using xml Or annotation
            manager.setPropagationBehavior(XX);
            manager.setIsolationLevelName(XX);
           
            status = manager.getTransaction(Def);
        
        }
    
        public void commitTransaction()
        {
           
          
                if(status.isCompleted()){
                    manager.commit(status);
            } 
        }
    
        public void rollbackTransaction()
        {
           
                if(!status.isCompleted()){
                    manager.rollback(status);
            }
        }
        Main method{
            beginTransaction()
            M1();
            If error(){
                rollbackTransaction()
            }
             commitTransaction();
        }
       
    }
    

    You can debug and see the result with different values for isolation and propagation.

    Prevent a webpage from navigating away using JavaScript

    Unlike other methods presented here, this bit of code will not cause the browser to display a warning asking the user if he wants to leave; instead, it exploits the evented nature of the DOM to redirect back to the current page (and thus cancel navigation) before the browser has a chance to unload it from memory.

    Since it works by short-circuiting navigation directly, it cannot be used to prevent the page from being closed; however, it can be used to disable frame-busting.

    (function () {
        var location = window.document.location;
    
        var preventNavigation = function () {
            var originalHashValue = location.hash;
    
            window.setTimeout(function () {
                location.hash = 'preventNavigation' + ~~ (9999 * Math.random());
                location.hash = originalHashValue;
            }, 0);
        };
    
        window.addEventListener('beforeunload', preventNavigation, false);
        window.addEventListener('unload', preventNavigation, false);
    })();
    

    Disclaimer: You should never do this. If a page has frame-busting code on it, please respect the wishes of the author.

    Ruby: Calling class method from instance

    If you have access to the delegate method you can do this:

    [20] pry(main)> class Foo
    [20] pry(main)*   def self.bar
    [20] pry(main)*     "foo bar"
    [20] pry(main)*   end  
    [20] pry(main)*   delegate :bar, to: 'self.class'
    [20] pry(main)* end  
    => [:bar]
    [21] pry(main)> Foo.new.bar
    => "foo bar"
    [22] pry(main)> Foo.bar
    => "foo bar"
    

    Alternatively, and probably cleaner if you have more then a method or two you want to delegate to class & instance:

    [1] pry(main)> class Foo
    [1] pry(main)*   module AvailableToClassAndInstance
    [1] pry(main)*     def bar
    [1] pry(main)*       "foo bar"
    [1] pry(main)*     end  
    [1] pry(main)*   end  
    [1] pry(main)*   include AvailableToClassAndInstance
    [1] pry(main)*   extend AvailableToClassAndInstance
    [1] pry(main)* end  
    => Foo
    [2] pry(main)> Foo.new.bar
    => "foo bar"
    [3] pry(main)> Foo.bar
    => "foo bar"
    

    A word of caution:

    Don't just randomly delegate everything that doesn't change state to class and instance because you'll start running into strange name clash issues. Do this sparingly and only after you checked nothing else is squashed.

    How to find file accessed/created just few minutes ago

    Simply specify whether you want the time to be greater, smaller, or equal to the time you want, using, respectively:

    find . -cmin +<time>
    find . -cmin -<time>
    find . -cmin  <time>
    

    In your case, for example, the files with last edition in a maximum of 5 minutes, are given by:

    find . -cmin -5
    

    Cannot create Maven Project in eclipse

    It's actually easy and straight forward.

    just navigate to your .m2 folder.

    .m2/repository/org/apache/maven

    inside this maven folder, you will see a folder called Archetypes... delete this folder and the problem is solved.

    but if you don't feel like deleting the whole folder, you can navigate into the archetype folder and delete all the archetype you want there. The reason why it keeps failing is because, the archetype you are trying to create is trying to tell you that she already exists in that folder, hence move away...

    summarily, deleting the archetype folder in the .m2 folder is the easiest solution.

    CSS3 selector :first-of-type with class name?

    Not sure how to explain this but I ran into something similar today. Not being able to set .user:first-of-type{} while .user:last-of-type{} worked fine. This was fixed after I wrapped them inside a div without any class or styling:

    https://codepen.io/adrianTNT/pen/WgEpbE

    <style>
    .user{
      display:block;
      background-color:#FFCC00;
    }
    
    .user:first-of-type{
      background-color:#FF0000;
    }
    </style>
    
    <p>Not working while this P additional tag exists</p>
    
    <p class="user">A</p>
    <p class="user">B</p>
    <p class="user">C</p>
    
    <p>Working while inside a div:</p>
    
    <div>
    <p class="user">A</p>
    <p class="user">B</p>
    <p class="user">C</p>
    </div>
    

    Difference between text and varchar (character varying)

    There is no difference, under the hood it's all varlena (variable length array).

    Check this article from Depesz: http://www.depesz.com/index.php/2010/03/02/charx-vs-varcharx-vs-varchar-vs-text/

    A couple of highlights:

    To sum it all up:

    • char(n) – takes too much space when dealing with values shorter than n (pads them to n), and can lead to subtle errors because of adding trailing spaces, plus it is problematic to change the limit
    • varchar(n) – it's problematic to change the limit in live environment (requires exclusive lock while altering table)
    • varchar – just like text
    • text – for me a winner – over (n) data types because it lacks their problems, and over varchar – because it has distinct name

    The article does detailed testing to show that the performance of inserts and selects for all 4 data types are similar. It also takes a detailed look at alternate ways on constraining the length when needed. Function based constraints or domains provide the advantage of instant increase of the length constraint, and on the basis that decreasing a string length constraint is rare, depesz concludes that one of them is usually the best choice for a length limit.

    Declare a Range relative to the Active Cell with VBA

    Like this:

    Dim rng as Range
    Set rng = ActiveCell.Resize(numRows, numCols)
    

    then read the contents of that range to an array:

    Dim arr As Variant
    arr = rng.Value
    'arr is now a two-dimensional array of size (numRows, numCols)
    

    or, select the range (I don't think that's what you really want, but you ask for this in the question).

    rng.Select
    

    MySQL Update Inner Join tables query

    For MySql WorkBench, Please use below :

    update emp as a
    inner join department b on a.department_id=b.id
    set a.department_name=b.name
    where a.emp_id in (10,11,12); 
    

    Convert bytes to a string

    If you don't know the encoding, then to read binary input into string in Python 3 and Python 2 compatible way, use the ancient MS-DOS CP437 encoding:

    PY3K = sys.version_info >= (3, 0)
    
    lines = []
    for line in stream:
        if not PY3K:
            lines.append(line)
        else:
            lines.append(line.decode('cp437'))
    

    Because encoding is unknown, expect non-English symbols to translate to characters of cp437 (English characters are not translated, because they match in most single byte encodings and UTF-8).

    Decoding arbitrary binary input to UTF-8 is unsafe, because you may get this:

    >>> b'\x00\x01\xffsd'.decode('utf-8')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 2: invalid
    start byte
    

    The same applies to latin-1, which was popular (the default?) for Python 2. See the missing points in Codepage Layout - it is where Python chokes with infamous ordinal not in range.

    UPDATE 20150604: There are rumors that Python 3 has the surrogateescape error strategy for encoding stuff into binary data without data loss and crashes, but it needs conversion tests, [binary] -> [str] -> [binary], to validate both performance and reliability.

    UPDATE 20170116: Thanks to comment by Nearoo - there is also a possibility to slash escape all unknown bytes with backslashreplace error handler. That works only for Python 3, so even with this workaround you will still get inconsistent output from different Python versions:

    PY3K = sys.version_info >= (3, 0)
    
    lines = []
    for line in stream:
        if not PY3K:
            lines.append(line)
        else:
            lines.append(line.decode('utf-8', 'backslashreplace'))
    

    See Python’s Unicode Support for details.

    UPDATE 20170119: I decided to implement slash escaping decode that works for both Python 2 and Python 3. It should be slower than the cp437 solution, but it should produce identical results on every Python version.

    # --- preparation
    
    import codecs
    
    def slashescape(err):
        """ codecs error handler. err is UnicodeDecode instance. return
        a tuple with a replacement for the unencodable part of the input
        and a position where encoding should continue"""
        #print err, dir(err), err.start, err.end, err.object[:err.start]
        thebyte = err.object[err.start:err.end]
        repl = u'\\x'+hex(ord(thebyte))[2:]
        return (repl, err.end)
    
    codecs.register_error('slashescape', slashescape)
    
    # --- processing
    
    stream = [b'\x80abc']
    
    lines = []
    for line in stream:
        lines.append(line.decode('utf-8', 'slashescape'))
    

    How to fix Git error: object file is empty?

    This error happens to me when I am pushing my commit and my computer hangs. This is how I've fix it.


    Steps to fix

    git status
    

    show the empty/corrupt object file

    rm .git/objects/08/3834cb34d155e67a8930604d57d3d302d7ec12
    

    remove it

    git status
    

    I got fatal: bad object HEAD message

    rm .git/index
    

    I remove the index for the reset

    git reset
    

    fatal: Could not parse object 'HEAD'.

    git status
    git pull
    

    just to check whats happening

    tail -n 2 .git/logs/refs/heads/MY-CURRENT-BRANCH
    

    prints the last 2 lines tail -n 2 of log branch to show my last 2 commit hash

    git update-ref HEAD 7221fa02cb627470db163826da4265609aba47b2
    

    I pick the last commit hash

    git status
    

    shows all my file as deleted because i removed the .git/index file

    git reset
    

    continue to the reset

    git status
    

    verify my fix


    Note: The steps starts when I landed on this question and used the answers as reference.

    Returning binary file from controller in ASP.NET Web API

    For those using .NET Core:

    You can make use of the IActionResult interface in an API controller method, like so...

        [HttpGet("GetReportData/{year}")]
        public async Task<IActionResult> GetReportData(int year)
        {
            // Render Excel document in memory and return as Byte[]
            Byte[] file = await this._reportDao.RenderReportAsExcel(year);
    
            return File(file, "application/vnd.openxmlformats", "fileName.xlsx");
        }
    

    This example is simplified, but should get the point across. In .NET Core this process is so much simpler than in previous versions of .NET - i.e. no setting response type, content, headers, etc.

    Also, of course the MIME type for the file and the extension will depend on individual needs.

    Reference: SO Post Answer by @NKosi

    What is this date format? 2011-08-12T20:17:46.384Z

    This technique translates java.util.Date to UTC format (or any other) and back again.

    Define a class like so:

    import java.util.Date;
    
    import org.joda.time.DateTime;
    import org.joda.time.format.DateTimeFormat;
    import org.joda.time.format.DateTimeFormatter;
    
    public class UtcUtility {
    
    public static DateTimeFormatter UTC = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZoneUTC();
    
    
    public static Date parse(DateTimeFormatter dateTimeFormatter, String date) {
        return dateTimeFormatter.parseDateTime(date).toDate();
    }
    
    public static String format(DateTimeFormatter dateTimeFormatter, Date date) {
        return format(dateTimeFormatter, date.getTime());
    }
    
    private static String format(DateTimeFormatter dateTimeFormatter, long timeInMillis) {
        DateTime dateTime = new DateTime(timeInMillis);
        String formattedString = dateTimeFormatter.print(dateTime);
        return formattedString;
    }
    

    }

    Then use it like this:

    Date date = format(UTC, "2020-04-19T00:30:07.000Z")
    

    or

    String date = parse(UTC, new Date())
    

    You can also define other date formats if you require (not just UTC)

    Spring Boot yaml configuration for a list of strings

    use comma separated values in application.yml

    ignoreFilenames: .DS_Store, .hg
    

    java code for access

    @Value("${ignoreFilenames}")    
    String[] ignoreFilenames
    

    It is working ;)

    BehaviorSubject vs Observable?

    BehaviorSubject

    The BehaviorSubject builds on top of the same functionality as our ReplaySubject, subject like, hot, and replays previous value.

    The BehaviorSubject adds one more piece of functionality in that you can give the BehaviorSubject an initial value. Let’s go ahead and take a look at that code

    import { ReplaySubject } from 'rxjs';
    
    const behaviorSubject = new BehaviorSubject(
      'hello initial value from BehaviorSubject'
    );
    
    behaviorSubject.subscribe(v => console.log(v));
    
    behaviorSubject.next('hello again from BehaviorSubject');
    

    Observables

    To get started we are going to look at the minimal API to create a regular Observable. There are a couple of ways to create an Observable. The way we will create our Observable is by instantiating the class. Other operators can simplify this, but we will want to compare the instantiation step to our different Observable types

    import { Observable } from 'rxjs';
    
    const observable = new Observable(observer => {
      setTimeout(() => observer.next('hello from Observable!'), 1000);
    });
    
    observable.subscribe(v => console.log(v));
    

    Disable password authentication for SSH

    Here's a script to do this automatically

    # Only allow key based logins
    sed -n 'H;${x;s/\#PasswordAuthentication yes/PasswordAuthentication no/;p;}' /etc/ssh/sshd_config > tmp_sshd_config
    cat tmp_sshd_config > /etc/ssh/sshd_config
    rm tmp_sshd_config
    

    Online SQL syntax checker conforming to multiple databases

    I haven't ever seen such a thing, but there is this dev tool that includes a syntax checker for oracle, mysql, db2, and sql server... http://www.sqlparser.com/index.php

    However this seems to be just the library. You'd need to build an app to leverage the parser to do what you want. And the Enterprise edition that includes all of the databases would cost you $450... ouch!

    EDIT: And, after saying that - it looks like someone might already have done what you want using that library: http://www.wangz.net/cgi-bin/pp/gsqlparser/sqlpp/sqlformat.tpl

    The online tool doesn't automatically check against each DB though, you need to run each manually. Nor can I say how good it is at checking the syntax. That you'd need to investigate yourself.

    Display label text with line breaks in c#

    Or simply add one line of:

    Text='<%# Eval("Comments").ToString().Replace("\n","<br />") %>'
    

    Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty

    The issue for me was calling get_text_noop in the LANGUAGES iterable.

    Changing

    LANGUAGES = (
        ('en-gb', get_text_noop('British English')),
        ('fr', get_text_noop('French')),
    )
    

    to

    from django.utils.translation import gettext_lazy as _
    
    LANGUAGES = (
        ('en-gb', _('British English')),
        ('fr', _('French')),
    )
    

    in the base settings file resolved the ImproperlyConfigured: The SECRET_KEY setting must not be empty exception.

    How do you decompile a swf file

    Usually 'lost' is a euphemism for "We stopped paying the developer and now he wont give us the source code."

    That being said, I own a copy of Burak's ActionScript Viewer, and it works pretty well. A simple google search will find you many other SWF decompilers.

    Trouble using ROW_NUMBER() OVER (PARTITION BY ...)

    A bit involved. Easiest would be to refer to this SQL Fiddle I created for you that produces the exact result. There are ways you can improve it for performance or other considerations, but this should hopefully at least be clearer than some alternatives.

    The gist is, you get a canonical ranking of your data first, then use that to segment the data into groups, then find an end date for each group, then eliminate any intermediate rows. ROW_NUMBER() and CROSS APPLY help a lot in doing it readably.


    EDIT 2019:

    The SQL Fiddle does in fact seem to be broken, for some reason, but it appears to be a problem on the SQL Fiddle site. Here's a complete version, tested just now on SQL Server 2016:

    CREATE TABLE Source
    (
      EmployeeID int,
      DateStarted date,
      DepartmentID int
    )
    
    INSERT INTO Source
    VALUES
    (10001,'2013-01-01',001),
    (10001,'2013-09-09',001),
    (10001,'2013-12-01',002),
    (10001,'2014-05-01',002),
    (10001,'2014-10-01',001),
    (10001,'2014-12-01',001)
    
    
    SELECT *, 
      ROW_NUMBER() OVER (PARTITION BY EmployeeID ORDER BY DateStarted) AS EntryRank,
      newid() as GroupKey,
      CAST(NULL AS date) AS EndDate
    INTO #RankedData
    FROM Source
    ;
    
    UPDATE #RankedData
    SET GroupKey = beginDate.GroupKey
    FROM #RankedData sup
      CROSS APPLY 
      (
        SELECT TOP 1 GroupKey
        FROM #RankedData sub 
        WHERE sub.EmployeeID = sup.EmployeeID AND
          sub.DepartmentID = sup.DepartmentID AND
          NOT EXISTS 
            (
              SELECT * 
              FROM #RankedData bot 
              WHERE bot.EmployeeID = sup.EmployeeID AND
                bot.EntryRank BETWEEN sub.EntryRank AND sup.EntryRank AND
                bot.DepartmentID <> sup.DepartmentID
            )
          ORDER BY DateStarted ASC
        ) beginDate (GroupKey);
    
    UPDATE #RankedData
    SET EndDate = nextGroup.DateStarted
    FROM #RankedData sup
      CROSS APPLY 
      (
        SELECT TOP 1 DateStarted
        FROM #RankedData sub
        WHERE sub.EmployeeID = sup.EmployeeID AND
          sub.DepartmentID <> sup.DepartmentID AND
          sub.EntryRank > sup.EntryRank
        ORDER BY EntryRank ASC
      ) nextGroup (DateStarted);
    
    SELECT * FROM 
    (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY GroupKey ORDER BY EntryRank ASC) AS GroupRank FROM #RankedData
    ) FinalRanking
    WHERE GroupRank = 1
    ORDER BY EntryRank;
    
    DROP TABLE #RankedData
    DROP TABLE Source
    

    php Replacing multiple spaces with a single space

    preg_replace("/[[:blank:]]+/"," ",$input)