Programs & Examples On #Livequery

Live Query utilizes the power of jQuery selectors by binding events or firing callbacks for matched elements auto-magically, even after the page has been loaded and the DOM updated.

jQuery "on create" event for dynamically-created elements

You can on the DOMNodeInserted event to get an event for when it's added to the document by your code.

$('body').on('DOMNodeInserted', 'select', function () {
      //$(this).combobox();
});

$('<select>').appendTo('body');
$('<select>').appendTo('body');

Fiddled here: http://jsfiddle.net/Codesleuth/qLAB2/3/

EDIT: after reading around I just need to double check DOMNodeInserted won't cause problems across browsers. This question from 2010 suggests IE doesn't support the event, so test it if you can.

See here: [link] Warning! the DOMNodeInserted event type is defined in this specification for reference and completeness, but this specification deprecates the use of this event type.

Event binding on dynamically created elements?

As of jQuery 1.7 you should use jQuery.fn.on with the selector parameter filled:

$(staticAncestors).on(eventName, dynamicChild, function() {});

Explanation:

This is called event delegation and works as followed. The event is attached to a static parent (staticAncestors) of the element that should be handled. This jQuery handler is triggered every time the event triggers on this element or one of the descendant elements. The handler then checks if the element that triggered the event matches your selector (dynamicChild). When there is a match then your custom handler function is executed.


Prior to this, the recommended approach was to use live():

$(selector).live( eventName, function(){} );

However, live() was deprecated in 1.7 in favour of on(), and completely removed in 1.9. The live() signature:

$(selector).live( eventName, function(){} );

... can be replaced with the following on() signature:

$(document).on( eventName, selector, function(){} );

For example, if your page was dynamically creating elements with the class name dosomething you would bind the event to a parent which already exists (this is the nub of the problem here, you need something that exists to bind to, don't bind to the dynamic content), this can be (and the easiest option) is document. Though bear in mind document may not be the most efficient option.

$(document).on('mouseover mouseout', '.dosomething', function(){
    // what you want to happen when mouseover and mouseout 
    // occurs on elements that match '.dosomething'
});

Any parent that exists at the time the event is bound is fine. For example

$('.buttons').on('click', 'button', function(){
    // do something here
});

would apply to

<div class="buttons">
    <!-- <button>s that are generated dynamically and added here -->
</div>

Array Length in Java

if you mean by "logical size", the index of array, then simply int arrayLength = arr.length-1; since the the array index starts with "0", so the logical or "array index" will always be less than the actual size by "one".

Is JavaScript's "new" keyword considered harmful?

I have just read some parts of his Crockfords book "Javascript: The Good Parts". I get the feeling that he considers everything that ever has bitten him as harmful:

About switch fall through:

I never allow switch cases to fall through to the next case. I once found a bug in my code caused by an unintended fall through immediately after having made a vigorous speech about why fall through was sometimes useful. (page 97, ISBN 978-0-596-51774-8)

About ++ and --

The ++ (increment) and -- (decrement) operators have been known to contribute to bad code by encouraging exessive trickiness. They are second only to faulty architecture in enabling viruses and other security menaces. (page 122)

About new:

If you forget to include the new prefix when calling a constructor function, then this will not be bound to the new object. Sadly, this will be bound to the global object, so instead of augmenting your new object, you will be clobbering global variables. That is really bad. There is no compile warning, and there is no runtime warning. (page 49)

There are more, but I hope you get the picture.

My answer to your question: No, it's not harmful. but if you forget to use it when you should you could have some problems. If you are developing in a good environment you notice that.

Update

About a year after this answer was written the 5th edition of ECMAScript was released, with support for strict mode. In strict mode, this is no longer bound to the global object but to undefined.

Export HTML page to PDF on user click using JavaScript

This is because you define your "doc" variable outside of your click event. The first time you click the button the doc variable contains a new jsPDF object. But when you click for a second time, this variable can't be used in the same way anymore. As it is already defined and used the previous time.

change it to:

$(function () {

    var specialElementHandlers = {
        '#editor': function (element,renderer) {
            return true;
        }
    };
 $('#cmd').click(function () {
        var doc = new jsPDF();
        doc.fromHTML(
            $('#target').html(), 15, 15, 
            { 'width': 170, 'elementHandlers': specialElementHandlers }, 
            function(){ doc.save('sample-file.pdf'); }
        );

    });  
});

and it will work.

Polling the keyboard (detect a keypress) in python

You might look at how pygame handles this to steal some ideas.

Create a BufferedImage from file and make it TYPE_INT_ARGB

Create a BufferedImage from file and make it TYPE_INT_RGB

import java.io.*;
import java.awt.image.*;
import javax.imageio.*;
public class Main{
    public static void main(String args[]){
        try{
            BufferedImage img = new BufferedImage( 
                500, 500, BufferedImage.TYPE_INT_RGB );
            File f = new File("MyFile.png");
            int r = 5;
            int g = 25; 
            int b = 255;
            int col = (r << 16) | (g << 8) | b;
            for(int x = 0; x < 500; x++){
                for(int y = 20; y < 300; y++){
                    img.setRGB(x, y, col);
                }
            }
            ImageIO.write(img, "PNG", f); 
        }
        catch(Exception e){ 
            e.printStackTrace();
        }
    }
}

This paints a big blue streak across the top.

If you want it ARGB, do it like this:

    try{
        BufferedImage img = new BufferedImage( 
            500, 500, BufferedImage.TYPE_INT_ARGB );
        File f = new File("MyFile.png");
        int r = 255;
        int g = 10;
        int b = 57;
        int alpha = 255;
        int col = (alpha << 24) | (r << 16) | (g << 8) | b;
        for(int x = 0; x < 500; x++){
            for(int y = 20; y < 30; y++){
                img.setRGB(x, y, col);
            }
        }
        ImageIO.write(img, "PNG", f);
    }
    catch(Exception e){
        e.printStackTrace();
    }

Open up MyFile.png, it has a red streak across the top.

file_get_contents(): SSL operation failed with code 1, Failed to enable crypto

You basically have to set the environment variable SSL_CERT_FILE to the path of the PEM file of the ssl-certificate downloaded from the following link : http://curl.haxx.se/ca/cacert.pem.

It took me a lot of time to figure this out.

How to resize image (Bitmap) to a given size?

 Bitmap yourBitmap;
 Bitmap resized = Bitmap.createScaledBitmap(yourBitmap, newWidth, newHeight, true);

or:

 resized = Bitmap.createScaledBitmap(yourBitmap,(int)(yourBitmap.getWidth()*0.8), (int)(yourBitmap.getHeight()*0.8), true);

Excel VBA function to print an array to the workbook

A more elegant way is to assign the whole array at once:

Sub PrintArray(Data, SheetName, StartRow, StartCol)

    Dim Rng As Range

    With Sheets(SheetName)
        Set Rng = .Range(.Cells(StartRow, StartCol), _
            .Cells(UBound(Data, 1) - LBound(Data, 1) + StartRow, _
            UBound(Data, 2) - LBound(Data, 2) + StartCol))
    End With
    Rng.Value2 = Data

End Sub

But watch out: it only works up to a size of about 8,000 cells. Then Excel throws a strange error. The maximum size isn't fixed and differs very much from Excel installation to Excel installation.

Removing duplicate characters from a string

Create a list in Python and also a set which doesn't allow any duplicates. Solution1 :

def fix(string):
    s = set()
    list = []
    for ch in string:
        if ch not in s:
            s.add(ch)
            list.append(ch)

    return ''.join(list)        

string = "Protiijaayiiii"
print(fix(string))

Method 2 :

s = "Protijayi"

aa = [ ch  for i, ch in enumerate(s) if ch not in s[:i]]
print(''.join(aa))

How can I get a character in a string by index?

Do you mean like this

int index = 2;
string s = "hello";
Console.WriteLine(s[index]);

string also implements IEnumberable<char> so you can also enumerate it like this

foreach (char c in s)
    Console.WriteLine(c);

How do I decrease the size of my sql server log file?

I had the same problem, my database log file size was about 39 gigabyte, and after shrinking (both database and files) it reduced to 37 gigabyte that was not enough, so I did this solution: (I did not need the ldf file (log file) anymore)

(**Important) : Get a full backup of your database before the process.

  1. Run "checkpoint" on that database.

  2. Detach that database (right click on the database and chose tasks >> Detach...) {if you see an error, do the steps in the end of this text}

  3. Move MyDatabase.ldf to another folder, you can find it in your hard disk in the same folder as your database (Just in case you need it in the future for some reason such as what user did some task).

  4. Attach the database (right click on Databases and chose Attach...)

  5. On attach dialog remove the .ldf file (which shows 'file not found' comment) and click Ok. (don`t worry the ldf file will be created after the attachment process.)

  6. After that, a new log file create with a size of 504 KB!!!.

In step 2, if you faced an error that database is used by another user, you can:

1.run this command on master database "sp_who2" and see what process using your database.

2.read the process number, for example it is 52 and type "kill 52", now your database is free and ready to detach.

If the number of processes using your database is too much:

1.Open services (type services in windows start) find SQL Server ... process and reset it (right click and chose reset).

  1. Immediately click Ok button in the detach dialog box (that showed the detach error previously).

PHPExcel auto size column width

for phpspreadsheet:

$sheet = $spreadsheet->getActiveSheet(); // $spreadsheet is instance of PhpOffice\PhpSpreadsheet\Spreadsheet

foreach (
    range(
         1, 
         Coordinate::columnIndexFromString($sheet->getHighestColumn(1))
    ) as $column
) {
    $sheet
          ->getColumnDimension(Coordinate::stringFromColumnIndex($column))
          ->setAutoSize(true);
}

how to refresh my datagridview after I add new data

I think the problem is that you're adding a new entry to the database, but not the data structure that the datagrid represents. You're only querying the database for data in the load event, so if the database changes after that you're not going to know about it.

To solve the problem you need to either re-query the database after each insert, or add the item to tables(0) data structure in addition to the Access table after each insert.

How to justify navbar-nav in Bootstrap 3

You can justify the navbar contents by using:

@media (min-width: 768px){
  .navbar-nav{
     margin: 0 auto;
     display: table;
     table-layout: fixed;
     float: none;
  }
}  

See this live: http://jsfiddle.net/panchroma/2fntE/

Good luck!

Create an ArrayList with multiple object types?

You don't know the type is Integer or String then you no need Generic. Go With old style.

List list= new ArrayList ();

list.add(1);
list.add("myname");

for(Object o = list){

} 

How to kill a process in MacOS?

in the spotlight, search for Activity Monitor. You can force fully remove any application from here.

enter image description here

How to send image to PHP file using Ajax?

Jquery code which contains simple ajax :

   $("#product").on("input", function(event) {
      var data=$("#nameform").serialize();
    $.post("./__partails/search-productbyCat.php",data,function(e){
       $(".result").empty().append(e);

     });


    });

Html elements you can use any element:

     <form id="nameform">
     <input type="text" name="product" id="product">
     </form>

php Code:

  $pdo=new PDO("mysql:host=localhost;dbname=onlineshooping","root","");
  $Catagoryf=$_POST['product'];

 $pricef=$_POST['price'];
  $colorf=$_POST['color'];

  $stmtcat=$pdo->prepare('SELECT * from products where Catagory =?');
  $stmtcat->execute(array($Catagoryf));

  while($result=$stmtcat->fetch(PDO::FETCH_ASSOC)){
  $iddb=$result['ID'];
     $namedb=$result['Name'];
    $pricedb=$result['Price'];
     $colordb=$result['Color'];

   echo "<tr>";
   echo "<td><a href=./pages/productsinfo.php?id=".$iddb."> $namedb</a> </td>".'<br>'; 
   echo "<td><pre>$pricedb</pre></td>";
   echo "<td><pre>    $colordb</pre>";
   echo "</tr>";

The easy way

How to retrieve the current version of a MySQL database management system (DBMS)?

Go to MySQL workbench and log to the server. There is a field called Server Status under MANAGEMENT. Click on Server Status and find out the version. enter image description here

Or else go to following location and open cmd -> C:\Windows\System32\cmd.exe. Then hit the command -> mysql -V

enter image description here

Removing elements by class name?

Recursive function might solve your problem like below

removeAllByClassName = function (className) {
    function findToRemove() {
        var sets = document.getElementsByClassName(className);
        if (sets.length > 0) {
            sets[0].remove();
            findToRemove();
        }
    }
    findToRemove();
};
//
removeAllByClassName();

Deleting an SVN branch

From the working copy:

svn rm branches/features
svn commit -m "delete stale feature branch"

How do I read a text file of about 2 GB?

Instead of loading / reading the complete file, you could use a tool to split the text file in smaller chunks. If you're using Linux, you could just use the split command (see this stackoverflow thread). For Windows, there are several tools available like HJSplit (see this superuser thread).

Global Variable from a different file Python

Importing file2 in file1.py makes the global (i.e., module level) names bound in file2 available to following code in file1 -- the only such name is SomeClass. It does not do the reverse: names defined in file1 are not made available to code in file2 when file1 imports file2. This would be the case even if you imported the right way (import file2, as @nate correctly recommends) rather than in the horrible, horrible way you're doing it (if everybody under the Sun forgot the very existence of the construct from ... import *, life would be so much better for everybody).

Apparently you want to make global names defined in file1 available to code in file2 and vice versa. This is known as a "cyclical dependency" and is a terrible idea (in Python, or anywhere else for that matter).

So, rather than showing you the incredibly fragile, often unmaintainable hacks to achieve (some semblance of) a cyclical dependency in Python, I'd much rather discuss the many excellent way in which you can avoid such terrible structure.

For example, you could put global names that need to be available to both modules in a third module (e.g. file3.py, to continue your naming streak;-) and import that third module into each of the other two (import file3 in both file1 and file2, and then use file3.foo etc, that is, qualified names, for the purpose of accessing or setting those global names from either or both of the other modules, not barenames).

Of course, more and more specific help could be offered if you clarified (by editing your Q) exactly why you think you need a cyclical dependency (just one easy prediction: no matter what makes you think you need a cyclical dependency, you're wrong;-).

Twitter Bootstrap 3: How to center a block

You can use class .center-block in combination with style="width:400px;max-width:100%;" to preserve responsiveness.

Using .col-md-* class with .center-block will not work because of the float on .col-md-*.

How do I store data in local storage using Angularjs?

You can use localStorage for the purpose.

Steps:

  1. add ngStorage.min.js in your file
  2. add ngStorage dependency in your module
  3. add $localStorage module in your controller
  4. use $localStorage.key = value

How to print a string in C++

If you'd like to use printf(), you might want to also:

#include <stdio.h>

Append value to empty vector in R?

In R, you can try out this way:

X = NULL
X
# NULL
values = letters[1:10]
values
# [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j"
X = append(X,values)
X
# [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j"
X = append(X,letters[23:26])
X
# [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "w" "x" "y" "z"

Postgresql Windows, is there a default password?

Try this:

Open PgAdmin -> Files -> Open pgpass.conf

You would get the path of pgpass.conf at the bottom of the window. Go to that location and open this file, you can find your password there.

Reference

If the above does not work, you may consider trying this:

 1. edit pg_hba.conf to allow trust authorization temporarily
 2. Reload the config file (pg_ctl reload)
 3. Connect and issue ALTER ROLE / PASSWORD to set the new password
 4. edit pg_hba.conf again and restore the previous settings
 5. Reload the config file again

How do I upload a file with metadata using a REST web service?

I don't understand why, over the course of eight years, no one has posted the easy answer. Rather than encode the file as base64, encode the json as a string. Then just decode the json on the server side.

In Javascript:

let formData = new FormData();
formData.append("file", myfile);
formData.append("myjson", JSON.stringify(myJsonObject));

POST it using Content-Type: multipart/form-data

On the server side, retrieve the file normally, and retrieve the json as a string. Convert the string to an object, which is usually one line of code no matter what programming language you use.

(Yes, it works great. Doing it in one of my apps.)

How do I catch a numpy warning like it's an exception (not just for testing)?

It seems that your configuration is using the print option for numpy.seterr:

>>> import numpy as np
>>> np.array([1])/0   #'warn' mode
__main__:1: RuntimeWarning: divide by zero encountered in divide
array([0])
>>> np.seterr(all='print')
{'over': 'warn', 'divide': 'warn', 'invalid': 'warn', 'under': 'ignore'}
>>> np.array([1])/0   #'print' mode
Warning: divide by zero encountered in divide
array([0])

This means that the warning you see is not a real warning, but it's just some characters printed to stdout(see the documentation for seterr). If you want to catch it you can:

  1. Use numpy.seterr(all='raise') which will directly raise the exception. This however changes the behaviour of all the operations, so it's a pretty big change in behaviour.
  2. Use numpy.seterr(all='warn'), which will transform the printed warning in a real warning and you'll be able to use the above solution to localize this change in behaviour.

Once you actually have a warning, you can use the warnings module to control how the warnings should be treated:

>>> import warnings
>>> 
>>> warnings.filterwarnings('error')
>>> 
>>> try:
...     warnings.warn(Warning())
... except Warning:
...     print 'Warning was raised as an exception!'
... 
Warning was raised as an exception!

Read carefully the documentation for filterwarnings since it allows you to filter only the warning you want and has other options. I'd also consider looking at catch_warnings which is a context manager which automatically resets the original filterwarnings function:

>>> import warnings
>>> with warnings.catch_warnings():
...     warnings.filterwarnings('error')
...     try:
...         warnings.warn(Warning())
...     except Warning: print 'Raised!'
... 
Raised!
>>> try:
...     warnings.warn(Warning())
... except Warning: print 'Not raised!'
... 
__main__:2: Warning: 

JavaScript for handling Tab Key press

Given this piece of HTML code:

<a href='https://facebook.com/'>Facebook</a>
<a href='https://google.ca/'>Google</a>
<input type='text' placeholder='an input box'>

We can use this JavaScript:

function checkTabPress(e) {
    'use strict';
    var ele = document.activeElement;

    if (e.keyCode === 9 && ele.nodeName.toLowerCase() === 'a') {
        console.log(ele.href);
    }
}

document.addEventListener('keyup', function (e) {
    checkTabPress(e);
}, false);

I have bound an event listener to the document element for the keyUp event, which triggers a function to check if the Tab key was pressed (or technically, released).

The function checks the currently focused element and whether the NodeName is a. If so, it enters the if block and, in my case, writes the value of the href property to the JavaScript console.

Here's a jsFiddle

Instant run in Android Studio 2.0 (how to turn off)

Using Android Studio newest version and update Android Plugin to 'newest alpha version`, I can disable Instant Run: Android studio Instant Run view with Version highlighted Android studio Project view with Android Plugin Version highlighted

Try to update Android Studio.

How does MySQL process ORDER BY and LIMIT in a query?

You can use this code SELECT article FROM table1 ORDER BY publish_date LIMIT 0,10 where 0 is a start limit of record & 10 number of record

How to dismiss keyboard for UITextView with return key?

Add this method in your view controller.

Swift:

func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
    if text == "\n" {
        textView.resignFirstResponder()
        return false
    }
    return true
}

This method also can be helpful for you:

/**
Dismiss keyboard when tapped outside the keyboard or textView

:param: touches the touches
:param: event   the related event
*/
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    if let touch = touches.anyObject() as? UITouch {
        if touch.phase == UITouchPhase.Began {
            textField?.resignFirstResponder()
        }
    }
}

