Programs & Examples On #Reload

reloading is the process of re-requesting and re-rendering the currently displayed page

One time page refresh after first page load

use this

<body onload =  "if (location.search.length < 1){window.location.reload()}">

How to reload a div without reloading the entire page?

write a button tag and on click function

var x = document.getElementById('codeRefer').innerHTML;
  document.getElementById('codeRefer').innerHTML = x;

write this all in onclick function

How do I reload a page without a POSTDATA warning in Javascript?

The other solutions with window.location didn't work for me since they didn't make it refresh at all, so what I did was that I used an empty form to pass new and empty postdata to the same page. This is a way to do that based on this answer:

function refreshAndClearPost() {
    var form = document.createElement("form");
    form.method = "POST";
    form.action = location.href;
    form.style.display = "none";

    document.body.appendChild(form);
    form.submit();    //since the form is empty, it will pass empty postdata
    document.body.removeChild(form);
}

Refresh (reload) a page once using jQuery?

Use this:

    <script type="text/javascript">
        $(document).ready(function(){

            // Check if the current URL contains '#'
            if(document.URL.indexOf("#")==-1)
            {
                // Set the URL to whatever it was plus "#".
                url = document.URL+"#";
                location = "#";

                //Reload the page
                 location.reload(true);
            }
        });
    </script>

Due to the if condition, the page will reload only once.

How to reload page the page with pagination in Angular 2?

This should technically be achievable using window.location.reload():

HTML:

<button (click)="refresh()">Refresh</button>

TS:

refresh(): void {
    window.location.reload();
}

Update:

Here is a basic StackBlitz example showing the refresh in action. Notice the URL on "/hello" path is retained when window.location.reload() is executed.

How to reload .bashrc settings without logging out and back in again?

You can enter the long form command:

source ~/.bashrc

or you can use the shorter version of the command:

. ~/.bashrc

PHP refresh window? equivalent to F5 page reload?

Use JavaScript for this. You can do:

echo '
<script type="text/javascript">
   parent.window.location.reload(true);
</script>
';

In PHP and it will refresh the parent's frame page.

How do I detect a page refresh using jquery?

There are two events on client side as given below.

1. window.onbeforeunload (calls on Browser/tab Close & Page Load)

2. window.onload (calls on Page Load)

On server Side

public JsonResult TestAjax( string IsRefresh)
    {
        JsonResult result = new JsonResult();
        return result = Json("Called", JsonRequestBehavior.AllowGet);
    }

On Client Side

_x000D_
_x000D_
 <script type="text/javascript">_x000D_
    window.onbeforeunload = function (e) {_x000D_
        _x000D_
        $.ajax({_x000D_
            type: 'GET',_x000D_
            async: false,_x000D_
            url: '/Home/TestAjax',_x000D_
            data: { IsRefresh: 'Close' }_x000D_
        });_x000D_
    };_x000D_
_x000D_
    window.onload = function (e) {_x000D_
_x000D_
        $.ajax({_x000D_
            type: 'GET',_x000D_
            async: false,_x000D_
            url: '/Home/TestAjax',_x000D_
            data: {IsRefresh:'Load'}_x000D_
        });_x000D_
    };_x000D_
</script>
_x000D_
_x000D_
_x000D_

On Browser/Tab Close: if user close the Browser/tab, then window.onbeforeunload will fire and IsRefresh value on server side will be "Close".

On Refresh/Reload/F5: If user will refresh the page, first window.onbeforeunload will fire with IsRefresh value = "Close" and then window.onload will fire with IsRefresh value = "Load", so now you can determine at last that your page is refreshing.

How do I unload (reload) a Python module?

Another way could be to import the module in a function. This way when the function completes the module gets garbage collected.

Button that refreshes the page on click

Use onClick with one of the following:

window.location.reload(), i.e.:

<button onClick="window.location.reload();">Refresh Page</button>

Or history.go(0), i.e.:

<button onClick="history.go(0);">Refresh Page</button>

Or window.location.href=window.location.href for 'full' reload, i.e.:

<button onClick="window.location.href=window.location.href">Refresh Page</button>

MDN page on the <button> element.

Is there a better way to refresh WebView?

You could call an mWebView.reload(); That's what it does

Is there an easy way to reload css without reloading the page?

i now have this:

    function swapStyleSheet() {
        var old = $('#pagestyle').attr('href');
        var newCss = $('#changeCss').attr('href');
        var sheet = newCss +Math.random(0,10);
        $('#pagestyle').attr('href',sheet);
        $('#profile').attr('href',old);
        }
    $("#changeCss").on("click", function(event) { 
        swapStyleSheet();
    } );

make any element in your page with id changeCss with a href attribute with the new css url in it. and a link element with the starting css:

<link id="pagestyle" rel="stylesheet" type="text/css" href="css1.css?t=" />

<img src="click.jpg" id="changeCss" href="css2.css?t=">

JavaScript hard refresh of current page

window.location.href = window.location.href

How to reload or re-render the entire page using AngularJS

Try one of the following:

$route.reload(); // don't forget to inject $route in your controller
$window.location.reload();
location.reload();

Change hash without reload in jQuery

You can simply assign it a new value as follows,

window.location.hash

How can I refresh a page with jQuery?

To reload a page with jQuery, do:

$.ajax({
    url: "",
    context: document.body,
    success: function(s,x){
        $(this).html(s);
    }
});

The approach here that I used was Ajax jQuery. I tested it on Chrome 13. Then I put the code in the handler that will trigger the reload. The URL is "", which means this page.

How to force page refreshes or reloads in jQuery?

You don't need jQuery to do this. Embrace the power of JavaScript.

window.location.reload()

How to reload a page using JavaScript

You can perform this task using window.location.reload();. As there are many ways to do this but I think it is the appropriate way to reload the same document with JavaScript. Here is the explanation

JavaScript window.location object can be used

  • to get current page address (URL)
  • to redirect the browser to another page
  • to reload the same page

window: in JavaScript represents an open window in a browser.

location: in JavaScript holds information about current URL.

The location object is like a fragment of the window object and is called up through the window.location property.

location object has three methods:

  1. assign(): used to load a new document
  2. reload(): used to reload current document
  3. replace(): used to replace current document with a new one

So here we need to use reload(), because it can help us in reloading the same document.

So use it like window.location.reload();.

Online demo on jsfiddle

To ask your browser to retrieve the page directly from the server not from the cache, you can pass a true parameter to location.reload(). This method is compatible with all major browsers, including IE, Chrome, Firefox, Safari, Opera.

Reload the page after ajax success

use this Reload page

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

Rails: Adding an index after adding column

Add in the generated migration after creating the column the following (example)

add_index :photographers, :email, :unique => true

How do I do a simple 'Find and Replace" in MsSQL?

If you are working with SQL Server 2005 or later there is also a CLR library available at http://www.sqlsharp.com/ that provides .NET implementations of string and RegEx functions which, depending on your volume and type of data may be easier to use and in some cases the .NET string manipulation functions can be more efficient than T-SQL ones.

Android ListView with Checkbox and all clickable

Set the listview adapter to "simple_list_item_multiple_choice"

ArrayAdapter<String> adapter;

List<String> values; // put values in this

//Put in listview
adapter = new ArrayAdapter<UserProfile>(
this,
android.R.layout.simple_list_item_multiple_choice, 
values);
setListAdapter(adapter);    

The AWS Access Key Id does not exist in our records

I made the mistake of setting my variables with quotation marks like this:

AWS_ACCESS_KEY_ID="..."

How do I trim whitespace from a string?

Just one space or all consecutive spaces? If the second, then strings already have a .strip() method:

>>> ' Hello '.strip()
'Hello'
>>> ' Hello'.strip()
'Hello'
>>> 'Bob has a cat'.strip()
'Bob has a cat'
>>> '   Hello   '.strip()  # ALL consecutive spaces at both ends removed
'Hello'

If you only need to remove one space however, you could do it with:

def strip_one_space(s):
    if s.endswith(" "): s = s[:-1]
    if s.startswith(" "): s = s[1:]
    return s

>>> strip_one_space("   Hello ")
'  Hello'

Also, note that str.strip() removes other whitespace characters as well (e.g. tabs and newlines). To remove only spaces, you can specify the character to remove as an argument to strip, i.e.:

>>> "  Hello\n".strip(" ")
'Hello\n'

Find indices of elements equal to zero in a NumPy array

You can use numpy.nonzero to find zero.

>>> import numpy as np
>>> x = np.array([1,0,2,0,3,0,0,4,0,5,0,6]).reshape(4, 3)
>>> np.nonzero(x==0)  # this is what you want
(array([0, 1, 1, 2, 2, 3]), array([1, 0, 2, 0, 2, 1]))
>>> np.nonzero(x)
(array([0, 0, 1, 2, 3, 3]), array([0, 2, 1, 1, 0, 2]))

How can I add new array elements at the beginning of an array in Javascript?

If you want to push elements that are in a array at the beginning of you array use <func>.apply(<this>, <Array of args>) :

_x000D_
_x000D_
const arr = [1, 2];
arr.unshift.apply(arr, [3, 4]);
console.log(arr); // [3, 4, 1, 2]
_x000D_
_x000D_
_x000D_

Calculating bits required to store decimal number

Assuming that the question is asking what's the minimum bits required for you to store

  1. 3 digits number

My approach to this question would be:

  • what's the maximum number of 3 digits number we need to store? Ans: 999
  • what's the minimum amount of bits required for me to store this number?

This problem can be solved this way by dividing 999 by 2 recursively. However, it's simpler to use the power of maths to help us. Essentially, we're solving n for the equation below:

2^n = 999
nlog2 = log999
n ~ 10

You'll need 10 bits to store 3 digit number.

Use similar approach to solve the other subquestions!

Hope this helps!

Find all matches in workbook using Excel VBA

Below code avoids creating infinite loop. Assume XYZ is the string which we are looking for in the workbook.

   Private Sub CommandButton1_Click()
   Dim Sh As Worksheet, myCounter
   Dim Loc As Range

   For Each Sh In ThisWorkbook.Worksheets
   With Sh.UsedRange
   Set Loc = .Cells.Find(What:="XYZ")

    If Not Loc Is Nothing Then

           MsgBox ("Value is found  in " & Sh.Name)
           myCounter = 1
            Set Loc = .FindNext(Loc)

    End If
End With
Next
If myCounter = 0 Then
MsgBox ("Value not present in this worrkbook")
End If

End Sub

Xcode couldn't find any provisioning profiles matching

Try to check Signing settings in Build settings for your project and target. Be sure that code signing identity section has correct identities for Debug and Release.

image description here

Passing multiple parameters with $.ajax url

why not just pass an data an object with your key/value pairs then you don't have to worry about encoding

$.ajax({
    type: "Post",
    url: "getdata.php",
    data:{
       timestamp: timestamp,
       uid: id,
       uname: name
    },
    async: true,
    cache: false,
    success: function(data) {


    };
}?);?

Auto increment in MongoDB to store sequence of Unique User ID

First Record should be add

"_id" = 1    in your db

$database = "demo";
$collections ="democollaction";
echo getnextid($database,$collections);

function getnextid($database,$collections){

     $m = new MongoClient();
    $db = $m->selectDB($database);
    $cursor = $collection->find()->sort(array("_id" => -1))->limit(1);
    $array = iterator_to_array($cursor);

    foreach($array as $value){



        return $value["_id"] + 1;

    }
 }

CSS: Set Div height to 100% - Pixels

The best way to do this is to use view port styles. It just does the work and no other techniques needed.

Code:

_x000D_
_x000D_
div{_x000D_
  height:100vh;_x000D_
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

Convert DateTime to long and also the other way around

Since you're using ToFileTime, you'll want to use FromFileTime to go the other way. But note:

Ordinarily, the FromFileTime method restores a DateTime value that was saved by the ToFileTime method. However, the two values may differ under the following conditions:

If the serialization and deserialization of the DateTime value occur in different time zones. For example, if a DateTime value with a time of 12:30 P.M. in the U.S. Eastern Time zone is serialized, and then deserialized in the U.S. Pacific Time zone, the original value of 12:30 P.M. is adjusted to 9:30 A.M. to reflect the difference between the two time zones.

If the DateTime value that is serialized represents an invalid time in the local time zone. In this case, the ToFileTime method adjusts the restored DateTime value so that it represents a valid time in the local time zone.

If you don't care which long representation of a DateTime is stored, you can use Ticks as others have suggested (Ticks is probably preferable, depending on your requirements, since the value returned by ToFileTime seems to be in the context of the Windows filesystem API).

Checking for empty or null JToken in a JObject

Try something like this to convert JToken to JArray:

static public JArray convertToJArray(JToken obj)
{
    // if ((obj).Type == JTokenType.Null) --> You can check if it's null here

    if ((obj).Type == JTokenType.Array)
        return (JArray)(obj);
    else
        return new JArray(); // this will return an empty JArray
}

Test process.env with Jest

I think you could try this too:

const currentEnv = process.env;
process.env = { ENV_NODE: 'whatever' };

// test code...

process.env = currentEnv;

This works for me and you don't need module things

How to load a jar file at runtime

Use org.openide.util.Lookup and ClassLoader to dynamically load the Jar plugin, as shown here.

public LoadEngine() {
    Lookup ocrengineLookup;
    Collection<OCREngine> ocrengines;
    Template ocrengineTemplate;
    Result ocrengineResults;
    try {
        //ocrengineLookup = Lookup.getDefault(); this only load OCREngine in classpath of  application
        ocrengineLookup = Lookups.metaInfServices(getClassLoaderForExtraModule());//this load the OCREngine in the extra module as well
        ocrengineTemplate = new Template(OCREngine.class);
        ocrengineResults = ocrengineLookup.lookup(ocrengineTemplate); 
        ocrengines = ocrengineResults.allInstances();//all OCREngines must implement the defined interface in OCREngine. Reference to guideline of implement org.openide.util.Lookup for more information

    } catch (Exception ex) {
    }
}

public ClassLoader getClassLoaderForExtraModule() throws IOException {

    List<URL> urls = new ArrayList<URL>(5);
    //foreach( filepath: external file *.JAR) with each external file *.JAR, do as follows
    File jar = new File(filepath);
    JarFile jf = new JarFile(jar);
    urls.add(jar.toURI().toURL());
    Manifest mf = jf.getManifest(); // If the jar has a class-path in it's manifest add it's entries
    if (mf
            != null) {
        String cp =
                mf.getMainAttributes().getValue("class-path");
        if (cp
                != null) {
            for (String cpe : cp.split("\\s+")) {
                File lib =
                        new File(jar.getParentFile(), cpe);
                urls.add(lib.toURI().toURL());
            }
        }
    }
    ClassLoader cl = ClassLoader.getSystemClassLoader();
    if (urls.size() > 0) {
        cl = new URLClassLoader(urls.toArray(new URL[urls.size()]), ClassLoader.getSystemClassLoader());
    }
    return cl;
}

Implicit type conversion rules in C++ operators

The type of the expression, when not both parts are of the same type, will be converted to the biggest of both. The problem here is to understand which one is bigger than the other (it does not have anything to do with size in bytes).

In expressions in which a real number and an integer number are involved, the integer will be promoted to real number. For example, in int + float, the type of the expression is float.

The other difference are related to the capability of the type. For example, an expression involving an int and a long int will result of type long int.

What are the parameters for the number Pipe - Angular 2

'1.0-0' will give you zero decimal places i.e. no decimals. e.g.$500

How can I check if an ip is in a network in Python?

previous solution have a bug in ip & net == net. Correct ip lookup is ip & netmask = net

bugfixed code:

import socket
import struct

def makeMask(n):
    "return a mask of n bits as a long integer"
    return (2L<<n-1) - 1

def dottedQuadToNum(ip):
    "convert decimal dotted quad string to long integer"
    return struct.unpack('L',socket.inet_aton(ip))[0]

def addressInNetwork(ip,net,netmask):
   "Is an address in a network"
   print "IP "+str(ip) + " NET "+str(net) + " MASK "+str(netmask)+" AND "+str(ip & netmask)
   return ip & netmask == net

def humannetcheck(ip,net):
        address=dottedQuadToNum(ip)
        netaddr=dottedQuadToNum(net.split("/")[0])
        netmask=makeMask(long(net.split("/")[1]))
        return addressInNetwork(address,netaddr,netmask)


print humannetcheck("192.168.0.1","192.168.0.0/24");
print humannetcheck("192.169.0.1","192.168.0.0/24");

How do I set up IntelliJ IDEA for Android applications?

You just need to install Android development kit from http://developer.android.com/sdk/installing/studio.html#Updating

and also Download and install Java JDK (Choose the Java platform)

define the environment variable in windows System setting https://confluence.atlassian.com/display/DOC/Setting+the+JAVA_HOME+Variable+in+Windows

Voila ! You are Donezo !

css 100% width div not taking up full width of parent

html, body{ 
  width:100%;
}

This tells the html to be 100% wide. But 100% refers to the whole browser window width, so no more than that.

You may want to set a min width instead.

html, body{ 
  min-width:100%;
}

So it will be 100% as a minimum, bot more if needed.

RESTful call in Java

If you just need to make a simple call to a REST service from java you use something along these line

/*
 * Stolen from http://xml.nig.ac.jp/tutorial/rest/index.html
 * and http://www.dr-chuck.com/csev-blog/2007/09/calling-rest-web-services-from-java/
*/
import java.io.*;
import java.net.*;

public class Rest {

    public static void main(String[] args) throws IOException {
        URL url = new URL(INSERT_HERE_YOUR_URL);
        String query = INSERT_HERE_YOUR_URL_PARAMETERS;

        //make connection
        URLConnection urlc = url.openConnection();

        //use post mode
        urlc.setDoOutput(true);
        urlc.setAllowUserInteraction(false);

        //send query
        PrintStream ps = new PrintStream(urlc.getOutputStream());
        ps.print(query);
        ps.close();

        //get result
        BufferedReader br = new BufferedReader(new InputStreamReader(urlc
            .getInputStream()));
        String l = null;
        while ((l=br.readLine())!=null) {
            System.out.println(l);
        }
        br.close();
    }
}

C++ initial value of reference to non-const must be an lvalue

The &nKByte creates a temporary value, which cannot be bound to a reference to non-const.

You could change void test(float *&x) to void test(float * const &x) or you could just drop the pointer altogether and use void test(float &x); /*...*/ test(nKByte);.

How to parse a JSON file in swift?

Below is a Swift Playground example:

import UIKit

let jsonString = "{\"name\": \"John Doe\", \"phone\":123456}"

let data = jsonString.data(using: .utf8)

var jsonObject: Any
do {
    jsonObject = try JSONSerialization.jsonObject(with: data!) as Any

    if let obj = jsonObject as? NSDictionary {
        print(obj["name"])
    }
} catch {
    print("error")
}

Maven - Failed to execute goal org.apache.maven.plugins:maven-clean-plugin:2.4.1:clean

If you have opened the command prompt(cmd) to run the jar on current folder,then the error will come as above.so close the command prompt and try maven clean and install,it will work definitely.

How to add image in a TextView text?

I tried many different solutions and this for me was the best:

SpannableStringBuilder ssb = new SpannableStringBuilder(" Hello world!");
ssb.setSpan(new ImageSpan(context, R.drawable.image), 0, 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
tv_text.setText(ssb, TextView.BufferType.SPANNABLE);

This code uses a minimum of memory.

Convert INT to VARCHAR SQL

Use the STR function:

SELECT STR(field_name) FROM table_name

Arguments

float_expression

Is an expression of approximate numeric (float) data type with a decimal point.

length

Is the total length. This includes decimal point, sign, digits, and spaces. The default is 10.

decimal

Is the number of places to the right of the decimal point. decimal must be less than or equal to 16. If decimal is more than 16 then the result is truncated to sixteen places to the right of the decimal point.

source: https://msdn.microsoft.com/en-us/library/ms189527.aspx

How to read an excel file in C# without using Microsoft.Office.Interop.Excel libraries

var fileName = @"C:\ExcelFile.xlsx";
var connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;IMEX=1;HDR=NO;TypeGuessRows=0;ImportMixedTypes=Text\""; ;
using (var conn = new OleDbConnection(connectionString))
{
    conn.Open();

    var sheets = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
    using (var cmd = conn.CreateCommand())
    {
        cmd.CommandText = "SELECT * FROM [" + sheets.Rows[0]["TABLE_NAME"].ToString() + "] ";

        var adapter = new OleDbDataAdapter(cmd);
        var ds = new DataSet();
        adapter.Fill(ds);
    }
}

Importing files from different folder

I bumped into the same question several times, so I would like to share my solution.

Python Version: 3.X

The following solution is for someone who develops your application in Python version 3.X because Python 2 is not supported since Jan/1/2020.

Project Structure

In python 3, you don't need __init__.py in your project subdirectory due to the Implicit Namespace Packages. See Is init.py not required for packages in Python 3.3+

Project 
+-- main.py
+-- .gitignore
|
+-- a
|   +-- file_a.py
|
+-- b
    +-- file_b.py

Problem Statement

In file_b.py, I would like to import a class A in file_a.py under the folder a.

Solutions

#1 A quick but dirty way

Without installing the package like you are currently developing a new project

Using the try catch to check if the errors. Code example:

import sys
try:
    # The insertion index should be 1 because index 0 is this file
    sys.path.insert(1, '/absolute/path/to/folder/a')  # the type of path is string
    # because the system path already have the absolute path to folder a
    # so it can recognize file_a.py while searching 
    from file_a import A
except (ModuleNotFoundError, ImportError) as e:
    print("{} fileure".format(type(e)))
else:
    print("Import succeeded")

#2 Install your package

Once you installed your application (in this post, the tutorial of installation is not included)

You can simply

try:
    from __future__ import absolute_import
    # now it can reach class A of file_a.py in folder a 
    # by relative import
    from ..a.file_a import A  
except (ModuleNotFoundError, ImportError) as e:
    print("{} fileure".format(type(e)))
else:
    print("Import succeeded")

Happy coding!

I want to get the type of a variable at runtime

I think the question is incomplete. if you meant that you wish to get the type information of some typeclass then below:

If you wish to print as you have specified then:

scala>  def manOf[T: Manifest](t: T): Manifest[T] = manifest[T]
manOf: [T](t: T)(implicit evidence$1: Manifest[T])Manifest[T]

scala> val x = List(1,2,3)
x: List[Int] = List(1, 2, 3)

scala> println(manOf(x))
scala.collection.immutable.List[Int]

If you are in repl mode then

scala> :type List(1,2,3)
List[Int]

Or if you just wish to know what the class type then as @monkjack explains "string".getClass might solve the purpose

What is Join() in jQuery?

You would probably use your example like this

var newText = "<span>" + $("p").text().split(" ").join("</span> <span>") + "</span>";

This will put span tags around all the words in you paragraphs, turning

<p>Test is a demo.</p>

into

<p><span>Test</span> <span>is</span> <span>a</span> <span>demo.</span></p>

I do not know what the practical use of this could be.

error LNK2038: mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '0' doesn't match value '2' in main.obj

I managed to get rid of this error (in my case using Ogre3D + Bullet) by changing the dependency libraries to the debug versions in Project Properties -> Linker -> Input -> Additional Dependencies (VC10).

I changed BulletCollision.lib to BulletCollision_debug.lib (for debug configuration) and it compiled.

How to pass parameters in GET requests with jQuery

Had the same problem where I specified data but the browser was sending requests to URL ending with [Object object].

You should have processData set to true.

processData: true, // You should comment this out if is false or set to true

When should I use a List vs a LinkedList

I asked a similar question related to performance of the LinkedList collection, and discovered Steven Cleary's C# implement of Deque was a solution. Unlike the Queue collection, Deque allows moving items on/off front and back. It is similar to linked list, but with improved performance.

How to substitute shell variables in complex text files

Actually you need to change your read to read -r which will make it ignore backslashes.

Also, you should escape quotes and backslashes. So

while read -r line; do
  line="${line//\\/\\\\}"
  line="${line//\"/\\\"}"
  line="${line//\`/\\\`}"
  eval echo "\"$line\""
done > destination.txt < source.txt

Still a terrible way to do expansion though.

Error in contrasts when defining a linear model in R

If your independent variable (RHS variable) is a factor or a character taking only one value then that type of error occurs.

Example: iris data in R

(model1 <- lm(Sepal.Length ~ Sepal.Width + Species, data=iris))

# Call:
# lm(formula = Sepal.Length ~ Sepal.Width + Species, data = iris)

# Coefficients:
#       (Intercept)        Sepal.Width  Speciesversicolor   Speciesvirginica  
#            2.2514             0.8036             1.4587             1.9468  

Now, if your data consists of only one species:

(model1 <- lm(Sepal.Length ~ Sepal.Width + Species,
              data=iris[iris$Species == "setosa", ]))
# Error in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]) : 
#   contrasts can be applied only to factors with 2 or more levels

If the variable is numeric (Sepal.Width) but taking only a single value say 3, then the model runs but you will get NA as coefficient of that variable as follows:

(model2 <-lm(Sepal.Length ~ Sepal.Width + Species,
             data=iris[iris$Sepal.Width == 3, ]))

# Call:
# lm(formula = Sepal.Length ~ Sepal.Width + Species, 
#    data = iris[iris$Sepal.Width == 3, ])

# Coefficients:
#       (Intercept)        Sepal.Width  Speciesversicolor   Speciesvirginica  
#             4.700                 NA              1.250              2.017

Solution: There is not enough variation in dependent variable with only one value. So, you need to drop that variable, irrespective of whether that is numeric or character or factor variable.

Updated as per comments: Since you know that the error will only occur with factor/character, you can focus only on those and see whether the length of levels of those factor variables is 1 (DROP) or greater than 1 (NODROP).

To see, whether the variable is a factor or not, use the following code:

(l <- sapply(iris, function(x) is.factor(x)))
# Sepal.Length  Sepal.Width Petal.Length  Petal.Width      Species 
#        FALSE        FALSE        FALSE        FALSE         TRUE 

Then you can get the data frame of factor variables only

m <- iris[, l]

Now, find the number of levels of factor variables, if this is one you need to drop that

ifelse(n <- sapply(m, function(x) length(levels(x))) == 1, "DROP", "NODROP")

Note: If the levels of factor variable is only one then that is the variable, you have to drop.

git rebase merge conflict

If you have a lot of commits to rebase, and some part of them are giving conflicts, that really hurts. But I can suggest a less-known approach how to "squash all the conflicts".

First, checkout temp branch and start standard merge

git checkout -b temp
git merge origin/master

You will have to resolve conflicts, but only once and only real ones. Then stage all files and finish merge.

git commit -m "Merge branch 'origin/master' into 'temp'"

Then return to your branch (let it be alpha) and start rebase, but with automatical resolving any conflicts.

git checkout alpha
git rebase origin/master -X theirs

Branch has been rebased, but project is probably in invalid state. That's OK, we have one final step. We just need to restore project state, so it will be exact as on branch 'temp'. Technically we just need to copy its tree (folder state) via low-level command git commit-tree. Plus merging into current branch just created commit.

git merge --ff $(git commit-tree temp^{tree} -m "Fix after rebase" -p HEAD)

And delete temporary branch

git branch -D temp

That's all. We did a rebase via hidden merge.

Also I wrote a script, so that can be done in a dialog manner, you can find it here.

Pass request headers in a jQuery AJAX GET call

_x000D_
_x000D_
$.ajax({_x000D_
            url: URL,_x000D_
            type: 'GET',_x000D_
            dataType: 'json',_x000D_
            headers: {_x000D_
                'header1': 'value1',_x000D_
                'header2': 'value2'_x000D_
            },_x000D_
            contentType: 'application/json; charset=utf-8',_x000D_
            success: function (result) {_x000D_
               // CallBack(result);_x000D_
            },_x000D_
            error: function (error) {_x000D_
                _x000D_
            }_x000D_
        });
_x000D_
_x000D_
_x000D_

Excel: Can I create a Conditional Formula based on the Color of a Cell?

You can use this function (I found it here: http://excelribbon.tips.net/T010780_Colors_in_an_IF_Function.html):

Function GetFillColor(Rng As Range) As Long
    GetFillColor = Rng.Interior.ColorIndex
End Function

Here is an explanation, how to create user-defined functions: http://www.wikihow.com/Create-a-User-Defined-Function-in-Microsoft-Excel

In your worksheet, you can use the following: =GetFillColor(B5)

The easiest way to transform collection to array?

With JDK/11, an alternate way of converting a Collection<Foo> to an Foo[] could be to make use of Collection.toArray(IntFunction<T[]> generator) as:

Foo[] foos = fooCollection.toArray(new Foo[0]); // before JDK 11
Foo[] updatedFoos = fooCollection.toArray(Foo[]::new); // after JDK 11

As explained by @Stuart on the mailing list(emphasis mine), the performance of this should essentially be the same as that of the existing Collection.toArray(new T[0]) --

The upshot is that implementations that use Arrays.copyOf() are the fastest, probably because it's an intrinsic.

It can avoid zero-filling the freshly allocated array because it knows the entire array contents will be overwritten. This is true regardless of what the public API looks like.

The implementation of the API within the JDK reads:

default <T> T[] toArray(IntFunction<T[]> generator) {
    return toArray(generator.apply(0));
}

The default implementation calls generator.apply(0) to get a zero-length array and then simply calls toArray(T[]). This goes through the Arrays.copyOf() fast path, so it's essentially the same speed as toArray(new T[0]).


Note:- Just that the API use shall be guided along with a backward incompatibility when used for code with null values e.g. toArray(null) since these calls would now be ambiguous because of existing toArray(T[] a) and would fail to compile.

Cannot install NodeJs: /usr/bin/env: node: No such file or directory

if you are able to access node on ubuntu terminal using nodejs command,then this problem can be simply solved using -creating a symbolic link of nodejs and node using

ln -s /usr/bin/nodejs /usr/bin/node

and this may solve the problem

How to programmatically set the layout_align_parent_right attribute of a Button in Relative Layout?

You can access any LayoutParams from code using View.getLayoutParams. You just have to be very aware of what LayoutParams your accessing. This is normally achieved by checking the containing ViewGroup if it has a LayoutParams inner child then that's the one you should use. In your case it's RelativeLayout.LayoutParams. You'll be using RelativeLayout.LayoutParams#addRule(int verb) and RelativeLayout.LayoutParams#addRule(int verb, int anchor)

You can get to it via code:

RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)button.getLayoutParams();
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
params.addRule(RelativeLayout.LEFT_OF, R.id.id_to_be_left_of);

button.setLayoutParams(params); //causes layout update

Get list of filenames in folder with Javascript

I made a different route for every file in a particular directory. Therefore, going to that path meant opening that file.

function getroutes(list){
list.forEach(function(element) {
  app.get("/"+ element,  function(req, res) {
    res.sendFile(__dirname + "/public/extracted/" + element);
  });
});

I called this function passing the list of filename in the directory __dirname/public/extracted and it created a different route for each filename which I was able to render on server side.

How can one print a size_t variable portably using the printf family?

std::size_t s = 1024;
std::cout << s; // or any other kind of stream like stringstream!

Hibernate Criteria Restrictions AND / OR combination

For the new Criteria since version Hibernate 5.2:

CriteriaBuilder criteriaBuilder = getSession().getCriteriaBuilder();
CriteriaQuery<SomeClass> criteriaQuery = criteriaBuilder.createQuery(SomeClass.class);

Root<SomeClass> root = criteriaQuery.from(SomeClass.class);

Path<Object> expressionA = root.get("A");
Path<Object> expressionB = root.get("B");

Predicate predicateAEqualX = criteriaBuilder.equal(expressionA, "X");
Predicate predicateBInXY = expressionB.in("X",Y);
Predicate predicateLeft = criteriaBuilder.and(predicateAEqualX, predicateBInXY);

Predicate predicateAEqualY = criteriaBuilder.equal(expressionA, Y);
Predicate predicateBEqualZ = criteriaBuilder.equal(expressionB, "Z");
Predicate predicateRight = criteriaBuilder.and(predicateAEqualY, predicateBEqualZ);

Predicate predicateResult = criteriaBuilder.or(predicateLeft, predicateRight);

criteriaQuery
        .select(root)
        .where(predicateResult);

List<SomeClass> list = getSession()
        .createQuery(criteriaQuery)
        .getResultList();  

Java generating Strings with placeholders

Justas answer is outdated so I'm posting up to date answer with apache text commons.

StringSubstitutor from Apache Commons Text may be used for string formatting with named placeholders: https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/StringSubstitutor.html

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-text</artifactId>
    <version>1.9</version>
</dependency>

This class takes a piece of text and substitutes all the variables within it. The default definition of a variable is ${variableName}. The prefix and suffix can be changed via constructors and set methods. Variable values are typically resolved from a map, but could also be resolved from system properties, or by supplying a custom variable resolver.

Example:

 // Build map
 Map<String, String> valuesMap = new HashMap<>();
 valuesMap.put("animal", "quick brown fox");
 valuesMap.put("target", "lazy dog");
 String templateString = "The ${animal} jumped over the ${target}.";

 // Build StringSubstitutor
 StringSubstitutor sub = new StringSubstitutor(valuesMap);

 // Replace
 String resolvedString = sub.replace(templateString);

How to convert Nonetype to int or string?

In one of the comments, you say:

Somehow I got an Nonetype value, it supposed to be an int, but it's now a Nonetype object

If it's your code, figure out how you're getting None when you expect a number and stop that from happening.

If it's someone else's code, find out the conditions under which it gives None and determine a sensible value to use for that, with the usual conditional code:

result = could_return_none(x)

if result is None:
    result = DEFAULT_VALUE

...or even...

if x == THING_THAT_RESULTS_IN_NONE:
    result = DEFAULT_VALUE
else:
    result = could_return_none(x) # But it won't return None, because we've restricted the domain.

There's no reason to automatically use 0 here — solutions that depend on the "false"-ness of None assume you will want this. The DEFAULT_VALUE (if it even exists) completely depends on your code's purpose.

Delimiters in MySQL

Delimiters other than the default ; are typically used when defining functions, stored procedures, and triggers wherein you must define multiple statements. You define a different delimiter like $$ which is used to define the end of the entire procedure, but inside it, individual statements are each terminated by ;. That way, when the code is run in the mysql client, the client can tell where the entire procedure ends and execute it as a unit rather than executing the individual statements inside.

Note that the DELIMITER keyword is a function of the command line mysql client (and some other clients) only and not a regular MySQL language feature. It won't work if you tried to pass it through a programming language API to MySQL. Some other clients like PHPMyAdmin have other methods to specify a non-default delimiter.

Example:

DELIMITER $$
/* This is a complete statement, not part of the procedure, so use the custom delimiter $$ */
DROP PROCEDURE my_procedure$$

/* Now start the procedure code */
CREATE PROCEDURE my_procedure ()
BEGIN    
  /* Inside the procedure, individual statements terminate with ; */
  CREATE TABLE tablea (
     col1 INT,
     col2 INT
  );

  INSERT INTO tablea
    SELECT * FROM table1;

  CREATE TABLE tableb (
     col1 INT,
     col2 INT
  );
  INSERT INTO tableb
    SELECT * FROM table2;
  
/* whole procedure ends with the custom delimiter */
END$$

/* Finally, reset the delimiter to the default ; */
DELIMITER ;

Attempting to use DELIMITER with a client that doesn't support it will cause it to be sent to the server, which will report a syntax error. For example, using PHP and MySQLi:

$mysqli = new mysqli('localhost', 'user', 'pass', 'test');
$result = $mysqli->query('DELIMITER $$');
echo $mysqli->error;

Errors with:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DELIMITER $$' at line 1

Save multiple sheets to .pdf

Similar to Tim's answer - but with a check for 2007 (where the PDF export is not installed by default):

Public Sub subCreatePDF()

    If Not IsPDFLibraryInstalled Then
        'Better show this as a userform with a proper link:
        MsgBox "Please install the Addin to export to PDF. You can find it at http://www.microsoft.com/downloads/details.aspx?familyid=4d951911-3e7e-4ae6-b059-a2e79ed87041". 
        Exit Sub
    End If

    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
        Filename:=ActiveWorkbook.Path & Application.PathSeparator & _
        ActiveSheet.Name & " für " & Range("SelectedName").Value & ".pdf", _
        Quality:=xlQualityStandard, IncludeDocProperties:=True, _
        IgnorePrintAreas:=False, OpenAfterPublish:=True
End Sub

Private Function IsPDFLibraryInstalled() As Boolean
'Credits go to Ron DeBruin (http://www.rondebruin.nl/pdf.htm)
    IsPDFLibraryInstalled = _
        (Dir(Environ("commonprogramfiles") & _
        "\Microsoft Shared\OFFICE" & _
        Format(Val(Application.Version), "00") & _
        "\EXP_PDF.DLL") <> "")
End Function

Where does PHP's error log reside in XAMPP?

I found it in: \xampp\php\logs\php_error_log

Document directory path of Xcode Device Simulator

If your app uses CoreData, a nifty trick is to search for the name of the sqlite file using terminal.

find ~ -name my_app_db_name.sqlite

The results will list the full file paths to any simulators that have run your app.

I really wish Apple would just add a button to the iOS Simulator file menu like "Reveal Documents folder in Finder".

How can I capitalize the first letter of each word in a string?

In case you want to downsize

# Assuming you are opening a new file
with open(input_file) as file:
    lines = [x for x in reader(file) if x]

# for loop to parse the file by line
for line in lines:
    name = [x.strip().lower() for x in line if x]
    print(name) # Check the result

Run Jquery function on window events: load, resize, and scroll?

You can bind listeners to one common functions -

$(window).bind("load resize scroll",function(e){
  // do stuff
});

Or another way -

$(window).bind({
     load:function(){

     },
     resize:function(){

     },
     scroll:function(){

    }
});

Alternatively, instead of using .bind() you can use .on() as bind directly maps to on(). And maybe .bind() won't be there in future jquery versions.

$(window).on({
     load:function(){

     },
     resize:function(){

     },
     scroll:function(){

    }
});

MySQL JOIN the most recent row only?

I know this question is old, but it's got a lot of attention over the years and I think it's missing a concept which may help someone in a similar case. I'm adding it here for completeness sake.

If you cannot modify your original database schema, then a lot of good answers have been provided and solve the problem just fine.

If you can, however, modify your schema, I would advise to add a field in your customer table that holds the id of the latest customer_data record for this customer:

CREATE TABLE customer (
  id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  current_data_id INT UNSIGNED NULL DEFAULT NULL
);

CREATE TABLE customer_data (
   id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
   customer_id INT UNSIGNED NOT NULL, 
   title VARCHAR(10) NOT NULL,
   forename VARCHAR(10) NOT NULL,
   surname VARCHAR(10) NOT NULL
);

Querying customers

Querying is as easy and fast as it can be:

SELECT c.*, d.title, d.forename, d.surname
FROM customer c
INNER JOIN customer_data d on d.id = c.current_data_id
WHERE ...;

The drawback is the extra complexity when creating or updating a customer.

Updating a customer

Whenever you want to update a customer, you insert a new record in the customer_data table, and update the customer record.

INSERT INTO customer_data (customer_id, title, forename, surname) VALUES(2, 'Mr', 'John', 'Smith');
UPDATE customer SET current_data_id = LAST_INSERT_ID() WHERE id = 2;

Creating a customer

Creating a customer is just a matter of inserting the customer entry, then running the same statements:

INSERT INTO customer () VALUES ();

SET @customer_id = LAST_INSERT_ID();
INSERT INTO customer_data (customer_id, title, forename, surname) VALUES(@customer_id, 'Mr', 'John', 'Smith');
UPDATE customer SET current_data_id = LAST_INSERT_ID() WHERE id = @customer_id;

Wrapping up

The extra complexity for creating/updating a customer might be fearsome, but it can easily be automated with triggers.

Finally, if you're using an ORM, this can be really easy to manage. The ORM can take care of inserting the values, updating the ids, and joining the two tables automatically for you.

Here is how your mutable Customer model would look like:

class Customer
{
    private int id;
    private CustomerData currentData;

    public Customer(String title, String forename, String surname)
    {
        this.update(title, forename, surname);
    }

    public void update(String title, String forename, String surname)
    {
        this.currentData = new CustomerData(this, title, forename, surname);
    }

    public String getTitle()
    {
        return this.currentData.getTitle();
    }

    public String getForename()
    {
        return this.currentData.getForename();
    }

    public String getSurname()
    {
        return this.currentData.getSurname();
    }
}

And your immutable CustomerData model, that contains only getters:

class CustomerData
{
    private int id;
    private Customer customer;
    private String title;
    private String forename;
    private String surname;

    public CustomerData(Customer customer, String title, String forename, String surname)
    {
        this.customer = customer;
        this.title    = title;
        this.forename = forename;
        this.surname  = surname;
    }

    public String getTitle()
    {
        return this.title;
    }

    public String getForename()
    {
        return this.forename;
    }

    public String getSurname()
    {
        return this.surname;
    }
}

C++ Convert string (or char*) to wstring (or wchar_t*)

int StringToWString(std::wstring &ws, const std::string &s)
{
    std::wstring wsTmp(s.begin(), s.end());

    ws = wsTmp;

    return 0;
}

Differences Between vbLf, vbCrLf & vbCr Constants

The three constants have similar functions nowadays, but different historical origins, and very occasionally you may be required to use one or the other.

You need to think back to the days of old manual typewriters to get the origins of this. There are two distinct actions needed to start a new line of text:

  1. move the typing head back to the left. In practice in a typewriter this is done by moving the roll which carries the paper (the "carriage") all the way back to the right -- the typing head is fixed. This is a carriage return.
  2. move the paper up by the width of one line. This is a line feed.

In computers, these two actions are represented by two different characters - carriage return is CR, ASCII character 13, vbCr; line feed is LF, ASCII character 10, vbLf. In the old days of teletypes and line printers, the printer needed to be sent these two characters -- traditionally in the sequence CRLF -- to start a new line, and so the CRLF combination -- vbCrLf -- became a traditional line ending sequence, in some computing environments.

The problem was, of course, that it made just as much sense to only use one character to mark the line ending, and have the terminal or printer perform both the carriage return and line feed actions automatically. And so before you knew it, we had 3 different valid line endings: LF alone (used in Unix and Macintoshes), CR alone (apparently used in older Mac OSes) and the CRLF combination (used in DOS, and hence in Windows). This in turn led to the complications of DOS / Windows programs having the option of opening files in text mode, where any CRLF pair read from the file was converted to a single CR (and vice versa when writing).

So - to cut a (much too) long story short - there are historical reasons for the existence of the three separate line separators, which are now often irrelevant: and perhaps the best course of action in .NET is to use Environment.NewLine which means someone else has decided for you which to use, and future portability issues should be reduced.

Android: I lost my android key store, what should I do?

You can create a new keystore, but the Android Market wont allow you to upload the apk as an update - worse still, if you try uploading the apk as a new app it will not allow it either as it knows there is a 'different' version of the same apk already in the market even if you delete your previous version from the market

Do your absolute best to find that keystore!!

When you find it, email it to yourself so you have a copy on your gmail that you can go and get in the case you loose it from your hard drive!

Bootstrap 3 and Youtube in Modal

Ok. I found a solution.

                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">
                        <span aria-hidden="true">&times;</span><span class="sr-only">Close</span>
                    </button>
                    <h3 class="modal-title" id="modal-login-label">Capital Get It</h3>
                    <p>Log in:</p>
                </div>

                <div class="modal-body">

                    <h4>Youtube stuff</h4>



             <iframe src="//www.youtube.com/embed/lAU0yCDKWb4" allowfullscreen="" frameborder="0" height="315" width="100%"></iframe>       
             </div>


                </div>

            </div>
        </div>
    </div>

CREATE DATABASE permission denied in database 'master' (EF code-first)

run this on your master database

ALTER SERVER ROLE sysadmin ADD MEMBER your-user;  
GO 

Random number c++ in some range

Since nobody posted the modern C++ approach yet,

#include <iostream>
#include <random>
int main()
{
    std::random_device rd; // obtain a random number from hardware
    std::mt19937 gen(rd()); // seed the generator
    std::uniform_int_distribution<> distr(25, 63); // define the range

    for(int n=0; n<40; ++n)
        std::cout << distr(gen) << ' '; // generate numbers
}

ECONNREFUSED error when connecting to mongodb from node.js

Mongodb was not running but I had the module for node.js The database path was missing. Fix was create new folder in the root so run sudo mkdir -p /data/db/ then run sudo chown id -u /data/db

How to check type of variable in Java?

Actually quite easy to roll your own tester, by abusing Java's method overload ability. Though I'm still curious if there is an official method in the sdk.

Example:

class Typetester {
    void printType(byte x) {
        System.out.println(x + " is an byte");
    }
    void printType(int x) {
        System.out.println(x + " is an int");
    }
    void printType(float x) {
        System.out.println(x + " is an float");
    }
    void printType(double x) {
        System.out.println(x + " is an double");
    }
    void printType(char x) {
        System.out.println(x + " is an char");
    }
}

then:

Typetester t = new Typetester();
t.printType( yourVariable );

How to use CURL via a proxy?

Here is a working version with your bugs removed.

$url = 'http://dynupdate.no-ip.com/ip.php';
$proxy = '127.0.0.1:8888';
//$proxyauth = 'user:password';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_PROXY, $proxy);
//curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyauth);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$curl_scraped_page = curl_exec($ch);
curl_close($ch);

echo $curl_scraped_page;

I have added CURLOPT_PROXYUSERPWD in case any of your proxies require a user name and password. I set CURLOPT_RETURNTRANSFER to 1, so that the data will be returned to $curl_scraped_page variable.

I removed a second extra curl_exec($ch); which would stop the variable being returned. I consolidated your proxy IP and port into one setting.

I also removed CURLOPT_HTTPPROXYTUNNEL and CURLOPT_CUSTOMREQUEST as it was the default.

If you don't want the headers returned, comment out CURLOPT_HEADER.

To disable the proxy simply set it to null.

curl_setopt($ch, CURLOPT_PROXY, null);

Any questions feel free to ask, I work with cURL every day.

Using different Web.config in development and production environment

I'd like to know, too. This helps isolate the problem for me

<connectionStrings configSource="connectionStrings.config"/>

I then keep a connectionStrings.config as well as a "{host} connectionStrings.config". It's still a problem, but if you do this for sections that differ in the two environments, you can deploy and version the same web.config.

(And I don't use VS, btw.)

Simple way to copy or clone a DataRow?

But to make sure that your new row is accessible in the new table, you need to close the table:

DataTable destination = new DataTable(source.TableName);
destination = source.Clone();
DataRow sourceRow = source.Rows[0];
destination.ImportRow(sourceRow);

javascript node.js next()

It's basically like a callback that express.js use after a certain part of the code is executed and done, you can use it to make sure that part of code is done and what you wanna do next thing, but always be mindful you only can do one res.send in your each REST block...

So you can do something like this as a simple next() example:

app.get("/", (req, res, next) => {
  console.log("req:", req, "res:", res);
  res.send(["data": "whatever"]);
  next();
},(req, res) =>
  console.log("it's all done!");
);

It's also very useful when you'd like to have a middleware in your app...

To load the middleware function, call app.use(), specifying the middleware function. For example, the following code loads the myLogger middleware function before the route to the root path (/).

var express = require('express');
var app = express();

var myLogger = function (req, res, next) {
  console.log('LOGGED');
  next();
}

app.use(myLogger);

app.get('/', function (req, res) {
  res.send('Hello World!');
})

app.listen(3000);

Angular 2 : No NgModule metadata found

I finally found the solution.

  1. Remove webpack by using following command.
npm remove webpack
  1. Install cli by using following command.
npm install --save-dev @angular/cli@latest

after successfully test app, it will work :)

If not then follow below steps:

  1. Delete node_module folder.
  2. Clear cache by using following command.
npm cache clean --force
  1. Install node packages by using following command.
npm install
  1. Install angular@cli by using following command.
npm install --save-dev @angular/cli@latest

Note: If failed, try step 4 again. It will work.

Eclipse - "Workspace in use or cannot be created, chose a different one."

for windows users: In case of you can't remove .lock file and it gives you the following:

enter image description here

And you know that eclipse is already closed, just open Task Manager then processes then end precess for all eclipse.exe occurrences in the processes list.

How to calculate Date difference in Hive

yes datediff is implemented; see: https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF

By the way I found this by Google-searching "hive datediff", it was the first result ;)

java.io.IOException: Invalid Keystore format

for me that issue happened because i generated .jks file on my laptop with 1.8.0_251 and i copied it on server witch had java 1.8.0_45 and when I used that .jks file in my code i got java.io.IOException: Invalid Keystore format.

to solve this issue i generated .jks file directly on the server instead of copy there from my laptop which had different java version.

Check if cookie exists else set cookie to Expire in 10 days

if (/(^|;)\s*visited=/.test(document.cookie)) {
    alert("Hello again!");
} else {
    document.cookie = "visited=true; max-age=" + 60 * 60 * 24 * 10; // 60 seconds to a minute, 60 minutes to an hour, 24 hours to a day, and 10 days.
    alert("This is your first time!");
}

is one way to do it. Note that document.cookie is a magic property, so you don't have to worry about overwriting anything, either.

There are also more convenient libraries to work with cookies, and if you don’t need the information you’re storing sent to the server on every request, HTML5’s localStorage and friends are convenient and useful.

cannot call member function without object

just add static keyword at the starting of the function return type.. and then you can access the member function of the class without object:) for ex:

static void Name_pairs::read_names()
{
   cout << "Enter name: ";
   cin >> name;
   names.push_back(name);
   cout << endl;
}

How to detect if a string contains special characters?

SELECT * FROM tableName WHERE columnName LIKE "%#%" OR columnName LIKE "%$%" OR (etc.)

HTML <select> selected option background-color CSS style

In CSS:

SELECT OPTION:checked { background-color: red; }

Is it possible in Java to access private fields via reflection

Yes it is possible.

You need to use the getDeclaredField method (instead of the getField method), with the name of your private field:

Field privateField = Test.class.getDeclaredField("str");

Additionally, you need to set this Field to be accessible, if you want to access a private field:

privateField.setAccessible(true);

Once that's done, you can use the get method on the Field instance, to access the value of the str field.

to remove first and last element in array

Creates a 1 level deep copy.

fruits.slice(1, -1)

Let go of the original array.

Thanks to @Tim for pointing out the spelling errata.

How to Inspect Element using Safari Browser

In your Safari menu bar click Safari > Preferences & then select the Advanced tab.

Select: "Show Develop menu in menu bar"

Now you can click Develop in your menu bar and choose Show Web Inspector

You can also right-click and press "Inspect element".

What is a 'Closure'?

A closure is a stateful function that is returned by another function. It acts as a container to remember variables and parameters from its parent scope even if the parent function has finished executing. Consider this simple example.

  function sayHello() {
  const greeting = "Hello World";

  return function() { // anonymous function/nameless function
    console.log(greeting)
  }
}


const hello = sayHello(); // hello holds the returned function
hello(); // -> Hello World

Look! we have a function that returns a function! The returned function gets saved to a variable and invoked the line below.

Converting HTML to Excel?

Change the content type to ms-excel in the html and browser shall open the html in the Excel as xls. If you want control over the transformation of HTML to excel use POI libraries to do so.

No module named setuptools

The question mentions Windows, and the accepted answer also works for Ubuntu, but for those who found this question coming from a Redhat flavor of Linux, this did the trick:

sudo yum install -y python-setuptools

Splitting on first occurrence

>>> s = "123mango abcd mango kiwi peach"
>>> s.split("mango", 1)
['123', ' abcd mango kiwi peach']
>>> s.split("mango", 1)[1]
' abcd mango kiwi peach'

How to Convert datetime value to yyyymmddhhmmss in SQL server?

This query is to convert the DateTimeOffset into the format yyyyMMddhhss with Offset. I have replaced the hyphens, colon(:), period(.) from the data, and kept the hyphen for the seperation of Offset from the DateTime.

SELECT REPLACE(SUBSTRING(CONVERT(VARCHAR(33),SYSDATETIMEOFFSET(),126), 1, 8), '-', '') +
SUBSTRING(REPLACE(REPLACE(REPLACE(CONVERT(VARCHAR(33), SYSDATETIMEOFFSET(), 126),'T',''),'.',''),':',''),9,DATALENGTH(CONVERT(VARCHAR(33), SYSDATETIMEOFFSET(), 126)))

How to pass params with history.push/Link/Redirect in react-router v4?

Extending the solution (suggested by Shubham Khatri) for use with React hooks (16.8 onwards):

package.json (always worth updating to latest packages)

{
     ...

     "react": "^16.12.0",
     "react-router-dom": "^5.1.2",

     ...
}

Passing parameters with history push:

import { useHistory } from "react-router-dom";

const FirstPage = props => {
    let history = useHistory();

    const someEventHandler = event => {
       history.push({
           pathname: '/secondpage',
           search: '?query=abc',
           state: { detail: 'some_value' }
       });
    };

};

export default FirstPage;


Accessing the passed parameter using useLocation from 'react-router-dom':

import { useEffect } from "react";
import { useLocation } from "react-router-dom";

const SecondPage = props => {
    const location = useLocation();

    useEffect(() => {
       console.log(location.pathname); // result: '/secondpage'
       console.log(location.search); // result: '?query=abc'
       console.log(location.state.detail); // result: 'some_value'
    }, [location]);

};

How to set image on QPushButton?

You can do this in QtDesigner. Just click on your button then go to icon property and then choose your image file.

How do I use WebRequest to access an SSL encrypted site using https?

This link will be of interest to you: http://msdn.microsoft.com/en-us/library/ds8bxk2a.aspx

For http connections, the WebRequest and WebResponse classes use SSL to communicate with web hosts that support SSL. The decision to use SSL is made by the WebRequest class, based on the URI it is given. If the URI begins with "https:", SSL is used; if the URI begins with "http:", an unencrypted connection is used.

How to allow CORS in react.js?

there are 6 ways to do this in React,

number 1 and 2 and 3 are the best:

1-config CORS in the Server-Side

2-set headers manually like this:

resonse_object.header("Access-Control-Allow-Origin", "*");
resonse_object.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

3-config NGINX for proxy_pass which is explained here.

4-bypass the Cross-Origin-Policy with chrom extension(only for development and not recommended !)

5-bypass the cross-origin-policy with URL bellow(only for development)

"https://cors-anywhere.herokuapp.com/{type_your_url_here}"

6-use proxy in your package.json file:(only for development)

if this is your API: http://45.456.200.5:7000/api/profile/

add this part in your package.json file: "proxy": "http://45.456.200.5:7000/",

and then make your request with the next parts of the api:

React.useEffect(() => {
    axios
        .get('api/profile/')
        .then(function (response) {
            console.log(response);
        })
        .catch(function (error) {
            console.log(error);
        });
});

Programmatically change the height and width of a UIImageView Xcode Swift

let screenSize: CGRect = UIScreen.mainScreen().bounds
image.frame = CGRectMake(0,0, screenSize.height * 0.2, 50)

Java ArrayList Index

Using an Array:

String[] fruits = new String[3]; // make a 3 element array
fruits[0]="apple";
fruits[1]="banana";
fruits[2]="orange";
System.out.println(fruits[1]); // output the second element

Using a List

ArrayList<String> fruits = new ArrayList<String>();
fruits.add("apple");
fruits.add("banana");
fruits.add("orange");
System.out.println(fruits.get(1));

How to add property to object in PHP >= 5.3 strict mode without generating error

If you absolutely have to add the property to the object, I believe you could cast it as an array, add your property (as a new array key), then cast it back as an object. The only time you run into stdClass objects (I believe) is when you cast an array as an object or when you create a new stdClass object from scratch (and of course when you json_decode() something - silly me for forgetting!).

Instead of:

$foo = new StdClass();
$foo->bar = '1234';

You'd do:

$foo = array('bar' => '1234');
$foo = (object)$foo;

Or if you already had an existing stdClass object:

$foo = (array)$foo;
$foo['bar'] = '1234';
$foo = (object)$foo;

Also as a 1 liner:

$foo = (object) array_merge( (array)$foo, array( 'bar' => '1234' ) );

Razor If/Else conditional operator syntax

You need to put the entire ternary expression in parenthesis. Unfortunately that means you can't use "@:", but you could do something like this:

@(deletedView ? "Deleted" : "Created by")

Razor currently supports a subset of C# expressions without using @() and unfortunately, ternary operators are not part of that set.

ld cannot find an existing library

The problem is the linker is looking for libmagic.so but you only have libmagic.so.1

A quick hack is to symlink libmagic.so.1 to libmagic.so

Database cluster and load balancing

Clustering uses shared storage of some kind (a drive cage or a SAN, for example), and puts two database front-ends on it. The front end servers share an IP address and cluster network name that clients use to connect, and they decide between themselves who is currently in charge of serving client requests.

If you're asking about a particular database server, add that to your question and we can add details on their implementation, but at its core, that's what clustering is.

jQuery UI DatePicker to show month year only

I liked the @user1857829 answer and his "extend-jquery-like-a-plugin approach". I just made a litte modification so that when you change month or year in any way the picker actually writes the date in the field. I found that I'd like that behaviour after using it a bit.

jQuery.fn.monthYearPicker = function(options) {
  options = $.extend({
    dateFormat: "mm/yy",
    changeMonth: true,
    changeYear: true,
    showButtonPanel: true,
    showAnim: "",
    onChangeMonthYear: writeSelectedDate
  }, options);
  function writeSelectedDate(year, month, inst ){
   var thisFormat = jQuery(this).datepicker("option", "dateFormat");
   var d = jQuery.datepicker.formatDate(thisFormat, new Date(year, month-1, 1));
   inst.input.val(d);
  }
  function hideDaysFromCalendar() {
    var thisCalendar = $(this);
    jQuery('.ui-datepicker-calendar').detach();
    // Also fix the click event on the Done button.
    jQuery('.ui-datepicker-close').unbind("click").click(function() {
      var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
      var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
      thisCalendar.datepicker('setDate', new Date(year, month, 1));
      thisCalendar.datepicker("hide");
    });
  }
  jQuery(this).datepicker(options).focus(hideDaysFromCalendar);
}

how to convert `content://media/external/images/media/Y` to `file:///storage/sdcard0/Pictures/X.jpg` in android?

If you just want the bitmap, This too works

InputStream inputStream = mContext.getContentResolver().openInputStream(uri);
Bitmap bmp = BitmapFactory.decodeStream(inputStream);
if( inputStream != null ) inputStream.close();

sample uri : content://media/external/images/media/12345

xls to csv converter

I would use pandas. The computationally heavy parts are written in cython or c-extensions to speed up the process and the syntax is very clean. For example, if you want to turn "Sheet1" from the file "your_workbook.xls" into the file "your_csv.csv", you just use the top-level function read_excel and the method to_csv from the DataFrame class as follows:

import pandas as pd
data_xls = pd.read_excel('your_workbook.xls', 'Sheet1', index_col=None)
data_xls.to_csv('your_csv.csv', encoding='utf-8')

Setting encoding='utf-8' alleviates the UnicodeEncodeError mentioned in other answers.

Running npm command within Visual Studio Code

Install

  • Ctrl+P, write ext install npm script runner
  • Restart VS Code

Use (two ways)

  • Ctrl+R Shift+R
  • Ctrl+P, write >npm, select run script, select the desired task

Update: Since version 1.3 Visual Studio Code has integrated terminal. To open it, use any of these methods:

  • Use the Ctrl+` keyboard shortcut.
  • Use the View | Toggle Integrated Terminal menu command.
  • From the Command Palette (Ctrl+Shift+P), use the View:Toggle Integrated Terminal command.

android image button

You can just set the onClick of an ImageView and also set it to be clickable, Or set the drawableBottom property of a regular button.

    ImageView iv = (ImageView)findViewById(R.id.ImageView01);
   iv.setOnClickListener(new OnClickListener() {
   public void onClick(View v) {
    // TODO Auto-generated method stub

   }
   });

How can I use optional parameters in a T-SQL stored procedure?

You can do in the following case,

CREATE PROCEDURE spDoSearch
   @FirstName varchar(25) = null,
   @LastName varchar(25) = null,
   @Title varchar(25) = null
AS
  BEGIN
      SELECT ID, FirstName, LastName, Title
      FROM tblUsers
      WHERE
        (@FirstName IS NULL OR FirstName = @FirstName) AND
        (@LastNameName IS NULL OR LastName = @LastName) AND
        (@Title IS NULL OR Title = @Title)
END

however depend on data sometimes better create dynamic query and execute them.

WebView and Cookies on Android

If you are using Android Lollipop i.e. SDK 21, then:

CookieManager.getInstance().setAcceptCookie(true);

won't work. You need to use:

CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);

I ran into same issue and the above line worked as a charm.

How to empty a redis database?

With redis-cli:

FLUSHDB       - Removes data from your connection's CURRENT database.
FLUSHALL      - Removes data from ALL databases.

Redis Docs: FLUSHDB, FLUSHALL

How to delete a column from a table in MySQL

ALTER TABLE `tablename` DROP `columnname`;

Or,

ALTER TABLE `tablename` DROP COLUMN `columnname`;

What is the difference between Bootstrap .container and .container-fluid classes?

.container has a max width pixel value, whereas .container-fluid is max-width 100%.

.container-fluid continuously resizes as you change the width of your window/browser by any amount.

.container resizes in chunks at several certain widths, controlled by media queries (technically we can say it’s “fixed width” because pixels values are specified, but if you stop there, people may get the impression that it can’t change size – i.e. not responsive.)

Can you Run Xcode in Linux?

If you cannot shell out thousands of dollars for a decent Mac then there is an option to run OSX and XCode in the cloud:

http://www.macincloud.com/

How do I access an access array item by index in handlebars?

In my case I wanted to access an array inside a custom helper like so,

{{#ifCond arr.[@index] "foo" }}

Which did not work, but the answer suggested by @julesbou worked.

Working code:

{{#ifCond (lookup arr @index) "" }}

Hope this helps! Cheers.

Dynamically load a JavaScript file

Something like this...

<script>
     $(document).ready(function() {
          $('body').append('<script src="https://maps.googleapis.com/maps/api/js?key=KEY&libraries=places&callback=getCurrentPickupLocation" async defer><\/script>');
     });
</script>

Is System.nanoTime() completely useless?

This doesn't seem to be a problem on a Core 2 Duo running Windows XP and JRE 1.5.0_06.

In a test with three threads I don't see System.nanoTime() going backwards. The processors are both busy, and threads go to sleep occasionally to provoke moving threads around.

[EDIT] I would guess that it only happens on physically separate processors, i.e. that the counters are synchronized for multiple cores on the same die.

What's the difference between HTML 'hidden' and 'aria-hidden' attributes?

ARIA (Accessible Rich Internet Applications) defines a way to make Web content and Web applications more accessible to people with disabilities.

The hidden attribute is new in HTML5 and tells browsers not to display the element. The aria-hidden property tells screen-readers if they should ignore the element. Have a look at the w3 docs for more details:

https://www.w3.org/WAI/PF/aria/states_and_properties#aria-hidden

Using these standards can make it easier for disabled people to use the web.

How to parse a text file with C#

One way that I've found really useful in situations like this is to go old-school and use the Jet OLEDB provider, together with a schema.ini file to read large tab-delimited files in using ADO.Net. Obviously, this method is really only useful if you know the format of the file to be imported.

public void ImportCsvFile(string filename)
{
    FileInfo file = new FileInfo(filename);

    using (OleDbConnection con = 
            new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"" +
            file.DirectoryName + "\";
            Extended Properties='text;HDR=Yes;FMT=TabDelimited';"))
    {
        using (OleDbCommand cmd = new OleDbCommand(string.Format
                                  ("SELECT * FROM [{0}]", file.Name), con))
        {
            con.Open();

            // Using a DataReader to process the data
            using (OleDbDataReader reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    // Process the current reader entry...
                }
            }

            // Using a DataTable to process the data
            using (OleDbDataAdapter adp = new OleDbDataAdapter(cmd))
            {
                DataTable tbl = new DataTable("MyTable");
                adp.Fill(tbl);

                foreach (DataRow row in tbl.Rows)
                {
                    // Process the current row...
                }
            }
        }
    }
} 

Once you have the data in a nice format like a datatable, filtering out the data you need becomes pretty trivial.

Why is this rsync connection unexpectedly closed on Windows?

This error message probably means that you either mistyped the server name or forgot to start an ssh server at server. Make absolutely certain that an ssh server is running on the server at port 22, and that it's not firewalled. You can test that with ssh user@server.

How to navigate to a directory in C:\ with Cygwin?

I'll add something that helps me out a lot with cygwin. Whenever setting up a new system, I always do this

ln -s /cygdrive/c /c

This creates a symbolic link to /cygdrive/c with a new file called /c (in the home directory)

Then you can do this in your shell

cd /c/Foo
cd /c/

Very handy.

How do I get into a non-password protected Java keystore or change the password?

The password of keystore by default is: "changeit". I functioned to my commands you entered here, for the import of the certificate. I hope you have already solved your problem.

List the queries running on SQL Server

You should try very usefull procedure sp_whoIsActive which can be found here: http://whoisactive.com and it is free.

Check if instance is of a type

As others have mentioned, the "is" keyword. However, if you're going to later cast it to that type, eg.

TForm t = (TForm)c;

Then you should use the "as" keyword.

e.g. TForm t = c as TForm.

Then you can check

if(t != null)
{
 // put TForm specific stuff here
}

Don't combine as with is because it's a duplicate check.

How to implement the ReLU function in Numpy

This is more precise implementation:

def ReLU(x):
    return abs(x) * (x > 0)

Spring - applicationContext.xml cannot be opened because it does not exist

I placed the applicationContext.xml in the src/main/java folder and it worked

git rebase: "error: cannot stat 'file': Permission denied"

If you're running webpack shut it down. Shut down your IDE as well. Should work fine after doing those things.

Aligning textviews on the left and right edges in Android layout

Dave Webb's answer did work for me. Thanks! Here my code, hope this helps someone!

<RelativeLayout
    android:background="#FFFFFF"
    android:layout_width="match_parent"
    android:minHeight="30dp"
    android:layout_height="wrap_content">
    <TextView
        android:height="25dp"
        android:layout_width="wrap_content"
        android:layout_marginLeft="20dp"
        android:text="ABA Type"
        android:padding="3dip"
        android:layout_gravity="center_vertical"
        android:gravity="left|center_vertical"
        android:layout_height="match_parent" />
    <TextView
        android:background="@color/blue"
        android:minWidth="30px"
        android:minHeight="30px"
        android:layout_column="1"
        android:id="@+id/txtABAType"
        android:singleLine="false"
        android:layout_gravity="center_vertical"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_marginRight="20dp"
        android:layout_width="wrap_content" />
</RelativeLayout>

Image: Image

git remote prune – didn't show as many pruned branches as I expected

When you use git push origin :staleStuff, it automatically removes origin/staleStuff, so when you ran git remote prune origin, you have pruned some branch that was removed by someone else. It's more likely that your co-workers now need to run git prune to get rid of branches you have removed.


So what exactly git remote prune does? Main idea: local branches (not tracking branches) are not touched by git remote prune command and should be removed manually.

Now, a real-world example for better understanding:

You have a remote repository with 2 branches: master and feature. Let's assume that you are working on both branches, so as a result you have these references in your local repository (full reference names are given to avoid any confusion):

  • refs/heads/master (short name master)
  • refs/heads/feature (short name feature)
  • refs/remotes/origin/master (short name origin/master)
  • refs/remotes/origin/feature (short name origin/feature)

Now, a typical scenario:

  1. Some other developer finishes all work on the feature, merges it into master and removes feature branch from remote repository.
  2. By default, when you do git fetch (or git pull), no references are removed from your local repository, so you still have all those 4 references.
  3. You decide to clean them up, and run git remote prune origin.
  4. git detects that feature branch no longer exists, so refs/remotes/origin/feature is a stale branch which should be removed.
  5. Now you have 3 references, including refs/heads/feature, because git remote prune does not remove any refs/heads/* references.

It is possible to identify local branches, associated with remote tracking branches, by branch.<branch_name>.merge configuration parameter. This parameter is not really required for anything to work (probably except git pull), so it might be missing.

(updated with example & useful info from comments)

Programmatically obtain the phone number of the Android phone

Wouldn't be recommending to use TelephonyManager as it requires the app to require READ_PHONE_STATE permission during runtime.

<uses-permission android:name="android.permission.READ_PHONE_STATE"/> 

Should be using Google's Play Service for Authentication, and it will able to allow User to select which phoneNumber to use, and handles multiple SIM cards, rather than us trying to guess which one is the primary SIM Card.

implementation "com.google.android.gms:play-services-auth:$play_service_auth_version"
fun main() {
    val googleApiClient = GoogleApiClient.Builder(context)
        .addApi(Auth.CREDENTIALS_API).build()

    val hintRequest = HintRequest.Builder()
        .setPhoneNumberIdentifierSupported(true)
        .build()

    val hintPickerIntent = Auth.CredentialsApi.getHintPickerIntent(
        googleApiClient, hintRequest
    )

    startIntentSenderForResult(
        hintPickerIntent.intentSender, REQUEST_PHONE_NUMBER, null, 0, 0, 0
    )
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    when (requestCode) {
        REQUEST_PHONE_NUMBER -> {
            if (requestCode == Activity.RESULT_OK) {
                val credential = data?.getParcelableExtra<Credential>(Credential.EXTRA_KEY)
                val selectedPhoneNumber = credential?.id
            }
        }
    }
}

how does array[100] = {0} set the entire array to 0?

It depends where you put this initialisation.

If the array is static as in

char array[100] = {0};

int main(void)
{
...
}

then it is the compiler that reserves the 100 0 bytes in the data segement of the program. In this case you could have omitted the initialiser.

If your array is auto, then it is another story.

int foo(void)
{
char array[100] = {0};
...
}

In this case at every call of the function foo you will have a hidden memset.

The code above is equivalent to

int foo(void)
{ 
char array[100];

memset(array, 0, sizeof(array));
....
}

and if you omit the initializer your array will contain random data (the data of the stack).

If your local array is declared static like in

int foo(void)
{ 
static char array[100] = {0};
...
}

then it is technically the same case as the first one.

Google Maps Api v3 - find nearest markers

Use computeDistanceBetween() Google map API method to calculate near marker between your location and markers list on google map.

Steps:-

  1. Create marker on google map.
    function addMarker(location) { var marker = new google.maps.Marker({ title: 'User added marker', icon: { path: google.maps.SymbolPath.BACKWARD_CLOSED_ARROW, scale: 5 }, position: location, map: map }); }

  2. On Mouse click create event for getting lat, long of your location and pass that to find_closest_marker().

    function find_closest_marker(event) {
          var distances = [];
          var closest = -1;
          for (i = 0; i < markers.length; i++) {
            var d = google.maps.geometry.spherical.computeDistanceBetween(markers[i].position, event.latLng);
            distances[i] = d;
            if (closest == -1 || d < distances[closest]) {
              closest = i;
            }
          }
          alert('Closest marker is: ' + markers[closest].getTitle());
        }
    

visit this link follow the steps. You will able to get nearer marker to your location.

Convert comma separated string of ints to int array

This is for longs, but you can modify it easily to work with ints.

private static long[] ConvertStringArrayToLongArray(string str)
{
    return str.Split(",".ToCharArray()).Select(x => long.Parse(x.ToString())).ToArray();
}

Batch file to copy directories recursively

Look into xcopy, which will recursively copy files and subdirectories.

There are examples, 2/3 down the page. Of particular use is:

To copy all the files and subdirectories (including any empty subdirectories) from drive A to drive B, type:

xcopy a: b: /s /e

Git Clone: Just the files, please?

git checkout -f

There's another way to do this by splitting the repo from the working tree.

This method is useful if you need to update these git-less git files on a regular basis. For instance, I use it when I need to check out source files and build an artifact, then copy the artifact into a different repo just for deployment to a server, and I also use it when pushing source code to a server when I want the source code to checkout and build into the www directory.

We'll make two folders, one for the git one for the working files:

mkdir workingfiles
mkdir barerepo.git

initialize a bare git repo:

cd barerepo.git
git --bare init 

Then create a post-receive hook:

touch hooks/post-receive
chmod ug+x hooks/post-receive

Edit post-receive in your favorite editor:

GIT_WORK_TREE=/path/to/workingfiles git checkout -f
# optional stuff:
cd down/to/some/directory
[do some stuff]

Add this as a remote:

git remote add myserver ssh://user@host:/path/to/barerepo.git

Now every time you push to this bare repo it will checkout the working tree to /workingfiles/. But /workingfiles/ itself is not under version control; running git status in /workingfiles/ will give the error fatal: Not a git repository (or any parent up to mount point /data). It's just plain files.

Unlike other solutions rm -r .git command is not needed, so if /workingfiles/ is some other git repo you don't have to worry about the command used removing the other repo's git files.

Oracle ORA-12154: TNS: Could not resolve service name Error?

I had a same problem and the same error was showing up. my TNSNAMES:ORA file was also good to go but apparently there was a problem due to firewall blocking the access. SO a good tip would be to make sure that firewall is not blocking the access to the datasource.

Looping through a Scripting.Dictionary using index/item number

Adding to assylias's answer - assylias shows us D.ITEMS is a method that returns an array. Knowing that, we don't need the variant array a(i) [See caveat below]. We just need to use the proper array syntax.

For i = 0 To d.Count - 1
    s = d.Items()(i)
    Debug.Print s
Next i()

KEYS works the same way

For i = 0 To d.Count - 1
    Debug.Print d.Keys()(i), d.Items()(i)
Next i

This syntax is also useful for the SPLIT function which may help make this clearer. SPLIT also returns an array with lower bounds at 0. Thus, the following prints "C".

Debug.Print Split("A,B,C,D", ",")(2)

SPLIT is a function. Its parameters are in the first set of parentheses. Methods and Functions always use the first set of parentheses for parameters, even if no parameters are needed. In the example SPLIT returns the array {"A","B","C","D"}. Since it returns an array we can use a second set of parentheses to identify an element within the returned array just as we would any array.

Caveat: This shorter syntax may not be as efficient as using the variant array a() when iterating through the entire dictionary since the shorter syntax invokes the dictionary's Items method with each iteration. The shorter syntax is best for plucking a single item by number from a dictionary.

How to solve "Unresolved inclusion: <iostream>" in a C++ file in Eclipse CDT?

I tried all previously mentioned answers, but in my case I had to manually specify the include path of the iostream file. As I use MinGW the path was:

C:\MinGW\lib\gcc\mingw32\4.8.1\include\c++

You can add the path in Eclipse under: Project > C/C++ General > Paths and Symbols > Includes > Add. I hope that helps

What are the differences between Deferred, Promise and Future in JavaScript?

These answers, including the selected answer, are good for introducing promises conceptually, but lacking in specifics of what exactly the differences are in the terminology that arises when using libraries implementing them (and there are important differences).

Since it is still an evolving spec, the answer currently comes from attempting to survey both references (like wikipedia) and implementations (like jQuery):

  • Deferred: Never described in popular references, 1 2 3 4 but commonly used by implementations as the arbiter of promise resolution (implementing resolve and reject). 5 6 7

    Sometimes deferreds are also promises (implementing then), 5 6 other times it's seen as more pure to have the Deferred only capable of resolution, and forcing the user to access the promise for using then. 7

  • Promise: The most all-encompasing word for the strategy under discussion.

    A proxy object storing the result of a target function whose synchronicity we would like to abstract, plus exposing a then function accepting another target function and returning a new promise. 2

    Example from CommonJS:

    > asyncComputeTheAnswerToEverything()
        .then(addTwo)
        .then(printResult);
    44
    

     

    Always described in popular references, although never specified as to whose responsibility resolution falls to. 1 2 3 4

    Always present in popular implementations, and never given resolution abilites. 5 6 7

  • Future: a seemingly deprecated term found in some popular references 1 and at least one popular implementation, 8 but seemingly being phased out of discussion in preference for the term 'promise' 3 and not always mentioned in popular introductions to the topic. 9

    However, at least one library uses the term generically for abstracting synchronicity and error handling, while not providing then functionality. 10 It's unclear if avoiding the term 'promise' was intentional, but probably a good choice since promises are built around 'thenables.' 2

References

  1. Wikipedia on Promises & Futures
  2. Promises/A+ spec
  3. DOM Standard on Promises
  4. DOM Standard Promises Spec WIP
  5. DOJO Toolkit Deferreds
  6. jQuery Deferreds
  7. Q
  8. FutureJS
  9. Functional Javascript section on Promises
  10. Futures in AngularJS Integration Testing

Misc potentially confusing things

How can Perl's print add a newline by default?

If you're stuck with pre-5.10, then the solutions provided above will not fully replicate the say function. For example

sub say { print @_, "\n"; }

Will not work with invocations such as

say for @arr;

or

for (@arr) {
    say;
}

... because the above function does not act on the implicit global $_ like print and the real say function.

To more closely replicate the perl 5.10+ say you want this function

sub say {
    if (@_) { print @_, "\n"; }
    else { print $_, "\n"; }
}

Which now acts like this

my @arr = qw( alpha beta gamma );
say @arr;
# OUTPUT
# alphabetagamma
#
say for @arr;
# OUTPUT
# alpha
# beta
# gamma
#

The say builtin in perl6 behaves a little differently. Invoking it with say @arr or @arr.say will not just concatenate the array items, but instead prints them separated with the list separator. To replicate this in perl5 you would do this

sub say {
    if (@_) { print join($", @_) . "\n"; }
    else { print $_ . "\n"; }
}

$" is the global list separator variable, or if you're using English.pm then is is $LIST_SEPARATOR

It will now act more like perl6, like so

say @arr;
# OUTPUT
# alpha beta gamma
#

React img tag issue with url and class

var Hello = React.createClass({
    render: function() {
      return (
        <div className="divClass">
           <img src={this.props.url} alt={`${this.props.title}'s picture`}  className="img-responsive" />
           <span>Hello {this.props.name}</span>
        </div>
      );
    }
});

