Programs & Examples On #Delta row compression

jQuery selector for inputs with square brackets in the name attribute

Per the jQuery documentation, try this:

$('input[inputName\\[\\]=someValue]')

[EDIT] However, I'm not sure that's the right syntax for your selector. You probably want:

$('input[name="inputName[]"][value="someValue"]')

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 can I link to a specific glibc version?

Link with -static. When you link with -static the linker embeds the library inside the executable, so the executable will be bigger, but it can be executed on a system with an older version of glibc because the program will use it's own library instead of that of the system.

Launch an event when checking a checkbox in Angular2

Check Demo: https://stackblitz.com/edit/angular-6-checkbox?embed=1&file=src/app/app.component.html

  CheckBox: use change event to call the function and pass the event.

<label class="container">    
   <input type="checkbox" [(ngModel)]="theCheckbox"  data-md-icheck 
    (change)="toggleVisibility($event)"/>
      Checkbox is <span *ngIf="marked">checked</span><span 
     *ngIf="!marked">unchecked</span>
     <span class="checkmark"></span>
</label>
 <div>And <b>ngModel</b> also works, it's value is <b>{{theCheckbox}}</b></div>

Add newly created specific folder to .gitignore in Git

From "git help ignore" we learn:

If the pattern ends with a slash, it is removed for the purpose of the following description, but it would only find a match with a directory. In other words, foo/ will match a directory foo and paths underneath it, but will not match a regular file or a symbolic link foo (this is consistent with the way how pathspec works in general in git).

Therefore what you need is

public_html/stats/

Chrome says "Resource interpreted as script but transferred with MIME type text/plain.", what gives?

I was having the same issue when trying to change a background images in a array through javascript (jQuery in this case).

Anyway.

Instead of this:

m.setStyle('background-image','url(/templates/site/images/style5/'+backgs[i]+')')

do this:

eval("m.setStyle('background-image','url(/templates/site/images/style5/'+backgs[i]+')')");

Chrome javascript gets screwed when trying to parse a variable inside an element structured with ' . In my case it stopped just before the image array being inserted. Instead of parsing the image url + image name (inside the array), it was parsing just the image url.

You probably need to search inside the code and see where it happens. FF, IE and all other don't have this problem.

How to sort multidimensional array by column?

below solution worked for me in case of required number is float. Solution:

table=sorted(table,key=lambda x: float(x[5]))
for row in table[:]:
    Ntable.add_row(row)

'

invalid operands of types int and double to binary 'operator%'

Because % is only defined for integer types. That's the modulus operator.

5.6.2 of the standard:

The operands of * and / shall have arithmetic or enumeration type; the operands of % shall have integral or enumeration type. [...]

As Oli pointed out, you can use fmod(). Don't forget to include math.h.

T-SQL get SELECTed value of stored procedure

Try do this:

EXEC @SelectedValue = GetMyInt

Resize to fit image in div, and center horizontally and vertically

SOLUTION

<style>
.container {
    margin: 10px;
    width: 115px;
    height: 115px;
    line-height: 115px;
    text-align: center;
    border: 1px solid red;
    background-image: url("http://i.imgur.com/H9lpVkZ.jpg");
    background-repeat: no-repeat;
    background-position: center;
    background-size: contain;

}

</style>

<div class='container'>
</div>

<div class='container' style='width:50px;height:100px;line-height:100px'>
</div>

<div class='container' style='width:140px;height:70px;line-height:70px'>
</div>

Better way to find control in ASP.NET

I decided to just build controls dictionaries. Harder to maintain, might run faster than the recursive FindControl().

protected void Page_Load(object sender, EventArgs e)
{
  this.BuildControlDics();
}

private void BuildControlDics()
{
  _Divs = new Dictionary<MyEnum, HtmlContainerControl>();
  _Divs.Add(MyEnum.One, this.divOne);
  _Divs.Add(MyEnum.Two, this.divTwo);
  _Divs.Add(MyEnum.Three, this.divThree);

}

And before I get down-thumbs for not answering the OP's question...

Q: Now, my question is that is there any other way/solution to find the nested control in ASP.NET? A: Yes, avoid the need to search for them in the first place. Why search for things you already know are there? Better to build a system allowing reference of known objects.

Execute another jar in a Java program

If you are java 1.6 then the following can also be done:

import javax.tools.JavaCompiler; 
import javax.tools.ToolProvider; 

public class CompilerExample {

    public static void main(String[] args) {
        String fileToCompile = "/Users/rupas/VolatileExample.java";

        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

        int compilationResult = compiler.run(null, null, null, fileToCompile);

        if (compilationResult == 0) {
            System.out.println("Compilation is successful");
        } else {
            System.out.println("Compilation Failed");
        }
    }
}