htaccess Access-Control-Allow-Origin

Add an .htaccess file with the following directives to your fonts folder, if have problems accessing your fonts. Can easily be modified for use with .css or .js files.

<FilesMatch "\.(eot|ttf|otf|woff)$">
    Header set Access-Control-Allow-Origin "*"
</FilesMatch>

Delete ActionLink with confirm dialog

Don't confuse routeValues with htmlAttributes. You probably want this overload:

<%= Html.ActionLink(
    "Delete", 
    "Delete", 
    new { id = item.storyId }, 
    new { onclick = "return confirm('Are you sure you wish to delete this article?');" }) 
%>

How to force link from iframe to be opened in the parent window

I found the best solution was to use the base tag. Add the following to the head of the page in the iframe:

<base target="_parent">

This will load all links on the page in the parent window. If you want your links to load in a new window, use:

<base target="_blank">

Browser Support

How can I develop for iPhone using a Windows development machine?

I use Flutter. I develop on my Windows machine and test on an Android emulator. When I'm ready to test on iOS, I run the code on macOS. From my experience, a Flutter app runs exactly the same on Android and iOS. If you don't have a Mac, you can download VirtualBox and install macOS on it. On VirtualBox, macOS runs exactly as it does on a real Mac, and you can build your app on it.

How do I clear all variables in the middle of a Python script?

No, you are best off restarting the interpreter

IPython is an excellent replacement for the bundled interpreter and has the %reset command which usually works

What is polymorphism, what is it for, and how is it used?

Polymorphism gives you the ability to create one module calling another, and yet have the compile time dependency point against the flow of control instead of with the flow of control.

By using polymorphism, a high level module does not depend on low-level module. Both depend on abstractions. This helps us to apply the dependency inversion principle(https://en.wikipedia.org/wiki/Dependency_inversion_principle).

This is where I found the above definition. Around 50 minutes into the video the instructor explains the above. https://www.youtube.com/watch?v=TMuno5RZNeE

What is the meaning of "this" in Java?

(I know Im late but shh Im being the sneaky boi you never saw me)

The this keyword in most Object Oriented programming languages if not all means that its a reference towards the current object instance of that class. It's essentially the same thing as calling on that object from outside of the method by name. That probably made no sense so Ill elaborate:

Outside of the class, in order to call something within that instance of the object, for example a say you have an object called object and you want to get a field you would need to use

object.field

Say for instance you are trying to access object.field from inside of your class in say, your constructor for example, you could use

this.field

The this keyword essentially replaces the object name keyword when being called inside of the class. There usually isn't much of a reason to do this outside of if you have two variables of the same name one of which being a field of the class and the other just being a variable inside of a method, it helps decipher between the two. For example if you have this: (Hah, get it? this? Hehe .... just me? okay :( I'll leave now)

public String Name;
//Constructor for {object} class
public object(String Name){
    Name = Name;
}

That would cause some problems, the compiler wouldn't be able to know the difference between the Name variable defined in the parameters for the constructor and the Name variable inside of your class' field declarations so it would instead assign the Name parameter to.... the value of the Name parameter which does nothing beneficial and literally has no purpose. This is a common issue that most newer programs do and I was a victim of as well. Anyways, the correct way to define this parameter would be to use:

public String Name;
//Constructor for {object} class
public object(String Name){
    this.Name = Name;
}

This way, the compiler knows the Name variable you are trying to assign is a part of the class and not a part of the method and assigns it correctly, meaning it assigns the Name field to whatever you put into the constructor.

To sum it up, it essentially references a field of the object instance of the class you are working on, hence it being the keyword "this", meaning its this object, or this instance. Its a good practice to use this when calling a field of your class rather than just using the name to avoid possible bugs that are difficult to find as the compiler runs right over them.

Is a slash ("/") equivalent to an encoded slash ("%2F") in the path portion of an HTTP URL

The story of %2F vs / was that, according to the initial W3C recommendations, slashes «must imply a hierarchical structure»:

The slash ("/", ASCII 2F hex) character is reserved for the delimiting of substrings whose relationship is hierarchical. This enables partial forms of the URI.

Example 2

The URIs

http://www.w3.org/albert/bertram/marie-claude

and

http://www.w3.org/albert/bertram%2Fmarie-claude

are NOT identical, as in the second case the encoded slash does not have hierarchical significance.

T-SQL loop over query results

You could do something like this:

create procedure test
as
BEGIN

    create table #ids
    (
        rn int,
        id int
    )

    insert into #ids (rn, id)
    select distinct row_number() over(order by id) as rn, id
    from table

    declare @id int
    declare @totalrows int = (select count(*) from #ids)
    declare @currentrow int = 0

    while @currentrow <  @totalrows  
    begin 
        set @id = (select id from #ids where rn = @currentrow)

        exec stored_proc @varName=@id, @otherVarName='test'

        set @currentrow = @currentrow +1
    end  

END

Convert string to title case with JavaScript

function toTitleCase(str) {
  var strnew = "";
  var i = 0;

  for (i = 0; i < str.length; i++) {
    if (i == 0) {
      strnew = strnew + str[i].toUpperCase();
    } else if (i != 0 && str[i - 1] == " ") {
      strnew = strnew + str[i].toUpperCase();
    } else {
      strnew = strnew + str[i];
    }
  }

  alert(strnew);
}

toTitleCase("hello world how are u");

What is the difference between syntax and semantics in programming languages?

The syntax of a programming language is the form of its expressions, statements, and program units. Its semantics is the meaning of those expressions, statements, and program units. For example, the syntax of a Java while statement is

while (boolean_expr) statement

The semantics of this statement form is that when the current value of the Boolean expression is true, the embedded statement is executed. Then control implicitly returns to the Boolean expression to repeat the process. If the Boolean expression is false, control transfers to the statement following the while construct.

Plotting dates on the x-axis with Python's matplotlib

You can do this more simply using plot() instead of plot_date().

First, convert your strings to instances of Python datetime.date:

import datetime as dt

dates = ['01/02/1991','01/03/1991','01/04/1991']
x = [dt.datetime.strptime(d,'%m/%d/%Y').date() for d in dates]
y = range(len(x)) # many thanks to Kyss Tao for setting me straight here

Then plot:

import matplotlib.pyplot as plt
import matplotlib.dates as mdates

plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator())
plt.plot(x,y)
plt.gcf().autofmt_xdate()

Result:

enter image description here

Evenly space multiple views within a container view

I wanted to horizontally align 5 images, so I ended up following Mete's response with a small difference.

The first image will be centered horizontally in container equal to 0 and a multiplier of 1:5:

first image

The second image will be centered horizontally in container equal to 0 and a multiplier of 3:5: second image

And like that for the rest of the images. For example, the fifth (and last) image will be centered horizontally in container equal to 0 and a multiplier of 9:5: last image

As Mete explained, the order goes 1, 3, 5, 7, 9, etc. The positions follow the same logic: the first position is 1, then space, then the next position 3, and so on.

Bootstrap center heading

Per your comments, to center all headings all you have to do is add text-align:center to all of them at the same time, like so:

CSS

    h1, h2, h3, h4, h5, h6 {
        text-align: center;
    }

php: how to get associative array key from numeric index?

Expanding on Ram Dane's answer, the key function is an alternative way to get the key of the current index of the array. You can create the following function,

    function get_key($array, $index){
      $idx=0;
      while($idx!=$index  && next($array)) $idx++;
      if($idx==$index) return key($array);
      else return '';
    }

iOS - Dismiss keyboard when touching outside of UITextField

Add this code in your ViewController.m file :

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

Location of ini/config files in linux/unix?

  1. Generally system/global config is stored somewhere under /etc.
  2. User-specific config is stored in the user's home directory, often as a hidden file, sometimes as a hidden directory containing non-hidden files (and possibly more subdirectories).

Generally speaking, command line options will override environment variables which will override user defaults which will override system defaults.

How do I set the proxy to be used by the JVM

I am also behind firewall, this worked for me!!

System.setProperty("http.proxyHost", "proxy host addr");
System.setProperty("http.proxyPort", "808");
Authenticator.setDefault(new Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {

        return new PasswordAuthentication("domain\\user","password".toCharArray());
    }
});

URL url = new URL("http://www.google.com/");
URLConnection con = url.openConnection();

BufferedReader in = new BufferedReader(new InputStreamReader(
                    con.getInputStream()));

// Read it ...
String inputLine;
while ((inputLine = in.readLine()) != null)
    System.out.println(inputLine);

in.close();

Does bootstrap have builtin padding and margin classes?

For bootstrap 4 we have new classes named with following notation

m - for classes that set margin
p - for classes that set padding

Specify Top, bottom,left, right, left & right, top & bottom using below letters

t - for classes that set margin-top (mt) or padding-top (pt)
b - for classes that set margin-bottom or padding-bottom
l - for classes that set margin-left or padding-left
r - for classes that set margin-right or padding-right
x - for classes that set both *-left and *-right
y - for classes that set both *-top and *-bottom

Specify size using following numbers

0 - for classes that eliminate the margin or padding by setting it to 0
1 - (by default) for classes that set the margin or padding to $spacer * .25
2 - (by default) for classes that set the margin or padding to $spacer * .5
3 - (by default) for classes that set the margin or padding to $spacer
4 - (by default) for classes that set the margin or padding to $spacer * 1.5
5 - (by default) for classes that set the margin or padding to $spacer * 3

Actual Code from bootstrap 4 css file

.mt-0 {
  margin-top: 0 !important;
}

.ml-1 {
  margin-left: ($spacer * .25) !important;
}

.px-2 {
  padding-left: ($spacer * .5) !important;
  padding-right: ($spacer * .5) !important;
}

.p-3 {
  padding: $spacer !important;
}

Usage

So when you need some padding left just add any class from pl-0 to pl-5 based on your need

If you need margin on top just add any class from mt-0 to mt-5 based on your need

<div class="col-sm-6 mt-5"> this div will have margin top added </div>
<div class="col-sm-6 pl-5"> this div will have padding left added </div>

Bootstrap 4 CDN

How to import Google Web Font in CSS file?

  1. Just go to https://fonts.google.com/
  2. Add font by clicking +
  3. Go to selected font > Embed > @IMPORT > copy url and paste in your .css file above body tag.
  4. It's done.

Syntax for if/else condition in SCSS mixin

You can assign default parameter values inline when you first create the mixin:

@mixin clearfix($width: 'auto') {

  @if $width == 'auto' {

    // if width is not passed, or empty do this

  } @else {

    display: inline-block;
    width: $width;

  }
}

Extract values in Pandas value_counts()

#!/usr/bin/env python

import pandas as pd

# Make example dataframe
df = pd.DataFrame([(1, 'Germany'),
                   (2, 'France'),
                   (3, 'Indonesia'),
                   (4, 'France'),
                   (5, 'France'),
                   (6, 'Germany'),
                   (7, 'UK'),
                   ],
                  columns=['groupid', 'country'],
                  index=['a', 'b', 'c', 'd', 'e', 'f', 'g'])

# What you're looking for
values = df['country'].value_counts().keys().tolist()
counts = df['country'].value_counts().tolist()

Now, print(df['country'].value_counts()) gives:

France       3
Germany      2
UK           1
Indonesia    1

and print(values) gives:

['France', 'Germany', 'UK', 'Indonesia']

and print(counts) gives:

[3, 2, 1, 1]

How to filter Pandas dataframe using 'in' and 'not in' like in SQL

A trick if you want to keep the order of the list:

df = pd.DataFrame({'country': ['US', 'UK', 'Germany', 'China']})
countries_to_keep = ['Germany', 'US']


ind=[df.index[df['country']==i].tolist() for i in countries_to_keep]
flat_ind=[item for sublist in ind for item in sublist]

df.reindex(flat_ind)

   country
2  Germany
0       US

JavaScript equivalent to printf/String.Format

I didn't see pyformat in the list so I thought I'd throw it in:

console.log(pyformat( 'The {} {} jumped over the {}'
                , ['brown' ,'fox' ,'foobar']
                ))
console.log(pyformat('The {0} {1} jumped over the {1}'
                , ['brown' ,'fox' ,'foobar']
                ))
console.log(pyformat('The {color} {animal} jumped over the {thing}'
                , [] ,{color: 'brown' ,animal: 'fox' ,thing: 'foobaz'}
                ))

