Programs & Examples On #Session cookies

Session cookies enable a server and a browser to establish an identified connection (through cookies) and communicate though it.

Check if cookies are enabled

JavaScript

In JavaScript you simple test for the cookieEnabled property, which is supported in all major browsers. If you deal with an older browser, you can set a cookie and check if it exists. (borrowed from Modernizer):

if (navigator.cookieEnabled) return true;

// set and read cookie
document.cookie = "cookietest=1";
var ret = document.cookie.indexOf("cookietest=") != -1;

// delete cookie
document.cookie = "cookietest=1; expires=Thu, 01-Jan-1970 00:00:01 GMT";

return ret;

PHP

In PHP it is rather "complicated" since you have to refresh the page or redirect to another script. Here I will use two scripts:

somescript.php

<?php
session_start();
setcookie('foo', 'bar', time()+3600);
header("location: check.php");

check.php

<?php echo (isset($_COOKIE['foo']) && $_COOKIE['foo']=='bar') ? 'enabled' : 'disabled';

PHP session lost after redirect

OP didn't specify if he's redirecting to the same page (for example after login) if so server/browser caching could also be the problem

A simple workaround would be to append version number at the end of the URL (like you would when forcing .CSS file refresh)

Example:

header('Location: index.php?v='.time());

So the user is redirected to which is treated like a new page

domain.com/index.php?v=122234982323

How to secure the ASP.NET_SessionId cookie?

To add the ; secure suffix to the Set-Cookie http header I simply used the <httpCookies> element in the web.config:

<system.web>
  <httpCookies httpOnlyCookies="true" requireSSL="true" />
</system.web>

IMHO much more handy than writing code as in the article of Anubhav Goyal.

See: http://msdn.microsoft.com/en-us/library/ms228262(v=vs.100).aspx

Invalidating JSON Web Tokens

I too have been researching this question, and while none of the ideas below are complete solutions, they might help others rule out ideas, or provide further ones.

1) Simply remove the token from the client

Obviously this does nothing for server side security, but it does stop an attacker by removing the token from existence (ie. they would have to have stolen the token prior to logout).

2) Create a token blocklist

You could store the invalid tokens until their initial expiry date, and compare them against incoming requests. This seems to negate the reason for going fully token based in the first place though, as you would need to touch the database for every request. The storage size would likely be lower though, as you would only need to store tokens that were between logout & expiry time (this is a gut feeling, and is definitely dependent on context).

3) Just keep token expiry times short and rotate them often

If you keep the token expiry times at short enough intervals, and have the running client keep track and request updates when necessary, number 1 would effectively work as a complete logout system. The problem with this method, is that it makes it impossible to keep the user logged in between closes of the client code (depending on how long you make the expiry interval).

Contingency Plans

If there ever was an emergency, or a user token was compromised, one thing you could do is allow the user to change an underlying user lookup ID with their login credentials. This would render all associated tokens invalid, as the associated user would no longer be able to be found.

I also wanted to note that it is a good idea to include the last login date with the token, so that you are able to enforce a relogin after some distant period of time.

In terms of similarities/differences with regards to attacks using tokens, this post addresses the question: https://github.com/dentarg/blog/blob/master/_posts/2014-01-07-angularjs-authentication-with-cookies-vs-token.markdown

Using Python Requests: Sessions, Cookies, and POST

I don't know how stubhub's api works, but generally it should look like this:

s = requests.Session()
data = {"login":"my_login", "password":"my_password"}
url = "http://example.net/login"
r = s.post(url, data=data)

Now your session contains cookies provided by login form. To access cookies of this session simply use

s.cookies

Any further actions like another requests will have this cookie

How to delete cookies on an ASP.NET website

It is 2018 now, so in ASP.NET Core, there is a straight forward built in function. To delete a cookie try this code:

if(Request.Cookies["aa"] != null)
{
    Response.Cookies.Delete("aa");
}
return View();

What is the difference between Sessions and Cookies in PHP?

The main difference between a session and a cookie is that session data is stored on the server, whereas cookies store data in the visitor’s browser.

Sessions are more secure than cookies as it is stored in server. Cookie can be turned off from browser.

Data stored in cookie can be stored for months or years, depending on the life span of the cookie. But the data in the session is lost when the web browser is closed.

How to use cURL to send Cookies?

You are using a wrong format in your cookie file. As curl documentation states, it uses an old Netscape cookie file format, which is different from the format used by web browsers. If you need to create a curl cookie file manually, this post should help you. In your example the file should contain following line

127.0.0.1   FALSE   /   FALSE   0   USER_TOKEN  in

having 7 TAB-separated fields meaning domain, tailmatch, path, secure, expires, name, value.

What is the difference between server side cookie and client side cookie?

You probably mean the difference between Http Only cookies and their counter part?

Http Only cookies cannot be accessed (read from or written to) in client side JavaScript, only server side. If the Http Only flag is not set, or the cookie is created in (client side) JavaScript, the cookie can be read from and written to in (client side) JavaScript as well as server side.

How can I easily switch between PHP versions on Mac OSX?

Using brew

Show current version

$ php -v

Change to different version
(eg. changing from 5.5.x to version 7.0.latest) :

$ brew unlink php55
$ brew install php70

JQuery .each() backwards

I found Array.prototype.reverse unsuccessful with objects, so I made a new jQuery function to use as an alternative: jQuery.eachBack(). It iterates through as the normal jQuery.each() would, and stores each key into an array. It then reverses that array and performs the callback on the original array/object in the order of the reversed keys.

jQuery.eachBack=function (obj, callback) {
    var revKeys=[]; $.each(obj,function(rind,rval){revKeys.push(rind);}); 
    revKeys.reverse();
    $.each(revKeys,function (kind,i){
        if(callback.call(obj[i], i, obj[i]) === false) {    return false;}
    });
    return obj;
}   
jQuery.fn.eachBack=function (callback,args) {
    return jQuery.eachBack(this, callback, args);
}

How to return a string from a C++ function?

You never give any value to your strings in main so they are empty, and thus obviously the function returns an empty string.

Replace:

string str1, str2, str3;

with:

string str1 = "the dog jumped over the fence";
string str2 = "the";
string str3 = "that";

Also, you have several problems in your replaceSubstring function:

int index = s1.find(s2, 0);
s1.replace(index, s2.length(), s3);
  • std::string::find returns a std::string::size_type (aka. size_t) not an int. Two differences: size_t is unsigned, and it's not necessarily the same size as an int depending on your platform (eg. on 64 bits Linux or Windows size_t is unsigned 64 bits while int is signed 32 bits).
  • What happens if s2 is not part of s1? I'll leave it up to you to find how to fix that. Hint: std::string::npos ;)

How to fix docker: Got permission denied issue

After Docker Installation on Centos. While running below command I got below error.

[centos@aiops-dev-cassandra3 ~]$ docker run hello-world
docker: Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Post http://%2Fvar%2Frun%2Fdocker.soc k/v1.40/containers/create: dial unix /var/run/docker.sock: connect: permission denied.
See 'docker run --help'.

Change Group and Permission for docker.socket

[centos@aiops-dev-cassandra3 ~]$ ls -l /lib/systemd/system/docker.socket
-rw-r--r--. 1 root root 197 Nov 13 07:25 /lib/systemd/system/docker.socket
[centos@aiops-dev-cassandra3 ~]$ sudo chgrp docker /lib/systemd/system/docker.socket
[centos@aiops-dev-cassandra3 ~]$ sudo chmod 666 /var/run/docker.sock
[centos@aiops-dev-cassandra3 ~]$ ls -lrth /var/run/docker.sock
srw-rw-rw-. 1 root docker 0 Nov 20 11:59 /var/run/docker.sock
[centos@aiops-dev-cassandra3 ~]$

Verify by using below docker command

[centos@aiops-dev-cassandra3 ~]$ docker run hello-world
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
1b930d010525: Pull complete
Digest: sha256:c3b4ada4687bbaa170745b3e4dd8ac3f194ca95b2d0518b417fb47e5879d9b5f
Status: Downloaded newer image for hello-world:latest

Hello from Docker!
This message shows that your installation appears to be working correctly.

To generate this message, Docker took the following steps:
 1. The Docker client contacted the Docker daemon.
 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
    (amd64)
 3. The Docker daemon created a new container from that image which runs the
    executable that produces the output you are currently reading.
 4. The Docker daemon streamed that output to the Docker client, which sent it
    to your terminal.

To try something more ambitious, you can run an Ubuntu container with:
 $ docker run -it ubuntu bash

Share images, automate workflows, and more with a free Docker ID:
 https://hub.docker.com/

For more examples and ideas, visit:
 https://docs.docker.com/get-started/

[centos@aiops-dev-cassandra3 ~]$

Javascript to set hidden form value on drop down change

Here you can set hidden's value at onchange event of dropdown list :

$('#myDropDown').bind('change', function () {
  $('#myHidden').val('setted value');
});

your hidden and drop down list :

<input type="hidden" id="myHidden" />

<select id="myDropDown">
   <option value="opt 1">Option 1</option>
   <option value="opt 2">Option 2</option>
   <option value="opt 3">Option 3</option>
</ select>

sed: print only matching group

grep is the right tool for extracting.

using your example and your regex:

kent$  echo 'foo bar <foo> bla 1 2 3.4'|grep -o '[0-9][0-9]*[\ \t][0-9.]*[\ \t]*$'
2 3.4

Make file echo displaying "$PATH" string

The make uses the $ for its own variable expansions. E.g. single character variable $A or variable with a long name - ${VAR} and $(VAR).

To put the $ into a command, use the $$, for example:

all:
  @echo "Please execute next commands:"
  @echo 'setenv PATH /usr/local/greenhills/mips5/linux86:$$PATH'

Also note that to make the "" and '' (double and single quoting) do not play any role and they are passed verbatim to the shell. (Remove the @ sign to see what make sends to shell.) To prevent the shell from expanding $PATH, second line uses the ''.

Parser Error Message: Could not load type 'TestMvcApplication.MvcApplication'

I have found that when you are forced to use the Configuration Manager to run under x86 or anything other than the standard project "out of the box" settings, the IDE creates a bunch of sub directories under the bin folder for the web project.

Once this starts happening, if the Cassini server is running, then the project does not serve properly.

I fixed it by going into the Web Project properties -> Build settings and changing the Output Path to be bin\

Then rebuild and all works as it should.

jquery Ajax call - data parameters are not being passed to MVC Controller action

  var json = {"ListID" : "1", "ItemName":"test"};
    $.ajax({
            url: url,
            type: 'POST',        
            data: username, 
            cache:false,
            beforeSend: function(xhr) {  
                xhr.setRequestHeader("Accept", "application/json");  
                xhr.setRequestHeader("Content-Type", "application/json");  
            },       
            success:function(response){
             console.log("Success")
            },
              error : function(xhr, status, error) {
            console.log("error")
            }
);

Is it possible to force Excel recognize UTF-8 CSV files automatically?

Working solution for office 365

  • save in UTF-16 (no LE, BE)
  • use separator \t

Code in PHP

$header = ['císlo', 'vytvoreno', 'ešcržýáíé'];
$fileName = 'excel365.csv';
$fp = fopen($fileName, 'w');
fputcsv($fp, $header, "\t");
fclose($fp);

$handle = fopen($fileName, "r");
$contents = fread($handle, filesize($fileName));
$contents = iconv('UTF-8', 'UTF-16', $contents);
fclose($handle);

$handle = fopen($fileName, "w");
fwrite($handle, $contents);
fclose($handle);

Remove CSS from a Div using JQuery

i have same prob too, just remove the value

<script>
      $("#play").toggle(function(){$(this).css("background","url(player.png) -100px 0px no-repeat");},
      function(){$(this).css("background","");});
</script>

Path.Combine absolute with relative path strings

Be careful with Backslashes, don't forget them (neither use twice:)

string relativePath = "..\\bling.txt";
string baseDirectory = "C:\\blah\\";
//OR:
//string relativePath = "\\..\\bling.txt";
//string baseDirectory = "C:\\blah";
//THEN
string absolutePath = Path.GetFullPath(baseDirectory + relativePath);

What is the convention for word separator in Java package names?

Here's what the official naming conventions document prescribes:

Packages

The prefix of a unique package name is always written in all-lowercase ASCII letters and should be one of the top-level domain names, currently com, edu, gov, mil, net, org, or one of the English two-letter codes identifying countries as specified in ISO Standard 3166, 1981.

Subsequent components of the package name vary according to an organization's own internal naming conventions. Such conventions might specify that certain directory name components be division, department, project, machine, or login names.

Examples

  • com.sun.eng
  • com.apple.quicktime.v2
  • edu.cmu.cs.bovik.cheese

References


Note that in particular, anything following the top-level domain prefix isn't specified by the above document. The JLS also agrees with this by giving the following examples:

  • com.sun.sunsoft.DOE
  • gov.whitehouse.socks.mousefinder
  • com.JavaSoft.jag.Oak
  • org.npr.pledge.driver
  • uk.ac.city.rugby.game

The following excerpt is also relevant:

In some cases, the internet domain name may not be a valid package name. Here are some suggested conventions for dealing with these situations:

  • If the domain name contains a hyphen, or any other special character not allowed in an identifier, convert it into an underscore.
  • If any of the resulting package name components are keywords then append underscore to them.
  • If any of the resulting package name components start with a digit, or any other character that is not allowed as an initial character of an identifier, have an underscore prefixed to the component.

References

Loading state button in Bootstrap 3

You need to detect the click from js side, your HTML remaining same. Note: this method is deprecated since v3.5.5 and removed in v4.

$("button").click(function() {
    var $btn = $(this);
    $btn.button('loading');
    // simulating a timeout
    setTimeout(function () {
        $btn.button('reset');
    }, 1000);
});

Also, don't forget to load jQuery and Bootstrap js (based on jQuery) file in your page.

JSFIDDLE

Official Documentation

How can I show a combobox in Android?

Not tested, but the closer you can get seems to be is with AutoCompleteTextView. You can write an adapter wich ignores the filter functions. Something like:

class UnconditionalArrayAdapter<T> extends ArrayAdapter<T> {
    final List<T> items;
    public UnconditionalArrayAdapter(Context context, int textViewResourceId, List<T> items) {
        super(context, textViewResourceId, items);
        this.items = items;
    }

    public Filter getFilter() {
        return new NullFilter();
    }

    class NullFilter extends Filter {
        protected Filter.FilterResults performFiltering(CharSequence constraint) {
            final FilterResults results = new FilterResults();
            results.values = items;
            return results;
        }

        protected void publishResults(CharSequence constraint, Filter.FilterResults results) {
            items.clear(); // `items` must be final, thus we need to copy the elements by hand.
            for (Object item : (List) results.values) {
                items.add((String) item);
            }
            if (results.count > 0) {
                notifyDataSetChanged();
            } else {
                notifyDataSetInvalidated();
            }
        }
    }
}

... then in your onCreate:

String[] COUNTRIES = new String[] {"Belgium", "France", "Italy", "Germany"};
List<String> contriesList = Arrays.asList(COUNTRIES());
ArrayAdapter<String> adapter = new UnconditionalArrayAdapter<String>(this,
    android.R.layout.simple_dropdown_item_1line, contriesList);
AutoCompleteTextView textView = (AutoCompleteTextView)
    findViewById(R.id.countries_list);
textView.setAdapter(adapter);

The code is not tested, there can be some features with the filtering method I did not consider, but there you have it, the basic principles to emulate a ComboBox with an AutoCompleteTextView.

Edit Fixed NullFilter implementation. We need access on the items, thus the constructor of the UnconditionalArrayAdapter needs to take a reference to a List (kind of a buffer). You can also use e.g. adapter = new UnconditionalArrayAdapter<String>(..., new ArrayList<String>); and then use adapter.add("Luxemburg"), so you don't need to manage the buffer list.

how to set font size based on container size?

You may be able to do this with CSS3 using calculations, however it would most likely be safer to use JavaScript.

Here is an example: http://jsfiddle.net/8TrTU/

Using JS you can change the height of the text, then simply bind this same calculation to a resize event, during resize so it scales while the user is making adjustments, or however you are allowing resizing of your elements.

MATLAB, Filling in the area between two sets of data, lines in one figure

Personally, I find it both elegant and convenient to wrap the fill function. To fill between two equally sized row vectors Y1 and Y2 that share the support X (and color C):

fill_between_lines = @(X,Y1,Y2,C) fill( [X fliplr(X)],  [Y1 fliplr(Y2)], C );

When and why do I need to use cin.ignore() in C++?

As pointed right by many other users. It's because there may be whitespace or a newline character.

Consider the following code, it removes all the duplicate characters from a given string.

#include <bits/stdc++.h>
using namespace std;

int main() {
    int t;
    cin>>t;
    cin.ignore(); //Notice that this cin.ignore() is really crucial for any extra whitespace or newline character
    while(t--){
        vector<int> v(256,0);
        string s;
        getline(cin,s);
        string s2;
        for(int i=0;i<s.size();i++){
            if (v[s[i]]) continue;
            else{
                s2.push_back(s[i]);
                v[s[i]]++;
            }
        }
        cout<<s2<<endl;
    }
    return 0;
}

So, You get the point that it will ignore those unwanted inputs and will get the job done.

Vim: faster way to select blocks of text in visual mode

} means move cursor to next paragraph. so, use v} to select entire paragraph.