How to solve '...is a 'type', which is not valid in the given context'? (C#)

You forgot to specify the variable name. It should be CERas.CERAS newCeras = new CERas.CERAS();

Get an array of list element contents in jQuery

var arr = new Array();

$('li').each(function() { 
  arr.push(this.innerHTML); 
})

Calling pylab.savefig without display in ipython

This is a matplotlib question, and you can get around this by using a backend that doesn't display to the user, e.g. 'Agg':

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

plt.plot([1,2,3])
plt.savefig('/tmp/test.png')

EDIT: If you don't want to lose the ability to display plots, turn off Interactive Mode, and only call plt.show() when you are ready to display the plots:

import matplotlib.pyplot as plt

# Turn interactive plotting off
plt.ioff()

# Create a new figure, plot into it, then close it so it never gets displayed
fig = plt.figure()
plt.plot([1,2,3])
plt.savefig('/tmp/test0.png')
plt.close(fig)

# Create a new figure, plot into it, then don't close it so it does get displayed
plt.figure()
plt.plot([1,3,2])
plt.savefig('/tmp/test1.png')

# Display all "open" (non-closed) figures
plt.show()

Extracting just Month and Year separately from Pandas Datetime column

SINGLE LINE: Adding a column with 'year-month'-paires: ('pd.to_datetime' first changes the column dtype to date-time before the operation)

df['yyyy-mm'] = pd.to_datetime(df['ArrivalDate']).dt.strftime('%Y-%m')?

Accordingly for an extra 'year' or 'month' column:

df['yyyy'] = pd.to_datetime(df['ArrivalDate']).dt.strftime('%Y')?
df['mm'] = pd.to_datetime(df['ArrivalDate']).dt.strftime('%m')?

Using "label for" on radio buttons

(Firstly read the other answers which has explained the for in the <label></label> tags. Well, both the tops answers are correct, but for my challenge, it was when you have several radio boxes, you should select for them a common name like name="r1" but with different ids id="r1_1" ... id="r1_2"

So this way the answer is more clear and removes the conflicts between name and ids as well.

You need different ids for different options of the radio box.

_x000D_
_x000D_
<input type="radio" name="r1" id="r1_1" />_x000D_
_x000D_
       <label for="r1_1">button text one</label>_x000D_
       <br/>_x000D_
       <input type="radio" name="r1" id="r1_2" />_x000D_
_x000D_
       <label for="r1_2">button text two</label>_x000D_
       <br/>_x000D_
       <input type="radio" name="r1" id="r1_3" />_x000D_
_x000D_
       <label for="r1_3">button text three</label>
_x000D_
_x000D_
_x000D_

Finding the type of an object in C++

As others indicated you can use dynamic_cast. But generally using dynamic_cast for finding out the type of the derived class you are working upon indicates the bad design. If you are overriding a function that takes pointer of A as the parameter then it should be able to work with the methods/data of class A itself and should not depend on the the data of class B. In your case instead of overriding if you are sure that the method you are writing will work with only class B, then you should write a new method in class B.

How to create a thread?

The following ways work.

// The old way of using ParameterizedThreadStart. This requires a
// method which takes ONE object as the parameter so you need to
// encapsulate the parameters inside one object.
Thread t = new Thread(new ParameterizedThreadStart(StartupA));
t.Start(new MyThreadParams(path, port));

// You can also use an anonymous delegate to do this.
Thread t2 = new Thread(delegate()
{
    StartupB(port, path);
});
t2.Start();

// Or lambda expressions if you are using C# 3.0
Thread t3 = new Thread(() => StartupB(port, path));
t3.Start();

The Startup methods have following signature for these examples.

public void StartupA(object parameters);

public void StartupB(int port, string path);

Excel compare two columns and highlight duplicates

I was trying to compare A-B columns and highlight equal text, but usinng the obove fomrulas some text did not match at all. So I used form (VBA macro to compare two columns and color highlight cell differences) codes and I modified few things to adapt it to my application and find any desired column (just by clicking it). In my case, I use large and different numbers of rows on each column. Hope this helps:

Sub ABTextCompare()

Dim Report As Worksheet
Dim i, j, colNum, vMatch As Integer
Dim lastRowA, lastRowB, lastRow, lastColumn As Integer
Dim ColumnUsage As String
Dim colA, colB, colC As String
Dim A, B, C As Variant

Set Report = Excel.ActiveSheet
vMatch = 1

'Select A and B Columns to compare
On Error Resume Next
 Set A = Application.InputBox(Prompt:="Select column to compare", Title:="Column A", Type:=8)
  If A Is Nothing Then Exit Sub
colA = Split(A(1).Address(1, 0), "$")(0)
 Set B = Application.InputBox(Prompt:="Select column being searched", Title:="Column B", Type:=8)
   If A Is Nothing Then Exit Sub
  colB = Split(B(1).Address(1, 0), "$")(0)
 'Select Column to show results
 Set C = Application.InputBox("Select column  to show results", "Results", Type:=8)
    If C Is Nothing Then Exit Sub
  colC = Split(C(1).Address(1, 0), "$")(0)

'Get Last Row
lastRowA = Report.Cells.Find("", Range(colA & 1), xlFormulas, xlByRows, xlPrevious).Row - 1 ' Last row in column A
lastRowB = Report.Cells.Find("", Range(colB & 1), xlFormulas, xlByRows, xlPrevious).Row - 1 ' Last row in column B

 Application.ScreenUpdating = False
'***************************************************
For i = 2 To lastRowA
      For j = 2 To lastRowB
          If Report.Cells(i, A.Column).Value <> "" Then
              If InStr(1, Report.Cells(j, B.Column).Value, Report.Cells(i, A.Column).Value, vbTextCompare) > 0 Then
                  vMatch = vMatch + 1
                  Report.Cells(i, A.Column).Interior.ColorIndex = 35 'Light green background
                  Range(colC & 1).Value = "Items Found"
                  Report.Cells(i, A.Column).Copy Destination:=Range(colC & vMatch)
                  Exit For
              Else
                  'Do Nothing
              End If
          End If
      Next j
  Next i
If vMatch = 1 Then
    MsgBox Prompt:="No Itmes Found", Buttons:=vbInformation
End If
'***************************************************
Application.ScreenUpdating = True

End Sub

How do I check in SQLite whether a table exists?

If you are getting a "table already exists" error, make changes in the SQL string as below:

CREATE table IF NOT EXISTS table_name (para1,para2);

This way you can avoid the exceptions.

How to decrypt the password generated by wordpress

You will not be able to retrieve a plain text password from wordpress.

Wordpress use a 1 way encryption to store the passwords using a variation of md5. There is no way to reverse this.

See this article for more info http://wordpress.org/support/topic/how-is-the-user-password-encrypted-wp_hash_password

Android difference between Two Dates

Short & Sweet:

/**
 * Get a diff between two dates
 *
 * @param oldDate the old date
 * @param newDate the new date
 * @return the diff value, in the days
 */
public static long getDateDiff(SimpleDateFormat format, String oldDate, String newDate) {
    try {
        return TimeUnit.DAYS.convert(format.parse(newDate).getTime() - format.parse(oldDate).getTime(), TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        e.printStackTrace();
        return 0;
    }
}

Usage:

int dateDifference = (int) getDateDiff(new SimpleDateFormat("dd/MM/yyyy"), "29/05/2017", "31/05/2017");
System.out.println("dateDifference: " + dateDifference);

Output:

dateDifference: 2

Kotlin Version:

@ExperimentalTime
fun getDateDiff(format: SimpleDateFormat, oldDate: String, newDate: String): Long {
    return try {
        DurationUnit.DAYS.convert(
            format.parse(newDate).time - format.parse(oldDate).time,
            DurationUnit.MILLISECONDS
        )
    } catch (e: Exception) {
        e.printStackTrace()
        0
    }
}

Remove insignificant trailing zeros from a number?

I first used a combination of matti-lyra and gary's answers:

r=(+n).toFixed(4).replace(/\.0+$/,'')

Results:

  • 1234870.98762341: "1234870.9876"
  • 1230009100: "1230009100"
  • 0.0012234: "0.0012"
  • 0.1200234: "0.12"
  • 0.000001231: "0"
  • 0.10001: "0.1000"
  • "asdf": "NaN" (so no runtime error)

The somewhat problematic case is 0.10001. I ended up using this longer version:

    r = (+n).toFixed(4);
    if (r.match(/\./)) {
      r = r.replace(/\.?0+$/, '');
    }
  • 1234870.98762341: "1234870.9876"
  • 1230009100: "1230009100"
  • 0.0012234: "0.0012"
  • 0.1200234: "0.12"
  • 0.000001231: "0"
  • 0.10001: "0.1"
  • "asdf": "NaN" (so no runtime error)

Update: And this is Gary's newer version (see comments):

r=(+n).toFixed(4).replace(/([0-9]+(\.[0-9]+[1-9])?)(\.?0+$)/,'$1')

This gives the same results as above.

Java Timestamp - How can I create a Timestamp with the date 23/09/2007?

You could also do the following:

// untested
Calendar cal = GregorianCalendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 23);// I might have the wrong Calendar constant...
cal.set(Calendar.MONTH, 8);// -1 as month is zero-based
cal.set(Calendar.YEAR, 2009);
Timestamp tstamp = new Timestamp(cal.getTimeInMillis());

Changing git commit message after push (given that no one pulled from remote)

git commit --amend

then edit and change the message in the current window. After that do

git push --force-with-lease

Egit rejected non-fast-forward

  1. Go in Github an create a repo for your new code.
  2. Use the new https or ssh url in Eclise when you are doing the push to upstream;

Relative path in HTML

The easiest way to solve this in pure HTML is to use the <base href="…"> element like so:

<base href="http://localhost/mywebsite/" />

Then all of the URLs in your HTML can just be this:

<a href="images/example.png">Link To Image</a>

Just change the <base href="…"> to match your server. The rest of the HTML paths will just fall in line and will be appended to that.

Difference in make_shared and normal shared_ptr in C++

Shared_ptr: Performs two heap allocation

  1. Control block(reference count)
  2. Object being managed

Make_shared: Performs only one heap allocation

  1. Control block and object data.

WPF Timer Like C# Timer

With Dispatcher you will need to include

using System.Windows.Threading;

Also note that if you right-click DispatcherTimer and click Resolve it should add the appropriate references.

val() doesn't trigger change() in jQuery

From redsquare's excellent suggestion, this works nicely:

$.fn.changeVal = function (v) {
    return this.val(v).trigger("change");
}

$("#my-input").changeVal("Tyrannosaurus Rex");

Find files and tar them (with spaces)

Big warning on several of the solutions (and your own test) :

When you do : anything | xargs something

xargs will try to fit "as many arguments as possible" after "something", but then you may end up with multiple invocations of "something".

So your attempt: find ... | xargs tar czvf file.tgz may end up overwriting "file.tgz" at each invocation of "tar" by xargs, and you end up with only the last invocation! (the chosen solution uses a GNU -T special parameter to avoid the problem, but not everyone has that GNU tar available)

You could do instead:

find . -type f -print0 | xargs -0 tar -rvf backup.tar
gzip backup.tar

Proof of the problem on cygwin:

$ mkdir test
$ cd test
$ seq 1 10000 | sed -e "s/^/long_filename_/" | xargs touch 
    # create the files
$ seq 1 10000 | sed -e "s/^/long_filename_/" | xargs tar czvf archive.tgz
    # will invoke tar several time as it can'f fit 10000 long filenames into 1
$ tar tzvf archive.tgz | wc -l
60
    # in my own machine, I end up with only the 60 last filenames, 
    # as the last invocation of tar by xargs overwrote the previous one(s)

# proper way to invoke tar: with -r  (which append to an existing tar file, whereas c would overwrite it)
# caveat: you can't have it compressed (you can't add to a compressed archive)
$ seq 1 10000 | sed -e "s/^/long_filename_/" | xargs tar rvf archive.tar #-r, and without z
$ gzip archive.tar
$ tar tzvf archive.tar.gz | wc -l
10000 
  # we have all our files, despite xargs making several invocations of the tar command

 

Note: that behavior of xargs is a well know diccifulty, and it is also why, when someone wants to do :

find .... | xargs grep "regex"

they intead have to write it:

find ..... | xargs grep "regex" /dev/null

That way, even if the last invocation of grep by xargs appends only 1 filename, grep sees at least 2 filenames (as each time it has: /dev/null, where it won't find anything, and the filename(s) appended by xargs after it) and thus will always display the file names when something maches "regex". Otherwise you may end up with the last results showing matches without a filename in front.

Static link of shared library function in gcc

If you want to link, say, libapplejuice statically, but not, say, liborangejuice, you can link like this:

gcc object1.o object2.o -Wl,-Bstatic -lapplejuice -Wl,-Bdynamic -lorangejuice -o binary

There's a caveat -- if liborangejuice uses libapplejuice, then libapplejuice will be dynamically linked too.

You'll have to link liborangejuice statically alongside with libapplejuice to get libapplejuice static.

And don't forget to keep -Wl,-Bdynamic else you'll end up linking everything static, including libc (which isn't a good thing to do).

How to set the min and max height or width of a Frame?

A workaround - at least for the minimum size: You can use grid to manage the frames contained in root and make them follow the grid size by setting sticky='nsew'. Then you can use root.grid_rowconfigure and root.grid_columnconfigure to set values for minsize like so:

from tkinter import Frame, Tk

class MyApp():
    def __init__(self):
        self.root = Tk()

        self.my_frame_red = Frame(self.root, bg='red')
        self.my_frame_red.grid(row=0, column=0, sticky='nsew')

        self.my_frame_blue = Frame(self.root, bg='blue')
        self.my_frame_blue.grid(row=0, column=1, sticky='nsew')

        self.root.grid_rowconfigure(0, minsize=200, weight=1)
        self.root.grid_columnconfigure(0, minsize=200, weight=1)
        self.root.grid_columnconfigure(1, weight=1)

        self.root.mainloop()

if __name__ == '__main__':
    app = MyApp()

But as Brian wrote (in 2010 :D) you can still resize the window to be smaller than the frame if you don't limit its minsize.

javascript create array from for loop

Remove obj and just do this inside your for loop:

arr.push(i);

Also, the i < yearEnd condition will not include the final year, so change it to i <= yearEnd.

Why is width: 100% not working on div {display: table-cell}?

Putting display:table; inside .outer-wrapper seemed to work...

JSFiddle Link


EDIT: Two Wrappers Using Display Table Cell

I would comment on your answer but i have too little rep :( anyways...

Going off your answer, seems like all you need to do is add display:table; inside .outer-wrapper (Dejavu?), and you can get rid of table-wrapper whole-heartedly.

JSFiddle

But yeah, the position:absolute lets you place the div over the img, I read too quickly and thought that you couldn't use position:absolute at all, but seems like you figured it out already. Props!

I'm not going to post the source code, after all its 99% timshutes's work, so please refer to his answer, or just use my jsfiddle link

Update: One Wrapper Using Flexbox

It's been a while, and all the cool kids are using flexbox:

<div style="display: flex; flex-direction: column; justify-content: center; align-items: center;">
    stuff to be centered
</div>

Full JSFiddle Solution

Browser Support (source): IE 11+, FireFox 42+, Chrome 46+, Safari 8+, iOS 8.4+ (-webkit- prefix), Android 4.1+ (-webkit- prefix)

CSS Tricks: a Guide to Flexbox

How to Center in CSS: input how you want your content to be centered, and it outputs how to do it in html and css. The future is here!

How to get terminal's Character Encoding

The terminal uses environment variables to determine which character set to use, therefore you can determine it by looking at those variables:

echo $LC_CTYPE

or

echo $LANG

How can I dynamically switch web service addresses in .NET without a recompile?

open solition explorer

right click the webservice change URL Behavior to Dynamic

click the 'show all files' icon in solution explorer

in the web reference edit the Reference.cs file

change constructer

public Service1() {
        this.Url = "URL"; // etc. string  variable this.Url = ConfigClass.myURL
      }

Internet Explorer 11 detection

A pretty safe & concise way to detect IE 11 only is

if(window.msCrypto) {
    // I'm IE11 for sure
}

or something like this

var IE11= !!window.msCrypto;

msCrypto is a prefixed version of the window.crypto object and only implemented in IE 11.
https://developer.mozilla.org/en-US/docs/Web/API/Window/crypto

jQuery: Check if div with certain class name exists

Here is very sample solution for check class (hasClass) in Javascript:

const mydivclass = document.querySelector('.mydivclass');
// if 'hasClass' is exist on 'mydivclass'
if(mydivclass.classList.contains('hasClass')) {
   // do something if 'hasClass' is exist.
}

jquery to validate phone number

I know this is an old post, but I thought I would share my solution to help others.

This function will work if you want to valid 10 digits phone number "US number"

function getValidNumber(value)
{
    value = $.trim(value).replace(/\D/g, '');

    if (value.substring(0, 1) == '1') {
        value = value.substring(1);
    }

    if (value.length == 10) {

        return value;
    }

    return false;
}

Here how to use this method

var num = getValidNumber('(123) 456-7890');
if(num !== false){
     alert('The valid number is: ' + num);
} else {
     alert('The number you passed is not a valid US phone number');
}

How to label each equation in align environment?

You can label each line separately, in your case:

\begin{align}
  \lambda_i + \mu_i = 0 \label{eq:1}\\
  \mu_i \xi_i = 0 \label{eq:2}\\
  \lambda_i [y_i( w^T x_i + b) - 1 + \xi_i] = 0 \label{eq:3}
\end{align} 

Note that this only works for AMS environments that are designed for multiple equations (as opposed to multiline single equations).

Polygon Drawing and Getting Coordinates with Google Map API v3

Since Google updates sometimes the name of fixed object properties, the best practice is to use GMaps V3 methods to get coordinates event.overlay.getPath().getArray() and to get lat latlng.lat() and lng latlng.lng().

So, I just wanted to improve this answer a bit exemplifying with polygon and POSTGIS insert case scenario:

google.maps.event.addListener(drawingManager, 'overlaycomplete', function(event) {
    var str_input ='POLYGON((';
    if (event.type == google.maps.drawing.OverlayType.POLYGON) {
      console.log('polygon path array', event.overlay.getPath().getArray());
      $.each(event.overlay.getPath().getArray(), function(key, latlng){
        var lat = latlng.lat();
        var lon = latlng.lng();
        console.log(lat, lon); 
        str_input += lat +' '+ lon +',';
      });
    }
    str_input = str_input.substr(0,str_input.length-1) + '))';
    console.log('the str_input will be:', str_input);

    // YOU CAN THEN USE THE str_inputs AS IN THIS EXAMPLE OF POSTGIS POLYGON INSERT
    // INSERT INTO your_table (the_geom, name) VALUES (ST_GeomFromText(str_input, 4326), 'Test')

  });

Android – Listen For Incoming SMS Messages

The accepted answer is correct and works on older versions of Android where Android OS asks for permissions at the app install, However on newer versions Android it doesn't work straight away because newer Android OS asks for permissions during runtime when the app requires that feature. Therefore in order to receive SMS on newer versions of Android using technique mentioned in accepted answer programmer must also implement code that will check and ask for permissions from user during runtime. In this case permissions checking functionality/code can be implemented in onCreate() of app's first activity. Just copy and paste following two methods in your first activity and call checkForSmsReceivePermissions() method at the end of onCreate().

    void checkForSmsReceivePermissions(){
    // Check if App already has permissions for receiving SMS
    if(ContextCompat.checkSelfPermission(getBaseContext(), "android.permission.RECEIVE_SMS") == PackageManager.PERMISSION_GRANTED) {
        // App has permissions to listen incoming SMS messages
        Log.d("adnan", "checkForSmsReceivePermissions: Allowed");
    } else {
        // App don't have permissions to listen incoming SMS messages
        Log.d("adnan", "checkForSmsReceivePermissions: Denied");

        // Request permissions from user 
        ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.RECEIVE_SMS}, 43391);
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if(requestCode == 43391){
        if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
            Log.d("adnan", "Sms Receive Permissions granted");
        } else {
            Log.d("adnan", "Sms Receive Permissions denied");
        }
    }
}

Set variable with multiple values and use IN

Ideally you shouldn't be splitting strings in T-SQL at all.

Barring that change, on older versions before SQL Server 2016, create a split function:

CREATE FUNCTION dbo.SplitStrings
(
    @List      nvarchar(max), 
    @Delimiter nvarchar(2)
)
RETURNS TABLE
WITH SCHEMABINDING
AS
  RETURN ( WITH x(x) AS
    (
      SELECT CONVERT(xml, N'<root><i>' 
        + REPLACE(@List, @Delimiter, N'</i><i>') 
        + N'</i></root>')
    )
    SELECT Item = LTRIM(RTRIM(i.i.value(N'.',N'nvarchar(max)')))
      FROM x CROSS APPLY x.nodes(N'//root/i') AS i(i)
  );
GO

Now you can say:

DECLARE @Values varchar(1000);

SET @Values = 'A, B, C';

SELECT blah
  FROM dbo.foo
  INNER JOIN dbo.SplitStrings(@Values, ',') AS s
    ON s.Item = foo.myField;

On SQL Server 2016 or above (or Azure SQL Database), it is much simpler and more efficient, however you do have to manually apply LTRIM() to take away any leading spaces:

DECLARE @Values varchar(1000) = 'A, B, C';

SELECT blah
  FROM dbo.foo
  INNER JOIN STRING_SPLIT(@Values, ',') AS s
    ON LTRIM(s.value) = foo.myField;

Alternate table with new not null Column in existing table in SQL

There are two ways to add the NOT NULL Columns to the table :

  1. ALTER the table by adding the column with NULL constraint. Fill the column with some data. Ex: column can be updated with ''

  2. ALTER the table by adding the column with NOT NULL constraint by giving DEFAULT values. ALTER table TableName ADD NewColumn DataType NOT NULL DEFAULT ''

Edit a commit message in SourceTree Windows (already pushed to remote)

If the comment message includes non-English characters, using method provided by user456814, those characters will be replaced by question marks. (tested under sourcetree Ver2.5.5.0)

So I have to use the following method.

CAUTION: if the commit has been pulled by other members, changes below might cause chaos for them.

Step1: In the sourcetree main window, locate your repo tab, and click the "terminal" button to open the git command console.

Step2:

[Situation A]: target commit is the latest one.

1) In the git command console, input

git commit --amend -m "new comment message"

2) If the target commit has been pushed to remote, you have to push again by force. In the git command console, input

git push --force

[Situation B]: target commit is not the latest one.

1) In the git command console, input

git rebase -i HEAD~n

It is to squash the latest n commits. e.g. if you want to edit the message before the last one, n is 2. This command will open a vi window, the first word of each line is "pick", and you change the "pick" to "reword" for the line you want to edit. Then, input :wq to save&quit that vi window. Now, a new vi window will be open, in this window you input your new message. Also use :wq to save&quit.

2) If the target commit has been pushed to remote, you have to push again by force. In the git command console, input

git push --force


Finally: In the sourcetree main window, Press F5 to refresh.

List of all special characters that need to be escaped in a regex

  • Java characters that have to be escaped in regular expressions are:
    \.[]{}()<>*+-=!?^$|
  • Two of the closing brackets (] and }) are only need to be escaped after opening the same type of bracket.
  • In []-brackets some characters (like + and -) do sometimes work without escape.

