Programs & Examples On #Pi db

A historical database by OSIsoft used to archive data consisting mainly of timestamps and values.

yii2 redirect in controller action does not work?

In Yii2 we need to return() the result from the action.I think you need to add a return in front of your redirect.

  return $this->redirect(['user/index']);

How to restrict UITextField to take only numbers in Swift?

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    // return true if the replacementString only contains numeric characters
    let digits = NSCharacterSet.decimalDigitCharacterSet()
    for c in string {
        if !digits.characterIsMember(c) {
            return false
        }
    }

    return true
}

This solution will work even if the user switches keyboards or tries to paste a non-numeric string into the text field.

Make sure to set the delegate property of the appropriate text field.

json_encode is returning NULL?

ntd's anwser didn't solve my problem. For those in same situation, here is how I finally handled this error: Just utf8_encode each of your results.

while($row = mysql_fetch_assoc($result)){
    $rows[] = array_map('utf8_encode', $row);
}

Hope it helps!

Why is SQL Server 2008 Management Studio Intellisense not working?

I've had the same problem too. Searched everywhere online and can't find a solution. I did install Redgate's SQL Prompt which functions similarly to Intellisense, so maybe there was a conflict. I've since stopped the Prompt from running, but now no intellisense at all. Using SQL Server 2008 will SQLCMD mode off, no luck at all. This has happened before, a reinstall of SQL Server was the only thing that I could get to work.

Rails select helper - Default selected value, how?

This should work for you. It just passes {:value => params[:pid] } to the html_options variable.

<%= f.select :project_id, @project_select, {}, {:value => params[:pid] } %>

IF...THEN...ELSE using XML

<IF>
    <CONDITIONS>
        <CONDITION field="time" from="5pm" to="9pm"></CONDITION>
    </CONDITIONS>
    <RESULTS><...some actions defined.../></RESULTS>
    <ELSE>
        <RESULTS><...some other actions defined.../></RESULTS>        
    </ELSE>
</IF>

Here's my take on it. This will allow you to have multiple conditions.

jQuery trigger event when click outside the element

try these..

$(document).click(function(evt) {
    var target = evt.target.className;
    var inside = $(".menuWraper");
    //alert($(target).html());
    if ($.trim(target) != '') {
        if ($("." + target) != inside) {
            alert("bleep");
        }
    }
});

How to move from one fragment to another fragment on click of an ImageView in Android?

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_profile, container, false);
    notification = (ImageView)v.findViewById(R.id.notification);

    notification.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            FragmentTransaction fr = getFragmentManager().beginTransaction();
            fr.replace(R.id.container,new NotificationFragment());
            fr.commit();
        }
    });

    return v;
}

How to change the docker image installation directory?

With recent versions of Docker, you would set the value of the data-root parameter to your custom path, in /etc/docker/daemon.json (according to https://docs.docker.com/engine/reference/commandline/dockerd/#daemon-configuration-file).

With older versions, you can change Docker's storage base directory (where container and images go) using the -goption when starting the Docker daemon. (check docker --help). You can have this setting applied automatically when Docker starts by adding it to /etc/default/docker

How exactly does the android:onClick XML attribute differ from setOnClickListener?

Supporting Ruivo's answer, yes you have to declare method as "public" to be able to use in Android's XML onclick - I am developing an app targeting from API Level 8 (minSdk...) to 16 (targetSdk...).

I was declaring my method as private and it caused error, just declaring it as public works great.

How to escape the % (percent) sign in C's printf?

With itself...

printf("hello%%"); /* like this */

Difference between volatile and synchronized in Java

synchronized is method level/block level access restriction modifier. It will make sure that one thread owns the lock for critical section. Only the thread,which own a lock can enter synchronized block. If other threads are trying to access this critical section, they have to wait till current owner releases the lock.

volatile is variable access modifier which forces all threads to get latest value of the variable from main memory. No locking is required to access volatile variables. All threads can access volatile variable value at same time.

A good example to use volatile variable : Date variable.

Assume that you have made Date variable volatile. All the threads, which access this variable always get latest data from main memory so that all threads show real (actual) Date value. You don't need different threads showing different time for same variable. All threads should show right Date value.

enter image description here

Have a look at this article for better understanding of volatile concept.

Lawrence Dol cleary explained your read-write-update query.

Regarding your other queries

When is it more suitable to declare variables volatile than access them through synchronized?

You have to use volatile if you think all threads should get actual value of the variable in real time like the example I have explained for Date variable.

Is it a good idea to use volatile for variables that depend on input?

Answer will be same as in first query.

Refer to this article for better understanding.

SQL: parse the first, middle and last name from a fullname field

As everyone else says, you can't from a simple programmatic way.

Consider these examples:

  • President "George Herbert Walker Bush" (First Middle Middle Last)

  • Presidential assassin "John Wilkes Booth" (First Middle Last)

  • Guitarist "Eddie Van Halen" (First Last Last)

  • And his mom probably calls him Edward Lodewijk Van Halen (First Middle Last Last)

  • Famed castaway "Mary Ann Summers" (First First Last)

  • New Mexico GOP chairman "Fernando C de Baca" (First Last Last Last)

Most efficient way to check if a file is empty in Java on Windows

This is an improvement of Saik0's answer based on Anwar Shaikh's comment that too big files (above available memory) will throw an exception:

Using Apache Commons FileUtils

private void printEmptyFileName(final File file) throws IOException {
    /*Arbitrary big-ish number that definitely is not an empty file*/
    int limit = 4096;
    if(file.length < limit && FileUtils.readFileToString(file).trim().isEmpty()) {
        System.out.println("File is empty: " + file.getName());
    }        
}

JavaScript: how to change form action attribute value based on selection?

Simple and easy in javascipt

<script>

  document.getElementById("selectsearch").addEventListener("change", function(){

  var get_form =   document.getElementById("search-form") // get form 
  get_form.action =  '/search/' +  this.value; // assign value 

});

</script>

How Do I Insert a Byte[] Into an SQL Server VARBINARY Column

My solution would be to use a parameterised query, as the connectivity objects take care of formatting the data correctly (including ensuring the correct data-type, and escaping "dangerous" characters where applicable):

// Assuming "conn" is an open SqlConnection
using(SqlCommand cmd = new SqlCommand("INSERT INTO mssqltable(varbinarycolumn) VALUES (@binaryValue)", conn))
{
    // Replace 8000, below, with the correct size of the field
    cmd.Parameters.Add("@binaryValue", SqlDbType.VarBinary, 8000).Value = arraytoinsert;
    cmd.ExecuteNonQuery();
}

Edit: Added the wrapping "using" statement as suggested by John Saunders to correctly dispose of the SqlCommand after it is finished with

How do I programmatically force an onchange event on an input?

In jQuery I mostly use:

$("#element").trigger("change");

Checking whether a String contains a number value in Java

Another possible solution is to use a Scanner object like this:

Scanner scanner = new Scanner(inputString);  
if (scanner.hasNextInt()) {  
  return true;
}
else {
  return false
}

Of course, if you are looking for a double, use hasNextDouble() method (see: Scanner javadoc)

How do you test to see if a double is equal to NaN?

If your value under test is a Double (not a primitive) and might be null (which is obviously not a number too), then you should use the following term:

(value==null || Double.isNaN(value))

Since isNaN() wants a primitive (rather than boxing any primitive double to a Double), passing a null value (which can't be unboxed to a Double) will result in an exception instead of the expected false.

Sorting a Data Table

private void SortDataTable(DataTable dt, string sort)
{
DataTable newDT = dt.Clone();
int rowCount = dt.Rows.Count;

DataRow[] foundRows = dt.Select(null, sort);
// Sort with Column name
for (int i = 0; i < rowCount; i++)
{
object[] arr = new object[dt.Columns.Count];
for (int j = 0; j < dt.Columns.Count; j++)
{
arr[j] = foundRows[i][j];
}
DataRow data_row = newDT.NewRow();
data_row.ItemArray = arr;
newDT.Rows.Add(data_row);
}

//clear the incoming dt
dt.Rows.Clear();

for (int i = 0; i < newDT.Rows.Count; i++)
{
object[] arr = new object[dt.Columns.Count];
for (int j = 0; j < dt.Columns.Count; j++)
{
arr[j] = newDT.Rows[i][j];
}

DataRow data_row = dt.NewRow();
data_row.ItemArray = arr;
dt.Rows.Add(data_row);
}
}

How to import a module given the full path?

In Linux, adding a symbolic link in the directory your python script is located works.

ie:

ln -s /absolute/path/to/module/module.py /absolute/path/to/script/module.py

python will create /absolute/path/to/script/module.pyc and will update it if you change the contents of /absolute/path/to/module/module.py

then include the following in mypythonscript.py

from module import *

Compare two different files line by line in python

Yet another example...

from __future__ import print_function #Only for Python2

with open('file1.txt') as f1, open('file2.txt') as f2, open('outfile.txt', 'w') as outfile:
    for line1, line2 in zip(f1, f2):
        if line1 == line2:
            print(line1, end='', file=outfile)

And if you want to eliminate common blank lines, just change the if statement to:

if line1.strip() and line1 == line2:

.strip() removes all leading and trailing whitespace, so if that's all that's on a line, it will become an empty string "", which is considered false.

Detect If Browser Tab Has Focus

I would do it this way (Reference http://www.w3.org/TR/page-visibility/):

    window.onload = function() {

        // check the visiblility of the page
        var hidden, visibilityState, visibilityChange;

        if (typeof document.hidden !== "undefined") {
            hidden = "hidden", visibilityChange = "visibilitychange", visibilityState = "visibilityState";
        }
        else if (typeof document.mozHidden !== "undefined") {
            hidden = "mozHidden", visibilityChange = "mozvisibilitychange", visibilityState = "mozVisibilityState";
        }
        else if (typeof document.msHidden !== "undefined") {
            hidden = "msHidden", visibilityChange = "msvisibilitychange", visibilityState = "msVisibilityState";
        }
        else if (typeof document.webkitHidden !== "undefined") {
            hidden = "webkitHidden", visibilityChange = "webkitvisibilitychange", visibilityState = "webkitVisibilityState";
        }


        if (typeof document.addEventListener === "undefined" || typeof hidden === "undefined") {
            // not supported
        }
        else {
            document.addEventListener(visibilityChange, function() {
                console.log("hidden: " + document[hidden]);
                console.log(document[visibilityState]);

                switch (document[visibilityState]) {
                case "visible":
                    // visible
                    break;
                case "hidden":
                    // hidden
                    break;
                }
            }, false);
        }

        if (document[visibilityState] === "visible") {
            // visible
        }

    };  

Open file in a relative location in Python

This code works fine:

import os


def readFile(filename):
    filehandle = open(filename)
    print filehandle.read()
    filehandle.close()



fileDir = os.path.dirname(os.path.realpath('__file__'))
print fileDir

#For accessing the file in the same folder
filename = "same.txt"
readFile(filename)

#For accessing the file in a folder contained in the current folder
filename = os.path.join(fileDir, 'Folder1.1/same.txt')
readFile(filename)

#For accessing the file in the parent folder of the current folder
filename = os.path.join(fileDir, '../same.txt')
readFile(filename)

#For accessing the file inside a sibling folder.
filename = os.path.join(fileDir, '../Folder2/same.txt')
filename = os.path.abspath(os.path.realpath(filename))
print filename
readFile(filename)

Why is ZoneOffset.UTC != ZoneId.of("UTC")?

The answer comes from the javadoc of ZoneId (emphasis mine) ...

A ZoneId is used to identify the rules used to convert between an Instant and a LocalDateTime. There are two distinct types of ID:

  • Fixed offsets - a fully resolved offset from UTC/Greenwich, that uses the same offset for all local date-times
  • Geographical regions - an area where a specific set of rules for finding the offset from UTC/Greenwich apply

Most fixed offsets are represented by ZoneOffset. Calling normalized() on any ZoneId will ensure that a fixed offset ID will be represented as a ZoneOffset.

... and from the javadoc of ZoneId#of (emphasis mine):

This method parses the ID producing a ZoneId or ZoneOffset. A ZoneOffset is returned if the ID is 'Z', or starts with '+' or '-'.

The argument id is specified as "UTC", therefore it will return a ZoneId with an offset, which also presented in the string form:

System.out.println(now.withZoneSameInstant(ZoneOffset.UTC));
System.out.println(now.withZoneSameInstant(ZoneId.of("UTC")));

Outputs:

2017-03-10T08:06:28.045Z
2017-03-10T08:06:28.045Z[UTC]

As you use the equals method for comparison, you check for object equivalence. Because of the described difference, the result of the evaluation is false.

When the normalized() method is used as proposed in the documentation, the comparison using equals will return true, as normalized() will return the corresponding ZoneOffset:

Normalizes the time-zone ID, returning a ZoneOffset where possible.

now.withZoneSameInstant(ZoneOffset.UTC)
    .equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())); // true

As the documentation states, if you use "Z" or "+0" as input id, of will return the ZoneOffset directly and there is no need to call normalized():

now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("Z"))); //true
now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("+0"))); //true

To check if they store the same date time, you can use the isEqual method instead:

now.withZoneSameInstant(ZoneOffset.UTC)
    .isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))); // true

Sample

