Programs & Examples On #Interstitial

Executing JavaScript after X seconds

onclick = "setTimeout(function() { document.getElementById('div1').style.display='none';document.getElementById('div2').style.display='none'}, 1000)"

Change 1000 to the number of milliseconds you want to delay.

Reading Space separated input in python

For Python3:

a, b = list(map(str, input().split()))
v = int(b)

How do I merge changes to a single file, rather than merging commits?

I came across the same problem. To be precise, I have two branches A and B with the same files but a different programming interface in some files. Now the methods of file f, which is independent of the interface differences in the two branches, were changed in branch B, but the change is important for both branches. Thus, I need to merge just file f of branch B into file f of branch A.

A simple command already solved the problem for me if I assume that all changes are committed in both branches A and B:

git checkout A

git checkout --patch B f

The first command switches into branch A, into where I want to merge B's version of the file f. The second command patches the file f with f of HEAD of B. You may even accept/discard single parts of the patch. Instead of B you can specify any commit here, it does not have to be HEAD.

Community edit: If the file f on B does not exist on A yet, then omit the --patch option. Otherwise, you'll get a "No Change." message.

Opening new window in HTML for target="_blank"

You can't influence neither type (tab/window) nor dimensions that way. You'll have to use JavaScript's window.open() for that.

How to output in CLI during execution of PHP Unit tests?

If you use Laravel, then you can use logging functions such as info() to log to the Laravel log file under storage/logs. So it won't appear in your terminal but in the log file.

JavaScript - onClick to get the ID of the clicked button

You need to send the ID as the function parameters. Do it like this:

_x000D_
_x000D_
<button id="1" onClick="reply_click(this.id)">B1</button>_x000D_
<button id="2" onClick="reply_click(this.id)">B2</button>_x000D_
<button id="3" onClick="reply_click(this.id)">B3</button>_x000D_
    _x000D_
<script type="text/javascript">_x000D_
  function reply_click(clicked_id)_x000D_
  {_x000D_
      alert(clicked_id);_x000D_
  }_x000D_
</script>
_x000D_
_x000D_
_x000D_

This will send the ID this.id as clicked_id which you can use in your function. See it in action here.

Exclude Blank and NA in R

A good idea is to set all of the "" (blank cells) to NA before any further analysis.

If you are reading your input from a file, it is a good choice to cast all "" to NAs:

foo <- read.table(file="Your_file.txt", na.strings=c("", "NA"), sep="\t") # if your file is tab delimited

If you have already your table loaded, you can act as follows:

foo[foo==""] <- NA

Then to keep only rows with no NA you may just use na.omit():

foo <- na.omit(foo)

Or to keep columns with no NA:

foo <- foo[, colSums(is.na(foo)) == 0] 

PHP: if !empty & empty

if(!empty($youtube) && empty($link)) {

}
else if(empty($youtube) && !empty($link)) {

}
else if(empty($youtube) && empty($link)) {
}

How to create an email form that can send email using html

As many answers in this thread already suggest it is not possible to send a mail from a static HTML page without using PHP or JS. I just wanted to add that there a some great solutions which will take your HTTP Post request generated by your form and create a mail from it. Those solutions are especially useful in case you do not want to add JS or PHP to your website.

Those servers basically can be configured with a mail-server which is responsible for then sending the email. The receiver, subject, body etc. is received by the server from your HTTP(S) post and then stuffed into the mail you want to send. So technically speaking it is still not possible to send mails from your HTML form but the outcome is the same.

Some of these solutions can be bought as SaaS solution or you can host them by yourself. I'll just name a few but I'm sure there are plenty in case anyone is interested in the technology or the service itself.

Formatting a Date String in React Native

There is no need to include a bulky library such as Moment.js to fix such a simple issue.

The issue you are facing is not with formatting, but with parsing.

As John Shammas mentions in another answer, the Date constructor (and Date.parse) are picky about the input. Your 2016-01-04 10:34:23 may work in one JavaScript implementation, but not necessarily in the other.

According to the specification of ECMAScript 5.1, Date.parse supports (a simplification of) ISO 8601. That's good news, because your date is already very ISO 8601-like.

All you have to do is change the input format just a little. Swap the space for a T: 2016-01-04T10:34:23; and optionally add a time zone (2016-01-04T10:34:23+01:00), otherwise UTC is assumed.

Eclipse/Java code completion not working

I experience problems on Eclipse Neon when editing a file which does not belong to the project directory. When I copy the same file to the project root directory, not even to the src directory, the completion starts working.

When the file is opened from a different directory, only completion for JRE works. That is for example: java. completes, but junit. does not.

How to convert .pfx file to keystore with private key?

Your PFX file should contain the private key within it. Export the private key and certificate directly from your PFX file (e.g. using OpenSSL) and import them into your Java keystore.

Edit

Further information:

  • Download OpenSSL for Windows here.
  • Export private key: openssl pkcs12 -in filename.pfx -nocerts -out key.pem
  • Export certificate: openssl pkcs12 -in filename.pfx -clcerts -nokeys -out cert.pem
  • Import private key and certificate into Java keystore using keytool.

How to generate JAXB classes from XSD?

In intellij click .xsd file -> WebServices ->Generate Java code from Xml Schema JAXB then give package path and package name ->ok

How do I exit the results of 'git diff' in Git Bash on windows?

Using WIN + Q worked for me. Just q alone gave me "command not found" and eventually it jumped back into the git diff insanity.

check if a std::vector contains a certain object?

If searching for an element is important, I'd recommend std::set instead of std::vector. Using this:

std::find(vec.begin(), vec.end(), x) runs in O(n) time, but std::set has its own find() member (ie. myset.find(x)) which runs in O(log n) time - that's much more efficient with large numbers of elements

std::set also guarantees all the added elements are unique, which saves you from having to do anything like if not contained then push_back()....

How to print a linebreak in a python function?

Also if you're making it a console program, you can do: print(" ") and continue your program. I've found it the easiest way to separate my text.

sql searching multiple words in a string

Oracle SQL:

There is the "IN" Operator in Oracle SQL which can be used for that:

select 
    namet.customerfirstname, addrt.city, addrt.postalcode
from schemax.nametable namet
join schemax.addresstable addrt on addrt.adtid = namet.natadtid
where namet.customerfirstname in ('David', 'Moses', 'Robi'); 

How to "git clone" including submodules?

Try this:

git clone --recurse-submodules

It automatically pulls in the submodule data assuming you have already added the submodules to the parent project.

Is there a function to split a string in PL/SQL?

You can use regexp_substr(). Example:

create or replace type splitTable_Type is table of varchar2(100);

declare
    l_split_table splitTable_Type;
begin
  select
      regexp_substr('SMITH,ALLEN,WARD,JONES','[^,]+', 1, level)
  bulk collect into
      l_split_table
  from dual
  connect by
      regexp_substr('SMITH,ALLEN,WARD,JONES', '[^,]+', 1, level) is not null;
end;

The query iterates through the comma separated string, searches for the comma (,) and then splits the string by treating the comma as delimiter. It returns the string as a row, whenever it hits a delimiter.

level in statement regexp_substr('SMITH,ALLEN,WARD,JONES','[^,]+', 1, level) refers to a pseudocolumn in Oracle which is used in a hierarchical query to identify the hierarchy level in numeric format: level in connect by

Latex Remove Spaces Between Items in List

You could do something like this:

\documentclass{article}

\begin{document}

Normal:

\begin{itemize}
  \item foo
  \item bar
  \item baz
\end{itemize}

Less space:

\begin{itemize}
  \setlength{\itemsep}{1pt}
  \setlength{\parskip}{0pt}
  \setlength{\parsep}{0pt}
  \item foo
  \item bar
  \item baz
\end{itemize}

\end{document}

Copy a file list as text from Windows Explorer

If you paste the listing into your word processor instead of Notepad, (since each file name is in quotation marks with the full path name), you can highlight all the stuff you don't want on the first file, then use Find and Replace to replace every occurrence of that with nothing. Same with the ending quote (").

It makes a nice clean list of file names.

How do I get the last inserted ID of a MySQL table in PHP?

NOTE: if you do multiple inserts with one statement mysqli::insert_id will not be correct.

The table:

create table xyz (id int(11) auto_increment, name varchar(255), primary key(id));

Now if you do:

insert into xyz (name) values('one'),('two'),('three');

The mysqli::insert_id will be 1 not 3.

To get the correct value do:

mysqli::insert_id + mysqli::affected_rows) - 1

This has been document but it is a bit obscure.

Get last n lines of a file, similar to tail

If reading the whole file is acceptable then use a deque.

from collections import deque
deque(f, maxlen=n)

Prior to 2.6, deques didn't have a maxlen option, but it's easy enough to implement.

import itertools
def maxque(items, size):
    items = iter(items)
    q = deque(itertools.islice(items, size))
    for item in items:
        del q[0]
        q.append(item)
    return q

If it's a requirement to read the file from the end, then use a gallop (a.k.a exponential) search.

def tail(f, n):
    assert n >= 0
    pos, lines = n+1, []
    while len(lines) <= n:
        try:
            f.seek(-pos, 2)
        except IOError:
            f.seek(0)
            break
        finally:
            lines = list(f)
        pos *= 2
    return lines[-n:]

while installing vc_redist.x64.exe, getting error "Failed to configure per-machine MSU package."

I faced a similar problem but in my case I was trying to install Visual C++ Redistributable for Visual Studio 2015 Update 1 on Windows Server 2012 R2. However the root cause should be the same.

In short, you need to install the prerequisites of KB2999226.

In more details, the installation log I got stated that the installation for Windows Update KB2999226 failed. According to the Microsoft website here:

Prerequisites To install this update, you must have April 2014 update rollup for Windows RT 8.1, Windows 8.1, and Windows Server 2012 R2 (2919355) installed in Windows 8.1 or Windows Server 2012 R2. Or, install Service Pack 1 for Windows 7 or Windows Server 2008 R2. Or, install Service Pack 2 for Windows Vista and for Windows Server 2008.

After I have installed April 2014 on my Windows Server 2012 R2, I am able to install the Visual C++ Redistributable correctly.

Is there an equivalent to the SUBSTRING function in MS Access SQL?

I have worked alot with msaccess vba. I think you are looking for MID function

example

    dim myReturn as string
    myreturn = mid("bonjour tout le monde",9,4)

will give you back the value "tout"

Make a directory and copy a file

Use the FileSystemObject object, namely, its CreateFolder and CopyFile methods. Basically, this is what your script will look like:

Dim oFSO
Set oFSO = CreateObject("Scripting.FileSystemObject")

' Create a new folder
oFSO.CreateFolder "C:\MyFolder"

' Copy a file into the new folder
' Note that the destination folder path must end with a path separator (\)
oFSO.CopyFile "\\server\folder\file.ext", "C:\MyFolder\"

You may also want to add additional logic, like checking whether the folder you want to create already exists (because CreateFolder raises an error in this case) or specifying whether or not to overwrite the file being copied. So, you can end up with this:

Const strFolder = "C:\MyFolder\", strFile = "\\server\folder\file.ext"
Const Overwrite = True
Dim oFSO

Set oFSO = CreateObject("Scripting.FileSystemObject")

If Not oFSO.FolderExists(strFolder) Then
  oFSO.CreateFolder strFolder
End If

oFSO.CopyFile strFile, strFolder, Overwrite

Regex pattern to match at least 1 number and 1 character in a string

The accepted answers is not worked as it is not allow to enter special characters.

Its worked perfect for me.

^(?=.*[0-9])(?=.*[a-zA-Z])(?=\S+$).{6,20}$

  • one digit must
  • one character must (lower or upper)
  • every other things optional

Thank you.

Passing an Object from an Activity to a Fragment

This one worked for me:

In Activity:

User user;
public User getUser(){ return this.user;}

In Fragment's onCreateView method:

User user = ((MainActivity)getActivity()).getUser(); 

Replace the MainActivity with your Activity Name.

Running an executable in Mac Terminal

Unix will only run commands if they are available on the system path, as you can view by the $PATH variable

echo $PATH

Executables located in directories that are not on the path cannot be run unless you specify their full location. So in your case, assuming the executable is in the current directory you are working with, then you can execute it as such

./my-exec

Where my-exec is the name of your program.

UIScrollView Scrollable Content Size Ambiguity

I know I may be late, but next solution solves this kind of problems without additional code, just using storyboards:

For your content view you need to set constraints for leading/trailing/top/bottom spaces to scrollview and this will not change content view frame, like this: enter image description here

Of course you need to create additional constraints for content view so scroll view could know content size. For example set fixed height and center x.

Hope this helps.

How do I get the HTML code of a web page in PHP?

Simple way: Use file_get_contents():

$page = file_get_contents('http://stackoverflow.com/questions/ask');

Please note that allow_url_fopen must be true in you php.ini to be able to use URL-aware fopen wrappers.

More advanced way: If you cannot change your PHP configuration, allow_url_fopen is false by default and if ext/curl is installed, use the cURL library to connect to the desired page.

How to install PyQt4 on Windows using pip?

I am using PyCharm, and was able to install PyQt5.

PyQt4, as well as PyQt4Enhanced and windows_whl both failed to install, I'm guessing that's because Qt4 is no longer supported.

