Programs & Examples On #Web scraping

Web scraping is the process of extracting specific information from websites that do not readily provide an API or other methods of automated data retrieval. Questions about "How To Get Started With Scraping" (e.g. with Excel VBA) should be *thoroughly researched* as numerous functional code samples are available. Web scraping methods include 3rd-party applications, development of custom software, or even manual data collection in a standardized way.

Scraping: SSL: CERTIFICATE_VERIFY_FAILED error for http://en.wikipedia.org

I had the same error and solved the problem by running the program code below:

# install_certifi.py
#
# sample script to install or update a set of default Root Certificates
# for the ssl module.  Uses the certificates provided by the certifi package:
#       https://pypi.python.org/pypi/certifi

import os
import os.path
import ssl
import stat
import subprocess
import sys

STAT_0o775 = ( stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR
             | stat.S_IRGRP | stat.S_IWGRP | stat.S_IXGRP
             | stat.S_IROTH |                stat.S_IXOTH )


def main():
    openssl_dir, openssl_cafile = os.path.split(
        ssl.get_default_verify_paths().openssl_cafile)

    print(" -- pip install --upgrade certifi")
    subprocess.check_call([sys.executable,
        "-E", "-s", "-m", "pip", "install", "--upgrade", "certifi"])

    import certifi

    # change working directory to the default SSL directory
    os.chdir(openssl_dir)
    relpath_to_certifi_cafile = os.path.relpath(certifi.where())
    print(" -- removing any existing file or link")
    try:
        os.remove(openssl_cafile)
    except FileNotFoundError:
        pass
    print(" -- creating symlink to certifi certificate bundle")
    os.symlink(relpath_to_certifi_cafile, openssl_cafile)
    print(" -- setting permissions")
    os.chmod(openssl_cafile, STAT_0o775)
    print(" -- update complete")

if __name__ == '__main__':
    main()

Use getElementById on HTMLElement instead of HTMLDocument

I don't like it either.

So use javascript:

Public Function GetJavaScriptResult(doc as HTMLDocument, jsString As String) As String

    Dim el As IHTMLElement
    Dim nd As HTMLDOMTextNode

    Set el = doc.createElement("INPUT")
    Do
        el.ID = GenerateRandomAlphaString(100)
    Loop Until Document.getElementById(el.ID) Is Nothing
    el.Style.display = "none"
    Set nd = Document.appendChild(el)

    doc.parentWindow.ExecScript "document.getElementById('" & el.ID & "').value = " & jsString

    GetJavaScriptResult = Document.getElementById(el.ID).Value

    Document.removeChild nd

End Function


Function GenerateRandomAlphaString(Length As Long) As String

    Dim i As Long
    Dim Result As String

    Randomize Timer

    For i = 1 To Length
        Result = Result & Chr(Int(Rnd(Timer) * 26 + 65 + Round(Rnd(Timer)) * 32))
    Next i

    GenerateRandomAlphaString = Result

End Function

Let me know if you have any problems with this; I've changed the context from a method to a function.

By the way, what version of IE are you using? I suspect you're on < IE8. If you upgrade to IE8 I presume it'll update shdocvw.dll to ieframe.dll and you will be able to use document.querySelector/All.

Edit

Comment response which isn't really a comment: Basically the way to do this in VBA is to traverse the child nodes. The problem is you don't get the correct return types. You could fix this by making your own classes that (separately) implement IHTMLElement and IHTMLElementCollection; but that's WAY too much of a pain for me to do it without getting paid :). If you're determined, go and read up on the Implements keyword for VB6/VBA.

Public Function getSubElementsByTagName(el As IHTMLElement, tagname As String) As Collection

    Dim descendants As New Collection
    Dim results As New Collection
    Dim i As Long

    getDescendants el, descendants

    For i = 1 To descendants.Count
        If descendants(i).tagname = tagname Then
            results.Add descendants(i)
        End If
    Next i

    getSubElementsByTagName = results

End Function

Public Function getDescendants(nd As IHTMLElement, ByRef descendants As Collection)
    Dim i As Long
    descendants.Add nd
    For i = 1 To nd.Children.Length
        getDescendants nd.Children.Item(i), descendants
    Next i
End Function

retrieve links from web page using python and BeautifulSoup

BeatifulSoup's own parser can be slow. It might be more feasible to use lxml which is capable of parsing directly from a URL (with some limitations mentioned below).

import lxml.html

doc = lxml.html.parse(url)

links = doc.xpath('//a[@href]')

for link in links:
    print link.attrib['href']

The code above will return the links as is, and in most cases they would be relative links or absolute from the site root. Since my use case was to only extract a certain type of links, below is a version that converts the links to full URLs and which optionally accepts a glob pattern like *.mp3. It won't handle single and double dots in the relative paths though, but so far I didn't have the need for it. If you need to parse URL fragments containing ../ or ./ then urlparse.urljoin might come in handy.

NOTE: Direct lxml url parsing doesn't handle loading from https and doesn't do redirects, so for this reason the version below is using urllib2 + lxml.

#!/usr/bin/env python
import sys
import urllib2
import urlparse
import lxml.html
import fnmatch

try:
    import urltools as urltools
except ImportError:
    sys.stderr.write('To normalize URLs run: `pip install urltools --user`')
    urltools = None


def get_host(url):
    p = urlparse.urlparse(url)
    return "{}://{}".format(p.scheme, p.netloc)


if __name__ == '__main__':
    url = sys.argv[1]
    host = get_host(url)
    glob_patt = len(sys.argv) > 2 and sys.argv[2] or '*'

    doc = lxml.html.parse(urllib2.urlopen(url))
    links = doc.xpath('//a[@href]')

    for link in links:
        href = link.attrib['href']

        if fnmatch.fnmatch(href, glob_patt):

            if not href.startswith(('http://', 'https://' 'ftp://')):

                if href.startswith('/'):
                    href = host + href
                else:
                    parent_url = url.rsplit('/', 1)[0]
                    href = urlparse.urljoin(parent_url, href)

                    if urltools:
                        href = urltools.normalize(href)

            print href

The usage is as follows:

getlinks.py http://stackoverflow.com/a/37758066/191246
getlinks.py http://stackoverflow.com/a/37758066/191246 "*users*"
getlinks.py http://fakedomain.mu/somepage.html "*.mp3"

How to find tag with particular text with Beautiful Soup?

With bs4 4.7.1+ you can use :contains pseudo class to specify the td containing your search string

from bs4 import BeautifulSoup
html = '''
<tr>
  <td class="pos">\n
      "Some text:"\n
      <br>\n
      <strong>some value</strong>\n
  </td>
</tr>
<tr>
  <td class="pos">\n
      "Fixed text:"\n
      <br>\n
      <strong>text I am looking for</strong>\n
  </td>
</tr>
<tr>
  <td class="pos">\n
      "Some other text:"\n
      <br>\n
      <strong>some other value</strong>\n
  </td>
</tr>'''
soup = bs(html, 'lxml')
print(soup.select_one('td:contains("Fixed text:")'))

How to print an exception in Python 3?

I've use this :

except (socket.timeout, KeyboardInterrupt) as e:
    logging.debug("Exception : {}".format(str(e.__str__).split(" ")[3]))
    break

Let me know if it does not work for you !!

Web scraping with Python

Use urllib2 in combination with the brilliant BeautifulSoup library:

import urllib2
from BeautifulSoup import BeautifulSoup
# or if you're using BeautifulSoup4:
# from bs4 import BeautifulSoup

soup = BeautifulSoup(urllib2.urlopen('http://example.com').read())

for row in soup('table', {'class': 'spad'})[0].tbody('tr'):
    tds = row('td')
    print tds[0].string, tds[1].string
    # will print date and sunrise

Web-scraping JavaScript page with Python

A mix of BeautifulSoup and Selenium works very well for me.

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from bs4 import BeautifulSoup as bs

driver = webdriver.Firefox()
driver.get("http://somedomain/url_that_delays_loading")
    try:
        element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "myDynamicElement"))) #waits 10 seconds until element is located. Can have other wait conditions  such as visibility_of_element_located or text_to_be_present_in_element

        html = driver.page_source
        soup = bs(html, "lxml")
        dynamic_text = soup.find_all("p", {"class":"class_name"}) #or other attributes, optional
    else:
        print("Couldnt locate element")

P.S. You can find more wait conditions here

How to save an image locally using Python whose URL address I already know?

Python 2

Here is a more straightforward way if all you want to do is save it as a file:

import urllib

urllib.urlretrieve("http://www.digimouth.com/news/media/2011/09/google-logo.jpg", "local-filename.jpg")

The second argument is the local path where the file should be saved.

Python 3

As SergO suggested the code below should work with Python 3.

import urllib.request

urllib.request.urlretrieve("http://www.digimouth.com/news/media/2011/09/google-logo.jpg", "local-filename.jpg")

How to find elements by class

Use class_= If you want to find element(s) without stating the HTML tag.

For single element:

soup.find(class_='my-class-name')

For multiple elements:

soup.find_all(class_='my-class-name')

How to use Python requests to fake a browser visit a.k.a and generate User Agent?

I used fake UserAgent.

How to use:

from fake_useragent import UserAgent
import requests
   

ua = UserAgent()
print(ua.chrome)
header = {'User-Agent':str(ua.chrome)}
print(header)
url = "https://www.hybrid-analysis.com/recent-submissions?filter=file&sort=^timestamp"
htmlContent = requests.get(url, headers=header)
print(htmlContent)

Output:

Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1309.0 Safari/537.17
{'User-Agent': 'Mozilla/5.0 (X11; OpenBSD i386) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36'}
<Response [200]>

Using BeautifulSoup to extract text without tags

I think you can get it using subc1.text.

>>> html = """
<p>
    <strong class="offender">YOB:</strong> 1987<br />
    <strong class="offender">RACE:</strong> WHITE<br />
    <strong class="offender">GENDER:</strong> FEMALE<br />
    <strong class="offender">HEIGHT:</strong> 5'05''<br />
    <strong class="offender">WEIGHT:</strong> 118<br />
    <strong class="offender">EYE COLOR:</strong> GREEN<br />
    <strong class="offender">HAIR COLOR:</strong> BROWN<br />
</p>
"""
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup(html)
>>> print soup.text


YOB: 1987
RACE: WHITE
GENDER: FEMALE
HEIGHT: 5'05''
WEIGHT: 118
EYE COLOR: GREEN
HAIR COLOR: BROWN

Or if you want to explore it, you can use .contents :

>>> p = soup.find('p')
>>> from pprint import pprint
>>> pprint(p.contents)
[u'\n',
 <strong class="offender">YOB:</strong>,
 u' 1987',
 <br/>,
 u'\n',
 <strong class="offender">RACE:</strong>,
 u' WHITE',
 <br/>,
 u'\n',
 <strong class="offender">GENDER:</strong>,
 u' FEMALE',
 <br/>,
 u'\n',
 <strong class="offender">HEIGHT:</strong>,
 u" 5'05''",
 <br/>,
 u'\n',
 <strong class="offender">WEIGHT:</strong>,
 u' 118',
 <br/>,
 u'\n',
 <strong class="offender">EYE COLOR:</strong>,
 u' GREEN',
 <br/>,
 u'\n',
 <strong class="offender">HAIR COLOR:</strong>,
 u' BROWN',
 <br/>,
 u'\n']

and filter out the necessary items from the list:

>>> data = dict(zip([x.text for x in p.contents[1::4]], [x.strip() for x in p.contents[2::4]]))
>>> pprint(data)
{u'EYE COLOR:': u'GREEN',
 u'GENDER:': u'FEMALE',
 u'HAIR COLOR:': u'BROWN',
 u'HEIGHT:': u"5'05''",
 u'RACE:': u'WHITE',
 u'WEIGHT:': u'118',
 u'YOB:': u'1987'}

Options for HTML scraping?

BeautifulSoup is a great way to go for HTML scraping. My previous job had me doing a lot of scraping and I wish I knew about BeautifulSoup when I started. It's like the DOM with a lot more useful options and is a lot more pythonic. If you want to try Ruby they ported BeautifulSoup calling it RubyfulSoup but it hasn't been updated in a while.

Other useful tools are HTMLParser or sgmllib.SGMLParser which are part of the standard Python library. These work by calling methods every time you enter/exit a tag and encounter html text. They're like Expat if you're familiar with that. These libraries are especially useful if you are going to parse very large files and creating a DOM tree would be long and expensive.

Regular expressions aren't very necessary. BeautifulSoup handles regular expressions so if you need their power you can utilize it there. I say go with BeautifulSoup unless you need speed and a smaller memory footprint. If you find a better HTML parser on Python, let me know.

Scraping html tables into R data frames using the XML package

library(RCurl)
library(XML)

# Download page using RCurl
# You may need to set proxy details, etc.,  in the call to getURL
theurl <- "http://en.wikipedia.org/wiki/Brazil_national_football_team"
webpage <- getURL(theurl)
# Process escape characters
webpage <- readLines(tc <- textConnection(webpage)); close(tc)

# Parse the html tree, ignoring errors on the page
pagetree <- htmlTreeParse(webpage, error=function(...){})

# Navigate your way through the tree. It may be possible to do this more efficiently using getNodeSet
body <- pagetree$children$html$children$body 
divbodyContent <- body$children$div$children[[1]]$children$div$children[[4]]
tables <- divbodyContent$children[names(divbodyContent)=="table"]

#In this case, the required table is the only one with class "wikitable sortable"  
tableclasses <- sapply(tables, function(x) x$attributes["class"])
thetable  <- tables[which(tableclasses=="wikitable sortable")]$table

#Get columns headers
headers <- thetable$children[[1]]$children
columnnames <- unname(sapply(headers, function(x) x$children$text$value))

# Get rows from table
content <- c()
for(i in 2:length(thetable$children))
{
   tablerow <- thetable$children[[i]]$children
   opponent <- tablerow[[1]]$children[[2]]$children$text$value
   others <- unname(sapply(tablerow[-1], function(x) x$children$text$value)) 
   content <- rbind(content, c(opponent, others))
}

# Convert to data frame
colnames(content) <- columnnames
as.data.frame(content)

Edited to add:

Sample output

                     Opponent Played Won Drawn Lost Goals for Goals against  % Won
    1               Argentina     94  36    24   34       148           150  38.3%
    2                Paraguay     72  44    17   11       160            61  61.1%
    3                 Uruguay     72  33    19   20       127            93  45.8%
    ...

Scraping data from website using vba

I modified some thing that were poping up error for me and end up with this which worked great to extract the data as I needed:

Sub get_data_web()

Dim appIE As Object
Set appIE = CreateObject("internetexplorer.application")

With appIE
    .navigate "https://finance.yahoo.com/quote/NQ%3DF/futures?p=NQ%3DF"
    .Visible = True
End With

Do While appIE.Busy
    DoEvents
Loop

Set allRowofData = appIE.document.getElementsByClassName("Ta(end) BdT Bdc($c-fuji-grey-c) H(36px)")

Dim i As Long
Dim myValue As String

Count = 1

    For Each itm In allRowofData

        For i = 0 To 4

        myValue = itm.Cells(i).innerText
        ActiveSheet.Cells(Count, i + 1).Value = myValue

        Next

        Count = Count + 1

    Next

appIE.Quit
Set appIE = Nothing


End Sub

Use Excel VBA to click on a button in Internet Explorer, when the button has no "name" associated

IE.Document.getElementById("dgTime").getElementsByTagName("a")(0).Click

EDIT: to loop through the collection (items should appear in the same order as they are in the source document)

Dim links, link 

Set links = IE.Document.getElementById("dgTime").getElementsByTagName("a")

'For Each loop
For Each link in links
    link.Click
Next link

'For Next loop
Dim n, i
n = links.length
For i = 0 to n-1 Step 2
    links(i).click
Next I

Is it ok to scrape data from Google results?

Google thrives on scraping websites of the world...so if it was "so illegal" then even Google won't survive ..of course other answers mention ways of mitigating IP blocks by Google. One more way to explore avoiding captcha could be scraping at random times (dint try) ..Moreover, I have a feeling, that if we provide novelty or some significant processing of data then it sounds fine at least to me...if we are simply copying a website.. or hampering its business/brand in some way...then it is bad and should be avoided..on top of it all...if you are a startup then no one will fight you as there is no benefit.. but if your entire premise is on scraping even when you are funded then you should think of more sophisticated ways...alternative APIs..eventually..Also Google keeps releasing (or depricating) fields for its API so what you want to scrap now may be in roadmap of new Google API releases..

Web scraping with Java