regex match any whitespace

The reason I used a + instead of a '*' is because a plus is defined as one or more of the preceding element, where an asterisk is zero or more. In this case we want a delimiter that's a little more concrete, so "one or more" spaces.

word[Aa]\s+word[Bb]\s+word[Cc]

will match:

wordA wordB     wordC
worda wordb wordc
wordA   wordb   wordC

The words, in this expression, will have to be specific, and also in order (a, b, then c)

Laravel: getting a a single value from a MySQL query

[EDIT] The expected output of the pluck function has changed from Laravel 5.1 to 5.2. Hence why it is marked as deprecated in 5.1

In Laravel 5.1, pluck gets a single column's value from the first result of a query.

In Laravel 5.2, pluck gets an array with the values of a given column. So it's no longer deprecated, but it no longer do what it used to.

So short answer is use the value function if you want one column from the first row and you are using Laravel 5.1 or above.

Thanks to Tomas Buteler for pointing this out in the comments.

[ORIGINAL] For anyone coming across this question who is using Laravel 5.1, pluck() has been deprecated and will be removed completely in Laravel 5.2.

Consider future proofing your code by using value() instead.

return DB::table('users')->where('username', $username)->value('groupName');

PDOException SQLSTATE[HY000] [2002] No such file or directory

In may case, I'd simply used