How to get the location of the DLL currently executing?

In my case (dealing with my assemblies loaded [as file] into Outlook):

typeof(OneOfMyTypes).Assembly.CodeBase

Note the use of CodeBase (not Location) on the Assembly. Others have pointed out alternative methods of locating the assembly.

java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing

You need junit-dep.jar because the junit.jar has a copy of old Hamcrest classes.

MySQL: ignore errors when importing?

Use the --force (-f) flag on your mysql import. Rather than stopping on the offending statement, MySQL will continue and just log the errors to the console.

For example:

mysql -u userName -p -f -D dbName < script.sql

Java "?" Operator for checking null - What is it? (Not Ternary!)

Since Android does not support Lambda Functions unless your installed OS is >= 24, we need to use reflection.

// Example using doIt function with sample classes
public void Test() {
    testEntry(new Entry(null));
    testEntry(new Entry(new Person(new Name("Bob"))));
}

static void testEntry(Entry entry) {
    doIt(doIt(doIt(entry,  "getPerson"), "getName"), "getName");
}

// Helper to safely execute function 
public static <T,R> R doIt(T obj, String methodName) {
    try {
       if (obj != null) 
           return (R)obj.getClass().getDeclaredMethod(methodName).invoke(obj);
    } catch (Exception ignore) {
    }
    return null;
}
// Sample test classes
    static class Entry {
        Person person;
        Entry(Person person) { this.person = person; }
        Person getPerson() { return person; }
    }

    static class Person {
        Name name;
        Person(Name name) { this.name = name; }
        Name getName() { return name; }
    }

    static class Name {
        String name;
        Name(String name) { this.name = name; }
        String getName() {
            System.out.print(" Name:" + name + " ");
            return name;
        }
    }
}

Setting an image button in CSS - image:active

Check this link . You were missing . before myButton. It was a small error. :)

.myButton{
    background:url(./images/but.png) no-repeat;
    cursor:pointer;
    border:none;
    width:100px;
    height:100px;
}

.myButton:active  /* use Dot here */
{   
    background:url(./images/but2.png) no-repeat;
}

How to write a link like <a href="#id"> which link to the same page in PHP?

Edit:

Are you trying to do sth like this? See: http://twitter.github.com/bootstrap/javascript.html#tabs


See the working example: http://jsfiddle.net/U6aKT/

<a href="#id">go to id</a>
<div style="margin-top:2000px;"></div>
<a id="id">id</a>

How to suppress "unused parameter" warnings in C?

In gcc, you can label the parameter with the unused attribute.

This attribute, attached to a variable, means that the variable is meant to be possibly unused. GCC will not produce a warning for this variable.

In practice this is accomplished by putting __attribute__ ((unused)) just before the parameter. For example:

void foo(workerid_t workerId) { }

becomes

void foo(__attribute__((unused)) workerid_t workerId) { }

Query to check index on a table

If you just need the indexed columns EXEC sp_helpindex 'TABLE_NAME'

Access parent URL from iframe

The following line will work: document.location.ancestorOrigins[0] this one returns the ancestor domain name.

Calculate distance between 2 GPS coordinates

you can find a implementation of this (with some good explanation) in F# on fssnip

here are the important parts:


let GreatCircleDistance<[<Measure>] 'u> (R : float<'u>) (p1 : Location) (p2 : Location) =
    let degToRad (x : float<deg>) = System.Math.PI * x / 180.0<deg/rad>

    let sq x = x * x
    // take the sin of the half and square the result
    let sinSqHf (a : float<rad>) = (System.Math.Sin >> sq) (a / 2.0<rad>)
    let cos (a : float<deg>) = System.Math.Cos (degToRad a / 1.0<rad>)

    let dLat = (p2.Latitude - p1.Latitude) |> degToRad
    let dLon = (p2.Longitude - p1.Longitude) |> degToRad

    let a = sinSqHf dLat + cos p1.Latitude * cos p2.Latitude * sinSqHf dLon
    let c = 2.0 * System.Math.Atan2(System.Math.Sqrt(a), System.Math.Sqrt(1.0-a))

    R * c

Mockito : how to verify method was called on an object created within a method?

The classic response is, "You don't." You test the public API of Foo, not its internals.

Is there any behavior of the Foo object (or, less good, some other object in the environment) that is affected by foo()? If so, test that. And if not, what does the method do?

Best practice to validate null and empty collection in Java

You can use org.apache.commons.lang.Validate's "notEmpty" method:

Validate.notEmpty(myCollection) -> Validate that the specified argument collection is neither null nor a size of zero (no elements); otherwise throwing an exception.

Remove or adapt border of frame of legend using matplotlib

When plotting a plot using matplotlib:

How to remove the box of the legend?

plt.legend(frameon=False)

How to change the color of the border of the legend box?

leg = plt.legend()
leg.get_frame().set_edgecolor('b')

How to remove only the border of the box of the legend?

leg = plt.legend()
leg.get_frame().set_linewidth(0.0)

Java ArrayList replace at specific index

We can replace element in arraylist using ArrayList Set() method.We are a example for this as below.

Create Arraylist

 ArrayList<String> arr = new ArrayList<String>();
 arr.add("c");
 arr.add("php");
 arr.add("html");
 arr.add("java");

Now replcae Element on index 2

 arr.set(2,"Mysql");
 System.out.println("after replace arrayList is = " + arr);

OutPut :

 after replace arrayList is = [c, php, Mysql, java]

Reference :

Replace element in ArrayList

Missing artifact com.sun:tools:jar

The same with me and Windows 7. I ended up adding two lines to eclipse.ini:

-vm 
C:\Program Files\Java\jdk1.6.0_35\bin

I tried using %JAVA_HOME% there, but it did not work.

How can I get the line number which threw exception?

Extension Method

static class ExceptionHelpers
{
    public static int LineNumber(this Exception ex)
    {
        int n;
        int i = ex.StackTrace.LastIndexOf(" ");
        if (i > -1)
        {
            string s = ex.StackTrace.Substring(i + 1);
            if (int.TryParse(s, out n))
                return n;
        }
        return -1;
    }
}

Usage

try
{
    throw new Exception("A new error happened");
}
catch (Exception ex)
{
    //If error in exception LineNumber() will be -1
    System.Diagnostics.Debug.WriteLine("[" + ex.LineNumber() + "] " + ex.Message);
}

saving a file (from stream) to disk using c#

Just do it with a simple filestream.

var sr1 = new FileStream(FilePath, FileMode.Create);
                sr1.Write(_UploadFile.File, 0, _UploadFile.File.Length);
                sr1.Close();
                sr1.Dispose();

_UploadFile.File is a byte[], and in the FilePath you get to specify the file extention.

Installing NumPy and SciPy on 64-bit Windows (with Pip)

You can now pip install numpy on Windows!

"Note: this page has only historical relevance, you can now pip-install for windows" Source: https://github.com/numpy/numpy/wiki/Whats-with-Windows-builds

getting JRE system library unbound error in build path

oh boy, this got resolved, I just had to name my Installed JRE appropriately. I had only the jdk installed and eclipse had taken the default jdk name, i renamed it to JavaSE-1.6 and voila it worked, though i had to redo everthing from the scratch.

Is it possible to hide the cursor in a webpage using CSS or Javascript?

If you want to hide the cursor in the entire webpage, using body will not work unless it covers the entire visible page, which is not always the case. To make sure the cursor is hidden everywhere in the page, use:

document.documentElement.style.cursor = 'none';

To reenable it:

document.documentElement.style.cursor = 'auto';

The analogue with static CSS notation is in the answer by Pavel Salaquarda (in essence: html * {cursor:none})

Using sed and grep/egrep to search and replace

I couldn't get any of the commands on this page to work for me: the sed solution added a newline to the end of all the files it processed, and the perl solution was unable to accept enough arguments from find. I found this solution which works perfectly:

find . -type f -name '*.[hm]' -print0 
    | xargs -0 perl -pi -e 's/search_regex/replacement_string/g'

This will recurse down the current directory tree and replace search_regex with replacement_string in any files ending in .h or .m.

I have also used rpl for this purpose in the past.

How to solve PHP error 'Notice: Array to string conversion in...'

Array to string conversion in latest versions of php 7.x is error, rather than notice, and prevents further code execution.

Using print, echo on array is not an option anymore.

Suppressing errors and notices is not a good practice, especially when in development environment and still debugging code.

Use var_dump,print_r, iterate through input value using foreach or for to output input data for names that are declared as input arrays ('name[]')

Most common practice to catch errors is using try/catch blocks, that helps us prevent interruption of code execution that might cause possible errors wrapped within try block.

  try{  //wrap around possible cause of error or notice
    
    if(!empty($_POST['C'])){
        echo $_POST['C'];
    }

  }catch(Exception $e){

    //handle the error message $e->getMessage();
  }

Colon (:) in Python list index

: is the delimiter of the slice syntax to 'slice out' sub-parts in sequences , [start:end]

[1:5] is equivalent to "from 1 to 5" (5 not included)
[1:] is equivalent to "1 to end"
[len(a):] is equivalent to "from length of a to end"

Watch https://youtu.be/tKTZoB2Vjuk?t=41m40s at around 40:00 he starts explaining that.

Works with tuples and strings, too.

How can I color dots in a xy scatterplot according to column value?

I see there is a VBA solution and a non-VBA solution, which both are really good. I wanted to propose my Javascript solution.

There is an Excel add-in called Funfun that allows you to use javascript, HTML and css in Excel. It has an online editor with an embedded spreadsheet where you can build your chart.

I have written this code for you with Chart.js:

https://www.funfun.io/1/#/edit/5a61ed15404f66229bda3f44

To create this chart, I entered my data on the spreadsheet and read it with a json file, it is the short file.

I make sure to put it in the right format, in script.js, so I can add it to my chart:

var data = [];
var color = [];
var label = [];

for (var i = 1; i < $internal.data.length; i++)
{
    label.push($internal.data[i][0]);
    data.push([$internal.data[i][1], $internal.data[i][2]]);
    color.push($internal.data[i][3]);
}

I then create the scatter chart with each dot having his designated color and position:

 var dataset = [];
  for (var i = 0; i < data.length; i++) {   
    dataset.push({
      data: [{
        x: data[i][0],
        y: data[i][1] 
      }],
      pointBackgroundColor: color[i],
      pointStyle: "cercle",
      radius: 6  
    });
  }

After I've created my scatter chart I can upload it in Excel by pasting the URL in the funfun Excel add-in. Here is how it looks like with my example:

final

Once this is done You can change the color or the position of a dot instantly, in Excel, by changing the values in the spreadsheet.

If you want to add extra dots in the charts you just need to modify the radius of data in the short json file.

Hope this Javascript solution helps !

Disclosure : I’m a developer of funfun

How to refactor Node.js code that uses fs.readFileSync() into using fs.readFile()?

This variant is better because you could not know whether file exists or not. You should send correct header when you know for certain that you can read contents of your file. Also, if you have branches of code that does not finish with '.end()', browser will wait until it get them. In other words, your browser will wait a long time.

var fs = require("fs");
var filename = "./index.html";

function start(resp) {

    fs.readFile(filename, "utf8", function(err, data) {
        if (err) {
            // may be filename does not exists?
            resp.writeHead(404, {
                'Content-Type' : 'text/html'
            });
            // log this error into browser
            resp.write(err.toString());
            resp.end();
        } else {

            resp.writeHead(200, {
                "Content-Type": "text/html"
            });      
            resp.write(data.toString());
            resp.end();
        }
    });
}