There is also Jaunt Java Web Scraping & JSON Querying - http://jaunt-api.com

How to "scan" a website (or page) for info, and bring it into my program?

Look into the cURL library. I've never used it in Java, but I'm sure there must be bindings for it. Basically, what you'll do is send a cURL request to whatever page you want to 'scrape'. The request will return a string with the source code to the page. From there, you will use regex to parse whatever data you want from the source code. That's generally how you are going to do it.

What's the best way of scraping data from a website?

Yes you can do it yourself. It is just a matter of grabbing the sources of the page and parsing them the way you want.

There are various possibilities. A good combo is using python-requests (built on top of urllib2, it is urllib.request in Python3) and BeautifulSoup4, which has its methods to select elements and also permits CSS selectors:

import requests
from BeautifulSoup4 import BeautifulSoup as bs
request = requests.get("http://foo.bar")
soup = bs(request.text) 
some_elements = soup.find_all("div", class_="myCssClass")

Some will prefer xpath parsing or jquery-like pyquery, lxml or something else.

When the data you want is produced by some JavaScript, the above won't work. You either need python-ghost or Selenium. I prefer the latter combined with PhantomJS, much lighter and simpler to install, and easy to use:

from selenium import webdriver
client = webdriver.PhantomJS()
client.get("http://foo")
soup = bs(client.page_source)

I would advice to start your own solution. You'll understand Scrapy's benefits doing so.

ps: take a look at scrapely: https://github.com/scrapy/scrapely

pps: take a look at Portia, to start extracting information visually, without programming knowledge: https://github.com/scrapinghub/portia

What should I use to open a url instead of urlopen in urllib3

With gazpacho you could pipeline the page straight into a parse-able soup object:

from gazpacho import Soup
url = "http://www.thefamouspeople.com/singers.php"
soup = Soup.get(url)

And run finds on top of it:

soup.find("div")

How can I get the Google cache age of any URL or web page?

You'll need to scrape the resulting page, but you can view the most recent cache page using this URL:

http://webcache.googleusercontent.com/search?q=cache:www.something.com/path

Google information is put in the first div in the body tag.

Java HTML Parsing

The main problem as stated by preceding coments is malformed HTML, so an html cleaner or HTML-XML converter is a must. Once you get the XML code (XHTML) there are plenty of tools to handle it. You could get it with a simple SAX handler that extracts only the data you need or any tree-based method (DOM, JDOM, etc.) that let you even modify original code.

Here is a sample code that uses HTML cleaner to get all DIVs that use a certain class and print out all Text content inside it.

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;

/**
 * @author Fernando Miguélez Palomo <fernandoDOTmiguelezATgmailDOTcom>
 */
public class TestHtmlParse
{
    static final String className = "tags";
    static final String url = "http://www.stackoverflow.com";

    TagNode rootNode;

    public TestHtmlParse(URL htmlPage) throws IOException
    {
        HtmlCleaner cleaner = new HtmlCleaner();
        rootNode = cleaner.clean(htmlPage);
    }

    List getDivsByClass(String CSSClassname)
    {
        List divList = new ArrayList();

        TagNode divElements[] = rootNode.getElementsByName("div", true);
        for (int i = 0; divElements != null && i < divElements.length; i++)
        {
            String classType = divElements[i].getAttributeByName("class");
            if (classType != null && classType.equals(CSSClassname))
            {
                divList.add(divElements[i]);
            }
        }

        return divList;
    }

    public static void main(String[] args)
    {
        try
        {
            TestHtmlParse thp = new TestHtmlParse(new URL(url));

            List divs = thp.getDivsByClass(className);
            System.out.println("*** Text of DIVs with class '"+className+"' at '"+url+"' ***");
            for (Iterator iterator = divs.iterator(); iterator.hasNext();)
            {
                TagNode divElement = (TagNode) iterator.next();
                System.out.println("Text child nodes of DIV: " + divElement.getText().toString());
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}

What version of JBoss I am running?

You can retrieve information about the version of your JBoss EAP installation by running the same script used to start the server with the -V switch. For Linux and Unix installations this script is run.sh and on Microsoft Windows installations it is run.bat. Regardless of platform the script is located in $JBOSS_HOME/bin. Using these scripts to actually start your server is dealt with in Chapter 4, Launching the JBoss EAP Server.

Difference between long and int data types

The long must be at least the same size as an int, and possibly, but not necessarily, longer.

On common 32-bit systems, both int and long are 4-bytes/32-bits, and this is valid according to the C++ spec.

On other systems, both int and long long may be a different size. I used to work on a platform where int was 2-bytes, and long was 4-bytes.

SQL Server 100% CPU Utilization - One database shows high CPU usage than others

You can see some reports in SSMS:

Right-click the instance name / reports / standard / top sessions

You can see top CPU consuming sessions. This may shed some light on what SQL processes are using resources. There are a few other CPU related reports if you look around. I was going to point to some more DMVs but if you've looked into that already I'll skip it.

You can use sp_BlitzCache to find the top CPU consuming queries. You can also sort by IO and other things as well. This is using DMV info which accumulates between restarts.

This article looks promising.

Some stackoverflow goodness from Mr. Ozar.

edit: A little more advice... A query running for 'only' 5 seconds can be a problem. It could be using all your cores and really running 8 cores times 5 seconds - 40 seconds of 'virtual' time. I like to use some DMVs to see how many executions have happened for that code to see what that 5 seconds adds up to.

Variables declared outside function

When Python parses a function, it notes when a variable assignment is made. When there is an assignment, it assumes by default that that variable is a local variable. To declare that the assignment refers to a global variable, you must use the global declaration.

When you access a variable in a function, its value is looked up using the LEGB scoping rules.


So, the first example

  x = 1
  def inc():
      x += 5
  inc()

produces an UnboundLocalError because Python determined x inside inc to be a local variable,

while accessing x works in your second example

 def inc():
    print x

because here, in accordance with the LEGB rule, Python looks for x in the local scope, does not find it, then looks for it in the extended scope, still does not find it, and finally looks for it in the global scope successfully.

Simple java program of pyramid

Try this one

 public static void main(String[] args) 
{
     int x=11;
     int y=x/2; // spaces
     int z=1; // *`s

     for(int i=0;i<5;i++)
    {
         for(int j=0;j<y;j++)
        {
             System.out.print(" ");
        }
        for(int k=0;k<z;k++)
        {
            System.out.print("*");
        }

        y=y-1;
        z=z+2;
        System.out.println();  
    }

}

Set custom attribute using JavaScript

For people coming from Google, this question is not about data attributes - OP added a non-standard attribute to their HTML object, and wondered how to set it.

However, you should not add custom attributes to your properties - you should use data attributes - e.g. OP should have used data-icon, data-url, data-target, etc.

In any event, it turns out that the way you set these attributes via JavaScript is the same for both cases. Use:

ele.setAttribute(attributeName, value);

to change the given attribute attributeName to value for the DOM element ele.

For example:

document.getElementById("someElement").setAttribute("data-id", 2);

Note that you can also use .dataset to set the values of data attributes, but as @racemic points out, it is 62% slower (at least in Chrome on macOS at the time of writing). So I would recommend using the setAttribute method instead.

"The following SDK components were not installed: sys-img-x86-addon-google_apis-google-22 and addon-google_apis-google-22"

When this error occured I first clicked retry for few times and waited for 2 minutes and clicked 'retry' then it installed without any error.(for 2 minutes I was searching to solve this problem online).

Best way to read a large file into a byte array in C#?

I might argue that the answer here generally is "don't". Unless you absolutely need all the data at once, consider using a Stream-based API (or some variant of reader / iterator). That is especially important when you have multiple parallel operations (as suggested by the question) to minimise system load and maximise throughput.

For example, if you are streaming data to a caller:

Stream dest = ...
using(Stream source = File.OpenRead(path)) {
    byte[] buffer = new byte[2048];
    int bytesRead;
    while((bytesRead = source.Read(buffer, 0, buffer.Length)) > 0) {
        dest.Write(buffer, 0, bytesRead);
    }
}

AngularJS : Initialize service with asynchronous data

The "manual bootstrap" case can gain access to Angular services by manually creating an injector before bootstrap. This initial injector will stand alone (not be attached to any elements) and include only a subset of the modules that are loaded. If all you need is core Angular services, it's sufficient to just load ng, like this:

angular.element(document).ready(
    function() {
        var initInjector = angular.injector(['ng']);
        var $http = initInjector.get('$http');
        $http.get('/config.json').then(
            function (response) {
               var config = response.data;
               // Add additional services/constants/variables to your app,
               // and then finally bootstrap it:
               angular.bootstrap(document, ['myApp']);
            }
        );
    }
);

You can, for example, use the module.constant mechanism to make data available to your app:

myApp.constant('myAppConfig', data);

This myAppConfig can now be injected just like any other service, and in particular it's available during the configuration phase:

myApp.config(
    function (myAppConfig, someService) {
        someService.config(myAppConfig.someServiceConfig);
    }
);

or, for a smaller app, you could just inject the global config directly into your service, at the expense of spreading knowledge about the configuration format throughout the application.

Of course, since the async operations here will block the bootstrap of the application, and thus block the compilation/linking of the template, it's wise to use the ng-cloak directive to prevent the unparsed template from showing up during the work. You could also provide some sort of loading indication in the DOM , by providing some HTML that gets shown only until AngularJS initializes:

<div ng-if="initialLoad">
    <!-- initialLoad never gets set, so this div vanishes as soon as Angular is done compiling -->
    <p>Loading the app.....</p>
</div>
<div ng-cloak>
    <!-- ng-cloak attribute is removed once the app is done bootstrapping -->
    <p>Done loading the app!</p>
</div>

I created a complete, working example of this approach on Plunker, loading the configuration from a static JSON file as an example.

Setting Timeout Value For .NET Web Service

After creating your client specifying the binding and endpoint address, you can assign an OperationTimeout,

client.InnerChannel.OperationTimeout = new TimeSpan(0, 5, 0);

Converting between java.time.LocalDateTime and java.util.Date

the following seems to work when converting from new API LocalDateTime into java.util.date:

Date.from(ZonedDateTime.of({time as LocalDateTime}, ZoneId.systemDefault()).toInstant());

the reverse conversion can be (hopefully) achieved similar way...

hope it helps...

Fragment onResume() & onPause() is not called on backstack

A fragment must always be embedded in an activity and the fragment's lifecycle is directly affected by the host activity's lifecycle. For example, when the activity is paused, so are all fragments in it, and when the activity is destroyed, so are all fragments

Netbeans how to set command line arguments in Java

I am guessing that you are running the file using Run | Run File (or shift-F6) rather than Run | Run Main Project. The NetBeans 7.1 help file (F1 is your friend!) states for the Arguments parameter:

Add arguments to pass to the main class during application execution. Note that arguments cannot be passed to individual files.

I verified this with a little snippet of code:

public class Junk
{
    public static void main(String[] args)
    {
        for (String s : args)
            System.out.println("arg -> " + s);
    }
}

I set Run -> Arguments to x y z. When I ran the file by itself I got no output. When I ran the project the output was:

arg -> x
arg -> y
arg -> z

how to set background image in submit button?

The way I usually do it, is with the following css:

div#submitForm input {
  background: url("../images/buttonbg.png") no-repeat scroll 0 0 transparent;
  color: #000000;
  cursor: pointer;
  font-weight: bold;
  height: 20px;
  padding-bottom: 2px;
  width: 75px;
}

and the markup:

<div id="submitForm">
    <input type="submit" value="Submit" name="submit">
</div>

If things look different in the various browsers I implore you to use a reset style sheet which sets all margins, padding and maybe even borders to zero.

Check for internet connection with Swift

Although it does not directly answers your question, I would like to mention Apple recentely had this talk:

https://developer.apple.com/videos/play/wwdc2018/714/

At around 09:55 he talks about doing this stuff you are asking about:

  1. Check connection
  2. If connection -> Do something
  3. If no connection -> Do something else (wait? retry?)

However, this has a few pitfalls:

  • What if in step 2 it says it has a connection, but 0.5 seconds later he hasn't?
  • What if the user is behind a proxy
  • Last but not least, what if some answers here can not determine the connectivity right? (I am sure that if you rapidly switch your connection, go to wi-fi and turn it off (just make it complicated), it almost never can correctly determine whetever I got a connection or not).
  • Quote from the video: "There is no way to guarentee whether a future operation will succeed or not"

The following points are some best practices according to Apple:

According to the talk, there shouldn't be any reason to pre-check whetever you got internet connection or not, since it may not be accurate at the time you send your request to the server.

What ports need to be open for TortoiseSVN to authenticate (clear text) and commit?

What's the first part of your Subversion repository URL?

  • If your URL looks like: http://subversion/repos/, then you're probably going over Port 80.
  • If your URL looks like: https://subversion/repos/, then you're probably going over Port 443.
  • If your URL looks like: svn://subversion/, then you're probably going over Port 3690.
  • If your URL looks like: svn+ssh://subversion/repos/, then you're probably going over Port 22.
  • If your URL contains a port number like: http://subversion/repos:8080, then you're using that port.

I can't guarantee the first four since it's possible to reconfigure everything to use different ports, of if you go through a proxy of some sort.

If you're using a VPN, you may have to configure your VPN client to reroute these to their correct ports. A lot of places don't configure their correctly VPNs to do this type of proxying. It's either because they have some sort of anal-retentive IT person who's being overly security conscious, or because they simply don't know any better. Even worse, they'll give you a client where this stuff can't be reconfigured.

The only way around that is to log into a local machine over the VPN, and then do everything from that system.

How to validate an e-mail address in swift?

I prefer use an extension for that. Besides, this url http://emailregex.com can help you to test if regex is correct. In fact, the site offers differents implementations for some programming languages. I share my implementation for Swift 3.

extension String {
    func validateEmail() -> Bool {
        let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}"
        return NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: self)
    }
}

Unknown version of Tomcat was specified in Eclipse

For Windows Users,

Use the Tomcat Service Installer from the Apache tomcat downloads page. You will get a .exe file. which Installs the service for windows. It will usually install Apache tomcat at "C:\Program Files\Apache Software Foundation\Tomcat 8.0" and its easily recognized in eclipse.

Specifying and saving a figure with exact size in pixels

I had same issue. I used PIL Image to load the images and converted to a numpy array then patched a rectangle using matplotlib. It was a jpg image, so there was no way for me to get the dpi from PIL img.info['dpi'], so the accepted solution did not work for me. But after some tinkering I figured out way to save the figure with the same size as the original.

I am adding the following solution here thinking that it will help somebody who had the same issue as mine.

import matplotlib.pyplot as plt
from PIL import Image
import numpy as np

img = Image.open('my_image.jpg') #loading the image
image = np.array(img) #converting it to ndarray
dpi = plt.rcParams['figure.dpi'] #get the default dpi value
fig_size = (img.size[0]/dpi, img.size[1]/dpi) #saving the figure size
fig, ax = plt.subplots(1, figsize=fig_size) #applying figure size
#do whatver you want to do with the figure
fig.tight_layout() #just to be sure
fig.savefig('my_updated_image.jpg') #saving the image

This saved the image with the same resolution as the original image.

In case you are not working with a jupyter notebook. you can get the dpi in the following manner.

figure = plt.figure()
dpi = figure.dpi

C#: List All Classes in Assembly

Use Assembly.GetTypes. For example:

Assembly mscorlib = typeof(string).Assembly;
foreach (Type type in mscorlib.GetTypes())
{
    Console.WriteLine(type.FullName);
}

Creating an empty Pandas DataFrame, then filling it?

Here's a couple of suggestions:

Use date_range for the index:

import datetime
import pandas as pd
import numpy as np

todays_date = datetime.datetime.now().date()
index = pd.date_range(todays_date-datetime.timedelta(10), periods=10, freq='D')

columns = ['A','B', 'C']

Note: we could create an empty DataFrame (with NaNs) simply by writing:

df_ = pd.DataFrame(index=index, columns=columns)
df_ = df_.fillna(0) # with 0s rather than NaNs

To do these type of calculations for the data, use a numpy array:

data = np.array([np.arange(10)]*3).T

Hence we can create the DataFrame:

In [10]: df = pd.DataFrame(data, index=index, columns=columns)

In [11]: df
Out[11]: 
            A  B  C
2012-11-29  0  0  0
2012-11-30  1  1  1
2012-12-01  2  2  2
2012-12-02  3  3  3
2012-12-03  4  4  4
2012-12-04  5  5  5
2012-12-05  6  6  6
2012-12-06  7  7  7
2012-12-07  8  8  8
2012-12-08  9  9  9