how can get index & count in vuejs

Alternatively, you can just use,

<li v-for="catalog, key in catalogs">this is index {{++key}}</li>

This is working just fine.

Setting Django up to use MySQL

MySQL support is simple to add. In your DATABASES dictionary, you will have an entry like this:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', 
        'NAME': 'DB_NAME',
        'USER': 'DB_USER',
        'PASSWORD': 'DB_PASSWORD',
        'HOST': 'localhost',   # Or an IP Address that your DB is hosted on
        'PORT': '3306',
    }
}

You also have the option of utilizing MySQL option files, as of Django 1.7. You can accomplish this by setting your DATABASES array like so:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'OPTIONS': {
            'read_default_file': '/path/to/my.cnf',
        },
    }
}

You also need to create the /path/to/my.cnf file with similar settings from above

[client]
database = DB_NAME
host = localhost
user = DB_USER
password = DB_PASSWORD
default-character-set = utf8

With this new method of connecting in Django 1.7, it is important to know the order connections are established:

1. OPTIONS.
2. NAME, USER, PASSWORD, HOST, PORT
3. MySQL option files.

In other words, if you set the name of the database in OPTIONS, this will take precedence over NAME, which would override anything in a MySQL option file.


If you are just testing your application on your local machine, you can use

python manage.py runserver

Adding the ip:port argument allows machines other than your own to access your development application. Once you are ready to deploy your application, I recommend taking a look at the chapter on Deploying Django on the djangobook

Mysql default character set is often not utf-8, therefore make sure to create your database using this sql:

CREATE DATABASE mydatabase CHARACTER SET utf8 COLLATE utf8_bin

If you are using Oracle's MySQL connector your ENGINE line should look like this:

'ENGINE': 'mysql.connector.django',

Note that you will first need to install mysql on your OS.

brew install mysql (MacOS)

Also, the mysql client package has changed for python 3 (MySQL-Client works only for python 2)

pip3 install mysqlclient

Codeigniter LIKE with wildcard(%)

$this->db->like()

This method enables you to generate LIKE clauses, useful for doing searches.

$this->db->like('title', 'match');

Produces: WHERE title LIKE '%match%'

If you want to control where the wildcard (%) is placed, you can use an optional third argument. Your options are ‘before’, ‘after’, ‘none’ and ‘both’ (which is the default).

$this->db->like('title', 'match', 'before');

Produces: WHERE title LIKE '%match'

$this->db->like('title', 'match', 'after');

Produces: WHERE title LIKE 'match%'

$this->db->like('title', 'match', 'none');

Produces: WHERE title LIKE 'match'

$this->db->like('title', 'match', 'both');

Produces: WHERE title LIKE '%match%'

stop service in android

To stop the service we must use the method stopService():

  Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
  //startService(myService);
  stopService(myService);

then the method onDestroy() in the service is called:

  @Override
    public void onDestroy() {

        Log.i(TAG, "onCreate() , service stopped...");
    }

Here is a complete example including how to stop the service.

How to truncate string using SQL server

If you only want to return a few characters of your long string, you can use:

select 
  left(col, 15) + '...' col
from yourtable

See SQL Fiddle with Demo.

This will return the first 15 characters of the string and then concatenates the ... to the end of it.

If you want to to make sure than strings less than 15 do not get the ... then you can use:

select 
  case 
    when len(col)>=15
    then left(col, 15) + '...' 
    else col end col
from yourtable

See SQL Fiddle with Demo

Java - Using Accessor and Mutator methods

You need to remove the static from your accessor methods - these methods need to be instance methods and access the instance variables

public class IDCard {
    public String name, fileName;
    public int id;

    public IDCard(final String name, final String fileName, final int id) {
        this.name = name;
        this.fileName = fileName
        this.id = id;
    }

    public String getName() {
        return name;
    }
}

You can the create an IDCard and use the accessor like this:

final IDCard card = new IDCard();
card.getName();

Each time you call new a new instance of the IDCard will be created and it will have it's own copies of the 3 variables.

If you use the static keyword then those variables are common across every instance of IDCard.

A couple of things to bear in mind:

  1. don't add useless comments - they add code clutter and nothing else.
  2. conform to naming conventions, use lower case of variable names - name not Name.

How can I add a hint text to WPF textbox?

I used the got and lost focus events:

Private Sub txtSearchBox_GotFocus(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles txtSearchBox.GotFocus
    If txtSearchBox.Text = "Search" Then
        txtSearchBox.Text = ""
    Else

    End If

End Sub

Private Sub txtSearchBox_LostFocus(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles txtSearchBox.LostFocus
    If txtSearchBox.Text = "" Then
        txtSearchBox.Text = "Search"
    Else

    End If
End Sub

It works well, but the text is in gray still. Needs cleaning up. I was using VB.NET

Open Cygwin at a specific folder

Probably the simplest one:

1) Create file foo.reg

2) Insert content:

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\Directory\background\shell\open_mintty]
@="open mintty"

[HKEY_CLASSES_ROOT\Directory\background\shell\open_mintty\command]
@="cmd /C mintty"

3) Execute foo.reg

Now just right-click in any folder, click open mintty and it will spawn mintty in that folder.

Remove empty lines in a text file via grep

grep . FILE


(And if you really want to do it in sed, then: sed -e /^$/d FILE)

(And if you really want to do it in awk, then: awk /./ FILE)

Push an associative item into an array in JavaScript

To make something like associative array in JavaScript you have to use objects. ?

_x000D_
_x000D_
var obj = {}; // {} will create an object
var name = "name";
var val = 2;
obj[name] = val;
console.log(obj);
_x000D_
_x000D_
_x000D_

DEMO: http://jsfiddle.net/bz8pK/1/

Error:java: invalid source release: 8 in Intellij. What does it mean?

I checked all above said project version, module version, project bytecode version, target bytecode version settings in IntelliJ Idea, but all were the same as I scratched.

I face this error Error:java: invalid source release: 1.8 in IntelliJ Idea 2017.2.6 because I upgraded the dependency version Maven pom file, which(dependency) were supposed to build for JDK 1.8 application and I were building my application on and with maven compiler source and target JDK 1.7.

Hence I again downgrade the dependency version to earlier one in Maven pom, and the error gone after project Rebuild Module 'xyz_project'.

batch to copy files with xcopy

Based on xcopy help, I tried and found that following works perfectly for me (tried on Win 7)

xcopy C:\folder1 C:\folder2\folder1 /E /C /I /Q /G /H /R /K /Y /Z /J

Make Font Awesome icons in a circle?

_x000D_
_x000D_
i.fa {_x000D_
  display: inline-block;_x000D_
  border-radius: 60px;_x000D_
  box-shadow: 0px 0px 2px #888;_x000D_
  padding: 0.5em 0.6em;_x000D_
_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />_x000D_
<i class="fa fa-wrench"></i>
_x000D_
_x000D_
_x000D_


JsFiddle of old answer: http://fiddle.jshell.net/4LqeN/

I want to exception handle 'list index out of range.'

You have two options; either handle the exception or test the length:

if len(dlist) > 1:
    newlist.append(dlist[1])
    continue

or

try:
    newlist.append(dlist[1])
except IndexError:
    pass
continue

Use the first if there often is no second item, the second if there sometimes is no second item.

How do I remove the space between inline/inline-block elements?

I’ve been tackling this recently and instead of setting the parent font-size:0 then setting the child back to a reasonable value, I’ve been getting consistent results by setting the parent container letter-spacing:-.25em then the child back to letter-spacing:normal.

In an alternate thread I saw a commenter mention that font-size:0 isn’t always ideal because people can control minimum font sizes in their browsers, completely negating the possibility of setting the font-size to zero.

Using ems appears to work regardless of whether the font-size specified is 100%, 15pt or 36px.

http://cdpn.io/dKIjo

Calling a stored procedure in Oracle with IN and OUT parameters

If you set the server output in ON mode before the entire code, it works, otherwise put_line() will not work. Try it!

The code is,

set serveroutput on;
CREATE OR REPLACE PROCEDURE PROC1(invoicenr IN NUMBER, amnt OUT NUMBER)
AS BEGIN
SELECT AMOUNT INTO amnt FROM INVOICE WHERE INVOICE_NR = invoicenr;
END;

And then call the function as it is:

DECLARE
amount NUMBER;
BEGIN
PROC1(1000001, amount);
dbms_output.put_line(amount);
END;

Change the Blank Cells to "NA"

I'm assuming you are talking about row 5 column "sex." It could be the case that in the data2.csv file, the cell contains a space and hence is not considered empty by R.

Also, I noticed that in row 5 columns "axles" and "door", the original values read from data2.csv are string "NA". You probably want to treat those as na.strings as well. To do this,

dat2 <- read.csv("data2.csv", header=T, na.strings=c("","NA"))

EDIT:

I downloaded your data2.csv. Yes, there is a space in row 5 column "sex". So you want

na.strings=c(""," ","NA")

Rename multiple files in a folder, add a prefix (Windows)

Free Software 'Bulk Rename Utility' also works well (and is powerful for advanced tasks also). Download and installation takes a minute.

See screenshots and tutorial on original website.

--

I cannot provide step-by-step screenshots as the images will have to be released under Creative Commons License, and I do not own the screenshots of the software.

Disclaimer: I am not associated with the said software/company in any way. I liked the product for my own task, it serves OP's and similar requirements, thus recommending.

How do I tell Matplotlib to create a second (new) plot, then later plot on the old one?

When you call figure, simply number the plot.

x = arange(5)
y = np.exp(5)
plt.figure(0)
plt.plot(x, y)

z = np.sin(x)
plt.figure(1)
plt.plot(x, z)

w = np.cos(x)
plt.figure(0) # Here's the part I need
plt.plot(x, w)

Edit: Note that you can number the plots however you want (here, starting from 0) but if you don't provide figure with a number at all when you create a new one, the automatic numbering will start at 1 ("Matlab Style" according to the docs).

What is the difference between YAML and JSON?

From: Arnaud Lauret Book “The Design of Web APIs.” :

The JSON data format

JSON is a text data format based on how the JavaScript programming language describes data but is, despite its name, completely language-independent (see https://www.json.org/). Using JSON, you can describe objects containing unordered name/value pairs and also arrays or lists containing ordered values, as shown in this figure.

enter image description here

An object is delimited by curly braces ({}). A name is a quoted string ("name") and is sep- arated from its value by a colon (:). A value can be a string like "value", a number like 1.23, a Boolean (true or false), the null value null, an object, or an array. An array is delimited by brackets ([]), and its values are separated by commas (,). The JSON format is easily parsed using any programming language. It is also relatively easy to read and write. It is widely adopted for many uses such as databases, configura- tion files, and, of course, APIs.

YAML

YAML (YAML Ain’t Markup Language) is a human-friendly, data serialization format. Like JSON, YAML (http://yaml.org) is a key/value data format. The figure shows a comparison of the two.

enter image description here

Note the following points:

  • There are no double quotes (" ") around property names and values in YAML.

  • JSON’s structural curly braces ({}) and commas (,) are replaced by newlines and indentation in YAML.

  • Array brackets ([]) and commas (,) are replaced by dashes (-) and newlines in YAML.

  • Unlike JSON, YAML allows comments beginning with a hash mark (#). It is relatively easy to convert one of those formats into the other. Be forewarned though, you will lose comments when converting a YAML document to JSON.

How to filter keys of an object with lodash?

Here is an example using lodash 4.x:

_x000D_
_x000D_
const data = {_x000D_
  aaa: 111,_x000D_
  abb: 222,_x000D_
  bbb: 333_x000D_
};_x000D_
_x000D_
const result = _.pickBy(data, (value, key) => key.startsWith("a"));_x000D_
_x000D_
console.log(result);_x000D_
// Object { aaa: 111, abb: 222 }
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>_x000D_
<strong>Open your javascript console to see the output.</strong>
_x000D_
_x000D_
_x000D_

C# JSON Serialization of Dictionary into {key:value, ...} instead of {key:key, value:value, ...}

I'm using out of the box MVC4 with this code (note the two parameters inside ToDictionary)

 var result = new JsonResult()
 {
     Data = new
     {
         partials = GetPartials(data.Partials).ToDictionary(x => x.Key, y=> y.Value)
     }
 };

I get what's expected:

{"partials":{"cartSummary":"\u003cb\u003eCART SUMMARY\u003c/b\u003e"}}

Important: WebAPI in MVC4 uses JSON.NET serialization out of the box, but the standard web JsonResult action result doesn't. Therefore I recommend using a custom ActionResult to force JSON.NET serialization. You can also get nice formatting

Here's a simple actionresult JsonNetResult

http://james.newtonking.com/archive/2008/10/16/asp-net-mvc-and-json-net.aspx

You'll see the difference (and can make sure you're using the right one) when serializing a date:

Microsoft way:

 {"wireTime":"\/Date(1355627201572)\/"}

JSON.NET way:

 {"wireTime":"2012-12-15T19:07:03.5247384-08:00"}

How do I check which version of NumPy I'm using?

You can try this:

pip show numpy

How can I resolve the error "The security token included in the request is invalid" when running aws iam upload-server-certificate?

This is weird, but in my case whenever I wanted to retype the access id and the key by typing aws configure.

Adding the id access end up always with a mess in the access id entry in the file located ~/.aws/credentials(see the picture) The messed access id

I have removed this mess and left only the access id. And the error resolved.

Reference to a non-shared member requires an object reference occurs when calling public sub

Go to the Declaration of the desired object and mark it Shared.

Friend Shared WithEvents MyGridCustomer As Janus.Windows.GridEX.GridEX

What data type to use in MySQL to store images?

This can be done from the command line. This will create a column for your image with a NOT NULL property.

CREATE TABLE `test`.`pic` (
`idpic` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
`caption` VARCHAR(45) NOT NULL,
`img` LONGBLOB NOT NULL,
PRIMARY KEY(`idpic`)
)
TYPE = InnoDB; 

From here

Change the color of cells in one column when they don't match cells in another column

you could try this:

I have these two columns (column "A" and column "B"). I want to color them when the values between cells in the same row mismatch.

Follow these steps:

  1. Select the elements in column "A" (excluding A1);

  2. Click on "Conditional formatting -> New Rule -> Use a formula to determine which cells to format";

  3. Insert the following formula: =IF(A2<>B2;1;0);

  4. Select the format options and click "OK";

  5. Select the elements in column "B" (excluding B1) and repeat the steps from 2 to 4.

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

You could use the library lxml (Note top level link is now spam) , which is a superset of ElementTree. Its tostring() method includes a parameter pretty_print - for example:

>>> print(etree.tostring(root, pretty_print=True))
<root>
  <child1/>
  <child2/>
  <child3/>
</root>

select2 - hiding the search box

This is the best solution, clean and work good :

$("#select2Id").select2 () ;
$("#select2Id").select2 ('container').find ('.select2-search').addClass ('hidden') ;

Then, create a class .hidden { display;none; }

Why use a ReentrantLock if one can use synchronized(this)?

Lets assume this code is running in a thread:

private static ReentrantLock lock = new ReentrantLock();

void accessResource() {
    lock.lock();
    if( checkSomeCondition() ) {
        accessResource();
    }
    lock.unlock();
}

Because the thread owns the lock it will allow multiple calls to lock(), so it re-enter the lock. This can be achieved with a reference count so it doesn't has to acquire lock again.

Variable is accessed within inner class. Needs to be declared final

Here's a funny answer.

You can declare a final one-element array and change the elements of the array all you want apparently. I'm sure it breaks the very reason why this compiler rule was implemented in the first place but it's handy when you're in a time-bind as I was today.

I actually can't claim credit for this one. It was IntelliJ's recommendation! Feels a bit hacky. But doesn't seem as bad as a global variable so I thought it worth mentioning here. It's just one solution to the problem. Not necessarily the best one.

final int[] tapCount = {0};

addSiteButton.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
       tapCount[0]++;
    }

});