System.out.println("equals - ZoneId.of(\"UTC\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("UTC"))));
System.out.println("equals - ZoneId.of(\"UTC\").normalized(): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())));
System.out.println("equals - ZoneId.of(\"Z\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("Z"))));
System.out.println("equals - ZoneId.of(\"+0\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("+0"))));
System.out.println("isEqual - ZoneId.of(\"UTC\"): "+ nowZoneOffset
        .isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))));

Output:

equals - ZoneId.of("UTC"): false
equals - ZoneId.of("UTC").normalized(): true
equals - ZoneId.of("Z"): true
equals - ZoneId.of("+0"): true
isEqual - ZoneId.of("UTC"): true

What is class="mb-0" in Bootstrap 4?

Bootstrap 4

It is used to create a bottom margin of 0 (margin-bottom:0). You can see more of the new spacing utility classes here: https://getbootstrap.com/docs/4.0/utilities/spacing/

Related: How do I use the Spacing Utility Classes on Bootstrap 4

Select mySQL based only on month and year

Here is a query that I use and it will return each record within a period as a sum.

Here is the code:

$result = mysqli_query($conn,"SELECT emp_nr, SUM(az) 
FROM az_konto 
WHERE date BETWEEN '2018-01-01 00:00:00' AND '2018-01-31 23:59:59' 
GROUP BY emp_nr ASC");

echo "<table border='1'>
<tr>
<th>Mitarbeiter NR</th>
<th>Stunden im Monat</th>
</tr>";

while($row = mysqli_fetch_array($result))
{
$emp_nr=$row['emp_nr'];
$az=$row['SUM(az)'];
echo "<tr>";
echo "<td>" . $emp_nr . "</td>";
echo "<td>" . $az . "</td>";
echo "</tr>";
}
echo "</table>";
$conn->close();
?>

This lists each emp_nr and the sum of the monthly hours that they have accumulated.

datetime datatype in java

I used this import:

import java.util.Date;

And declared my variable like this:

Date studentEnrollementDate;

Better way to Format Currency Input editText?

I got this from here and changed it to comply with Portuguese currency format.

import java.text.NumberFormat;
import java.util.Currency;
import java.util.Locale;

import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

public class CurrencyTextWatcher implements TextWatcher {

    private String current = "";
    private int index;
    private boolean deletingDecimalPoint;
    private final EditText currency;

    public CurrencyTextWatcher(EditText p_currency) {
        currency = p_currency;
    }


    @Override
    public void beforeTextChanged(CharSequence p_s, int p_start, int p_count, int p_after) {

        if (p_after>0) {
                index = p_s.length() - p_start;
            } else {
                index = p_s.length() - p_start - 1;
            }
            if (p_count>0 && p_s.charAt(p_start)==',') {
                deletingDecimalPoint = true;
            } else {
                deletingDecimalPoint = false;
            }

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable p_s) {


         if(!p_s.toString().equals(current)){
                currency.removeTextChangedListener(this);
                if (deletingDecimalPoint) {
                    p_s.delete(p_s.length()-index-1, p_s.length()-index);
                }
                // Currency char may be retrieved from  NumberFormat.getCurrencyInstance()
                String v_text = p_s.toString().replace("€","").replace(",", "");
                v_text = v_text.replaceAll("\\s", "");
                double v_value = 0;
                if (v_text!=null && v_text.length()>0) {
                    v_value = Double.parseDouble(v_text);
                }
                // Currency instance may be retrieved from a static member.
                NumberFormat numberFormat = NumberFormat.getCurrencyInstance(new Locale("pt", "PT"));
                String v_formattedValue = numberFormat.format((v_value/100));
                current = v_formattedValue;
                currency.setText(v_formattedValue);
                if (index>v_formattedValue.length()) {
                    currency.setSelection(v_formattedValue.length());
                } else {
                    currency.setSelection(v_formattedValue.length()-index);
                }
                // include here anything you may want to do after the formatting is completed.
                currency.addTextChangedListener(this);
             }
    }

}

The layout.xml

<EditText
    android:id="@+id/edit_text_your_id"
    ...
    android:text="0,00 €"
    android:inputType="numberDecimal"
    android:digits="0123456789" />

Get it to work

    yourEditText = (EditText) findViewById(R.id.edit_text_your_id);
    yourEditText.setRawInputType(Configuration.KEYBOARD_12KEY);
    yourEditText.addTextChangedListener(new CurrencyTextWatcher(yourEditText));

XML to CSV Using XSLT

Here is a version with configurable parameters that you can set programmatically:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text" encoding="utf-8" />

  <xsl:param name="delim" select="','" />
  <xsl:param name="quote" select="'&quot;'" />
  <xsl:param name="break" select="'&#xA;'" />

  <xsl:template match="/">
    <xsl:apply-templates select="projects/project" />
  </xsl:template>

  <xsl:template match="project">
    <xsl:apply-templates />
    <xsl:if test="following-sibling::*">
      <xsl:value-of select="$break" />
    </xsl:if>
  </xsl:template>

  <xsl:template match="*">
    <!-- remove normalize-space() if you want keep white-space at it is --> 
    <xsl:value-of select="concat($quote, normalize-space(), $quote)" />
    <xsl:if test="following-sibling::*">
      <xsl:value-of select="$delim" />
    </xsl:if>
  </xsl:template>

  <xsl:template match="text()" />
</xsl:stylesheet>

reStructuredText tool support

Salvaging (and extending) the list from an old version of the Wikipedia page:

Documentation

Implementations

Although the reference implementation of reStructuredText is written in Python, there are reStructuredText parsers in other languages too.

Python - Docutils

The main distribution of reStructuredText is the Python Docutils package. It contains several conversion tools:

  • rst2html - from reStructuredText to HTML
  • rst2xml - from reStructuredText to XML
  • rst2latex - from reStructuredText to LaTeX
  • rst2odt - from reStructuredText to ODF Text (word processor) document.
  • rst2s5 - from reStructuredText to S5, a Simple Standards-based Slide Show System
  • rst2man - from reStructuredText to Man page

Haskell - Pandoc

Pandoc is a Haskell library for converting from one markup format to another, and a command-line tool that uses this library. It can read Markdown and (subsets of) reStructuredText, HTML, and LaTeX, and it can write Markdown, reStructuredText, HTML, LaTeX, ConTeXt, PDF, RTF, DocBook XML, OpenDocument XML, ODT, GNU Texinfo, MediaWiki markup, groff man pages, and S5 HTML slide shows.

There is an Pandoc online tool (POT) to try this library. Unfortunately, compared to the reStructuredText online renderer (ROR),

  • POT truncates input rather more shortly. The POT user must render input in chunks that could be rendered whole by the ROR.
  • POT output lacks the helpful error messages displayed by the ROR (and generated by docutils)

Java - JRst

JRst is a Java reStructuredText parser. It can currently output HTML, XHTML, DocBook xdoc and PDF, BUT seems to have serious problems: neither PDF or (X)HTML generation works using the current full download, result pages in (X)HTML are empty and PDF generation fails on IO problems with XSL files (not bundled??). Note that the original JRst has been removed from the website; a fork is found on GitHub.

Scala - Laika

Laika is a new library for transforming markup languages to other output formats. Currently it supports input from Markdown and reStructuredText and produce HTML output. The library is written in Scala but should be also usable from Java.

Perl

PHP

C#/.NET

Nim/C

The Nim compiler features the commands rst2htmland rst2tex which transform reStructuredText files to HTML and TeX files. The standard library provides the following modules (used by the compiler) to handle reStructuredText files programmatically:

  • rst - implements a reStructuredText parser
  • rstast - implements an AST for the reStructuredText parser
  • rstgen - implements a generator of HTML/Latex from reStructuredText

Other 3rd party converters

Most (but not all) of these tools are based on Docutils (see above) and provide conversion to or from formats that might not be supported by the main distribution.

From reStructuredText

  • restview - This pip-installable python package requires docutils, which does the actual rendering. restview's major ease-of-use feature is that, when you save changes to your document(s), it automagically re-renders and re-displays them. restview
    1. starts a small web server
    2. calls docutils to render your document(s) to HTML
    3. calls your device's browser to display the output HTML.
  • rst2pdf - from reStructuredText to PDF
  • rst2odp - from reStructuredText to ODF Presentation
  • rst2beamer - from reStructuredText to LaTeX beamer Presentation class
  • Wikir - from reStructuredText to a Google (and possibly other) Wiki formats
  • rst2qhc - Convert a collection of reStructuredText files into a Qt (toolkit) Help file and (optional) a Qt Help Project file

To reStructuredText

  • xml2rst is an XSLT script to convert Docutils internal XML representation (back) to reStructuredText
  • Pandoc (see above) can also convert from Markdown, HTML and LaTeX to reStructuredText
  • db2rst is a simple and limited DocBook to reStructuredText translator
  • pod2rst - convert .pod files to reStructuredText files

Extensions

Some projects use reStructuredText as a baseline to build on, or provide extra functionality extending the utility of the reStructuredText tools.

Sphinx

The Sphinx documentation generator translates a set of reStructuredText source files into various output formats, automatically producing cross-references, indices etc.

rest2web

rest2web is a simple tool that lets you build your website from a single template (or as many as you want), and keep the contents in reStructuredText.

Pygments

Pygments is a generic syntax highlighter for general use in all kinds of software such as forum systems, Wikis or other applications that need to prettify source code. See Using Pygments in reStructuredText documents.

Free Editors

While any plain text editor is suitable to write reStructuredText documents, some editors have better support than others.

Emacs

The Emacs support via rst-mode comes as part of the Docutils package under /docutils/tools/editors/emacs/rst.el

Vim

The vim-common package for that comes with most GNU/Linux distributions has reStructuredText syntax highlight and indentation support of reStructuredText out of the box:

Jed

There is a rst mode for the Jed programmers editor.

gedit

gedit, the official text editor of the GNOME desktop environment. There is a gedit reStructuredText plugin.

Geany

Geany, a small and lightweight Integrated Development Environment include support for reStructuredText from version 0.12 (October 10, 2007).

Leo

Leo, an outlining editor for programmers, supports reStructuredText via rst-plugin or via "@auto-rst" nodes (it's not well-documented, but @auto-rst nodes allow editing rst files directly, parsing the structure into the Leo outline).

It also provides a way to preview the resulting HTML, in a "viewrendered" pane.

FTE

The FTE Folding Text Editor - a free (licensed under the GNU GPL) text editor for developers. FTE has a mode for reStructuredText support. It provides color highlighting of basic RSTX elements and special menu that provide easy way to insert most popular RSTX elements to a document.

PyK

PyK is a successor of PyEdit and reStInPeace, written in Python with the help of the Qt4 toolkit.

Eclipse

The Eclipse IDE with the ReST Editor plug-in provides support for editing reStructuredText files.

NoTex

NoTex is a browser based (general purpose) text editor, with integrated project management and syntax highlighting. Plus it enables to write books, reports, articles etc. using rST and convert them to LaTex, PDF or HTML. The PDF files are of high publication quality and are produced via Sphinx with the Texlive LaTex suite.

Notepad++

Notepad++ is a general purpose text editor for Windows. It has syntax highlighting for many languages built-in and support for reStructuredText via a user defined language for reStructuredText.

Visual Studio Code

Visual Studio Code is a general purpose text editor for Windows/macOS/Linux. It has syntax highlighting for many languages built-in and supports reStructuredText via an extension from LeXtudio.

Dedicated reStructuredText Editors

Proprietary editors

Sublime Text

Sublime Text is a completely customizable and extensible source code editor available for Windows, OS X, and Linux. Registration is required for long-term use, but all functions are available in the unregistered version, with occasional reminders to purchase a license. Versions 2 and 3 (currently in beta) support reStructuredText syntax highlighting by default, and several plugins are available through the package manager Package Control to provide snippets and code completion, additional syntax highlighting, conversion to/from RST and other formats, and HTML preview in the browser.

BBEdit / TextWrangler

BBEdit (and its free variant TextWrangler) for Mac can syntax-highlight reStructuredText using this codeless language module.

TextMate

TextMate, a proprietary general-purpose GUI text editor for Mac OS X, has a bundle for reStructuredText.

Intype

Intype is a proprietary text editor for Windows, that support reStructuredText out of the box.

E Text Editor

E is a proprietary Text Editor licensed under the "Open Company License". It supports TextMate's bundles, so it should support reStructuredText the same way TextMate does.

PyCharm

PyCharm (and other IntelliJ platform IDEs?) has ReST/Sphinx support (syntax highlighting, autocomplete and preview).instant preview)

Wiki

here are some Wiki programs that support the reStructuredText markup as the native markup syntax, or as an add-on:

MediaWiki

MediaWiki reStructuredText extension allows for reStructuredText markup in MediaWiki surrounded by <rst> and </rst>.

MoinMoin

MoinMoin is an advanced, easy to use and extensible WikiEngine with a large community of users. Said in a few words, it is about collaboration on easily editable web pages.

There is a reStructuredText Parser for MoinMoin.

Trac

Trac is an enhanced wiki and issue tracking system for software development projects. There is a reStructuredText Support in Trac.

This Wiki

This Wiki is a Webware for Python Wiki written by Ian Bicking. This wiki uses ReStructuredText for its markup.

rstiki

rstiki is a minimalist single-file personal wiki using reStructuredText syntax (via docutils) inspired by pwyky. It does not support authorship indication, versioning, hierarchy, chrome/framing/templating or styling. It leverages docutils/reStructuredText as the wiki syntax. As such, it's under 200 lines of code, and in a single file. You put it in a directory and it runs.

ikiwiki

Ikiwiki is a wiki compiler. It converts wiki pages into HTML pages suitable for publishing on a website. Ikiwiki stores pages and history in a revision control system such as Subversion or Git. There are many other features, including support for blogging, as well as a large array of plugins. It's reStructuredText plugin, however is somewhat limited and is not recommended as its' main markup language at this time.

Web Services

Sandbox

An Online reStructuredText editor can be used to play with the markup and see the results immediately.

Blogging frameworks

WordPress

WordPreSt reStructuredText plugin for WordPress. (PHP)

Zine

reStructuredText parser plugin for Zine (will become obsolete in version 0.2 when Zine is scheduled to get a native reStructuredText support). Zine is discontinued. (Python)

pelican

Pelican is a static blog generator that supports writing articles in ReST. (Python)

hyde

Hyde is a static website generator that supports ReST. (Python)

Acrylamid

Acrylamid is a static blog generator that supports writing articles in ReST. (Python)

Nikola

Nikola is a Static Site and Blog Generator that supports ReST. (Python)

ipsum genera

Ipsum genera is a static blog generator written in Nim.

Yozuch

Yozuch is a static blog generator written in Python.

More

How to get htaccess to work on MAMP

I'm using MAMP (downloaded today) and had this problem also. The issue is with this version of the MAMP stack's default httpd.conf directive around line 370. Look at httpd.conf down at around line 370 and you will find:

<Directory "/Applications/MAMP/bin/mamp">
    Options Indexes MultiViews
    AllowOverride None
    Order allow,deny
    Allow from all
</Directory>

You need to change: AllowOverride None To: AllowOverride All

visual c++: #include files from other projects in the same solution

Try to avoid complete path references in the #include directive, whether they are absolute or relative. Instead, add the location of the other project's include folder in your project settings. Use only subfolders in path references when necessary. That way, it is easier to move things around without having to update your code.

How do you UDP multicast in Python?

This example doesn't work for me, for an obscure reason.

Not obscure, it's simple routing.

On OpenBSD

route add -inet 224.0.0.0/4 224.0.0.1

You can set the route to a dev on Linux

route add -net 224.0.0.0 netmask 240.0.0.0 dev wlp2s0

force all multicast traffic to one interface on Linux

   ifconfig wlp2s0 allmulti

tcpdump is super simple

tcpdump -n multicast

In your code you have:

while True:
  # For Python 3, change next line to "print(sock.recv(10240))"

Why 10240?

multicast packet size should be 1316 bytes

Abstract methods in Python

Before abc was introduced you would see this frequently.

class Base(object):
    def go(self):
        raise NotImplementedError("Please Implement this method")


class Specialized(Base):
    def go(self):
        print "Consider me implemented"

UITableView Cell selected Color?

Create a custom cell for your table cell and in the custom cell class.m put the code below, it will work fine. You need to place the desired color image in selectionBackground UIImage.

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    UIImage *selectionBackground = [UIImage imageNamed:@"yellow_bar.png"];
    UIImageView *iview=[[UIImageView alloc] initWithImage:selectionBackground];
    self.selectedBackgroundView=iview;
}

How do I change select2 box height

I came here looking for a way to specify the height of the select2-enabled dropdown. That what has worked for me:

.select2-container .select2-choice, .select2-result-label {
  font-size: 1.5em;
  height: 41px; 
  overflow: auto;
}

.select2-arrow, .select2-chosen {
  padding-top: 6px;
}

BEFORE:

enter image description here enter image description here

AFTER: select-2 enabled dropdown with css-defined height enter image description here

How to determine if Javascript array contains an object with an attribute that equals a given value?

May be too late, but javascript array has two methods some and every method that returns a boolean and can help you achieve this.

I think some would be most appropriate for what you intend to achieve.

vendors.some( vendor => vendor['Name'] !== 'Magenic' )

Some validates that any of the objects in the array satisfies the given condition.

vendors.every( vendor => vendor['Name'] !== 'Magenic' )

Every validates that all the objects in the array satisfies the given condition.

Byte Array to Hex String

Using str.format:

>>> array_alpha = [ 133, 53, 234, 241 ]
>>> print ''.join('{:02x}'.format(x) for x in array_alpha)
8535eaf1

or using format

>>> print ''.join(format(x, '02x') for x in array_alpha)
8535eaf1

Note: In the format statements, the 02 means it will pad with up to 2 leading 0s if necessary. This is important since [0x1, 0x1, 0x1] i.e. (0x010101) would be formatted to "111" instead of "010101"

or using bytearray with binascii.hexlify:

>>> import binascii
>>> binascii.hexlify(bytearray(array_alpha))
'8535eaf1'

Here is a benchmark of above methods in Python 3.6.1:

from timeit import timeit
import binascii

number = 10000

def using_str_format() -> str:
    return "".join("{:02x}".format(x) for x in test_obj)

def using_format() -> str:
    return "".join(format(x, "02x") for x in test_obj)

def using_hexlify() -> str:
    return binascii.hexlify(bytearray(test_obj)).decode('ascii')

def do_test():
    print("Testing with {}-byte {}:".format(len(test_obj), test_obj.__class__.__name__))
    if using_str_format() != using_format() != using_hexlify():
        raise RuntimeError("Results are not the same")

    print("Using str.format       -> " + str(timeit(using_str_format, number=number)))
    print("Using format           -> " + str(timeit(using_format, number=number)))
    print("Using binascii.hexlify -> " + str(timeit(using_hexlify, number=number)))

test_obj = bytes([i for i in range(255)])
do_test()

test_obj = bytearray([i for i in range(255)])
do_test()

Result:

Testing with 255-byte bytes:
Using str.format       -> 1.459474583090427
Using format           -> 1.5809937679100738
Using binascii.hexlify -> 0.014521426401399307
Testing with 255-byte bytearray:
Using str.format       -> 1.443447684109402
Using format           -> 1.5608712609513171
Using binascii.hexlify -> 0.014114164661833684

Methods using format do provide additional formatting options, as example separating numbers with spaces " ".join, commas ", ".join, upper-case printing "{:02X}".format(x)/format(x, "02X"), etc., but at a cost of great performance impact.

The located assembly's manifest definition does not match the assembly reference

I got this error while building on Team Foundation Server's build-service. It turned out I had multiple projects in my solution using different versions of the same library added with NuGet. I removed all old versions with NuGet and added the new one as reference for all.

Team Foundation Server puts all DLL files in one directory, and there can only be one DLL file of a certain name at a time of course.

Renaming files in a folder to sequential numbers

I like gauteh's solution for its simplicity, but it has an important drawback. When running on thousands of files, you can get "argument list too long" message (more on this), and second, the script can get really slow. In my case, running it on roughly 36.000 files, script moved approx. one item per second! I'm not really sure why this happens, but the rule I got from colleagues was "find is your friend".

find -name '*.jpg' | # find jpegs
gawk 'BEGIN{ a=1 }{ printf "mv %s %04d.jpg\n", $0, a++ }' | # build mv command
bash # run that command

To count items and build command, gawk was used. Note the main difference, though. By default find searches for files in current directory and its subdirectories, so be sure to limit the search on current directory only, if necessary (use man find to see how).

PHP - Redirect and send data via POST

I used the following code to capture POST data that was submitted from form.php and then concatenate it onto a URL to send it BACK to the form for validation corrections. Works like a charm, and in effect converts POST data into GET data.

foreach($_POST as $key => $value) {
   $urlArray[] =  $key."=".$value;  
}
$urlString = implode("&", $urlArray);

echo "Please <a href='form.php?".$urlString."'>go back</a>";

Where is the WPF Numeric UpDown control?

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:numericButton2">


    <Style TargetType="{x:Type local:NumericUpDown}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:NumericUpDown}">              
                        <Grid>
                            <Grid.RowDefinitions>
                                <RowDefinition Height="*"/>
                                <RowDefinition Height="*"/>
                                <RowDefinition Height="*"/>
                            </Grid.RowDefinitions>
                            <RepeatButton Grid.Row="0" Name="Part_UpButton"/>
                            <ContentPresenter Grid.Row="1"></ContentPresenter>
                            <RepeatButton Grid.Row="2" Name="Part_DownButton"/>
                        </Grid>                  
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

    <Window x:Class="numericButton2.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:local="clr-namespace:numericButton2"
            Title="MainWindow" Height="350" Width="525">
        <Grid>
            <local:NumericUpDown Margin="181,94,253,161" x:Name="ufuk" StepValue="4" Minimum="0" Maximum="20">            
            </local:NumericUpDown>
            <TextBlock Margin="211,112,279,0" Text="{Binding ElementName=ufuk, Path=Value}" Height="20" VerticalAlignment="Top"></TextBlock>
        </Grid>
    </Window>
public class NumericUpDown : Control
{
    private RepeatButton _UpButton;
    private RepeatButton _DownButton;
    public readonly static DependencyProperty MaximumProperty;
    public readonly static DependencyProperty MinimumProperty;
    public readonly static DependencyProperty ValueProperty;
    public readonly static DependencyProperty StepProperty;   
    static NumericUpDown()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(NumericUpDown), new FrameworkPropertyMetadata(typeof(NumericUpDown)));
        MaximumProperty = DependencyProperty.Register("Maximum", typeof(int), typeof(NumericUpDown), new UIPropertyMetadata(10));
        MinimumProperty = DependencyProperty.Register("Minimum", typeof(int), typeof(NumericUpDown), new UIPropertyMetadata(0));
        StepProperty = DependencyProperty.Register("StepValue", typeof(int), typeof(NumericUpDown), new FrameworkPropertyMetadata(5));
        ValueProperty = DependencyProperty.Register("Value", typeof(int), typeof(NumericUpDown), new FrameworkPropertyMetadata(0));
    }
    #region DpAccessior
    public int Maximum
    {
        get { return (int)GetValue(MaximumProperty); }
        set { SetValue(MaximumProperty, value); }
    }
    public int Minimum
    {
        get { return (int)GetValue(MinimumProperty); }
        set { SetValue(MinimumProperty, value); }
    }
    public int Value
    {
        get { return (int)GetValue(ValueProperty); }
        set { SetCurrentValue(ValueProperty, value); }
    }
    public int StepValue
    {
        get { return (int)GetValue(StepProperty); }
        set { SetValue(StepProperty, value); }
    }
    #endregion
    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
        _UpButton = Template.FindName("Part_UpButton", this) as RepeatButton;
        _DownButton = Template.FindName("Part_DownButton", this) as RepeatButton;
        _UpButton.Click += _UpButton_Click;
        _DownButton.Click += _DownButton_Click;
    }

    void _DownButton_Click(object sender, RoutedEventArgs e)
    {
        if (Value > Minimum)
        {
            Value -= StepValue;
            if (Value < Minimum)
                Value = Minimum;
        }
    }

    void _UpButton_Click(object sender, RoutedEventArgs e)
    {
        if (Value < Maximum)
        {
            Value += StepValue;
            if (Value > Maximum)
                Value = Maximum;
        }
    }

}

