Programs & Examples On #Embedded fonts

Mime type for WOFF fonts?

Mime type might not be your only problem. If the font file is hosted on S3 or other domain, you may additionally have the issue that Firefox will not load fonts from different domains. It's an easy fix with Apache, but in Nginx, I've read that you may need to encode your font files in base-64 and embed them directly in your font css file.

How can I extract embedded fonts from a PDF as valid font files?

Eventually found the FontForge Windows installer package and opened the PDF through the installed program. Worked a treat, so happy.

How to multiply a BigDecimal by an integer in Java

First off, BigDecimal.multiply() returns a BigDecimal and you're trying to store that in an int.

Second, it takes another BigDecimal as the argument, not an int.

If you just use the BigDecimal for all variables involved in these calculations, it should work fine.

RSA: Get exponent and modulus given a public key

It depends on the tools you can use. I doubt there is a JavaScript too that could do it directly within the browser. It also depends if it's a one-off (always the same key) or whether you need to script it.

Command-line / OpenSSL

If you want to use something like OpenSSL on a unix command line, you can do something as follows. I'm assuming you public.key file contains something like this:

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmBAjFv+29CaiQqYZIw4P
J0q5Qz2gS7kbGleS3ai8Xbhu5n8PLomldxbRz0RpdCuxqd1yvaicqpDKe/TT09sR
mL1h8Sx3Qa3EQmqI0TcEEqk27Ak0DTFxuVrq7c5hHB5fbJ4o7iEq5MYfdSl4pZax
UxdNv4jRElymdap8/iOo3SU1RsaK6y7kox1/tm2cfWZZhMlRFYJnpoXpyNYrp+Yo
CNKxmZJnMsS698kaFjDlyznLlihwMroY0mQvdD7dCeBoVlfPUGPAlamwWyqtIU+9
5xVkSp3kxcNcNb/mePSKQIPafQ1sAmBKPwycA/1I5nLzDVuQa95ZWMn0JkphtFIh
HQIDAQAB
-----END PUBLIC KEY-----

Then, the commands would be:

PUBKEY=`grep -v -- ----- public.key | tr -d '\n'`

Then, you can look into the ASN.1 structure:

echo $PUBKEY | base64 -d | openssl asn1parse -inform DER -i

This should give you something like this:

    0:d=0  hl=4 l= 290 cons: SEQUENCE          
    4:d=1  hl=2 l=  13 cons:  SEQUENCE          
    6:d=2  hl=2 l=   9 prim:   OBJECT            :rsaEncryption
   17:d=2  hl=2 l=   0 prim:   NULL              
   19:d=1  hl=4 l= 271 prim:  BIT STRING 

The modulus and public exponent are in the last BIT STRING, offset 19, so use -strparse:

 echo $PUBKEY | base64 -d | openssl asn1parse -inform DER -i -strparse 19

This will give you the modulus and the public exponent, in hexadecimal (the two INTEGERs):

    0:d=0  hl=4 l= 266 cons: SEQUENCE          
    4:d=1  hl=4 l= 257 prim:  INTEGER           :98102316FFB6F426A242A619230E0F274AB9433DA04BB91B1A5792DDA8BC5DB86EE67F0F2E89A57716D1CF4469742BB1A9DD72BDA89CAA90CA7BF4D3D3DB1198BD61F12C7741ADC4426A88D1370412A936EC09340D3171B95AEAEDCE611C1E5F6C9E28EE212AE4C61F752978A596B153174DBF88D1125CA675AA7CFE23A8DD253546C68AEB2EE4A31D7FB66D9C7D665984C951158267A685E9C8D62BA7E62808D2B199926732C4BAF7C91A1630E5CB39CB96287032BA18D2642F743EDD09E0685657CF5063C095A9B05B2AAD214FBDE715644A9DE4C5C35C35BFE678F48A4083DA7D0D6C02604A3F0C9C03FD48E672F30D5B906BDE5958C9F4264A61B452211D
  265:d=1  hl=2 l=   3 prim:  INTEGER           :010001

That's probably fine if it's always the same key, but this is probably not very convenient to put in a script.

Alternatively (and this might be easier to put into a script),

openssl rsa -pubin -inform PEM -text -noout < public.key

will return this:

Modulus (2048 bit):
    00:98:10:23:16:ff:b6:f4:26:a2:42:a6:19:23:0e:
    0f:27:4a:b9:43:3d:a0:4b:b9:1b:1a:57:92:dd:a8:
    bc:5d:b8:6e:e6:7f:0f:2e:89:a5:77:16:d1:cf:44:
    69:74:2b:b1:a9:dd:72:bd:a8:9c:aa:90:ca:7b:f4:
    d3:d3:db:11:98:bd:61:f1:2c:77:41:ad:c4:42:6a:
    88:d1:37:04:12:a9:36:ec:09:34:0d:31:71:b9:5a:
    ea:ed:ce:61:1c:1e:5f:6c:9e:28:ee:21:2a:e4:c6:
    1f:75:29:78:a5:96:b1:53:17:4d:bf:88:d1:12:5c:
    a6:75:aa:7c:fe:23:a8:dd:25:35:46:c6:8a:eb:2e:
    e4:a3:1d:7f:b6:6d:9c:7d:66:59:84:c9:51:15:82:
    67:a6:85:e9:c8:d6:2b:a7:e6:28:08:d2:b1:99:92:
    67:32:c4:ba:f7:c9:1a:16:30:e5:cb:39:cb:96:28:
    70:32:ba:18:d2:64:2f:74:3e:dd:09:e0:68:56:57:
    cf:50:63:c0:95:a9:b0:5b:2a:ad:21:4f:bd:e7:15:
    64:4a:9d:e4:c5:c3:5c:35:bf:e6:78:f4:8a:40:83:
    da:7d:0d:6c:02:60:4a:3f:0c:9c:03:fd:48:e6:72:
    f3:0d:5b:90:6b:de:59:58:c9:f4:26:4a:61:b4:52:
    21:1d
Exponent: 65537 (0x10001)

Java

It depends on the input format. If it's an X.509 certificate in a keystore, use (RSAPublicKey)cert.getPublicKey(): this object has two getters for the modulus and the exponent.

If it's in the format as above, you might want to use BouncyCastle and its PEMReader to read it. I haven't tried the following code, but this would look more or less like this:

PEMReader pemReader = new PEMReader(new FileReader("file.pem"));
Object obj = pemReader.readObject();
pemReader.close();
if (obj instanceof X509Certificate) {
   // Just in case your file contains in fact an X.509 certificate,
   // useless otherwise.
   obj = ((X509Certificate)obj).getPublicKey();
}
if (obj instanceof RSAPublicKey) {
   // ... use the getters to get the BigIntegers.
}

(You can use BouncyCastle similarly in C# too.)

What is the difference between mocking and spying when using Mockito?

Difference between a Spy and a Mock

When Mockito creates a mock – it does so from the Class of a Type, not from an actual instance. The mock simply creates a bare-bones shell instance of the Class, entirely instrumented to track interactions with it. On the other hand, the spy will wrap an existing instance. It will still behave in the same way as the normal instance – the only difference is that it will also be instrumented to track all the interactions with it.

In the following example – we create a mock of the ArrayList class:

@Test
public void whenCreateMock_thenCreated() {
    List mockedList = Mockito.mock(ArrayList.class);

    mockedList.add("one");
    Mockito.verify(mockedList).add("one");

    assertEquals(0, mockedList.size());
}

As you can see – adding an element into the mocked list doesn’t actually add anything – it just calls the method with no other side-effect. A spy on the other hand will behave differently – it will actually call the real implementation of the add method and add the element to the underlying list:

@Test
public void whenCreateSpy_thenCreate() {
    List spyList = Mockito.spy(new ArrayList());
    spyList.add("one");
    Mockito.verify(spyList).add("one");

    assertEquals(1, spyList.size());
}

Here we can surely say that the real internal method of the object was called because when you call the size() method you get the size as 1, but this size() method isn’t been mocked! So where does 1 come from? The internal real size() method is called as size() isn’t mocked (or stubbed) and hence we can say that the entry was added to the real object.

Source: http://www.baeldung.com/mockito-spy + self notes.

how to upload file using curl with php

Use:

if (function_exists('curl_file_create')) { // php 5.5+
  $cFile = curl_file_create($file_name_with_full_path);
} else { // 
  $cFile = '@' . realpath($file_name_with_full_path);
}
$post = array('extra_info' => '123456','file_contents'=> $cFile);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result=curl_exec ($ch);
curl_close ($ch);

You can also refer:

http://blog.derakkilgo.com/2009/06/07/send-a-file-via-post-with-curl-and-php/

Important hint for PHP 5.5+:

Now we should use https://wiki.php.net/rfc/curl-file-upload but if you still want to use this deprecated approach then you need to set curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);

MVC4 Passing model from view to controller

I hope this complete example will help you.

This is the TaxiInfo class which holds information about a taxi ride:

namespace Taxi.Models
{
    public class TaxiInfo
    {
        public String Driver { get; set; }
        public Double Fare { get; set; }
        public Double Distance { get; set; }
        public String StartLocation { get; set; }
        public String EndLocation { get; set; }
    }
}

We also have a convenience model which holds a List of TaxiInfo(s):

namespace Taxi.Models
{
    public class TaxiInfoSet
    {
        public List<TaxiInfo> TaxiInfoList { get; set; }

        public TaxiInfoSet(params TaxiInfo[] TaxiInfos)
        {
            TaxiInfoList = new List<TaxiInfo>();

            foreach(var TaxiInfo in TaxiInfos)
            {
                TaxiInfoList.Add(TaxiInfo);
            }
        }
    }
}

Now in the home controller we have the default Index action which for this example makes two taxi drivers and adds them to the list contained in a TaxiInfo:

public ActionResult Index()
{
    var taxi1 = new TaxiInfo() { Fare = 20.2, Distance = 15, Driver = "Billy", StartLocation = "Perth", EndLocation = "Brisbane" };
    var taxi2 = new TaxiInfo() { Fare = 2339.2, Distance = 1500, Driver = "Smith", StartLocation = "Perth", EndLocation = "America" };

    return View(new TaxiInfoSet(taxi1,taxi2));
}

The code for the view is as follows:

@model Taxi.Models.TaxiInfoSet
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@foreach(var TaxiInfo in Model.TaxiInfoList){
    <form>
        <h1>Cost: [email protected]</h1>
        <h2>Distance: @(TaxiInfo.Distance) km</h2>
        <p>
            Our diver, @TaxiInfo.Driver will take you from @TaxiInfo.StartLocation to @TaxiInfo.EndLocation
        </p>
        @Html.ActionLink("Home","Booking",TaxiInfo)
    </form>
}

The ActionLink is responsible for the re-directing to the booking action of the Home controller (and passing in the appropriate TaxiInfo object) which is defiend as follows:

    public ActionResult Booking(TaxiInfo Taxi)
    {
        return View(Taxi);
    }

This returns a the following view:

@model Taxi.Models.TaxiInfo

@{
    ViewBag.Title = "Booking";
}

<h2>Booking For</h2>
<h1>@Model.Driver, going from @Model.StartLocation to @Model.EndLocation (a total of @Model.Distance km) for [email protected]</h1>

A visual tour:

The Index view

The Booking view

MongoDB: Server has startup warnings ''Access control is not enabled for the database''

You need to delete your old db folder and recreate new one. It will resolve your issue.

Visual Studio replace tab with 4 spaces?

First set in the following path Tools->Options->Text Editor->All Languages->Tabs if still didn't work modify as mentioned below Go to Edit->Advanced->Set Indentation ->Spaces

finished with non zero exit value

Follow this simple steps to recover this error:

Method 1:

-Go to File->project structure->Project
-Check Android plugin Version and change it to 1.3.0(Latest one)
-Go to File->project structure->app->Properties->Build Tools Version
-Change it to latest one(22.0.1). Also do this for any other module you have for your project.
-Clean and build project.

Note: If your build tool version is less than 22.0.1 then you may still face same error while gradle build so please update your SDK from SDK Manager to latest one then restart android studio and follow above steps.

Method 2:

-If you don't want to update build tools version or you don't have latest SDK version just Go to File->project structure->Project.
-Check Android plugin Version and change it to 1.0.0(Older one)
-Clean and build project.

I recommended Method 1.

How do I migrate an SVN repository with history to a new Git repository?

I've posted an step by step guide (here) to convert svn in to git including converting svn tags in to git tags and svn branches in to git branches.

Short version:

1) clone svn from an specific revision number. (the revision number must be the oldest you want to migrate)

git svn clone --username=yourSvnUsername -T trunk_subdir -t tags_subdir -b branches_subdir -r aRevisionNumber svn_url gitreponame

2) fetch svn data. This step it's the one it takes most time.

cd gitreponame
git svn fetch

repeat git svn fetch until finishes without error

3) get master branch updated

git svn rebase

4) Create local branches from svn branches by copying references