Best way to Format a Double value to 2 Decimal places

An alternative is to use String.format:

double[] arr = { 23.59004,
    35.7,
    3.0,
    9
};

for ( double dub : arr ) {
  System.out.println( String.format( "%.2f", dub ) );
}

output:

23.59
35.70
3.00
9.00

You could also use System.out.format (same method signature), or create a java.util.Formatter which works in the same way.

The permissions granted to user ' are insufficient for performing this operation. (rsAccessDenied)"}

The report might want to access a DataSource or DataView where the AD user (or AD group) has insuficcient access rights.

Make sure you check out the following URLs:

  • http://REPORTSERVERNAME/Reports/Pages/Folder.aspx?ItemPath=%2fDataSources
  • http://REPORTSERVERNAME/Reports/Pages/Folder.aspx?ItemPath=%2fDataSets

Then choose Folder Settings

Folder Settings

(or the appropriate individual DataSource or DataSet) and select Security. The user group needs to have the Browser permission.

enter image description here

Maximum Length of Command Line String

From the Microsoft documentation: Command prompt (Cmd. exe) command-line string limitation

On computers running Microsoft Windows XP or later, the maximum length of the string that you can use at the command prompt is 8191 characters.

How to find EOF through fscanf?

fscanf - "On success, the function returns the number of items successfully read. This count can match the expected number of readings or be less -even zero- in the case of a matching failure. In the case of an input failure before any data could be successfully read, EOF is returned."

So, instead of doing nothing with the return value like you are right now, you can check to see if it is == EOF.

You should check for EOF when you call fscanf, not check the array slot for EOF.

How do I get the APK of an installed app without root access?

I found a way to get the APK's package name in a non-root device. it's not so elegant, but works all the time.

Step 1: on your device, open the target APK

Step 2: on PC cmd window, type this commands:

 adb shell dumpsys activity a > dump.txt

because the output of this command is numerous, redirect to a file is recommended.

Step 3: open this dump.txt file with any editor.

for device befor Android 4.4:
the beginning of the file would be looked like this:

ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)  
  Main stack:  
  * TaskRecord{41aa9ed0 #4 A com.tencent.mm U 0}  
    numActivities=1 rootWasReset=true userId=0  
    affinity=com.tencent.mm  
    intent={act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10600000 cmp=com.tencent.mm/.ui.LauncherUI}  
    realActivity=com.tencent.mm/.ui.LauncherUI  
    askedCompatMode=false  
    lastThumbnail=null lastDescription=null  
    lastActiveTime=19915965 (inactive for 10s)  
    * Hist #9: ActivityRecord{41ba1a30 u0 com.tencent.mm/.ui.LauncherUI}  
        packageName=com.tencent.mm processName=com.tencent.mm 

the package name is in the 3rd line, com.tencent.mm for this example.

for Android 4.4 and later:
the dumpsys output has changed a little. try search "Stack #1", the package name would be very close below it.

Also, search "baseDir", you will find the full path of the apk file!

JDBC connection failed, error: TCP/IP connection to host failed

The error is self explanatory:

  • Check if your SQL server is actually up and running
  • Check SQL server hostname, username and password is correct
  • Check there's no firewall rule blocking TCP connection to port 1433
  • Check the host is actually reachable

A good check I often use is to use telnet, eg on a windows command prompt run:

telnet 127.0.0.1 1433

If you get a blank screen it indicates network connection established successfully, and it's not a network problem. If you get 'Could not open connection to the host' then this is network problem

Remove spacing between table cells and rows

Hi as @andrew mentioned make cellpadding = 0, you still might have some space as you are using table border=1.

Error: ANDROID_HOME is not set and "android" command not in your PATH. You must fulfill at least one of these conditions.

It's is mostly with missing andriod SDK. for this issue and "JAVA_HOME" error following solution worked for me... hole day saved after following steps.

To build and run apps, you need to install SDKs for each platform you wish to target. Alternatively, if you are using browser for development you can use browser platform which does not require any platform SDKs.

To check if you satisfy requirements for building the platform:

$ cordova requirements
Requirements check results for android:
Java JDK: installed .
Android SDK: installed
Android target: installed android-19,android-21,android-22,android-23,Google Inc.:Google APIs:19,Google Inc.:Google APIs (x86 System Image):19,Google Inc.:Google APIs:23
Gradle: installed

Requirements check results for ios:
Apple OS X: not installed
Cordova tooling for iOS requires Apple OS X
Error: Some of requirements check failed

JUnit Testing Exceptions

An adventage of use ExpectedException Rule (version 4.7) is that you can test exception message and not only the expected exception.

And using Matchers, you can test the part of message you are interested:

exception.expectMessage(containsString("income: -1000.0"));

Java Try Catch Finally blocks without Catch

The Java Language Specification(1) describes how try-catch-finally is executed. Having no catch is equivalent to not having a catch able to catch the given Throwable.

  • If execution of the try block completes abruptly because of a throw of a value V, then there is a choice:
    • If the run-time type of V is assignable to the parameter of any catch clause of the try statement, then …
    • If the run-time type of V is not assignable to the parameter of any catch clause of the try statement, then the finally block is executed. Then there is a choice:
      • If the finally block completes normally, then the try statement completes abruptly because of a throw of the value V.
      • If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and the throw of value V is discarded and forgotten).

(1) Execution of try-catch-finally

Combine [NgStyle] With Condition (if..else)

I have used the below code in my existing project

<div class="form-group" [ngStyle]="{'border':isSubmitted && form_data.controls.first_name.errors?'1px solid red':'' }">
</div>

Looping over elements in jQuery

jQuery has an excellent function for looping through a set of elements: .each()

$('#formId').children().each(
    function(){
        //access to form element via $(this)
    }
);

How do I write dispatch_after GCD in Swift 3, 4, and 5?

You can use

DispatchQueue.main.asyncAfter(deadline: .now() + .microseconds(100)) {
        // Code
    }

Better way to check if a Path is a File or a Directory?

As an alternative to Directory.Exists(), you can use the File.GetAttributes() method to get the attributes of a file or a directory, so you could create a helper method like this:

private static bool IsDirectory(string path)
{
    System.IO.FileAttributes fa = System.IO.File.GetAttributes(path);
    return (fa & FileAttributes.Directory) != 0;
}

You could also consider adding an object to the tag property of the TreeView control when populating the control that contains additional metadata for the item. For instance, you could add a FileInfo object for files and a DirectoryInfo object for directories and then test for the item type in the tag property to save making additional system calls to get that data when clicking on the item.

How to use hex color values

This is a function that takes a hex string and returns a UIColor.
(You can enter hex strings with either format: #ffffff or ffffff)

Usage:

var color1 = hexStringToUIColor("#d3d3d3")

Swift 5: (Swift 4+)

func hexStringToUIColor (hex:String) -> UIColor {
    var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()

    if (cString.hasPrefix("#")) {
        cString.remove(at: cString.startIndex)
    }

    if ((cString.count) != 6) {
        return UIColor.gray
    }

    var rgbValue:UInt64 = 0
    Scanner(string: cString).scanHexInt64(&rgbValue)

    return UIColor(
        red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
        green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
        blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
        alpha: CGFloat(1.0)
    )
}

Swift 3:

func hexStringToUIColor (hex:String) -> UIColor {
    var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()

    if (cString.hasPrefix("#")) {
        cString.remove(at: cString.startIndex)
    }

    if ((cString.characters.count) != 6) {
        return UIColor.gray
    }

    var rgbValue:UInt32 = 0
    Scanner(string: cString).scanHexInt32(&rgbValue)

    return UIColor(
        red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
        green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
        blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
        alpha: CGFloat(1.0)
    )
}

Swift 2:

func hexStringToUIColor (hex:String) -> UIColor {
    var cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet() as NSCharacterSet).uppercaseString

    if (cString.hasPrefix("#")) {
      cString = cString.substringFromIndex(cString.startIndex.advancedBy(1))
    }

    if ((cString.characters.count) != 6) {
      return UIColor.grayColor()
    }

    var rgbValue:UInt32 = 0
    NSScanner(string: cString).scanHexInt(&rgbValue)

    return UIColor(
        red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
        green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
        blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
        alpha: CGFloat(1.0)
    )
}



Source: arshad/gist:de147c42d7b3063ef7bc

Edit: Updated the code. Thanks, Hlung, jaytrixz, Ahmad F, Kegham K, and Adam Waite!

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

I tried all solution here but none is working, then I realise I made a mistake, I put the .aar in wrong folder, as you can see below, I thought I should put in root folder, so I created a libs folder there (1 in picture), but inside the app folder, there is already a libs, you should put in second libs, hope this help those who has same issue as mine:

enter image description here

JPA eager fetch does not join

Two things occur to me.

First, are you sure you mean ManyToOne for address? That means multiple people will have the same address. If it's edited for one of them, it'll be edited for all of them. Is that your intent? 99% of the time addresses are "private" (in the sense that they belong to only one person).

Secondly, do you have any other eager relationships on the Person entity? If I recall correctly, Hibernate can only handle one eager relationship on an entity but that is possibly outdated information.

I say that because your understanding of how this should work is essentially correct from where I'm sitting.

Check if AJAX response data is empty/blank/null/undefined/0

if(data.trim()==''){alert("Nothing Found");}

How can I take a screenshot/image of a website using Python?

I can't comment on ars's answer, but I actually got Roland Tapken's code running using QtWebkit and it works quite well.

Just wanted to confirm that what Roland posts on his blog works great on Ubuntu. Our production version ended up not using any of what he wrote but we are using the PyQt/QtWebKit bindings with much success.

Note: The URL used to be: http://www.blogs.uni-osnabrueck.de/rotapken/2008/12/03/create-screenshots-of-a-web-page-using-python-and-qtwebkit/ I've updated it with a working copy.

Python: How to get values of an array at certain index positions?

The one liner "no imports" version

a = [0,88,26,3,48,85,65,16,97,83,91]
ind_pos = [1,5,7]
[ a[i] for i in ind_pos ]

Convert hex string to int

Try with this:

long abc=convertString2Hex("1A2A3B");

private  long  convertString2Hex(String numberHexString)
{
    char[] ChaArray = numberHexString.toCharArray();
    long HexSum=0;
    long cChar =0;

    for(int i=0;i<numberHexString.length();i++ )
    {
        if( (ChaArray[i]>='0') && (ChaArray[i]<='9') )
            cChar = ChaArray[i] - '0';
        else
            cChar = ChaArray[i]-'A'+10;
        HexSum = 16 * HexSum + cChar;
    }
    return  HexSum;
}

What is the best IDE for PHP?

I'm always amazed that more people don't use ActiveState Komodo.

It has the best debugging facilities of any PHP IDE I have tried, is a very mature product and has more useful features than you can shake a stick at. Of note, it has a fantastic HTTP inspector, Javascript debugger and Regular Expression Toolkit. You can get it so that it steps through your PHP, then you see your Javascript running, and then see your HTTP traffic going out over the wire!

It also comes in free (Komodo Edit) and open (OpenKomodo versions).

Oh, and if you don't always hack just on PHP, it's designed as a multi-language editor and rocks for Ruby and Python too.

I've been a happy customer for around 5 years.

Comparing arrays in C#

For .NET 4.0 and higher, you can compare elements in array or tuples using the StructuralComparisons type:

object[] a1 = { "string", 123, true };
object[] a2 = { "string", 123, true };
        
Console.WriteLine (a1 == a2);        // False (because arrays is reference types)
Console.WriteLine (a1.Equals (a2));  // False (because arrays is reference types)
        
IStructuralEquatable se1 = a1;
//Next returns True
Console.WriteLine (se1.Equals (a2, StructuralComparisons.StructuralEqualityComparer)); 

How to read file using NPOI

If you don't want to use NPOI.Mapper, then I'd advise you to check out this solution - it handles reading excel cell into various type and also has a simple import helper: https://github.com/hidegh/NPOI.Extensions