Cannot uninstall angular-cli

For those using Windows, I had this issue because :

  • after running npm uninstall -g @ angular/cli, the folder AppData\Roaming\npm were still containing a ng file
  • this file prevented a complete uninstall of the CLI

I tried then to remove the ng file manually, but for some reasons it was not possible (I did not have the right), even as admin.

The only hack I found was using a 'linux based' command (I used Git bash) as admin and removing this file from command line: cd AppData/Roaming/npm rm ng.cmd

For information: this was with the version 6 of the CLI. There is not problem anymore to remove manually this specific file after the update.

Hashmap holding different data types as values for instance Integer, String and Object

Do simply like below....

HashMap<String,Object> yourHash = new HashMap<String,Object>();
yourHash.put(yourKey+"message","message");
yourHash.put(yourKey+"timestamp",timestamp);
yourHash.put(yourKey+"count ",count);
yourHash.put(yourKey+"version ",version);

typecast the value while getting back. For ex:

    int count = Integer.parseInt(yourHash.get(yourKey+"count"));
//or
int count = Integer.valueOf(yourHash.get(yourKey+"count"));
//or
int count = (Integer)yourHash.get(yourKey+"count"); //or (int)

how to get list of port which are in use on the server

TCPView is a Windows program that will show you detailed listings of all TCP and UDP endpoints on your system, including the local and remote addresses and state of TCP connections. On Windows Server 2008, Vista, NT, 2000 and XP TCPView also reports the name of the process that owns the endpoint. TCPView provides a more informative and conveniently presented subset of the Netstat program that ships with Windows. The TCPView download includes Tcpvcon, a command-line version with the same functionality.

http://technet.microsoft.com/en-us/sysinternals/bb897437.aspx

Remove special symbols and extra spaces and replace with underscore using the replace method

Remove the \s from your new regex and it should work - whitespace is already included in "anything but alphanumerics".

Note that you may want to add a + after the ] so you don't get sequences of more than one underscore. You can also chain onto .replace(/^_+|_+$/g,'') to trim off underscores at the start or end of the string.

iterating through Enumeration of hastable keys throws NoSuchElementException error

You call nextElement() twice in your loop. This call moves the enumeration pointer forward. You should modify your code like the following:

while (e.hasMoreElements()) {
    String param = e.nextElement();
    System.out.println(param);
}

How do I generate a list with a specified increment step?

Executing seq(1, 10, 1) does what 1:10 does. You can change the last parameter of seq, i.e. by, to be the step of whatever size you like.

> #a vector of even numbers
> seq(0, 10, by=2) # Explicitly specifying "by" only to increase readability 
> [1]  0  2  4  6  8 10

Can I call a base class's virtual function if I'm overriding it?

Yes you can call it. C++ syntax for calling parent class function in child class is

class child: public parent {
  // ...

  void methodName() {
    parent::methodName(); // calls Parent class' function
  }
};

Read more about function overriding.

How to run Unix shell script from Java code?

Here is my example. Hope it make sense.

public static void excuteCommand(String filePath) throws IOException{
    File file = new File(filePath);
    if(!file.isFile()){
        throw new IllegalArgumentException("The file " + filePath + " does not exist");
    }
    if(isLinux()){
        Runtime.getRuntime().exec(new String[] {"/bin/sh", "-c", filePath}, null);
    }else if(isWindows()){
        Runtime.getRuntime().exec("cmd /c start " + filePath);
    }
}
public static boolean isLinux(){
    String os = System.getProperty("os.name");  
    return os.toLowerCase().indexOf("linux") >= 0;
}

public static boolean isWindows(){
    String os = System.getProperty("os.name");
    return os.toLowerCase().indexOf("windows") >= 0;
}

Extract a part of the filepath (a directory) in Python

import os

directory = os.path.abspath('\\') # root directory
print(directory) # e.g. 'C:\'

directory = os.path.abspath('.') # current directory
print(directory) # e.g. 'C:\Users\User\Desktop'

parent_directory, directory_name = os.path.split(directory)
print(directory_name) # e.g. 'Desktop'
parent_parent_directory, parent_directory_name = os.path.split(parent_directory)
print(parent_directory_name) # e.g. 'User'

This should also do the trick.

number of values in a list greater than a certain number

I'll add a map and filter version because why not.

sum(map(lambda x:x>5, j))
sum(1 for _ in filter(lambda x:x>5, j))

C++ Calling a function from another class

in A you have used a definition of B which is not given until then , that's why the compiler is giving error .

isPrime Function for Python Language

Implemented a pseudocode (https://en.wikipedia.org/wiki/Primality_test) in python, hope this help.

# original pseudocode https://en.wikipedia.org/wiki/Primality_test
def isPrime(n):
    # Corner Cases
    if (n<= 1): return False
    elif (n<= 3): return True
    elif (n%2 == 0 or n%3 == 0): return False

    i = 5
    while i*i<=n:
        if (n%i==0 or n%(i+2)==0): return False
        i += 6

    return True;

%timeit isPrime(800)

How to get the pure text without HTML element using JavaScript?

That should work:

function get_content(){
   var p = document.getElementById("txt");
   var spans = p.getElementsByTagName("span");
   var text = '';
   for (var i = 0; i < spans.length; i++){
       text += spans[i].innerHTML;
   }

   p.innerHTML = text;
}

Try this fiddle: http://jsfiddle.net/7gnyc/2/

How do I use Ruby for shell scripting?

As the others have said already, your first line should be

#!/usr/bin/env ruby

And you also have to make it executable: (in the shell)

chmod +x test.rb

Then follows the ruby code. If you open a file

File.open("file", "r") do |io|
    # do something with io
end

the file is opened in the current directory you'd get with pwd in the shell.

The path to your script is also simple to get. With $0 you get the first argument of the shell, which is the relative path to your script. The absolute path can be determined like that:

#!/usr/bin/env ruby
require 'pathname'
p Pathname.new($0).realpath()

For file system operations I almost always use Pathname. This is a wrapper for many of the other file system related classes. Also useful: Dir, File...

C# : 'is' keyword and checking for Not

The extension method IsNot<T> is a nice way to extend the syntax. Keep in mind

var container = child as IContainer;
if(container != null)
{
  // do something w/ contianer
}

performs better than doing something like

if(child is IContainer)
{
  var container = child as IContainer;
  // do something w/ container
}

In your case, it doesn't matter as you are returning from the method. In other words, be careful to not do both the check for type and then the type conversion immediately after.

How to draw a standard normal distribution in R

By the way, instead of generating the x and y coordinates yourself, you can also use the curve() function, which is intended to draw curves corresponding to a function (such as the density of a standard normal function).

see

help(curve)

and its examples.

And if you want to add som text to properly label the mean and standard deviations, you can use the text() function (see also plotmath, for annotations with mathematical symbols) .

see

help(text)
help(plotmath)

onclick on a image to navigate to another page using Javascript

You can define a a click function and then set the onclick attribute for the element.

function imageClick(url) {
    window.location = url;
}

<img src="../images/bottle.jpg" alt="bottle" class="thumbnails" onclick="imageClick('../images/bottle.html')" />

This approach lets you get rid of the surrounding <a> element. If you want to keep it, then define the onclick attribute on <a> instead of on <img>.

The smallest difference between 2 Angles

For UnityEngine users, the easy way is just to use Mathf.DeltaAngle.

MySql export schema without data

You can use the -d option with mysqldump command

mysqldump -u root -p -d databasename > database.sql

How to check if BigDecimal variable == 0 in java?

You would want to use equals() since they are objects, and utilize the built in ZERO instance:

if (selectPrice.equals(BigDecimal.ZERO))

Note that .equals() takes scale into account, so unless selectPrice is the same scale (0) as .ZERO then this will return false.

To take scale out of the equation as it were:

if (selectPrice.compareTo(BigDecimal.ZERO) == 0)

I should note that for certain mathematical situations, 0.00 != 0, which is why I imagine .equals() takes the scale into account. 0.00 gives precision to the hundredths place, whereas 0 is not that precise. Depending on the situation you may want to stick with .equals().

Export HTML table to pdf using jspdf

Here is working example:

in head

<script type="text/javascript" src="jspdf.debug.js"></script>

script:

<script type="text/javascript">
        function demoFromHTML() {
            var pdf = new jsPDF('p', 'pt', 'letter');
            // source can be HTML-formatted string, or a reference
            // to an actual DOM element from which the text will be scraped.
            source = $('#customers')[0];

            // we support special element handlers. Register them with jQuery-style 
            // ID selector for either ID or node name. ("#iAmID", "div", "span" etc.)
            // There is no support for any other type of selectors 
            // (class, of compound) at this time.
            specialElementHandlers = {
                // element with id of "bypass" - jQuery style selector
                '#bypassme': function(element, renderer) {
                    // true = "handled elsewhere, bypass text extraction"
                    return true
                }
            };
            margins = {
                top: 80,
                bottom: 60,
                left: 40,
                width: 522
            };
            // all coords and widths are in jsPDF instance's declared units
            // 'inches' in this case
            pdf.fromHTML(
                    source, // HTML string or DOM elem ref.
                    margins.left, // x coord
                    margins.top, {// y coord
                        'width': margins.width, // max width of content on PDF
                        'elementHandlers': specialElementHandlers
                    },
            function(dispose) {
                // dispose: object with X, Y of the last line add to the PDF 
                //          this allow the insertion of new lines after html
                pdf.save('Test.pdf');
            }
            , margins);
        }
    </script>

and table:

<div id="customers">
        <table id="tab_customers" class="table table-striped" >
            <colgroup>
                <col width="20%">
                <col width="20%">
                <col width="20%">
                <col width="20%">
            </colgroup>
            <thead>         
                <tr class='warning'>
                    <th>Country</th>
                    <th>Population</th>
                    <th>Date</th>
                    <th>Age</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>Chinna</td>
                    <td>1,363,480,000</td>
                    <td>March 24, 2014</td>
                    <td>19.1</td>
                </tr>
                <tr>
                    <td>India</td>
                    <td>1,241,900,000</td>
                    <td>March 24, 2014</td>
                    <td>17.4</td>
                </tr>
                <tr>
                    <td>United States</td>
                    <td>317,746,000</td>
                    <td>March 24, 2014</td>
                    <td>4.44</td>
                </tr>
                <tr>
                    <td>Indonesia</td>
                    <td>249,866,000</td>
                    <td>July 1, 2013</td>
                    <td>3.49</td>
                </tr>
                <tr>
                    <td>Brazil</td>
                    <td>201,032,714</td>
                    <td>July 1, 2013</td>
                    <td>2.81</td>
                </tr>
            </tbody>
        </table> 
    </div>

and button to run:

<button onclick="javascript:demoFromHTML()">PDF</button>

and working example online:

tabel to pdf jspdf

or try this: HTML Table Export

Best way to extract a subvector from a vector?

You can use STL copy with O(M) performance when M is the size of the subvector.

select dept names who have more than 2 employees whose salary is greater than 1000

select min(DEPARTMENT.DeptName) as deptname 
from DEPARTMENT
inner join employee on
DEPARTMENT.DeptId = employee.DeptId
where Salary > 1000
group by (EmpId) having count(EmpId) > =2 

How to escape the % (percent) sign in C's printf?

You can use %%:

printf("100%%");

The result is:

100%

Is it possible to use jQuery .on and hover?

None of these solutions worked for me when mousing over/out of objects created after the document has loaded as the question requests. I know this question is old but I have a solution for those still looking:

$("#container").on('mouseenter', '.selector', function() {
    //do something
});
$("#container").on('mouseleave', '.selector', function() {
    //do something
});

This will bind the functions to the selector so that objects with this selector made after the document is ready will still be able to call it.

Cannot start MongoDB as a service

Following works with MongoDB 3.6.0

Make sure you have these folders:

  • C:\mongodb\data
  • C:\mongodb\data\db

Then all you need are these commands:

  • mongod --directoryperdb -dbpath C:\mongodb\data\db --logpath C:\mongodb\log\mongo.log --logappend --service --install
  • net start MongoDB
  • mongo

Quick-and-dirty way to ensure only one instance of a shell script is running at a time

PID and lockfiles are definitely the most reliable. When you attempt to run the program, it can check for the lockfile which and if it exists, it can use ps to see if the process is still running. If it's not, the script can start, updating the PID in the lockfile to its own.

How do I find the version of Apache running without access to the command line?

httpd -v will give you the version of Apache running on your server (if you have SSH/shell access).

The output should be something like this:

Server version: Apache/2.2.3
Server built:   Oct 20 2011 17:00:12

As has been suggested you can also do apachectl -v which will give you the same output, but will be supported by more flavours of Linux.

Mongodb service won't start

After running the repair I was able to start the mongod proccessor but as root, which meant that service mongod start would not work. To repair this issue, I needed to make sure that all the files inside the database folder were owned and grouped to mongod. I did this by the following:

  1. Check the file permissions inside your database folder
    1. note you need to be in your dbpath folder mine was /var/lib/mongo I went to cd /var/lib
    2. I ran ls -l mongo
  2. This showed me that databases were owned by root, which is wrong. I ran the following to fix this: chown -R mongod:mongod mongo. This changed the owner and group of every file in the folder to mongod. (If using the mongodb package, chown -R mongodb:mongodb mongodb)

I hope this helps someone else in the future.

How to merge a list of lists with same type of items to a single list of items?

For List<List<List<x>>> and so on, use

list.SelectMany(x => x.SelectMany(y => y)).ToList();

This has been posted in a comment, but it does deserves a separate reply in my opinion.

Access restriction on class due to restriction on required library rt.jar?

I have been getting this error too, but my project is built on the command line using Maven and the tycho compiler (it's a set of OSGi plugins). After masses of sifting through people having the same problem but fixing it in Eclipse rather than on the command line, I found a message on the Tycho developer forum that answered my question, using configuration in pom.xml to ignore the compiler warning about the access restriction:

<plugin>
    <groupId>org.eclipse.tycho</groupId>
    <artifactId>tycho-compiler-plugin</artifactId>
    <version>${tycho.version}</version>
    <configuration>
        <compilerArgument>-warn:+discouraged,forbidden</compilerArgument>
    </configuration>
</plugin>

More information can be found in the Tycho FAQ. This took me AGES to work out, so I figured I would assist anyone else trying to fix these access restriction errors from the command line by posting this answer.

Add a auto increment primary key to existing table in oracle

Snagged from Oracle OTN forums

Use alter table to add column, for example:

alter table tableName add(columnName NUMBER);

Then create a sequence:

CREATE SEQUENCE SEQ_ID
START WITH 1
INCREMENT BY 1
MAXVALUE 99999999
MINVALUE 1
NOCYCLE;

and, the use update to insert values in column like this

UPDATE tableName SET columnName = seq_test_id.NEXTVAL

How do I use su to execute the rest of the bash script as that user?

You need to execute all the different-user commands as their own script. If it's just one, or a few commands, then inline should work. If it's lots of commands then it's probably best to move them to their own file.

su -c "cd /home/$USERNAME/$PROJECT ; svn update" -m "$USERNAME" 

Convert python long/int to fixed size byte array

Basically what you need to do is convert the int/long into its base 256 representation -- i.e. a number whose "digits" range from 0-255. Here's a fairly efficient way to do something like that:

def base256_encode(n, minwidth=0): # int/long to byte array
    if n > 0:
        arr = []
        while n:
            n, rem = divmod(n, 256)
            arr.append(rem)
        b = bytearray(reversed(arr))
    elif n == 0:
        b = bytearray(b'\x00')
    else:
        raise ValueError

    if minwidth > 0 and len(b) < minwidth: # zero padding needed?
        b = (minwidth-len(b)) * '\x00' + b
    return b

You many not need thereversed()call depending on the endian-ness desired (doing so would require the padding to be done differently as well). Also note that as written it doesn't handle negative numbers.

You might also want to take a look at the similar but highly optimized long_to_bytes() function in thenumber.pymodule which is part of the open source Python Cryptography Toolkit. It actually converts the number into a string, not a byte array, but that's a minor issue.

How to exit an if clause

use return in the if condition will returns you out from the function, so that you can use return to break the the if condition.

In the shell, what does " 2>&1 " mean?

People, always remember paxdiablo's hint about the current location of the redirection target... It is important.

My personal mnemonic for the 2>&1 operator is this:

  • Think of & as meaning 'and' or 'add' (the character is an ampers-and, isn't it?)
  • So it becomes: 'redirect 2 (stderr) to where 1 (stdout) already/currently is and add both streams'.

The same mnemonic works for the other frequently used redirection too, 1>&2:

  • Think of & meaning and or add... (you get the idea about the ampersand, yes?)
  • So it becomes: 'redirect 1 (stdout) to where 2 (stderr) already/currently is and add both streams'.

And always remember: you have to read chains of redirections 'from the end', from right to left (not from left to right).

JavaScript and getElementById for multiple elements with the same ID

The HTML spec required the ID attribute to be unique in a page:

This attribute assigns a name to an element. This name must be unique in a document.

If you have several elements with the same ID, your HTML is not valid.

So, getElementById() should only ever return one element. You can't make it return multiple elements.

There are a couple of related functions that will return an array of elements - getElementsByName, or getElementsByClassName that may be more suited to your requirements, though getElementsByClassName is new to HTML 5, which is still in draft.

Rendering JSON in controller

You'll normally be returning JSON either because:

A) You are building part / all of your application as a Single Page Application (SPA) and you need your client-side JavaScript to be able to pull in additional data without fully reloading the page.

or

B) You are building an API that third parties will be consuming and you have decided to use JSON to serialize your data.

Or, possibly, you are eating your own dogfood and doing both

In both cases render :json => some_data will JSON-ify the provided data. The :callback key in the second example needs a bit more explaining (see below), but it is another variation on the same idea (returning data in a way that JavaScript can easily handle.)

Why :callback?

JSONP (the second example) is a way of getting around the Same Origin Policy that is part of every browser's built-in security. If you have your API at api.yoursite.com and you will be serving your application off of services.yoursite.com your JavaScript will not (by default) be able to make XMLHttpRequest (XHR - aka ajax) requests from services to api. The way people have been sneaking around that limitation (before the Cross-Origin Resource Sharing spec was finalized) is by sending the JSON data over from the server as if it was JavaScript instead of JSON). Thus, rather than sending back:

{"name": "John", "age": 45}

the server instead would send back:

valueOfCallbackHere({"name": "John", "age": 45})

Thus, a client-side JS application could create a script tag pointing at api.yoursite.com/your/endpoint?name=John and have the valueOfCallbackHere function (which would have to be defined in the client-side JS) called with the data from this other origin.)