cp .git/refs/remotes/origin/* .git/refs/heads/

5) convert svn tags into git tags

git for-each-ref refs/remotes/origin/tags | sed 's#^.*\([[:xdigit:]]\{40\}\).*refs/remotes/origin/tags/\(.*\)$#\2 \1#g' | while read p; do git tag -m "tag from svn" $p; done

6) Put a repository at a better place like github

git remotes add newrepo [email protected]:aUser/aProjectName.git
git push newrepo refs/heads/*
git push --tags newrepo

If you want more details, read my post or ask me.

How do MySQL indexes work?

The first thing you must know is that indexes are a way to avoid scanning the full table to obtain the result that you're looking for.

There are different kinds of indexes and they're implemented in the storage layer, so there's no standard between them and they also depend on the storage engine that you're using.

InnoDB and the B+Tree index

For InnoDB, the most common index type is the B+Tree based index, that stores the elements in a sorted order. Also, you don't have to access the real table to get the indexed values, which makes your query return way faster.

The "problem" about this index type is that you have to query for the leftmost value to use the index. So, if your index has two columns, say last_name and first_name, the order that you query these fields matters a lot.

So, given the following table:

CREATE TABLE person (
    last_name VARCHAR(50) NOT NULL,
    first_name VARCHAR(50) NOT NULL,
    INDEX (last_name, first_name)
);

This query would take advantage of the index:

SELECT last_name, first_name FROM person
WHERE last_name = "John" AND first_name LIKE "J%"

But the following one would not

SELECT last_name, first_name FROM person WHERE first_name = "Constantine"

Because you're querying the first_name column first and it's not the leftmost column in the index.

This last example is even worse:

SELECT last_name, first_name FROM person WHERE first_name LIKE "%Constantine"

Because now, you're comparing the rightmost part of the rightmost field in the index.

The hash index

This is a different index type that unfortunately, only the memory backend supports. It's lightning fast but only useful for full lookups, which means that you can't use it for operations like >, < or LIKE.

Since it only works for the memory backend, you probably won't use it very often. The main case I can think of right now is the one that you create a temporary table in the memory with a set of results from another select and perform a lot of other selects in this temporary table using hash indexes.

If you have a big VARCHAR field, you can "emulate" the use of a hash index when using a B-Tree, by creating another column and saving a hash of the big value on it. Let's say you're storing a url in a field and the values are quite big. You could also create an integer field called url_hash and use a hash function like CRC32 or any other hash function to hash the url when inserting it. And then, when you need to query for this value, you can do something like this:

SELECT url FROM url_table WHERE url_hash=CRC32("http://gnu.org");

The problem with the above example is that since the CRC32 function generates a quite small hash, you'll end up with a lot of collisions in the hashed values. If you need exact values, you can fix this problem by doing the following:

SELECT url FROM url_table 
WHERE url_hash=CRC32("http://gnu.org") AND url="http://gnu.org";

It's still worth to hash things even if the collision number is high cause you'll only perform the second comparison (the string one) against the repeated hashes.

Unfortunately, using this technique, you still need to hit the table to compare the url field.

Wrap up

Some facts that you may consider every time you want to talk about optimization:

  1. Integer comparison is way faster than string comparison. It can be illustrated with the example about the emulation of the hash index in InnoDB.

  2. Maybe, adding additional steps in a process makes it faster, not slower. It can be illustrated by the fact that you can optimize a SELECT by splitting it into two steps, making the first one store values in a newly created in-memory table, and then execute the heavier queries on this second table.

MySQL has other indexes too, but I think the B+Tree one is the most used ever and the hash one is a good thing to know, but you can find the other ones in the MySQL documentation.

I highly recommend you to read the "High Performance MySQL" book, the answer above was definitely based on its chapter about indexes.

Create auto-numbering on images/figures in MS Word

I assume you are using the caption feature of Word, that is, captions were not typed in as normal text, but were inserted using Insert > Caption (Word versions before 2007), or References > Insert Caption (in the ribbon of Word 2007 and up). If done correctly, the captions are really 'fields'. You'll know if it is a field if the caption's background turns grey when you put your cursor on them (or is permanently displayed grey).

Captions are fields - Unfortunately fields (like caption fields) are only updated on specific actions, like opening of the document, printing, switching from print view to normal view, etc. The easiest way to force updating of all (caption) fields when you want it is by doing the following:

  1. Select all text in your document (easiest way is to press ctrl-a)
  2. Press F9, this command tells Word to update all fields in the selection.

Captions are normal text - If the caption number is not a field, I am afraid you'll have to edit the text manually.

Comparing boxed Long values 127 and 128

num1 and num2 are Long objects. You should be using equals() to compare them. == comparison might work sometimes because of the way JVM boxes primitives, but don't depend on it.

if (num1.equals(num1))
{
 //code
}

'dispatch' is not a function when argument to mapToDispatchToProps() in Redux

I needed an example using React.Component so I am posting it:

import React from 'react';
import * as Redux from 'react-redux';

class NavigationHeader extends React.Component {

}

const mapStateToProps = function (store) {
    console.log(`mapStateToProps ${store}`);
    return {
        navigation: store.navigation
    };
};

export default Redux.connect(mapStateToProps)(NavigationHeader);

Python 2.7 getting user input and manipulating as string without quotations

Use raw_input() instead of input():

testVar = raw_input("Ask user for something.")

input() actually evaluates the input as Python code. I suggest to never use it. raw_input() returns the verbatim string entered by the user.

Ball to Ball Collision - Detection and Handling

A good way of reducing the number of collision checks is to split the screen into different sections. You then only compare each ball to the balls in the same section.

What is the meaning of Bus: error 10 in C

There is no space allocated for the strings. use array (or) pointers with malloc() and free()

Other than that

#import <stdio.h>
#import <string.h>

should be

#include <stdio.h>
#include <string.h>

NOTE:

  • anything that is malloc()ed must be free()'ed
  • you need to allocate n + 1 bytes for a string which is of length n (the last byte is for \0)

Please you the following code as a reference

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[])
{
    //char *str1 = "First string";
    char *str1 = "First string is a big string";
    char *str2 = NULL;

    if ((str2 = (char *) malloc(sizeof(char) * strlen(str1) + 1)) == NULL) {
        printf("unable to allocate memory \n");
        return -1; 
    }   

    strcpy(str2, str1);

    printf("str1 : %s \n", str1);
    printf("str2 : %s \n", str2);

    free(str2);
    return 0;
}

makefile:4: *** missing separator. Stop

If you are editing your Makefile in eclipse:

Windows-> Preferences->General->Editor->Text Editors->Show Whitespace Characters -> Apply

Or use the shortcut shown below.

Tab will be represented by gray ">>" and Space will be represented by gray "." as in figure below.

enter image description here

mysql.h file can't be found

You have to let the compiler know where the mysql.h file can be found. This can be done by giving the path to the header before compiling. In IDEs you have a setting where you can give these paths.

This link gives you more info on what options to use while compiling.

To your second problem You need to link the libraries. The linker needs to know where the library files are which has the implementation for the mysql functions that you use.

This link gives you more info on how to link libraries.

Can't connect to MySQL server on 'localhost' (10061)

To connect locally to MySql, you do not have to setup a firewall with inbound rules. But, even if you already setup iptables to allow the TCP inbound port 3306 and grant the privilege to the user to access the db locally, you may have to setup the bind address in your my.cnf file, edit the default address there and put the server IP address that is running the MySql service.

What exactly does the .join() method do?

list = ["my", "name", "is", "kourosh"]   
" ".join(list)

If this is an input, using the JOIN method, we can add the distance between the words and also convert the list to the string.

This is Python output

'my name is kourosh'

Case Statement Equivalent in R

i dont like any of these, they are not clear to the reader or the potential user. I just use an anonymous function, the syntax is not as slick as a case statement, but the evaluation is similar to a case statement and not that painful. this also assumes your evaluating it within where your variables are defined.

result <- ( function() { if (x==10 | y< 5) return('foo') 
                         if (x==11 & y== 5) return('bar')
                        })()

all of those () are necessary to enclose and evaluate the anonymous function.

How to get multiple select box values using jQuery?

var selected=[];
 $('#multipleSelect :selected').each(function(){
     selected[$(this).val()]=$(this).text();
    });
console.log(selected);

Yet another approch to this problem. The selected array will have the indexes as the option values and the each array item will have the text as its value.

for example

<select id="multipleSelect" multiple="multiple">
    <option value="abc">Text 1</option>
    <option value="def">Text 2</option>
    <option value="ghi">Text 3</option>
</select>

if say option 1 and 2 are selected.

the selected array will be :

selected['abc']=1; 
selected['def']=2.

How to set proper codeigniter base url?

Change in config.php like this.

$base_url = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "https" : "http");
$base_url .= "://". @$_SERVER['HTTP_HOST'];
$base_url .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);
$config['base_url'] = $base_url;

How to print VARCHAR(MAX) using Print Statement?

If the source code will not have issues with LF to be replaced by CRLF, No debugging is required by following simple codes outputs.

--http://stackoverflow.com/questions/7850477/how-to-print-varcharmax-using-print-statement
--Bill Bai
SET @SQL=replace(@SQL,char(10),char(13)+char(10))
SET @SQL=replace(@SQL,char(13)+char(13)+char(10),char(13)+char(10) )
DECLARE @Position int 
WHILE Len(@SQL)>0 
BEGIN
SET @Position=charindex(char(10),@SQL)
PRINT left(@SQL,@Position-2)
SET @SQL=substring(@SQL,@Position+1,len(@SQL))
end; 

How do I build JSON dynamically in javascript?

As myJSON is an object you can just set its properties, for example:

myJSON.list1 = ["1","2"];

If you dont know the name of the properties, you have to use the array access syntax:

myJSON['list'+listnum] = ["1","2"];

If you want to add an element to one of the properties, you can do;

myJSON.list1.push("3");

cleanest way to skip a foreach if array is empty

Best practice is to define variable as an array at the very top of your code.

foreach((array)$myArr as $oneItem) { .. }

will also work but you will duplicate this (array) conversion everytime you need to loop through the array.

since it's important not to duplicate even a word of your code, you do better to define it as an empty array at top.

Reading file using fscanf() in C

In your code:

while(fscanf(fp,"%s %c",item,&status) == 1)  

why 1 and not 2? The scanf functions return the number of objects read.

How exactly does binary code get converted into letters?

Why not just do this take 010010001001001 split it into two bits 8 letter each (01001000, 01001001). Then issue the powers

01001000. 01001001.

The first 8 ignore the first three they determine if it's capital or not, the go right to left doing powers of 2 (2^1, 2^2 2^3 2^4 2^5). So then add all the ones up , there's only one, and it = 8, and te eight letter in the alphabet is h so our first bit is the letter h, try it on the other bit

git still shows files as modified after adding to .gitignore

  1. Git add .

  2. Git status //Check file that being modified

    // git reset HEAD --- replace to which file you want to ignore

  3. git reset HEAD .idea/ <-- Those who wanted to exclude .idea from before commit // git check status and the idea file will be gone, and you're ready to go!

  4. git commit -m ''

  5. git push

Invoking a static method using reflection

public class Add {
    static int add(int a, int b){
        return (a+b);
    }
}

In the above example, 'add' is a static method that takes two integers as arguments.

Following snippet is used to call 'add' method with input 1 and 2.

Class myClass = Class.forName("Add");
Method method = myClass.getDeclaredMethod("add", int.class, int.class);
Object result = method.invoke(null, 1, 2);

Reference link.

How do you connect localhost in the Android emulator?

Instead of giving localhost give the IP.

What does if [ $? -eq 0 ] mean for shell scripts?

$? is the exit status of the most recently-executed command; by convention, 0 means success and anything else indicates failure. That line is testing whether the grep command succeeded.

The grep manpage states:

The exit status is 0 if selected lines are found, and 1 if not found. If an error occurred the exit status is 2. (Note: POSIX error handling code should check for '2' or greater.)

So in this case it's checking whether any ERROR lines were found.

How do I create documentation with Pydoc?

Another thing that people may find useful...make sure to leave off ".py" from your module name. For example, if you are trying to generate documentation for 'original' in 'original.py':

yourcode_dir$ pydoc -w original.py
no Python documentation found for 'original.py'

yourcode_dir$ pydoc -w original
wrote original.html

How to print all information from an HTTP request to the screen, in PHP

in addition, you can use get_headers(). it doesn't depend on apache..

print_r(get_headers());

How to disable/enable a button with a checkbox if checked

You can use onchangeevent of the checkbox to enable/disable button based on checked value

<input type="submit" name="sendNewSms" class="inputButton" id="sendNewSms" value=" Send " />

<input type="checkbox"  onchange="document.getElementById('sendNewSms').disabled = !this.checked;" />

How to add image that is on my computer to a site in css or html?

Upload the image on your server or in images hosting site where you get image link and then add the line on your website page where you get that image the line is

<img src="paste here your image full path"/>

How to replace substrings in windows batch file

Expanding from Andriy M, and yes you can do this from a file, even one with multiple lines

@echo off
setlocal EnableExtensions EnableDelayedExpansion
set "INTEXTFILE=test.txt"
set "OUTTEXTFILE=test_out.txt"
set "SEARCHTEXT=bath"
set "REPLACETEXT=hello"

for /f "delims=" %%A in ('type "%INTEXTFILE%"') do (
    set "string=%%A"
    set "modified=!string:%SEARCHTEXT%=%REPLACETEXT%!"
    echo !modified!>>"%OUTTEXTFILE%"
)

del "%INTEXTFILE%"
rename "%OUTTEXTFILE%" "%INTEXTFILE%"
endlocal

EDIT

Thanks David Nelson, I have updated the script so it doesn't have the hard coded values anymore.

How do you share constants in NodeJS modules?

Since Node.js is using the CommonJS patterns, you can only share variables between modules with module.exports or by setting a global var like you would in the browser, but instead of using window you use global.your_var = value;.

What is the difference between json.dump() and json.dumps() in python?

In memory usage and speed.

When you call jsonstr = json.dumps(mydata) it first creates a full copy of your data in memory and only then you file.write(jsonstr) it to disk. So this is a faster method but can be a problem if you have a big piece of data to save.

When you call json.dump(mydata, file) -- without 's', new memory is not used, as the data is dumped by chunks. But the whole process is about 2 times slower.

Source: I checked the source code of json.dump() and json.dumps() and also tested both the variants measuring the time with time.time() and watching the memory usage in htop.

Linux command: How to 'find' only text files?

If you are interested in finding any file type by their magic bytes using the awesome file utility combined with power of find, this can come in handy:

$ # Let's make some test files
$ mkdir ASCII-finder
$ cd ASCII-finder
$ dd if=/dev/urandom of=binary.file bs=1M count=1
1+0 records in
1+0 records out
1048576 bytes (1.0 MB, 1.0 MiB) copied, 0.009023 s, 116 MB/s
$ file binary.file
binary.file: data
$ echo 123 > text.txt
$ # Let the magic begin
$ find -type f -print0 | \
    xargs -0 -I @@ bash -c 'file "$@" | grep ASCII &>/dev/null && echo "file is ASCII: $@"' -- @@

Output:

file is ASCII: ./text.txt

Legend: $ is the interactive shell prompt where we enter our commands

You can modify the part after && to call some other script or do some other stuff inline as well, i.e. if that file contains given string, cat the entire file or look for a secondary string in it.

Explanation:

  • find items that are files
  • Make xargs feed each item as a line into one liner bash command/script
  • file checks type of file by magic byte, grep checks if ASCII exists, if so, then after && your next command executes.
  • find prints results null separated, this is good to escape filenames with spaces and meta-characters in it.
  • xargs , using -0 option, reads them null separated, -I @@ takes each record and uses as positional parameter/args to bash script.
  • -- for bash ensures whatever comes after it is an argument even if it starts with - like -c which could otherwise be interpreted as bash option

If you need to find types other than ASCII, simply replace grep ASCII with other type, like grep "PDF document, version 1.4"

Are HTTPS headers encrypted?

With SSL the encryption is at the transport level, so it takes place before a request is sent.

So everything in the request is encrypted.

Arduino COM port doesn't work

Abstract: Steps of How to resolve "Serial port 'COM1' not found" in fedora 17.

Today install the packages for Arduino in Fedora 17. (yum install arduino) and I have the same problem: I decided to upload an example to the chip. and got the same error "Serial port 'COM1' not found".

In this case when I run Arduino program, some banner appears which warns me that my user is not in 'dialout' and 'lock' group. Do you want add your user in this groups? I click in add button, but for some reason the program fail and not say nothing.

Step1: recognize the Arduino device unplug your Arduino and list /dev files:

#ls -l /dev

plug your Arduino and go and list /dev files

#ls -l /dev

Find the new file (device) that was not before plugging, for example:

ttyACM0 or ttyUSB1

Read this properties:

ls -l /dev/ttyACM0

crw-rw---- 1 root dialout 166, 0 Dec 24 19:25 /dev/ttyACM0

the first c mean that Arduino is a character device.

user owner: root

group owner: dialout

mayor number: 166

minor number: 0

Step2: set your user as group owner.

If you do:

groups <yourUser>

And you are not in 'dialout' and/or 'lock' group. Add yourself in this groups run as root:

usermod -aG lock <yourUser>
usermod -aG dialout <yourUser>

restart the pc, and set /dev/<yourDeviceFile> as your serial port before upload.

Test if element is present using Selenium WebDriver?

I would use something like (with Scala [the code in old "good" Java 8 may be similar to this]):

object SeleniumFacade {

  def getElement(bySelector: By, maybeParent: Option[WebElement] = None, withIndex: Int = 0)(implicit driver: RemoteWebDriver): Option[WebElement] = {
    val elements = maybeParent match {
      case Some(parent) => parent.findElements(bySelector).asScala
      case None => driver.findElements(bySelector).asScala
    }
    if (elements.nonEmpty) {
      Try { Some(elements(withIndex)) } getOrElse None
    } else None
  }
  ...
}

so then,

val maybeHeaderLink = SeleniumFacade getElement(By.xpath(".//a"), Some(someParentElement))

Submit two forms with one button

You should be able to do this with JavaScript:

<input type="button" value="Click Me!" onclick="submitForms()" />

If your forms have IDs:

submitForms = function(){
    document.getElementById("form1").submit();
    document.getElementById("form2").submit();
}

If your forms don't have IDs but have names:

submitForms = function(){
    document.forms["form1"].submit();
    document.forms["form2"].submit();
}

Angular JS Uncaught Error: [$injector:modulerr]

Just throwing this in in case it helps, I had this issue and the reason for me was because when I bundled my Angular stuff I referenced the main app file as "AngularWebApp" instead of "AngularWebApp.js", hope this helps.

How to install and run Typescript locally in npm?

tsc requires a config file or .ts(x) files to compile.

To solve both of your issues, create a file called tsconfig.json with the following contents:

{
    "compilerOptions": {
        "outFile": "../../built/local/tsc.js"
    },
    "exclude": [
        "node_modules"
    ]
}

Also, modify your npm run with this

tsc --config /path/to/a/tsconfig.json

How can I create a self-signed cert for localhost?

Yes and no. Self signed certificates result in that warning message because the certificate was not signed by a trusted Certificate Authority. There are a few options that you can consider to remove this warning on your local machine. See the highest ranked answers to this question for details:

What do I need to do to get Internet Explorer 8 to accept a self signed certificate?

Hope this helps!


EDIT:

Sorry, I wasn't initially aware that you were constrained to localhost. You can attempt to follow the directions on the the link below to "Generate a Self Signed Certificate with the Correct Common Name."

http://www.sslshopper.com/article-how-to-create-a-self-signed-certificate-in-iis-7.html

C++, how to declare a struct in a header file

C++, how to declare a struct in a header file:

Put this in a file called main.cpp:

#include <cstdlib>
#include <iostream>
#include "student.h"

using namespace std;    //Watchout for clashes between std and other libraries

int main(int argc, char** argv) {
    struct Student s1;
    s1.firstName = "fred"; s1.lastName = "flintstone";
    cout << s1.firstName << " " << s1.lastName << endl;
    return 0;
}

put this in a file named student.h

#ifndef STUDENT_H
#define STUDENT_H

#include<string>
struct Student {
    std::string lastName, firstName;
};

#endif

Compile it and run it, it should produce this output:

s1.firstName = "fred";

Protip:

You should not place a using namespace std; directive in the C++ header file because you may cause silent name clashes between different libraries. To remedy this, use the fully qualified name: std::string foobarstring; instead of including the std namespace with string foobarstring;.

WARNING: sanitizing unsafe style value url

There is an open issue to only print this warning if there was actually something sanitized: https://github.com/angular/angular/pull/10272

I didn't read in detail when this warning is printed when nothing was sanitized.

Pycharm and sys.argv arguments

Notice that for some unknown reason, it is not possible to add command line arguments in the PyCharm Edu version. It can be only done in Professional and Community editions.

Determine the size of an InputStream

    try {
        InputStream connInputStream = connection.getInputStream();
    } catch (IOException e) {
        e.printStackTrace();
    }

    int size = connInputStream.available();

int available () Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream. The next invocation might be the same thread or another thread. A single read or skip of this many bytes will not block, but may read or skip fewer bytes.

InputStream - Android SDK | Android Developers

C# how to wait for a webpage to finish loading before continuing

I think the DocumentCompleted event of the WebBrowser control should get you where you need to go.

Get data type of field in select statement in ORACLE

I usually create a view and use the DESC command:

CREATE VIEW tmp_view AS 
SELECT 
      a.name
    , a.surname
    , b.ordernum 
FROM customer a
  JOIN orders b
    ON a.id = b.id

Then, the DESC command will show the type of each field.

DESC tmp_view

How to get on scroll events?

You could use a @HostListener decorator. Works with Angular 4 and up.

import { HostListener } from '@angular/core';

@HostListener("window:scroll", []) onWindowScroll() {
    // do some stuff here when the window is scrolled
    const verticalOffset = window.pageYOffset 
          || document.documentElement.scrollTop 
          || document.body.scrollTop || 0;
}

Reading Email using Pop3 in C#

You can also try Mail.dll mail component, it has SSL support, unicode, and multi-national email support:

using(Pop3 pop3 = new Pop3())
{
    pop3.Connect("mail.host.com");           // Connect to server and login
    pop3.Login("user", "password");

    foreach(string uid in pop3.GetAll())
    {
        IMail email = new MailBuilder()
            .CreateFromEml(pop3.GetMessageByUID(uid));
          Console.WriteLine( email.Subject );
    }
    pop3.Close(false);      
}

You can download it here at https://www.limilabs.com/mail

Please note that this is a commercial product I've created.

Datatable vs Dataset

One major difference is that DataSets can hold multiple tables and you can define relationships between those tables.

If you are only returning a single result set though I would think a DataTable would be more optimized. I would think there has to be some overhead (granted small) to offer the functionality a DataSet does and keep track of multiple DataTables.

jquery fill dropdown with json data

Here is an example of code, that attempts to featch AJAX data from /Ajax/_AjaxGetItemListHelp/ URL. Upon success, it removes all items from dropdown list with id = OfferTransModel_ItemID and then it fills it with new items based on AJAX call's result:

if (productgrpid != 0) {    
    $.ajax({
        type: "POST",
        url: "/Ajax/_AjaxGetItemListHelp/",
        data:{text:"sam",OfferTransModel_ItemGrpid:productgrpid},
        contentType: "application/json",              
        dataType: "json",
        success: function (data) {
            $("#OfferTransModel_ItemID").empty();

            $.each(data, function () {
                $("#OfferTransModel_ItemID").append($("<option>                                                      
                </option>").val(this['ITEMID']).html(this['ITEMDESC']));
            });
        }
    });
}

Returned AJAX result is expected to return data encoded as AJAX array, where each item contains ITEMID and ITEMDESC elements. For example:

{
    {
        "ITEMID":"13",
        "ITEMDESC":"About"
    },
    {
        "ITEMID":"21",
        "ITEMDESC":"Contact"
    }
}

The OfferTransModel_ItemID listbox is populated with above data and its code should look like:

<select id="OfferTransModel_ItemID" name="OfferTransModel[ItemID]">
    <option value="13">About</option>
    <option value="21">Contact</option>
</select>

When user selects About, form submits 13 as value for this field and 21 when user selects Contact and so on.

Fell free to modify above code if your server returns URL in a different format.

how to save canvas as png image?

I maybe discovered a better way for not forcing the user to right click and "save image as". Live draw the canvas base64 code into the href of the link and modify it so the download will start automatically. I don't know if it's universally browser compatible, but it should work with the main/new browsers.

var canvas = document.getElementById('your-canvas');
    if (canvas.getContext) {
        var C = canvas.getContext('2d');
    }

$('#your-canvas').mousedown(function(event) {
    // feel free to choose your event ;) 

    // just for example
    // var OFFSET = $(this).offset();
    // var x = event.pageX - OFFSET.left;
    // var y = event.pageY - OFFSET.top;

    // standard data to url
    var imgdata = canvas.toDataURL('image/png');
    // modify the dataUrl so the browser starts downloading it instead of just showing it
    var newdata = imgdata.replace(/^data:image\/png/,'data:application/octet-stream');
    // give the link the values it needs
    $('a.linkwithnewattr').attr('download','your_pic_name.png').attr('href',newdata);

});

You can wrap the <a> around anything you want.

MVC3 DropDownListFor - a simple example?

You should do like this:

@Html.DropDownListFor(m => m.ContribType, 
                new SelectList(Model.ContribTypeOptions, 
                               "ContribId", "Value"))

Where:

m => m.ContribType

is a property where the result value will be.

Convert RGB to Black & White in OpenCV

AFAIK, you have to convert it to grayscale and then threshold it to binary.

1. Read the image as a grayscale image If you're reading the RGB image from disk, then you can directly read it as a grayscale image, like this:

// C
IplImage* im_gray = cvLoadImage("image.jpg",CV_LOAD_IMAGE_GRAYSCALE);

// C++ (OpenCV 2.0)
Mat im_gray = imread("image.jpg",CV_LOAD_IMAGE_GRAYSCALE);

2. Convert an RGB image im_rgb into a grayscale image: Otherwise, you'll have to convert the previously obtained RGB image into a grayscale image

// C
IplImage *im_rgb  = cvLoadImage("image.jpg");
IplImage *im_gray = cvCreateImage(cvGetSize(im_rgb),IPL_DEPTH_8U,1);
cvCvtColor(im_rgb,im_gray,CV_RGB2GRAY);

// C++
Mat im_rgb  = imread("image.jpg");
Mat im_gray;
cvtColor(im_rgb,im_gray,CV_RGB2GRAY);

3. Convert to binary You can use adaptive thresholding or fixed-level thresholding to convert your grayscale image to a binary image.

E.g. in C you can do the following (you can also do the same in C++ with Mat and the corresponding functions):

// C
IplImage* im_bw = cvCreateImage(cvGetSize(im_gray),IPL_DEPTH_8U,1);
cvThreshold(im_gray, im_bw, 128, 255, CV_THRESH_BINARY | CV_THRESH_OTSU);

// C++
Mat img_bw = im_gray > 128;

In the above example, 128 is the threshold.

4. Save to disk

// C
cvSaveImage("image_bw.jpg",img_bw);

// C++
imwrite("image_bw.jpg", img_bw);

How to cancel a pull request on github?

Go to conversation tab then come down there is one "close pull request" button is there use that button to close pull request, Take ref of attached image

Linq to Entities - SQL "IN" clause

I will go for Inner Join in this context. If I would have used contains, it would iterate 6 times despite if the fact that there are just one match.

var desiredNames = new[] { "Pankaj", "Garg" }; 

var people = new[]  
{  
    new { FirstName="Pankaj", Surname="Garg" },  
    new { FirstName="Marc", Surname="Gravell" },  
    new { FirstName="Jeff", Surname="Atwood" }  
}; 

var records = (from p in people join filtered in desiredNames on p.FirstName equals filtered  select p.FirstName).ToList(); 

Disadvantages of Contains

Suppose I have two list objects.

List 1      List 2
  1           12
  2            7
  3            8
  4           98
  5            9
  6           10
  7            6

Using Contains, it will search for each List 1 item in List 2 that means iteration will happen 49 times !!!

How to delete session cookie in Postman?

Postman 4.0.5 has a feature named Manage Cookies located below the Send button which manages the cookies separately from Chrome it seems.

enter image description here

css ellipsis on second line

I used these css properties for line ellipsis-

overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 3; 
-webkit-box-orient: vertical;

here -webkit-line-clamp: 3; is the number of line(3 lines) after which ... shows.

What is "entropy and information gain"?

Informally

entropy is availability of information or knowledge, Lack of information will leads to difficulties in prediction of future which is high entropy (next word prediction in text mining) and availability of information/knowledge will help us more realistic prediction of future (low entropy).

Relevant information of any type will reduce entropy and helps us predict more realistic future, that information can be word "meat" is present in sentence or word "meat" is not present. This is called Information Gain


Formally

entropy is lack of order of predicability

Can a JSON value contain a multiline string

I'm not sure of your exact requirement but one possible solution to improve 'readability' is to store it as an array.

{
  "testCases" :
  {
    "case.1" :
    {
      "scenario" : "this the case 1.",
      "result" : ["this is a very long line which is not easily readble.",
                  "so i would like to write it in multiple lines.",
                  "but, i do NOT require any new lines in the output."]
    }
  }
}

}

The join in back again whenever required with

result.join(" ")

Converting Numpy Array to OpenCV Array

The simplest solution would be to use Pillow lib:

from PIL import Image

image = Image.fromarray(<your_numpy_array>.astype(np.uint8))

And you can use it as an image.

Why is null an object and what's the difference between null and undefined?

The other fun thing about null, compared to undefined, is that it can be incremented.

_x000D_
_x000D_
x = undefined_x000D_
x++_x000D_
y = null_x000D_
y++_x000D_
console.log(x) // NaN_x000D_
console.log(y) // 0
_x000D_
_x000D_
_x000D_

This is useful for setting default numerical values for counters. How many times have you set a variable to -1 in its declaration?

Handle spring security authentication exceptions with @ExceptionHandler

In case of Spring Boot and @EnableResourceServer, it is relatively easy and convenient to extend ResourceServerConfigurerAdapter instead of WebSecurityConfigurerAdapter in the Java configuration and register a custom AuthenticationEntryPoint by overriding configure(ResourceServerSecurityConfigurer resources) and using resources.authenticationEntryPoint(customAuthEntryPoint()) inside the method.

Something like this:

@Configuration
@EnableResourceServer
public class CommonSecurityConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.authenticationEntryPoint(customAuthEntryPoint());
    }

    @Bean
    public AuthenticationEntryPoint customAuthEntryPoint(){
        return new AuthFailureHandler();
    }
}

There's also a nice OAuth2AuthenticationEntryPoint that can be extended (since it's not final) and partially re-used while implementing a custom AuthenticationEntryPoint. In particular, it adds "WWW-Authenticate" headers with error-related details.

Hope this will help someone.

How to loop through a JSON object with typescript (Angular2)

ECMAScript 6 introduced the let statement. You can use it in a for statement.

var ids:string = [];

for(let result of this.results){
   ids.push(result.Id);
}

VT-x is disabled in the BIOS for both all CPU modes (VERR_VMX_MSR_ALL_VMX_DISABLED)

In Virtual Box "Settings" > System Settings > Processor > Enable the PAE/NX option. It resolved my issue.

ImportError: No module named dateutil.parser

In Ubuntu 18.04 for Python2:

sudo apt-get install python-dateutil

Use of the MANIFEST.MF file in Java

The content of the Manifest file in a JAR file created with version 1.0 of the Java Development Kit is the following.

Manifest-Version: 1.0

All the entries are as name-value pairs. The name of a header is separated from its value by a colon. The default manifest shows that it conforms to version 1.0 of the manifest specification. The manifest can also contain information about the other files that are packaged in the archive. Exactly what file information is recorded in the manifest will depend on the intended use for the JAR file. The default manifest file makes no assumptions about what information it should record about other files, so its single line contains data only about itself. Special-Purpose Manifest Headers

Depending on the intended role of the JAR file, the default manifest may have to be modified. If the JAR file is created only for the purpose of archival, then the MANIFEST.MF file is of no purpose. Most uses of JAR files go beyond simple archiving and compression and require special information to be in the manifest file. Summarized below are brief descriptions of the headers that are required for some special-purpose JAR-file functions

Applications Bundled as JAR Files: If an application is bundled in a JAR file, the Java Virtual Machine needs to be told what the entry point to the application is. An entry point is any class with a public static void main(String[] args) method. This information is provided in the Main-Class header, which has the general form:

Main-Class: classname

The value classname is to be replaced with the application's entry point.

Download Extensions: Download extensions are JAR files that are referenced by the manifest files of other JAR files. In a typical situation, an applet will be bundled in a JAR file whose manifest references a JAR file (or several JAR files) that will serve as an extension for the purposes of that applet. Extensions may reference each other in the same way. Download extensions are specified in the Class-Path header field in the manifest file of an applet, application, or another extension. A Class-Path header might look like this, for example:

Class-Path: servlet.jar infobus.jar acme/beans.jar

With this header, the classes in the files servlet.jar, infobus.jar, and acme/beans.jar will serve as extensions for purposes of the applet or application. The URLs in the Class-Path header are given relative to the URL of the JAR file of the applet or application.

Package Sealing: A package within a JAR file can be optionally sealed, which means that all classes defined in that package must be archived in the same JAR file. A package might be sealed to ensure version consistency among the classes in your software or as a security measure. To seal a package, a Name header needs to be added for the package, followed by a Sealed header, similar to this:

Name: myCompany/myPackage/
Sealed: true

The Name header's value is the package's relative pathname. Note that it ends with a '/' to distinguish it from a filename. Any headers following a Name header, without any intervening blank lines, apply to the file or package specified in the Name header. In the above example, because the Sealed header occurs after the Name: myCompany/myPackage header, with no blank lines between, the Sealed header will be interpreted as applying (only) to the package myCompany/myPackage.

Package Versioning: The Package Versioning specification defines several manifest headers to hold versioning information. One set of such headers can be assigned to each package. The versioning headers should appear directly beneath the Name header for the package. This example shows all the versioning headers:

Name: java/util/
Specification-Title: "Java Utility Classes" 
Specification-Version: "1.2"
Specification-Vendor: "Sun Microsystems, Inc.".
Implementation-Title: "java.util" 
Implementation-Version: "build57"
Implementation-Vendor: "Sun Microsystems, Inc."

OpenCV with Network Cameras

rtsp protocol did not work for me. mjpeg worked first try. I assume it is built into my camera (Dlink DCS 900).

Syntax found here: http://answers.opencv.org/question/133/how-do-i-access-an-ip-camera/

I did not need to compile OpenCV with ffmpg support.

How to use OpenFileDialog to select a folder?

Basically you need the FolderBrowserDialog class:

Prompts the user to select a folder. This class cannot be inherited.

Example:

using(var fbd = new FolderBrowserDialog())
{
    DialogResult result = fbd.ShowDialog();

    if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
    {
        string[] files = Directory.GetFiles(fbd.SelectedPath);

        System.Windows.Forms.MessageBox.Show("Files found: " + files.Length.ToString(), "Message");
    }
}

If you work in WPF you have to add the reference to System.Windows.Forms.

you also have to add using System.IO for Directory class

Nth word in a string variable

A file containing some statements :

cat test.txt

Result :

This is the 1st Statement
This is the 2nd Statement
This is the 3rd Statement
This is the 4th Statement
This is the 5th Statement

So, to print the 4th word of this statement type :

cat test.txt |awk '{print $4}'

Output :

1st
2nd
3rd
4th
5th

Extract Data from PDF and Add to Worksheet

I know this is an old issue but I just had to do this for a project at work, and I am very surprised that nobody has thought of this solution yet: Just open the .pdf with Microsoft word.

The code is a lot easier to work with when you are trying to extract data from a .docx because it opens in Microsoft Word. Excel and Word play well together because they are both Microsoft programs. In my case, the file of question had to be a .pdf file. Here's the solution I came up with:

  1. Choose the default program to open .pdf files to be Microsoft Word
  2. The first time you open a .pdf file with word, a dialogue box pops up claiming word will need to convert the .pdf into a .docx file. Click the check box in the bottom left stating "do not show this message again" and then click OK.
  3. Create a macro that extracts data from a .docx file. I used MikeD's Code as a resource for this.
  4. Tinker around with the MoveDown, MoveRight, and Find.Execute methods to fit the need of your task.

Yes you could just convert the .pdf file to a .docx file but this is a much simpler solution in my opinion.

What is "with (nolock)" in SQL Server?

You can use it when you're only reading data, and you don't really care about whether or not you might be getting back data that is not committed yet.

It can be faster on a read operation, but I cannot really say by how much.

In general, I recommend against using it - reading uncommitted data can be a bit confusing at best.

How do you use window.postMessage across domains?

Here is an example that works on Chrome 5.0.375.125.

The page B (iframe content):

<html>
    <head></head>
    <body>
        <script>
            top.postMessage('hello', 'A');
        </script>
    </body>
</html>

Note the use of top.postMessage or parent.postMessage not window.postMessage here

The page A:

<html>
<head></head>
<body>
    <iframe src="B"></iframe>
    <script>
        window.addEventListener( "message",
          function (e) {
                if(e.origin !== 'B'){ return; } 
                alert(e.data);
          },
          false);
    </script>
</body>
</html>

A and B must be something like http://domain.com

EDIT:

From another question, it looks the domains(A and B here) must have a / for the postMessage to work properly.

Stop Excel from automatically converting certain text values to dates

Its not the Excel. Windows does recognize the formula, the data as a date and autocorrects. You have to change the Windows settings.

"Control Panel" (-> "Switch to Classic View") -> "Regional and Language Options" -> tab "Regional Options" -> "Customize..." -> tab "Numbers" -> And then change the symbols according to what you want.

http://www.pcreview.co.uk/forums/enable-disable-auto-convert-number-date-t3791902.html

It will work on your computer, if these settings are not changed for example on your customers' computer they will see dates instead of data.

Print text in Oracle SQL Developer SQL Worksheet window

You could put your text in a select statement such as...

SELECT 'Querying Table1' FROM dual;

Linear Layout and weight in Android

It's android:layout_weight. Weight can only be used in LinearLayout. If the orientation of linearlayout is Vertical, then use android:layout_height="0dp" and if the orientation is horizontal, then use android:layout_width = "0dp". It'll work perfectly.

Kotlin: How to get and set a text to TextView in Android using Kotlin?

to set text in kotlin

textview.text = "write here"

After updating Entity Framework model, Visual Studio does not see changes

Are you working in an N-Tiered project? If so, try rebuilding your Data Layer (or wherever your EDMX file is stored) before using it.

TypeError: unhashable type: 'dict', when dict used as a key for another dict

What it seems like to me is that by calling the keys method you're returning to python a dictionary object when it's looking for a list or a tuple. So try taking all of the keys in the dictionary, putting them into a list and then using the for loop.

Java logical operator short-circuiting

The && and || operators "short-circuit", meaning they don't evaluate the right-hand side if it isn't necessary.

The & and | operators, when used as logical operators, always evaluate both sides.

There is only one case of short-circuiting for each operator, and they are:

  • false && ... - it is not necessary to know what the right-hand side is because the result can only be false regardless of the value there
  • true || ... - it is not necessary to know what the right-hand side is because the result can only be true regardless of the value there

Let's compare the behaviour in a simple example:

public boolean longerThan(String input, int length) {
    return input != null && input.length() > length;
}

public boolean longerThan(String input, int length) {
    return input != null & input.length() > length;
}

The 2nd version uses the non-short-circuiting operator & and will throw a NullPointerException if input is null, but the 1st version will return false without an exception.

How to use cURL to get jSON data and decode the data?

You can use this:

curl_setopt_array($ch, $options);
$resultado = curl_exec($ch);
$info = curl_getinfo($ch);
print_r($info["url"]);

How to extract year and month from date in PostgreSQL without using to_char() function?

date_part(text, timestamp)

e.g.

date_part('month', timestamp '2001-02-16 20:38:40'),
date_part('year', timestamp '2001-02-16 20:38:40') 

http://www.postgresql.org/docs/8.0/interactive/functions-datetime.html

ActiveRecord find and only return selected columns

My answer comes quite late because I'm a pretty new developer. This is what you can do:

Location.select(:name, :website, :city).find(row.id)

Btw, this is Rails 4

How do I mock a static method that returns void with PowerMock?

To mock a static method that return void for e.g. Fileutils.forceMKdir(File file),

Sample code:

File file =PowerMockito.mock(File.class);
PowerMockito.doNothing().when(FileUtils.class,"forceMkdir",file);

Ansible - Use default if a variable is not defined

If you have a single play that you want to loop over the items, define that list in group_vars/all or somewhere else that makes sense:

all_items:
  - first
  - second
  - third
  - fourth

Then your task can look like this:

  - name: List items or default list
    debug:
      var: item
    with_items: "{{ varlist | default(all_items) }}"

Pass in varlist as a JSON array:

ansible-playbook <playbook_name> --extra-vars='{"varlist": [first,third]}'

Prior to that, you might also want a task that checks that each item in varlist is also in all_items:

  - name: Ensure passed variables are in all_items
    fail:
      msg: "{{ item }} not  in all_items list"
    when: item not in all_items
    with_items: "{{ varlist | default(all_items) }}"

What does 'const static' mean in C and C++?

In C++,

static const int foo = 42;

is the preferred way to define & use constants. I.e. use this rather than

#define foo 42

because it doesn't subvert the type-safety system.

Chrome desktop notification example

I made this simple Notification wrapper. It works on Chrome, Safari and Firefox.

Probably on Opera, IE and Edge as well but I haven't tested it yet.

Just get the notify.js file from here https://github.com/gravmatt/js-notify and put it into your page.

Get it on Bower

$ bower install js-notify

This is how it works:

notify('title', {
    body: 'Notification Text',
    icon: 'path/to/image.png',
    onclick: function(e) {}, // e -> Notification object
    onclose: function(e) {},
    ondenied: function(e) {}
  });

You have to set the title but the json object as the second argument is optional.

Is there an alternative sleep function in C to milliseconds?

Beyond usleep, the humble select with NULL file descriptor sets will let you pause with microsecond precision, and without the risk of SIGALRM complications.

sigtimedwait and sigwaitinfo offer similar behavior.

In ASP.NET MVC: All possible ways to call Controller Action Method from a Razor View

Method 1 : Using jQuery Ajax Get call (partial page update).

Suitable for when you need to retrieve jSon data from database.

Controller's Action Method

[HttpGet]
public ActionResult Foo(string id)
{
    var person = Something.GetPersonByID(id);
    return Json(person, JsonRequestBehavior.AllowGet);
}

Jquery GET

function getPerson(id) {
    $.ajax({
        url: '@Url.Action("Foo", "SomeController")',
        type: 'GET',
        dataType: 'json',
        // we set cache: false because GET requests are often cached by browsers
        // IE is particularly aggressive in that respect
        cache: false,
        data: { id: id },
        success: function(person) {
            $('#FirstName').val(person.FirstName);
            $('#LastName').val(person.LastName);
        }
    });
}

Person class

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Method 2 : Using jQuery Ajax Post call (partial page update).

Suitable for when you need to do partial page post data into database.

Post method is also same like above just replace [HttpPost] on Action method and type as post for jquery method.

For more information check Posting JSON Data to MVC Controllers Here

Method 3 : As a Form post scenario (full page update).

Suitable for when you need to save or update data into database.

View

@using (Html.BeginForm("SaveData","ControllerName", FormMethod.Post))
{        
    @Html.TextBoxFor(model => m.Text)
    
    <input type="submit" value="Save" />
}

Action Method

[HttpPost]
public ActionResult SaveData(FormCollection form)
    {
        // Get movie to update
        return View();
   }

Method 4 : As a Form Get scenario (full page update).

Suitable for when you need to Get data from database

Get method also same like above just replace [HttpGet] on Action method and FormMethod.Get for View's form method.

I hope this will help to you.

R object identification

attributes(someObject) 

Can also be useful

How do I make a WinForms app go Full Screen

A tested and simple solution

I've been looking for an answer for this question in SO and some other sites, but one gave an answer was very complex to me and some others answers simply doesn't work correctly, so after a lot code testing I solved this puzzle.

Note: I'm using Windows 8 and my taskbar isn't on auto-hide mode.

I discovered that setting the WindowState to Normal before performing any modifications will stop the error with the not covered taskbar.

The code

I created this class that have two methods, the first enters in the "full screen mode" and the second leaves the "full screen mode". So you just need to create an object of this class and pass the Form you want to set full screen as an argument to the EnterFullScreenMode method or to the LeaveFullScreenMode method:

class FullScreen
{
    public void EnterFullScreenMode(Form targetForm)
    {
        targetForm.WindowState = FormWindowState.Normal;
        targetForm.FormBorderStyle = FormBorderStyle.None;
        targetForm.WindowState = FormWindowState.Maximized;
    }

    public void LeaveFullScreenMode(Form targetForm)
    {
        targetForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;
        targetForm.WindowState = FormWindowState.Normal;
    }
}

Usage example

    private void fullScreenToolStripMenuItem_Click(object sender, EventArgs e)
    {
        FullScreen fullScreen = new FullScreen();

        if (fullScreenMode == FullScreenMode.No)  // FullScreenMode is an enum
        {
            fullScreen.EnterFullScreenMode(this);
            fullScreenMode = FullScreenMode.Yes;
        }
        else
        {
            fullScreen.LeaveFullScreenMode(this);
            fullScreenMode = FullScreenMode.No;
        }
    }

I have placed this same answer on another question that I'm not sure if is a duplicate or not of this one. (Link to the other question: How to display a Windows Form in full screen on top of the taskbar?)

AngularJS - How can I do a redirect with a full page load?

I had the same issue. When I use window.location, $window.location or even <a href="..." target="_self"> the route does not refresh the page. So the cached services are used which is not what I want in my app. I resolved it by adding window.location.reload() after window.location to force the page to reload after routing. This method seems to load the page twice though. Might be a dirty trick, but it does the work. This is how I have it now:

  $scope.openPage = function (pageName) {
      window.location = '#/html/pages/' + pageName;
      window.location.reload();
  };

Can I invoke an instance method on a Ruby module without including it?

A. In case you, always want to call them in a "qualified", standalone way (UsefulThings.get_file), then just make them static as others pointed out,

module UsefulThings
  def self.get_file; ...
  def self.delete_file; ...

  def self.format_text(x); ...

  # Or.. make all of the "static"
  class << self
     def write_file; ...
     def commit_file; ...
  end

end

B. If you still want to keep the mixin approach in same cases, as well the one-off standalone invocation, you can have a one-liner module that extends itself with the mixin:

module UsefulThingsMixin
  def get_file; ...
  def delete_file; ...

  def format_text(x); ...
end

module UsefulThings
  extend UsefulThingsMixin
end

So both works then:

  UsefulThings.get_file()       # one off

   class MyUser
      include UsefulThingsMixin  
      def f
         format_text             # all useful things available directly
      end
   end 

IMHO it's cleaner than module_function for every single method - in case want all of them.

Java equivalent to JavaScript's encodeURIComponent that produces identical output?

This is a straightforward example Ravi Wallau's solution:

public String buildSafeURL(String partialURL, String documentName)
        throws ScriptException {
    ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
    ScriptEngine scriptEngine = scriptEngineManager
            .getEngineByName("JavaScript");

    String urlSafeDocumentName = String.valueOf(scriptEngine
            .eval("encodeURIComponent('" + documentName + "')"));
    String safeURL = partialURL + urlSafeDocumentName;

    return safeURL;
}

public static void main(String[] args) {
    EncodeURIComponentDemo demo = new EncodeURIComponentDemo();
    String partialURL = "https://www.website.com/document/";
    String documentName = "Tom & Jerry Manuscript.pdf";

    try {
        System.out.println(demo.buildSafeURL(partialURL, documentName));
    } catch (ScriptException se) {
        se.printStackTrace();
    }
}

Output: https://www.website.com/document/Tom%20%26%20Jerry%20Manuscript.pdf

It also answers the hanging question in the comments by Loren Shqipognja on how to pass a String variable to encodeURIComponent(). The method scriptEngine.eval() returns an Object, so it can converted to String via String.valueOf() among other methods.

Is the 'as' keyword required in Oracle to define an alias?

(Tested on Oracle 11g)

About AS:

  • When used on result column, AS is optional.
  • When used on table name, AS shouldn't be added, otherwise it's an error.

About double quote:

  • It's optional & valid for both result column & table name.

e.g

-- 'AS' is optional for result column
select (1+1) as result from dual;
select (1+1) result from dual;


-- 'AS' shouldn't be used for table name
select 'hi' from dual d;


-- Adding double quotes for alias name is optional, but valid for both result column & table name,
select (1+1) as "result" from dual;
select (1+1) "result" from dual;

select 'hi' from dual "d";

Session 'app' error while installing APK

i was also getting the same error repeatedly but could not solve it as i am complete new to android development. But then it came to my mind that the error is appearing because its not able to install the apk in the device as the error says. So i make sure that my Oneplus3 is in debugging mode and also allowing file transfer when connected via USB. And this solved the problem.

Also previously it was not doing the instant run but now it does.

So check whether your android device is allowed to transfer files while connected via USB. This might help.

Is there a difference between `continue` and `pass` in a for loop in python?

x = [1,2,3,4] 
for i in x:
    if i==2:
         pass  #Pass actually does nothing. It continues to execute statements below it.
         print "This statement is from pass."
for i in x:
    if i==2:
         continue #Continue gets back to top of the loop.And statements below continue are executed.
         print "This statement is from continue."

The output is

>>> This statement is from pass.

Again, let run same code with minor changes.

x = [1,2,3,4]
for i in x:
    if i==2:
       pass  #Pass actually does nothing. It continues to execute statements below it.
    print "This statement is from pass."
for i in x:
    if i==2:
        continue #Continue gets back to top of the loop.And statements below continue are executed.
    print "This statement is from continue."

The output is -

>>> This statement is from pass.
This statement is from pass.
This statement is from pass.
This statement is from pass.
This statement is from continue.
This statement is from continue.
This statement is from continue.

Pass doesn't do anything. Computation is unaffected. But continue gets back to top of the loop to procced with next computation.

How to generate random number with the specific length in python

From the official documentation, does it not seem that the sample() method is appropriate for this purpose?

import random

def random_digits(n):
    num = range(0, 10)
    lst = random.sample(num, n)
    print str(lst).strip('[]')

Output:

>>>random_digits(5)
2, 5, 1, 0, 4

unable to dequeue a cell with identifier Cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard

I was also struggling with the same problem. I had actually deleted the class and rebuilt it. Someone, the storyboard had dropped the link between prototype cell and the identifier.

I deleted the identifier name and re-typed the identifier name again.

It worked.

How to get item's position in a list?

Hmmm. There was an answer with a list comprehension here, but it's disappeared.

Here:

 [i for i,x in enumerate(testlist) if x == 1]

Example:

>>> testlist
[1, 2, 3, 5, 3, 1, 2, 1, 6]
>>> [i for i,x in enumerate(testlist) if x == 1]
[0, 5, 7]

Update:

Okay, you want a generator expression, we'll have a generator expression. Here's the list comprehension again, in a for loop:

>>> for i in [i for i,x in enumerate(testlist) if x == 1]:
...     print i
... 
0
5
7

Now we'll construct a generator...

>>> (i for i,x in enumerate(testlist) if x == 1)
<generator object at 0x6b508>
>>> for i in (i for i,x in enumerate(testlist) if x == 1):
...     print i
... 
0
5
7

and niftily enough, we can assign that to a variable, and use it from there...

>>> gen = (i for i,x in enumerate(testlist) if x == 1)
>>> for i in gen: print i
... 
0
5
7

And to think I used to write FORTRAN.

how to disable DIV element and everything inside

Try this!

$("#test *").attr("disabled", "disabled").off('click');

I don't see you using jquery above, but you have it listed as a tag.

RESTful call in Java

I want to share my personal experience, calling a REST WS with Post JSON call:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.URL;
import java.net.URLConnection;

public class HWS {

    public static void main(String[] args) throws IOException {
        URL url = new URL("INSERT YOUR SERVER REQUEST");
        //Insert your JSON query request
        String query = "{'PARAM1': 'VALUE','PARAM2': 'VALUE','PARAM3': 'VALUE','PARAM4': 'VALUE'}";
        //It change the apostrophe char to double quote char, to form a correct JSON string
        query=query.replace("'", "\"");

        try{
            //make connection
            URLConnection urlc = url.openConnection();
            //It Content Type is so important to support JSON call
            urlc.setRequestProperty("Content-Type", "application/xml");
            Msj("Conectando: " + url.toString());
            //use post mode
            urlc.setDoOutput(true);
            urlc.setAllowUserInteraction(false);
    
            //send query
            PrintStream ps = new PrintStream(urlc.getOutputStream());
            ps.print(query);
            Msj("Consulta: " + query);
            ps.close();
    
            //get result
            BufferedReader br = new BufferedReader(new InputStreamReader(urlc.getInputStream()));
            String l = null;
            while ((l=br.readLine())!=null) {
                Msj(l);
            }
            br.close();
        } catch (Exception e){
            Msj("Error ocurrido");
            Msj(e.toString());
        }
    }
    
    private static void Msj(String texto){
        System.out.println(texto);
    }
}

What is the difference between "INNER JOIN" and "OUTER JOIN"?

There are major mainly 2 types of JOINs in SQL: [INNER and OUTER]


Examples

Suppose you have two tables, with a single column each, and data as follows:

A    B
-    -
1    3
2    4
3    5
4    6
7
8

Note that (1,2,7,8) are unique to A, (3,4) are common, and (5,6) are unique to B.



  • (INNER) JOIN:

The INNER JOIN keyword selects all rows from both the tables as long as the condition satisfies. This keyword will create the result-set by combining all rows from both the tables where the condition satisfies i.e value of the common field will be the same.

INNER JOIN

select * from a INNER JOIN b on a.a = b.b;
select a.*, b.*  from a,b where a.a = b.b;

Result:

a | b
--+--
3 | 3
4 | 4


  • LEFT (OUTER) JOIN:

This join returns all the rows of the table on the left side of the join and matching rows for the table on the right side of the join. The rows for which there is no matching row on the right side, the result-set will contain null. LEFT JOIN is also known as LEFT OUTER JOIN.

LEFT JOIN / LEFT OUTER JOIN

select * from a LEFT OUTER JOIN b on a.a = b.b;
select a.*, b.*  from a,b where a.a = b.b(+);

Result:

a |  b
--+-----
1 | null
2 | null
3 |    3
4 |    4
7 | null
8 | null


  • RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched records from the left table

RIGHT JOIN / RIGHT OUTER JOIN

select * from a RIGHT OUTER JOIN b on a.a = b.b;
select a.*, b.*  from a,b where a.a(+) = b.b;

Result:

a    |  b
-----+----
3    |  3
4    |  4
null |  5
null |  6


  • FULL (OUTER) JOIN:

    FULL JOIN creates the result-set by combining the result of both LEFT JOIN and RIGHT JOIN. The result-set will contain all the rows from both the tables. The rows for which there is no matching, the result-set will contain NULL values.

FULL JOIN / FULL OUTER JOIN

select * from a FULL OUTER JOIN b on a.a = b.b;

Result:

 a   |  b
-----+-----
   1 | null
   2 | null
   3 |    3
   4 |    4
null |    6
null |    5
   7 | null
   8 | null

JavaScript function to add X months to a date

From the answers above, the only one that handles the edge cases (bmpasini's from datejs library) has an issue:

var date = new Date("03/31/2015");
var newDate = date.addMonths(1);
console.log(newDate);
// VM223:4 Thu Apr 30 2015 00:00:00 GMT+0200 (CEST)

ok, but:

newDate.toISOString()
//"2015-04-29T22:00:00.000Z"

worse :

var date = new Date("01/01/2015");
var newDate = date.addMonths(3);
console.log(newDate);
//VM208:4 Wed Apr 01 2015 00:00:00 GMT+0200 (CEST)
newDate.toISOString()
//"2015-03-31T22:00:00.000Z"

This is due to the time not being set, thus reverting to 00:00:00, which then can glitch to previous day due to timezone or time-saving changes or whatever...

Here's my proposed solution, which does not have that problem, and is also, I think, more elegant in that it does not rely on hard-coded values.

/**
* @param isoDate {string} in ISO 8601 format e.g. 2015-12-31
* @param numberMonths {number} e.g. 1, 2, 3...
* @returns {string} in ISO 8601 format e.g. 2015-12-31
*/
function addMonths (isoDate, numberMonths) {
    var dateObject = new Date(isoDate),
        day = dateObject.getDate(); // returns day of the month number

    // avoid date calculation errors
    dateObject.setHours(20);

    // add months and set date to last day of the correct month
    dateObject.setMonth(dateObject.getMonth() + numberMonths + 1, 0);

    // set day number to min of either the original one or last day of month
    dateObject.setDate(Math.min(day, dateObject.getDate()));

    return dateObject.toISOString().split('T')[0];
};