Wildcard string comparison in Javascript

if(mas[i].indexOf("bird") == 0)
    //there is bird

You.can read about indexOf here: http://www.w3schools.com/jsref/jsref_indexof.asp

Difference between signed / unsigned char

The same way -- e.g. if you have an 8-bit char, 7 bits can be used for magnitude and 1 for sign. So an unsigned char might range from 0 to 255, whilst a signed char might range from -128 to 127 (for example).

Question mark and colon in statement. What does it mean?

It is the ternary conditional operator.

If the condition in the parenthesis before the ? is true, it returns the value to the left of the :, otherwise the value to the right.

How can I see the current value of my $PATH variable on OS X?

By entering $PATH on its own at the command prompt, you're trying to run it. This isn't like Windows where you can get your path output by simply typing path.

If you want to see what the path is, simply echo it:

echo $PATH

T-SQL How to create tables dynamically in stored procedures?

You will need to build that CREATE TABLE statement from the inputs and then execute it.

A simple example:

declare @cmd nvarchar(1000), @TableName nvarchar(100);

set @TableName = 'NewTable';

set @cmd = 'CREATE TABLE dbo.' + quotename(@TableName, '[') + '(newCol int not null);';

print @cmd;

--exec(@cmd);

How to select rows from a DataFrame based on column values

Here is a simple example

from pandas import DataFrame

# Create data set
d = {'Revenue':[100,111,222], 
     'Cost':[333,444,555]}
df = DataFrame(d)


# mask = Return True when the value in column "Revenue" is equal to 111
mask = df['Revenue'] == 111

print mask

# Result:
# 0    False
# 1     True
# 2    False
# Name: Revenue, dtype: bool


# Select * FROM df WHERE Revenue = 111
df[mask]

# Result:
#    Cost    Revenue
# 1  444     111

iPad Web App: Detect Virtual Keyboard Using JavaScript in Safari?

This solution remembers the scroll position

    var currentscroll = 0;

    $('input').bind('focus',function() {
        currentscroll = $(window).scrollTop();
    });

    $('input').bind('blur',function() {
        if(currentscroll != $(window).scrollTop()){

        $(window).scrollTop(currentscroll);

        }
    });

Maximum Java heap size of a 32-bit JVM on a 64-bit OS

The limitations of a 32-bit JVM on a 64-bit OS will be exactly the same as the limitations of a 32-bit JVM on a 32-bit OS. After all, the 32-bit JVM will be running In a 32-bit virtual machine (in the virtualization sense) so it won't know that it's running on a 64-bit OS/machine.

The one advantage to running a 32-bit JVM on a 64-bit OS versus a 32-bit OS is that you can have more physical memory, and therefore will encounter swapping/paging less frequently. This advantage is only really fully realized when you have multiple processes, however.

Is there a Subversion command to reset the working copy?

svn revert . -R

to reset everything.

svn revert path/to/file

for a single file

HTML.ActionLink vs Url.Action in ASP.NET Razor

@HTML.ActionLink generates a HTML anchor tag. While @Url.Action generates a URL for you. You can easily understand it by;

// 1. <a href="/ControllerName/ActionMethod">Item Definition</a>
@HTML.ActionLink("Item Definition", "ActionMethod", "ControllerName")

// 2. /ControllerName/ActionMethod
@Url.Action("ActionMethod", "ControllerName")

// 3. <a href="/ControllerName/ActionMethod">Item Definition</a>
<a href="@Url.Action("ActionMethod", "ControllerName")"> Item Definition</a>

Both of these approaches are different and it totally depends upon your need.

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

In case this is helpful to others... I had this issue because my virtualenv defaulted to python2.7 and I was calling Django using Python3 while using Ubuntu.

to check which python my virtualenv was using:

$ which python3
>> /usr/bin/python3

created new virtualenv with python3 specified (using virtualenv wrapper https://virtualenvwrapper.readthedocs.org/en/latest/):

$ mkvirtualenv --python=/usr/bin/python3 ENV_NAME

the python path should now point to the virtualenv python:

$ which python3
>> /home/user/.virtualenvs/ENV_NAME/bin/python3

"Invalid JSON primitive" in Ajax processing

I was facing the same issue, what i came with good solution is as below:

Try this...

$.ajax({
    type: "POST",
    url: "EditUserProfile.aspx/DeleteRecord",
    data: '{RecordId: ' + RecordId + ', UserId: ' + UId + ', UserProfileId:' + UserProfileId + ', ItemType: \'' + ItemType + '\', FileName: '\' + XmlName + '\'}',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    async: true,
    cache: false,
    success: function(msg) {
        if (msg.d != null) {
            RefreshData(ItemType, msg.d);
        }
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert("error occured during deleting");
    }
});

Please note here for string type parameter i have used (\') escape sequence character for denoting it as string value.

Read whole ASCII file into C++ std::string

If you happen to use glibmm you can try Glib::file_get_contents.

#include <iostream>
#include <glibmm.h>

int main() {
    auto filename = "my-file.txt";
    try {
        std::string contents = Glib::file_get_contents(filename);
        std::cout << "File data:\n" << contents << std::endl;
    catch (const Glib::FileError& e) {
        std::cout << "Oops, an error occurred:\n" << e.what() << std::endl;
    }

    return 0;
}

Javascript: output current datetime in YYYY/mm/dd hh:m:sec format

With jQuery date format :

$.format.date(new Date(), 'yyyy/MM/dd HH:mm:ss');

https://github.com/phstc/jquery-dateFormat

Enjoy

Refresh (reload) a page once using jQuery?

window.location.href=window.location.href;

Use Invoke-WebRequest with a username and password for basic authentication on the GitHub API

I had to do this to get it to work:

$pair = "$($user):$($pass)"
$encodedCredentials = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($Pair))
$headers = @{ Authorization = "Basic $encodedCredentials" }
Invoke-WebRequest -Uri $url -Method Get -Headers $headers -OutFile Config.html

Display current date and time without punctuation

If you're using Bash you could also use one of the following commands:

printf '%(%Y%m%d%H%M%S)T'       # prints the current time
printf '%(%Y%m%d%H%M%S)T' -1    # same as above
printf '%(%Y%m%d%H%M%S)T' -2    # prints the time the shell was invoked

You can use the Option -v varname to store the result in $varname instead of printing it to stdout:

printf -v varname '%(%Y%m%d%H%M%S)T'

While the date command will always be executed in a subshell (i.e. in a separate process) printf is a builtin command and will therefore be faster.

What is the difference between Views and Materialized Views in Oracle?

Views

They evaluate the data in the tables underlying the view definition at the time the view is queried. It is a logical view of your tables, with no data stored anywhere else.

The upside of a view is that it will always return the latest data to you. The downside of a view is that its performance depends on how good a select statement the view is based on. If the select statement used by the view joins many tables, or uses joins based on non-indexed columns, the view could perform poorly.

Materialized views

They are similar to regular views, in that they are a logical view of your data (based on a select statement), however, the underlying query result set has been saved to a table. The upside of this is that when you query a materialized view, you are querying a table, which may also be indexed.

In addition, because all the joins have been resolved at materialized view refresh time, you pay the price of the join once (or as often as you refresh your materialized view), rather than each time you select from the materialized view. In addition, with query rewrite enabled, Oracle can optimize a query that selects from the source of your materialized view in such a way that it instead reads from your materialized view. In situations where you create materialized views as forms of aggregate tables, or as copies of frequently executed queries, this can greatly speed up the response time of your end user application. The downside though is that the data you get back from the materialized view is only as up to date as the last time the materialized view has been refreshed.


Materialized views can be set to refresh manually, on a set schedule, or based on the database detecting a change in data from one of the underlying tables. Materialized views can be incrementally updated by combining them with materialized view logs, which act as change data capture sources on the underlying tables.

Materialized views are most often used in data warehousing / business intelligence applications where querying large fact tables with thousands of millions of rows would result in query response times that resulted in an unusable application.


Materialized views also help to guarantee a consistent moment in time, similar to snapshot isolation.

JRE 1.7 - java version - returns: java/lang/NoClassDefFoundError: java/lang/Object

In window 10 there is already a path present in env as C:\>ProgramData\Oracle\Java\javapath that holds symlinks to the executables.

When I install a new version and remove that from my environment variable, my all project start showing it.

I am using eclipse oxygen in window 10

To resolve it:-

  1. I just remove path C:\>ProgramData\Oracle\Java\javapath from environment variable and added new env as JAVA_HOME and %JAVA_HOME%/bin in path

  2. I reinstall the jdk with admin privileges (delete the previous JRE folder)

  3. Open your eclipse project > right click > Goto Proprieties> In Libraries > Now remove JRE System Library > Click on Add Library > select "JRE System Library" > Click on Next > Select "Workspace default JRE(jre1.8.x_xxx)" > finish

My issue is resolved :) Hope it will help you :)

Change the location of an object programmatically

When the parent panel has locked property set to true, we could not change the location property and the location property will act like read only by that time.

HTML character codes for this ? or this ?

The Big and small black triangles facing the 4 directions can be represented thus:

&#x25B2;

&#x25B4;

&#x25B6;

&#x25B8;

&#x25BA;

&#x25BC;

&#x25BE;

&#x25C0;

&#x25C2;

&#x25C4;

SQL query for extracting year from a date

SELECT date_column_name FROM table_name WHERE EXTRACT(YEAR FROM date_column_name) = 2020

"Cannot start compilation: the output path is not specified for module..."

If none of the above method worked then try this it worked for me.

Go to File > Project Structure> Project and then in Project Compiler Output click on the three dots and provide the path of your project name(name of the file) and then click on Apply and than on Ok.

postgres: upgrade a user to be a superuser?

You can create a SUPERUSER or promote USER, so for your case

$ sudo -u postgres psql -c "ALTER USER myuser WITH SUPERUSER;"

or rollback

$ sudo -u postgres psql -c "ALTER USER myuser WITH NOSUPERUSER;"

To prevent a command from logging when you set password, insert a whitespace in front of it, but check that your system supports this option.

$  sudo -u postgres psql -c "CREATE USER my_user WITH PASSWORD 'my_pass';"
$  sudo -u postgres psql -c "CREATE USER my_user WITH SUPERUSER PASSWORD 'my_pass';"

SVN icon overlays not showing properly

My overlays disappeared all of a sudden (or so I thought). I came across this article https://corengen.wordpress.com/2014/07/30/my-tortoisesvn-icon-overlays-have-disappeared/ which points out that windows has 15 slots for overlay icons; 4 are reserved for windows, which leaves 11 for other applications. Regardless of how many overlay keys are in the registry, Windows selects the first 11 in alphabetical order.

When I upgraded Office, OneDrive added overlay icons -- prefixed with a lot of spaces -- pushing down Tortoise's overlays below the threshold: windows registry Since I am not using OneDrive, the solution was to add a "z" to the OneDrive key names.

What is the difference between Linear search and Binary search?

A linear search looks down a list, one item at a time, without jumping. In complexity terms this is an O(n) search - the time taken to search the list gets bigger at the same rate as the list does.

A binary search is when you start with the middle of a sorted list, and see whether that's greater than or less than the value you're looking for, which determines whether the value is in the first or second half of the list. Jump to the half way through the sublist, and compare again etc. This is pretty much how humans typically look up a word in a dictionary (although we use better heuristics, obviously - if you're looking for "cat" you don't start off at "M"). In complexity terms this is an O(log n) search - the number of search operations grows more slowly than the list does, because you're halving the "search space" with each operation.

How to convert IPython notebooks to PDF and HTML?

If you are using sagemath cloud version, you can simply go to the left corner,
select File ? Download as ? Pdf via LaTeX (.pdf)
Check the screenshot if you want.

Screenshot Convert ipynb to pdf

If it dosn't work for any reason, you can try another way.
select File ? Print Preview and then on the preview
right click ? Print and then select save as pdf.

HTTP POST using JSON in Java

@momo's answer for Apache HttpClient, version 4.3.1 or later. I'm using JSON-Java to build my JSON object:

JSONObject json = new JSONObject();
json.put("someKey", "someValue");    

CloseableHttpClient httpClient = HttpClientBuilder.create().build();

try {
    HttpPost request = new HttpPost("http://yoururl");
    StringEntity params = new StringEntity(json.toString());
    request.addHeader("content-type", "application/json");
    request.setEntity(params);
    httpClient.execute(request);
// handle response here...
} catch (Exception ex) {
    // handle exception here
} finally {
    httpClient.close();
}

Please explain the exec() function and its family

The exec(3,3p) functions replace the current process with another. That is, the current process stops, and another runs instead, taking over some of the resources the original program had.

Save and retrieve image (binary) from SQL Server using Entity Framework 6

Convert the image to a byte[] and store that in the database.


Add this column to your model:

public byte[] Content { get; set; }

Then convert your image to a byte array and store that like you would any other data:

public byte[] ImageToByteArray(System.Drawing.Image imageIn)
{
    using(var ms = new MemoryStream())
    {
        imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);

        return ms.ToArray();
    }
}

public Image ByteArrayToImage(byte[] byteArrayIn)
{
     using(var ms = new MemoryStream(byteArrayIn))
     {
         var returnImage = Image.FromStream(ms);

         return returnImage;
     }
}

Source: Fastest way to convert Image to Byte array

var image = new ImageEntity()
{
   Content = ImageToByteArray(image)
};

_context.Images.Add(image);
_context.SaveChanges();

When you want to get the image back, get the byte array from the database and use the ByteArrayToImage and do what you wish with the Image

This stops working when the byte[] gets to big. It will work for files under 100Mb

Python safe method to get value of nested dictionary

There are already lots of good answers but I have come up with a function called get similar to lodash get in JavaScript land that also supports reaching into lists by index:

def get(value, keys, default_value = None):
'''
    Useful for reaching into nested JSON like data
    Inspired by JavaScript lodash get and Clojure get-in etc.
'''
  if value is None or keys is None:
      return None
  path = keys.split('.') if isinstance(keys, str) else keys
  result = value
  def valid_index(key):
      return re.match('^([1-9][0-9]*|[0-9])$', key) and int(key) >= 0
  def is_dict_like(v):
      return hasattr(v, '__getitem__') and hasattr(v, '__contains__')
  for key in path:
      if isinstance(result, list) and valid_index(key) and int(key) < len(result):
          result = result[int(key)] if int(key) < len(result) else None
      elif is_dict_like(result) and key in result:
          result = result[key]
      else:
          result = default_value
          break
  return result

def test_get():
  assert get(None, ['foo']) == None
  assert get({'foo': 1}, None) == None
  assert get(None, None) == None
  assert get({'foo': 1}, []) == {'foo': 1}
  assert get({'foo': 1}, ['foo']) == 1
  assert get({'foo': 1}, ['bar']) == None
  assert get({'foo': 1}, ['bar'], 'the default') == 'the default'
  assert get({'foo': {'bar': 'hello'}}, ['foo', 'bar']) == 'hello'
  assert get({'foo': {'bar': 'hello'}}, 'foo.bar') == 'hello'
  assert get({'foo': [{'bar': 'hello'}]}, 'foo.0.bar') == 'hello'
  assert get({'foo': [{'bar': 'hello'}]}, 'foo.1') == None
  assert get({'foo': [{'bar': 'hello'}]}, 'foo.1.bar') == None
  assert get(['foo', 'bar'], '1') == 'bar'
  assert get(['foo', 'bar'], '2') == None

Bizarre Error in Chrome Developer Console - Failed to load resource: net::ERR_CACHE_MISS

See if you can recreate the issue in an Incognito tab. If you find that the problem no longer occurs then I would recommend you go through your extensions, perhaps disabling them one at a time. This is commonly the cause as touched on by Nikola

Choosing a file in Python with simple Dialog

Another option to consider is Zenity: http://freecode.com/projects/zenity.

I had a situation where I was developing a Python server application (no GUI component) and hence didn't want to introduce a dependency on any python GUI toolkits, but I wanted some of my debug scripts to be parameterized by input files and wanted to visually prompt the user for a file if they didn't specify one on the command line. Zenity was a perfect fit. To achieve this, invoke "zenity --file-selection" using the subprocess module and capture the stdout. Of course this solution isn't Python-specific.

Zenity supports multiple platforms and happened to already be installed on our dev servers so it facilitated our debugging/development without introducing an unwanted dependency.

Bin size in Matplotlib (Histogram)