new Date() is working in Chrome but not Firefox

I have used following date format and it's working in all browser.

var target_date = new Date("Jul 17, 2015 16:55:22").getTime();

var days, hours, minutes, seconds;

var countdown = document.getElementById("countdown");

remaining = setInterval(function () {

    var current_date = new Date().getTime();
    var seconds_left = (target_date - current_date) / 1000;
    days = parseInt(seconds_left / 86400);
    seconds_left = seconds_left % 86400;
    hours = parseInt(seconds_left / 3600);
    seconds_left = seconds_left % 3600;
    minutes = parseInt(seconds_left / 60);
    seconds = parseInt(seconds_left % 60);
    countdown.innerHTML = "<b>"+days + " day, " + hours + " hour, "
        + minutes + " minute, " + seconds + " second.</b>";  
}, 1000);

How to do one-liner if else statement?

Ternary ? operator alternatives | golang if else one line You can’t write a short one-line conditional in Go language ; there is no ternary conditional operator. Read more about if..else of Golang

ASP.NET GridView RowIndex As CommandArgument

Here is a very simple way:

<asp:ButtonField ButtonType="Button" CommandName="Edit" Text="Edit" Visible="True" 
                 CommandArgument='<%# Container.DataItemIndex %>' />

Convert tabs to spaces in Notepad++

CLR Tabs to Spaces plugin should be a good option. I have used it and it worked.

How to write/update data into cells of existing XLSX workbook using xlsxwriter in python

You can do by xlwings as well

import xlwings as xw
for book in xlwings.books:
    print(book)

Align two divs horizontally side by side center to the page using bootstrap css

This should do the trick:

<div class="container">
    <div class="row">
        <div class="col-xs-6">
            ONE
        </div>
        <div class="col-xs-6">
            TWO
        </div>
    </div>
</div>

Have a read of the grid system section of the Bootstrap docs to familiarise yourself with how Bootstrap's grids work:

http://getbootstrap.com/css/#grid

Return list from async/await method

you can use the following

private async Task<List<string>> GetItems()
{
    return await Task.FromResult(new List<string> 
    { 
      "item1", "item2", "item3" 
    });
}

Change Git repository directory location.

If you are using GitHub Desktop, then just do the following steps:

  1. Close GitHub Desktop and all other applications with open files to your current directory path.
  2. Move the whole directory as mentioned above to the new directory location.
  3. Open GitHub Desktop and click on the blue (!) "repository not found" icon. Then a dialog will open and you will see a "Locate..." button which will open a popup allowing you to direct its path to a new location.

Prevent linebreak after </div>

try float your div's in css

.label {
float:left;
width:200px;
}
.text {
float:left;
}

How do I style a <select> dropdown with only CSS?

It is possible, but unfortunately mostly in WebKit-based browsers to the extent we, as developers, require. Here is the example of CSS styling gathered from Chrome options panel via built-in developer tools inspector, improved to match currently supported CSS properties in most modern browsers:

select {
    -webkit-appearance: button;
    -moz-appearance: button;
    -webkit-user-select: none;
    -moz-user-select: none;
    -webkit-padding-end: 20px;
    -moz-padding-end: 20px;
    -webkit-padding-start: 2px;
    -moz-padding-start: 2px;
    background-color: #F07575; /* Fallback color if gradients are not supported */
    background-image: url(../images/select-arrow.png), -webkit-linear-gradient(top, #E5E5E5, #F4F4F4); /* For Chrome and Safari */
    background-image: url(../images/select-arrow.png), -moz-linear-gradient(top, #E5E5E5, #F4F4F4); /* For old Firefox (3.6 to 15) */
    background-image: url(../images/select-arrow.png), -ms-linear-gradient(top, #E5E5E5, #F4F4F4); /* For pre-releases of Internet Explorer  10*/
    background-image: url(../images/select-arrow.png), -o-linear-gradient(top, #E5E5E5, #F4F4F4); /* For old Opera (11.1 to 12.0) */
    background-image: url(../images/select-arrow.png), linear-gradient(to bottom, #E5E5E5, #F4F4F4); /* Standard syntax; must be last */
    background-position: center right;
    background-repeat: no-repeat;
    border: 1px solid #AAA;
    border-radius: 2px;
    box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.1);
    color: #555;
    font-size: inherit;
    margin: 0;
    overflow: hidden;
    padding-top: 2px;
    padding-bottom: 2px;
    text-overflow: ellipsis;
    white-space: nowrap;
}

When you run this code on any page within a WebKit-based browser it should change the appearance of the select box, remove standard OS-arrow and add a PNG-arrow, put some spacing before and after the label, almost anything you want.

The most important part is appearance property, which changes how the element behaves.

It works perfectly in almost all WebKit-based browser, including mobile ones, though Gecko doesn't support appearance as well as WebKit, it seems.

How to do a SUM() inside a case statement in SQL server

The error you posted can happen when you're using a clause in the GROUP BY statement without including it in the select.

Example

This one works!

     SELECT t.device,
            SUM(case when transits.direction = 1 then 1 else 0 end) ,
            SUM(case when transits.direction = 0 then 1 else 0 end) from t1 t 
            where t.device in ('A','B') group by t.device

This one not (omitted t.device from the select)

     SELECT 
            SUM(case when transits.direction = 1 then 1 else 0 end) ,
            SUM(case when transits.direction = 0 then 1 else 0 end) from t1 t 
            where t.device in ('A','B') group by t.device

This will produce your error complaining that I'm grouping for something that is not included in the select

Please, provide all the query to get more support.

How to clear all input fields in a specific div with jQuery?

inspired from https://stackoverflow.com/a/10892768/2087666 but I use the selector instead of a class and prefer if over switch:

function clearAllInputs(selector) {
  $(selector).find(':input').each(function() {
    if(this.type == 'submit'){
          //do nothing
      }
      else if(this.type == 'checkbox' || this.type == 'radio') {
        this.checked = false;
      }
      else if(this.type == 'file'){
        var control = $(this);
        control.replaceWith( control = control.clone( true ) );
      }else{
        $(this).val('');
      }
   });
}

this should take care of almost all input inside any selector.

How to make a local variable (inside a function) global

If you need access to the internal states of a function, you're possibly better off using a class. You can make a class instance behave like a function by making it a callable, which is done by defining __call__:

class StatefulFunction( object ):
    def __init__( self ):
        self.public_value = 'foo'

    def __call__( self ):
        return self.public_value


>> f = StatefulFunction()
>> f()
`foo`
>> f.public_value = 'bar'
>> f()
`bar`

jQuery to serialize only elements within a div

No problem. Just use the following. This will behave exactly like serializing a form but using a div's content instead.

$('#divId :input').serialize();

Check https://jsbin.com/xabureladi/1 for a demonstration (https://jsbin.com/xabureladi/1/edit for the code)

How to deal with page breaks when printing a large HTML table

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Test</title>
<style type="text/css">
    table { page-break-inside:auto }
    tr    { page-break-inside:avoid; page-break-after:auto }
    thead { display:table-header-group }
    tfoot { display:table-footer-group }
</style>
</head>
<body>
    <table>
        <thead>
            <tr><th>heading</th></tr>
        </thead>
        <tfoot>
            <tr><td>notes</td></tr>
        </tfoot>
        <tbody>
        <tr>
            <td>x</td>
        </tr>
        <tr>
            <td>x</td>
        </tr>
        <!-- 500 more rows -->
        <tr>
            <td>x</td>
        </tr>
    </tbody>
    </table>
</body>
</html>

Writing a Python list of lists to a csv file

Using csv.writer in my very large list took quite a time. I decided to use pandas, it was faster and more easy to control and understand:

 import pandas

 yourlist = [[...],...,[...]]
 pd = pandas.DataFrame(yourlist)
 pd.to_csv("mylist.csv")

The good part you can change somethings to make a better csv file:

 yourlist = [[...],...,[...]]
 columns = ["abcd","bcde","cdef"] #a csv with 3 columns
 index = [i[0] for i in yourlist] #first element of every list in yourlist
 not_index_list = [i[1:] for i in yourlist]
 pd = pandas.DataFrame(not_index_list, columns = columns, index = index)

 #Now you have a csv with columns and index:
 pd.to_csv("mylist.csv")

What is the opposite of evt.preventDefault();

There is no opposite method of event.preventDefault() to understand why you first have to look into what event.preventDefault() does when you call it.

Underneath the hood, the functionality for preventDefault is essentially calling a return false which halts any further execution. If you’re familiar with the old ways of Javascript, it was once in fashion to use return false for canceling events on things like form submits and buttons using return true (before jQuery was even around).

As you probably might have already worked out based on the simple explanation above: the opposite of event.preventDefault() is nothing. You just don’t prevent the event, by default the browser will allow the event if you are not preventing it.

See below for an explanation:

;(function($, window, document, undefined)) {

    $(function() {
        // By default deny the submit
        var allowSubmit = false;

        $("#someform").on("submit", function(event) {

            if (!allowSubmit) {
                event.preventDefault();

                // Your code logic in here (maybe form validation or something)
                // Then you set allowSubmit to true so this code is bypassed

                allowSubmit = true;
            }

        });
    });

})(jQuery, window, document);

In the code above you will notice we are checking if allowSubmit is false. This means we will prevent our form from submitting using event.preventDefault and then we will do some validation logic and if we are happy, set allowSubmit to true.

This is really the only effective method of doing the opposite of event.preventDefault() – you can also try removing events as well which essentially would achieve the same thing.

Python: Convert timedelta to int in a dataframe

Timedelta objects have read-only instance attributes .days, .seconds, and .microseconds.

Spring Boot - Cannot determine embedded database driver class for database type NONE

Now that I look closer, I think that the DataSource problem is a red-herring. Boot's Hibernate auto-configuration is being triggered and that's what causing a DataSource to be required. Hibernate's on the classpath because you've got a dependency on spring-boot-starter-data-jpa which pulls in hibernate-entitymanager.

Update your spring-boot-starter-data-jpa dependency to exclude Hibernate:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
        </exclusion>
    </exclusions>
</dependency>

c# - approach for saving user settings in a WPF application?

In my experience storing all the settings in a database table is the best solution. Don't even worry about performance. Today's databases are fast and can easily store thousands columns in a table. I learned this the hard way - before I was serilizing/deserializing - nightmare. Storing it in local file or registry has one big problem - if you have to support your app and computer is off - user is not in front of it - there is nothing you can do.... if setings are in DB - you can changed them and viola not to mention that you can compare the settings....

Remove "whitespace" between div element

You can remove extra space inside DIv by using below property of CSS in a parent (container) div element

display:inline-flex

Before Adding dislay:inline-flex;

After Adding display:inline-flex; in css

How to read file binary in C#?

Well, reading it isn't hard, just use FileStream to read a byte[]. Converting it to text isn't really generally possible or meaningful unless you convert the 1's and 0's to hex. That's easy to do with the BitConverter.ToString(byte[]) overload. You'd generally want to dump 16 or 32 bytes in each line. You could use Encoding.ASCII.GetString() to try to convert the bytes to characters. A sample program that does this:

using System;
using System.IO;
using System.Text;

class Program {
    static void Main(string[] args) {
        // Read the file into <bits>
        var fs = new FileStream(@"c:\temp\test.bin", FileMode.Open);
        var len = (int)fs.Length;
        var bits = new byte[len];
        fs.Read(bits, 0, len);
        // Dump 16 bytes per line
        for (int ix = 0; ix < len; ix += 16) {
            var cnt = Math.Min(16, len - ix);
            var line = new byte[cnt];
            Array.Copy(bits, ix, line, 0, cnt);
            // Write address + hex + ascii
            Console.Write("{0:X6}  ", ix);
            Console.Write(BitConverter.ToString(line));
            Console.Write("  ");
            // Convert non-ascii characters to .
            for (int jx = 0; jx < cnt; ++jx)
                if (line[jx] < 0x20 || line[jx] > 0x7f) line[jx] = (byte)'.';
            Console.WriteLine(Encoding.ASCII.GetString(line));
        }
        Console.ReadLine();
    }
}

jquery find element by specific class when element has multiple classes

you are looking for http://api.jquery.com/hasClass/

<div id="mydiv" class="foo bar"></div>

$('#mydiv').hasClass('foo') //returns ture

Python - Locating the position of a regex match in a string?

re.Match objects have a number of methods to help you with this:

>>> m = re.search("is", String)
>>> m.span()
(2, 4)
>>> m.start()
2
>>> m.end()
4

ValueError when checking if variable is None or numpy.array

If you are trying to do something very similar: a is not None, the same issue comes up. That is, Numpy complains that one must use a.any or a.all.

A workaround is to do:

if not (a is None):
    pass

Not too pretty, but it does the job.

How to get the selected radio button value using js

Possibly not the most efficient way... but I have used an ID on each radio button (this is just because I'm not passing it as an actual form, it is just the raw fields).

I then call a function with a button, which checks each radio button to see if it is checked. It does this using the .checked function. If this is set to true I can change the value of another variable.

_x000D_
_x000D_
function createOutput() {_x000D_
  var order = "in";_x000D_
  if (document.getElementById('radio1').checked == true) {_x000D_
    order = "pre";_x000D_
  } else if (document.getElementById('radio2').checked == true) {_x000D_
    order = "in";_x000D_
  } else if (document.getElementById('radio3').checked == true) {_x000D_
    order = "post";_x000D_
  }_x000D_
  document.getElementById('outputBox').innerHTML = order;_x000D_
}
_x000D_
<input id="radio1" type="radio" name="order" value="preorder" />Preorder_x000D_
<input id="radio2" type="radio" name="order" value="inorder" checked="true" />Inorder_x000D_
<input id="radio3" type="radio" name="order" value="postorder" />Postorder_x000D_
<button onclick="createOutput();">Generate Output</button>_x000D_
<textarea id="outputBox" rows="10" cols="50"></textarea>
_x000D_
_x000D_
_x000D_

Hope this is useful, in someway,

Beanz

ASP.net Getting the error "Access to the path is denied." while trying to upload files to my Windows Server 2008 R2 Web server

Right click on your folder on your server or local machine and give full permissions to

IIS_IUSRS

that's it.

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

Complete guide : https://developer.android.com/studio/build/application-id.html

As per Android official Blogs : https://android-developers.googleblog.com/2011/06/things-that-cannot-change.html

We can say that:

  • If the manifest package name has changed, the new application will be installed alongside the old application, so they both co-exist on the user’s device at the same time.

  • If the signing certificate changes, trying to install the new application on to the device will fail until the old version is uninstalled.

As per Google App Update check list : https://support.google.com/googleplay/android-developer/answer/113476?hl=en

Update your apps

Prepare your APK

When you're ready to make changes to your APK, make sure to update your app’s version code as well so that existing users will receive your update.

Use the following checklist to make sure your new APK is ready to update your existing users:

  • The package name of the updated APK needs to be the same as the current version.
  • The version code needs to be greater than that current version. Learn more about versioning your applications.
  • The updated APK needs to be signed with the same signature as the current version.

To verify that your APK is using the same certification as the previous version, you can run the following command on both APKs and compare the results:

$ jarsigner -verify -verbose -certs my_application.apk

If the results are identical, you’re using the same key and are ready to continue. If the results are different, you will need to re-sign the APK with the correct key.

Learn more about signing your applications

Upload your APK Once your APK is ready, you can create a new release.

How to output to the console and file?

Use logging module (http://docs.python.org/library/logging.html):

import logging

logger = logging.getLogger('scope.name')

file_log_handler = logging.FileHandler('logfile.log')
logger.addHandler(file_log_handler)

stderr_log_handler = logging.StreamHandler()
logger.addHandler(stderr_log_handler)

# nice output format
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
file_log_handler.setFormatter(formatter)
stderr_log_handler.setFormatter(formatter)

logger.info('Info message')
logger.error('Error message')

Remove NA values from a vector

Trying ?max, you'll see that it actually has a na.rm = argument, set by default to FALSE. (That's the common default for many other R functions, including sum(), mean(), etc.)

Setting na.rm=TRUE does just what you're asking for:

d <- c(1, 100, NA, 10)
max(d, na.rm=TRUE)

If you do want to remove all of the NAs, use this idiom instead:

d <- d[!is.na(d)]

A final note: Other functions (e.g. table(), lm(), and sort()) have NA-related arguments that use different names (and offer different options). So if NA's cause you problems in a function call, it's worth checking for a built-in solution among the function's arguments. I've found there's usually one already there.

Java get String CompareTo as a comparator object

The Arrays class has versions of sort() and binarySearch() which don't require a Comparator. For example, you can use the version of Arrays.sort() which just takes an array of objects. These methods call the compareTo() method of the objects in the array.

How to make a Python script run like a service or daemon in Linux

to creating some thing that is running like service you can use this thing :

The first thing that you must do is installing the Cement framework: Cement frame work is a CLI frame work that you can deploy your application on it.

command line interface of the app :

interface.py

 from cement.core.foundation import CementApp
 from cement.core.controller import CementBaseController, expose
 from YourApp import yourApp

 class Meta:
    label = 'base'
    description = "your application description"
    arguments = [
        (['-r' , '--run'],
          dict(action='store_true', help='Run your application')),
        (['-v', '--version'],
          dict(action='version', version="Your app version")),
        ]
        (['-s', '--stop'],
          dict(action='store_true', help="Stop your application")),
        ]

    @expose(hide=True)
    def default(self):
        if self.app.pargs.run:
            #Start to running the your app from there !
            YourApp.yourApp()
        if self.app.pargs.stop:
            #Stop your application
            YourApp.yourApp.stop()

 class App(CementApp):
       class Meta:
       label = 'Uptime'
       base_controller = 'base'
       handlers = [MyBaseController]

 with App() as app:
       app.run()

YourApp.py class:

 import threading

 class yourApp:
     def __init__:
        self.loger = log_exception.exception_loger()
        thread = threading.Thread(target=self.start, args=())
        thread.daemon = True
        thread.start()

     def start(self):
        #Do every thing you want
        pass
     def stop(self):
        #Do some things to stop your application

Keep in mind that your app must run on a thread to be daemon

To run the app just do this in command line

python interface.py --help

ImportError: No module named 'MySQL'

You need to use anaconda to manage python environment dependencies. MySQL connector can be installed using conda installer

conda install -c anaconda mysql-connector-python

Git error on git pull (unable to update local ref)

What worked for me was:

git config --global fetch.prune true

Now it keeps on running prune automatically.

How to clear PermGen space Error in tomcat

The PermGen space is what Tomcat uses to store class definitions (definitions only, no instantiations) and string pools that have been interned. From experience, the PermGen space issues tend to happen frequently in dev environments really since Tomcat has to load new classes every time it deploys a WAR or does a jspc (when you edit a jsp file). Personally, I tend to deploy and redeploy wars a lot when I’m in dev testing so I know I’m bound to run out sooner or later (primarily because Java’s GC cycles are still kinda crap so if you redeploy your wars quickly and frequently enough, the space fills up faster than they can manage).

This should theoretically be less of an issue in production environments since you (hopefully) don’t change the codebase on a 10 minute basis. If it still occurs, that just means your codebase (and corresponding library dependencies) are too large for the default memory allocation and you’ll just need to mess around with stack and heap allocation. I think the standards are stuff like:

-XX:MaxPermSize=SIZE

I’ve found however the best way to take care of that for good is to allow classes to be unloaded so your PermGen never runs out:

-XX:+CMSClassUnloadingEnabled -XX:+CMSPermGenSweepingEnabled

Stuff like that worked magic for me in the past. One thing tho, there’s a significant performance tradeoff in using those, since permgen sweeps will make like an extra 2 requests for every request you make or something along those lines. You’ll need to balance your use with the tradeoffs.

NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder

Add the all tiles jars like(tiles-jsp,tiles-servlet,tiles-template,tiles-extras.tiles-core ) to your server lib folder and your application build path then it work if you using apache tailes with spring mvc application

What is the difference between MVC and MVVM?

Well, generally MVC is used in Web development and MVVM is most popular in WPF/Silverlight development. However, sometimes the web architecute might have a mix of MVC and MVVM.

For example: you might use knockout.js and in this case you will have MVVM on your client side. And your MVC's server side can also change. In the complex apps, nobody uses the pure Model. It might have a sense to use a ViewModel as a "Model" of MVC and your real Model basically will be a part of this VM. This gives you an extra abstraction layer.

How to do date/time comparison

Recent protocols prefer usage of RFC3339 per golang time package documentation.

In general RFC1123Z should be used instead of RFC1123 for servers that insist on that format, and RFC3339 should be preferred for new protocols. RFC822, RFC822Z, RFC1123, and RFC1123Z are useful for formatting; when used with time.Parse they do not accept all the time formats permitted by the RFCs.

cutOffTime, _ := time.Parse(time.RFC3339, "2017-08-30T13:35:00Z")
// POSTDATE is a date time field in DB (datastore)
query := datastore.NewQuery("db").Filter("POSTDATE >=", cutOffTime).

How to install wkhtmltopdf on a linux based (shared hosting) web server

Version 12.5 of wkhtmltopdf only lists DEB files on their download page now. Being a mac user and not knowing much linux or what DEB files were I couldn't use the solutions posted.

This page helped me get past the knew twist of downloading a DEB file: http://www.g-loaded.eu/2008/01/28/how-to-extract-rpm-or-deb-packages/

Basically what I did was:

  1. Downloaded from https://wkhtmltopdf.org/downloads.html
  2. Unzipped the DEB file.
  3. Unzipped data.tar.xz
  4. Uploaded the binary in the unzipped 'usr' folder from step 3 (usr/local/bin/wkhtmltopdf)

Then I found out that the 'exec' function was disabled on my host. So make sure you can specifically run 'exec' if you're using PHP to run this. "Can I run the wkhtmltopdf binary" isn't specific enough. My fault.

Find a string between 2 known values

Solution without need of regular expression:

string ExtractString(string s, string tag) {
     // You should check for errors in real-world code, omitted for brevity
     var startTag = "<" + tag + ">";
     int startIndex = s.IndexOf(startTag) + startTag.Length;
     int endIndex = s.IndexOf("</" + tag + ">", startIndex);
     return s.Substring(startIndex, endIndex - startIndex);
}

How to get value of a div using javascript

Value is not a valid attribute of DIV

try this

var divElement = document.getElementById('demo');
alert( divElement .getAttribute('value'));

How to assign string to bytes array

For converting from a string to a byte slice, string -> []byte:

[]byte(str)

For converting an array to a slice, [20]byte -> []byte:

arr[:]

For copying a string to an array, string -> [20]byte:

copy(arr[:], str)

Same as above, but explicitly converting the string to a slice first:

copy(arr[:], []byte(str))

  • The built-in copy function only copies to a slice, from a slice.
  • Arrays are "the underlying data", while slices are "a viewport into underlying data".
  • Using [:] makes an array qualify as a slice.
  • A string does not qualify as a slice that can be copied to, but it qualifies as a slice that can be copied from (strings are immutable).
  • If the string is too long, copy will only copy the part of the string that fits.

This code:

var arr [20]byte
copy(arr[:], "abc")
fmt.Printf("array: %v (%T)\n", arr, arr)

...gives the following output:

array: [97 98 99 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] ([20]uint8)

I also made it available at the Go Playground

Use of Greater Than Symbol in XML

You can try to use CDATA to put all your symbols that don't work.

An example of something that will work in XML:

<![CDATA[
function matchwo(a,b) {
    if (a < b && a < 0) {
        return 1;
   } else {
       return 0;
   }
}
]]>

And of course you can use &lt; and &gt;.

StringStream in C#

You can create a MemoryStream from a String and use that in any third-party function that requires a stream. In this case, MemoryStream, with the help of UTF8.GetBytes, provides the functionality of Java's StringStream.

From String examples

String content = "stuff";
using (MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(content)))
{
    Print(stream); //or whatever action you need to perform with the stream
    stream.Seek(0, SeekOrigin.Begin); //If you need to use the same stream again, don't forget to reset it.
    UseAgain(stream);
}

To String example

stream.Seek(0, SeekOrigin.Begin);
string s;
using (var readr = new StreamReader(stream))
{
    s = readr.ReadToEnd();
}
//and don't forget to dispose the stream if you created it

CSS: how do I create a gap between rows in a table?

the padding in the TD works if you want the space to have the same background color as the td

in my case, requirement was for white space between header row and whatever was above it

by applying this styling to a single cell, i was able to get the desired separation. It was not necessary to add it to all cells... Arguably not the MOST elegant, but possibly more elegant than separator rows.

<td colspan="10"> 
    <div class="HeaderRow" 
         style="margin-top:10px;">
            <%# Eval("VendorName")%>
     </div>
</td>  

Opening database file from within SQLite command-line shell

The same way you do it in other db system, you can use the name of the db for identifying double named tables. unique tablenames can used directly.

select * from ttt.table_name;

or if table name in all attached databases is unique

select * from my_unique_table_name;

But I think the of of sqlite-shell is only for manual lookup or manual data manipulation and therefor this way is more inconsequential

normally you would use sqlite-command-line in a script

How to use 'hover' in CSS

a.hover:hover {
    text-decoration:underline;
}

CSS - display: none; not working

In the HTML source provided, the element #tfl has an inline style "display:block". Inline style will always override stylesheets styles…

Then, you have some options (while as you said you can't modify the html code nor using javascript):

  • force display:none with !important rule (not recommended)
  • put the div offscreen with theses rules :

    #tfl {
        position: absolute;
        left: -9999px;
    }
    

ImportError: No module named dateutil.parser

None of the solutions worked for me. If you are using PIP do:

pip install pycrypto==2.6.1

How to hide/show more text within a certain length (like youtube)

So much answers and all them good, but I will suggest my own, maybe it will be usefull for somebody.

We have HTML in the template:

<div class="listing-item-excerpt" id="listing-item-excerpt-<?= $task['id'] ?>">
    <?= mb_substr($txt, 0, 150) ?><span class="complete_txt"><?= mb_substr($txt, 150) ?></span>
    <a href="javascript: show_more_less(<?= $task['id'] ?>);void(0);" class="more_less_btn" data-more-txt="<?= __('... show more') ?>" data-less-txt="&nbsp;<?= __('show less') ?>" data-state="0"><?= __('... show more') ?></a>
</div>

JS function for toggling which:

function show_more_less(task_id) {

    var btn = jQuery('#listing-item-excerpt-' + task_id).find('.more_less_btn');
    var txt_container = jQuery('#listing-item-excerpt-' + task_id).find('.complete_txt');
    var state = parseInt(jQuery(btn).data('state'), 10);
    if (state === 0) {
        jQuery(txt_container).show();
        jQuery(btn).text(jQuery(btn).data('less-txt'));
        jQuery(btn).data('state', 1);
    } else {
        jQuery(txt_container).hide();
        jQuery(btn).text(jQuery(btn).data('more-txt'));
        jQuery(btn).data('state', 0);
    }
}

Check whether a value exists in JSON object

You could improve on the answer from Ponmudi VN:

  • Shorter Code
  • Look for a key and a value

See this fiddle: https://jsfiddle.net/solarbaypilot/sn3wtea2/

function _isContains(json, keyname, value) {

return Object.keys(json).some(key => {
        return typeof json[key] === 'object' ? 
        _isContains(json[key], keyname, value) : key === keyname && json[key] === value;
    });
}

var JSONObject = {"animals": [{name:"cat"}, {name:"dog"}]};


document.getElementById('dog').innerHTML = _isContains(JSONObject, "name", "dog");
document.getElementById('puppy').innerHTML = _isContains(JSONObject, "name", "puppy");

Java error: Implicit super constructor is undefined for default constructor

For those who Google for this error and arrive here: there might be another reason for receiving it. Eclipse gives this error when you have project setup - system configuration mismatch.

For example, if you import Java 1.7 project to Eclipse and you do not have 1.7 correctly set up then you will get this error. Then you can either go to Project - Preference - Java - Compiler and switch to 1.6 or earlier; or go to Window - Preferences - Java - Installed JREs and add/fix your JRE 1.7 installation.

Load vs. Stress testing

Load testing = putting a specified amount of load on the server for certain amount of time. 100 simultaneous users for 10 minutes. Ensure stability of software. Stress testing = increasing the amount of load steadily until the software crashes. 10 simultaneous users increasing every 2 minutes until the server crashes.

To make a comparison to weight lifting: You "max" your weight to see what you can do for 1 rep (stress testing) and then on regular workouts you do 85% of your max value for 3 sets of 10 reps (load testing)

How to display table data more clearly in oracle sqlplus

Ahhh, the stupid linesize ... Here is what I do in my profile.sql - works only on unixes:

echo SET LINES $(tput cols) > $HOME/.login_tmp.sql
@$HOME/.login_tmp.sql

if you find an equivalent for tput on Windows, it might work there as well

Groovy built-in REST/HTTP client?

I don't think http-builder is a Groovy module, but rather an external API on top of apache http-client so you do need to import classes and download a bunch of APIs. You are better using Gradle or @Grab to download the jar and dependencies:

@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7.1' )
import groovyx.net.http.*
import static groovyx.net.http.ContentType.*
import static groovyx.net.http.Method.*

Note: since the CodeHaus site went down, you can find the JAR at (https://mvnrepository.com/artifact/org.codehaus.groovy.modules.http-builder/http-builder)

How to prevent a double-click using jQuery?

The solution provided by @Kichrum almost worked for me. I did have to add e.stopImmediatePropagation() also to prevent the default action. Here is my code:

$('a, button').on('click', function (e) {
    var $link = $(e.target);
    if (!$link.data('lockedAt')) {
        $link.data('lockedAt', +new Date());
    } else if (+new Date() - $link.data('lockedAt') > 500) {
        $link.data('lockedAt', +new Date());
    } else {
        e.preventDefault();
        e.stopPropagation();
        e.stopImmediatePropagation();
    }
});

How to destroy JWT Tokens on logout?

While other answers provide detailed solutions for various setups, this might help someone who is just looking for a general answer.

There are three general options, pick one or more:

  1. On the client side, delete the cookie from the browser using javascript.

  2. On the server side, set the cookie value to an empty string or something useless (for example "deleted"), and set the cookie expiration time to a time in the past.

  3. On the server side, update the refreshtoken stored in your database. Use this option to log out the user from all devices where they are logged in (their refreshtokens will become invalid and they have to log in again).

When should you use constexpr capability in C++11?

All of the other answers are great, I just want to give a cool example of one thing you can do with constexpr that is amazing. See-Phit (https://github.com/rep-movsd/see-phit/blob/master/seephit.h) is a compile time HTML parser and template engine. This means you can put HTML in and get out a tree that is able to be manipulated. Having the parsing done at compile time can give you a bit of extra performance.

From the github page example:

#include <iostream>
#include "seephit.h"
using namespace std;



int main()
{
  constexpr auto parser =
    R"*(
    <span >
    <p  color="red" height='10' >{{name}} is a {{profession}} in {{city}}</p  >
    </span>
    )*"_html;

  spt::tree spt_tree(parser);

  spt::template_dict dct;
  dct["name"] = "Mary";
  dct["profession"] = "doctor";
  dct["city"] = "London";

  spt_tree.root.render(cerr, dct);
  cerr << endl;

  dct["city"] = "New York";
  dct["name"] = "John";
  dct["profession"] = "janitor";

  spt_tree.root.render(cerr, dct);
  cerr << endl;
}

Equivalent of Math.Min & Math.Max for Dates?

// Two different dates
var date1 = new Date(2013, 05, 13); 
var date2 = new Date(2013, 04, 10) ;
// convert both dates in milliseconds and use Math.min function
var minDate = Math.min(date1.valueOf(), date2.valueOf());
// convert minDate to Date
var date = new Date(minDate); 

http://jsfiddle.net/5CR37/

What do these operators mean (** , ^ , %, //)?

  • **: exponentiation
  • ^: exclusive-or (bitwise)
  • %: modulus
  • //: divide with integral result (discard remainder)

Use Invoke-WebRequest with a username and password for basic authentication on the GitHub API

Use this:

$root = 'REST_SERVICE_URL'
$user = "user"
$pass= "password"
$secpasswd = ConvertTo-SecureString $pass -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($user, $secpasswd)

$result = Invoke-RestMethod $root -Credential $credential

What's the difference between git reset --mixed, --soft, and --hard?

There are a number of answers here with a misconception about git reset --soft. While there is a specific condition in which git reset --soft will only change HEAD (starting from a detached head state), typically (and for the intended use), it moves the branch reference you currently have checked out. Of course it can't do this if you don't have a branch checked out (hence the specific condition where git reset --soft will only change HEAD).

I've found this to be the best way to think about git reset. You're not just moving HEAD (everything does that), you're also moving the branch ref, e.g., master. This is similar to what happens when you run git commit (the current branch moves along with HEAD), except instead of creating (and moving to) a new commit, you move to a prior commit.

This is the point of reset, changing a branch to something other than a new commit, not changing HEAD. You can see this in the documentation example:

Undo a commit, making it a topic branch

          $ git branch topic/wip     (1)
          $ git reset --hard HEAD~3  (2)
          $ git checkout topic/wip   (3)
  1. You have made some commits, but realize they were premature to be in the "master" branch. You want to continue polishing them in a topic branch, so create "topic/wip" branch off of the current HEAD.
  2. Rewind the master branch to get rid of those three commits.
  3. Switch to "topic/wip" branch and keep working.

What's the point of this series of commands? You want to move a branch, here master, so while you have master checked out, you run git reset.

The top voted answer here is generally good, but I thought I'd add this to correct the several answers with misconceptions.

Change your branch

git reset --soft <ref>: resets the branch pointer for the currently checked out branch to the commit at the specified reference, <ref>. Files in your working directory and index are not changed. Committing from this stage will take you right back to where you were before the git reset command.

Change your index too

git reset --mixed <ref>

or equivalently

git reset <ref>:

Does what --soft does AND also resets the index to the match the commit at the specified reference. While git reset --soft HEAD does nothing (because it says move the checked out branch to the checked out branch), git reset --mixed HEAD, or equivalently git reset HEAD, is a common and useful command because it resets the index to the state of your last commit.

Change your working directory too

git reset --hard <ref>: does what --mixed does AND also overwrites your working directory. This command is similar to git checkout <ref>, except that (and this is the crucial point about reset) all forms of git reset move the branch ref HEAD is pointing to.

A note about "such and such command moves the HEAD":

It is not useful to say a command moves the HEAD. Any command that changes where you are in your commit history moves the HEAD. That's what the HEAD is, a pointer to wherever you are. HEADis you, and so will move whenever you do.

Python 3 ImportError: No module named 'ConfigParser'

Try this solution which worked fine for me.

Basically it's to reinstall/upgrade to latest version of mysql from brew, and then installing mysqlclient or MySQL-Python from global pip3 instead of virtualenv pip3.

Then accessing the virtualenv and successfully install mysqlclient or MySQL-Python.

Working with select using AngularJS's ng-options

I'm learning AngularJS and was struggling with selection as well. I know this question is already answered, but I wanted to share some more code nevertheless.

In my test I have two listboxes: car makes and car models. The models list is disabled until some make is selected. If selection in makes listbox is later reset (set to 'Select Make') then the models listbox becomes disabled again AND its selection is reset as well (to 'Select Model'). Makes are retrieved as a resource while models are just hard-coded.

Makes JSON:

[
{"code": "0", "name": "Select Make"},
{"code": "1", "name": "Acura"},
{"code": "2", "name": "Audi"}
]

services.js:

angular.module('makeServices', ['ngResource']).
factory('Make', function($resource){
    return $resource('makes.json', {}, {
        query: {method:'GET', isArray:true}
    });
});

HTML file:

<div ng:controller="MakeModelCtrl">
  <div>Make</div>
  <select id="makeListBox"
      ng-model="make.selected"
      ng-options="make.code as make.name for make in makes"
      ng-change="makeChanged(make.selected)">
  </select>

  <div>Model</div>
  <select id="modelListBox"
     ng-disabled="makeNotSelected"
     ng-model="model.selected"
     ng-options="model.code as model.name for model in models">
  </select>
</div>

controllers.js:

function MakeModelCtrl($scope)
{
    $scope.makeNotSelected = true;
    $scope.make = {selected: "0"};
    $scope.makes = Make.query({}, function (makes) {
         $scope.make = {selected: makes[0].code};
    });

    $scope.makeChanged = function(selectedMakeCode) {
        $scope.makeNotSelected = !selectedMakeCode;
        if ($scope.makeNotSelected)
        {
            $scope.model = {selected: "0"};
        }
    };

    $scope.models = [
      {code:"0", name:"Select Model"},
      {code:"1", name:"Model1"},
      {code:"2", name:"Model2"}
    ];
    $scope.model = {selected: "0"};
}

Android SQLite SELECT Query

Try trimming the string to make sure there is no extra white space:

Cursor c = db.rawQuery("SELECT * FROM tbl1 WHERE TRIM(name) = '"+name.trim()+"'", null);

Also use c.moveToFirst() like @thinksteep mentioned.


This is a complete code for select statements.

SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("SELECT column1,column2,column3 FROM table ", null);
if (c.moveToFirst()){
    do {
        // Passing values 
        String column1 = c.getString(0);
        String column2 = c.getString(1);
        String column3 = c.getString(2); 
        // Do something Here with values
    } while(c.moveToNext());
}
c.close();
db.close();

How to use the ConfigurationManager.AppSettings

ConfigurationManager.AppSettings is actually a property, so you need to use square brackets.

Overall, here's what you need to do:

SqlConnection con= new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]);

The problem is that you tried to set con to a string, which is not correct. You have to either pass it to the constructor or set con.ConnectionString property.

Error:Execution failed for task ':ProjectName:mergeDebugResources'. > Crunching Cruncher *some file* failed, see logs

I faced the same error but i solved this by selecting invalidate caches/restart option.

Click

  1. file >> invalidate caches/restart

How to store decimal values in SQL Server?

The other answers are right. Assuming your examples reflect the full range of possibilities what you want is DECIMAL(3, 1). Or, DECIMAL(14, 1) will allow a total of 14 digits. It's your job to think about what's enough.

How do I write a for loop in bash

for ((i = 0 ; i < max ; i++ )); do echo "$i"; done

convert strtotime to date time format in php

Use date() function to get the desired date

<?php
// set default timezone
date_default_timezone_set('UTC');

//define date and time
$strtotime = 1307595105;

// output
echo date('d M Y H:i:s',$strtotime);

// more formats
echo date('c',$strtotime); // ISO 8601 format
echo date('r',$strtotime); // RFC 2822 format
?>

Recommended online tool for strtotime to date conversion:

http://freeonlinetools24.com/

How to export data as CSV format from SQL Server using sqlcmd?

With PowerShell you can solve the problem neatly by piping Invoke-Sqlcmd into Export-Csv.

#Requires -Module SqlServer
Invoke-Sqlcmd -Query "SELECT * FROM DimDate;" `
              -Database AdventureWorksDW2012 `
              -Server localhost |
Export-Csv -NoTypeInformation `
           -Path "DimDate.csv" `
           -Encoding UTF8

SQL Server 2016 includes the SqlServer module, which contains the Invoke-Sqlcmd cmdlet, which you'll have even if you just install SSMS 2016. Prior to that, SQL Server 2012 included the old SQLPS module, which would change the current directory to SQLSERVER:\ when the module was first used (among other bugs) so for it, you'll need to change the #Requires line above to:

Push-Location $PWD
Import-Module -Name SQLPS
# dummy query to catch initial surprise directory change
Invoke-Sqlcmd -Query "SELECT 1" `
              -Database  AdventureWorksDW2012 `
              -Server localhost |Out-Null
Pop-Location
# actual Invoke-Sqlcmd |Export-Csv pipeline

To adapt the example for SQL Server 2008 and 2008 R2, remove the #Requires line entirely and use the sqlps.exe utility instead of the standard PowerShell host.

Invoke-Sqlcmd is the PowerShell equivalent of sqlcmd.exe. Instead of text it outputs System.Data.DataRow objects.

The -Query parameter works like the -Q parameter of sqlcmd.exe. Pass it a SQL query that describes the data you want to export.

The -Database parameter works like the -d parameter of sqlcmd.exe. Pass it the name of the database that contains the data to be exported.

The -Server parameter works like the -S parameter of sqlcmd.exe. Pass it the name of the server that contains the data to be exported.

Export-CSV is a PowerShell cmdlet that serializes generic objects to CSV. It ships with PowerShell.

The -NoTypeInformation parameter suppresses extra output that is not part of the CSV format. By default the cmdlet writes a header with type information. It lets you know the type of the object when you deserialize it later with Import-Csv, but it confuses tools that expect standard CSV.

The -Path parameter works like the -o parameter of sqlcmd.exe. A full path for this value is safest if you are stuck using the old SQLPS module.

The -Encoding parameter works like the -f or -u parameters of sqlcmd.exe. By default Export-Csv outputs only ASCII characters and replaces all others with question marks. Use UTF8 instead to preserve all characters and stay compatible with most other tools.

The main advantage of this solution over sqlcmd.exe or bcp.exe is that you don't have to hack the command to output valid CSV. The Export-Csv cmdlet handles it all for you.

The main disadvantage is that Invoke-Sqlcmd reads the whole result set before passing it along the pipeline. Make sure you have enough memory for the whole result set you want to export.

It may not work smoothly for billions of rows. If that's a problem, you could try the other tools, or roll your own efficient version of Invoke-Sqlcmd using System.Data.SqlClient.SqlDataReader class.

Efficient way to remove ALL whitespace from String?

Using Linq, you can write a readable method this way :

    public static string RemoveAllWhitespaces(this string source)
    {
        return string.IsNullOrEmpty(source) ? source : new string(source.Where(x => !char.IsWhiteSpace(x)).ToArray());
    }

Hide html horizontal but not vertical scrollbar

Disable horizontal scrollbar completely by adding this code.

body{
  overflow-x: hidden;
  overflow-y: scroll;
}

How can I count all the lines of code in a directory recursively?

Yet another variation :)

$ find . -name '*.php' | xargs cat | wc -l

This will give the total sum, instead of file-by-file.

Add . after find to make it work.

Where can I find the API KEY for Firebase Cloud Messaging?

STEP 1: Go to Firebase Console

STEP 2: Select your Project

STEP 3: Click on Settings icon and select Project Settings

Select Project Setting

STEP 4: Select CLOUD MESSAGING tab

enter image description here

How can I add JAR files to the web-inf/lib folder in Eclipse?

They are automatically added to the project classpath if its a web project. Sometimes it does not work properly, a refresh or close/open of the project helps.

if its not a web project you can right click on the library and go to "Build Path" -> "Add to Build Path"

How SQL query result insert in temp table?

Suppose your existing reporting query is

Select EmployeeId,EmployeeName 
from Employee 
Where EmployeeId>101 order by EmployeeName

and you have to save this data into temparory table then you query goes to

Select EmployeeId,EmployeeName 
into #MyTempTable 
from Employee 
Where EmployeeId>101 order by EmployeeName  

Python 3: EOF when reading a line (Sublime Text 2 is angry)

It seems as of now, the only solution is still to install SublimeREPL.

To extend on Raghav's answer, it can be quite annoying to have to go into the Tools->SublimeREPL->Python->Run command every time you want to run a script with input, so I devised a quick key binding that may be handy:

To enable it, go to Preferences->Key Bindings - User, and copy this in there:

[
    {"keys":["ctrl+r"] , 
    "caption": "SublimeREPL: Python - RUN current file",
    "command": "run_existing_window_command", 
    "args":
        {
            "id": "repl_python_run",
            "file": "config/Python/Main.sublime-menu"
        }
    },
]

Naturally, you would just have to change the "keys" argument to change the shortcut to whatever you'd like.

Factorial in numpy and scipy

You can import them like this:

In [7]: import scipy, numpy, math                                                          

In [8]: scipy.math.factorial, numpy.math.factorial, math.factorial
Out[8]: 
(<function math.factorial>,                                                                
 <function math.factorial>,                                                                
 <function math.factorial>)

scipy.math.factorial and numpy.math.factorial seem to simply be aliases/references for/to math.factorial, that is scipy.math.factorial is math.factorial and numpy.math.factorial is math.factorial should both give True.

Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)