var data = sheet.MapTo<OrderDetails>(true, rowMapper =>
{
  // map singleItem
  return new OrderDetails()
  {
    Date = rowMapper.GetValue<DateTime>(SheetColumnTitles.Date),

    // use reusable mapper for re-curring scenarios
    Region = regionMapper(rowMapper.GetValue<string>(SheetColumnTitles.Region)),

    Representative = rowMapper.GetValue<string>(SheetColumnTitles.Representative),
    Item = rowMapper.GetValue<string>(SheetColumnTitles.Item),
    Units = rowMapper.GetValue<int>(SheetColumnTitles.Units),
    UnitCost = rowMapper.GetValue<decimal>(SheetColumnTitles.UnitCost),
    Total = rowMapper.GetValue<decimal>(SheetColumnTitles.Total),

    // read date and total as string, as they're displayed/formatted on the excel
    DateFormatted = rowMapper.GetValue<string>(SheetColumnTitles.Date),
    TotalFormatted = rowMapper.GetValue<string>(SheetColumnTitles.Total)
  };
});

How to pass data using NotificationCenter in swift 3.0 and NSNotificationCenter in swift 2.0?

this is how I implement it .

let dictionary = self.convertStringToDictionary(responceString)            
     NotificationCenter.default.post(name: NSNotification.Name(rawValue: "SOCKET_UPDATE"), object: dictionary)

Get google map link with latitude/longitude

None of the above answers worked for me, but I got it working with the following:

src="'https://maps.google.com/maps?q=' + lat + ',' + long + '&t=&z=15&ie=UTF8&iwloc=&output=embed'"

How do I POST JSON data with cURL?

For Windows, having a single quote for the -d value did not work for me, but it did work after changing to double quote. Also I needed to escape double quotes inside curly brackets.

That is, the following did not work:

curl -i -X POST -H "Content-Type: application/json" -d '{"key":"val"}' http://localhost:8080/appname/path

But the following worked:

curl -i -X POST -H "Content-Type: application/json" -d "{\"key\":\"val\"}" http://localhost:8080/appname/path

Uncaught TypeError: .indexOf is not a function

Basically indexOf() is a method belongs to string(array object also), But while calling the function you are passing a number, try to cast it to a string and pass it.

document.getElementById("oset").innerHTML = timeD2C(timeofday + "");

_x000D_
_x000D_
 var timeofday = new Date().getHours() + (new Date().getMinutes()) / 60;_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
 function timeD2C(time) { // Converts 11.5 (decimal) to 11:30 (colon)_x000D_
    var pos = time.indexOf('.');_x000D_
    var hrs = time.substr(1, pos - 1);_x000D_
    var min = (time.substr(pos, 2)) * 60;_x000D_
_x000D_
    if (hrs > 11) {_x000D_
        hrs = (hrs - 12) + ":" + min + " PM";_x000D_
    } else {_x000D_
        hrs += ":" + min + " AM";_x000D_
    }_x000D_
    return hrs;_x000D_
}_x000D_
alert(timeD2C(timeofday+""));
_x000D_
_x000D_
_x000D_


And it is good to do the string conversion inside your function definition,

function timeD2C(time) { 
  time = time + "";
  var pos = time.indexOf('.');

So that the code flow won't break at times when devs forget to pass a string into this function.

How can I temporarily disable a foreign key constraint in MySQL?

I normally only disable foreign key constraints when I want to truncate a table, and since I keep coming back to this answer this is for future me:

SET FOREIGN_KEY_CHECKS=0;
TRUNCATE TABLE table;
SET FOREIGN_KEY_CHECKS=1;

Getting the .Text value from a TextBox

Use this instead:

string objTextBox = t.Text;

The object t is the TextBox. The object you call objTextBox is assigned the ID property of the TextBox.

So better code would be:

TextBox objTextBox = (TextBox)sender;
string theText = objTextBox.Text;

How to scroll to top of page with JavaScript/jQuery?

First add a blank anchor tag to the place where you want to go

<a href="#topAnchor"></a> 

Now add a function in header section

 function GoToTop() {
            var urllocation = location.href;
            if (urllocation.indexOf("#topAnchor") > -1) {
                window.location.hash = "topAnchor";
            } else {
                return false;
            }
        }

finally add an onload event to the body tag

<body onload="GoToTop()">

Using union and order by clause in mysql

When you use an ORDER BY clause inside of a sub query used in conjunction with a UNION mysql will optimise away the ORDER BY clause.

This is because by default a UNION returns an unordered list so therefore an ORDER BY would do nothing.

The optimisation is mentioned in the docs and says:

To apply ORDER BY or LIMIT to an individual SELECT, place the clause inside the parentheses that enclose the SELECT:

(SELECT a FROM t1 WHERE a=10 AND B=1 ORDER BY a LIMIT 10) UNION
(SELECT a FROM t2 WHERE a=11 AND B=2 ORDER BY a LIMIT 10);

However, use of ORDER BY for individual SELECT statements implies nothing about the order in which the rows appear in the final result because UNION by default produces an unordered set of rows. Therefore, the use of ORDER BY in this context is typically in conjunction with LIMIT, so that it is used to determine the subset of the selected rows to retrieve for the SELECT, even though it does not necessarily affect the order of those rows in the final UNION result. If ORDER BY appears without LIMIT in a SELECT, it is optimized away because it will have no effect anyway.

The last sentence of this is a bit misleading because it should have an effect. This optimisation causes a problem when you are in a situation where you need to order within the subquery.

To force MySQL to not do this optimisation you can add a LIMIT clause like so:

(SELECT 1 AS rank, id, add_date FROM my_table WHERE distance < 5 ORDER BY add_date LIMIT 9999999999)
UNION ALL
(SELECT 2 AS rank, id, add_date FROM my_table WHERE distance BETWEEN 5 AND 15 ORDER BY rank LIMIT 9999999999)
UNION ALL
(SELECT 3 AS rank, id, add_date from my_table WHERE distance BETWEEN 5 and 15 ORDER BY id LIMIT 9999999999)

A high LIMIT means that you could add an OFFSET on the overall query if you want to do something such as pagination.

This also gives you the added benefit of being able to ORDER BY different columns for each union.

Recursive mkdir() system call on Unix

The two other answers given are for mkdir(1) and not mkdir(2) like you ask for, but you can look at the source code for that program and see how it implements the -p options which calls mkdir(2) repeatedly as needed.

How to get 'System.Web.Http, Version=5.2.3.0?

Uninstalling and re-installing the NuGet package worked for me.

  1. Remove any old reference from the project.

Execute this in the Package Manager Console:

  1. UnInstall-Package Microsoft.AspNet.WebApi.Core -version 5.2.3
  2. Install-Package Microsoft.AspNet.WebApi.Core -version 5.2.3

javascript function wait until another function to finish

Following answer can help in this and other similar situations like synchronous AJAX call -

Working example

waitForMe().then(function(intentsArr){
  console.log('Finally, I can execute!!!');
},
function(err){
  console.log('This is error message.');
})

function waitForMe(){
    // Returns promise
    console.log('Inside waitForMe');
    return new Promise(function(resolve, reject){
        if(true){ // Try changing to 'false'
            setTimeout(function(){
                console.log('waitForMe\'s function succeeded');
                resolve();
            }, 2500);
        }
        else{
            setTimeout(function(){
                console.log('waitForMe\'s else block failed');
                resolve();
            }, 2500);
        }
    });
}

Laravel Escaping All HTML in Blade Template

I had the same issue. Thanks for the answers above, I solved my issue. If there are people facing the same problem, here is two way to solve it:

  • You can use {!! $news->body !!}
  • You can use traditional php openning (It is not recommended) like: <?php echo $string ?>

I hope it helps.

How can I add the new "Floating Action Button" between two widgets/layouts

Now it is part of official Design Support Library.

In your gradle:

compile 'com.android.support:design:22.2.0'

http://developer.android.com/reference/android/support/design/widget/FloatingActionButton.html

How to convert integer to decimal in SQL Server query?

SELECT height/10.0 AS HeightDecimal FROM dbo.whatever;

If you want a specific precision scale, then say so:

SELECT CONVERT(DECIMAL(16,4), height/10.0) AS HeightDecimal
  FROM dbo.whatever;

Why do abstract classes in Java have constructors?

Implementation wise you will often see inside super() statement in subclasses constructors, something like:


public class A extends AbstractB{

  public A(...){
     super(String constructorArgForB, ...);
     ...
  }
}


Combine a list of data frames into one data frame by row

For the purpose of completeness, I thought the answers to this question required an update. "My guess is that using do.call("rbind", ...) is going to be the fastest approach that you will find..." It was probably true for May 2010 and some time after, but in about Sep 2011 a new function rbindlist was introduced in the data.table package version 1.8.2, with a remark that "This does the same as do.call("rbind",l), but much faster". How much faster?

library(rbenchmark)
benchmark(
  do.call = do.call("rbind", listOfDataFrames),
  plyr_rbind.fill = plyr::rbind.fill(listOfDataFrames), 
  plyr_ldply = plyr::ldply(listOfDataFrames, data.frame),
  data.table_rbindlist = as.data.frame(data.table::rbindlist(listOfDataFrames)),
  replications = 100, order = "relative", 
  columns=c('test','replications', 'elapsed','relative')
  ) 

                  test replications elapsed relative
4 data.table_rbindlist          100    0.11    1.000
1              do.call          100    9.39   85.364
2      plyr_rbind.fill          100   12.08  109.818
3           plyr_ldply          100   15.14  137.636

Delete newline in Vim

I would just press A (append to end of line, puts you into insert mode) on the line where you want to remove the newline and then press delete.

Using Python Requests: Sessions, Cookies, and POST

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

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

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

s.cookies

Any further actions like another requests will have this cookie

Find everything between two XML tags with RegEx

this can capture most outermost layer pair of tags, even with attribute in side or without end tags

(<!--((?!-->).)*-->|<\w*((?!\/<).)*\/>|<(?<tag>\w+)[^>]*>(?>[^<]|(?R))*<\/\k<tag>\s*>)

edit: as mentioned in comment above, regex is always not enough to parse xml, trying to modify the regex to fit more situation only makes it longer but still useless

Checking character length in ruby

Ruby provides a built-in function for checking the length of a string. Say it's called s:

if s.length <= 25
  # We're OK
else
  # Too long
end

[Vue warn]: Property or method is not defined on the instance but referenced during render

I had two methods: in the <script>, goes to show, that you can spend hours looking for something that was such a simple mistake.

Removing empty rows of a data file in R

This is similar to some of the above answers, but with this, you can specify if you want to remove rows with a percentage of missing values greater-than or equal-to a given percent (with the argument pct)

drop_rows_all_na <- function(x, pct=1) x[!rowSums(is.na(x)) >= ncol(x)*pct,]

Where x is a dataframe and pct is the threshold of NA-filled data you want to get rid of.

pct = 1 means remove rows that have 100% of its values NA. pct = .5 means remome rows that have at least half its values NA

Keylistener in Javascript

Here's an update for modern browsers in 2019

_x000D_
_x000D_
let playerSpriteX = 0;_x000D_
_x000D_
document.addEventListener('keyup', (e) => {_x000D_
  if (e.code === "ArrowUp")        playerSpriteX += 10_x000D_
  else if (e.code === "ArrowDown") playerSpriteX -= 10_x000D_
_x000D_
  document.getElementById('test').innerHTML = 'playerSpriteX = ' + playerSpriteX;_x000D_
});
_x000D_
Click on this window to focus it, and hit keys up and down_x000D_
<br><br><br>_x000D_
<div id="test">playerSpriteX = 0</div>
_x000D_
_x000D_
_x000D_


Original answer from 2013

window.onkeyup = function(e) {
   var key = e.keyCode ? e.keyCode : e.which;

   if (key == 38) {
       playerSpriteX += 10;
   }else if (key == 40) {
       playerSpriteX -= 10;
   }
}

FIDDLE

How to display HTML in TextView?

If you want to be able to configure it through xml without any modification in java code you may find this idea helpful. Simply you call init from constructor and set the text as html

public class HTMLTextView extends TextView {
    ... constructors calling init...
    private void init(){
       setText(Html.fromHtml(getText().toString()));
    }    
}

xml:

<com.package.HTMLTextView
android:text="@string/about_item_1"/>

Calculating Pearson correlation and significance in Python

I have a very simple and easy to understand solution for this. For two arrays of equal length, Pearson coefficient can be easily computed as follows:

def manual_pearson(a,b):
"""
Accepts two arrays of equal length, and computes correlation coefficient. 
Numerator is the sum of product of (a - a_avg) and (b - b_avg), 
while denominator is the product of a_std and b_std multiplied by 
length of array. 
"""
  a_avg, b_avg = np.average(a), np.average(b)
  a_stdev, b_stdev = np.std(a), np.std(b)
  n = len(a)
  denominator = a_stdev * b_stdev * n
  numerator = np.sum(np.multiply(a-a_avg, b-b_avg))
  p_coef = numerator/denominator
  return p_coef

How to make a HTTP PUT request?

using(var client = new System.Net.WebClient()) {
    client.UploadData(address,"PUT",data);
}

What is the syntax to insert one list into another list in python?

If we just do x.append(y), y gets referenced into x such that any changes made to y will affect appended x as well. So if we need to insert only elements, we should do following:

x = [1,2,3] y = [4,5,6] x.append(y[:])

Setting value of active workbook in Excel VBA

This is all you need

Set wbOOR = ActiveWorkbook

Can I serve multiple clients using just Flask app.run() as standalone?

Tips from 2020:

From Flask 1.0, it defaults to enable multiple threads (source), you don't need to do anything, just upgrade it with:

$ pip install -U flask

If you are using flask run instead of app.run() with older versions, you can control the threaded behavior with a command option (--with-threads/--without-threads):

$ flask run --with-threads

It's same as app.run(threaded=True)

Can I change the fill color of an svg path with CSS?

If you go into the source code of an SVG file you can change the color fill by modifying the fill property.

<svg fill="#3F6078" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
</svg> 

Use your favorite text editor, open the SVG file and play around with it.

How to get week number of the month from the date in sql server 2008

Code is below:

set datefirst 7
declare @dt datetime='29/04/2016 00:00:00'
select (day(@dt)+datepart(WEEKDAY,dateadd(d,-day(@dt),@dt+1)))/7

Is it possible to style a mouseover on an image map using CSS?

Here's one that is pure css that uses the + next sibling selector, :hover, and pointer-events. It doesn't use an imagemap, technically, but the rect concept totally carries over:

_x000D_
_x000D_
.hotspot {_x000D_
    position: absolute;_x000D_
    border: 1px solid blue;_x000D_
}_x000D_
.hotspot + * {_x000D_
    pointer-events: none;_x000D_
    opacity: 0;_x000D_
}_x000D_
.hotspot:hover + * {_x000D_
    opacity: 1.0;_x000D_
}_x000D_
.wash {_x000D_
    position: absolute;_x000D_
    top: 0;_x000D_
    left: 0;_x000D_
    bottom: 0;_x000D_
    right: 0;_x000D_
    background-color: rgba(255, 255, 255, 0.6);_x000D_
}
_x000D_
<div style="position: relative; height: 188px; width: 300px;">_x000D_
    <img src="http://demo.cloudimg.io/s/width/300/sample.li/boat.jpg">_x000D_
        _x000D_
    <div class="hotspot" style="top: 50px; left: 50px; height: 30px; width: 30px;"></div>_x000D_
    <div>_x000D_
        <div class="wash"></div>_x000D_
        <div style="position: absolute; top: 0; left: 0;">A</div>_x000D_
    </div>_x000D_
        _x000D_
    <div class="hotspot" style="top: 100px; left: 120px; height: 30px; width: 30px;"></div>_x000D_
    <div>_x000D_
        <div class="wash"></div>_x000D_
        <div style="position: absolute; top: 0; left: 0;">B</div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to access Anaconda command prompt in Windows 10 (64-bit)

After installing Anaconda3 on your system you need to add Anaconda to the PATH environment variable. This will allow you to access Anaconda with the 'conda' command from cmd.exe or PowerShell.

The link I provided below go through the three major issues with not recognized error. Which are:

  1. Environment PATH for Conda is not set
  2. Environment PATH is incorrectly added
  3. Anaconda version is older than the version of the Anaconda Navigator

LINK: https://appuals.com/fix-conda-is-not-recognized-as-an-internal-or-external-command-operable-program-or-batch-file/

My issue was resolved following the steps for issue #2 Environment PATH is incorrectly added. I did not have all three file paths in my variable environment.

Check which element has been clicked with jQuery

Answer from vpiTriumph lays out the details nicely.
Here's a small handy variation for when there are unique element ids for the data set you want to access:

$('.news-article').click(function(event){    
    var id = event.target.id;
    console.log('id = ' + id); 
});

How to create multiple page app using react

This is a broad question and there are multiple ways you can achieve this. In my experience, I've seen a lot of single page applications having an entry point file such as index.js. This file would be responsible for 'bootstrapping' the application and will be your entry point for webpack.

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import Application from './components/Application';

const root = document.getElementById('someElementIdHere');

ReactDOM.render(
  <Application />,
  root,
);

Your <Application /> component would contain the next pieces of your app. You've stated you want different pages and that leads me to believe you're using some sort of routing. That could be included into this component along with any libraries that need to be invoked on application start. react-router, redux, redux-saga, react-devtools come to mind. This way, you'll only need to add a single entry point into your webpack configuration and everything will trickle down in a sense.

When you've setup a router, you'll have options to set a component to a specific matched route. If you had a URL of /about, you should create the route in whatever routing package you're using and create a component of About.js with whatever information you need.

Vertical Alignment of text in a table cell

CSS {vertical-align: top;} or html Attribute {valign="top"}

_x000D_
_x000D_
.table td, 
.table th {
    border: 1px solid #161b21;
    text-align: left;
    padding: 8px;
    width: 250px;
    height: 100px;
    
    /* style for table */
}

.table-body-text {
  vertical-align: top;
}
_x000D_
<table class="table">
    <tr>
      <th valign="top">Title 1</th>
      <th valign="top">Title 2</th>
    </tr>
    <tr>
      <td class="table-body-text">text</td>
      <td class="table-body-text">text</td>
    </tr>
   </table>
_x000D_
_x000D_
_x000D_

For table vertical-align we have 2 options.

  1. is to use css {vertical-align: top;}
  1. another way is to user attribute "valign" and the property should be "top" {valign="top"}

Accept server's self-signed ssl certificate in Java client

I had the issue that I was passing a URL into a library which was calling url.openConnection(); I adapted jon-daniel's answer,

public class TrustHostUrlStreamHandler extends URLStreamHandler {

    private static final Logger LOG = LoggerFactory.getLogger(TrustHostUrlStreamHandler.class);

    @Override
    protected URLConnection openConnection(final URL url) throws IOException {

        final URLConnection urlConnection = new URL(url.getProtocol(), url.getHost(), url.getPort(), url.getFile()).openConnection();

        // adapated from
        // https://stackoverflow.com/questions/2893819/accept-servers-self-signed-ssl-certificate-in-java-client
        if (urlConnection instanceof HttpsURLConnection) {
            final HttpsURLConnection conHttps = (HttpsURLConnection) urlConnection;

            try {
                // Set up a Trust all manager
                final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

                    @Override
                    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }

                    @Override
                    public void checkClientTrusted(final java.security.cert.X509Certificate[] certs, final String authType) {
                    }

                    @Override
                    public void checkServerTrusted(final java.security.cert.X509Certificate[] certs, final String authType) {
                    }
                } };

                // Get a new SSL context
                final SSLContext sc = SSLContext.getInstance("TLSv1.2");
                sc.init(null, trustAllCerts, new java.security.SecureRandom());
                // Set our connection to use this SSL context, with the "Trust all" manager in place.
                conHttps.setSSLSocketFactory(sc.getSocketFactory());
                // Also force it to trust all hosts
                final HostnameVerifier allHostsValid = new HostnameVerifier() {
                    @Override
                    public boolean verify(final String hostname, final SSLSession session) {
                        return true;
                    }
                };

                // and set the hostname verifier.
                conHttps.setHostnameVerifier(allHostsValid);

            } catch (final NoSuchAlgorithmException e) {
                LOG.warn("Failed to override URLConnection.", e);
            } catch (final KeyManagementException e) {
                LOG.warn("Failed to override URLConnection.", e);
            }

        } else {
            LOG.warn("Failed to override URLConnection. Incorrect type: {}", urlConnection.getClass().getName());
        }

        return urlConnection;
    }

}