Unit tested successfully with:

function assertEqual(a,b) {
    return a === b;
}
console.log(
    assertEqual(addMonths('2015-01-01', 1), '2015-02-01'),
    assertEqual(addMonths('2015-01-01', 2), '2015-03-01'),
    assertEqual(addMonths('2015-01-01', 3), '2015-04-01'),
    assertEqual(addMonths('2015-01-01', 4), '2015-05-01'),
    assertEqual(addMonths('2015-01-15', 1), '2015-02-15'),
    assertEqual(addMonths('2015-01-31', 1), '2015-02-28'),
    assertEqual(addMonths('2016-01-31', 1), '2016-02-29'),
    assertEqual(addMonths('2015-01-01', 11), '2015-12-01'),
    assertEqual(addMonths('2015-01-01', 12), '2016-01-01'),
    assertEqual(addMonths('2015-01-01', 24), '2017-01-01'),
    assertEqual(addMonths('2015-02-28', 12), '2016-02-28'),
    assertEqual(addMonths('2015-03-01', 12), '2016-03-01'),
    assertEqual(addMonths('2016-02-29', 12), '2017-02-28')
);

PHP - SSL certificate error: unable to get local issuer certificate

elaborating on the above answers for server deployment.

$hostname = gethostname();
if($hostname=="mydevpc")
{
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
}