I guess the easy way would be to calculate the minimum and maximum of the data you have, then calculate L = max - min. Then you divide L by the desired bin width (I'm assuming this is what you mean by bin size) and use the ceiling of this value as the number of bins.

Export P7b file with all the certificate chain into CER file

The only problem is that any additional certificates in resulted file will not be recognized, as tools don't expect more than one certificate per PEM/DER encoded file. Even openssl itself. Try

openssl x509 -outform DER -in certificate.cer | openssl x509 -inform DER -outform PEM

and see for yourself.

What does the CSS rule "clear: both" do?

When you want one element placed at the bottom other element you use this code in CSS. It is used for floats.

If you float content you can float left or right... so in a common layout you might have a left nav, a content div and a footer.

To ensure the footer stays below both of these floats (if you have floated left and right) then you put the footer as clear: both.

This way it will stay below both floats.

(If you are only clearing left then you only really need to clear: left;.)

Go through this tutorial:

Constant pointer vs Pointer to constant

const int* ptr; 

declares ptr a pointer to const int type. You can modify ptr itself but the object pointed to by ptr shall not be modified.

const int a = 10;
const int* ptr = &a;  
*ptr = 5; // wrong
ptr++;    // right  

While

int * const ptr;  

declares ptr a const pointer to int type. You are not allowed to modify ptr but the object pointed to by ptr can be modified.

int a = 10;
int *const ptr = &a;  
*ptr = 5; // right
ptr++;    // wrong

Generally I would prefer the declaration like this which make it easy to read and understand (read from right to left):

int const  *ptr; // ptr is a pointer to constant int 
int *const ptr;  // ptr is a constant pointer to int

Select distinct values from a table field

By example:

# select distinct code from Platform where id in ( select platform__id from Build where product=p)
pl_ids = Build.objects.values('platform__id').filter(product=p)
platforms = Platform.objects.values_list('code', flat=True).filter(id__in=pl_ids).distinct('code')
platforms = list(platforms) if platforms else []

Java: How to access methods from another class

Maybe you need some dependency injection

public class Alpha {

    private Beta cbeta;

    public Alpha(Beta beta) {
        this.cbeta = beta;
    }

    public void DoSomethingAlpha() {
        this.cbeta.DoSomethingBeta();
    }
}

and then

Alpha cAlpha = new Alpha(new Beta());   

iOS: set font size of UILabel Programmatically

Objective-C:

[label setFont: [label.font fontWithSize: sizeYouWant]];

Swift:

label.font = label.font.fontWithSize(sizeYouWant)

just changes font size of a UILabel.

Does height and width not apply to span?

Span takes width and height only when we make it block element.

span {display:block;}

Get element inside element by class and ID - JavaScript

Well, first you need to select the elements with a function like getElementById.

var targetDiv = document.getElementById("foo").getElementsByClassName("bar")[0];

getElementById only returns one node, but getElementsByClassName returns a node list. Since there is only one element with that class name (as far as I can tell), you can just get the first one (that's what the [0] is for—it's just like an array).

Then, you can change the html with .textContent.

targetDiv.textContent = "Goodbye world!";

_x000D_
_x000D_
var targetDiv = document.getElementById("foo").getElementsByClassName("bar")[0];_x000D_
targetDiv.textContent = "Goodbye world!";
_x000D_
<div id="foo">_x000D_
    <div class="bar">_x000D_
        Hello world!_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Direct download from Google Drive using Google Drive API

I faced an issue in direct download because I was logged in using multiple Google accounts. Solution is append authUser=0 parameter. Sample request URL to download :https://drive.google.com/uc?id=FILEID&authuser=0&export=download

What is the difference between hg forget and hg remove?

'hg forget' is just shorthand for 'hg remove -Af'. From the 'hg remove' help:

...and -Af can be used to remove files from the next revision without deleting them from the working directory.

Bottom line: 'remove' deletes the file from your working copy on disk (unless you uses -Af) and 'forget' doesn't.

Android Webview - Webpage should fit the device screen

webview.setInitialScale(1);
webview.getSettings().setLoadWithOverviewMode(true);
webview.getSettings().setUseWideViewPort(true);
webview.getSettings().setJavaScriptEnabled(true);

will work, but remember to remove something like:

<meta name="viewport" content="user-scalable=no"/>

if existed in the html file or change user-scalable=yes, otherwise it won't.

Java HashMap: How to get a key and value by index?

I came across the same problem, read a couple of answers from different related questions and came up with my own class.

public class IndexableMap<K, V> extends HashMap<K, V> {

    private LinkedList<K> keyList = new LinkedList<>();

    @Override
    public V put(K key, V value) {
        if (!keyList.contains(key))
            keyList.add(key);
        return super.put(key, value);
    }

    @Override
    public void putAll(Map<? extends K, ? extends V> m) {
        for (Entry<? extends K, ? extends V> entry : m.entrySet()) {
            put(entry.getKey(), entry.getValue());
        }
    }

    @Override
    public void clear() {
        keyList.clear();
        super.clear();
    }

    public List<K> getKeys() {
        return keyList;
    }

    public int getKeyIndex(K key) {
        return keyList.indexOf(key);
    }

    public K getKeyAt(int index) {
        if (keyList.size() > index)
            return keyList.get(index);
        return null;
    }

    public V getValueAt(int index) {
        K key = getKeyAt(index);
        if (key != null)
            return get(key);
        return null;
    }
}

Example (types are differing from OPs question just for clarity):

Map<String, Double> myMap = new IndexableMap<>();

List<String> keys = myMap.getKeys();
int keyIndex = myMap.getKeyIndex("keyString");
String key = myMap.getKeyAt(2);
Double value myMap.getValueAt(2);

Keep in mind that it does not override any of the complex methods, so you will need to do this on your own if you want to reliably access one of these.

Edit: I made a change to the putAll() method, because the old one had a rare chance to cause HashMap and LinkedList being in different states.

How do you perform wireless debugging in Xcode 9 with iOS 11, Apple TV 4K, etc?

Try this:

1) Plug your iOS device into your Mac using a lightning cable. You may need to select to Trust This Computer on your device.

2) Open Xcode and go to Window > Devices and Simulators.

3) Select your device and then select the Connect via network checkbox to pair your device.

4) Run your project after removing your lighting cable.

VideoView Full screen in android application

I have done this way:

Check these reference screen shots.

enter image description here

Add class FullScreenVideoView.java:

import android.content.Context;
import android.util.AttributeSet;
import android.widget.VideoView;

public class FullScreenVideoView extends VideoView {
    public FullScreenVideoView(Context context) {
        super(context);
    }

    public FullScreenVideoView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public FullScreenVideoView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
    }
}

How to bind with xml:

<FrameLayout
   android:id="@+id/secondMedia"
   android:layout_width="match_parent"
   android:layout_height="match_parent">

     <com.my.package.customview.FullScreenVideoView
           android:layout_width="match_parent"
           android:layout_height="match_parent" 
           android:id="@+id/fullScreenVideoView"/>

</FrameLayout>

Hope this will help you.

Get Android API level of phone currently running my application

Check android.os.Build.VERSION, which is a static class that holds various pieces of information about the Android OS a system is running.

If you care about all versions possible (back to original Android version), as in minSdkVersion is set to anything less than 4, then you will have to use android.os.Build.VERSION.SDK, which is a String that can be converted to the integer of the release.

If you are on at least API version 4 (Android 1.6 Donut), the current suggested way of getting the API level would be to check the value of android.os.Build.VERSION.SDK_INT, which is an integer.

In either case, the integer you get maps to an enum value from all those defined in android.os.Build.VERSION_CODES:

SDK_INT value        Build.VERSION_CODES        Human Version Name       
    1                  BASE                      Android 1.0 (no codename)
    2                  BASE_1_1                  Android 1.1 Petit Four
    3                  CUPCAKE                   Android 1.5 Cupcake
    4                  DONUT                     Android 1.6 Donut
    5                  ECLAIR                    Android 2.0 Eclair
    6                  ECLAIR_0_1                Android 2.0.1 Eclair                  
    7                  ECLAIR_MR1                Android 2.1 Eclair
    8                  FROYO                     Android 2.2 Froyo
    9                  GINGERBREAD               Android 2.3 Gingerbread
   10                  GINGERBREAD_MR1           Android 2.3.3 Gingerbread
   11                  HONEYCOMB                 Android 3.0 Honeycomb
   12                  HONEYCOMB_MR1             Android 3.1 Honeycomb
   13                  HONEYCOMB_MR2             Android 3.2 Honeycomb
   14                  ICE_CREAM_SANDWICH        Android 4.0 Ice Cream Sandwich
   15                  ICE_CREAM_SANDWICH_MR1    Android 4.0.3 Ice Cream Sandwich
   16                  JELLY_BEAN                Android 4.1 Jellybean
   17                  JELLY_BEAN_MR1            Android 4.2 Jellybean
   18                  JELLY_BEAN_MR2            Android 4.3 Jellybean
   19                  KITKAT                    Android 4.4 KitKat
   20                  KITKAT_WATCH              Android 4.4 KitKat Watch
   21                  LOLLIPOP                  Android 5.0 Lollipop
   22                  LOLLIPOP_MR1              Android 5.1 Lollipop
   23                  M                         Android 6.0 Marshmallow
   24                  N                         Android 7.0 Nougat
   25                  N_MR1                     Android 7.1.1 Nougat
   26                  O                         Android 8.0 Oreo
   27                  O_MR1                     Android 8 Oreo MR1
   28                  P                         Android 9 Pie
   29                  Q                         Android 10
  10000                CUR_DEVELOPMENT           Current Development Version

Note that some time between Android N and O, the Android SDK began aliasing CUR_DEVELOPMENT and the developer preview of the next major Android version to be the same SDK_INT value (10000).

Java 8: How do I work with exception throwing methods in streams?

You might want to do one of the following:

  • propagate checked exception,
  • wrap it and propagate unchecked exception, or
  • catch the exception and stop propagation.

Several libraries let you do that easily. Example below is written using my NoException library.

// Propagate checked exception
as.forEach(Exceptions.sneak().consumer(A::foo));

// Wrap and propagate unchecked exception
as.forEach(Exceptions.wrap().consumer(A::foo));
as.forEach(Exceptions.wrap(MyUncheckedException::new).consumer(A::foo));

// Catch the exception and stop propagation (using logging handler for example)
as.forEach(Exceptions.log().consumer(Exceptions.sneak().consumer(A::foo)));

What is Shelving in TFS?

Shelving is like your changes have been stored in the source control without affecting the existing changes. Means if you check in a file in source control it will modify the existing file but shelving is like storing your changes in source control but without modifying the actual changes.

Another Repeated column in mapping for entity error

Hope this will help!

@OneToOne(optional = false)
    @JoinColumn(name = "department_id", insertable = false, updatable = false)
    @JsonManagedReference
    private Department department;

@JsonIgnore
    public Department getDepartment() {
        return department;
    }

@OneToOne(mappedBy = "department")
private Designation designation;

@JsonIgnore
    public Designation getDesignation() {
        return designation;
    }

Android Gradle Could not reserve enough space for object heap

I ran into the same issue, here's my post:

Android Studio - Gradle build failing - Java Heap Space

exec summary: Windows looks for the gradle.properties file here:

C:\Users\.gradle\gradle.properties

So create that file, and add a line like this:

org.gradle.jvmargs=-XX\:MaxHeapSize\=256m -Xmx256m

as per @Faiz Siddiqui post

What do pty and tty mean?

tty: teletype. Usually refers to the serial ports of a computer, to which terminals were attached.

pty: pseudoteletype. Kernel provided pseudoserial port connected to programs emulating terminals, such as xterm, or screen.

Execute JavaScript code stored as a string

Run code using string

_x000D_
_x000D_
function runMe(x,y,z){
console.log(x);
console.log(y);
console.log(z);

}

// function name and parameters to pass
var fnstring = "runMe";
var fnparams = [1, 2, 3];//<--parameters

// find object
var fn = window[fnstring];

// is object a function?
if (typeof fn === "function") fn.apply(null, fnparams);//<--apply parameter
_x000D_
enter code here
_x000D_
_x000D_
_x000D_

jquery append div inside div with id and manipulate

var e = $('<div style="display:block; id="myid" float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');
$("#box").html(e);

How to properly set the 100% DIV height to match document/window height?

You could make it absolute and put zeros to top and bottom that is:

#fullHeightDiv {
    position: absolute;
    top: 0;
    bottom: 0;
}

XSL if: test with multiple test conditions

Just for completeness and those unaware XSL 1 has choose for multiple conditions.

<xsl:choose>
 <xsl:when test="expression">
  ... some output ...
 </xsl:when>
 <xsl:when test="another-expression">
  ... some output ...
 </xsl:when>
 <xsl:otherwise>
   ... some output ....
 </xsl:otherwise>
</xsl:choose>

CSS fixed width in a span

_x000D_
_x000D_
ul {_x000D_
 list-style-type: none;_x000D_
 padding-left: 0px;_x000D_
}_x000D_
_x000D_
ul li span { _x000D_
 float: left;_x000D_
 width: 40px;_x000D_
}
_x000D_
<ul>_x000D_
    <li><span></span> The lazy dog.</li>_x000D_
    <li><span>AND</span> The lazy cat.</li>_x000D_
    <li><span>OR</span> The active goldfish.</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

SQLite UPSERT / UPDATE OR INSERT

Here's an approach that doesn't require the brute-force 'ignore' which would only work if there was a key violation. This way works based on any conditions you specify in the update.

Try this...

-- Try to update any existing row
UPDATE players
SET age=32
WHERE user_name='steven';