How to replace multiple white spaces with one white space

VB.NET

Linha.Split(" ").ToList().Where(Function(x) x <> " ").ToArray

C#

Linha.Split(" ").ToList().Where(x => x != " ").ToArray();

Enjoy the power of LINQ =D

codeigniter model error: Undefined property

It solved throung second parameter in Model load:

$this->load->model('user','User');

first parameter is the model's filename, and second it defining the name of model to be used in the controller:

function alluser() 
{
$this->load->model('User');
$result = $this->User->showusers();
}

Create a date from day month and year with T-SQL

I personally Prefer Substring as it provide cleansing options and ability to split the string as needed. The assumption is that the data is of the format 'dd, mm, yyyy'.

--2012 and above
SELECT CONCAT (
        RIGHT(REPLACE(@date, ' ', ''), 4)
        ,'-'
        ,RIGHT(CONCAT('00',SUBSTRING(REPLACE(@date, ' ', ''), CHARINDEX(',', REPLACE(@date, ' ', '')) + 1, LEN(REPLACE(@date, ' ', '')) - CHARINDEX(',', REPLACE(@date, ' ', '')) - 5)),2)
        ,'-'
        ,RIGHT(CONCAT('00',SUBSTRING(REPLACE(@date, ' ', ''), 1, CHARINDEX(',', REPLACE(@date, ' ', '')) - 1)),2)
        )

--2008 and below
SELECT   RIGHT(REPLACE(@date, ' ', ''), 4)
        +'-'
        +RIGHT('00'+SUBSTRING(REPLACE(@date, ' ', ''), CHARINDEX(',', REPLACE(@date, ' ', '')) + 1, LEN(REPLACE(@date, ' ', '')) - CHARINDEX(',', REPLACE(@date, ' ', '')) - 5),2)
        +'-'
        +RIGHT('00'+SUBSTRING(REPLACE(@date, ' ', ''), 1, CHARINDEX(',', REPLACE(@date, ' ', '')) - 1),2)

Here is a demonstration of how it can be sued if the data is stored in a column. Needless to say, its ideal to check the result-set before applying to the column

DECLARE @Table TABLE (ID INT IDENTITY(1000,1), DateString VARCHAR(50), DateColumn DATE)

INSERT INTO @Table
SELECT'12, 1, 2007',NULL
UNION
SELECT'15,3, 2007',NULL
UNION
SELECT'18, 11 , 2007',NULL
UNION
SELECT'22 , 11, 2007',NULL
UNION
SELECT'30, 12, 2007  ',NULL

UPDATE @Table
SET DateColumn = CONCAT (
        RIGHT(REPLACE(DateString, ' ', ''), 4)
        ,'-'
        ,RIGHT(CONCAT('00',SUBSTRING(REPLACE(DateString, ' ', ''), CHARINDEX(',', REPLACE(DateString, ' ', '')) + 1, LEN(REPLACE(DateString, ' ', '')) - CHARINDEX(',', REPLACE(DateString, ' ', '')) - 5)),2)
        ,'-'
        ,RIGHT(CONCAT('00',SUBSTRING(REPLACE(DateString, ' ', ''), 1, CHARINDEX(',', REPLACE(DateString, ' ', '')) - 1)),2)
        ) 

SELECT ID,DateString,DateColumn
FROM @Table

Angular 4: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'

I found another solution to get the data. according to the documentation Please check documentation link

In service file add following.

import { Injectable } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';

@Injectable()
export class MoviesService {

  constructor(private db: AngularFireDatabase) {}
  getMovies() {
    this.db.list('/movies').valueChanges();
  }
}

In Component add following.

import { Component, OnInit } from '@angular/core';
import { MoviesService } from './movies.service';

@Component({
  selector: 'app-movies',
  templateUrl: './movies.component.html',
  styleUrls: ['./movies.component.css']
})
export class MoviesComponent implements OnInit {
  movies$;

  constructor(private moviesDb: MoviesService) { 
   this.movies$ = moviesDb.getMovies();
 }

In your html file add following.

<li  *ngFor="let m of movies$ | async">{{ m.name }} </li>

Android: Background Image Size (in Pixel) which Support All Devices

GIMP tool is exactly what you need to create the images for different pixel resolution devices.

Follow these steps:

  1. Open the existing image in GIMP tool.
  2. Go to "Image" menu, and select "Scale Image..."
  3. Use below pixel dimension that you need:

    xxxhdpi: 1280x1920 px

    xxhdpi: 960x1600 px

    xhdpi: 640x960 px

    hdpi: 480x800 px

    mdpi: 320x480 px

    ldpi: 240x320 px

  4. Then "Export" the image from "File" menu.

Import JavaScript file and call functions using webpack, ES6, ReactJS

Named exports:

Let's say you create a file called utils.js, with utility functions that you want to make available for other modules (e.g. a React component). Then you would make each function a named export:

export function add(x, y) {
  return x + y
}

export function mutiply(x, y) {
  return x * y
}

Assuming that utils.js is located in the same directory as your React component, you can use its exports like this:

import { add, multiply } from './utils.js';
...
add(2, 3) // Can be called wherever in your component, and would return 5.

Or if you prefer, place the entire module's contents under a common namespace:

import * as utils from './utils.js'; 
...
utils.multiply(2,3)

Default exports:

If you on the other hand have a module that only does one thing (could be a React class, a normal function, a constant, or anything else) and want to make that thing available to others, you can use a default export. Let's say we have a file log.js, with only one function that logs out whatever argument it's called with:

export default function log(message) {
  console.log(message);
}

This can now be used like this:

import log from './log.js';
...
log('test') // Would print 'test' in the console.

You don't have to call it log when you import it, you could actually call it whatever you want:

import logToConsole from './log.js';
...
logToConsole('test') // Would also print 'test' in the console.

Combined:

A module can have both a default export (max 1), and named exports (imported either one by one, or using * with an alias). React actually has this, consider:

import React, { Component, PropTypes } from 'react';

Vue.js: Conditional class style binding

Why not pass an object to v-bind:class to dynamically toggle the class:

<div v-bind:class="{ disabled: order.cancelled_at }"></div>

This is what is recommended by the Vue docs.

CSS I want a div to be on top of everything

I gonna assumed you making a popup with code from WW3 school, correct? check it css. the .modal one, there're already word z-index there. just change from 1 to 100.

.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    padding-top: 100px; /* Location of the box */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

How to convert numbers between hexadecimal and decimal

To convert from decimal to hex do...

string hexValue = decValue.ToString("X");

To convert from hex to decimal do either...

int decValue = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);

or

int decValue = Convert.ToInt32(hexValue, 16);

Understanding Fragment's setRetainInstance(boolean)

setRetainInstance() - Deprecated

As Fragments Version 1.3.0-alpha01

The setRetainInstance() method on Fragments has been deprecated. With the introduction of ViewModels, developers have a specific API for retaining state that can be associated with Activities, Fragments, and Navigation graphs. This allows developers to use a normal, not retained Fragment and keep the specific state they want retained separate, avoiding a common source of leaks while maintaining the useful properties of a single creation and destruction of the retained state (namely, the constructor of the ViewModel and the onCleared() callback it receives).

Searching a list of objects in Python

[x for x in myList if x.n == 30]               # list of all matches
[x.n_squared for x in myList if x.n == 30]     # property of matches
any(x.n == 30 for x in myList)                 # if there is any matches
[i for i,x in enumerate(myList) if x.n == 30]  # indices of all matches

def first(iterable, default=None):
  for item in iterable:
    return item
  return default

first(x for x in myList if x.n == 30)          # the first match, if any

How do I convert date/time from 24-hour format to 12-hour AM/PM?

I think you can use date() function to achive this

$date = '19:24:15 06/13/2013'; 
echo date('h:i:s a m/d/Y', strtotime($date));

This will output

07:24:15 pm 06/13/2013

Live Sample

h is used for 12 digit time
i stands for minutes
s seconds
a will return am or pm (use in uppercase for AM PM)
m is used for months with digits
d is used for days in digit
Y uppercase is used for 4 digit year (use it lowercase for two digit)

Updated

This is with DateTime

$date = new DateTime('19:24:15 06/13/2013');
echo $date->format('h:i:s a m/d/Y') ;

Live Sample

Removing NA in dplyr pipe

I don't think desc takes an na.rm argument... I'm actually surprised it doesn't throw an error when you give it one. If you just want to remove NAs, use na.omit (base) or tidyr::drop_na:

outcome.df %>%
  na.omit() %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

library(tidyr)
outcome.df %>%
  drop_na() %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

If you only want to remove NAs from the HeartAttackDeath column, filter with is.na, or use tidyr::drop_na:

outcome.df %>%
  filter(!is.na(HeartAttackDeath)) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

outcome.df %>%
  drop_na(HeartAttackDeath) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

As pointed out at the dupe, complete.cases can also be used, but it's a bit trickier to put in a chain because it takes a data frame as an argument but returns an index vector. So you could use it like this:

outcome.df %>%
  filter(complete.cases(.)) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

ResultSet exception - before start of result set

It's better if you create a class that has all the query methods, inclusively, in a different package, so instead of typing all the process in every class, you just call the method from that class.

Determine if running on a rooted device

You can do this by following code :

public boolean getRootInfo() {
    if (checkRootFiles() || checkTags()) {
        return true;
    }
    return false;
}

private boolean checkRootFiles() {
    boolean root = false;
    String[] paths = {"/system/app/Superuser.apk", "/sbin/su", "/system/bin/su", "/system/xbin/su", "/data/local/xbin/su", "/data/local/bin/su", "/system/sd/xbin/su",
            "/system/bin/failsafe/su", "/data/local/su", "/su/bin/su"};
    for (String path : paths) {
        root = new File(path).exists();
        if (root)
            break;
    }
    return root;
}

private boolean checkTags() {
    String tag = Build.TAGS;
    return tag != null && tag.trim().contains("test-keys");
}

You can also check this library RootBeer.

How to change Hash values?

This will do it:

my_hash.each_with_object({}) { |(key, value), hash| hash[key] = value.upcase }

As opposed to inject the advantage is that you are in no need to return the hash again inside the block.

Deep cloning objects

Q. Why would I choose this answer?

  • Choose this answer if you want the fastest speed .NET is capable of.
  • Ignore this answer if you want a really, really easy method of cloning.

In other words, go with another answer unless you have a performance bottleneck that needs fixing, and you can prove it with a profiler.

10x faster than other methods

The following method of performing a deep clone is:

  • 10x faster than anything that involves serialization/deserialization;
  • Pretty darn close to the theoretical maximum speed .NET is capable of.

And the method ...

For ultimate speed, you can use Nested MemberwiseClone to do a deep copy. Its almost the same speed as copying a value struct, and is much faster than (a) reflection or (b) serialization (as described in other answers on this page).

Note that if you use Nested MemberwiseClone for a deep copy, you have to manually implement a ShallowCopy for each nested level in the class, and a DeepCopy which calls all said ShallowCopy methods to create a complete clone. This is simple: only a few lines in total, see the demo code below.

Here is the output of the code showing the relative performance difference for 100,000 clones:

  • 1.08 seconds for Nested MemberwiseClone on nested structs
  • 4.77 seconds for Nested MemberwiseClone on nested classes
  • 39.93 seconds for Serialization/Deserialization

Using Nested MemberwiseClone on a class almost as fast as copying a struct, and copying a struct is pretty darn close to the theoretical maximum speed .NET is capable of.

Demo 1 of shallow and deep copy, using classes and MemberwiseClone:
  Create Bob
    Bob.Age=30, Bob.Purchase.Description=Lamborghini
  Clone Bob >> BobsSon
  Adjust BobsSon details
    BobsSon.Age=2, BobsSon.Purchase.Description=Toy car
  Proof of deep copy: If BobsSon is a true clone, then adjusting BobsSon details will not affect Bob:
    Bob.Age=30, Bob.Purchase.Description=Lamborghini
  Elapsed time: 00:00:04.7795670,30000000

Demo 2 of shallow and deep copy, using structs and value copying:
  Create Bob
    Bob.Age=30, Bob.Purchase.Description=Lamborghini
  Clone Bob >> BobsSon
  Adjust BobsSon details:
    BobsSon.Age=2, BobsSon.Purchase.Description=Toy car
  Proof of deep copy: If BobsSon is a true clone, then adjusting BobsSon details will not affect Bob:
    Bob.Age=30, Bob.Purchase.Description=Lamborghini
  Elapsed time: 00:00:01.0875454,30000000

Demo 3 of deep copy, using class and serialize/deserialize:
  Elapsed time: 00:00:39.9339425,30000000

To understand how to do a deep copy using MemberwiseCopy, here is the demo project that was used to generate the times above:

// Nested MemberwiseClone example. 
// Added to demo how to deep copy a reference class.
[Serializable] // Not required if using MemberwiseClone, only used for speed comparison using serialization.
public class Person
{
    public Person(int age, string description)
    {
        this.Age = age;
        this.Purchase.Description = description;
    }
    [Serializable] // Not required if using MemberwiseClone
    public class PurchaseType
    {
        public string Description;
        public PurchaseType ShallowCopy()
        {
            return (PurchaseType)this.MemberwiseClone();
        }
    }
    public PurchaseType Purchase = new PurchaseType();
    public int Age;
    // Add this if using nested MemberwiseClone.
    // This is a class, which is a reference type, so cloning is more difficult.
    public Person ShallowCopy()
    {
        return (Person)this.MemberwiseClone();
    }
    // Add this if using nested MemberwiseClone.
    // This is a class, which is a reference type, so cloning is more difficult.
    public Person DeepCopy()
    {
            // Clone the root ...
        Person other = (Person) this.MemberwiseClone();
            // ... then clone the nested class.
        other.Purchase = this.Purchase.ShallowCopy();
        return other;
    }
}
// Added to demo how to copy a value struct (this is easy - a deep copy happens by default)
public struct PersonStruct
{
    public PersonStruct(int age, string description)
    {
        this.Age = age;
        this.Purchase.Description = description;
    }
    public struct PurchaseType
    {
        public string Description;
    }
    public PurchaseType Purchase;
    public int Age;
    // This is a struct, which is a value type, so everything is a clone by default.
    public PersonStruct ShallowCopy()
    {
        return (PersonStruct)this;
    }
    // This is a struct, which is a value type, so everything is a clone by default.
    public PersonStruct DeepCopy()
    {
        return (PersonStruct)this;
    }
}
// Added only for a speed comparison.
public class MyDeepCopy
{
    public static T DeepCopy<T>(T obj)
    {
        object result = null;
        using (var ms = new MemoryStream())
        {
            var formatter = new BinaryFormatter();
            formatter.Serialize(ms, obj);
            ms.Position = 0;
            result = (T)formatter.Deserialize(ms);
            ms.Close();
        }
        return (T)result;
    }
}

Then, call the demo from main:

void MyMain(string[] args)
{
    {
        Console.Write("Demo 1 of shallow and deep copy, using classes and MemberwiseCopy:\n");
        var Bob = new Person(30, "Lamborghini");
        Console.Write("  Create Bob\n");
        Console.Write("    Bob.Age={0}, Bob.Purchase.Description={1}\n", Bob.Age, Bob.Purchase.Description);
        Console.Write("  Clone Bob >> BobsSon\n");
        var BobsSon = Bob.DeepCopy();
        Console.Write("  Adjust BobsSon details\n");
        BobsSon.Age = 2;
        BobsSon.Purchase.Description = "Toy car";
        Console.Write("    BobsSon.Age={0}, BobsSon.Purchase.Description={1}\n", BobsSon.Age, BobsSon.Purchase.Description);
        Console.Write("  Proof of deep copy: If BobsSon is a true clone, then adjusting BobsSon details will not affect Bob:\n");
        Console.Write("    Bob.Age={0}, Bob.Purchase.Description={1}\n", Bob.Age, Bob.Purchase.Description);
        Debug.Assert(Bob.Age == 30);
        Debug.Assert(Bob.Purchase.Description == "Lamborghini");
        var sw = new Stopwatch();
        sw.Start();
        int total = 0;
        for (int i = 0; i < 100000; i++)
        {
            var n = Bob.DeepCopy();
            total += n.Age;
        }
        Console.Write("  Elapsed time: {0},{1}\n\n", sw.Elapsed, total);
    }
    {               
        Console.Write("Demo 2 of shallow and deep copy, using structs:\n");
        var Bob = new PersonStruct(30, "Lamborghini");
        Console.Write("  Create Bob\n");
        Console.Write("    Bob.Age={0}, Bob.Purchase.Description={1}\n", Bob.Age, Bob.Purchase.Description);
        Console.Write("  Clone Bob >> BobsSon\n");
        var BobsSon = Bob.DeepCopy();
        Console.Write("  Adjust BobsSon details:\n");
        BobsSon.Age = 2;
        BobsSon.Purchase.Description = "Toy car";
        Console.Write("    BobsSon.Age={0}, BobsSon.Purchase.Description={1}\n", BobsSon.Age, BobsSon.Purchase.Description);
        Console.Write("  Proof of deep copy: If BobsSon is a true clone, then adjusting BobsSon details will not affect Bob:\n");
        Console.Write("    Bob.Age={0}, Bob.Purchase.Description={1}\n", Bob.Age, Bob.Purchase.Description);                
        Debug.Assert(Bob.Age == 30);
        Debug.Assert(Bob.Purchase.Description == "Lamborghini");
        var sw = new Stopwatch();
        sw.Start();
        int total = 0;
        for (int i = 0; i < 100000; i++)
        {
            var n = Bob.DeepCopy();
            total += n.Age;
        }
        Console.Write("  Elapsed time: {0},{1}\n\n", sw.Elapsed, total);
    }
    {
        Console.Write("Demo 3 of deep copy, using class and serialize/deserialize:\n");
        int total = 0;
        var sw = new Stopwatch();
        sw.Start();
        var Bob = new Person(30, "Lamborghini");
        for (int i = 0; i < 100000; i++)
        {
            var BobsSon = MyDeepCopy.DeepCopy<Person>(Bob);
            total += BobsSon.Age;
        }
        Console.Write("  Elapsed time: {0},{1}\n", sw.Elapsed, total);
    }
    Console.ReadKey();
}

Again, note that if you use Nested MemberwiseClone for a deep copy, you have to manually implement a ShallowCopy for each nested level in the class, and a DeepCopy which calls all said ShallowCopy methods to create a complete clone. This is simple: only a few lines in total, see the demo code above.

Value types vs. References Types

Note that when it comes to cloning an object, there is is a big difference between a "struct" and a "class":

  • If you have a "struct", it's a value type so you can just copy it, and the contents will be cloned (but it will only make a shallow clone unless you use the techniques in this post).
  • If you have a "class", it's a reference type, so if you copy it, all you are doing is copying the pointer to it. To create a true clone, you have to be more creative, and use differences between value types and references types which creates another copy of the original object in memory.

See differences between value types and references types.

Checksums to aid in debugging

  • Cloning objects incorrectly can lead to very difficult-to-pin-down bugs. In production code, I tend to implement a checksum to double check that the object has been cloned properly, and hasn't been corrupted by another reference to it. This checksum can be switched off in Release mode.
  • I find this method quite useful: often, you only want to clone parts of the object, not the entire thing.

Really useful for decoupling many threads from many other threads

One excellent use case for this code is feeding clones of a nested class or struct into a queue, to implement the producer / consumer pattern.

  • We can have one (or more) threads modifying a class that they own, then pushing a complete copy of this class into a ConcurrentQueue.
  • We then have one (or more) threads pulling copies of these classes out and dealing with them.

This works extremely well in practice, and allows us to decouple many threads (the producers) from one or more threads (the consumers).

And this method is blindingly fast too: if we use nested structs, it's 35x faster than serializing/deserializing nested classes, and allows us to take advantage of all of the threads available on the machine.

Update

Apparently, ExpressMapper is as fast, if not faster, than hand coding such as above. I might have to see how they compare with a profiler.

How to compare timestamp dates with date-only parameter in MySQL?

Use

SELECT * FROM table WHERE DATE(2012-05-05 00:00:00) = '2012-05-05' 

How can I reload .emacs after changing it?

I suggest that you don't do this, initially. Instead, start a new emacs session and test whatever changes you made to see if they work correctly. The reason to do it this way is to avoid leaving you in a state where you have an inoperable .emacs file, which fails to load or fails to load cleanly. If you do all of your editing in the original session, and all of your testing in a new session, you'll always have something reliable to comment out offending code.

When you are finally happy with your changes, then go ahead and use one of the other answers to re-load. My personal preference is to eval just the section you've added/changed, and to do that just highlight the region of added/changed code and call M-x eval-region. Doing that minimizes the code that's evaluated, minimizing any unintentional side-effects, as luapyad points out.

Extract the first word of a string in a SQL Server query

Try This:

Select race_id, race_description
, Case patIndex ('%[ /-]%', LTrim (race_description))
    When 0 Then LTrim (race_description)
    Else substring (LTrim (race_description), 1, patIndex ('%[ /-]%', LTrim (race_description)) - 1)
End race_abbreviation

from tbl_races

How do I change the text size in a label widget, python tkinter

Try passing width=200 as additional paramater when creating the Label.

This should work in creating label with specified width.

If you want to change it later, you can use:

label.config(width=200)

As you want to change the size of font itself you can try:

label.config(font=("Courier", 44))

Passing Variable through JavaScript from one html page to another page

There are two pages: Pageone.html :

<script>
var hello = "hi"
location.replace("http://example.com/PageTwo.html?" + hi + "");
</script>

PageTwo.html :

<script>
var link = window.location.href;
link = link.replace("http://example.com/PageTwo.html?","");
document.write("The variable contained this content:" + link + "");
</script>

Hope it helps!

How to get row count in an Excel file using POI library?

Since Sheet.getPhysicalNumberOfRows() does not count empty rows and Sheet.getLastRowNum() returns 0 both if there is one row or no rows, I use a combination of the two methods to accurately calculate the total number of rows.

int rowTotal = sheet.getLastRowNum();

if ((rowTotal > 0) || (sheet.getPhysicalNumberOfRows() > 0)) {
    rowTotal++;
}

Note: This will treat a spreadsheet with one empty row as having none but for most purposes this is probably okay.

Parse JSON from HttpURLConnection object

You can get raw data using below method. BTW, this pattern is for Java 6. If you are using Java 7 or newer, please consider try-with-resources pattern.

public String getJSON(String url, int timeout) {
    HttpURLConnection c = null;
    try {
        URL u = new URL(url);
        c = (HttpURLConnection) u.openConnection();
        c.setRequestMethod("GET");
        c.setRequestProperty("Content-length", "0");
        c.setUseCaches(false);
        c.setAllowUserInteraction(false);
        c.setConnectTimeout(timeout);
        c.setReadTimeout(timeout);
        c.connect();
        int status = c.getResponseCode();

        switch (status) {
            case 200:
            case 201:
                BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line+"\n");
                }
                br.close();
                return sb.toString();
        }

    } catch (MalformedURLException ex) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
    } finally {
       if (c != null) {
          try {
              c.disconnect();
          } catch (Exception ex) {
             Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
          }
       }
    }
    return null;
}

And then you can use returned string with Google Gson to map JSON to object of specified class, like this:

String data = getJSON("http://localhost/authmanager.php");
AuthMsg msg = new Gson().fromJson(data, AuthMsg.class);
System.out.println(msg);

There is a sample of AuthMsg class:

public class AuthMsg {
    private int code;
    private String message;

    public int getCode() {
        return code;
    }
    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
}

JSON returned by http://localhost/authmanager.php must look like this:

{"code":1,"message":"Logged in"}

Regards

Eclipse - debugger doesn't stop at breakpoint

If you are on Eclipse,

Right click on your project folder under "Package Explorer".

Goto Source -> Clean up and choose your project.

This will cleanup any mess and your break-point should work now.

Get current date in DD-Mon-YYY format in JavaScript/Jquery

Here's a simple solution, using TypeScript:

  convertDateStringToDate(dateStr) {
    //  Convert a string like '2020-10-04T00:00:00' into '4/Oct/2020'
    let months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
    let date = new Date(dateStr);
    let str = date.getDate()
                + '/' + months[date.getMonth()]
                + '/' + date.getFullYear()
    return str;
  }

(Yeah, I know the question was about JavaScript, but I'm sure I won't be the only Angular developer coming across this article !)

Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'

In your controller add the following:

@RequestParam(value = "_csrf", required = false) String csrf

And on jsp page add

<form:form modelAttribute="someName" action="someURI?${_csrf.parameterName}=${_csrf.token}

How to check that a string is parseable to a double?

You can always wrap Double.parseDouble() in a try catch block.

try
{
  Double.parseDouble(number);
}
catch(NumberFormatException e)
{
  //not a double
}

How to convert a string of numbers to an array of numbers?

As a variant you can use combiantion _.map and _.ary methods from the lodash library. Whole transformation will be a more compact. Here is example from the official documentation:

_.map(['6', '8', '10'], _.ary(parseInt, 1));
// ? [6, 8, 10]

How to open .SQLite files

SQLite is database engine, .sqlite or .db should be a database. If you don't need to program anything, you can use a GUI like sqlitebrowser or anything like that to view the database contents.

There is also spatialite, https://www.gaia-gis.it/fossil/spatialite_gui/index

Exception in thread "main" java.lang.UnsupportedClassVersionError: a (Unsupported major.minor version 51.0)

I had this problem, after installing jdk7 next to Java 6. The binaries were correctly updated using update-alternatives --config java to jdk7, but the $JAVA_HOME environment variable still pointed to the old directory of Java 6.

Rollback to an old Git commit in a public repo

Here is an example to do that

    cd /yourprojects/project-acme 


    git checkout efc11170c78 .

Playing m3u8 Files with HTML Video Tag

Use Flowplayer:

<link rel="stylesheet" href="//releases.flowplayer.org/7.0.4/commercial/skin/skin.css">
    <style>

   </style>
   <script src="//code.jquery.com/jquery-1.12.4.min.js"></script>
  <script src="//releases.flowplayer.org/7.0.4/commercial/flowplayer.min.js"></script>
  <script src="//releases.flowplayer.org/hlsjs/flowplayer.hlsjs.min.js"></script> 
  <script>
  flowplayer(function (api) {
    api.on("load", function (e, api, video) {
      $("#vinfo").text(api.engine.engineName + " engine playing " + video.type);
    }); });
  </script>

<div class="flowplayer fixed-controls no-toggle no-time play-button obj"
      style="    width: 85.5%;
    height: 80%;
    margin-left: 7.2%;
    margin-top: 6%;
    z-index: 1000;" data-key="$812975748999788" data-live="true" data-share="false" data-ratio="0.5625"  data-logo="">
      <video autoplay="true" stretch="true">

         <source type="application/x-mpegurl" src="http://live.wmncdn.net/safaritv2/live2.stream/index.m3u8">
      </video>   
   </div>

Different methods are available in flowplayer.org website.

Why is quicksort better than mergesort?

While they're both in the same complexity class, that doesn't mean they both have the same runtime. Quicksort is usually faster than mergesort, just because it's easier to code a tight implementation and the operations it does can go faster. It's because that quicksort is generally faster that people use it instead of mergesort.

However! I personally often will use mergesort or a quicksort variant that degrades to mergesort when quicksort does poorly. Remember. Quicksort is only O(n log n) on average. It's worst case is O(n^2)! Mergesort is always O(n log n). In cases where realtime performance or responsiveness is a must and your input data could be coming from a malicious source, you should not use plain quicksort.

DataTables warning: Requested unknown parameter '0' from the data source for row '0'

You're using an array of objects. Can you use a two dimensional array instead?

http://www.datatables.net/examples/data_sources/js_array.html

See this jsfiddle: http://jsfiddle.net/QhYse/

I used an array like this and it worked fine:

var data = [
    ["UpdateBootProfile","PASS","00:00:00",[]] ,
    ["NRB Boot","PASS","00:00:50.5000000",[{"TestName":"TOTAL_TURN_ON_TIME","Result":"PASS","Value":"50.5","LowerLimit":"NaN","UpperLimit":"NaN","ComparisonType":"nctLOG","Units":"SECONDS"}]] ,
    ["NvMgrCommit","PASS","00:00:00",[]] ,
    ["SyncNvToEFS","PASS","00:00:01.2500000",[]]
];

Edit to include array of objects

There's a possible solution from this question: jQuery DataTables fnrender with objects

This jsfiddle http://jsfiddle.net/j2C7j/ uses an array of objects. To not get the error I had to pad it with 3 blank values - less than optimal, I know. You may find a better way with fnRender, please post if you do.

var data = [
   ["","","", {"Name":"UpdateBootProfile","Result":"PASS","ExecutionTime":"00:00:00","Measurement":[]} ]

];

$(function() {
        var testsTable = $('#tests').dataTable({
                bJQueryUI: true,
                aaData: data,
                aoColumns: [
                        { mData: 'Name', "fnRender": function( oObj ) { return oObj.aData[3].Name}},
                        { mData: 'Result' ,"fnRender": function( oObj ) { return oObj.aData[3].Result }},
                        { mData: 'ExecutionTime',"fnRender": function( oObj ) { return oObj.aData[3].ExecutionTime } }
                ]
        });
});

Use images instead of radio buttons

Images can be placed in place of radio buttons by using label and span elements.

   <div class="customize-radio">
        <label>Favourite Smiley</label><br>
        <label for="hahaha">
        <input type="radio" name="smiley" id="hahaha">
        <span class="haha-img"></span>
        HAHAHA
        </label>
        <label for="kiss">
        <input type="radio" name="smiley" id="kiss">
        <span class="kiss-img"></span>
        Kiss
        </label>
        <label for="tongueOut">
        <input type="radio" name="smiley" id="tongueOut">
        <span class="tongueout-img"></span>
        TongueOut
        </label>
    </div>

Radio button should be hidden,

.customize-radio label > input[type = 'radio'] {
    visibility: hidden;
    position: absolute;
}

Image can be given in the span tag,

.customize-radio label > input[type = 'radio'] ~ span{
    cursor: pointer;
    width: 27px;
    height: 24px;
    display: inline-block;
    background-size: 27px 24px;
    background-repeat: no-repeat;
}
.haha-img {
    background-image: url('hahabefore.png');
}

.kiss-img{
    background-image: url('kissbefore.png');
}
.tongueout-img{
    background-image: url('tongueoutbefore.png');
}

To change the image on click of radio button, add checked state to the input tag,

.customize-radio label > input[type = 'radio']:checked ~ span.haha-img{
     background-image: url('haha.png');
}
.customize-radio label > input[type = 'radio']:checked ~ span.kiss-img{
    background-image: url('kiss.png');
}
.customize-radio label > input[type = 'radio']:checked ~ span.tongueout-img{
        background-image: url('tongueout.png');
}

If you have any queries, Refer to the following link, As I have taken solution from the below blog, http://frontendsupport.blogspot.com/2018/06/cool-radio-buttons-with-images.html

Strip out HTML and Special Characters

Probably better here for a regex replace

// Strip HTML Tags
$clear = strip_tags($des);
// Clean up things like &amp;
$clear = html_entity_decode($clear);
// Strip out any url-encoded stuff
$clear = urldecode($clear);
// Replace non-AlNum characters with space
$clear = preg_replace('/[^A-Za-z0-9]/', ' ', $clear);
// Replace Multiple spaces with single space
$clear = preg_replace('/ +/', ' ', $clear);
// Trim the string of leading/trailing space
$clear = trim($clear);

Or, in one go