Using this class it is possible to create a new URL with:

trustedUrl = new URL(new URL(originalUrl), "", new TrustHostUrlStreamHandler());
trustedUrl.openConnection();

This has the advantage that it is localized and not replacing the default URL.openConnection.

How to Count Duplicates in List with LINQ

Slightly shorter version using methods chain:

var list = new List<string> {"a", "b", "a", "c", "a", "b"};
var q = list.GroupBy(x => x)
            .Select(g => new {Value = g.Key, Count = g.Count()})
            .OrderByDescending(x=>x.Count);

foreach (var x in q)
{
    Console.WriteLine("Value: " + x.Value + " Count: " + x.Count);
}

Byte Array and Int conversion in Java

Instead of allocating space, et al, an approach using ByteBuffer from java.nio....

byte[] arr = { 0x01, 0x00, 0x00, 0x00, 0x48, 0x01};

// say we want to consider indices 1, 2, 3, 4 {0x00, 0x00, 0x00, 0x48};
ByteBuffer bf = ByteBuffer.wrap(arr, 1, 4); // big endian by default
int num = bf.getInt();    // 72

Now, to go the other way.

ByteBuffer newBuf = ByteBuffer.allocate(4);
newBuf.putInt(num);
byte[] bytes = newBuf.array();  // [0, 0, 0, 72] {0x48 = 72}

CSS3 selector :first-of-type with class name?

As a fallback solution, you could wrap your classes in a parent element like this:

<div>
    <div>This text should appear as normal</div>
    <p>This text should be blue.</p>
    <div>
        <!-- first-child / first-of-type starts from here -->
        <p class="myclass1">This text should appear red.</p>
        <p class="myclass2">This text should appear green.</p>
    </div>
</div>

Best way to do multiple constructors in PHP

I created this method to let use it not only on constructors but in methods:

My constructor:

function __construct() {
    $paramsNumber=func_num_args();
    if($paramsNumber==0){
        //do something
    }else{
        $this->overload('__construct',func_get_args());
    }
}

My doSomething method:

public function doSomething() {
    $paramsNumber=func_num_args();
    if($paramsNumber==0){
        //do something
    }else{
        $this->overload('doSomething',func_get_args());
    }
}

Both works with this simple method:

public function overloadMethod($methodName,$params){
    $paramsNumber=sizeof($params);
    //methodName1(), methodName2()...
    $methodNameNumber =$methodName.$paramsNumber;
    if (method_exists($this,$methodNameNumber)) {
        call_user_func_array(array($this,$methodNameNumber),$params);
    }
}

So you can declare

__construct1($arg1), __construct2($arg1,$arg2)...

or

methodName1($arg1), methodName2($arg1,$arg2)...

and so on :)

And when using:

$myObject =  new MyClass($arg1, $arg2,..., $argN);

it will call __constructN, where you defined N args

then $myObject -> doSomething($arg1, $arg2,..., $argM)

it will call doSomethingM, , where you defined M args;

Check if bash variable equals 0

you can also use this format and use comparison operators like '==' '<='

  if (( $total == 0 )); then
      echo "No results for ${1}"
      return
  fi

Triangle Draw Method

Use a line algorithm to connect point A with point C, and in an outer loop, let point A wander towards point B with the same line algorithm and with the wandering coordinates, repeat drawing that line. You can probably also include a z delta with which is also incremented iteratively. For the line algorithm, just calculate two or three slopes for the delta change of each coordinate and set one slope to 1 after changing the two others proportionally so they are below 1. This is very important for drawing closed geometrical areas between connected mesh particles. Take a look at the Qt Elastic Nodes example and now imagine drawing triangles between the nodes after stretching this over a skeleton. As long as it will remain online

How to download Google Play Services in an Android emulator?

I got it working by

  • Installing the Google Play Services through the Android SDK Manager
  • Using a Galaxy Nexus Device (4.65", 720 x 1280: xhdpi)
  • Targeting the Android 4.2.2 Google API Level 17

Object comparison in JavaScript

I have modified a bit the code above. for me 0 !== false and null !== undefined. If you do not need such strict check remove one "=" sign in "this[p] !== x[p]" inside the code.

Object.prototype.equals = function(x){
    for (var p in this) {
        if(typeof(this[p]) !== typeof(x[p])) return false;
        if((this[p]===null) !== (x[p]===null)) return false;
        switch (typeof(this[p])) {
            case 'undefined':
                if (typeof(x[p]) != 'undefined') return false;
                break;
            case 'object':
                if(this[p]!==null && x[p]!==null && (this[p].constructor.toString() !== x[p].constructor.toString() || !this[p].equals(x[p]))) return false;
                break;
            case 'function':
                if (p != 'equals' && this[p].toString() != x[p].toString()) return false;
                break;
            default:
                if (this[p] !== x[p]) return false;
        }
    }
    return true;
}

Then I have tested it with next objects:

var a = {a: 'text', b:[0,1]};
var b = {a: 'text', b:[0,1]};
var c = {a: 'text', b: 0};
var d = {a: 'text', b: false};
var e = {a: 'text', b:[1,0]};
var f = {a: 'text', b:[1,0], f: function(){ this.f = this.b; }};
var g = {a: 'text', b:[1,0], f: function(){ this.f = this.b; }};
var h = {a: 'text', b:[1,0], f: function(){ this.a = this.b; }};
var i = {
    a: 'text',
    c: {
        b: [1, 0],
        f: function(){
            this.a = this.b;
        }
    }
};
var j = {
    a: 'text',
    c: {
        b: [1, 0],
        f: function(){
            this.a = this.b;
        }
    }
};
var k = {a: 'text', b: null};
var l = {a: 'text', b: undefined};

a==b expected true; returned true

a==c expected false; returned false

c==d expected false; returned false

a==e expected false; returned false

f==g expected true; returned true

h==g expected false; returned false

i==j expected true; returned true

d==k expected false; returned false

k==l expected false; returned false

How to zero pad a sequence of integers in bash so that all have the same width?

One way without using external process forking is string manipulation, in a generic case it would look like this:

#start value
CNT=1

for [whatever iterative loop, seq, cat, find...];do
   # number of 0s is at least the amount of decimals needed, simple concatenation
   TEMP="000000$CNT"
   # for example 6 digits zero padded, get the last 6 character of the string
   echo ${TEMP:(-6)}
   # increment, if the for loop doesn't provide the number directly
   TEMP=$(( TEMP + 1 ))
done

This works quite well on WSL as well, where forking is a really heavy operation. I had a 110000 files list, using printf "%06d" $NUM took over 1 minute, the solution above ran in about 1 second.

SQL Statement using Where clause with multiple values

Try this:

select songName from t
where personName in ('Ryan', 'Holly')
group by songName
having count(distinct personName) = 2

The number in the having should match the amount of people. If you also need the Status to be Complete use this where clause instead of the previous one:

where personName in ('Ryan', 'Holly') and status = 'Complete'

Java String remove all non numeric characters

str = str.replaceAll("\\D+","");

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

I made a script expanding on Yup.'s script. I fixed some things. It will now bypass 403:Forbidden problems. It wont crash when an image fails to be retrieved. It tries to avoid corrupted previews. It gets the right absolute urls. It gives out more information. It can be run with an argument from the command line.

# getem.py
# python2 script to download all images in a given url
# use: python getem.py http://url.where.images.are

from bs4 import BeautifulSoup
import urllib2
import shutil
import requests
from urlparse import urljoin
import sys
import time

def make_soup(url):
    req = urllib2.Request(url, headers={'User-Agent' : "Magic Browser"}) 
    html = urllib2.urlopen(req)
    return BeautifulSoup(html, 'html.parser')

def get_images(url):
    soup = make_soup(url)
    images = [img for img in soup.findAll('img')]
    print (str(len(images)) + " images found.")
    print 'Downloading images to current working directory.'
    image_links = [each.get('src') for each in images]
    for each in image_links:
        try:
            filename = each.strip().split('/')[-1].strip()
            src = urljoin(url, each)
            print 'Getting: ' + filename
            response = requests.get(src, stream=True)
            # delay to avoid corrupted previews
            time.sleep(1)
            with open(filename, 'wb') as out_file:
                shutil.copyfileobj(response.raw, out_file)
        except:
            print '  An error occured. Continuing.'
    print 'Done.'

if __name__ == '__main__':
    url = sys.argv[1]
    get_images(url)

What linux shell command returns a part of a string?

expr(1) has a substr subcommand:

expr substr <string> <start-index> <length>

This may be useful if you don't have bash (perhaps embedded Linux) and you don't want the extra "echo" process you need to use cut(1).

memcpy() vs memmove()

C11 standard draft

The C11 N1570 standard draft says:

7.24.2.1 "The memcpy function":

2 The memcpy function copies n characters from the object pointed to by s2 into the object pointed to by s1. If copying takes place between objects that overlap, the behavior is undefined.

7.24.2.2 "The memmove function":

2 The memmove function copies n characters from the object pointed to by s2 into the object pointed to by s1. Copying takes place as if the n characters from the object pointed to by s2 are first copied into a temporary array of n characters that does not overlap the objects pointed to by s1 and s2, and then the n characters from the temporary array are copied into the object pointed to by s1

Therefore, any overlap on memcpy leads to undefined behavior, and anything can happen: bad, nothing or even good. Good is rare though :-)