Remove portion of a string after a certain character

If you're using PHP 5.3+ take a look at the $before_needle flag of strstr()

$s = 'Posted On April 6th By Some Dude';
echo strstr($s, 'By', true);

Python: TypeError: object of type 'NoneType' has no len()

shuffle(names) is an in-place operation. Drop the assignment.

This function returns None and that's why you have the error:

TypeError: object of type 'NoneType' has no len()

PHP: Update multiple MySQL fields in single query

If you are using pdo, it will look like

$sql = "UPDATE users SET firstname = :firstname, lastname = :lastname WHERE id= :id";
$query = $this->pdo->prepare($sql);
$result = $query->execute(array(':firstname' => $firstname, ':lastname' => $lastname, ':id' => $id));

How to get current foreground activity context in android?

I could not find a solution that our team would be happy with so we rolled our own. We use ActivityLifecycleCallbacks to keep track of current activity and then expose it through a service. More details here: https://stackoverflow.com/a/38650587/10793

Using FileSystemWatcher to monitor a directory

The reason may be that watcher is declared as local variable to a method and it is garbage collected when the method finishes. You should declare it as a class member. Try the following:

FileSystemWatcher watcher;

private void watch()
{
  watcher = new FileSystemWatcher();
  watcher.Path = path;
  watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                         | NotifyFilters.FileName | NotifyFilters.DirectoryName;
  watcher.Filter = "*.*";
  watcher.Changed += new FileSystemEventHandler(OnChanged);
  watcher.EnableRaisingEvents = true;
}

private void OnChanged(object source, FileSystemEventArgs e)
{
  //Copies file to another directory.
}

Rollback a Git merge

From here:

http://www.christianengvall.se/undo-pushed-merge-git/

git revert -m 1 <merge commit hash>

Git revert adds a new commit that rolls back the specified commit.

Using -m 1 tells it that this is a merge and we want to roll back to the parent commit on the master branch. You would use -m 2 to specify the develop branch.

How to show all privileges from a user in oracle?

To show all privileges:

select name from system_privilege_map;

How to make a programme continue to run after log out from ssh?

You should try using nohup and running it in the background:

nohup sleep 3600 &

The meaning of NoInitialContextException error

you need to put the following name/value pairs into a hash table and call this constructor:

public InitialContext(Hashtable<?,?> environment)

the exact values depend on your application server, this example is for jboss

jndi.java.naming.provider.url=jnp://localhost:1099/
jndi.java.naming.factory.url=org.jboss.naming:org.jnp.interfaces
jndi.java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory

How can I parse a YAML file in Python

To access any element of a list in a YAML file like this:

global:
  registry:
    url: dtr-:5000/
    repoPath:
  dbConnectionString: jdbc:oracle:thin:@x.x.x.x:1521:abcd

You can use following python script:

import yaml

with open("/some/path/to/yaml.file", 'r') as f:
    valuesYaml = yaml.load(f, Loader=yaml.FullLoader)

print(valuesYaml['global']['dbConnectionString'])

No resource found that matches the given name '@style/Theme.AppCompat.Light'

If you are looking for the solution in Android Studio :

  1. Right click on your app
  2. Open Module Settings
  3. Select Dependencies tab
  4. Click on green + symbol which is on the right side
  5. Select Library Dependency
  6. Choose appcompat-v7 from list

What's the best practice for primary keys in tables?

Natural versus artificial keys to me is a matter of how much of the business logic you want in your database. Social Security number (SSN) is a great example.

"Each client in my database will, and must, have an SSN." Bam, done, make it the primary key and be done with it. Just remember when your business rule changes you're burned.

I don't like natural keys myself, due to my experience with changing business rules. But if your sure it won't change, it might prevent a few critical joins.

No 'Access-Control-Allow-Origin' header is present on the requested resource- AngularJS

The Chrome Webstore has an extension that adds the 'Access-Control-Allow-Origin' header for you when there is an asynchronous call in the page that tries to access a different host than yours.

The name of the extension is: "Allow-Control-Allow-Origin: *" and this is the link: https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi

Difference between null and empty string

No method can be invoked on a object which is assigned a NULL value. It will give a nullPointerException. Hence, s2.length() is giving an exception.

Target a css class inside another css class

I use div instead of tables and am able to target classes within the main class, as below:

CSS

.main {
    .width: 800px;
    .margin: 0 auto;
    .text-align: center;
}
.main .table {
    width: 80%;
}
.main .row {
   / ***something ***/
}
.main .column {
    font-size: 14px;
    display: inline-block;
}
.main .left {
    width: 140px;
    margin-right: 5px;
    font-size: 12px;
}
.main .right {
    width: auto;
    margin-right: 20px;
    color: #fff;
    font-size: 13px;
    font-weight: normal;
}

HTML

<div class="main">
    <div class="table">
        <div class="row">
            <div class="column left">Swing Over Bed</div>
            <div class="column right">650mm</div>
            <div class="column left">Swing In Gap</div>
            <div class="column right">800mm</div>
        </div>
    </div>
</div>

If you want to style a particular "cell" exclusively you can use another sub-class or the id of the div e.g:

.main #red { color: red; }

<div class="main">
    <div class="table">
        <div class="row">
            <div id="red" class="column left">Swing Over Bed</div>
            <div class="column right">650mm</div>
            <div class="column left">Swing In Gap</div>
            <div class="column right">800mm</div>
        </div>
    </div>
</div>

Get the name of an object's type

Use class.name. This also works with function.name.

class TestA {}
console.log(TestA.name); // "TestA"

function TestB() {}
console.log(TestB.name); // "TestB"

How to detect installed version of MS-Office?

Despite the fact that this question has been answered long time ago, I found some interesting facts to add that are related to the answers above.

As Dirk mentioned, there seems to be a weird fashion of version control from MS, starting from Office 365 / 2019. You cannot distinguish among the three(2016, 2019, O365), by seeing at the executable paths anymore. And just like he reputed himself, looking at the builds of the executable, as a mean of telling which is what, isn't quite effective either.

After some researching, I found a feasible solution. The solution lies under the registry subkey Computer\HKEY_CURRENT_USER\Software\Microsoft\Office\16.0\Common\Licensing\LicensingNext.

So, my logic follows below:

Case 1: If the computer has the MSOffice 2016 installed, there is no subkeys under Licensing.

Case 2: if the computer has MSOffice 2019 installed, there is the name of the value (which is one of the Office Product ID). (e.g. Standard2019Volume)

Case 3: if the computer has Office365 installed, there is a value called o365bussinessretail(which is also a product ID) along with some other values.

The possible productIds are provided here.

To distinguish the three, I just opened the key and see if fails. If the open fails, its Office 2016. Then I enumerate LicensingNext and try to see if any name has a prefix o365, if it finds it then its O365. If it does not, then its Office 2019.

Frankly speaking, I did not have enough time to test the logic under varying environment. So please, note that.

Hope this will help whoever's interest.

The type initializer for 'MyClass' threw an exception

I too faced this error in two situation

  1. While performing redirection from BAL layer to DAL layer I faced this exception. Inner exception says that "Object Reference error".

  2. Web.Config file key does not match.

Hope this useful to solve your problem.

How to use FormData for AJAX file upload?

Actually The documentation shows that you can use XMLHttpRequest().send() to simply send multiform data in case jquery sucks

Fastest way to extract frames using ffmpeg?