Ensure that your mysql service is running

service mysqld start

Then, try the one of the following following:

(if you have not set password for mysql)

mysql -u root

if you have set password already

mysql -u root -p

Installing SciPy with pip

I tried all the above and nothing worked for me. This solved all my problems:

pip install -U numpy

pip install -U scipy

Note that the -U option to pip install requests that the package be upgraded. Without it, if the package is already installed pip will inform you of this and exit without doing anything.

Failed to load ApplicationContext (with annotation)

In my case, I had to do the following while running with Junit5

@SpringBootTest(classes = {abc.class}) @ExtendWith(SpringExtension.class

Here abc.class was the class that was being tested

How do I get a PHP class constructor to call its parent's parent's constructor?

Another option that doesn't use a flag and might work in your situation:

<?php
// main class that everything inherits
class Grandpa 
{
    public function __construct(){
        $this->GrandpaSetup();
    }

    public function GrandpaSetup(){
        $this->prop1 = 'foo';
        $this->prop2 = 'bar';
    }
}

class Papa extends Grandpa
{
    public function __construct()
    {
        // call Grandpa's constructor
        parent::__construct();
        $this->prop1 = 'foobar';
    }

}
class Kiddo extends Papa
{
    public function __construct()
    {
        $this->GrandpaSetup();
    }
}

$kid = new Kiddo();
echo "{$kid->prop1}\n{$kid->prop2}\n";

Most efficient way to check if a file is empty in Java on Windows

I think the best way is to use file.length == 0.

It is sometimes possible that the first line is empty.

Command to find information about CPUs on a UNIX machine

There is no standard Unix command, AFAIK. I haven't used Sun OS, but on Linux, you can use this:

cat /proc/cpuinfo

Sorry that it is Linux, not Sun OS. There is probably something similar though for Sun OS.

How to run Spring Boot web application in Eclipse itself?

In my case, I had to select the "src/main/java" and select the "Run As" menu Just like this, so that "Spring Boot App" would be displayed as here.

How to run cron job every 2 hours

Just do:

0 */2 * * *  /home/username/test.sh 

The 0 at the beginning means to run at the 0th minute. (If it were an *, the script would run every minute during every second hour.)

Don't forget, you can check syslog to see if it ever actually ran!

How do I get the result of a command in a variable in windows?

If you have to capture all the command output you can use a batch like this:

@ECHO OFF
IF NOT "%1"=="" GOTO ADDV
SET VAR=
FOR /F %%I IN ('DIR *.TXT /B /O:D') DO CALL %0 %%I
SET VAR
GOTO END

:ADDV
SET VAR=%VAR%!%1

:END

All output lines are stored in VAR separated with "!".

@John: is there any practical use for this? I think you should watch PowerShell or any other programming language capable to perform scripting tasks easily (Python, Perl, PHP, Ruby)

IE8 support for CSS Media Query

An easy way to use the css3-mediaqueries-js is to include the following before the closing body tag:

<!-- css3-mediaqueries.js for IE less than 9 -->
<!--[if lt IE 9]>
<script 
   src="//css3-mediaqueries-js.googlecode.com/svn/trunk/css3-mediaqueries.js">
</script>
<![endif]-->

make: *** [ ] Error 1 error

From GNU Make error appendix, as you see this is not a Make error but an error coming from gcc.

‘[foo] Error NN’ ‘[foo] signal description’ These errors are not really make errors at all. They mean that a program that make invoked as part of a recipe returned a non-0 error code (‘Error NN’), which make interprets as failure, or it exited in some other abnormal fashion (with a signal of some type). See Errors in Recipes. If no *** is attached to the message, then the subprocess failed but the rule in the makefile was prefixed with the - special character, so make ignored the error.

So in order to attack the problem, the error message from gcc is required. Paste the command in the Makefile directly to the command line and see what gcc says. For more details on Make errors click here.

jQuery Datepicker with text input that doesn't allow user input

$("#my_txtbox").prop('readonly', true)

worked like a charm..

How to do a logical OR operation for integer comparison in shell scripting?

If a bash script

If [[ $input -gt number  ||  $input  -lt number  ]]
then 
    echo .........
else
    echo .........

fi

exit

Retrofit and GET using parameters

Complete working example in Kotlin, I have replaced my API keys with 1111...

        val apiService = API.getInstance().retrofit.create(MyApiEndpointInterface::class.java)
        val params = HashMap<String, String>()
        params["q"] =  "munich,de"
        params["APPID"] = "11111111111111111"

        val call = apiService.getWeather(params)

        call.enqueue(object : Callback<WeatherResponse> {
            override fun onFailure(call: Call<WeatherResponse>?, t: Throwable?) {
                Log.e("Error:::","Error "+t!!.message)
            }

            override fun onResponse(call: Call<WeatherResponse>?, response: Response<WeatherResponse>?) {
                if (response != null && response.isSuccessful && response.body() != null) {
                    Log.e("SUCCESS:::","Response "+ response.body()!!.main.temp)

                    temperature.setText(""+ response.body()!!.main.temp)

                }
            }

        })

How to sort a HashMap in Java

HashMap doesnt maintain any order, so if you want any kind of ordering, you need to store that in something else, which is a map and can have some kind of ordering, like LinkedHashMap

below is a simple program, by which you can sort by key, value, ascending ,descending ..( if you modify the compactor, you can use any kind of ordering, on keys and values)

package com.edge.collection.map;

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class SortMapByKeyValue {
Map<String, Integer> map = new HashMap<String, Integer>();

public static void main(String[] args) {

    SortMapByKeyValue smkv = new SortMapByKeyValue();
    smkv.createMap();

    System.out.println("After sorting by key ascending order......");
    smkv.sortByKey(true);

    System.out.println("After sorting by key descindeng order......");
    smkv.sortByKey(false);

    System.out.println("After sorting by value ascending order......");
    smkv.sortByValue(true);

    System.out.println("After sorting by value  descindeng order......");
    smkv.sortByValue(false);

}

void createMap() {
    map.put("B", 55);
    map.put("A", 80);
    map.put("D", 20);
    map.put("C", 70);
    map.put("AC", 70);
    map.put("BC", 70);
    System.out.println("Before sorting......");
    printMap(map);
}

void sortByValue(boolean order) {

    List<Entry<String, Integer>> list = new LinkedList<Entry<String, Integer>>(map.entrySet());
    Collections.sort(list, new Comparator<Entry<String, Integer>>() {
        public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
            if (order) {
                return o1.getValue().compareTo(o2.getValue());
            } else {
                return o2.getValue().compareTo(o1.getValue());

            }
        }
    });
    Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
    for (Entry<String, Integer> entry : list) {
        sortedMap.put(entry.getKey(), entry.getValue());
    }
    printMap(sortedMap);

}

void sortByKey(boolean order) {

    List<Entry<String, Integer>> list = new LinkedList<Entry<String, Integer>>(map.entrySet());
    Collections.sort(list, new Comparator<Entry<String, Integer>>() {
        public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
            if (order) {
                return o1.getKey().compareTo(o2.getKey());
            } else {
                return o2.getKey().compareTo(o1.getKey());

            }
        }
    });
    Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
    for (Entry<String, Integer> entry : list) {
        sortedMap.put(entry.getKey(), entry.getValue());
    }
    printMap(sortedMap);
}