vagrant up

instead of

homestead up

for my forge larval setup using homestead. I'm assuming this meant the site was getting served, but the MySQL server wasn't ever booted. When I used the latter command to launch my vagrant box, the error went away.

Convert a space delimited string to list

states_list = states.split(' ')

In regards to your edit:

from random import choice
random_state = choice(states_list)

How can I write a byte array to a file in Java?

As Sebastian Redl points out the most straight forward now java.nio.file.Files.write. Details for this can be found in the Reading, Writing, and Creating Files tutorial.


Old answer: FileOutputStream.write(byte[]) would be the most straight forward. What is the data you want to write?

The tutorials for Java IO system may be of some use to you.

Python Selenium accessing HTML source

To answer your question about getting the URL to use for urllib, just execute this JavaScript code:

url = browser.execute_script("return window.location;")

How to draw rounded rectangle in Android UI?

<shape xmlns:android="http://schemas.android.com/apk/res/android"
  android:padding="10dp"
  android:shape="rectangle">
    <solid android:color="@color/colorAccent" /> 
    <corners
      android:bottomLeftRadius="500dp"
      android:bottomRightRadius="500dp"
      android:topLeftRadius="500dp"
      android:topRightRadius="500dp" />
</shape>

Now, in which element you want to use this shape just add: android:background="@drawable/custom_round_ui_shape"