I tried it. 3600 frame in 32 seconds. your method is really slow. You should try this.

ffmpeg -i file.mpg -s 240x135 -vf fps=1 %d.jpg

Read file content from S3 bucket with boto3

You might also consider the smart_open module, which supports iterators:

from smart_open import smart_open

# stream lines from an S3 object
for line in smart_open('s3://mybucket/mykey.txt', 'rb'):
    print(line.decode('utf8'))

and context managers:

with smart_open('s3://mybucket/mykey.txt', 'rb') as s3_source:
    for line in s3_source:
         print(line.decode('utf8'))

    s3_source.seek(0)  # seek to the beginning
    b1000 = s3_source.read(1000)  # read 1000 bytes

Find smart_open at https://pypi.org/project/smart_open/

Store multiple values in single key in json

{
  "number" : ["1","2","3"],
  "alphabet" : ["a", "b", "c"]
}

Squaring all elements in a list

def square(a):
    squares = []
    for i in a:
        squares.append(i**2)
    return squares

using javascript to detect whether the url exists before display in iframe

You can try and do a simple GET on the page, if you get a 200 back it means the page exists. Try this (using jQuery), the function is the success callback function on a successful page load. Note this will only work on sites within your domain to prevent XSS. Other domains will have to be handled server side

$.get(
   yourURL,
   function(data, textStatus, jqXHR) {
      //load the iframe here...
   }
);

How to get the Power of some Integer in Swift language?

mklbtz is correct about exponentiation by squaring being the standard algorithm for computing integer powers, but the tail-recursive implementation of the algorithm seems a bit confusing. See http://www.programminglogic.com/fast-exponentiation-algorithms/ for a non-recursive implementation of exponentiation by squaring in C. I've attempted to translate it to Swift here:

func expo(_ base: Int, _ power: Int) -> Int {
    var result = 1

    while (power != 0){
        if (power%2 == 1){
            result *= base
        }
        power /= 2
        base *= base
    }
    return result
}

Of course, this could be fancied up by creating an overloaded operator to call it and it could be re-written to make it more generic so it worked on anything that implemented the IntegerType protocol. To make it generic, I'd probably start with something like

    func expo<T:IntegerType>(_ base: T, _ power: T) -> T {
    var result : T = 1

But, that is probably getting carried away.

SQL Joins Vs SQL Subqueries (Performance)?

Well, I believe it's an "Old but Gold" question. The answer is: "It depends!". The performances are such a delicate subject that it would be too much silly to say: "Never use subqueries, always join". In the following links, you'll find some basic best practices that I have found to be very helpful:

I have a table with 50000 elements, the result i was looking for was 739 elements.

My query at first was this:

SELECT  p.id,
    p.fixedId,
    p.azienda_id,
    p.categoria_id,
    p.linea,
    p.tipo,
    p.nome
FROM prodotto p
WHERE p.azienda_id = 2699 AND p.anno = (
    SELECT MAX(p2.anno) 
    FROM prodotto p2 
    WHERE p2.fixedId = p.fixedId 
)

and it took 7.9s to execute.

My query at last is this:

SELECT  p.id,
    p.fixedId,
    p.azienda_id,
    p.categoria_id,
    p.linea,
    p.tipo,
    p.nome
FROM prodotto p
WHERE p.azienda_id = 2699 AND (p.fixedId, p.anno) IN
(
    SELECT p2.fixedId, MAX(p2.anno)
    FROM prodotto p2
    WHERE p.azienda_id = p2.azienda_id
    GROUP BY p2.fixedId
)

and it took 0.0256s

Good SQL, good.

Remove specific characters from a string in Python

If you want your string to be just allowed characters by using ASCII codes, you can use this piece of code:

for char in s:
    if ord(char) < 96 or ord(char) > 123:
        s = s.replace(char, "")

It will remove all the characters beyond a....z even upper cases.

How to use linux command line ftp with a @ sign in my username?

Try to define the account in a ~/.netrc file like this:

machine host login [email protected] password mypassword

Check man netrc for details.

How do I set up cron to run a file just once at a specific time?

Your comment suggests you're trying to call this from a programming language. If that's the case, can your program fork a child process that calls sleep then does the work?

What about having your program calculate the number of seconds until the desired runtime, and have it call shell_exec("sleep ${secondsToWait) ; myCommandToRun");

http://localhost/ not working on Windows 7. What's the problem?

It was Skype interfering for me too. I changed the Skype settings (in Skype go to Tools > options > advanced > Connection and UNCHECK "use port 80 and 443 as alternatives for incoming connections") save then close Skype. I have Win 7 HomePremium 64 bit, had installed Xampp fine with MySQL running fine, but no matter how many times I started Apache (and console showed "Apache started") I still got the "firefox can't establish a connection" error in the browser. After Skype changes were saved, Apache showed the green "Running" and all working now thanks

_tkinter.TclError: no display name and no $DISPLAY environment variable

I also met this problem while using Xshell to connect Linux server.

After seaching for methods, I find Xming + Xshell to solve image imshow problem with matplotlib.

If solutions aboved can't solve your problem, just try to download Xming under the condition you're using Xshell. Then set the attribute in Xshell, SSH->tunnel->X11transfer->choose X DISPLAY localhost:0.0

How to Determine the Screen Height and Width in Flutter

You can use:

  • double width = MediaQuery.of(context).size.width;
  • double height = MediaQuery.of(context).size.height;

To get height just of SafeArea (for iOS 11 and above):

  • var padding = MediaQuery.of(context).padding;
  • double newheight = height - padding.top - padding.bottom;

java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex in Android Studio 3.0

I am using Android Studio 3.0 and was facing the same problem. I add this to my gradle:

multiDexEnabled true

And it worked!

Example

android {
    compileSdkVersion 27
    buildToolsVersion '27.0.1'
    defaultConfig {
        applicationId "com.xx.xxx"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        multiDexEnabled true //Add this
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            shrinkResources true
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

And clean the project.

How to output numbers with leading zeros in JavaScript?

UPDATE: Small one-liner function using the ES2017 String.prototype.padStart method:

_x000D_
_x000D_
const zeroPad = (num, places) => String(num).padStart(places, '0')_x000D_
_x000D_
console.log(zeroPad(5, 2)); // "05"_x000D_
console.log(zeroPad(5, 4)); // "0005"_x000D_
console.log(zeroPad(5, 6)); // "000005"_x000D_
console.log(zeroPad(1234, 2)); // "1234"
_x000D_
_x000D_
_x000D_

Another ES5 approach:

function zeroPad(num, places) {
  var zero = places - num.toString().length + 1;
  return Array(+(zero > 0 && zero)).join("0") + num;
}

zeroPad(5, 2); // "05"
zeroPad(5, 4); // "0005"
zeroPad(5, 6); // "000005"
zeroPad(1234, 2); // "1234" :)

Gradle sync failed: failed to find Build Tools revision 24.0.0 rc1

I ran into this problem after a fresh install of Android Studio (in GNU/Linux). I also used the installation wizard for Android SDK, and the Build Tools 28.0.3 were installed, although Android Studio tried to use 28.0.2 instead.

But the problem was not the build tools version but the license. I had not accepted the Android SDK license (the wizard does not ask for it), and Android Studio refused to use the build tools; the error message just is wrong.

In order to solve the problem, I manually accepted the license. In a terminal, I launched $ANDROID_SDK/tools/bin/sdkmanager --licenses and answered "Yes" for the SDK license. The other ones can be refused.

Add text to Existing PDF using Python

You may have better luck breaking the problem down into converting PDF into an editable format, writing your changes, then converting it back into PDF. I don't know of a library that lets you directly edit PDF but there are plenty of converters between DOC and PDF for example.

CSS - Make divs align horizontally

This seems close to what you want:

_x000D_
_x000D_
#foo {_x000D_
  background: red;_x000D_
  max-height: 100px;_x000D_
  overflow-y: hidden;_x000D_
}_x000D_
_x000D_
.bar {_x000D_
  background: blue;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  float: left;_x000D_
  margin: 1em;_x000D_
}
_x000D_
<div id="foo">_x000D_
  <div class="bar"></div>_x000D_
  <div class="bar"></div>_x000D_
  <div class="bar"></div>_x000D_
  <div class="bar"></div>_x000D_
  <div class="bar"></div>_x000D_
  <div class="bar"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?

Only for .NET Core Web API project, add following changes:

  1. Add the following code after the services.AddMvc() line in the ConfigureServices() method of the Startup.cs file:
services.AddCors(allowsites=>{allowsites.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
            });
  1. Add the following code after app.UseMvc() line in the Configure() method of the Startup.cs file:
app.UseCors(options => options.AllowAnyOrigin());
  1. Open the controller which you want to access outside the domain and add this following attribute at the controller level:
[EnableCors("AllowOrigin")]

Check Whether a User Exists

Using sed:

username="alice"
if [ `sed -n "/^$username/p" /etc/passwd` ]
then
    echo "User [$username] already exists"
else
    echo "User [$username] doesn't exist"
fi

How can I use if/else in a dictionary comprehension?

You've already got it: A if test else B is a valid Python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon:

{ (some_key if condition else default_key):(something_if_true if condition
          else something_if_false) for key, value in dict_.items() }

The final if clause acts as a filter, which is different from having the conditional expression.


Worth mentioning that you don't need to have an if-else condition for both the key and the value. For example, {(a if condition else b): value for key, value in dict.items()} will work.

Rails: Using greater than/less than with a where statement

If you want a more intuitive writing, it exist a gem called squeel that will let you write your instruction like this:

User.where{id > 200}

Notice the 'brace' characters { } and id being just a text.

All you have to do is to add squeel to your Gemfile:

gem "squeel"

This might ease your life a lot when writing complex SQL statement in Ruby.

Removing special characters VBA Excel

What do you consider "special" characters, just simple punctuation? You should be able to use the Replace function: Replace("p.k","."," ").

Sub Test()
Dim myString as String
Dim newString as String

myString = "p.k"

newString = replace(myString, ".", " ")

MsgBox newString

End Sub

If you have several characters, you can do this in a custom function or a simple chained series of Replace functions, etc.

  Sub Test()
Dim myString as String
Dim newString as String

myString = "!p.k"

newString = Replace(Replace(myString, ".", " "), "!", " ")

'## OR, if it is easier for you to interpret, you can do two sequential statements:
'newString = replace(myString, ".", " ")
'newString = replace(newString, "!", " ")

MsgBox newString

End Sub

If you have a lot of potential special characters (non-English accented ascii for example?) you can do a custom function or iteration over an array.

Const SpecialCharacters As String = "!,@,#,$,%,^,&,*,(,),{,[,],},?"  'modify as needed
Sub test()
Dim myString as String
Dim newString as String
Dim char as Variant
myString = "!p#*@)k{kdfhouef3829J"
newString = myString
For each char in Split(SpecialCharacters, ",")
    newString = Replace(newString, char, " ")
Next
End Sub

MySQL remove all whitespaces from the entire column

To replace all spaces :

UPDATE `table` SET `col_name` = REPLACE(`col_name`, ' ', '')

To remove all tabs characters :

UPDATE `table` SET `col_name` = REPLACE(`col_name`, '\t', '' )

To remove all new line characters :

UPDATE `table` SET `col_name` = REPLACE(`col_name`, '\n', '')

http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_replace

To remove first and last space(s) of column :

UPDATE `table` SET `col_name` = TRIM(`col_name`)

http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_trim

How to properly ignore exceptions

First I quote the answer of Jack o'Connor from this thread. The referenced thread got closed so I write here:

"There's a new way to do this coming in Python 3.4:

from contextlib import suppress

with suppress(Exception):
    # your code

Here's the commit that added it: http://hg.python.org/cpython/rev/406b47c64480

And here's the author, Raymond Hettinger, talking about this and all sorts of other Python hotness: https://youtu.be/OSGv2VnC0go?t=43m23s

My addition to this is the Python 2.7 equivalent:

from contextlib import contextmanager

@contextmanager
def ignored(*exceptions):
    try:
        yield
    except exceptions:
        pass

Then you use it like in Python 3.4:

with ignored(Exception):
    # your code

Why don't Java's +=, -=, *=, /= compound assignment operators require casting?

Subtle point here...

There is an implicit typecast for i+j when j is a double and i is an int. Java ALWAYS converts an integer into a double when there is an operation between them.

To clarify i+=j where i is an integer and j is a double can be described as

i = <int>(<double>i + j)

See: this description of implicit casting

You might want to typecast j to (int) in this case for clarity.

Location Services not working in iOS 8

I ended up solving my own problem.

Apparently in iOS 8 SDK, requestAlwaysAuthorization (for background location) or requestWhenInUseAuthorization (location only when foreground) call on CLLocationManager is needed before starting location updates.

There also needs to be NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription key in Info.plist with a message to be displayed in the prompt. Adding these solved my problem.

enter image description here

For more extensive information, have a look at: Core-Location-Manager-Changes-in-ios-8

Delete all rows in an HTML table

Just Clear the table body.

$("#tblbody").html("");

Float a div right, without impacting on design

If you don't want the image to affect the layout at all (and float on top of other content) you can apply the following CSS to the image:

position:absolute;
right:0;
top:0;

If you want it to float at the right of a particular parent section, you can add position: relative to that section.

Alter and Assign Object Without Side Effects

This is a textbook case for a constructor function:

var myArray = [];

function myElement(id, value){
    this.id = id
    this.value = value
}

myArray[0] = new myElement(0,1)
myArray[1] = new myElement(2,3)
// or myArray.push(new myElement(1, 1))

HTML select dropdown list

_x000D_
_x000D_
<select>_x000D_
    <option value="" style="display:none">Choose one provider</option>_x000D_
    <option value="1">One</option>_x000D_
    <option value="2">Two</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

This way the user cannot see this option, but it shows in the select box.

Reverting single file in SVN to a particular revision

For a single file, you could do:

svn export -r <REV> svn://host/path/to/file/on/repos file.ext

You could do svn revert <file> but that will only restore the last working copy.

List all virtualenv

Silly question. Found that there's a

lsvirtualenv

command which lists all existing virtualenv.

How can I programmatically generate keypress events in C#?

Easily! (because someone else already did the work for us...)

After spending a lot of time trying to this with the suggested answers I came across this codeplex project Windows Input Simulator which made it simple as can be to simulate a key press:

  1. Install the package, can be done or from the NuGet package manager or from the package manager console like:

    Install-Package InputSimulator

  2. Use this 2 lines of code:

    inputSimulator = new InputSimulator() inputSimulator.Keyboard.KeyDown(VirtualKeyCode.RETURN)

And that's it!

-------EDIT--------

The project page on codeplex is flagged for some reason, this is the link to the NuGet gallery.

How can I prevent the textarea from stretching beyond his parent DIV element? (google-chrome issue only)

Textarea resize control is available via the CSS3 resize property:

textarea { resize: both; } /* none|horizontal|vertical|both */
textarea.resize-vertical{ resize: vertical; }
textarea.resize-none { resize: none; }

Allowable values self-explanatory: none (disables textarea resizing), both, vertical and horizontal.

Notice that in Chrome, Firefox and Safari the default is both.

If you want to constrain the width and height of the textarea element, that's not a problem: these browsers also respect max-height, max-width, min-height, and min-width CSS properties to provide resizing within certain proportions.

Code example:

_x000D_
_x000D_
#textarea-wrapper {_x000D_
  padding: 10px;_x000D_
  background-color: #f4f4f4;_x000D_
  width: 300px;_x000D_
}_x000D_
_x000D_
#textarea-wrapper textarea {_x000D_
  min-height:50px;_x000D_
  max-height:120px;_x000D_
  width: 290px;_x000D_
}_x000D_
_x000D_
#textarea-wrapper textarea.vertical { _x000D_
  resize: vertical;_x000D_
}
_x000D_
<div id="textarea-wrapper">_x000D_
  <label for="resize-default">Textarea (default):</label>_x000D_
  <textarea name="resize-default" id="resize-default"></textarea>_x000D_
  _x000D_
  <label for="resize-vertical">Textarea (vertical):</label>_x000D_
  <textarea name="resize-vertical" id="resize-vertical" class="vertical">Notice this allows only vertical resize!</textarea>_x000D_