public void printMap(Map<String, Integer> map) {
    // System.out.println(map);
    for (Entry<String, Integer> entry : map.entrySet()) {
        System.out.println(entry.getKey() + " : " + entry.getValue());
    }
}
}

here is the git link

splitting a string into an array in C++ without using vector

#include <iostream>
#include <sstream>
#include <iterator>
#include <string>

using namespace std;

template <size_t N>
void splitString(string (&arr)[N], string str)
{
    int n = 0;
    istringstream iss(str);
    for (auto it = istream_iterator<string>(iss); it != istream_iterator<string>() && n < N; ++it, ++n)
        arr[n] = *it;
}

int main()
{
    string line = "test one two three.";
    string arr[4];

    splitString(arr, line);

    for (int i = 0; i < 4; i++)
       cout << arr[i] << endl;
}

MessageBodyWriter not found for media type=application/json

In my experience this error is pretty common, for some reason jersey sometimes has problems parsing custom java types. Usually all you have to do is make sure that you respect the following 3 conditions:

  1. you have jersey-media-json-jackson in you pom.xml if using maven or added to your build path;
  2. you have an empty constructor in the data type you are trying to de-/serialize;
  3. you have the relevant annotation at the class and field level for your custom data type (xmlelement and/or jsonproperty);

However, I have ran into cases where this just was not enough. Then you can always wrap you custom data type in a GenericEntity and pass it as such to your ResponseBuilder:

GenericEntity<CustomDataType> entity = new GenericEntity<CustomDataType>(myObj) {};
return Response.status(httpCode).entity(entity).build();

This way you are trying to help jersey to find the proper/relevant serialization provider for you object. Well, sometimes this also is not enough. In my case I was trying to produce a text/plain from a custom data type. Theoretically jersey should have used the StringMessageProvider, but for some reason that I did not manage to discover it was giving me this error:

org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyWriter not found for media type=text/plain

So what solved the problem for me was to do my own serialization with jackson's writeValueAsString(). I'm not proud of it but at the end of the day I can deliver an acceptable solution.

How to run Maven from another directory (without cd to project dir)?

For me, works this way: mvn -f /path/to/pom.xml [goals]

How do I check if PHP is connected to a database already?

Baron Schwartz blogs that due to race conditions, this 'check before write' is a bad practice. He advocates a try/catch pattern with a reconnect in the catch. Here is the pseudo code he recommends:

function query_database(connection, sql, retries=1)
   while true
      try
         result=connection.execute(sql)
         return result
      catch InactiveConnectionException e
         if retries > 0 then
            retries = retries - 1
            connection.reconnect()
         else
            throw e
         end
      end
   end
end

Here is his full blog: https://www.percona.com/blog/2010/05/05/checking-for-a-live-database-connection-considered-harmful/

how to download file using AngularJS and calling MVC API?

using FileSaver.js solved my issue thanks for help, below code helped me

'$'

 DownloadClaimForm: function (claim) 
{
 url = baseAddress + "DownLoadFile";
 return  $http.post(baseAddress + "DownLoadFile", claim, {responseType: 'arraybuffer' })
                            .success(function (data) {
                                var file = new Blob([data], { type: 'application/pdf' });
                                saveAs(file, 'Claims.pdf');
                            });


    }

git: Your branch is ahead by X commits

Someone said you might be misreading your message, you aren't. This issue actually has to do with your <project>/.git/config file. In it will be a section similar to this:

[remote "origin"]
    url = <url>
    fetch = +refs/heads/*:refs/remotes/origin/*

If you remove the fetch line from your project's .git/config file you'll stop the "Your branch is ahead of 'origin/master' by N commits." annoyance from occurring.

Or so I hope. :)

How to update Git clone

git pull origin master

this will sync your master to the central repo and if new branches are pushed to the central repo it will also update your clone copy.

What is difference between XML Schema and DTD?

DTD can have only two types of data, the CDATA and the PCDATA. But in a schema you can use all the primitive data type that you use in the programming language and you have the flexibility of defining your own custom data types.

The developer building a schema can create custom data types based on the core data types and by using different operators and modifiers.

jQuery Validation plugin: disable validation for specified submit buttons

You can add a CSS class of cancel to a submit button to suppress the validation

e.g

<input class="cancel" type="submit" value="Save" />

See the jQuery Validator documentation of this feature here: Skipping validation on submit


EDIT:

The above technique has been deprecated and replaced with the formnovalidate attribute.

<input formnovalidate="formnovalidate" type="submit" value="Save" />

Remove scrollbar from iframe

iframe {
  display: block;
  border: none;         /* Reset default border */
  height: 100vh;        /* Viewport-relative units */
  width: calc(100% + 17px);
}
div {
  overflow-x: hidden;
}

Like this you make the width of the Iframe larger than it should be. Then you hide the horizontal scrollbar with overflow-x: hidden.

Ruby: How to get the first character of a string

You can also use truncate

> 'Smith'.truncate(1, omission: '')
#=> "S"

or for additional formatting:

> 'Smith'.truncate(4)
#=> "S..."

> 'Smith'.truncate(2, omission: '.')
#=> "S."

Output data with no column headings using PowerShell

If you use "format-table" you can use -hidetableheaders

c# datatable insert column at position 0

You can use the following code to add column to Datatable at postion 0:

    DataColumn Col   = datatable.Columns.Add("Column Name", System.Type.GetType("System.Boolean"));
    Col.SetOrdinal(0);// to put the column in position 0;

How can I get the name of an html page in Javascript?

Try this

location.pathname.substring(location.pathname.lastIndexOf("/") + 1);

location.pathname gives the part (domain not included) of the page URL. To get only the filename you have to extract it using the substring method.

Should try...catch go inside or outside a loop?

I's like to add my own 0.02c about two competing considerations when looking at the general problem of where to position exception handling:

  1. The "wider" the responsibility of the try-catch block (i.e. outside the loop in your case) means that when changing the code at some later point, you may mistakenly add a line which is handled by your existing catch block; possibly unintentionally. In your case, this is less likely because you are explicitly catching a NumberFormatException

  2. The "narrower" the responsibility of the try-catch block, the more difficult refactoring becomes. Particularly when (as in your case) you are executing a "non-local" instruction from within the catch block (the return null statement).

How to automatically reload a page after a given period of inactivity

With on page confirmation text instead of alert

Since this is another method to auto load if inactive I give it a second answer. This one is more simple and easier to understand.

With reload confirmation on the page

<script language="javaScript" type="text/javascript">
<!--
var autoCloseTimer;
var timeoutObject;
var timePeriod = 5100; // 5,1 seconds
var warnPeriod = 5000; // 5 seconds
// Warning period should always be a bit shorter then time period

function promptForClose() {
autoCloseDiv.style.display = 'block';
autoCloseTimer = setTimeout("definitelyClose()", warnPeriod);
}


function autoClose() {
autoCloseDiv.style.display = 'block'; //shows message on page
autoCloseTimer = setTimeout("definitelyClose()", timePeriod); //starts countdown to closure
}

function cancelClose() {
clearTimeout(autoCloseTimer); //stops auto-close timer
autoCloseDiv.style.display = 'none'; //hides message
}

function resetTimeout() {
clearTimeout(timeoutObject); //stops timer
timeoutObject = setTimeout("promptForClose()", timePeriod); //restarts timer from 0
}


function definitelyClose() {

// If you use want targeted reload: parent.Iframe0.location.href = "https://URLHERE.com/"
// or  this: window.open('http://www.YourPageAdress.com', '_self');

// of for the same page reload use: window.top.location=self.location;
// or window.open(self.location;, '_self');

window.top.location=self.location;
}
-->
</script>

Confirmation box when using with on page confirmation

<div class="leftcolNon">
<div id='autoCloseDiv' style="display:none">
<center>
<b>Inactivity warning!</b><br />
This page will Reloads automatically unless you hit 'Cancel.'</p>
<input type='button' value='Load' onclick='definitelyClose();' />
<input type='button' value='Cancel' onclick='cancelClose();' />
</center>
</div>
</div>

Body codes for both are the SAME

<body onmousedown="resetTimeout();" onmouseup="resetTimeout();" onmousemove="resetTimeout();" onkeydown="resetTimeout();" onload="timeoutObject=setTimeout('promptForClose()',timePeriod);">

NOTE: If you do not want to have the on page confirmation, use Without confirmation

<script language="javaScript" type="text/javascript">
<!--
var autoCloseTimer;
var timeoutObject;
var timePeriod = 5000; // 5 seconds

function resetTimeout() {
clearTimeout(timeoutObject); //stops timer
timeoutObject = setTimeout("definitelyClose()", timePeriod); //restarts timer from 0
}

