Programs & Examples On #Relative url

Relative path in HTML

You say your website is in http://localhost/mywebsite, and let's say that your image is inside a subfolder named pictures/:

Absolute path

If you use an absolute path, / would point to the root of the site, not the root of the document: localhost in your case. That's why you need to specify your document's folder in order to access the pictures folder:

"/mywebsite/pictures/picture.png"

And it would be the same as:

"http://localhost/mywebsite/pictures/picture.png"

Relative path

A relative path is always relative to the root of the document, so if your html is at the same level of the directory, you'd need to start the path directly with your picture's directory name:

"pictures/picture.png"

But there are other perks with relative paths:

dot-slash (./)

Dot (.) points to the same directory and the slash (/) gives access to it:

So this:

"pictures/picture.png"

Would be the same as this:

"./pictures/picture.png"

Double-dot-slash (../)

In this case, a double dot (..) points to the upper directory and likewise, the slash (/) gives you access to it. So if you wanted to access a picture that is on a directory one level above of the current directory your document is, your URL would look like this:

"../picture.png"

You can play around with them as much as you want, a little example would be this:

Let's say you're on directory A, and you want to access directory X.

- root
   |- a
      |- A
   |- b
   |- x
      |- X

Your URL would look either:

Absolute path

"/x/X/picture.png"

Or:

Relative path

"./../x/X/picture.png"

Why does Git say my master branch is "already up to date" even though it is not?

Any changes you commit, like deleting all your project files, will still be in place after a pull. All a pull does is merge the latest changes from somewhere else into your own branch, and if your branch has deleted everything, then at best you'll get merge conflicts when upstream changes affect files you've deleted. So, in short, yes everything is up to date.

If you describe what outcome you'd like to have instead of "all files deleted", maybe someone can suggest an appropriate course of action.

Update:

GET THE MOST RECENT OF THE CODE ON MY SYSTEM

What you don't seem to understand is that you already have the most recent code, which is yours. If what you really want is to see the most recent of someone else's work that's on the master branch, just do:

git fetch upstream
git checkout upstream/master

Note that this won't leave you in a position to immediately (re)start your own work. If you need to know how to undo something you've done or otherwise revert changes you or someone else have made, then please provide details. Also, consider reading up on what version control is for, since you seem to misunderstand its basic purpose.

Is it possible to capture a Ctrl+C signal and run a cleanup function, in a "defer" fashion?

You can use the os/signal package to handle incoming signals. Ctrl+C is SIGINT, so you can use this to trap os.Interrupt.

c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func(){
    for sig := range c {
        // sig is a ^C, handle it
    }
}()

The manner in which you cause your program to terminate and print information is entirely up to you.

Get the distance between two geo points

There are a couple of methods you could use, but to determine which one is best we first need to know if you are aware of the user's altitude, as well as the altitude of the other points?

Depending on the level of accuracy you are after, you could look into either the Haversine or Vincenty formulae...

These pages detail the formulae, and, for the less mathematically inclined also provide an explanation of how to implement them in script!

Haversine Formula: http://www.movable-type.co.uk/scripts/latlong.html

Vincenty Formula: http://www.movable-type.co.uk/scripts/latlong-vincenty.html

If you have any problems with any of the meanings in the formulae, just comment and I'll do my best to answer them :)

What datatype should be used for storing phone numbers in SQL Server 2005?

SQL Server 2005 is pretty well optimized for substring queries for text in indexed varchar fields. For 2005 they introduced new statistics to the string summary for index fields. This helps significantly with full text searching.

INNER JOIN in UPDATE sql for DB2

Update to the answer https://stackoverflow.com/a/4184237/565525:

if you want multiple columns, that can be achived like this:

update file1
set
  (firstfield, secondfield) = (
        select 'stuff' concat 'something from file2', 
               'some secondfield value' 
        from file2
        where substr(file1.field1, 10, 20) = substr(file2.xxx,1,10) )
where
  file1.foo like 'BLAH%'

Source: http://www.dbforums.com/db2/1615011-sql-update-using-join-subquery.html#post6257307

Explain the concept of a stack frame in a nutshell

"A call stack is composed of stack frames..." — Wikipedia

A stack frame is a thing that you put on the stack. They are data structures that contain information about subroutines to call.

posting hidden value

You should never assume register_global_variables is turned on. Even if it is, it's deprecated and you should never use it that way.

Refer directly to the $_POST or $_GET variables. Most likely your form is POSTing, so you'd want your code to look something along the lines of this:

<input type="hidden" name="date" id="hiddenField" value="<?php echo $_POST['date'] ?>" />

If this doesn't work for you right away, print out the $_POST or $_GET variable on the page that would have the hidden form field and determine exactly what you want and refer to it.

echo "<pre>";
print_r($_POST);
echo "</pre>";

"SetPropertiesRule" warning message when starting Tomcat from Eclipse

I'm finding that Tomcat can't seem to find classes defined in other projects, maybe even in the main project. It's failing on the filter definition which is the first definition in web.xml. If I add the project and its dependencies to the server's launch configuration then I just move on to a new error, all of which seems to point to it not setting up the project properly.

Our setup is quite complex. We have multiple components as projects in Eclipse with separate output projects. We have a separate webapp directory which contains the static HTML and images, as well as our WEB-INF.

Eclipse is "Europa Winter release". Tomcat is 6.0.18. I tried version 2.4 and 2.5 of the "Dynamic Web Module" facet.

Thanks for any help!

  • Richard

How to change lowercase chars to uppercase using the 'keyup' event?

Make sure that the field has this attribute in its html.

_x000D_
_x000D_
ClientIDMode="Static"
_x000D_
_x000D_
_x000D_

and then use this in your script:

_x000D_
_x000D_
$("#NameOfYourTextBox").change(function () {_x000D_
                 $(this).val($(this).val().toUpperCase());_x000D_
             });
_x000D_
_x000D_
_x000D_

Const in JavaScript: when to use it and is it necessary?

You have great answers, but let's keep it simple.

const should be used when you have a defined constant (read as: it won't change during your program execution).

For example:

const pi = 3.1415926535

If you think that it is something that may be changed on later execution then use a var.

The practical difference, based on the example, is that with const you will always asume that pi will be 3.14[...], it's a fact.

If you define it as a var, it might be 3.14[...] or not.

For a more technical answer @Tibos is academically right.

npm ERR cb() never called

For me on npm 6.4.0 and node 10.9.0 none of the answers worked. Reinstalled node, npm, cleaned cache, removed folders ...

After some debugging it turned out I used npm link for two of my modules under development to link to each other. Once I removed and redid some linking I was able to get it all working again.

Error to run Android Studio

First check if the Java JDK is installed correctly:

dpkg --list | grep -i jdk

If not, install the JDK:

  1. Download the latest version of the JDK from Oracle: http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

  2. Extract it to the appropriate location in your machine. Get the extract location:

    vi ~/.bashrc or vi ~./ bash_profile

    JAVA_HOME=/home/user/installs/jdk1.7.0_40
    PATH=$JAVA_HOME/bin
    

    source ~/.bashrc or source ~/.bash_profile

  3. After the installation you can check it:

    java -version
    which java
    

    If all things are correct then the right the answer should be something like this:

    java version "1.7.0_40"
    Java(TM) SE Runtime Environment (build 1.7.0_40-b43)
    Java HotSpot(TM) 64-Bit Server VM (build 24.0-b56, mixed mode)

  4. Append the following statement to studio.sh the file in android-studio/bin directory:

    JAVA_HOME=/home/user/installs/jdk1.7.0_40
    

Finally start your Android Studio with the following command:

./studio.sh 

Case statement in MySQL

MySQL also has IF():

SELECT 
  id, action_heading, 
      IF(action_type='Income',action_amount,0) income, 
      IF(action_type='Expense', action_amount, 0) expense
FROM tbl_transaction

XMLHttpRequest module not defined/found

XMLHttpRequest is a built-in object in web browsers.

It is not distributed with Node; you have to install it separately,

  1. Install it with npm,

    npm install xmlhttprequest
    
  2. Now you can require it in your code.

    var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
    var xhr = new XMLHttpRequest();
    

That said, the http module is the built-in tool for making HTTP requests from Node.

Axios is a library for making HTTP requests which is available for Node and browsers that is very popular these days.

How do I add files and folders into GitHub repos?

If you want to add an empty folder you can add a '.keep' file in your folder.

This is because git does not care about folders.

Python in Xcode 4+?

Another way, which I've been using for awhile in XCode3:

See steps 1-15 above.

  1. Choose /bin/bash as your executable
  2. For the "Debugger" field, select "None".
  3. In the "Arguments" tab, click the "Base Expansions On" field and select the target you created earlier.
  4. Click the "+" icon under "Arguments Passed On Launch". You may have to expand that section by clicking on the triangle pointing to the right.
  5. Type in "-l". This will tell bash to use your login environment (PYTHONPATH, etc..)
  6. Do step #19 again.
  7. Type in "-c '$(SOURCE_ROOT)/.py'"
  8. Click "OK".
  9. Start coding.

The nice thing about this way is it will use the same environment to develop in that you would use to run in outside of XCode (as setup from your bash .profile).

It's also generic enough to let you develop/run any type of file, not just python.

ASP.NET MVC Bundle not rendering script files on staging server. It works on development server

I ran into the same problem, and I'm not sure why, but it turned out to be that the script link generated by Scripts.Render did not have a .js extension. Because it also does not have a Type attribute the browser was just unable to use it (chrome and firefox).

To resolve this, I changed my bundle configuration to generate compiled files with a js extension, e.g.

            var coreScripts = new ScriptBundle("~/bundles/coreAssets.js")
            .Include("~/scripts/jquery.js");

        var coreStyles = new StyleBundle("~/bundles/coreStyles.css")
            .Include("~/css/bootstrap.css");

Notice in new StyleBundle(... instead of saying ~/bundles/someBundle, I am saying ~/bundlers/someBundle.js or ~/bundles/someStyles.css..

This causes the link generated in the src attribute to have .js or .css on it when optimizations are enabled, as such the browsers know based on the file extension what mime/type to use on the get request and everything works.

If I take off the extension, everything breaks. That's because @Scripts and @Styles doesn't render all the necessary attributes to understand a src to a file with no extension.

Install pip in docker

An alternative is to use the Alpine Linux containers, e.g. python:2.7-alpine. They offer pip out of the box (and have a smaller footprint which leads to faster builds etc).

Reading a string with scanf

I think that this below is accurate and it may help. Feel free to correct it if you find any errors. I'm new at C.

char str[]  
  1. array of values of type char, with its own address in memory
  2. array of values of type char, with its own address in memory as many consecutive addresses as elements in the array
  3. including termination null character '\0' &str, &str[0] and str, all three represent the same location in memory which is address of the first element of the array str

    char *strPtr = &str[0]; //declaration and initialization

alternatively, you can split this in two:

char *strPtr; strPtr = &str[0];
  1. strPtr is a pointer to a char
  2. strPtr points at array str
  3. strPtr is a variable with its own address in memory
  4. strPtr is a variable that stores value of address &str[0]
  5. strPtr own address in memory is different from the memory address that it stores (address of array in memory a.k.a &str[0])
  6. &strPtr represents the address of strPtr itself

I think that you could declare a pointer to a pointer as:

char **vPtr = &strPtr;  

declares and initializes with address of strPtr pointer

Alternatively you could split in two:

char **vPtr;
*vPtr = &strPtr
  1. *vPtr points at strPtr pointer
  2. *vPtr is a variable with its own address in memory
  3. *vPtr is a variable that stores value of address &strPtr
  4. final comment: you can not do str++, str address is a const, but you can do strPtr++

What value could I insert into a bit type column?

If you're using SQL Server, you can set the value of bit fields with 0 and 1

or

'true' and 'false' (yes, using strings)

...your_bit_field='false'... => equivalent to 0

Declare a const array

You could take a different approach: define a constant string to represent your array and then split the string into an array when you need it, e.g.

const string DefaultDistances = "5,10,15,20,25,30,40,50";
public static readonly string[] distances = DefaultDistances.Split(',');

This approach gives you a constant which can be stored in configuration and converted to an array when needed.

Django set default form values

Other solution: Set initial after creating the form:

form.fields['tank'].initial = 123

How can I replace a newline (\n) using sed?

Replace newlines with any string, and replace the last newline too

The pure tr solutions can only replace with a single character, and the pure sed solutions don't replace the last newline of the input. The following solution fixes these problems, and seems to be safe for binary data (even with a UTF-8 locale):

printf '1\n2\n3\n' |
  sed 's/%/%p/g;s/@/%a/g' | tr '\n' @ | sed 's/@/<br>/g;s/%a/@/g;s/%p/%/g'

Result:

1<br>2<br>3<br>

Html.DropdownListFor selected value not being set

You should forget the class

SelectList

Use this in your Controller:

var customerTypes = new[] 
{ 
    new SelectListItem(){Value = "all", Text= "All"},
    new SelectListItem(){Value = "business", Text= "Business"},
    new SelectListItem(){Value = "private", Text= "Private"},
};

Select the value:

var selectedCustomerType = customerTypes.FirstOrDefault(d => d.Value == "private");
if (selectedCustomerType != null)
    selectedCustomerType.Selected = true;

Add the list to the ViewData:

ViewBag.CustomerTypes = customerTypes;

Use this in your View:

@Html.DropDownList("SectionType", (SelectListItem[])ViewBag.CustomerTypes)

-

More information at: http://www.asp.net/mvc/overview/older-versions/working-with-the-dropdownlist-box-and-jquery/using-the-dropdownlist-helper-with-aspnet-mvc

What is the maximum length of a String in PHP?

The maximum length of a string variable is only 2GiB - (2^(32-1) bits). Variables can be addressed on a character (8 bits/1 byte) basis and the addressing is done by signed integers which is why the limit is what it is. Arrays can contain multiple variables that each follow the previous restriction but can have a total cumulative size up to memory_limit of which a string variable is also subject to.

How Can I Bypass the X-Frame-Options: SAMEORIGIN HTTP Header?

The X-Frame-Options header is a security feature enforced at the browser level.

If you have control over your user base (IT dept for corp app), you could try something like a greasemonkey script (if you can a) deploy greasemonkey across everyone and b) deploy your script in a shared way)...

Alternatively, you can proxy their result. Create an endpoint on your server, and have that endpoint open a connection to the target endpoint, and simply funnel traffic backwards.

How to compare Boolean?

From your comments, it seems like you're looking for "best practices" for the use of the Boolean wrapper class. But there really aren't any best practices, because it's a bad idea to use this class to begin with. The only reason to use the object wrapper is in cases where you absolutely must (such as when using Generics, i.e., storing a boolean in a HashMap<String, Boolean> or the like). Using the object wrapper has no upsides and a lot of downsides, most notably that it opens you up to NullPointerExceptions.

Does it matter if '!' is used instead of .equals() for Boolean?

Both techniques will be susceptible to a NullPointerException, so it doesn't matter in that regard. In the first scenario, the Boolean will be unboxed into its respective boolean value and compared as normal. In the second scenario, you are invoking a method from the Boolean class, which is the following:

public boolean equals(Object obj) {
    if (obj instanceof Boolean) {
        return value == ((Boolean)obj).booleanValue();
    }
    return false;
}