$clear = trim(preg_replace('/ +/', ' ', preg_replace('/[^A-Za-z0-9 ]/', ' ', urldecode(html_entity_decode(strip_tags($des))))));

Get all column names of a DataTable into string array using (LINQ/Predicate)

Use

var arrayNames = (from DataColumn x in dt.Columns
                  select x.ColumnName).ToArray();

How to correctly set Http Request Header in Angular 2

Your parameter for the request options in http.put() should actually be of type RequestOptions. Try something like this:

let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('authentication', `${student.token}`);

let options = new RequestOptions({ headers: headers });
return this.http
    .put(url, JSON.stringify(student), options)

How to use code to open a modal in Angular 2?

The Way i used to do it without lots of coding is.. I have the hidden button with the id="employeeRegistered"

On my .ts file I import ElementRef from '@angular/core'

Then after I process everything on my (click) method do as follow:

this.el.nativeElement.querySelector('#employeeRegistered').click();

then the modal displays as expected..

java.nio.file.Path for a classpath resource

Read a File from resources folder using NIO, in java8

public static String read(String fileName) {

        Path path;
        StringBuilder data = new StringBuilder();
        Stream<String> lines = null;
        try {
            path = Paths.get(Thread.currentThread().getContextClassLoader().getResource(fileName).toURI());
            lines = Files.lines(path);
        } catch (URISyntaxException | IOException e) {
            logger.error("Error in reading propertied file " + e);
            throw new RuntimeException(e);
        }

        lines.forEach(line -> data.append(line));
        lines.close();
        return data.toString();
    }

Angular error: "Can't bind to 'ngModel' since it isn't a known property of 'input'"

After spending hours on this issue found solution here

import { FormsModule, ReactiveFormsModule } from '@angular/forms';
    
@NgModule({
    imports: [
         FormsModule,
         ReactiveFormsModule      
    ]
})

Copying a local file from Windows to a remote server using scp

I have found it easiest to use a graphical interface on windows (I recommend mobaXTerm it has ssh, scp, ftp, remote desktop, and many more) but if you are set on command line I would recommend cd'ing into the directory with the source folder then
scp -r yourFolder username@server:/path/to/dir
the -r indicates recursive to be used on directories

Python [Errno 98] Address already in use

$ ps -fA | grep python
501 81211 12368   0  10:11PM ttys000    0:03.12  
python -m SimpleHTTPServer

$ kill 81211

Refresh a page using PHP

header('Location: .'); seems to refresh the page in Chrome, Firefox, Edge, and Internet Explorer 11.

Java function for arrays like PHP's join()?

In case you're using Functional Java library and for some reason can't use Streams from Java 8 (which might be the case when using Android + Retrolambda plugin), here is a functional solution for you:

String joinWithSeparator(List<String> items, String separator) {
    return items
            .bind(id -> list(separator, id))
            .drop(1)
            .foldLeft(
                    (result, item) -> result + item,
                    ""
            );
}

Note that it's not the most efficient approach, but it does work good for small lists.

Easiest way to read from and write to files

These are the best and most commonly used methods for writing to and reading from files:

using System.IO;

File.AppendAllText(sFilePathAndName, sTextToWrite);//add text to existing file
File.WriteAllText(sFilePathAndName, sTextToWrite);//will overwrite the text in the existing file. If the file doesn't exist, it will create it. 
File.ReadAllText(sFilePathAndName);

The old way, which I was taught in college was to use stream reader/stream writer, but the File I/O methods are less clunky and require fewer lines of code. You can type in "File." in your IDE (make sure you include the System.IO import statement) and see all the methods available. Below are example methods for reading/writing strings to/from text files (.txt.) using a Windows Forms App.

Append text to an existing file:

private void AppendTextToExistingFile_Click(object sender, EventArgs e)
{
    string sTextToAppend = txtMainUserInput.Text;
    //first, check to make sure that the user entered something in the text box.
    if (sTextToAppend == "" || sTextToAppend == null)
    {MessageBox.Show("You did not enter any text. Please try again");}
    else
    {
        string sFilePathAndName = getFileNameFromUser();// opens the file dailog; user selects a file (.txt filter) and the method returns a path\filename.txt as string.
        if (sFilePathAndName == "" || sFilePathAndName == null)
        {
            //MessageBox.Show("You cancalled"); //DO NOTHING
        }
        else 
        {
            sTextToAppend = ("\r\n" + sTextToAppend);//create a new line for the new text
            File.AppendAllText(sFilePathAndName, sTextToAppend);
            string sFileNameOnly = sFilePathAndName.Substring(sFilePathAndName.LastIndexOf('\\') + 1);
            MessageBox.Show("Your new text has been appended to " + sFileNameOnly);
        }//end nested if/else
    }//end if/else

}//end method AppendTextToExistingFile_Click

Get file name from the user via file explorer/open file dialog (you will need this to select existing files).

private string getFileNameFromUser()//returns file path\name
{
    string sFileNameAndPath = "";
    OpenFileDialog fd = new OpenFileDialog();
    fd.Title = "Select file";
    fd.Filter = "TXT files|*.txt";
    fd.InitialDirectory = Environment.CurrentDirectory;
    if (fd.ShowDialog() == DialogResult.OK)
    {
        sFileNameAndPath = (fd.FileName.ToString());
    }
    return sFileNameAndPath;
}//end method getFileNameFromUser

Get text from an existing file:

private void btnGetTextFromExistingFile_Click(object sender, EventArgs e)
{
    string sFileNameAndPath = getFileNameFromUser();
    txtMainUserInput.Text = File.ReadAllText(sFileNameAndPath); //display the text
}

Python - Dimension of Data Frame

df.shape, where df is your DataFrame.

READ_EXTERNAL_STORAGE permission for Android

Please Check below code that using that You can find all Music Files from sdcard :

public class MainActivity extends Activity{

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

}

public void getAllSongsFromSDCARD() {
    String[] STAR = { "*" };
    Cursor cursor;
    Uri allsongsuri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";

    cursor = managedQuery(allsongsuri, STAR, selection, null, null);

    if (cursor != null) {
        if (cursor.moveToFirst()) {
            do {
                String song_name = cursor
                        .getString(cursor
                                .getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
                int song_id = cursor.getInt(cursor
                        .getColumnIndex(MediaStore.Audio.Media._ID));

                String fullpath = cursor.getString(cursor
                        .getColumnIndex(MediaStore.Audio.Media.DATA));

                String album_name = cursor.getString(cursor
                        .getColumnIndex(MediaStore.Audio.Media.ALBUM));
                int album_id = cursor.getInt(cursor
                        .getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));

                String artist_name = cursor.getString(cursor
                        .getColumnIndex(MediaStore.Audio.Media.ARTIST));
                int artist_id = cursor.getInt(cursor
                        .getColumnIndex(MediaStore.Audio.Media.ARTIST_ID));
                System.out.println("sonng name"+fullpath);
            } while (cursor.moveToNext());

        }
        cursor.close();
    }
}


}

I have also added following line in the AndroidManifest.xml file as below:

<uses-sdk
    android:minSdkVersion="16"
    android:targetSdkVersion="17" />

<uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

AJAX in Chrome sending OPTIONS instead of GET/POST/PUT/DELETE?

If it is possible pass the params through regular GET/POST with a different name and let your server side code handles it.

I had a similar issue with my own proxy to bypass CORS and I got the same error of POST->OPTION in Chrome. It was the Authorization header in my case ("x-li-format" and "X-UserName" here in your case.) I ended up passing it in a dummy format (e.g. AuthorizatinJack in GET) and I changed the code for my proxy to turn that into a header when making the call to the destination. Here it is in PHP:

if (isset($_GET['AuthorizationJack'])) {
    $request_headers[] = "Authorization: Basic ".$_GET['AuthorizationJack'];
}

VBA: Convert Text to Number

Use the below function (changing [E:E] to the appropriate range for your needs) to circumvent this issue (or change to any other format such as "mm/dd/yyyy"):

[E:E].Select
With Selection
    .NumberFormat = "General"
    .Value = .Value
End With

P.S. In my experience, this VBA solution works SIGNIFICANTLY faster on large data sets and is less likely to crash Excel than using the 'warning box' method.

How to delete Tkinter widgets from a window?


clear_btm=Button(master,text="Clear") #this button will delete the widgets 
clear_btm["command"] = lambda one = button1, two = text1, three = entry1: clear(one,two,three) #pass the widgets
clear_btm.pack()

def clear(*widgets):
    for widget in widgets:
        widget.destroy() #finally we are deleting the widgets.

Comparing floating point number to zero

You can use std::nextafter with a fixed factor of the epsilon of a value like the following:

bool isNearlyEqual(double a, double b)
{
  int factor = /* a fixed factor of epsilon */;

  double min_a = a - (a - std::nextafter(a, std::numeric_limits<double>::lowest())) * factor;
  double max_a = a + (std::nextafter(a, std::numeric_limits<double>::max()) - a) * factor;

  return min_a <= b && max_a >= b;
}

CodeIgniter activerecord, retrieve last insert id?

$this->db->insert_id();

Returns the insert ID number when performing database inserts

Query Helper Methods for codeigniter-3

Padding characters in printf

Pure Bash. Use the length of the value of 'PROC_NAME' as offset for the fixed string 'line':

line='----------------------------------------'
PROC_NAME='abc'
printf "%s %s [UP]\n" $PROC_NAME "${line:${#PROC_NAME}}"
PROC_NAME='abcdef'
printf "%s %s [UP]\n" $PROC_NAME "${line:${#PROC_NAME}}"

This gives

abc ------------------------------------- [UP]
abcdef ---------------------------------- [UP]

XMLHttpRequest cannot load file. Cross origin requests are only supported for HTTP

This error is happening because you are just opening html documents directly from the browser. To fix this you will need to serve your code from a webserver and access it on localhost. If you have Apache setup, use it to serve your files. Some IDE's have built in web servers, like JetBrains IDE's, Eclipse...

If you have Node.Js setup then you can use http-server. Just run npm install http-server -g and you will be able to use it in terminal like http-server C:\location\to\app. Kirill Fuchs

How to efficiently concatenate strings in go

package main

import (
"fmt"
)

func main() {
    var str1 = "string1"
    var str2 = "string2"
    result := make([]byte, 0)
    result = append(result, []byte(str1)...)
    result = append(result, []byte(str2)...)
    result = append(result, []byte(str1)...)
    result = append(result, []byte(str2)...)

    fmt.Println(string(result))
}

Objective-C: Extract filename from path string

At the risk of being years late and off topic - and notwithstanding @Marc's excellent insight, in Swift it looks like:

let basename = NSURL(string: "path/to/file.ext")?.URLByDeletingPathExtension?.lastPathComponent

The value violated the integrity constraints for the column

You can replace the values "null" from the original file & field/column.

How do I convert a C# List<string[]> to a Javascript array?

Here's how you accomplish that:

//View.cshtml
<script type="text/javascript">
    var arrayOfArrays = JSON.parse('@Html.Raw(Json.Encode(Model.Addresses))');
</script>

Select 2 columns in one and combine them

Your syntax should work, maybe add a space between the colums like

SELECT something + ' ' + somethingElse as onlyOneColumn FROM someTable

Initializing IEnumerable<string> In C#

You cannot instantiate an interface - you must provide a concrete implementation of IEnumerable.

How are Anonymous inner classes used in Java?

I use them sometimes as a syntax hack for Map instantiation:

Map map = new HashMap() {{
   put("key", "value");
}};

vs

Map map = new HashMap();
map.put("key", "value");

It saves some redundancy when doing a lot of put statements. However, I have also run into problems doing this when the outer class needs to be serialized via remoting.

SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified

Goto window+R and type services.msc and press enter.

Then start SQL server manually if not automatically started.

Then you try to login, it must be works.

Accessing elements of Python dictionary by index

I know this is 8 years old, but no one seems to have actually read and answered the question.

You can call .values() on a dict to get a list of the inner dicts and thus access them by index.

>>> mydict = {
...  'Apple': {'American':'16', 'Mexican':10, 'Chinese':5},
...  'Grapes':{'Arabian':'25','Indian':'20'} }

>>>mylist = list(mydict.values())
>>>mylist[0]
{'American':'16', 'Mexican':10, 'Chinese':5},
>>>mylist[1]
{'Arabian':'25','Indian':'20'}

>>>myInnerList1 = list(mylist[0].values())
>>>myInnerList1
['16', 10, 5]
>>>myInnerList2 = list(mylist[1].values())
>>>myInnerList2
['25', '20']

var self = this?

Yeah, this appears to be a common standard. Some coders use self, others use me. It's used as a reference back to the "real" object as opposed to the event.

It's something that took me a little while to really get, it does look odd at first.

I usually do this right at the top of my object (excuse my demo code - it's more conceptual than anything else and isn't a lesson on excellent coding technique):

function MyObject(){
  var me = this;

  //Events
  Click = onClick; //Allows user to override onClick event with their own

  //Event Handlers
  onClick = function(args){
    me.MyProperty = args; //Reference me, referencing this refers to onClick
    ...
    //Do other stuff
  }
}

WebSockets vs. Server-Sent events/EventSource

Opera, Chrome, Safari supports SSE, Chrome, Safari supports SSE inside of SharedWorker Firefox supports XMLHttpRequest readyState interactive, so we can make EventSource polyfil for Firefox

Good beginners tutorial to socket.io?

A 'fun' way to learn socket.io is to play BrowserQuest by mozilla and look at its source code :-)

http://browserquest.mozilla.org/

https://github.com/mozilla/BrowserQuest

Intercept a form submit in JavaScript and prevent normal submission

Use @Kristian Antonsen's answer, or you can use:

$('button').click(function() {
    preventDefault();
    captureForm();
});

Fastest way to count number of occurrences in a Python list

You can use pandas, by transforming the list to a pd.Series then simply use .value_counts()