Create a new XML in drawable named "custom_round_ui_shape"

Using two CSS classes on one element

Instead of using multiple CSS classes, to address your underlying problem you can use the :focus pseudo-selector:

input[type="text"] {
   border: 1px solid grey;
   width: 40%;
   height: 30px;
   border-radius: 0;
}
input[type="text"]:focus {
   border: 1px solid #5acdff;
}

How to center a label text in WPF?

use the HorizontalContentAlignment property.

Sample

<Label HorizontalContentAlignment="Center"/>

Is the size of C "int" 2 bytes or 4 bytes?

This is a good source for answering this question.

But this question is a kind of a always truth answere "Yes. Both."

It depends on your architecture. If you're going to work on a 16-bit machine or less, it can't be 4 byte (=32 bit). If you're working on a 32-bit or better machine, its length is 32-bit.

To figure out, get you program ready to output something readable and use the "sizeof" function. That returns the size in bytes of your declared datatype. But be carfull using this with arrays.

If you're declaring int t[12]; it will return 12*4 byte. To get the length of this array, just use sizeof(t)/sizeof(t[0]). If you are going to build up a function, that should calculate the size of a send array, remember that if

typedef int array[12];
int function(array t){
    int size_of_t = sizeof(t)/sizeof(t[0]);
    return size_of_t;
}
void main(){
    array t = {1,1,1};  //remember: t= [1,1,1,0,...,0]
    int a = function(t);    //remember: sending t is just a pointer and equal to int* t
   print(a);   // output will be 1, since t will be interpreted as an int itselve. 
}