How to set JAVA_HOME in Mac permanently?

You can use /usr/libexec/java_home -v <version you want> to get the path you need for JAVA_HOME. For instance, to get the path to the 1.7 JDK you can run /usr/libexec/java_home -v 1.7 and it will return the path to the JDK. In your .profile or .bash_profile just add

export JAVA_HOME=`/usr/libexec/java_home -v <version>`

and you should be good. Alternatively, try and convince the maintainers of java tools you use to make use of this method to get the version they need.

To open '.bash_profile' type the following in terminal :

nano ~/.bash_profile 

and add the following line to the file:

export JAVA_HOME=`/usr/libexec/java_home -v <version>`

Press CTRL+X to exit the bash. Press 'Y' to save changes.

To check whether the path has been added, type following in terminal:

source ~/.bash_profile
echo $JAVA_HOME

System.BadImageFormatException An attempt was made to load a program with an incorrect format

I had the same issue when getting my software running on another machine. On my developer pc (Windows 7), I had Visual Studio 2015 installed, the target pc was a clean installation of Windows 10 (.Net installed). I also tested it on another clean Windows 7 pc including .Net Framework. However, on both target pc's I needed to install the Visual C++ Redistributable for Visual Studio 2015 package for x86 or x64 (depends on what your application is build for). That was already installed on my developer pc.

My application was using a C library, which has been compiled to a C++ application using /clr and /TP options in visual studio. Also the application was providing functions to C# by using dllexport method signatures. Not sure if the C# integration leaded to give me that error or if a C++ application would have given me the same.

Hope it helps anybody.

What are the safe characters for making URLs?

From an SEO perspective, hyphens are preferred over underscores. Convert to lowercase, remove all apostrophes, then replace all non-alphanumeric strings of characters with a single hyphen. Trim excess hyphens off the start and finish.

Catch browser's "zoom" event in JavaScript

The resize event works on modern browsers by attaching the event on window, and then reading values of thebody, or other element with for example (.getBoundingClientRect()).

In some earlier browsers it was possible to register resize event handlers on any HTML element. It is still possible to set onresize attributes or use addEventListener() to set a handler on any element. However, resize events are only fired on the window object (i.e. returned by document.defaultView). Only handlers registered on the window object will receive resize events.

_x000D_
_x000D_
window.addEventListener("resize", getSizes, false)_x000D_
        _x000D_
function getSizes(){_x000D_
  let body = document.body_x000D_
  console.log(body.clientWidth +"px x "+ body.clientHeight + "px")_x000D_
}
_x000D_
_x000D_
_x000D_

An other alternative: the ResizeObserver API

Depending your layout, you can watch for resizing on a particular element.

This works well on «responsive» layouts, because the container box get resized when zooming.

_x000D_
_x000D_
function watchBoxchange(e){_x000D_
 // console.log(e[0].contentBoxSize.inlineSize+" "+e[0].contentBoxSize.blockSize)_x000D_
 info.textContent = e[0].contentBoxSize.inlineSize+" * "+e[0].contentBoxSize.blockSize + "px"_x000D_
}_x000D_
_x000D_
new ResizeObserver(watchBoxchange).observe(fluid)
_x000D_
#fluid {_x000D_
  width: 200px;_x000D_
  height:100px;_x000D_
  overflow: auto;_x000D_
  resize: both;_x000D_
  border: 3px black solid;_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  justify-content: center;_x000D_
  align-items: center;_x000D_
  font-size: 8vh_x000D_
}
_x000D_
<div id="fluid">_x000D_
   <info id="info"></info> _x000D_
</div>
_x000D_
_x000D_
_x000D_


Be careful to not overload javascript tasks from user gestures events. Use requestAnimationFrame whenever you needs redraws.

jQueryUI modal dialog does not show close button (x)

I suppose there is some conflict with other JS library in your code. Try to force showing the close button:

...
open:function () {
  $(".ui-dialog-titlebar-close").show();
} 
...

This worked for me.

C++ code file extension? .cc vs .cpp

I've use .C and .h for source and header, respectively. One nice thing with that choice is that, on the command line, its easy to use *.[Ch] to select all of the code files. Using .C could be a problem on case insensitive filesystems, but if you have foo.c and foo.C in the same directory, you deserve what you get anyway :)

convert string to specific datetime format?

This another helpful code:

"2011-05-19 10:30:14".to_datetime.strftime('%a %b %d %H:%M:%S %Z %Y')

JPA - Returning an auto generated id after persist()

This is how I did it:

EntityManager entityManager = getEntityManager();
EntityTransaction transaction = entityManager.getTransaction();
transaction.begin();
entityManager.persist(object);
transaction.commit();
long id = object.getId();
entityManager.close();

Pretty printing XML with javascript

You can get pretty formatted xml with xml-beautify

var prettyXmlText = new XmlBeautify().beautify(xmlText, 
                    {indent: "  ",useSelfClosingElement: true});

indent:indent pattern like white spaces

useSelfClosingElement: true=>use self-closing element when empty element.

JSFiddle

Original(Before)

<?xml version="1.0" encoding="utf-8"?><example version="2.0">
  <head><title>Original aTitle</title></head>
  <body info="none" ></body>
</example>

Beautified(After)

<?xml version="1.0" encoding="utf-8"?>
<example version="2.0">
  <head>
    <title>Original aTitle</title>
  </head>
  <body info="none" />
</example>

Configuring user and password with Git Bash

For those who are using access token and a Windows environment, there is a simple way to do it:

Start menu ? Credential Manager ? Windows Credentials ? find the line (Git: https://whatever/your-repository/url) ? edit, user name is "PersonalAccessToken" and password is your access token.

Difference between a virtual function and a pure virtual function

For a virtual function you need to provide implementation in the base class. However derived class can override this implementation with its own implementation. Normally , for pure virtual functions implementation is not provided. You can make a function pure virtual with =0 at the end of function declaration. Also, a class containing a pure virtual function is abstract i.e. you can not create a object of this class.

Angular 2 - Using 'this' inside setTimeout

You need to use Arrow function ()=> ES6 feature to preserve this context within setTimeout.

// var that = this;                             // no need of this line
this.messageSuccess = true;

setTimeout(()=>{                           //<<<---using ()=> syntax
      this.messageSuccess = false;
 }, 3000);

How to set UITextField height?

An update for iOS 6 : using auto-layout, even though you still can't set the UITextField's height from the Size Inspector in the Interface Builder (as of Xcode 4.5 DP4 at least), it is now possible to set a Height constraint on it, which you can edit from the Interface Builder.

Also, if you're setting the frame's height by code, auto-layout may reset it depending on the other constraints your view may have.

Set content of HTML <span> with Javascript

With modern browsers, you can set the textContent property, see Node.textContent:

var span = document.getElementById("myspan");
span.textContent = "some text";

Switch firefox to use a different DNS than what is in the windows.host file

Since http proxy protocol is similar to raw http protocol, you can redirect desired traffic to your development server by telling firefox it's a proxy server.

two limitations:

A. this won't let you use https connections.

B. some frameworks (e,g: wordpress) don't like this method and redirect the request the wrong way

just copy the following code into a .pac file (enter your site domain and IP address, of course), and switch development/production just by changing proxy configuration.

function FindProxyForURL(url, host) {
    var prox4site = {
        "mysite.com":"PROXY 10.0.1.100:80",
        "www.mysite.com":"PROXY 10.0.1.100:80"
    }

    return prox4site[host] || "DIRECT";
}

jQuery "on create" event for dynamically-created elements

Just came up with this solution that seems to solve all my ajax problems.

For on ready events I now use this:

function loaded(selector, callback){
    //trigger after page load.
    $(function () {
        callback($(selector));
    });
    //trigger after page update eg ajax event or jquery insert.
    $(document).on('DOMNodeInserted', selector, function () {
        callback($(this));
    });
}

loaded('.foo', function(el){
    //some action
    el.css('background', 'black');
});

And for normal trigger events I now use this:

$(document).on('click', '.foo', function () {
    //some action
    $(this).css('background', 'pink');
});

How to draw a circle with text in the middle?

You can use css3 flexbox.

HTML:

<div class="circle-with-text">
    Here is some text in circle
</div>

CSS:

.circle-with-text {
  justify-content: center;
  align-items: center;
  border-radius: 100%;
  text-align: center;
  display: flex;
}

This will allow you to have vertically and horizontally middle aligned single line and multi-line text.

_x000D_
_x000D_
body {_x000D_
  margin: 0;_x000D_
}_x000D_
.circles {_x000D_
  display: flex;_x000D_
}_x000D_
.circle-with-text {_x000D_
  background: linear-gradient(orange, red);_x000D_
  justify-content: center;_x000D_
  align-items: center;_x000D_
  border-radius: 100%;_x000D_
  text-align: center;_x000D_
  margin: 5px 20px;_x000D_
  font-size: 15px;_x000D_
  padding: 15px;_x000D_
  display: flex;_x000D_
  height: 180px;_x000D_
  width: 180px;_x000D_
  color: #fff;_x000D_
}_x000D_
.multi-line-text {_x000D_
  font-size: 20px;_x000D_
}
_x000D_
<div class="circles">_x000D_
  <div class="circle-with-text">_x000D_
    Here is some text in circle_x000D_
  </div>_x000D_
  <div class="circle-with-text multi-line-text">_x000D_
    Here is some multi-line text in circle_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do you convert epoch time in C#?

// convert datetime to unix epoch seconds
public static long ToUnixTime(DateTime date)
{
    var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    return Convert.ToInt64((date.ToUniversalTime() - epoch).TotalSeconds);
}

Should use ToUniversalTime() for the DateTime object.

How to set a background image in Xcode using swift?

I am beginner to iOS development so I would like to share whole info I got in this section.

First from image assets (images.xcassets) create image set .

According to Documentation here is all sizes need to create background image.

For iPhone 5:
   640 x 1136

   For iPhone 6:
   750 x 1334 (@2x) for portrait
   1334 x 750 (@2x) for landscape

   For iPhone 6 Plus:
   1242 x 2208 (@3x) for portrait
   2208 x 1242 (@3x) for landscape

   iPhone 4s (@2x)      
   640 x 960

   iPad and iPad mini (@2x) 
   1536 x 2048 (portrait)
   2048 x 1536 (landscape)

   iPad 2 and iPad mini (@1x)
   768 x 1024 (portrait)
   1024 x 768 (landscape)

   iPad Pro (@2x)
   2048 x 2732 (portrait)
   2732 x 2048 (landscape)

call the image background we can call image from image assets by using this method UIImage(named: "background") here is full code example

  override func viewDidLoad() {
          super.viewDidLoad()
             assignbackground()
            // Do any additional setup after loading the view.
        }

  func assignbackground(){
        let background = UIImage(named: "background")

        var imageView : UIImageView!
        imageView = UIImageView(frame: view.bounds)
        imageView.contentMode =  UIViewContentMode.ScaleAspectFill
        imageView.clipsToBounds = true
        imageView.image = background
        imageView.center = view.center
        view.addSubview(imageView)
        self.view.sendSubviewToBack(imageView)
    }

Bootstrap datepicker hide after selection

$('.datepicker').datepicker({
    autoclose: true
}); 

Text File Parsing with Python

There are a few ways to go about this. One option would be to use inputfile.read() instead of inputfile.readlines() - you'd need to write separate code to strip the first four lines, but if you want the final output as a single string anyway, this might make the most sense.

A second, simpler option would be to rejoin the strings after striping the first four lines with my_text = ''.join(my_text). This is a little inefficient, but if speed isn't a major concern, the code will be simplest.

Finally, if you actually want the output as a list of strings instead of a single string, you can just modify your data parser to iterate over the list. That might looks something like this:

def data_parser(lines, dic):
    for i, j in dic.iteritems():
        for (k, line) in enumerate(lines):
            lines[k] = line.replace(i, j)
    return lines

Pass by Reference / Value in C++

I think much confusion is generated by not communicating what is meant by passed by reference. When some people say pass by reference they usually mean not the argument itself, but rather the object being referenced. Some other say that pass by reference means that the object can't be changed in the callee. Example:

struct Object {
    int i;
};

void sample(Object* o) { // 1
    o->i++;
}

void sample(Object const& o) { // 2
    // nothing useful here :)
}

void sample(Object & o) { // 3
    o.i++;
}

void sample1(Object o) { // 4
    o.i++;
}

int main() {
    Object obj = { 10 };
    Object const obj_c = { 10 };

    sample(&obj); // calls 1
    sample(obj) // calls 3
    sample(obj_c); // calls 2
    sample1(obj); // calls 4
}

Some people would claim that 1 and 3 are pass by reference, while 2 would be pass by value. Another group of people say all but the last is pass by reference, because the object itself is not copied.

I would like to draw a definition of that here what i claim to be pass by reference. A general overview over it can be found here: Difference between pass by reference and pass by value. The first and last are pass by value, and the middle two are pass by reference:

    sample(&obj);
       // yields a `Object*`. Passes a *pointer* to the object by value. 
       // The caller can change the pointer (the parameter), but that 
       // won't change the temporary pointer created on the call side (the argument). 

    sample(obj)
       // passes the object by *reference*. It denotes the object itself. The callee
       // has got a reference parameter.

    sample(obj_c);
       // also passes *by reference*. the reference parameter references the
       // same object like the argument expression. 

    sample1(obj);
       // pass by value. The parameter object denotes a different object than the 
       // one passed in.

I vote for the following definition:

An argument (1.3.1) is passed by reference if and only if the corresponding parameter of the function that's called has reference type and the reference parameter binds directly to the argument expression (8.5.3/4). In all other cases, we have to do with pass by value.

That means that the following is pass by value:

void f1(Object const& o);
f1(Object()); // 1

void f2(int const& i);
f2(42); // 2

void f3(Object o);
f3(Object());     // 3
Object o1; f3(o1); // 4

void f4(Object *o);
Object o1; f4(&o1); // 5

1 is pass by value, because it's not directly bound. The implementation may copy the temporary and then bind that temporary to the reference. 2 is pass by value, because the implementation initializes a temporary of the literal and then binds to the reference. 3 is pass by value, because the parameter has not reference type. 4 is pass by value for the same reason. 5 is pass by value because the parameter has not got reference type. The following cases are pass by reference (by the rules of 8.5.3/4 and others):

void f1(Object *& op);
Object a; Object *op1 = &a; f1(op1); // 1

void f2(Object const& op);
Object b; f2(b); // 2

struct A { };
struct B { operator A&() { static A a; return a; } };
void f3(A &);
B b; f3(b); // passes the static a by reference

convert string to date in sql server

This will do the trick:

SELECT CONVERT(char(10), GetDate(),126)

How to dynamic filter options of <select > with jQuery?

Update Lessan's answer to also keep the attributes of the options.

This is my first time answering on Stack Overflow so not sure if I should edit his answer or create my own.

jQuery.fn.allAttr = function() {
  var a, aLength, attributes, map;
  if (!this[0]) return null;
  if (arguments.length === 0) {
    map = {};
    attributes = this[0].attributes;
    aLength = attributes.length;
    for (a = 0; a < aLength; a++) {
      map[attributes[a].name.toLowerCase()] = attributes[a].value;
    }
    return map;
  } else {
    for (var propin arguments[0]) {
      $(this[0]).attr(prop, arguments[0][prop]);
    }
    return this[0];
  }
};


jQuery.fn.filterByText = function(textbox) {
  return this.each(function() {
    var select = this;
    var options = [];
    $(select).find('option').each(function() {
      options.push({ value: $(this).val(), 
        text: $(this).text(), 
        allAttr: $(this).allAttr() });
    });
    $(select).data('options', options);

    $(textbox).bind('change keyup', function() {
      var search = $.trim($(this).val());
      var regex = new RegExp(search, "gi");

      $.each($(select).empty().data('options'), function(i, option) {
        if (option.text.match(regex) !== null) {
          $(select).append(
            $('<option>').text(option.text)
            .val(option.value)
            .allAttr(option.allAttr)
          );
        }
      });
    });
  });
};

How to create a fix size list in python?

Note also that when you used arrays in C++ you might have had somewhat different needs, which are solved in different ways in Python:

  1. You might have needed just a collection of items; Python lists deal with this usecase just perfectly.
  2. You might have needed a proper array of homogenous items. Python lists are not a good way to store arrays.

Python solves the need in arrays by NumPy, which, among other neat things, has a way to create an array of known size:

from numpy import *

l = zeros(10)

How do I write JSON data to a file?

json.dump(data, open('data.txt', 'wb'))

How can we generate getters and setters in Visual Studio?

If you're using ReSharper, go into the ReSharper menu → CodeGenerate...

(Or hit Alt + Ins inside the surrounding class), and you'll get all the options for generating getters and/or setters you can think of :-)

Trying to get PyCharm to work, keep getting "No Python interpreter selected"

Your problem probably is that you haven't installed python. Meaning that, if you are using Windows, you have not downloaded the installer for Windows, that you can find on the official Python website.

In case you have, chances are that PyCharm cannot find your Python installation because its not in the default location, which is usually C:\Python27 or C:\Python33 (for me at least).

So, if you have installed Python and it still gives this error, then there can be two things that have happened:

  1. You use a virtualenv and that virtualenv has been deleted or the filepath changed. In this case, you will have to find proceed to the next part of this answer.
  2. Your python installation is not in its default place, in which case you will need to find its location, and locate the python.exe file.

Once you have located the necessary binaries, you will need to tell PyCharm were to look:

  1. Open your settings dialogue CTRL + ALT + S
  2. Then you will need to type in interpreter in the search box:

    enter image description here

  3. As you can see above, you will need to go to Project Interpreter and then go to Python Interpreter. The location has been selected for you in the above image.

  4. To the side you will see a couple of options as icons, click the big + icon, then click on local, because your interpreter is on this computer.

  5. This will open up a dialogue box. Make sure to select the python.exe file of that directory, do not give pycharm the whole directory. It just wants the interpreter.

TypeError: Converting circular structure to JSON in nodejs

TypeError: Converting circular structure to JSON in nodejs: This error can be seen on Arangodb when using it with Node.js, because storage is missing in your database. If the archive is created under your database, check in the Aurangobi web interface.

How to use a switch case 'or' in PHP

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

$today = date("D");

    switch($today){

        case "Mon":

        case "Tue":

            echo "Today is Tuesday or Monday. Buy some food.";

            break;

        case "Wed":

            echo "Today is Wednesday. Visit a doctor.";

            break;

        case "Thu":

            echo "Today is Thursday. Repair your car.";

            break;

        default:

            echo "No information available for that day.";

            break;

    }

setting content between div tags using javascript

See Creating and modifying HTML at what used to be called the Web Standards Curriculum.

Use the createElement, createTextNode and appendChild methods.

How to blur background images in Android

The easiest way to do that is use a library. Take a look at this one: https://github.com/wasabeef/Blurry

With the library you only need to do this:

Blurry.with(context)
  .radius(10)
  .sampling(8)
  .color(Color.argb(66, 255, 255, 0))
  .async()
  .onto(rootView);

Programmatically scroll a UIScrollView

With Animation in Swift

scrollView.setContentOffset(CGPointMake(x, y), animated: true)

load scripts asynchronously

You might find this wiki article interesting : http://ajaxpatterns.org/On-Demand_Javascript

It explains how and when to use such technique.

Python causing: IOError: [Errno 28] No space left on device: '../results/32766.html' on disk with lots of space

The ENOSPC ("No space left on device") error will be triggered in any situation in which the data or the metadata associated with an I/O operation can't be written down anywhere because of lack of space. This doesn't always mean disk space – it could mean physical disk space, logical space (e.g. maximum file length), space in a certain data structure or address space. For example you can get it if there isn't space in the directory table (vfat) or there aren't any inodes left. It roughly means “I can't find where to write this down”.

Particularly in Python, this can happen on any write I/O operation. It can happen during f.write, but it can also happen on open, on f.flush and even on f.close. Where it happened provides a vital clue for the reason that it did – if it happened on open there wasn't enough space to write the metadata for the entry, if it happened during f.write, f.flush or f.close there wasn't enough disk space left or you've exceeded the maximum file size.

If the filesystem in the given directory is vfat you'd hit the maximum file limit at about the same time that you did. The limit is supposed to be 2^16 directory entries, but if I recall correctly some other factors can affect it (e.g. some files require more than one entry).

It would be best to avoid creating so many files in a directory. Few filesystems handle so many directory entries with ease. Unless you're certain that your filesystem deals well with many files in a directory, you can consider another strategy (e.g. create more directories).

P.S. Also do not trust the remaining disk space – some file systems reserve some space for root and others miscalculate the free space and give you a number that just isn't true.

operator << must take exactly one argument

A friend function is not a member function, so the problem is that you declare operator<< as a friend of A:

 friend ostream& operator<<(ostream&, A&);

then try to define it as a member function of the class logic

 ostream& logic::operator<<(ostream& os, A& a)
          ^^^^^^^

Are you confused about whether logic is a class or a namespace?

The error is because you've tried to define a member operator<< taking two arguments, which means it takes three arguments including the implicit this parameter. The operator can only take two arguments, so that when you write a << b the two arguments are a and b.

You want to define ostream& operator<<(ostream&, const A&) as a non-member function, definitely not as a member of logic since it has nothing to do with that class!

std::ostream& operator<<(std::ostream& os, const A& a)
{
  return os << a.number;
}

How does Tomcat find the HOME PAGE of my Web App?

I already had index.html in the WebContent folder but it was not showing up , finally i added the following piece of code in my projects web.xml and it started showing up

  <servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping> 

Generate random colors (RGB)

With custom colours (for example, dark red, dark green and dark blue):

import random

COLORS = [(139, 0, 0), 
          (0, 100, 0),
          (0, 0, 139)]

def random_color():
    return random.choice(COLORS)

Comparing two vectors in an if statement

all is one option:

> A <- c("A", "B", "C", "D")
> B <- A
> C <- c("A", "C", "C", "E")

> all(A==B)
[1] TRUE
> all(A==C)
[1] FALSE

But you may have to watch out for recycling:

> D <- c("A","B","A","B")
> E <- c("A","B")
> all(D==E)
[1] TRUE
> all(length(D)==length(E)) && all(D==E)
[1] FALSE

The documentation for length says it currently only outputs an integer of length 1, but that it may change in the future, so that's why I wrapped the length test in all.

SVN Repository on Google Drive or DropBox

For free private SVN hosting try the following:

Or use BitBucket for free private git/mercurial repositories

Update Git branches from master

To update other branches like (backup) with your master branch copy. You can do follow either way (rebase or merge)...

  1. Do rebase (there won't be any extra commit made to the backup branch).
  2. Merge branches (there will be an extra commit automatically to the backup branch).

    Note : Rebase is nothing but establishing a new base (a new copy)

git checkout backup
git merge master
git push

(Repeat for other branches if any like backup2 & etc..,)

git checkout backup
git rebase master
git push

(Repeat for other branches if any like backup2 & etc..,)

Retrieve the commit log for a specific line in a file?

An extremely easy way to do this is by using vim-fugitive. Just open the file in vim, select the line(s) you're interested in using V, then enter

:Glog

Now you can use :cnext and :cprev to see all the revisions of the file where that line is modified. At any point, enter :Gblame to see the sha, author, and date info.

How to write loop in a Makefile?

This is not really a pure answer to the question, but an intelligent way to work around such problems:

instead of writing a complex file, simply delegate control to for instance a bash script like: makefile

foo : bar.cpp baz.h
    bash script.sh

and script.sh looks like:

for number in 1 2 3 4
do
    ./a.out $number
done

Configuration Error: <compilation debug="true" targetFramework="4.0"> ASP.NET MVC3

This typically happens when you have an attribute of targetFramework="4.0" in the web.config but the App Pool is set to run ASP.NET 2.0. The targetFramework attribute is entirely unrecognized by ASP.NET 2.0 - so changing it to 2.0 won't have the desired effect.

Contact Support / Your Administrator and have the AppPool switched to 4.0.

You could also remove the attribute entirely, however if your site was coded with the 4.0 Framework, then I'm sure something else will cause an error as well.

Unrecognized attribute 'targetFramework'. Note that attribute names are case-sensitive

Python+OpenCV: cv2.imwrite

This following code should extract face in images and save faces on disk

def detect(image):
    image_faces = []
    bitmap = cv.fromarray(image)
    faces = cv.HaarDetectObjects(bitmap, cascade, cv.CreateMemStorage(0))
    if faces:
        for (x,y,w,h),n in faces:
            image_faces.append(image[y:(y+h), x:(x+w)])
            #cv2.rectangle(image,(x,y),(x+w,y+h),(255,255,255),3)
    return image_faces

if __name__ == "__main__":
    cam = cv2.VideoCapture(0)
    while 1:
        _,frame =cam.read()
        image_faces = []
        image_faces = detect(frame)
        for i, face in enumerate(image_faces):
            cv2.imwrite("face-" + str(i) + ".jpg", face)

        #cv2.imshow("features", frame)
        if cv2.waitKey(1) == 0x1b: # ESC
            print 'ESC pressed. Exiting ...'
            break

Select mySQL based only on month and year

you can do it by changing $q to this:

$q="SELECT * FROM projects WHERE YEAR(date) = $year_v AND MONTH(date) = $month_v;

How to make the HTML link activated by clicking on the <li>?

You could try an "onclick" event inside the LI tag, and change the "location.href" as in javascript.

You could also try placing the li tags within the a tags, however this is probably not valid HTML.

Android - shadow on text?

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:padding="20dp" >

    <TextView
        android:id="@+id/textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:shadowColor="#000"
        android:shadowDx="0"
        android:shadowDy="0"
        android:shadowRadius="50"
        android:text="Text Shadow Example1"
        android:textColor="#FBFBFB"
        android:textSize="28dp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/textview2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="Text Shadow Example2"
        android:textColor="#FBFBFB"
        android:textSize="28dp"
        android:textStyle="bold" />

</LinearLayout>

In the above XML layout code, the textview1 is given with Shadow effect in the layout. below are the configuration items are

android:shadowDx – specifies the X-axis offset of shadow. You can give -/+ values, where -Dx draws a shadow on the left of text and +Dx on the right

android:shadowDy – it specifies the Y-axis offset of shadow. -Dy specifies a shadow above the text and +Dy specifies below the text.

android:shadowRadius – specifies how much the shadow should be blurred at the edges. Provide a small value if shadow needs to be prominent. android:shadowColor – specifies the shadow color


Shadow Effect on Android TextView pragmatically

Use below code snippet to get the shadow effect on the second TextView pragmatically.

TextView textv = (TextView) findViewById(R.id.textview2);
textv.setShadowLayer(30, 0, 0, Color.RED);        

Output :

enter image description here

EnterKey to press button in VBA Userform

Be sure to avoid "magic numbers" whenever possible, either by defining your own constants, or by using the built-in vbXXX constants.

In this instance we could use vbKeyReturn to indicate the enter key's keycode (replacing YourInputControl and SubToBeCalled).

   Private Sub YourInputControl_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
        If KeyCode = vbKeyReturn Then
             SubToBeCalled
        End If
   End Sub

This prevents a whole category of compatibility issues and simple typos, especially because VBA capitalizes identifiers for us.

Cheers!

How to get integer values from a string in Python?

Iterator version

>>> import re
>>> string1 = "498results should get"
>>> [int(x.group()) for x in re.finditer(r'\d+', string1)]
[498]

Access denied; you need (at least one of) the SUPER privilege(s) for this operation

Problem: You're trying to import data (using mysqldump file) to your mysql database ,but it seems you don't have permission to perform that operation.

Solution: Assuming you data is migrated ,seeded and updated in your mysql database, take snapshot using mysqldump and export it to file

mysqldump -u [username] -p [databaseName] --set-gtid-purged=OFF > [filename].sql

From mysql documentation:

GTID - A global transaction identifier (GTID) is a unique identifier created and associated with each transaction committed on the server of origin (master). This identifier is unique not only to the server on which it originated, but is unique across all servers in a given replication setup. There is a 1-to-1 mapping between all transactions and all GTIDs.

--set-gtid-purged=OFF SET @@GLOBAL.gtid_purged is not added to the output, and SET @@SESSION.sql_log_bin=0 is not added to the output. For a server where GTIDs are not in use, use this option or AUTO. Only use this option for a server where GTIDs are in use if you are sure that the required GTID set is already present in gtid_purged on the target server and should not be changed, or if you plan to identify and add any missing GTIDs manually.

Afterwards connect to your mysql with user root ,give permissions , flush them ,and verify that your user privileges were updated correctly.

mysql -u root -p
UPDATE mysql.user SET Super_Priv='Y' WHERE user='johnDoe' AND host='%';
FLUSH PRIVILEGES;
mysql> SHOW GRANTS FOR 'johnDoe';
+------------------------------------------------------------------+
| Grants for johnDoe                                               |
+------------------------------------------------------------------+
| GRANT USAGE ON *.* TO `johnDoe`                                  |
| GRANT ALL PRIVILEGES ON `db1`.* TO `johnDoe`                     |
+------------------------------------------------------------------+

now reload the data and the operation should be permitted.

mysql -h [host] -u [user] -p[pass] [db_name] < [mysql_dump_name].sql

Remove blank lines with grep

awk 'NF' file-with-blank-lines > file-with-no-blank-lines

CURL and HTTPS, "Cannot resolve host"

Your getting the error because you're probably doing it on your Local server environment. You need to skip the certificates check when the cURL call is made. For that just add the following options

curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($c, CURLOPT_SSL_VERIFYHOST,  0);

Java ArrayList for integers

You are trying to add an integer into an ArrayList that takes an array of integers Integer[]. It should be

ArrayList<Integer> list = new ArrayList<>();

or better

List<Integer> list = new ArrayList<>();

How to get the current working directory using python 3?

It seems that IDLE changes its current working dir to location of the script that is executed, while when running the script using cmd doesn't do that and it leaves CWD as it is.

To change current working dir to the one containing your script you can use:

import os
os.chdir(os.path.dirname(__file__))
print(os.getcwd())

The __file__ variable is available only if you execute script from file, and it contains path to the file. More on it here: Python __file__ attribute absolute or relative?

pandas resample documentation

B         business day frequency
C         custom business day frequency (experimental)
D         calendar day frequency
W         weekly frequency
M         month end frequency
SM        semi-month end frequency (15th and end of month)
BM        business month end frequency
CBM       custom business month end frequency
MS        month start frequency
SMS       semi-month start frequency (1st and 15th)
BMS       business month start frequency
CBMS      custom business month start frequency
Q         quarter end frequency
BQ        business quarter endfrequency
QS        quarter start frequency
BQS       business quarter start frequency
A         year end frequency
BA, BY    business year end frequency
AS, YS    year start frequency
BAS, BYS  business year start frequency
BH        business hour frequency
H         hourly frequency
T, min    minutely frequency
S         secondly frequency
L, ms     milliseconds
U, us     microseconds
N         nanoseconds

See the timeseries documentation. It includes a list of offsets (and 'anchored' offsets), and a section about resampling.

Note that there isn't a list of all the different how options, because it can be any NumPy array function and any function that is available via groupby dispatching can be passed to how by name.

How to increase the max upload file size in ASP.NET?

for a 2 GB max limit, on your application web.config:

<system.web>
  <compilation debug="true" targetFramework="4.5" />
  <httpRuntime targetFramework="4.5" maxRequestLength="2147483647" executionTimeout="1600" requestLengthDiskThreshold="2147483647" />
</system.web>

<system.webServer>
  <security>
    <requestFiltering>
      <requestLimits maxAllowedContentLength="2147483647" />
    </requestFiltering>
  </security>
</system.webServer>

How to use struct timeval to get the execution time?

Change:

struct timeval, tvalBefore, tvalAfter; /* Looks like an attempt to
                                          delcare a variable with
                                          no name. */

to:

struct timeval tvalBefore, tvalAfter;

It is less likely (IMO) to make this mistake if there is a single declaration per line:

struct timeval tvalBefore;
struct timeval tvalAfter;

It becomes more error prone when declaring pointers to types on a single line:

struct timeval* tvalBefore, tvalAfter;

tvalBefore is a struct timeval* but tvalAfter is a struct timeval.

Eclipse CDT: Symbol 'cout' could not be resolved

I had this happen after updating gcc and eclipse on ArchLinux. What solved it for me was Project -> C/C++ Index -> Rebuild.

What is the difference between a Docker image and a container?

Dockerfile is like your Bash script that produce a tarball (Docker image).

Docker containers is like extracted version of the tarball. You can have as many copies as you like in different folders (the containers).

SqlBulkCopy - The given value of type String from the data source cannot be converted to type money of the specified target column

Please use SqlBulkCopyColumnMapping.

Example:

private void SaveFileToDatabase(string filePath)
{
    string strConnection = System.Configuration.ConfigurationManager.ConnectionStrings["MHMRA_TexMedEvsConnectionString"].ConnectionString.ToString();

    String excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0\"", filePath);
    //Create Connection to Excel work book 
    using (OleDbConnection excelConnection = new OleDbConnection(excelConnString))
    {
        //Create OleDbCommand to fetch data from Excel 
        using (OleDbCommand cmd = new OleDbCommand("Select * from [Crosswalk$]", excelConnection))
        {
            excelConnection.Open();
            using (OleDbDataReader dReader = cmd.ExecuteReader())
            {
                using (SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection))
                {
                    //Give your Destination table name 
                    sqlBulk.DestinationTableName = "PaySrcCrosswalk";

                    // this is a simpler alternative to explicit column mappings, if the column names are the same on both sides and data types match
                    foreach(DataColumn column in dt.Columns) {
                         s.ColumnMappings.Add(new SqlBulkCopyColumnMapping(column.ColumnName, column.ColumnName));
                     }
                   
                    sqlBulk.WriteToServer(dReader);
                }
            }
        }
    }
}  