memmove however clearly says that everything happens as if an intermediate buffer is used, so clearly overlaps are OK.

C++ std::copy is more forgiving however, and allows overlaps: Does std::copy handle overlapping ranges?

In Python, how do I convert all of the items in a list to floats?

for i in range(len(list)): list[i]=float(list[i])

C++ Get name of type in template

typeid(T).name() is implementation defined and doesn't guarantee human readable string.

Reading cppreference.com :

Returns an implementation defined null-terminated character string containing the name of the type. No guarantees are given, in particular, the returned string can be identical for several types and change between invocations of the same program.

...

With compilers such as gcc and clang, the returned string can be piped through c++filt -t to be converted to human-readable form.

But in some cases gcc doesn't return right string. For example on my machine I have gcc whith -std=c++11 and inside template function typeid(T).name() returns "j" for "unsigned int". It's so called mangled name. To get real type name, use abi::__cxa_demangle() function (gcc only):

#include <string>
#include <cstdlib>
#include <cxxabi.h>

template<typename T>
std::string type_name()
{
    int status;
    std::string tname = typeid(T).name();
    char *demangled_name = abi::__cxa_demangle(tname.c_str(), NULL, NULL, &status);
    if(status == 0) {
        tname = demangled_name;
        std::free(demangled_name);
    }   
    return tname;
}

How to find the kth largest element in an unsorted array of length n in O(n)?

kth largest element means, we need to sort the array and then, count down from the end of array. For example

 const array= [2, 32, 12, 3, 78, 99, 898, 8, 1] // we need to sort this
 const sortedArray= [1,  2,  3,   8, 12, 32, 78, 99, 898] 

5th largest element means from the end count down 5 elements which is 12.

By default most languages implement quick sort or merge sort because they are the most optimized sorts. I solve this problem with the quick sort. Quick sort sorts the array in place, it does not give us back a new array and like merge sort it is recursive. Downside of quick sort, in worst case scenario, its time complexity is O(n**2) "n square".

Quick sort is divide-and-conquer algorithm which is a problem is solved by solving all of its smaller components. We choose the last element as the pivot element (Some algorithms choose the first item as pivot, some choose the last item when it starts). Pivot element is the partitioning element. this is our array=[2, 32, 12, 3, 78, 99, 898, 8, 1]

we use 2 pointers, i,j starts from the first element. "i" keeps track of where is the final place of pivot.

i=j=2 //starting point

"j" is going to scan the array, and compare each element to the pivot. If "j" is smaller than pivot, we will swap "i" and "j" and move "i" and "j" forward. When "j" reaches pivot, we swap "i" with pivot. In our example pivot is 1, 1 is the smaller number, "j" will reach the pivot=1 without swapping "i","j". Remember "i" is the placeholder for the pivot. So when "j" reaches pivot, 1 and 2 will be swapped.

The purpose of this operation to find all of elements that smaller than pivot to its left. Note that all the elements that are on the left of pivot is smaller than pivot, but left side is not sorted. Then we divide the array from the pivot into 2 sub arrays and recursively apply the quick sort.

const quickSort = function (array, left, right) {
  // if left=right, it means we have only one item, it is already sorted
  if (left < right) {
    const partitionIndex = partition(array, left, right);
    quickSort(array, left, partitionIndex - 1); 
    quickSort(array, partitionIndex + 1, right);
  }
};

With using "i" and "j" pointers, this is how we find the partitioning index

const partition = function (array, left, right) {
  const pivotElement = array[right];
  let partitionIndex = left;
  for (let j = left; j < right; j++) {
    if (array[j] < pivotElement) {
      swap(array, partitionIndex, j);
      partitionIndex++;
    }
  }
  // if none of the "j" values is smaller than pivot, when "j" reaches the pivot, we swap "i'th" element with pivot
  swap(array, partitionIndex, right);
  return partitionIndex;
};

this is a simple implementation of swap function:

const swap = function (array, i, j) {
  const temp = array[i];
  array[i] = array[j];
  array[j] = temp;
};

Oracle query to identify columns having special characters

Compare the length using lengthB and length function in oracle.

SELECT * FROM test WHERE length(sampletext) <> lengthb(sampletext)

Status bar and navigation bar appear over my view's bounds in iOS 7

You don't have to calculate how far to shift everything down, there's a build in property for this. In Interface Builder, highlight your view controller, and then navigate to the attributes inspector. Here you'll see some check boxes next to the words "Extend Edges". As you can see, in the first screenshot, the default selection is for content to appear under top and bottom bars, but not under opaque bars, which is why setting the bar style to not translucent worked for you.