</div>
_x000D_
_x000D_
_x000D_

URL for public Amazon S3 bucket

The URL structure you're referring to is called the REST endpoint, as opposed to the Web Site Endpoint.


Note: Since this answer was originally written, S3 has rolled out dualstack support on REST endpoints, using new hostnames, while leaving the existing hostnames in place. This is now integrated into the information provided, below.


If your bucket is really in the us-east-1 region of AWS -- which the S3 documentation formerly referred to as the "US Standard" region, but was subsequently officially renamed to the "U.S. East (N. Virginia) Region" -- then http://s3-us-east-1.amazonaws.com/bucket/ is not the correct form for that endpoint, even though it looks like it should be. The correct format for that region is either http://s3.amazonaws.com/bucket/ or http://s3-external-1.amazonaws.com/bucket/

The format you're using is applicable to all the other S3 regions, but not US Standard US East (N. Virginia) [us-east-1].

S3 now also has dual-stack endpoint hostnames for the REST endpoints, and unlike the original endpoint hostnames, the names of these have a consistent format across regions, for example s3.dualstack.us-east-1.amazonaws.com. These endpoints support both IPv4 and IPv6 connectivity and DNS resolution, but are otherwise functionally equivalent to the existing REST endpoints.

If your permissions and configuration are set up such that the web site endpoint works, then the REST endpoint should work, too.

However... the two endpoints do not offer the same functionality.

Roughly speaking, the REST endpoint is better-suited for machine access and the web site endpoint is better suited for human access, since the web site endpoint offers friendly error messages, index documents, and redirects, while the REST endpoint doesn't. On the other hand, the REST endpoint offers HTTPS and support for signed URLs, while the web site endpoint doesn't.

Choose the correct type of endpoint (REST or web site) for your application:

http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteEndpoints.html#WebsiteRestEndpointDiff


¹ s3-external-1.amazonaws.com has been referred to as the "Northern Virginia endpoint," in contrast to the "Global endpoint" s3.amazonaws.com. It was unofficially possible to get read-after-write consistency on new objects in this region if the "s3-external-1" hostname was used, because this would send you to a subset of possible physical endpoints that could provide that functionality. This behavior is now officially supported on this endpoint, so this is probably the better choice in many applications. Previously, s3-external-2 had been referred to as the "Pacific Northwest endpoint" for US-Standard, though it is now a CNAME in DNS for s3-external-1 so s3-external-2 appears to have no purpose except backwards-compatibility.

Non-static method requires a target

Normally it happens when the target is null. So better check the invoke target first then do the linq query.

css absolute position won't work with margin-left:auto margin-right: auto

I've used this trick to center an absolutely positioned element. Though, you have to know the element's width.

.divtagABS {
    width: 100px;
    position: absolute;
    left: 50%;
    margin-left: -50px;
  }

Basically, you use left: 50%, then back it out half of it's width with a negative margin.

Using an authorization header with Fetch in React Native

Example fetch with authorization header:

fetch('URL_GOES_HERE', { 
   method: 'post', 
   headers: new Headers({
     'Authorization': 'Basic '+btoa('username:password'), 
     'Content-Type': 'application/x-www-form-urlencoded'
   }), 
   body: 'A=1&B=2'
 });

Can't update: no tracked branch

I got the same error but in PyCharm because I accidentally deleted my VCS origin. After re-adding my origin I ran:

git fetch

which reloaded all of my branches. I then clicked the button to update the project, and I was back to normal.

Found a swap file by the name

.MERGE_MSG.swp is open in your git, you just need to delete this .swp file. In my case I used following command and it worked fine.

rm .MERGE_MSG.swp

Tokenizing strings in C

Here's an example of strtok usage, keep in mind that strtok is destructive of its input string (and therefore can't ever be used on a string constant

char *p = strtok(str, " ");
while(p != NULL) {
    printf("%s\n", p);
    p = strtok(NULL, " ");
}

Basically the thing to note is that passing a NULL as the first parameter to strtok tells it to get the next token from the string it was previously tokenizing.

how to get current month and year

label1.Text = DateTime.Now.Month.ToString();

and

label2.Text = DateTime.Now.Year.ToString();

Ruby: Merging variables in to a string

You can use it with your local variables, like this:

@animal = "Dog"
@action = "licks"
@second_animal = "Bird"

"The #{@animal} #{@action} the #{@second_animal}"

the output would be: "The Dog licks the Bird"

Difference between $(this) and event.target?

this is a reference for the DOM element for which the event is being handled (the current target). event.target refers to the element which initiated the event. They were the same in this case, and can often be, but they aren't necessarily always so.

You can get a good sense of this by reviewing the jQuery event docs, but in summary:

event.currentTarget

The current DOM element within the event bubbling phase.

event.delegateTarget

The element where the currently-called jQuery event handler was attached.

event.relatedTarget

The other DOM element involved in the event, if any.

event.target

The DOM element that initiated the event.

To get the desired functionality using jQuery, you must wrap it in a jQuery object using either: $(this) or $(evt.target).

The .attr() method only works on a jQuery object, not on a DOM element. $(evt.target).attr('href') or simply evt.target.href will give you what you want.

How do I remove/delete a folder that is not empty?

def deleteDir(dirPath):
    deleteFiles = []
    deleteDirs = []
    for root, dirs, files in os.walk(dirPath):
        for f in files:
            deleteFiles.append(os.path.join(root, f))
        for d in dirs:
            deleteDirs.append(os.path.join(root, d))
    for f in deleteFiles:
        os.remove(f)
    for d in deleteDirs:
        os.rmdir(d)
    os.rmdir(dirPath)

WCF service startup error "This collection already contains an address with scheme http"

Did you see this - http://kb.discountasp.net/KB/a799/error-accessing-wcf-service-this-collection-already.aspx

You can resolve this error by changing the web.config file.

With ASP.NET 4.0, add the following lines to your web.config:

<system.serviceModel> 
     <serviceHostingEnvironment multipleSiteBindingsEnabled="true" /> 
</system.serviceModel> 

With ASP.NET 2.0/3.0/3.5, add the following lines to your web.config:

<system.serviceModel> 
     <serviceHostingEnvironment> 
          <baseAddressPrefixFilters> 
               <add prefix="http://www.YourHostedDomainName.com"/> 
          </baseAddressPrefixFilters> 
     </serviceHostingEnvironment> 
</system.serviceModel> 

How do I get the full path to a Perl script that is executing?

You could use FindBin, Cwd, File::Basename, or a combination of them. They're all in the base distribution of Perl IIRC.

I used Cwd in the past:

Cwd:

use Cwd qw(abs_path);
my $path = abs_path($0);
print "$path\n";

Apply a theme to an activity in Android?

Before you call setContentView(), call setTheme(android.R.style...) and just replace the ... with the theme that you want(Theme, Theme_NoTitleBar, etc.).

Or if your theme is a custom theme, then replace the entire thing, so you get setTheme(yourThemesResouceId)

Java - How to convert type collection into ArrayList?

The following code will fail:

List<String> will_fail =  (List<String>)Collections.unmodifiableCollection(new ArrayList<String>());

This instead will work:

List<String> will_work = new ArrayList<String>(Collections.unmodifiableCollection(new ArrayList<String>()));

How can I selectively escape percent (%) in Python strings?

You can't selectively escape %, as % always has a special meaning depending on the following character.

In the documentation of Python, at the bottem of the second table in that section, it states:

'%'        No argument is converted, results in a '%' character in the result.

Therefore you should use:

selectiveEscape = "Print percent %% in sentence and not %s" % (test, )

(please note the expicit change to tuple as argument to %)

Without knowing about the above, I would have done:

selectiveEscape = "Print percent %s in sentence and not %s" % ('%', test)

with the knowledge you obviously already had.

pandas dataframe create new columns and fill with calculated values from same df

In [56]: df = pd.DataFrame(np.abs(randn(3, 4)), index=[1,2,3], columns=['A','B','C','D'])

In [57]: df.divide(df.sum(axis=1), axis=0)
Out[57]: 
          A         B         C         D
1  0.319124  0.296653  0.138206  0.246017
2  0.376994  0.326481  0.230464  0.066062
3  0.036134  0.192954  0.430341  0.340571

How to change mysql to mysqli?

The ultimate guide to upgrading mysql_* functions to MySQLi API

The reason for the new mysqli extension was to take advantage of new features found in MySQL systems versions 4.1.3 and newer. When changing your existing code from mysql_* to mysqli API you should avail of these improvements, otherwise your upgrade efforts could go in vain.
The mysqli extension has a number of benefits, the key enhancements over the mysql extension being:

  • Object-oriented interface
  • Support for Prepared Statements
  • Enhanced debugging capabilities

When upgrading from mysql_* functions to MySQLi, it is important to take these features into consideration, as well as some changes in the way this API should be used.

1. Object-oriented interface versus procedural functions.

The new mysqli object-oriented interface is a big improvement over the older functions and it can make your code cleaner and less susceptible to typographical errors. There is also the procedural version of this API, but its use is discouraged as it leads to less readable code, which is more prone to errors.

To open new connection to the database with MySQLi you need to create new instance of MySQLi class.

$mysqli = new \mysqli($host, $user, $password, $dbName);
$mysqli->set_charset('utf8mb4');

Using procedural style it would look like this:

$mysqli = mysqli_connect($host, $user, $password, $dbName);
mysqli_set_charset($mysqli, 'utf8mb4');

Keep in mind that only the first 3 parameters are the same as in mysql_connect. The same code in the old API would be:

$link = mysql_connect($host, $user, $password);
mysql_select_db($dbName, $link);
mysql_query('SET NAMES utf8');

If your PHP code relied on implicit connection with default parameters defined in php.ini, you now have to open the MySQLi connection passing the parameters in your code, and then provide the connection link to all procedural functions or use the OOP style.

For more information see the article: How to connect properly using mysqli

2. Support for Prepared Statements

This is a big one. MySQL has added support for native prepared statements in MySQL 4.1 (2004). Prepared statements are the best way to prevent SQL injection. It was only logical that support for native prepared statements was added to PHP. Prepared statements should be used whenever data needs to be passed along with the SQL statement (i.e. WHERE, INSERT or UPDATE are the usual use cases).

The old MySQL API had a function to escape the strings used in SQL called mysql_real_escape_string, but it was never intended for protection against SQL injections and naturally shouldn't be used for the purpose.
The new MySQLi API offers a substitute function mysqli_real_escape_string for backwards compatibility, which suffers from the same problems as the old one and therefore should not be used unless prepared statements are not available.

The old mysql_* way:

$login = mysql_real_escape_string($_POST['login']);
$result = mysql_query("SELECT * FROM users WHERE user='$login'");

The prepared statement way:

$stmt = $mysqli->prepare('SELECT * FROM users WHERE user=?');
$stmt->bind_param('s', $_POST['login']);
$stmt->execute();
$result = $stmt->get_result();

Prepared statements in MySQLi can look a little off-putting to beginners. If you are starting a new project then deciding to use the more powerful and simpler PDO API might be a good idea.

3. Enhanced debugging capabilities

Some old-school PHP developers are used to checking for SQL errors manually and displaying them directly in the browser as means of debugging. However, such practice turned out to be not only cumbersome, but also a security risk. Thankfully MySQLi has improved error reporting capabilities.

MySQLi is able to report any errors it encounters as PHP exceptions. PHP exceptions will bubble up in the script and if unhandled will terminate it instantly, which means that no statement after the erroneous one will ever be executed. The exception will trigger PHP Fatal error and will behave as any error triggered from PHP core obeying the display_errors and log_errors settings. To enable MySQLi exceptions use the line mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT) and insert it right before you open the DB connection.

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new \mysqli($host, $user, $password, $dbName);
$mysqli->set_charset('utf8mb4');

If you were used to writing code such as:

$result = mysql_query('SELECT * WHERE 1=1');
if (!$result) {
    die('Invalid query: ' . mysql_error());
}

or

$result = mysql_query('SELECT * WHERE 1=1') or die(mysql_error());

you no longer need to die() in your code.

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new \mysqli($host, $user, $password, $dbName);
$mysqli->set_charset('utf8mb4');

$result = $mysqli->query('SELECT * FROM non_existent_table');
// The following line will never be executed due to the mysqli_sql_exception being thrown above
foreach ($result as $row) {
    // ...
}

If for some reason you can't use exceptions, MySQLi has equivalent functions for error retrieval. You can use mysqli_connect_error() to check for connection errors and mysqli_error($mysqli) for any other errors. Pay attention to the mandatory argument in mysqli_error($mysqli) or alternatively stick to OOP style and use $mysqli->error.

$result = $mysqli->query('SELECT * FROM non_existent_table') or trigger_error($mysqli->error, E_USER_ERROR);

See these posts for more explanation:
mysqli or die, does it have to die?
How to get MySQLi error information in different environments?

4. Other changes

Unfortunately not every function from mysql_* has its counterpart in MySQLi only with an "i" added in the name and connection link as first parameter. Here is a list of some of them:

  • mysql_client_encoding() has been replaced by mysqli_character_set_name($mysqli)
  • mysql_create_db has no counterpart. Use prepared statements or mysqli_query instead
  • mysql_drop_db has no counterpart. Use prepared statements or mysqli_query instead
  • mysql_db_name & mysql_list_dbs support has been dropped in favour of SQL's SHOW DATABASES
  • mysql_list_tables support has been dropped in favour of SQL's SHOW TABLES FROM dbname
  • mysql_list_fields support has been dropped in favour of SQL's SHOW COLUMNS FROM sometable
  • mysql_db_query -> use mysqli_select_db() then the query or specify the DB name in the query
  • mysql_fetch_field($result, 5) -> the second parameter (offset) is not present in mysqli_fetch_field. You can use mysqli_fetch_field_direct keeping in mind the different results returned
  • mysql_field_flags, mysql_field_len, mysql_field_name, mysql_field_table & mysql_field_type -> has been replaced with mysqli_fetch_field_direct
  • mysql_list_processes has been removed. If you need thread ID use mysqli_thread_id
  • mysql_pconnect has been replaced with mysqli_connect() with p: host prefix
  • mysql_result -> use mysqli_data_seek() in conjunction with mysqli_field_seek() and mysqli_fetch_field()
  • mysql_tablename support has been dropped in favour of SQL's SHOW TABLES
  • mysql_unbuffered_query has been removed. See this article for more information Buffered and Unbuffered queries