-- If no update happened (i.e. the row didn't exist) then insert one
INSERT INTO players (user_name, age)
SELECT 'steven', 32
WHERE (Select Changes() = 0);

How It Works

The 'magic sauce' here is using Changes() in the Where clause. Changes() represents the number of rows affected by the last operation, which in this case is the update.

In the above example, if there are no changes from the update (i.e. the record doesn't exist) then Changes() = 0 so the Where clause in the Insert statement evaluates to true and a new row is inserted with the specified data.

If the Update did update an existing row, then Changes() = 1 (or more accurately, not zero if more than one row was updated), so the 'Where' clause in the Insert now evaluates to false and thus no insert will take place.

The beauty of this is there's no brute-force needed, nor unnecessarily deleting, then re-inserting data which may result in messing up downstream keys in foreign-key relationships.

Additionally, since it's just a standard Where clause, it can be based on anything you define, not just key violations. Likewise, you can use Changes() in combination with anything else you want/need anywhere expressions are allowed.

Mod of negative number is melting my brain

Here's my one liner for positive integers, based on this answer:

usage:

(-7).Mod(3); // returns 2

implementation:

static int Mod(this int a, int n) => (((a %= n) < 0) ? n : 0) + a;

Pass value to iframe from a window

What you have to do is to append the values as parameters in the iframe src (URL).

E.g. <iframe src="some_page.php?somedata=5&more=bacon"></iframe>

And then in some_page.php file you use php $_GET['somedata'] to retrieve it from the iframe URL. NB: Iframes run as a separate browser window in your file.

Dynamic array in C#

Use the array list which is actually implement array. It takes initially array of size 4 and when it gets full, a new array is created with its double size and the data of first array get copied into second array, now the new item is inserted into new array. Also the name of second array creates an alias of first so that it can be accessed by the same name as previous and the first array gets disposed

Using getResources() in non-activity class

here is my answer:

public class WigetControl {
private Resources res;

public WigetControl(Resources res) 
{
    this.res = res;
}

public void setButtonDisable(Button mButton)
{
    mButton.setBackgroundColor(res.getColor(R.color.loginbutton_unclickable));
    mButton.setEnabled(false);
}

}

and the call can be like this:

        WigetControl control = new WigetControl(getResources());
        control.setButtonDisable(btNext);

How do I put the image on the right side of the text in a UIButton?

To right align image within UIButton try below code

btn.contentHorizontalAlignment = .right

How to display hexadecimal numbers in C?

You can use the following snippet code:

#include<stdio.h>
int main(int argc, char *argv[]){
    unsigned int i;
    printf("decimal  hexadecimal\n");
    for (i = 0; i <= 256; i+=16)
        printf("%04d     0x%04X\n", i, i);
    return 0;
}

It prints both decimal and hexadecimal numbers in 4 places with zero padding.

IE Driver download location Link for Selenium

You can download IE Driver (both 32 and 64-bit) from Selenium official site: http://docs.seleniumhq.org/download/

32 bit Windows IE

64 bit Windows IE

IE Driver is also available in the following site:

http://selenium-release.storage.googleapis.com/index.html

update listview dynamically with adapter

I created a method just for that. I use it any time I need to manually update a ListView. Hopefully this gives you an idea of how to implement your own

public static void UpdateListView(List<SomeObject> SomeObjects, ListView ListVw)
{    
    if(ListVw != null)
    {
        final YourAdapter adapter = (YourAdapter) ListVw.getAdapter();

        //You'll have to create this method in your adapter class. It's a simple setter.
        adapter.SetList(SomeObjects);

        adapter.notifyDataSetChanged();
    }
}

I'm using an adapter that inherites from BaseAdapter. Should work for any other type of adapter.

Set Windows process (or user) memory limit

Use the Application Verifier (AppVerifier) tool from Microsoft.

In my case I need to simulate memory no longer being available so I did the following in the tool:

  1. Added my application
  2. Unchecked Basic
  3. Checked Low Resource Simulation
    • Changed TimeOut to 120000 - my application will run normally for 2 minutes before anything goes into effect.
    • Changed HeapAlloc to 100 - 100% chance of heap allocation error
    • Set Stacks to true - the stack will not be able to grow any larger
  4. Save
  5. Start my application

After 2 minutes my program could no longer allocate new memory and I was able to see how everything was handled.

How to change the Content of a <textarea> with JavaScript

If you can use jQuery, and I highly recommend you do, you would simply do

$('#myTextArea').val('');

Otherwise, it is browser dependent. Assuming you have

var myTextArea = document.getElementById('myTextArea');

In most browsers you do

myTextArea.innerHTML = '';

But in Firefox, you do

myTextArea.innerText = '';

Figuring out what browser the user is using is left as an exercise for the reader. Unless you use jQuery, of course ;)

Edit: I take that back. Looks like support for .innerHTML on textarea's has improved. I tested in Chrome, Firefox and Internet Explorer, all of them cleared the textarea correctly.

Edit 2: And I just checked, if you use .val('') in jQuery, it just sets the .value property for textarea's. So .value should be fine.

How can I export Excel files using JavaScript?

Create an AJAX postback method which writes a CSV file to your webserver and returns the url.. Set a hidden IFrame in the browser to the location of the CSV file on the server.

Your user will then be presented with the CSV download link.

How to use the pass statement?

You can say that pass means NOP (No Operation) operation. You will get a clear picture after this example :-

C Program

#include<stdio.h>

void main()
{
    int age = 12;

    if( age < 18 )
    {
         printf("You are not adult, so you can't do that task ");
    }
    else if( age >= 18 && age < 60)
    {
        // I will add more code later inside it 
    }
    else
    {
         printf("You are too old to do anything , sorry ");
    }
}

Now how you will write that in Python :-

age = 12

if age < 18:

    print "You are not adult, so you can't do that task"

elif age >= 18 and age < 60:

else:

    print "You are too old to do anything , sorry "

But your code will give error because it required an indented block after elif . Here is the role of pass keyword.

age = 12

if age < 18:

    print "You are not adult, so you can't do that task"

elif age >= 18 and age < 60:

    pass

else:

    print "You are too old to do anything , sorry "

Now I think its clear to you.

Changing the page title with Jquery

Html code:

Change Title:
<input type="text" id="changeTitle" placeholder="Enter title tag">
<button id="changeTitle1">Click!</button>

Jquery code:

$(document).ready(function(){   
    $("#changeTitle1").click(function() {
        $(document).prop('title',$("#changeTitle").val()); 
    });
});

How to get cookie expiration date / creation date from javascript?

Yes, It is possible. I've separated the code in two files:

index.php

<?php

    $time = time()+(60*60*24*10);
    $timeMemo = (string)$time;
    setcookie("cookie", "" . $timeMemo . "", $time);

?>
<html>
    <head>
        <title>
            Get cookie expiration date from JS
        </title>
        <script type="text/javascript">

            function cookieExpirationDate(){

                var infodiv = document.getElementById("info");

                var xmlhttp;
                if (window.XMLHttpRequest){ 
                    xmlhttp = new XMLHttpRequest;
                }else{
                    xmlhttp = new ActiveXObject(Microsoft.XMLHTTP);
                }

                xmlhttp.onreadystatechange = function (){
                    if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
                        infodiv.innerHTML = xmlhttp.responseText;
                    }
                }

                xmlhttp.open("GET", "cookie.php", true);
                xmlhttp.send();

            }

        </script>
    </head>
    <body>
        <input type="button" onclick="javascript:cookieExpirationDate();" value="Get Cookie expire date" />
        <hr />
        <div id="info">
        </div>
    </body>
</html>

cookie.php

<?php

    function secToDays($sec){
        return ($sec / 60 / 60 / 24);
    }

    if(isset($_COOKIE['cookie'])){

        if(round(secToDays((intval($_COOKIE['cookie']) - time())),1) < 1){
            echo "Cookie will expire today";
        }else{
            echo "Cookie will expire in " . round(secToDays((intval($_COOKIE['cookie']) - time())),1) . " day(s)";
        }
    }else{
        echo "Cookie not set...";
    }

?>

Now, index.php must be loaded once. The button "Get Cookie expire date", thru an AJAX request, will always get you an updated "time left" for cookie expiration, in this case in days.

How can I find the link URL by link text with XPath?

Should be something similar to:

//a[text()='text_i_want_to_find']/@href

HTML: How to make a submit button with text + image in it?

Let's say your image is a 16x16 .png icon called icon.png Use the power of CSS!

CSS:

input#image-button{
    background: #ccc url('icon.png') no-repeat top left;
    padding-left: 16px;
    height: 16px;
}

HTML:

<input type="submit" id="image-button" value="Text"></input>

This will put the image to the left of the text.

Convert MySql DateTime stamp into JavaScript's Date format

Why not do this:

var d = new Date.parseDate( "2000-09-10 00:00:00", 'Y-m-d H:i:s' );

Set up adb on Mac OS X

MacPorts

It seems like android-platform-tools was first added to MacPorts only very recently — in 2018-10-20, under java/android-platform-tools/Portfile:

It would appear that it relies on a compiled binary that's provided by Google; it would appear that the source code for the binary might not be available.

The adb binary

Reverse-engineering the android-platform-tools/Portfile from above reveals that the following archive is fetched from Google in order to build the port:

The abd binary is pre-compiled, available in platform-tools/adb within the above archive, which is a Mach-O 64-bit executable x86_64, as per file(1). It's ready to be used and doesn't seem to have any external dependencies (e.g., doesn't look like it depends on java or anything).

Using adb

In order to use adb to restart the device, for example, in case the power button is stuck, the following steps could be used:

cd /tmp
curl https://dl.google.com/android/repository/platform-tools_r28.0.1-darwin.zip -o apt.zip
unzip apt.zip
./platform-tools/adb devices
./platform-tools/adb reboot

Upon first use since a reboot, you also have to first confirm the pairing with the phone through the Allow USB debugging? popup on the phone (phone has to have USB debugging enabled through the Developer Options, no root access required).

Python function global variables?

If you want to simply access a global variable you just use its name. However to change its value you need to use the global keyword.

E.g.

global someVar
someVar = 55

This would change the value of the global variable to 55. Otherwise it would just assign 55 to a local variable.

The order of function definition listings doesn't matter (assuming they don't refer to each other in some way), the order they are called does.

How to install pip for Python 3 on Mac OS X?

On MacOS 10.12

download pip: pip as get-pip.py

download python3: python3

  1. install python3
  2. open terminal: python3 get-pip.py
  3. pip3 is available

Get content uri from file path in android

The accepted solution is probably the best bet for your purposes, but to actually answer the question in the subject line:

In my app, I have to get the path from URIs and get the URI from paths. The former:

/**
 * Gets the corresponding path to a file from the given content:// URI
 * @param selectedVideoUri The content:// URI to find the file path from
 * @param contentResolver The content resolver to use to perform the query.
 * @return the file path as a string
 */
private String getFilePathFromContentUri(Uri selectedVideoUri,
        ContentResolver contentResolver) {
    String filePath;
    String[] filePathColumn = {MediaColumns.DATA};

    Cursor cursor = contentResolver.query(selectedVideoUri, filePathColumn, null, null, null);
    cursor.moveToFirst();

    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
    filePath = cursor.getString(columnIndex);
    cursor.close();
    return filePath;
}

The latter (which I do for videos, but can also be used for Audio or Files or other types of stored content by substituting MediaStore.Audio (etc) for MediaStore.Video):

/**
 * Gets the MediaStore video ID of a given file on external storage
 * @param filePath The path (on external storage) of the file to resolve the ID of
 * @param contentResolver The content resolver to use to perform the query.
 * @return the video ID as a long
 */
private long getVideoIdFromFilePath(String filePath,
        ContentResolver contentResolver) {


    long videoId;
    Log.d(TAG,"Loading file " + filePath);

            // This returns us content://media/external/videos/media (or something like that)
            // I pass in "external" because that's the MediaStore's name for the external
            // storage on my device (the other possibility is "internal")
    Uri videosUri = MediaStore.Video.Media.getContentUri("external");

    Log.d(TAG,"videosUri = " + videosUri.toString());

    String[] projection = {MediaStore.Video.VideoColumns._ID};

    // TODO This will break if we have no matching item in the MediaStore.
    Cursor cursor = contentResolver.query(videosUri, projection, MediaStore.Video.VideoColumns.DATA + " LIKE ?", new String[] { filePath }, null);
    cursor.moveToFirst();

    int columnIndex = cursor.getColumnIndex(projection[0]);
    videoId = cursor.getLong(columnIndex);

    Log.d(TAG,"Video ID is " + videoId);
    cursor.close();
    return videoId;
}

