Programs & Examples On #Telerik reporting

Telerik Reporting is a .Net reporting solution for building rich and interactive reports. It provides a Visual Studio-based report designer and report viewing clients that work across all .Net platforms (ASP.Net, Silverlight, WPF, WinForms, and Azure).

Best way to style a TextBox in CSS

You can use:

input[type=text]
{
 /*Styles*/
}

Define your common style attributes inside this. and for extra style you can add a class then.

Check which element has been clicked with jQuery

The basis of jQuery is the ability to find items in the DOM through selectors, and then checking properties on those selectors. Read up on Selectors here:

http://api.jquery.com/category/selectors/

However, it would make more sense to create event handlers for the click events for the different functionality that should occur based on what is clicked.

Convert Linq Query Result to Dictionary

Looking at your example, I think this is what you want:

var dict = TableObj.ToDictionary(t => t.Key, t=> t.TimeStamp);

check if a number already exist in a list in python

If you want to have unique elements in your list, then why not use a set, if of course, order does not matter for you: -

>>> s = set()
>>> s.add(2)
>>> s.add(4)
>>> s.add(5)
>>> s.add(2)
>>> s
39: set([2, 4, 5])

If order is a matter of concern, then you can use: -

>>> def addUnique(l, num):
...     if num not in l:
...         l.append(num)
...     
...     return l

You can also find an OrderedSet recipe, which is referred to in Python Documentation

Custom fonts and XML layouts (Android)

Peter's answer is the best, but it can be improved by using the styles.xml from Android to customize your fonts for all textviews in your app.

My code is here

Html attributes for EditorFor() in ASP.NET MVC

Html.TextBoxFor(model => model.Control.PeriodType, 
    new { @class="text-box single-line"})

you can use like this ; same output with Html.EditorFor ,and you can add your html attributes

MySQL: Grant **all** privileges on database

This will be helpful for some people:

From MySQL command line:

CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password';

Sadly, at this point newuser has no permissions to do anything with the databases. In fact, if newuser even tries to login (with the password, password), they will not be able to reach the MySQL shell.

Therefore, the first thing to do is to provide the user with access to the information they will need.

GRANT ALL PRIVILEGES ON * . * TO 'newuser'@'localhost';

The asterisks in this command refer to the database and table (respectively) that they can access—this specific command allows to the user to read, edit, execute and perform all tasks across all the databases and tables.

Once you have finalized the permissions that you want to set up for your new users, always be sure to reload all the privileges.

FLUSH PRIVILEGES;

Your changes will now be in effect.

For more information: http://dev.mysql.com/doc/refman/5.6/en/grant.html

If you are not comfortable with the command line then you can use a client like MySQL workbench, Navicat or SQLyog

How to URL encode in Python 3?

For Python 3 you could try using quote instead of quote_plus:

import urllib.parse

print(urllib.parse.quote("http://www.sample.com/"))

Result:

http%3A%2F%2Fwww.sample.com%2F

Or:

from requests.utils import requote_uri
requote_uri("http://www.sample.com/?id=123 abc")

Result:

'https://www.sample.com/?id=123%20abc'

Regex to Match Symbols: !$%^&*()_+|~-=`{}[]:";'<>?,./

Replace all latters from any language in 'A', and if you wish for example all digits to 0:

return str.replace(/[^\s!-@[-`{-~]/g, "A").replace(/\d/g, "0");

Shorter syntax for casting from a List<X> to a List<Y>?

dynamic data = List<x> val;  
List<y> val2 = ((IEnumerable)data).Cast<y>().ToList();

How do I use jQuery to redirect?

I found out why this happening.

After looking at my settings on my wamp, i did not check http headers, since activated this, it now works.

Thank you everyone for trying to solve this. :)

Angular expression if array contains

You shouldn't overload the templates with complex logic, it's a bad practice. Remember to always keep it simple!

The better approach would be to extract this logic into reusable function on your $rootScope:

.run(function ($rootScope) {
  $rootScope.inArray = function (item, array) {
    return (-1 !== array.indexOf(item));
  };
})

Then, use it in your template:

<li ng-class="{approved: inArray(jobSet, selectedForApproval)}"></li>

I think everyone will agree that this example is much more readable and maintainable.

How to remove all characters after a specific character in python?

Assuming your separator is '...', but it can be any string.

text = 'some string... this part will be removed.'
head, sep, tail = text.partition('...')

>>> print head
some string

If the separator is not found, head will contain all of the original string.

The partition function was added in Python 2.5.

partition(...) S.partition(sep) -> (head, sep, tail)

Searches for the separator sep in S, and returns the part before it,
the separator itself, and the part after it.  If the separator is not
found, returns S and two empty strings.

DataGridView - Focus a specific cell

you can set Focus to a specific Cell by setting Selected property to true

dataGridView1.Rows[rowindex].Cells[columnindex].Selected = true;

to avoid Multiple Selection just set

dataGridView1.MultiSelect = false;

Understanding SQL Server LOCKS on SELECT queries

At my work, we have a very big system that runs on many PCs at the same time, with very big tables with hundreds of thousands of rows, and sometimes many millions of rows.

When you make a SELECT on a very big table, let's say you want to know every transaction a user has made in the past 10 years, and the primary key of the table is not built in an efficient way, the query might take several minutes to run.

Then, our application might me running on many user's PCs at the same time, accessing the same database. So if someone tries to insert into the table that the other SELECT is reading (in pages that SQL is trying to read), then a LOCK can occur and the two transactions block each other.

We had to add a "NO LOCK" to our SELECT statement, because it was a huge SELECT on a table that is used a lot by a lot of users at the same time and we had LOCKS all the time.

I don't know if my example is clear enough? This is a real life example.

JAVA - using FOR, WHILE and DO WHILE loops to sum 1 through 100

- First to me Iterating and Looping are 2 different things.

Eg: Increment a variable till 5 is Looping.

    int count = 0;

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

        count = count + 1;

   }

Eg: Iterate over the Array to print out its values, is about Iteration

    int[] arr = {5,10,15,20,25};

    for (int i=0 ; i<arr.length ; i++){

        System.out.println(arr[i]);

   }

Now about all the Loops:

- Its always better to use For-Loop when you know the exact nos of time you gonna Loop, and if you are not sure of it go for While-Loop. Yes out there many geniuses can say that it can be done gracefully with both of them and i don't deny with them...but these are few things which makes me execute my program flawlessly...

For Loop :

int sum = 0; 

for (int i = 1; i <= 100; i++) {

  sum += i; 

}

 System.out.println("The sum is " + sum);

The Difference between While and Do-While is as Follows :

- While is a Entry Control Loop, Condition is checked in the Beginning before entering the loop.

- Do-While is a Exit Control Loop, Atleast once the block is always executed then the Condition is checked.

While Loop :

int sum = 0; 
int i = 0;       // i is 0 Here

    while (i<100) {

      sum += i; 
      i++;

    }

  System.out.println("The sum is " + sum);

do-While :

int sum = 0; 
int i = 0;      // i is 0 Here

    do{ 

      sum += i; 
       i++
    }while(i < 100; );

     System.out.println("The sum is " + sum);

From Java 5 we also have For-Each Loop to iterate over the Collections, even its handy with Arrays.

ArrayList<String> arr = new ArrayList<String>();

arr.add("Vivek");
arr.add("Is");
arr.add("Good");
arr.add("Boy");

for (String str : arr){         // str represents the value in each index of arr

    System.out.println(str);     

 }

Skip Git commit hooks

Maybe (from git commit man page):

git commit --no-verify

-n  
--no-verify

This option bypasses the pre-commit and commit-msg hooks. See also githooks(5).

As commented by Blaise, -n can have a different role for certain commands.
For instance, git push -n is actually a dry-run push.
Only git push --no-verify would skip the hook.


Note: Git 2.14.x/2.15 improves the --no-verify behavior:

See commit 680ee55 (14 Aug 2017) by Kevin Willford (``).
(Merged by Junio C Hamano -- gitster -- in commit c3e034f, 23 Aug 2017)

commit: skip discarding the index if there is no pre-commit hook

"git commit" used to discard the index and re-read from the filesystem just in case the pre-commit hook has updated it in the middle; this has been optimized out when we know we do not run the pre-commit hook.


Davi Lima points out in the comments the git cherry-pick does not support --no-verify.
So if a cherry-pick triggers a pre-commit hook, you might, as in this blog post, have to comment/disable somehow that hook in order for your git cherry-pick to proceed.
The same process would be necessary in case of a git rebase --continue, after a merge conflict resolution.

Install-Module : The term 'Install-Module' is not recognized as the name of a cmdlet

I have Windows 10 and PowerShell 5.1 was already installed. For whatever reason the x86 version works and can find "Install-Module", but the other version cannot.

Search your Start Menu for "powershell", and find the entry that ends in "(x86)":

Windows 10 Start Menu searching for PowerShell

Here is what I experience between the two different versions:

PowerShell x86 vs x64 running Install-Module cmdlet comparison

decompiling DEX into Java sourcecode

Recent Debian have Python package androguard:

Description-en: full Python tool to play with Android files
 Androguard is a full Python tool to play with Android files.
  * DEX, ODEX
  * APK
  * Android's binary xml
  * Android resources
  * Disassemble DEX/ODEX bytecodes
  * Decompiler for DEX/ODEX files

Install corresponding packages:

sudo apt-get install androguard python-networkx

Decompile DEX file:

$ androdd -i classes.dex -o ./dir-for-output

Extract classes.dex from Apk + Decompile:

$ androdd -i app.apk -o ./dir-for-output

Apk file is nothing more that Java archive (JAR), you may extract files from archive via:

$ unzip app.apk -d ./dir-for-output

Parsing JSON in Excel VBA

Lots of good answers here - just chipping in my own.

I had a requirement to parse a very specific JSON string, representing the results of making a web-API call. The JSON described a list of objects, and looked something like this:

[
   {
     "property1": "foo",
     "property2": "bar",
     "timeOfDay": "2019-09-30T00:00:00",
     "numberOfHits": 98,
     "isSpecial": false,
     "comment": "just to be awkward, this contains a comma"
   },
   {
     "property1": "fool",
     "property2": "barrel",
     "timeOfDay": "2019-10-31T00:00:00",
     "numberOfHits": 11,
     "isSpecial": false,
     "comment": null
   },
   ...
]