import pandas as pd
a = ['1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '7', '7', '7', '10', '10']
a_cnts = pd.Series(a).value_counts().to_dict()

Input  >> a_cnts["1"], a_cnts["10"]
Output >> (6, 2)

Sorting HashMap by values

public static TreeMap<String, String> sortMap(HashMap<String, String> passedMap, String byParam) {
    if(byParam.trim().toLowerCase().equalsIgnoreCase("byValue")) {
        // Altering the (key, value) -> (value, key)
        HashMap<String, String> newMap =  new HashMap<String, String>();
        for (Map.Entry<String, String> entry : passedMap.entrySet()) {
            newMap.put(entry.getValue(), entry.getKey());
        }
        return new TreeMap<String, String>(newMap);
    }
    return new TreeMap<String, String>(passedMap);
}

SSL received a record that exceeded the maximum permissible length. (Error code: ssl_error_rx_record_too_long)

My case is related to Greg B's -- Visual Studio creates two sites when SSL is enabled -- one for secure, and one for normal http requests. However Visual Studio chooses two ports at random, and depending on how you start the debugger you might be pointing towards the wrong page for the request type. Especially if you edit the URL but don't change the port number.

Seeing these posts jogged my memory.

I know this isn't APACHE related, but it is definitely a page that people with that error will find..

Using CookieContainer with WebClient class

 WebClient wb = new WebClient();
 wb.Headers.Add(HttpRequestHeader.Cookie, "somecookie");

From Comments

How do you format the name and value of the cookie in place of "somecookie" ?

wb.Headers.Add(HttpRequestHeader.Cookie, "cookiename=cookievalue"); 

For multiple cookies:

wb.Headers.Add(HttpRequestHeader.Cookie, 
              "cookiename1=cookievalue1;" +
              "cookiename2=cookievalue2");

How to download videos from youtube on java?

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

public class JavaYoutubeDownloader {

 public static String newline = System.getProperty("line.separator");
 private static final Logger log = Logger.getLogger(JavaYoutubeDownloader.class.getCanonicalName());
 private static final Level defaultLogLevelSelf = Level.FINER;
 private static final Level defaultLogLevel = Level.WARNING;
 private static final Logger rootlog = Logger.getLogger("");
 private static final String scheme = "http";
 private static final String host = "www.youtube.com";
 private static final Pattern commaPattern = Pattern.compile(",");
 private static final Pattern pipePattern = Pattern.compile("\\|");
 private static final char[] ILLEGAL_FILENAME_CHARACTERS = { '/', '\n', '\r', '\t', '\0', '\f', '`', '?', '*', '\\', '<', '>', '|', '\"', ':' };

 private static void usage(String error) {
  if (error != null) {
   System.err.println("Error: " + error);
  }
  System.err.println("usage: JavaYoutubeDownload VIDEO_ID DESTINATION_DIRECTORY");
  System.exit(-1);
 }

 public static void main(String[] args) {
  if (args == null || args.length == 0) {
   usage("Missing video id. Extract from http://www.youtube.com/watch?v=VIDEO_ID");
  }
  try {
   setupLogging();

   log.fine("Starting");
   String videoId = null;
   String outdir = ".";
   // TODO Ghetto command line parsing
   if (args.length == 1) {
    videoId = args[0];
   } else if (args.length == 2) {
    videoId = args[0];
    outdir = args[1];
   }

   int format = 18; // http://en.wikipedia.org/wiki/YouTube#Quality_and_codecs
   String encoding = "UTF-8";
   String userAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13";
   File outputDir = new File(outdir);
   String extension = getExtension(format);

   play(videoId, format, encoding, userAgent, outputDir, extension);

  } catch (Throwable t) {
   t.printStackTrace();
  }
  log.fine("Finished");
 }

 private static String getExtension(int format) {
  // TODO
  return "mp4";
 }

 private static void play(String videoId, int format, String encoding, String userAgent, File outputdir, String extension) throws Throwable {
  log.fine("Retrieving " + videoId);
  List<NameValuePair> qparams = new ArrayList<NameValuePair>();
  qparams.add(new BasicNameValuePair("video_id", videoId));
  qparams.add(new BasicNameValuePair("fmt", "" + format));
  URI uri = getUri("get_video_info", qparams);

  CookieStore cookieStore = new BasicCookieStore();
  HttpContext localContext = new BasicHttpContext();
  localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

  HttpClient httpclient = new DefaultHttpClient();
  HttpGet httpget = new HttpGet(uri);
  httpget.setHeader("User-Agent", userAgent);

  log.finer("Executing " + uri);
  HttpResponse response = httpclient.execute(httpget, localContext);
  HttpEntity entity = response.getEntity();
  if (entity != null && response.getStatusLine().getStatusCode() == 200) {
   InputStream instream = entity.getContent();
   String videoInfo = getStringFromInputStream(encoding, instream);
   if (videoInfo != null && videoInfo.length() > 0) {
    List<NameValuePair> infoMap = new ArrayList<NameValuePair>();
    URLEncodedUtils.parse(infoMap, new Scanner(videoInfo), encoding);
    String token = null;
    String downloadUrl = null;
    String filename = videoId;

    for (NameValuePair pair : infoMap) {
     String key = pair.getName();
     String val = pair.getValue();
     log.finest(key + "=" + val);
     if (key.equals("token")) {
      token = val;
     } else if (key.equals("title")) {
      filename = val;
     } else if (key.equals("fmt_url_map")) {
      String[] formats = commaPattern.split(val);
      for (String fmt : formats) {
       String[] fmtPieces = pipePattern.split(fmt);
       if (fmtPieces.length == 2) {
        // in the end, download somethin!
        downloadUrl = fmtPieces[1];
        int pieceFormat = Integer.parseInt(fmtPieces[0]);
        if (pieceFormat == format) {
         // found what we want
         downloadUrl = fmtPieces[1];
         break;
        }
       }
      }
     }
    }

    filename = cleanFilename(filename);
    if (filename.length() == 0) {
     filename = videoId;
    } else {
     filename += "_" + videoId;
    }
    filename += "." + extension;
    File outputfile = new File(outputdir, filename);

    if (downloadUrl != null) {
     downloadWithHttpClient(userAgent, downloadUrl, outputfile);
    }
   }
  }
 }

 private static void downloadWithHttpClient(String userAgent, String downloadUrl, File outputfile) throws Throwable {
  HttpGet httpget2 = new HttpGet(downloadUrl);
  httpget2.setHeader("User-Agent", userAgent);

  log.finer("Executing " + httpget2.getURI());
  HttpClient httpclient2 = new DefaultHttpClient();
  HttpResponse response2 = httpclient2.execute(httpget2);
  HttpEntity entity2 = response2.getEntity();
  if (entity2 != null && response2.getStatusLine().getStatusCode() == 200) {
   long length = entity2.getContentLength();
   InputStream instream2 = entity2.getContent();
   log.finer("Writing " + length + " bytes to " + outputfile);
   if (outputfile.exists()) {
    outputfile.delete();
   }
   FileOutputStream outstream = new FileOutputStream(outputfile);
   try {
    byte[] buffer = new byte[2048];
    int count = -1;
    while ((count = instream2.read(buffer)) != -1) {
     outstream.write(buffer, 0, count);
    }
    outstream.flush();
   } finally {
    outstream.close();
   }
  }
 }

 private static String cleanFilename(String filename) {
  for (char c : ILLEGAL_FILENAME_CHARACTERS) {
   filename = filename.replace(c, '_');
  }
  return filename;
 }

 private static URI getUri(String path, List<NameValuePair> qparams) throws URISyntaxException {
  URI uri = URIUtils.createURI(scheme, host, -1, "/" + path, URLEncodedUtils.format(qparams, "UTF-8"), null);
  return uri;
 }

 private static void setupLogging() {
  changeFormatter(new Formatter() {
   @Override
   public String format(LogRecord arg0) {
    return arg0.getMessage() + newline;
   }
  });
  explicitlySetAllLogging(Level.FINER);
 }

 private static void changeFormatter(Formatter formatter) {
  Handler[] handlers = rootlog.getHandlers();
  for (Handler handler : handlers) {
   handler.setFormatter(formatter);
  }
 }

 private static void explicitlySetAllLogging(Level level) {
  rootlog.setLevel(Level.ALL);
  for (Handler handler : rootlog.getHandlers()) {
   handler.setLevel(defaultLogLevelSelf);
  }
  log.setLevel(level);
  rootlog.setLevel(defaultLogLevel);
 }

 private static String getStringFromInputStream(String encoding, InputStream instream) throws UnsupportedEncodingException, IOException {
  Writer writer = new StringWriter();

  char[] buffer = new char[1024];
  try {
   Reader reader = new BufferedReader(new InputStreamReader(instream, encoding));
   int n;
   while ((n = reader.read(buffer)) != -1) {
    writer.write(buffer, 0, n);
   }
  } finally {
   instream.close();
  }
  String result = writer.toString();
  return result;
 }
}

/**
 * <pre>
 * Exploded results from get_video_info:
 * 
 * fexp=90...
 * allow_embed=1
 * fmt_stream_map=35|http://v9.lscache8...
 * fmt_url_map=35|http://v9.lscache8...
 * allow_ratings=1
 * keywords=Stefan Molyneux,Luke Bessey,anarchy,stateless society,giant stone cow,the story of our unenslavement,market anarchy,voluntaryism,anarcho capitalism
 * track_embed=0
 * fmt_list=35/854x480/9/0/115,34/640x360/9/0/115,18/640x360/9/0/115,5/320x240/7/0/0
 * author=lukebessey
 * muted=0
 * length_seconds=390
 * plid=AA...
 * ftoken=null
 * status=ok
 * watermark=http://s.ytimg.com/yt/swf/logo-vfl_bP6ud.swf,http://s.ytimg.com/yt/swf/hdlogo-vfloR6wva.swf
 * timestamp=12...
 * has_cc=False
 * fmt_map=35/854x480/9/0/115,34/640x360/9/0/115,18/640x360/9/0/115,5/320x240/7/0/0
 * leanback_module=http://s.ytimg.com/yt/swfbin/leanback_module-vflJYyeZN.swf
 * hl=en_US
 * endscreen_module=http://s.ytimg.com/yt/swfbin/endscreen-vflk19iTq.swf
 * vq=auto
 * avg_rating=5.0
 * video_id=S6IZP3yRJ9I
 * token=vPpcFNh...
 * thumbnail_url=http://i4.ytimg.com/vi/S6IZP3yRJ9I/default.jpg
 * title=The Story of Our Unenslavement - Animated
 * </pre>
 */

Simulating Key Press C#

Simple one, add before Main

[DllImport("USER32.DLL", CharSet = CharSet.Unicode)]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("USER32.DLL")]
public static extern bool SetForegroundWindow(IntPtr hWnd);

Code inside Main/Method:

string className = "IEFrame";
string windowName = "New Tab - Windows Internet Explorer";
IntPtr IE = FindWindow(className, windowName);
if (IE == IntPtr.Zero)
{
   return;
}
SetForegroundWindow(IE);
InputSimulator.SimulateKeyPress(VirtualKeyCode.F5);

Note:

  1. Add InputSimulator as reference. To download Click here

  2. To find Class & Window name, use WinSpy++. To download Click here

How do I run a bat file in the background from another bat file?

Since START is the only way to execute something in the background from a CMD script, I would recommend you keep using it. Instead of the /B modifier, try /MIN so the newly created window won't bother you. Also, you can set the priority to something lower with /LOW or /BELOWNORMAL, which should improve your system responsiveness.

What are the complexity guarantees of the standard containers?

I found the nice resource Standard C++ Containers. Probably this is what you all looking for.

VECTOR

Constructors

vector<T> v;              Make an empty vector.                                     O(1)
vector<T> v(n);           Make a vector with N elements.                            O(n)
vector<T> v(n, value);    Make a vector with N elements, initialized to value.      O(n)
vector<T> v(begin, end);  Make a vector and copy the elements from begin to end.    O(n)

Accessors

v[i]          Return (or set) the I'th element.                        O(1)
v.at(i)       Return (or set) the I'th element, with bounds checking.  O(1)
v.size()      Return current number of elements.                       O(1)
v.empty()     Return true if vector is empty.                          O(1)
v.begin()     Return random access iterator to start.                  O(1)
v.end()       Return random access iterator to end.                    O(1)
v.front()     Return the first element.                                O(1)
v.back()      Return the last element.                                 O(1)
v.capacity()  Return maximum number of elements.                       O(1)

Modifiers

v.push_back(value)         Add value to end.                                                O(1) (amortized)
v.insert(iterator, value)  Insert value at the position indexed by iterator.                O(n)
v.pop_back()               Remove value from end.                                           O(1)
v.assign(begin, end)       Clear the container and copy in the elements from begin to end.  O(n)
v.erase(iterator)          Erase value indexed by iterator.                                 O(n)
v.erase(begin, end)        Erase the elements from begin to end.                            O(n)

For other containers, refer to the page.

Correct way to try/except using Python requests module?

Exception object also contains original response e.response, that could be useful if need to see error body in response from the server. For example:

try:
    r = requests.post('somerestapi.com/post-here', data={'birthday': '9/9/3999'})
    r.raise_for_status()
except requests.exceptions.HTTPError as e:
    print (e.response.text)

WPF MVVM: How to close a window

I also had to deal with this problem, so here my solution. It works great for me.

1. Create class DelegateCommand

    public class DelegateCommand<T> : ICommand
{
    private Predicate<T> _canExecuteMethod;
    private readonly Action<T> _executeMethod;
    public event EventHandler CanExecuteChanged;

    public DelegateCommand(Action<T> executeMethod) : this(executeMethod, null)
    {
    }
    public DelegateCommand(Action<T> executeMethod, Predicate<T> canExecuteMethod)
    {
        this._canExecuteMethod = canExecuteMethod;
        this._executeMethod = executeMethod ?? throw new ArgumentNullException(nameof(executeMethod), "Command is not specified."); 
    }


    public void RaiseCanExecuteChanged()
    {
        if (this.CanExecuteChanged != null)
            CanExecuteChanged(this, null);
    }
    public bool CanExecute(object parameter)
    {
        return _canExecuteMethod == null || _canExecuteMethod((T)parameter) == true;
    }

    public void Execute(object parameter)
    {
        _executeMethod((T)parameter);
    }
}

2. Define your command

        public DelegateCommand<Window> CloseWindowCommand { get; private set; }


    public MyViewModel()//ctor of your viewmodel
    {
        //do something

        CloseWindowCommand = new DelegateCommand<Window>(CloseWindow);


    }
        public void CloseWindow(Window win) // this method is also in your viewmodel
    {
        //do something
        win?.Close();
    }

3. Bind your command in the view

public MyView(Window win) //ctor of your view, window as parameter
    {
        InitializeComponent();
        MyButton.CommandParameter = win;
        MyButton.Command = ((MyViewModel)this.DataContext).CloseWindowCommand;
    }

4. And now the window

  Window win = new Window()
        {
            Title = "My Window",
            Height = 800,
            Width = 800,
            WindowStartupLocation = WindowStartupLocation.CenterScreen,

        };
        win.Content = new MyView(win);
        win.ShowDialog();

so thats it, you can also bind the command in the xaml file and find the window with FindAncestor and bind it to the command parameter.

How to loop through key/value object in Javascript?

for (var key in data) {
    alert("User " + data[key] + " is #" + key); // "User john is #234"
}

Set mouse focus and move cursor to end of input using jQuery

Here is another one, a one liner which does not reassign the value:

$("#inp").focus()[0].setSelectionRange(99999, 99999);

MongoDB: How to update multiple documents with a single command?

I had the same problem , and i found the solution , and it works like a charm

just set the flag multi to true like this :

 db.Collection.update(
                {_id_receiver: id_receiver},
               {$set: {is_showed: true}},
                {multi: true}   /* --> multiple update */
            , function (err, updated) {...});

i hope that helps :)

How do I merge a specific commit from one branch into another in Git?

The git cherry-pick <commit> command allows you to take a single commit (from whatever branch) and, essentially, rebase it in your working branch.

Chapter 5 of the Pro Git book explains it better than I can, complete with diagrams and such. (The chapter on Rebasing is also good reading.)

Lastly, there are some good comments on the cherry-picking vs merging vs rebasing in another SO question.

Mongoose, Select a specific field with find

Example 1:

0 means ignore

1 means show

User.find({}, { createdAt: 0, updatedAt: 0, isActive: 0, _id : 1 }).then(...)

Example 2:

User.findById(id).select("_id, isActive").then(...)

System.Data.SqlClient.SqlException: Invalid object name 'dbo.Projects'

Try to do this way

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
{ 
     modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}

or if you use .net core try it

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Usuario>().ToTable("Usuario");
}

Replace Usuario for your Entity Name, like a DbSet<<EntityName>> Entities without Plural

Connecting an input stream to an outputstream

Asynchronous way to achieve it.

void inputStreamToOutputStream(final InputStream inputStream, final OutputStream out) {
    Thread t = new Thread(new Runnable() {

        public void run() {
            try {
                int d;
                while ((d = inputStream.read()) != -1) {
                    out.write(d);
                }
            } catch (IOException ex) {
                //TODO make a callback on exception.
            }
        }
    });
    t.setDaemon(true);
    t.start();
}

Java JSON serialization - best practice

As others have hinted, you should consider dumping org.json's library. It's pretty much obsolete these days, and trying to work around its problems is waste of time.

But to specific question; type variable T just does not have any information to help you, as it is little more than compile-time information. Instead you need to pass actual class (as 'Class cls' argument), and you can then create an instance with 'cls.newInstance()'.

How to compare binary files to check if they are the same?

Diff with the following options would do a binary comparison to check just if the files are different at all and it'd output if the files are the same as well:

diff -qs {file1} {file2}

If you are comparing two files with the same name in different directories, you can use this form instead:

diff -qs {file1} --to-file={dir2}

OS X El Capitan