Installation failed with message Invalid File

I solved it this way:

Click Build tab ---> Clean Project

Click Build tab ---> Rebuild Project

Click Build tab ---> Build APK

Run.

Reset/remove CSS styles for element only

For future readers. I think this is what was meant but currently isn't really wide supported (see below):

#someselector {
  all: initial;
  * {
    all: unset;
  }
}
  • Supported in (source): Chrome 37, Firefox 27, IE 11, Opera 24
  • Not supported: Safari

How can I get all a form's values that would be submitted without submitting

Thanks Chris. That's what I was looking for. However, note that the method is serialize(). And there is another method serializeArray() that looks very useful that I may use. Thanks for pointing me in the right direction.

var queryString = $('#frmAdvancedSearch').serialize();
alert(queryString);

var fieldValuePairs = $('#frmAdvancedSearch').serializeArray();
$.each(fieldValuePairs, function(index, fieldValuePair) {
    alert("Item " + index + " is [" + fieldValuePair.name + "," + fieldValuePair.value + "]");
});

Current user in Magento?

This way:

$email = Mage::getSingleton('customer/session')->getCustomer()->getEmail();
echo $email;

Wait until an HTML5 video loads

In response to the final part of your question, which is still unanswered... When you write $('#video').duration, you're asking for the duration property of the jQuery collection object, which doesn't exist. The native DOM video element does have the duration. You can get that in a few ways.

Here's one:

// get the native element directly
document.getElementById('video').duration

Here's another:

// get it out of the jQuery object
$('#video').get(0).duration

And another:

// use the event object
v.bind('loadeddata', function(e) {
  console.log(e.target.duration);
});

Jquery Smooth Scroll To DIV - Using ID value from Link

Ids are meant to be unique, and never use an id that starts with a number, use data-attributes instead to set the target like so :

<div id="searchbycharacter">
    <a class="searchbychar" href="#" data-target="numeric">0-9 |</a> 
    <a class="searchbychar" href="#" data-target="A"> A |</a> 
    <a class="searchbychar" href="#" data-target="B"> B |</a> 
    <a class="searchbychar" href="#" data-target="C"> C |</a> 
    ... Untill Z
</div>

As for the jquery :

$(document).on('click','.searchbychar', function(event) {
    event.preventDefault();
    var target = "#" + this.getAttribute('data-target');
    $('html, body').animate({
        scrollTop: $(target).offset().top
    }, 2000);
});

Check if a string contains an element from a list (of strings)

With LINQ, and using C# (I don't know VB much these days):

bool b = listOfStrings.Any(s=>myString.Contains(s));

or (shorter and more efficient, but arguably less clear):

bool b = listOfStrings.Any(myString.Contains);

If you were testing equality, it would be worth looking at HashSet etc, but this won't help with partial matches unless you split it into fragments and add an order of complexity.


update: if you really mean "StartsWith", then you could sort the list and place it into an array ; then use Array.BinarySearch to find each item - check by lookup to see if it is a full or partial match.

Checkbox for nullable boolean

The cleanest approach I could come up with is to expand the extensions available to HtmlHelper while still reusing functionality provided by the framework.

public static MvcHtmlString CheckBoxFor<T>(this HtmlHelper<T> htmlHelper, Expression<Func<T, bool?>> expression, IDictionary<string, object> htmlAttributes) {

    ModelMetadata modelMeta = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
    bool? value = (modelMeta.Model as bool?);

    string name = ExpressionHelper.GetExpressionText(expression);

    return htmlHelper.CheckBox(name, value ?? false, htmlAttributes);
}

I experimented with 'shaping' the expression to allow a straight pass through to the native CheckBoxFor<Expression<Func<T, bool>>> but I don't think it's possible.

how to "execute" make file

You don't tend to execute the make file itself, rather you execute make, giving it the make file as an argument:

make -f pax.mk

If your make file is actually one of the standard names (like makefile or Makefile), you don't even need to specify it. It'll be picked up by default (if you have more than one of these standard names in your build directory, you better look up the make man page to see which takes precedence).

How to find out if an installed Eclipse is 32 or 64 bit version?

Go to the Eclipse base folder ? open eclipse.ini ? you will find the below line at line no 4:

plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.200.v20150204-1316 plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.200.v20120913-144807

As you can see, line 1 is of 64-bit Eclipse. It contains x86_64 and line 2 is of 32-bit Eclipse. It contains x_86.

For 32-bit Eclipse only x86 will be present and for 64-bit Eclipse x86_64 will be present.

What are access specifiers? Should I inherit with private, protected or public?

The explanation from Scott Meyers in Effective C++ might help understand when to use them:

Public inheritance should model "is-a relationship," whereas private inheritance should be used for "is-implemented-in-terms-of" - so you don't have to adhere to the interface of the superclass, you're just reusing the implementation.

org.apache.poi.POIXMLException: org.apache.poi.openxml4j.exceptions.InvalidFormatException:

You are trying to read xls with explicit implementation poi classes for xlsx.

G:\Selenium Jar Files\TestData\Data.xls

Either use HSSFWorkbook and HSSFSheet classes or make your implementation more generic by using shared interfaces, like;

Change:

XSSFWorkbook workbook = new XSSFWorkbook(file);

To:

 org.apache.poi.ss.usermodel.Workbook workbook = WorkbookFactory.create(file);

And Change:

XSSFSheet sheet = workbook.getSheetAt(0);

To:

org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(0);

Looping through list items with jquery

Try this code. By using the parent>child selector "#productList li" it should find all li elements. Then, you can iterate through the result object using the each() method which will only alter li elements that have been found.

listItems = $("#productList li").each(function(){

        var product = $(this);
        var productid = product.children(".productId").val();
        var productPrice = product.find(".productPrice").val();
        var productMSRP = product.find(".productMSRP").val();

        totalItemsHidden.val(parseInt(totalItemsHidden.val(), 10) + 1);
        subtotalHidden.val(parseFloat(subtotalHidden.val()) + parseFloat(productMSRP));
        savingsHidden.val(parseFloat(savingsHidden.val()) + parseFloat(productMSRP - productPrice));
        totalHidden.val(parseFloat(totalHidden.val()) + parseFloat(productPrice));

    });

Deep copy in ES6 using the spread syntax

I often use this:

function deepCopy(obj) {
    if(typeof obj !== 'object' || obj === null) {
        return obj;
    }

    if(obj instanceof Date) {
        return new Date(obj.getTime());
    }

    if(obj instanceof Array) {
        return obj.reduce((arr, item, i) => {
            arr[i] = deepCopy(item);
            return arr;
        }, []);
    }

    if(obj instanceof Object) {
        return Object.keys(obj).reduce((newObj, key) => {
            newObj[key] = deepCopy(obj[key]);
            return newObj;
        }, {})
    }
}

send Content-Type: application/json post with node.js

Since the request module that other answers use has been deprecated, may I suggest switching to node-fetch:

const fetch = require("node-fetch")

const url = "https://www.googleapis.com/urlshortener/v1/url"
const payload = { longUrl: "http://www.google.com/" }

const res = await fetch(url, {
  method: "post",
  body: JSON.stringify(payload),
  headers: { "Content-Type": "application/json" },
})

const { id } = await res.json()

Recover unsaved SQL query scripts

I am using Windows 8 and found the missing scripts in the path below:

C:\Users\YourUsername\Documents\SQL Server Management Studio\Backup Files

How can I easily convert DataReader to List<T>?

I would suggest writing an extension method for this:

public static IEnumerable<T> Select<T>(this IDataReader reader,
                                       Func<IDataReader, T> projection)
{
    while (reader.Read())
    {
        yield return projection(reader);
    }
}

You can then use LINQ's ToList() method to convert that into a List<T> if you want, like this:

using (IDataReader reader = ...)
{
    List<Customer> customers = reader.Select(r => new Customer {
        CustomerId = r["id"] is DBNull ? null : r["id"].ToString(),
        CustomerName = r["name"] is DBNull ? null : r["name"].ToString() 
    }).ToList();
}

I would actually suggest putting a FromDataReader method in Customer (or somewhere else):

public static Customer FromDataReader(IDataReader reader) { ... }

That would leave:

using (IDataReader reader = ...)
{
    List<Customer> customers = reader.Select<Customer>(Customer.FromDataReader)
                                     .ToList();
}

(I don't think type inference would work in this case, but I could be wrong...)

adding directory to sys.path /PYTHONPATH

This is working as documented. Any paths specified in PYTHONPATH are documented as normally coming after the working directory but before the standard interpreter-supplied paths. sys.path.append() appends to the existing path. See here and here. If you want a particular directory to come first, simply insert it at the head of sys.path:

import sys
sys.path.insert(0,'/path/to/mod_directory')

That said, there are usually better ways to manage imports than either using PYTHONPATH or manipulating sys.path directly. See, for example, the answers to this question.

How to copy directory recursively in python and overwrite all?

Here's a simple solution to recursively overwrite a destination with a source, creating any necessary directories as it goes. This does not handle symlinks, but it would be a simple extension (see answer by @Michael above).

def recursive_overwrite(src, dest, ignore=None):
    if os.path.isdir(src):
        if not os.path.isdir(dest):
            os.makedirs(dest)
        files = os.listdir(src)
        if ignore is not None:
            ignored = ignore(src, files)
        else:
            ignored = set()
        for f in files:
            if f not in ignored:
                recursive_overwrite(os.path.join(src, f), 
                                    os.path.join(dest, f), 
                                    ignore)
    else:
        shutil.copyfile(src, dest)

Static array vs. dynamic array in C++

Static Array :

  1. Static arrays are allocated memory at compile time.
  2. Size is fixed.
  3. Located in stack memory space.
  4. Eg. : int array[10]; //array of size 10

Dynamic Array :

  1. Memory is allocated at run time.
  2. Size is not fixed.
  3. Located in Heap memory space.
  4. Eg. : int* array = new int[10];

When should I use the Visitor Design Pattern?

The Visitor design pattern works really well for "recursive" structures like directory trees, XML structures, or document outlines.

A Visitor object visits each node in the recursive structure: each directory, each XML tag, whatever. The Visitor object doesn't loop through the structure. Instead Visitor methods are applied to each node of the structure.

Here's a typical recursive node structure. Could be a directory or an XML tag. [If your a Java person, imagine of a lot of extra methods to build and maintain the children list.]

class TreeNode( object ):
    def __init__( self, name, *children ):
        self.name= name
        self.children= children
    def visit( self, someVisitor ):
        someVisitor.arrivedAt( self )
        someVisitor.down()
        for c in self.children:
            c.visit( someVisitor )
        someVisitor.up()

The visit method applies a Visitor object to each node in the structure. In this case, it's a top-down visitor. You can change the structure of the visit method to do bottom-up or some other ordering.

Here's a superclass for visitors. It's used by the visit method. It "arrives at" each node in the structure. Since the visit method calls up and down, the visitor can keep track of the depth.

class Visitor( object ):
    def __init__( self ):
        self.depth= 0
    def down( self ):
        self.depth += 1
    def up( self ):
        self.depth -= 1
    def arrivedAt( self, aTreeNode ):
        print self.depth, aTreeNode.name

A subclass could do things like count nodes at each level and accumulate a list of nodes, generating a nice path hierarchical section numbers.

Here's an application. It builds a tree structure, someTree. It creates a Visitor, dumpNodes.

Then it applies the dumpNodes to the tree. The dumpNode object will "visit" each node in the tree.

someTree= TreeNode( "Top", TreeNode("c1"), TreeNode("c2"), TreeNode("c3") )
dumpNodes= Visitor()
someTree.visit( dumpNodes )

The TreeNode visit algorithm will assure that every TreeNode is used as an argument to the Visitor's arrivedAt method.

Trying to add adb to PATH variable OSX

In order to make the terminal always have the file ~/.bashrc and there put the path you wish to use, by adding:

export PATH=$PATH:/XXX

where XXX is the path that you wish to use.

for adb, here's what i use:

export PATH=$PATH:/home/user/Android/android-sdk-linux_x86/platform-tools/

(where "user" is my user name).

Translating touch events from Javascript to jQuery

$(window).on("touchstart", function(ev) {
    var e = ev.originalEvent;
    console.log(e.touches);
});

I know it been asked a long time ago, but I thought a concrete example might help.

UNC path to a folder on my local computer

If you're going to access your local computer (or any computer) using UNC, you'll need to setup a share. If you haven't already setup a share, you could use the default administrative shares. Example:

\\localhost\c$\my_dir

... accesses a folder called "my_dir" via UNC on your C: drive. By default all the hard drives on your machine are shared with hidden shares like c$, d$, etc.

How to Import 1GB .sql file to WAMP/phpmyadmin

What are the possible ways to do that such as any SQL query to import .sql file ?

Try this

 mysql -u<user> -p<password> <database name> < /path/to/dump.sql

assuming dump.sql is your 1 GB dump file

Twitter Bootstrap modal on mobile devices

Admittedly, I haven't tried any of the solutions listed above but I was (eventually) jumping for joy when I tried jschr's Bootstrap-modal project in Bootstrap 3 (linked to in the top answer). The js was giving me trouble so I abandoned it (maybe mine was a unique issue or it works fine for Bootstrap 2) but the CSS files on their own seem to do the trick in Android's native 2.3.4 browser.

In my case, I've resorted so far to using (sub-optimal) user-agent detection before using the overrides to allow expected behaviour in modern phones.

For example, if you wanted all Android phones ver 3.x and below only to use the full set of hacks you could add a class "oldPhoneModalNeeded" to the body after user agent detection using javascript and then modify jschr's Bootstrap-modal CSS properties to always have .oldPhoneModalNeeded as an ancestor.

How to remove html special chars?

The function I used to perform the task, joining the upgrade made by schnaader is:

    mysql_real_escape_string(
        preg_replace_callback("/&#?[a-z0-9]+;/i", function($m) { 
            return mb_convert_encoding($m[1], "UTF-8", "HTML-ENTITIES"); 
        }, strip_tags($row['cuerpo'])))

This function removes every html tag and html symbol, converted in UTF-8 ready to save in MySQL

How can I initialize a C# List in the same line I declare it. (IEnumerable string Collection Example)

I think this will work for int, long and string values.

List<int> list = new List<int>(new int[]{ 2, 3, 7 });


var animals = new List<string>() { "bird", "dog" };

How can I find last row that contains data in a specific column?

function LastRowIndex(byval w as worksheet, byval col as variant) as long
  dim r as range

  set r = application.intersect(w.usedrange, w.columns(col))
  if not r is nothing then
    set r = r.cells(r.cells.count)

    if isempty(r.value) then
      LastRowIndex = r.end(xlup).row
    else
      LastRowIndex = r.row
    end if
  end if
end function

Usage:

? LastRowIndex(ActiveSheet, 5)
? LastRowIndex(ActiveSheet, "AI")

URL encoding the space character: + or %20?

I would recommend %20.

Are you hard-coding them?

This is not very consistent across languages, though. If I'm not mistaken, in PHP urlencode() treats spaces as + whereas Python's urlencode() treats them as %20.

EDIT:

It seems I'm mistaken. Python's urlencode() (at least in 2.7.2) uses quote_plus() instead of quote() and thus encodes spaces as "+". It seems also that the W3C recommendation is the "+" as per here: http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.1

And in fact, you can follow this interesting debate on Python's own issue tracker about what to use to encode spaces: http://bugs.python.org/issue13866.

EDIT #2:

I understand that the most common way of encoding " " is as "+", but just a note, it may be just me, but I find this a bit confusing:

import urllib
print(urllib.urlencode({' ' : '+ '})

>>> '+=%2B+'

Can't connect to local MySQL server through socket '/var/mysql/mysql.sock' (38)

Edit your config file /etc/mysql/my.cnf:

[client]
host        = 127.0.0.1
port        = 3306
socket      =/var/run/mysql/mysql.sock

Understanding SQL Server LOCKS on SELECT queries

On performance you keep focusing on select.
Shared does not block reads.
Shared lock blocks update.
If you have hundreds of shared locks it is going to take an update a while to get an exclusive lock as it must wait for shared locks to clear.

By default a select (read) takes a shared lock.
Shared (S) locks allow concurrent transactions to read (SELECT) a resource.
A shared lock as no effect on other selects (1 or a 1000).

The difference is how the nolock versus shared lock effects update or insert operation.

No other transactions can modify the data while shared (S) locks exist on the resource.

A shared lock blocks an update!
But nolock does not block an update.

This can have huge impacts on performance of updates. It also impact inserts.

Dirty read (nolock) just sounds dirty. You are never going to get partial data. If an update is changing John to Sally you are never going to get Jolly.

I use shared locks a lot for concurrency. Data is stale as soon as it is read. A read of John that changes to Sally the next millisecond is stale data. A read of Sally that gets rolled back John the next millisecond is stale data. That is on the millisecond level. I have a dataloader that take 20 hours to run if users are taking shared locks and 4 hours to run is users are taking no lock. Shared locks in this case cause data to be 16 hours stale.

Don't use nolocks wrong. But they do have a place. If you are going to cut a check when a byte is set to 1 and then set it to 2 when the check is cut - not a time for a nolock.

How to change row color in datagridview?

I typically Like to use the GridView.RowDataBound Event event for this.

protected void OrdersGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        e.Row.ForeColor = System.Drawing.Color.Red;
    }
}