There are a few things to note about this:

  1. The JSON should always describe a list (even if empty), which should only contain objects.
  2. The objects in the list should only contain properties with simple types (string / date / number / boolean or null).
  3. The value of a property may contain a comma - which makes parsing the JSON somewhat harder - but may not contain any quotes (because I'm too lazy to deal with that).

The ParseListOfObjects function in the code below takes the JSON string as input, and returns a Collection representing the items in the list. Each item is represented as a Dictionary, where the keys of the dictionary correspond to the names of the object's properties. The values are automatically converted to the appropriate type (String, Date, Double, Boolean - or Empty if the value is null).

Your VBA project will need a reference to the Microsoft Scripting Runtime library to use the Dictionary object - though it would not be difficult to remove this dependency if you use a different way of encoding the results.

Here's my JSON.bas:

Option Explicit

' NOTE: a fully-featured JSON parser in VBA would be a beast.
' This simple parser only supports VERY simple JSON (which is all we need).
' Specifically, it supports JSON comprising a list of objects, each of which has only simple properties.

Private Const strSTART_OF_LIST As String = "["
Private Const strEND_OF_LIST As String = "]"

Private Const strLIST_DELIMITER As String = ","

Private Const strSTART_OF_OBJECT As String = "{"
Private Const strEND_OF_OBJECT As String = "}"

Private Const strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR As String = ":"

Private Const strQUOTE As String = """"

Private Const strNULL_VALUE As String = "null"
Private Const strTRUE_VALUE As String = "true"
Private Const strFALSE_VALUE As String = "false"


Public Function ParseListOfObjects(ByVal strJson As String) As Collection

    ' Takes a JSON string that represents a list of objects (where each object has only simple value properties), and
    ' returns a collection of dictionary objects, where the keys and values of each dictionary represent the names and
    ' values of the JSON object properties.

    Set ParseListOfObjects = New Collection

    Dim strList As String: strList = Trim(strJson)

    ' Check we have a list
    If Left(strList, Len(strSTART_OF_LIST)) <> strSTART_OF_LIST _
    Or Right(strList, Len(strEND_OF_LIST)) <> strEND_OF_LIST Then
        Err.Raise vbObjectError, Description:="The provided JSON does not appear to be a list (it does not start with '" & strSTART_OF_LIST & "' and end with '" & strEND_OF_LIST & "')"
    End If

    ' Get the list item text (between the [ and ])
    Dim strBody As String: strBody = Trim(Mid(strList, 1 + Len(strSTART_OF_LIST), Len(strList) - Len(strSTART_OF_LIST) - Len(strEND_OF_LIST)))

    If strBody = "" Then
        Exit Function
    End If

    ' Check we have a list of objects
    If Left(strBody, Len(strSTART_OF_OBJECT)) <> strSTART_OF_OBJECT Then
        Err.Raise vbObjectError, Description:="The provided JSON does not appear to be a list of objects (the content of the list does not start with '" & strSTART_OF_OBJECT & "')"
    End If

    ' We now have something like:
    '    {"property":"value", "property":"value"}, {"property":"value", "property":"value"}, ...
    ' so we can't just split on a comma to get the various items (because the items themselves have commas in them).
    ' HOWEVER, since we know we're dealing with very simple JSON that has no nested objects, we can split on "}," because
    ' that should only appear between items. That'll mean that all but the last item will be missing it's closing brace.
    Dim astrItems() As String: astrItems = Split(strBody, strEND_OF_OBJECT & strLIST_DELIMITER)

    Dim ixItem As Long
    For ixItem = LBound(astrItems) To UBound(astrItems)

        Dim strItem As String: strItem = Trim(astrItems(ixItem))

        If Left(strItem, Len(strSTART_OF_OBJECT)) <> strSTART_OF_OBJECT Then
            Err.Raise vbObjectError, Description:="Mal-formed list item (does not start with '" & strSTART_OF_OBJECT & "')"
        End If

        ' Only the last item will have a closing brace (see comment above)
        Dim bIsLastItem As Boolean: bIsLastItem = ixItem = UBound(astrItems)

        If bIsLastItem Then
            If Right(strItem, Len(strEND_OF_OBJECT)) <> strEND_OF_OBJECT Then
                Err.Raise vbObjectError, Description:="Mal-formed list item (does not end with '" & strEND_OF_OBJECT & "')"
            End If
        End If

        Dim strContent: strContent = Mid(strItem, 1 + Len(strSTART_OF_OBJECT), Len(strItem) - Len(strSTART_OF_OBJECT) - IIf(bIsLastItem, Len(strEND_OF_OBJECT), 0))

        ParseListOfObjects.Add ParseObjectContent(strContent)

    Next ixItem

End Function

Private Function ParseObjectContent(ByVal strContent As String) As Scripting.Dictionary

    Set ParseObjectContent = New Scripting.Dictionary
    ParseObjectContent.CompareMode = TextCompare

    ' The object content will look something like:
    '    "property":"value", "property":"value", ...
    ' ... although the value may not be in quotes, since numbers are not quoted.
    ' We can't assume that the property value won't contain a comma, so we can't just split the
    ' string on the commas, but it's reasonably safe to assume that the value won't contain further quotes
    ' (and we're already assuming no sub-structure).
    ' We'll need to scan for commas while taking quoted strings into account.

    Dim ixPos As Long: ixPos = 1
    Do While ixPos <= Len(strContent)

        Dim strRemainder As String

        ' Find the opening quote for the name (names should always be quoted)
        Dim ixOpeningQuote As Long: ixOpeningQuote = InStr(ixPos, strContent, strQUOTE)

        If ixOpeningQuote <= 0 Then
            ' The only valid reason for not finding a quote is if we're at the end (though white space is permitted)
            strRemainder = Trim(Mid(strContent, ixPos))
            If Len(strRemainder) = 0 Then
                Exit Do
            End If
            Err.Raise vbObjectError, Description:="Mal-formed object (the object name does not start with a quote)"
        End If

        ' Now find the closing quote for the name, which we assume is the very next quote
        Dim ixClosingQuote As Long: ixClosingQuote = InStr(ixOpeningQuote + 1, strContent, strQUOTE)
        If ixClosingQuote <= 0 Then
            Err.Raise vbObjectError, Description:="Mal-formed object (the object name does not end with a quote)"
        End If

        If ixClosingQuote - ixOpeningQuote - Len(strQUOTE) = 0 Then
            Err.Raise vbObjectError, Description:="Mal-formed object (the object name is blank)"
        End If

        Dim strName: strName = Mid(strContent, ixOpeningQuote + Len(strQUOTE), ixClosingQuote - ixOpeningQuote - Len(strQUOTE))

        ' The next thing after the quote should be the colon

        Dim ixNameValueSeparator As Long: ixNameValueSeparator = InStr(ixClosingQuote + Len(strQUOTE), strContent, strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR)

        If ixNameValueSeparator <= 0 Then
            Err.Raise vbObjectError, Description:="Mal-formed object (missing '" & strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR & "')"
        End If

        ' Check that there was nothing between the closing quote and the colon

        strRemainder = Trim(Mid(strContent, ixClosingQuote + Len(strQUOTE), ixNameValueSeparator - ixClosingQuote - Len(strQUOTE)))
        If Len(strRemainder) > 0 Then
            Err.Raise vbObjectError, Description:="Mal-formed object (unexpected content between name and '" & strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR & "')"
        End If

        ' What comes after the colon is the value, which may or may not be quoted (e.g. numbers are not quoted).
        ' If the very next thing we see is a quote, then it's a quoted value, and we need to find the matching
        ' closing quote while ignoring any commas inside the quoted value.
        ' If the next thing we see is NOT a quote, then it must be an unquoted value, and we can scan directly
        ' for the next comma.
        ' Either way, we're looking for a quote or a comma, whichever comes first (or neither, in which case we
        ' have the last - unquoted - value).

        ixOpeningQuote = InStr(ixNameValueSeparator + Len(strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR), strContent, strQUOTE)
        Dim ixPropertySeparator As Long: ixPropertySeparator = InStr(ixNameValueSeparator + Len(strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR), strContent, strLIST_DELIMITER)

        If ixOpeningQuote > 0 And ixPropertySeparator > 0 Then
            ' Only use whichever came first
            If ixOpeningQuote < ixPropertySeparator Then
                ixPropertySeparator = 0
            Else
                ixOpeningQuote = 0
            End If
        End If

        Dim strValue As String
        Dim vValue As Variant

        If ixOpeningQuote <= 0 Then ' it's not a quoted value

            If ixPropertySeparator <= 0 Then ' there's no next value; this is the last one
                strValue = Trim(Mid(strContent, ixNameValueSeparator + Len(strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR)))
                ixPos = Len(strContent) + 1
            Else ' this is not the last value
                strValue = Trim(Mid(strContent, ixNameValueSeparator + Len(strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR), ixPropertySeparator - ixNameValueSeparator - Len(strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR)))
                ixPos = ixPropertySeparator + Len(strLIST_DELIMITER)
            End If

            vValue = ParseUnquotedValue(strValue)

        Else ' It is a quoted value

            ' Find the corresponding closing quote, which should be the very next one

            ixClosingQuote = InStr(ixOpeningQuote + Len(strQUOTE), strContent, strQUOTE)

            If ixClosingQuote <= 0 Then
                Err.Raise vbObjectError, Description:="Mal-formed object (the value does not end with a quote)"
            End If

            strValue = Mid(strContent, ixOpeningQuote + Len(strQUOTE), ixClosingQuote - ixOpeningQuote - Len(strQUOTE))
            vValue = ParseQuotedValue(strValue)

            ' Re-scan for the property separator, in case we hit one that was part of the quoted value
            ixPropertySeparator = InStr(ixClosingQuote + Len(strQUOTE), strContent, strLIST_DELIMITER)

            If ixPropertySeparator <= 0 Then ' this was the last value

                ' Check that there's nothing between the closing quote and the end of the text
                strRemainder = Trim(Mid(strContent, ixClosingQuote + Len(strQUOTE)))
                If Len(strRemainder) > 0 Then
                    Err.Raise vbObjectError, Description:="Mal-formed object (there is content after the last value)"
                End If

                ixPos = Len(strContent) + 1

            Else ' this is not the last value

                ' Check that there's nothing between the closing quote and the property separator
                strRemainder = Trim(Mid(strContent, ixClosingQuote + Len(strQUOTE), ixPropertySeparator - ixClosingQuote - Len(strQUOTE)))
                If Len(strRemainder) > 0 Then
                    Err.Raise vbObjectError, Description:="Mal-formed object (there is content after the last value)"
                End If

                ixPos = ixPropertySeparator + Len(strLIST_DELIMITER)

            End If

        End If

        ParseObjectContent.Add strName, vValue

    Loop

End Function

Private Function ParseUnquotedValue(ByVal strValue As String) As Variant

    If StrComp(strValue, strNULL_VALUE, vbTextCompare) = 0 Then
        ParseUnquotedValue = Empty
    ElseIf StrComp(strValue, strTRUE_VALUE, vbTextCompare) = 0 Then
        ParseUnquotedValue = True
    ElseIf StrComp(strValue, strFALSE_VALUE, vbTextCompare) = 0 Then
        ParseUnquotedValue = False
    ElseIf IsNumeric(strValue) Then
        ParseUnquotedValue = CDbl(strValue)
    Else
        Err.Raise vbObjectError, Description:="Mal-formed value (not null, true, false or a number)"
    End If

End Function

Private Function ParseQuotedValue(ByVal strValue As String) As Variant

    ' Both dates and strings are quoted; we'll treat it as a date if it has the expected date format.
    ' Dates are in the form:
    '    2019-09-30T00:00:00
    If strValue Like "####-##-##T##:00:00" Then
        ' NOTE: we just want the date part
        ParseQuotedValue = CDate(Left(strValue, Len("####-##-##")))
    Else
        ParseQuotedValue = strValue
    End If

End Function

A simple test:

Const strJSON As String = "[{""property1"":""foo""}]"
Dim oObjects As Collection: Set oObjects = Json.ParseListOfObjects(strJSON)

MsgBox oObjects(1)("property1") ' shows "foo"

JQuery: How to get selected radio button value?

To get the value of the selected Radio Button, Use RadioButtonName and the Form Id containing the RadioButton.

$('input[name=radioName]:checked', '#myForm').val()

OR by only

$('form input[type=radio]:checked').val();

How do I find the number of arguments passed to a Bash script?

Below is the easy one -

cat countvariable.sh

echo "$@" |awk '{for(i=0;i<=NF;i++); print i-1 }'

Output :

#./countvariable.sh 1 2 3 4 5 6
6
#./countvariable.sh 1 2 3 4 5 6 apple orange
8

How do I indent multiple lines at once in Notepad++?

The problem was with the QuickText plugin. After removing it, indent worked as normal.

Creating a new user and password with Ansible

My solution is using lookup and generate password automatically.

---
- hosts: 'all'
  remote_user: root
  gather_facts: no
  vars:
    deploy_user: deploy
    deploy_password: "{{ lookup('password', '/tmp/password chars=ascii_letters') }}"

  tasks:
    - name: Create deploy user
      user:
        name: "{{ deploy_user }}"
        password: "{{ deploy_password | password_hash('sha512') }}"

How to get the difference between two arrays in JavaScript?

const difference = function (baseArray, arrayToCampare, callback = (a, b) => a!== b) {
  if (!(arrayToCampare instanceof Array)) {
    return baseArray;
  }
  return baseArray.filter(baseEl =>
    arrayToCampare.every(compareEl => callback(baseEl, compareEl)));
}

How to find rows that have a value that contains a lowercase letter

I'm not an expert on MySQL I would suggest you look at REGEXP.

SELECT * FROM MyTable WHERE ColumnX REGEXP '^[a-z]';

Android Support Design TabLayout: Gravity Center and Mode Scrollable

My final solution

class DynamicModeTabLayout : TabLayout {

    constructor(context: Context?) : super(context)
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)

    override fun setupWithViewPager(viewPager: ViewPager?) {
        super.setupWithViewPager(viewPager)

        val view = getChildAt(0) ?: return
        view.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED)
        val size = view.measuredWidth

        if (size > measuredWidth) {
            tabMode = MODE_SCROLLABLE
            tabGravity = GRAVITY_CENTER
        } else {
            tabMode = MODE_FIXED
            tabGravity = GRAVITY_FILL
        }
    }
}

How To Get Selected Value From UIPickerView

You will need to ask the picker's delegate, in the same way your application does. Here is how I do it from within my UIPickerViewDelegate:

func selectedRowValue(picker : UIPickerView, ic : Int) -> String {

    //Row Index
    let ir  = picker.selectedRow(inComponent: ic);

    //Value
    let val = self.pickerView(picker,
                              titleForRow:  ir,
                              forComponent: ic);
    return val!;
}

sending email via php mail function goes to spam

What we usually do with e-mail, preventing spam-folders as the end destination, is using either Gmail as the smtp server or Mandrill as the smtp server.

Unable to locate an executable at "/usr/bin/java/bin/java" (-1)

For those using newer versions of java: jhat has been removed since Java 9. Source: https://www.infoq.com/news/2015/12/OpenJDK-9-removal-of-HPROF-jhat/

That same article recommends using Java VisualVM instead.

show icon in actionbar/toolbar with AppCompat-v7 21

Try using:

ActionBar ab = getSupportActionBar();
ab.setHomeButtonEnabled(true);
ab.setDisplayUseLogoEnabled(true);
ab.setLogo(R.drawable.ic_launcher);

NoClassDefFoundError - Eclipse and Android

By adding the external jar into your build path just adds the jar to your package, but it will not be available during runtime.

In order for the jar to be available at runtime, you need to:

  • Put the jar under your assets folder
  • Include this copy of the jar in your build path
  • Go to the export tab on the same popup window
  • Check the box against the newly added jar

Create a table without a header in Markdown

Universal Solution

Many of the suggestions unfortunately do not work for all Markdown viewers/editors, for instance, the popular Markdown Viewer Chrome extension, but they do work with iA Writer.

What does seem to work across both of these popular programs (and might work for your particular application) is to use HTML comment blocks ('<!-- -->'):

| <!-- -->    | <!-- -->    |
|-------------|-------------|
| Foo         | Bar         |

Like some of the earlier suggestions stated, this does add an empty header row in your Markdown viewer/editor. In iA Writer, it's aesthetically small enough that it doesn't get in my way too much.

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

One classic root cause for this message is:

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

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

Try first to create a commit:

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

And then try git push -u origin master again.

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

How to read/process command line arguments?

I use optparse myself, but really like the direction Simon Willison is taking with his recently introduced optfunc library. It works by:

"introspecting a function definition (including its arguments and their default values) and using that to construct a command line argument parser."

So, for example, this function definition:

def geocode(s, api_key='', geocoder='google', list_geocoders=False):

is turned into this optparse help text:

    Options:
      -h, --help            show this help message and exit
      -l, --list-geocoders
      -a API_KEY, --api-key=API_KEY
      -g GEOCODER, --geocoder=GEOCODER

Programmatically stop execution of python script?

You could raise SystemExit(0) instead of going to all the trouble to import sys; sys.exit(0).

VBA module that runs other modules

Is "Module1" part of the same workbook that contains "moduleController"?
If not, you could call public method of "Module1" using Application.Run someWorkbook.xlsm!methodOfModule.

CMD (command prompt) can't go to the desktop

You need to use the change directory command 'cd' to change directory

cd C:\Users\MyName\Desktop

you can use cd \d to change the drive as well.

link for additional resources http://ss64.com/nt/cd.html

What's the equivalent of Java's Thread.sleep() in JavaScript?

Try with this code. I hope it's useful for you.

function sleep(seconds) 
{
  var e = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= e) {}
}

Can you call ko.applyBindings to bind a partial view?

I've managed to bind a custom model to an element at runtime. The code is here: http://jsfiddle.net/ZiglioNZ/tzD4T/457/

The interesting bit is that I apply the data-bind attribute to an element I didn't define:

    var handle = slider.slider().find(".ui-slider-handle").first();
    $(handle).attr("data-bind", "tooltip: viewModel.value");
    ko.applyBindings(viewModel.value, $(handle)[0]);

How can I clear previous output in Terminal in Mac OS X?

With Mac OS X v10.10 (Yosemite), use Option + Command + K to clear the scrollback in Terminal.app.

PHP: How to check if a date is today, yesterday or tomorrow

function getRangeDateString($timestamp) {
    if ($timestamp) {
        $currentTime=strtotime('today');
        // Reset time to 00:00:00
        $timestamp=strtotime(date('Y-m-d 00:00:00',$timestamp));
        $days=round(($timestamp-$currentTime)/86400);
        switch($days) {
            case '0';
                return 'Today';
                break;
            case '-1';
                return 'Yesterday';
                break;
            case '-2';
                return 'Day before yesterday';
                break;
            case '1';
                return 'Tomorrow';
                break;
            case '2';
                return 'Day after tomorrow';
                break;
            default:
                if ($days > 0) {
                    return 'In '.$days.' days';
                } else {
                    return ($days*-1).' days ago';
                }
                break;
        }
    }
}

Checking the equality of two slices

You should use reflect.DeepEqual()

DeepEqual is a recursive relaxation of Go's == operator.

DeepEqual reports whether x and y are “deeply equal,” defined as follows. Two values of identical type are deeply equal if one of the following cases applies. Values of distinct types are never deeply equal.

Array values are deeply equal when their corresponding elements are deeply equal.

Struct values are deeply equal if their corresponding fields, both exported and unexported, are deeply equal.

Func values are deeply equal if both are nil; otherwise they are not deeply equal.

Interface values are deeply equal if they hold deeply equal concrete values.

Map values are deeply equal if they are the same map object or if they have the same length and their corresponding keys (matched using Go equality) map to deeply equal values.

Pointer values are deeply equal if they are equal using Go's == operator or if they point to deeply equal values.

Slice values are deeply equal when all of the following are true: they are both nil or both non-nil, they have the same length, and either they point to the same initial entry of the same underlying array (that is, &x[0] == &y[0]) or their corresponding elements (up to length) are deeply equal. Note that a non-nil empty slice and a nil slice (for example, []byte{} and []byte(nil)) are not deeply equal.

Other values - numbers, bools, strings, and channels - are deeply equal if they are equal using Go's == operator.

Javascript: set label text

InnerHTML should be innerHTML:

document.getElementById('LblAboutMeCount').innerHTML = charsleft;

You should bind your checkLength function to your textarea with jQuery rather than calling it inline and rather intrusively:

$(document).ready(function() {
    $('textarea[name=text]').keypress(function(e) {
        checkLength($(this),512,$('#LblTextCount'));
    }).focus(function() {
        checkLength($(this),512,$('#LblTextCount'));
    });
});

You can neaten up checkLength by using more jQuery, and I wouldn't use 'object' as a formal parameter:

function checkLength(obj, maxlength, label) {
    charsleft = (maxlength - obj.val().length);
    // never allow to exceed the specified limit
    if( charsleft < 0 ) {
        obj.val(obj.val().substring(0, maxlength-1));
    }
    // I'm trying to set the value of charsleft into the label
    label.text(charsleft);
    $('#LblAboutMeCount').html(charsleft);
}

So if you apply the above, you can change your markup to:

<textarea name="text"></textarea>

jQuery plugin returning "Cannot read property of undefined"

I had same problem with 'parallax' plugin. I changed jQuery librery version to *jquery-1.6.4* from *jquery-1.10.2*. And error cleared.

show all tags in git log

Note: the commit 5e1361c from brian m. carlson (bk2204) (for git 1.9/2.0 Q1 2014) deals with a special case in term of log decoration with tags:

log: properly handle decorations with chained tags

git log did not correctly handle decorations when a tag object referenced another tag object that was no longer a ref, such as when the second tag was deleted.
The commit would not be decorated correctly because parse_object had not been called on the second tag and therefore its tagged field had not been filled in, resulting in none of the tags being associated with the relevant commit.

Call parse_object to fill in this field if it is absent so that the chain of tags can be dereferenced and the commit can be properly decorated.
Include tests as well to prevent future regressions.

Example:

git tag -a tag1 -m tag1 &&
git tag -a tag2 -m tag2 tag1 &&
git tag -d tag1 &&
git commit --amend -m shorter &&
git log --no-walk --tags --pretty="%H %d" --decorate=full

Maven skip tests

During maven compilation you can skip test execution by adding following plugin in pom.xml

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.20.1</version>
    <configuration>
         <skipTests>true</skipTests>
    </configuration>
</plugin>

Session state can only be used when enableSessionState is set to true either in a configuration

This error was raised for me because of an unhandled exception thrown in the Public Sub New() (Visual Basic) constructor function of the Web Page in the code behind.

If you implement the constructor function wrap the code in a Try/Catch statement and see if it solves the problem.

What's the difference between 'git merge' and 'git rebase'?

I found one really interesting article on git rebase vs merge, thought of sharing it here

  • If you want to see the history completely same as it happened, you should use merge. Merge preserves history whereas rebase rewrites it.
  • Merging adds a new commit to your history
  • Rebasing is better to streamline a complex history, you are able to change the commit history by interactive rebase.

Force flushing of output to a file while bash script is still running

How just spotted here the problem is that you have to wait that the programs that you run from your script finish their jobs.
If in your script you run program in background you can try something more.

In general a call to sync before you exit allows to flush file system buffers and can help a little.

If in the script you start some programs in background (&), you can wait that they finish before you exit from the script. To have an idea about how it can function you can see below

#!/bin/bash
#... some stuffs ...
program_1 &          # here you start a program 1 in background
PID_PROGRAM_1=${!}   # here you remember its PID
#... some other stuffs ... 
program_2 &          # here you start a program 2 in background
wait ${!}            # You wait it finish not really useful here
#... some other stuffs ... 
daemon_1 &           # We will not wait it will finish
program_3 &          # here you start a program 1 in background
PID_PROGRAM_3=${!}   # here you remember its PID
#... last other stuffs ... 
sync
wait $PID_PROGRAM_1
wait $PID_PROGRAM_3  # program 2 is just ended
# ...

Since wait works with jobs as well as with PID numbers a lazy solution should be to put at the end of the script

for job in `jobs -p`
do
   wait $job 
done

More difficult is the situation if you run something that run something else in background because you have to search and wait (if it is the case) the end of all the child process: for example if you run a daemon probably it is not the case to wait it finishes :-).

Note:

  • wait ${!} means "wait till the last background process is completed" where $! is the PID of the last background process. So to put wait ${!} just after program_2 & is equivalent to execute directly program_2 without sending it in background with &

  • From the help of wait:

    Syntax    
        wait [n ...]
    Key  
        n A process ID or a job specification
    

Sum one number to every element in a list (or array) in Python

if you want to operate with list of numbers it is better to use NumPy arrays:

import numpy
a = [1, 1, 1 ,1, 1]
ar = numpy.array(a)
print ar + 2

gives

[3, 3, 3, 3, 3]

How do I make an attributed string using Swift?

Swift 3.0 // create attributed string

Define attributes like

let attributes = [NSAttributedStringKey.font : UIFont.init(name: "Avenir-Medium", size: 13.0)]

git ahead/behind info between master and branch?

After doing a git fetch, you can run git status to show how many commits the local branch is ahead or behind of the remote version of the branch.

This won't show you how many commits it is ahead or behind of a different branch though. Your options are the full diff, looking at github, or using a solution like Vimhsa linked above: Git status over all repo's

Converting list to numpy array

If you have a list of lists, you only needed to use ...

import numpy as np
...
npa = np.asarray(someListOfLists, dtype=np.float32)

per this LINK in the scipy / numpy documentation. You just needed to define dtype inside the call to asarray.

How to read connection string in .NET Core?

The way that I found to resolve this was to use AddJsonFile in a builder at Startup (which allows it to find the configuration stored in the appsettings.json file) and then use that to set a private _config variable

public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
        _config = builder.Build();
    }

And then I could set the configuration string as follows:

var connectionString = _config.GetConnectionString("DbContextSettings:ConnectionString"); 

This is on dotnet core 1.1

Unzip files (7-zip) via cmd command

In Windows 10 I had to run the batch file as an administrator.

How to populate a dropdownlist with json data in jquery?

To populate ComboBox with JSON, you can consider using the: jqwidgets combobox, too.

How do you add input from user into list in Python

shopList = [] 
maxLengthList = 6
while len(shopList) < maxLengthList:
    item = input("Enter your Item to the List: ")
    shopList.append(item)
    print shopList
print "That's your Shopping List"
print shopList

How to find the nearest parent of a Git branch?

You can also try:

git log --graph --decorate

Get Cell Value from a DataTable in C#

To get cell column name as well as cell value :

List<JObject> dataList = new List<JObject>();

for (int i = 0; i < dataTable.Rows.Count; i++)
{
    JObject eachRowObj = new JObject();

    for (int j = 0; j < dataTable.Columns.Count; j++)
    {
        string key = Convert.ToString(dataTable.Columns[j]);
        string value = Convert.ToString(dataTable.Rows[i].ItemArray[j]);

        eachRowObj.Add(key, value);

    }

    dataList.Add(eachRowObj);

}

CSS: How to remove pseudo elements (after, before,...)?

had a same problem few minutes ago and just content:none; did not do work but adding content:none !important; and display:none !important; worked for me

How to trim a string to N chars in Javascript?

I think that you should use this code :-)

    // sample string
            const param= "Hi you know anybody like pizaa";

         // You can change limit parameter(up to you)
         const checkTitle = (str, limit = 17) => {
      var newTitle = [];
      if (param.length >= limit) {
        param.split(" ").reduce((acc, cur) => {
          if (acc + cur.length <= limit) {
            newTitle.push(cur);
          }
          return acc + cur.length;
        }, 0);
        return `${newTitle.join(" ")} ...`;
      }
      return param;
    };
    console.log(checkTitle(str));

// result : Hi you know anybody ...

What is the difference between HTTP_HOST and SERVER_NAME in PHP?

As I mentioned in this answer, if the server runs on a port other than 80 (as might be common on a development/intranet machine) then HTTP_HOST contains the port, while SERVER_NAME does not.

$_SERVER['HTTP_HOST'] == 'localhost:8080'
$_SERVER['SERVER_NAME'] == 'localhost'

(At least that's what I've noticed in Apache port-based virtualhosts)

Note that HTTP_HOST does not contain :443 when running on HTTPS (unless you're running on a non-standard port, which I haven't tested).

As others have noted, the two also differ when using IPv6:

$_SERVER['HTTP_HOST'] == '[::1]'
$_SERVER['SERVER_NAME'] == '::1'

Problem in running .net framework 4.0 website on iis 7.0

If you are running Delphi, or other native compiled CGI, this solution will work:

  1. As other pointed, go to IIS manager and click on the server name. Then click on the "ISAPI and CGI Restrictions" icon under the IIS header.

  2. If you have everything allowed, it will still not work. You need to click on "Edit Feature Settings" in Actions (on the right side), and check "Allow unspecified CGI modules", or "Allow unspecified ISAPI modules" respectively.

  3. Click OK

foreach loop in angularjs

you have to use nested angular.forEach loops for JSON as shown below:

 var values = [
        {
            "name":"Thomas",
            "password":"thomas"
        },
        { 
            "name":"linda",
            "password":"linda"
        }];

    angular.forEach(values,function(value,key){
        angular.forEach(value,function(v1,k1){//this is nested angular.forEach loop
            console.log(k1+":"+v1);
        });
    });

Parse query string into an array

For this specific question the chosen answer is correct but if there is a redundant parameter—like an extra "e"—in the URL the function will silently fail without an error or exception being thrown:

a=2&b=2&c=5&d=4&e=1&e=2&e=3 

So I prefer using my own parser like so:

//$_SERVER['QUERY_STRING'] = `a=2&b=2&c=5&d=4&e=100&e=200&e=300` 

$url_qry_str  = explode('&', $_SERVER['QUERY_STRING']);

//arrays that will hold the values from the url
$a_arr = $b_arr = $c_arr = $d_arr = $e_arr =  array();

foreach( $url_qry_str as $param )
    {
      $var =  explode('=', $param, 2);
      if($var[0]=="a")      $a_arr[]=$var[1];
      if($var[0]=="b")      $b_arr[]=$var[1];
      if($var[0]=="c")      $c_arr[]=$var[1];
      if($var[0]=="d")      $d_arr[]=$var[1];
      if($var[0]=="e")      $e_arr[]=$var[1];
    }

    var_dump($e_arr); 
    // will return :
    //array(3) { [0]=> string(1) "100" [1]=> string(1) "200" [2]=> string(1) "300" } 

Now you have all the occurrences of each parameter in its own array, you can always merge them into one array if you want to.

Hope that helps!

Two Divs on the same row and center align both of them

Could this do for you? Check my JSFiddle

And the code:

HTML

<div class="container">
    <div class="div1">Div 1</div>
    <div class="div2">Div 2</div>
</div>

CSS

div.container {
    background-color: #FF0000;
    margin: auto;   
    width: 304px;
}

div.div1 {
    border: 1px solid #000;
    float: left;
    width: 150px;
}

div.div2 {
    border: 1px solid red;
    float: left;
    width: 150px;
}

Javascript: Call a function after specific time period

You can use JavaScript Timing Events to call function after certain interval of time:

This shows the alert box after 3 seconds:

setInterval(function(){alert("Hello")},3000);

You can use two method of time event in javascript.i.e.

  1. setInterval(): executes a function, over and over again, at specified time intervals
  2. setTimeout() : executes a function, once, after waiting a specified number of milliseconds

password-check directive in angularjs

As of angular 1.3.0-beta12, invalid inputs don't write to ngModel, so you can't watch AND THEN validate as you can see here: http://plnkr.co/edit/W6AFHF308nyKVMQ9vomw?p=preview. A new validators pipeline was introduced and you can attach to this to achieve the same thing.

Actually, on that note I've created a bower component for common extra validators: https://github.com/intellix/angular-validators which includes this.

angular.module('validators').directive('equals', function() {
    return {
        restrict: 'A',
        require: '?ngModel',
        link: function(scope, elem, attrs, ngModel)
        {
            if (!ngModel) return;

            attrs.$observe('equals', function() {
                ngModel.$validate();
            });

            ngModel.$validators.equals = function(value) {
                return value === attrs.equals;
            };
        }
    };
});

angular.module('validators').directive('notEquals', function() {
    return {
        restrict: 'A',
        require: '?ngModel',
        link: function(scope, elem, attrs, ngModel)
        {
            if (!ngModel) return;

            attrs.$observe('notEquals', function() {
                ngModel.$validate();
            });

            ngModel.$validators.notEquals = function(value) {
                return value === attrs.notEquals;
            };
        }
    };
});

No assembly found containing an OwinStartupAttribute Error

Check if you have the Startup class created in your project. This is an example:

using Microsoft.Owin;
using Owin;

[assembly: OwinStartupAttribute(typeof({project_name}.Startup))]

namespace AuctionPortal
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
        }
    }
}

Correctly ignore all files recursively under a specific folder except for a specific file type

The best answer is to add a Resources/.gitignore file under Resources containing:

# Ignore any file in this directory except for this file and *.foo files
*
!/.gitignore
!*.foo

If you are unwilling or unable to add that .gitignore file, there is an inelegant solution:

# Ignore any file but *.foo under Resources. Update this if we add deeper directories
Resources/*
!Resources/*/
!Resources/*.foo
Resources/*/*
!Resources/*/*/
!Resources/*/*.foo
Resources/*/*/*
!Resources/*/*/*/
!Resources/*/*/*.foo
Resources/*/*/*/*
!Resources/*/*/*/*/
!Resources/*/*/*/*.foo

You will need to edit that pattern if you add directories deeper than specified.

Pandas (python): How to add column to dataframe for index?

How about this:

from pandas import *

idx = Int64Index([171, 174, 173])
df = DataFrame(index = idx, data =([1,2,3]))
print df

It gives me:

     0
171  1
174  2
173  3

Is this what you are looking for?

MySQL ON DUPLICATE KEY UPDATE for multiple rows insert in single query

INSERT INTO ... ON DUPLICATE KEY UPDATE will only work for MYSQL, not for SQL Server.

for SQL server, the way to work around this is to first declare a temp table, insert value to that temp table, and then use MERGE

Like this:

declare @Source table
(
name varchar(30),
age decimal(23,0)
)

insert into @Source VALUES
('Helen', 24),
('Katrina', 21),
('Samia', 22),
('Hui Ling', 25),
('Yumie', 29);


MERGE beautiful  AS Tg
using  @source as Sc
on tg.namet=sc.name 

when matched then update 
set tg.age=sc.age

when not matched then 
insert (name, age) VALUES
(SC.name, sc.age);

Moving average or running mean

or module for python that calculates

in my tests at Tradewave.net TA-lib always wins:

import talib as ta
import numpy as np
import pandas as pd
import scipy
from scipy import signal
import time as t

PAIR = info.primary_pair
PERIOD = 30

def initialize():
    storage.reset()
    storage.elapsed = storage.get('elapsed', [0,0,0,0,0,0])

def cumsum_sma(array, period):
    ret = np.cumsum(array, dtype=float)
    ret[period:] = ret[period:] - ret[:-period]
    return ret[period - 1:] / period

def pandas_sma(array, period):
    return pd.rolling_mean(array, period)

def api_sma(array, period):
    # this method is native to Tradewave and does NOT return an array
    return (data[PAIR].ma(PERIOD))

def talib_sma(array, period):
    return ta.MA(array, period)

def convolve_sma(array, period):
    return np.convolve(array, np.ones((period,))/period, mode='valid')

def fftconvolve_sma(array, period):    
    return scipy.signal.fftconvolve(
        array, np.ones((period,))/period, mode='valid')    

def tick():

    close = data[PAIR].warmup_period('close')

    t1 = t.time()
    sma_api = api_sma(close, PERIOD)
    t2 = t.time()
    sma_cumsum = cumsum_sma(close, PERIOD)
    t3 = t.time()
    sma_pandas = pandas_sma(close, PERIOD)
    t4 = t.time()
    sma_talib = talib_sma(close, PERIOD)
    t5 = t.time()
    sma_convolve = convolve_sma(close, PERIOD)
    t6 = t.time()
    sma_fftconvolve = fftconvolve_sma(close, PERIOD)
    t7 = t.time()

    storage.elapsed[-1] = storage.elapsed[-1] + t2-t1
    storage.elapsed[-2] = storage.elapsed[-2] + t3-t2
    storage.elapsed[-3] = storage.elapsed[-3] + t4-t3
    storage.elapsed[-4] = storage.elapsed[-4] + t5-t4
    storage.elapsed[-5] = storage.elapsed[-5] + t6-t5    
    storage.elapsed[-6] = storage.elapsed[-6] + t7-t6        

    plot('sma_api', sma_api)  
    plot('sma_cumsum', sma_cumsum[-5])
    plot('sma_pandas', sma_pandas[-10])
    plot('sma_talib', sma_talib[-15])
    plot('sma_convolve', sma_convolve[-20])    
    plot('sma_fftconvolve', sma_fftconvolve[-25])

def stop():

    log('ticks....: %s' % info.max_ticks)

    log('api......: %.5f' % storage.elapsed[-1])
    log('cumsum...: %.5f' % storage.elapsed[-2])
    log('pandas...: %.5f' % storage.elapsed[-3])
    log('talib....: %.5f' % storage.elapsed[-4])
    log('convolve.: %.5f' % storage.elapsed[-5])    
    log('fft......: %.5f' % storage.elapsed[-6])

results:

[2015-01-31 23:00:00] ticks....: 744
[2015-01-31 23:00:00] api......: 0.16445
[2015-01-31 23:00:00] cumsum...: 0.03189
[2015-01-31 23:00:00] pandas...: 0.03677
[2015-01-31 23:00:00] talib....: 0.00700  # <<< Winner!
[2015-01-31 23:00:00] convolve.: 0.04871
[2015-01-31 23:00:00] fft......: 0.22306

enter image description here

Vertical Align text in a Label

To do this you should alter the vertical-align property of the input.

<dd><label class="<?=$email_confirm_class;?>" style="text-align:right; padding-right:3px">Confirm Email</label><input class="text" type="text" style="vertical-align: middle; border:none;" name="email_confirm" id="email_confirm" size="18" value="<?=$_POST['email_confirm'];?>" tabindex="4" /> *</dd>

Here is a more complete version. It has been tested in IE 8 and it works. see the difference by removing the vertical-align: middle from the input:

<html><head></head><body><dl><dt>test</dt><dd><label class="test" style="text-align:right; padding-right:3px">Confirm Email</label><input class="text" type="text" style="vertical-align: middle; font-size: 22px" name="email_confirm" id="email_confirm" size="28" value="test" tabindex="4" /> *</dd></dl></body></html>

Updating a java map entry

Use

table.put(key, val);

to add a new key/value pair or overwrite an existing key's value.

From the Javadocs:

V put(K key, V value): Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for the key, the old value is replaced by the specified value. (A map m is said to contain a mapping for a key k if and only if m.containsKey(k) would return true.)

Tooltip on image

You can use the following format to generate a tooltip for an image.

<div class="tooltip"><img src="joe.jpg" />
  <span class="tooltiptext">Tooltip text</span>
</div>

Regular Expression for any number greater than 0?

I think this would perfectly work :

([1-9][0-9]*(\.[0-9]*[1-9])?|0\.[0-9]*[1-9])

Valid:

 1
 1.2
 1.02
 0.1 
 0.02

Not valid :

0
01
01.2
1.10

Lowercase and Uppercase with jQuery

I think you want to lowercase the checked value? Try:

var jIsHasKids = $('#chkIsHasKids:checked').val().toLowerCase();

or you want to check it, then get its value as lowercase:

var jIsHasKids = $('#chkIsHasKids').attr("checked", true).val().toLowerCase();

Convert a PHP object to an associative array

Here is some code:

function object_to_array($data) {
    if ((! is_array($data)) and (! is_object($data)))
        return 'xxx'; // $data;

    $result = array();

    $data = (array) $data;
    foreach ($data as $key => $value) {
        if (is_object($value))
            $value = (array) $value;
        if (is_array($value))
            $result[$key] = object_to_array($value);
        else
            $result[$key] = $value;
    }
    return $result;
}

Why this "Implicit declaration of function 'X'"?

summation and your other functions are defined after they're used in main, and so the compiler has made a guess about it's signature; in other words, an implicit declaration has been assumed.

You should declare the function before it's used and get rid of the warning. In the C99 specification, this is an error.

Either move the function bodies before main, or include method signatures before main, e.g.:

#include <stdio.h>

int summation(int *, int *, int *);

int main()
{
    // ...

Where does MySQL store database files on Windows and what are the names of the files?

It's usually in the folder specified below, but ProgramData is usually a hidden folder. To show it, go to control panel search for "folder" then under advanced settings tick show hidden files and click apply. C:/ProgramData/MySQL/MySQL Server 5.5/Data/

How do I get AWS_ACCESS_KEY_ID for Amazon?

  1. Open the AWS Console
  2. Click on your username near the top right and select My Security Credentials
  3. Click on Users in the sidebar
  4. Click on your username
  5. Click on the Security Credentials tab
  6. Click Create Access Key
  7. Click Show User Security Credentials

How to remove constraints from my MySQL table?

There is no such thing as DROP CONSTRAINT in MySQL. In your case you could use DROP FOREIGN KEY instead.

SQLite select where empty?

You can do this with the following:

int counter = 0;
String sql = "SELECT projectName,Owner " + "FROM Project WHERE Owner= ?";
PreparedStatement prep = conn.prepareStatement(sql);
prep.setString(1, "");
ResultSet rs = prep.executeQuery();
while (rs.next()) {
    counter++;
}
System.out.println(counter);

This will give you the no of rows where the column value is null or blank.

JVM property -Dfile.encoding=UTF8 or UTF-8?

It will be:

UTF8

See here for the definitions.

Execute cmd command from VBScript

Can also invoke oShell.Exec in order to be able to read STDIN/STDOUT/STDERR responses. Perfect for error checking which it seems you're doing with your sanity .BAT.

SQL Server format decimal places with commas

If you are using SQL Azure Reporting Services, the "format" function is unsupported. This is really the only way to format a tooltip in a chart in SSRS. So the workaround is to return a column that has a string representation of the formatted number to use for the tooltip. So, I do agree that SQL is not the place for formatting. Except in cases like this where the tool does not have proper functions to handle display formatting.

In my case I needed to show a number formatted with commas and no decimals (type decimal 2) and ended up with this gem of a calculated column in my dataset query:

,Fmt_DDS=reverse(stuff(reverse(CONVERT(varchar(25),cast(SUM(kv.DeepDiveSavingsEst) as money),1)), 1, 3, ''))

It works, but is very ugly and non-obvious to whoever maintains the report down the road. Yay Cloud!

Program to find largest and second largest number in array

(I'm going to ignore handling input, its just a distraction.)

The easy way is to sort it.

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

int cmp_int( const void *a, const void *b ) {
    return *(int*)a - *(int*)b;
}

int main() {
    int a[] = { 1, 5, 3, 2, 0, 5, 7, 6 };
    const int n = sizeof(a) / sizeof(a[0]);

    qsort(a, n, sizeof(a[0]), cmp_int);
    printf("%d %d\n", a[n-1], a[n-2]);
}

But that isn't the most efficient because it's O(n log n), meaning as the array gets bigger the number of comparisons gets bigger faster. Not too fast, slower than exponential, but we can do better.

We can do it in O(n) or "linear time" meaning as the array gets bigger the number of comparisons grows at the same rate.

Loop through the array tracking the max, that's the usual way to find the max. When you find a new max, the old max becomes the 2nd highest number.

Instead of having a second loop to find the 2nd highest number, throw in a special case for running into the 2nd highest number.

#include <stdio.h>
#include <limits.h>

int main() {
    int a[] = { 1, 5, 3, 2, 0, 5, 7, 6 };
    // This trick to get the size of an array only works on stack allocated arrays.
    const int n = sizeof(a) / sizeof(a[0]);

    // Initialize them to the smallest possible integer.
    // This avoids having to special case the first elements.
    int max = INT_MIN;
    int second_max = INT_MIN;

    for( int i = 0; i < n; i++ ) {
        // Is it the max?
        if( a[i] > max ) {
            // Make the old max the new 2nd max.
            second_max = max;
            // This is the new max.
            max = a[i];
        }
        // It's not the max, is it the 2nd max?
        else if( a[i] > second_max ) {
            second_max = a[i];
        }
    }

    printf("max: %d, second_max: %d\n", max, second_max);
}

There might be a more elegant way to do it, but that will do, at most, 2n comparisons. At best it will do n.

Note that there's an open question of what to do with { 1, 2, 3, 3 }. Should that return 3, 3 or 2, 3? I'll leave that to you to decide and adjust accordingly.

How to initailize byte array of 100 bytes in java with all 0's

Actually the default value of byte is 0.

Maven version with a property

See the Maven - Users forum 'version' contains an expression but should be a constant. Better way to add a new version?:

here is why this is a bad plan.

the pom that gets deployed will not have the property value resolved, so anyone depending on that pom will pick up the dependency as being the string uninterpolated with the ${ } and much hilarity will ensue in your build process.

in maven 2.1.0 and/or 2.2.0 an attempt was made to deploy poms with resolved properties... this broke more than expected, which is why those two versions are not recommended, 2.2.1 being the recommended 2.x version.

mySQL :: insert into table, data from another table?

for whole row

insert into xyz select * from xyz2 where id="1";

for selected column

insert into xyz(t_id,v_id,f_name) select t_id,v_id,f_name from xyz2 where id="1";

Printing chars and their ASCII-code in C

Try this:

char c = 'a'; // or whatever your character is
printf("%c %d", c, c);

The %c is the format string for a single character, and %d for a digit/integer. By casting the char to an integer, you'll get the ascii value.

how to access downloads folder in android?

You need to set this permission in your manifest.xml file

android.permission.WRITE_EXTERNAL_STORAGE

How to resolve "Waiting for Debugger" message?

I ran into this problem today. After spending most of the day trying to fix it, the only thing that ended up working was to create a new workspace and import my project into it. I hope this helps someone avoid all the trouble that I went through.

How do I push a local Git branch to master branch in the remote?

As an extend to @Eugene's answer another version which will work to push code from local repo to master/develop branch .

Switch to branch ‘master’:

$ git checkout master

Merge from local repo to master:

$ git merge --no-ff FEATURE/<branch_Name>

Push to master:

$ git push

installing vmware tools: location of GCC binary?

Entering: /usr/bin/gcc worked for me.

How can I toggle word wrap in Visual Studio?

Following https://docs.microsoft.com/en-gb/visualstudio/ide/reference/how-to-manage-word-wrap-in-the-editor

When viewing a document: Edit / Advanced / Word Wrap (Ctrl+E, Ctrl+W)

General settings: Tools / Options / Text Editor / All Languages / Word wrap

Or search for 'word wrap' in the Quick Launch box.


Known issues:

If you're familiar with word wrap in Notepad++, Sublime Text, or Visual Studio Code, be aware of the following issues where Visual Studio behaves differently to other editors:

  1. Triple click doesn't select whole line
  2. Cut command doesn't delete whole line
  3. Pressing End key twice does not move cursor to end of line

Unfortunately these bugs have been closed "lower priority". If you'd like these bugs fixed, please vote for the feature request Fix known issues with word wrap.

Using AJAX to pass variable to PHP and retrieve those using AJAX again

In your PhP file there's going to be a variable called $_REQUEST and it contains an array with all the data send from Javascript to PhP using AJAX.

Try this: var_dump($_REQUEST); and check if you're receiving the values.

git clone error: RPC failed; curl 56 OpenSSL SSL_read: SSL_ERROR_SYSCALL, errno 10054

I had the exact same problem while trying to setup a Gitlab pipeline executed by a Docker runner installed on a Raspberry Pi 4

Using nload to follow bandwidth usage within Docker runner container while pipeline was cloning the repo i saw the network usage dropped down to a few bytes per seconds..

After a some deeper investigations i figured out that the Raspberry temperature was too high and the network card start to dysfunction above 50° Celsius.

Adding a fan to my Raspberry solved the issue.

If statements for Checkboxes

private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
    if (checkBoxImage.Checked)
    {
        groupBoxImage.Show();
    }
    else if (!checkBoxImage.Checked)
    {
        groupBoxImage.Hide(); 
    }
}

Common HTTPclient and proxy

Although this question is very old, but I see still there are no exact answer. I will try to answer the question here.

I believe the question in short here is how to set the proxy settings for the Apache commons HttpClient (org.apache.commons.httpclient.HttpClient).

Code snippet below should work :

HttpClient client = new HttpClient();
HostConfiguration hostConfiguration = client.getHostConfiguration();
hostConfiguration.setProxy("localhost", 8080);
client.setHostConfiguration(hostConfiguration);

Remove scroll bar track from ScrollView in Android

These solutions Failed in my case with Relative Layout and If KeyBoard is Open android:scrollbars="none" & android:scrollbarStyle="insideOverlay" also not working.

toolbar is gone, my done button is gone.

not Working

This one is Working for me

myScrollView.setVerticalScrollBarEnabled(false);

SQL update fields of one table from fields of another one

Try Following

Update A a, B b, SET a.column1=b.column1 where b.id=1

EDITED:- Update more than one column

Update A a, B b, SET a.column1=b.column1, a.column2=b.column2 where b.id=1

'DataFrame' object has no attribute 'sort'

sort() was deprecated for DataFrames in favor of either:

sort() was deprecated (but still available) in Pandas with release 0.17 (2015-10-09) with the introduction of sort_values() and sort_index(). It was removed from Pandas with release 0.20 (2017-05-05).

C# equivalent of C++ map<string,double>

Dictionary<string, double> accounts;

Ajax Success and Error function failure

Try this:

$.ajax({
    beforeSend: function() { textreplace(description); },
    type: "POST",  
    url: "updatedjob.php",
    data: "jobID="+ job +"& description="+ description +"& startDate="+ startDate +"& releaseDate="+ releaseDate +"& status="+ status, 
    success: function(){  
        $("form#updatejob").hide(function(){$("div.success").fadeIn();});  
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) { 
        alert("Status: " + textStatus); alert("Error: " + errorThrown); 
    }       
});

The beforeSend property is set to function() { textreplace(description); } instead of textreplace(description). The beforeSend property needs a function.

Fixed positioning in Mobile Safari

See Google's solution to this problem. You basically have to scroll content yourself using JavaScript. Sencha Touch also provides a library for getting this behavior in a very performant manor.

With jQuery, how do I capitalize the first letter of a text field while the user is still editing that field?

I answered this somewhere else . However, here are two function you might want to call on keyup event.

To capitalize first word

  function ucfirst(str,force){
          str=force ? str.toLowerCase() : str;
          return str.replace(/(\b)([a-zA-Z])/,
                   function(firstLetter){
                      return   firstLetter.toUpperCase();
                   });
     }

And to capitalize all words

function ucwords(str,force){
  str=force ? str.toLowerCase() : str;  
  return str.replace(/(\b)([a-zA-Z])/g,
           function(firstLetter){
              return   firstLetter.toUpperCase();
           });
}

As @Darrell Suggested

$('input[type="text"]').keyup(function(evt){

      // force: true to lower case all letter except first
      var cp_value= ucfirst($(this).val(),true) ;

      // to capitalize all words  
      //var cp_value= ucwords($(this).val(),true) ;


      $(this).val(cp_value );

   });

Hope this is helpful

Cheers :)

ng-model for `<input type="file"/>` (with directive DEMO)

I had to do same on multiple input, so i updated @Endy Tjahjono method. It returns an array containing all readed files.

  .directive("fileread", function () {
    return {
      scope: {
        fileread: "="
      },
      link: function (scope, element, attributes) {
        element.bind("change", function (changeEvent) {
          var readers = [] ,
              files = changeEvent.target.files ,
              datas = [] ;
          for ( var i = 0 ; i < files.length ; i++ ) {
            readers[ i ] = new FileReader();
            readers[ i ].onload = function (loadEvent) {
              datas.push( loadEvent.target.result );
              if ( datas.length === files.length ){
                scope.$apply(function () {
                  scope.fileread = datas;
                });
              }
            }
            readers[ i ].readAsDataURL( files[i] );
          }
        });

      }
    }
  });

How can I uninstall npm modules in Node.js?

Use

npm uninstall <package_name>

Example to uninstall express

npm uninstall express

How to Copy Text to Clip Board in Android?

Just write this code:

clipboard.setText(getstring);

Delete from two tables in one query

no need for JOINS:

DELETE m, um FROM messages m, usersmessages um

WHERE m.messageid = 1 

AND m.messageid = um.messageid 

Compare cell contents against string in Excel

If a case-insensitive comparison is acceptable, just use =:

=IF(A1="ENG",1,0)

How to stop IIS asking authentication for default website on localhost

If you want authentication try domainname\administrator as the username.

If you don't want authentication then remove all the tickboxes in the authenticated access section of the direcory security > edit window.

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select * from `songs` where `id` = 5 limit 1)

I am running laravel 5.8 and i experienced the same problem. The solution that worked for me is as follows :

  1. I used bigIncrements('id') to define my primary key.
  2. I used unsignedBigInteger('user_id') to define the foreign referenced key.

        Schema::create('generals', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('general_name');
            $table->string('status');
            $table->timestamps();
        });
    
    
        Schema::create('categories', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('general_id');
            $table->foreign('general_id')->references('id')->on('generals');
            $table->string('category_name');
            $table->string('status');
            $table->timestamps();
        });
    

I hope this helps out.

Converting Decimal to Binary Java

Integer.toBinaryString() is an in-built method and will do quite well.

mysql datatype for telephone number and address

Actually you can use a varchar for a telephone number. You do not need an int because you are not going to perform arithmetic on the numbers.

ES6 modules implementation, how to load a json file

This just works on React & React Native

const data = require('./data/photos.json');

console.log('[-- typeof data --]', typeof data); // object


const fotos = data.xs.map(item => {
    return { uri: item };
});

React passing parameter via onclick event using ES6 syntax

in function component, this works great - a new React user since 2020 :)

handleRemove = (e, id) => {
    //removeById(id);
}

return(<button onClick={(e)=> handleRemove(e, id)}></button> )

How to restart ADB manually from Android Studio

Open task manager and kill adb.exe, now adb will start normally

Staging Deleted files

If you want to simply add all the deleted files to stage then you can use git add .

This is the easiest way right now with git v2.27.0. Note that using * and . are different approaches. Using git add * would only add currently present files whereas git add . would also stage the files deleted with rm command.

It's obvious but worth mentioning that other files which have been modified would also be added to the staging area when you use git add ..

Select folder dialog WPF

I wrote about it on my blog a long time ago, WPF's support for common file dialogs is really bad (or at least is was in 3.5 I didn't check in version 4) - but it's easy to work around it.

You need to add the correct manifest to your application - that will give you a modern style message boxes and folder browser (WinForms FolderBrowserDialog) but not WPF file open/save dialogs, this is described in those 3 posts (if you don't care about the explanation and only want the solution go directly to the 3rd):

Fortunately, the open/save dialogs are very thin wrappers around the Win32 API that is easy to call with the right flags to get the Vista/7 style (after setting the manifest)

Spool Command: Do not output SQL statement to file

Exec the query in TOAD or SQL DEVELOPER

---select /*csv*/ username, user_id, created from all_users;

Save in .SQL format in "C" drive

--- x.sql

execute command

---- set serveroutput on
     spool y.csv
     @c:\x.sql
     spool off;

What is causing this error - "Fatal error: Unable to find local grunt"

Could be a few problems here depending on what version of grunt is being used. Newer versions of grunt actually specify that you have a file named Gruntfile.js (instead of the old grunt.js).

You should have the grunt-cli tool be installed globally (this is done via npm install -g grunt-cli). This allows you to actually run grunt commands from the command line.

Secondly make sure you've installed grunt locally for your project. If you see your package.json doesn't have something like "grunt": "0.4.5" in it then you should do npm install grunt --save in your project directory.

What's the difference between REST & RESTful

REST based Services/Architecture vs. RESTFUL Services/Architecture

To differentiate or compare these 2, you should know what REST is.

REST (REpresentational State Transfer) is basically an architectural style of development having some principles:

  • It should be stateless

  • It should access all the resources from the server using only URI

  • It does not have inbuilt encryption

  • It does not have session

  • It uses one and only one protocol - HTTP

  • For performing CRUD operations, it should use HTTP verbs such as get, post, put and delete

  • It should return the result only in the form of JSON or XML, atom, OData etc. (lightweight data )

REST based services follow some of the above principles and not all

RESTFUL services means it follows all the above principles.

It is similar to the concept of:

Object oriented languages support all the OOP concepts, examples: C++, C#

Object-based languages support some of the OOP features, examples: JavaScript, VB


Example:

ASP Dot NET MVC 4 is REST-Based while Microsoft WEB API is RESTFul.

MVC supports only some of the above REST principles whereas WEB API supports all the above REST Principles.

MVC only supports the following from the REST API

  • We can access the resource using URI

  • It supports the HTTP verb to access the resource from server

  • It can return the results in the form of JSON, XML, that is the HTTPResponse.

However, at the same time in MVC

  • We can use the session

  • We can make it stateful

  • We can return video or image from the controller action method which basically violates the REST principles

That is why MVC is REST-Based whereas WEB API supports all the above principles and is RESTFul.

MYSQL order by both Ascending and Descending sorting

I don't understand what the meaning of ordering with the same column ASC and DESC in the same ORDER BY, but this how you can do it: naam DESC, naam ASC like so:

ORDER BY `product_category_id` DESC,`naam` DESC, `naam` ASC

HTTPS connection Python

If using httplib.HTTPSConnection:

Please take a look at:

Changed in version 2.7.9:

This class now performs all the necessary certificate and hostname checks by default. To revert to the previous, unverified, behavior ssl._create_unverified_context() can be passed to the context parameter. You can use:

if hasattr(ssl, '_create_unverified_context'):
  ssl._create_default_https_context = ssl._create_unverified_context

What is git tag, How to create tags & How to checkout git remote tag(s)

This is bit out of context but in case you are here because you want to tag a specific commit like i do

Here's a command to do that :-

Example:

git tag -a v1.0 7cceb02 -m "Your message here"

Where 7cceb02 is the beginning part of the commit id.

You can then push the tag using git push origin v1.0.

You can do git log to show all the commit id's in your current branch.

lvalue required as left operand of assignment error when using C++

To assign, you should use p=p+1; instead of p+1=p;

int main()
{

   int x[3]={4,5,6};
   int *p=x;
   p=p+1; /*You just needed to switch the terms around*/
   cout<<p<<endl;
   getch();
}

How do you copy the contents of an array to a std::vector in C++ without looping?

Since I can only edit my own answer, I'm going to make a composite answer from the other answers to my question. Thanks to all of you who answered.

Using std::copy, this still iterates in the background, but you don't have to type out the code.

int foo(int* data, int size)
{
   static std::vector<int> my_data; //normally a class variable
   std::copy(data, data + size, std::back_inserter(my_data));
   return 0;
}

Using regular memcpy. This is probably best used for basic data types (i.e. int) but not for more complex arrays of structs or classes.

vector<int> x(size);
memcpy(&x[0], source, size*sizeof(int));

Push item to associative array in PHP

You can use array_merge($array1, $array2) to merge the associative array. Example:

$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_merge($a1,$a2));

Output:

Array ( [0] => red [1] => green [2] => blue [3] => yellow )

How do I get a list of installed CPAN modules?

As you enter your Perl script you have all the installed modules as .pm files below the folders in @INC so a small bash script will do the job for you:

#!/bin/bash

echo -e -n "Content-type: text/plain\n\n"

inc=`perl -e '$, = "\n"; print @INC;'`

for d in $inc
do
   find $d -name '*.pm'
done

Removing array item by value

How about:

if (($key = array_search($id, $items)) !== false) unset($items[$key]);

or for multiple values:

while(($key = array_search($id, $items)) !== false) {
    unset($items[$key]);
}

This would prevent key loss as well, which is a side effect of array_flip().

What does MVW stand for?

It stands indeed for whatever, as in whatever works for you

MVC vs MVVM vs MVP. What a controversial topic that many developers can spend hours and hours debating and arguing about.

For several years +AngularJS was closer to MVC (or rather one of its client-side variants), but over time and thanks to many refactorings and api improvements, it's now closer to MVVM – the $scope object could be considered the ViewModel that is being decorated by a function that we call a Controller.

Being able to categorize a framework and put it into one of the MV* buckets has some advantages. It can help developers get more comfortable with its apis by making it easier to create a mental model that represents the application that is being built with the framework. It can also help to establish terminology that is used by developers.

Having said, I'd rather see developers build kick-ass apps that are well-designed and follow separation of concerns, than see them waste time arguing about MV* nonsense. And for this reason, I hereby declare AngularJS to be MVW framework - Model-View-Whatever. Where Whatever stands for "whatever works for you".

Angular gives you a lot of flexibility to nicely separate presentation logic from business logic and presentation state. Please use it fuel your productivity and application maintainability rather than heated discussions about things that at the end of the day don't matter that much.

How to solve this java.lang.NoClassDefFoundError: org/apache/commons/io/output/DeferredFileOutputStream?

If you are receiving this error in a WebSphere container, then make sure you set your Apps class loading policy correctly. I had to change mine from the default to 'parent last' and also ‘Single class loader for application’ for the WAR policy. This is because in my case the commons-io*.jar was packaged with in the application, so it had to be loaded first.

Using classes with the Arduino

On this page, the Arduino sketch defines a couple of Structs (plus a couple of methods) which are then called in the setup loop and main loop. Simple enough to interpret, even for a barely-literate programmer like me.

Call Activity method from adapter

Yes you can.

In the adapter Add a new Field :

private Context mContext;

In the adapter Constructor add the following code :

public AdapterName(......, Context context) {
  //your code.
  this.mContext = context;
}

In the getView(...) of Adapter:

Button btn = (Button) convertView.findViewById(yourButtonId);
btn.setOnClickListener(new Button.OnClickListener() {
  @Override
  public void onClick(View v) {
    if (mContext instanceof YourActivityName) {
      ((YourActivityName)mContext).yourDesiredMethod();
    }
  }
});

replace with your own class names where you see your code, your activity etc.

If you need to use this same adapter for more than one activity then :

Create an Interface

public interface IMethodCaller {
    void yourDesiredMethod();
}

Implement this interface in activities you require to have this method calling functionality.

Then in Adapter getView(), call like:

Button btn = (Button) convertView.findViewById(yourButtonId);
btn.setOnClickListener(new Button.OnClickListener() {
    @Override
    public void onClick(View v) {
        if (mContext instanceof IMethodCaller) {
            ((IMethodCaller) mContext).yourDesiredMethod();
        }
    }
});

You are done. If you need to use this adapter for activities which does not require this calling mechanism, the code will not execute (If check fails).

How to initialize all members of an array to the same value?

I see no requirements in the question, so the solution must be generic: initialization of an unspecified possibly multidimensional array built from unspecified possibly structure elements with an initial member value:

#include <string.h> 

void array_init( void *start, size_t element_size, size_t elements, void *initval ){
  memcpy(        start,              initval, element_size              );
  memcpy( (char*)start+element_size, start,   element_size*(elements-1) );
}

// testing
#include <stdio.h> 

struct s {
  int a;
  char b;
} array[2][3], init;

int main(){
  init = (struct s){.a = 3, .b = 'x'};
  array_init( array, sizeof(array[0][0]), 2*3, &init );

  for( int i=0; i<2; i++ )
    for( int j=0; j<3; j++ )
      printf("array[%i][%i].a = %i .b = '%c'\n",i,j,array[i][j].a,array[i][j].b);
}

Result:

array[0][0].a = 3 .b = 'x'
array[0][1].a = 3 .b = 'x'
array[0][2].a = 3 .b = 'x'
array[1][0].a = 3 .b = 'x'
array[1][1].a = 3 .b = 'x'
array[1][2].a = 3 .b = 'x'

EDIT: start+element_size changed to (char*)start+element_size

How to get current date in jquery?

You can do this:

    var now = new Date();
    dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT");
     // Saturday, June 9th, 2007, 5:46:21 PM

OR Something like

    var dateObj = new Date();
    var month = dateObj.getUTCMonth();
    var day = dateObj.getUTCDate();
    var year = dateObj.getUTCFullYear();
    var newdate = month + "/" + day + "/" + year;
    alert(newdate);

Apache Spark: The number of cores vs. the number of executors

Short answer: I think tgbaggio is right. You hit HDFS throughput limits on your executors.

I think the answer here may be a little simpler than some of the recommendations here.

The clue for me is in the cluster network graph. For run 1 the utilization is steady at ~50 M bytes/s. For run 3 the steady utilization is doubled, around 100 M bytes/s.

From the cloudera blog post shared by DzOrd, you can see this important quote:

I’ve noticed that the HDFS client has trouble with tons of concurrent threads. A rough guess is that at most five tasks per executor can achieve full write throughput, so it’s good to keep the number of cores per executor below that number.

So, let's do a few calculations see what performance we expect if that is true.


Run 1: 19 GB, 7 cores, 3 executors

  • 3 executors x 7 threads = 21 threads
  • with 7 cores per executor, we expect limited IO to HDFS (maxes out at ~5 cores)
  • effective throughput ~= 3 executors x 5 threads = 15 threads

Run 3: 4 GB, 2 cores, 12 executors

  • 2 executors x 12 threads = 24 threads
  • 2 cores per executor, so hdfs throughput is ok
  • effective throughput ~= 12 executors x 2 threads = 24 threads

If the job is 100% limited by concurrency (the number of threads). We would expect runtime to be perfectly inversely correlated with the number of threads.

ratio_num_threads = nthread_job1 / nthread_job3 = 15/24 = 0.625
inv_ratio_runtime = 1/(duration_job1 / duration_job3) = 1/(50/31) = 31/50 = 0.62

So ratio_num_threads ~= inv_ratio_runtime, and it looks like we are network limited.

This same effect explains the difference between Run 1 and Run 2.


Run 2: 19 GB, 4 cores, 3 executors

  • 3 executors x 4 threads = 12 threads
  • with 4 cores per executor, ok IO to HDFS
  • effective throughput ~= 3 executors x 4 threads = 12 threads

Comparing the number of effective threads and the runtime:

ratio_num_threads = nthread_job2 / nthread_job1 = 12/15 = 0.8
inv_ratio_runtime = 1/(duration_job2 / duration_job1) = 1/(55/50) = 50/55 = 0.91

It's not as perfect as the last comparison, but we still see a similar drop in performance when we lose threads.

Now for the last bit: why is it the case that we get better performance with more threads, esp. more threads than the number of CPUs?

A good explanation of the difference between parallelism (what we get by dividing up data onto multiple CPUs) and concurrency (what we get when we use multiple threads to do work on a single CPU) is provided in this great post by Rob Pike: Concurrency is not parallelism.

The short explanation is that if a Spark job is interacting with a file system or network the CPU spends a lot of time waiting on communication with those interfaces and not spending a lot of time actually "doing work". By giving those CPUs more than 1 task to work on at a time, they are spending less time waiting and more time working, and you see better performance.

How do I install a custom font on an HTML site

If you are using an external style sheet, the code could look something like this:

@font-face { font-family: Junebug; src: url('Junebug.ttf'); } 
.junebug { font-family: Junebug; font-size: 4.2em; }

And should be saved in a separate .css file (eg styles.css). If your .css file is in a location separate from the page code, the actual font file should have the same path as the .css file, NOT the .html or .php web page file. Then the web page needs something like:

<link rel="stylesheet" href="css/styles.css">

in the <head> section of your html page. In this example, the font file should be located in the css folder along with the stylesheet. After this, simply add the class="junebug" inside any tag in your html to use Junebug font in that element.

If you're putting the css in the actual web page, add the style tag in the head of the html like:

<style>
    @font-face { font-family: Junebug; src: url('Junebug.ttf'); } 
</style>

And the actual element style can either be included in the above <style> and called per element by class or id, or you can just declare the style inline with the element. By element I mean <div>, <p>, <h1> or any other element within the html that needs to use the Junebug font. With both of these options, the font file (Junebug.ttf) should be located in the same path as the html page. Of these two options, the best practice would look like:

<style>
    @font-face { font-family: Junebug; src: url('Junebug.ttf'); } 
    .junebug { font-family: Junebug; font-size: 4.2em; }
</style>

and

<h1 class="junebug">This is Junebug</h1>

And the least acceptable way would be:

<style>
    @font-face { font-family: Junebug; src: url('Junebug.ttf'); } 
</style>

and

<h1 style="font-family: Junebug;">This is Junebug</h1>

The reason it's not good to use inline styles is best practice dictates that styles should be kept all in one place so editing is practical. This is also the main reason that I recommend using the very first option of using external style sheets. I hope this helps.

How to change the Spyder editor background to dark?

hey there go to GITHUB link here(https://github.com/joonro/Spyder-Color-Themes) do as the page says u can get the stunning tomorrow night theme

How to set a JavaScript breakpoint from code in Chrome?

I wouldn't recommend debugger; if you just want to kill and stop the javascript code, since debugger; will just temporally freeze your javascript code and not stop it permanently.

If you want to properly kill and stop javascript code at your command use the following:

throw new Error("This error message appears because I placed it");

Link to "pin it" on pinterest without generating a button

I had the same question. This works great in Wordpress!

<a href="//pinterest.com/pin/create/link/?url=<?php the_permalink();?>&amp;description=<?php the_title();?>">Pin this</a>

How to remove all listeners in an element?

I think that the fastest way to do this is to just clone the node, which will remove all event listeners:

var old_element = document.getElementById("btn");
var new_element = old_element.cloneNode(true);
old_element.parentNode.replaceChild(new_element, old_element);

Just be careful, as this will also clear event listeners on all child elements of the node in question, so if you want to preserve that you'll have to resort to explicitly removing listeners one at a time.

How to do a num_rows() on COUNT query in codeigniter?

Doing a COUNT(*) will only give you a singular row containing the number of rows and not the results themselves.

To access COUNT(*) you would need to do

$result = $query->row_array();
$count = $result['COUNT(*)'];

The second option performs much better since it does not need to return a dataset to PHP but instead just a count and therefore is much more optimized.

What is use of c_str function In c++

It's used to make std::string interoperable with C code that requires a null terminated char*.

How can I check if a scrollbar is visible?

I should change a little thing of what Reigel said:

(function($) {
    $.fn.hasScrollBar = function() {
        return this[0] ? this[0].scrollHeight > this.innerHeight() : false;
    }
})(jQuery);

innerHeight counts control's height and its top and bottom paddings

What's the best way to detect a 'touch screen' device using JavaScript?

Many of these work but either require jQuery, or javascript linters complain about the syntax. Considering your initial question asks for a "JavaScript" (not jQuery, not Modernizr) way of solving this, here's a simple function that works every time. It's also about as minimal as you can get.

function isTouchDevice() {
    return !!window.ontouchstart;
}

console.log(isTouchDevice());

One last benefit I'll mention is that this code is framework and device agnostic. Enjoy!

How to override the properties of a CSS class using another CSS class

You should override by increasing Specificity of your styling. There are different ways of increasing the Specificity. Usage of !important which effects specificity, is a bad practice because it breaks natural cascading in your style sheet.

Following diagram taken from css-tricks.com will help you produce right specificity for your element based on a points structure. Whichever specificity has higher points, will win. Sounds like a game - doesn't it?

enter image description here

Checkout sample calculations here on css-tricks.com. This will help you understand the concept very well and it will only take 2 minutes.

If you then like to produce and/or compare different specificities by yourself, try this Specificity Calculator: https://specificity.keegan.st/ or you can just use traditional paper/pencil.

For further reading try MDN Web Docs.

All the best for not using !important.

How to use the 'main' parameter in package.json?

Just think of it as the "starting point".

In a sense of object-oriented programming, say C#, it's the init() or constructor of the object class, that's what "entry point" meant.

For example

public class IamMain  // when export and require this guy
{
    public IamMain()  // this is "main"
    {...}

    ...   // many others such as function, properties, etc.
}

how to convert Lower case letters to upper case letters & and upper case letters to lower case letters

import java.util.Scanner;
class TestClass {
    public static void main(String args[]) throws Exception {
        Scanner s = new Scanner(System.in);
        String str = s.nextLine();
        char[] ch = str.toCharArray();
        for (int i = 0; i < ch.length; i++) {
            if (Character.isUpperCase(ch[i])) {
                ch[i] = Character.toLowerCase(ch[i]);
            } else {
                ch[i] = Character.toUpperCase(ch[i]);
            }
        }
        System.out.println(ch);
    }
}

Applying styles to tables with Twitter Bootstrap

Twitter bootstrap tables can be styled and well designed. You can style your table just adding some classes on your table and it’ll look nice. You might use it on your data reports, showing information, etc.

enter image description here You can use :

basic table
Striped rows
Bordered table
Hover rows
Condensed table
Contextual classes
Responsive tables

Striped rows Table :

    <table class="table table-striped" width="647">
    <thead>
    <tr>
    <th>#</th>
    <th>Name</th>
    <th>Address</th>
    <th>mail</th>
    </tr>
    </thead>
    <tbody>
    <tr>
    <td>1</td>
    <td>Thomas bell</td>
    <td>Brick lane, London</td>
    <td>[email protected]</td>
    </tr>
    <tr>
    <td height="29">2</td>
    <td>Yan Chapel</td>
    <td>Toronto Australia</td>
    <td>[email protected]</td>
    </tr>
    <tr>
    <td>3</td>
    <td>Pit Sampras</td>
    <td>Berlin, Germany</td>
    <td>Pit @yahoo.com</td>
    </tr>
    </tbody>
    </table>

Condensed table :

Compacting a table you need to add class class=”table table-condensed” .

    <table class="table table-condensed" width="647">
    <thead>
    <tr>
    <th>#</th>
    <th>Sample Name</th>
    <th>Address</th>
    <th>Mail</th>
    </tr>
    </thead>
    <tbody>
    <tr>
    <td>1</td>
    <td>Thomas bell</td>
    <td>Brick lane, London</td>
    <td>[email protected]</td>
    </tr>
    <tr>
    <td height="29">2</td>
    <td>Yan Chapel</td>
    <td>Toronto Australia</td>
    <td>[email protected]</td>
    </tr>
    <tr>
    <td>3</td>
    <td>Pit Sampras</td>
    <td>Berlin, Germany</td>
    <td>Pit @yahoo.com</td>
    </tr>
    <tr>
    <td></td>
    <td colspan="3" align="center"></td>
    </tr>
    </tbody>
    </table>

Ref : http://twitterbootstrap.org/twitter-bootstrap-table-example-tutorial

pyplot scatter plot marker size

I also attempted to use 'scatter' initially for this purpose. After quite a bit of wasted time - I settled on the following solution.

import matplotlib.pyplot as plt
input_list = [{'x':100,'y':200,'radius':50, 'color':(0.1,0.2,0.3)}]    
output_list = []   
for point in input_list:
    output_list.append(plt.Circle((point['x'], point['y']), point['radius'], color=point['color'], fill=False))
ax = plt.gca(aspect='equal')
ax.cla()
ax.set_xlim((0, 1000))
ax.set_ylim((0, 1000))
for circle in output_list:    
   ax.add_artist(circle)

enter image description here

This is based on an answer to this question

Comparing strings in Java

Try to use .trim() first, before .equals(), or create a new String var that has these things.

How to check if variable's type matches Type stored in a variable

The other answers all contain significant omissions.

The is operator does not check if the runtime type of the operand is exactly the given type; rather, it checks to see if the runtime type is compatible with the given type:

class Animal {}
class Tiger : Animal {}
...
object x = new Tiger();
bool b1 = x is Tiger; // true
bool b2 = x is Animal; // true also! Every tiger is an animal.

But checking for type identity with reflection checks for identity, not for compatibility

bool b5 = x.GetType() == typeof(Tiger); // true
bool b6 = x.GetType() == typeof(Animal); // false! even though x is an animal

or with the type variable
bool b7 = t == typeof(Tiger); // true
bool b8 = t == typeof(Animal); // false! even though x is an 

If that's not what you want, then you probably want IsAssignableFrom:

bool b9 = typeof(Tiger).IsAssignableFrom(x.GetType()); // true
bool b10 = typeof(Animal).IsAssignableFrom(x.GetType()); // true! A variable of type Animal may be assigned a Tiger.

or with the type variable
bool b11 = t.IsAssignableFrom(x.GetType()); // true
bool b12 = t.IsAssignableFrom(x.GetType()); // true! A 

editing PATH variable on mac

use

~/.bash_profile

or

~/.MacOSX/environment.plist

(see Runtime Configuration Guidelines)

Why can't I duplicate a slice with `copy()`?

The copy() runs for the least length of dst and src, so you must initialize the dst to the desired length.

A := []int{1, 2, 3}
B := make([]int, 3)
copy(B, A)
C := make([]int, 2)
copy(C, A)
fmt.Println(A, B, C)

Output:

[1 2 3] [1 2 3] [1 2]

You can initialize and copy all elements in one line using append() to a nil slice.

x := append([]T{}, []...)

Example:

A := []int{1, 2, 3}
B := append([]int{}, A...)
C := append([]int{}, A[:2]...)
fmt.Println(A, B, C)    

Output:

[1 2 3] [1 2 3] [1 2]

Comparing with allocation+copy(), for greater than 1,000 elements, use append. Actually bellow 1,000 the difference may be neglected, make it a go for rule of thumb unless you have many slices.

BenchmarkCopy1-4                50000000            27.0 ns/op
BenchmarkCopy10-4               30000000            53.3 ns/op
BenchmarkCopy100-4              10000000           229 ns/op
BenchmarkCopy1000-4              1000000          1942 ns/op
BenchmarkCopy10000-4              100000         18009 ns/op
BenchmarkCopy100000-4              10000        220113 ns/op
BenchmarkCopy1000000-4              1000       2028157 ns/op
BenchmarkCopy10000000-4              100      15323924 ns/op
BenchmarkCopy100000000-4               1    1200488116 ns/op
BenchmarkAppend1-4              50000000            34.2 ns/op
BenchmarkAppend10-4             20000000            60.0 ns/op
BenchmarkAppend100-4             5000000           240 ns/op
BenchmarkAppend1000-4            1000000          1832 ns/op
BenchmarkAppend10000-4            100000         13378 ns/op
BenchmarkAppend100000-4            10000        142397 ns/op
BenchmarkAppend1000000-4            2000       1053891 ns/op
BenchmarkAppend10000000-4            200       9500541 ns/op
BenchmarkAppend100000000-4            20     176361861 ns/op

How to specify multiple return types using type-hints

From the documentation

class typing.Union

Union type; Union[X, Y] means either X or Y.

Hence the proper way to represent more than one return data type is

from typing import Union


def foo(client_id: str) -> Union[list,bool]

But do note that typing is not enforced. Python continues to remain a dynamically-typed language. The annotation syntax has been developed to help during the development of the code prior to being released into production. As PEP 484 states, "no type checking happens at runtime."

>>> def foo(a:str) -> list:
...     return("Works")
... 
>>> foo(1)
'Works'

As you can see I am passing a int value and returning a str. However the __annotations__ will be set to the respective values.

>>> foo.__annotations__ 
{'return': <class 'list'>, 'a': <class 'str'>}

Please Go through PEP 483 for more about Type hints. Also see What are Type hints in Python 3.5?

Kindly note that this is available only for Python 3.5 and upwards. This is mentioned clearly in PEP 484.

How to find good looking font color if background color is known?

I have implemented something similar for a different reason - that was code to tell the end user whether the foreground and background colors that they selected would result in unreadable text. To do this, rather than examining the RGB values, I converted the color value to HSL/HSV and then determined by experimentation what my cutoff point was for readability when comparing the fg and bg values. This is something you may want/need to consider.

How to generate random colors in matplotlib?

Here is a more concise version of Ali's answer giving one distinct color per plot :

import matplotlib.pyplot as plt

N = len(data)
cmap = plt.cm.get_cmap("hsv", N+1)
for i in range(N):
    X,Y = data[i]
    plt.scatter(X, Y, c=cmap(i))

Checking whether a variable is an integer or not

I've had this problem before, if your type to use it in a if statement, and let's just say you wanted it to return true, you would enter this into a line, (The bottom line in all that is really needed to be looked at):

In [1]: test = 1

In [2]: test2 = 1.0

In [3]: type(test) == int
Out[3]: True

In [4]: type(test2) == int
Out[4]: False

In [5]: if type(x) == int is True:

You can do the same thing to check if it's a float, if it's true or false, and use to assign a name, (like x if you know what I mean.)

How to call a method in another class in Java?

in School,

public void addTeacherName(classroom classroom, String teacherName) {
    classroom.setTeacherName(teacherName);
}

BTW, use Pascal Case for class names. Also, I would suggest a Map<String, classroom> to map a classroom name to a classroom.

Then, if you use my suggestion, this would work

public void addTeacherName(String className, String teacherName) {
    classrooms.get(className).setTeacherName(teacherName);
}

How to avoid pressing Enter with getchar() for reading a single character only?

getchar() is a standard function that on many platforms requires you to press ENTER to get the input, because the platform buffers input until that key is pressed. Many compilers/platforms support the non-standard getch() that does not care about ENTER (bypasses platform buffering, treats ENTER like just another key).

how to get the value of css style using jquery

You code is correct. replace items with .items as below

<script>
  var n = $(".items").css("left");
  if(n == -900){
    $(".items span").fadeOut("slow");
  }
</script>

Can Twitter Bootstrap alerts fade in as well as out?

I strongly disagree with most answers previously mentioned.

Short answer:

Omit the "in" class and add it using jQuery to fade it in.

See this jsfiddle for an example that fades in alert after 3 seconds http://jsfiddle.net/QAz2U/3/

Long answer:

Although it is true bootstrap doesn't natively support fading in alerts, most answers here use the jQuery fade function, which uses JavaScript to animate (fade) the element. The big advantage of this is cross browser compatibility. The downside is performance (see also: jQuery to call CSS3 fade animation?).

Bootstrap uses CSS3 transitions, which have way better performance. Which is important for mobile devices:

Bootstraps CSS to fade the alert:

.fade {
  opacity: 0;
  -webkit-transition: opacity 0.15s linear;
  -moz-transition: opacity 0.15s linear;
  -o-transition: opacity 0.15s linear;
  transition: opacity 0.15s linear;
}
.fade.in {
  opacity: 1;
}

Why do I think this performance is so important? People using old browsers and hardware will potentially get a choppy transitions with jQuery.fade(). The same goes for old hardware with modern browsers. Using CSS3 transitions people using modern browsers will get a smooth animation even with older hardware, and people using older browsers that don't support CSS transitions will just instantly see the element pop in, which I think is a better user experience than choppy animations.

I came here looking for the same answer as the above: to fade in a bootstrap alert. After some digging in the code and CSS of Bootstrap the answer is rather straightforward. Don't add the "in" class to your alert. And add this using jQuery when you want to fade in your alert.

HTML (notice there is NO in class!)

<div id="myAlert" class="alert success fade" data-alert="alert">
  <!-- rest of alert code goes here -->
</div>

Javascript:

function showAlert(){
  $("#myAlert").addClass("in")
}

Calling the function above function adds the "in" class and fades in the alert using CSS3 transitions :-)

Also see this jsfiddle for an example using a timeout (thanks John Lehmann!): http://jsfiddle.net/QAz2U/3/

How to dockerize maven project? and how many ways to accomplish it?

Here is my contribution.
I will not try to list all tools/libraries/plugins that exist to take advantage of Docker with Maven. Some answers have already done it.
instead of, I will focus on applications typology and the Dockerfile way.
Dockerfile is really a simple and important concept of Docker (all known/public images rely on that) and I think that trying to avoid understanding and using Dockerfiles is not necessarily the better way to enter in the Docker world.

Dockerizing an application depends on the application itself and the goal to reach

1) For applications that we want to go on to run them on installed/standalone Java server (Tomcat, JBoss, etc...)

The road is harder and that is not the ideal target because that adds complexity (we have to manage/maintain the server) and it is less scalable and less fast than embedded servers in terms of build/deploy/undeploy.
But for legacy applications, that may considered as a first step.
Generally, the idea here is to define a Docker image for the server and to define an image per application to deploy.
The docker images for the applications produce the expected WAR/EAR but these are not executed as container and the image for the server application deploys the components produced by these images as deployed applications.
For huge applications (millions of line of codes) with a lot of legacy stuffs, and so hard to migrate to a full spring boot embedded solution, that is really a nice improvement.
I will not detail more that approach since that is for minor use cases of Docker but I wanted to expose the overall idea of that approach because I think that for developers facing to these complex cases, it is great to know that some doors are opened to integrate Docker.

2) For applications that embed/bootstrap the server themselves (Spring Boot with server embedded : Tomcat, Netty, Jetty...)

That is the ideal target with Docker. I specified Spring Boot because that is a really nice framework to do that and that has also a very high level of maintainability but in theory we could use any other Java way to achieve that.
Generally, the idea here is to define a Docker image per application to deploy.
The docker images for the applications produce a JAR or a set of JAR/classes/configuration files and these start a JVM with the application (java command) when we create and start a container from these images.
For new applications or applications not too complex to migrate, that way has to be favored over standalone servers because that is the standard way and the most efficient way of using containers.
I will detail that approach.

Dockerizing a maven application

1) Without Spring Boot

The idea is to create a fat jar with Maven (the maven assembly plugin and the maven shade plugin help for that) that contains both the compiled classes of the application and needed maven dependencies.
Then we can identify two cases :

  • if the application is a desktop or autonomous application (that doesn't need to be deployed on a server) : we could specify as CMD/ENTRYPOINT in the Dockerfile the java execution of the application : java -cp .:/fooPath/* -jar myJar

  • if the application is a server application, for example Tomcat, the idea is the same : to get a fat jar of the application and to run a JVM in the CMD/ENTRYPOINT. But here with an important difference : we need to include some logic and specific libraries (org.apache.tomcat.embed libraries and some others) that starts the embedded server when the main application is started.
    We have a comprehensive guide on the heroku website.
    For the first case (autonomous application), that is a straight and efficient way to use Docker.
    For the second case (server application), that works but that is not straight, may be error prone and is not a very extensible model because you don't place your application in the frame of a mature framework such as Spring Boot that does many of these things for you and also provides a high level of extension.
    But that has a advantage : you have a high level of freedom because you use directly the embedded Tomcat API.

2) With Spring Boot

At last, here we go.
That is both simple, efficient and very well documented.
There are really several approaches to make a Maven/Spring Boot application to run on Docker.
Exposing all of them would be long and maybe boring.
The best choice depends on your requirement.
But whatever the way, the build strategy in terms of docker layers looks like the same.
We want to use a multi stage build : one relying on Maven for the dependency resolution and for build and another one relying on JDK or JRE to start the application.

Build stage (Maven image) :

  • pom copy to the image
  • dependencies and plugins downloads.
    About that, mvn dependency:resolve-plugins chained to mvn dependency:resolve may do the job but not always.
    Why ? Because these plugins and the package execution to package the fat jar may rely on different artifacts/plugins and even for a same artifact/plugin, these may still pull a different version. So a safer approach while potentially slower is resolving dependencies by executing exactly the mvn command used to package the application (which will pull exactly dependencies that you are need) but by skipping the source compilation and by deleting the target folder to make the processing faster and to prevent any undesirable layer change detection for that step.
  • source code copy to the image
  • package the application

Run stage (JDK or JRE image) :

  • copy the jar from the previous stage

Here two examples.

a) A simple way without cache for downloaded maven dependencies

Dockerfile :

########Maven build stage########
FROM maven:3.6-jdk-11 as maven_build
WORKDIR /app

#copy pom
COPY pom.xml .

#resolve maven dependencies
RUN mvn clean package -Dmaven.test.skip -Dmaven.main.skip -Dspring-boot.repackage.skip && rm -r target/

#copy source
COPY src ./src

# build the app (no dependency download here)
RUN mvn clean package  -Dmaven.test.skip

# split the built app into multiple layers to improve layer rebuild
RUN mkdir -p target/docker-packaging && cd target/docker-packaging && jar -xf ../my-app*.jar

########JRE run stage########
FROM openjdk:11.0-jre
WORKDIR /app

#copy built app layer by layer
ARG DOCKER_PACKAGING_DIR=/app/target/docker-packaging
COPY --from=maven_build ${DOCKER_PACKAGING_DIR}/BOOT-INF/lib /app/lib
COPY --from=maven_build ${DOCKER_PACKAGING_DIR}/BOOT-INF/classes /app/classes
COPY --from=maven_build ${DOCKER_PACKAGING_DIR}/META-INF /app/META-INF

#run the app
CMD java -cp .:classes:lib/* \
         -Djava.security.egd=file:/dev/./urandom \
         foo.bar.MySpringBootApplication

Drawback of that solution ? Any changes in the pom.xml means re-creates the whole layer that download and stores the maven dependencies. That is generally not acceptable for applications with many dependencies (and Spring Boot pulls many dependencies), overall if you don't use a maven repository manager during the image build.

b) A more efficient way with cache for maven dependencies downloaded

The approach is here the same but maven dependencies downloads that are cached in the docker builder cache.
The cache operation relies on buildkit (experimental api of docker).
To enable buildkit, the env variable DOCKER_BUILDKIT=1 has to be set (you can do that where you want : .bashrc, command line, docker daemon json file...).

Dockerfile :

# syntax=docker/dockerfile:experimental

########Maven build stage########
FROM maven:3.6-jdk-11 as maven_build
WORKDIR /app

#copy pom
COPY pom.xml .

#copy source
COPY src ./src

# build the app (no dependency download here)
RUN --mount=type=cache,target=/root/.m2  mvn clean package -Dmaven.test.skip

# split the built app into multiple layers to improve layer rebuild
RUN mkdir -p target/docker-packaging && cd target/docker-packaging && jar -xf ../my-app*.jar

########JRE run stage########
FROM openjdk:11.0-jre
WORKDIR /app

#copy built app layer by layer
ARG DOCKER_PACKAGING_DIR=/app/target/docker-packaging
COPY --from=maven_build ${DOCKER_PACKAGING_DIR}/BOOT-INF/lib /app/lib
COPY --from=maven_build ${DOCKER_PACKAGING_DIR}/BOOT-INF/classes /app/classes
COPY --from=maven_build ${DOCKER_PACKAGING_DIR}/META-INF /app/META-INF

#run the app
CMD java -cp .:classes:lib/* \
         -Djava.security.egd=file:/dev/./urandom \
         foo.bar.MySpringBootApplication

How to ignore the first line of data when processing CSV data?

The new 'pandas' package might be more relevant than 'csv'. The code below will read a CSV file, by default interpreting the first line as the column header and find the minimum across columns.

import pandas as pd

data = pd.read_csv('all16.csv')
data.min()

How can I get the assembly file version

When I want to access the application file version (what is set in Assembly Information -> File version), say to set a label's text to it on form load to display the version, I have just used

versionlabel.Text = "Version " + Application.ProductVersion;

This approach requires a reference to System.Windows.Forms.

Reset IntelliJ UI to Default

The existing answers are outdated. This is now doable from the menu:

Window -> Restore Default Layout (shift+f12)

Make sure nothing is currently running, as the Run/Debug window layout will not be reset otherwise.

How to reload .bash_profile from the command line?

I am running Sierra, and was working on this for a while (trying all recommended solutions). I became confounded so eventually tried restarting my computer! It worked

my conclusion is that sometimes a hard reset is necessary

Correct use for angular-translate in controllers

EDIT: Please see the answer from PascalPrecht (the author of angular-translate) for a better solution.


The asynchronous nature of the loading causes the problem. You see, with {{ pageTitle | translate }}, Angular will watch the expression; when the localization data is loaded, the value of the expression changes and the screen is updated.

So, you can do that yourself:

.controller('FirstPageCtrl', ['$scope', '$filter', function ($scope, $filter) {
    $scope.$watch(
        function() { return $filter('translate')('HELLO_WORLD'); },
        function(newval) { $scope.pageTitle = newval; }
    );
});

However, this will run the watched expression on every digest cycle. This is suboptimal and may or may not cause a visible performance degradation. Anyway it is what Angular does, so it cant be that bad...

Way to create multiline comments in Bash?

Here's how I do multiline comments in bash.

This mechanism has two advantages that I appreciate. One is that comments can be nested. The other is that blocks can be enabled by simply commenting out the initiating line.

#!/bin/bash
# : <<'####.block.A'
echo "foo {" 1>&2
fn data1
echo "foo }" 1>&2
: <<'####.block.B'
fn data2 || exit
exit 1
####.block.B
echo "can't happen" 1>&2
####.block.A

In the example above the "B" block is commented out, but the parts of the "A" block that are not the "B" block are not commented out.

Running that example will produce this output:

foo {
./example: line 5: fn: command not found
foo }
can't happen

What is REST? Slightly confused

http://en.wikipedia.org/wiki/Representational_State_Transfer

The basic idea is that instead of having an ongoing connection to the server, you make a request, get some data, show that to a user, but maybe not all of it, and then when the user does something which calls for more data, or to pass some up to the server, the client initiates a change to a new state.

Java way to check if a string is palindrome

Here's a good class :

public class Palindrome {

  public static boolean isPalindrome(String stringToTest) {
    String workingCopy = removeJunk(stringToTest);
    String reversedCopy = reverse(workingCopy);

    return reversedCopy.equalsIgnoreCase(workingCopy);
  }

  protected static String removeJunk(String string) {
    int i, len = string.length();
    StringBuffer dest = new StringBuffer(len);
    char c;

    for (i = (len - 1); i >= 0; i--) {
      c = string.charAt(i);
      if (Character.isLetterOrDigit(c)) {
        dest.append(c);
      }
    }

    return dest.toString();
  }

  protected static String reverse(String string) {
    StringBuffer sb = new StringBuffer(string);

    return sb.reverse().toString();
  }

  public static void main(String[] args) {
    String string = "Madam, I'm Adam.";

    System.out.println();
    System.out.println("Testing whether the following "
        + "string is a palindrome:");
    System.out.println("    " + string);
    System.out.println();

    if (isPalindrome(string)) {
      System.out.println("It IS a palindrome!");
    } else {
      System.out.println("It is NOT a palindrome!");
    }
    System.out.println();
  }
}

Enjoy.

JSON ValueError: Expecting property name: line 1 column 2 (char 1)

I encountered another problem that returns the same error.

Single quote issue

I used a json string with single quotes :

{
    'property': 1
}

But json.loads accepts only double quotes for json properties :

{
    "property": 1
}

Final comma issue

json.loads doesn't accept a final comma:

{
  "property": "text", 
  "property2": "text2",
}

Solution: ast to solve single quote and final comma issues

You can use ast (part of standard library for both Python 2 and 3) for this processing. Here is an example :

import ast
# ast.literal_eval() return a dict object, we must use json.dumps to get JSON string
import json

# Single quote to double with ast.literal_eval()
json_data = "{'property': 'text'}"
json_data = ast.literal_eval(json_data)
print(json.dumps(json_data))
# Displays : {"property": "text"}

# ast.literal_eval() with double quotes
json_data = '{"property": "text"}'
json_data = ast.literal_eval(json_data)
print(json.dumps(json_data))
# Displays : {"property": "text"}

# ast.literal_eval() with final coma
json_data = "{'property': 'text', 'property2': 'text2',}"
json_data = ast.literal_eval(json_data)
print(json.dumps(json_data))
# Displays : {"property2": "text2", "property": "text"}

Using ast will prevent you from single quote and final comma issues by interpet the JSON like Python dictionnary (so you must follow the Python dictionnary syntax). It's a pretty good and safely alternative of eval() function for literal structures.

Python documentation warned us of using large/complex string :

Warning It is possible to crash the Python interpreter with a sufficiently large/complex string due to stack depth limitations in Python’s AST compiler.

json.dumps with single quotes

To use json.dumps with single quotes easily you can use this code:

import ast
import json

data = json.dumps(ast.literal_eval(json_data_single_quote))

ast documentation

ast Python 3 doc

ast Python 2 doc

Tool

If you frequently edit JSON, you may use CodeBeautify. It helps you to fix syntax error and minify/beautify JSON.

I hope it helps.

IntelliJ IDEA generating serialVersionUID

I am using Android Studio 2.1 and I have better consistency of getting the lightbulb by clicking on the class Name and hover over it for a second.

jQuery AJAX form data serialize using PHP

<form method="post" name="myForm" id="myForm">

replace with above form tag remove action from form tag. and set url : "check.php" in ajax in your case first it goes to jQuery ajax then submit again the form. that's why it's creating issue.

i know i'm too late for this reply but i think it would help.

Quickest way to convert a base 10 number to any base in .NET?

I had a similar need, except I needed to do math on the "numbers" as well. I took some of the suggestions here and created a class that will do all this fun stuff. It allows for any unicode character to be used to represent a number and it works with decimals too.

This class is pretty easy to use. Just create a number as a type of New BaseNumber, set a few properties, and your off. The routines take care of switching between base 10 and base x automatically and the value you set is preserved in the base you set it in, so no accuracy is lost (until conversion that is, but even then precision loss should be very minimal since this routine uses Double and Long where ever possible).

I can't command on the speed of this routine. It is probably quite slow, so I'm not sure if it will suit the needs of the one who asked the question, but it certain is flexible, so hopefully someone else can use this.

For anyone else that may need this code for calculating the next column in Excel, I will include the looping code I used that leverages this class.

Public Class BaseNumber

    Private _CharacterArray As List(Of Char)

    Private _BaseXNumber As String
    Private _Base10Number As Double?

    Private NumberBaseLow As Integer
    Private NumberBaseHigh As Integer

    Private DecimalSeparator As Char = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator
    Private GroupSeparator As Char = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberGroupSeparator

    Public Sub UseCapsLetters()
        'http://unicodelookup.com
        TrySetBaseSet(65, 90)
    End Sub

    Public Function GetCharacterArray() As List(Of Char)
        Return _CharacterArray
    End Function

    Public Sub SetCharacterArray(CharacterArray As String)
        _CharacterArray = New List(Of Char)
        _CharacterArray.AddRange(CharacterArray.ToList)

        TrySetBaseSet(_CharacterArray)
    End Sub

    Public Sub SetCharacterArray(CharacterArray As List(Of Char))
        _CharacterArray = CharacterArray
        TrySetBaseSet(_CharacterArray)
    End Sub

    Public Sub SetNumber(Value As String)
        _BaseXNumber = Value
        _Base10Number = Nothing
    End Sub

    Public Sub SetNumber(Value As Double)
        _Base10Number = Value
        _BaseXNumber = Nothing
    End Sub

    Public Function GetBaseXNumber() As String
        If _BaseXNumber IsNot Nothing Then
            Return _BaseXNumber
        Else
            Return ToBaseString()
        End If
    End Function

    Public Function GetBase10Number() As Double
        If _Base10Number IsNot Nothing Then
            Return _Base10Number
        Else
            Return ToBase10()
        End If
    End Function

    Private Sub TrySetBaseSet(Values As List(Of Char))
        For Each value As Char In _BaseXNumber
            If Not Values.Contains(value) Then
                Throw New ArgumentOutOfRangeException("The string has a value, " & value & ", not contained in the selected 'base' set.")
                _CharacterArray.Clear()
                DetermineNumberBase()
            End If
        Next

        _CharacterArray = Values

    End Sub

    Private Sub TrySetBaseSet(LowValue As Integer, HighValue As Integer)

        Dim HighLow As KeyValuePair(Of Integer, Integer) = GetHighLow()

        If HighLow.Key < LowValue OrElse HighLow.Value > HighValue Then
            Throw New ArgumentOutOfRangeException("The string has a value not contained in the selected 'base' set.")
            _CharacterArray.Clear()
            DetermineNumberBase()
        End If

        NumberBaseLow = LowValue
        NumberBaseHigh = HighValue

    End Sub

    Private Function GetHighLow(Optional Values As List(Of Char) = Nothing) As KeyValuePair(Of Integer, Integer)
        If Values Is Nothing Then
            Values = _BaseXNumber.ToList
        End If

        Dim lowestValue As Integer = Convert.ToInt32(Values(0))
        Dim highestValue As Integer = Convert.ToInt32(Values(0))

        Dim currentValue As Integer

        For Each value As Char In Values

            If value <> DecimalSeparator AndAlso value <> GroupSeparator Then
                currentValue = Convert.ToInt32(value)
                If currentValue > highestValue Then
                    highestValue = currentValue
                End If
                If currentValue < lowestValue Then
                    currentValue = lowestValue
                End If
            End If
        Next

        Return New KeyValuePair(Of Integer, Integer)(lowestValue, highestValue)

    End Function

    Public Sub New(BaseXNumber As String)
        _BaseXNumber = BaseXNumber
        DetermineNumberBase()
    End Sub

    Public Sub New(BaseXNumber As String, NumberBase As Integer)
        Me.New(BaseXNumber, Convert.ToInt32("0"c), NumberBase)
    End Sub

    Public Sub New(BaseXNumber As String, NumberBaseLow As Integer, NumberBaseHigh As Integer)
        _BaseXNumber = BaseXNumber
        Me.NumberBaseLow = NumberBaseLow
        Me.NumberBaseHigh = NumberBaseHigh
    End Sub

    Public Sub New(Base10Number As Double)
        _Base10Number = Base10Number
    End Sub

    Private Sub DetermineNumberBase()
        Dim highestValue As Integer

        Dim currentValue As Integer

        For Each value As Char In _BaseXNumber

            currentValue = Convert.ToInt32(value)
            If currentValue > highestValue Then
                highestValue = currentValue
            End If
        Next

        NumberBaseHigh = highestValue
        NumberBaseLow = Convert.ToInt32("0"c) 'assume 0 is the lowest

    End Sub

    Private Function ToBaseString() As String
        Dim Base10Number As Double = _Base10Number

        Dim intPart As Long = Math.Truncate(Base10Number)
        Dim fracPart As Long = (Base10Number - intPart).ToString.Replace(DecimalSeparator, "")

        Dim intPartString As String = ConvertIntToString(intPart)
        Dim fracPartString As String = If(fracPart <> 0, DecimalSeparator & ConvertIntToString(fracPart), "")

        Return intPartString & fracPartString

    End Function

    Private Function ToBase10() As Double
        Dim intPartString As String = _BaseXNumber.Split(DecimalSeparator)(0).Replace(GroupSeparator, "")
        Dim fracPartString As String = If(_BaseXNumber.Contains(DecimalSeparator), _BaseXNumber.Split(DecimalSeparator)(1), "")

        Dim intPart As Long = ConvertStringToInt(intPartString)
        Dim fracPartNumerator As Long = ConvertStringToInt(fracPartString)
        Dim fracPartDenominator As Long = ConvertStringToInt(GetEncodedChar(1) & String.Join("", Enumerable.Repeat(GetEncodedChar(0), fracPartString.ToString.Length)))

        Return Convert.ToDouble(intPart + fracPartNumerator / fracPartDenominator)

    End Function

    Private Function ConvertIntToString(ValueToConvert As Long) As String
        Dim result As String = String.Empty
        Dim targetBase As Long = GetEncodingCharsLength()

        Do
            result = GetEncodedChar(ValueToConvert Mod targetBase) & result
            ValueToConvert = ValueToConvert \ targetBase
        Loop While ValueToConvert > 0

        Return result
    End Function

    Private Function ConvertStringToInt(ValueToConvert As String) As Long
        Dim result As Long
        Dim targetBase As Integer = GetEncodingCharsLength()
        Dim startBase As Integer = GetEncodingCharsStartBase()

        Dim value As Char
        For x As Integer = 0 To ValueToConvert.Length - 1
            value = ValueToConvert(x)
            result += GetDecodedChar(value) * Convert.ToInt32(Math.Pow(GetEncodingCharsLength, ValueToConvert.Length - (x + 1)))
        Next

        Return result

    End Function

    Private Function GetEncodedChar(index As Integer) As Char
        If _CharacterArray IsNot Nothing AndAlso _CharacterArray.Count > 0 Then
            Return _CharacterArray(index)
        Else
            Return Convert.ToChar(index + NumberBaseLow)
        End If
    End Function

    Private Function GetDecodedChar(character As Char) As Integer
        If _CharacterArray IsNot Nothing AndAlso _CharacterArray.Count > 0 Then
            Return _CharacterArray.IndexOf(character)
        Else
            Return Convert.ToInt32(character) - NumberBaseLow
        End If
    End Function

    Private Function GetEncodingCharsLength() As Integer
        If _CharacterArray IsNot Nothing AndAlso _CharacterArray.Count > 0 Then
            Return _CharacterArray.Count
        Else
            Return NumberBaseHigh - NumberBaseLow + 1
        End If
    End Function

    Private Function GetEncodingCharsStartBase() As Integer
        If _CharacterArray IsNot Nothing AndAlso _CharacterArray.Count > 0 Then
            Return GetHighLow.Key
        Else
            Return NumberBaseLow
        End If
    End Function
End Class

And now for the code to loop through Excel columns:

    Public Function GetColumnList(DataSheetID As String) As List(Of String)
        Dim workingColumn As New BaseNumber("A")
        workingColumn.SetCharacterArray("@ABCDEFGHIJKLMNOPQRSTUVWXYZ")

        Dim listOfPopulatedColumns As New List(Of String)
        Dim countOfEmptyColumns As Integer

        Dim colHasData As Boolean
        Dim cellHasData As Boolean

        Do
            colHasData = True
            cellHasData = False
            For r As Integer = 1 To GetMaxRow(DataSheetID)
                cellHasData = cellHasData Or XLGetCellValue(DataSheetID, workingColumn.GetBaseXNumber & r) <> ""
            Next
            colHasData = colHasData And cellHasData

            'keep trying until we get 4 empty columns in a row
            If colHasData Then
                listOfPopulatedColumns.Add(workingColumn.GetBaseXNumber)
                countOfEmptyColumns = 0
            Else
                countOfEmptyColumns += 1
            End If

            'we are already starting with column A, so increment after we check column A
            Do
                workingColumn.SetNumber(workingColumn.GetBase10Number + 1)
            Loop Until Not workingColumn.GetBaseXNumber.Contains("@")

        Loop Until countOfEmptyColumns > 3

        Return listOfPopulatedColumns

    End Function

You'll note the important part of the Excel part is that 0 is identified by a @ in the re-based number. So I just filter out all the numbers that have an @ in them and I get the proper sequence (A, B, C, ..., Z, AA, AB, AC, ...).

log4net hierarchy and logging levels

This might help to understand what is recorded at what level Loggers may be assigned levels. Levels are instances of the log4net.Core.Level class. The following levels are defined in order of increasing severity - Log Level.

Number of levels recorded for each setting level:

 ALL    DEBUG   INFO    WARN    ERROR   FATAL   OFF
•All                        
•DEBUG  •DEBUG                  
•INFO   •INFO   •INFO               
•WARN   •WARN   •WARN   •WARN           
•ERROR  •ERROR  •ERROR  •ERROR  •ERROR      
•FATAL  •FATAL  •FATAL  •FATAL  •FATAL  •FATAL  
•OFF    •OFF    •OFF    •OFF    •OFF    •OFF    •OFF

How can I find whitespace in a String?

Use this code, was better solution for me.

public static boolean containsWhiteSpace(String line){
    boolean space= false; 
    if(line != null){


        for(int i = 0; i < line.length(); i++){

            if(line.charAt(i) == ' '){
            space= true;
            }

        }
    }
    return space;
}

g++ undefined reference to typeinfo

I just spent a few hours on this error, and while the other answers here helped me understand what was going on, they did not fix my particular problem.

I am working on a project that compiles using both clang++ and g++. I was having no linking issues using clang++, but was getting the undefined reference to 'typeinfo for error with g++.

The important point: Linking order MATTERS with g++. If you list the libraries you want to link in an order which is incorrect you can get the typeinfo error.

See this SO question for more details on linking order with gcc/g++.

Java 8 stream's .min() and .max(): why does this compile?

This works because Integer::min resolves to an implementation of the Comparator<Integer> interface.

The method reference of Integer::min resolves to Integer.min(int a, int b), resolved to IntBinaryOperator, and presumably autoboxing occurs somewhere making it a BinaryOperator<Integer>.

And the min() resp max() methods of the Stream<Integer> ask the Comparator<Integer> interface to be implemented.
Now this resolves to the single method Integer compareTo(Integer o1, Integer o2). Which is of type BinaryOperator<Integer>.

And thus the magic has happened as both methods are a BinaryOperator<Integer>.

Is there a Google Voice API?

Well... These are PHP. There is an sms one from google here.

And github has one here.

Another sms one is here. However, this one has a lot more code, so it may take up more space.

How to get the last element of a slice?

Bit less elegant but can also do:

sl[len(sl)-1: len(sl)]

Passing 'this' to an onclick event

In JavaScript this always refers to the “owner” of the function we're executing, or rather, to the object that a function is a method of. When we define our faithful function doSomething() in a page, its owner is the page, or rather, the window object (or global object) of JavaScript.

How does the "this" keyword work?

How do I access my SSH public key?

On Mac/unix and Windows:

ssh-keygen then follow the prompts. It will ask you for a name to the file (say you call it pubkey, for example). Right away, you should have your key fingerprint and your key's randomart image visible to you.

Then just use your favourite text editor and enter command vim pubkey.pub and it (your ssh-rsa key) should be there.

Replace vim with emacs or whatever other editor you have/prefer.

How can I get the "network" time, (from the "Automatic" setting called "Use network-provided values"), NOT the time on the phone?

Try this snippet of code:

String timeSettings = android.provider.Settings.System.getString(
                this.getContentResolver(),
                android.provider.Settings.System.AUTO_TIME);
        if (timeSettings.contentEquals("0")) {
            android.provider.Settings.System.putString(
                    this.getContentResolver(),
                    android.provider.Settings.System.AUTO_TIME, "1");
        }
        Date now = new Date(System.currentTimeMillis());
        Log.d("Date", now.toString());

Make sure to add permission in Manifest

<uses-permission android:name="android.permission.WRITE_SETTINGS"/>

setting multiple column using one update

Just add parameters, split by comma:

UPDATE tablename SET column1 = "value1", column2 = "value2" ....

See also: mySQL manual on UPDATE

OpenSSL and error in reading openssl.conf file

If you installed OpenSSL on Windows together with Git, then add this to your command:

-config "C:\Program Files\Git\usr\ssl\openssl.cnf"

How to execute an .SQL script file using c#

There are two points to considerate.

1) This source code worked for me:

private static string Execute(string credentials, string scriptDir, string scriptFilename)
{ 
  Process process = new Process();
  process.StartInfo.UseShellExecute = false;
  process.StartInfo.WorkingDirectory = scriptDir;
  process.StartInfo.RedirectStandardOutput = true;
  process.StartInfo.FileName = "sqlplus";
  process.StartInfo.Arguments = string.Format("{0} @{1}", credentials, scriptFilename);
  process.StartInfo.CreateNoWindow = true;

  process.Start();
  string output = process.StandardOutput.ReadToEnd();
  process.WaitForExit();

  return output;
}

I set the working directory to the script directory, so that sub scripts within the script also work.

Call it e.g. as Execute("usr/pwd@service", "c:\myscripts", "script.sql")

2) You have to finalize your SQL script with the statement EXIT;

increase legend font size ggplot2

theme(plot.title = element_text(size = 12, face = "bold"),
    legend.title=element_text(size=10), 
    legend.text=element_text(size=9))

fcntl substitute on Windows

The substitute of fcntl on windows are win32api calls. The usage is completely different. It is not some switch you can just flip.

In other words, porting a fcntl-heavy-user module to windows is not trivial. It requires you to analyze what exactly each fcntl call does and then find the equivalent win32api code, if any.

There's also the possibility that some code using fcntl has no windows equivalent, which would require you to change the module api and maybe the structure/paradigm of the program using the module you're porting.

If you provide more details about the fcntl calls people can find windows equivalents.

error: expected declaration or statement at end of input in c

You probably have syntax error. You most likely forgot to put a } or ; somewhere above this function.

Docker: How to use bash with an Alpine based docker image?

Alpine docker image doesn't have bash installed by default. You will need to add following commands to get bash:

RUN apk update && apk add bash

If youre using Alpine 3.3+ then you can just do

RUN apk add --no-cache bash

to keep docker image size small. (Thanks to comment from @sprkysnrky)

Creating a thumbnail from an uploaded image

I know this is an old question, but I stumbled upon the same problem and tried to use the function given in Alex's answer.

But the quality in the jpeg result was too low. So I changed the function a little bit to become more usable in my project and changed the "imagecopyresized" to "imagecopyresampled" (according to this recomendation).

If you are having questions about how to use this function, then try taking a look at the well documented version here.

function createThumbnail($filepath, $thumbpath, $thumbnail_width, $thumbnail_height, $background=false) {
    list($original_width, $original_height, $original_type) = getimagesize($filepath);
    if ($original_width > $original_height) {
        $new_width = $thumbnail_width;
        $new_height = intval($original_height * $new_width / $original_width);
    } else {
        $new_height = $thumbnail_height;
        $new_width = intval($original_width * $new_height / $original_height);
    }
    $dest_x = intval(($thumbnail_width - $new_width) / 2);
    $dest_y = intval(($thumbnail_height - $new_height) / 2);

    if ($original_type === 1) {
        $imgt = "ImageGIF";
        $imgcreatefrom = "ImageCreateFromGIF";
    } else if ($original_type === 2) {
        $imgt = "ImageJPEG";
        $imgcreatefrom = "ImageCreateFromJPEG";
    } else if ($original_type === 3) {
        $imgt = "ImagePNG";
        $imgcreatefrom = "ImageCreateFromPNG";
    } else {
        return false;
    }

    $old_image = $imgcreatefrom($filepath);
    $new_image = imagecreatetruecolor($thumbnail_width, $thumbnail_height); // creates new image, but with a black background

    // figuring out the color for the background
    if(is_array($background) && count($background) === 3) {
      list($red, $green, $blue) = $background;
      $color = imagecolorallocate($new_image, $red, $green, $blue);
      imagefill($new_image, 0, 0, $color);
    // apply transparent background only if is a png image
    } else if($background === 'transparent' && $original_type === 3) {
      imagesavealpha($new_image, TRUE);
      $color = imagecolorallocatealpha($new_image, 0, 0, 0, 127);
      imagefill($new_image, 0, 0, $color);
    }

    imagecopyresampled($new_image, $old_image, $dest_x, $dest_y, 0, 0, $new_width, $new_height, $original_width, $original_height);
    $imgt($new_image, $thumbpath);
    return file_exists($thumbpath);
}

I want to multiply two columns in a pandas DataFrame and add the result into a new column

I think an elegant solution is to use the where method (also see the API docs):

In [37]: values = df.Prices * df.Amount

In [38]: df['Values'] = values.where(df.Action == 'Sell', other=-values)

In [39]: df
Out[39]: 
   Prices  Amount Action  Values
0       3      57   Sell     171
1      89      42   Sell    3738
2      45      70    Buy   -3150
3       6      43   Sell     258
4      60      47   Sell    2820
5      19      16    Buy    -304
6      56      89   Sell    4984
7       3      28    Buy     -84
8      56      69   Sell    3864
9      90      49    Buy   -4410

Further more this should be the fastest solution.