As you can somewhat see in the first screenshot, there are two UI elements hiding below the navigation bar. (I've enabled wireframes in IB to illustrate this) These elements, a UIButton and a UISegmentedControl both have their "y" origin set to zero, and the view controller is set to allow content below the top bar.

enter image description here

This second screenshot shows what happens when you deselect the "Under Top Bars" check box. As you can see, the view controllers view has been shifted down appropriately for its y origin to be right underneath the navigation bar.

enter image description here

This can also be accomplished programmatically through the usage of -[UIViewController edgesForExtendedLayout]. Here's a link to the class reference for edgeForExtendedLayout, and for UIRectEdge

[self setEdgesForExtendedLayout:UIRectEdgeNone];

How to make a div fill a remaining horizontal space?

_x000D_
_x000D_
.container {_x000D_
  width:100%;_x000D_
  display:table;_x000D_
  vertical-align:middle;_x000D_
}_x000D_
_x000D_
.left {_x000D_
  width:100%;_x000D_
  display:table-cell;_x000D_
  text-align:center;_x000D_
}_x000D_
_x000D_
.right {_x000D_
  width:40px;_x000D_
  height:40px;_x000D_
  display:table-cell;_x000D_
  float:right;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="left">Left</div>_x000D_
  <div class="right">Right</div>_x000D_
</div
_x000D_
_x000D_
_x000D_

Try this. It worked for me.

Play an audio file using jQuery when a button is clicked

$("#myAudioElement")[0].play();

It doesn't work with $("#myAudioElement").play() like you would expect. The official reason is that incorporating it into jQuery would add a play() method to every single element, which would cause unnecessary overhead. So instead you have to refer to it by its position in the array of DOM elements that you're retrieving with $("#myAudioElement"), aka 0.

This quote is from a bug that was submitted about it, which was closed as "feature/wontfix":

To do that we'd need to add a jQuery method name for each DOM element method name. And of course that method would do nothing for non-media elements so it doesn't seem like it would be worth the extra bytes it would take.

Insert 2 million rows into SQL Server quickly

Re the solution for SqlBulkCopy:

I used the StreamReader to convert and process the text file. The result was a list of my object.

I created a class than takes Datatable or a List<T> and a Buffer size (CommitBatchSize). It will convert the list to a data table using an extension (in the second class).

It works very fast. On my PC, I am able to insert more than 10 million complicated records in less than 10 seconds.

Here is the class:

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DAL
{

public class BulkUploadToSql<T>
{
    public IList<T> InternalStore { get; set; }
    public string TableName { get; set; }
    public int CommitBatchSize { get; set; }=1000;
    public string ConnectionString { get; set; }

    public void Commit()
    {
        if (InternalStore.Count>0)
        {
            DataTable dt;
            int numberOfPages = (InternalStore.Count / CommitBatchSize)  + (InternalStore.Count % CommitBatchSize == 0 ? 0 : 1);
            for (int pageIndex = 0; pageIndex < numberOfPages; pageIndex++)
                {
                    dt= InternalStore.Skip(pageIndex * CommitBatchSize).Take(CommitBatchSize).ToDataTable();
                BulkInsert(dt);
                }
        } 
    }

    public void BulkInsert(DataTable dt)
    {
        using (SqlConnection connection = new SqlConnection(ConnectionString))
        {
            // make sure to enable triggers
            // more on triggers in next post
            SqlBulkCopy bulkCopy =
                new SqlBulkCopy
                (
                connection,
                SqlBulkCopyOptions.TableLock |
                SqlBulkCopyOptions.FireTriggers |
                SqlBulkCopyOptions.UseInternalTransaction,
                null
                );

            // set the destination table name
            bulkCopy.DestinationTableName = TableName;
            connection.Open();

            // write the data in the "dataTable"
            bulkCopy.WriteToServer(dt);
            connection.Close();
        }
        // reset
        //this.dataTable.Clear();
    }

}

public static class BulkUploadToSqlHelper
{
    public static DataTable ToDataTable<T>(this IEnumerable<T> data)
    {
        PropertyDescriptorCollection properties =
            TypeDescriptor.GetProperties(typeof(T));
        DataTable table = new DataTable();
        foreach (PropertyDescriptor prop in properties)
            table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
        foreach (T item in data)
        {
            DataRow row = table.NewRow();
            foreach (PropertyDescriptor prop in properties)
                row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
            table.Rows.Add(row);
        }
        return table;
    }
}

}

Here is an example when I want to insert a List of my custom object List<PuckDetection> (ListDetections):

var objBulk = new BulkUploadToSql<PuckDetection>()
{
        InternalStore = ListDetections,
        TableName= "PuckDetections",
        CommitBatchSize=1000,
        ConnectionString="ENTER YOU CONNECTION STRING"
};
objBulk.Commit();

The BulkInsert class can be modified to add column mapping if required. Example you have an Identity key as first column.(this assuming that the column names in the datatable are the same as the database)

//ADD COLUMN MAPPING
foreach (DataColumn col in dt.Columns)
{
        bulkCopy.ColumnMappings.Add(col.ColumnName, col.ColumnName);
}

How to solve Permission denied (publickey) error when using Git?

Its pretty straight forward. Type the below command

ssh-keygen -t rsa -b 4096 -C "[email protected]"

Generate the SSH key. Open the file and copy the contents. Go to GitHub setting page , and click on SSH key . Click on Add new SSH key, and paste the contents here. That's it :) You shouldn't see the issue again.

How to define the basic HTTP authentication using cURL correctly?

curl -u username:password http://
curl -u username http://

From the documentation page:

-u, --user <user:password>

Specify the user name and password to use for server authentication. Overrides -n, --netrc and --netrc-optional.

If you simply specify the user name, curl will prompt for a password.

The user name and passwords are split up on the first colon, which makes it impossible to use a colon in the user name with this option. The password can, still.

When using Kerberos V5 with a Windows based server you should include the Windows domain name in the user name, in order for the server to succesfully obtain a Kerberos Ticket. If you don't then the initial authentication handshake may fail.

When using NTLM, the user name can be specified simply as the user name, without the domain, if there is a single domain and forest in your setup for example.

To specify the domain name use either Down-Level Logon Name or UPN (User Principal Name) formats. For example, EXAMPLE\user and [email protected] respectively.

If you use a Windows SSPI-enabled curl binary and perform Kerberos V5, Negotiate, NTLM or Digest authentication then you can tell curl to select the user name and password from your environment by specifying a single colon with this option: "-u :".

If this option is used several times, the last one will be used.

http://curl.haxx.se/docs/manpage.html#-u

Note that you do not need --basic flag as it is the default.

SSL: CERTIFICATE_VERIFY_FAILED with Python3

Go to the folder where Python is installed, e.g., in my case (Mac OS) it is installed in the Applications folder with the folder name 'Python 3.6'. Now double click on 'Install Certificates.command'. You will no longer face this error.

For those not running a mac, or having a different setup and can't find this file, the file merely runs:

pip install --upgrade certifi

Hope that helps someone :)

What's the best UI for entering date of birth?

I had tried datePicker with my user but it turn out to be a bad UI to them. What I end up base on their request is to have 3 textbox where they can quickly type [ day ] [ month ] [ year ] :(

PHP cURL error code 60

i fixed this by modifying php.ini file at C:\wamp\bin\apache\apache2.4.9\bin\

curl.cainfo = "C:/wamp/bin/php/php5.5.12/cacert.pem"

first i was trying by modifying php.ini file at C:\wamp\bin\php\php5.5.12\ and it didn't work.

hope this helps someone who is searching for the right php.ini to modify

The view didn't return an HttpResponse object. It returned None instead

if qs.count()==1:
        print('cart id exists')
        if ....

else:    
        return render(request,"carts/home.html",{})

Such type of code will also return you the same error this is because of the intents as the return statement should be for else not for if statement.

above code can be changed to

if qs.count()==1:
        print('cart id exists')
        if ....

else:   

return render(request,"carts/home.html",{})

This may solve such issues

How to set environment variables in Jenkins?

This is the snippet to store environment variable and access it.

node {
   withEnv(["ENABLE_TESTS=true", "DISABLE_SQL=false"]) {
      stage('Select Jenkinsfile') {
          echo "Enable test?: ${env.DEVOPS_SKIP_TESTS}
          customStep script: this
      }
   }
}

Note: The value of environment variable is coming as a String. If you want to use it as a boolean then you have to parse it using Boolean.parse(env.DISABLE_SQL).

PHP cURL HTTP CODE return 0

Like said here and below, a failed request (i.e. the server is not found) returns false, no HTTP status code, since a reply has never been received.

Call curl_error().

How to unpack and pack pkg file?

In addition to what @abarnert said, I today had to find out that the default cpio utility on Mountain Lion uses a different archive format per default (not sure which), even with the man page stating it would use the old cpio/odc format. So, if anyone stumbles upon the cpio read error: bad file format message while trying to install his/her manipulated packages, be sure to include the format in the re-pack step:

find ./Foo.app | cpio -o --format odc | gzip -c > Payload

Is a Python dictionary an example of a hash table?

Yes. Internally it is implemented as open hashing based on a primitive polynomial over Z/2 (source).

Can you split a stream into two streams?

Not exactly. You can't get two Streams out of one; this doesn't make sense -- how would you iterate over one without needing to generate the other at the same time? A stream can only be operated over once.

However, if you want to dump them into a list or something, you could do

stream.forEach((x) -> ((x == 0) ? heads : tails).add(x));

file path Windows format to java format

String path = "C:\\Documents and Settings\\Manoj\\Desktop";
path = path.replace("\\", "/");
// or
path = path.replaceAll("\\\\", "/");

Find more details in the Docs

String comparison technique used by Python

A pure Python equivalent for string comparisons would be:

def less(string1, string2):
    # Compare character by character
    for idx in range(min(len(string1), len(string2))):
        # Get the "value" of the character
        ordinal1, ordinal2 = ord(string1[idx]), ord(string2[idx])
        # If the "value" is identical check the next characters
        if ordinal1 == ordinal2:
            continue
        # It's not equal so we're finished at this index and can evaluate which is smaller.
        else:
            return ordinal1 < ordinal2
    # We're out of characters and all were equal, so the result depends on the length
    # of the strings.
    return len(string1) < len(string2)

This function does the equivalent of the real method (Python 3.6 and Python 2.7) just a lot slower. Also note that the implementation isn't exactly "pythonic" and only works for < comparisons. It's just to illustrate how it works. I haven't checked if it works like Pythons comparison for combined unicode characters.

A more general variant would be:

from operator import lt, gt

def compare(string1, string2, less=True):
    op = lt if less else gt
    for char1, char2 in zip(string1, string2):
        ordinal1, ordinal2 = ord(char1), ord(char1)
        if ordinal1 == ordinal2:
            continue
        else:
            return op(ordinal1, ordinal2)
    return op(len(string1), len(string2))

Are static class variables possible in Python?

You can use a list or a dictionary to get "static behavior" between instances.

class Fud:

     class_vars = {'origin_open':False}

     def __init__(self, origin = True):
         self.origin = origin
         self.opened = True
         if origin:
             self.class_vars['origin_open'] = True


     def make_another_fud(self):
         ''' Generating another Fud() from the origin instance '''

         return Fud(False)


     def close(self):
         self.opened = False
         if self.origin:
             self.class_vars['origin_open'] = False


fud1 = Fud()
fud2 = fud1.make_another_fud()

print (f"is this the original fud: {fud2.origin}")
print (f"is the original fud open: {fud2.class_vars['origin_open']}")
# is this the original fud: False
# is the original fud open: True

fud1.close()

print (f"is the original fud open: {fud2.class_vars['origin_open']}")
# is the original fud open: False

Android - SMS Broadcast receiver

Also note that the Hangouts application will currently block my BroadcastReceiver from receiving SMS messages. I had to disable SMS functionality in the Hangouts application (Settings->SMS->Turn on SMS), before my SMS BroadcastReceived started getting fired.

Edit: It appears as though some applications will abortBroadcast() on the intent which will prevent other applications from receiving the intent. The solution is to increase the android:priority attribute in the intent-filter tag:

<receiver android:name="com.company.application.SMSBroadcastReceiver" >
  <intent-filter android:priority="500">
    <action android:name="android.provider.Telephony.SMS_RECEIVED" />
  </intent-filter>
</receiver>

See more details here: Enabling SMS support in Hangouts 2.0 breaks the BroadcastReceiver of SMS_RECEIVED in my app

IE prompts to open or save json result from server

Sadly, this is just another annoying quirk of using Internet Explorer.

enter image description here

The simple solution is to run a small .reg file on your PC, to tell IE to automatically open .json files, rather than nag about whether to open/save it.

I've put a copy of the file you'll need here:

JSON mime type

You'll need to have Admin rights to run this.

How Can I Override Style Info from a CSS Class in the Body of a Page?

Eli, it is important to remember that in css specificity goes a long way. If your inline css is using the !important and isn't overriding the imported stylesheet rules then closely observe the code using a tool such as 'firebug' for firefox. It will show you the css being applied to your element. If there is a syntax error firebug will show you in the warning panel that it has thrown out the declaration.

Also remember that in general an id is more specific than a class is more specific than an element.

Hope that helps.

-Rick

Git clone without .git directory

You can always do

git clone git://repo.org/fossproject.git && rm -rf fossproject/.git

Delete from a table based on date

This is pretty vague. Do you mean like in SQL:

DELETE FROM myTable
WHERE dateColumn < '2007'

Problem in running .net framework 4.0 website on iis 7.0

  1. Go to the IIS Manager.
  2. open the server name like (PC-Name)\.
  3. then double click on the ISAPI and CGI Restriction.
  4. then select ASP.NET v4.0.30319(32-bit) Restriction allowed.

Removing double quotes from variables in batch file creates problems with CMD environment

I thought I had the solution, but I soon experienced unusual behavior with execution of batch files. Suddenly CMD is no recognizing long path statments. Normal execution of batch file from full path

C:\Documents and Settings\Administrator\My Documents\Txt\batchtest\dataout.bat

returns

'C:\Documents' is not recognized as an internal or external command....

There's your whole problem. CMD doesn't understand spaces inside of filenames from the command line, so it thinks you're trying to pass

and Settings\Administrator\My Documents\Txt\batchtest\dataout.bat

as parameters to the

"C:\Documents"

program.

You need to quote it to run a batch file with spaces in the path:

> "C:\Documents and Settings\Administrator\My Documents\Txt\batchtest\dataout.bat"

would have worked.

Insert text into textarea with jQuery

have you tried:

$("#yourAnchor").click(function () {
    $("#yourTextarea").val("your text");
});

not sure about autohighlighting, though.

EDIT:

To append:

$("#yourAnchor").click(function () {
    $("#yourTextarea").append("your text to append");
});

python capitalize first letter only

This is similar to @Anon's answer in that it keeps the rest of the string's case intact, without the need for the re module.

def sliceindex(x):
    i = 0
    for c in x:
        if c.isalpha():
            i = i + 1
            return i
        i = i + 1

def upperfirst(x):
    i = sliceindex(x)
    return x[:i].upper() + x[i:]

x = '0thisIsCamelCase'

y = upperfirst(x)

print(y)
# 0ThisIsCamelCase

As @Xan pointed out, the function could use more error checking (such as checking that x is a sequence - however I'm omitting edge cases to illustrate the technique)

Updated per @normanius comment (thanks!)

Thanks to @GeoStoneMarten in pointing out I didn't answer the question! -fixed that

How can I check file size in Python?

Strictly sticking to the question, the Python code (+ pseudo-code) would be:

import os
file_path = r"<path to your file>"
if os.stat(file_path).st_size > 0:
    <send an email to somebody>
else:
    <continue to other things>

The type 'string' must be a non-nullable type in order to use it as parameter T in the generic type or method 'System.Nullable<T>'

Please note that in upcoming version of C# which is 8, the answers are not true.

All the reference types are non-nullable by default and you can actually do the following:

public string? MyNullableString; 
this.MyNullableString = null; //Valid

However,

public string MyNonNullableString; 
this.MyNonNullableString = null; //Not Valid and you'll receive compiler warning. 

The important thing here is to show the intent of your code. If the "intent" is that the reference type can be null, then mark it so otherwise assigning null value to non-nullable would result in compiler warning.

More info

Equal height rows in a flex container

You can accomplish that now with display: grid:

_x000D_
_x000D_
.list {_x000D_
  display: grid;_x000D_
  overflow: hidden;_x000D_
  grid-template-columns: repeat(3, 1fr);_x000D_
  grid-auto-rows: 1fr;_x000D_
  grid-column-gap: 5px;_x000D_
  grid-row-gap: 5px;_x000D_
  max-width: 500px;_x000D_
}_x000D_
.list-item {_x000D_
  background-color: #ccc;_x000D_
  display: flex;_x000D_
  padding: 0.5em;_x000D_
  margin-bottom: 20px;_x000D_
}_x000D_
.list-content {_x000D_
  width: 100%;_x000D_
}
_x000D_
<ul class="list">_x000D_
  <li class="list-item">_x000D_
    <div class="list-content">_x000D_
      <h2>box 1</h2>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>_x000D_
    </div>_x000D_
  </li>_x000D_
  <li class="list-item">_x000D_
    <div class="list-content">_x000D_
      <h3>box 2</h3>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>_x000D_
    </div>_x000D_
  </li>_x000D_
_x000D_
  <li class="list-item">_x000D_
    <div class="list-content">_x000D_
      <h3>box 2</h3>_x000D_
      <p>Lorem ipsum dolor</p>_x000D_
    </div>_x000D_
  </li>_x000D_
_x000D_
  <li class="list-item">_x000D_
    <div class="list-content">_x000D_
      <h3>box 2</h3>_x000D_
      <p>Lorem ipsum dolor</p>_x000D_
    </div>_x000D_
  </li>_x000D_
  <li class="list-item">_x000D_
    <div class="list-content">_x000D_
      <h1>h1</h1>_x000D_
    </div>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Although the grid itself is not flexbox, it behaves very similar to a flexbox container, and the items inside the grid can be flex.

The grid layout is also very handy in the case you want responsive grids. That is, if you want the grid to have a different number of columns per row you can then just change grid-template-columns:

grid-template-columns: repeat(1, 1fr); // 1 column
grid-template-columns: repeat(2, 1fr); // 2 columns
grid-template-columns: repeat(3, 1fr); // 3 columns

and so on...

You can mix it with media queries and change according to the size of the page.

Sadly there is still no support for container queries / element queries in the browsers (out of the box) to make it work well with changing the number of columns according to the container size, not to the page size (this would be great to use with reusable webcomponents).

More information about the grid layout:

https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout

Support of the Grid Layout accross browsers:

https://caniuse.com/#feat=css-grid

Generate table relationship diagram from existing schema (SQL Server)

SchemaCrawler for SQL Server can generate database diagrams, with the help of GraphViz. Foreign key relationships are displayed (and can even be inferred, using naming conventions), and tables and columns can be excluded using regular expressions.

Session 'app': Error Installing APK

It was written above: in my case it was just out of memory on device storage. Add more empty space - and error will disappear

What Are Some Good .NET Profilers?

The NuMega True Time profiler lives on in DevPartner Studio by Micro Focus. It provides line and method level detail for .NET apps requiring only PDBs, no source needed (but it helps.) It can discriminate between algorithmically heavy routines versus those with long I/O waits using our proprietary per thread kernel mode timing driver. Version 10.5 ships with new 64-process support on February 4, 2011. Shameless plug: I work on the DevPartner product line. Follow up at http://www.DevPartner.com for news of the 10.5 launch.

Disclaimer: I am the Product Manager for DevPartner at Micro Focus.

How do I implement Cross Domain URL Access from an Iframe using Javascript?

You can try and check for the referer, which should be the parent site if you're an iframe

you can do that like this:

var href = document.referrer;

Non-alphanumeric list order from os.listdir()

Python for whatever reason does not come with a built-in way to have natural sorting (meaning 1, 2, 10 instead of 1, 10, 2), so you have to write it yourself:

import re
def sorted_alphanumeric(data):
    convert = lambda text: int(text) if text.isdigit() else text.lower()
    alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ] 
    return sorted(data, key=alphanum_key)

You can now use this function to sort a list:

dirlist = sorted_alphanumeric(os.listdir(...))

PROBLEMS: In case you use the above function to sort strings (for example folder names) and want them sorted like Windows Explorer does, it will not work properly in some edge cases.
This sorting function will return incorrect results on Windows, if you have folder names with certain 'special' characters in them. For example this function will sort 1, !1, !a, a, whereas Windows Explorer would sort !1, 1, !a, a.

So if you want to sort exactly like Windows Explorer does in Python you have to use the Windows built-in function StrCmpLogicalW via ctypes (this of course won't work on Unix):

from ctypes import wintypes, windll
from functools import cmp_to_key

def winsort(data):
    _StrCmpLogicalW = windll.Shlwapi.StrCmpLogicalW
    _StrCmpLogicalW.argtypes = [wintypes.LPWSTR, wintypes.LPWSTR]
    _StrCmpLogicalW.restype  = wintypes.INT

    cmp_fnc = lambda psz1, psz2: _StrCmpLogicalW(psz1, psz2)
    return sorted(data, key=cmp_to_key(cmp_fnc))

This function is slightly slower than sorted_alphanumeric().

Bonus: winsort can also sort full paths on Windows.

Alternatively, especially if you use Unix, you can use the natsort library (pip install natsort) to sort by full paths in a correct way (meaning subfolders at the correct position).

You can use it like this to sort full paths:

from natsort import natsorted, ns
dirlist = natsorted(dirlist, alg=ns.PATH | ns.IGNORECASE)

Starting with version 7.1.0 natsort supports os_sorted which internally uses either the beforementioned Windows API or Linux sorting and should be used instead of natsorted().