So this won't even return something different. If you define an array and try to get the length afterwards, use sizeof. If you send an array to a function, remember the send value is just a pointer on the first element. But in case one, you always knows, what size your array has. Case two can be figured out by defining two functions and miss some performance. Define function(array t) and define function2(array t, int size_of_t). Call "function(t)" measure the length by some copy-work and send the result to function2, where you can do whatever you want on variable array-sizes.

how to use getSharedPreferences in android

After reading around alot, only this worked: In class to set Shared preferences:

 SharedPreferences userDetails = getApplicationContext().getSharedPreferences("test", MODE_PRIVATE);
                    SharedPreferences.Editor edit = userDetails.edit();
                    edit.clear();
                    edit.putString("test1", "1");
                    edit.putString("test2", "2");
                    edit.commit();

In AlarmReciever:

SharedPreferences userDetails = context.getSharedPreferences("test", Context.MODE_PRIVATE);
    String test1 = userDetails.getString("test1", "");
    String test2 = userDetails.getString("test2", "");

Proper use of the IDisposable interface

Apart from its primary use as a way to control the lifetime of system resources (completely covered by the awesome answer of Ian, kudos!), the IDisposable/using combo can also be used to scope the state change of (critical) global resources: the console, the threads, the process, any global object like an application instance.

I've written an article about this pattern: http://pragmateek.com/c-scope-your-global-state-changes-with-idisposable-and-the-using-statement/

It illustrates how you can protect some often used global state in a reusable and readable manner: console colors, current thread culture, Excel application object properties...

Adding 1 hour to time variable

2020 Update

It is weird that no one has suggested the OOP way:

$date = new \DateTime(); //now
$date->add(new \DateInterval('PT3600S'));//add 3600s / 1 hour

OR

$date = new \DateTime(); //now
$date->add(new \DateInterval('PT60M'));//add 60 min / 1 hour

OR

$date = new \DateTime(); //now
$date->add(new \DateInterval('PT1H'));//add 1 hour

Extract it in string with format:

var_dump($date->format('Y-m-d H:i:s'));

I hope it helps

Finding Key associated with max Value in a Java Map

Is this solution ok?

int[] a = { 1, 2, 3, 4, 5, 6, 7, 7, 7, 7 };
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i : a) {
Integer count = map.get(i);
map.put(i, count != null ? count + 1 : 0);
}
Integer max = Collections.max(map.keySet());
System.out.println(max);
System.out.println(map);

How to detect when facebook's FB.init is complete

Update on Jan 04, 2012

It seems like you can't just call FB-dependent methods (for example FB.getAuthResponse()) right after FB.init() like before, as FB.init() seems to be asynchronous now. Wrapping your code into FB.getLoginStatus() response seems to do the trick of detecting when API is fully ready:

window.fbAsyncInit = function() {
    FB.init({
        //...
    });

    FB.getLoginStatus(function(response){
        runFbInitCriticalCode(); 
    });

};  

or if using fbEnsureInit() implementation from below:

window.fbAsyncInit = function() {
    FB.init({
        //...
    });

    FB.getLoginStatus(function(response){
        fbApiInit = true;
    });

};  

Original Post:

If you want to just run some script when FB is initialized you can put some callback function inside fbAsyncInit:

  window.fbAsyncInit = function() {
    FB.init({
      appId  : '<?php echo $conf['fb']['appid']; ?>',
      status : true, // check login status
      cookie : true, // enable cookies to allow the server to access the session
      xfbml  : true  // parse XFBML
    });
    FB.Canvas.setAutoResize();

    runFbInitCriticalCode(); //function that contains FB init critical code
  };

If you want exact replacement of FB.ensureInit then you would have to write something on your own as there is no official replacement (big mistake imo). Here is what I use:

  window.fbAsyncInit = function() {
    FB.init({
      appId  : '<?php echo $conf['fb']['appid']; ?>',
      status : true, // check login status
      cookie : true, // enable cookies to allow the server to access the session
      xfbml  : true  // parse XFBML
    });
    FB.Canvas.setAutoResize();

    fbApiInit = true; //init flag
  };

  function fbEnsureInit(callback) {
        if(!window.fbApiInit) {
            setTimeout(function() {fbEnsureInit(callback);}, 50);
        } else {
            if(callback) {
                callback();
            }
        }
    }

Usage:

fbEnsureInit(function() {
    console.log("this will be run once FB is initialized");
});

Reference to non-static member function must be called

The problem is that buttonClickedEvent is a member function and you need a pointer to member in order to invoke it.

Try this:

void (MyClass::*func)(int);
func = &MyClass::buttonClickedEvent;

And then when you invoke it, you need an object of type MyClass to do so, for example this:

(this->*func)(<argument>);

http://www.codeguru.com/cpp/cpp/article.php/c17401/C-Tutorial-PointertoMember-Function.htm

Make ABC Ordered List Items Have Bold Style

I know this question is a little old, but it still comes up first in a lot of Google searches. I wanted to add in a solution that doesn't involve editing the style sheet (in my case, I didn't have access):

_x000D_
_x000D_
<ol type="A">_x000D_
  <li style="font-weight: bold;">_x000D_
    <p><span style="font-weight: normal;">Text</span></p>_x000D_
  </li>_x000D_
  <li style="font-weight: bold;">_x000D_
    <p><span style="font-weight: normal;">More text</span></p>_x000D_
  </li>_x000D_
</ol>
_x000D_
_x000D_
_x000D_

Force browser to download image files on click

<html>
<head>
<script type="text/javascript">
function prepHref(linkElement) {
    var myDiv = document.getElementById('Div_contain_image');
    var myImage = myDiv.children[0];
    linkElement.href = myImage.src;
}
</script>
</head>
<body>
<div id="Div_contain_image"><img src="YourImage.jpg" alt='MyImage'></div>
<a href="#" onclick="prepHref(this)" download>Click here to download image</a>
</body>
</html>

Creating a blurring overlay view

An important supplement to @Joey's answer

This applies to a situation where you want to present a blurred-background UIViewController with UINavigationController.

// suppose you've done blur effect with your presented view controller
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController];

// this is very important, if you don't do this, the blur effect will darken after view did appeared
// the reason is that you actually present navigation controller, not presented controller
// please note it's "OverFullScreen", not "OverCurrentContext"
nav.modalPresentationStyle = UIModalPresentationOverFullScreen;