function definitelyClose() {

// If you use want targeted reload: parent.Iframe0.location.href = "https://URLHERE.com/"
// or  this: window.open('http://www.YourPageAdress.com', '_self');

// of for the same page reload use: window.top.location=self.location;
// or window.open(self.location;, '_self');

window.top.location=self.location;
}
-->
</script>

How to pass an event object to a function in Javascript?

I would change your binding to be:

<button type="button" value="click me" onclick="check_me" />

I would then change your check_me() function declaration to be:

function check_me() {   
  //event.preventDefault();
  var hello = document.myForm.username.value;
  var err = '';

  if(hello == '' || hello == null) {
    err = 'User name required';
  }

  if(err != '') { 
     alert(err); 
     $('username').focus(); 
     event.preventDefault(); 
   } else { 
    return true; }
}

Fail during installation of Pillow (Python module) in Linux

On debian / ubuntu you only need: libjpeg62-turbo-dev

So a simple sudo apt install libjpeg62-turbo-dev and a pip install pillow

Including jars in classpath on commandline (javac or apt)

Note for Windows users, the jars should be separated by ; and not :.

for example: javac -cp external_libs\lib1.jar;other\lib2.jar;

Windows Batch: How to add Host-Entries?

Well I write a script which works very well.

> @echo off TITLE Modifying your HOSTS file COLOR F0 ECHO.
> 
> :LOOP SET Choice= SET /P Choice="Do you want to modify HOSTS file ?
> (Y/N)"
> 
> IF NOT '%Choice%'=='' SET Choice=%Choice:~0,1%
> 
> ECHO. IF /I '%Choice%'=='Y' GOTO ACCEPTED IF /I '%Choice%'=='N' GOTO
> REJECTED ECHO Please type Y (for Yes) or N (for No) to proceed! ECHO.
> GOTO Loop
> 
> 
> :REJECTED ECHO Your HOSTS file was left
> unchanged>>%systemroot%\Temp\hostFileUpdate.log ECHO Finished. GOTO
> END
> 
> 
> :ACCEPTED SET NEWLINE=^& echo. ECHO Carrying out requested
> modifications to your HOSTS file FIND /C /I "www.youtube.com"
> %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0 ECHO
> %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO 127.0.0.1    www.youtube.com>>%WINDIR%\system32\drivers\etc\hosts
> FIND /C /I "youtube.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> youtube.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.zacebookpk.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.zacebookpk.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "zacebookpk.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> zacebookpk.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.proxysite.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.proxysite.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.proxfree.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.proxfree.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.hidemyass.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.hidemyass.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.freeyoutubeproxy.org" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.freeyoutubeproxy.org>>%WINDIR%\system32\drivers\etc\hosts FIND /C
> /I "www.facebook.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.facebook.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "facebook.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> facebook.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.4everproxy.com " %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1    www.4everproxy.com
> >>%WINDIR%\system32\drivers\etc\hosts FIND /C /I "4everproxy.com " %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0 ECHO
> %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO 127.0.0.1    4everproxy.com >>%WINDIR%\system32\drivers\etc\hosts
> FIND /C /I "proxysite.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> proxysite.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "proxfree.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> proxfree.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "hidemyass.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> hidemyass.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "freeyoutubeproxy.org" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> freeyoutubeproxy.org>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "unblockvideos.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> unblockvideos.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "proxyone.net" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> proxyone.net>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "kuvia.eu" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1    kuvia.eu>>%WINDIR%\system32\drivers\etc\hosts
> FIND /C /I "kuvia.eu/facebook-proxy"
> %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0 ECHO
> %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO 127.0.0.1   
> kuvia.eu/facebook-proxy>>%WINDIR%\system32\drivers\etc\hosts FIND /C
> /I "hidemytraxproxy.ca" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> hidemytraxproxy.ca>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "github.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> github.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "funproxy.net" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> funproxy.net>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "en.wikipedia.org" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> en.wikipedia.org>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "wikipedia.org" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> wikipedia.org>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "dronten.proxylistpro.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> dronten.proxylistpro.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C
> /I "proxylistpro.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> proxylistpro.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "zfreez.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> zfreez.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "zendproxy.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> zendproxy.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "zalmos.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> zalmos.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "zacebookpk.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> zacebookpk.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "youtubeunblockproxy.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> youtubeunblockproxy.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C
> /I "youtubefreeproxy.net" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> youtubefreeproxy.net>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "youliaoren.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> youliaoren.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "xitenow.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> xitenow.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.youtubeproxy.pk" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.youtubeproxy.pk>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "youtubeproxy.pk" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> youtubeproxy.pk>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.youproxytube.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.youproxytube.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.webmasterview.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.webmasterview.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "webmasterview.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> webmasterview.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "youproxytube.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> youproxytube.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.vobas.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.vobas.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "vobas.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1    vobas.com>>%WINDIR%\system32\drivers\etc\hosts
> FIND /C /I "www.unblockmyweb.com" %WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO
> %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO 127.0.0.1   
> www.unblockmyweb.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "unblockmyweb.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> unblockmyweb.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.unblocker.yt" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.unblocker.yt>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "unblocker.yt" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> unblocker.yt>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.unblock.pk" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.unblock.pk>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "unblock.pk" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> unblock.pk>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.techgyd.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.techgyd.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "techgyd.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> techgyd.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.snapdeal.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.snapdeal.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "snapdeal.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> snapdeal.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.site2unblock.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.site2unblock.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "site2unblock.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> site2unblock.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.shopclues.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.shopclues.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "shopclues.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> shopclues.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.proxypk.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.proxypk.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "proxypk.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> proxypk.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.proxay.co.uk" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.proxay.co.uk>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "proxay.co.uk" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> proxay.co.uk>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.myntra.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.myntra.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "myntra.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> myntra.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.maddw.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.maddw.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "maddw.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1    maddw.com>>%WINDIR%\system32\drivers\etc\hosts
> FIND /C /I "www.lenskart.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.lenskart.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "lenskart.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> lenskart.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.kproxy.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.kproxy.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "kproxy.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> kproxy.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.jabong.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.jabong.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "jabong.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> jabong.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.flipkart.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.flipkart.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "flipkart.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> flipkart.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.facebook-proxyserver.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.facebook-proxyserver.com>>%WINDIR%\system32\drivers\etc\hosts FIND
> /C /I "facebook-proxyserver.com" %WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO
> %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO 127.0.0.1   
> facebook-proxyserver.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C
> /I "www.dontfilter.us" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.dontfilter.us>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "dontfilter.us" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> dontfilter.us>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.dolopo.net" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.dolopo.net>>%WINDIR%\system32\drivers\etc\hosts ECHO Finished GOTO
> END
> 
> 
> :END ECHO. ping -n 11 127.0.0.1 > nul EXIT

Replace text inside td using jQuery having td containing other elements

A bit late to the party, but JQuery change inner text but preserve html has at least one approach not mentioned here:

var $td = $("#demoTable td");
$td.html($td.html().replace('Tap on APN and Enter', 'new text'));

Without fixing the text, you could use (snother)[https://stackoverflow.com/a/37828788/1587329]:

var $a = $('#demoTable td');
var inner = '';
$a.children.html().each(function() {
    inner = inner + this.outerHTML;
});
$a.html('New text' + inner);

How do I get the offset().top value of an element without using jQuery?

Here is a function that will do it without jQuery:

function getElementOffset(element)
{
    var de = document.documentElement;
    var box = element.getBoundingClientRect();
    var top = box.top + window.pageYOffset - de.clientTop;
    var left = box.left + window.pageXOffset - de.clientLeft;
    return { top: top, left: left };
}

Is it possible to decrypt MD5 hashes?

MD5 is a cryptographic (one-way) hash function, so there is no direct way to decode it. The entire purpose of a cryptographic hash function is that you can't undo it.

One thing you can do is a brute-force strategy, where you guess what was hashed, then hash it with the same function and see if it matches. Unless the hashed data is very easy to guess, it could take a long time though.

How to set the value of a hidden field from a controller in mvc

If you're going to reuse the value like an id or if you want to just keep it you can add a "new{id = 'desiredID/value'}) as its parameters so you can access the value thru jquery/javascript

@Html.HiddenFor(model => model.Car_id)

How to find the Vagrant IP?

run:

vagrant ssh-config > .ssh.config

and then in config/deploy.rb

role :web, "default"     
role :app, "default"
set :use_sudo, true
set :user, 'root'
set :run_method, :sudo

# Must be set for the password prompt from git to work
default_run_options[:pty] = true
ssh_options[:forward_agent] = true
ssh_options[:config] = '.ssh.config'

Matplotlib make tick labels font size smaller

To specify both font size and rotation at the same time, try this:

plt.xticks(fontsize=14, rotation=90)

Converting array to list in Java

Using Arrays

This is the simplest way to convert an array to List. However, if you try to add a new element or remove an existing element from the list, an UnsupportedOperationException will be thrown.

Integer[] existingArray = {1, 2, 3};
List<Integer> list1 = Arrays.asList(existingArray);
List<Integer> list2 = Arrays.asList(1, 2, 3);

// WARNING:
list2.add(1);     // Unsupported operation!
list2.remove(1);  // Unsupported operation!

Using ArrayList or Other List Implementations

You can use a for loop to add all the elements of the array into a List implementation, e.g. ArrayList:

List<Integer> list = new ArrayList<>();
for (int i : new int[]{1, 2, 3}) {
  list.add(i);
}

Using Stream API in Java 8

You can turn the array into a stream, then collect the stream using different collectors: The default collector in Java 8 use ArrayList behind the screen, but you can also impose your preferred implementation.

List<Integer> list1, list2, list3;
list1 = Stream.of(1, 2, 3).collect(Collectors.toList());
list2 = Stream.of(1, 2, 3).collect(Collectors.toCollection(ArrayList::new));
list3 = Stream.of(1, 2, 3).collect(Collectors.toCollection(LinkedList::new));

See also:

Apache Cordova - uninstall globally

Try this for Windows:

    npm uninstall -g cordova

Try this for MAC:

    sudo npm uninstall -g cordova

You can also add Cordova like this:

  1. If You Want To install the previous version of Cordova through the Node Package Manager (npm):

    npm install -g [email protected]
    
  2. If You Want To install the latest version of Cordova:

    npm install -g cordova 
    

Enjoy!

Websocket connections with Postman

I ran into the exact same problem. Had to make a Web Socket call. I was able to accomplish this using Advanced Rest Client. I'm using ARC version : 12.1.3

enter image description here

What underlies this JavaScript idiom: var self = this?

See this article on alistapart.com. (Ed: The article has been updated since originally linked)

self is being used to maintain a reference to the original this even as the context is changing. It's a technique often used in event handlers (especially in closures).

Edit: Note that using self is now discouraged as window.self exists and has the potential to cause errors if you are not careful.

What you call the variable doesn't particularly matter. var that = this; is fine, but there's nothing magic about the name.

Functions declared inside a context (e.g. callbacks, closures) will have access to the variables/function declared in the same scope or above.

For example, a simple event callback:

_x000D_
_x000D_
function MyConstructor(options) {_x000D_
  let that = this;_x000D_
_x000D_
  this.someprop = options.someprop || 'defaultprop';_x000D_
_x000D_
  document.addEventListener('click', (event) => {_x000D_
    alert(that.someprop);_x000D_
  });_x000D_
}_x000D_
_x000D_
new MyConstructor({_x000D_
  someprop: "Hello World"_x000D_
});
_x000D_
_x000D_
_x000D_

Change New Google Recaptcha (v2) Width

You can use parameter from reCaptcha. By default it uses normal value on data-size, You just have to use compact to fit this on small devices or some-kind small width layouts.

example:

<div class="g-recaptcha" data-size="compact"></div>

Disable developer mode extensions pop up in Chrome

Based on Antony Hatchkins's answer:

The official way to disable the popup seems to be like this:

  1. Pack your extension (chrome://extensions/, tick at 'Developer mode', hit 'Pack extension...') and install it via drag-and-dropping the .crx file into the chrome://extensions page.

    (Since the extension is not from Chrome Web Store, it will be disabled by default.)

Then for Windows:

  1. In Chrome, go to the Extensions page (chrome://extensions)
  2. Check the Developer Mode checkbox at the top
  3. Scroll down the list of disabled extensions and note the ID(s) of the extensions you want to enable. LogMeIn, for example, is ID: nmgnihglilniboicepgjclfiageofdfj
  4. Click Start > Run, and type regedit <ENTER>
  5. Under key HKLM\Software\Policies\Google\Chrome\ExtensionInstallWhitelist (create it if not exists), create a new string for each extension you want to enable with sequential names (indices), e.g. 1, 2, ...
  6. Enter the extension ID(s) as string values in any order. For example, there is a string with name 1 and value nmgnihglilniboicepgjclfiageofdfj
  7. Restart Chrome

That's it!

Note: When you update a whitelisted extension, you do not have to follow the same steps since the ID of the extension will not change.

How to check existence of user-define table type in SQL Server 2008?

You can use also system table_types view

IF EXISTS (SELECT *
           FROM   [sys].[table_types]
           WHERE  user_type_id = Type_id(N'[dbo].[UdTableType]'))
  BEGIN
      PRINT 'EXISTS'
  END 

Rounding to 2 decimal places in SQL

This works too. The below statement rounds to two decimal places.

SELECT ROUND(92.258,2) from dual;