should do the trick for development environment without compromising the server when deployed.

Curl GET request with json parameter

If you really want to submit the GET request with JSON in the body (say for an XHR request and you know the server supports processing the body on GET requests), you can:

curl -X GET \
  -H "Content-type: application/json" \
  -H "Accept: application/json" \
  -d '{"param0":"pradeep"}' \
  "http://server:5050/a/c/getName"

Most modern web servers accept this type of request.

How to format a java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) to a date(yyyy-MM-dd HH:mm:ss)

A date-time object is not a String

The java.sql.Timestamp class has no format. Its toString method generates a String with a format.

Do not conflate a date-time object with a String that may represent its value. A date-time object can parse strings and generate strings but is not itself a string.

java.time

First convert from the troubled old legacy date-time classes to java.time classes. Use the new methods added to the old classes.

Instant instant = mySqlDate.toInstant() ;

Lose the fraction of a second you don't want.

instant = instant.truncatedTo( ChronoUnit.Seconds );

Assign the time zone to adjust from UTC used by Instant.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z );

Generate a String close to your desired output. Replace its T in the middle with a SPACE.

DateTimeFormatter f = DateTimeFormatter.ISO_LOCAL_DATE_TIME ;
String output = zdt.format( f ).replace( "T" , " " );

jquery 3.0 url.indexOf error