UIViewController *presentedViewController = [[UIViewController alloc] init]; 
// the presented view controller's modalPresentationStyle is "OverCurrentContext"
presentedViewController.modalPresentationStyle = UIModalPresentationOverCurrentContext;

[presentingViewController presentViewController:nav animated:YES completion:nil];

Enjoy!

Couldn't process file resx due to its being in the Internet or Restricted zone or having the mark of the web on the file

Although this is an older question, I spent several hours tracking down a way to handle this error when it applies to multiple files that are located in sub folders throughout the project.

To fix this for all files within a project, Visual Studio -> Tools -> Options -> Trust Settings and add the project path as a trusted path.

Visual Studio trusted paths

Unicode character for "X" cancel / close?

? works really well. The HTML code is &#10006;.

An alternative is &#x2715: ?

Pass value to iframe from a window

Incase you're using angular and an iframe inside, you'll need need to listen to the iframe to finish loading. You can do something like this:

         document.getElementsByTagName("iframe")[0].addEventListener('load', () => {
            document.getElementsByTagName("iframe")[0].contentWindow.postMessage(
                {
                    call: 'sendValue',
                    value: 'data'
                },
                window.location.origin)
        })

You will have to get the iframe one way or another (there are better ways to do it in angular) and then wait for it to load. Or else the listener won't be attached to it even if you do it inside lifecycle methods like ngAfterViewInit()

Exclude Blank and NA in R

Don't know exactly what kind of dataset you have, so I provide general answer.

x <- c(1,2,NA,3,4,5)
y <- c(1,2,3,NA,6,8)
my.data <- data.frame(x, y)
> my.data
   x  y
1  1  1
2  2  2
3 NA  3
4  3 NA
5  4  6
6  5  8
# Exclude rows with NA values
my.data[complete.cases(my.data),]
  x y
1 1 1
2 2 2
5 4 6
6 5 8

How to use MySQL DECIMAL?

DOUBLE columns are not the same as DECIMAL columns, and you will get in trouble if you use DOUBLE columns for financial data.

DOUBLE is actually just a double precision (64 bit instead of 32 bit) version of FLOAT. Floating point numbers are approximate representations of real numbers and they are not exact. In fact, simple numbers like 0.01 do not have an exact representation in FLOAT or DOUBLE types.

DECIMAL columns are exact representations, but they take up a lot more space for a much smaller range of possible numbers. To create a column capable of holding values from 0.0001 to 99.9999 like you asked you would need the following statement

CREATE TABLE your_table
(
    your_column DECIMAL(6,4) NOT NULL
);

The column definition follows the format DECIMAL(M, D) where M is the maximum number of digits (the precision) and D is the number of digits to the right of the decimal point (the scale).

This means that the previous command creates a column that accepts values from -99.9999 to 99.9999. You may also create an UNSIGNED DECIMAL column, ranging from 0.0000 to 99.9999.

For more information on MySQL DECIMAL the official docs are always a great resource.

Bear in mind that all of this information is true for versions of MySQL 5.0.3 and greater. If you are using previous versions, you really should upgrade.

How to build an APK file in Eclipse?

Right click on the project in Eclipse -> Android tools -> Export without signed key. Connect your device. Mount it by sdk/tools.

How to change the color of winform DataGridview header?

dataGridView1.EnableHeadersVisualStyles = false;
dataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Blue;

How to update the constant height constraint of a UIView programmatically?

First connect the Height constraint in to our viewcontroller for creating IBOutlet like the below code shown

@IBOutlet weak var select_dateHeight: NSLayoutConstraint!

then put the below code in view did load or inside any actions

self.select_dateHeight.constant = 0 // we can change the height value

if it is inside a button click

@IBAction func Feedback_button(_ sender: Any) {
 self.select_dateHeight.constant = 0

}

How to get year/month/day from a date object?

I am using this which works if you pass it a date obj or js timestamp:

getHumanReadableDate: function(date) {
    if (date instanceof Date) {
         return date.getDate() + "/" + (date.getMonth() + 1) + "/" + date.getFullYear();
    } else if (isFinite(date)) {//timestamp
        var d = new Date();
        d.setTime(date);
        return this.getHumanReadableDate(d);
    }
}

How to fix "Attempted relative import in non-package" even with __init__.py

If someone is looking for a workaround, I stumbled upon one. Here's a bit of context. I wanted to test out one of the methods I've in a file. When I run it from within

if __name__ == "__main__":

it always complained of the relative imports. I tried to apply the above solutions, but failed to work, since there were many nested files, each with multiple imports.

Here's what I did. I just created a launcher, an external program that would import necessary methods and call them. Though, not a great solution, it works.

How can I get all the request headers in Django?

<b>request.META</b><br>
{% for k_meta, v_meta in request.META.items %}
  <code>{{ k_meta }}</code> : {{ v_meta }} <br>
{% endfor %}

What function is to replace a substring from a string in C?

As strings in C can not dynamically grow inplace substitution will generally not work. Therefore you need to allocate space for a new string that has enough room for your substitution and then copy the parts from the original plus the substitution into the new string. To copy the parts you would use strncpy.

How to change the Text color of Menu item in Android?

Options menu in android can be customized to set the background or change the text appearance. The background and text color in the menu couldn’t be changed using themes and styles. The android source code (data\res\layout\icon_menu_item_layout.xml)uses a custom item of class “com.android.internal.view.menu.IconMenuItem”View for the menu layout. We can make changes in the above class to customize the menu. To achieve the same, use LayoutInflater factory class and set the background and text color for the view.


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.my_menu, menu);
    getLayoutInflater().setFactory(new Factory() {
        @Override
        public View onCreateView(String name, Context context, AttributeSet attrs) {
            if (name .equalsIgnoreCase(“com.android.internal.view.menu.IconMenuItemView”)) {
                try{
                    LayoutInflater f = getLayoutInflater();
                    final View view = f.createView(name, null, attrs);
                    new Handler().post(new Runnable() {
                        public void run() {
                            // set the background drawable
                            view .setBackgroundResource(R.drawable.my_ac_menu_background);

                            // set the text color
                            ((TextView) view).setTextColor(Color.WHITE);
                        }
                    });
                    return view;
                } catch (InflateException e) {
                    } catch (ClassNotFoundException e) {}
            }
            return null;
        }
    });
    return super.onCreateOptionsMenu(menu);
}


Error:Execution failed for task ':app:compileDebugKotlin'. > Compilation error. See log for more details

in my case I accidentally changed version="1.0" to xml version="1.0" in my XML file.

I only had to change it back.

if you have the same problem and the solutions above didn't work for you. open Gradle Console and scroll to Run with --debug option click it and it will show you more useful info about your error.

some notes:

this error doesn't appear directly after I make the change in XML it appear only after I change some java code. I think it has something to do with the instant run and build cash.

How to check if an user is logged in Symfony2 inside a controller?

It's good practise to extend from a baseController and implement some base functions implement a function to check if the user instance is null like this if the user form the Userinterface then there is no user logged in

/**

*/
class BaseController extends AbstractController
{

    /**
     * @return User

     */
    protected function getUser(): ?User
    {
        return parent::getUser();
    }

    /**
     * @return bool
     */
    protected function isUserLoggedIn(): bool
    {
        return $this->getUser() instanceof User;
    }
}

C# string reference type?

Try:


public static void TestI(ref string test)
    {
        test = "after passing";
    }

Display the current date and time using HTML and Javascript with scrollable effects in hta application

Try this one:

HTML:

<div id="para1"></div>

JavaScript:

document.getElementById("para1").innerHTML = formatAMPM();

function formatAMPM() {
var d = new Date(),
    minutes = d.getMinutes().toString().length == 1 ? '0'+d.getMinutes() : d.getMinutes(),
    hours = d.getHours().toString().length == 1 ? '0'+d.getHours() : d.getHours(),
    ampm = d.getHours() >= 12 ? 'pm' : 'am',
    months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],
    days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
return days[d.getDay()]+' '+months[d.getMonth()]+' '+d.getDate()+' '+d.getFullYear()+' '+hours+':'+minutes+ampm;
}

Result:

Mon Sep 18 2017 12:40pm

How to check currently internet connection is available or not in android

This function works fine...

public void checkConnection()
    {
        ConnectivityManager connectivityManager=(ConnectivityManager)

                this.getSystemService(Context.CONNECTIVITY_SERVICE);


  NetworkInfo wifi=connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);


 NetworkInfo  network=connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);


        if (wifi.isConnected())
        {
           //Internet available

        }
        else if(network.isConnected())
        {
             //Internet available


        }
        else
        {
             //Internet is not available
        }
    }

Add the permission to AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Updating Python on Mac

Instal aws cli via homebrew package manager. It is the simplest and easiest method.

  1. If you dont have homebrew installed , enter this command in your terminal

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

  1. Next 'brew install awscli'

This will install aws cli on your mac

Get and set position with jQuery .offset()

It's doable but you have to know that using offset() sets the position of the element relative to the document:

$('.layer1').offset( $('.layer2').offset() );

Android Overriding onBackPressed()

You may just call the onBackPressed()and if you want some activity to display after the back button you have mention the

Intent intent = new Intent(ResetPinActivity.this, MenuActivity.class);
    startActivity(intent);
    finish();

that worked for me.

HTML table sort

Another approach to sort HTML table. (based on W3.JS HTML Sort)

_x000D_
_x000D_
let tid = "#usersTable";_x000D_
let headers = document.querySelectorAll(tid + " th");_x000D_
_x000D_
// Sort the table element when clicking on the table headers_x000D_
headers.forEach(function(element, i) {_x000D_
  element.addEventListener("click", function() {_x000D_
    w3.sortHTML(tid, ".item", "td:nth-child(" + (i + 1) + ")");_x000D_
  });_x000D_
});
_x000D_
th {_x000D_
  cursor: pointer;_x000D_
  background-color: coral;_x000D_
}
_x000D_
<script src="https://www.w3schools.com/lib/w3.js"></script>_x000D_
<link href="https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet" />_x000D_
<p>Click the <strong>table headers</strong> to sort the table accordingly:</p>_x000D_
_x000D_
<table id="usersTable" class="w3-table-all">_x000D_
  <!--     _x000D_
  <tr>_x000D_
    <th onclick="w3.sortHTML('#usersTable', '.item', 'td:nth-child(1)')">Name</th>_x000D_
    <th onclick="w3.sortHTML('#usersTable', '.item', 'td:nth-child(2)')">Address</th>_x000D_
    <th onclick="w3.sortHTML('#usersTable', '.item', 'td:nth-child(3)')">Sales Person</th>_x000D_
  </tr> _x000D_
  -->_x000D_
  <tr>_x000D_
    <th>Name</th>_x000D_
    <th>Address</th>_x000D_
    <th>Sales Person</th>_x000D_
  </tr>_x000D_
_x000D_
  <tr class="item">_x000D_
    <td>user:2911002</td>_x000D_
    <td>UK</td>_x000D_
    <td>Melissa</td>_x000D_
  </tr>_x000D_
  <tr class="item">_x000D_
    <td>user:2201002</td>_x000D_
    <td>France</td>_x000D_
    <td>Justin</td>_x000D_
  </tr>_x000D_
  <tr class="item">_x000D_
    <td>user:2901092</td>_x000D_
    <td>San Francisco</td>_x000D_
    <td>Judy</td>_x000D_
  </tr>_x000D_
  <tr class="item">_x000D_
    <td>user:2801002</td>_x000D_
    <td>Canada</td>_x000D_
    <td>Skipper</td>_x000D_
  </tr>_x000D_
  <tr class="item">_x000D_
    <td>user:2901009</td>_x000D_
    <td>Christchurch</td>_x000D_
    <td>Alex</td>_x000D_
  </tr>_x000D_
_x000D_
</table>
_x000D_
_x000D_
_x000D_

Angular and Typescript: Can't find names - Error: cannot find name

If npm install -g typings typings install still does not help, delete node_modules and typings folders before executing this command.

Load CSV data into MySQL in Python

If it is a pandas data frame you could do:

Sending the data

csv_data.to_sql=(con=mydb, name='<the name of your table>',
  if_exists='replace', flavor='mysql')

to avoid the use of the for.

Lock screen orientation (Android)

In the Manifest, you can set the screenOrientation to landscape. It would look something like this in the XML:

<activity android:name="MyActivity"
android:screenOrientation="landscape"
android:configChanges="keyboardHidden|orientation|screenSize">
...
</activity>

Where MyActivity is the one you want to stay in landscape.

The android:configChanges=... line prevents onResume(), onPause() from being called when the screen is rotated. Without this line, the rotation will stay as you requested but the calls will still be made.

Note: keyboardHidden and orientation are required for < Android 3.2 (API level 13), and all three options are required 3.2 or above, not just orientation.

Print to the same line and not a new line?

In Python 3.3+ you don’t need sys.stdout.flush(). print(string, end='', flush=True) works.

So

print('foo', end='')
print('\rbar', end='', flush=True)

will overwrite ‘foo’ with ‘bar’.

Select NOT IN multiple columns

Another mysteriously unknown RDBMS. Your Syntax is perfectly fine in PostgreSQL. Other query styles may perform faster (especially the NOT EXISTS variant or a LEFT JOIN), but your query is perfectly legit.

Be aware of pitfalls with NOT IN, though, when involving any NULL values:

Variant with LEFT JOIN:

SELECT *
FROM   friend f
LEFT   JOIN likes l USING (id1, id2)
WHERE  l.id1 IS NULL;

See @Michal's answer for the NOT EXISTS variant.
A more detailed assessment of four basic variants:

Provide static IP to docker containers via docker-compose

I was facing some difficulties with an environment variable that is with custom name (not with container name /port convention for KAPACITOR_BASE_URL and KAPACITOR_ALERTS_ENDPOINT). If we give service name in this case it wouldn't resolve the ip as

KAPACITOR_BASE_URL:  http://kapacitor:9092

In above http://[**kapacitor**]:9092 would not resolve to http://172.20.0.2:9092

I resolved the static IPs issues using subnetting configurations.

version: "3.3"

networks:
  frontend:
    ipam:
      config:
        - subnet: 172.20.0.0/24