Either way, the results are the same.

Would it matter if .equals(false) was used to check for the value of the Boolean checker?

Per above, no.

Secondary question: Should Boolean be dealt differently than boolean?

If you absolutely must use the Boolean class, always check for null before performing any comparisons. e.g.,

Map<String, Boolean> map = new HashMap<String, Boolean>();
//...stuff to populate the Map
Boolean value = map.get("someKey");
if(value != null && value) {
    //do stuff
}

This will work because Java short-circuits conditional evaluations. You can also use the ternary operator.

boolean easyToUseValue = value != null ? value : false;

But seriously... just use the primitive type, unless you're forced not to.

How do you find the first key in a dictionary?

Well as simple, the answer according to me will be

first = list(prices)[0]

converting the dictionary to list will output the keys and we will select the first key from the list.

Adding click event listener to elements with the same class

I find it more convenient to use something like the following:

document.querySelector('*').addEventListener('click',function(event){

    if( event.target.tagName != "IMG"){
        return;
    }

    // HANDLE CLICK ON IMAGES HERE
});

store return value of a Python script in a bash script

read it in the docs. If you return anything but an int or None it will be printed to stderr.

To get just stderr while discarding stdout do:

output=$(python foo.py 2>&1 >/dev/null)

Node.js: Python not found exception due to node-sass and node-gyp

I had node 15.x.x , and "node-sass": "^4.11.0". I saw in the release notes from node-sass and saw the node higest version compatible with node-sass 4.11.0 was 11, so I uninstalled node and reinstall 11.15.0 version (I'm working with Windows). Check node-sass releases. (this is what you should see in the node-sass releases.)

Hope that helps and sorry for my english :)

Is there a way to use use text as the background with CSS?

SVG text background image

_x000D_
_x000D_
body {_x000D_
    background-image:url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' version='1.1' height='50px' width='120px'><text x='0' y='15' fill='red' font-size='20'>I love SVG!</text></svg>");_x000D_
}
_x000D_
<p>I hate SVG!</p><p>I hate SVG!</p><p>I hate SVG!</p><p>I hate SVG!</p>_x000D_
<p>I hate SVG!</p><p>I hate SVG!</p><p>I hate SVG!</p><p>I hate SVG!</p>
_x000D_
_x000D_
_x000D_

Here is an indented version of the CSS so you can understand better. Note that this does not work, you need to use the single liner SVG from the snippet above instead:

body {
  background-image:url("data:image/svg+xml;utf8,
  <svg xmlns='http://www.w3.org/2000/svg' version='1.1'
       height='50px' width='120px'>
    <text x='0' y='15' fill='red' font-size='20'>I love SVG!</text>
  </svg>");
}

Not sure how portable this is (works on Firefox 31 and Chrome 36), and it is technically an image... but the source is inline and plain text, and it scales infinitely.

@senectus found that it works better on IE if you base64 encode it: https://stackoverflow.com/a/25593531/895245

How do I write to the console from a Laravel Controller?

Aha!

This can be done with the following PHP function:

error_log('Some message here.');

Found the answer here: Print something in PHP built-in web server

How to compile C++ under Ubuntu Linux?

You should use g++, not gcc, to compile C++ programs.

For this particular program, I just typed

make avishay

and let make figure out the rest. Gives your executable a decent name, too, instead of a.out.

SQL How to remove duplicates within select query?

You mention that there are date duplicates, but it appears they're quite unique down to the precision of seconds.

Can you clarify what precision of date you start considering dates duplicate - day, hour, minute?

In any case, you'll probably want to floor your datetime field. You didn't indicate which field is preferred when removing duplicates, so this query will prefer the last name in alphabetical order.

 SELECT MAX(owner_name), 
        --floored to the second
        dateadd(second,datediff(second,'2000-01-01',start_date),'2000-01-01') AS StartDate
 From   MyTable
 GROUP BY dateadd(second,datediff(second,'2000-01-01',start_date),'2000-01-01')

(413) Request Entity Too Large | uploadReadAheadSize

That is not problem of IIS but the problem of WCF. WCF by default limits messages to 65KB to avoid denial of service attack with large messages. Also if you don't use MTOM it sends byte[] to base64 encoded string (33% increase in size) => 48KB * 1,33 = 64KB

To solve this issue you must reconfigure your service to accept larger messages. This issue previously fired 400 Bad Request error but in newer version WCF started to use 413 which is correct status code for this type of error.

You need to set maxReceivedMessageSize in your binding. You can also need to set readerQuotas.

<system.serviceModel>
  <bindings>
    <basicHttpBinding>
      <binding maxReceivedMessageSize="10485760">
        <readerQuotas ... />
      </binding>
    </basicHttpBinding>
  </bindings>  
</system.serviceModel>

Creating a new database and new connection in Oracle SQL Developer

  1. Connect to sys.
  2. Give your password for sys.
  3. Unlock hr user by running following query:

alter user hr identified by hr account unlock;

  1. Then, Click on new connection
  2. Give connection name as HR_ORCL Username: hr Password: hr Connection Type: Basic Role: default Hostname: localhost Port: 1521 SID: xe

  3. Click on test and Connect

Git Push error: refusing to update checked out branch

cd into the repo/directory that you're pushing into on the remote machine and enter

$ git config core.bare true

Is there a method that calculates a factorial in Java?

Try this

public static BigInteger factorial(int value){
    if(value < 0){
        throw new IllegalArgumentException("Value must be positive");
    }

    BigInteger result = BigInteger.ONE;
    for (int i = 2; i <= value; i++) {
        result = result.multiply(BigInteger.valueOf(i));
    }

    return result;
}

CSS: Change image src on img:hover

Concerning semantics, I do not like any solution given so far. Therefore, I personally use the following solution:

_x000D_
_x000D_
.img-wrapper {_x000D_
  display: inline-block;_x000D_
  background-image: url(https://www.w3schools.com/w3images/fjords.jpg);_x000D_
}_x000D_
_x000D_
.img-wrapper > img {_x000D_
  vertical-align: top;_x000D_
}_x000D_
_x000D_
.img-wrapper > img:hover {_x000D_
  opacity: 0;_x000D_
}
_x000D_
<div class="img-wrapper">_x000D_
  <img src="https://www.w3schools.com/w3css/img_lights.jpg" alt="image" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

This is a CSS only solution with good browser compatibility. It makes use of an image wrapper that has a background which is initially hidden by the image itself. On hover, the image is hidden through the opacity, hence the background image becomes visible. This way, one does not have an empty wrapper but a real image in the markup code.

Adb install failure: INSTALL_CANCELED_BY_USER

Faced the same Issue in MI devices and figured out the problem by following these Steps :

1) Go to Setting

2) Click on Additional Settings

3) Click on Developer Options

4) Click toggle of Install via USB to enable it

and the issue will be resolved.

enter image description here

How to Convert Datetime to Date in dd/MM/yyyy format

Give a different alias

SELECT  Convert(varchar,A.InsertDate,103) as converted_Tran_Date from table as A
order by A.InsertDate 

Javascript decoding html entities

var text = '&lt;p&gt;name&lt;/p&gt;&lt;p&gt;&lt;span style="font-size:xx-small;"&gt;ajde&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;em&gt;da&lt;/em&gt;&lt;/p&gt;';
var decoded = $('<textarea/>').html(text).text();
alert(decoded);

This sets the innerHTML of a new element (not appended to the page), causing jQuery to decode it into HTML, which is then pulled back out with .text().

Live demo.

Refresh Part of Page (div)

Let's assume that you have 2 divs inside of your html file.

<div id="div1">some text</div>
<div id="div2">some other text</div>

The java program itself can't update the content of the html file because the html is related to the client, meanwhile java is related to the back-end.

You can, however, communicate between the server (the back-end) and the client.

What we're talking about is AJAX, which you achieve using JavaScript, I recommend using jQuery which is a common JavaScript library.

Let's assume you want to refresh the page every constant interval, then you can use the interval function to repeat the same action every x time.

setInterval(function()
{
    alert("hi");
}, 30000);

You could also do it like this:

setTimeout(foo, 30000);

Whereea foo is a function.

Instead of the alert("hi") you can perform the AJAX request, which sends a request to the server and receives some information (for example the new text) which you can use to load into the div.

A classic AJAX looks like this:

var fetch = true;
var url = 'someurl.java';
$.ajax(
{
    // Post the variable fetch to url.
    type : 'post',
    url : url,
    dataType : 'json', // expected returned data format.
    data : 
    {
        'fetch' : fetch // You might want to indicate what you're requesting.
    },
    success : function(data)
    {
        // This happens AFTER the backend has returned an JSON array (or other object type)
        var res1, res2;

        for(var i = 0; i < data.length; i++)
        {
            // Parse through the JSON array which was returned.
            // A proper error handling should be added here (check if
            // everything went successful or not)

            res1 = data[i].res1;
            res2 = data[i].res2;

            // Do something with the returned data
            $('#div1').html(res1);
        }
    },
    complete : function(data)
    {
        // do something, not critical.
    }
});

Wherea the backend is able to receive POST'ed data and is able to return a data object of information, for example (and very preferrable) JSON, there are many tutorials out there with how to do so, GSON from Google is something that I used a while back, you could take a look into it.

I'm not professional with Java POST receiving and JSON returning of that sort so I'm not going to give you an example with that but I hope this is a decent start.

sorting integers in order lowest to highest java

Take Inputs from User and Insertion Sort. Here is how it works:

package com.learning.constructor;

import java.util.Scanner;



public class InsertionSortArray {

public static void main(String[] args) {    

Scanner s=new Scanner(System.in);

System.out.println("enter number of elements");

int n=s.nextInt();


int arr[]=new int[n];

System.out.println("enter elements");

for(int i=0;i<n;i++){//for reading array
    arr[i]=s.nextInt();

}

System.out.print("Your Array Is: ");
//for(int i: arr){ //for printing array
for (int i = 0; i < arr.length; i++){
    System.out.print(arr[i] + ",");

}
System.out.println("\n");        

    int[] input = arr;
    insertionSort(input);
}

private static void printNumbers(int[] input) {

    for (int i = 0; i < input.length; i++) {
        System.out.print(input[i] + ", ");
    }
    System.out.println("\n");
}

public static void insertionSort(int array[]) {
    int n = array.length;
    for (int j = 1; j < n; j++) {
        int key = array[j];
        int i = j-1;
        while ( (i > -1) && ( array [i] > key ) ) {
            array [i+1] = array [i];
            i--;
        }
        array[i+1] = key;
        printNumbers(array);
    }
}

}

Create a branch in Git from another branch

Do simultaneous work on the dev branch. What happens is that in your scenario the feature branch moves forward from the tip of the dev branch, but the dev branch does not change. It's easier to draw as a straight line, because it can be thought of as forward motion. You made it to point A on dev, and from there you simply continued on a parallel path. The two branches have not really diverged.

Now, if you make a commit on dev, before merging, you will again begin at the same commit, A, but now features will go to C and dev to B. This will show the split you are trying to visualize, as the branches have now diverged.

*-----*Dev-------*Feature

Versus

       /----*DevB
*-----*DevA
       \----*FeatureC

Sending "User-agent" using Requests library in Python

The user-agent should be specified as a field in the header.

Here is a list of HTTP header fields, and you'd probably be interested in request-specific fields, which includes User-Agent.

If you're using requests v2.13 and newer

The simplest way to do what you want is to create a dictionary and specify your headers directly, like so:

import requests

url = 'SOME URL'

headers = {
    'User-Agent': 'My User Agent 1.0',
    'From': '[email protected]'  # This is another valid field
}

response = requests.get(url, headers=headers)

If you're using requests v2.12.x and older

Older versions of requests clobbered default headers, so you'd want to do the following to preserve default headers and then add your own to them.

import requests

url = 'SOME URL'

# Get a copy of the default headers that requests would use
headers = requests.utils.default_headers()

# Update the headers with your custom ones
# You don't have to worry about case-sensitivity with
# the dictionary keys, because default_headers uses a custom
# CaseInsensitiveDict implementation within requests' source code.
headers.update(
    {
        'User-Agent': 'My User Agent 1.0',
    }
)

response = requests.get(url, headers=headers)

How to send post request with x-www-form-urlencoded body

As you set application/x-www-form-urlencoded as content type so data sent must be like this format.

String urlParameters  = "param1=data1&param2=data2&param3=data3";

Sending part now is quite straightforward.

byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 );
int postDataLength = postData.length;
String request = "<Url here>";
URL url = new URL( request );
HttpURLConnection conn= (HttpURLConnection) url.openConnection();           
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
conn.setRequestProperty("charset", "utf-8");
conn.setRequestProperty("Content-Length", Integer.toString(postDataLength ));
conn.setUseCaches(false);
try(DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
   wr.write( postData );
}

Or you can create a generic method to build key value pattern which is required for application/x-www-form-urlencoded.

private String getDataString(HashMap<String, String> params) throws UnsupportedEncodingException{
    StringBuilder result = new StringBuilder();
    boolean first = true;
    for(Map.Entry<String, String> entry : params.entrySet()){
        if (first)
            first = false;
        else
            result.append("&");    
        result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
    }    
    return result.toString();
}

Serialize Property as Xml Attribute in Element

You will need wrapper classes:

public class SomeIntInfo
{
    [XmlAttribute]
    public int Value { get; set; }
}

public class SomeStringInfo
{
    [XmlAttribute]
    public string Value { get; set; }
}

public class SomeModel
{
    [XmlElement("SomeStringElementName")]
    public SomeStringInfo SomeString { get; set; }

    [XmlElement("SomeInfoElementName")]
    public SomeIntInfo SomeInfo { get; set; }
}

or a more generic approach if you prefer:

public class SomeInfo<T>
{
    [XmlAttribute]
    public T Value { get; set; }
}

public class SomeModel
{
    [XmlElement("SomeStringElementName")]
    public SomeInfo<string> SomeString { get; set; }

    [XmlElement("SomeInfoElementName")]
    public SomeInfo<int> SomeInfo { get; set; }
}

And then:

class Program
{
    static void Main()
    {
        var model = new SomeModel
        {
            SomeString = new SomeInfo<string> { Value = "testData" },
            SomeInfo = new SomeInfo<int> { Value = 5 }
        };
        var serializer = new XmlSerializer(model.GetType());
        serializer.Serialize(Console.Out, model);
    }
}

will produce:

<?xml version="1.0" encoding="ibm850"?>
<SomeModel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <SomeStringElementName Value="testData" />
  <SomeInfoElementName Value="5" />
</SomeModel>

"Could not find a valid gem in any repository" (rubygame and others)

I know this is a little late, but I was also having this issue a while ago. This is what worked for me:

REALLY_GEM_UPDATE_SYSTEM=1 
sudo gem update --system
sudo gem install rails

Hope this helps anyone else having this issue :)

Decode Hex String in Python 3

The answers from @unbeli and @Niklas are good, but @unbeli's answer does not work for all hex strings and it is desirable to do the decoding without importing an extra library (codecs). The following should work (but will not be very efficient for large strings):