Basically, the DATA column of MediaStore (or whichever sub-section of it you're querying) stores the file path, so you use that info to look it up.

Update query PHP MySQL

Update a row or column of a table

$update = "UPDATE daily_patients SET queue_status = 'pending' WHERE doctor_id = $room_no and serial_number= $serial_num";

if ($con->query($update) === TRUE) {
    echo "Record updated successfully";
} else {
    echo "Error updating record: " . $con->error;
}

What is the best way to connect and use a sqlite database from C#

Here I am trying to help you do the job step by step: (this may be the answer to other questions)

  1. Go to this address , down the page you can see something like "List of Release Packages". Based on your system and .net framework version choose the right one for you. for example if your want to use .NET Framework 4.6 on a 64-bit Windows, choose this version and download it.
  2. Then install the file somewhere on your hard drive, just like any other software.
  3. Open Visual studio and your project. Then in solution explorer, right-click on "References" and choose "add Reference...".
  4. Click the browse button and choose where you install the previous file and go to .../bin/System.Data.SQLite.dll and click add and then OK buttons.

that is pretty much it. now you can use SQLite in your project. to use it in your project on the code level you may use this below example code:

  1. make a connection string:

    string connectionString = @"URI=file:{the location of your sqlite database}";

  2. establish a sqlite connection:

    SQLiteConnection theConnection = new SQLiteConnection(connectionString );

  3. open the connection:

    theConnection.Open();

  4. create a sqlite command:

    SQLiteCommand cmd = new SQLiteCommand(theConnection);

  5. Make a command text, or better said your SQLite statement:

    cmd.CommandText = "INSERT INTO table_name(col1, col2) VALUES(val1, val2)";

  6. Execute the command

    cmd.ExecuteNonQuery();

that is it.

Getting the ID of the element that fired an event

Element which fired event we have in event property

event.currentTarget

We get DOM node object on which was set event handler.


Most nested node which started bubbling process we have in

event.target

Event object is always first attribute of event handler, example:

document.querySelector("someSelector").addEventListener(function(event){

 console.log(event.target);
 console.log(event.currentTarget);

});

More about event delegation You can read in http://maciejsikora.com/standard-events-vs-event-delegation/

What Content-Type value should I send for my XML sitemap?

both are fine.

text/xxx means that in case the program does not understand xxx it makes sense to show the file to the user as plain text. application/xxx means that it is pointless to show it.

Please note that those content-types were originally defined for E-Mail attachment before they got later used in Web world.

How would you make a comma-separated string from a list of strings?

>>> my_list = ['A', '', '', 'D', 'E',]
>>> ",".join([str(i) for i in my_list if i])
'A,D,E'

my_list may contain any type of variables. This avoid the result 'A,,,D,E'.

How to deep copy a list?

E0_copy is not a deep copy. You don't make a deep copy using list() (Both list(...) and testList[:] are shallow copies).

You use copy.deepcopy(...) for deep copying a list.

deepcopy(x, memo=None, _nil=[])
    Deep copy operation on arbitrary Python objects.

See the following snippet -

>>> a = [[1, 2, 3], [4, 5, 6]]
>>> b = list(a)
>>> a
[[1, 2, 3], [4, 5, 6]]
>>> b
[[1, 2, 3], [4, 5, 6]]
>>> a[0][1] = 10
>>> a
[[1, 10, 3], [4, 5, 6]]
>>> b   # b changes too -> Not a deepcopy.
[[1, 10, 3], [4, 5, 6]]

Now see the deepcopy operation

>>> import copy
>>> b = copy.deepcopy(a)
>>> a
[[1, 10, 3], [4, 5, 6]]
>>> b
[[1, 10, 3], [4, 5, 6]]
>>> a[0][1] = 9
>>> a
[[1, 9, 3], [4, 5, 6]]
>>> b    # b doesn't change -> Deep Copy
[[1, 10, 3], [4, 5, 6]]

How can I define an array of objects?

 var xxxx : { [key:number]: MyType };

Java method: Finding object in array list given a known attribute value

You have to loop through the entire array, there's no changing that. You can however, do it a little easier

for (Dog dog : list) {
  if (dog.getId() == id) {
    return dog; //gotcha!
  }
}
return null; // dog not found.

or without the new for loop

for (int i = 0; i < list.size(); i++) {
  if (list.get(i).getId() == id) {
    return list.get(i);
  }
}

<DIV> inside link (<a href="">) tag

Nesting of 'a' will not be possible. However if you badly want to keep the structure and still make it work like the way you want, then override the anchor tag click in javascript /jquery .

so you can have 2 event listeners for the two and control them accordingly.

How to advance to the next form input when the current input has a value?

you just need to give focus to the next input field (by invoking focus()method on that input element), for example if you're using jQuery this code will simulate the tab key when enter is pressed:

var inputs = $(':input').keypress(function(e){ 
    if (e.which == 13) {
       e.preventDefault();
       var nextInput = inputs.get(inputs.index(this) + 1);
       if (nextInput) {
          nextInput.focus();
       }
    }
});

C# 30 Days From Todays Date

string dateInString = "01.10.2009";

DateTime startDate = DateTime.Parse(dateInString);
DateTime expiryDate = startDate.AddDays(30);
if (DateTime.Now > expiryDate) {
  //... trial expired
}

Python MySQLdb TypeError: not all arguments converted during string formatting

According PEP8,I prefer to execute SQL in this way:

cur = con.cursor()
# There is no need to add single-quota to the surrounding of `%s`,
# because the MySQLdb precompile the sql according to the scheme type
# of each argument in the arguments list.
sql = "SELECT * FROM records WHERE email LIKE %s;"
args = [search, ]
cur.execute(sql, args)

In this way, you will recognize that the second argument args of execute method must be a list of arguments.

May this helps you.

OpenCV - Saving images to a particular folder of choice

The solution provided by ebeneditos works perfectly.

But if you have cv2.imwrite() in several sections of a large code snippet and you want to change the path where the images get saved, you will have to change the path at every occurrence of cv2.imwrite() individually.

As Soltius stated, here is a better way. Declare a path and pass it as a string into cv2.imwrite()

import cv2
import os
img = cv2.imread('1.jpg', 1)
path = 'D:/OpenCV/Scripts/Images'
cv2.imwrite(os.path.join(path , 'waka.jpg'), img)
cv2.waitKey(0)

Now if you want to modify the path, you just have to change the path variable.

Edited based on solution provided by Kallz

VBA Count cells in column containing specified value

If you're looking to match non-blank values or empty cells and having difficulty with wildcard character, I found the solution below from here.

Dim n as Integer
n = Worksheets("Sheet1").Range("A:A").Cells.SpecialCells(xlCellTypeConstants).Count

AngularJS : Difference between the $observe and $watch methods

I think this is pretty obvious :

  • $observe is used in linking function of directives.
  • $watch is used on scope to watch any changing in its values.

Keep in mind : both the function has two arguments,

$observe/$watch(value : string, callback : function);
  • value : is always a string reference to the watched element (the name of a scope's variable or the name of the directive's attribute to be watched)
  • callback : the function to be executed of the form function (oldValue, newValue)

I have made a plunker, so you can actually get a grasp on both their utilization. I have used the Chameleon analogy as to make it easier to picture.

Limit Get-ChildItem recursion depth

@scanlegentil I like this.
A little improvement would be:

$Depth = 2
$Path = "."

$Levels = "\*" * $Depth
$Folder = Get-Item $Path
$FolderFullName = $Folder.FullName
Resolve-Path $FolderFullName$Levels | Get-Item | ? {$_.PsIsContainer} | Write-Host

As mentioned, this would only scan the specified depth, so this modification is an improvement:

$StartLevel = 1 # 0 = include base folder, 1 = sub-folders only, 2 = start at 2nd level
$Depth = 2      # How many levels deep to scan
$Path = "."     # starting path

For ($i=$StartLevel; $i -le $Depth; $i++) {
    $Levels = "\*" * $i
    (Resolve-Path $Path$Levels).ProviderPath | Get-Item | Where PsIsContainer |
    Select FullName
}

jQuery callback on image load (even when the image is cached)

If the src is already set, then the event is firing in the cached case, before you even get the event handler bound. To fix this, you can loop through checking and triggering the event based off .complete, like this:

$("img").one("load", function() {
  // do stuff
}).each(function() {
  if(this.complete) {
      $(this).load(); // For jQuery < 3.0 
      // $(this).trigger('load'); // For jQuery >= 3.0 
  }
});

Note the change from .bind() to .one() so the event handler doesn't run twice.

convert big endian to little endian in C [without using provided func]

Assuming what you need is a simple byte swap, try something like

Unsigned 16 bit conversion:

swapped = (num>>8) | (num<<8);

Unsigned 32-bit conversion:

swapped = ((num>>24)&0xff) | // move byte 3 to byte 0
                    ((num<<8)&0xff0000) | // move byte 1 to byte 2
                    ((num>>8)&0xff00) | // move byte 2 to byte 1
                    ((num<<24)&0xff000000); // byte 0 to byte 3

This swaps the byte orders from positions 1234 to 4321. If your input was 0xdeadbeef, a 32-bit endian swap might have output of 0xefbeadde.

The code above should be cleaned up with macros or at least constants instead of magic numbers, but hopefully it helps as is

EDIT: as another answer pointed out, there are platform, OS, and instruction set specific alternatives which can be MUCH faster than the above. In the Linux kernel there are macros (cpu_to_be32 for example) which handle endianness pretty nicely. But these alternatives are specific to their environments. In practice endianness is best dealt with using a blend of available approaches

Adding padding to a tkinter widget only on one side

There are multiple ways of doing that you can use either place or grid or even the packmethod.

Sample code:

from tkinter import *
root = Tk()

l = Label(root, text="hello" )
l.pack(padx=6, pady=4) # where padx and pady represent the x and y axis respectively
# well you can also use side=LEFT inside the pack method of the label widget.

To place a widget to on basis of columns and rows , use the grid method:

but = Button(root, text="hello" )
but.grid(row=0, column=1)

Invoke-Command error "Parameter set cannot be resolved using the specified named parameters"

I was solving same problem recently. I was designing a write cmdlet for my Subtitle module. I had six different user stories:

  • Subtitle only
  • Subtitle and path (original file name is used)
  • Subtitle and new file name (original path is used)
  • Subtitle and name suffix is used (original path and modified name is used).
  • Subtile, new path and new file name is is used.
  • Subtitle, new path and suffix is used.

I end up in the big frustration because I though that 4 parameters will be enough. Like most of the times, the frustration was pointless because it was my fault. I didn't know enough about parameter sets.

After some research in documentation, I realized where is the problem. With knowledge how the parameter sets should be used, I developed a general and simple approach how to solve this problem. A pencil and a sheet of paper is required but a spreadsheet editor is better:

  1. Write down all intended ways how the cmdlet should be used => user stories.
  2. Keep adding parameters with meaningful names and mark the use of the parameters until you have a unique collection set => no repetitive combination of parameters.
  3. Implement parameter sets into your code.
  4. Prepare tests for all possible user stories.
  5. Run tests (big surprise, right?). IDEs doesn't checks parameter sets collision, tests could save lots of trouble later one.

Example:

Unique parameter binding resolution approach.

The practical example could be seen over here.

BTW: The parameter uniqueness within parameter sets is the reason why the ParameterSetName property doesn't support [String[]]. It doesn't really make any sense.

Get a list of dates between two dates

You can use this

SELECT CAST(cal.date_list AS DATE) day_year
FROM (
  SELECT SUBDATE('2019-01-01', INTERVAL 1 YEAR) + INTERVAL xc DAY AS date_list
  FROM (
        SELECT @xi:=@xi+1 as xc from
        (SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4) xc1,
        (SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4) xc2,
        (SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4) xc3,
        (SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4) xc4,
        (SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4) xc5,
        (SELECT @xi:=-1) xc0
    ) xxc1
) cal
WHERE cal.date_list BETWEEN '2019-01-01' AND '2019-12-31'
ORDER BY cal.date_list DESC;

How to Consume WCF Service with Android

From my recent experience i would recommend ksoap library to consume a Soap WCF Service, its actually really easy, this anddev thread migh help you out too.

What is the difference between window, screen, and document in Javascript?

the window contains everything, so you can call window.screen and window.document to get those elements. Check out this fiddle, pretty-printing the contents of each object: http://jsfiddle.net/JKirchartz/82rZu/

You can also see the contents of the object in firebug/dev tools like this:

console.dir(window);
console.dir(document);
console.dir(screen);

window is the root of everything, screen just has screen dimensions, and document is top DOM object. so you can think of it as window being like a super-document...

How can I get session id in php and show it?

session_start();    
echo session_id();

Where is the documentation for the values() method of Enum?

Run this

    for (Method m : sex.class.getDeclaredMethods()) {
        System.out.println(m);
    }

you will see

public static test.Sex test.Sex.valueOf(java.lang.String)
public static test.Sex[] test.Sex.values()

These are all public methods that "sex" class has. They are not in the source code, javac.exe added them

Notes:

  1. never use sex as a class name, it's difficult to read your code, we use Sex in Java

  2. when facing a Java puzzle like this one, I recommend to use a bytecode decompiler tool (I use Andrey Loskutov's bytecode outline Eclispe plugin). This will show all what's inside a class

In a Git repository, how to properly rename a directory?

Basic rename (or move):

git mv <old name> <new name>

Case sensitive rename—eg. from casesensitive to CaseSensitive—you must use a two step:

git mv casesensitive tmp
git mv tmp CaseSensitive

(More about case sensitivity in Git…)

…followed by commit and push would be the simplest way to rename a directory in a git repo.

Constructors in JavaScript objects

This pattern has served me well. With this pattern, you create classes in separate files, load them into your overall app "as needed".

// Namespace
// (Creating new if not instantiated yet, otherwise, use existing and just add to it)
var myApp = myApp || {};

// "Package" 
// Similar to how you would establish a package in other languages
(function() {

// "Class"
var MyClass = function(params) {
    this.initialize(params);
}

    // "Private Static" vars 
    //    - Only accessible to functions in this class.
    //    - Doesn't get wiped out when we create a new instance.
    var countInstances = 0;
    var allInstances = [];

    // "Private Static" functions 
    //    - Same as above, but it's a function accessible 
    //      only to other functions in this class.
    function doSomething(){
    }

    // "Public Static" vars
    //    - Everyone has access.
    //    - Doesn't get wiped out when we create a new instance.
    MyClass.counter = 0;

    // "Public Static" functions
    //    - Same as above, but anyone can call this "static method".
    //    - Kinda like a singleton class situation.
    MyClass.foobar = function(){
    }

    // Public properties and methods are built into the "prototype"
    //    - This is how each instance can become unique unto itself.
    //    - Establishing "p" as "local" (Static Private) variable 
    //      simply so we don't have to keep typing "MyClass.prototype" 
    //      for each property and function.
var p = MyClass.prototype;

    // "Public" vars
    p.id = null;
    p.firstname = null;
    p.lastname = null;

    // "Private" vars
    //    - Only used by "this" instance.
    //    - There isn't "true" privacy for each 
    //      instance so we have to fake it. 
    //    - By tradition, we indicate "privacy"  
    //      by prefixing it with an underscore. 
    //    - So technically, anyone can access, but we simply 
    //      don't tell anyone about it (e.g. in your API)
    //      so no one knows about it :)
    p._foo = null;

    p.initialize = function(params){
        this.id = MyClass.counter++;
        this.firstname = params.firstname;
        this.lastname = params.lastname;
        MyClass.counter++;
        countInstances++;
        allInstances.push(this);
    }

    p.doAlert = function(theMessage){
        alert(this.firstname + " " + this.lastname + " said: " + theMessage + ". My id:" + this.id + ".  Total People:" + countInstances + ". First Person:" + allInstances[0].firstname + " " + allInstances[0].lastname);
    }


// Assign class to app
myApp.MyClass = MyClass;

// Close the "Package"
}());

// Usage example:
var bob = new myApp.MyClass({   firstname   :   "bob",
                                lastname    :   "er"
                            });

bob.doAlert("hello there");

How to read text file in JavaScript

my example

<html>

<head>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">
  <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
  <script src="http://code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
</head>

<body>
  <script>
    function PreviewText() {
      var oFReader = new FileReader();
      oFReader.readAsDataURL(document.getElementById("uploadText").files[0]);
      oFReader.onload = function(oFREvent) {
        document.getElementById("uploadTextValue").value = oFREvent.target.result;
        document.getElementById("obj").data = oFREvent.target.result;
      };
    };
    jQuery(document).ready(function() {
      $('#viewSource').click(function() {
        var text = $('#uploadTextValue').val();
        alert(text);
        //here ajax
      });
    });
  </script>
  <object width="100%" height="400" data="" id="obj"></object>
  <div>
    <input type="hidden" id="uploadTextValue" name="uploadTextValue" value="" />
    <input id="uploadText" style="width:120px" type="file" size="10" onchange="PreviewText();" />
  </div>
  <a href="#" id="viewSource">Source file</a>
</body>

</html>

Labeling file upload button

Pure CSS solution:

_x000D_
_x000D_
.inputfile {_x000D_
  /* visibility: hidden etc. wont work */_x000D_
  width: 0.1px;_x000D_
  height: 0.1px;_x000D_
  opacity: 0;_x000D_
  overflow: hidden;_x000D_
  position: absolute;_x000D_
  z-index: -1;_x000D_
}_x000D_
.inputfile:focus + label {_x000D_
  /* keyboard navigation */_x000D_
  outline: 1px dotted #000;_x000D_
  outline: -webkit-focus-ring-color auto 5px;_x000D_
}_x000D_
.inputfile + label * {_x000D_
  pointer-events: none;_x000D_
}
_x000D_
<input type="file" name="file" id="file" class="inputfile">_x000D_
<label for="file">Choose a file (Click me)</label>
_x000D_
_x000D_
_x000D_

source: http://tympanus.net/codrops

How to export MySQL database with triggers and procedures?

May be it's obvious for expert users of MYSQL but I wasted some time while trying to figure out default value would not export functions. So I thought to mention here that --routines param needs to be set to true to make it work.

mysqldump --routines=true -u <user> my_database > my_database.sql

Storyboard - refer to ViewController in AppDelegate

If you use XCode 5 you should do it in a different way.

  • Select your UIViewController in UIStoryboard
  • Go to the Identity Inspector on the right top pane
  • Check the Use Storyboard ID checkbox
  • Write a unique id to the Storyboard ID field

Then write your code.

// Override point for customization after application launch.

if (<your implementation>) {
    UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" 
                                                             bundle: nil];
    YourViewController *yourController = (YourViewController *)[mainStoryboard 
      instantiateViewControllerWithIdentifier:@"YourViewControllerID"];
    self.window.rootViewController = yourController;
}

return YES;

Error: Cannot find module 'webpack'

If you have installed a node package and are still getting message that the package is undefined, you might have an issue with the PATH linking to the binary. Just to clarify a binary and executable essentially do the same thing, which is to execute a package or application. ei webpack... executes the node package webpack.

In both Windows and Linux there is a global binary folder. In Windows I believe it's something like C://Windows/System32 and in Linux it's usr/bin. When you open the terminal/command prompt, the profile of it links the PATH variable to the global bin folder so you are able to execute packages/applications from it.

My best guess is that installing webpack globally may not have successfully put the executable file in the global binary folder. Without the executable there, you will get an error message. It could be another issue, but it is safe to say the that if you are here reading this, running webpack globally is not working for you.

My resolution to this problem is to do away with running webpack globally and link the PATH to the node_module binary folder, which is /node_modules/.bin.

WINDOWS: add node_modules/.bin to your PATH. Here is a tutorial on how to change the PATH variable in windows.

LINUX: Go to your project root and execute this...

export PATH=$PWD/node_modules/.bin:$PATH 

In Linux you will have to execute this command every time you open your terminal. This link here shows you how to make a change to your PATH variable permanent.

Using ng-click vs bind within link function of Angular Directive

myApp.directive("clickme",function(){
    return function(scope,element,attrs){
        element.bind("mousedown",function(){
             <<call the Controller function>>
              scope.loadEditfrm(attrs.edtbtn); 
        });
    };
});

this will act as onclick events on the attribute clickme

Reorder bars in geom_bar ggplot2 by value

Your code works fine, except that the barplot is ordered from low to high. When you want to order the bars from high to low, you will have to add a -sign before value:

ggplot(corr.m, aes(x = reorder(miRNA, -value), y = value, fill = variable)) + 
  geom_bar(stat = "identity")

which gives:

enter image description here


Used data:

corr.m <- structure(list(miRNA = structure(c(5L, 2L, 3L, 6L, 1L, 4L), .Label = c("mmu-miR-139-5p", "mmu-miR-1983", "mmu-miR-301a-3p", "mmu-miR-5097", "mmu-miR-532-3p", "mmu-miR-96-5p"), class = "factor"),
                         variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "pos", class = "factor"),
                         value = c(7L, 75L, 70L, 5L, 10L, 47L)),
                    class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6"))

Android SDK Manager Not Installing Components

The Access denied is because Windows doesn't give the default write and modify permission to the files in its install drive viz. c: To resolve this issue I usually use a separate drive or in your case, you need to set the access rights to the specific folder in the options right click -> options > security -> edit enter image description here

Plotting multiple curves same graph and same scale

points or lines comes handy if

  • y2 is generated later, or
  • the new data does not have the same x but still should go into the same coordinate system.

As your ys share the same x, you can also use matplot:

matplot (x, cbind (y1, y2), pch = 19)

matplot (x, cbind (y1, y2), pch = 19)

(without the pch matplopt will plot the column numbers of the y matrix instead of dots).

How to get the list of all installed color schemes in Vim?

Try

set wildmenu
set wildmode=list:full
set wildcharm=<C-z>
let mapleader=','
nnoremap <leader>c :colorscheme <C-z><S-Tab>

in your ~/.vimrc.

The first two lines make possible matches appear as lists. You can use either or both.

The fourth line makes leader , instead of the default \.

The last line allows you to simply type ,c to get a list and a prompt to change your colorscheme.

The third line effectively allows for Tabs to appear in key maps.

(Of course, all of these strategies I've learned from the internet, and mostly SO, very recently.)

Is it better to use NOT or <> when comparing values?

Agreed, code readability is very important for others, but more importantly yourself. Imagine how difficult it would be to understand the first example in comparison to the second.

If code takes more than a few seconds to read (understand), perhaps there is a better way to write it. In this case, the second way.

Eclipse C++ : "Program "g++" not found in PATH"

Maybe it has nothing to do here, but it could be useful for someone.
I installed jdk on: D:\Program Files\Java\jdk1.7.0_06\bin
So I added it to %PATH% variable and checked it on cmd and everything was ok, but Eclipse kept showing me that error.
I used quotation marks on %PATH% so it reads something like:

%SYSTEMROOT%\System32;"D:\Program Files\Java\jdk1.7.0_06\bin"

and problem solved.

CSS - make div's inherit a height

The Problem

When an element is floated, its parent no longer contains it because the float is removed from the flow. The floated element is out of the natural flow, so all block elements will render as if the floated element is not even there, so a parent container will not fully expand to hold the floated child element.

Take a look at the following article to get a better idea of how the CSS Float property works:

The Mystery Of The CSS Float Property


A Potential Solution

Now, I think the following article resembles what you're trying to do. Take a look at it and see if you can solve your problem.

Equal Height Columns with Cross-Browser CSS

I hope this helps.

How to convert Blob to String and String to Blob in java

How are you setting blob to DB? You should do:

 //imagine u have a a prepared statement like:
 PreparedStatement ps = conn.prepareStatement("INSERT INTO table VALUES (?)");
 String blobString= "This is the string u want to convert to Blob";
oracle.sql.BLOB myBlob = oracle.sql.BLOB.createTemporary(conn, false,oracle.sql.BLOB.DURATION_SESSION);
 byte[] buff = blobString.getBytes();
 myBlob.putBytes(1,buff);
 ps.setBlob(1, myBlob);
 ps.executeUpdate();

Using Caps Lock as Esc in Mac OS X

You can also use DoubleCommand to remap this, and other keys.

IIRC, it will map Caps Lock to Esc.

How to remove .html from URL?

For those who are using Firebase hosting none of the answers will work on this page. Because you can't use .htaccess in Firebase hosting. You will have to configure the firebase.json file. Just add the line "cleanUrls": true in your file and save it. That's it.

After adding the line firebase.json will look like this :

{
  "hosting": {
    "public": "public",
    "cleanUrls": true, 
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ]
  }
}

Performing Breadth First Search recursively

The dumb way:

template<typename T>
struct Node { Node* left; Node* right; T value; };

template<typename T, typename P>
bool searchNodeDepth(Node<T>* node, Node<T>** result, int depth, P pred) {
    if (!node) return false;
    if (!depth) {
        if (pred(node->value)) {
            *result = node;
        }
        return true;
    }
    --depth;
    searchNodeDepth(node->left, result, depth, pred);
    if (!*result)
        searchNodeDepth(node->right, result, depth, pred);
    return true;
}

template<typename T, typename P>
Node<T>* searchNode(Node<T>* node, P pred) {
    Node<T>* result = NULL;
    int depth = 0;
    while (searchNodeDepth(node, &result, depth, pred) && !result)
        ++depth;
    return result;
}

int main()
{
    // a c   f
    //  b   e
    //    d
    Node<char*>
        a = { NULL, NULL, "A" },
        c = { NULL, NULL, "C" },
        b = { &a, &c, "B" },
        f = { NULL, NULL, "F" },
        e = { NULL, &f, "E" },
        d = { &b, &e, "D" };

    Node<char*>* found = searchNode(&d, [](char* value) -> bool {
        printf("%s\n", value);
        return !strcmp((char*)value, "F");
    });

    printf("found: %s\n", found->value);

    return 0;
}

Generate a dummy-variable

Another way is to use mtabulate from qdapTools package, i.e.

df <- data.frame(var = sample(c("A", "B", "C"), 5, replace = TRUE))
  var
#1   C
#2   A
#3   C
#4   B
#5   B

library(qdapTools)
mtabulate(df$var)

which gives,

  A B C
1 0 0 1
2 1 0 0
3 0 0 1
4 0 1 0
5 0 1 0

Bootstrap 3 Styled Select dropdown looks ugly in Firefox on OS X

You can actually change the grey box around the dropdown arrow in IE:

        select::-ms-expand {
            width:12px;
            border:none;
            background:#fff;
        }

enter image description here

Why dict.get(key) instead of dict[key]?

What is the dict.get() method?

As already mentioned the get method contains an additional parameter which indicates the missing value. From the documentation

get(key[, default])

Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

An example can be

>>> d = {1:2,2:3}
>>> d[1]
2
>>> d.get(1)
2
>>> d.get(3)
>>> repr(d.get(3))
'None'
>>> d.get(3,1)
1

Are there speed improvements anywhere?

As mentioned here,

It seems that all three approaches now exhibit similar performance (within about 10% of each other), more or less independent of the properties of the list of words.

Earlier get was considerably slower, However now the speed is almost comparable along with the additional advantage of returning the default value. But to clear all our queries, we can test on a fairly large list (Note that the test includes looking up all the valid keys only)

def getway(d):
    for i in range(100):
        s = d.get(i)

def lookup(d):
    for i in range(100):
        s = d[i]

Now timing these two functions using timeit

>>> import timeit
>>> print(timeit.timeit("getway({i:i for i in range(100)})","from __main__ import getway"))
20.2124660015
>>> print(timeit.timeit("lookup({i:i for i in range(100)})","from __main__ import lookup"))
16.16223979

As we can see the lookup is faster than the get as there is no function lookup. This can be seen through dis

>>> def lookup(d,val):
...     return d[val]
... 
>>> def getway(d,val):
...     return d.get(val)
... 
>>> dis.dis(getway)
  2           0 LOAD_FAST                0 (d)
              3 LOAD_ATTR                0 (get)
              6 LOAD_FAST                1 (val)
              9 CALL_FUNCTION            1
             12 RETURN_VALUE        
>>> dis.dis(lookup)
  2           0 LOAD_FAST                0 (d)
              3 LOAD_FAST                1 (val)
              6 BINARY_SUBSCR       
              7 RETURN_VALUE  

Where will it be useful?

It will be useful whenever you want to provide a default value whenever you are looking up a dictionary. This reduces

 if key in dic:
      val = dic[key]
 else:
      val = def_val

To a single line, val = dic.get(key,def_val)

Where will it be NOT useful?

Whenever you want to return a KeyError stating that the particular key is not available. Returning a default value also carries the risk that a particular default value may be a key too!

Is it possible to have get like feature in dict['key']?

Yes! We need to implement the __missing__ in a dict subclass.

A sample program can be

class MyDict(dict):
    def __missing__(self, key):
        return None

A small demonstration can be

>>> my_d = MyDict({1:2,2:3})
>>> my_d[1]
2
>>> my_d[3]
>>> repr(my_d[3])
'None'

How to fix curl: (60) SSL certificate: Invalid certificate chain

After updating to OS X 10.9.2, I started having invalid SSL certificate issues with Homebrew, Textmate, RVM, and Github.

When I initiate a brew update, I was getting the following error:

fatal: unable to access 'https://github.com/Homebrew/homebrew/': SSL certificate problem: Invalid certificate chain
Error: Failure while executing: git pull -q origin refs/heads/master:refs/remotes/origin/master

I was able to alleviate some of the issue by just disabling the SSL verification in Git. From the console (a.k.a. shell or terminal):

git config --global http.sslVerify false

I am leary to recommend this because it defeats the purpose of SSL, but it is the only advice I've found that works in a pinch.

I tried rvm osx-ssl-certs update all which stated Already are up to date.

In Safari, I visited https://github.com and attempted to set the certificate manually, but Safari did not present the options to trust the certificate.

Ultimately, I had to Reset Safari (Safari->Reset Safari... menu). Then afterward visit github.com and select the certificate, and "Always trust" This feels wrong and deletes the history and stored passwords, but it resolved my SSL verification issues. A bittersweet victory.

CSS image overlay with color and transparency

JSFiddle Demo

HTML:

<div class="image-holder">
    <img src="http://codemancers.com/img/who-we-are-bg.png" />
</div>

CSS:

.image-holder {
    display:inline-block;
    position: relative;
}
.image-holder:after {
    content:'';
    top: 0;
    left: 0;
    z-index: 10;
    width: 100%;
    height: 100%;
    display: block;
    position: absolute;
    background: blue;
    opacity: 0.1;
}
.image-holder:hover:after {
    opacity: 0;
}

How can I change the font size using seaborn FacetGrid?

I've made small modifications to @paul-H code, such that you can set the font size for the x/y axes and legend independently. Hope it helps:

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
x = np.random.normal(size=37)
y = np.random.lognormal(size=37)

# defaults                                                                                                         
sns.set()
fig, ax = plt.subplots()
ax.plot(x, y, marker='s', linestyle='none', label='small')
ax.legend(loc='upper left', fontsize=20,bbox_to_anchor=(0, 1.1))
ax.set_xlabel('X_axi',fontsize=20);
ax.set_ylabel('Y_axis',fontsize=20);

plt.show()

This is the output:

enter image description here

How to change xampp localhost to another folder ( outside xampp folder)?

steps :

  1. run your xampp control panel
  2. click the button saying config
  3. select apache( httpd.conf )
  4. find document root

replace

DocumentRoot "C:/xampp/htdocs"
<Directory "C:/xampp/htdocs">

Those 2 lines

| C:/xampp/htdocs == current location for root |

|change C:/xampp/htdocs with any location you want|

  1. save it

DONE: start apache and go to the localhost see in action [ watch video click here ]

Finding row index containing maximum value using R

See ?order. You just need the last index (or first, in decreasing order), so this should do the trick:

order(matrix[,2],decreasing=T)[1]

Switch between python 2.7 and python 3.5 on Mac OS X

Similar to John Wilkey's answer I would run python2 by finding which python, something like using /usr/bin/python and then creating an alias in .bash_profile:

alias python2="/usr/bin/python"

I can now run python3 by calling python and python2 by calling python2.

How to use Elasticsearch with MongoDB?

Here how to do this on mongodb 3.0. I used this nice blog

  1. Install mongodb.
  2. Create data directories:
$ mkdir RANDOM_PATH/node1
$ mkdir RANDOM_PATH/node2> 
$ mkdir RANDOM_PATH/node3
  1. Start Mongod instances
$ mongod --replSet test --port 27021 --dbpath node1
$ mongod --replSet test --port 27022 --dbpath node2
$ mongod --replSet test --port 27023 --dbpath node3
  1. Configure the Replica Set:
$ mongo
config = {_id: 'test', members: [ {_id: 0, host: 'localhost:27021'}, {_id: 1, host: 'localhost:27022'}]};    
rs.initiate(config);
  1. Installing Elasticsearch:
a. Download and unzip the [latest Elasticsearch][2] distribution

b. Run bin/elasticsearch to start the es server.

c. Run curl -XGET http://localhost:9200/ to confirm it is working.
  1. Installing and configuring the MongoDB River:

$ bin/plugin --install com.github.richardwilly98.elasticsearch/elasticsearch-river-mongodb

$ bin/plugin --install elasticsearch/elasticsearch-mapper-attachments

  1. Create the “River” and the Index:

curl -XPUT 'http://localhost:8080/_river/mongodb/_meta' -d '{ "type": "mongodb", "mongodb": { "db": "mydb", "collection": "foo" }, "index": { "name": "name", "type": "random" } }'

  1. Test on browser:

    http://localhost:9200/_search?q=home

Get bytes from std::string in C++

If this is just plain vanilla C, then:

strcpy(buffer, text.c_str());

Assuming that buffer is allocated and large enough to hold the contents of 'text', which is the assumption in your original code.

If encrypt() takes a 'const char *' then you can use

encrypt(text.c_str())

and you do not need to copy the string.

Server.MapPath("."), Server.MapPath("~"), Server.MapPath(@"\"), Server.MapPath("/"). What is the difference?

Server.MapPath specifies the relative or virtual path to map to a physical directory.

  • Server.MapPath(".")1 returns the current physical directory of the file (e.g. aspx) being executed
  • Server.MapPath("..") returns the parent directory
  • Server.MapPath("~") returns the physical path to the root of the application
  • Server.MapPath("/") returns the physical path to the root of the domain name (is not necessarily the same as the root of the application)

An example:

Let's say you pointed a web site application (http://www.example.com/) to

C:\Inetpub\wwwroot

and installed your shop application (sub web as virtual directory in IIS, marked as application) in

D:\WebApps\shop

For example, if you call Server.MapPath() in following request:

http://www.example.com/shop/products/GetProduct.aspx?id=2342

then:

  • Server.MapPath(".")1 returns D:\WebApps\shop\products
  • Server.MapPath("..") returns D:\WebApps\shop
  • Server.MapPath("~") returns D:\WebApps\shop
  • Server.MapPath("/") returns C:\Inetpub\wwwroot
  • Server.MapPath("/shop") returns D:\WebApps\shop

If Path starts with either a forward slash (/) or backward slash (\), the MapPath() returns a path as if Path was a full, virtual path.

If Path doesn't start with a slash, the MapPath() returns a path relative to the directory of the request being processed.

Note: in C#, @ is the verbatim literal string operator meaning that the string should be used "as is" and not be processed for escape sequences.

Footnotes

  1. Server.MapPath(null) and Server.MapPath("") will produce this effect too.

Step-by-step debugging with IPython

the right, easy, cool, exact answer for the question is to use %run macro with -d flag.

In [4]: run -d myscript.py
NOTE: Enter 'c' at the ipdb>  prompt to continue execution.        
> /cygdrive/c/Users/mycodefolder/myscript.py(4)<module>()
      2                                                            
      3                        
----> 4 a=1                                            
      5 b=2

Drawing Circle with OpenGL

We will find the value of X and Y from this image. We know, sin?=vertical/hypotenuse and cos?=base/hypotenuse from the image we can say base=X and Y=vertical. Now we can write X=hypotenuse*cos? and Y=hypotenuse*sin?. We will find the value of X and Y from this image. We know, sin?=vertical/hypotenuse and cos?=base/hypotenuse from the image we can say X=base and Y=vertical. Now we can write X=hypotenuse * cos? and Y=hypotenuse * sin?.

Now look at this code

void display(){
float x,y;
glColor3f(1, 1, 0);
for(double i =0; i <= 360;){
    glBegin(GL_TRIANGLES);
    x=5*cos(i);
    y=5*sin(i);
    glVertex2d(x, y);
    i=i+.5;
    x=5*cos(i);
    y=5*sin(i);
    glVertex2d(x, y);
    glVertex2d(0, 0);
    glEnd();
    i=i+.5;
}
glEnd();

glutSwapBuffers();
}

How can I convert a string to upper- or lower-case with XSLT?

In XSLT 1.0 the upper-case() and lower-case() functions are not available. If you're using a 1.0 stylesheet the common method of case conversion is translate():

<xsl:variable name="lowercase" select="'abcdefghijklmnopqrstuvwxyz'" />
<xsl:variable name="uppercase" select="'ABCDEFGHIJKLMNOPQRSTUVWXYZ'" />


<xsl:template match="/">
  <xsl:value-of select="translate(doc, $lowercase, $uppercase)" />
</xsl:template>

Guzzle 6: no more json() method for responses

I use $response->getBody()->getContents() to get JSON from response. Guzzle version 6.3.0.

Initialize static variables in C++ class?

Since C++11 it can be done inside a class with constexpr.

class stat {
    public:
        // init inside class
        static constexpr double inlineStaticVar = 22;
};

The variable can now be accessed with:

stat::inlineStaticVar

Detect if PHP session exists

I use a combined version:

if(session_id() == '' || !isset($_SESSION)) {
    // session isn't started
    session_start();
}

Oracle 10g: Extract data (select) from XML (CLOB Type)

Try this instead:

select xmltype(t.xml).extract('//fax/text()').getStringVal() from mytab t

..The underlying connection was closed: An unexpected error occurred on a receive

The underlying connection was closed: An unexpected error occurred on a receive.

This problem occurs when the server or another network device unexpectedly closes an existing Transmission Control Protocol (TCP) connection. This problem may occur when a time-out value on the server or on the network device is set too low. To resolve this problem, see resolutions A, D, E, F, and O. The problem can also occur if the server resets the connection unexpectedly, such as if an unhandled exception crashes the server process. Analyze the server logs to see if this may be the issue.

Resolution

To resolve this problem, make sure that you are using the most recent version of the .NET Framework.

Add a method to the class to override the GetWebRequest method. This change lets you access the HttpWebRequest object. If you are using Microsoft Visual C#, the new method must be similar to the following.

class MyTestService:TestService.TestService
{
    protected override WebRequest GetWebRequest(Uri uri)
    {
        HttpWebRequest webRequest = (HttpWebRequest) base.GetWebRequest(uri);
        //Setting KeepAlive to false
        webRequest.KeepAlive = false;
        return webRequest;
    }
}

Excerpt from KB915599: You receive one or more error messages when you try to make an HTTP request in an application that is built on the .NET Framework 1.1 Service Pack 1.

how to force maven to update local repo

Even though this is an old question, I 've stumbled upon this issue multiple times and until now never figured out how to fix it. The update maven indices is a term coined by IntelliJ, and if it still doesn't work after you've compiled the first project, chances are that you are using 2 different maven installations.

Press CTRL+Shift+A to open up the Actions menu. Type Maven and go to Maven Settings. Check the Home Directory to use the same maven as you use via the command line

How to replace existing value of ArrayList element in Java

If you are unaware of the position to replace, use list iterator to find and replace element ListIterator.set(E e)

ListIterator<String> iterator = list.listIterator();
while (iterator.hasNext()) {
     String next = iterator.next();
     if (next.equals("Two")) {
         //Replace element
         iterator.set("New");
     }
 }

Cygwin Make bash command not found

I faced the same problem too. Look up to the left side, and select (full). (Make), (gcc) and many others will appear. You will be able to chose the search bar to find them easily.

How to uninstall Eclipse?

There is no automated uninstaller.

You have to remove Eclipse manually. At least Eclipse does not write anything in the system registry, so deleting some directories and files is enough.

Note: I use Unix style paths in this answer but the locations should be the same on Windows or Unix systems, so ~ refers to the user home directory even on Windows.

Why is there no uninstaller?

According to this discussion about uninstalling Eclipse, the reasoning for not providing an uninstaller is that the Eclipse installer is supposed to just automate a few tasks that in the past had to be done manually (like downloading and extracting Eclipse and adding shortcuts), so they also can be undone manually. There is no entry in "Programs and Features" because the installer does not register anything in the system registry.

How to quickly uninstall Eclipse

Just delete the Eclipse directory and any desktop and start menu shortcuts and be done with it, if you don't mind a few leftover files.

In my opinion this is generally enough and I would stop here, because multiple Eclipse installations can share some files and you don't accidentally want to delete those shared files. You also keep all your projects.

How to completely uninstall Eclipse

If you really want to remove Eclipse without leaving any traces, you have to manually delete

  • all desktop and start menu shortcuts
  • the installation directory (e.g. ~/eclipse/photon/)
  • the p2 bundle pool (which is often shared with other eclipse installations)

The installer has a "Bundle Pools" menu entry which lists the locations of all bundle pools. If you have other Eclipse installations on your system you can use the "Cleanup Agent" to clean up unused bundles. If you don't have any other Eclipse installations you can delete the whole bundle pool directory instead (by default ~/p2/).

If you want to completely remove the Eclipse installer too, delete the installer's executable and the ~/.eclipse/ directory.

Depending on what kind of work you did with Eclipse, there can be more directories that you may want to delete. If you used Maven, then ~/.m2/ contains the Maven cache and settings (shared with Maven CLI and other IDEs). If you develop Eclipse plugins, then there might be JUnit workspaces from test runs, next to you Eclipse workspace. Likewise other build tools and development environments used in Eclipse could have created similar directories.

How to delete all projects

If you want to delete your projects and workspace metadata, you have to delete your workspace(s). The default workspace location is ´~/workspace/´. You can also search for the .metadata directory to get all Eclipse workspaces on your machine.

If you are working with Git projects, these are generally not saved in the workspace but in the ~/git/ directory.

Using two CSS classes on one element

You can try this:

HTML

<div class="social">
    <div class="socialIcon"><img src="images/facebook.png" alt="Facebook" /></div>
    <div class="socialText">Find me on Facebook</div>
</div>

CSS CODE

.social {
  width:330px;
  height:75px;
  float:right;
  text-align:left;
  padding:10px 0;
  border-bottom:dotted 1px #6d6d6d;
}
.social .socialIcon{
  padding-top:0;
}
.social .socialText{
  border:0;
}

To add multiple class in the same element you can use the following format:

<div class="class1 class2 class3"></div>

DEMO

Convert String to Date in MS Access Query

If you need to display all the records after 2014-09-01, add this to your query:

SELECT * FROM Events
WHERE Format(Events.DATE_TIME,'yyyy-MM-dd hh:mm:ss')  >= Format("2014-09-01 00:00:00","yyyy-MM-dd hh:mm:ss")

How do I unset an element in an array in javascript?

This is how I would do it

 myArray.splice( myArray.indexOf('bar') , 1) 

How to align absolutely positioned element to center?

If you set both left and right to zero, and left and right margins to auto you can center an absolutely positioned element.

position:absolute;
left:0;
right:0;
margin-left:auto;
margin-right:auto;

What is the difference between npm install and npm run build?

The main difference is ::

npm install is a npm cli-command which does the predefined thing i.e, as written by Churro, to install dependencies specified inside package.json

npm run command-name or npm run-script command-name ( ex. npm run build ) is also a cli-command predefined to run your custom scripts with the name specified in place of "command-name". So, in this case npm run build is a custom script command with the name "build" and will do anything specified inside it (for instance echo 'hello world' given in below example package.json).

Ponits to note::

  1. One more thing, npm build and npm run build are two different things, npm run build will do custom work written inside package.json and npm build is a pre-defined script (not available to use directly)

  2. You cannot specify some thing inside custom build script (npm run build) script and expect npm build to do the same. Try following thing to verify in your package.json:

    { "name": "demo", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "build":"echo 'hello build'" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": {}, "dependencies": {} }

and run npm run build and npm build one by one and you will see the difference. For more about commands kindly follow npm documentation.

Cheers!!

Usages of doThrow() doAnswer() doNothing() and doReturn() in mockito

doThrow : Basically used when you want to throw an exception when a method is being called within a mock object.

public void validateEntity(final Object object){}
Mockito.doThrow(IllegalArgumentException.class)
.when(validationService).validateEntity(Matchers.any(AnyObjectClass.class));

doReturn : Used when you want to send back a return value when a method is executed.

public Socket getCosmosSocket() throws IOException {}
Mockito.doReturn(cosmosSocket).when(cosmosServiceImpl).getCosmosSocket();

doAnswer: Sometimes you need to do some actions with the arguments that are passed to the method, for example, add some values, make some calculations or even modify them doAnswer gives you the Answer interface that being executed in the moment that method is called, this interface allows you to interact with the parameters via the InvocationOnMock argument. Also, the return value of answer method will be the return value of the mocked method.

public ReturnValueObject quickChange(Object1 object);
Mockito.doAnswer(new Answer<ReturnValueObject>() {

        @Override
        public ReturnValueObject answer(final InvocationOnMock invocation) throws Throwable {

            final Object1 originalArgument = (invocation.getArguments())[0];
            final ReturnValueObject returnedValue = new ReturnValueObject();
            returnedValue.setCost(new Cost());

            return returnedValue ;
        }
}).when(priceChangeRequestService).quickCharge(Matchers.any(Object1.class));

doNothing: Is the easiest of the list, basically it tells Mockito to do nothing when a method in a mock object is called. Sometimes used in void return methods or method that does not have side effects, or are not related to the unit testing you are doing.

public void updateRequestActionAndApproval(final List<Object1> cmItems);

Mockito.doNothing().when(pagLogService).updateRequestActionAndApproval(
                Matchers.any(Object1.class));

How to tell if a connection is dead in python

If I'm not mistaken this is usually handled via a timeout.

Create a branch in Git from another branch

Various ways to create a branch in git from another branch:

This answer adds some additional insight, not already present in the existing answers, regarding just the title of the question itself (Create a branch in Git from another branch), but does not address the more narrow specifics of the question which already have sufficient answers here.

I'm adding this because I really needed to know how to do #1 below just now (create a new branch from a branch I do NOT have checked out), and it wasn't obvious how to do it, and Google searches led to here as a top search result. So, I'll share my findings here. This isn't touched upon well, if at all, by any other answer here.

While I'm at it, I'll also add my other most-common git branch commands I use in my regular workflow, below.

1. To create a new branch from a branch you do NOT have checked out:

Create branch2 from branch1 while you have any branch whatsoever checked out (ex: let's say you have master checked out):

git branch branch2 branch1

The general format is:

git branch <new_branch> [from_branch]

man git branch shows it as:

git branch [--track | --no-track] [-l] [-f] <branchname> [<start-point>]

2. To create a new branch from the branch you DO have checked out:

git branch new_branch

This is great for making backups before rebasing, squashing, hard resetting, etc.--before doing anything which could mess up your branch badly.

Ex: I'm on feature_branch1, and I'm about to squash 20 commits into 1 using git rebase -i master. In case I ever want to "undo" this, let's back up this branch first! I do this ALL...THE...TIME and find it super helpful and comforting to know I can always easily go back to this backup branch and re-branch off of it to try again in case I mess up feature_branch1 in the process:

git branch feature_branch1_BAK_20200814-1320hrs_about_to_squash

The 20200814-1120hrs part is the date and time in format YYYYMMDD-HHMMhrs, so that would be 13:20hrs (1:20pm) on 14 Aug. 2020. This way I have an easy way to find my backup branches until I'm sure I'm ready to delete them. If you don't do this and you mess up badly, you have to use git reflog to go find your branch prior to messing it up, which is much harder, more stressful, and more error-prone.

3. To create and check out a new branch from the branch you DO have checked out:

git checkout -b new_branch

4. To rename a branch

Just like renaming a regular file or folder in the terminal, git considered "renaming" to be more like a 'm'ove command, so you use git branch -m to rename a branch. Here's the general format:

git branch -m <old_name> <new_name>

man git branch shows it like this:

git branch (-m | -M) [<oldbranch>] <newbranch>

Example: let's rename branch_1 to branch_1.5:

git branch -m branch_1 branch_1.5

How to start Spyder IDE on Windows

If you are using Anaconda execute the following commands and your life will be saved!

conda update qt pyqt
conda update spyder

List of strings to one string

I would go with option A:

String.Join(String.Empty, los.ToArray());

My reasoning is because the Join method was written for that purpose. In fact if you look at Reflector, you'll see that unsafe code was used to really optimize it. The other two also WORK, but I think the Join function was written for this purpose, and I would guess, the most efficient. I could be wrong though...

As per @Nuri YILMAZ without .ToArray(), but this is .NET 4+:

String.Join(String.Empty, los);

Equivalent of Oracle's RowID in SQL Server

From http://vyaskn.tripod.com/programming_faq.htm#q17:

Oracle has a rownum to access rows of a table using row number or row id. Is there any equivalent for that in SQL Server? Or how to generate output with row number in SQL Server?

There is no direct equivalent to Oracle's rownum or row id in SQL Server. Strictly speaking, in a relational database, rows within a table are not ordered and a row id won't really make sense. But if you need that functionality, consider the following three alternatives:

  • Add an IDENTITY column to your table.

  • Use the following query to generate a row number for each row. The following query generates a row number for each row in the authors table of pubs database. For this query to work, the table must have a unique key.

    SELECT (SELECT COUNT(i.au_id) 
            FROM pubs..authors i 
            WHERE i.au_id >= o.au_id ) AS RowID, 
           au_fname + ' ' + au_lname AS 'Author name'
    FROM          pubs..authors o
    ORDER BY      RowID
    
  • Use a temporary table approach, to store the entire resultset into a temporary table, along with a row id generated by the IDENTITY() function. Creating a temporary table will be costly, especially when you are working with large tables. Go for this approach, if you don't have a unique key in your table.

Prevent typing non-numeric in input type number

Based on Nrzonline's answer: I fixed the problem of the multiple "." at the end of the input by adding a

let lastCharacterEntered

outside of the input and then onKeyPress

e => {
          var allowedChars = "0123456789.";
          function contains(stringValue, charValue) {
            return stringValue.indexOf(charValue) > -1;
          }
          var invalidKey =
            (e.key.length === 1 && !contains(allowedChars, e.key)) ||
            (e.key === "." && contains(e.target.value, "."));
          console.log(e.target.value);
          invalidKey && e.preventDefault();
          if (!invalidKey) {
            if (lastCharacterEntered === "." && e.key === ".") {
              e.preventDefault();
            } else {
              lastCharacterEntered = e.key;
            }
          }
        }

How to jump to top of browser page

I know this is old, but for those having problems in Edge:

Plain JS: window.scrollTop=0;

Unfortunately, scroll() and scrollTo() throw errors in Edge.

Spring Data JPA find by embedded object property

The above - findByBookIdRegion() did not work for me. The following works with the latest release of String Data JPA:

Page<QueuedBook> findByBookId_Region(Region region, Pageable pageable);

What is the difference between SQL Server 2012 Express versions?

Scroll down on that page and you'll see:

Express with Tools (with LocalDB) Includes the database engine and SQL Server Management Studio Express)
This package contains everything needed to install and configure SQL Server as a database server. Choose either LocalDB or Express depending on your needs above.

That's the SQLEXPRWT_x64_ENU.exe download.... (WT = with tools)


Express with Advanced Services (contains the database engine, Express Tools, Reporting Services, and Full Text Search)
This package contains all the components of SQL Express. This is a larger download than “with Tools,” as it also includes both Full Text Search and Reporting Services.

That's the SQLEXPRADV_x64_ENU.exe download ... (ADV = Advanced Services)


The SQLEXPR_x64_ENU.exe file is just the database engine - no tools, no Reporting Services, no fulltext-search - just barebones engine.

Parsing PDF files (especially with tables) with PDFBox

Try using TabulaPDF (https://github.com/tabulapdf/tabula) . This is very good library to extract table content from the PDF file. It is very as expected.

Good luck. :)

Why can't Python import Image from PIL?

had the same error while using pytorch code which had deprecated pillow code. since PILLOW_VERSION was deprecated, i worked around it by:

Simply duplicating the _version file and renaming it as PILLOW_VERSION.py in the same folder.

worked for me

How do I convert hh:mm:ss.000 to milliseconds in Excel?

you can do it like this:

cell[B1]: 0:04:58.727

cell[B2]: =FIND(".";B1)

cell[B3]: =LEFT(B1;B2-7)

cell[B4]: =MID(B1;11-8;2)

cell[B5]: =RIGHT(B1;6)

cell[B6]: =B3*3600000+B4*60000+B5

maybe you have to multiply B5 also with 1000.

=FIND(".";B1) is only necessary because you might have inputs like '0:04:58.727' or '10:04:58.727' with different length.

Turn off warnings and errors on PHP and MySQL

If you can't get to your php.ini file for some reason, disable errors to stdout (display_errors) in a .htaccess file in any directory by adding the following line:

php_flag display_errors off

additionally, you can add error logging to a file:

php_flag log_errors on

How do I delete virtual interface in Linux?

You can use sudo ip link delete to remove the interface.

Adding HTML entities using CSS content

CSS is not HTML. &nbsp; is a named character reference in HTML; equivalent to the decimal numeric character reference &#160;. 160 is the decimal code point of the NO-BREAK SPACE character in Unicode (or UCS-2; see the HTML 4.01 Specification). The hexadecimal representation of that code point is U+00A0 (160 = 10 × 161 + 0 × 160). You will find that in the Unicode Code Charts and Character Database.

In CSS you need to use a Unicode escape sequence for such characters, which is based on the hexadecimal value of the code point of a character. So you need to write

.breadcrumbs a:before {
  content: '\a0';
}

This works as long as the escape sequence comes last in a string value. If characters follow, there are two ways to avoid misinterpretation:

a) (mentioned by others) Use exactly six hexadecimal digits for the escape sequence:

.breadcrumbs a:before {
  content: '\0000a0foo';
}

b) Add one white-space (e. g., space) character after the escape sequence:

.breadcrumbs a:before {
  content: '\a0 foo';
}

(Since f is a hexadecimal digit, \a0f would otherwise mean GURMUKHI LETTER EE here, or ? if you have a suitable font.)

The delimiting white-space will be ignored, and this will be displayed  foo, where the displayed space here would be a NO-BREAK SPACE character.

The white-space approach ('\a0 foo') has the following advantages over the six-digit approach ('\0000a0foo'):

  • it is easier to type, because leading zeroes are not necessary, and digits do not need to be counted;
  • it is easier to read, because there is white-space between escape sequence and following text, and digits do not need to be counted;
  • it requires less space, because leading zeroes are not necessary;
  • it is upwards-compatible, because Unicode supporting code points beyond U+10FFFF in the future would require a modification of the CSS Specification.

Thus, to display a space after an escaped character, use two spaces in the stylesheet –

.breadcrumbs a:before {
  content: '\a0  foo';
}

– or make it explicit:

.breadcrumbs a:before {
  content: '\a0\20 foo';
}

See CSS 2.1, section "4.1.3 Characters and case" for details.

Sequel Pro Alternative for Windows

You say you've had problems with Navicat. For the record, I use Navicat and I haven't experienced the issue you describe. You might want to dig around, see if there's a reason for your problem and/or a solution, because given the question asked, my first recommendation would have been Navicat.

But if you want alternative suggestions, here are a few that I know of and have used:

MySQL has its own tool which you can download for free, called MySQL Workbench. Download it from here: http://wb.mysql.com/. My experience is that it's powerful, but I didn't really like the UI. But that's just my personal taste.

Another free program you might want to try is HeidiSQL. It's more similar to Navicat than MySQL Workbench. A colleague of mine loves it.

(interesting to note, by the way, that MariaDB (the forked version of MySQL) is currently shipped with HeidiSQL as its GUI tool)

Finally, if you're running a web server on your machine, there's always the option of a browser-based tool like PHPMyAdmin. It's actually a surprisingly powerful piece of software.