Jquery 3.0 has some breaking changes that remove certain methods due to conflicts. Your error is most likely due to one of these changes such as the removal of the .load() event.

Read more in the jQuery Core 3.0 Upgrade Guide

To fix this you either need to rewrite the code to be compatible with Jquery 3.0 or else you can use the JQuery Migrate plugin which restores the deprecated and/or removed APIs and behaviours.

In VBA get rid of the case sensitivity when comparing words?

There is a statement you can issue at the module level:

Option Compare Text

This makes all "text comparisons" case insensitive. This means the following code will show the message "this is true":

Option Compare Text

Sub testCase()
  If "UPPERcase" = "upperCASE" Then
    MsgBox "this is true: option Compare Text has been set!"
  End If
End Sub

See for example http://www.ozgrid.com/VBA/vba-case-sensitive.htm . I'm not sure it will completely solve the problem for all instances (such as the Application.Match function) but it will take care of all the if a=b statements. As for Application.Match - you may want to convert the arguments to either upper case or lower case using the LCase function.

How to write the code for the back button?

In my application,above javascript function didnt work,because i had many procrosses inside one page.so following code worked for me hope it helps you guys.

  function redirection()
        {
           <?php $send=$_SERVER['HTTP_REFERER'];?> 
            var redirect_to="<?php echo $send;?>";             
            window.location = redirect_to;

        }

Delete dynamically-generated table row using jQuery

A simple solution is encapsulate code of button event in a function, and call it when you add TRs too:

 var i = 1;
$("#addbutton").click(function() {
  $("table tr:first").clone().find("input").each(function() {
    $(this).val('').attr({
      'id': function(_, id) {return id + i },
      'name': function(_, name) { return name + i },
      'value': ''               
    });
  }).end().appendTo("table");
  i++;

  applyRemoveEvent();  
});


function applyRemoveEvent(){
    $('button.removebutton').on('click',function() {
        alert("aa");
      $(this).closest( 'tr').remove();
      return false;
    });
};

applyRemoveEvent();

http://jsfiddle.net/Z7fG7/2/

reading and parsing a TSV file, then manipulating it for saving as CSV (*efficiently*)

You should use the csv module to read the tab-separated value file. Do not read it into memory in one go. Each row you read has all the information you need to write rows to the output CSV file, after all. Keep the output file open throughout.

import csv

with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
    tsvin = csv.reader(tsvin, delimiter='\t')
    csvout = csv.writer(csvout)

    for row in tsvin:
        count = int(row[4])
        if count > 0:
            csvout.writerows([row[2:4] for _ in range(count)])

or, using the itertools module to do the repeating with itertools.repeat():

from itertools import repeat
import csv

with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
    tsvin = csv.reader(tsvin, delimiter='\t')
    csvout = csv.writer(csvout)

    for row in tsvin:
        count = int(row[4])
        if count > 0:
            csvout.writerows(repeat(row[2:4], count))