>>> result = bytes.fromhex((lambda s: ("%s%s00" * (len(s)//2)) % tuple(s))('4a82fdfeff00')).decode('utf-16-le')
>>> result == '\x4a\x82\xfd\xfe\xff\x00'
True

Basically, it works around having invalid utf-8 bytes by padding with zeros and decoding as utf-16.

Simulator or Emulator? What is the difference?

The definitions of the words describe the difference the best. A google search gives the following definitions of simulate and emulate:

simulate imitate the appearance or character of.

emulate match or surpass (a person or achievement), typically by imitation.

A simulation imitates a system. An emulation simulates a system so well that it could replace it or may even surpass it.

In computing, an emulation would be a drop in replacement for the system it is emulating. Often times it will even outperform the system it is imitating. For example, game console emulators usually make improvements such as greater hardware compatibility, better performance, and improved audio/video quality.

Simulations, on the other hand, are limited by them being models. They are a best attempt to mimic a system, but not replacements for it. There are hardware emulators because hardware can be imitated and it would be hard to tell the difference. There is no Farming Emulator because there is no emulation that could replace actual farming. We can only simulate a model of farming to gain insight on how to farm better.

How do you check if a selector matches something in jQuery?

Alternatively:

if( jQuery('#elem').get(0) ) {}

Getting The ASCII Value of a character in a C# string

Here is another alternative. It will of course give you a bad result if the input char is not ascii. I've not perf tested it but I think it would be pretty fast:

[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int GetAsciiVal(string s, int index) {
    return GetAsciiVal(s[index]);
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int GetAsciiVal(char c) {
    return unchecked(c & 0xFF);
}

import module from string variable

The __import__ function can be a bit hard to understand.

If you change

i = __import__('matplotlib.text')

to

i = __import__('matplotlib.text', fromlist=[''])

then i will refer to matplotlib.text.

In Python 2.7 and Python 3.1 or later, you can use importlib:

import importlib

i = importlib.import_module("matplotlib.text")

Some notes

  • If you're trying to import something from a sub-folder e.g. ./feature/email.py, the code will look like importlib.import_module("feature.email")

  • You can't import anything if there is no __init__.py in the folder with file you are trying to import

Allow only pdf, doc, docx format for file upload?

For only acept files with extension doc and docx in the explorer window try this

    <input type="file" id="docpicker"
  accept=".doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document">

how to set textbox value in jquery

I think you want to set the response of the call to the URL 'compz.php?prodid=' + x + '&qbuys=' + y as value of the textbox right? If so, you have to do something like:

$.get('compz.php?prodid=' + x + '&qbuys=' + y, function(data) {
    $('#subtotal').val(data);
});

Reference: get()

You have two errors in your code:

  • load() puts the HTML returned from the Ajax into the specified element:

    Load data from the server and place the returned HTML into the matched element.

    You cannot set the value of a textbox with that method.

  • $(selector).load() returns the a jQuery object. By default an object is converted to [object Object] when treated as string.

Further clarification:

Assuming your URL returns 5.

If your HTML looks like:

<div id="foo"></div>

then the result of

$('#foo').load('/your/url');

will be

<div id="foo">5</div>

But in your code, you have an input element. Theoretically (it is not valid HTML and does not work as you noticed), an equivalent call would result in

<input id="foo">5</input>

But you actually need

<input id="foo" value="5" />

Therefore, you cannot use load(). You have to use another method, get the response and set it as value yourself.

Android: Remove all the previous activities from the back stack

Here is one solution to clear all your application's activities when you use the logout button.

Every time you start an Activity, start it like this:

Intent myIntent = new Intent(getBaseContext(), YourNewActivity.class);
startActivityForResult(myIntent, 0);

When you want to close the entire app, do this:

setResult(RESULT_CLOSE_ALL);
finish();

RESULT_CLOSE_ALL is a final global variable with a unique integer to signal you want to close all activities.

Then define every activity's onActivityResult(...) callback so when an activity returns with the RESULT_CLOSE_ALL value, it also calls finish():

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch(resultCode)
    {
    case RESULT_CLOSE_ALL:
        setResult(RESULT_CLOSE_ALL);
        finish();
    }
    super.onActivityResult(requestCode, resultCode, data);
}

This will cause a cascade effect that closes all your activities.

This is a hack however and uses startActivityForResult in a way that it was not designed to be used.

Perhaps a better way to do this would be using broadcast receivers as shown here:

On logout, clear Activity history stack, preventing "back" button from opening logged-in-only Activites

See these threads for other methods as well:

Android: Clear the back stack

Finish all previous activities

How to do multiline shell script in Ansible

I prefer this syntax as it allows to set configuration parameters for the shell:

---
- name: an example
  shell:
    cmd: |
      docker build -t current_dir .
      echo "Hello World"
      date

    chdir: /home/vagrant/

Prevent wrapping of span or div

Looks like divs will not go outside of their body's width. Even within another div.

I threw this up to test (without a doctype though) and it does not work as thought.

_x000D_
_x000D_
.slideContainer {_x000D_
    overflow-x: scroll;_x000D_
}_x000D_
.slide {_x000D_
    float: left;_x000D_
}
_x000D_
<div class="slideContainer">_x000D_
    <div class="slide" style="background: #f00">Some content Some content Some content Some content Some content Some content</div>_x000D_
    <div class="slide" style="background: #ff0">More content More content More content More content More content More content</div>_x000D_
    <div class="slide" style="background: #f0f">Even More content! Even More content! Even More content!</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What i am thinking is that the inner div's could be loaded through an iFrame, since that is another page and its content could be very wide.

Get Locale Short Date Format using javascript

Can't be done.

Cross-browser JavaScript has no way to use the actual short date format selected by the user on platforms that offer such regional customization. Besides, JavaScript has huge holes where any sort of formatting is concerned. Look how much hassle zero-padding is!

You can go to great lengths to obtain the language setting, and get the typical format for that locale. That's a lot of work when you don't even know if it's the correct locale (I'd bet that international language headers are often incorrect or not specific enough), or if the user has customized the format to something else.

You can try using client VBScript (which has functions for all of these regional formatting permutations), but that's not a good idea because it's a dying (dead?) IE-specific technology.

You can also try using Java/Flash/Silverlight to dig up the format. This is also a great deal of extra work, but may have the best chance for success. You'd want to cache it for the session to minimize the overhead.

Hopefully the HTML5 <time> element will provide some relief for i18n date/time display.

Making an asynchronous task in Flask

Threading is another possible solution. Although the Celery based solution is better for applications at scale, if you are not expecting too much traffic on the endpoint in question, threading is a viable alternative.

This solution is based on Miguel Grinberg's PyCon 2016 Flask at Scale presentation, specifically slide 41 in his slide deck. His code is also available on github for those interested in the original source.

From a user perspective the code works as follows:

  1. You make a call to the endpoint that performs the long running task.
  2. This endpoint returns 202 Accepted with a link to check on the task status.
  3. Calls to the status link returns 202 while the taks is still running, and returns 200 (and the result) when the task is complete.

To convert an api call to a background task, simply add the @async_api decorator.

Here is a fully contained example:

from flask import Flask, g, abort, current_app, request, url_for
from werkzeug.exceptions import HTTPException, InternalServerError
from flask_restful import Resource, Api
from datetime import datetime
from functools import wraps
import threading
import time
import uuid

tasks = {}

app = Flask(__name__)
api = Api(app)


@app.before_first_request
def before_first_request():
    """Start a background thread that cleans up old tasks."""
    def clean_old_tasks():
        """
        This function cleans up old tasks from our in-memory data structure.
        """
        global tasks
        while True:
            # Only keep tasks that are running or that finished less than 5
            # minutes ago.
            five_min_ago = datetime.timestamp(datetime.utcnow()) - 5 * 60
            tasks = {task_id: task for task_id, task in tasks.items()
                     if 'completion_timestamp' not in task or task['completion_timestamp'] > five_min_ago}
            time.sleep(60)

    if not current_app.config['TESTING']:
        thread = threading.Thread(target=clean_old_tasks)
        thread.start()


def async_api(wrapped_function):
    @wraps(wrapped_function)
    def new_function(*args, **kwargs):
        def task_call(flask_app, environ):
            # Create a request context similar to that of the original request
            # so that the task can have access to flask.g, flask.request, etc.
            with flask_app.request_context(environ):
                try:
                    tasks[task_id]['return_value'] = wrapped_function(*args, **kwargs)
                except HTTPException as e:
                    tasks[task_id]['return_value'] = current_app.handle_http_exception(e)
                except Exception as e:
                    # The function raised an exception, so we set a 500 error
                    tasks[task_id]['return_value'] = InternalServerError()
                    if current_app.debug:
                        # We want to find out if something happened so reraise
                        raise
                finally:
                    # We record the time of the response, to help in garbage
                    # collecting old tasks
                    tasks[task_id]['completion_timestamp'] = datetime.timestamp(datetime.utcnow())

                    # close the database session (if any)

        # Assign an id to the asynchronous task
        task_id = uuid.uuid4().hex

        # Record the task, and then launch it
        tasks[task_id] = {'task_thread': threading.Thread(
            target=task_call, args=(current_app._get_current_object(),
                               request.environ))}
        tasks[task_id]['task_thread'].start()

        # Return a 202 response, with a link that the client can use to
        # obtain task status
        print(url_for('gettaskstatus', task_id=task_id))
        return 'accepted', 202, {'Location': url_for('gettaskstatus', task_id=task_id)}
    return new_function


class GetTaskStatus(Resource):
    def get(self, task_id):
        """
        Return status about an asynchronous task. If this request returns a 202
        status code, it means that task hasn't finished yet. Else, the response
        from the task is returned.
        """
        task = tasks.get(task_id)
        if task is None:
            abort(404)
        if 'return_value' not in task:
            return '', 202, {'Location': url_for('gettaskstatus', task_id=task_id)}
        return task['return_value']


class CatchAll(Resource):
    @async_api
    def get(self, path=''):
        # perform some intensive processing
        print("starting processing task, path: '%s'" % path)
        time.sleep(10)
        print("completed processing task, path: '%s'" % path)
        return f'The answer is: {path}'


api.add_resource(CatchAll, '/<path:path>', '/')
api.add_resource(GetTaskStatus, '/status/<task_id>')


if __name__ == '__main__':
    app.run(debug=True)

How to replace comma (,) with a dot (.) using java

Just use replace instead of replaceAll (which expects regex):

str = str.replace(",", ".");

or

str = str.replace(',', '.');

(replace takes as input either char or CharSequence, which is an interface implemented by String)

Also note that you should reassign the result

How to run a Runnable thread in Android at defined intervals?

The simple fix to your example is :

handler = new Handler();

final Runnable r = new Runnable() {
    public void run() {
        tv.append("Hello World");
        handler.postDelayed(this, 1000);
    }
};

handler.postDelayed(r, 1000);

Or we can use normal thread for example (with original Runner) :

Thread thread = new Thread() {
    @Override
    public void run() {
        try {
            while(true) {
                sleep(1000);
                handler.post(this);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
};

thread.start();

You may consider your runnable object just as a command that can be sent to the message queue for execution, and handler as just a helper object used to send that command.

More details are here http://developer.android.com/reference/android/os/Handler.html

How to set JVM parameters for Junit Unit Tests?

You can use systemPropertyVariables (java.protocol.handler.pkgs is your JVM argument name):

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.12.4</version>
    <configuration>
        <systemPropertyVariables>
            <java.protocol.handler.pkgs>com.zunix.base</java.protocol.handler.pkgs>
            <log4j.configuration>log4j-core.properties</log4j.configuration>
        </systemPropertyVariables>
    </configuration>
</plugin>

http://maven.apache.org/surefire/maven-surefire-plugin/examples/system-properties.html

where to place CASE WHEN column IS NULL in this query

Thanks for all your help! @Svetoslav Tsolov had it very close, but I was still getting an error, until I figured out the closing parenthesis was in the wrong place. Here's the final query that works:

SELECT dbo.AdminID.CountryID, dbo.AdminID.CountryName, dbo.AdminID.RegionID, 
dbo.AdminID.[Region name], dbo.AdminID.DistrictID, dbo.AdminID.DistrictName,
dbo.AdminID.ADMIN3_ID, dbo.AdminID.ADMIN3,
(CASE WHEN dbo.EU_Admin3.EUID IS NULL THEN dbo.EU_Admin2.EUID ELSE dbo.EU_Admin3.EUID END) AS EUID
FROM dbo.AdminID 

LEFT OUTER JOIN dbo.EU_Admin2
ON dbo.AdminID.DistrictID = dbo.EU_Admin2.DistrictID

LEFT OUTER JOIN dbo.EU_Admin3
ON dbo.AdminID.ADMIN3_ID = dbo.EU_Admin3.ADMIN3_ID

How do I start my app on startup?

screenshot

I would like to add one point in this question which I was facing for couple of days. I tried all the answers but those were not working for me. If you are using android version 5.1 please change these settings.

If you are using android version 5.1 then you have to dis-select (Restrict to launch) from app settings.

settings> app > your app > Restrict to launch (dis-select)

Compare two different files line by line in python

This solution reads both files in one pass, excludes blank lines, and prints common lines regardless of their position in the file:

with open('some_file_1.txt', 'r') as file1:
    with open('some_file_2.txt', 'r') as file2:
        same = set(file1).intersection(file2)

same.discard('\n')

with open('some_output_file.txt', 'w') as file_out:
    for line in same:
        file_out.write(line)

AngularJS: Insert HTML from a string

Have a look at the example in this link :

http://docs.angularjs.org/api/ngSanitize.$sanitize

Basically, angular has a directive to insert html into pages. In your case you can insert the html using the ng-bind-html directive like so :

If you already have done all this :

// My magic HTML string function.
function htmlString (str) {
    return "<h1>" + str + "</h1>";
}

function Ctrl ($scope) {
  var str = "HELLO!";
  $scope.htmlString = htmlString(str);
}
Ctrl.$inject = ["$scope"];

Then in your html within the scope of that controller, you could

<div ng-bind-html="htmlString"></div>

System.Runtime.InteropServices.COMException (0x800A03EC)

Found Answer.......!!!!!!!

Officially Microsoft Office 2003 Interop is not supported on Windows server 2008 by Microsoft.

But after a lot of permutations & combinations with the code and search, we came across one solution which works for our scenario.

The solution is to plug the difference between the way Windows 2003 and 2008 maintains its folder structure, because Office Interop depends on the desktop folder for file open/save intermediately. The 2003 system houses the desktop folder under systemprofile which is absent in 2008.

So when we create this folder on 2008 under the respective hierarchy as indicated below; the office Interop is able to save the file as required. This Desktop folder is required to be created under

C:\Windows\System32\config\systemprofile

AND

C:\Windows\SysWOW64\config\systemprofile

This worked for me...

Also do check if .NET 1.1 is installed because its needed by Interop and ot preinstalled by Windows Server 2008

Or you can also Use SaveCopyas() method ist just take onargument as filename string)

Thanks Guys..!

How to push objects in AngularJS between ngRepeat arrays

change your method to:

$scope.toggleChecked = function (index) {
    $scope.checked.push($scope.items[index]);
    $scope.items.splice(index, 1);
};

Working Demo

Is it possible to remove inline styles with jQuery?

Here is an inlineStyle selector filter I wrote that plugs into jQuery.

$("div:inlineStyle(display:block)") // will select all divs with an inline style of display: block set

In your case you could use this like:

$("div:inlineStyle(display:block)").hide();

How to POST JSON data with Python Requests?

The better way is:

url = "http://xxx.xxxx.xx"
data = {
    "cardno": "6248889874650987",
    "systemIdentify": "s08",
    "sourceChannel": 12
}
resp = requests.post(url, json=data)

How to get the part of a file after the first line that matches a regular expression?

Use bash parameter expansion like the following:

content=$(cat file)
echo "${content#*TERMINATE}"

Rails find_or_create_by more than one attribute?

For anyone else who stumbles across this thread but needs to find or create an object with attributes that might change depending on the circumstances, add the following method to your model:

# Return the first object which matches the attributes hash
# - or -
# Create new object with the given attributes
#
def self.find_or_create(attributes)
  Model.where(attributes).first || Model.create(attributes)
end

Optimization tip: regardless of which solution you choose, consider adding indexes for the attributes you are querying most frequently.

AWS EFS vs EBS vs S3 (differences & when to use?)

The main difference between EBS and EFS is that EBS is only accessible from a single EC2 instance in your particular AWS region, while EFS allows you to mount the file system across multiple regions and instances.

Finally, Amazon S3 is an object store good at storing vast numbers of backups or user files.

Exercises to improve my Java programming skills

When learning a new language, there are some nice problem sets you can use to learn the language better.

  • Project Euler has some nice problems with a strong mathematical twist.
  • Practice on Google Code Jam past problems, stick to the qualification rounds for the easier problems

Step-by-step debugging with IPython

Running from inside Emacs' IPython-shell and breakpoint set via pdb.set_trace() should work.

Checked with python-mode.el, M-x ipython RET etc.

Chrome DevTools Devices does not detect device when plugged in

I've worked with six different Android devices and multiple cables and I have to say that debugger works unstably. Sometimes it can see the device, sometimes it doesn't. Sometimes restarting Chrome helps. Here is a related bug https://bugs.chromium.org/p/chromium/issues/detail?id=788161, may be you can contribute with your evidence.

How to use OpenSSL to encrypt/decrypt files?

Encrypt:

openssl enc -in infile.txt -out encrypted.dat -e -aes256 -k symmetrickey

Decrypt:

openssl enc -in encrypted.dat -out outfile.txt -d -aes256 -k symmetrickey

For details, see the openssl(1) docs.

Explain the different tiers of 2 tier & 3 tier architecture?

Tiers are nothing but the separation of concerns and in general the presentation layer (the forms or pages that is visible to the user) is separated from the data tier (the class or file interact with the database). This separation is done in order to improve the maintainability, scalability, re-usability, flexibility and performance as well.

A good explanations with demo code of 3-tier and 4-tier architecture can be read at http://www.dotnetfunda.com/articles/article71.aspx

IIS7: A process serving application pool 'YYYYY' suffered a fatal communication error with the Windows Process Activation Service

When I had this problem, I installed 'Remote Tools for Visual Studio 2015' from MSDN. I attached my local VS to the server to debug.

I appreciate that some folks may not have the ability to either install on or access other servers, but I thought I'd throw it out there as an option.

How to stretch a table over multiple pages

You should \usepackage{longtable}.

How to load CSS Asynchronously

you can try to get it in a lot of ways :

1.Using media="bogus" and a <link> at the foot

<head>
    <!-- unimportant nonsense -->
    <link rel="stylesheet" href="style.css" media="bogus">
</head>
<body>
    <!-- other unimportant nonsense, such as content -->
    <link rel="stylesheet" href="style.css">
</body>

2.Inserting DOM in the old way

<script type="text/javascript">
(function(){
  var bsa = document.createElement('script');
     bsa.type = 'text/javascript';
     bsa.async = true;
     bsa.src = 'https://s3.buysellads.com/ac/bsa.js';
  (document.getElementsByTagName('head')[0]||document.getElementsByTagName('body')[0]).appendChild(bsa);
})();
</script>

3.if you can try plugins you could try loadCSS

<script>
  // include loadCSS here...
  function loadCSS( href, before, media ){ ... }
  // load a file
  loadCSS( "path/to/mystylesheet.css" );
</script>

Mouseover or hover vue.js

Please take a look at the vue-mouseover package if you are not satisfied how does this code look:

<div
    @mouseover="isMouseover = true"
    @mouseleave="isMouseover = false"
/>

vue-mouseover provides a v-mouseover directive that automaticaly updates the specified data context property when the cursor enters or leaves an HTML element the directive is attached to.

By default in the next example isMouseover property will be true when the cursor is over an HTML element and false otherwise:

<div v-mouseover="isMouseover" />

Also by default isMouseover will be initially assigned when v-mouseover is attached to the div element, so it will not remain unassigned before the first mouseenter/mouseleave event.

You can specify custom values via v-mouseover-value directive:

<div
    v-mouseover="isMouseover"
    v-mouseover-value="customMouseenterValue"/>

or

<div
    v-mouseover="isMouseover"
    v-mouseover-value="{
        mouseenter: customMouseenterValue,
        mouseleave: customMouseleaveValue
    }"
/>

Custom default values can be passed to the package via options object during setup.

one line if statement in php

Something like this?

($var > 2 ? echo "greater" : echo "smaller")

Adding event listeners to dynamically added elements using jQuery

You are dynamically generating those elements so any listener applied on page load wont be available. I have edited your fiddle with the correct solution. Basically jQuery holds the event for later binding by attaching it to the parent Element and propagating it downward to the correct dynamically created element.

$('#musics').on('change', '#want',function(e) {
    $(this).closest('.from-group').val(($('#want').is(':checked')) ? "yes" : "no");
    var ans=$(this).val();
    console.log(($('#want').is(':checked')));
});

http://jsfiddle.net/swoogie/1rkhn7ek/39/

How can I use an http proxy with node.js http.Client?

In case you need to the use basic authorisation for your proxy provider, just use the following:

var http = require("http");

var options = {
    host:       FarmerAdapter.PROXY_HOST,
    port:       FarmerAdapter.PROXY_PORT,
    path:       requestedUrl,
    headers:    {
        'Proxy-Authorization':  'Basic ' + new Buffer(FarmerAdapter.PROXY_USER + ':' + FarmerAdapter.PROXY_PASS).toString('base64')
    }
};

var request = http.request(options, function(response) {
    var chunks = [];
    response.on('data', function(chunk) {
        chunks.push(chunk);
    });
    response.on('end', function() {
        console.log('Response', Buffer.concat(chunks).toString());
    });
});

request.on('error', function(error) {
    console.log(error.message);
});

request.end();

CSS table column autowidth

The following will solve your problem:

td.last {
    width: 1px;
    white-space: nowrap;
}

Flexible, Class-Based Solution

And a more flexible solution is creating a .fitwidth class and applying that to any columns you want to ensure their contents are fit on one line:

td.fitwidth {
    width: 1px;
    white-space: nowrap;
}

And then in your HTML:

<tr>
    <td class="fitwidth">ID</td>
    <td>Description</td>
    <td class="fitwidth">Status</td>
    <td>Notes</td>
</tr>

Declaring a python function with an array parameters and passing an array argument to the function call?

What you have is on the right track.

def dosomething( thelist ):
    for element in thelist:
        print element

dosomething( ['1','2','3'] )
alist = ['red','green','blue']
dosomething( alist )  

Produces the output:

1
2
3
red
green
blue

A couple of things to note given your comment above: unlike in C-family languages, you often don't need to bother with tracking the index while iterating over a list, unless the index itself is important. If you really do need the index, though, you can use enumerate(list) to get index,element pairs, rather than doing the x in range(len(thelist)) dance.

Uninstall mongoDB from ubuntu

To uninstalling existing MongoDB packages. I think this link will helpful.

Display unescaped HTML in Vue.js

Vue by default ships with the v-html directive to show it, you bind it onto the element itself rather than using the normal moustache binding for string variables.

So for your specific example you would need:

<div id="logapp">    
    <table>
        <tbody>
            <tr v-repeat="logs">
                <td v-html="fail"></td>
                <td v-html="type"></td>
                <td v-html="description"></td>
                <td v-html="stamp"></td>
                <td v-html="id"></td>
            </tr>
        </tbody>
    </table>
</div>

Unable to connect to SQL Server instance remotely

I know this is almost 1.5 years old, but I hope I can help someone with what I found.

I had built both a console app and a UWP app and my console connnected fine, but not my UWP. After hours of banging my head against the desk - if it's a intranet server hosting the SQL database you must enable "Private Networks (Client & Server)". It's under Package.appxmanifest and the Capabilities tab.Screenshot

Export HTML page to PDF on user click using JavaScript

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

change it to:

$(function () {

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

    });  
});

and it will work.

How to change navbar/container width? Bootstrap 3

Container widths will drop down to 940 pixels for viewports less than 992 pixels. If you really don’t want containers larger than 940 pixels wide, then go to the Bootstrap customize page, and set @container-lg-desktop to either @container-desktop or hard-coded 940px.

Why doesn't Java offer operator overloading?

Groovy has operator overloading, and runs in the JVM. If you don't mind the performance hit (which gets smaller everyday). It's automatic based on method names. e.g., '+' calls the 'plus(argument)' method.

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

A bit late to the party, but Krux has created a script for this, called Postscribe. We were able to use this to get past this issue.

Object Library Not Registered When Adding Windows Common Controls 6.0

You Just execute the following commands in your command prompt,

For 32 bit machine,

cd C:\Windows\System32
regsvr32 mscomctl.ocx
regtlib msdatsrc.tlb

For 64 bit machine,

cd C:\Windows\SysWOW64
regsvr32 mscomctl.ocx
regtlib msdatsrc.tlb

Embedding Windows Media Player for all browsers

May I suggest the jQuery Media Plugin? Provides embed code for all kinds of video, not just WMV and does browser detection, keeping all that messy switch/case statements out of your templates.

Iterating through all nodes in XML file

You can use XmlDocument. Also some XPath can be useful.

Just a simple example

XmlDocument doc = new XmlDocument();
doc.Load("sample.xml");
XmlElement root = doc.DocumentElement;
XmlNodeList nodes = root.SelectNodes("some_node"); // You can also use XPath here
foreach (XmlNode node in nodes)
{
   // use node variable here for your beeds
}

Difference Between $.getJSON() and $.ajax() in jQuery

There is lots of confusion in some of the function of jquery like $.ajax, $.get, $.post, $.getScript, $.getJSON that what is the difference among them which is the best, which is the fast, which to use and when so below is the description of them to make them clear and to get rid of this type of confusions.

$.getJSON() function is a shorthand Ajax function (internally use $.get() with data type script), which is equivalent to below expression, Uses some limited criteria like Request type is GET and data Type is json.

Read More .. jquery-post-vs-get-vs-ajax

How to start and stop/pause setInterval?

add is a local variable not a global variable try this

_x000D_
_x000D_
var add;_x000D_
var input = document.getElementById("input");_x000D_
_x000D_
function start() {_x000D_
  add = setInterval("input.value++", 1000);_x000D_
}_x000D_
start();
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input type="number" id="input" />_x000D_
<input type="button" onclick="clearInterval(add)" value="stop" />_x000D_
<input type="button" onclick="start()" value="start" />
_x000D_
_x000D_
_x000D_

How can I split a string with a string delimiter?

.Split(new string[] { "is Marco and" }, StringSplitOptions.None)

Consider the spaces surronding "is Marco and". Do you want to include the spaces in your result, or do you want them removed? It's quite possible that you want to use " is Marco and " as separator...

How to prevent line breaks in list items using CSS

You could add this little snippet of code to add a nice "…" to the ending of the line if the content is to large to fit on one line:

li {
  overflow: hidden; 
  text-overflow: ellipsis;
  white-space: nowrap;
}

How to copy file from one location to another location?

You can use this (or any variant):

Files.copy(src, dst, StandardCopyOption.REPLACE_EXISTING);

Also, I'd recommend using File.separator or / instead of \\ to make it compliant across multiple OS, question/answer on this available here.

Since you're not sure how to temporarily store files, take a look at ArrayList:

List<File> files = new ArrayList();
files.add(foundFile);

To move a List of files into a single directory:

List<File> files = ...;
String path = "C:/destination/";
for(File file : files) {
    Files.copy(file.toPath(),
        (new File(path + file.getName())).toPath(),
        StandardCopyOption.REPLACE_EXISTING);
}

One-liner if statements, how to convert this if-else-statement

All you'd need in your case is:

return expression;

The reason why is that the expression itself evaluates to a boolean value of true or false, so it's redundant to have an if block (or even a ?: operator).

How to see my Eclipse version?

Help -> About Eclipse Platform

For Eclipse Mars - you can check Eclipse -> About Eclipse or Help -> Installation Details, then you should see the version:

enter image description here

Comparing two vectors in an if statement

I'd probably use all.equal and which to get the information you want. It's not recommended to use all.equal in an if...else block for some reason, so we wrap it in isTRUE(). See ?all.equal for more:

foo <- function(A,B){
  if (!isTRUE(all.equal(A,B))){
    mismatches <- paste(which(A != B), collapse = ",")
    stop("error the A and B does not match at the following columns: ", mismatches )
  } else {
    message("Yahtzee!")
  }
}

And in use:

> foo(A,A)
Yahtzee!
> foo(A,B)
Yahtzee!
> foo(A,C)
Error in foo(A, C) : 
  error the A and B does not match at the following columns: 2,4

Remove last commit from remote git repository

If nobody has pulled it, you can probably do something like

git push remote +branch^1:remotebranch

which will forcibly update the remote branch to the last but one commit of your branch.

What is a typedef enum in Objective-C?

enum is used to assign value to enum elements which cannot be done in struct. So everytime instead of accessing the complete variable we can do it by the value we assign to the variables in enum. By default it starts with 0 assignment but we can assign it any value and the next variable in enum will be assigned a value the previous value +1.

What can be the reasons of connection refused errors?

From the standpoint of a Checkpoint firewall, you will see a message from the firewall if you actually choose Reject as an Action thereby exposing to a propective attacker the presence of a firewall in front of the server. The firewall will silently drop all connections that doesn't match the policy. Connection refused almost always comes from the server

What is the correct way to check for string equality in JavaScript?

Considering that both strings may be very large, there are 2 main approaches bitwise search and localeCompare

I recommed this function

function compareLargeStrings(a,b){
    if (a.length !== b.length) {
         return false;
    }
    return a.localeCompare(b) === 0;
}

Connect to docker container as user other than root

The only way I am able to make it work is by:

docker run -it -e USER=$USER -v /etc/passwd:/etc/passwd -v `pwd`:/siem mono bash
su - magnus

So I have to both specify $USER environment variable as well a point the /etc/passwd file. In this way, I can compile in /siem folder and retain ownership of files there not as root.

Format in kotlin string templates

Kotlin's String class has a format function now, which internally uses Java's String.format method:

/**
 * Uses this string as a format string and returns a string obtained by substituting the specified arguments,
 * using the default locale.
 */
@kotlin.internal.InlineOnly
public inline fun String.Companion.format(format: String, vararg args: Any?): String = java.lang.String.format(format, *args)

Usage

val pi = 3.14159265358979323
val formatted = String.format("%.2f", pi) ;
println(formatted)
>>3.14

How to compile and run C files from within Notepad++ using NppExec plugin?

I've made a single powerfull script that will:

-Compile and run multi language code like C, C++, Java, Python and C#.
-Delete the old executable before compiling code.
-Only run the code if it's compiled successfully.

I've also made a very noob friendly tutorial Transform Notepad++ to Powerful Multi Languages IDE which contains some additional scripts like to only run or Compile the code, run code inside CMD etc.

npp_console 1               //open console
NPP_CONSOLE -               //disable output of commands
npe_console m-              //disable unnecessary output
con_colour bg= 191919 fg= F5F5F5    //set console colors
npp_save                //save the file
cd $(CURRENT_DIRECTORY)         //follow current directory
NPP_CONSOLE +               //enable output
IF $(EXT_PART)==.c GOTO C       //if .c file goto C label
IF $(EXT_PART)==.cpp GOTO CPP       //if .cpp file goto CPP label
IF $(EXT_PART)==.java GOTO JAVA     //if .java file goto JAVA label
IF $(EXT_PART)==.cs GOTO C#     //if .cs file goto C# label
IF $(EXT_PART)==.py GOTO PYTHON     //if .py file goto PYTHON label
echo FILE SAVED
GOTO EXITSCRIPT             // else treat it as a text file and goto EXITSCRIPT
//C label
:C                                                                  
cmd /C if exist "$(NAME_PART).exe" cmd /c del "$(NAME_PART).exe"//delete existing executable file if exists
gcc "$(FILE_NAME)" -o $(NAME_PART)              //compile file
IF $(EXITCODE) != 0 GOTO EXITSCRIPT             //if any compilation error then abort
echo C CODE COMPILED SUCCESSFULLY:              //print message on console
$(NAME_PART)                                            //run file in cmd, set color to green and pause cmd after output
GOTO EXITSCRIPT                         //finally exits

:CPP
cmd /C if exist "$(NAME_PART).exe" cmd /c del "$(NAME_PART).exe"
g++ "$(FILE_NAME)" -o $(NAME_PART)
IF $(EXITCODE) != 0 GOTO EXITSCRIPT
echo C++ CODE COMPILED SUCCESSFULLY:
$(NAME_PART)
GOTO EXITSCRIPT

:JAVA
cmd /C if exist "$(NAME_PART).class" cmd /c del "$(NAME_PART).class"
javac $(FILE_NAME) -Xlint
IF $(EXITCODE) != 0 GOTO EXITSCRIPT
echo JAVA CODE COMPILED SUCCESSFULLY:
java $(NAME_PART)
GOTO EXITSCRIPT

:C#
cmd /C if exist "$(NAME_PART).exe" cmd /c del "$(NAME_PART).exe"
csc $(FILE_NAME)
IF $(EXITCODE) != 0 GOTO EXITSCRIPT
echo C# CODE COMPILED SUCCESSFULLY:
$(NAME_PART)
GOTO EXITSCRIPT

:PYTHON
echo RUNNING PYTHON SCRIPT IN CMD:              //python is a script so no need to compile
python $(NAME_PART).py
GOTO EXITSCRIPT

:EXITSCRIPT
// that's all, folks!

Simple dynamic breadcrumb

A better one using explode() function is as follows...

Don't forget to replace your URL variable in the hyperlink href.

<?php 
    if($url != ''){
        $b = '';
        $links = explode('/',rtrim($url,'/'));
        foreach($links as $l){
            $b .= $l;
            if($url == $b){
                echo $l;
            }else{
                echo "<a href='URL?url=".$b."'>".$l."/</a>";
            }
            $b .= '/';
         }
     }
?>

Angular 2 TypeScript how to find element in Array

Assume I have below array:

Skins[
    {Id: 1, Name: "oily skin"}, 
    {Id: 2, Name: "dry skin"}
];

If we want to get item with Id = 1 and Name = "oily skin", We'll try as below:

var skinName = skins.find(x=>x.Id == "1").Name;

The result will return the skinName is "Oily skin".

enter image description here

Remove all special characters except space from a string using JavaScript

Whose special characters you want to remove from a string, prepare a list of them and then user javascript replace function to remove all special characters.

var str = 'abc'de#;:sfjkewr47239847duifyh';
alert(str.replace("'","").replace("#","").replace(";","").replace(":",""));

or you can run loop for a whole string and compare single single character with the ASCII code and regenerate a new string.

How do I replace text in a selection?

As @JOPLOmacedo stated, ctrl + F is what you need, but if you can't use that shortcut you can check in menu:

  • Find -> Find..

    and there you have it.
    You can also set a custom keybind for Find going in:

  • Preferences -> Key Bindings - User

    As your request for the selection only request, there is a button right next to the search field where you can opt-in for "in selection".

  • Associative arrays in Shell scripts

    For Bash 3, there is a particular case that has a nice and simple solution:

    If you don't want to handle a lot of variables, or keys are simply invalid variable identifiers, and your array is guaranteed to have less than 256 items, you can abuse function return values. This solution does not require any subshell as the value is readily available as a variable, nor any iteration so that performance screams. Also it's very readable, almost like the Bash 4 version.

    Here's the most basic version:

    hash_index() {
        case $1 in
            'foo') return 0;;
            'bar') return 1;;
            'baz') return 2;;
        esac
    }
    
    hash_vals=("foo_val"
               "bar_val"
               "baz_val");
    
    hash_index "foo"
    echo ${hash_vals[$?]}
    

    Remember, use single quotes in case, else it's subject to globbing. Really useful for static/frozen hashes from the start, but one could write an index generator from a hash_keys=() array.

    Watch out, it defaults to the first one, so you may want to set aside zeroth element:

    hash_index() {
        case $1 in
            'foo') return 1;;
            'bar') return 2;;
            'baz') return 3;;
        esac
    }
    
    hash_vals=("",           # sort of like returning null/nil for a non existent key
               "foo_val"
               "bar_val"
               "baz_val");
    
    hash_index "foo" || echo ${hash_vals[$?]}  # It can't get more readable than this
    

    Caveat: the length is now incorrect.

    Alternatively, if you want to keep zero-based indexing, you can reserve another index value and guard against a non-existent key, but it's less readable:

    hash_index() {
        case $1 in
            'foo') return 0;;
            'bar') return 1;;
            'baz') return 2;;
            *)   return 255;;
        esac
    }
    
    hash_vals=("foo_val"
               "bar_val"
               "baz_val");
    
    hash_index "foo"
    [[ $? -ne 255 ]] && echo ${hash_vals[$?]}
    

    Or, to keep the length correct, offset index by one:

    hash_index() {
        case $1 in
            'foo') return 1;;
            'bar') return 2;;
            'baz') return 3;;
        esac
    }
    
    hash_vals=("foo_val"
               "bar_val"
               "baz_val");
    
    hash_index "foo" || echo ${hash_vals[$(($? - 1))]}
    

    Comparing two columns, and returning a specific adjacent cell in Excel

    I would advise you to swap B and C columns for the reason that I will explain. Then in D2 type: =VLOOKUP(A2, B2:C4, 2, FALSE)

    Finally, copy the formula for the remaining cells.

    Explanation: VLOOKUP will first find the value of A2 in the range B2 to C4 (second argument). NOTE: VLOOKUP always searches the first column in this range. This is the reason why you have to swap the two columns before doing anything.

    Once the exact match is found, it will return the value in the adjacent cell (third argument).

    This means that, if you put 1 as the third argument, the function will return the value in the first column of the range (which will be the same value you were looking for). If you put 2, it will return the value from the second column in the range (the value in the adjacent cell-RIGHT SIDE of the found value).

    FALSE indicates that you are finding the exact match. If you put TRUE, you will be searching for the approximate match.

    ArrayList initialization equivalent to array initialization

    How about this one.

    ArrayList<String> names = new ArrayList<String>();
    Collections.addAll(names, "Ryan", "Julie", "Bob");
    

    How to get past the login page with Wget?

    You can log in via browser and copy the needed headers afterwards:

    screenshot

    Use "Copy as cURL" in the Network tab of browser developer tools and replace curl's flag -H with wget's --header (and also --data with --post-data if needed).

    How to restrict the selectable date ranges in Bootstrap Datepicker?

    Another possibility is to use the options with data attributes, like this(minimum date 1 week before):

    <input class='datepicker' data-date-start-date="-1w">
    

    More info: http://bootstrap-datepicker.readthedocs.io/en/latest/options.html

    Using `date` command to get previous, current and next month

    The problem is that date takes your request quite literally and tries to use a date of 31st September (being 31st October minus one month) and then because that doesn't exist it moves to the next day which does. The date documentation (from info date) has the following advice:

    The fuzz in units can cause problems with relative items. For example, `2003-07-31 -1 month' might evaluate to 2003-07-01, because 2003-06-31 is an invalid date. To determine the previous month more reliably, you can ask for the month before the 15th of the current month. For example:

     $ date -R
     Thu, 31 Jul 2003 13:02:39 -0700
     $ date --date='-1 month' +'Last month was %B?'
     Last month was July?
     $ date --date="$(date +%Y-%m-15) -1 month" +'Last month was %B!'
     Last month was June!
    

    Fixing Xcode 9 issue: "iPhone is busy: Preparing debugger support for iPhone"

    just unpaired your iPhone and reconnected it and make connect via network this not use cable any more.

    jQuery map vs. each

    var intArray = [1, 2, 3, 4, 5];
    //lets use each function
    $.each(intArray, function(index, element) {
      if (element === 3) {
        return false;
      }
      console.log(element); // prints only 1,2. Breaks the loop as soon as it encountered number 3
    });
    
    //lets use map function
    $.map(intArray, function(element, index) {
      if (element === 3) {
        return false;
      }
      console.log(element); // prints only 1,2,4,5. skip the number 3.
    });
    

    How can I access an internal class from an external assembly?

    I would like to argue one point - that you cannot augment the original assembly - using Mono.Cecil you can inject [InternalsVisibleTo(...)] to the 3pty assembly. Note there might be legal implications - you're messing with 3pty assembly and technical implications - if the assembly has strong name you either need to strip it or re-sign it with different key.

     Install-Package Mono.Cecil
    

    And the code like:

    static readonly string[] s_toInject = {
      // alternatively "MyAssembly, PublicKey=0024000004800000... etc."
      "MyAssembly"
    };
    
    static void Main(string[] args) {
      const string THIRD_PARTY_ASSEMBLY_PATH = @"c:\folder\ThirdPartyAssembly.dll";
    
       var parameters = new ReaderParameters();
       var asm = ModuleDefinition.ReadModule(INPUT_PATH, parameters);
       foreach (var toInject in s_toInject) {
         var ca = new CustomAttribute(
           asm.Import(typeof(InternalsVisibleToAttribute).GetConstructor(new[] {
                          typeof(string)})));
         ca.ConstructorArguments.Add(new CustomAttributeArgument(asm.TypeSystem.String, toInject));
         asm.Assembly.CustomAttributes.Add(ca);
       }
       asm.Write(@"c:\folder-modified\ThirdPartyAssembly.dll");
       // note if the assembly is strongly-signed you need to resign it like
       // asm.Write(@"c:\folder-modified\ThirdPartyAssembly.dll", new WriterParameters {
       //   StrongNameKeyPair = new StrongNameKeyPair(File.ReadAllBytes(@"c:\MyKey.snk"))
       // });
    }
    

    git: 'credential-cache' is not a git command

    A similar error is 'credential-wincred' is not a git command

    The accepted and popular answers are now out of date...

    wincred is for the project git-credential-winstore which is no longer maintained.

    It was replaced by Git-Credential-Manager-for-Windows maintained by Microsoft open source.

    Download the release as zip file from link above and extract contents to

    \cygwin\usr\libexec\git-core
    

    (or \cygwin64\usr\libexec\git-core as it may be)

    Then enable it, (by setting the global .gitconfig) - execute:

    git config --global credential.helper manager
    

    How to use

    No further config is needed.

    It works [automatically] when credentials are needed.

    For example, when pushing to Azure DevOps, it opens a window and initializes an oauth2 flow to get your token.

    ref:

    How can I tell where mongoDB is storing data? (its not in the default /data/db!)

    mongod defaults the database location to /data/db/.

    If you run ps -xa | grep mongod and you don't see a --dbpath which explicitly tells mongod to look at that parameter for the db location and you don't have a dbpath in your mongodb.conf, then the default location will be: /data/db/ and you should look there.

    How do I write the 'cd' command in a makefile?

    Like this:

    target:
        $(shell cd ....); \
        # ... commands execution in this directory
        # ... no need to go back (using "cd -" or so)
        # ... next target will be automatically in prev dir
    

    Good luck!

    Get the last inserted row ID (with SQL statement)

    If your SQL Server table has a column of type INT IDENTITY (or BIGINT IDENTITY), then you can get the latest inserted value using:

    INSERT INTO dbo.YourTable(columns....)
       VALUES(..........)
    
    SELECT SCOPE_IDENTITY()
    

    This works as long as you haven't inserted another row - it just returns the last IDENTITY value handed out in this scope here.

    There are at least two more options - @@IDENTITY and IDENT_CURRENT - read more about how they works and in what way they're different (and might give you unexpected results) in this excellent blog post by Pinal Dave here.

    android: how to use getApplication and getApplicationContext from non activity / service class

    Casting a Context object to an Activity object compiles fine.

    Try this:

    ((Activity) mContext).getApplication(...)

    What are the recommendations for html <base> tag?

    I have found a way to use <base> and anchor based links. You can use JavaScript to keep links like #contact working as they have to. I used it in some parallax pages and it works for me.

    <base href="http://www.mywebsite.com/templates/"><!--[if lte IE 6]></base><![endif]-->
    
    ...content...
    
    <script>
    var link='',pathname = window.location.href;
    $('a').each(function(){
        link = $(this).attr('href');
        if(link[0]=="#"){
            $(this).attr('href', pathname + link);
        }
    });
    </script>
    

    You should use at the end of the page

    How to suppress binary file matching results in grep

    There are three options, that you can use. -I is to exclude binary files in grep. Other are for line numbers and file names.

    grep -I -n -H 
    
    
    -I -- process a binary file as if it did not contain matching data; 
    -n -- prefix each line of output with the 1-based line number within its input file
    -H -- print the file name for each match
    

    So this might be a way to run grep:

    grep -InH your-word *
    

    Unknown SSL protocol error in connection

    According to bitbucket knowledgebase it may also be caused by the owner of the repository being over the plan limit.

    If you look further down the page it seems to also be possible to trig this error by using a too old git version (1.7 is needed at the moment).

    how to bind datatable to datagridview in c#

    Try this:

        ServersTable.Columns.Clear();
        ServersTable.DataSource = SBind;
    

    If you don't want to clear all the existing columns, you have to set DataPropertyName for each existing column like this:

    for (int i = 0; i < ServersTable.ColumnCount; ++i) {
      DTable.Columns.Add(new DataColumn(ServersTable.Columns[i].Name));
      ServersTable.Columns[i].DataPropertyName = ServersTable.Columns[i].Name;
    }
    

    How to run a single RSpec test?

    I use this guard gem to auto-run my test. It execute test after create or update operations on test file.

    https://github.com/guard/guard-test

    or usually you can run using following command

    rspec spec/controllers/groups_controller_spec.rb

    How do I test if a string is empty in Objective-C?

    Marc's answer is correct. But I'll take this opportunity to include a pointer to Wil Shipley's generalized isEmpty, which he shared on his blog:

    static inline BOOL IsEmpty(id thing) {
    return thing == nil
    || ([thing respondsToSelector:@selector(length)]
    && [(NSData *)thing length] == 0)
    || ([thing respondsToSelector:@selector(count)]
    && [(NSArray *)thing count] == 0);
    }
    

    Return a value of '1' a referenced cell is empty

    Beware: There are also cells which are seemingly blank, but are not truly empty but containg "" or something that is called NULL in other languages. As an example, when a formula results in "" or such result is copied to a cell, the formula

    ISBLANK(A1) 
    

    returns FALSE. That means the cell is not truly empty.

    The way to go there is to use enter code here

    COUNTBLANK(A1)
    

    Which finds both truly empty cells and those containing "". See also this very good answer here

    IntelliJ show JavaDocs tooltip on mouse over

    The answer is CTRL + P (NOT CTRL + Q)

    Someone else posted this answer on JetBrains forum: The idea is a different IDE. Try to discover its features and try to make the best of it, rather than trying to emulate whatever you used before. For the most part, Idea has very high usability (much better than Eclipse IMHO) and is streamlined for supporting code editing as best as possible (rather than relying on wizards too much for example).

    • Javadoc: Ctrl-Q
    • A quick view of the implementation: Ctrl-Shift-I
    • Show context: Alt-Q
    • Show parameters (in a method call): Ctrl-P
    • Show error description. Ctrl-F1

    ... plus many more shortcuts to navigate in code and different idea views.

    I think it rather nice that you can see just the specific bit of information you are interested in with a simple keystroke. Have a look at the menus which will also show the possibly modified shortcuts for your keymap.

    0 Avatar Jens Voß Created June 12, 2008, 09:26 And, elsandros, in addition to what Stephen writes: Since you seem to be interested in IDEA's keyboard shortcuts, I highly recommend the "Key Promoter" plugin which helps you memorize the relevant shortcuts quickly.

    Also very useful is the "Goto Action" feature, invoked by Ctrl-Shift-A. In the popup, you can enter a keyword (e.g. "Javadoc"), and the IDE tells you the available actions matching your search, along with keyboard shortcuts and the containing action groups (which often also give you a clue about how to navigate to the action using the menu).

    Rails: How to list database tables/objects using the Rails console?

    You are probably seeking:

    ActiveRecord::Base.connection.tables
    

    and

    ActiveRecord::Base.connection.columns('projects').map(&:name)
    

    You should probably wrap them in shorter syntax inside your .irbrc.

    How to overcome TypeError: unhashable type: 'list'

    You're trying to use k (which is a list) as a key for d. Lists are mutable and can't be used as dict keys.

    Also, you're never initializing the lists in the dictionary, because of this line:

    if k not in d == False:
    

    Which should be:

    if k not in d == True:
    

    Which should actually be:

    if k not in d:
    

    html button to send email

     <form action="mailto:[email protected]" method="post"               enctype="text/plain">
     Name:<br>
    <input type="text" name="name"><br>
     E-mail:<br>
    <input type="text" name="mail"><br>
    Comment:<br>
    <input type="text" name="comment" size="50"><br><br>
    <input type="submit" value="Send">
    <input type="reset" value="Reset">
    

    how to check the version of jar file?

    For Linux, try following:

    find . -name "YOUR_JAR_FILE.jar" -exec zipgrep "Implementation-Version:" '{}' \;|awk -F ': ' '{print $2}'

    What linux shell command returns a part of a string?

    From the bash manpage:

    ${parameter:offset}
    ${parameter:offset:length}
            Substring  Expansion.   Expands  to  up  to length characters of
            parameter starting at the character  specified  by  offset.
    [...]
    

    Or, if you are not sure of having bash, consider using cut.

    Named tuple and default values for optional keyword arguments

    Here is a more compact version inspired by justinfay's answer:

    from collections import namedtuple
    from functools import partial
    
    Node = namedtuple('Node', ('val left right'))
    Node.__new__ = partial(Node.__new__, left=None, right=None)
    

    How can I escape a single quote?

    use javascript inbuild functions escape and unescape

    for example

    var escapedData = escape("hel'lo");   
    output = "%27hel%27lo%27" which can be used in the attribute.
    
    again to read the value from the attr
    
    var unescapedData = unescape("%27hel%27lo%27")
    output = "'hel'lo'"
    

    This will be helpful if you have huge json stringify data to be used in the attribute

    How can I make a .NET Windows Forms application that only runs in the System Tray?

    As mat1t says - you need to add a NotifyIcon to your application and then use something like the following code to set the tooltip and context menu:

    this.notifyIcon.Text = "This is the tooltip";
    this.notifyIcon.ContextMenu = new ContextMenu();
    this.notifyIcon.ContextMenu.MenuItems.Add(new MenuItem("Option 1", new EventHandler(handler_method)));
    

    This code shows the icon in the system tray only:

    this.notifyIcon.Visible = true;  // Shows the notify icon in the system tray
    

    The following will be needed if you have a form (for whatever reason):

    this.ShowInTaskbar = false;  // Removes the application from the taskbar
    Hide();
    

    The right click to get the context menu is handled automatically, but if you want to do some action on a left click you'll need to add a Click handler:

        private void notifyIcon_Click(object sender, EventArgs e)
        {
            var eventArgs = e as MouseEventArgs;
            switch (eventArgs.Button)
            {
                // Left click to reactivate
                case MouseButtons.Left:
                    // Do your stuff
                    break;
            }
        }
    

    This version of Android Studio cannot open this project, please retry with Android Studio 3.4 or newer

    In IntelliJ IDEA this is an open bug: https://youtrack.jetbrains.com/issue/IDEA-252823

    As a workaround, you can change the build tools version as other people advise.

    My project was failing with this dependency:

    com.android.tools.build:gradle:7.0.0-alpha03
    

    Now it's working with this:

    com.android.tools.build:gradle:4.0.2
    

    As a side note, you should change that dependency in build.gradle in some projects or in dependencies.kt in newer projects.

    That was the most updated version that worked.

    How to target the href to div

    havent tried but this might help

    $(document).ready(function(){
    r=0;s=-1;
    $(a).click(function(){
    v=$(this).html();
    $(a).each(function(){
    if($(this).html()==v)
    return;
    else ++r;
    $(div).each(function(){
    if(s==r)
    $(div).appendTo($(".target")); 
    ++S;
    });
    
    });
    
    });
    

    });

    OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection

    Well, I'm late.


    In your image, the paper is white, while the background is colored. So, it's better to detect the paper is Saturation(???) channel in HSV color space. Take refer to wiki HSL_and_HSV first. Then I'll copy most idea from my answer in this Detect Colored Segment in an image.


    Main steps:

    1. Read into BGR
    2. Convert the image from bgr to hsv space
    3. Threshold the S channel
    4. Then find the max external contour(or do Canny, or HoughLines as you like, I choose findContours), approx to get the corners.

    This is my result:

    enter image description here


    The Python code(Python 3.5 + OpenCV 3.3):

    #!/usr/bin/python3
    # 2017.12.20 10:47:28 CST
    # 2017.12.20 11:29:30 CST
    
    import cv2
    import numpy as np
    
    ##(1) read into  bgr-space
    img = cv2.imread("test2.jpg")
    
    ##(2) convert to hsv-space, then split the channels
    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    h,s,v = cv2.split(hsv)
    
    ##(3) threshold the S channel using adaptive method(`THRESH_OTSU`) or fixed thresh
    th, threshed = cv2.threshold(s, 50, 255, cv2.THRESH_BINARY_INV)
    
    ##(4) find all the external contours on the threshed S
    #_, cnts, _ = cv2.findContours(threshed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    cnts = cv2.findContours(threshed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]
    
    canvas  = img.copy()
    #cv2.drawContours(canvas, cnts, -1, (0,255,0), 1)
    
    ## sort and choose the largest contour
    cnts = sorted(cnts, key = cv2.contourArea)
    cnt = cnts[-1]
    
    ## approx the contour, so the get the corner points
    arclen = cv2.arcLength(cnt, True)
    approx = cv2.approxPolyDP(cnt, 0.02* arclen, True)
    cv2.drawContours(canvas, [cnt], -1, (255,0,0), 1, cv2.LINE_AA)
    cv2.drawContours(canvas, [approx], -1, (0, 0, 255), 1, cv2.LINE_AA)
    
    ## Ok, you can see the result as tag(6)
    cv2.imwrite("detected.png", canvas)
    

    Related answers:

    1. How to detect colored patches in an image using OpenCV?
    2. Edge detection on colored background using OpenCV
    3. OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection
    4. How to use `cv2.findContours` in different OpenCV versions?

    How to do a "Save As" in vba code, saving my current Excel workbook with datestamp?

    It could be that your default format doesn't match the file extension. You should specify the file format along with the filename, making sure the format matches the extension:

    With someWorkbook
    .SaveAs "C:\someDirector\Awesome.xlsm", fileformat:=xlOpenXMLWorkbookMacroEnabled
    End With
    

    OTOH, I don't see an extension on your .SaveAs filename. Maybe you need to supply one when doing this programmatically. That makes sense--not having to supply an extension from the GUI interface is convenient, but we programmers are expected to write unambiguous code. I suggest adding the extension and the matching format. See this msdn page for a list of file formats. To be honest, I don't recognize a lot o the descripions.

    xlExcel8 = 56 is the .xls format

    xlExcel12 = 50 is the .xlsb format

    xlOpenXMLWorkbook = 51 is the .xlsx format

    xlOpenXMLWorkbookMacroEnabled = 52 is the .xlsm format

    xlWorkbookDefault is also listed with a value of 51, which puzzles me since I thought the default format could be changed.

    Keyboard shortcut to "untab" (move a block of code to the left) in eclipse / aptana?

    Shift-tab doesn't seem to work on multi-lines in Aptana. It also doesn't work on single lines with a single preceding space. Any workarounds? I use shift-tab (outdent) to fix badly formatted code all the time.

    I miss NetBeans ...

    UPDATE: it works on multi-newlines, if the multi-lines have the same level of indentation. It should just continue outdenting the other lines that haven't reached the beginning of the new line yet. Is there an option to change this I wonder?

    Spring: How to inject a value to static field?

    This is my sample code for load static variable

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Component;
    
    @Component
    public class OnelinkConfig {
        public static int MODULE_CODE;
        public static int DEFAULT_PAGE;
        public static int DEFAULT_SIZE;
    
        @Autowired
        public void loadOnelinkConfig(@Value("${onelink.config.exception.module.code}") int code,
                @Value("${onelink.config.default.page}") int page, @Value("${onelink.config.default.size}") int size) {
            MODULE_CODE = code;
            DEFAULT_PAGE = page;
            DEFAULT_SIZE = size;
        }
    }
    

    Xcode doesn't see my iOS device but iTunes does

    After 20 minutes of debugging, I realized I had to hover over the up button () at the top of the Devices picker in the top left hand corner, to the right of the run app button

    Generating random number between 1 and 10 in Bash Shell Script

    You can also use /dev/urandom:

    grep -m1 -ao '[0-9]' /dev/urandom | sed s/0/10/ | head -n1
    

    Do you need to dispose of objects and set them to null?

    Objects never go out of scope in C# as they do in C++. They are dealt with by the Garbage Collector automatically when they are not used anymore. This is a more complicated approach than C++ where the scope of a variable is entirely deterministic. CLR garbage collector actively goes through all objects that have been created and works out if they are being used.

    An object can go "out of scope" in one function but if its value is returned, then GC would look at whether or not the calling function holds onto the return value.

    Setting object references to null is unnecessary as garbage collection works by working out which objects are being referenced by other objects.

    In practice, you don't have to worry about destruction, it just works and it's great :)

    Dispose must be called on all objects that implement IDisposable when you are finished working with them. Normally you would use a using block with those objects like so:

    using (var ms = new MemoryStream()) {
      //...
    }
    

    EDIT On variable scope. Craig has asked whether the variable scope has any effect on the object lifetime. To properly explain that aspect of CLR, I'll need to explain a few concepts from C++ and C#.

    Actual variable scope

    In both languages the variable can only be used in the same scope as it was defined - class, function or a statement block enclosed by braces. The subtle difference, however, is that in C#, variables cannot be redefined in a nested block.

    In C++, this is perfectly legal:

    int iVal = 8;
    //iVal == 8
    if (iVal == 8){
        int iVal = 5;
        //iVal == 5
    }
    //iVal == 8
    

    In C#, however you get a a compiler error:

    int iVal = 8;
    if(iVal == 8) {
        int iVal = 5; //error CS0136: A local variable named 'iVal' cannot be declared in this scope because it would give a different meaning to 'iVal', which is already used in a 'parent or current' scope to denote something else
    }
    

    This makes sense if you look at generated MSIL - all the variables used by the function are defined at the start of the function. Take a look at this function:

    public static void Scope() {
        int iVal = 8;
        if(iVal == 8) {
            int iVal2 = 5;
        }
    }
    

    Below is the generated IL. Note that iVal2, which is defined inside the if block is actually defined at function level. Effectively this means that C# only has class and function level scope as far as variable lifetime is concerned.

    .method public hidebysig static void  Scope() cil managed
    {
      // Code size       19 (0x13)
      .maxstack  2
      .locals init ([0] int32 iVal,
               [1] int32 iVal2,
               [2] bool CS$4$0000)
    
    //Function IL - omitted
    } // end of method Test2::Scope
    

    C++ scope and object lifetime

    Whenever a C++ variable, allocated on the stack, goes out of scope it gets destructed. Remember that in C++ you can create objects on the stack or on the heap. When you create them on the stack, once execution leaves the scope, they get popped off the stack and gets destroyed.

    if (true) {
      MyClass stackObj; //created on the stack
      MyClass heapObj = new MyClass(); //created on the heap
      obj.doSomething();
    } //<-- stackObj is destroyed
    //heapObj still lives
    

    When C++ objects are created on the heap, they must be explicitly destroyed, otherwise it is a memory leak. No such problem with stack variables though.

    C# Object Lifetime

    In CLR, objects (i.e. reference types) are always created on the managed heap. This is further reinforced by object creation syntax. Consider this code snippet.

    MyClass stackObj;
    

    In C++ this would create an instance on MyClass on the stack and call its default constructor. In C# it would create a reference to class MyClass that doesn't point to anything. The only way to create an instance of a class is by using new operator:

    MyClass stackObj = new MyClass();
    

    In a way, C# objects are a lot like objects that are created using new syntax in C++ - they are created on the heap but unlike C++ objects, they are managed by the runtime, so you don't have to worry about destructing them.

    Since the objects are always on the heap the fact that object references (i.e. pointers) go out of scope becomes moot. There are more factors involved in determining if an object is to be collected than simply presence of references to the object.

    C# Object references

    Jon Skeet compared object references in Java to pieces of string that are attached to the balloon, which is the object. Same analogy applies to C# object references. They simply point to a location of the heap that contains the object. Thus, setting it to null has no immediate effect on the object lifetime, the balloon continues to exist, until the GC "pops" it.

    Continuing down the balloon analogy, it would seem logical that once the balloon has no strings attached to it, it can be destroyed. In fact this is exactly how reference counted objects work in non-managed languages. Except this approach doesn't work for circular references very well. Imagine two balloons that are attached together by a string but neither balloon has a string to anything else. Under simple ref counting rules, they both continue to exist, even though the whole balloon group is "orphaned".

    .NET objects are a lot like helium balloons under a roof. When the roof opens (GC runs) - the unused balloons float away, even though there might be groups of balloons that are tethered together.

    .NET GC uses a combination of generational GC and mark and sweep. Generational approach involves the runtime favouring to inspect objects that have been allocated most recently, as they are more likely to be unused and mark and sweep involves runtime going through the whole object graph and working out if there are object groups that are unused. This adequately deals with circular dependency problem.

    Also, .NET GC runs on another thread(so called finalizer thread) as it has quite a bit to do and doing that on the main thread would interrupt your program.

    How to read from a text file using VBScript?

    Use first the method OpenTextFile, and then...

    either read the file at once with the method ReadAll:

    Set file = fso.OpenTextFile("C:\test.txt", 1)
    content = file.ReadAll
    

    or line by line with the method ReadLine:

    Set dict = CreateObject("Scripting.Dictionary")
    Set file = fso.OpenTextFile ("c:\test.txt", 1)
    row = 0
    Do Until file.AtEndOfStream
      line = file.Readline
      dict.Add row, line
      row = row + 1
    Loop
    
    file.Close
    
    'Loop over it
    For Each line in dict.Items
      WScript.Echo line
    Next
    

    How to load an external webpage into a div of a html page

    Using simple html,

     <div> 
        <object type="text/html" data="http://validator.w3.org/" width="800px" height="600px" style="overflow:auto;border:5px ridge blue">
        </object>
     </div>
    

    Or jquery,

    <script>
            $("#mydiv")
                .html('<object data="http://your-website-domain"/>');
    </script>
    

    JSFIDDLE DEMO

    HTML tag <a> want to add both href and onclick working

    No jQuery needed.

    Some people say using onclick is bad practice...

    This example uses pure browser javascript. By default, it appears that the click handler will evaluate before the navigation, so you can cancel the navigation and do your own if you wish.

    <a id="myButton" href="http://google.com">Click me!</a>
    <script>
        window.addEventListener("load", () => {
            document.querySelector("#myButton").addEventListener("click", e => {
                alert("Clicked!");
                // Can also cancel the event and manually navigate
                // e.preventDefault();
                // window.location = e.target.href;
            });
        });
    </script>
    

    Why should I use a pointer rather than the object itself?

    There are many benefits of using pointers to object -

    1. Efficiency (as you already pointed out). Passing objects to functions mean creating new copies of object.
    2. Working with objects from third party libraries. If your object belongs to a third party code and the authors intend the usage of their objects through pointers only (no copy constructors etc) the only way you can pass around this object is using pointers. Passing by value may cause issues. (Deep copy / shallow copy issues).
    3. if the object owns a resource and you want that the ownership should not be sahred with other objects.

    Codeigniter $this->db->order_by(' ','desc') result is not complete

    Put from before where, and order_by on last:

    $this->db->select('*');
    $this->db->from('courses');
    $this->db->where('tennant_id',$tennant_id);
    $this->db->order_by("UPPER(course_name)","desc");
    

    Or try BINARY:

    ORDER BY BINARY course_name DESC;
    

    You should add manually on codeigniter for binary sorting.

    And set "course_name" character column.

    If sorting is used on a character type column, normally the sort is conducted in a case-insensitive fashion.

    What type of structure data in courses table?

    If you frustrated you can put into array and return using PHP:

    Use natcasesort for order in "natural order": (Reference: http://php.net/manual/en/function.natcasesort.php)

    Your array from database as example: $array_db = $result_from_db:

    $final_result = natcasesort($array_db);
    
    print_r($final_result);
    

    Git - Ignore files during merge

    I ended up finding git attributes. Trying it. Working so far. Did not check all scenarios yet. But it should be the solution.

    Merge Strategies - Git attributes

    What's a quick way to comment/uncomment lines in Vim?

    This answer is most useful if you are unable to install plugins but you still want your comment characters to follow existing indentation levels.

    This answer is here to 1) show the correct code to paste into a .vimrc to get vim 7.4+ to do block commenting/uncommenting while keeping indentation level with 1 shortcut in visual mode and 2) to explain it. Here is the code:

    let b:commentChar='//'
    autocmd BufNewFile,BufReadPost *.[ch]    let b:commentChar='//'
    autocmd BufNewFile,BufReadPost *.cpp    let b:commentChar='//'
    autocmd BufNewFile,BufReadPost *.py    let b:commentChar='#'
    autocmd BufNewFile,BufReadPost *.*sh    let b:commentChar='#'
    function! Docomment ()
      "make comments on all the lines we've grabbed
      execute '''<,''>s/^\s*/&'.escape(b:commentChar, '\/').' /e'
    endfunction
    function! Uncomment ()
      "uncomment on all our lines
      execute '''<,''>s/\v(^\s*)'.escape(b:commentChar, '\/').'\v\s*/\1/e'
    endfunction
    function! Comment ()
      "does the first line begin with a comment?
      let l:line=getpos("'<")[1]
      "if there's a match
      if match(getline(l:line), '^\s*'.b:commentChar)>-1
        call Uncomment()
      else
        call Docomment()
      endif
    endfunction
    vnoremap <silent> <C-r> :<C-u>call Comment()<cr><cr>
    

    How it works:

    • let b:commentChar='//' : This creates a variable in vim. the b here refers to the scope, which in this case is contained to the buffer, meaning the currently opened file. Your comment characters are strings and need to be wrapped in quotes, the quotes are not part of what will be substituted in when toggling comments.

    • autocmd BufNewFile,BufReadPost *... : Autocommands trigger on different things, in this case, these are triggering when a new file or the read file ends with a certain extension. Once triggered, the execute the following command, which allows us to change the commentChar depending on filetype. There are other ways to do this, but they are more confusing to novices (like me).

    • function! Docomment() : Functions are declared by starting with function and ending with endfunction. Functions must start with a capital. the ! ensures that this function overwrites any previous functions defined as Docomment() with this version of Docomment(). Without the !, I had errors, but that might be because I was defining new functions through the vim command line.

    • execute '''<,''>s/^\s*/&'.escape(b:commentChar, '\/').' /e' : Execute calls a command. In this case, we are executing substitute, which can take a range (by default this is the current line) such as % for the whole buffer or '<,'> for the highlighted section. ^\s* is regex to match the start of a line followed by any amount of whitespace, which is then appended to (due to &). The . here is used for string concatenation, since escape() can't be wrapped in quotes. escape() allows you to escape character in commentChar that matches the arguments (in this case, \ and /) by prepending them with a \. After this, we concatenate again with the end of our substitute string, which has the e flag. This flag lets us fail silently, meaning that if we do not find a match on a given line, we won't yell about it. As a whole, this line lets us put a comment character followed by a space just before the first text, meaning we keep our indentation level.

    • execute '''<,''>s/\v(^\s*)'.escape(b:commentChar, '\/').'\v\s*/\1/e' : This is similar to our last huge long command. Unique to this one, we have \v, which makes sure that we don't have to escape our (), and 1, which refers to the group we made with our (). Basically, we're matching a line that starts with any amount of whitespace and then our comment character followed by any amount of whitespace, and we are only keeping the first set of whitespace. Again, e lets us fail silently if we don't have a comment character on that line.

    • let l:line=getpos("'<")[1] : this sets a variable much like we did with our comment character, but l refers to the local scope (local to this function). getpos() gets the position of, in this case, the start of our highlighting, and the [1] means we only care about the line number, not other things like the column number.

    • if match(getline(l:line), '^\s*'.b:commentChar)>-1 : you know how if works. match() checks if the first thing contains the second thing, so we grab the line that we started our highlighting on, and check if it starts with whitespace followed by our comment character. match() returns the index where this is true, and -1 if no matches were found. Since if evaluates all nonzero numbers to be true, we have to compare our output to see if it's greater than -1. Comparison in vim returns 0 if false and 1 if true, which is what if wants to see to evaluate correctly.

    • vnoremap <silent> <C-r> :<C-u>call Comment()<cr><cr> : vnoremap means map the following command in visual mode, but don't map it recursively (meaning don't change any other commands that might use in other ways). Basically, if you're a vim novice, always use noremap to make sure you don't break things. <silent> means "I don't want your words, just your actions" and tells it not to print anything to the command line. <C-r> is the thing we're mapping, which is ctrl+r in this case (note that you can still use C-r normally for "redo" in normal mode with this mapping). C-u is kinda confusing, but basically it makes sure you don't lose track of your visual highlighting (according to this answer it makes your command start with '<,'> which is what we want). call here just tells vim to execute the function we named, and <cr> refers to hitting the enter button. We have to hit it once to actually call the function (otherwise we've just typed call function() on the command line, and we have to hit it again to get our substitutes to go through all the way (not really sure why, but whatever).

    Anyway, hopefully this helps. This will take anything highlighted with v, V, or C-v, check if the first line is commented, if yes, try to uncomment all highlighted lines, and if not, add an extra layer of comment characters to each line. This is my desired behavior; I did not just want it to toggle whether each line in the block was commented or not, so it works perfectly for me after asking multiple questions on the subject.

    JavaScript Array splice vs slice

    Splice - MDN reference - ECMA-262 spec

    Syntax
    array.splice(start[, deleteCount[, item1[, item2[, ...]]]])

    Parameters

    • start: required. Initial index.
      If start is negative it is treated as "Math.max((array.length + start), 0)" as per spec (example provided below) effectively from the end of array.
    • deleteCount: optional. Number of elements to be removed (all from start if not provided).
    • item1, item2, ...: optional. Elements to be added to the array from start index.

    Returns: An array with deleted elements (empty array if none removed)

    Mutate original array: Yes

    Examples:

    _x000D_
    _x000D_
    const array = [1,2,3,4,5];
    
    // Remove first element
    console.log('Elements deleted:', array.splice(0, 1), 'mutated array:', array);
    // Elements deleted: [ 1 ] mutated array: [ 2, 3, 4, 5 ]
    
    // array = [ 2, 3, 4, 5]
    // Remove last element (start -> array.length+start = 3)
    console.log('Elements deleted:', array.splice(-1, 1), 'mutated array:', array);
    // Elements deleted: [ 5 ] mutated array: [ 2, 3, 4 ]
    _x000D_
    _x000D_
    _x000D_

    More examples in MDN Splice examples


    Slice - MDN reference - ECMA-262 spec

    Syntax
    array.slice([begin[, end]])
    Parameters

    • begin: optional. Initial index (default 0).
      If begin is negative it is treated as "Math.max((array.length + begin), 0)" as per spec (example provided below) effectively from the end of array.
    • end: optional. Last index for extraction but not including (default array.length). If end is negative it is treated as "Math.max((array.length + begin),0)" as per spec (example provided below) effectively from the end of array.

    Returns: An array containing the extracted elements.

    Mutate original: No

    Examples:

    _x000D_
    _x000D_
    const array = [1,2,3,4,5];
    
    // Extract first element
    console.log('Elements extracted:', array.slice(0, 1), 'array:', array);
    // Elements extracted: [ 1 ] array: [ 1, 2, 3, 4, 5 ]
    
    // Extract last element (start -> array.length+start = 4)
    console.log('Elements extracted:', array.slice(-1), 'array:', array);
    // Elements extracted: [ 5 ] array: [ 1, 2, 3, 4, 5 ]
    _x000D_
    _x000D_
    _x000D_

    More examples in MDN Slice examples

    Performance comparison

    Don't take this as absolute truth as depending on each scenario one might be performant than the other.
    Performance test

    .NET Events - What are object sender & EventArgs e?

    sender refers to the object that invoked the event that fired the event handler. This is useful if you have many objects using the same event handler.

    EventArgs is something of a dummy base class. In and of itself it's more or less useless, but if you derive from it, you can add whatever data you need to pass to your event handlers.

    When you implement your own events, use an EventHandler or EventHandler<T> as their type. This guarantees that you'll have exactly these two parameters for all your events (which is a good thing).

    How do I print the key-value pairs of a dictionary in python

    A little intro to dictionary

    d={'a':'apple','b':'ball'}
    d.keys()  # displays all keys in list
    ['a','b']
    d.values() # displays your values in list
    ['apple','ball']
    d.items() # displays your pair tuple of key and value
    [('a','apple'),('b','ball')
    

    Print keys,values method one

    for x in d.keys():
        print x +" => " + d[x]
    

    Another method

    for key,value in d.items():
        print key + " => " + value
    

    You can get keys using iter

    >>> list(iter(d))
    ['a', 'b']
    

    You can get value of key of dictionary using get(key, [value]):

    d.get('a')
    'apple'
    

    If key is not present in dictionary,when default value given, will return value.

    d.get('c', 'Cat')
    'Cat'
    

    Converting from a string to boolean in Python?

    I just had to do this... so maybe late to the party - but someone may find it useful

    def str_to_bool(input, default):
        """
        | Default | not_default_str | input   | result
        | T       |  "false"        | "true"  |  T
        | T       |  "false"        | "false" |  F
        | F       |  "true"         | "true"  |  T
        | F       |  "true"         | "false" |  F
    
        """
        if default:
            not_default_str = "false"
        else:
            not_default_str = "true"
    
        if input.lower() == not_default_str:
            return not default
        else:
            return default
    

    Removing input background colour for Chrome autocomplete?

    This is my solution, I used transition and transition delay therefore I can have a transparent background on my input fields.

    input:-webkit-autofill,
    input:-webkit-autofill:hover,
    input:-webkit-autofill:focus,
    input:-webkit-autofill:active {
        -webkit-transition: "color 9999s ease-out, background-color 9999s ease-out";
        -webkit-transition-delay: 9999s;
    }
    

    Is it possible to add dynamically named properties to JavaScript object?

    Yes it is possible. Assuming:

    var data = {
        'PropertyA': 1,
        'PropertyB': 2,
        'PropertyC': 3
    };
    var propertyName = "someProperty";
    var propertyValue = "someValue";
    

    Either:

    data[propertyName] = propertyValue;
    

    or

    eval("data." + propertyName + " = '" + propertyValue + "'");
    

    The first method is preferred. eval() has the obvious security concerns if you're using values supplied by the user so don't use it if you can avoid it but it's worth knowing it exists and what it can do.

    You can reference this with:

    alert(data.someProperty);
    

    or

    data(data["someProperty"]);
    

    or

    alert(data[propertyName]);
    

    How can I replace newline or \r\n with <br/>?

    You may have real characters "\" in the string (the single quote strings, as said @Robik).

    If you are quite sure the '\r' or '\n' strings should be replaced as well, I'm not talking of special characters here but a sequence of two chars '\' and 'r', then escape the '\' in the replace string and it will work:

    str_replace(array("\r\n","\r","\n","\\r","\\n","\\r\\n"),"<br/>",$description);
    

    Bootstrap carousel resizing image

    i had this issue years back..but I got this. All you need to do is set the width and the height of the image to whatever you want..what i mean is your image in your carousel inner ...don't add the style attribut like "style:"(no not this) but something like this and make sure your codes ar correct its gonna work...Good luck

    How to retrieve an Oracle directory path?

    select directory_path from dba_directories where upper(directory_name) = 'CSVDIR'
    

    Use a.any() or a.all()

    This should also work and is a closer answer to what is asked in the question:

    for i in range(len(x)):
        if valeur.item(i) <= 0.6:
            print ("this works")
        else:   
            print ("valeur is too high")
    

    How do I join two SQLite tables in my Android application?

    "Ambiguous column" usually means that the same column name appears in at least two tables; the database engine can't tell which one you want. Use full table names or table aliases to remove the ambiguity.

    Here's an example I happened to have in my editor. It's from someone else's problem, but should make sense anyway.

    select P.* 
    from product_has_image P
    inner join highest_priority_images H 
            on (H.id_product = P.id_product and H.priority = p.priority)
    

    Fastest way to serialize and deserialize .NET objects

    Yet another serializer out there that claims to be super fast is netserializer.

    The data given on their site shows performance of 2x - 4x over protobuf, I have not tried this myself, but if you are evaluating various options, try this as well

    In Angular, how to add Validator to FormControl after control is created?

    If you are using reactiveFormModule and have formGroup defined like this:

    public exampleForm = new FormGroup({
            name: new FormControl('Test name', [Validators.required, Validators.minLength(3)]),
            email: new FormControl('[email protected]', [Validators.required, Validators.maxLength(50)]),
            age: new FormControl(45, [Validators.min(18), Validators.max(65)])
    });
    

    than you are able to add a new validator (and keep old ones) to FormControl with this approach:

    this.exampleForm.get('age').setValidators([
            Validators.pattern('^[0-9]*$'),
            this.exampleForm.get('age').validator
    ]);
    this.exampleForm.get('email').setValidators([
            Validators.email,
            this.exampleForm.get('email').validator
    ]);
    

    FormControl.validator returns a compose validator containing all previously defined validators.

    Why is there no multiple inheritance in Java, but implementing multiple interfaces is allowed?

    Java supports multiple inheritance through interfaces only. A class can implement any number of interfaces but can extend only one class.

    Multiple inheritance is not supported because it leads to deadly diamond problem. However, it can be solved but it leads to complex system so multiple inheritance has been dropped by Java founders.

    In a white paper titled “Java: an Overview” by James Gosling in February 1995(link) gives an idea on why multiple inheritance is not supported in Java.

    According to Gosling:

    "JAVA omits many rarely used, poorly understood, confusing features of C++ that in our experience bring more grief than bene?t. This primarily consists of operator overloading (although it does have method overloading), multiple inheritance, and extensive automatic coercions."

    Are email addresses case sensitive?

    From RFC 5321, section 2.3.11:

    The standard mailbox naming convention is defined to be "local-part@domain"; contemporary usage permits a much broader set of applications than simple "user names". Consequently, and due to a long history of problems when intermediate hosts have attempted to optimize transport by modifying them, the local-part MUST be interpreted and assigned semantics only by the host specified in the domain part of the address.

    So yes, the part before the "@" could be case-sensitive, since it is entirely under the control of the host system. In practice though, no widely used mail systems distinguish different addresses based on case.

    The part after the @ sign however is the domain and according to RFC 1035, section 3.1,

    "Name servers and resolvers must compare [domains] in a case-insensitive manner"

    In short, you are safe to treat email addresses as case-insensitive.

    parse html string with jquery

    One thing to note - as I had exactly this problem today, depending on your HTML jQuery may or may not parse it that well. jQuery wouldn't parse my HTML into a correct DOM - on smaller XML compliant files it worked fine, but the HTML I had (that would render in a page) wouldn't parse when passed back to an Ajax callback.

    In the end I simply searched manually in the string for the tag I wanted, not ideal but did work.

    Why does cURL return error "(23) Failed writing body"?

    For me, it was permission issue. Docker run is called with a user profile but root is the user inside the container. The solution was to make curl write to /tmp since that has write permission for all users , not just root.

    I used the -o option.

    -o /tmp/file_to_download

    How to get the employees with their managers

    Perhaps your subquery (SELECT ename FROM EMP WHERE empno = mgr) thinks, give me the employee records that are their own managers! (i.e., where the empno of a row is the same as the mgr of the same row.)

    have you considered perhaps rewriting this to use an inner (self) join? (I'm asking, becuase i'm not even sure if the following will work or not.)

    SELECT t1.ename, t1.empno, t2.ename as MANAGER, t1.mgr
    from emp as t1
    inner join emp t2 ON t1.mgr = t2.empno
    order by t1.empno;
    

    MySQL - How to increase varchar size of an existing column in a database without breaking existing data?

    I normally use this statement:

    ALTER TABLE `table_name`
      CHANGE COLUMN `col_name` `col_name` VARCHAR(10000);
    

    But, I think SET will work too, never have tried it. :)

    Sending POST data without form

    If you don't want your data to be seen by the user, use a PHP session.

    Data in a post request is still accessible (and manipulable) by the user.

    Checkout this tutorial on PHP Sessions.

    What's sizeof(size_t) on 32-bit vs the various 64-bit data models?

    size_t is 64 bit normally on 64 bit machine

    Using "super" in C++

    Super (or inherited) is Very Good Thing because if you need to stick another inheritance layer in between Base and Derived, you only have to change two things: 1. the "class Base: foo" and 2. the typedef

    If I recall correctly, the C++ Standards committee was considering adding a keyword for this... until Michael Tiemann pointed out that this typedef trick works.

    As for multiple inheritance, since it's under programmer control you can do whatever you want: maybe super1 and super2, or whatever.

    How to fill background image of an UIView

    For Swift use this...

    UIGraphicsBeginImageContext(self.view.frame.size)
    UIImage(named: "ImageName.png")?.draw(in: self.view.bounds)
    
    if let image = UIGraphicsGetImageFromCurrentImageContext(){
        UIGraphicsEndImageContext()
        self.view.backgroundColor = UIColor(patternImage: image)
    }else{
        UIGraphicsEndImageContext()
        debugPrint("Image not available")
     }
    

    reading external sql script in python

    Your code already contains a beautiful way to execute all statements from a specified sql file

    # Open and read the file as a single buffer
    fd = open('ZooDatabase.sql', 'r')
    sqlFile = fd.read()
    fd.close()
    
    # all SQL commands (split on ';')
    sqlCommands = sqlFile.split(';')
    
    # Execute every command from the input file
    for command in sqlCommands:
        # This will skip and report errors
        # For example, if the tables do not yet exist, this will skip over
        # the DROP TABLE commands
        try:
            c.execute(command)
        except OperationalError, msg:
            print "Command skipped: ", msg
    

    Wrap this in a function and you can reuse it.

    def executeScriptsFromFile(filename):
        # Open and read the file as a single buffer
        fd = open(filename, 'r')
        sqlFile = fd.read()
        fd.close()
    
        # all SQL commands (split on ';')
        sqlCommands = sqlFile.split(';')
    
        # Execute every command from the input file
        for command in sqlCommands:
            # This will skip and report errors
            # For example, if the tables do not yet exist, this will skip over
            # the DROP TABLE commands
            try:
                c.execute(command)
            except OperationalError, msg:
                print "Command skipped: ", msg
    

    To use it

    executeScriptsFromFile('zookeeper.sql')
    

    You said you were confused by

    result = c.execute("SELECT * FROM %s;" % table);
    

    In Python, you can add stuff to a string by using something called string formatting.

    You have a string "Some string with %s" with %s, that's a placeholder for something else. To replace the placeholder, you add % ("what you want to replace it with") after your string

    ex:

    a = "Hi, my name is %s and I have a %s hat" % ("Azeirah", "cool")
    print(a)
    >>> Hi, my name is Azeirah and I have a Cool hat
    

    Bit of a childish example, but it should be clear.

    Now, what

    result = c.execute("SELECT * FROM %s;" % table);
    

    means, is it replaces %s with the value of the table variable.

    (created in)

    for table in ['ZooKeeper', 'Animal', 'Handles']:
    
    
    # for loop example
    
    for fruit in ["apple", "pear", "orange"]:
        print fruit
    >>> apple
    >>> pear
    >>> orange
    

    If you have any additional questions, poke me.

    How do I send a POST request as a JSON?

    In the lastest requests package, you can use json parameter in requests.post() method to send a json dict, and the Content-Type in header will be set to application/json. There is no need to specify header explicitly.

    import requests
    
    payload = {'key': 'value'}
    requests.post(url, json=payload)
    

    an attempt was made to access a socket in a way forbbiden by its access permissions. why?

    I had a similar problem but I fixed it with by doing some changes in firewall setting.

    You can follow the below steps

    1. Go to "Start" --> "Control Panel"
    2. Click on "Windows Firewall" enter image description here

    3. Inside Windows Firewall, click on "Allow a program or feature through Windows Firewall" enter image description here

    4. Now inside of Allow Programs, Click on "Change Settings" button. Once you clicked on Change Settings button, the "Allow another program..." button gets enabled. enter image description here

    5. Click on "Allow another program..." button , a new dialog box will be opened. Choose the programs or application for which you are getting the socket exception and click on "Add" button. enter image description here

    6. Click OK, and restart your machine.

    7. Try to run your application (which has an exception) with administrative rights.

    I hope this helps.

    Peace,

    Sunny Makode

    Action bar navigation modes are deprecated in Android L

    Well for me to handle the deprecated navigation toolbar by using toolbar v7 widget appcompat.

        setSupportActionBar(toolbar);
        getSupportActionBar().setSubtitle("Feed Detail");
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //goToWhere
            }
        });
    

    How to get disk capacity and free space of remote computer

    I created a PowerShell advanced function (script cmdlet) a while back that allows you to query multiple computers.

    The code for the function is a little over 100 lines long, so you can find it here: PowerShell version of the df command

    Check out the Usage section for examples. The following usage example queries a set of remote computers (input from the PowerShell pipeline) and displays the output in a table format with numeric values in human-readable form:

    PS> $cred = Get-Credential -Credential 'example\administrator'
    PS> 'db01','dc01','sp01' | Get-DiskFree -Credential $cred -Format | Format-Table -GroupBy Name -AutoSize
    
       Name: DB01
    
    Name Vol Size  Used  Avail Use% FS   Type
    ---- --- ----  ----  ----- ---- --   ----
    DB01 C:  39.9G 15.6G 24.3G   39 NTFS Local Fixed Disk
    DB01 D:  4.1G  4.1G  0B     100 CDFS CD-ROM Disc
    
    
       Name: DC01
    
    Name Vol Size  Used  Avail Use% FS   Type
    ---- --- ----  ----  ----- ---- --   ----
    DC01 C:  39.9G 16.9G 23G     42 NTFS Local Fixed Disk
    DC01 D:  3.3G  3.3G  0B     100 CDFS CD-ROM Disc
    DC01 Z:  59.7G 16.3G 43.4G   27 NTFS Network Connection
    
    
       Name: SP01
    
    Name Vol Size   Used   Avail Use% FS   Type
    ---- --- ----   ----   ----- ---- --   ----
    SP01 C:  39.9G  20G    19.9G   50 NTFS Local Fixed Disk
    SP01 D:  722.8M 722.8M 0B     100 UDF  CD-ROM Disc
    

    linux execute command remotely

    I think this article explains well:

    Running Commands on a Remote Linux / UNIX Host

    Google is your best friend ;-)

    MySQL update CASE WHEN/THEN/ELSE

    Try this

    UPDATE `table` SET `uid` = CASE
        WHEN id = 1 THEN 2952
        WHEN id = 2 THEN 4925
        WHEN id = 3 THEN 1592
        ELSE `uid`
        END
    WHERE id  in (1,2,3)
    

    Psql could not connect to server: No such file or directory, 5432 error?

    I've had this same issue, related to the configuration of my pg_hba.conf file (located in /etc/postgresql/9.6/main). Please note that 9.6 is the postgresql version I am using.

    The error itself is related to a misconfiguration of postgresql, which causes the server to crash before it starts.

    I would suggest following these instructions:

    1. Certify that postgresql service is running, using sudo service postgresql start
    2. Run pg_lsclusters from your terminal
    3. Check what is the cluster you are running, the output should be something like:

      Version - Cluster Port Status Owner Data directory

      9.6 ------- main -- 5432 online postgres /var/lib/postgresql/9.6/main

      Disregard the '---' signs, as they are being used there only for alignment. The important information are the version and the cluster. You can also check whether the server is running or not in the status column.

    4. Copy the info from the version and the cluster, and use like so: pg_ctlcluster <version> <cluster> start, so in my case, using version 9.6 and cluster 'main', it would be pg_ctlcluster 9.6 main start
    5. If something is wrong, then postgresql will generate a log, that can be accessed on /var/log/postgresql/postgresql-<version>-main.log, so in my case, the full command would be sudo nano /var/log/postgresql/postgresql-9.6-main.log.
    6. The output should show what is the error.

      2017-07-13 16:53:04 BRT [32176-1] LOG: invalid authentication method "all"
      2017-07-13 16:53:04 BRT [32176-2] CONTEXT: line 90 of configuration file "/etc/postgresql/9.5/main/pg_hba.conf"
      2017-07-13 16:53:04 BRT [32176-3] FATAL: could not load pg_hba.conf

    7. Fix the errors and restart postgresql service through sudo service postgresql restart and it should be fine.

    I have searched a lot to find this, credit goes to this post.

    Best of luck!

    How to rollback everything to previous commit

    If you have pushed the commits upstream...

    Select the commit you would like to roll back to and reverse the changes by clicking Reverse File, Reverse Hunk or Reverse Selected Lines. Do this for all the commits after the commit you would like to roll back to also.

    reverse stuff reverse commit

    If you have not pushed the commits upstream...

    Right click on the commit and click on Reset current branch to this commit.

    reset branch to commit

    Tkinter example code for multiple windows, why won't buttons load correctly?

    You need to specify the master for the second button. Otherwise it will get packed onto the first window. This is needed not only for Button, but also for other widgets and non-gui objects such as StringVar.

    Quick fix: add the frame new as the first argument to your Button in Demo2.

    Possibly better: Currently you have Demo2 inheriting from tk.Frame but I think this makes more sense if you change Demo2 to be something like this,

    class Demo2(tk.Toplevel):     
        def __init__(self):
            tk.Toplevel.__init__(self)
            self.title("Demo 2")
            self.button = tk.Button(self, text="Button 2", # specified self as master
                                    width=25, command=self.close_window)
            self.button.pack()
    
        def close_window(self):
            self.destroy()
    

    Just as a suggestion, you should only import tkinter once. Pick one of your first two import statements.

    How to solve "The directory is not empty" error when running rmdir command in a batch script?

    I experienced the same issues as Harry Johnston has mentioned. rmdir /s /q would complain that a directory was not empty even though /s is meant to do the emptying for you! I think it's a bug in Windows, personally.

    My workaround is to del everything in the directory before deleting the directory itself:

    del /f /s /q mydir 1>nul
    rmdir /s /q mydir
    

    (The 1>nul hides the standard output of del because otherwise, it lists every single file it deletes.)

    Cocoa Autolayout: content hugging vs content compression resistance priority

    contentCompressionResistancePriority – The view with the lowest value gets truncated when there is not enough space to fit everything’s intrinsicContentSize

    contentHuggingPriority – The view with the lowest value gets expanded beyond its intrinsicContentSize when there is leftover space to fill