Programs & Examples On #Unary operator

How do I install a NuGet package .nupkg file locally?

For Visual Studio 2017 and its new .csproj format

You can no longer just use Install-Package to point to a local file. (That's likely because the PackageReference element doesn't support file paths; it only allows you to specify the package's Id.)

You first have to tell Visual Studio about the location of your package, and then you can add it to a project. What most people do is go into the NuGet Package Manager and add the local folder as a source (menu Tools ? Options ? NuGet Package Manager ? Package Sources). But that means your dependency's location isn't committed (to version-control) with the rest of your codebase.

Local NuGet packages using a relative path

This will add a package source that only applies to a specific solution, and you can use relative paths.

You need to create a nuget.config file in the same directory as your .sln file. Configure the file with the package source(s) you want. When you next open the solution in Visual Studio 2017, any .nupkg files from those source folders will be available. (You'll see the source(s) listed in the Package Manager, and you'll find the packages on the "Browse" tab when you're managing packages for a project.)

Here's an example nuget.config to get you started:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <packageSources>
        <add key="MyLocalSharedSource" value="..\..\..\some\folder" />
    </packageSources>
</configuration>

Backstory

My use case for this functionality is that I have multiple instances of a single code repository on my machine. There's a shared library within the codebase that's published/deployed as a .nupkg file. This approach allows the various dependent solutions throughout our codebase to use the package within the same repository instance. Also, someone with a fresh install of Visual Studio 2017 can just checkout the code wherever they want, and the dependent solutions will successfully restore and build.

Property 'value' does not exist on type 'EventTarget'

Here is one more way to specify event.target:

_x000D_
_x000D_
import { Component, EventEmitter, Output } from '@angular/core';_x000D_
_x000D_
@Component({_x000D_
    selector: 'text-editor',_x000D_
    template: `<textarea (keyup)="emitWordCount($event)"></textarea>`_x000D_
})_x000D_
export class TextEditorComponent {_x000D_
_x000D_
   @Output() countUpdate = new EventEmitter<number>();_x000D_
_x000D_
    emitWordCount({ target = {} as HTMLTextAreaElement }) { // <- right there_x000D_
_x000D_
        this.countUpdate.emit(_x000D_
          // using it directly without `event`_x000D_
            (target.value.match(/\S+/g) || []).length);_x000D_
    }_x000D_
}
_x000D_
_x000D_
_x000D_

Count number of files within a directory in Linux?

this is one:

ls -l . | egrep -c '^-'

Note:

ls -1 | wc -l

Which means: ls: list files in dir

-1: (that's a ONE) only one entry per line. Change it to -1a if you want hidden files too

|: pipe output onto...

wc: "wordcount"

-l: count lines.

What does 'URI has an authority component' mean?

After trying a skeleton project called "jsf-blank", which did not demonstrate this problem with xhtml files; I concluded that there was an unknown problem in my project. My solution may not have been too elegant, but it saved time. I backed up the code and other files I'd already developed, deleted the project, and started over - recreated the project. So far, I've added back most of the files and it looks pretty good.

Windows recursive grep command-line

for /f %G in ('dir *.cpp *.h /s/b') do  ( find /i "what you search"  "%G") >> out_file.txt

Java how to sort a Linked List?

Here is the example to sort implemented linked list in java without using any standard java libraries.

package SelFrDemo;

class NodeeSort {
    Object value;
    NodeeSort next;

    NodeeSort(Object val) {
        value = val;
        next = null;

    }

    public Object getValue() {
        return value;
    }

    public void setValue(Object value) {
        this.value = value;
    }

    public NodeeSort getNext() {
        return next;
    }

    public void setNext(NodeeSort next) {
        this.next = next;
    }

}

public class SortLinkList {
    NodeeSort head;
    int size = 0;

    NodeeSort add(Object val) {
        // TODO Auto-generated method stub
        if (head == null) {
            NodeeSort nodee = new NodeeSort(val);
            head = nodee;
            size++;
            return head;
        }
        NodeeSort temp = head;

        while (temp.next != null) {
            temp = temp.next;
        }

        NodeeSort newNode = new NodeeSort(val);
        temp.setNext(newNode);
        newNode.setNext(null);
        size++;
        return head;
    }

    NodeeSort sort(NodeeSort nodeSort) {

        for (int i = size - 1; i >= 1; i--) {
            NodeeSort finalval = nodeSort;
            NodeeSort tempNode = nodeSort;

            for (int j = 0; j < i; j++) {

                int val1 = (int) nodeSort.value;
                NodeeSort nextnode = nodeSort.next;
                int val2 = (int) nextnode.value;
                if (val1 > val2) {

                    if (nodeSort.next.next != null) {
                        NodeeSort CurrentNext = nodeSort.next.next;
                        nextnode.next = nodeSort;
                        nextnode.next.next = CurrentNext;
                        if (j == 0) {
                            finalval = nextnode;
                        } else
                            nodeSort = nextnode;

                        for (int l = 1; l < j; l++) {
                            tempNode = tempNode.next;
                        }

                        if (j != 0) {
                            tempNode.next = nextnode;

                            nodeSort = tempNode;
                        }
                    } else if (nodeSort.next.next == null) {
                        nextnode.next = nodeSort;
                        nextnode.next.next = null;
                        for (int l = 1; l < j; l++) {
                            tempNode = tempNode.next;
                        }
                        tempNode.next = nextnode;
                        nextnode = tempNode;
                        nodeSort = tempNode;

                    }

                } else
                    nodeSort = tempNode;
                nodeSort = finalval;
                tempNode = nodeSort;
                for (int k = 0; k <= j && j < i - 1; k++) {
                    nodeSort = nodeSort.next;
                }

            }

        }
        return nodeSort;

    }

    public static void main(String[] args) {
        SortLinkList objsort = new SortLinkList();
        NodeeSort nl1 = objsort.add(9);
        NodeeSort nl2 = objsort.add(71);
        NodeeSort nl3 = objsort.add(6);
        NodeeSort nl4 = objsort.add(81);
        NodeeSort nl5 = objsort.add(2);

        NodeeSort NodeSort = nl5;

        NodeeSort finalsort = objsort.sort(NodeSort);
        while (finalsort != null) {
            System.out.println(finalsort.getValue());
            finalsort = finalsort.getNext();
        }

    }
}

Xpath for href element

Try below locator.

selenium.click("css=a[href*='listDetails.do'][id='oldcontent']");

or

selenium.click("xpath=//a[contains(@href,'listDetails.do') and @id='oldcontent']");

How to merge two PDF files into one in Java?

Using iText (existing PDF in bytes)

    public static byte[] mergePDF(List<byte[]> pdfFilesAsByteArray) throws DocumentException, IOException {

    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    Document document = null;
    PdfCopy writer = null;

    for (byte[] pdfByteArray : pdfFilesAsByteArray) {

        try {
            PdfReader reader = new PdfReader(pdfByteArray);
            int numberOfPages = reader.getNumberOfPages();

            if (document == null) {
                document = new Document(reader.getPageSizeWithRotation(1));
                writer = new PdfCopy(document, outStream); // new
                document.open();
            }
            PdfImportedPage page;
            for (int i = 0; i < numberOfPages;) {
                ++i;
                page = writer.getImportedPage(reader, i);
                writer.addPage(page);
            }
        }

        catch (Exception e) {
            e.printStackTrace();
        }

    }

    document.close();
    outStream.close();
    return outStream.toByteArray();

}

find difference between two text files with one item per line

A tried a slight variation on Luca's answer and it worked for me.

diff file1 file2 | grep ">" | sed 's/^> //g' > diff_file

Note that the searched pattern in sed is a > followed by a space.

How to reset postgres' primary key sequence when it falls out of sync?

Reset all sequences, no assumptions about names except that the primary key of each table is "id":

CREATE OR REPLACE FUNCTION "reset_sequence" (tablename text, columnname text)
RETURNS "pg_catalog"."void" AS
$body$
DECLARE
BEGIN
    EXECUTE 'SELECT setval( pg_get_serial_sequence(''' || tablename || ''', ''' || columnname || '''),
    (SELECT COALESCE(MAX(id)+1,1) FROM ' || tablename || '), false)';
END;
$body$  LANGUAGE 'plpgsql';

select table_name || '_' || column_name || '_seq', reset_sequence(table_name, column_name) from information_schema.columns where column_default like 'nextval%';

Swift 3: Display Image from URL

let url = URL(string: "http://i.imgur.com/w5rkSIj.jpg")
let data = try? Data(contentsOf: url)

if let imageData = data {
    let image = UIImage(data: imageData)
}

CSS/HTML: What is the correct way to make text italic?

I'd say use <em> to emphasize inline elements. Use a class for block elements like blocks of text. CSS or not, the text still has to be tagged. Whether its for semantics or for visual aid, I'm assuming you'd be using it for something meaningful...

If you're emphasizing text for ANY reason, you could use <em>, or a class that italicizes your text.

It's OK to break the rules sometimes!

FontAwesome icons not showing. Why?

For version 5:

If you downloaded the free package from this site:

https://fontawesome.com/download

The fonts are in the all.css and all.min.css file.

So your reference will look something like this:

<link href="/MyProject/Content/fontawesome-free-5.10.1-web/css/all.min.css" rel="stylesheet">

The fontawesome.css file does not include the font reference.

mingw-w64 threads: posix vs win32

GCC comes with a compiler runtime library (libgcc) which it uses for (among other things) providing a low-level OS abstraction for multithreading related functionality in the languages it supports. The most relevant example is libstdc++'s C++11 <thread>, <mutex>, and <future>, which do not have a complete implementation when GCC is built with its internal Win32 threading model. MinGW-w64 provides a winpthreads (a pthreads implementation on top of the Win32 multithreading API) which GCC can then link in to enable all the fancy features.

I must stress this option does not forbid you to write any code you want (it has absolutely NO influence on what API you can call in your code). It only reflects what GCC's runtime libraries (libgcc/libstdc++/...) use for their functionality. The caveat quoted by @James has nothing to do with GCC's internal threading model, but rather with Microsoft's CRT implementation.

To summarize:

  • posix: enable C++11/C11 multithreading features. Makes libgcc depend on libwinpthreads, so that even if you don't directly call pthreads API, you'll be distributing the winpthreads DLL. There's nothing wrong with distributing one more DLL with your application.
  • win32: No C++11 multithreading features.

Neither have influence on any user code calling Win32 APIs or pthreads APIs. You can always use both.

ASP.NET: HTTP Error 500.19 – Internal Server Error 0x8007000d

In my case, because I had reinstalled iis, I needed to register iis with dot net 4 using this command:

C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -i

Xampp-mysql - "Table doesn't exist in engine" #1932

If you have copied & Pasted files from an old backup folder to new then its simple. Just copy the old ibdata1 into your new one. You can find it from \xampp\mysql\data

Magento How to debug blank white screen

I was also facing this error. The error has been fixed by changing content of core function getRowUrl in app\code\core\Mage\Adminhtml\Block\Widget\Grid.php The core function is :

public function getRowUrl($item) 
{ 
$res = parent::getRowUrl($item); 
return ($res ? $res : ‘#’); 
}

Replaced with :

public function getRowUrl($item) 
{ 
return $this->getUrl(’*/*/edit’, array(’id’ => $item->getId())); 
}

For more detail : http://bit.ly/iTKcer

Enjoy!!!!!!!!!!!!!

How to manually include external aar package using new Gradle Android Build System

before(default)

implementation fileTree(include: ['*.jar'], dir: 'libs')

just add '*.aar' in include array.

implementation fileTree(include: ['*.jar', '*.aar'], dir: 'libs')

it works well on Android Studio 3.x.

if you want ignore some library? do like this.

implementation fileTree(include: ['*.jar', '*.aar'], exclude: 'test_aar*', dir: 'libs')
debugImplementation files('libs/test_aar-debug.aar')
releaseImplementation files('libs/test_aar-release.aar')

Wait until boolean value changes it state

Ok maybe this one should solve your problem. Note that each time you make a change you call the change() method that releases the wait.

Integer any = new Integer(0);

public synchronized boolean waitTillChange() {
    any.wait();
    return true;
}

public synchronized void change() {
    any.notify();
}

input type="submit" Vs button tag are they interchangeable?

Use <button> tag instead of <input type="button"..>. It is the advised practice in bootstrap 3.

http://getbootstrap.com/css/#buttons-tags

"Cross-browser rendering

As a best practice, we highly recommend using the <button> element whenever possible to ensure matching cross-browser rendering.

Among other things, there's a Firefox bug that prevents us from setting the line-height of <input>-based buttons, causing them to not exactly match the height of other buttons on Firefox."

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 7: ordinal not in range(128)

You need to encode Unicode explicitly before writing to a file, otherwise Python does it for you with the default ASCII codec.

Pick an encoding and stick with it:

f.write(printinfo.encode('utf8') + '\n')

or use io.open() to create a file object that'll encode for you as you write to the file:

import io

f = io.open(filename, 'w', encoding='utf8')

You may want to read:

before continuing.

How does HTTP file upload work?

I have this sample Java Code:

import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;

public class TestClass {
    public static void main(String[] args) throws IOException {
        ServerSocket socket = new ServerSocket(8081);
        Socket accept = socket.accept();
        InputStream inputStream = accept.getInputStream();

        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
        char readChar;
        while ((readChar = (char) inputStreamReader.read()) != -1) {
            System.out.print(readChar);
        }

        inputStream.close();
        accept.close();
        System.exit(1);
    }
}

and I have this test.html file:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>File Upload!</title>
</head>
<body>
<form method="post" action="http://localhost:8081" enctype="multipart/form-data">
    <input type="file" name="file" id="file">
    <input type="submit">
</form>
</body>
</html>

and finally the file I will be using for testing purposes, named a.dat has the following content:

0x39 0x69 0x65

if you interpret the bytes above as ASCII or UTF-8 characters, they will actually will be representing:

9ie

So let 's run our Java Code, open up test.html in our favorite browser, upload a.dat and submit the form and see what our server receives:

POST / HTTP/1.1
Host: localhost:8081
Connection: keep-alive
Content-Length: 196
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Origin: null
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.97 Safari/537.36
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary06f6g54NVbSieT6y
DNT: 1
Accept-Encoding: gzip, deflate
Accept-Language: en,en-US;q=0.8,tr;q=0.6
Cookie: JSESSIONID=27D0A0637A0449CF65B3CB20F40048AF

------WebKitFormBoundary06f6g54NVbSieT6y
Content-Disposition: form-data; name="file"; filename="a.dat"
Content-Type: application/octet-stream

9ie
------WebKitFormBoundary06f6g54NVbSieT6y--

Well I am not surprised to see the characters 9ie because we told Java to print them treating them as UTF-8 characters. You may as well choose to read them as raw bytes..

Cookie: JSESSIONID=27D0A0637A0449CF65B3CB20F40048AF 

is actually the last HTTP Header here. After that comes the HTTP Body, where meta and contents of the file we uploaded actually can be seen.

Convert between UIImage and Base64 string

Swift 5, Xcode 10.

_x000D_
_x000D_
 let imageData = UIImage(named:"imagename").pngData()?.base64EncodedString(options: .lineLength64Characters)_x000D_
_x000D_
print(imageData)
_x000D_
_x000D_
_x000D_

How do I create and store md5 passwords in mysql

you have to reason in terms of hased password:

store the password as md5('bob123'); when bob is register to your app

$query = "INSERT INTO users (username,password) VALUES('bob','".md5('bob123')."');

then, when bob is logging-in:

$query = "SELECT * FROM users WHERE username = 'bob' AND password = '".md5('bob123')."';

obvioulsy use variables for username and password, these queries are generated by php and then you can execute them on mysql

Best approach to real time http streaming to HTML5 video client

Take a look at this solution. As I know, Flashphoner allows to play Live audio+video stream in the pure HTML5 page.

They use MPEG1 and G.711 codecs for playback. The hack is rendering decoded video to HTML5 canvas element and playing decoded audio via HTML5 audio context.

What does ^M character mean in Vim?

If you didn't specify a different fileformat intentionally (say, :e ++ff=unix for a Windows file), it's likely that the target file has mixed EOLs.

For example, if a file has some lines with <CR><NL> endings and others with <NL> endings, and fileformat is set to unix automatically by Vim when reading it, ^M (<CR>) will appear. In such cases, fileformats (note: there's an extra s) comes into play. See :help ffs for the details.

How to cin Space in c++?

I have the same problem and I just used cin.getline(input,300);.

noskipws and cin.get() sometimes are not easy to use. Since you have the right size of your array try using cin.getline() which does not care about any character and read the whole line in specified character count.

No restricted globals

For me I had issues with history and location... As the accepted answer using window before history and location (i.e) window.history and window.location solved mine

How to compile Go program consisting of multiple files?

You could also just run

go build

in your project folder myproject/go/src/myprog

Then you can just type

./myprog

to run your app

UILabel with text of two different colors

Swift 4 and above: Inspired by anoop4real's solution, here's a String extension that can be used to generate text with 2 different colors.

extension String {

    func attributedStringForPartiallyColoredText(_ textToFind: String, with color: UIColor) -> NSMutableAttributedString {
        let mutableAttributedstring = NSMutableAttributedString(string: self)
        let range = mutableAttributedstring.mutableString.range(of: textToFind, options: .caseInsensitive)
        if range.location != NSNotFound {
            mutableAttributedstring.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: range)
        }
        return mutableAttributedstring
    }
}

Following example changes color of asterisk to red while retaining original label color for remaining text.

label.attributedText = "Enter username *".attributedStringForPartiallyColoredText("*", with: #colorLiteral(red: 1, green: 0, blue: 0, alpha: 1))

Convert output of MySQL query to utf8

Addition:

When using the MySQL client library, then you should prevent a conversion back to your connection's default charset. (see mysql_set_character_set()[1])

In this case, use an additional cast to binary:

SELECT column1, CAST(CONVERT(column2 USING utf8) AS binary)
FROM my_table
WHERE my_condition;

Otherwise, the SELECT statement converts to utf-8, but your client library converts it back to a (potentially different) default connection charset.

Formatting "yesterday's" date in python

This should do what you want:

import datetime
yesterday = datetime.datetime.now() - datetime.timedelta(days = 1)
print yesterday.strftime("%m%d%y")

Tower of Hanoi: Recursive Algorithm

The answer for the question, how does the program know, that even is "src" to "aux", and odd is "src" to "dst" for the opening move lies in the program. If you break down fist move with 4 discs, then this looks like this:

hanoi(4, "src", "aux", "dst");
if (disc > 0) {
    hanoi(3, 'src', 'dst', 'aux');
        if (disc > 0) {
            hanoi(2, 'src', 'aux', 'dst');
                if (disc > 0) {
                    hanoi(1, 'src', 'dst', 'aux');
                        if (disc > 0) {
                            hanoi(0, 'src', 'aux', 'dst');
                                END
                        document.writeln("Move disc" + 1 + "from" + Src + "to" + Aux);
                        hanoi(0, 'aux', 'src', 'dst');
                                END
                        }

also the first move with 4 disc(even) goes from Src to Aux.

Writing html form data to a txt file without the use of a webserver

I know this is old, but it's the first example of saving form data to a txt file I found in a quick search. So I've made a couple edits to the above code that makes it work more smoothly. It's now easier to add more fields, including the radio button as @user6573234 requested.

https://jsfiddle.net/cgeiser/m0j7Lwyt/1/

<!DOCTYPE html>
<html>
<head>
<style>
form * {
  display: block;
  margin: 10px;
}
</style>
<script language="Javascript" >
function download() {
  var filename = window.document.myform.docname.value;
  var name =  window.document.myform.name.value;
  var text =  window.document.myform.text.value;
  var problem =  window.document.myform.problem.value;
  
  var pom = document.createElement('a');
  pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + 
    "Your Name: " + encodeURIComponent(name) + "\n\n" +
    "Problem: " + encodeURIComponent(problem) + "\n\n" +
    encodeURIComponent(text)); 

  pom.setAttribute('download', filename);

  pom.style.display = 'none';
  document.body.appendChild(pom);

  pom.click();

  document.body.removeChild(pom);
}
</script>
</head>
<body>
<form name="myform" method="post" >
  <input type="text" id="docname" value="test.txt" />
  <input type="text" id="name" placeholder="Your Name" />
  <div style="display:unblock">
    Option 1 <input type="radio" value="Option 1" onclick="getElementById('problem').value=this.value; getElementById('problem').show()" style="display:inline" />
    Option 2 <input type="radio" value="Option 2" onclick="getElementById('problem').value=this.value;" style="display:inline" />
    <input type="text" id="problem" />
  </div>
  <textarea rows=3 cols=50 id="text" />Please type in this box. 
When you click the Download button, the contents of this box will be downloaded to your machine at the location you specify. Pretty nifty. </textarea>
  
  <input id="download_btn" type="submit" class="btn" style="width: 125px" onClick="download();" />
  
</form>
</body>
</html>

TypeError("'bool' object is not iterable",) when trying to return a Boolean

Look at the traceback:

Traceback (most recent call last):
  File "C:\Python33\lib\site-packages\bottle.py", line 821, in _cast
    out = iter(out)
TypeError: 'bool' object is not iterable

Your code isn't iterating the value, but the code receiving it is.

The solution is: return an iterable. I suggest that you either convert the bool to a string (str(False)) or enclose it in a tuple ((False,)).

Always read the traceback: it's correct, and it's helpful.

MySQL Results as comma separated list

In my case i have to concatenate all the account number of a person who's mobile number is unique. So i have used the following query to achieve that.

SELECT GROUP_CONCAT(AccountsNo) as Accounts FROM `tblaccounts` GROUP BY MobileNumber

Query Result is below:

Accounts
93348001,97530801,93348001,97530801
89663501
62630701
6227895144840002
60070021
60070020
60070019
60070018
60070017
60070016
60070015

MySQL server has gone away - in exactly 60 seconds

I noticed something perhaps relevant.

I had two scripts running, both doing rather slow queries. One of them locked a table and the other had to wait. The one that was waiting had default_socket_timeout = 300. Eventually it quit with "MySQL server has gone away". However, the mysql process list continued to show both query, the slow one still running and the other locked and waiting.

So I don't think mysqld is the culprit. Something has changed in the php mysql client. Quite possibly the default_socket_timeout which I will now set to -1 to see if that changes anything.

pdftk compression option

In case you want to compress a PDF which contains a lot of selectable text, on Windows you can use NicePDF Compressor - choose "Flate" option. After trying everything (cpdf, pdftk, gs) it finally helped me to compress my 1360 pages PDF from 500 MB down to 10 MB.

String.Format not work in TypeScript

If you are using NodeJS, you can use the build-in util function:

import * as util from "util";
util.format('My string: %s', 'foo');

Document can be found here: https://nodejs.org/api/util.html#util_util_format_format_args

jQuery : select all element with custom attribute

As described by the link I've given in comment, this

$('p[MyTag]').each(function(index) {
  document.write(index + ': ' + $(this).text() + "<br>");});

works (playable example).

JIRA JQL searching by date - is there a way of getting Today() (Date) instead of Now() (DateTime)

Just for the sake of keeping the information up-to-date, with at least JIRA 7.3.0 (maybe older as well) you can explicitly specify the date in multiple formats:

  • 'yyyy/MM/dd HH:mm';
  • 'yyyy-MM-dd HH:mm';
  • 'yyyy/MM/dd';
  • 'yyyy-MM-dd';
  • period format, e.g. '-5d', '4w 2d'.

Example:

updatedDate > '2018/06/09 0:00' and updatedDate < '2018/06/10 15:00'

Date validation with ASP.NET validator

A CustomValidator would also work here:

<asp:CustomValidator runat="server"
    ID="valDateRange" 
    ControlToValidate="txtDatecompleted"
    onservervalidate="valDateRange_ServerValidate" 
    ErrorMessage="enter valid date" />

Code-behind:

protected void valDateRange_ServerValidate(object source, ServerValidateEventArgs args)
{
    DateTime minDate = DateTime.Parse("1000/12/28");
    DateTime maxDate = DateTime.Parse("9999/12/28");
    DateTime dt;

    args.IsValid = (DateTime.TryParse(args.Value, out dt) 
                    && dt <= maxDate 
                    && dt >= minDate);
}

Simulate user input in bash script

You should find the 'expect' command will do what you need it to do. Its widely available. See here for an example : http://www.thegeekstuff.com/2010/10/expect-examples/

(very rough example)

#!/usr/bin/expect
set pass "mysecret"

spawn /usr/bin/passwd

expect "password: "
send "$pass"
expect "password: "
send "$pass"

Merge, update, and pull Git branches without using checkouts

You can simply git pull origin branchB into your branchA and git will do the trick for you.

How to write a shell script that runs some commands as superuser and some commands not as superuser, without having to babysit it?

You should run your entire script as superuser. If you want to run some command as non-superuser, use "-u" option of sudo:

#!/bin/bash

sudo -u username command1
command2
sudo -u username command3
command4

When running as root, sudo doesn't ask for a password.

How do a send an HTTPS request through a proxy in Java?

Try the Apache Commons HttpClient library instead of trying to roll your own: http://hc.apache.org/httpclient-3.x/index.html

From their sample code:

  HttpClient httpclient = new HttpClient();
  httpclient.getHostConfiguration().setProxy("myproxyhost", 8080);

  /* Optional if authentication is required.
  httpclient.getState().setProxyCredentials("my-proxy-realm", " myproxyhost",
   new UsernamePasswordCredentials("my-proxy-username", "my-proxy-password"));
  */

  PostMethod post = new PostMethod("https://someurl");
  NameValuePair[] data = {
     new NameValuePair("user", "joe"),
     new NameValuePair("password", "bloggs")
  };
  post.setRequestBody(data);
  // execute method and handle any error responses.
  // ...
  InputStream in = post.getResponseBodyAsStream();
  // handle response.


  /* Example for a GET reqeust
  GetMethod httpget = new GetMethod("https://someurl");
  try { 
    httpclient.executeMethod(httpget);
    System.out.println(httpget.getStatusLine());
  } finally {
    httpget.releaseConnection();
  }
  */

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

for key, value in d.iteritems():
    print key, '\t', value

ASP.NET page life cycle explanation

There are 10 events in ASP.NET page life cycle, and the sequence is:

  1. Init
  2. Load view state
  3. Post back data
  4. Load
  5. Validate
  6. Events
  7. Pre-render
  8. Save view state
  9. Render
  10. Unload

Below is a pictorial view of ASP.NET Page life cycle with what kind of code is expected in that event. I suggest you read this article I wrote on the ASP.NET Page life cycle, which explains each of the 10 events in detail and when to use them.

ASP.NET life cycle

Image source: my own article at https://www.c-sharpcorner.com/uploadfile/shivprasadk/Asp-Net-application-and-page-life-cycle/ from 19 April 2010

HTML5 Video not working in IE 11

I used MP4Box to decode the atom tags in the mp4. (MP4Box -v myfile.mp4) I also used ffmpeg to convert the mp41 to mp42. After comparing the differences and experimenting, I found that IE11 did not like that my original mp4 had two avC1 atoms inside stsd.

After deleting the duplicate avC1 in my original mp41 mp4, IE11 would play the mp4.

How to run function of parent window when child window closes?

The answers as they are require you to add code to the spawned window. That is unnecessary coupling.

// In parent window
var pop = open(url);
pop.onunload = function() {
  // Run your code, the popup window is unloading
  // Beware though, this will also fire if the user navigates to a different
  // page within thepopup. If you need to support that, you will have to play around
  // with pop.closed and setTimeouts
}

Serial Port (RS -232) Connection in C++

For the answer above, the default serial port is

        serialParams.BaudRate = 9600;
        serialParams.ByteSize = 8;
        serialParams.StopBits = TWOSTOPBITS;
        serialParams.Parity = NOPARITY;

In Python, how do I read the exif data for an image?

I use this:

import os,sys
from PIL import Image
from PIL.ExifTags import TAGS

for (k,v) in Image.open(sys.argv[1])._getexif().items():
        print('%s = %s' % (TAGS.get(k), v))

or to get a specific field:

def get_field (exif,field) :
  for (k,v) in exif.items():
     if TAGS.get(k) == field:
        return v

exif = image._getexif()
print get_field(exif,'ExposureTime')

Oracle client ORA-12541: TNS:no listener

According to oracle online documentation

ORA-12541: TNS:no listener

Cause: The connection request could not be completed because the listener is not running.

Action: Ensure that the supplied destination address matches one of the addresses used by 
the listener - compare the TNSNAMES.ORA entry with the appropriate LISTENER.ORA file (or  
TNSNAV.ORA if the connection is to go by way of an Interchange). Start the listener on 
the remote machine.

Can Twitter Bootstrap alerts fade in as well as out?

For 2.3 and above, just add:

$(".alert").fadeOut(3000 );

bootstrap:

<div class="alert success fade in" data-alert="alert" >
    <a class="close" data-dismiss="alert" href="#">&times;</a>
    // code 
</div>

Works in all browsers.

Failed to load ApplicationContext from Unit Test: FileNotFound

I faced the same error and realized that pom.xml had java 1.7 and STS compiler pointed to Java 1.8. Upon changing compiler to 1.7 and rebuild fixed the issue.

PS: This answer is not related to actual question posted but applies to similar error for app Context not loading

Could not find module FindOpenCV.cmake ( Error in configuration process)

Followed @hugh-pearse 's and @leszek-hanusz 's answers, with a little tweak. I had installed opencv from ubuntu 12.10 repository (libopencv-)* and had the same problem. Couldn't solve it with export OpenCV_DIR=/usr/share/OpenCV/ (since my OpenCVConfig.cmake whas there). It was solved when I also changed some lines on the OpenCVConfig.cmake file:

# ======================================================
# Include directories to add to the user project:
# ======================================================

# Provide the include directories to the caller

#SET(OpenCV_INCLUDE_DIRS "${OpenCV_INSTALL_PATH}/include/opencv;${OpenCV_INSTALL_PATH}/include")

SET(OpenCV_INCLUDE_DIRS "/usr/include/opencv;/usr/include/opencv2")
INCLUDE_DIRECTORIES(${OpenCV_INCLUDE_DIRS})

# ======================================================
# Link directories to add to the user project:
# ======================================================

# Provide the libs directory anyway, it may be needed in some cases.

#SET(OpenCV_LIB_DIR "${OpenCV_INSTALL_PATH}/lib")

SET(OpenCV_LIB_DIR "/usr/lib")

LINK_DIRECTORIES(${OpenCV_LIB_DIR})

And that worked on my Ubuntu 12.10. Remember to add the target_link_libraries(yourprojectname ${OpenCV_LIBS}) in your CMakeLists.txt.

How can I bind to the change event of a textarea in jQuery?

2018, without JQUERY

The question is with JQuery, it's just FYI.

JS

let textareaID = document.getElementById('textareaID');
let yourBtnID = document.getElementById('yourBtnID');
textareaID.addEventListener('input', function() {
    yourBtnID.style.display = 'none';
    if (textareaID.value.length) {
        yourBtnID.style.display = 'inline-block';
    }
});

HTML

<textarea id="textareaID"></textarea>
<button id="yourBtnID" style="display: none;">click me</div>

How to add a second x-axis in matplotlib

I'm forced to post this as an answer instead of a comment due to low reputation. I had a similar problem to Matteo. The difference being that I had no map from my first x-axis to my second x-axis, only the x-values themselves. So I wanted to set the data on my second x-axis directly, not the ticks, however, there is no axes.set_xdata. I was able to use Dhara's answer to do this with a modification:

ax2.lines = []

instead of using:

ax2.cla()

When in use also cleared my plot from ax1.

Static variables in C++

Excuse me when I answer your questions out-of-order, it makes it easier to understand this way.

When static variable is declared in a header file is its scope limited to .h file or across all units.

There is no such thing as a "header file scope". The header file gets included into source files. The translation unit is the source file including the text from the header files. Whatever you write in a header file gets copied into each including source file.

As such, a static variable declared in a header file is like a static variable in each individual source file.

Since declaring a variable static this way means internal linkage, every translation unit #includeing your header file gets its own, individual variable (which is not visible outside your translation unit). This is usually not what you want.

I would like to know what is the difference between static variables in a header file vs declared in a class.

In a class declaration, static means that all instances of the class share this member variable; i.e., you might have hundreds of objects of this type, but whenever one of these objects refers to the static (or "class") variable, it's the same value for all objects. You could think of it as a "class global".

Also generally static variable is initialized in .cpp file when declared in a class right ?

Yes, one (and only one) translation unit must initialize the class variable.

So that does mean static variable scope is limited to 2 compilation units ?

As I said:

  • A header is not a compilation unit,
  • static means completely different things depending on context.

Global static limits scope to the translation unit. Class static means global to all instances.

I hope this helps.

PS: Check the last paragraph of Chubsdad's answer, about how you shouldn't use static in C++ for indicating internal linkage, but anonymous namespaces. (Because he's right. ;-) )

PKIX path building failed: unable to find valid certification path to requested target

I also faced this type of issue.I am using tomcat server then i put endorsed folder in tomcat then its start working.And also i replaced JDK1.6 with 1.7 then also its working.Finally i learn SSL then I resolved this type of issues.First you need to download the certificates from that servie provider server.then you are handshake is successfull. 1.Try to put endorsed folder in your server Next way 2.use jdk1.7

Next 3.Try to download valid certificates using SSL

web-api POST body object always null

I had the same problem.

In my case, the problem was in public int? CreditLimitBasedOn { get; set; } property I had.

my JSON had the value "CreditLimitBasedOn":true when It should contain an integer. This property prevented the whole object being deserialized on my api method.

Android Studio - Failed to apply plugin [id 'com.android.application']

delete C:\Users\username\.gradle\caches folder.

"Rate This App"-link in Google Play store app on the phone

You can always call getInstalledPackages() from the PackageManager class and check to make sure the market class is installed. You could also use queryIntentActivities() to make sure that the Intent you construct will be able to be handled by something, even if it's not the market application. This is probably the best thing to do actually because its the most flexible and robust.

You can check if the market app is there by

Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(Uri.parse("market://search?q=foo"));
PackageManager pm = getPackageManager();
List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);

If the list has at least one entry, the Market's there.

You can use the following to launch Android Market on your application's page, it's a bit more automated:

Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("market://details?id=" + getPackageName()));
startActivity(i);

If you want to test this on your emulator you probably you don't have the market installed on it : see these links for more details:

How To Enable the Android Market in the Google Android Emulator

Installing Google Play on Android Emulator

Show/hide 'div' using JavaScript

You can easily achieve this with the use of jQuery .toggle().

$("#btnDisplay").click(function() {
  $("#div1").toggle();
  $("#div2").toggle();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="div1">
  First Div
</div>
<div id="div2" style="display: none;">
  Second Div
</div>
<button id="btnDisplay">Display</button>

How do I correctly upgrade angular 2 (npm) to the latest version?

If you are looking like me for just updating your project to the latest these is what works form me since Angular 6:

Open the console on your project folder: If you type: ng update then you will get the below message:

        We analyzed your package.json, there are some packages to update:

          Name                               Version                  Command to update
         --------------------------------------------------------------------------------
          @angular/cli                       7.0.7 -> 7.2.2           ng update @angular/cli
          @angular/core                      7.0.4 -> 7.2.1           ng update @angular/core

There might be additional packages that are outdated.
    Run "ng update --all" to try to update all at the same time.

So I usually go straight and do:

ng update --all

Finally you can check your new version:

ng version
Angular CLI: 7.2.2
Node: 8.12.0
OS: win32 x64
Angular: 7.2.1
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.12.2
@angular-devkit/build-angular     0.12.2
@angular-devkit/build-optimizer   0.12.2
@angular-devkit/build-webpack     0.12.2
@angular-devkit/core              7.2.2
@angular-devkit/schematics        7.2.2
@angular/cli                      7.2.2
@ngtools/webpack                  7.2.2
@schematics/angular               7.2.2
@schematics/update                0.12.2
rxjs                              6.3.3
typescript                        3.2.4
webpack                           4.28.4

Get current clipboard content?

window.clipboardData.getData('Text') will work in some browsers. However, many browsers where it does work will prompt the user as to whether or not they wish the web page to have access to the clipboard.

How to display a loading screen while site content loads

You said you didn't want to do this in AJAX. While AJAX is great for this, there is a way to show one DIV while waiting for the entire <body> to load. It goes something like this:

<html>
  <head>
    <style media="screen" type="text/css">
      .layer1_class { position: absolute; z-index: 1; top: 100px; left: 0px; visibility: visible; }
      .layer2_class { position: absolute; z-index: 2; top: 10px; left: 10px; visibility: hidden }
    </style>
    <script>
      function downLoad(){
        if (document.all){
            document.all["layer1"].style.visibility="hidden";
            document.all["layer2"].style.visibility="visible";
        } else if (document.getElementById){
            node = document.getElementById("layer1").style.visibility='hidden';
            node = document.getElementById("layer2").style.visibility='visible';
        }
      }
    </script>
  </head>
  <body onload="downLoad()">
    <div id="layer1" class="layer1_class">
      <table width="100%">
        <tr>
          <td align="center"><strong><em>Please wait while this page is loading...</em></strong></p></td>
        </tr>
      </table>
    </div>
    <div id="layer2" class="layer2_class">
        <script type="text/javascript">
                alert('Just holding things up here.  While you are reading this, the body of the page is not loading and the onload event is being delayed');
        </script>
        Final content.      
    </div>
  </body>
</html>

The onload event won't fire until all of the page has loaded. So the layer2 <DIV> won't be displayed until the page has finished loading, after which onload will fire.

Attach Authorization header for all axios requests

If you use "axios": "^0.17.1" version you can do like this:

Create instance of axios:

// Default config options
  const defaultOptions = {
    baseURL: <CHANGE-TO-URL>,
    headers: {
      'Content-Type': 'application/json',
    },
  };

  // Create instance
  let instance = axios.create(defaultOptions);

  // Set the AUTH token for any request
  instance.interceptors.request.use(function (config) {
    const token = localStorage.getItem('token');
    config.headers.Authorization =  token ? `Bearer ${token}` : '';
    return config;
  });

Then for any request the token will be select from localStorage and will be added to the request headers.

I'm using the same instance all over the app with this code:

import axios from 'axios';

const fetchClient = () => {
  const defaultOptions = {
    baseURL: process.env.REACT_APP_API_PATH,
    method: 'get',
    headers: {
      'Content-Type': 'application/json',
    },
  };

  // Create instance
  let instance = axios.create(defaultOptions);

  // Set the AUTH token for any request
  instance.interceptors.request.use(function (config) {
    const token = localStorage.getItem('token');
    config.headers.Authorization =  token ? `Bearer ${token}` : '';
    return config;
  });

  return instance;
};

export default fetchClient();

Good luck.

git diff between cloned and original remote repository

This example might help someone:

Note "origin" is my alias for remote "What is on Github"
Note "mybranch" is my alias for my branch "what is local" that I'm syncing with github
--your branch name is 'master' if you didn't create one. However, I'm using the different name mybranch to show where the branch name parameter is used.


What exactly are my remote repos on github?

$ git remote -v
origin  https://github.com/flipmcf/Playground.git (fetch)
origin  https://github.com/flipmcf/Playground.git (push)

Add the "other github repository of the same code" - we call this a fork:

$ git remote add someOtherRepo https://github.com/otherUser/Playground.git

$git remote -v
origin  https://github.com/flipmcf/Playground.git (fetch)
origin  https://github.com/flipmcf/Playground.git (push)
someOtherRepo https://github.com/otherUser/Playground.git (push)
someOtherRepo https://github.com/otherUser/Playground.git (fetch)

make sure our local repo is up to date:

$ git fetch

Change some stuff locally. let's say file ./foo/bar.py

$ git status
# On branch mybranch
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#   modified:   foo/bar.py

Review my uncommitted changes

$ git diff mybranch
diff --git a/playground/foo/bar.py b/playground/foo/bar.py
index b4fb1be..516323b 100655
--- a/playground/foo/bar.py
+++ b/playground/foo/bar.py
@@ -1,27 +1,29 @@
- This line is wrong
+ This line is fixed now - yea!
+ And I added this line too.

Commit locally.

$ git commit foo/bar.py -m"I changed stuff"
[myfork 9f31ff7] I changed stuff
1 files changed, 2 insertions(+), 1 deletions(-)

Now, I'm different than my remote (on github)

$ git status
# On branch mybranch
# Your branch is ahead of 'origin/mybranch' by 1 commit.
#
nothing to commit (working directory clean)

Diff this with remote - your fork: (this is frequently done with git diff master origin)

$ git diff mybranch origin
diff --git a/playground/foo/bar.py b/playground/foo/bar.py
index 516323b..b4fb1be 100655
--- a/playground/foo/bar.py
+++ b/playground/foo/bar.py
@@ -1,27 +1,29 @@
- This line is wrong
+ This line is fixed now - yea!
+ And I added this line too.

(git push to apply these to remote)

How does my remote branch differ from the remote master branch?

$ git diff origin/mybranch origin/master

How does my local stuff differ from the remote master branch?

$ git diff origin/master

How does my stuff differ from someone else's fork, master branch of the same repo?

$git diff mybranch someOtherRepo/master

Understanding the Linux oom-killer's logs

Sum of total_vm is 847170 and sum of rss is 214726, these two values are counted in 4kB pages, which means when oom-killer was running, you had used 214726*4kB=858904kB physical memory and swap space.

Since your physical memory is 1GB and ~200MB was used for memory mapping, it's reasonable for invoking oom-killer when 858904kB was used.

rss for process 2603 is 181503, which means 181503*4KB=726012 rss, was equal to sum of anon-rss and file-rss.

[11686.043647] Killed process 2603 (flasherav) total-vm:1498536kB, anon-rss:721784kB, file-rss:4228kB

How to get JSON from webpage into Python script

I'll take a guess that you actually want to get data from the URL:

jsonurl = urlopen(url)
text = json.loads(jsonurl.read()) # <-- read from it

Or, check out JSON decoder in the requests library.

import requests
r = requests.get('someurl')
print r.json() # if response type was set to JSON, then you'll automatically have a JSON response here...

problem with php mail 'From' header

I had the same Issue, I checked the php.net site. And found the right format.
This is my updated code.

$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From:  ' . $fromName . ' <' . $fromEmail .'>' . " \r\n" .
            'Reply-To: '.  $fromEmail . "\r\n" .
            'X-Mailer: PHP/' . phpversion();

The \r\n should be in double quotes(") itself, the single quotes(') will not work.

Copying files to a container with Docker Compose

Given

    volumes:
      - /dir/on/host:/var/www/html

if /dir/on/host doesn't exist, it is created on the host and the empty content is mounted in the container at /var/www/html. Whatever content you had before in /var/www/html inside the container is inaccessible, until you unmount the volume; the new mount is hiding the old content.

How to pass a view's onClick event to its parent on Android?

This answer is similar to Alexander Ukhov's answer, except that it uses touch events rather than click events. Those event allow the parent to display the proper pressed states (e.g., ripple effect). This answer is also in Kotlin instead of Java.

view.setOnTouchListener { view, motionEvent ->
    (view.parent as View).onTouchEvent(motionEvent)
}

Using array map to filter results with if conditional

You could use flatMap. It can filter and map in one.

$scope.appIds = $scope.applicationsHere.flatMap(obj => obj.selected ? obj.id : [])

jQuery - how to check if an element exists?

I use this:

if ($('.div1').size() || $('.div2').size()) {
    console.log('ok');
}

What is the keyguard in Android?

Yes, I also found it here: http://developer.android.com/tools/testing/activity_testing.html It's seems a key-input protection mechanism which includes the screen-lock, but not only includes it. According to this webpage, it also defines some key-input restriction for auto-test framework in Android.

Uncaught TypeError: (intermediate value)(...) is not a function

The error is a result of the missing semicolon on the third line:

window.Glog = function(msg) {
  console.log(msg);
}; // <--- Add this semicolon

(function(win) {
  // ...
})(window);

The ECMAScript specification has specific rules for automatic semicolon insertion, however in this case a semicolon isn't automatically inserted because the parenthesised expression that begins on the next line can be interpreted as an argument list for a function call.

This means that without that semicolon, the anonymous window.Glog function was being invoked with a function as the msg parameter, followed by (window) which was subsequently attempting to invoke whatever was returned.

This is how the code was being interpreted:

window.Glog = function(msg) {
  console.log(msg);
}(function(win) {
  // ...
})(window);

TypeScript error: Type 'void' is not assignable to type 'boolean'

It means that the callback function you passed to this.dataStore.data.find should return a boolean and have 3 parameters, two of which can be optional:

  • value: Conversations
  • index: number
  • obj: Conversation[]

However, your callback function does not return anything (returns void). You should pass a callback function with the correct return value:

this.dataStore.data.find((element, index, obj) => {
    // ...

    return true; // or false
});

or:

this.dataStore.data.find(element => {
    // ...

    return true; // or false
});

Reason why it's this way: the function you pass to the find method is called a predicate. The predicate here defines a boolean outcome based on conditions defined in the function itself, so that the find method can determine which value to find.

In practice, this means that the predicate is called for each item in data, and the first item in data for which your predicate returns true is the value returned by find.

How can JavaScript save to a local file?

It all depends on what you are trying to achieve with "saving locally". Do you want to allow the user to download the file? then <a download> is the way to go. Do you want to save it locally, so you can restore your application state? Then you might want to look into the various options of WebStorage. Specifically localStorage or IndexedDB. The FilesystemAPI allows you to create local virtual file systems you can store arbitrary data in.

How to select rows in a DataFrame between two values, in Python Pandas?

If one has to call pd.Series.between(l,r) repeatedly (for different bounds l and r), a lot of work is repeated unnecessarily. In this case, it's beneficial to sort the frame/series once and then use pd.Series.searchsorted(). I measured a speedup of up to 25x, see below.

def between_indices(x, lower, upper, inclusive=True):
    """
    Returns smallest and largest index i for which holds 
    lower <= x[i] <= upper, under the assumption that x is sorted.
    """
    i = x.searchsorted(lower, side="left" if inclusive else "right")
    j = x.searchsorted(upper, side="right" if inclusive else "left")
    return i, j

# Sort x once before repeated calls of between()
x = x.sort_values().reset_index(drop=True)
# x = x.sort_values(ignore_index=True) # for pandas>=1.0
ret1 = between_indices(x, lower=0.1, upper=0.9)
ret2 = between_indices(x, lower=0.2, upper=0.8)
ret3 = ...

Benchmark

Measure repeated evaluations (n_reps=100) of pd.Series.between() as well as the method based on pd.Series.searchsorted(), for different arguments lower and upper. On my MacBook Pro 2015 with Python v3.8.0 and Pandas v1.0.3, the below code results in the following outpu

# pd.Series.searchsorted()
# 5.87 ms ± 321 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
# pd.Series.between(lower, upper)
# 155 ms ± 6.08 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# Logical expressions: (x>=lower) & (x<=upper)
# 153 ms ± 3.52 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
import numpy as np
import pandas as pd

def between_indices(x, lower, upper, inclusive=True):
    # Assumption: x is sorted.
    i = x.searchsorted(lower, side="left" if inclusive else "right")
    j = x.searchsorted(upper, side="right" if inclusive else "left")
    return i, j

def between_fast(x, lower, upper, inclusive=True):
    """
    Equivalent to pd.Series.between() under the assumption that x is sorted.
    """
    i, j = between_indices(x, lower, upper, inclusive)
    if True:
        return x.iloc[i:j]
    else:
        # Mask creation is slow.
        mask = np.zeros_like(x, dtype=bool)
        mask[i:j] = True
        mask = pd.Series(mask, index=x.index)
        return x[mask]

def between(x, lower, upper, inclusive=True):
    mask = x.between(lower, upper, inclusive=inclusive)
    return x[mask]

def between_expr(x, lower, upper, inclusive=True):
    if inclusive:
        mask = (x>=lower) & (x<=upper)
    else:
        mask = (x>lower) & (x<upper)
    return x[mask]

def benchmark(func, x, lowers, uppers):
    for l,u in zip(lowers, uppers):
        func(x,lower=l,upper=u)

n_samples = 1000
n_reps = 100
x = pd.Series(np.random.randn(n_samples))
# Sort the Series.
# For pandas>=1.0:
# x = x.sort_values(ignore_index=True)
x = x.sort_values().reset_index(drop=True)

# Assert equivalence of different methods.
assert(between_fast(x, 0, 1, True ).equals(between(x, 0, 1, True)))
assert(between_expr(x, 0, 1, True ).equals(between(x, 0, 1, True)))
assert(between_fast(x, 0, 1, False).equals(between(x, 0, 1, False)))
assert(between_expr(x, 0, 1, False).equals(between(x, 0, 1, False)))

# Benchmark repeated evaluations of between().
uppers = np.linspace(0, 3, n_reps)
lowers = -uppers
%timeit benchmark(between_fast, x, lowers, uppers)
%timeit benchmark(between, x, lowers, uppers)
%timeit benchmark(between_expr, x, lowers, uppers)

Visual Studio Code open tab in new window

With Visual Studio 1.43 (Q1 2020), the Ctrl+K then O keyboard shortcut will work for a file.

See issue 89989:

It should be possible to e.g. invoke the "Open Active File in New Window" command and open that file into an empty workspace in the web.

new windows -- https://user-images.githubusercontent.com/900690/73733120-aa0f6680-473b-11ea-8bcd-f2f71b75b496.png

How to multiply values using SQL

Why are you grouping by? Do you mean order by?

SELECT player_name, player_salary, player_salary * 1.1 AS NewSalary
FROM players
ORDER BY player_salary, player_name;

Could not load file or assembly 'Microsoft.Web.Infrastructure,

Resharper detected Microsoft.Web.Infrastructure as an unused reference an so I deleted it. Locally was working fine but then I got the same error after publishing to dev.

Conclusion, beware when deleting references marked as unused by Resharper

is there any IE8 only css hack?

So a recent question prompted me to notice a selector set hack for excluding IE 8 only.

.selector, #excludeIE8::before {} will cause IE 8 to throw out the entire selector set, while 5-7 and 9-11 will read it just fine. Any of the :: selectors (::first-line, ::before, ::first-letter, ::selection) will work, I've merely chosen ::before so the line reads accurately. Note that the goal of the fake ::before selector is to be fake, so be sure to change it to something else if you actually have an element with the ID excludeIE8

Interestingly enough, in modern browsers (FF 45-52, GC 49-57, Edge 25/13) a bad :: selector eats the entire selector set (dabblet demo). It seems that the last Windows version of Safari (and LTE IE 7, lol) doesn't have this behavior while still understanding ::before. Additionally, I can't find anything in the spec to indicate that this is intended behavior, and since it would cause breakage on any selector set containing: ::future-legitimate-pseudoelement... I'm inclined to say this is a bug- and one that'll nibble our rears in the future.


However, if you only want something at the property level (rather than the rule level), Ziga above had the best solution via appending  \9 (the space is key; do NOT copypaste that inline as it uses an nbsp):

/*property-level hacks:*/
/*Standards, Edge*/
prop:val;
/*lte ie 11*/
prop:val\9;
/*lte ie 8*/
prop:val \9;
/*lte ie 7*/
*prop:val;
/*lte ie 6*/
_prop:val;

/*other direction...*/
/*gte ie 8, NOT Edge*/
prop:val\0;

Side note, I feel like a dirty necromancer- but I wanted somewhere to document the exclude-IE8-only selector set hack I found today, and this seemed to be the most fitting place.

Httpd returning 503 Service Unavailable with mod_proxy for Tomcat 8

this worked for me:

ProxyRequests     Off
ProxyPreserveHost On
RewriteEngine On

<Proxy http://localhost:8123>
Order deny,allow
Allow from all
</Proxy>

ProxyPass         /node  http://localhost:8123  
ProxyPassReverse  /node  http://localhost:8123

Cannot insert explicit value for identity column in table 'table' when IDENTITY_INSERT is set to OFF

The best solution is to use annotation GeneratedValue(strategy = ...), i.e.

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column ...
private int OperationID;

it says, that this column is generated by database using IDENTITY strategy and you don't need to take care of - database will do it.

How can one see content of stack with GDB?

Use:

  • bt - backtrace: show stack functions and args
  • info frame - show stack start/end/args/locals pointers
  • x/100x $sp - show stack memory
(gdb) bt
#0  zzz () at zzz.c:96
#1  0xf7d39cba in yyy (arg=arg@entry=0x0) at yyy.c:542
#2  0xf7d3a4f6 in yyyinit () at yyy.c:590
#3  0x0804ac0c in gnninit () at gnn.c:374
#4  main (argc=1, argv=0xffffd5e4) at gnn.c:389

(gdb) info frame
Stack level 0, frame at 0xffeac770:
 eip = 0x8049047 in main (goo.c:291); saved eip 0xf7f1fea1
 source language c.
 Arglist at 0xffeac768, args: argc=1, argv=0xffffd5e4
 Locals at 0xffeac768, Previous frame's sp is 0xffeac770
 Saved registers:
  ebx at 0xffeac75c, ebp at 0xffeac768, esi at 0xffeac760, edi at 0xffeac764, eip at 0xffeac76c

(gdb) x/10x $sp
0xffeac63c: 0xf7d39cba  0xf7d3c0d8  0xf7d3c21b  0x00000001
0xffeac64c: 0xf78d133f  0xffeac6f4  0xf7a14450  0xffeac678
0xffeac65c: 0x00000000  0xf7d3790e

How should I have explained the difference between an Interface and an Abstract class?

To keep it down to a simple, reasonable response you can provide in an interview, I offer the following...

An interface is used to specify an API for a family of related classes - the relation being the interface. Typically used in a situation that has multiple implementations, the correct implementation being chosen either by configuration or at runtime. (Unless using Spring, at which point an interface is basically a Spring Bean). Interfaces are often used to solve the multiple inheritance issue.

An abstract class is a class designed specifically for inheritance. This also implies multiple implementations, with all implementations having some commonality (that found in the abstract class).

If you want to nail it, then say that an abstract class often implements a portion of an interface - job is yours!

Multiple returns from a function

Since PHP 7.1 we have proper destructuring for lists. Thereby you can do things like this:

$test = [1, 2, 3, 4];
[$a, $b, $c, $d] = $test;
echo($a);
> 1
echo($d);
> 4

In a function this would look like this:

function multiple_return() {
    return ['this', 'is', 'a', 'test'];
}

[$first, $second, $third, $fourth] = multiple_return();
echo($first);
> this
echo($fourth);
> test

Destructuring is a very powerful tool. It's capable of destructuring key=>value pairs as well:

["a" => $a, "b" => $b, "c" => $c] = ["a" => 1, "b" => 2, "c" => 3];

Take a look at the new feature page for PHP 7.1:

New features

How to fill a datatable with List<T>

I also had to come up with an alternate solution, as none of the options listed here worked in my case. I was using an IEnumerable and the underlying data was a IEnumerable and the properties couldn't be enumerated. This did the trick:

// remove "this" if not on C# 3.0 / .NET 3.5
public static DataTable ConvertToDataTable<T>(this IEnumerable<T> data)
{
    List<IDataRecord> list = data.Cast<IDataRecord>().ToList();

    PropertyDescriptorCollection props = null;
    DataTable table = new DataTable();
    if (list != null && list.Count > 0)
    {
        props = TypeDescriptor.GetProperties(list[0]);
        for (int i = 0; i < props.Count; i++)
        {
            PropertyDescriptor prop = props[i];
            table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
        }
    }
    if (props != null)
    {
        object[] values = new object[props.Count];
        foreach (T item in data)
        {
            for (int i = 0; i < values.Length; i++)
            {
                values[i] = props[i].GetValue(item) ?? DBNull.Value;
            }
            table.Rows.Add(values);
        }
    }
    return table;
}

How to create a 100% screen width div inside a container in bootstrap?

The reason why your full-width-div doesn't stretch 100% to your screen it's because of its parent "container" which occupies only about 80% of the screen.

If you want to make it stretch 100% to the screen either you make the "full-width-div" position fixed or use the "container-fluid" class instead of "container".

see Bootstrap 3 docs: http://getbootstrap.com/css/#grid

How to delete all files and folders in a directory?

use DirectoryInfo's GetDirectories method.

foreach (DirectoryInfo subDir in new DirectoryInfo(targetDir).GetDirectories())
                    subDir.Delete(true);

Specify the date format in XMLGregorianCalendar

you don't need to specify a "SimpleDateFormat", it's simple: You must do specify the constant "DatatypeConstants.FIELD_UNDEFINED" where you don't want to show

GregorianCalendar cal = new GregorianCalendar();
cal.setTime(new Date());
XMLGregorianCalendar xmlDate = DatatypeFactory.newInstance().newXMLGregorianCalendarDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH)+1, cal.get(Calendar.DAY_OF_MONTH), DatatypeConstants.FIELD_UNDEFINED);

How to make borders collapse (on a div)?

Example of using border-collapse: separate; as

  • container displayed as table:

    ol[type="I"]>li{
      display: table;
      border-collapse: separate;
      border-spacing: 1rem;
    }
    
  • Passing arguments to C# generic new() of templated type

    If all is you need is convertion from ListItem to your type T you can implement this convertion in T class as conversion operator.

    public class T
    {
        public static implicit operator T(ListItem listItem) => /* ... */;
    }
    
    public static string GetAllItems(...)
    {
        ...
        List<T> tabListItems = new List<T>();
        foreach (ListItem listItem in listCollection) 
        {
            tabListItems.Add(listItem);
        } 
        ...
    }
    

    Best way to use Google's hosted jQuery, but fall back to my hosted library on Google fail

    Although writing document.write("<script></script>") seems easier for jQuery backoff, Chrome gives validation error on that case. So I prefer breaking "script" word. So it becomes safer like above.

    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.1.min.js"></script>
    <script>if (typeof jQuery === "undefined") {
       window.jqFallback = true;
       document.write("<scr"+"ipt src='http://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.1/jquery.min.js'></scr"+"ipt>");
    } </script>
    

    For long term issues, it would be better to log JQuery fallbacks. In the code above, if first CDN is not available JQuery is loaded from another CDN. But you could want to know that erroneous CDN and remove it permanently. (this case is very exceptional case) Also it is better to log fallback issues. So you can send erroneous cases with AJAX. Because of JQuery isn't defined, you should use vanilla javascript for AJAX request.

    <script type="text/javascript">
        if (typeof jQuery === 'undefined' || window.jqFallback == true) {
            // XMLHttpRequest for IE7+, Firefox, Chrome, Opera, Safari
            // ActiveXObject for IE6, IE5
            var xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
            var url = window.jqFallback == true ? "/yourUrl/" : "/yourUrl2/";
            xmlhttp.open("POST", url, true);
            xmlhttp.send();
        }
    </script>
    

    How to add row of data to Jtable from values received from jtextfield and comboboxes

    Peeskillet's lame tutorial for working with JTables in Netbeans GUI Builder

    • Set the table column headers
      1. Highglight the table in the design view then go to properties pane on the very right. Should be a tab that says "Properties". Make sure to highlight the table and not the scroll pane surrounding it, or the next step wont work
      2. Click on the ... button to the right of the property model. A dialog should appear.
      3. Set rows to 0, set the number of columns you want, and their names.
    • Add a button to the frame somwhere,. This button will be clicked when the user is ready to submit a row

      1. Right-click on the button and select Events -> Action -> actionPerformed
      2. You should see code like the following auto-generated

        private void jButton1ActionPerformed(java.awt.event.ActionEvent) {}
        
    • The jTable1 will have a DefaultTableModel. You can add rows to the model with your data

      private void jButton1ActionPerformed(java.awt.event.ActionEvent) {
          String data1 = something1.getSomething();
          String data2 = something2.getSomething();
          String data3 = something3.getSomething();
          String data4 = something4.getSomething();
      
          Object[] row = { data1, data2, data3, data4 };
      
          DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
      
          model.addRow(row);
      
          // clear the entries.
      }
      

    So for every set of data like from a couple text fields, a combo box, and a check box, you can gather that data each time the button is pressed and add it as a row to the model.

    allowing only alphabets in text box using java script

    :::::HTML:::::

    <input type="text" onkeypress="return lettersValidate(event)" />
    

    Only letters no spaces

    ::::JS::::::::

    // ===================== Allow - Only Letters ===============================================================
    
    function lettersValidate(key) {
        var keycode = (key.which) ? key.which : key.keyCode;
    
        if ((keycode > 64 && keycode < 91) || (keycode > 96 && keycode < 123))  
        {     
               return true;    
        }
        else
        {
            return false;
        }
             
    }
     
    

    Capture screenshot of active window?

    I assume you use Graphics.CopyFromScreen to get the screenshot.

    You can use P/Invoke to GetForegroundWindow (and then get its position and size) to determine which region you need to copy from.

    VBA Go to last empty row

    try this:

    Sub test()
    
    With Application.WorksheetFunction
        Cells(.CountA(Columns("A:A")) + 1, 1).Select
    End With
    
    End Sub
    

    Hope this works for you.

    Creating dummy variables in pandas for python

    Based on the official documentation:

    dummies = pd.get_dummies(df['Category']).rename(columns=lambda x: 'Category_' + str(x))
    df = pd.concat([df, dummies], axis=1)
    df = df.drop(['Category'], inplace=True, axis=1)
    

    There is also a nice post in the FastML blog.

    What's an easy way to read random line from a file in Unix command line?

    A solution that also works on MacOSX, and should also works on Linux(?):

    N=5
    awk 'NR==FNR {lineN[$1]; next}(FNR in lineN)' <(jot -r $N 1 $(wc -l < $file)) $file 
    

    Where:

    • N is the number of random lines you want

    • NR==FNR {lineN[$1]; next}(FNR in lineN) file1 file2 --> save line numbers written in file1 and then print corresponding line in file2

    • jot -r $N 1 $(wc -l < $file) --> draw N numbers randomly (-r) in range (1, number_of_line_in_file) with jot. The process substitution <() will make it look like a file for the interpreter, so file1 in previous example.

    Reading Excel file using node.js

    install exceljs and use the following code,

    var Excel = require('exceljs');
    
    var wb = new Excel.Workbook();
    var path = require('path');
    var filePath = path.resolve(__dirname,'sample.xlsx');
    
    wb.xlsx.readFile(filePath).then(function(){
    
        var sh = wb.getWorksheet("Sheet1");
    
        sh.getRow(1).getCell(2).value = 32;
        wb.xlsx.writeFile("sample2.xlsx");
        console.log("Row-3 | Cell-2 - "+sh.getRow(3).getCell(2).value);
    
        console.log(sh.rowCount);
        //Get all the rows data [1st and 2nd column]
        for (i = 1; i <= sh.rowCount; i++) {
            console.log(sh.getRow(i).getCell(1).value);
            console.log(sh.getRow(i).getCell(2).value);
        }
    });
    

    What is the best way to programmatically detect porn images?

    Two options I can think of (though neither of them is programatically detecting porn):

    1. Block all uploaded images until one of your administrators has looked at them. There's no reason why this should take a long time: you could write some software that shows 10 images a second, almost as a movie - even at this speed, it's easy for a human being to spot a potentially pornographic image. Then you rewind in this software and have a closer look.
    2. Add the usual "flag this image as inappropriate" option.

    What does it mean to have an index to scalar variable error? python

    exponent is a 1D array. This means that exponent[0] is a scalar, and exponent[0][i] is trying to access it as if it were an array.

    Did you mean to say:

    L = identity(len(l))
    for i in xrange(len(l)):
        L[i][i] = exponent[i]
    

    or even

    L = diag(exponent)
    

    ?

    Visual Studio Post Build Event - Copy to Relative Directory Location

    I think this is related, but I had a problem when building directly using msbuild command line (from a batch file) vs building from within VS.

    Using something like the following:

    <PostBuildEvent>
      MOVE /Y "$(TargetDir)something.file1" "$(ProjectDir)something.file1"
      start XCOPY /Y /R "$(SolutionDir)SomeConsoleApp\bin\$(ConfigurationName)\*" "$(ProjectDir)App_Data\Consoles\SomeConsoleApp\"
    </PostBuildEvent>
    

    (note: start XCOPY rather than XCOPY used to get around a permissions issue which prevented copying)

    The macro $(SolutionDir) evaluated to ..\ when executing msbuild from a batchfile, which resulted in the XCOPY command failing. It otherwise worked fine when built from within Visual Studio. Confirmed using /verbosity:diagnostic to see the evaluated output.

    Using the macro $(ProjectDir)..\ instead, which amounts to the same thing, worked fine and retained the full path in both build scenarios.

    Deleting a SQL row ignoring all foreign keys and constraints

    You can disable all of the constaints on your database by the following line of code:

    EXEC sp_MSforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
    

    and after the runing your update/delete command, you can enable it again as the following:

    EXEC sp_MSforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"
    

    Using CSS for a fade-in effect on page load

    Method 1:

    If you are looking for a self-invoking transition then you should use CSS 3 Animations. They aren't supported either, but this is exactly the kind of thing they were made for.

    CSS

    #test p {
        margin-top: 25px;
        font-size: 21px;
        text-align: center;
    
        -webkit-animation: fadein 2s; /* Safari, Chrome and Opera > 12.1 */
           -moz-animation: fadein 2s; /* Firefox < 16 */
            -ms-animation: fadein 2s; /* Internet Explorer */
             -o-animation: fadein 2s; /* Opera < 12.1 */
                animation: fadein 2s;
    }
    
    @keyframes fadein {
        from { opacity: 0; }
        to   { opacity: 1; }
    }
    
    /* Firefox < 16 */
    @-moz-keyframes fadein {
        from { opacity: 0; }
        to   { opacity: 1; }
    }
    
    /* Safari, Chrome and Opera > 12.1 */
    @-webkit-keyframes fadein {
        from { opacity: 0; }
        to   { opacity: 1; }
    }
    
    /* Internet Explorer */
    @-ms-keyframes fadein {
        from { opacity: 0; }
        to   { opacity: 1; }
    }
    
    /* Opera < 12.1 */
    @-o-keyframes fadein {
        from { opacity: 0; }
        to   { opacity: 1; }
    }
    

    Demo

    Browser Support

    All modern browsers and Internet Explorer 10 (and later): http://caniuse.com/#feat=css-animation


    Method 2:

    Alternatively, you can use jQuery (or plain JavaScript; see the third code block) to change the class on load:

    jQuery

    $("#test p").addClass("load");?
    

    CSS

    #test p {
        opacity: 0;
        font-size: 21px;
        margin-top: 25px;
        text-align: center;
    
        -webkit-transition: opacity 2s ease-in;
           -moz-transition: opacity 2s ease-in;
            -ms-transition: opacity 2s ease-in;
             -o-transition: opacity 2s ease-in;
                transition: opacity 2s ease-in;
    }
    
    #test p.load {
        opacity: 1;
    }
    

    Plain JavaScript (not in the demo)

    document.getElementById("test").children[0].className += " load";
    

    Demo

    Browser Support

    All modern browsers and Internet Explorer 10 (and later): http://caniuse.com/#feat=css-transitions


    Method 3:

    Or, you can use the method that .Mail uses:

    jQuery

    $("#test p").delay(1000).animate({ opacity: 1 }, 700);?
    

    CSS

    #test p {
        opacity: 0;
        font-size: 21px;
        margin-top: 25px;
        text-align: center;
    }
    

    Demo

    Browser Support

    jQuery 1.x: All modern browsers and Internet Explorer 6 (and later): http://jquery.com/browser-support/
    jQuery 2.x: All modern browsers and Internet Explorer 9 (and later): http://jquery.com/browser-support/

    This method is the most cross-compatible as the target browser does not need to support CSS 3 transitions or animations.

    How to stretch children to fill cross-axis?

    • The children of a row-flexbox container automatically fill the container's vertical space.

    • Specify flex: 1; for a child if you want it to fill the remaining horizontal space:

    _x000D_
    _x000D_
    .wrapper {_x000D_
      display: flex;_x000D_
      flex-direction: row;_x000D_
      align-items: stretch;_x000D_
      width: 100%;_x000D_
      height: 5em;_x000D_
      background: #ccc;_x000D_
    }_x000D_
    .wrapper > .left_x000D_
    {_x000D_
      background: #fcc;_x000D_
    }_x000D_
    .wrapper > .right_x000D_
    {_x000D_
      background: #ccf;_x000D_
      flex: 1; _x000D_
    }
    _x000D_
    <div class="wrapper">_x000D_
      <div class="left">Left</div>_x000D_
      <div class="right">Right</div>_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    • Specify flex: 1; for both children if you want them to fill equal amounts of the horizontal space:

    _x000D_
    _x000D_
    .wrapper {_x000D_
      display: flex;_x000D_
      flex-direction: row;_x000D_
      align-items: stretch;_x000D_
      width: 100%;_x000D_
      height: 5em;_x000D_
      background: #ccc;_x000D_
    }_x000D_
    .wrapper > div _x000D_
    {_x000D_
      flex: 1; _x000D_
    }_x000D_
    .wrapper > .left_x000D_
    {_x000D_
      background: #fcc;_x000D_
    }_x000D_
    .wrapper > .right_x000D_
    {_x000D_
      background: #ccf;_x000D_
    }
    _x000D_
    <div class="wrapper">_x000D_
      <div class="left">Left</div>_x000D_
      <div class="right">Right</div>_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    How do I compile jrxml to get jasper?

    If you are using iReport you can easily do it.

    1. When you click preview it will automatically compile.
    2. There is an option to make it complie. You can compile by selecting the page then right click you will get the compile option.

    How do I call a JavaScript function on page load?

    _x000D_
    _x000D_
    <!DOCTYPE html>_x000D_
    <html>_x000D_
        <head>_x000D_
            <title>Test</title>_x000D_
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />_x000D_
            <script type="text/javascript">_x000D_
            function codeAddress() {_x000D_
                alert('ok');_x000D_
            }_x000D_
            window.onload = codeAddress;_x000D_
            </script>_x000D_
        </head>_x000D_
        <body>_x000D_
        _x000D_
        </body>_x000D_
    </html>
    _x000D_
    _x000D_
    _x000D_

    Setting Authorization Header of HttpClient

    This may help Setting the header:

    WebClient client = new WebClient();
    
    string authInfo = this.credentials.UserName + ":" + this.credentials.Password;
    authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
    client.Headers["Authorization"] = "Basic " + authInfo;
    

    Why Java Calendar set(int year, int month, int date) not returning correct date?

    Selected date at the example is interesting. Example code block is:

    Calendar c1 = GregorianCalendar.getInstance();
    c1.set(2000, 1, 30);  //January 30th 2000
    Date sDate = c1.getTime();
    
    System.out.println(sDate);
    

    and output Wed Mar 01 19:32:21 JST 2000.

    When I first read the example i think that output is wrong but it is true:)

    • Calendar.Month is starting from 0 so 1 means February.
    • February last day is 28 so output should be 2 March.
    • But selected year is important, it is 2000 which means February 29 so result should be 1 March.

    jQuery jump or scroll to certain position, div or target on the page from button onclick

    $("html, body").scrollTop($(element).offset().top); // <-- Also integer can be used
    

    In javascript, how do you search an array for a substring match

    I think this may help you. I had a similar issue. If your array looks like this:

    var array = ["page1","1973","Jimmy"]; 
    

    You can do a simple "for" loop to return the instance in the array when you get a match.

    var c; 
    for (i = 0; i < array.length; i++) {
    if (array[i].indexOf("page") > -1){ 
    c = i;}
    } 
    

    We create an empty variable, c to host our answer. We then loop through the array to find where the array object (e.g. "page1") matches our indexOf("page"). In this case, it's 0 (the first result)

    Happy to expand if you need further support.

    Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools)

    On Mac OS X Catalina the following worked just fine

    xcode-select --install
    

    After this, a UI prompt showed up and that complete the install of the tools

    Razor View throwing "The name 'model' does not exist in the current context"

    Changing following line in web.config of view folder solved the same error.

    From

     <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.2.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    

    To

    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    

    Write a function that returns the longest palindrome in a given string

    See Wikipedia article on this topic. Sample Manacher's Algorithm Java implementation for linear O(n) solution from the article below:

    import java.util.Arrays; public class ManachersAlgorithm { public static String findLongestPalindrome(String s) { if (s==null || s.length()==0) return "";

    char[] s2 = addBoundaries(s.toCharArray());
    int[] p = new int[s2.length]; 
    int c = 0, r = 0; // Here the first element in s2 has been processed.
    int m = 0, n = 0; // The walking indices to compare if two elements are the same
    for (int i = 1; i<s2.length; i++) {
      if (i>r) {
        p[i] = 0; m = i-1; n = i+1;
      } else {
        int i2 = c*2-i;
        if (p[i2]<(r-i)) {
          p[i] = p[i2];
          m = -1; // This signals bypassing the while loop below. 
        } else {
          p[i] = r-i;
          n = r+1; m = i*2-n;
        }
      }
      while (m>=0 && n<s2.length && s2[m]==s2[n]) {
        p[i]++; m--; n++;
      }
      if ((i+p[i])>r) {
        c = i; r = i+p[i];
      }
    }
    int len = 0; c = 0;
    for (int i = 1; i<s2.length; i++) {
      if (len<p[i]) {
        len = p[i]; c = i;
      }
    }
    char[] ss = Arrays.copyOfRange(s2, c-len, c+len+1);
    return String.valueOf(removeBoundaries(ss));   }
    private static char[] addBoundaries(char[] cs) {
    if (cs==null || cs.length==0)
      return "||".toCharArray();
    
    char[] cs2 = new char[cs.length*2+1];
    for (int i = 0; i<(cs2.length-1); i = i+2) {
      cs2[i] = '|';
      cs2[i+1] = cs[i/2];
    }
    cs2[cs2.length-1] = '|';
    return cs2;   }
    private static char[] removeBoundaries(char[] cs) {
    if (cs==null || cs.length<3)
      return "".toCharArray();
    
    char[] cs2 = new char[(cs.length-1)/2];
    for (int i = 0; i<cs2.length; i++) {
      cs2[i] = cs[i*2+1];
    }
    return cs2;   }     }
    

    How to display a Windows Form in full screen on top of the taskbar?

    My simple fix it turned out to be calling the form's Activate() method, so there's no need to use TopMost (which is what I was aiming at).

    How best to include other scripts?

    You need to specify the location of the other scripts, there is no other way around it. I'd recommend a configurable variable at the top of your script:

    #!/bin/bash
    installpath=/where/your/scripts/are
    
    . $installpath/incl.sh
    
    echo "The main script"
    

    Alternatively, you can insist that the user maintain an environment variable indicating where your program home is at, like PROG_HOME or somesuch. This can be supplied for the user automatically by creating a script with that information in /etc/profile.d/, which will be sourced every time a user logs in.

    Pandas: Appending a row to a dataframe and specify its index label

    I shall refer to the same sample of data as posted in the question:

    import numpy as np
    import pandas as pd
    df = pd.DataFrame(np.random.randn(8, 4), columns=['A','B','C','D'])
    print('The original data frame is: \n{}'.format(df))
    

    Running this code will give you

    The original data frame is:
    
              A         B         C         D
    0  0.494824 -0.328480  0.818117  0.100290
    1  0.239037  0.954912 -0.186825 -0.651935
    2 -1.818285 -0.158856  0.359811 -0.345560
    3 -0.070814 -0.394711  0.081697 -1.178845
    4 -1.638063  1.498027 -0.609325  0.882594
    5 -0.510217  0.500475  1.039466  0.187076
    6  1.116529  0.912380  0.869323  0.119459
    7 -1.046507  0.507299 -0.373432 -1.024795
    

    Now you wish to append a new row to this data frame, which doesn't need to be copy of any other row in the data frame. @Alon suggested an interesting approach to use df.loc to append a new row with different index. The issue, however, with this approach is if there is already a row present at that index, it will be overwritten by new values. This is typically the case for datasets when row index is not unique, like store ID in transaction datasets. So a more general solution to your question is to create the row, transform the new row data into a pandas series, name it to the index you want to have and then append it to the data frame. Don't forget to overwrite the original data frame with the one with appended row. The reason is df.append returns a view of the dataframe and does not modify its contents. Following is the code:

    row = pd.Series({'A':10,'B':20,'C':30,'D':40},name=3)
    df = df.append(row)
    print('The new data frame is: \n{}'.format(df))
    

    Following would be the new output:

    The new data frame is:
    
               A          B          C          D
    0   0.494824  -0.328480   0.818117   0.100290
    1   0.239037   0.954912  -0.186825  -0.651935
    2  -1.818285  -0.158856   0.359811  -0.345560
    3  -0.070814  -0.394711   0.081697  -1.178845
    4  -1.638063   1.498027  -0.609325   0.882594
    5  -0.510217   0.500475   1.039466   0.187076
    6   1.116529   0.912380   0.869323   0.119459
    7  -1.046507   0.507299  -0.373432  -1.024795
    3  10.000000  20.000000  30.000000  40.000000
    

    MySQL DISTINCT on a GROUP_CONCAT()

    DISTINCT: will gives you unique values.

    SELECT GROUP_CONCAT(DISTINCT(categories )) AS categories FROM table
    

    How to get JS variable to retain value after page refresh?

    This is possible with window.localStorage or window.sessionStorage. The difference is that sessionStorage lasts for as long as the browser stays open, localStorage survives past browser restarts. The persistence applies to the entire web site not just a single page of it.

    When you need to set a variable that should be reflected in the next page(s), use:

    var someVarName = "value";
    localStorage.setItem("someVarKey", someVarName);
    

    And in any page (like when the page has loaded), get it like:

    var someVarName = localStorage.getItem("someVarKey");
    

    .getItem() will return null if no value stored, or the value stored.

    Note that only string values can be stored in this storage, but this can be overcome by using JSON.stringify and JSON.parse. Technically, whenever you call .setItem(), it will call .toString() on the value and store that.

    MDN's DOM storage guide (linked below), has workarounds/polyfills, that end up falling back to stuff like cookies, if localStorage isn't available.

    It wouldn't be a bad idea to use an existing, or create your own mini library, that abstracts the ability to save any data type (like object literals, arrays, etc.).


    References:

    OpenCV in Android Studio

    For everyone who felt they want to run away with all the steps and screen shots on the (great!) above answers, this worked for me with android studio 2.2.1:

    1. Create a new project, name it as you want and take the default (minSdkVersion 15 is fine).

    2. Download the zip file from here: https://sourceforge.net/projects/opencvlibrary/files/opencv-android/ (I downloaded 3.2.0 version, but there may be a newer versions).

    3. Unzip the zip file, the best place is in your workspace folder, but it not really matter.

    4. Inside Android Studio, click File->New-> Import Module and navigate to \path_to_your_unzipped_file\OpenCV-android-sdk\sdk\java and hit Ok, then accept all default dialogs.

    5. In the gradle file of your app module, add this to the dependencies block:

       dependencies {
           compile project(':openCVLibraryXYZ')
           //rest of code
       }
      

    Where XYZ is the exact version you downloaded, for example in my case:

        dependencies {
            compile project(':openCVLibrary320')
            //rest of code
        }
    

    document.getElementById().value doesn't set the value

    Your response is almost certainly a string. You need to make sure it gets converted to a number:

    document.getElementById("points").value= new Number(request.responseText);
    

    You might take a closer look at your responseText. It sound like you are getting a string that contains quotes. If you are getting JSON data via AJAX, you might have more consistent results running it through JSON.parse().

    document.getElementById("points").value= new Number(JSON.parse(request.responseText));
    

    NoSQL Use Case Scenarios or WHEN to use NoSQL

    It really is an "it depends" kinda question. Some general points:

    • NoSQL is typically good for unstructured/"schemaless" data - usually, you don't need to explicitly define your schema up front and can just include new fields without any ceremony
    • NoSQL typically favours a denormalised schema due to no support for JOINs per the RDBMS world. So you would usually have a flattened, denormalized representation of your data.
    • Using NoSQL doesn't mean you could lose data. Different DBs have different strategies. e.g. MongoDB - you can essentially choose what level to trade off performance vs potential for data loss - best performance = greater scope for data loss.
    • It's often very easy to scale out NoSQL solutions. Adding more nodes to replicate data to is one way to a) offer more scalability and b) offer more protection against data loss if one node goes down. But again, depends on the NoSQL DB/configuration. NoSQL does not necessarily mean "data loss" like you infer.
    • IMHO, complex/dynamic queries/reporting are best served from an RDBMS. Often the query functionality for a NoSQL DB is limited.
    • It doesn't have to be a 1 or the other choice. My experience has been using RDBMS in conjunction with NoSQL for certain use cases.
    • NoSQL DBs often lack the ability to perform atomic operations across multiple "tables".

    You really need to look at and understand what the various types of NoSQL stores are, and how they go about providing scalability/data security etc. It's difficult to give an across-the-board answer as they really are all different and tackle things differently.

    For MongoDb as an example, check out their Use Cases to see what they suggest as being "well suited" and "less well suited" uses of MongoDb.

    Using Thymeleaf when the value is null

       <p data-th-text ="${#strings.defaultString(yourNullable,'defaultValueIfYourValueIsNull')}"></p>
    

    Handling data in a PHP JSON Object

    You mean something like this?

    <?php
    
    $jsonurl = "http://search.twitter.com/trends.json";
    $json = file_get_contents($jsonurl,0,null,null);
    $json_output = json_decode($json);
    
    foreach ( $json_output->trends as $trend )
    {
        echo "{$trend->name}\n";
    }
    

    Error installing mysql2: Failed to build gem native extension

    This solved my problem once in Windows:

    subst X: "C:\Program files\MySQL\MySQL Server 5.5" 
    gem install mysql2 -v 0.x.x --platform=ruby -- --with-mysql-dir=X: --with-mysql-lib=X:\lib\opt 
    subst X: /D
    

    Best way to work with transactions in MS SQL Server Management Studio

    The easisest thing to do is to wrap your code in a transaction, and then execute each batch of T-SQL code line by line.

    For example,

    Begin Transaction
    
             -Do some T-SQL queries here.
    
    Rollback transaction -- OR commit transaction
    

    If you want to incorporate error handling you can do so by using a TRY...CATCH BLOCK. Should an error occur you can then rollback the tranasction within the catch block.

    For example:

    USE AdventureWorks;
    GO
    BEGIN TRANSACTION;
    
    BEGIN TRY
        -- Generate a constraint violation error.
        DELETE FROM Production.Product
        WHERE ProductID = 980;
    END TRY
    BEGIN CATCH
        SELECT 
            ERROR_NUMBER() AS ErrorNumber
            ,ERROR_SEVERITY() AS ErrorSeverity
            ,ERROR_STATE() AS ErrorState
            ,ERROR_PROCEDURE() AS ErrorProcedure
            ,ERROR_LINE() AS ErrorLine
            ,ERROR_MESSAGE() AS ErrorMessage;
    
        IF @@TRANCOUNT > 0
            ROLLBACK TRANSACTION;
    END CATCH;
    
    IF @@TRANCOUNT > 0
        COMMIT TRANSACTION;
    GO
    

    See the following link for more details.

    http://msdn.microsoft.com/en-us/library/ms175976.aspx

    Hope this helps but please let me know if you need more details.

    How do I convert a String to an InputStream in Java?

    You could use a StringReader and convert the reader to an input stream using the solution in this other stackoverflow post.

    How to replace a hash key with another key

    you can do

    hash.inject({}){|option, (k,v) | option["id"] = v if k == "_id"; option}
    

    This should work for your case!

    Vba macro to copy row from table if value in table meets condition

    Selects are slow and unnescsaary. The following code will be far faster:

    Sub CopyRowsAcross() 
    Dim i As Integer 
    Dim ws1 As Worksheet: Set ws1 = ThisWorkbook.Sheets("Sheet1") 
    Dim ws2 As Worksheet: Set ws2 = ThisWorkbook.Sheets("Sheet2") 
    
    For i = 2 To ws1.Range("B65536").End(xlUp).Row 
        If ws1.Cells(i, 2) = "Your Critera" Then ws1.Rows(i).Copy ws2.Rows(ws2.Cells(ws2.Rows.Count, 2).End(xlUp).Row + 1) 
    Next i 
    End Sub 
    

    PersistentObjectException: detached entity passed to persist thrown by JPA and Hibernate

    If nothing helps and you are still getting this exception, review your equals() methods - and don't include child collection in it. Especially if you have deep structure of embedded collections (e.g. A contains Bs, B contains Cs, etc.).

    In example of Account -> Transactions:

      public class Account {
    
        private Long id;
        private String accountName;
        private Set<Transaction> transactions;
    
        @Override
        public boolean equals(Object obj) {
          if (this == obj)
            return true;
          if (obj == null)
            return false;
          if (!(obj instanceof Account))
            return false;
          Account other = (Account) obj;
          return Objects.equals(this.id, other.id)
              && Objects.equals(this.accountName, other.accountName)
              && Objects.equals(this.transactions, other.transactions); // <--- REMOVE THIS!
        }
      }
    

    In above example remove transactions from equals() checks. This is because hibernate will imply that you are not trying to update old object, but you pass a new object to persist, whenever you change element on the child collection.
    Of course this solutions will not fit all applications and you should carefully design what you want to include in the equals and hashCode methods.

    How to remove commits from a pull request

    You have several techniques to do it.

    This post - read the part about the revert will explain in details what we want to do and how to do it.

    Here is the most simple solution to your problem:

    # Checkout the desired branch
    git checkout <branch>
    
    # Undo the desired commit
    git revert <commit>
    
    # Update the remote with the undo of the code
    git push origin <branch>
    

    The revert command will create a new commit with the undo of the original commit.

    Mail multipart/alternative vs multipart/mixed

    Here is the best: Multipart/mixed mime message with attachments and inline images

    And image: https://www.qcode.co.uk/images/mime-nesting-structure.png

    From: [email protected]
    To: to@@qcode.co.uk
    Subject: Example Email
    MIME-Version: 1.0
    Content-Type: multipart/mixed; boundary="MixedBoundaryString"
    
    --MixedBoundaryString
    Content-Type: multipart/related; boundary="RelatedBoundaryString"
    
    --RelatedBoundaryString
    Content-Type: multipart/alternative; boundary="AlternativeBoundaryString"
    
    --AlternativeBoundaryString
    Content-Type: text/plain;charset="utf-8"
    Content-Transfer-Encoding: quoted-printable
    
    This is the plain text part of the email.
    
    --AlternativeBoundaryString
    Content-Type: text/html;charset="utf-8"
    Content-Transfer-Encoding: quoted-printable
    
    <html>
      <body>=0D
        <img src=3D=22cid:masthead.png=40qcode.co.uk=22 width 800 height=3D80=
     =5C>=0D
        <p>This is the html part of the email.</p>=0D
        <img src=3D=22cid:logo.png=40qcode.co.uk=22 width 200 height=3D60 =5C=
    >=0D
      </body>=0D
    </html>=0D
    
    --AlternativeBoundaryString--
    
    --RelatedBoundaryString
    Content-Type: image/jpgeg;name="logo.png"
    Content-Transfer-Encoding: base64
    Content-Disposition: inline;filename="logo.png"
    Content-ID: <[email protected]>
    
    amtsb2hiaXVvbHJueXZzNXQ2XHVmdGd5d2VoYmFmaGpremxidTh2b2hydHVqd255aHVpbnRyZnhu
    dWkgb2l1b3NydGhpdXRvZ2hqdWlyb2h5dWd0aXJlaHN1aWhndXNpaHhidnVqZmtkeG5qaG5iZ3Vy
    ...
    ...
    a25qbW9nNXRwbF0nemVycHpvemlnc3k5aDZqcm9wdHo7amlodDhpOTA4N3U5Nnkwb2tqMm9sd3An
    LGZ2cDBbZWRzcm85eWo1Zmtsc2xrZ3g=
    
    --RelatedBoundaryString
    Content-Type: image/jpgeg;name="masthead.png"
    Content-Transfer-Encoding: base64
    Content-Disposition: inline;filename="masthead.png"
    Content-ID: <[email protected]>
    
    aXR4ZGh5Yjd1OHk3MzQ4eXFndzhpYW9wO2tibHB6c2tqOTgwNXE0aW9qYWJ6aXBqOTBpcjl2MC1t
    dGlmOTA0cW05dGkwbWk0OXQwYVttaXZvcnBhXGtsbGo7emt2c2pkZnI7Z2lwb2F1amdpNTh1NDlh
    ...
    ...
    eXN6dWdoeXhiNzhuZzdnaHQ3eW9zemlqb2FqZWt0cmZ1eXZnamhka3JmdDg3aXV2dWd5aGVidXdz
    dhyuhehe76YTGSFGA=
    
    --RelatedBoundaryString--
    
    --MixedBoundaryString
    Content-Type: application/pdf;name="Invoice_1.pdf"
    Content-Transfer-Encoding: base64
    Content-Disposition: attachment;filename="Invoice_1.pdf"
    
    aGZqZGtsZ3poZHVpeWZoemd2dXNoamRibngganZodWpyYWRuIHVqO0hmSjtyRVVPIEZSO05SVURF
    SEx1aWhudWpoZ3h1XGh1c2loZWRma25kamlsXHpodXZpZmhkcnVsaGpnZmtsaGVqZ2xod2plZmdq
    ...
    ...
    a2psajY1ZWxqanNveHV5ZXJ3NTQzYXRnZnJhZXdhcmV0eXRia2xhanNueXVpNjRvNWllc3l1c2lw
    dWg4NTA0
    
    --MixedBoundaryString
    Content-Type: application/pdf;name="SpecialOffer.pdf"
    Content-Transfer-Encoding: base64
    Content-Disposition: attachment;filename="SpecialOffer.pdf"
    
    aXBvY21odWl0dnI1dWk4OXdzNHU5NTgwcDN3YTt1OTQwc3U4NTk1dTg0dTV5OGlncHE1dW4zOTgw
    cS0zNHU4NTk0eWI4OTcwdjg5MHE4cHV0O3BvYTt6dWI7dWlvenZ1em9pdW51dDlvdTg5YnE4N3Z3
    ...
    ...
    OTViOHk5cDV3dTh5bnB3dWZ2OHQ5dTh2cHVpO2p2Ymd1eTg5MGg3ajY4bjZ2ODl1ZGlvcjQ1amts
    dfnhgjdfihn=
    
    --MixedBoundaryString--
    
    .
    

    Schema multipart/related/alternative

    Header
    |From: email
    |To: email
    |MIME-Version: 1.0
    |Content-Type: multipart/mixed; boundary="boundary1";
    Message body
    |multipart/mixed --boundary1
    |--boundary1
    |   multipart/related --boundary2
    |   |--boundary2
    |   |   multipart/alternative --boundary3
    |   |   |--boundary3
    |   |   |text/plain
    |   |   |--boundary3
    |   |   |text/html
    |   |   |--boundary3--
    |   |--boundary2    
    |   |Inline image
    |   |--boundary2    
    |   |Inline image
    |   |--boundary2--
    |--boundary1    
    |Attachment1
    |--boundary1
    |Attachment2
    |--boundary1
    |Attachment3
    |--boundary1--
    |
    .
    

    Difference between \w and \b regular expression meta characters

    \w is not a word boundary, it matches any word character, including underscores: [a-zA-Z0-9_]. \b is a word boundary, that is, it matches the position between a word and a non-alphanumeric character: \W or [^\w].

    These implementations may vary from language to language though.

    %i or %d to print integer in C using printf()?

    both %d and %i can be used to print an integer

    %d stands for "decimal", and %i for "integer." You can use %x to print in hexadecimal, and %o to print in octal.

    You can use %i as a synonym for %d, if you prefer to indicate "integer" instead of "decimal."

    On input, using scanf(), you can use use both %i and %d as well. %i means parse it as an integer in any base (octal, hexadecimal, or decimal, as indicated by a 0 or 0x prefix), while %d means parse it as a decimal integer.

    check here for more explanation

    why does %d stand for Integer?

    How can I schedule a job to run a SQL query daily?

    Here's a sample code:

    Exec sp_add_schedule
        @schedule_name = N'SchedulName' 
        @freq_type = 1
        @active_start_time = 08300
    

    Send HTML in email via PHP

    Sending an html email is not much different from sending normal emails using php. What is necessary to add is the content type along the header parameter of the php mail() function. Here is an example.

    <?php
        $to = "[email protected]";
        $subject = "HTML email";
        $message = "
        <html>
        <head>
        <title>HTML email</title>
        </head>
        <body>
        <p>A table as email</p>
        <table>
        <tr>
        <th>Firstname</th>
        <th>Lastname</th>
        </tr>
        <tr>
        <td>Fname</td>
        <td>Sname</td>
        </tr>
        </table>
        </body>
        </html>
        ";
        // Always set content-type when sending HTML email
        $headers = "MIME-Version: 1.0" . "\r\n";
        $headers .= "Content-type:text/html;charset=UTF-8" . "\r\b";
        $headers .= 'From: name' . "\r\n";
        mail($to,$subject,$message,$headers);
    ?>
    

    You can also check here for more detailed explanations by w3schools

    How to determine a user's IP address in node

    Had the same problem...im also new at javascript but i solved this with req.connection.remoteAddress; that gave me th IP address (but in ipv6 format ::ffff.192.168.0.101 ) and then .slice to remove the 7 first digits.

    var ip = req.connection.remoteAddress;
    
    if (ip.length < 15) 
    {   
       ip = ip;
    }
    else
    {
       var nyIP = ip.slice(7);
       ip = nyIP;
    }
    

    How to update a value in a json file and save it through node.js

    //change the value in the in-memory object
    content.val1 = 42;
    //Serialize as JSON and Write it to a file
    fs.writeFileSync(filename, JSON.stringify(content));
    

    Removing NA in dplyr pipe

    I don't think desc takes an na.rm argument... I'm actually surprised it doesn't throw an error when you give it one. If you just want to remove NAs, use na.omit (base) or tidyr::drop_na:

    outcome.df %>%
      na.omit() %>%
      group_by(Hospital, State) %>%
      arrange(desc(HeartAttackDeath)) %>%
      head()
    
    library(tidyr)
    outcome.df %>%
      drop_na() %>%
      group_by(Hospital, State) %>%
      arrange(desc(HeartAttackDeath)) %>%
      head()
    

    If you only want to remove NAs from the HeartAttackDeath column, filter with is.na, or use tidyr::drop_na:

    outcome.df %>%
      filter(!is.na(HeartAttackDeath)) %>%
      group_by(Hospital, State) %>%
      arrange(desc(HeartAttackDeath)) %>%
      head()
    
    outcome.df %>%
      drop_na(HeartAttackDeath) %>%
      group_by(Hospital, State) %>%
      arrange(desc(HeartAttackDeath)) %>%
      head()
    

    As pointed out at the dupe, complete.cases can also be used, but it's a bit trickier to put in a chain because it takes a data frame as an argument but returns an index vector. So you could use it like this:

    outcome.df %>%
      filter(complete.cases(.)) %>%
      group_by(Hospital, State) %>%
      arrange(desc(HeartAttackDeath)) %>%
      head()
    

    Use xml.etree.ElementTree to print nicely formatted xml files

    You can use the function toprettyxml() from xml.dom.minidom in order to do that:

    def prettify(elem):
        """Return a pretty-printed XML string for the Element.
        """
        rough_string = ElementTree.tostring(elem, 'utf-8')
        reparsed = minidom.parseString(rough_string)
        return reparsed.toprettyxml(indent="\t")
    

    The idea is to print your Element in a string, parse it using minidom and convert it again in XML using the toprettyxml function.

    Source: http://pymotw.com/2/xml/etree/ElementTree/create.html

    error: command 'gcc' failed with exit status 1 while installing eventlet

    If it is still not working, you can try this

    sudo apt-get install build-essential
    

    in my case, it solved the problem.

    What is the best way to convert an array to a hash in Ruby

    If the numeric values are seq indexes, then we could have simpler ways... Here's my code submission, My Ruby is a bit rusty

       input = ["cat", 1, "dog", 2, "wombat", 3]
       hash = Hash.new
       input.each_with_index {|item, index|
         if (index%2 == 0) hash[item] = input[index+1]
       }
       hash   #=> {"cat"=>1, "wombat"=>3, "dog"=>2}
    

    Difference between Hashing a Password and Encrypting it

    Hashing is a one way function (well, a mapping). It's irreversible, you apply the secure hash algorithm and you cannot get the original string back. The most you can do is to generate what's called "a collision", that is, finding a different string that provides the same hash. Cryptographically secure hash algorithms are designed to prevent the occurrence of collisions. You can attack a secure hash by the use of a rainbow table, which you can counteract by applying a salt to the hash before storing it.

    Encrypting is a proper (two way) function. It's reversible, you can decrypt the mangled string to get original string if you have the key.

    The unsafe functionality it's referring to is that if you encrypt the passwords, your application has the key stored somewhere and an attacker who gets access to your database (and/or code) can get the original passwords by getting both the key and the encrypted text, whereas with a hash it's impossible.

    People usually say that if a cracker owns your database or your code he doesn't need a password, thus the difference is moot. This is naïve, because you still have the duty to protect your users' passwords, mainly because most of them do use the same password over and over again, exposing them to a greater risk by leaking their passwords.

    How to add a new column to an existing sheet and name it?

    Use insert method from range, for example

    Sub InsertColumn()
            Columns("C:C").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
            Range("C1").Value = "Loc"
    End Sub
    

    SOAP-ERROR: Parsing WSDL: Couldn't load from - but works on WAMP

    I might have read all questions about this for two days. None of the answers worked for me.

    In my case I was lacking cURL module for PHP.

    Be aware that, just because you can use cURL on terminal, it does not mean that you have PHP cURL module and it is active. There was no error showing about it. Not even on /var/log/apache2/error.log

    How to install module: (replace version number for the apropiated one)

    sudo apt install php7.2-curl
    sudo service apache2 reload
    

    Difference between add(), replace(), and addToBackStack()

    Example an activity have 2 fragments and we use FragmentManager to replace/add with addToBackstack each fragment to a layout in activity

    Use replace

    Go Fragment1

    Fragment1: onAttach
    Fragment1: onCreate
    Fragment1: onCreateView
    Fragment1: onActivityCreated
    Fragment1: onStart
    Fragment1: onResume
    

    Go Fragment2

    Fragment2: onAttach
    Fragment2: onCreate
    Fragment1: onPause
    Fragment1: onStop
    Fragment1: onDestroyView
    Fragment2: onCreateView
    Fragment2: onActivityCreated
    Fragment2: onStart
    Fragment2: onResume
    

    Pop Fragment2

    Fragment2: onPause
    Fragment2: onStop
    Fragment2: onDestroyView
    Fragment2: onDestroy
    Fragment2: onDetach
    Fragment1: onCreateView
    Fragment1: onStart
    Fragment1: onResume
    

    Pop Fragment1

    Fragment1: onPause
    Fragment1: onStop
    Fragment1: onDestroyView
    Fragment1: onDestroy
    Fragment1: onDetach
    

    Use add

    Go Fragment1

    Fragment1: onAttach
    Fragment1: onCreate
    Fragment1: onCreateView
    Fragment1: onActivityCreated
    Fragment1: onStart
    Fragment1: onResume
    

    Go Fragment2

    Fragment2: onAttach
    Fragment2: onCreate
    Fragment2: onCreateView
    Fragment2: onActivityCreated
    Fragment2: onStart
    Fragment2: onResume
    

    Pop Fragment2

    Fragment2: onPause
    Fragment2: onStop
    Fragment2: onDestroyView
    Fragment2: onDestroy
    Fragment2: onDetach
    

    Pop Fragment1

    Fragment1: onPause
    Fragment1: onStop
    Fragment1: onDestroyView
    Fragment1: onDestroy
    Fragment1: onDetach
    

    Sample project

    Passing data between different controller action methods

    Personally I don't like to use TempData, but I prefer to pass a strongly typed object as explained in Passing Information Between Controllers in ASP.Net-MVC.

    You should always find a way to make it explicit and expected.

    Package Manager Console Enable-Migrations CommandNotFoundException only in a specific VS project

    I had the same issue and I tried most of the solution provided by other folks but it worked for me with below steps. I have VS 2017.

    Steps:

    Install-Package EntityFramework -IncludePrerelease
    

    then create a class as

    public class MyDBContext : DbContext { public MyDBContext() { } }
    

    and at the last execute

    Enable-Migrations -EnableAutomaticMigrations
    

    What didn't work for me:

    : Restarting VS.

    : only "Enable-Migrations" command, which is without -EnableAutomaticMigrations.

    : restoring or updating Nuget Package Manager.

    My original error in the beginning was

    /* The term 'enable-migration' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.At line:1 char:1 + enable-migration + ~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (enable-migration:String) [], CommandNotFoundException */

    PHP - Indirect modification of overloaded property

    Nice you gave me something to play around with

    Run

    class Sample extends Creator {
    
    }
    
    $a = new Sample ();
    $a->role->rolename = 'test';
    echo  $a->role->rolename , PHP_EOL;
    $a->role->rolename->am->love->php = 'w00';
    echo  $a->role->rolename  , PHP_EOL;
    echo  $a->role->rolename->am->love->php   , PHP_EOL;
    

    Output

    test
    test
    w00
    

    Class Used

    abstract class Creator {
        public function __get($name) {
            if (! isset ( $this->{$name} )) {
                $this->{$name} = new Value ( $name, null );
            }
            return $this->{$name};
        }
    
        public function __set($name, $value) {
            $this->{$name} = new Value ( $name, $value );
        }
    
    
    
    }
    
    class Value extends Creator {
        private $name;
        private $value;
        function __construct($name, $value) {
            $this->name = $name;
            $this->value = $value;
        }
    
        function __toString()
        {
            return (string) $this->value ;
        }
    }      
    

    Edit : New Array Support as requested

    class Sample extends Creator {
    
    }
    
    $a = new Sample ();
    $a->role = array (
            "A",
            "B",
            "C" 
    );
    
    
    $a->role[0]->nice = "OK" ;
    
    print ($a->role[0]->nice  . PHP_EOL);
    
    $a->role[1]->nice->ok = array("foo","bar","die");
    
    print ($a->role[1]->nice->ok[2]  . PHP_EOL);
    
    
    $a->role[2]->nice->raw = new stdClass();
    $a->role[2]->nice->raw->name = "baba" ;
    
    print ($a->role[2]->nice->raw->name. PHP_EOL);
    

    Output

     Ok die baba
    

    Modified Class

    abstract class Creator {
        public function __get($name) {
            if (! isset ( $this->{$name} )) {
                $this->{$name} = new Value ( $name, null );
            }
            return $this->{$name};
        }
    
        public function __set($name, $value) {
            if (is_array ( $value )) {
                array_walk ( $value, function (&$item, $key) {
                    $item = new Value ( $key, $item );
                } );
            }
            $this->{$name} = $value;
    
        }
    
    }
    
    class Value {
        private $name ;
        function __construct($name, $value) {
            $this->{$name} = $value;
            $this->name = $value ;
        }
    
        public function __get($name) {
            if (! isset ( $this->{$name} )) {
                $this->{$name} = new Value ( $name, null );
            }
    
            if ($name == $this->name) {
                return $this->value;
            }
    
            return $this->{$name};
        }
    
        public function __set($name, $value) {
            if (is_array ( $value )) {
                array_walk ( $value, function (&$item, $key) {
                    $item = new Value ( $key, $item );
                } );
            }
            $this->{$name} = $value;
        }
    
        public function __toString() {
            return (string) $this->name ;
        }   
    }
    

    How to add Web API to an existing ASP.NET MVC 4 Web Application project?

    I had same problem, the solution was so easy

    Right click on solotion install Microsoft.ASP.NET.WebApi from "Manage Nuget Package for Sulotion"

    boom that's it ;)

    Why does an image captured using camera intent gets rotated on some devices on Android?

    Better try to take the picture in a specific orientation.

    android:screenOrientation="landscape"
    android:configChanges="orientation|keyboardHidden"
    

    For best results give landscape orientation in the cameraview activity.

    Function not defined javascript

    important: in this kind of error you should look for simple mistakes in most cases

    besides syntax error, I should say once I had same problem and it was because of bad name I have chosen for function. I have never searched for the reason but I remember that I copied another function and change it to use. I add "1" after the name to changed the function name and I got this error.

    Where do I find some good examples for DDD?

    Not source projects per say but I stumbled upon Parleys.com which has a few good videos that cover DDD quite well (requires flash):

    I found these much more helpful than the almost non-existent DDD examples that are currently available.

    How to read/write arbitrary bits in C/C++

    If you keep grabbing bits from your data, you might want to use a bitfield. You'll just have to set up a struct and load it with only ones and zeroes:

    struct bitfield{
        unsigned int bit : 1
    }
    struct bitfield *bitstream;
    

    then later on load it like this (replacing char with int or whatever data you are loading):

    long int i;
    int j, k;
    unsigned char c, d;
    
    bitstream=malloc(sizeof(struct bitfield)*charstreamlength*sizeof(char));
    for (i=0; i<charstreamlength; i++){
        c=charstream[i];
        for(j=0; j < sizeof(char)*8; j++){
            d=c;
            d=d>>(sizeof(char)*8-j-1);
            d=d<<(sizeof(char)*8-1);
            k=d;
            if(k==0){
                bitstream[sizeof(char)*8*i + j].bit=0;
            }else{
                bitstream[sizeof(char)*8*i + j].bit=1;
            }
        }
    }
    

    Then access elements:

    bitstream[bitpointer].bit=...
    

    or

    ...=bitstream[bitpointer].bit
    

    All of this is assuming are working on i86/64, not arm, since arm can be big or little endian.

    The forked VM terminated without saying properly goodbye. VM crash or System.exit called

    I had the same problem and solved by adding:

    <argLine>-Xmx1024m -XX:MaxPermSize=256m</argLine>
    

    The whole plugin element is:

    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-surefire-plugin</artifactId>
      <configuration>
        <forkCount>3</forkCount>
        <reuseForks>true</reuseForks>
        <argLine>-Xmx1024m -XX:MaxPermSize=256m</argLine>
      </configuration>
    </plugin>
    

    How can I recognize touch events using jQuery in Safari for iPad? Is it possible?

    I was a little bit worried about using only touchmove for my project, since it only seems to fire when your touch moves from one location to another (and not on the initial touch). So I combined it with touchstart, and this seems to work very well for the initial touch and any movements.

    <script>
    
    function doTouch(e) {
        e.preventDefault();
        var touch = e.touches[0];
    
        document.getElementById("xtext").innerHTML = touch.pageX;
        document.getElementById("ytext").innerHTML = touch.pageY;   
    }
    
    document.addEventListener('touchstart', function(e) {doTouch(e);}, false);
    document.addEventListener('touchmove', function(e) {doTouch(e);}, false);
    
    </script>
    
    X: <div id="xtext">0</div>
    Y: <div id="ytext">0</div>
    

    git: fatal unable to auto-detect email address

    Had similar problem, I'm fairly new so take this with a grain of salt but I needed to go up a directory first, set the username, then go back down to git repository.

    cd ..    
    git config --global user.email "[email protected]"
    git config --global user.name "your_name"
    cd <your repository folder>
    

    Hope this helps anyone else that gets stuck

    How do I consume the JSON POST data in an Express application

    I think you're conflating the use of the response object with that of the request.

    The response object is for sending the HTTP response back to the calling client, whereas you are wanting to access the body of the request. See this answer which provides some guidance.

    If you are using valid JSON and are POSTing it with Content-Type: application/json, then you can use the bodyParser middleware to parse the request body and place the result in request.body of your route.

    For earlier versions of Express (< 4)

    var express = require('express')
      , app = express.createServer();
    
    app.use(express.bodyParser());
    
    app.post('/', function(request, response){
      console.log(request.body);      // your JSON
      response.send(request.body);    // echo the result back
    });
    
    app.listen(3000);
    

    Test along the lines of:

    $ curl -d '{"MyKey":"My Value"}' -H "Content-Type: application/json" http://127.0.0.1:3000/
    {"MyKey":"My Value"}
    

    Updated for Express 4+

    Body parser was split out into it's own npm package after v4, requires a separate install npm install body-parser

    var express = require('express')
      , bodyParser = require('body-parser');
    
    var app = express();
    
    app.use(bodyParser.json());
    
    app.post('/', function(request, response){
      console.log(request.body);      // your JSON
       response.send(request.body);    // echo the result back
    });
    
    app.listen(3000);
    

    Update for Express 4.16+

    Starting with release 4.16.0, a new express.json() middleware is available.

    var express = require('express');
    
    var app = express();
    
    app.use(express.json());
    
    app.post('/', function(request, response){
      console.log(request.body);      // your JSON
       response.send(request.body);    // echo the result back
    });
    
    app.listen(3000);
    

    Plotting 4 curves in a single plot, with 3 y-axes

    PLOTYY allows two different y-axes. Or you might look into LayerPlot from the File Exchange. I guess I should ask if you've considered using HOLD or just rescaling the data and using regular old plot?

    OLD, not what the OP was looking for: SUBPLOT allows you to break a figure window into multiple axes. Then if you want to have only one x-axis showing, or some other customization, you can manipulate each axis independently.

    how to rotate a bitmap 90 degrees

    Short extension for Kotlin

    fun Bitmap.rotate(degrees: Float): Bitmap {
        val matrix = Matrix().apply { postRotate(degrees) }
        return Bitmap.createBitmap(this, 0, 0, width, height, matrix, true)
    }
    

    And usage:

    val rotatedBitmap = bitmap.rotate(90f)
    

    How can I format decimal property to currency?

    A decimal type can not contain formatting information. You can create another property, say FormattedProperty of a string type that does what you want.

    Java - Writing strings to a CSV file

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.PrintWriter;
    
    public class CsvFile {
    
        public static void main(String[]args){
            PrintWriter pw = null;
            try {
                pw = new PrintWriter(new File("NewData.csv"));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            StringBuilder builder = new StringBuilder();
            String columnNamesList = "Id,Name";
            // No need give the headers Like: id, Name on builder.append
            builder.append(columnNamesList +"\n");
            builder.append("1"+",");
            builder.append("Chola");
            builder.append('\n');
            pw.write(builder.toString());
            pw.close();
            System.out.println("done!");
        }
    }
    

    Why not inherit from List<T>?

    Does allowing people to say

    myTeam.subList(3, 5);
    

    make any sense at all? If not then it shouldn't be a List.

    Java out.println() how is this possible?

    You will have to create an object out first. More about this here:

        // write to stdout
        out = System.out;
        out.println("Test 1");
        out.close();
    

    Can you do a For Each Row loop using MySQL?

    Not a for each exactly, but you can do nested SQL

    SELECT 
        distinct a.ID, 
        a.col2, 
        (SELECT 
            SUM(b.size) 
        FROM 
            tableb b 
        WHERE 
            b.id = a.col3)
    FROM
        tablea a
    

    node.js vs. meteor.js what's the difference?

    A loose analogy is, "Meteor is to Node as Rails is to Ruby." It's a large, opinionated framework that uses Node on the server. Node itself is just a low-level framework providing functions for sending and receiving HTTP requests and performing other I/O.

    Meteor is radically ambitious: By default, every page it serves is actually a Handlebars template that's kept in sync with the server. Try the Leaderboard example: You create a template that simply says "List the names and scores," and every time any client changes a name or score, the page updates with the new data—not just for that client, but for everyone viewing the page.

    Another difference: While Node itself is stable and widely used in production, Meteor is in a "preview" state. There are serious bugs, and certain things that don't fit with Meteor's data-centric conceptual model (such as animations) are very hard to do.

    If you love playing with new technologies, give Meteor a spin. If you want a more traditional, stable web framework built on Node, take a look at Express.

    How do I check if there are duplicates in a flat list?

    Recommended for short lists only:

    any(thelist.count(x) > 1 for x in thelist)
    

    Do not use on a long list -- it can take time proportional to the square of the number of items in the list!

    For longer lists with hashable items (strings, numbers, &c):

    def anydup(thelist):
      seen = set()
      for x in thelist:
        if x in seen: return True
        seen.add(x)
      return False
    

    If your items are not hashable (sublists, dicts, etc) it gets hairier, though it may still be possible to get O(N logN) if they're at least comparable. But you need to know or test the characteristics of the items (hashable or not, comparable or not) to get the best performance you can -- O(N) for hashables, O(N log N) for non-hashable comparables, otherwise it's down to O(N squared) and there's nothing one can do about it:-(.

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

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

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

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

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

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

    jQuery .each() index?

    $('#list option').each(function(intIndex){
    //do stuff
    });
    

    Select all elements with a "data-xxx" attribute without using jQuery

    document.querySelectorAll('data-foo')
    

    to get list of all elements having attribute data-foo

    If you want to get element with data attribute which is having some specific value e.g

    <div data-foo="1"></div>
    <div data-foo="2" ></div>
    

    and I want to get div with data-foo set to "2"

    document.querySelector('[data-foo="2"]')
    

    But here comes the twist what if I want to match the data attirubte value with some variable's value like I want to get element if data-foo attribute is set to i

    var i=2;
    

    so you can dynamically select the element having specific data element using template literals

    document.querySelector(`[data-foo="${i}"]`)
    

    Note even if you don't write value in string it gets converted to string like if I write

    <div data-foo=1></div>
    

    and then inspect the element in Chrome developer tool the element will be shown as below

    <div data-foo="1"></div>
    

    You can also cross verify by writing below code in console

    console.log(typeof document.querySelector(`[data-foo]="${i}"`).dataset('dataFoo'))
    

    why I have written 'dataFoo' though the attribute is data-foo reason dataset properties are converted to camelCase properties

    I have referred below links

    https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/data-* https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes

    This is my first answer on stackoverflow please let me know how can I improve my answer writing way.

    Differences between INDEX, PRIMARY, UNIQUE, FULLTEXT in MySQL?

    Differences

    • KEY or INDEX refers to a normal non-unique index. Non-distinct values for the index are allowed, so the index may contain rows with identical values in all columns of the index. These indexes don't enforce any restraints on your data so they are used only for access - for quickly reaching certain ranges of records without scanning all records.

    • UNIQUE refers to an index where all rows of the index must be unique. That is, the same row may not have identical non-NULL values for all columns in this index as another row. As well as being used to quickly reach certain record ranges, UNIQUE indexes can be used to enforce restraints on data, because the database system does not allow the distinct values rule to be broken when inserting or updating data.

      Your database system may allow a UNIQUE index to be applied to columns which allow NULL values, in which case two rows are allowed to be identical if they both contain a NULL value (the rationale here is that NULL is considered not equal to itself). Depending on your application, however, you may find this undesirable: if you wish to prevent this, you should disallow NULL values in the relevant columns.

    • PRIMARY acts exactly like a UNIQUE index, except that it is always named 'PRIMARY', and there may be only one on a table (and there should always be one; though some database systems don't enforce this). A PRIMARY index is intended as a primary means to uniquely identify any row in the table, so unlike UNIQUE it should not be used on any columns which allow NULL values. Your PRIMARY index should be on the smallest number of columns that are sufficient to uniquely identify a row. Often, this is just one column containing a unique auto-incremented number, but if there is anything else that can uniquely identify a row, such as "countrycode" in a list of countries, you can use that instead.

      Some database systems (such as MySQL's InnoDB) will store a table's records on disk in the order in which they appear in the PRIMARY index.

    • FULLTEXT indexes are different from all of the above, and their behaviour differs significantly between database systems. FULLTEXT indexes are only useful for full text searches done with the MATCH() / AGAINST() clause, unlike the above three - which are typically implemented internally using b-trees (allowing for selecting, sorting or ranges starting from left most column) or hash tables (allowing for selection starting from left most column).

      Where the other index types are general-purpose, a FULLTEXT index is specialised, in that it serves a narrow purpose: it's only used for a "full text search" feature.

    Similarities

    • All of these indexes may have more than one column in them.

    • With the exception of FULLTEXT, the column order is significant: for the index to be useful in a query, the query must use columns from the index starting from the left - it can't use just the second, third or fourth part of an index, unless it is also using the previous columns in the index to match static values. (For a FULLTEXT index to be useful to a query, the query must use all columns of the index.)

    How long will my session last?

    You're searching for gc_maxlifetime, see http://php.net/manual/en/session.configuration.php#ini.session.gc-maxlifetime for a description.

    Your session will last 1440 seconds which is 24 minutes (default).

    Checkout multiple git repos into same Jenkins workspace

    I used the Multiple SCMs Plugin in conjunction with the Git Plugin successfully with Jenkins.

    How to split string and push in array using jquery

    var string = 'a,b,c,d',
        strx   = string.split(',');
        array  = [];
    
    array = array.concat(strx);
    // ["a","b","c","d"]
    

    MySQL Trigger: Delete From Table AFTER DELETE

    create trigger doct_trigger
    after delete on doctor
    for each row
    delete from patient where patient.PrimaryDoctor_SSN=doctor.SSN ;
    

    Real time face detection OpenCV, Python

    Your line:

    img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

    will draw a rectangle in the image, but the return value will be None, so img changes to None and cannot be drawn.

    Try

    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

    How do I include a JavaScript script file in Angular and call a function from that script?

    Add external js file in index.html.

    <script src="./assets/vendors/myjs.js"></script>
    

    Here's myjs.js file :

    var myExtObject = (function() {
    
        return {
          func1: function() {
            alert('function 1 called');
          },
          func2: function() {
            alert('function 2 called');
          }
        }
    
    })(myExtObject||{})
    
    
    var webGlObject = (function() { 
        return { 
          init: function() { 
            alert('webGlObject initialized');
          } 
        } 
    })(webGlObject||{})
    

    Then declare it is in component like below

    demo.component.ts

    declare var myExtObject: any;
    declare var webGlObject: any;
    
    constructor(){
        webGlObject.init();
    }
    
    callFunction1() {
        myExtObject.func1();
    }
    
    callFunction2() {
        myExtObject.func2();
    }
    

    demo.component.html

    <div>
        <p>click below buttons for function call</p>
        <button (click)="callFunction1()">Call Function 1</button>
        <button (click)="callFunction2()">Call Function 2</button>
    </div>
    

    It's working for me...

    Differences between time complexity and space complexity?

    The way in which the amount of storage space required by an algorithm varies with the size of the problem it is solving. Space complexity is normally expressed as an order of magnitude, e.g. O(N^2) means that if the size of the problem (N) doubles then four times as much working storage will be needed.

    Angular2 *ngIf check object array length in template

    This article helped me alot figuring out why it wasn't working for me either. It give me a lesson to think of the webpage loading and how angular 2 interacts as a timeline and not just the point in time i'm thinking of. I didn't see anyone else mention this point, so I will...

    The reason the *ngIf is needed because it will try to check the length of that variable before the rest of the OnInit stuff happens, and throw the "length undefined" error. So thats why you add the ? because it won't exist yet, but it will soon.

    List all files and directories in a directory + subdirectories

    Create List Of String

        public static List<string> HTMLFiles = new List<string>();
    
     private void Form1_Load(object sender, EventArgs e)
            {
    
         HTMLFiles.AddRange(Directory.GetFiles(@"C:\DataBase", "*.txt"));
                foreach (var item in HTMLFiles)
                {
                    MessageBox.Show(item);
                }
    
    }
    

    How can I use LEFT & RIGHT Functions in SQL to get last 3 characters?

    SELECT  RIGHT(RTRIM(column), 3),
            LEFT(column, LEN(column) - 3)
    FROM    table
    

    Use RIGHT w/ RTRIM (to avoid complications with a fixed-length column), and LEFT coupled with LEN (to only grab what you need, exempt of the last 3 characters).

    if there's ever a situation where the length is <= 3, then you're probably going to have to use a CASE statement so the LEFT call doesn't get greedy.

    Base64 decode snippet in C++

    Here's my modification of the implementation that was originally written by René Nyffenegger. And why have I modified it? Well, because it didn't seem appropriate to me that I should work with binary data stored within std::string object ;)

    base64.h:

    #ifndef _BASE64_H_
    #define _BASE64_H_
    
    #include <vector>
    #include <string>
    typedef unsigned char BYTE;
    
    std::string base64_encode(BYTE const* buf, unsigned int bufLen);
    std::vector<BYTE> base64_decode(std::string const&);
    
    #endif
    

    base64.cpp:

    #include "base64.h"
    #include <iostream>
    
    static const std::string base64_chars =
                 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                 "abcdefghijklmnopqrstuvwxyz"
                 "0123456789+/";
    
    
    static inline bool is_base64(BYTE c) {
      return (isalnum(c) || (c == '+') || (c == '/'));
    }
    
    std::string base64_encode(BYTE const* buf, unsigned int bufLen) {
      std::string ret;
      int i = 0;
      int j = 0;
      BYTE char_array_3[3];
      BYTE char_array_4[4];
    
      while (bufLen--) {
        char_array_3[i++] = *(buf++);
        if (i == 3) {
          char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
          char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
          char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
          char_array_4[3] = char_array_3[2] & 0x3f;
    
          for(i = 0; (i <4) ; i++)
            ret += base64_chars[char_array_4[i]];
          i = 0;
        }
      }
    
      if (i)
      {
        for(j = i; j < 3; j++)
          char_array_3[j] = '\0';
    
        char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
        char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
        char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
        char_array_4[3] = char_array_3[2] & 0x3f;
    
        for (j = 0; (j < i + 1); j++)
          ret += base64_chars[char_array_4[j]];
    
        while((i++ < 3))
          ret += '=';
      }
    
      return ret;
    }
    
    std::vector<BYTE> base64_decode(std::string const& encoded_string) {
      int in_len = encoded_string.size();
      int i = 0;
      int j = 0;
      int in_ = 0;
      BYTE char_array_4[4], char_array_3[3];
      std::vector<BYTE> ret;
    
      while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
        char_array_4[i++] = encoded_string[in_]; in_++;
        if (i ==4) {
          for (i = 0; i <4; i++)
            char_array_4[i] = base64_chars.find(char_array_4[i]);
    
          char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
          char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
          char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
    
          for (i = 0; (i < 3); i++)
              ret.push_back(char_array_3[i]);
          i = 0;
        }
      }
    
      if (i) {
        for (j = i; j <4; j++)
          char_array_4[j] = 0;
    
        for (j = 0; j <4; j++)
          char_array_4[j] = base64_chars.find(char_array_4[j]);
    
        char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
        char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
        char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
    
        for (j = 0; (j < i - 1); j++) ret.push_back(char_array_3[j]);
      }
    
      return ret;
    }
    

    Here's the usage:

    std::vector<BYTE> myData;
    ...
    std::string encodedData = base64_encode(&myData[0], myData.size());
    std::vector<BYTE> decodedData = base64_decode(encodedData);
    

    how to drop database in sqlite?

    From http://www.sqlite.org/cvstrac/wiki?p=UnsupportedSql

    To create a new database, just do sqlite_open(). To drop a database, delete the file.

    How can I resize an image dynamically with CSS as the browser width/height changes?

    Are you using jQuery?

    Because I did a quickly search on the jQuery plugings and they seem to have some plugin to do this, check this one, should work:

    http://plugins.jquery.com/project/jquery-afterresize

    EDIT:

    This is the CSS solution, I just add a style="width: 100%", and works for me at least in chrome and Safari. I dont have ie, so just test there, and let me know, here is the code:

                <div id="gallery" style="width: 100%">
                    <img src="images/fullsize.jpg" alt="" id="fullsize" />
                    <a href="#" id="prev">prev</a>
                    <a href="#" id="next">next</a>
                </div>
    

    How to refresh table contents in div using jquery/ajax

    You can load HTML page partial, in your case is everything inside div#mytable.

    setTimeout(function(){
       $( "#mytable" ).load( "your-current-page.html #mytable" );
    }, 2000); //refresh every 2 seconds
    

    more information read this http://api.jquery.com/load/

    Update Code (if you don't want it auto-refresh)

    <button id="refresh-btn">Refresh Table</button>
    
    <script>
    $(document).ready(function() {
    
       function RefreshTable() {
           $( "#mytable" ).load( "your-current-page.html #mytable" );
       }
    
       $("#refresh-btn").on("click", RefreshTable);
    
       // OR CAN THIS WAY
       //
       // $("#refresh-btn").on("click", function() {
       //    $( "#mytable" ).load( "your-current-page.html #mytable" );
       // });
    
    
    });
    </script>
    

    find files by extension, *.html under a folder in nodejs

    node.js, recursive simple function:

    var path = require('path'), fs=require('fs');
    
    function fromDir(startPath,filter){
    
        //console.log('Starting from dir '+startPath+'/');
    
        if (!fs.existsSync(startPath)){
            console.log("no dir ",startPath);
            return;
        }
    
        var files=fs.readdirSync(startPath);
        for(var i=0;i<files.length;i++){
            var filename=path.join(startPath,files[i]);
            var stat = fs.lstatSync(filename);
            if (stat.isDirectory()){
                fromDir(filename,filter); //recurse
            }
            else if (filename.indexOf(filter)>=0) {
                console.log('-- found: ',filename);
            };
        };
    };
    
    fromDir('../LiteScript','.html');
    

    add RegExp if you want to get fancy, and a callback to make it generic.

    var path = require('path'), fs=require('fs');
    
    function fromDir(startPath,filter,callback){
    
        //console.log('Starting from dir '+startPath+'/');
    
        if (!fs.existsSync(startPath)){
            console.log("no dir ",startPath);
            return;
        }
    
        var files=fs.readdirSync(startPath);
        for(var i=0;i<files.length;i++){
            var filename=path.join(startPath,files[i]);
            var stat = fs.lstatSync(filename);
            if (stat.isDirectory()){
                fromDir(filename,filter,callback); //recurse
            }
            else if (filter.test(filename)) callback(filename);
        };
    };
    
    fromDir('../LiteScript',/\.html$/,function(filename){
        console.log('-- found: ',filename);
    });