Using an HTTP PROXY - Python

Just wanted to mention, that you also may have to set the https_proxy OS environment variable in case https URLs need to be accessed. In my case it was not obvious to me and I tried for hours to discover this.

My use case: Win 7, jython-standalone-2.5.3.jar, setuptools installation via ez_setup.py

CSS last-child(-1)

Unless you can get PHP to label that element with a class you are better to use jQuery.

jQuery(document).ready(function () {
  $count =  jQuery("ul li").size() - 1;
  alert($count);
  jQuery("ul li:nth-child("+$count+")").css("color","red");
});

how to show only even or odd rows in sql server 2008?

SELECT *
  FROM   
  ( 
     SELECT rownum rn, empno, ename
     FROM emp
  ) temp
  WHERE  MOD(temp.rn,2) = 1

Printing Batch file results to a text file

Have you tried moving DEL %FILE%.txt% to after @echo %FILE% deleted. >> results.txt so that it looks like this?

@echo %FILE% deleted. >> results.txt
DEL %FILE%.txt

Send JSON data via POST (ajax) and receive json response from Controller (MVC)

You don't need to call $.toJSON and add traditional = true

data: { sendInfo: array },
traditional: true

would do.

ORACLE: Updating multiple columns at once

I guess the issue here is that you are updating INV_DISCOUNT and the INV_TOTAL uses the INV_DISCOUNT. so that is the issue here. You can use returning clause of update statement to use the new INV_DISCOUNT and use it to update INV_TOTAL.

this is a generic example let me know if this explains the point i mentioned

CREATE OR REPLACE PROCEDURE SingleRowUpdateReturn
IS
    empName VARCHAR2(50);
    empSalary NUMBER(7,2);      
BEGIN
    UPDATE emp
    SET sal = sal + 1000
    WHERE empno = 7499
    RETURNING ename, sal
    INTO empName, empSalary;

    DBMS_OUTPUT.put_line('Name of Employee: ' || empName);
    DBMS_OUTPUT.put_line('New Salary: ' || empSalary);
END;

Insert/Update/Delete with function in SQL Server

if you need to run the delete/insert/update you could also run dynamic statements. i.e.:

declare 
    @v_dynDelete                 NVARCHAR(500);

 SET @v_dynDelete = 'DELETE some_table;'; 
 EXEC @v_dynDelete

Cannot get a text value from a numeric cell “Poi”

As explained in the Apache POI Javadocs, you should not use cell.setCellType(Cell.CELL_TYPE_STRING) to get the string value of a numeric cell, as you'll loose all the formatting

Instead, as the javadocs explain, you should use DataFormatter

What DataFormatter does is take the floating point value representing the cell is stored in the file, along with the formatting rules applied to it, and returns you a string that look like it the cell does in Excel.

So, if you're after a String of the cell, looking much as you had it looking in Excel, just do:

 // Create a formatter, do this once
 DataFormatter formatter = new DataFormatter(Locale.US);

 .....

 for (int i=1; i <= sheet.getLastRowNum(); i++) {
        Row r = sheet.getRow(i);
        if (r == null) { 
           // empty row, skip
        } else {
           String j_username = formatter.formatCellValue(row.getCell(0));
           String j_password =  formatter.formatCellValue(row.getCell(1));

           // Use these
        }
 }

The formatter will return String cells as-is, and for Numeric cells will apply the formatting rules on the style to the number of the cell

How to read file with space separated values in pandas

add delim_whitespace=True argument, it's faster than regex.

Clear an input field with Reactjs?

The way I cleared my form input values was to add an id to my form tag. Then when I handleSubmit I call this.clearForm()

In the clearForm function I then use document.getElementById("myForm").reset();

import React, {Component } from 'react';
import './App.css';
import Button from './components/Button';
import Input from './components/Input';

class App extends Component {  
  state = {
    item: "", 
    list: []
}

componentDidMount() {
    this.clearForm();
  }

handleFormSubmit = event => {
   this.clearForm()
   event.preventDefault()
   const item = this.state.item

    this.setState ({
        list: [...this.state.list, item],
            })

}

handleInputChange = event => {
  this.setState ({
    item: event.target.value 
  })
}

clearForm = () => {
  document.getElementById("myForm").reset(); 
  this.setState({
    item: ""
  })
}



  render() {
    return (
      <form id="myForm">
      <Input

           name="textinfo"
           onChange={this.handleInputChange}
           value={this.state.item}
      />
      <Button
        onClick={this.handleFormSubmit}
      >  </Button>
      </form>
    );
  }
}

export default App;

Adding a css class to select using @Html.DropDownList()

Looking at the controller, and learing a bit more about how MVC actually works, I was able to make sense of this.

My view was one of the auto-generated ones, and contained this line of code:

@Html.DropDownList("PriorityID", string.Empty)

To add html attributes, I needed to do something like this:

@Html.DropDownList("PriorityID", (IEnumerable<SelectListItem>)ViewBag.PriorityID, new { @class="dropdown" })

Thanks again to @Laurent for your help, I realise the question wasn't as clear as it could have been...

UPDATE:

A better way of doing this would be to use DropDownListFor where possible, that way you don't rely on a magic string for the name attribute

@Html.DropDownListFor(x => x.PriorityID, (IEnumerable<SelectListItem>)ViewBag.PriorityID, new { @class = "dropdown" })

Spring: @Component versus @Bean

When you use the @Component tag, it's the same as having a POJO (Plain Old Java Object) with a vanilla bean declaration method (annotated with @Bean). For example, the following method 1 and 2 will give the same result.

Method 1

@Component
public class SomeClass {

    private int number;

    public SomeClass(Integer theNumber){
        this.number = theNumber.intValue();
    }

    public int getNumber(){
        return this.number;
    }
}

with a bean for 'theNumber':

@Bean
Integer theNumber(){
    return new Integer(3456);
}

Method 2

//Note: no @Component tag
public class SomeClass {

    private int number;

    public SomeClass(Integer theNumber){
        this.number = theNumber.intValue();
    }

    public int getNumber(){
        return this.number;
    }
}

with the beans for both:

@Bean
Integer theNumber(){
    return new Integer(3456);
}

@Bean
SomeClass someClass(Integer theNumber){
    return new SomeClass(theNumber);
}

Method 2 allows you to keep bean declarations together, it's a bit more flexible etc. You may even want to add another non-vanilla SomeClass bean like the following:

@Bean
SomeClass strawberryClass(){
    return new SomeClass(new Integer(1));
}

What does set -e mean in a bash script?

As per bash - The Set Builtin manual, if -e/errexit is set, the shell exits immediately if a pipeline consisting of a single simple command, a list or a compound command returns a non-zero status.

By default, the exit status of a pipeline is the exit status of the last command in the pipeline, unless the pipefail option is enabled (it's disabled by default).

If so, the pipeline's return status of the last (rightmost) command to exit with a non-zero status, or zero if all commands exit successfully.

If you'd like to execute something on exit, try defining trap, for example:

trap onexit EXIT

where onexit is your function to do something on exit, like below which is printing the simple stack trace:

onexit(){ while caller $((n++)); do :; done; }

There is similar option -E/errtrace which would trap on ERR instead, e.g.:

trap onerr ERR

Examples

Zero status example:

$ true; echo $?
0

Non-zero status example:

$ false; echo $?
1

Negating status examples:

$ ! false; echo $?
0
$ false || true; echo $?
0

Test with pipefail being disabled:

$ bash -c 'set +o pipefail -e; true | true | true; echo success'; echo $?
success
0
$ bash -c 'set +o pipefail -e; false | false | true; echo success'; echo $?
success
0
$ bash -c 'set +o pipefail -e; true | true | false; echo success'; echo $?
1

Test with pipefail being enabled:

$ bash -c 'set -o pipefail -e; true | false | true; echo success'; echo $?
1

Html.ActionLink as a button or an image, not a link

Do what Mehrdad says - or use the url helper from an HtmlHelper extension method like Stephen Walther describes here and make your own extension method which can be used to render all of your links.

Then it will be easy to render all links as buttons/anchors or whichever you prefer - and, most importantly, you can change your mind later when you find out that you actually prefer some other way of making your links.

What is SaaS, PaaS and IaaS? With examples

I know this question has been answered a while ago but this could help.

What do the following terms mean?

SaaS

Software as a Service - Essentially, any application that runs with its contents from the cloud is referred to as Software as a Service, As long as you do not own it.

Some examples are Gmail, Netflix, OneDrive etc.

AUDIENCE: End users, everybody

IaaS

Infrastructure as a Service means that the provider allows a portion of their computing power to its customers, It is purchased by the potency of the computing power and they are bundled in Virtual Machines. A company like Google Cloud platform, AWS, Alibaba Cloud can be referred to as IaaS providers because they sell processing powers (servers, storage, networking) to their users in terms of Virtual Machines.

AUDIENCE: IT professionals, System Admins

PaaS

Platform as a Service is more like the middle-man between IaaS and SaaS, Instead of a customer having to deal with the nitty-gritty of servers, networks and storage, everything is readily available by the PaaS providers. Essentially a development environment is initialized to make building applications easier.

Examples would be Heroku, AWS Elastic Beanstalk, Google App Engine etc

AUDIENCE: Software developers.

There are various cloud services available today, such as Amazon's EC2 and AWS, Apache Hadoop, Microsoft Azure and many others. Which category does each belong to and why?

Amazon EC2 and AWS - is an Infrastructure as a Service because you'll need System Administrators to manage the working process of your operating system. There is no abstraction to build a fully featured app ordinarily. Microsoft Azure would also fall under this category following the aforementioned guidelines.

I really haven't used Apache Hadoop, so I really cannot say.

Java NIO FileChannel versus FileOutputstream performance / usefulness

If you are not using the transferTo feature or non-blocking features you will not notice a difference between traditional IO and NIO(2) because the traditional IO maps to NIO.

But if you can use the NIO features like transferFrom/To or want to use Buffers, then of course NIO is the way to go.

You don't have permission to access / on this server

Set required all granted in /etc/httpd/conf/httpd.conf

Why is the time complexity of both DFS and BFS O( V + E )

Time complexity is O(E+V) instead of O(2E+V) because if the time complexity is n^2+2n+7 then it is written as O(n^2).

Hence, O(2E+V) is written as O(E+V)

because difference between n^2 and n matters but not between n and 2n.

Why use prefixes on member variables in C++ classes

I can't say how widespred it is, but speaking personally, I always (and have always) prefixed my member variables with 'm'. E.g.:

class Person {
   .... 
   private:
       std::string mName;
};

It's the only form of prefixing I do use (I'm very anti Hungarian notation) but it has stood me in good stead over the years. As an aside, I generally detest the use of underscores in names (or anywhere else for that matter), but do make an exception for preprocessor macro names, as they are usually all uppercase.

copy-item With Alternate Credentials

Here is a post where someone got it to work. It looks like it requires a registry change.

Java: Date from unix timestamp

Date d = new Date(i * 1000 + TimeZone.getDefault().getRawOffset());

Resizing image in Java

We're doing this to create thumbnails of images:

  BufferedImage tThumbImage = new BufferedImage( tThumbWidth, tThumbHeight, BufferedImage.TYPE_INT_RGB );
  Graphics2D tGraphics2D = tThumbImage.createGraphics(); //create a graphics object to paint to
  tGraphics2D.setBackground( Color.WHITE );
  tGraphics2D.setPaint( Color.WHITE );
  tGraphics2D.fillRect( 0, 0, tThumbWidth, tThumbHeight );
  tGraphics2D.setRenderingHint( RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR );
  tGraphics2D.drawImage( tOriginalImage, 0, 0, tThumbWidth, tThumbHeight, null ); //draw the image scaled

  ImageIO.write( tThumbImage, "JPG", tThumbnailTarget ); //write the image to a file

Array initialization syntax when not in a declaration

For those of you, who doesn't like this monstrous new AClass[] { ... } syntax, here's some sugar:

public AClass[] c(AClass... arr) { return arr; }

Use this little function as you like:

AClass[] array;
...
array = c(object1, object2);

Breadth First Vs Depth First