How to create a temporary table in SSIS control flow task and then use it in data flow task?

I'm late to this party but I'd like to add one bit to user756519's thorough, excellent answer. I don't believe the "RetainSameConnection on the Connection Manager" property is relevant in this instance based on my recent experience. In my case, the relevant point was their advice to set "ValidateExternalMetadata" to False.

I'm using a temp table to facilitate copying data from one database (and server) to another, hence the reason "RetainSameConnection" was not relevant in my particular case. And I don't believe it is important to accomplish what is happening in this example either, as thorough as it is.

Get the device width in javascript

I just had this idea, so maybe it's shortsighted, but it seems to work well and might be the most consistent between your CSS and JS.

In your CSS you set the max-width value for html based on the @media screen value:

@media screen and (max-width: 480px) and (orientation: portrait){

    html { 
        max-width: 480px;
    }

    ... more styles for max-width 480px screens go here

}

Then, using JS (probably via a framework like JQuery), you would just check the max-width value of the html tag:

maxwidth = $('html').css('max-width');

Now you can use this value to make conditional changes:

If (maxwidth == '480px') { do something }

If putting the max-width value on the html tag seems scary, then maybe you can put on a different tag, one that is only used for this purpose. For my purpose the html tag works fine and doesn't affect my markup.


Useful if you are using Sass, etc: To return a more abstract value, such as breakpoint name, instead of px value you can do something like:

  1. Create an element that will store the breakpoint name, e.g. <div id="breakpoint-indicator" />
  2. Using css media queries change the content property for this element, e. g. "large" or "mobile", etc (same basic media query approach as above, but setting css 'content' property instead of 'max-width').
  3. Get the css content property value using js or jquery (jquery e.g. $('#breakpoint-indicator').css('content');), which returns "large", or "mobile", etc depending on what the content property is set to by the media query.
  4. Act on the current value.