services:
    db:
        image: postgres:9.4.4
        networks:
            frontend:
                ipv4_address: 172.20.0.5
        ports:
            - "5432:5432"
        volumes:
            - postgres_data:/var/lib/postgresql/data

    redis:
        image: redis:latest
        networks:
            frontend:
                ipv4_address: 172.20.0.6
        ports:
            - "6379"

    influxdb:
        image: influxdb:latest
        ports:
            - "8086:8086"
            - "8083:8083"
        volumes:
            - ../influxdb/influxdb.conf:/etc/influxdb/influxdb.conf
            - ../influxdb/inxdb:/var/lib/influxdb
        networks:
            frontend:
                ipv4_address: 172.20.0.4
        environment:
          INFLUXDB_HTTP_AUTH_ENABLED: "false"
          INFLUXDB_ADMIN_ENABLED: "true"
          INFLUXDB_USERNAME: "db_username"
          INFLUXDB_PASSWORD: "12345678"
          INFLUXDB_DB: db_customers

    kapacitor:
        image: kapacitor:latest
        ports: 
            - "9092:9092"
        networks:
            frontend:
                ipv4_address: 172.20.0.2
        depends_on:
            - influxdb
        volumes:
            - ../kapacitor/kapacitor.conf:/etc/kapacitor/kapacitor.conf
            - ../kapacitor/kapdb:/var/lib/kapacitor
        environment:
          KAPACITOR_INFLUXDB_0_URLS_0: http://influxdb:8086

    web:
        build: .
        environment:
          RAILS_ENV: $RAILS_ENV
        command: bundle exec rails s -b 0.0.0.0
        ports:
            - "3000:3000"
        networks:
            frontend:
                ipv4_address: 172.20.0.3
        links:
            - db
            - kapacitor
        depends_on:
            - db
        volumes:
            - .:/var/app/current
        environment:
          DATABASE_URL: postgres://postgres@db
          DATABASE_USERNAME: postgres
          DATABASE_PASSWORD: postgres
          INFLUX_URL: http://influxdb:8086
          INFLUX_USER: db_username
          INFLUX_PWD: 12345678
          KAPACITOR_BASE_URL:  http://172.20.0.2:9092
          KAPACITOR_ALERTS_ENDPOINT: http://172.20.0.3:3000

volumes:
  postgres_data:

How do I make a simple makefile for gcc on Linux?

Depending on the number of headers and your development habits, you may want to investigate gccmakedep. This program examines your current directory and adds to the end of the makefile the header dependencies for each .c/cpp file. This is overkill when you have 2 headers and one program file. However, if you have 5+ little test programs and you are editing one of 10 headers, you can then trust make to rebuild exactly those programs which were changed by your modifications.

Angular 4 - Select default value in dropdown [Reactive Forms]

In your component -

Make sure to initialize the formControl name country with a value.

For instance: Assuming that your form group name is myForm and _fb is FormBuilder instance then,

....
this.myForm = this._fb.group({
  country:[this.default]
})

and also try replacing [value] with [ngValue].

EDIT 1: If you are unable to initialize the value when declaring then set the value when you have the value like this.

this.myForm.controls.country.controls.setValue(this.country) 

Reload the page after ajax success

BrixenDK is right.

.ajaxStop() callback executed when all ajax call completed. This is a best place to put your handler.

$(document).ajaxStop(function(){
    window.location.reload();
});

JQuery Ajax - How to Detect Network Connection error when making Ajax call

Since I can't duplicate the issue I can only suggest to try with a timeout on the ajax call. In jQuery you can set it with the $.ajaxSetup (and it will be global for all your $.ajax calls) or you can set it specifically for your call like this:

$.ajax({
    type: 'GET',
    url: 'http://www.mywebapp.com/keepAlive',
    timeout: 15000,
    success: function(data) {},
    error: function(XMLHttpRequest, textStatus, errorThrown) {}
})

JQuery will register a 15 seconds timeout on your call; after that without an http response code from the server jQuery will execute the error callback with the textStatus value set to "timeout". With this you can at least stop the ajax call but you won't be able to differentiate the real network issues from the loss of connections.

How to overcome TypeError: unhashable type: 'list'

Note: This answer does not explicitly answer the asked question. the other answers do it. Since the question is specific to a scenario and the raised exception is general, This answer points to the general case.

Hash values are just integers which are used to compare dictionary keys during a dictionary lookup quickly.

Internally, hash() method calls __hash__() method of an object which are set by default for any object.

Converting a nested list to a set

>>> a = [1,2,3,4,[5,6,7],8,9]
>>> set(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

This happens because of the list inside a list which is a list which cannot be hashed. Which can be solved by converting the internal nested lists to a tuple,

>>> set([1, 2, 3, 4, (5, 6, 7), 8, 9])
set([1, 2, 3, 4, 8, 9, (5, 6, 7)])

Explicitly hashing a nested list

>>> hash([1, 2, 3, [4, 5,], 6, 7])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'


>>> hash(tuple([1, 2, 3, [4, 5,], 6, 7]))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

>>> hash(tuple([1, 2, 3, tuple([4, 5,]), 6, 7]))
-7943504827826258506

The solution to avoid this error is to restructure the list to have nested tuples instead of lists.

How to call a Python function from Node.js

/*eslint-env es6*/
/*global require*/
/*global console*/
var express = require('express'); 
var app = express();

// Creates a server which runs on port 3000 and  
// can be accessed through localhost:3000
app.listen(3000, function() { 
    console.log('server running on port 3000'); 
} ) 

app.get('/name', function(req, res) {

    console.log('Running');

    // Use child_process.spawn method from  
    // child_process module and assign it 
    // to variable spawn 
    var spawn = require("child_process").spawn;   
    // Parameters passed in spawn - 
    // 1. type_of_script 
    // 2. list containing Path of the script 
    //    and arguments for the script  

    // E.g : http://localhost:3000/name?firstname=Levente
    var process = spawn('python',['apiTest.py', 
                        req.query.firstname]);

    // Takes stdout data from script which executed 
    // with arguments and send this data to res object
    var output = '';
    process.stdout.on('data', function(data) {

        console.log("Sending Info")
        res.end(data.toString('utf8'));
    });

    console.log(output);
}); 

This worked for me. Your python.exe must be added to you path variables for this code snippet. Also, make sure your python script is in your project folder.

How do I delete from multiple tables using INNER JOIN in SQL server

You can take advantage of the "deleted" pseudo table in this example. Something like:

begin transaction;

   declare @deletedIds table ( id int );

   delete from t1
   output deleted.id into @deletedIds
   from table1 as t1
    inner join table2 as t2
      on t2.id = t1.id
    inner join table3 as t3
      on t3.id = t2.id;

   delete from t2
   from table2 as t2
    inner join @deletedIds as d
      on d.id = t2.id;

   delete from t3
   from table3 as t3 ...

commit transaction;

Obviously you can do an 'output deleted.' on the second delete as well, if you needed something to join on for the third table.

As a side note, you can also do inserted.* on an insert statement, and both inserted.* and deleted.* on an update statement.

EDIT: Also, have you considered adding a trigger on table1 to delete from table2 + 3? You'll be inside of an implicit transaction, and will also have the "inserted." and "deleted." pseudo-tables available.

In a unix shell, how to get yesterday's date into a variable?

Try the following method:

dt=`case "$OSTYPE" in darwin*) date -v-1d "+%s"; ;; *) date -d "1 days ago" "+%s"; esac`
echo $dt

It works on both Linux and OSX.

Javascript: Easier way to format numbers?

Here's the YUI version if anyone's interested:

http://developer.yahoo.com/yui/docs/YAHOO.util.Number.html

var str = YAHOO.util.Number.format(12345, { thousandsSeparator: ',' } );

Using AND/OR in if else PHP statement

There's some joking, and misleading comments, even partially incorrect information in the answers here. I'd like to try to improve on them:

First, as some have pointed out, you have a bug in your code that relates to the question:

if ($status = 'clear' AND $pRent == 0)

should be (note the == instead of = in the first part):

if ($status == 'clear' AND $pRent == 0)

which in this case is functionally equivalent to

if ($status == 'clear' && $pRent == 0)

Second, note that these operators (and or && ||) are short-circuit operators. That means if the answer can be determined with certainty from the first expression, the second one is never evaluated. Again this doesn't matter for your debugged line above, but it is extremely important when you are combining these operators with assignments, because

Third, the real difference between and or and && || is their operator precedence. Specifically the importance is that && || have higher precedence than the assignment operators (= += -= *= **= /= .= %= &= |= ^= <<= >>=) while and or have lower precendence than the assignment operators. Thus in a statement that combines the use of assignment and logical evaluation it matters which one you choose.

Modified examples from PHP's page on logical operators:

$e = false || true;

will evaluate to true and assign that value to $e, because || has higher operator precedence than =, and therefore it essentially evaluates like this:

$e = (false || true);

however

$e = false or true;

will assign false to $e (and then perform the or operation and evaluate true) because = has higher operator precedence than or, essentially evaluating like this:

($e = false) or true;

The fact that this ambiguity even exists makes a lot of programmers just always use && || and then everything works clearly as one would expect in a language like C, ie. logical operations first, then assignment.

Some languages like Perl use this kind of construct frequently in a format similar to this:

$connection = database_connect($parameters) or die("Unable to connect to DB.");

This would theoretically assign the database connection to $connection, or if that failed (and we're assuming here the function would return something that evalues to false in that case), it will end the script with an error message. Because of short-circuiting, if the database connection succeeds, the die() is never evaluated.

Some languages that allow for this construct straight out forbid assignments in conditional/logical statements (like Python) to remove the amiguity the other way round.

PHP went with allowing both, so you just have to learn about your two options once and then code how you'd like, but hopefully you'll be consistent one way or another.

Whenever in doubt, just throw in an extra set of parenthesis, which removes all ambiguity. These will always be the same:

$e = (false || true);
$e = (false or true);

Armed with all that knowledge, I prefer using and or because I feel that it makes the code more readable. I just have a rule not to combine assignments with logical evaluations. But at that point it's just a preference, and consistency matters a lot more here than which side you choose.

Pass element ID to Javascript function

This'll work:

<!DOCTYPE HTML>
<html>
    <head>
        <script type="text/javascript">
            function myFunc(id)
            {
                alert(id);
            }
        </script>
    </head>

    <body>
        <button id="button1" class="MetroBtn" onClick="myFunc(this.id);">Btn1</button>
        <button id="button2" class="MetroBtn" onClick="myFunc(this.id);">Btn2</button>
        <button id="button3" class="MetroBtn" onClick="myFunc(this.id);">Btn3</button>
        <button id="button4" class="MetroBtn" onClick="myFunc(this.id);">Btn4</button>
    </body>
</html>

Calculate summary statistics of columns in dataframe

Now there is the pandas_profiling package, which is a more complete alternative to df.describe().

If your pandas dataframe is df, the below will return a complete analysis including some warnings about missing values, skewness, etc. It presents histograms and correlation plots as well.

import pandas_profiling
pandas_profiling.ProfileReport(df)

See the example notebook detailing the usage.

Where is the correct location to put Log4j.properties in an Eclipse project?

In general I put it in a special folder "res" or "resources as already said, but after for the web application, I copy the log4j.properties with the ant task to the WEB-INF/classes directory. It is the same like letting the file at the root of the src/ folder but generally I prefer to see it in a dedicated folder.

With Maven, the usual place to put is in the folder src/main/resources as answered in this other post. All resources there will go to your build in the root classpath (e.g. target/classes/)

If you want a powerful logger, you can have also a look to slf4j library which is a logger facade and can use the log4j implementation behind.

Writing List of Strings to Excel CSV File in Python

Very simple to fix, you just need to turn the parameter to writerow into a list.

for item in RESULTS:
     wr.writerow([item,])

How to add the text "ON" and "OFF" to toggle button

try this

_x000D_
_x000D_
.switch {_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
  width: 60px;_x000D_
  height: 34px;_x000D_
}_x000D_
_x000D_
.switch input {display:none;}_x000D_
_x000D_
.slider {_x000D_
  position: absolute;_x000D_
  cursor: pointer;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  bottom: 0;_x000D_
  background-color: #ccc;_x000D_
  -webkit-transition: .4s;_x000D_
  transition: .4s;_x000D_
}_x000D_
_x000D_
.slider:before {_x000D_
  position: absolute;_x000D_
  content: "";_x000D_
  height: 26px;_x000D_
  width: 26px;_x000D_
  left: 4px;_x000D_
  bottom: 4px;_x000D_
  background-color: white;_x000D_
  -webkit-transition: .4s;_x000D_
  transition: .4s;_x000D_
}_x000D_
_x000D_
input:checked + .slider {_x000D_
  background-color: #2196F3;_x000D_
}_x000D_
_x000D_
input:focus + .slider {_x000D_
  box-shadow: 0 0 1px #2196F3;_x000D_
}_x000D_
_x000D_
input:checked + .slider:before {_x000D_
  -webkit-transform: translateX(26px);_x000D_
  -ms-transform: translateX(26px);_x000D_
  transform: translateX(26px);_x000D_
}_x000D_
_x000D_
/* Rounded sliders */_x000D_
.slider.round {_x000D_
  border-radius: 34px;_x000D_
}_x000D_
_x000D_
.slider.round:before {_x000D_
  border-radius: 50%;_x000D_
}
_x000D_
<!doctype html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<title>Untitled Document</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
<h2>Toggle Switch</h2>_x000D_
_x000D_
<label class="switch">_x000D_
  <input type="checkbox">_x000D_
  <div class="slider"></div>_x000D_
</label>_x000D_
_x000D_
<label class="switch">_x000D_
  <input type="checkbox" checked>_x000D_
  <div class="slider"></div>_x000D_
</label><br><br>_x000D_
_x000D_
<label class="switch">_x000D_
  <input type="checkbox">_x000D_
  <div class="slider round"></div>_x000D_
</label>_x000D_
_x000D_
<label class="switch">_x000D_
  <input type="checkbox" checked>_x000D_
  <div class="slider round"></div>_x000D_
</label>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

"Unable to get the VLookup property of the WorksheetFunction Class" error

Try below code

I will recommend to use error handler while using vlookup because error might occur when the lookup_value is not found.

Private Sub ComboBox1_Change()


    On Error Resume Next
    Ret = Application.WorksheetFunction.VLookup(Me.ComboBox1.Value, Worksheets("Sheet3").Range("Names"), 2, False)
    On Error GoTo 0

    If Ret <> "" Then MsgBox Ret


End Sub

OR

 On Error Resume Next

    Result = Application.VLookup(Me.ComboBox1.Value, Worksheets("Sheet3").Range("Names"), 2, False)

    If Result = "Error 2042" Then
        'nothing found
    ElseIf cell <> Result Then
        MsgBox cell.Value
    End If

    On Error GoTo 0

Lost connection to MySQL server at 'reading initial communication packet', system error: 0

Someone here suggests that it might be a firewall problem:

I have just had this problem and found it was my firewall. I use PCTools Firewall Plus and it wasn't allowing full access to MySQL. Once I changed that it was fine. Hope that helps.

Could that be it?

Also, someone here suggests that it might be because the MySQL server is bound to the loop-back IP (127.0.0.1 / localhost) which effectively cuts you off from connecting from "outside".

If this is the case, you need to upload the script to the webserver (which is probably also running the MySQL server) and keep your server host as 'localhost'

Connection pooling options with JDBC: DBCP vs C3P0

c3p0 is good when we are using mutithreading projects. In our projects we used simultaneously multiple thread executions by using DBCP, then we got connection timeout if we used more thread executions. So we went with c3p0 configuration.