codes for ADD,EDIT,DELETE,SEARCH in vb2010

A good resource start off point would be MSDN as your looking into a microsoft product

virtualbox Raw-mode is unavailable courtesy of Hyper-V windows 10

You may need to disable the hypervisor.

So, follow the next steps:

1) Open command prompt as Administrator

2) Run bcdedit to check hypervisor status:

bcdedit

3) Check hypervisor launch type:

image showing command output with 'hypervisorlaunchtype Auto' marked

4) If is set to auto then disable it:

bcdedit /set hypervisorlaunchtype off

5) Reboot host machine and launch VirtualBox again

React: why child component doesn't update when prop changes

Use the setState function. So you could do

       this.setState({this.state.foo.bar:123}) 

inside the handle event method.

Once, the state is updated, it will trigger changes, and re-render will take place.

jQuery hover and class selector

I prefer foxy's answer because we should never use javascript when existing css properties are made for the job.

Don't forget to add display: block ; in .menuItem, so height and width are taken into account.

edit : for better script/look&feel decoupling, if you ever need to change style through jQuery I'd define an additional css class and use $(...).addClass("myclass") and $(...).removeClass("myclass")

Replace single quotes in SQL Server

Try escaping the single quote with a single quote:

Replace(@strip, '''', '')

Difference between matches() and find() in Java Regex

matches() will only return true if the full string is matched. find() will try to find the next occurrence within the substring that matches the regex. Note the emphasis on "the next". That means, the result of calling find() multiple times might not be the same. In addition, by using find() you can call start() to return the position the substring was matched.

final Matcher subMatcher = Pattern.compile("\\d+").matcher("skrf35kesruytfkwu4ty7sdfs");
System.out.println("Found: " + subMatcher.matches());
System.out.println("Found: " + subMatcher.find() + " - position " + subMatcher.start());
System.out.println("Found: " + subMatcher.find() + " - position " + subMatcher.start());
System.out.println("Found: " + subMatcher.find() + " - position " + subMatcher.start());
System.out.println("Found: " + subMatcher.find());
System.out.println("Found: " + subMatcher.find());
System.out.println("Matched: " + subMatcher.matches());

System.out.println("-----------");
final Matcher fullMatcher = Pattern.compile("^\\w+$").matcher("skrf35kesruytfkwu4ty7sdfs");
System.out.println("Found: " + fullMatcher.find() + " - position " + fullMatcher.start());
System.out.println("Found: " + fullMatcher.find());
System.out.println("Found: " + fullMatcher.find());
System.out.println("Matched: " + fullMatcher.matches());
System.out.println("Matched: " + fullMatcher.matches());
System.out.println("Matched: " + fullMatcher.matches());
System.out.println("Matched: " + fullMatcher.matches());

Will output:

Found: false
Found: true - position 4
Found: true - position 17
Found: true - position 20
Found: false
Found: false
Matched: false
-----------
Found: true - position 0
Found: false
Found: false
Matched: true
Matched: true
Matched: true
Matched: true

So, be careful when calling find() multiple times if the Matcher object was not reset, even when the regex is surrounded with ^ and $ to match the full string.

Remove a marker from a GoogleMap

to clear all scribbles in the map use

map.clear()

Fastest way to check a string is alphanumeric in Java

Use String.matches(), like:

String myString = "qwerty123456";
System.out.println(myString.matches("[A-Za-z0-9]+"));

That may not be the absolute "fastest" possible approach. But in general there's not much point in trying to compete with the people who write the language's "standard library" in terms of performance.

javascript set cookie with expire time

Your browser may be configured to accept only session cookies; if this is your case, any expiry time is transformed into session by your browser, you can change this setting of your browser or try another browser without such a configuration

In nodeJs is there a way to loop through an array without using array size?

    var count=0;
    let myArray = '{"1":"a","2":"b","3":"c","4":"d"}'
    var data = JSON.parse(myArray);
    for (let key in data) {
      let value =  data[key]; // get the value by key
      console.log("key: , value:", key, value);
      count = count + 1;
    }
   console.log("size:",count);

How to size an Android view based on its parent's dimensions

If the other side is empty. I guess the simplest way would be to add an empty view (e.g. a linear layout) then set both views' widths to fill_parent and both their weights to 1.

This works in a LinearLayout...

Display TIFF image in all web browser

You can try converting your image from tiff to PNG, here is how to do it:

import com.sun.media.jai.codec.ImageCodec;
import com.sun.media.jai.codec.ImageDecoder;
import com.sun.media.jai.codec.ImageEncoder;
import com.sun.media.jai.codec.PNGEncodeParam;
import com.sun.media.jai.codec.TIFFDecodeParam;
import java.awt.image.RenderedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import javaxt.io.Image;

public class ImgConvTiffToPng {

    public static byte[] convert(byte[] tiff) throws Exception {

        byte[] out = new byte[0];
        InputStream inputStream = new ByteArrayInputStream(tiff);

        TIFFDecodeParam param = null;

        ImageDecoder dec = ImageCodec.createImageDecoder("tiff", inputStream, param);
        RenderedImage op = dec.decodeAsRenderedImage(0);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        PNGEncodeParam jpgparam = null;
        ImageEncoder en = ImageCodec.createImageEncoder("png", outputStream, jpgparam);
        en.encode(op);
        outputStream = (ByteArrayOutputStream) en.getOutputStream();
        out = outputStream.toByteArray();
        outputStream.flush();
        outputStream.close();

        return out;

    }

Update React component every second

@Waisky suggested:

You need to use setInterval to trigger the change, but you also need to clear the timer when the component unmounts to prevent it leaving errors and leaking memory:

If you'd like to do the same thing, using Hooks:

const [time, setTime] = useState(Date.now());

useEffect(() => {
  const interval = setInterval(() => setTime(Date.now()), 1000);
  return () => {
    clearInterval(interval);
  };
}, []);

Regarding the comments:

You don't need to pass anything inside []. If you pass time in the brackets, it means run the effect every time the value of time changes, i.e., it invokes a new setInterval every time, time changes, which is not what we're looking for. We want to only invoke setInterval once when the component gets mounted and then setInterval calls setTime(Date.now()) every 1000 seconds. Finally, we invoke clearInterval when the component is unmounted.

Note that the component gets updated, based on how you've used time in it, every time the value of time changes. That has nothing to do with putting time in [] of useEffect.

How do I fix the indentation of selected lines in Visual Studio

Selecting the text to fix, and CtrlK, CtrlF shortcut certainly works. However, I generally find that if a particular method (for instance) has it's indentation messed up, simply removing the closing brace of the method, and re-adding, in fact fixes the indentation anyway, thereby doing without the need to select the code before hand, ergo is quicker. ymmv.

What is so bad about singletons?

Singletons solve one (and only one) problem.

Resource Contention.

If you have some resource that

(1) can only have a single instance, and

(2) you need to manage that single instance,

you need a singleton.

There aren't many examples. A log file is the big one. You don't want to just abandon a single log file. You want to flush, sync and close it properly. This is an example of a single shared resource that has to be managed.

It's rare that you need a singleton. The reason they're bad is that they feel like a global and they're a fully paid up member of the GoF Design Patterns book.

When you think you need a global, you're probably making a terrible design mistake.

slf4j: how to log formatted message, object array, exception

As of SLF4J 1.6.0, in the presence of multiple parameters and if the last argument in a logging statement is an exception, then SLF4J will presume that the user wants the last argument to be treated as an exception and not a simple parameter. See also the relevant FAQ entry.

So, writing (in SLF4J version 1.7.x and later)

 logger.error("one two three: {} {} {}", "a", "b", 
              "c", new Exception("something went wrong"));

or writing (in SLF4J version 1.6.x)

 logger.error("one two three: {} {} {}", new Object[] {"a", "b", 
              "c", new Exception("something went wrong")});

will yield

one two three: a b c
java.lang.Exception: something went wrong
    at Example.main(Example.java:13)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at ...

The exact output will depend on the underlying framework (e.g. logback, log4j, etc) as well on how the underlying framework is configured. However, if the last parameter is an exception it will be interpreted as such regardless of the underlying framework.

matplotlib colorbar in each subplot

This can be easily solved with the the utility make_axes_locatable. I provide a minimal example that shows how this works and should be readily adaptable:

bar to each image

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable

import numpy as np

m1 = np.random.rand(3, 3)
m2 = np.arange(0, 3*3, 1).reshape((3, 3))

fig = plt.figure(figsize=(16, 12))
ax1 = fig.add_subplot(121)
im1 = ax1.imshow(m1, interpolation='None')

divider = make_axes_locatable(ax1)
cax = divider.append_axes('right', size='5%', pad=0.05)
fig.colorbar(im1, cax=cax, orientation='vertical')

ax2 = fig.add_subplot(122)
im2 = ax2.imshow(m2, interpolation='None')

divider = make_axes_locatable(ax2)
cax = divider.append_axes('right', size='5%', pad=0.05)
fig.colorbar(im2, cax=cax, orientation='vertical');

java.io.IOException: Invalid Keystore format

Maybe maven encoding you KeyStore, you can set filtering=false to fix this problem.

<build>
    ...
    <resources>
        <resource>
            ...
            <!-- set filtering=false to fix -->
            <filtering>false</filtering>
            ...
        </resource>
    </resources>
</build>

Using variables inside a bash heredoc

Don't use quotes with <<EOF:

var=$1
sudo tee "/path/to/outfile" > /dev/null <<EOF
Some text that contains my $var
EOF

Variable expansion is the default behavior inside of here-docs. You disable that behavior by quoting the label (with single or double quotes).

How to transform numpy.matrix or array to scipy sparse matrix

In Python, the Scipy library can be used to convert the 2-D NumPy matrix into a Sparse matrix. SciPy 2-D sparse matrix package for numeric data is scipy.sparse

The scipy.sparse package provides different Classes to create the following types of Sparse matrices from the 2-dimensional matrix:

  1. Block Sparse Row matrix
  2. A sparse matrix in COOrdinate format.
  3. Compressed Sparse Column matrix
  4. Compressed Sparse Row matrix
  5. Sparse matrix with DIAgonal storage
  6. Dictionary Of Keys based sparse matrix.
  7. Row-based list of lists sparse matrix
  8. This class provides a base class for all sparse matrices.

CSR (Compressed Sparse Row) or CSC (Compressed Sparse Column) formats support efficient access and matrix operations.

Example code to Convert Numpy matrix into Compressed Sparse Column(CSC) matrix & Compressed Sparse Row (CSR) matrix using Scipy classes:

import sys                 # Return the size of an object in bytes
import numpy as np         # To create 2 dimentional matrix
from scipy.sparse import csr_matrix, csc_matrix 
# csr_matrix: used to create compressed sparse row matrix from Matrix
# csc_matrix: used to create compressed sparse column matrix from Matrix

create a 2-D Numpy matrix

A = np.array([[1, 0, 0, 0, 0, 0],\
              [0, 0, 2, 0, 0, 1],\
              [0, 0, 0, 2, 0, 0]])
print("Dense matrix representation: \n", A)
print("Memory utilised (bytes): ", sys.getsizeof(A))
print("Type of the object", type(A))

Print the matrix & other details:

Dense matrix representation: 
 [[1 0 0 0 0 0]
 [0 0 2 0 0 1]
 [0 0 0 2 0 0]]
Memory utilised (bytes):  184
Type of the object <class 'numpy.ndarray'>

Converting Matrix A to the Compressed sparse row matrix representation using csr_matrix Class:

S = csr_matrix(A)
print("Sparse 'row' matrix: \n",S)
print("Memory utilised (bytes): ", sys.getsizeof(S))
print("Type of the object", type(S))

The output of print statements:

Sparse 'row' matrix:
(0, 0) 1
(1, 2) 2
(1, 5) 1
(2, 3) 2
Memory utilised (bytes): 56
Type of the object: <class 'scipy.sparse.csr.csc_matrix'>

Converting Matrix A to Compressed Sparse Column matrix representation using csc_matrix Class:

S = csc_matrix(A)
print("Sparse 'column' matrix: \n",S)
print("Memory utilised (bytes): ", sys.getsizeof(S))
print("Type of the object", type(S))

The output of print statements:

Sparse 'column' matrix:
(0, 0) 1
(1, 2) 2
(2, 3) 2
(1, 5) 1
Memory utilised (bytes): 56
Type of the object: <class 'scipy.sparse.csc.csc_matrix'>

As it can be seen the size of the compressed matrices is 56 bytes and the original matrix size is 184 bytes.

For a more detailed explanation and code examples please refer to this article: https://limitlessdatascience.wordpress.com/2020/11/26/sparse-matrix-in-machine-learning/

How to ignore the certificate check when ssl

Tip: You can also use this method to track certificates that are due to expire soon. This can save your bacon if you discover a cert that is about to expire and can get it fixed in time. Good also for third party companies - for us this is DHL / FedEx. DHL just let a cert expire which is screwing us up 3 days before Thanksgiving. Fortunately I'm around to fix it ... this time!

    private static DateTime? _nextCertWarning;
    private static bool ValidateRemoteCertificate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)
    {
        if (error == SslPolicyErrors.None)
        {
            var cert2 = cert as X509Certificate2;
            if (cert2 != null)
            { 
                // If cert expires within 2 days send an alert every 2 hours
                if (cert2.NotAfter.AddDays(-2) < DateTime.Now)
                {
                    if (_nextCertWarning == null || _nextCertWarning < DateTime.Now)
                    {
                        _nextCertWarning = DateTime.Now.AddHours(2);

                        ProwlUtil.StepReached("CERT EXPIRING WITHIN 2 DAYS " + cert, cert.GetCertHashString());   // this is my own function
                    }
                }
            }

            return true;
        }
        else
        {
            switch (cert.GetCertHashString())
            {
                // Machine certs - SELF SIGNED
                case "066CF9CAD814DE2097D367F22D3A7E398B87C4D6":    

                    return true;

                default:
                    ProwlUtil.StepReached("UNTRUSTED CERT " + cert, cert.GetCertHashString());
                    return false;
            }
        }
    }

What does 'synchronized' mean?

Well, I think we had enough of theoretical explanations, so consider this code

public class SOP {
    public static void print(String s) {
        System.out.println(s+"\n");
    }
}

public class TestThread extends Thread {
    String name;
    TheDemo theDemo;
    public TestThread(String name,TheDemo theDemo) {
        this.theDemo = theDemo;
        this.name = name;
        start();
    }
    @Override
    public void run() {
        theDemo.test(name);
    }
}

public class TheDemo {
    public synchronized void test(String name) {
        for(int i=0;i<10;i++) {
            SOP.print(name + " :: "+i);
            try{
                Thread.sleep(500);
            } catch (Exception e) {
                SOP.print(e.getMessage());
            }
        }
    }
    public static void main(String[] args) {
        TheDemo theDemo = new TheDemo();
        new TestThread("THREAD 1",theDemo);
        new TestThread("THREAD 2",theDemo);
        new TestThread("THREAD 3",theDemo);
    }
}

Note: synchronized blocks the next thread's call to method test() as long as the previous thread's execution is not finished. Threads can access this method one at a time. Without synchronized all threads can access this method simultaneously.

When a thread calls the synchronized method 'test' of the object (here object is an instance of 'TheDemo' class) it acquires the lock of that object, any new thread cannot call ANY synchronized method of the same object as long as previous thread which had acquired the lock does not release the lock.

Similar thing happens when any static synchronized method of the class is called. The thread acquires the lock associated with the class(in this case any non static synchronized method of an instance of that class can be called by any thread because that object level lock is still available). Any other thread will not be able to call any static synchronized method of the class as long as the class level lock is not released by the thread which currently holds the lock.

Output with synchronised

THREAD 1 :: 0
THREAD 1 :: 1
THREAD 1 :: 2
THREAD 1 :: 3
THREAD 1 :: 4
THREAD 1 :: 5
THREAD 1 :: 6
THREAD 1 :: 7
THREAD 1 :: 8
THREAD 1 :: 9
THREAD 3 :: 0
THREAD 3 :: 1
THREAD 3 :: 2
THREAD 3 :: 3
THREAD 3 :: 4
THREAD 3 :: 5
THREAD 3 :: 6
THREAD 3 :: 7
THREAD 3 :: 8
THREAD 3 :: 9
THREAD 2 :: 0
THREAD 2 :: 1
THREAD 2 :: 2
THREAD 2 :: 3
THREAD 2 :: 4
THREAD 2 :: 5
THREAD 2 :: 6
THREAD 2 :: 7
THREAD 2 :: 8
THREAD 2 :: 9

Output without synchronized

THREAD 1 :: 0
THREAD 2 :: 0
THREAD 3 :: 0
THREAD 1 :: 1
THREAD 2 :: 1
THREAD 3 :: 1
THREAD 1 :: 2
THREAD 2 :: 2
THREAD 3 :: 2
THREAD 1 :: 3
THREAD 2 :: 3
THREAD 3 :: 3
THREAD 1 :: 4
THREAD 2 :: 4
THREAD 3 :: 4
THREAD 1 :: 5
THREAD 2 :: 5
THREAD 3 :: 5
THREAD 1 :: 6
THREAD 2 :: 6
THREAD 3 :: 6
THREAD 1 :: 7
THREAD 2 :: 7
THREAD 3 :: 7
THREAD 1 :: 8
THREAD 2 :: 8
THREAD 3 :: 8
THREAD 1 :: 9
THREAD 2 :: 9
THREAD 3 :: 9

grant remote access of MySQL database from any IP address

Use this command:

GRANT ALL ON yourdatabasename.* TO root@'%' IDENTIFIED BY 'yourRootPassword';

Then:

FLUSH PRIVILEGES; 

Then comment out the below line in file "/etc/mysql/mysql.conf.d/mysqld.cnf" (is required!):

bind-address = 127.0.0.1 

Works for me!

MySQL - UPDATE query based on SELECT Query

Easy in MySQL:

UPDATE users AS U1, users AS U2 
SET U1.name_one = U2.name_colX
WHERE U2.user_id = U1.user_id

Laravel 5 Failed opening required bootstrap/../vendor/autoload.php

I got this when I did composer update instead of composer install.

How to solve WAMP and Skype conflict on Windows 7?

I know this posting is old, but I had the same problem, WAMP would not go online (green) while SKYPE was running. I simply closed SKYPE, ran WAMP and then reloaded SKYPE. I have not verified this, but I think SKYPE port corrected to allow for WAMP settings. At least I have not experienced any problems doing it this way

How to stop event bubbling on checkbox click

Credit to @mehras for the code. I just created a snippet to demonstrate it because I thought that would be appreciated and I wanted an excuse to try that feature.

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('#container').addClass('hidden');_x000D_
  $('#header').click(function() {_x000D_
    if ($('#container').hasClass('hidden')) {_x000D_
      $('#container').removeClass('hidden');_x000D_
    } else {_x000D_
      $('#container').addClass('hidden');_x000D_
    }_x000D_
  });_x000D_
  $('#header input[type=checkbox]').click(function(event) {_x000D_
    if (event.stopPropagation) { // standard_x000D_
      event.stopPropagation();_x000D_
    } else { // IE6-8_x000D_
      event.cancelBubble = true;_x000D_
    }_x000D_
  });_x000D_
});
_x000D_
div {_x000D_
  text-align: center;_x000D_
  padding: 2em;_x000D_
  font-size: 1.2em_x000D_
}_x000D_
_x000D_
.hidden {_x000D_
  display: none;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div id="header"><input type="checkbox" />Checkbox won't bubble the event, but this text will.</div>_x000D_
<div id="container">click() bubbled up!</div>
_x000D_
_x000D_
_x000D_

Difference between object and class in Scala

In scala, there is no static concept. So scala creates a singleton object to provide entry point for your program execution. If you don't create singleton object, your code will compile successfully but will not produce any output. Methods declared inside Singleton Object are accessible globally. A singleton object can extend classes and traits.

Scala Singleton Object Example

object Singleton{  
    def main(args:Array[String]){  
        SingletonObject.hello()         // No need to create object.  
    }  
}  


object SingletonObject{  
    def hello(){  
        println("Hello, This is Singleton Object")  
    }  
}  

Output:

Hello, This is Singleton Object

In scala, when you have a class with same name as singleton object, it is called companion class and the singleton object is called companion object.

The companion class and its companion object both must be defined in the same source file.

Scala Companion Object Example

class ComapanionClass{  
    def hello(){  
        println("Hello, this is Companion Class.")  
    }  
}  
object CompanoinObject{  
    def main(args:Array[String]){  
        new ComapanionClass().hello()  
        println("And this is Companion Object.")  
    }  
}  

Output:

Hello, this is Companion Class.
And this is Companion Object.

In scala, a class can contain:

1. Data member

2. Member method

3. Constructor Block

4. Nested class

5. Super class information etc.

You must initialize all instance variables in the class. There is no default scope. If you don't specify access scope, it is public. There must be an object in which main method is defined. It provides starting point for your program. Here, we have created an example of class.

Scala Sample Example of Class

class Student{  
    var id:Int = 0;                         // All fields must be initialized  
    var name:String = null;  
}  
object MainObject{  
    def main(args:Array[String]){  
        var s = new Student()               // Creating an object  
        println(s.id+" "+s.name);  
    }  
} 

I am sorry, I am too late but I hope it will help you.

Bootstrap 3 breakpoints and media queries

Bootstrap does not document the media queries very well. Those variables of @screen-sm, @screen-md, @screen-lg are actually referring to LESS variables and not simple CSS.

When you customize Bootstrap you can change the media query breakpoints and when it compiles the @screen-xx variables are changed to whatever pixel width you defined as screen-xx. This is how a framework like this can be coded once and then customized by the end user to fit their needs.

A similar question on here that might provide more clarity: Bootstrap 3.0 Media queries

In your CSS, you will still have to use traditional media queries to override or add to what Bootstrap is doing.

In regards to your second question, that is not a typo. Once the screen goes below 768px the framework becomes completely fluid and resizes at any device width, removing the need for breakpoints. The breakpoint at 480px exists because there are specific changes that occur to the layout for mobile optimization.

To see this in action, go to this example on their site (http://getbootstrap.com/examples/navbar-fixed-top/), and resize your window to see how it treats the design after 768px.

How to run python script on terminal (ubuntu)?

First create the file you want, with any editor like vi r gedit. And save with. Py extension.In that the first line should be

!/usr/bin/env python

google console error `OR-IEH-01`

It looks like your Google Play registration payment didn’t process. This can happen sometimes if a card has expired, the credit card or credit card verification (CVC) number was entered incorrectly, or if your billing address doesn't match the address in your Google Payments account.

Here’s how you can find the details of your transaction:

  1. Sign in to your Google Payments account at https://payments.google.com.

  2. On the left menu, select the “Subscriptions and services” page.

  3. On the “Other purchase activity” card, click View purchases.

  4. Click the “Google Play” registration transaction to see your payment method.

  5. You can click “Payment methods” on the left menu if you need to edit the addresses on your Google Payments account.

To add a new credit or debit card to your account, you can follow the instructions on the Google Payments Help Center (https://support.google.com/payments/answer/6220309).

Select row and element in awk

Since awk and perl are closely related...


Perl equivalents of @Dennis's awk solutions:

To print the second line:
perl -ne 'print if $. == 2' file

To print the second field:
perl -lane 'print $F[1]' file

To print the third field of the fifth line:
perl -lane 'print $F[2] if $. == 5' file


Perl equivalent of @Glenn's solution:

Print the j'th field of the i'th line

perl -lanse 'print $F[$j-1] if $. == $i' -- -i=5 -j=3 file


Perl equivalents of @Hai's solutions:

if you are looking for second columns that contains abc:

perl -lane 'print if $F[1] =~ /abc/' foo

... and if you want to print only a particular column:

perl -lane 'print $F[2] if $F[1] =~ /abc/' foo

... and for a particular line number:

perl -lane 'print $F[2] if $F[1] =~ /abc/ && $. == 5' foo


-l removes newlines, and adds them back in when printing
-a autosplits the input line into array @F, using whitespace as the delimiter
-n loop over each line of the input file
-e execute the code within quotes
$F[1] is the second element of the array, since Perl starts at 0
$. is the line number

JSON.parse unexpected character error

You're not parsing a string, you're parsing an already-parsed object :)

var obj1 = JSON.parse('{"creditBalance":0,...,"starStatus":false}');
//                    ^                                          ^
//                    if you want to parse, the input should be a string 

var obj2 = {"creditBalance":0,...,"starStatus":false};
// or just use it directly.

SQL Server Profiler - How to filter trace to only display events from one database?

Create a new template and check DBname. Use that template for your tracefile.

How to download python from command-line?

wget --no-check-certificate https://www.python.org/ftp/python/2.7.11/Python-2.7.11.tgz
tar -xzf Python-2.7.11.tgz  
cd Python-2.7.11

Now read the README file to figure out how to install, or do the following with no guarantees from me that it will be exactly what you need.

./configure  
make  
sudo make install  

For Python 3.5 use the following download address:
http://www.python.org/ftp/python/3.5.1/Python-3.5.1.tgz

For other versions and the most up to date download links:
http://www.python.org/getit/

django MultiValueDictKeyError error, how do I deal with it

Choose what is best for you:

1

is_private = request.POST.get('is_private', False);

If is_private key is present in request.POST the is_private variable will be equal to it, if not, then it will be equal to False.

2

if 'is_private' in request.POST:
    is_private = request.POST['is_private']
else:
    is_private = False

3

from django.utils.datastructures import MultiValueDictKeyError
try:
    is_private = request.POST['is_private']
except MultiValueDictKeyError:
    is_private = False

How do you log content of a JSON object in Node.js?

This will for most of the objects for outputting in nodejs console

_x000D_
_x000D_
var util = require('util')_x000D_
function print (data){_x000D_
  console.log(util.inspect(data,true,12,true))_x000D_
  _x000D_
}_x000D_
_x000D_
print({name : "Your name" ,age : "Your age"})
_x000D_
_x000D_
_x000D_

How to catch an Exception from a thread

That's because exceptions are local to a thread, and your main thread doesn't actually see the run method. I suggest you read more about how threading works, but to quickly summarize: your call to start starts up a different thread, totally unrelated to your main thread. The call to join simply waits for it to be done. An exception that is thrown in a thread and never caught terminates it, which is why join returns on your main thread, but the exception itself is lost.

If you want to be aware of these uncaught exceptions you can try this:

Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
    @Override
    public void uncaughtException(Thread t, Throwable e) {
        System.out.println("Caught " + e);
    }
});

More information about uncaught exception handling can be found here.

Which characters make a URL invalid?

All valid characters that can be used in a URI (a URL is a type of URI) are defined in RFC 3986.

All other characters can be used in a URL provided that they are "URL Encoded" first. This involves changing the invalid character for specific "codes" (usually in the form of the percent symbol (%) followed by a hexadecimal number).

This link, HTML URL Encoding Reference, contains a list of the encodings for invalid characters.

Count number of times a date occurs and make a graph out of it

The simplest is to do a PivotChart. Select your array of dates (with a header) and create a new Pivot Chart (Insert / PivotChart / Ok) Then on the field list window, drag and drop the date column in the Axis list first and then in the value list first.

Step 1:

Step1

Step 2:

Step2

How do android screen coordinates work?

This picture will remove everyone's confusion hopefully which is collected from there.

Android screen coordinate

How can I convert a cv::Mat to a gray scale in OpenCv?

Using the C++ API, the function name has slightly changed and it writes now:

#include <opencv2/imgproc/imgproc.hpp>

cv::Mat greyMat, colorMat;
cv::cvtColor(colorMat, greyMat, CV_BGR2GRAY);

The main difficulties are that the function is in the imgproc module (not in the core), and by default cv::Mat are in the Blue Green Red (BGR) order instead of the more common RGB.

OpenCV 3

Starting with OpenCV 3.0, there is yet another convention. Conversion codes are embedded in the namespace cv:: and are prefixed with COLOR. So, the example becomes then:

#include <opencv2/imgproc/imgproc.hpp>

cv::Mat greyMat, colorMat;
cv::cvtColor(colorMat, greyMat, cv::COLOR_BGR2GRAY);

As far as I have seen, the included file path hasn't changed (this is not a typo).

How to save/restore serializable object to/from file?

You'll need to serialize to something: that is, pick binary, or xml (for default serializers) or write custom serialization code to serialize to some other text form.

Once you've picked that, your serialization will (normally) call a Stream that is writing to some kind of file.

So, with your code, if I were using XML Serialization:

var path = @"C:\Test\myserializationtest.xml";
using(FileStream fs = new FileStream(path, FileMode.Create))
{
    XmlSerializer xSer = new XmlSerializer(typeof(SomeClass));

    xSer.Serialize(fs, serializableObject);
}

Then, to deserialize:

using(FileStream fs = new FileStream(path, FileMode.Open)) //double check that...
{
    XmlSerializer _xSer = new XmlSerializer(typeof(SomeClass));

    var myObject = _xSer.Deserialize(fs);
}

NOTE: This code hasn't been compiled, let alone run- there may be some errors. Also, this assumes completely out-of-the-box serialization/deserialization. If you need custom behavior, you'll need to do additional work.

Action Bar's onClick listener for the Home button

You need to explicitly enable the home action if running on ICS. From the docs:

Note: If you're using the icon to navigate to the home activity, beware that beginning with Android 4.0 (API level 14), you must explicitly enable the icon as an action item by calling setHomeButtonEnabled(true) (in previous versions, the icon was enabled as an action item by default).

Find a file with a certain extension in folder

You could use the Directory class

 Directory.GetFiles(path, "*.txt", SearchOption.AllDirectories)

T-SQL query to show table definition?

I know it's an old question, but exactly what I was looking for. Because I want to batch script some tables, I rewrote the C# code from Anthony Faull for PowerShell.

This one is uses Integrated Security:

Import-Module sqlps

$serverInstance = "<server>"
$database = "<database>"
$table = "<table>"
$schema = "<schema>"

$options = New-Object -TypeName Microsoft.SqlServer.Management.Smo.ScriptingOptions
$options.DriAll = $true
$options.SchemaQualify = $true

$connection = New-Object -TypeName Microsoft.SqlServer.Management.Common.ServerConnection `
    -ArgumentList $serverInstance
$server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server `
    -ArgumentList $connection

$server.Databases.Item($database).Tables.Item($table, $schema).Script($options) `
    | ForEach-Object -Process { $_ + "`nGO"}

And here with username and password:

Import-Module sqlps

$serverInstance = "<server>"
$user = "<user>"
$password = "<pasword>"
$database = "<database>"
$table = "<table>"
$schema = "<schema>"

$options = New-Object -TypeName Microsoft.SqlServer.Management.Smo.ScriptingOptions
$options.DriAll = $true
$options.SchemaQualify = $true

$connection = New-Object -TypeName Microsoft.SqlServer.Management.Common.ServerConnection `
    -ArgumentList $serverInstance
$connection.LoginSecure = $false
$connection.Login = $user
$connection.Password = $password
$server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server `
    -ArgumentList $connection

$server.Databases.Item($database).Tables.Item($table, $schema).Script($options) `
    | ForEach-Object -Process { $_ + "`nGO"}

Add ... if string is too long PHP

$string = "Hello, this is the first example, where I am going to have a string that is over 50 characters and is super long, I don't know how long maybe around 1000 characters. Anyway this should be over 50 characters know...";

if(strlen($string) >= 50)
{
    echo substr($string, 50); //prints everything after 50th character
    echo substr($string, 0, 50); //prints everything before 50th character
}

Storing Images in DB - Yea or Nay?

This might be a bit of a long shot, but if you're using (or planning on using) SQL Server 2008 I'd recommend having a look at the new FileStream data type.

FileStream solves most of the problems around storing the files in the DB:

  1. The Blobs are actually stored as files in a folder.
  2. The Blobs can be accessed using either a database connection or over the filesystem.
  3. Backups are integrated.
  4. Migration "just works".

However SQL's "Transparent Data Encryption" does not encrypt FileStream objects, so if that is a consideration, you may be better off just storing them as varbinary.

From the MSDN Article:

Transact-SQL statements can insert, update, query, search, and back up FILESTREAM data. Win32 file system interfaces provide streaming access to the data.
FILESTREAM uses the NT system cache for caching file data. This helps reduce any effect that FILESTREAM data might have on Database Engine performance. The SQL Server buffer pool is not used; therefore, this memory is available for query processing.

blur vs focusout -- any real differences?

The documentation for focusout says (emphasis mine):

The focusout event is sent to an element when it, or any element inside of it, loses focus. This is distinct from the blur event in that it supports detecting the loss of focus on descendant elements (in other words, it supports event bubbling).

The same distinction exists between the focusin and focus events.

Warning message: In `...` : invalid factor level, NA generated

The warning message is because your "Type" variable was made a factor and "lunch" was not a defined level. Use the stringsAsFactors = FALSE flag when making your data frame to force "Type" to be a character.

> fixed <- data.frame("Type" = character(3), "Amount" = numeric(3))
> str(fixed)
'data.frame':   3 obs. of  2 variables:
 $ Type  : Factor w/ 1 level "": NA 1 1
 $ Amount: chr  "100" "0" "0"
> 
> fixed <- data.frame("Type" = character(3), "Amount" = numeric(3),stringsAsFactors=FALSE)
> fixed[1, ] <- c("lunch", 100)
> str(fixed)
'data.frame':   3 obs. of  2 variables:
 $ Type  : chr  "lunch" "" ""
 $ Amount: chr  "100" "0" "0"

How to Maximize window in chrome using webDriver (python)

I do the following:

from selenium import webdriver
browser = webdriver.Chrome('C:\chromedriver.exe')
browser.maximize_window()

How to find Port number of IP address?

Quite an old question, but might be helpful to somebody in need.

If you know the url, 1. open the chrome browser, 2. open developer tools in chrome , 3. Put the url in search bar and hit enter 4. look in network tab, you will see the ip and port both

Connect over ssh using a .pem file

To connect from Terminal to AWS AMI:

chmod 400 mykey.pem

ssh -i mykey.pem [email protected]

How can I view the contents of an ElasticSearch index?

I can recommend Elasticvue, which is modern, free and open source. It allows accessing your ES instance via browser add-ons quite easily (supports Firefox, Chrome, Edge). But there are also further ways.

Just make sure you set cors values in elasticsearch.yml appropiate.

How to yum install Node.JS on Amazon Linux

The easiest solution is this( do these as root)

sudo su root
cd /etc
mkdir node
yum install wget
wget https://nodejs.org/dist/v9.0.0/node-v9.0.0-linux-x64.tar.gz
tar -xvf node-v9.0.0-linux-x64.tar.gz
cd node-v9.0.0-linux-x64/bin
./node -v
ln -s /etc/node-v9.0.0-linux-x64/bin/node node

enter image description here

How can I make Bootstrap 4 columns all the same height?

Equal height columns is the default behaviour for Bootstrap 4 grids.

_x000D_
_x000D_
.col { background: red; }_x000D_
.col:nth-child(odd) { background: yellow; }
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
_x000D_
<div class="container">_x000D_
  <div class="row">_x000D_
    <div class="col">_x000D_
      1 of 3_x000D_
    </div>_x000D_
    <div class="col">_x000D_
      1 of 3_x000D_
      <br>_x000D_
      Line 2_x000D_
      <br>_x000D_
      Line 3_x000D_
    </div>_x000D_
    <div class="col">_x000D_
      1 of 3_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Unique constraint violation during insert: why? (Oracle)

It looks like you are not providing a value for the primary key field DB_ID. If that is a primary key, you must provide a unique value for that column. The only way not to provide it would be to create a database trigger that, on insert, would provide a value, most likely derived from a sequence.

If this is a restoration from another database and there is a sequence on this new instance, it might be trying to reuse a value. If the old data had unique keys from 1 - 1000 and your current sequence is at 500, it would be generating values that already exist. If a sequence does exist for this table and it is trying to use it, you would need to reconcile the values in your table with the current value of the sequence.

You can use SEQUENCE_NAME.CURRVAL to see the current value of the sequence (if it exists of course)

How to convert int to float in C?

Integer division truncates, so (50/100) results in 0. You can cast to float (better double) or multiply with 100.0 (for double precision, 100.0f for float precision) first,

double percentage;
// ...
percentage = 100.0*number/total;
// percentage = (double)number/total * 100;

or

float percentage;
// ...
percentage = (float)number/total * 100;
// percentage = 100.0f*number/total;

Since floating point arithmetic is not associative, the results of 100.0*number/total and (double)number/total * 100 may be slightly different (the same holds for float), but it's extremely unlikely to influence the first two places after the decimal point, so it probably doesn't matter which way you choose.

How to get all the values of input array element jquery

Use:

function getvalues(){
var inps = document.getElementsByName('pname[]');
for (var i = 0; i <inps.length; i++) {
var inp=inps[i];
    alert("pname["+i+"].value="+inp.value);
}
}

Here is Demo.

Request exceeded the limit of 10 internal redirects due to probable configuration error

This error occurred to me when I was debugging the PHP header() function:

header('Location: /aaa/bbb/ccc'); // error

If I use a relative path it works:

header('Location: aaa/bbb/ccc'); // success, but not what I wanted

However when I use an absolute path like /aaa/bbb/ccc, it gives the exact error:

Request exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace.

It appears the header function redirects internally without going HTTP at all which is weird. After some tests and trials, I found the solution of adding exit after header():

header('Location: /aaa/bbb/ccc');
exit;

And it works properly.

How do I upload a file to an SFTP server in C# (.NET)?

Unfortunately, it's not in the .NET Framework itself. My wish is that you could integrate with FileZilla, but I don't think it exposes an interface. They do have scripting I think, but it won't be as clean obviously.

I've used CuteFTP in a project which does SFTP. It exposes a COM component which I created a .NET wrapper around. The catch, you'll find, is permissions. It runs beautifully under the Windows credentials which installed CuteFTP, but running under other credentials requires permissions to be set in DCOM.

Window.Open with PDF stream instead of PDF location

It looks like window.open will take a Data URI as the location parameter.

So you can open it like this from the question: Opening PDF String in new window with javascript:

window.open("data:application/pdf;base64, " + base64EncodedPDF);

Here's an runnable example in plunker, and sample pdf file that's already base64 encoded.

Then on the server, you can convert the byte array to base64 encoding like this:

string fileName = @"C:\TEMP\TEST.pdf";
byte[] pdfByteArray = System.IO.File.ReadAllBytes(fileName);
string base64EncodedPDF = System.Convert.ToBase64String(pdfByteArray);

NOTE: This seems difficult to implement in IE because the URL length is prohibitively small for sending an entire PDF.

How to call a function after a div is ready?

inside your <div></div> element you can call the $(document).ready(function(){}); execute a command, something like

<div id="div1">
    <script>
        $(document).ready(function(){
         //do something
        });
    </script>
</div>

and you can do the same to other divs that you have. this was suitable if you loading your div via partial view

Read from database and fill DataTable

Private Function LoaderData(ByVal strSql As String) As DataTable
    Dim cnn As SqlConnection
    Dim dad As SqlDataAdapter

    Dim dtb As New DataTable
    cnn = New SqlConnection(My.Settings.mySqlConnectionString)
    Try
        cnn.Open()
        dad = New SqlDataAdapter(strSql, cnn)
        dad.Fill(dtb)
        cnn.Close()
        dad.Dispose()
    Catch ex As Exception
        cnn.Close()
        MsgBox(ex.Message)
    End Try
    Return dtb
End Function

How do I navigate to a parent route from a child route?

add Location to your constructor from @angular/common

constructor(private _location: Location) {}

add the back function:

back() {
  this._location.back();
}

and then in your view:

<button class="btn" (click)="back()">Back</button>

Finding out the name of the original repository you cloned from in Git

Powershell version of command for git repo name:

(git config --get remote.origin.url) -replace '.*/' -replace '.git'

The use of Swift 3 @objc inference in Swift 4 mode is deprecated?

You can try to "Pod update" and/or "flutter clean"

I also set this setting in xcode.

The Objective-C interface setting is as follows:

ObjectiveC interface setting

What does "all" stand for in a makefile?

Not sure it stands for anything special. It's just a convention that you supply an 'all' rule, and generally it's used to list all the sub-targets needed to build the entire project, hence the name 'all'. The only thing special about it is that often times people will put it in as the first target in the makefile, which means that just typing 'make' alone will do the same thing as 'make all'.

What is the meaning of @_ in Perl?

@ is used for an array.

In a subroutine or when you call a function in Perl, you may pass the parameter list. In that case, @_ is can be used to pass the parameter list to the function:

sub Average{

    # Get total number of arguments passed.
    $n = scalar(@_);
    $sum = 0;

    foreach $item (@_){

        # foreach is like for loop... It will access every
        # array element by an iterator
        $sum += $item;
    }

    $average = $sum / $n;

    print "Average for the given numbers: $average\n";
}

Function call

Average(10, 20, 30);

If you observe the above code, see the foreach $item(@_) line... Here it passes the input parameter.

Reverting to a specific commit based on commit id with Git?

I think, bwawok's answer is wrong at some point:

if you do

git reset --soft c14809fa

It will make your local files changed to be like they were then, but leave your history etc. the same.

According to manual: git-reset, "git reset --soft"...

does not touch the index file nor the working tree at all (but resets the head to <commit>, just like all modes do). This leaves all your changed files "Changes to be committed", as git status would put it.

So it will "remove" newer commits from the branch. This means, after looking at your old code, you cannot go to the newest commit in this branch again, easily. So it does the opposide as described by bwawok: Local files are not changed (they look exactly as before "git reset --soft"), but the history is modified (branch is truncated after the specified commit).

The command for bwawok's answer might be:

git checkout <commit>

You can use this to peek at old revision: How did my code look yesterday?

(I know, I should put this in comments to this answer, but stackoverflow does not allow me to do so! My reputation is too low.)

Html: Difference between cell spacing and cell padding

CellSpacing as the name suggests it is the Space between the Adjacent cells and CellPadding on the other hand means the padding around the cell content.

How to define relative paths in Visual Studio Project?

Instead of using relative paths, you could also use the predefined macros of VS to achieve this.

$(ProjectDir) points to the directory of your .vcproj file, $(SolutionDir) is the directory of the .sln file.

You get a list of available macros when opening a project, go to
Properties → Configuration Properties → C/C++ → General
and hit the three dots:

project properties

In the upcoming dialog, hit Macros to see the macros that are predefined by the Studio (consult MSDN for their meaning):

additional include directories

You can use the Macros by typing $(MACRO_NAME) (note the $ and the round brackets).

Summarizing count and conditional aggregate functions on the same factor

Assuming that your original dataset is similar to the one you created (i.e. with NA as character. You could specify na.strings while reading the data using read.table. But, I guess NAs would be detected automatically.

The price column is factor which needs to be converted to numeric class. When you use as.numeric, all the non-numeric elements (i.e. "NA", FALSE) gets coerced to NA) with a warning.

library(dplyr)
df %>%
     mutate(price=as.numeric(as.character(price))) %>%  
     group_by(company, year, product) %>%
     summarise(total.count=n(), 
               count=sum(is.na(price)), 
               avg.price=mean(price,na.rm=TRUE),
               max.price=max(price, na.rm=TRUE))

data

I am using the same dataset (except the ... row) that was showed.

df = tbl_df(data.frame(company=c("Acme", "Meca", "Emca", "Acme", "Meca","Emca"),
 year=c("2011", "2010", "2009", "2011", "2010", "2013"), product=c("Wrench", "Hammer",
 "Sonic Screwdriver", "Fairy Dust", "Kindness", "Helping Hand"), price=c("5.67",
 "7.12", "12.99", "10.99", "NA",FALSE)))

What Language is Used To Develop Using Unity

You can use C#, Javascript, Boo.

Unless computing requirement for the function you write cause heavy load on processor, Javascript gives good enough performance for most cases.

Using awk to print all columns from the nth to the last

I personally tried all the answers mentioned above, but most of them were a bit complex or just not right. The easiest way to do it from my point of view is:

awk -F" " '{ for (i=4; i<=NF; i++) print $i }'
  1. Where -F" " defines the delimiter for awk to use. In my case is the whitespace, which is also the default delimiter for awk. This means that -F" " can be ignored.

  2. Where NF defines the total number of fields/columns. Therefore the loop will begin from the 4th field up to the last field/column.

  3. Where $N retrieves the value of the Nth field. Therefore print $i will print the current field/column based based on the loop count.

Finding out current index in EACH loop (Ruby)

X.each_with_index do |item, index|
  puts "current_index: #{index}"
end

Could not open input file: artisan

The very first thing you have to check in this error is whether you are in the right folder. Direct the command prompt inside the project folder where all the Laravel package is existing.

How to remove non-alphanumeric characters?

I was looking for the answer too and my intention was to clean every non-alpha and there shouldn't have more than one space.
So, I modified Alex's answer to this, and this is working for me preg_replace('/[^a-z|\s+]+/i', ' ', $name)
The regex above turned sy8ed sirajul7_islam to sy ed sirajul islam
Explanation: regex will check NOT ANY from a to z in case insensitive way or more than one white spaces, and it will be converted to a single space.

vagrant primary box defined but commands still run against all boxes

The primary flag seems to only work for vagrant ssh for me.

In the past I have used the following method to hack around the issue.

# stage box intended for configuration closely matching production if ARGV[1] == 'stage'     config.vm.define "stage" do |stage|         box_setup stage, \         "10.9.8.31", "deploy/playbook_full_stack.yml", "deploy/hosts/vagrant_stage.yml"     end end 

How do I list all cron jobs for all users?

To get list from ROOT user.

for user in $(cut -f1 -d: /etc/passwd); do echo $user; sudo crontab -u $user -l; done

How can I run a html file from terminal?

For those like me, who have reached this thread because they want to serve an html file from linux terminal or want to view it using a terminal command, use these steps:-

1)If you want to view your html using a browser:-
Navigate to the directory containing the html file
If you have chrome installed, Use:-

google-chrome <filename>.html


                OR
Use:-

firefox <filename>.html

2)If you want to serve html file and view it using a browser
Navigate to the directory containing the html file
And Simply type the following on the Terminal:-

pushd <filename>.html; python3 -m http.server 9999; popd;


Then click the I.P. address 0.0.0.0:9999 OR localhost:9999 (Whatever is the result after executing the above commands). Or type on the terminal :-

firefox 0.0.0.0:9999


Using the second method, anyone else connected to the same network can also view your file by using the URL:- "0.0.0.0:9999"

Class method differences in Python: bound, unbound and static

Please read this docs from the Guido First Class everything Clearly explained how Unbound, Bound methods are born.

php codeigniter count rows

Try This :) I created my on model of count all results

in library_model

function count_all_results($column_name = array(),$where=array(), $table_name = array())
{
        $this->db->select($column_name);
        // If Where is not NULL
        if(!empty($where) && count($where) > 0 )
        {
            $this->db->where($where);
        }
        // Return Count Column
        return $this->db->count_all_results($table_name[0]);//table_name array sub 0
}

Your Controller will look like this

public function my_method()
{
  $data = array(
     $countall = $this->model->your_method_model()
  );
   $this->load->view('page',$data);
}

Then Simple Call The Library Model In Your Model

function your_method_model()
{
        return $this->library_model->count_all_results(
               ['id'],
               ['where],
               ['table name']
           );
}

How to change an Eclipse default project into a Java project

You can do it directly from eclipse using the Navigator view (Window -> Show View -> Navigator). In the Navigator view select the project and open it so that you can see the file .project. Right click -> Open. You will get a XML editor view. Edit the content of the node natures and insert a new child nature with org.eclipse.jdt.core.javanature as content. Save.

Now create a file .classpath, it will open in the XML editor. Add a node named classpath, add a child named classpathentry with the attributes kind with content con and another one named path and content org.eclipse.jdt.launching.JRE_CONTAINER. Save-

Much easier: copy the files .project and .classpath from an existing Java project and edit the node result name to the name of this project. Maybe you have to refresh the project (F5).

You'll get the same result as with the solution of Chris Marasti-Georg.

Edit

enter image description here

Put byte array to JSON and vice versa

The typical way to send binary in json is to base64 encode it.

Java provides different ways to Base64 encode and decode a byte[]. One of these is DatatypeConverter.

Very simply

byte[] originalBytes = new byte[] { 1, 2, 3, 4, 5};
String base64Encoded = DatatypeConverter.printBase64Binary(originalBytes);
byte[] base64Decoded = DatatypeConverter.parseBase64Binary(base64Encoded);

You'll have to make this conversion depending on the json parser/generator library you use.

Why am I getting a FileNotFoundError?

As noted above the problem is in specifying the path to your file. The default path in OS X is your home directory (/Users/macbook represented by ~ in terminal ...you can change or rename the home directory with the advanced options in System Preferences > Users & Groups).

Or you can specify the path from the drive to your file in the filename:

path = "/Users/macbook/Documents/MyPython/"
myFile = path + fileName

You can also catch the File Not Found Error and give another response using try:

try:
    with open(filename) as f:
        sequences = pick_lines(f)
except FileNotFoundError:
    print("File not found. Check the path variable and filename")
    exit()

Combine hover and click functions (jQuery)?

You could also use bind:

$('#myelement').bind('click hover', function yourCommonHandler (e) {
   // Your handler here
});

curl : (1) Protocol https not supported or disabled in libcurl

Solved this problem with flag --with-darwinssl

Go to folder with curl source code

Download it here https://curl.haxx.se/download.html

sudo ./configure --with-darwinssl
make
make install

restart your console and it is done!

if variable contains

If you have a lot of these to check you might want to store a list of the mappings and just loop over that, instead of having a bunch of if/else statements. Something like:

var CODE_TO_LOCATION = {
  'ST1': 'stoke central',
  'ST2': 'stoke north',
  // ...
};

function getLocation(text) {
  for (var code in CODE_TO_LOCATION) {
    if (text.indexOf(code) != -1) {
      return CODE_TO_LOCATION[code];
    }
  }
  return null;
}

This way you can easily add more code/location mappings. And if you want to handle more than one location you could just build up an array of locations in the function instead of just returning the first one you find.

Multiple condition in single IF statement

Yes it is, there have to be boolean expresion after IF. Here you have a direct link. I hope it helps. GL!

How to check if an email address exists without sending an email?

I can confirm Joseph's and Drew's answers to use RCTP TO: <address_to_check>. I would like to add some little addenda on top of those answers.

Catch-all providers

Some mail providers implement a catch-all policy, meaning that *@mydomain.com will return positive to the RCTP TO: command. But this doesn't necessarily mean that the mailbox "exists", as in "belongs to a human". Nothing much can be done here, just be aware.

IP Greylisting/Blacklisting

Greylisting: 1st connection from unknown IP is blocked. Solution: retry at least 2 times.

Blacklisting: if you send too many requests from the same IP, this IP is blocked. Solution: use IP rotation; Reacher uses Tor.

HTTP requests on sign-up forms

This is very provider-specific, but you sometimes can use well-crafted HTTP requests, and parse the responses of these requests to see if a username already signed up or not with this provider.

Here is the relevant function from an open-source library I wrote to check *@yahoo.com addresses using HTTP requests: check-if-email-exists. I know my code is Rust and this thread is tagged PHP, but the same ideas apply.

Full Inbox

This might be an edge case, but when the user has a full inbox, RCTP TO: will return a 5.1.1 DSN error message saying it's full. This means that the account actually exists!

Disclosure

I run Reacher, a real-time email verification API. My code is written in Rust, and is 100% open-source. Check it out if you want a more robust solution:

Github: https://github.com/amaurymartiny/check-if-email-exists

With a combination of various techniques to jump through hoops, I manage to verify around 80% of the emails my customers check.

How can I "disable" zoom on a mobile web page?

please try adding this meta-tag and style

<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport"/>


<style>
body{
        touch-action: manipulation;
    }
</style>

How to cast Object to boolean?

Assuming that yourObject.toString() returns "true" or "false", you can try

boolean b = Boolean.valueOf(yourObject.toString())