Now you can act on same breakpoint names as you do in sass, e.g. sass: @include respond-to(xs), and js if ($breakpoint = "xs) {}.

What I especially like about this is that I can define my breakpoint names all in css and in one place (likely a variables scss document) and my js can act on them independently.

Keep-alive header clarification

Where is this info kept ("this connection is between computer A and server F")?

A TCP connection is recognized by source IP and port and destination IP and port. Your OS, all intermediate session-aware devices and the server's OS will recognize the connection by this.

HTTP works with request-response: client connects to server, performs a request and gets a response. Without keep-alive, the connection to an HTTP server is closed after each response. With HTTP keep-alive you keep the underlying TCP connection open until certain criteria are met.

This allows for multiple request-response pairs over a single TCP connection, eliminating some of TCP's relatively slow connection startup.

When The IIS (F) sends keep alive header (or user sends keep-alive) , does it mean that (E,C,B) save a connection

No. Routers don't need to remember sessions. In fact, multiple TCP packets belonging to same TCP session need not all go through same routers - that is for TCP to manage. Routers just choose the best IP path and forward packets. Keep-alive is only for client, server and any other intermediate session-aware devices.

which is only for my session ?

Does it mean that no one else can use that connection

That is the intention of TCP connections: it is an end-to-end connection intended for only those two parties.

If so - does it mean that keep alive-header - reduce the number of overlapped connection users ?

Define "overlapped connections". See HTTP persistent connection for some advantages and disadvantages, such as:

  • Lower CPU and memory usage (because fewer connections are open simultaneously).
  • Enables HTTP pipelining of requests and responses.
  • Reduced network congestion (fewer TCP connections).
  • Reduced latency in subsequent requests (no handshaking).

if so , for how long does the connection is saved to me ? (in other words , if I set keep alive- "keep" till when?)

An typical keep-alive response looks like this:

Keep-Alive: timeout=15, max=100

See Hypertext Transfer Protocol (HTTP) Keep-Alive Header for example (a draft for HTTP/2 where the keep-alive header is explained in greater detail than both 2616 and 2086):

  • A host sets the value of the timeout parameter to the time that the host will allows an idle connection to remain open before it is closed. A connection is idle if no data is sent or received by a host.

  • The max parameter indicates the maximum number of requests that a client will make, or that a server will allow to be made on the persistent connection. Once the specified number of requests and responses have been sent, the host that included the parameter could close the connection.

However, the server is free to close the connection after an arbitrary time or number of requests (just as long as it returns the response to the current request). How this is implemented depends on your HTTP server.

Ignore .classpath and .project from Git

Use a .gitignore file. This allows you to ignore certain files. http://git-scm.com/docs/gitignore

Here's an example Eclipse one, which handles your classpath and project files: https://github.com/github/gitignore/blob/master/Global/Eclipse.gitignore

Ordering by specific field value first

SELECT * FROM cars_new WHERE status = '1' and car_hide !='1' and cname IN ('Executive Car','Saloon','MPV+','MPV5') ORDER BY FIELD(cname, 'Executive Car', 'Saloon','MPV+','mpv5')

Bad Request, Your browser sent a request that this server could not understand

Make sure you url encode all of the query params in your url.

In my case there was a space ' ' in my url, and I was making an API call using curl, and my api server was giving this error.

Means the following url http://somedomain.com?key=some value with space

should be http://somedomain.com/?key=some%20value%20with%20space

How to escape the equals sign in properties files

This method should help to programmatically generate values guaranteed to be 100% compatible with .properties files:

public static String escapePropertyValue(final String value) {
    if (value == null) {
        return null;
    }

    try (final StringWriter writer = new StringWriter()) {
        final Properties properties = new Properties();
        properties.put("escaped", value);
        properties.store(writer, null);
        writer.flush();

        final String stringifiedProperties = writer.toString();
        final Pattern pattern = Pattern.compile("(.*?)escaped=(.*?)" + Pattern.quote(System.lineSeparator()) + "*");
        final Matcher matcher = pattern.matcher(stringifiedProperties);

        if (matcher.find() && matcher.groupCount() <= 2) {
            return matcher.group(matcher.groupCount());
        }

        // This should never happen unless the internal implementation of Properties::store changed
        throw new IllegalStateException("Could not escape property value");
    } catch (final IOException ex) {
        // This should never happen. IOException is only because the interface demands it
        throw new IllegalStateException("Could not escape property value", ex);
    }
}

You can call it like this:

final String escapedPath = escapePropertyValue("C:\\Users\\X");
writeToFile(escapedPath); // will pass "C\\:\\\\Users\\\\X"

This method a little bit expensive but, writing properties to a file is typically an sporadic operation anyway.

TestNG ERROR Cannot find class in classpath

Please make sure that you have specified your class/package in TestNG.xml file.

<test name="test1" preserve-order="false">
    <classes>
        <class name="ABC"/>
    </classes>
</test>

java.lang.NoClassDefFoundError: com/sun/mail/util/MailLogger for JUnit test case for Java mail

com.sun.mail.util.MailLogger is part of JavaMail API. It is already included in EE environment (that's why you can use it on your live server), but it is not included in SE environment.

Oracle docs:

The JavaMail API is available as an optional package for use with Java SE platform and is also included in the Java EE platform.

99% that you run your tests in SE environment which means what you have to bother about adding it manually to your classpath when running tests.

If you're using maven add the following dependency (you might want to change version):

<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>javax.mail</artifactId>
    <version>1.6.0</version>
</dependency>

How to check if a stored procedure exists before creating it

I wonder! Why i don't write the whole query like

GO
create procedure [dbo].[spAddNewClass] @ClassName varchar(20),@ClassFee int
as
begin
insert into tblClass values (@ClassName,@ClassFee)
end

GO
create procedure [dbo].[spAddNewSection] @SectionName varchar(20),@ClassID       int
as
begin
insert into tblSection values(@SectionName,@ClassID)
end

Go
create procedure test
as
begin 
select * from tblstudent
end

i already know that first two procedures are already exist sql will run the query will give the error of first two procedures but still it will create the last procedure SQl is itself taking care of what is already exist this is what i always do to all my clients!

What does the "undefined reference to varName" in C mean?

You need to link both a.o and b.o:

gcc -o program a.c b.c

If you have a main() in each file, you cannot link them together.

However, your a.c file contains a reference to doSomething() and expects to be linked with a source file that defines doSomething() and does not define any function that is defined in a.c (such as main()).

You cannot call a function in Process B from Process A. You cannot send a signal to a function; you send signals to processes, using the kill() system call.

The signal() function specifies which function in your current process (program) is going to handle the signal when your process receives the signal.

You have some serious work to do understanding how this is going to work - how ProgramA is going to know which process ID to send the signal to. The code in b.c is going to need to call signal() with dosomething as the signal handler. The code in a.c is simply going to send the signal to the other process.

text-overflow: ellipsis not working

Just a headsup for anyone who may stumble across this... My h2 was inheriting

text-rendering: optimizelegibility; 
//Changed to text-rendering: none; for fix

which was not allowing ellipsis. Apparently this is very finickey eh?

Properties order in Margin

There are three unique situations:

  • 4 numbers, e.g. Margin="a,b,c,d".
  • 2 numbers, e.g. Margin="a,b".
  • 1 number, e.g. Margin="a".

4 Numbers

If there are 4 numbers, then its left, top, right, bottom (a clockwise circle starting from the middle left margin). First number is always the "West" like "WPF":

<object Margin="left,top,right,bottom"/>

Example: if we use Margin="10,20,30,40" it generates:

enter image description here

2 Numbers

If there are 2 numbers, then the first is left & right margin thickness, the second is top & bottom margin thickness. First number is always the "West" like "WPF":

<object Margin="a,b"/> // Equivalent to Margin="a,b,a,b".

Example: if we use Margin="10,30", the left & right margin are both 10, and the top & bottom are both 30.

enter image description here

1 Number

If there is 1 number, then the number is repeated (its essentially a border thickness).

<object Margin="a"/> // Equivalent to Margin="a,a,a,a".

Example: if we use Margin="20" it generates:

enter image description here

Update 2020-05-27

Have been working on a large-scale WPF application for the past 5 years with over 100 screens. Part of a team of 5 WPF/C#/Java devs. We eventually settled on either using 1 number (for border thickness) or 4 numbers. We never use 2. It is consistent, and seems to be a good way to reduce cognitive load when developing.


The rule:

All width numbers start on the left (the "West" like "WPF") and go clockwise (if two numbers, only go clockwise twice, then mirror the rest).

Controlling Maven final name of jar artifact

I am using the following

        ....
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>3.0.2</version>
            <configuration>
                <finalName>${project.groupId}/${project.artifactId}-${baseVersion}.${monthlyVersion}.${instanceVersion}</finalName>
            </configuration>
        </plugin>
        ....

This way you can define each value individually or pragmatically from Jenkins of some other system.

mvn package -DbaseVersion=1 -monthlyVersion=2 -instanceVersion=3

This will place a folder target\{group.id}\projectName-1.2.3.jar

A better way to save time might be

        ....
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>3.0.2</version>
            <configuration>
                <finalName>${project.groupId}/${project.artifactId}-${baseVersion}</finalName>
            </configuration>
        </plugin>
        ....

Like the same except I use on variable.

  mvn package -DbaseVersion=0.3.4

This will place a folder target\{group.id}\projectName-1.2.3.jar

you can also use outputDirectory inside of configuration to specify a location you may want the package to be located.

PHP removing a character in a string

$splitPos = strpos($url, "?/");
if ($splitPos !== false) {
    $url = substr($url, 0, $splitPos) . "?" . substr($url, $splitPos + 2);
}

Multiline for WPF TextBox

The only property corresponding in WPF to the

Winforms property: TextBox.Multiline = true

is the WPF property: TextBox.AcceptsReturn = true.

<TextBox AcceptsReturn="True" ...... />

All other settings, such as VerticalAlignement, WordWrap etc., only control how the TextBox interacts in the UI but do not affect the Multiline behaviour.

How to make one Observable sequence wait for another to complete before emitting?

Here is yet another possibility taking advantage of switchMap's result selector

var one$ = someObservable.take(1);
var two$ = someOtherObservable.take(1);
two$.switchMap(
    /** Wait for first Observable */
    () => one$,
    /** Only return the value we're actually interested in */
    (value2, value1) => value2
  )
  .subscribe((value2) => {
    /* do something */ 
  });

Since the switchMap's result selector has been depreciated, here is an updated version

const one$ = someObservable.pipe(take(1));
const two$ = someOtherObservable.pipe(
  take(1),
  switchMap(value2 => one$.map(_ => value2))
);
two$.subscribe(value2 => {
  /* do something */ 
});

checking memory_limit in PHP

Try to convert the value first (eg: 64M -> 64 * 1024 * 1024). After that, do comparison and print the result.

<?php
$memory_limit = ini_get('memory_limit');
if (preg_match('/^(\d+)(.)$/', $memory_limit, $matches)) {
    if ($matches[2] == 'M') {
        $memory_limit = $matches[1] * 1024 * 1024; // nnnM -> nnn MB
    } else if ($matches[2] == 'K') {
        $memory_limit = $matches[1] * 1024; // nnnK -> nnn KB
    }
}

$ok = ($memory_limit >= 64 * 1024 * 1024); // at least 64M?

echo '<phpmem>';
echo '<val>' . $memory_limit . '</val>';
echo '<ok>' . ($ok ? 1 : 0) . '</ok>';
echo '</phpmem>';

Please note that the above code is just an idea. Don't forget to handle -1 (no memory limit), integer-only value (value in bytes), G (value in gigabytes), k/m/g (value in kilobytes, megabytes, gigabytes because shorthand is case-insensitive), etc.

numpy.where() detailed, step-by-step explanation / examples

After fiddling around for a while, I figured things out, and am posting them here hoping it will help others.

Intuitively, np.where is like asking "tell me where in this array, entries satisfy a given condition".

>>> a = np.arange(5,10)
>>> np.where(a < 8)       # tell me where in a, entries are < 8
(array([0, 1, 2]),)       # answer: entries indexed by 0, 1, 2

It can also be used to get entries in array that satisfy the condition:

>>> a[np.where(a < 8)] 
array([5, 6, 7])          # selects from a entries 0, 1, 2

When a is a 2d array, np.where() returns an array of row idx's, and an array of col idx's:

>>> a = np.arange(4,10).reshape(2,3)
array([[4, 5, 6],
       [7, 8, 9]])
>>> np.where(a > 8)
(array(1), array(2))

As in the 1d case, we can use np.where() to get entries in the 2d array that satisfy the condition:

>>> a[np.where(a > 8)] # selects from a entries 0, 1, 2

array([9])


Note, when a is 1d, np.where() still returns an array of row idx's and an array of col idx's, but columns are of length 1, so latter is empty array.

How to add Google Maps Autocomplete search box?

I am currently using the Google API to retrieve the location that the user enters in the form/ input. I'm also using an angular function that showing the current location and suggests a city name pin code etc... - add google API index.html.
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=xxxxxxxx&libraries=geometry,places"></script>
- add id in input box to get string & charcters.
<input id="autocomplete" type="text"(keydown)="checkAddress($event.target.value)">
- and create function on your component.ts file.
import these file

import * as _ from 'lodash';
declare var google: any;
 checkAddress(value) {
    if (!value) {
      this.model.location = _.cloneDeep(value);
      this.rfpForm.controls['location'].setValue(this.model.location);
    }
  }
initLocationAutocomplete() {
    let autocomplete, place;
    const getLocation = () => {
        place = autocomplete.getPlace();
        if (place && (place.formatted_address || place.name)) {  
            // if you want set value in your form controls like this
            this.model.location = _.cloneDeep(place.formatted_address || place.name);
            // YourFormName.controls['location'].setValue(this.model.location);
            // YourFormName.controls['location']['_touched'] = true;
        }
    };
    autocomplete = new google.maps.places.Autocomplete((document.getElementById('autocomplete')), { types: ['geocode'] });
    autocomplete.addListener('place_changed', getLocation);
}

How to zip a file using cmd line?

tar.exe -acf out.zip in.txt

out.zip is an output folder or filename and in.txt is an input folder or filename. To use this command you should be in the file existing folder.

Difference between opening a file in binary vs text

The most important difference to be aware of is that with a stream opened in text mode you get newline translation on non-*nix systems (it's also used for network communications, but this isn't supported by the standard library). In *nix newline is just ASCII linefeed, \n, both for internal and external representation of text. In Windows the external representation often uses a carriage return + linefeed pair, "CRLF" (ASCII codes 13 and 10), which is converted to a single \n on input, and conversely on output.


From the C99 standard (the N869 draft document), §7.19.2/2,

A text stream is an ordered sequence of characters composed into lines, each line consisting of zero or more characters plus a terminating new-line character. Whether the last line requires a terminating new-line character is implementation-defined. Characters may have to be added, altered, or deleted on input and output to conform to differing conventions for representing text in the host environment. Thus, there need not be a one- to-one correspondence between the characters in a stream and those in the external representation. Data read in from a text stream will necessarily compare equal to the data that were earlier written out to that stream only if: the data consist only of printing characters and the control characters horizontal tab and new-line; no new-line character is immediately preceded by space characters; and the last character is a new-line character. Whether space characters that are written out immediately before a new-line character appear when read in is implementation-defined.

And in §7.19.3/2

Binary files are not truncated, except as defined in 7.19.5.3. Whether a write on a text stream causes the associated file to be truncated beyond that point is implementation- defined.

About use of fseek, in §7.19.9.2/4:

For a text stream, either offset shall be zero, or offset shall be a value returned by an earlier successful call to the ftell function on a stream associated with the same file and whence shall be SEEK_SET.

About use of ftell, in §17.19.9.4:

The ftell function obtains the current value of the file position indicator for the stream pointed to by stream. For a binary stream, the value is the number of characters from the beginning of the file. For a text stream, its file position indicator contains unspecified information, usable by the fseek function for returning the file position indicator for the stream to its position at the time of the ftell call; the difference between two such return values is not necessarily a meaningful measure of the number of characters written or read.

I think that’s the most important, but there are some more details.

How can prevent a PowerShell window from closing so I can see the error?

The simplest and easiest way is to execute your particular script with -NoExit param.

1.Open run box by pressing:

Win + R

2.Then type into input prompt:

PowerShell -NoExit "C:\folder\script.ps1"

and execute.

Preloading CSS Images

If you're reusing these bg images anywhere else on your site for form inputs, you probably want to use an image sprite. That way you can centrally manage your images (instead of having pic1, pic2, pic3, etc...).

Sprites are generally faster for the client, since they are only requesting one (albeit slightly larger) file from the server instead of multiple files. See SO article for more benefits:

CSS image sprites

Then again, this might not be helpful at all if you're just using these for one form and you really only want to load them if the user requests the contact form...might make sense though.

http://www.alistapart.com/articles/sprites

How to delete/remove nodes on Firebase

Firebase.remove() like probably most Firebase methods is asynchronous, thus you have to listen to events to know when something happened:

parent = ref.parent()
parent.on('child_removed', function (snapshot) {
    // removed!
})
ref.remove()

According to Firebase docs it should work even if you lose network connection. If you want to know when the change has been actually synchronized with Firebase servers, you can pass a callback function to Firebase.remove method:

ref.remove(function (error) {
    if (!error) {
        // removed!
    }
}

How can I be notified when an element is added to the page?

You can use livequery plugin for jQuery. You can provide a selector expression such as:

$("input[type=button].removeItemButton").livequery(function () {
    $("#statusBar").text('You may now remove items.');
});

Every time a button of a removeItemButton class is added a message appears in a status bar.

In terms of efficiency you might want avoid this, but in any case you could leverage the plugin instead of creating your own event handlers.

Revisited answer

The answer above was only meant to detect that an item has been added to the DOM through the plugin.

However, most likely, a jQuery.on() approach would be more appropriate, for example:

$("#myParentContainer").on('click', '.removeItemButton', function(){
          alert($(this).text() + ' has been removed');
});

If you have dynamic content that should respond to clicks for example, it's best to bind events to a parent container using jQuery.on.

git clone through ssh

This is possibly unrelated directly to the question; but one mistake I just made myself, and I see in the OP, is the URL specification ssh://user@server:/GitRepos/myproject.git - namely, you have both a colon :, and a forward slash / after it signifying an absolute path.

I then found Git clone, ssh: Could not resolve hostname – git , development – Nicolas Kuttler (as that was the error I was getting, on git version 1.7.9.5), noting:

The problem with the command I used initially was that I tried to use an scp-like syntax.

... which was also my problem! So basically in git with ssh, you either use

  • ssh://[email protected]/absolute/path/to/repo.git/ - just a forward slash for absolute path on server
  • [email protected]:relative/path/to/repo.git/ - just a colon (it mustn't have the ssh:// for relative path on server (relative to home dir of username on server machine)

Hope this helps someone,
Cheers!

Javascript Array inside Array - how can I call the child array name?

I would create an object like this:

var options = { 
    size: ["S", "M", "L", "XL", "XXL"],
    color: ["Red", "Blue", "Green", "White", "Black"]
};


alert(Object.keys(options));

To access the keys individualy:

for (var key in options) {
    alert(key);
}

P.S.: when you create a new array object do not use new Array use [] instead.

Chrome:The website uses HSTS. Network errors...this page will probably work later

When you visited https://localhost previously at some point it not only visited this over a secure channel (https rather than http), it also told your browser, using a special HTTP header: Strict-Transport-Security (often abbreviated to HSTS), that it should ONLY use https for all future visits.

This is a security feature web servers can use to prevent people being downgraded to http (either intentionally or by some evil party).

However if you then then turn off your https server, and just want to browse http you can't (by design - that's the point of this security feature).

HSTS also does prevents you from accepting and skipping past certificate errors.

To reset this, so HSTS is no longer set for localhost, type the following in your Chrome address bar:

chrome://net-internals/#hsts

Where you will be able to delete this setting for "localhost".

You might also want to find out what was setting this to avoid this problem in future!

Note that for other sites (e.g. www.google.com) these are "preloaded" into the Chrome code and so cannot be removed. When you query them at chrome://net-internals/#hsts you will see them listed as static HSTS entries.

And finally note that Google has started preloading HSTS for the entire .dev domain: https://ma.ttias.be/chrome-force-dev-domains-https-via-preloaded-hsts/

PHP: If internet explorer 6, 7, 8 , or 9

You can check the HTTP_USER_AGENT server variable. The user agent transfered by IE contains MSIE

if(strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false) { ... }

For specific versions you can extend your condition

if(strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 6.') !== false) { ... }

Also see this related question.

HTML button to NOT submit form

It's recommended not to use the <Button> tag. Use the <Input type='Button' onclick='return false;'> tag instead. (Using the "return false" should indeed not send the form.)

Some reference material

SQL : BETWEEN vs <= and >=

As mentioned by @marc_s, @Cloud, et al. they're basically the same for a closed range.

But any fractional time values may cause issues with a closed range (greater-or-equal and less-or-equal) as opposed to a half-open range (greater-or-equal and less-than) with an end value after the last possible instant.

So to avoid that the query should be rewritten as:

SELECT EventId, EventName
  FROM EventMaster
 WHERE (EventDate >= '2009-10-15' AND
        EventDate <  '2009-10-19')    /* <<<== 19th, not 18th */

Since BETWEEN doesn't work for half-open intervals I always take a hard look at any date/time query that uses it, since its probably an error.

How to get current value of RxJS Subject or Observable?

The only way you should be getting values "out of" an Observable/Subject is with subscribe!

If you're using getValue() you're doing something imperative in declarative paradigm. It's there as an escape hatch, but 99.9% of the time you should NOT use getValue(). There are a few interesting things that getValue() will do: It will throw an error if the subject has been unsubscribed, it will prevent you from getting a value if the subject is dead because it's errored, etc. But, again, it's there as an escape hatch for rare circumstances.

There are several ways of getting the latest value from a Subject or Observable in a "Rx-y" way:

  1. Using BehaviorSubject: But actually subscribing to it. When you first subscribe to BehaviorSubject it will synchronously send the previous value it received or was initialized with.
  2. Using a ReplaySubject(N): This will cache N values and replay them to new subscribers.
  3. A.withLatestFrom(B): Use this operator to get the most recent value from observable B when observable A emits. Will give you both values in an array [a, b].
  4. A.combineLatest(B): Use this operator to get the most recent values from A and B every time either A or B emits. Will give you both values in an array.
  5. shareReplay(): Makes an Observable multicast through a ReplaySubject, but allows you to retry the observable on error. (Basically it gives you that promise-y caching behavior).
  6. publishReplay(), publishBehavior(initialValue), multicast(subject: BehaviorSubject | ReplaySubject), etc: Other operators that leverage BehaviorSubject and ReplaySubject. Different flavors of the same thing, they basically multicast the source observable by funneling all notifications through a subject. You need to call connect() to subscribe to the source with the subject.

stopPropagation vs. stopImmediatePropagation

I am a late comer, but maybe I can say this with a specific example:

Say, if you have a <table>, with <tr>, and then <td>. Now, let's say you set 3 event handlers for the <td> element, then if you do event.stopPropagation() in the first event handler you set for <td>, then all event handlers for <td> will still run, but the event just won't propagate to <tr> or <table> (and won't go up and up to <body>, <html>, document, and window).

Now, however, if you use event.stopImmediatePropagation() in your first event handler, then, the other two event handlers for <td> WILL NOT run, and won't propagate up to <tr>, <table> (and won't go up and up to <body>, <html>, document, and window).

Note that it is not just for <td>. For other elements, it will follow the same principle.

Convert Dictionary to JSON in Swift

Here's an easy extension to do this:

https://gist.github.com/stevenojo/0cb8afcba721838b8dcb115b846727c3

extension Dictionary {
    func jsonString() -> NSString? {
        let jsonData = try? JSONSerialization.data(withJSONObject: self, options: [])
        guard jsonData != nil else {return nil}
        let jsonString = String(data: jsonData!, encoding: .utf8)
        guard jsonString != nil else {return nil}
        return jsonString! as NSString
    }

}

Remove a child with a specific attribute, in SimpleXML for PHP

With FluidXML you can use XPath to select the elements to remove.

$doc = fluidify($doc);

$doc->remove('//*[@id="A12"]');

https://github.com/servo-php/fluidxml


The XPath //*[@id="A12"] means:

  • in any point of the document (//)
  • every node (*)
  • with the attribute id equal to A12 ([@id="A12"]).

Error: getaddrinfo ENOTFOUND in nodejs for get call

I was running into the same problem and after some trial and error discovered that my hosts file customisation was causing the problem.

My localhost DNS was overwritten and because of that a simple ping was failing:

$ ping http://localhost
# ping: cannot resolve http://localhost: Unknown host

Once I resolved the configuration of /private/etc/hosts file, pinging localhost successfully worked, and was no longer getting the error that you were seeing:

# Fatal error: getaddrinfo ENOTFOUND

How to set variables in HIVE scripts

Have you tried using the dollar sign and brackets like this:

SELECT * 
FROM foo 
WHERE day >= '${CURRENT_DATE}';

Smart way to truncate long strings

Correcting Kooilnc's solution:

String.prototype.trunc = String.prototype.trunc ||
  function(n){
      return this.length>n ? this.substr(0,n-1)+'&hellip;' : this.toString();
  };

This returns the string value instead of the String object if it doesn't need to be truncated.

Objective C - Assign, Copy, Retain

The Memory Management Programming Guide from the iOS Reference Library has basics of assign, copy, and retain with analogies and examples.

copy Makes a copy of an object, and returns it with retain count of 1. If you copy an object, you own the copy. This applies to any method that contains the word copy where “copy” refers to the object being returned.

retain Increases the retain count of an object by 1. Takes ownership of an object.

release Decreases the retain count of an object by 1. Relinquishes ownership of an object.

DateTimePicker: pick both date and time

Unfortunately, this is one of the many misnomers in the framework, or at best a violation of SRP.

To use the DateTimePicker for times, set the Format property to either Time or Custom (Use Custom if you want to control the format of the time using the CustomFormat property). Then set the ShowUpDown property to true.

Although a user may set the date and time together manually, they cannot use the GUI to set both.

Open URL in new window with JavaScript

Use window.open():

<a onclick="window.open(document.URL, '_blank', 'location=yes,height=570,width=520,scrollbars=yes,status=yes');">
  Share Page
</a>

This will create a link titled Share Page which opens the current url in a new window with a height of 570 and width of 520.

PHP: if !empty & empty

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

switch( true ){

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

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

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

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

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

}

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

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

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

Checking whether a variable is an integer or not

Why not try something like:

if x%1 == 0: 

Best way to format integer as string with leading zeros?

The standard way is to use format string modifiers. These format string methods are available in most programming languages (via the sprintf function in c for example) and are a handy tool to know about.

To output a string of length 5:

... in Python 3.5 and above:

i = random.randint(0, 99999)
print(f'{i:05d}')

... Python 2.6 and above:

print '{0:05d}'.format(i)

... before Python 2.6:

print "%05d" % i

See: https://docs.python.org/3/library/string.html

Apache gives me 403 Access Forbidden when DocumentRoot points to two different drives

Somewhere, you need to tell Apache that people are allowed to see contents of this directory.

<Directory "F:/bar/public">
    Order Allow,Deny
    Allow from All
    # Any other directory-specific stuff
</Directory>

More info

Rails 4: assets not loading in production

In /config/environments/production.rb I had to add this:

Rails.application.config.assets.precompile += %w( *.js ^[^_]*.css *.css.erb )

The .js was getting precompiled already, but I added it anyway. The .css and .css.erb apparently don't happen automatically. The ^[^_] excludes partials from being compiled -- it's a regexp.

It's a little frustrating that the docs clearly state that asset pipeline IS enabled by default but doesn't clarify the fact that only applies to javascripts.

How to suspend/resume a process in Windows?

#pragma comment(lib,"ntdll.lib")
EXTERN_C NTSTATUS NTAPI NtSuspendProcess(IN HANDLE ProcessHandle);

void SuspendSelf(){
    NtSuspendProcess(GetCurrentProcess());
}

ntdll contains the exported function NtSuspendProcess, pass the handle to a process to do the trick.

How can I perform static code analysis in PHP?

There a new tool called nWire for PHP. It is a code exploration plugin for Eclipse PDT and Zend Studio 7.x. It enables real-time code analysis for PHP and provides the following tools:

  • Code visualization - interactive graphical representation of components and associations.
  • Code navigation - unique navigation view shows all the associations and works with you while you write or read code.
  • Quick search - search as you type for methods, fields, file, etc.

Python integer incrementing with ++

You can do:

number += 1

How to enable file upload on React's Material UI simple input?

Just the same as what should be but change the button component to be label like so

<form id='uploadForm'
      action='http://localhost:8000/upload'
      method='post'
      encType="multipart/form-data">
    <input type="file" id="sampleFile" style="display: none;" />
    <Button htmlFor="sampleFile" component="label" type={'submit'}>Upload</Button> 
</form>

Getting absolute URLs using ASP.NET Core

You don't need to create an extension method for this

@Url.Action("Action", "Controller", values: null);

  • Action - Name of the action
  • Controller - Name of the controller
  • values - Object containing route values: aka GET parameters

There are also lots of other overloads to Url.Action you can use to generate links.

Intercept page exit event

Similar to Ghommey's answer, but this also supports old versions of IE and Firefox.

window.onbeforeunload = function (e) {
  var message = "Your confirmation message goes here.",
  e = e || window.event;
  // For IE and Firefox
  if (e) {
    e.returnValue = message;
  }

  // For Safari
  return message;
};

Guzzle 6: no more json() method for responses

I use json_decode($response->getBody()) now instead of $response->json().

I suspect this might be a casualty of PSR-7 compliance.