These two terms differentiate between two different ways of walking a tree.

It is probably easiest just to exhibit the difference. Consider the tree:

    A
   / \
  B   C
 /   / \
D   E   F

A depth first traversal would visit the nodes in this order

A, B, D, C, E, F

Notice that you go all the way down one leg before moving on.

A breadth first traversal would visit the node in this order

A, B, C, D, E, F

Here we work all the way across each level before going down.

(Note that there is some ambiguity in the traversal orders, and I've cheated to maintain the "reading" order at each level of the tree. In either case I could get to B before or after C, and likewise I could get to E before or after F. This may or may not matter, depends on you application...)


Both kinds of traversal can be achieved with the pseudocode:

Store the root node in Container
While (there are nodes in Container)
   N = Get the "next" node from Container
   Store all the children of N in Container
   Do some work on N

The difference between the two traversal orders lies in the choice of Container.

  • For depth first use a stack. (The recursive implementation uses the call-stack...)
  • For breadth-first use a queue.

The recursive implementation looks like

ProcessNode(Node)
   Work on the payload Node
   Foreach child of Node
      ProcessNode(child)
   /* Alternate time to work on the payload Node (see below) */

The recursion ends when you reach a node that has no children, so it is guaranteed to end for finite, acyclic graphs.


At this point, I've still cheated a little. With a little cleverness you can also work-on the nodes in this order:

D, B, E, F, C, A

which is a variation of depth-first, where I don't do the work at each node until I'm walking back up the tree. I have however visited the higher nodes on the way down to find their children.

This traversal is fairly natural in the recursive implementation (use the "Alternate time" line above instead of the first "Work" line), and not too hard if you use a explicit stack, but I'll leave it as an exercise.

Check mySQL version on Mac 10.8.5

To check your MySQL version on your mac, navigate to the directory where you installed it (default is usr/local/mysql/bin) and issue this command:

./mysql --version

Alternatively, to avoid needing to navigate to that specific dir to run the command, add its location to your path ($PATH). There's more than one way to add a dir to your $PATH (with explanations on stackoverflow and other places on how to do so), such as adding it to your ./bash_profile.

After adding the mysql bin dir to your $PATH, verify it's there by executing:

echo $PATH

Thereafter you can check your mysql version from anywhere by running (note no "./"):

mysql --version

What is the T-SQL syntax to connect to another SQL Server?

Whenever we are trying to retrieve any data from another server we need two steps.

First step:

-- Server one scalar variable
DECLARE @SERVER VARCHAR(MAX)
--Oracle is the server to which we want to connect
EXEC SP_ADDLINKEDSERVER @SERVER='ORACLE'

Second step:

--DBO is the owner name to know table owner name execute (SP_HELP TABLENAME)    
SELECT * INTO DESTINATION_TABLE_NAME 
FROM ORACLE.SOURCE_DATABASENAME.DBO.SOURCE_TABLE

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

You might want to use your local file as a last resort.

Seems as of now jQuery's own CDN does not support https. If it did you then might want to load from there first.

So here's the sequence: Google CDN => Microsoft CDN => Your local copy.

<!-- load jQuery from Google's CDN -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> 
<!-- fallback to Microsoft's Ajax CDN -->
<script> window.jQuery || document.write('<script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.3.min.js">\x3C/script>')</script> 
<!-- fallback to local file -->
<script> window.jQuery || document.write('<script src="Assets/jquery-1.8.3.min.js">\x3C/script>')</script> 

Histogram Matplotlib

import matplotlib.pyplot as plt
import numpy as np

mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
hist, bins = np.histogram(x, bins=50)
width = 0.7 * (bins[1] - bins[0])
center = (bins[:-1] + bins[1:]) / 2
plt.bar(center, hist, align='center', width=width)
plt.show()

enter image description here

The object-oriented interface is also straightforward:

fig, ax = plt.subplots()
ax.bar(center, hist, align='center', width=width)
fig.savefig("1.png")

If you are using custom (non-constant) bins, you can pass compute the widths using np.diff, pass the widths to ax.bar and use ax.set_xticks to label the bin edges:

import matplotlib.pyplot as plt
import numpy as np

mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
bins = [0, 40, 60, 75, 90, 110, 125, 140, 160, 200]
hist, bins = np.histogram(x, bins=bins)
width = np.diff(bins)
center = (bins[:-1] + bins[1:]) / 2

fig, ax = plt.subplots(figsize=(8,3))
ax.bar(center, hist, align='center', width=width)
ax.set_xticks(bins)
fig.savefig("/tmp/out.png")

plt.show()

enter image description here

Getting Keyboard Input

You can use Scanner class like this:

  import java.util.Scanner;

public class Main{
    public static void main(String args[]){

    Scanner scan= new Scanner(System.in);

    //For string

    String text= scan.nextLine();

    System.out.println(text);

    //for int

    int num= scan.nextInt();

    System.out.println(num);
    }
}

Link a photo with the cell in excel

There is a much simpler way. Put your picture in a comment box within the description cell. That way you only have one column and when you sort the picture will always stay with the description. Okay... Right click the cell containing the description... Insert comment...right click the outer border... Format comment...colours and lines tab... Colour drop down...Fill effects...Picture tab...select picture...browse for your picture (it might be best to keep all pictures in one folder for ease of placement)...ok... you will probably need to go to the size tab and frig around with the height and width. Done... You now only need to mouse over the red in the top right corner of the cell and the picture will appear...like magic.

This method means that the row height can be kept to a minimum and the pictures can be as big as you like.

Git error: src refspec master does not match any error: failed to push some refs

One classic root cause for this message is:

  • when the repo has been initialized (git init lis4368/assignments),
  • but no commit has ever been made

Ie, if you don't have added and committed at least once, there won't be a local master branch to push to.

Try first to create a commit:

  • either by adding (git add .) then git commit -m "first commit"
    (assuming you have the right files in place to add to the index)
  • or by create a first empty commit: git commit --allow-empty -m "Initial empty commit"

And then try git push -u origin master again.

See "Why do I need to explicitly push a new branch?" for more.

How to remove all white spaces from a given text file

I think you may use sed to wipe out the space while not losing some infomation like changing to another line.

cat hello.txt | sed '/^$/d;s/[[:blank:]]//g'

Converting Integers to Roman Numerals - Java

After seeing some of the answers here I had to post this. I think that my algorithm is far the most easiest to understand and the bit of performance lost is not important even on a relatively large scale. I'm also obeying the standardized coding conventions as opposed to some of the users here.

Average conversion time: 0.05ms (based on converting all numbers 1-3999 and dividing by 3999)

public static String getRomanNumeral(int arabicNumber) {

    if (arabicNumber > 0 && arabicNumber < 4000) {

        final LinkedHashMap<Integer, String> numberLimits = 
            new LinkedHashMap<>();

        numberLimits.put(1, "I");
        numberLimits.put(4, "IV");
        numberLimits.put(5, "V");
        numberLimits.put(9, "IX");
        numberLimits.put(10, "X");
        numberLimits.put(40, "XL");
        numberLimits.put(50, "L");
        numberLimits.put(90, "XC");
        numberLimits.put(100, "C");
        numberLimits.put(400, "CD");
        numberLimits.put(500, "D");
        numberLimits.put(900, "CM");
        numberLimits.put(1000, "M");

        String romanNumeral = "";

        while (arabicNumber > 0) {
            int highestFound = 0;
            for (Map.Entry<Integer, String> current : numberLimits.entrySet()){
                if (current.getKey() <= arabicNumber) {
                    highestFound = current.getKey();
                }
            }
            romanNumeral += numberLimits.get(highestFound);
            arabicNumber -= highestFound;
        }

        return romanNumeral;

    } else {
        throw new UnsupportedOperationException(arabicNumber 
            + " is not a valid Roman numeral.");
    }
}

First you have to take into account that Roman numerals are only in the interval of <1-4000), but that can be solved by a simple if and a thrown exception. Then you can try to find the largest set roman numeral in a given integer and if found subtract it from the original number and add it to the result. Repeat with the newly acquired number until you hit zero.

Session variables not working php

Maybe if your session path is not working properly you can try session.save_path(path/to/any folder); function as alternative path. If it works you can ask your hosting provider about default path issue.

How exactly does __attribute__((constructor)) work?

  1. It runs when a shared library is loaded, typically during program startup.
  2. That's how all GCC attributes are; presumably to distinguish them from function calls.
  3. GCC-specific syntax.
  4. Yes, this works in C and C++.
  5. No, the function does not need to be static.
  6. The destructor runs when the shared library is unloaded, typically at program exit.

So, the way the constructors and destructors work is that the shared object file contains special sections (.ctors and .dtors on ELF) which contain references to the functions marked with the constructor and destructor attributes, respectively. When the library is loaded/unloaded the dynamic loader program (ld.so or somesuch) checks whether such sections exist, and if so, calls the functions referenced therein.

Come to think of it, there is probably some similar magic in the normal static linker so that the same code is run on startup/shutdown regardless if the user chooses static or dynamic linking.

How to copy data to clipboard in C#

My Experience with this issue using WPF C# coping to clipboard and System.Threading.ThreadStateException is here with my code that worked correctly with all browsers:

Thread thread = new Thread(() => Clipboard.SetText("String to be copied to clipboard"));
thread.SetApartmentState(ApartmentState.STA); //Set the thread to STA
thread.Start(); 
thread.Join();

credits to this post here

But this works only on localhost, so don't try this on a server, as it's not going to work.

On server-side, I did it by using zeroclipboard. The only way, after a lot of research.

How do I improve ASP.NET MVC application performance?

Use the latest version of Task Parallel Library (TPL), according to .Net version. Have to choose the correct modules of TPL for different purposes.

Git - how delete file from remote repository

The easiest thing to do is to move the file from your local directory temporarily, then commit changes to your remote repo. Then add it back to your local repo, make sure to update .gitignore so it doesn't commit to remote again

How can I add items to an empty set in python

>>> d = {}
>>> D = set()
>>> type(d)
<type 'dict'>
>>> type(D)
<type 'set'>

What you've made is a dictionary and not a Set.

The update method in dictionary is used to update the new dictionary from a previous one, like so,

>>> abc = {1: 2}
>>> d.update(abc)
>>> d
{1: 2}

Whereas in sets, it is used to add elements to the set.

>>> D.update([1, 2])
>>> D
set([1, 2])

Paging with Oracle

Ask Tom on pagination and very, very useful analytic functions.

This is excerpt from that page:

select * from (
    select /*+ first_rows(25) */
     object_id,object_name,
     row_number() over
    (order by object_id) rn
    from all_objects
)
where rn between :n and :m
order by rn;

jQuery Date Picker - disable past dates

just replace your code:

old code:

$("#dateSelect").datepicker({
    showOtherMonths: true,
    selectOtherMonths: true,
    changeMonth: true,
    changeYear: true,
    showButtonPanel: true,
    dateFormat: 'yy-mm-dd'

});

new code:

$("#dateSelect").datepicker({
    showOtherMonths: true,
    selectOtherMonths: true,
    changeMonth: true,
    changeYear: true,
    showButtonPanel: true,
    dateFormat: 'yy-mm-dd',
    minDate: 0
});

error_reporting(E_ALL) does not produce error

In your php.ini file check for display_errors. If it is off, then make it on as below:

display_errors = On

It should display warnings/notices/errors .

Please read this

http://www.php.net/manual/en/errorfunc.configuration.php#ini.error-reporting

I have Python on my Ubuntu system, but gcc can't find Python.h

Go to Synaptic package manager. Reload -> Search for python -> select the python package you want -> Submit -> Install Works for me ;)

Exactly, the package you need to install is python-dev.

Magento: get a static block as html in a phtml file

In the layout (app/design/frontend/your_theme/layout/default.xml):

<default>
    <cms_page> <!-- need to be redefined for your needs -->
        <reference name="content">
            <block type="cms/block" name="cms_newest_product" as="cms_newest_product">
                <action method="setBlockId"><block_id>newest_product</block_id></action>
            </block>
        </reference>
    </cms_page>
</default>

In your phtml template:

<?php echo $this->getChildHtml('newest_product'); ?>

Don't forget about cache cleaning.

I think it help.

Go to Matching Brace in Visual Studio?

On the Swiss-French keyboard : use CTRL + SHIFT + ^

How can I save a base64-encoded image to disk?

You can use a third-party library like base64-img or base64-to-image.

  1. base64-img
const base64Img = require('base64-img');

const data = 'data:image/png;base64,...';
const destpath = 'dir/to/save/image';
const filename = 'some-filename';

base64Img.img(data, destpath, filename, (err, filepath) => {}); // Asynchronous using

const filepath = base64Img.imgSync(data, destpath, filename); // Synchronous using
  1. base64-to-image
const base64ToImage = require('base64-to-image');

const base64Str = 'data:image/png;base64,...';
const path = 'dir/to/save/image/'; // Add trailing slash
const optionalObj = { fileName: 'some-filename', type: 'png' };

const { imageType, fileName } = base64ToImage(base64Str, path, optionalObj); // Only synchronous using

How to get the current location in Google Maps Android API v2?

To get the location when the user clicks on a button call this method in the onClick-

void getCurrentLocation() {
    Location myLocation  = mMap.getMyLocation();
    if(myLocation!=null)
    {
        double dLatitude = myLocation.getLatitude();
        double dLongitude = myLocation.getLongitude();
        Log.i("APPLICATION"," : "+dLatitude);
        Log.i("APPLICATION"," : "+dLongitude);
        mMap.addMarker(new MarkerOptions().position(
                new LatLng(dLatitude, dLongitude)).title("My Location").icon(BitmapDescriptorFactory.fromBitmap(Utils.getBitmap("pointer_icon.png"))));
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(dLatitude, dLongitude), 8));

    }
    else
    {
        Toast.makeText(this, "Unable to fetch the current location", Toast.LENGTH_SHORT).show();
    }

}

Also make sure that the

setMyLocationEnabled

is set to true.

Try and see if this works...

Extracting date from a string in Python

Using python-dateutil:

In [1]: import dateutil.parser as dparser

In [18]: dparser.parse("monkey 2010-07-10 love banana",fuzzy=True)
Out[18]: datetime.datetime(2010, 7, 10, 0, 0)

Invalid dates raise a ValueError:

In [19]: dparser.parse("monkey 2010-07-32 love banana",fuzzy=True)
# ValueError: day is out of range for month

It can recognize dates in many formats:

In [20]: dparser.parse("monkey 20/01/1980 love banana",fuzzy=True)
Out[20]: datetime.datetime(1980, 1, 20, 0, 0)

Note that it makes a guess if the date is ambiguous:

In [23]: dparser.parse("monkey 10/01/1980 love banana",fuzzy=True)
Out[23]: datetime.datetime(1980, 10, 1, 0, 0)

But the way it parses ambiguous dates is customizable:

In [21]: dparser.parse("monkey 10/01/1980 love banana",fuzzy=True, dayfirst=True)
Out[21]: datetime.datetime(1980, 1, 10, 0, 0)