Sending and Receiving SMS and MMS in Android (pre Kit Kat Android 4.4)

To send an mms for Android 4.0 api 14 or higher without permission to write apn settings, you can use this library: Retrieve mnc and mcc codes from android, then call

Carrier c = Carrier.getCarrier(mcc, mnc);
if (c != null) {
    APN a = c.getAPN();
    if (a != null) {
        String mmsc = a.mmsc;
        String mmsproxy = a.proxy; //"" if none
        int mmsport = a.port; //0 if none
    }
}

To use this, add Jsoup and droid prism jar to the build path, and import com.droidprism.*;

LINQ's Distinct() on a particular property

I've written an article that explains how to extend the Distinct function so that you can do as follows:

var people = new List<Person>();

people.Add(new Person(1, "a", "b"));
people.Add(new Person(2, "c", "d"));
people.Add(new Person(1, "a", "b"));

foreach (var person in people.Distinct(p => p.ID))
    // Do stuff with unique list here.

Here's the article (now in the Web Archive): Extending LINQ - Specifying a Property in the Distinct Function

Offline Speech Recognition In Android (JellyBean)

I successfully implemented my Speech-Service with offline capabilities by using onPartialResults when offline and onResults when online.

Trying to handle "back" navigation button action in iOS

None of the other solutions worked for me, but this does:

Create your own subclass of UINavigationController, make it implement the UINavigationBarDelegate (no need to manually set the navigation bar's delegate), add a UIViewController extension that defines a method to be called on a back button press, and then implement this method in your UINavigationController subclass:

func navigationBar(_ navigationBar: UINavigationBar, shouldPop item: UINavigationItem) -> Bool {
    self.topViewController?.methodToBeCalledOnBackButtonPress()
    self.popViewController(animated: true)
    return true
}

python ValueError: invalid literal for float()

Watch out for possible unintended literals in your argument

for example you can have a space within your argument, rendering it to a string / literal:

float(' 0.33')

After making sure the unintended space did not make it into the argument, I was left with:

float(0.33) 

Like this it works like a charm.

Take away is: Pay Attention for unintended literals (e.g. spaces that you didn't see) within your input.

javascript - match string against the array of regular expressions

look this way...

function matchInArray(stringSearch, arrayExpressions){
    var position = String(arrayExpressions).search(stringSearch);
    var result = (position > -1) ? true : false
    return result;
}

Remove the last character from a string

An alternative to substr is the following, as a function:

substr_replace($string, "", -1)

Is it the fastest? I don't know, but I'm willing to bet these alternatives are all so fast that it just doesn't matter.

What do 3 dots next to a parameter type mean in Java?

Just think of it as the keyword params in C#, if you are coming from that background :)

How to create a file on Android Internal Storage?

Write a file

When saving a file to internal storage, you can acquire the appropriate directory as a File by calling one of two methods:

getFilesDir()

      Returns a File representing an internal directory for your app.

getCacheDir()

     Returns a File representing an internal directory for your 
     app's temporary cache files.
     Be sure to delete each file once it is no longer needed and implement a reasonable 
     size limit for the amount of memory you use at any given time, such as 1MB.

Caution: If the system runs low on storage, it may delete your cache files without warning.

Count number of rows by group using dplyr

another approach is to use the double colons:

mtcars %>% 
  dplyr::group_by(cyl, gear) %>%
  dplyr::summarise(length(gear))

Unnamed/anonymous namespaces vs. static functions

In addition if one uses static keyword on a variable like this example:

namespace {
   static int flag;
}

It would not be seen in the mapping file

Populate a datagridview with sql query results

if you are using mysql this code you can use.

string con = "SERVER=localhost; user id=root; password=; database=databasename";
    private void loaddata()
{
MySqlConnection connect = new MySqlConnection(con);
connect.Open();
try
{
MySqlCommand cmd = connect.CreateCommand();
cmd.CommandText = "SELECT * FROM DATA1";
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
datagrid.DataSource = dt;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Why can't non-default arguments follow default arguments?

Let me clear two points here :

  • firstly non-default argument should not follow default argument , it means you can't define (a=b,c) in function the order of defining parameter in function are :
    • positional parameter or non-default parameter i.e (a,b,c)
    • keyword parameter or default parameter i.e (a="b",r="j")
    • keyword-only parameter i.e (*args)
    • var-keyword parameter i.e (**kwargs)

def example(a, b, c=None, r="w" , d=[], *ae, **ab):

(a,b) are positional parameter

(c=none) is optional parameter

(r="w") is keyword parameter

(d=[]) is list parameter

(*ae) is keyword-only

(**ab) is var-keyword parameter

  • now secondary thing is if i try something like this : def example(a, b, c=a,d=b):

argument is not defined when default values are saved,Python computes and saves default values when you define the function

c and d are not defined, does not exist, when this happens (it exists only when the function is executed)

"a,a=b" its not allowed in parameter.

Time complexity of accessing a Python dict

As others have pointed out, accessing dicts in Python is fast. They are probably the best-oiled data structure in the language, given their central role. The problem lies elsewhere.

How many tuples are you memoizing? Have you considered the memory footprint? Perhaps you are spending all your time in the memory allocator or paging memory.

How to format a number as percentage in R?

Even later:

As pointed out by @DzimitryM, percent() has been "retired" in favor of label_percent(), which is a synonym for the old percent_format() function.

label_percent() returns a function, so to use it, you need an extra pair of parentheses.

library(scales)
x <- c(-1, 0, 0.1, 0.555555, 1, 100)
label_percent()(x)
## [1] "-100%"   "0%"      "10%"     "56%"     "100%"    "10 000%"

Customize this by adding arguments inside the first set of parentheses.

label_percent(big.mark = ",", suffix = " percent")(x)
## [1] "-100 percent"   "0 percent"      "10 percent"    
## [4] "56 percent"     "100 percent"    "10,000 percent"

An update, several years later:

These days there is a percent function in the scales package, as documented in krlmlr's answer. Use that instead of my hand-rolled solution.


Try something like

percent <- function(x, digits = 2, format = "f", ...) {
  paste0(formatC(100 * x, format = format, digits = digits, ...), "%")
}

With usage, e.g.,

x <- c(-1, 0, 0.1, 0.555555, 1, 100)
percent(x)

(If you prefer, change the format from "f" to "g".)

When do we need curly braces around shell variables?

You are also able to do some text manipulation inside the braces:

STRING="./folder/subfolder/file.txt"
echo ${STRING} ${STRING%/*/*}

Result:

./folder/subfolder/file.txt ./folder

or

STRING="This is a string"
echo ${STRING// /_}

Result:

This_is_a_string

You are right in "regular variables" are not needed... But it is more helpful for the debugging and to read a script.

Automated testing for REST Api

You can also use Rest Assured library. For a demo with sample script, refer to http://artoftesting.com/automationTesting/restAPIAutomationGetRequest.html

How can I show/hide a specific alert with twitter bootstrap?

You need to use an id selector:

 //show
 $('#passwordsNoMatchRegister').show();
 //hide
 $('#passwordsNoMatchRegister').hide();

# is an id selector and passwordsNoMatchRegister is the id of the div.

How to show Snackbar when Activity starts?

A utils function for show snack bar

fun showSnackBar(activity: Activity, message: String, action: String? = null,
    actionListener: View.OnClickListener? = null, duration: Int = Snackbar.LENGTH_SHORT) {
    val snackBar = Snackbar.make(activity.findViewById(android.R.id.content), message, duration)
        .setBackgroundColor(Color.parseColor("#CC000000")) // todo update your color
        .setTextColor(Color.WHITE)
    if (action != null && actionListener!=null) {
        snackBar.setAction(action, actionListener)
    }
    snackBar.show()
}

Example using in Activity

  showSnackBar(this, "No internet")
  showSnackBar(this, "No internet", duration = Snackbar.LENGTH_LONG)
  showSnackBar(activity, "No internet", "OK", View.OnClickListener { 
       // handle click 
  })

Example using in Fragment

  showSnackBar(getActivity(), "No internet")

Hope it help

The split() method in Java does not work on a dot (.)

The documentation on split() says:

Splits this string around matches of the given regular expression.

(Emphasis mine.)

A dot is a special character in regular expression syntax. Use Pattern.quote() on the parameter to split() if you want the split to be on a literal string pattern:

String[] words = temp.split(Pattern.quote("."));

CSS center display inline block?

Try this. I added text-align: center to body and display:inline-block to wrap, and then removed your display: table

body {
    background: #bbb;
    text-align: center;
}

.wrap {
    background: #aaa;
    margin: 0 auto;
    display: inline-block;
    overflow: hidden;
}

Android 5.0 - Add header/footer to a RecyclerView

I had to add a footer to my RecyclerView and here I'm sharing my code snippet as I thought it might be useful. Please check the comments inside the code for better understanding of the overall flow.

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;

public class RecyclerViewWithFooterAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private static final int FOOTER_VIEW = 1;
    private ArrayList<String> data; // Take any list that matches your requirement.
    private Context context;

    // Define a constructor
    public RecyclerViewWithFooterAdapter(Context context, ArrayList<String> data) {
        this.context = context;
        this.data = data;
    }

    // Define a ViewHolder for Footer view
    public class FooterViewHolder extends ViewHolder {
        public FooterViewHolder(View itemView) {
            super(itemView);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // Do whatever you want on clicking the item
                }
            });
        }
    }

    // Now define the ViewHolder for Normal list item
    public class NormalViewHolder extends ViewHolder {
        public NormalViewHolder(View itemView) {
            super(itemView);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // Do whatever you want on clicking the normal items
                }
            });
        }
    }

    // And now in onCreateViewHolder you have to pass the correct view
    // while populating the list item.

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View v;

        if (viewType == FOOTER_VIEW) {
            v = LayoutInflater.from(context).inflate(R.layout.list_item_footer, parent, false);
            FooterViewHolder vh = new FooterViewHolder(v);
            return vh;
        }

        v = LayoutInflater.from(context).inflate(R.layout.list_item_normal, parent, false);

        NormalViewHolder vh = new NormalViewHolder(v);

        return vh;
    }

    // Now bind the ViewHolder in onBindViewHolder
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

        try {
            if (holder instanceof NormalViewHolder) {
                NormalViewHolder vh = (NormalViewHolder) holder;

                vh.bindView(position);
            } else if (holder instanceof FooterViewHolder) {
                FooterViewHolder vh = (FooterViewHolder) holder;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // Now the critical part. You have return the exact item count of your list
    // I've only one footer. So I returned data.size() + 1
    // If you've multiple headers and footers, you've to return total count
    // like, headers.size() + data.size() + footers.size()

    @Override
    public int getItemCount() {
        if (data == null) {
            return 0;
        }

        if (data.size() == 0) {
            //Return 1 here to show nothing
            return 1;
        }

        // Add extra view to show the footer view
        return data.size() + 1;
    }

    // Now define getItemViewType of your own.

    @Override
    public int getItemViewType(int position) {
        if (position == data.size()) {
            // This is where we'll add footer.
            return FOOTER_VIEW;
        }

        return super.getItemViewType(position);
    }

    // So you're done with adding a footer and its action on onClick.
    // Now set the default ViewHolder for NormalViewHolder

    public class ViewHolder extends RecyclerView.ViewHolder {
        // Define elements of a row here
        public ViewHolder(View itemView) {
            super(itemView);
            // Find view by ID and initialize here
        }

        public void bindView(int position) {
            // bindView() method to implement actions
        }
    }
}

The above code snippet adds a footer to the RecyclerView. You can check this GitHub repository for checking the implementation of adding both header and a footer.

How can I add an element after another element?

Solved jQuery: Add element after another element

<script>
$( "p" ).append( "<strong>Hello</strong>" );
</script>

OR

<script type="text/javascript"> 
jQuery(document).ready(function(){
jQuery ( ".sidebar_cart" ) .append( "<a href='http://#'>Continue Shopping</a>" );
});
</script>

Javascript - Get Image height

Just load the image in a hidden <img> tag (style = "display none"), listen to the load event firing with jQuery, create a new Image() with JavaScript, set the source to the invisible image, and get the size like above.

eclipse won't start - no java virtual machine was found

Via Puppet ATG installation Centos.

ERROR:

No Java virtual machine could be found from your PATH

SOLUTION:

Declear variable :

$java_home="/opt/oracle/product/java/jdk1.8.0_45/bin"

Add This "{$java_home}" Java Exec

require common, java
Exec {
    path => [ "${java_home}", "/usr/bin", "/bin", "/usr/sbin", "${temp_directory}"]
}

How to set $_GET variable

You can create a link , having get variable in href.

<a href="www.site.com/hello?getVar=value" >...</a>

How to verify an XPath expression in Chrome Developers tool or Firefox's Firebug?

Chrome

This can be achieved by three different approaches (see my blog article here for more details):

  • Search in Elements panel like below
  • Execute $x() and $$() in Console panel, as shown in Lawrence's answer
  • Third party extensions (not really necessary in most of the cases, could be an overkill)

Here is how you search XPath in Elements panel:

  1. Press F12 to open Chrome Developer Tool
  2. In "Elements" panel, press Ctrl+F
  3. In the search box, type in XPath or CSS Selector, if elements are found, they will be highlighted in yellow.

enter image description here

Firefox (since version 75)

Since FF 75 it's possible to use raw xpath query without evaluation xpath expressions, see documentation for more info.

Firefox (prior version 75)

  1. Either select "Web Console" from the Web Developer submenu in the Firefox Menu (or Tools menu if you display the menu bar or are on Mac OS X)
    or press the Ctrl+Shift+K (Command+Option+K on OS X) keyboard shortcut.
  2. In the command line at the bottom use the following:

    • $(): Returns the first element that matches. Equivalent to document.querySelector() or calls the $ function in the page, if it exists.

    • $$(): Returns an array of DOM nodes that match. This is like for document.querySelectorAll(), but returns an array instead of a NodeList.

    • $x(): Evaluates an XPath expression and returns an array of matching nodes.


Firefox (prior version 49)

  1. Install Firebug
  2. Install Firepath
  3. Press F12 to open Firebug
  4. Switch to FirePath panel
  5. In dropdown, select XPathor CSS
  6. Type in to locate

enter image description here

Representational state transfer (REST) and Simple Object Access Protocol (SOAP)

I think that this is as easy as I can explain it. Please, anyone is welcome to correct me or add to this.

SOAP is a message format used by disconnected systems (like across the internet) to exchange information / data. It does with XML messages going back and forth.

Web services transmit or receive SOAP messages. They work differently depending on what language they are written in.

Load a HTML page within another HTML page

iframe is the tag which you can use for call other html pages into your web page

<iframe src="http://www.google.co.in" name="targetframe" allowTransparency="true" scrolling="no" frameborder="0" >
    </iframe>

Is there a pretty print for PHP?

If you want a nicer representation of any PHP variable (than just plain text), I suggest you try nice_r(); it prints out values plus relevant useful information (eg: properties and methods for objects). enter image description here Disclaimer: I wrote this myself.

How to get the number of columns from a JDBC ResultSet?

After establising the connection and executing the query try this:

 ResultSet resultSet;
 int columnCount = resultSet.getMetaData().getColumnCount();
 System.out.println("column count : "+columnCount);

Onclick CSS button effect

You should apply the following styles:

#button:active {
    vertical-align: top;
    padding: 8px 13px 6px;
}

This will give you the necessary effect, demo here.

Disable the postback on an <ASP:LinkButton>

In C#, you'd do something like this:

MyButton.Attributes.Add("onclick", "put your javascript here including... return false;");

How to find the type of an object in Go?

reflect package comes to rescue:

reflect.TypeOf(obj).String()

Check this demo

How to Allow Remote Access to PostgreSQL database

This is a complementary answer for the specific case of you using AWS cloud computing (either EC2 or RDS machines).

Besides doing everything proposed above, when using AWS cloud computing you will need to set you inbound rules in a way that let you access to the ports. Please check this post, which is valid for EC2 and RDS.

Multiple conditions with CASE statements

It's not a cut and paste. The CASE expression must return a value, and you are returning a string containing SQL (which is technically a value but of a wrong type). This is what you wanted to write, I think:

SELECT * FROM [Purchasing].[Vendor] WHERE  
CASE
  WHEN @url IS null OR @url = '' OR @url = 'ALL'
    THEN PurchasingWebServiceURL LIKE '%'
  WHEN @url = 'blank'
    THEN PurchasingWebServiceURL = ''
  WHEN @url = 'fail'
    THEN PurchasingWebServiceURL NOT LIKE '%treyresearch%'
  ELSE PurchasingWebServiceURL = '%' + @url + '%' 
END

I also suspect that this might not work in some dialects, but can't test now (Oracle, I'm looking at you), due to not having booleans.

However, since @url is not dependent on the table values, why not make three different queries, and choose which to evaluate based on your parameter?

How do you render primitives as wireframes in OpenGL?

A good and simple way of drawing anti-aliased lines on a non anti-aliased render target is to draw rectangles of 4 pixel width with an 1x4 texture, with alpha channel values of {0.,1.,1.,0.}, and use linear filtering with mip-mapping off. This will make the lines 2 pixels thick, but you can change the texture for different thicknesses. This is faster and easier than barymetric calculations.

Mongodb find() query : return only unique values (no duplicates)

I think you can use db.collection.distinct(fields,query)

You will be able to get the distinct values in your case for NetworkID.

It should be something like this :

Db.collection.distinct('NetworkID')

How does the "this" keyword work?

this is one of the misunderstood concept in JavaScript because it behaves little differently from place to place. Simply, this refers to the "owner" of the function we are currently executing.

this helps to get the current object (a.k.a. execution context) we work with. If you understand in which object the current function is getting executed, you can understand easily what current this is

var val = "window.val"

var obj = {
    val: "obj.val",
    innerMethod: function () {
        var val = "obj.val.inner",
            func = function () {
                var self = this;
                return self.val;
            };

        return func;
    },
    outerMethod: function(){
        return this.val;
    }
};

//This actually gets executed inside window object 
console.log(obj.innerMethod()()); //returns window.val

//Breakdown in to 2 lines explains this in detail
var _inn = obj.innerMethod();
console.log(_inn()); //returns window.val

console.log(obj.outerMethod()); //returns obj.val

Above we create 3 variables with same name 'val'. One in global context, one inside obj and the other inside innerMethod of obj. JavaScript resolves identifiers within a particular context by going up the scope chain from local go global.


Few places where this can be differentiated

Calling a method of a object

var status = 1;
var helper = {
    status : 2,
    getStatus: function () {
        return this.status;
    }
};

var theStatus1 = helper.getStatus(); //line1
console.log(theStatus1); //2

var theStatus2 = helper.getStatus;
console.log(theStatus2()); //1

When line1 is executed, JavaScript establishes an execution context (EC) for the function call, setting this to the object referenced by whatever came before the last ".". so in the last line you can understand that a() was executed in the global context which is the window.

With Constructor

this can be used to refer to the object being created

function Person(name){
    this.personName = name;
    this.sayHello = function(){
        return "Hello " + this.personName;
    }
}

var person1 = new Person('Scott');
console.log(person1.sayHello()); //Hello Scott

var person2 = new Person('Hugh');
var sayHelloP2 = person2.sayHello;
console.log(sayHelloP2()); //Hello undefined

When new Person() is executed, a completely new object is created. Person is called and its this is set to reference that new object.

Function call

function testFunc() {
    this.name = "Name";
    this.myCustomAttribute = "Custom Attribute";
    return this;
}

var whatIsThis = testFunc();
console.log(whatIsThis); //window

var whatIsThis2 = new testFunc();
console.log(whatIsThis2);  //testFunc() / object

console.log(window.myCustomAttribute); //Custom Attribute 

If we miss new keyword, whatIsThis referes to the most global context it can find(window)

With event handlers

If the event handler is inline, this refers to global object

<script type="application/javascript">
    function click_handler() {
        alert(this); // alerts the window object
    }
</script>

<button id='thebutton' onclick='click_handler()'>Click me!</button>

When adding event handler through JavaScript, this refers to DOM element that generated the event.


How can I get the assembly file version

UPDATE: As mentioned by Richard Grimes in my cited post, @Iain and @Dmitry Lobanov, my answer is right in theory but wrong in practice.

As I should have remembered from countless books, etc., while one sets these properties using the [assembly: XXXAttribute], they get highjacked by the compiler and placed into the VERSIONINFO resource.

For the above reason, you need to use the approach in @Xiaofu's answer as the attributes are stripped after the signal has been extracted from them.


public static string GetProductVersion()
{
  var attribute = (AssemblyVersionAttribute)Assembly
    .GetExecutingAssembly()
    .GetCustomAttributes( typeof(AssemblyVersionAttribute), true )
    .Single();
   return attribute.InformationalVersion;
}

(From http://bytes.com/groups/net/420417-assemblyversionattribute - as noted there, if you're looking for a different attribute, substitute that into the above)

pretty-print JSON using JavaScript

To highlight and beautify it in HTML using Bootstrap:

function prettifyJson(json, prettify) {
    if (typeof json !== 'string') {
        if (prettify) {
            json = JSON.stringify(json, undefined, 4);
        } else {
            json = JSON.stringify(json);
        }
    }
    return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g,
        function(match) {
            let cls = "<span>";
            if (/^"/.test(match)) {
                if (/:$/.test(match)) {
                    cls = "<span class='text-danger'>";
                } else {
                    cls = "<span>";
                }
            } else if (/true|false/.test(match)) {
                cls = "<span class='text-primary'>";
            } else if (/null/.test(match)) {
                cls = "<span class='text-info'>";
            }
            return cls + match + "</span>";
        }
    );
}

Create tap-able "links" in the NSAttributedString of a UILabel?

(My answer builds on @NAlexN's excellent answer. I won't duplicate his detailed explanation of each step here.)

I found it most convenient and straightforward to add support for tap-able UILabel text as a category to UITapGestureRecognizer. (You don't have to use UITextView's data detectors, as some answers suggest.)

Add the following method to your UITapGestureRecognizer category:

/**
 Returns YES if the tap gesture was within the specified range of the attributed text of the label.
 */
- (BOOL)didTapAttributedTextInLabel:(UILabel *)label inRange:(NSRange)targetRange {
    NSParameterAssert(label != nil);

    CGSize labelSize = label.bounds.size;
    // create instances of NSLayoutManager, NSTextContainer and NSTextStorage
    NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
    NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:CGSizeZero];
    NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:label.attributedText];

    // configure layoutManager and textStorage
    [layoutManager addTextContainer:textContainer];
    [textStorage addLayoutManager:layoutManager];

    // configure textContainer for the label
    textContainer.lineFragmentPadding = 0.0;
    textContainer.lineBreakMode = label.lineBreakMode;
    textContainer.maximumNumberOfLines = label.numberOfLines;
    textContainer.size = labelSize;

    // find the tapped character location and compare it to the specified range
    CGPoint locationOfTouchInLabel = [self locationInView:label];
    CGRect textBoundingBox = [layoutManager usedRectForTextContainer:textContainer];
    CGPoint textContainerOffset = CGPointMake((labelSize.width - textBoundingBox.size.width) * 0.5 - textBoundingBox.origin.x,
                                              (labelSize.height - textBoundingBox.size.height) * 0.5 - textBoundingBox.origin.y);
    CGPoint locationOfTouchInTextContainer = CGPointMake(locationOfTouchInLabel.x - textContainerOffset.x,
                                                         locationOfTouchInLabel.y - textContainerOffset.y);
    NSInteger indexOfCharacter = [layoutManager characterIndexForPoint:locationOfTouchInTextContainer
                                                            inTextContainer:textContainer
                                   fractionOfDistanceBetweenInsertionPoints:nil];
    if (NSLocationInRange(indexOfCharacter, targetRange)) {
        return YES;
    } else {
        return NO;
    }
}

Example Code

// (in your view controller)    
// create your label, gesture recognizer, attributed text, and get the range of the "link" in your label
myLabel.userInteractionEnabled = YES;
[myLabel addGestureRecognizer:
   [[UITapGestureRecognizer alloc] initWithTarget:self 
                                           action:@selector(handleTapOnLabel:)]]; 

// create your attributed text and keep an ivar of your "link" text range
NSAttributedString *plainText;
NSAttributedString *linkText;
plainText = [[NSMutableAttributedString alloc] initWithString:@"Add label links with UITapGestureRecognizer"
                                                   attributes:nil];
linkText = [[NSMutableAttributedString alloc] initWithString:@" Learn more..."
                                                  attributes:@{
                                                      NSForegroundColorAttributeName:[UIColor blueColor]
                                                  }];
NSMutableAttributedString *attrText = [[NSMutableAttributedString alloc] init];
[attrText appendAttributedString:plainText];
[attrText appendAttributedString:linkText];

// ivar -- keep track of the target range so you can compare in the callback
targetRange = NSMakeRange(plainText.length, linkText.length);

Gesture Callback

// handle the gesture recognizer callback and call the category method
- (void)handleTapOnLabel:(UITapGestureRecognizer *)tapGesture {
    BOOL didTapLink = [tapGesture didTapAttributedTextInLabel:myLabel
                                            inRange:targetRange];
    NSLog(@"didTapLink: %d", didTapLink);

}

Python: Open file in zip without temporarily extracting it

In theory, yes, it's just a matter of plugging things in. Zipfile can give you a file-like object for a file in a zip archive, and image.load will accept a file-like object. So something like this should work:

import zipfile
archive = zipfile.ZipFile('images.zip', 'r')
imgfile = archive.open('img_01.png')
try:
    image = pygame.image.load(imgfile, 'img_01.png')
finally:
    imgfile.close()

Valid to use <a> (anchor tag) without href attribute?

It is valid. You can, for example, use it to show modals (or similar things that respond to data-toggle and data-target attributes).

Something like:

<a role="button" data-toggle="modal" data-target=".bs-example-modal-sm" aria-hidden="true"><i class="fa fa-phone"></i></a>

Here I use the font-awesome icon, which is better as a a tag rather than a button, to show a modal. Also, setting role="button" makes the pointer change to an action type. Without either href or role="button", the cursor pointer does not change.

Django - "no module named django.core.management"

I had the same issue and the reason I was getting this message was because I was doing "manage.py runserver" whereas doing "python manage.py runserver" fixed it.

PHP php_network_getaddresses: getaddrinfo failed: No such host is known

It is more flexible to use curl instead of fopen and file_get_content for opening a webpage.

How to do exponential and logarithmic curve fitting in Python? I found only polynomial fitting

You can also fit a set of a data to whatever function you like using curve_fit from scipy.optimize. For example if you want to fit an exponential function (from the documentation):

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

def func(x, a, b, c):
    return a * np.exp(-b * x) + c

x = np.linspace(0,4,50)
y = func(x, 2.5, 1.3, 0.5)
yn = y + 0.2*np.random.normal(size=len(x))

popt, pcov = curve_fit(func, x, yn)

And then if you want to plot, you could do:

plt.figure()
plt.plot(x, yn, 'ko', label="Original Noised Data")
plt.plot(x, func(x, *popt), 'r-', label="Fitted Curve")
plt.legend()
plt.show()

(Note: the * in front of popt when you plot will expand out the terms into the a, b, and c that func is expecting.)

Radio Buttons "Checked" Attribute Not Working

You're using non-standard xhtml code (values should be framed with double quotes, not single quotes)

Try this:

<form>
  <label>Do you want to accept American Express?</label>
  Yes<input id="amex" style="width: 20px;" type="radio" name="Contact0_AmericanExpress"  />  
  No<input style="width: 20px;" type="radio" name="Contact0_AmericanExpress" class="check" checked="checked" />
</form>

How to debug a stored procedure in Toad?

Open a PL/SQL object in the Editor.

Click on the main toolbar or select Session | Toggle Compiling with Debug. This enables debugging.

Compile the object on the database.

Select one of the following options on the Execute toolbar to begin debugging: Execute PL/SQL with debugger () Step over Step into Run to cursor

How to overwrite styling in Twitter Bootstrap

I know this is an old question but still, I came across a similar problem and i realized that my "not working" css code in my bootstrapOverload.css file was written after the media queries. when I moved it above media queries it started working.

Just in case someone else is facing the same problem

Disable developer mode extensions pop up in Chrome

The official way to disable the popup is this:

  1. Pack your extension: go to chrome://extensions, check Developer mode and click Pack extension

  2. Install the extension by dragging and dropping the .crx file into the chrome://extensions page.

You'll get an "Unsupported extensions disabled" popup if you try restarting Chrome at this point.

Then for Windows 7 or Windows 8:

  1. Download Chrome group policy templates here
  2. Copy [zip]\windows\admx\chrome.admx to c:\windows\policydefinitions
  3. Copy [zip]\windows\admx\[yourlanguage]\chrome.adml to c:\windows\policydefinitions\[yourlanguage]\chrome.adml (not c:\windows\[yourlanguage])
  4. In Chrome, go to the Extensions page: chrome://extensions
  5. Check Developer Mode
  6. Scroll down the list of disabled extensions and note the ID(s) of the extensions you want to enable.
  7. Click Start > Run, type gpedit.msc and hit enter.
  8. Click User Configuration > Administrative Templates > Google Chrome > Extensions
  9. Double click Configure extension installation whitelist policy
  10. Select Enabled, and click Show
  11. In the list, enter the ID(s) of the extensions you noted in Step 7
  12. Click OK and restart Chrome.

That's it!

EDIT: As of July 2018, this approach no longer works: it seems Google has stopped honouring the "whitelist".

EDIT 2: As of December 2018, this approach works in Chrome Version 69.0.3497.100 (Official Build) (64-bit):

  1. Temporarily enable Developer mode in chrome://extensions

  2. Uninstall the extension that causes the popup using the Load unpacked.

  3. Click on Pack extension, and find and select the folder containing the extension files. Don't enter the private key file if you don't have it.

  4. Click Pack extension. A .crx and .pem file will be created near the root directory of the extension. Install the extension using the .crx file and keep the .pem file safe.

  5. Copy the .crx installed extension ID to the whitelist and restart Chrome.

The popup should be gone.

Add CSS box shadow around the whole DIV

Just use the below code. It will shadow surround the entire DIV

-webkit-box-shadow: -1px 1px 5px 9px rgba(0,0,0,0.75);
-moz-box-shadow: -1px 1px 5px 9px rgba(0,0,0,0.75);
box-shadow: -1px 1px 5px 9px rgba(0,0,0,0.75);

Hope this will work

C++: Print out enum value as text

There has been a discussion here which might help: Is there a simple way to convert C++ enum to string?

UPDATE: Here#s a script for Lua which creates an operator<< for each named enum it encounters. This might need some work to make it work for the less simple cases [1]:

function make_enum_printers(s)
    for n,body in string.gmatch(s,'enum%s+([%w_]+)%s*(%b{})') do
    print('ostream& operator<<(ostream &o,'..n..' n) { switch(n){') 
    for k in string.gmatch(body,"([%w_]+)[^,]*") do
    print('  case '..k..': return o<<"'..k..'";')
    end
    print('  default: return o<<"(invalid value)"; }}')
    end
end

local f=io.open(arg[1],"r")
local s=f:read('*a')
make_enum_printers(s)

Given this input:

enum Errors
{ErrorA=0, ErrorB, ErrorC};

enum Sec {
    X=1,Y=X,foo_bar=X+1,Z
};

It produces:

ostream& operator<<(ostream &o,Errors n) { switch(n){
  case ErrorA: return o<<"ErrorA";
  case ErrorB: return o<<"ErrorB";
  case ErrorC: return o<<"ErrorC";
  default: return o<<"(invalid value)"; }}
ostream& operator<<(ostream &o,Sec n) { switch(n){
  case X: return o<<"X";
  case Y: return o<<"Y";
  case foo_bar: return o<<"foo_bar";
  case Z: return o<<"Z";
  default: return o<<"(invalid value)"; }}

So that's probably a start for you.

[1] enums in different or non-namespace scopes, enums with initializer expressions which contain a komma, etc.

What's the syntax for mod in java

Since everyone else already gave the answer, I'll add a bit of additional context. % the "modulus" operator is actually performing the remainder operation. The difference between mod and rem is subtle, but important.

(-1 mod 2) would normally give 1. More specifically given two integers, X and Y, the operation (X mod Y) tends to return a value in the range [0, Y). Said differently, the modulus of X and Y is always greater than or equal to zero, and less than Y.

Performing the same operation with the "%" or rem operator maintains the sign of the X value. If X is negative you get a result in the range (-Y, 0]. If X is positive you get a result in the range [0, Y).

Often this subtle distinction doesn't matter. Going back to your code question, though, there are multiple ways of solving for "evenness".

The first approach is good for beginners, because it is especially verbose.

// Option 1: Clearest way for beginners
boolean isEven;
if ((a % 2) == 0)
{
  isEven = true
}
else
{
  isEven = false
}

The second approach takes better advantage of the language, and leads to more succinct code. (Don't forget that the == operator returns a boolean.)

// Option 2: Clear, succinct, code
boolean isEven = ((a % 2) == 0);

The third approach is here for completeness, and uses the ternary operator. Although the ternary operator is often very useful, in this case I consider the second approach superior.

// Option 3: Ternary operator
boolean isEven = ((a % 2) == 0) ? true : false;

The fourth and final approach is to use knowledge of the binary representation of integers. If the least significant bit is 0 then the number is even. This can be checked using the bitwise-and operator (&). While this approach is the fastest (you are doing simple bit masking instead of division), it is perhaps a little advanced/complicated for a beginner.

// Option 4: Bitwise-and
boolean isEven = ((a & 1) == 0);

Here I used the bitwise-and operator, and represented it in the succinct form shown in option 2. Rewriting it in Option 1's form (and alternatively Option 3's) is left as an exercise to the reader. ;)

Hope that helps.

Bind a function to Twitter Bootstrap Modal Close

Bootstrap 4

$('#my-modal').on('hidden.bs.modal', function () {
  window.alert('hidden event fired!');
});

See this JSFiddle for a working example:

https://jsfiddle.net/6n7bg2c9/

See the Modal Events section of the docs here:

https://getbootstrap.com/docs/4.3/components/modal/#events

PHP Constants Containing Arrays?

If you are using PHP 5.6 or above, use Andrea Faulds answer

I am using it like this. I hope, it will help others.

config.php

class app{
    private static $options = array(
        'app_id' => 'hello',
    );
    public static function config($key){
        return self::$options[$key];
    }
}

In file, where I need constants.

require('config.php');
print_r(app::config('app_id'));

Redirecting to another page in ASP.NET MVC using JavaScript/jQuery

You are not subscribing to any success callback in your $.post AJAX call. Meaning that the request is executed, but you do nothing with the results. If you want to do something useful with the results, try:

$.post('/Branch/Details/' + id, function(result) {
    // Do something with the result like for example inject it into
    // some placeholder and update the DOM.
    // This obviously assumes that your controller action returns
    // a partial view otherwise you will break your markup
});

On the other hand if you want to redirect, you absolutely do not need AJAX. You use AJAX only when you want to stay on the same page and update only a portion of it.

So if you only wanted to redirect the browser:

function foo(id) {
    window.location.href = '/Branch/Details/' + id;
}

As a side note: You should never be hardcoding urls like this. You should always be using url helpers when dealing with urls in an ASP.NET MVC application. So:

function foo(id) {
    var url = '@Url.Action("Details", "Branch", new { id = "__id__" })';
    window.location.href = url.replace('__id__', id);
}

Is this the proper way to do boolean test in SQL?

MS SQL 2008 can also use the string version of true or false...

select * from users where active = 'true'
-- or --
select * from users where active = 'false'

How to pass boolean values to a PowerShell script from a command prompt

Try setting the type of your parameter to [bool]:

param
(
    [int]$Turn = 0
    [bool]$Unity = $false
)

switch ($Unity)
{
    $true { "That was true."; break }
    default { "Whatever it was, it wasn't true."; break }
}

This example defaults $Unity to $false if no input is provided.

Usage

.\RunScript.ps1 -Turn 1 -Unity $false

How to put an image in div with CSS?

Take this as a sample code. Replace imageheight and image width with your image dimensions.

<div style="background:yourimage.jpg no-repeat;height:imageheight px;width:imagewidth px">
</div>

How to move columns in a MySQL table?

If empName is a VARCHAR(50) column:

ALTER TABLE Employees MODIFY COLUMN empName VARCHAR(50) AFTER department;

EDIT

Per the comments, you can also do this:

ALTER TABLE Employees CHANGE COLUMN empName empName VARCHAR(50) AFTER department;

Note that the repetition of empName is deliberate. You have to tell MySQL that you want to keep the same column name.

You should be aware that both syntax versions are specific to MySQL. They won't work, for example, in PostgreSQL or many other DBMSs.

Another edit: As pointed out by @Luis Rossi in a comment, you need to completely specify the altered column definition just before the AFTER modifier. The above examples just have VARCHAR(50), but if you need other characteristics (such as NOT NULL or a default value) you need to include those as well. Consult the docs on ALTER TABLE for more info.

cannot open shared object file: No such file or directory

sudo ldconfig

ldconfig creates the necessary links and cache to the most recent shared libraries found in the directories specified on the command line, in the file /etc/ld.so.conf, and in the trusted directories (/lib and /usr/lib).

Generally package manager takes care of this while installing the new library, but not always (specially when you install library with cmake).

And if the output of this is empty

$ echo $LD_LIBRARY_PATH

Please set the default path

$ LD_LIBRARY_PATH=/usr/local/lib

How do I check if a property exists on a dynamic anonymous type in c#?

public static bool HasProperty(dynamic obj, string name)
{
    Type objType = obj.GetType();

    if (objType == typeof(ExpandoObject))
    {
        return ((IDictionary<string, object>)obj).ContainsKey(name);
    }

    return objType.GetProperty(name) != null;
}

Unsupported Media Type in postman

Http 415 Media Unsupported is responded back only when the content type header you are providing is not supported by the application.

With POSTMAN, the Content-type header you are sending is Content type 'multipart/form-data not application/json. While in the ajax code you are setting it correctly to application/json. Pass the correct Content-type header in POSTMAN and it will work.

How to remove the underline for anchors(links)?

I've been troubled with this problem in web printing and solved. Verified result.

a {
    text-decoration: none !important;
}

It works!.

How to create and handle composite primary key in JPA

The MyKey class must implement Serializable if you are using @IdClass

Animation CSS3: display + opacity

If possible - use visibility instead of display

For instance:

.child {
    visibility: hidden;
    opacity: 0;
    transition: opacity 0.3s, visibility 0.3s;
}

.parent:hover .child {
    visibility: visible;
    opacity: 1;
    transition: opacity 0.3s, visibility 0.3s;
}

Foreach with JSONArray and JSONObject

Apparently, org.json.simple.JSONArray implements a raw Iterator. This means that each element is considered to be an Object. You can try to cast:

for(Object o: arr){
    if ( o instanceof JSONObject ) {
        parse((JSONObject)o);
    }
}

This is how things were done back in Java 1.4 and earlier.

How to reset or change the passphrase for a GitHub SSH key?

If you had generate a SSH-key with passphrase and then you forget your passphrase for this SSH-key,there's no way to recover it, You'll need to generate a brand new SSH keypair or switch to HTTPS cloning so you can use your GitHub password instead.

BUT,there are exceptions

If you configured your SSH passphrase with the OS X Keychain, you may be able to recover it.

  1. In Finder, search for the Keychain Access app.
  2. In Keychain Access, search for SSH.
  3. Double click on the entry for your SSH key to open a new dialog box.
  4. Keychain access dialogIn the lower-left corner, select Show password.
  5. You'll be prompted for your administrative password. Type it into the "Keychain Access" dialog box.
  6. Your password will be revealed.

Refer to Github help - How do I recover my SSH key passphrase?

angularjs - using {{}} binding inside ng-src but ng-src doesn't load

Changing the ng-src value is actually very simple. Like this:

<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
</head>
<body>
<img ng-src="{{img_url}}">
<button ng-click="img_url = 'https://farm4.staticflickr.com/3261/2801924702_ffbdeda927_d.jpg'">Click</button>
</body>
</html>

Here is a jsFiddle of a working example: http://jsfiddle.net/Hx7B9/2/

Measuring the distance between two coordinates in PHP

For exact values do it like that:

public function DistAB()
{
      $delta_lat = $this->lat_b - $this->lat_a ;
      $delta_lon = $this->lon_b - $this->lon_a ;

      $a = pow(sin($delta_lat/2), 2);
      $a += cos(deg2rad($this->lat_a9)) * cos(deg2rad($this->lat_b9)) * pow(sin(deg2rad($delta_lon/29)), 2);
      $c = 2 * atan2(sqrt($a), sqrt(1-$a));

      $distance = 2 * $earth_radius * $c;
      $distance = round($distance, 4);

      $this->measure = $distance;
}

Hmm I think that should do it...

Edit:

For formulars and at least JS-implementations try: http://www.movable-type.co.uk/scripts/latlong.html

Dare me... I forgot to deg2rad all the values in the circle-functions...

T-SQL: Selecting rows to delete via joins

DELETE FROM table1
where id IN 
    (SELECT id FROM table2..INNER JOIN..INNER JOIN WHERE etc)

Minimize use of DML queries with Joins. You should be able to do most of all DML queries with subqueries like above.

In general, joins should only be used when you need to SELECT or GROUP by columns in 2 or more tables. If you're only touching multiple tables to define a population, use subqueries. For DELETE queries, use correlated subquery.

"Missing return statement" within if / for / while

That's because the function needs to return a value. Imagine what happens if you execute myMethod() and it doesn't go into if(condition) what would your function returns? The compiler needs to know what to return in every possible execution of your function

Checking Java documentation:

Definition: If a method declaration has a return type then there must be a return statement at the end of the method. If the return statement is not there the missing return statement error is thrown.

This error is also thrown if the method does not have a return type and has not been declared using void (i.e., it was mistakenly omitted).

You can do to solve your problem:

public String myMethod()
{
    String result = null;
    if(condition)
    {
       result = x;
    }
    return result;
}

Check if textbox has empty value

if ( $("#txt").val().length == 0 )
{
  // do something
}

I had to add in the == to get it to work for me, otherwise it ignored the condition even with empty text input. May help someone.

JFrame.dispose() vs System.exit()

System.exit(); causes the Java VM to terminate completely.

JFrame.dispose(); causes the JFrame window to be destroyed and cleaned up by the operating system. According to the documentation, this can cause the Java VM to terminate if there are no other Windows available, but this should really just be seen as a side effect rather than the norm.

The one you choose really depends on your situation. If you want to terminate everything in the current Java VM, you should use System.exit() and everything will be cleaned up. If you only want to destroy the current window, with the side effect that it will close the Java VM if this is the only window, then use JFrame.dispose().

jQuery UI Alert Dialog as a replacement for alert()

There is an issue that if you close the dialog it will execute the onCloseCallback function. This is a better design.

function jAlert2(outputMsg, titleMsg, onCloseCallback) {
    if (!titleMsg)
        titleMsg = 'Alert';

    if (!outputMsg)
        outputMsg = 'No Message to Display.';

    $("<div></div>").html(outputMsg).dialog({
        title: titleMsg,
        resizable: false,
        modal: true,
        buttons: {
            "OK": onCloseCallback,
            "Cancel": function() {
          $( this ).dialog( "destroy" );
            }

        },
    });

Double decimal formatting in Java

You could always use the static method printf from System.out - you'd then implement the corresponding formatter; this saves heap space in which other examples required you to do.

Ex:

System.out.format("%.4f %n", 4.0); 

System.out.printf("%.2f %n", 4.0); 

Saves heap space which is a pretty big bonus, nonetheless I hold the opinion that this example is much more manageable than any other answer, especially since most programmers know the printf function from C (Java changes the function/method slightly though).

twig: IF with multiple conditions

If I recall correctly Twig doesn't support || and && operators, but requires or and and to be used respectively. I'd also use parentheses to denote the two statements more clearly although this isn't technically a requirement.

{%if ( fields | length > 0 ) or ( trans_fields | length > 0 ) %}

Expressions

Expressions can be used in {% blocks %} and ${ expressions }.

Operator    Description
==          Does the left expression equal the right expression?
+           Convert both arguments into a number and add them.
-           Convert both arguments into a number and substract them.
*           Convert both arguments into a number and multiply them.
/           Convert both arguments into a number and divide them.
%           Convert both arguments into a number and calculate the rest of the integer division.
~           Convert both arguments into a string and concatenate them.
or          True if the left or the right expression is true.
and         True if the left and the right expression is true.
not         Negate the expression.

For more complex operations, it may be best to wrap individual expressions in parentheses to avoid confusion:

{% if (foo and bar) or (fizz and (foo + bar == 3)) %}

Check OS version in Swift?

Swift 5

func run() {
    let version = OperatingSystemVersion(majorVersion: 13, minorVersion: 0, patchVersion: 0)
    if ProcessInfo.processInfo.isOperatingSystemAtLeast(version) {
        runNewCode()
    } else {
        runLegacyCode()
    }
}

func runNewCode() {
    guard #available(iOS 13.0, *) else {
        fatalError()
    }
    // do new stuff
}

func runLegacyCode() {
    // do old stuff
}