Programs & Examples On #Miktex

MiKTeX is a typesetting system for Microsoft Windows, consisting of an implementation of TeX and a set of related programs.

How does jQuery work when there are multiple elements with the same ID value?

jQuery's id selector only returns one result. The descendant and multiple selectors in the second and third statements are designed to select multiple elements. It's similar to:

Statement 1

var length = document.getElementById('a').length;

...Yields one result.

Statement 2

var length = 0;
for (i=0; i<document.body.childNodes.length; i++) {
    if (document.body.childNodes.item(i).id == 'a') {
        length++;
    }
}

...Yields two results.

Statement 3

var length = document.getElementById('a').length + document.getElementsByTagName('div').length;

...Also yields two results.

Spring get current ApplicationContext

Step 1 :Inject following code in class

@Autowired
private ApplicationContext _applicationContext;

Step 2 : Write Getter & Setter

Step 3: define autowire="byType" in xml file in which bean is defined

XSLT string replace

The rouine is pretty good, however it causes my app to hang, so I needed to add the case:

  <xsl:when test="$text = '' or $replace = ''or not($replace)" >
    <xsl:value-of select="$text" />
    <!-- Prevent thsi routine from hanging -->
  </xsl:when>

before the function gets called recursively.

I got the answer from here: When test hanging in an infinite loop

Thank you!

Git/GitHub can't push to master

GitHub doesn't support pushing over the Git protocol, which is indicated by your use of the URL beginning git://. As the error message says, if you want to push, you should use either the SSH URL [email protected]:my_user_name/my_repo.git or the "smart HTTP" protocol by using the https:// URL that GitHub shows you for your repository.

(Update: to my surprise, some people apparently thought that by this I was suggesting that "https" means "smart HTTP", which I wasn't. Git used to have a "dumb HTTP" protocol which didn't allow pushing before the "smart HTTP" that GitHub uses was introduced - either could be used over either http or https. The differences between the transfer protocols used by Git are explained in the link below.)

If you want to change the URL of origin, you can just do:

git remote set-url origin [email protected]:my_user_name/my_repo.git

or

git remote set-url origin https://github.com/my_user_name/my_repo.git

More information is available in 10.6 Git Internals - Transfer Protocols.

Angular2 - Radio Button Binding

Simplest solution and workaround:

<input name="toRent" type="radio" (click)="setToRentControl(false)">
<input name="toRent" type="radio" (click)="setToRentControl(true)">

setToRentControl(value){
    this.vm.toRent.updateValue(value);
    alert(value); //true/false
}

What's the scope of a variable initialized in an if statement?

Yes, they're in the same "local scope", and actually code like this is common in Python:

if condition:
  x = 'something'
else:
  x = 'something else'

use(x)

Note that x isn't declared or initialized before the condition, like it would be in C or Java, for example.

In other words, Python does not have block-level scopes. Be careful, though, with examples such as

if False:
    x = 3
print(x)

which would clearly raise a NameError exception.

Count the number of occurrences of each letter in string

#include<stdio.h>
#include<string.h>

#define filename "somefile.txt"

int main()
{
    FILE *fp;
    int count[26] = {0}, i, c;  
    char ch;
    char alpha[27] = "abcdefghijklmnopqrstuwxyz";
    fp = fopen(filename,"r");
    if(fp == NULL)
        printf("file not found\n");
    while( (ch = fgetc(fp)) != EOF) {
        c = 0;
        while(alpha[c] != '\0') {

            if(alpha[c] == ch) {
                count[c]++; 
            }
            c++;
        }
    }
    for(i = 0; i<26;i++) {
        printf("character %c occured %d number of times\n",alpha[i], count[i]);
    }
    return 0;
}

How can I tell if a VARCHAR variable contains a substring?

CONTAINS is for a Full Text Indexed field - if not, then use LIKE

How to multiply duration by integer?

It's nice that Go has a Duration type -- having explicitly defined units can prevent real-world problems.

And because of Go's strict type rules, you can't multiply a Duration by an integer -- you must use a cast in order to multiply common types.

/*
MultiplyDuration Hide semantically invalid duration math behind a function
*/
func MultiplyDuration(factor int64, d time.Duration) time.Duration {
    return time.Duration(factor) * d        // method 1 -- multiply in 'Duration'
 // return time.Duration(factor * int64(d)) // method 2 -- multiply in 'int64'
}

The official documentation demonstrates using method #1:

To convert an integer number of units to a Duration, multiply:

seconds := 10
fmt.Print(time.Duration(seconds)*time.Second) // prints 10s

But, of course, multiplying a duration by a duration should not produce a duration -- that's nonsensical on the face of it. Case in point, 5 milliseconds times 5 milliseconds produces 6h56m40s. Attempting to square 5 seconds results in an overflow (and won't even compile if done with constants).

By the way, the int64 representation of Duration in nanoseconds "limits the largest representable duration to approximately 290 years", and this indicates that Duration, like int64, is treated as a signed value: (1<<(64-1))/(1e9*60*60*24*365.25) ~= 292, and that's exactly how it is implemented:

// A Duration represents the elapsed time between two instants
// as an int64 nanosecond count. The representation limits the
// largest representable duration to approximately 290 years.
type Duration int64

So, because we know that the underlying representation of Duration is an int64, performing the cast between int64 and Duration is a sensible NO-OP -- required only to satisfy language rules about mixing types, and it has no effect on the subsequent multiplication operation.

If you don't like the the casting for reasons of purity, bury it in a function call as I have shown above.

How can I check which version of Angular I'm using?

Edit: When this answer was written, there was only AngularJS 1.x. Look in the answers below for Angular versions >= 2.

AngularJS does not have a command line tool.

You can get the version number from the JavaScript file itself.

Header of the current angular.js:

/**
 * @license AngularJS v1.0.6
 * (c) 2010-2012 Google, Inc. http://angularjs.org
 * License: MIT
 */

TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

What the error is telling, is that you can't convert an entire list into an integer. You could get an index from the list and convert that into an integer:

x = ["0", "1", "2"] 
y = int(x[0]) #accessing the zeroth element

If you're trying to convert a whole list into an integer, you are going to have to convert the list into a string first:

x = ["0", "1", "2"]
y = ''.join(x) # converting list into string
z = int(y)

If your list elements are not strings, you'll have to convert them to strings before using str.join:

x = [0, 1, 2]
y = ''.join(map(str, x))
z = int(y)

Also, as stated above, make sure that you're not returning a nested list.

POST Content-Length exceeds the limit

I disagree, but the solution to increase the file size in php.ini or .htaccess won't work if the user sends a file larger than allowed by the server application.

I suggest validating this on the front end. For example:

_x000D_
_x000D_
$(document).ready(function() {
    $ ('#your_input_file_id').bind('change', function() {
        var fileSize = this.files[0].size/1024/1024;
        if (fileSize > 2) { // 2M
            alert('Your custom message for max file size exceeded');
            $('#your_input_file_id').val('');
        }
    });
});
_x000D_
_x000D_
_x000D_

Sum values from an array of key-value pairs in JavaScript

I would use reduce

var myData = new Array(['2013-01-22', 0], ['2013-01-29', 0], ['2013-02-05', 0], ['2013-02-12', 0], ['2013-02-19', 0], ['2013-02-26', 0], ['2013-03-05', 0], ['2013-03-12', 0], ['2013-03-19', 0], ['2013-03-26', 0], ['2013-04-02', 21], ['2013-04-09', 2]);

var sum = myData.reduce(function(a, b) {
    return a + b[1];
}, 0);

$("#result").text(sum);

Available on jsfiddle

Creating multiple objects with different names in a loop to store in an array list

ArrayList<Customer> custArr = new ArrayList<Customer>();
while(youWantToContinue) {
    //get a customerName
    //get an amount
    custArr.add(new Customer(customerName, amount);
}

For this to work... you'll have to fix your constructor...


Assuming your Customer class has variables called name and sale, your constructor should look like this:

public Customer(String customerName, double amount) {
    name = customerName;
    sale = amount;
}

Change your Store class to something more like this:

public class Store {

    private ArrayList<Customer> custArr;

    public new Store() {
        custArr = new ArrayList<Customer>();
    }

    public void addSale(String customerName, double amount) {
        custArr.add(new Customer(customerName, amount));
    }

    public Customer getSaleAtIndex(int index) {
        return custArr.get(index);
    }

    //or if you want the entire ArrayList:
    public ArrayList getCustArr() {
        return custArr;
    }
}

How does Facebook Sharer select Images and other metadata when sharing my URL?

I couldn't get Facebook to pick the right image from a specific post, so I did what's outlined on this page:

https://webapps.stackexchange.com/questions/18468/adding-meta-tags-to-individual-blogger-posts

In other words, something like this:

<b:if cond='data:blog.url == "http://urlofyourpost.com"'>
  <meta content='http://urlofyourimage.png' property='og:image'/>
 </b:if>

Basically, you're going to hard code an if statement into your site's HTML to get it to change the meta content for whatever you've changed for that one post. It's a messy solution, but it works.

How to iterate over the file in python

Just use for x in f: ..., this gives you line after line, is much shorter and readable (partly because it automatically stops when the file ends) and also saves you the rstrip call because the trailing newline is already stipped.

The error is caused by the exit condition, which can never be true: Even if the file is exhausted, readline will return an empty string, not None. Also note that you could still run into trouble with empty lines, e.g. at the end of the file. Adding if line.strip() == "": continue makes the code ignore blank lines, which is propably a good thing anyway.

Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

This worked for me after trying several ways.

In the file node_modules\metro-config\src\defaults\blacklist.js

Replace :

var sharedBlacklist = [
  /node_modules[/\\]react[/\\]dist[/\\].*/,
  /website\/node_modules\/.*/,
  /heapCapture\/bundle\.js/,
  /.*\/__tests__\/.*/
];

with :

var sharedBlacklist = [
  /node_modules[\/\\]react[\/\\]dist[\/\\].*/,
  /website\/node_modules\/.*/,
  /heapCapture\/bundle\.js/,
  /.*\/__tests__\/.*/
];

hope this helps.

How should I load files into my Java application?

public byte[] loadBinaryFile (String name) {
    try {

        DataInputStream dis = new DataInputStream(new FileInputStream(name));
        byte[] theBytes = new byte[dis.available()];
        dis.read(theBytes, 0, dis.available());
        dis.close();
        return theBytes;
    } catch (IOException ex) {
    }
    return null;
} // ()

Tree data structure in C#

Here's my own:

class Program
{
    static void Main(string[] args)
    {
        var tree = new Tree<string>()
            .Begin("Fastfood")
                .Begin("Pizza")
                    .Add("Margherita")
                    .Add("Marinara")
                .End()
                .Begin("Burger")
                    .Add("Cheese burger")
                    .Add("Chili burger")
                    .Add("Rice burger")
                .End()
            .End();

        tree.Nodes.ForEach(p => PrintNode(p, 0));
        Console.ReadKey();
    }

    static void PrintNode<T>(TreeNode<T> node, int level)
    {
        Console.WriteLine("{0}{1}", new string(' ', level * 3), node.Value);
        level++;
        node.Children.ForEach(p => PrintNode(p, level));
    }
}

public class Tree<T>
{
    private Stack<TreeNode<T>> m_Stack = new Stack<TreeNode<T>>();

    public List<TreeNode<T>> Nodes { get; } = new List<TreeNode<T>>();

    public Tree<T> Begin(T val)
    {
        if (m_Stack.Count == 0)
        {
            var node = new TreeNode<T>(val, null);
            Nodes.Add(node);
            m_Stack.Push(node);
        }
        else
        {
            var node = m_Stack.Peek().Add(val);
            m_Stack.Push(node);
        }

        return this;
    }

    public Tree<T> Add(T val)
    {
        m_Stack.Peek().Add(val);
        return this;
    }

    public Tree<T> End()
    {
        m_Stack.Pop();
        return this;
    }
}

public class TreeNode<T>
{
    public T Value { get; }
    public TreeNode<T> Parent { get; }
    public List<TreeNode<T>> Children { get; }

    public TreeNode(T val, TreeNode<T> parent)
    {
        Value = val;
        Parent = parent;
        Children = new List<TreeNode<T>>();
    }

    public TreeNode<T> Add(T val)
    {
        var node = new TreeNode<T>(val, this);
        Children.Add(node);
        return node;
    }
}

Output:

Fastfood
   Pizza
      Margherita
      Marinara
   Burger
      Cheese burger
      Chili burger
      Rice burger

Java generating non-repeating random numbers

In Java 8, if you want to have a list of non-repeating N random integers in range (a, b), where b is exclusive, you can use something like this:

Random random = new Random();
List<Integer> randomNumbers = random.ints(a, b).distinct().limit(N).boxed().collect(Collectors.toList());

What is the equivalent of ngShow and ngHide in Angular 2+?

According to Angular 1 documentation of ngShow and ngHide, both of these directive adds the css style display: none !important;, to the element according to the condition of that directive (for ngShow adds the css on false value, and for ngHide adds the css for true value).

We can achieve this behavior using Angular 2 directive ngClass:

/* style.css */
.hide 
{
    display: none !important;
}

<!-- old angular1 ngShow -->
<div ng-show="ngShowVal"> I'm Angular1 ngShow... </div>

<!-- become new angular2 ngClass -->
<div [ngClass]="{ 'hide': !ngShowVal }"> I'm Angular2 ngShow... </div>

<!-- old angular2 ngHide -->
<div ng-hide="ngHideVal"> I'm Angular1 ngHide... </div>

<!-- become new angular2 ngClass -->
<div [ngClass]="{ 'hide': ngHideVal }"> I'm Angular2 ngHide... </div>

Notice that for show behavior in Angular2 we need to add ! (not) before the ngShowVal, and for hide behavior in Angular2 we don't need to add ! (not) before the ngHideVal.

Python Pandas : group by in group by and average?

If you want to first take mean on the combination of ['cluster', 'org'] and then take mean on cluster groups, you can use:

In [59]: (df.groupby(['cluster', 'org'], as_index=False).mean()
            .groupby('cluster')['time'].mean())
Out[59]:
cluster
1          15
2          54
3           6
Name: time, dtype: int64

If you want the mean of cluster groups only, then you can use:

In [58]: df.groupby(['cluster']).mean()
Out[58]:
              time
cluster
1        12.333333
2        54.000000
3         6.000000

You can also use groupby on ['cluster', 'org'] and then use mean():

In [57]: df.groupby(['cluster', 'org']).mean()
Out[57]:
               time
cluster org
1       a    438886
        c        23
2       d      9874
        h        34
3       w         6

Autonumber value of last inserted row - MS Access / VBA

This is an adaptation from my code for you. I was inspired from developpez.com (Look in the page for : "Pour insérer des données, vaut-il mieux passer par un RecordSet ou par une requête de type INSERT ?"). They explain (with a little French). This way is much faster than the one upper. In the example, this way was 37 times faster. Try it.

Const tableName As String = "InvoiceNumbers"
Const columnIdName As String = "??"
Const columnDateName As String = "date"

Dim rsTable As DAO.recordSet
Dim recordId as long

Set rsTable = CurrentDb.OpenRecordset(tableName)
Call rsTable .AddNew
recordId = CLng(rsTable (columnIdName)) ' Save your Id in a variable
rsTable (columnDateName) = Now()        ' Store your data
rsTable .Update

recordSet.Close

LeCygne

How to assert greater than using JUnit Assert?

When using JUnit asserts, I always make the message nice and clear. It saves huge amounts of time debugging. Doing it this way avoids having to add a added dependency on hamcrest Matchers.

previousTokenValues[1] = "1378994409108";
currentTokenValues[1] = "1378994416509";

Long prev = Long.parseLong(previousTokenValues[1]);
Long curr = Long.parseLong(currentTokenValues[1]);
assertTrue("Previous (" + prev + ") should be greater than current (" + curr + ")", prev > curr);

In Java, how do I parse XML as a String instead of a file?

javadocs show that the parse method is overloaded.

Create a StringStream or InputSource using your string XML and you should be set.

How can I calculate the number of years between two dates?

Probably not the answer you're looking for, but at 2.6kb, I would not try to reinvent the wheel and I'd use something like moment.js. Does not have any dependencies.

The diff method is probably what you want: http://momentjs.com/docs/#/displaying/difference/

How do I convert a TimeSpan to a formatted string?

''' <summary>
''' Return specified Double # (NumDbl) as String using specified Number Format String (FormatStr, 
''' Default = "N0") and Format Provider (FmtProvider, Default = Nothing) followed by space and,  
''' if NumDbl = 1, the specified Singular Unit Name (SglUnitStr), else the Plural Unit Name 
''' (PluralUnitStr).
''' </summary>
''' <param name="NumDbl"></param>
''' <param name="SglUnitStr"></param>
''' <param name="PluralUnitStr"></param>
''' <param name="FormatStr"></param>
''' <param name="FmtProvider"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Function PluralizeUnitsStr( _
    ByVal NumDbl As Double, _
    ByVal SglUnitStr As String, _
    ByVal PluralUnitStr As String, _
    Optional ByVal FormatStr As String = "N0", _
    Optional ByVal FmtProvider As System.IFormatProvider = Nothing _
    ) As String

    PluralizeUnitsStr = NumDbl.ToString(FormatStr, FmtProvider) & " "

    Dim RsltUnitStr As String

    If NumDbl = 1 Then
        RsltUnitStr = SglUnitStr
    Else
        RsltUnitStr = PluralUnitStr
    End If

    PluralizeUnitsStr &= RsltUnitStr

End Function

''' <summary>
''' Info about a # Unit.
''' </summary>
''' <remarks></remarks>
Public Class clsNumUnitInfoItem
    ''' <summary>
    ''' Name of a Singular Unit (i.e. "day", "trillion", "foot")
    ''' </summary>
    ''' <remarks></remarks>
    Public UnitSglStr As String

    ''' <summary>
    ''' Name of a Plural Unit (i.e. "days", "trillion", "feet")
    ''' </summary>
    ''' <remarks></remarks>
    Public UnitPluralStr As String

    ''' <summary>
    ''' # of Units to = 1 of Next Higher (aka Parent) Unit (i.e. 24 "hours", 1000 "million", 
    ''' 5280 "feet")
    ''' </summary>
    ''' <remarks></remarks>
    Public UnitsInParentInt As Integer
End Class ' -- clsNumUnitInfoItem

Dim TimeLongEnUnitInfoItms As clsNumUnitInfoItem() = { _
    New clsNumUnitInfoItem With {.UnitSglStr = "day", .UnitPluralStr = "days", .UnitsInParentInt = 1}, _
    New clsNumUnitInfoItem With {.UnitSglStr = "hour", .UnitPluralStr = "hours", .UnitsInParentInt = 24}, _
    New clsNumUnitInfoItem With {.UnitSglStr = "minute", .UnitPluralStr = "minutes", .UnitsInParentInt = 60}, _
    New clsNumUnitInfoItem With {.UnitSglStr = "second", .UnitPluralStr = "seconds", .UnitsInParentInt = 60}, _
    New clsNumUnitInfoItem With {.UnitSglStr = "millisecond", .UnitPluralStr = "milliseconds", .UnitsInParentInt = 1000} _
    } ' -- Dim TimeLongEnUnitInfoItms

Dim TimeShortEnUnitInfoItms As clsNumUnitInfoItem() = { _
    New clsNumUnitInfoItem With {.UnitSglStr = "day", .UnitPluralStr = "days", .UnitsInParentInt = 1}, _
    New clsNumUnitInfoItem With {.UnitSglStr = "hr", .UnitPluralStr = "hrs", .UnitsInParentInt = 24}, _
    New clsNumUnitInfoItem With {.UnitSglStr = "min", .UnitPluralStr = "mins", .UnitsInParentInt = 60}, _
    New clsNumUnitInfoItem With {.UnitSglStr = "sec", .UnitPluralStr = "secs", .UnitsInParentInt = 60}, _
    New clsNumUnitInfoItem With {.UnitSglStr = "msec", .UnitPluralStr = "msecs", .UnitsInParentInt = 1000} _
    } ' -- Dim TimeShortEnUnitInfoItms

''' <summary>
''' Convert a specified Double Number (NumDbl) to a long (aka verbose) format (i.e. "1 day, 
''' 2 hours, 3 minutes, 4 seconds and 567 milliseconds") with a specified Array of Time Unit 
''' Info Items (TimeUnitInfoItms), Conjunction (ConjStr, Default = "and"), Minimum Unit Level 
''' Shown (MinUnitLevInt) (0 to TimeUnitInfoItms.Length - 1, -1=All), Maximum Unit Level Shown 
''' (MaxUnitLevInt) (-1=All), Maximum # of Unit Levels Shown (MaxNumUnitLevsInt) (1 to 0 to 
''' TimeUnitInfoItms.Length - 1, 0=All) and Round Last Shown Units Up Flag (RoundUpBool).  
''' Suppress leading 0 Unit Levels.
''' </summary>
''' <param name="NumDbl"></param>
''' <param name="NumUnitInfoItms"></param>
''' <param name="ConjStr"></param>
''' <param name="MinUnitLevInt"></param>
''' <param name="MaxUnitLevInt"></param>
''' <param name="MaxNumUnitLevsInt"></param>
''' <param name="RoundUpBool"></param>
''' <param name="FormatStr"></param>
''' <param name="FmtProvider"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Function NumToLongStr( _
    ByVal NumDbl As Double, _
    ByVal NumUnitInfoItms As clsNumUnitInfoItem(), _
    Optional ByVal ConjStr As String = "and", _
    Optional ByVal MinUnitLevInt As Integer = -1, _
    Optional ByVal MaxUnitLevInt As Integer = -1, _
    Optional ByVal MaxNumUnitLevsInt As Integer = 0, _
    Optional ByVal RoundUpBool As Boolean = False, _
    Optional ByVal FormatStr As String = "N0", _
    Optional ByVal FmtProvider As System.IFormatProvider = Nothing _
    ) As String
    NumToLongStr = ""

    Const TUnitDelimStr As String = ", "

    If (MinUnitLevInt < -1) OrElse (MinUnitLevInt >= NumUnitInfoItms.Length) Then
        Throw New Exception("Invalid MinUnitLevInt: " & MaxUnitLevInt)
    End If

    If (MaxUnitLevInt < -1) OrElse (MaxUnitLevInt >= NumUnitInfoItms.Length) Then
        Throw New Exception("Invalid MaxDetailLevelInt: " & MaxUnitLevInt)
    End If

    If (MaxNumUnitLevsInt < 0) OrElse (MaxNumUnitLevsInt > NumUnitInfoItms.Length) Then
        Throw New Exception("Invalid MaxNumUnitLevsInt: " & MaxNumUnitLevsInt)
    End If

    Dim PrevNumUnitsDbl As Double = NumDbl
    Dim CurrUnitLevInt As Integer = -1
    Dim NumUnitLevsShownInt As Integer = 0

    For Each UnitInfoItem In NumUnitInfoItms
        CurrUnitLevInt += 1

        With UnitInfoItem

            Dim CurrNumUnitsDbl As Double = PrevNumUnitsDbl * .UnitsInParentInt
            Dim CurrTruncNumUnitsInt As Integer = Math.Truncate(CurrNumUnitsDbl)
            PrevNumUnitsDbl = CurrNumUnitsDbl
            If CurrUnitLevInt < MinUnitLevInt Then Continue For
            PrevNumUnitsDbl -= CurrTruncNumUnitsInt

            'If (CurrUnitLevInt > TimeUnitInfoItms.Length) _
            '    OrElse _
            '    ( _
            '    (CurrUnitLevInt > MaxUnitLevInt) AndAlso _
            '    (MaxUnitLevInt <> -1) _
            '    ) _
            '    OrElse _
            '    ( _
            '    (NumUnitLevsShownInt + 1 > MaxNumUnitLevsInt) AndAlso _
            '    (MaxNumUnitLevsInt <> 0) _
            '    ) Then Exit For

            If (CurrUnitLevInt = (NumUnitInfoItms.Length - 1)) OrElse _
                (CurrUnitLevInt = MaxUnitLevInt) OrElse _
                ((NumUnitLevsShownInt + 1) = MaxNumUnitLevsInt) Then

                If NumUnitLevsShownInt > 0 Then
                    Dim TUnitDelimStrLenInt As Integer = TUnitDelimStr.Length
                    NumToLongStr = NumToLongStr.Remove( _
                        NumToLongStr.Length - TUnitDelimStrLenInt, _
                        TUnitDelimStrLenInt)
                    NumToLongStr &= " " & ConjStr & " "
                End If

                Dim CurrNunUnitsRoundedInt As Integer
                If RoundUpBool Then
                    If CurrNumUnitsDbl <> CurrTruncNumUnitsInt Then
                        CurrNunUnitsRoundedInt = CurrTruncNumUnitsInt + 1
                    Else
                        CurrNunUnitsRoundedInt = CurrTruncNumUnitsInt
                    End If
                Else
                    CurrNunUnitsRoundedInt = Math.Round( _
                        value:=CurrNumUnitsDbl, mode:=MidpointRounding.AwayFromZero)
                End If

                NumToLongStr &= _
                    PluralizeUnitsStr(CurrNunUnitsRoundedInt, _
                        .UnitSglStr, .UnitPluralStr, FormatStr, FmtProvider)
                Exit For

            Else ' -- Not (MaxUnitLevInt or MaxNumUnitLevsInt)

                If NumUnitLevsShownInt > 0 OrElse CurrTruncNumUnitsInt <> 0 Then
                    NumToLongStr &= _
                        PluralizeUnitsStr(CurrTruncNumUnitsInt, _
                            .UnitSglStr, .UnitPluralStr, FormatStr, FmtProvider) & _
                        TUnitDelimStr
                    NumUnitLevsShownInt += 1
                End If

            End If ' -- Else Not (MaxUnitLevInt or MaxNumUnitLevsInt)

        End With ' -- UnitInfoItem

    Next UnitInfoItem

End Function

''' <summary>
''' Call NumToLongStr with a specified TimeSpan's (TS) TotalDays.
''' </summary>
''' <param name="TS"></param>
''' <param name="TimeUnitInfoItms"></param>
''' <param name="ConjStr"></param>
''' <param name="MinUnitLevInt"></param>
''' <param name="MaxUnitLevInt"></param>
''' <param name="MaxNumUnitLevsInt"></param>
''' <param name="RoundUpBool"></param>
''' <param name="FormatStr"></param>
''' <param name="FmtProvider"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Function TimeSpanToStr( _
    ByVal TS As TimeSpan, _
    ByVal TimeUnitInfoItms As clsNumUnitInfoItem(), _
    Optional ByVal ConjStr As String = "and", _
    Optional ByVal MinUnitLevInt As Integer = -1, _
    Optional ByVal MaxUnitLevInt As Integer = -1, _
    Optional ByVal MaxNumUnitLevsInt As Integer = 0, _
    Optional ByVal RoundUpBool As Boolean = False, _
    Optional ByVal FormatStr As String = "N0", _
    Optional ByVal FmtProvider As System.IFormatProvider = Nothing _
    ) As String

    Return NumToLongStr( _
        NumDbl:=TS.TotalDays, _
        NumUnitInfoItms:=TimeUnitInfoItms, _
        ConjStr:=ConjStr, _
        MinUnitLevInt:=MinUnitLevInt, _
        MaxUnitLevInt:=MaxUnitLevInt, _
        MaxNumUnitLevsInt:=MaxNumUnitLevsInt, _
        RoundUpBool:=RoundUpBool, _
        FormatStr:=FormatStr, _
        FmtProvider:=FmtProvider _
        )

End Function

''' <summary>
''' Call TimeSpanToStr with TimeLongEnUnitInfoItms.
''' </summary>
''' <param name="TS"></param>
''' <param name="MinUnitLevInt"></param>
''' <param name="MaxUnitLevInt"></param>
''' <param name="MaxNumUnitLevsInt"></param>
''' <param name="RoundUpBool"></param>
''' <param name="FormatStr"></param>
''' <param name="FmtProvider"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Function TimeSpanToLongEnStr( _
    ByVal TS As TimeSpan, _
    Optional ByVal MinUnitLevInt As Integer = -1, _
    Optional ByVal MaxUnitLevInt As Integer = -1, _
    Optional ByVal MaxNumUnitLevsInt As Integer = 0, _
    Optional ByVal RoundUpBool As Boolean = False, _
    Optional ByVal FormatStr As String = "N0", _
    Optional ByVal FmtProvider As System.IFormatProvider = Nothing _
    ) As String

    Return TimeSpanToStr( _
        TS:=TS, _
        TimeUnitInfoItms:=TimeLongEnUnitInfoItms, _
        MinUnitLevInt:=MinUnitLevInt, _
        MaxUnitLevInt:=MaxUnitLevInt, _
        MaxNumUnitLevsInt:=MaxNumUnitLevsInt, _
        RoundUpBool:=RoundUpBool, _
        FormatStr:=FormatStr, _
        FmtProvider:=FmtProvider _
        )
End Function

React JS - Uncaught TypeError: this.props.data.map is not a function

try componentDidMount() lifecycle when fetching data

Ionic 2: Cordova is not available. Make sure to include cordova.js or run in a device/simulator (running in emulator)

I also had this same problem.

I build .apk file of the project and installed it into mobile(android) and got it working

Connecting to SQL Server with Visual Studio Express Editions

The only way I was able to get C# Express 2008 to work was to move the database file. So, I opened up SQL Server Management Studio and after dropping the database, I copied the file to my project folder. Then I reattached the database to management studio. Now, when I try to attach to the local copy it works. Apparently, you can not use the same database file more than once.

Calling ASP.NET MVC Action Methods from JavaScript

You can set up your element with

value="@model.productId"

and

onclick= addToWishList(this.value);

Hibernate: Automatically creating/updating the db tables based on entity classes

You might try changing this line in your persistence.xml from

<property name="hbm2ddl.auto" value="create"/>

to:

<property name="hibernate.hbm2ddl.auto" value="update"/>

This is supposed to maintain the schema to follow any changes you make to the Model each time you run the app.

Got this from JavaRanch

Lombok annotations do not compile under Intellij idea

If you're using Eclipse compiler with lombok, this setup finally worked for me:

  • IDEA 14.1
  • Lombok plugin
  • ... / Compiler / Java Compiler > Use Compiler: Eclipse
  • ... / Compiler / Annotation Processors > Enable annotation processing: checked (default configuration)
  • ... / Compiler > Additional build process VM options:(Shared build process VM options) -javaagent:lombok.jar

The most important part is the last one, mine looks like following: enter image description here

Plugin is needed for IntelliJ editor to recognize getters and setters, javaagent is needed for eclipse compiler to compile with lombok.

PostgreSQL: FOREIGN KEY/ON DELETE CASCADE

A foreign key with a cascade delete means that if a record in the parent table is deleted, then the corresponding records in the child table will automatically be deleted. This is called a cascade delete.

You are saying in a opposite way, this is not that when you delete from child table then records will be deleted from parent table.

UPDATE 1:

ON DELETE CASCADE option is to specify whether you want rows deleted in a child table when corresponding rows are deleted in the parent table. If you do not specify cascading deletes, the default behaviour of the database server prevents you from deleting data in a table if other tables reference it.

If you specify this option, later when you delete a row in the parent table, the database server also deletes any rows associated with that row (foreign keys) in a child table. The principal advantage to the cascading-deletes feature is that it allows you to reduce the quantity of SQL statements you need to perform delete actions.

So it's all about what will happen when you delete rows from Parent table not from child table.

So in your case when user removes entries from CATs table then rows will be deleted from books table. :)

Hope this helps you :)

How to add a where clause in a MySQL Insert statement?

I think you are looking for UPDATE and not insert?

UPDATE `users`
SET `username` = 'Jack', `password` = '123'
WHERE `id` = 1

How to check if a "lateinit" variable has been initialized?

kotlin.UninitializedPropertyAccessException: lateinit property clientKeypair has not been initialized

Bytecode says...blah blah..

public final static synthetic access$getClientKeypair$p(Lcom/takharsh/ecdh/MainActivity;)Ljava/security/KeyPair;

`L0
LINENUMBER 11 L0
ALOAD 0
GETFIELD com/takharsh/ecdh/MainActivity.clientKeypair : Ljava/security/KeyPair;
DUP
IFNONNULL L1
LDC "clientKeypair"
INVOKESTATIC kotlin/jvm/internal/Intrinsics.throwUninitializedPropertyAccessException (Ljava/lang/String;)V
    L1
ARETURN

L2 LOCALVARIABLE $this Lcom/takharsh/ecdh/MainActivity; L0 L2 0 MAXSTACK = 2 MAXLOCALS = 1

Kotlin creates an extra local variable of same instance and check if it null or not, if null then throws 'throwUninitializedPropertyAccessException' else return the local object. Above bytecode explained here Solution Since kotlin 1.2 it allows to check weather lateinit var has been initialized or not using .isInitialized

Saving a Excel File into .txt format without quotes

The answer from this question provided the answer to this question much more simply.

Write is a special statement designed to generate machine-readable files that are later consumed with Input.

Use Print to avoid any fiddling with data.

Thank you user GSerg

What issues should be considered when overriding equals and hashCode in Java?

Logically we have:

a.getClass().equals(b.getClass()) && a.equals(b) ? a.hashCode() == b.hashCode()

But not vice-versa!

SQL to Entity Framework Count Group-By

Here is a simple example of group by in .net core 2.1

var query = this.DbContext.Notifications.
            Where(n=> n.Sent == false).
            GroupBy(n => new { n.AppUserId })
            .Select(g => new { AppUserId = g.Key, Count =  g.Count() });

var query2 = from n in this.DbContext.Notifications
            where n.Sent == false
            group n by n.AppUserId into g
            select new { id = g.Key,  Count = g.Count()};

Which translates to:

SELECT [n].[AppUserId], COUNT(*) AS [Count]
FROM [Notifications] AS [n]
WHERE [n].[Sent] = 0
GROUP BY [n].[AppUserId]

How to pass multiple parameters from ajax to mvc controller?

  var data = JSON.stringify
            ({
            'StrContactDetails': Details,
            'IsPrimary': true
            })

How to tell if a <script> tag failed to load

Here is another JQuery-based solution without any timers:

<script type="text/javascript">
function loadScript(url, onsuccess, onerror) {
$.get(url)
    .done(function() {
        // File/url exists
        console.log("JS Loader: file exists, executing $.getScript "+url)
        $.getScript(url, function() {
            if (onsuccess) {
                console.log("JS Loader: Ok, loaded. Calling onsuccess() for " + url);
                onsuccess();
                console.log("JS Loader: done with onsuccess() for " + url);
            } else {
                console.log("JS Loader: Ok, loaded, no onsuccess() callback " + url)
            }
        });
    }).fail(function() {
            // File/url does not exist
            if (onerror) {
                console.error("JS Loader: probably 404 not found. Not calling $.getScript. Calling onerror() for " + url);
                onerror();
                console.error("JS Loader: done with onerror() for " + url);
            } else {
                console.error("JS Loader: probably 404 not found. Not calling $.getScript. No onerror() callback " + url);
            }
    });
}
</script>

Thanks to: https://stackoverflow.com/a/14691735/1243926

Sample usage (original sample from JQuery getScript documentation):

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jQuery.getScript demo</title>
  <style>
  .block {
     background-color: blue;
     width: 150px;
     height: 70px;
     margin: 10px;
  }
  </style>
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>

<button id="go">&raquo; Run</button>
<div class="block"></div>

<script>


function loadScript(url, onsuccess, onerror) {
$.get(url)
    .done(function() {
        // File/url exists
        console.log("JS Loader: file exists, executing $.getScript "+url)
        $.getScript(url, function() {
            if (onsuccess) {
                console.log("JS Loader: Ok, loaded. Calling onsuccess() for " + url);
                onsuccess();
                console.log("JS Loader: done with onsuccess() for " + url);
            } else {
                console.log("JS Loader: Ok, loaded, no onsuccess() callback " + url)
            }
        });
    }).fail(function() {
            // File/url does not exist
            if (onerror) {
                console.error("JS Loader: probably 404 not found. Not calling $.getScript. Calling onerror() for " + url);
                onerror();
                console.error("JS Loader: done with onerror() for " + url);
            } else {
                console.error("JS Loader: probably 404 not found. Not calling $.getScript. No onerror() callback " + url);
            }
    });
}


loadScript("https://raw.github.com/jquery/jquery-color/master/jquery.color.js", function() {
  console.log("loaded jquery-color");
  $( "#go" ).click(function() {
    $( ".block" )
      .animate({
        backgroundColor: "rgb(255, 180, 180)"
      }, 1000 )
      .delay( 500 )
      .animate({
        backgroundColor: "olive"
      }, 1000 )
      .delay( 500 )
      .animate({
        backgroundColor: "#00f"
      }, 1000 );
  });
}, function() { console.error("Cannot load jquery-color"); });


</script>
</body>
</html>

How can I count the rows with data in an Excel sheet?

This is what I finally came up with, which works great!

{=SUM(IF((ISTEXT('Worksheet Name!A:A))+(ISTEXT('CCSA Associates'!E:E)),1,0))-1}

Don't forget since it is an array to type the formula above without the "{}", and to CTRL + SHIFT + ENTER instead of just ENTER for the "{}" to appear and for it to be entered properly.

How can I tell how many objects I've stored in an S3 bucket?

2020/10/22

With AWS Console

Use AWS Cloudwatch's metrics

With AWS CLI

Number of objects:

or:

aws s3api list-objects --bucket <BUCKET_NAME> --prefix "<FOLDER_NAME>" | wc -l

or:

aws s3 ls s3://<BUCKET_NAME>/<FOLDER_NAME>/ --recursive --summarize --human-readable | grep "Total Objects"

or with s4cmd:

s4cmd ls -r s3://<BUCKET_NAME>/<FOLDER_NAME>/ | wc -l

Objects size:

aws s3api list-objects --bucket <BUCKET_NAME> --output json --query "[sum(Contents[].Size), length(Contents[])]" | awk  'NR!=2 {print $0;next}  NR==2 {print $0/1024/1024/1024" GB"}'

or:

aws s3 ls s3://<BUCKET_NAME>/<FOLDER_NAME>/ --recursive --summarize --human-readable | grep "Total Size"

or with s4cmd:

s4cmd du s3://<BUCKET_NAME>

or with CloudWatch metrics:

aws cloudwatch get-metric-statistics --metric-name BucketSizeBytes --namespace AWS/S3 --start-time 2020-10-20T16:00:00Z --end-time 2020-10-22T17:00:00Z --period 3600 --statistics Average --unit Bytes --dimensions Name=BucketName,Value=<BUCKET_NAME> Name=StorageType,Value=StandardStorage --output json | grep "Average"

Swift - encode URL

Swift 3:

let allowedCharacterSet = (CharacterSet(charactersIn: "!*'();:@&=+$,/?%#[] ").inverted)

if let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) {
//do something with escaped string
}

Performing user authentication in Java EE / JSF using j_security_check

The issue HttpServletRequest.login does not set authentication state in session has been fixed in 3.0.1. Update glassfish to the latest version and you're done.

Updating is quite straightforward:

glassfishv3/bin/pkg set-authority -P dev.glassfish.org
glassfishv3/bin/pkg image-update

Remote origin already exists on 'git push' to a new repository

The previous solutions seem to ignore origin, and they only suggest to use another name. When you just want to use git push origin, keep reading.

The problem appears because a wrong order of Git configuration is followed. You might have already added a 'git origin' to your .git configuration.

You can change the remote origin in your Git configuration with the following line:

git remote set-url origin [email protected]:username/projectname.git

This command sets a new URL for the Git repository you want to push to. Important is to fill in your own username and projectname

Changing datagridview cell color dynamically

Considere use DataBindingComplete event for update the style. The next code change the style of the cell:

    private void Grid_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
    {
        this.Grid.Rows[2].Cells[1].Style.BackColor = Color.Green;
    }

How do I set vertical space between list items?

You can use margin. See the example:

http://jsfiddle.net/LthgY/

li{
  margin: 10px 0;
}

What are the differences between 'call-template' and 'apply-templates' in XSL?

The functionality is indeed similar (apart from the calling semantics, where call-template requires a name attribute and a corresponding names template).

However, the parser will not execute the same way.

From MSDN:

Unlike <xsl:apply-templates>, <xsl:call-template> does not change the current node or the current node-list.

Forcing a postback

No, not from code behind. A postback is a request initiated from a page on the client back to itself on the server using the Http POST method. On the server side you can request a redirect but the will be Http GET request.

Which programming language for cloud computing?

Your question is a bit vague about what you are actually thinking about doing. "Cloud computing" can mean almost anything. If you're looking for languages with specific cloud computing advantages, Java has several because it's a compiled language that compiles to operating-system independent byte code.

I also chime in with the others about C++ being a low-level language. Yes, it is. But you're always going to have more than just the C++ language. If you separate both Java and C++ from the classes that come with them, Java and C++ are extremely similar. You have to adopt some rigid criterion like "pointers = low-level, garbage collection = high-level" to make the distinction stick. (And, of course, you can make pointers smart and invisible in C++ and you can use garbage collection in C++ too if you want to.)

"A lambda expression with a statement body cannot be converted to an expression tree"

You can use statement body in lamba expression for IEnumerable collections. try this one:

Obj[] myArray = objects.AsEnumerable().Select(o =>
{
    var someLocalVar = o.someVar;

    return new Obj() 
    { 
        Var1 = someLocalVar,
        Var2 = o.var2 
    };
}).ToArray();

Notice:
Think carefully when using this method, because this way, you will have all query result in memory, that may have unwanted side effects on the rest of your code.

How to group dataframe rows into list in pandas groupby

Building upon @B.M answer, here is a more general version and updated to work with newer library version: (numpy version 1.19.2, pandas version 1.2.1) And this solution can also deal with multi-indices:

However this is not heavily tested, use with caution.

If performance is important go down to numpy level:

import pandas as pd
import numpy as np

np.random.seed(0)
df = pd.DataFrame({'a': np.random.randint(0, 10, 90), 'b': [1,2,3]*30, 'c':list('abcefghij')*10, 'd': list('hij')*30})


def f_multi(df,col_names):
    if not isinstance(col_names,list):
        col_names = [col_names]
        
    values = df.sort_values(col_names).values.T

    col_idcs = [df.columns.get_loc(cn) for cn in col_names]
    other_col_names = [name for idx, name in enumerate(df.columns) if idx not in col_idcs]
    other_col_idcs = [df.columns.get_loc(cn) for cn in other_col_names]

    # split df into indexing colums(=keys) and data colums(=vals)
    keys = values[col_idcs,:]
    vals = values[other_col_idcs,:]
    
    # list of tuple of key pairs
    multikeys = list(zip(*keys))
    
    # remember unique key pairs and ther indices
    ukeys, index = np.unique(multikeys, return_index=True, axis=0)
    
    # split data columns according to those indices
    arrays = np.split(vals, index[1:], axis=1)

    # resulting list of subarrays has same number of subarrays as unique key pairs
    # each subarray has the following shape:
    #    rows = number of non-grouped data columns
    #    cols = number of data points grouped into that unique key pair
    
    # prepare multi index
    idx = pd.MultiIndex.from_arrays(ukeys.T, names=col_names) 

    list_agg_vals = dict()
    for tup in zip(*arrays, other_col_names):
        col_vals = tup[:-1] # first entries are the subarrays from above 
        col_name = tup[-1]  # last entry is data-column name
        
        list_agg_vals[col_name] = col_vals

    df2 = pd.DataFrame(data=list_agg_vals, index=idx)
    return df2

Tests:

In [227]: %timeit f_multi(df, ['a','d'])

2.54 ms ± 64.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [228]: %timeit df.groupby(['a','d']).agg(list)

4.56 ms ± 61.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)


Results:

for the random seed 0 one would get:

enter image description here

How do I perform a GROUP BY on an aliased column in MS-SQL Server?

Given your edited problem description, I'd suggest using COALESCE() instead of that unwieldy CASE expression:

SELECT FullName
FROM (
  SELECT COALESCE(LastName+', '+FirstName, FirstName) AS FullName
  FROM customers
) c
GROUP BY FullName;

How to sort Map values by key in Java?

This code can sort a key-value map in both orders i.e. ascending and descending.

<K, V extends Comparable<V>> Map<K, V> sortByValues
     (final Map<K, V> map, int ascending)
{
     Comparator<K> valueComparator =  new Comparator<K>() {         
        private int ascending;
        public int compare(K k1, K k2) {
            int compare = map.get(k2).compareTo(map.get(k1));
            if (compare == 0) return 1;
            else return ascending*compare;
        }
        public Comparator<K> setParam(int ascending)
        {
            this.ascending = ascending;
            return this;
        }
    }.setParam(ascending);

    Map<K, V> sortedByValues = new TreeMap<K, V>(valueComparator);
    sortedByValues.putAll(map);
    return sortedByValues;
}

As an example:

Map<Integer,Double> recommWarrVals = new HashMap<Integer,Double>();
recommWarrVals = sortByValues(recommWarrVals, 1);  // Ascending order
recommWarrVals = sortByValues(recommWarrVals,-1);  // Descending order

Xcode swift am/pm time to 24 hour format

Here is code for other way around

For Swift 3

 func amAppend(str:String) -> String{
    var temp = str
    var strArr = str.characters.split{$0 == ":"}.map(String.init)
    var hour = Int(strArr[0])!
    var min = Int(strArr[1])!
    if(hour > 12){
        temp = temp + "PM"
    }
    else{
        temp = temp + "AM"
    }
    return temp
}

SQL INSERT INTO from multiple tables

Here is an example if multiple tables don't have common Id, you can create yourself, I use 1 as commonId to create common id so that I can inner join them:

Insert Into #TempResult
select CountA, CountB, CountC  from

(
select Count(A_Id) as CountA, 1 as commonId from tableA
  where ....
  and  ...
  and   ...
) as tempA

inner join
(
select Count(B_Id) as CountB, 1 as commonId from tableB
  where ...
  and ...
  and  ...
 ) as tempB

on tempA.commonId = tempB.commonId

inner join
(
select Count(C_ID) as CountC, 1 as commonId from tableC
where ...
and   ...
) as tempC

on tmepB.commonId = tempC.commonId

--view insert result
select * from #TempResult

reading and parsing a TSV file, then manipulating it for saving as CSV (*efficiently*)

You should use the csv module to read the tab-separated value file. Do not read it into memory in one go. Each row you read has all the information you need to write rows to the output CSV file, after all. Keep the output file open throughout.

import csv

with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
    tsvin = csv.reader(tsvin, delimiter='\t')
    csvout = csv.writer(csvout)

    for row in tsvin:
        count = int(row[4])
        if count > 0:
            csvout.writerows([row[2:4] for _ in range(count)])

or, using the itertools module to do the repeating with itertools.repeat():

from itertools import repeat
import csv

with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
    tsvin = csv.reader(tsvin, delimiter='\t')
    csvout = csv.writer(csvout)

    for row in tsvin:
        count = int(row[4])
        if count > 0:
            csvout.writerows(repeat(row[2:4], count))

How to add a "open git-bash here..." context menu to the windows explorer?

Usually git bash here can be run only on directories so you have to go up a directory and right click on the previous directory then select git bash here (of course on Windows OS).
Note: context menu inside a directory does not have a git bash here option.

how to add values to an array of objects dynamically in javascript?

You have to instantiate the object first. The simplest way is:

var lab =["1","2","3"];
var val = [42,55,51,22];
var data = [];
for(var i=0; i<4; i++)  {
    data.push({label: lab[i], value: val[i]});
}

Or an other, less concise way, but closer to your original code:

for(var i=0; i<4; i++)  {
   data[i] = {};              // creates a new object
   data[i].label = lab[i];
   data[i].value = val[i];    
}

array() will not create a new array (unless you defined that function). Either Array() or new Array() or just [].

I recommend to read the MDN JavaScript Guide.

Converting a char to ASCII?

Uhm, what's wrong with this:

#include <iostream>

using namespace std;

int main(int, char **)
{
    char c = 'A';

    int x = c; // Look ma! No cast!

    cout << "The character '" << c << "' has an ASCII code of " << x << endl;

    return 0;
}

Detect If Browser Tab Has Focus

Cross Browser jQuery Solution! Raw available at GitHub

Fun & Easy to Use!

The following plugin will go through your standard test for various versions of IE, Chrome, Firefox, Safari, etc.. and establish your declared methods accordingly. It also deals with issues such as:

  • onblur|.blur/onfocus|.focus "duplicate" calls
  • window losing focus through selection of alternate app, like word
    • This tends to be undesirable simply because, if you have a bank page open, and it's onblur event tells it to mask the page, then if you open calculator, you can't see the page anymore!
  • Not triggering on page load

Use is as simple as: Scroll Down to 'Run Snippet'

$.winFocus(function(event, isVisible) {
    console.log("Combo\t\t", event, isVisible);
});

//  OR Pass False boolean, and it will not trigger on load,
//  Instead, it will first trigger on first blur of current tab_window
$.winFocus(function(event, isVisible) {
    console.log("Combo\t\t", event, isVisible);
}, false);

//  OR Establish an object having methods "blur" & "focus", and/or "blurFocus"
//  (yes, you can set all 3, tho blurFocus is the only one with an 'isVisible' param)
$.winFocus({
    blur: function(event) {
        console.log("Blur\t\t", event);
    },
    focus: function(event) {
        console.log("Focus\t\t", event);
    }
});

//  OR First method becoms a "blur", second method becoms "focus"!
$.winFocus(function(event) {
    console.log("Blur\t\t", event);
},
function(event) {
    console.log("Focus\t\t", event);
});

_x000D_
_x000D_
/*    Begin Plugin    */_x000D_
;;(function($){$.winFocus||($.extend({winFocus:function(){var a=!0,b=[];$(document).data("winFocus")||$(document).data("winFocus",$.winFocus.init());for(x in arguments)"object"==typeof arguments[x]?(arguments[x].blur&&$.winFocus.methods.blur.push(arguments[x].blur),arguments[x].focus&&$.winFocus.methods.focus.push(arguments[x].focus),arguments[x].blurFocus&&$.winFocus.methods.blurFocus.push(arguments[x].blurFocus),arguments[x].initRun&&(a=arguments[x].initRun)):"function"==typeof arguments[x]?b.push(arguments[x]):_x000D_
"boolean"==typeof arguments[x]&&(a=arguments[x]);b&&(1==b.length?$.winFocus.methods.blurFocus.push(b[0]):($.winFocus.methods.blur.push(b[0]),$.winFocus.methods.focus.push(b[1])));if(a)$.winFocus.methods.onChange()}}),$.winFocus.init=function(){$.winFocus.props.hidden in document?document.addEventListener("visibilitychange",$.winFocus.methods.onChange):($.winFocus.props.hidden="mozHidden")in document?document.addEventListener("mozvisibilitychange",$.winFocus.methods.onChange):($.winFocus.props.hidden=_x000D_
"webkitHidden")in document?document.addEventListener("webkitvisibilitychange",$.winFocus.methods.onChange):($.winFocus.props.hidden="msHidden")in document?document.addEventListener("msvisibilitychange",$.winFocus.methods.onChange):($.winFocus.props.hidden="onfocusin")in document?document.onfocusin=document.onfocusout=$.winFocus.methods.onChange:window.onpageshow=window.onpagehide=window.onfocus=window.onblur=$.winFocus.methods.onChange;return $.winFocus},$.winFocus.methods={blurFocus:[],blur:[],focus:[],_x000D_
exeCB:function(a){$.winFocus.methods.blurFocus&&$.each($.winFocus.methods.blurFocus,function(b,c){this.apply($.winFocus,[a,!a.hidden])});a.hidden&&$.winFocus.methods.blur&&$.each($.winFocus.methods.blur,function(b,c){this.apply($.winFocus,[a])});!a.hidden&&$.winFocus.methods.focus&&$.each($.winFocus.methods.focus,function(b,c){this.apply($.winFocus,[a])})},onChange:function(a){var b={focus:!1,focusin:!1,pageshow:!1,blur:!0,focusout:!0,pagehide:!0};if(a=a||window.event)a.hidden=a.type in b?b[a.type]:_x000D_
document[$.winFocus.props.hidden],$(window).data("visible",!a.hidden),$.winFocus.methods.exeCB(a);else try{$.winFocus.methods.onChange.call(document,new Event("visibilitychange"))}catch(c){}}},$.winFocus.props={hidden:"hidden"})})(jQuery);_x000D_
/*    End Plugin      */_x000D_
_x000D_
// Simple example_x000D_
$(function() {_x000D_
 $.winFocus(function(event, isVisible) {_x000D_
  $('td tbody').empty();_x000D_
  $.each(event, function(i) {_x000D_
   $('td tbody').append(_x000D_
    $('<tr />').append(_x000D_
     $('<th />', { text: i }),_x000D_
     $('<td />', { text: this.toString() })_x000D_
    )_x000D_
   )_x000D_
  });_x000D_
  if (isVisible) _x000D_
   $("#isVisible").stop().delay(100).fadeOut('fast', function(e) {_x000D_
    $('body').addClass('visible');_x000D_
    $(this).stop().text('TRUE').fadeIn('slow');_x000D_
   });_x000D_
  else {_x000D_
   $('body').removeClass('visible');_x000D_
   $("#isVisible").text('FALSE');_x000D_
  }_x000D_
 });_x000D_
})
_x000D_
body { background: #AAF; }_x000D_
table { width: 100%; }_x000D_
table table { border-collapse: collapse; margin: 0 auto; width: auto; }_x000D_
tbody > tr > th { text-align: right; }_x000D_
td { width: 50%; }_x000D_
th, td { padding: .1em .5em; }_x000D_
td th, td td { border: 1px solid; }_x000D_
.visible { background: #FFA; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<h3>See Console for Event Object Returned</h3>_x000D_
<table>_x000D_
    <tr>_x000D_
        <th><p>Is Visible?</p></th>_x000D_
        <td><p id="isVisible">TRUE</p></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td colspan="2">_x000D_
            <table>_x000D_
                <thead>_x000D_
                    <tr>_x000D_
                        <th colspan="2">Event Data <span style="font-size: .8em;">{ See Console for More Details }</span></th>_x000D_
                    </tr>_x000D_
                </thead>_x000D_
                <tbody></tbody>_x000D_
            </table>_x000D_
        </td>_x000D_
    </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How to use split?

If it is the basic JavaScript split function, look at documentation, JavaScript split() Method.

Basically, you just do this:

var array = myString.split(' -- ')

Then your two values are stored in the array - you can get the values like this:

var firstValue = array[0];
var secondValue = array[1];

Cannot use Server.MapPath

You need to add reference (System.Web) Reference to System.Web

How to set menu to Toolbar in Android

Here is a fuller answer as a reference to future visitors. I usually use a support toolbar but it works just as well either way.

enter image description here

1. Make a menu xml

This is going to be in res/menu/main_menu.

  • Right click the res folder and choose New > Android Resource File.
  • Type main_menu for the File name.
  • Choose Menu for the Resource type.

Paste in the following content as a starter.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_add"
        android:icon="@drawable/ic_add"
        app:showAsAction="ifRoom"
        android:title="Add">
    </item>
    <item
        android:id="@+id/action_settings"
        app:showAsAction="never"
        android:title="Settings">
    </item>
</menu>

You can right click res and choose New image asset to create the ic_add icon.

2. Inflate the menu

In your activity add the following method.

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main_menu, menu);
    return true;
}

3. Handle menu clicks

Also in your Activity, add the following method:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
        case R.id.action_add:
            addSomething();
            return true;
        case R.id.action_settings:
            startSettings();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

Further reading

Insert entire DataTable into database at once instead of row by row?

Consider this approach, you don't need a for loop:

using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection))
{
    bulkCopy.DestinationTableName = 
        "dbo.BulkCopyDemoMatchingColumns";

    try
    {
        // Write from the source to the destination.
        bulkCopy.WriteToServer(ExitingSqlTableName);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

Python list subtraction operation

This example subtracts two lists:

# List of pairs of points
list = []
list.append([(602, 336), (624, 365)])
list.append([(635, 336), (654, 365)])
list.append([(642, 342), (648, 358)])
list.append([(644, 344), (646, 356)])
list.append([(653, 337), (671, 365)])
list.append([(728, 13), (739, 32)])
list.append([(756, 59), (767, 79)])

itens_to_remove = []
itens_to_remove.append([(642, 342), (648, 358)])
itens_to_remove.append([(644, 344), (646, 356)])

print("Initial List Size: ", len(list))

for a in itens_to_remove:
    for b in list:
        if a == b :
            list.remove(b)

print("Final List Size: ", len(list))

Why is there still a row limit in Microsoft Excel?

In a word - speed. An index for up to a million rows fits in a 32-bit word, so it can be used efficiently on 32-bit processors. Function arguments that fit in a CPU register are extremely efficient, while ones that are larger require accessing memory on each function call, a far slower operation. Updating a spreadsheet can be an intensive operation involving many cell references, so speed is important. Besides, the Excel team expects that anyone dealing with more than a million rows will be using a database rather than a spreadsheet.

run a python script in terminal without the python command

You use a shebang line at the start of your script:

#!/usr/bin/env python

make the file executable:

chmod +x arbitraryname

and put it in a directory on your PATH (can be a symlink):

cd ~/bin/
ln -s ~/some/path/to/myscript/arbitraryname

Delete commit on gitlab

  1. git reset --hard CommitId
  2. git push -f origin master

1st command will rest your head to commitid and 2nd command will delete all commit after that commit id on master branch.

Note: Don't forget to add -f in push otherwise it will be rejected.

How to include Authorization header in cURL POST HTTP Request in PHP?

@jason-mccreary is totally right. Besides I recommend you this code to get more info in case of malfunction:

$rest = curl_exec($crl);

if ($rest === false)
{
    // throw new Exception('Curl error: ' . curl_error($crl));
    print_r('Curl error: ' . curl_error($crl));
}

curl_close($crl);
print_r($rest);

EDIT 1

To debug you can set CURLOPT_HEADER to true to check HTTP response with firebug::net or similar.

curl_setopt($crl, CURLOPT_HEADER, true);

EDIT 2

About Curl error: SSL certificate problem, verify that the CA cert is OK try adding this headers (just to debug, in a production enviroment you should keep these options in true):

curl_setopt($crl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($crl, CURLOPT_SSL_VERIFYPEER, false);

What is the difference between private and protected members of C++ classes?

private and protected access modifiers are one and same only that protected members of the base class can be accessed outside the scope of the base class in the child(derived)class. It also applies the same to inheritance . But with the private modifier the members of the base class can only be accessed in the scope or code of the base class and its friend functions only''''

How to find the operating system version using JavaScript?

If you list all of window.navigator's properties using

_x000D_
_x000D_
console.log(navigator);
_x000D_
_x000D_
_x000D_

You'll see something like this

# platform = Win32
# appCodeName = Mozilla
# appName = Netscape
# appVersion = 5.0 (Windows; en-US)
# language = en-US
# mimeTypes = [object MimeTypeArray]
# oscpu = Windows NT 5.1
# vendor = Firefox
# vendorSub = 1.0.7
# product = Gecko
# productSub = 20050915
# plugins = [object PluginArray]
# securityPolicy =
# userAgent = Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.12) Gecko/20050915 Firefox/1.0.7
# cookieEnabled = true
# javaEnabled = function javaEnabled() { [native code] }
# taintEnabled = function taintEnabled() { [native code] }
# preference = function preference() { [native code] }

Note that oscpu attribute gives you the Windows version. Also, you should know that:

'Windows 3.11' => 'Win16',
'Windows 95' => '(Windows 95)|(Win95)|(Windows_95)',
'Windows 98' => '(Windows 98)|(Win98)',
'Windows 2000' => '(Windows NT 5.0)|(Windows 2000)',
'Windows XP' => '(Windows NT 5.1)|(Windows XP)',
'Windows Server 2003' => '(Windows NT 5.2)',
'Windows Vista' => '(Windows NT 6.0)',
'Windows 7' => '(Windows NT 6.1)',
'Windows 8' => '(Windows NT 6.2)|(WOW64)',
'Windows 10' => '(Windows 10.0)|(Windows NT 10.0)',
'Windows NT 4.0' => '(Windows NT 4.0)|(WinNT4.0)|(WinNT)|(Windows NT)',
'Windows ME' => 'Windows ME',
'Open BSD' => 'OpenBSD',
'Sun OS' => 'SunOS',
'Linux' => '(Linux)|(X11)',
'Mac OS' => '(Mac_PowerPC)|(Macintosh)',
'QNX' => 'QNX',
'BeOS' => 'BeOS',
'OS/2' => 'OS/2',
'Search Bot'=>'(nuhk)|(Googlebot)|(Yammybot)|(Openbot)|(Slurp)|(MSNBot)|(Ask Jeeves/Teoma)|(ia_archiver)'

Executing JavaScript without a browser?

JSDB, available for Linux, Windows, and Mac should fit the bill pretty well. It uses Mozilla's Spidermonkey Javascript engine and seems to be less of a hassle to install compared to node.js (at least last time I tried node.js a couple of years ago).

I found JSDB from this interesting list of Javascript shells: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Shells

Skipping Iterations in Python

For this specific use-case using try..except..else is the cleanest solution, the else clause will be executed if no exception was raised.

NOTE: The else clause must follow all except clauses

for i in iterator:
    try:
        # Do something.
    except:
        # Handle exception
    else:
        # Continue doing something

mysqli_select_db() expects parameter 1 to be mysqli, string given

Your arguments are in the wrong order. The connection comes first according to the docs

<?php
require("constants.php");

// 1. Create a database connection
$connection = mysqli_connect(DB_SERVER,DB_USER,DB_PASS);

if (!$connection) {
    error_log("Failed to connect to MySQL: " . mysqli_error($connection));
    die('Internal server error');
}

// 2. Select a database to use 
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
    error_log("Database selection failed: " . mysqli_error($connection));
    die('Internal server error');
}

?>

Combining two Series into a DataFrame in pandas

If I may answer this.

The fundamentals behind converting series to data frame is to understand that

1. At conceptual level, every column in data frame is a series.

2. And, every column name is a key name that maps to a series.

If you keep above two concepts in mind, you can think of many ways to convert series to data frame. One easy solution will be like this:

Create two series here

import pandas as pd

series_1 = pd.Series(list(range(10)))

series_2 = pd.Series(list(range(20,30)))

Create an empty data frame with just desired column names

df = pd.DataFrame(columns = ['Column_name#1', 'Column_name#1'])

Put series value inside data frame using mapping concept

df['Column_name#1'] = series_1

df['Column_name#2'] = series_2

Check results now

df.head(5)

Using a global variable with a thread

Thanks so much Jason Pan for suggesting that method. The thread1 if statement is not atomic, so that while that statement executes, it's possible for thread2 to intrude on thread1, allowing non-reachable code to be reached. I've organized ideas from the prior posts into a complete demonstration program (below) that I ran with Python 2.7.

With some thoughtful analysis I'm sure we could gain further insight, but for now I think it's important to demonstrate what happens when non-atomic behavior meets threading.

# ThreadTest01.py - Demonstrates that if non-atomic actions on
# global variables are protected, task can intrude on each other.
from threading import Thread
import time

# global variable
a = 0; NN = 100

def thread1(threadname):
    while True:
      if a % 2 and not a % 2:
          print("unreachable.")
    # end of thread1

def thread2(threadname):
    global a
    for _ in range(NN):
        a += 1
        time.sleep(0.1)
    # end of thread2

thread1 = Thread(target=thread1, args=("Thread1",))
thread2 = Thread(target=thread2, args=("Thread2",))

thread1.start()
thread2.start()

thread2.join()
# end of ThreadTest01.py

As predicted, in running the example, the "unreachable" code sometimes is actually reached, producing output.

Just to add, when I inserted a lock acquire/release pair into thread1 I found that the probability of having the "unreachable" message print was greatly reduced. To see the message I reduced the sleep time to 0.01 sec and increased NN to 1000.

With a lock acquire/release pair in thread1 I didn't expect to see the message at all, but it's there. After I inserted a lock acquire/release pair also into thread2, the message no longer appeared. In hind signt, the increment statement in thread2 probably also is non-atomic.

How to read line by line of a text area HTML tag

This would give you all valid numeric values in lines. You can change the loop to validate, strip out invalid characters, etc - whichever you want.

var lines = [];
$('#my_textarea_selector').val().split("\n").each(function ()
{
    if (parseInt($(this) != 'NaN')
        lines[] = parseInt($(this));
}

ModuleNotFoundError: No module named 'sklearn'

I did the following:

import sys
!{sys.executable} -m pip install sklearn

ffmpeg - Converting MOV files to MP4

The command to just stream it to a new container (mp4) needed by some applications like Adobe Premiere Pro without encoding (fast) is:

ffmpeg -i input.mov -qscale 0 output.mp4

Alternative as mentioned in the comments, which re-encodes with best quaility (-qscale 0):

ffmpeg -i input.mov -q:v 0 output.mp4

Android - How to achieve setOnClickListener in Kotlin?

A simple way would be to register a click listener and create a click listener with a lambda expression.

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    // click listener registered
    myButton.setOnClickListener(clickListener)
}

And implement the clickListener:

private val clickListener: View.OnClickListener = View.OnClickListener { _ ->
    // do something here
}

You can replace _ with a name if you need the view to use it. For example, you need to check the id of click listener.

private val clickListener: View.OnClickListener = View.OnClickListener { view ->
    if(view.id == login.id) {
        // do something here
    }
}

Trying to SSH into an Amazon Ec2 instance - permission error

ssh -i /.pem user@host-machine-IP

I think it's because either you have entered wrong credentials or, you are using a public key rather than private key or, your port permissions are open for ALL to ssh. This is bad for Amazon.

Rails: How to run `rails generate scaffold` when the model already exists?

TL;DR: rails g scaffold_controller <name>

Even though you already have a model, you can still generate the necessary controller and migration files by using the rails generate option. If you run rails generate -h you can see all of the options available to you.

Rails:
  controller
  generator
  helper
  integration_test
  mailer
  migration
  model
  observer
  performance_test
  plugin
  resource
  scaffold
  scaffold_controller
  session_migration
  stylesheets

If you'd like to generate a controller scaffold for your model, see scaffold_controller. Just for clarity, here's the description on that:

Stubs out a scaffolded controller and its views. Pass the model name, either CamelCased or under_scored, and a list of views as arguments. The controller name is retrieved as a pluralized version of the model name.

To create a controller within a module, specify the model name as a path like 'parent_module/controller_name'.

This generates a controller class in app/controllers and invokes helper, template engine and test framework generators.

To create your resource, you'd use the resource generator, and to create a migration, you can also see the migration generator (see, there's a pattern to all of this madness). These provide options to create the missing files to build a resource. Alternatively you can just run rails generate scaffold with the --skip option to skip any files which exist :)

I recommend spending some time looking at the options inside of the generators. They're something I don't feel are documented extremely well in books and such, but they're very handy.

How do I iterate over an NSArray?

For OS X 10.4.x and previous:

 int i;
 for (i = 0; i < [myArray count]; i++) {
   id myArrayElement = [myArray objectAtIndex:i];
   ...do something useful with myArrayElement
 }

For OS X 10.5.x (or iPhone) and beyond:

for (id myArrayElement in myArray) {
   ...do something useful with myArrayElement
}

How can I truncate a double to only two decimal places in Java?

If, for whatever reason, you don't want to use a BigDecimal you can cast your double to an int to truncate it.

If you want to truncate to the Ones place:

  • simply cast to int

To the Tenths place:

  • multiply by ten
  • cast to int
  • cast back to double
  • and divide by ten.

Hundreths place

  • multiply and divide by 100 etc.

Example:

static double truncateTo( double unroundedNumber, int decimalPlaces ){
    int truncatedNumberInt = (int)( unroundedNumber * Math.pow( 10, decimalPlaces ) );
    double truncatedNumber = (double)( truncatedNumberInt / Math.pow( 10, decimalPlaces ) );
    return truncatedNumber;
}

In this example, decimalPlaces would be the number of places PAST the ones place you wish to go, so 1 would round to the tenths place, 2 to the hundredths, and so on (0 rounds to the ones place, and negative one to the tens, etc.)

Java: How to convert a File object to a String object in java?

Why you just not read the File line by line and add it to a StringBuffer?

After you reach end of File you can get the String from the StringBuffer.

Multiple Java versions running concurrently under Windows

Of course you can use multiple versions of Java under Windows. And different applications can use different Java versions. How is your application started? Usually you will have a batch file where there is something like

java ...

This will search the Java executable using the PATH variable. So if Java 5 is first on the PATH, you will have problems running a Java 6 application. You should then modify the batch file to use a certain Java version e.g. by defining a environment variable JAVA6HOME with the value C:\java\java6 (if Java 6 is installed in this directory) and change the batch file calling

%JAVA6HOME%\bin\java ...

Combine two columns and add into one new column

You don't need to store the column to reference it that way. Try this:

To set up:

CREATE TABLE tbl
  (zipcode text NOT NULL, city text NOT NULL, state text NOT NULL);
INSERT INTO tbl VALUES ('10954', 'Nanuet', 'NY');

We can see we have "the right stuff":

\pset border 2
SELECT * FROM tbl;
+---------+--------+-------+
| zipcode |  city  | state |
+---------+--------+-------+
| 10954   | Nanuet | NY    |
+---------+--------+-------+

Now add a function with the desired "column name" which takes the record type of the table as its only parameter:

CREATE FUNCTION combined(rec tbl)
  RETURNS text
  LANGUAGE SQL
AS $$
  SELECT $1.zipcode || ' - ' || $1.city || ', ' || $1.state;
$$;

This creates a function which can be used as if it were a column of the table, as long as the table name or alias is specified, like this:

SELECT *, tbl.combined FROM tbl;

Which displays like this:

+---------+--------+-------+--------------------+
| zipcode |  city  | state |      combined      |
+---------+--------+-------+--------------------+
| 10954   | Nanuet | NY    | 10954 - Nanuet, NY |
+---------+--------+-------+--------------------+

This works because PostgreSQL checks first for an actual column, but if one is not found, and the identifier is qualified with a relation name or alias, it looks for a function like the above, and runs it with the row as its argument, returning the result as if it were a column. You can even index on such a "generated column" if you want to do so.

Because you're not using extra space in each row for the duplicated data, or firing triggers on all inserts and updates, this can often be faster than the alternatives.

python request with authentication (access_token)

Have you tried the uncurl package (https://github.com/spulec/uncurl)? You can install it via pip, pip install uncurl. Your curl request returns:

>>> uncurl "curl --header \"Authorization:access_token myToken\" https://website.com/id"

requests.get("https://website.com/id",
    headers={
        "Authorization": "access_token myToken"
    },
    cookies={},
)

How to pass variable number of arguments to printf/sprintf

have a look at vsnprintf as this will do what ya want http://www.cplusplus.com/reference/clibrary/cstdio/vsprintf/

you will have to init the va_list arg array first, then call it.

Example from that link: /* vsprintf example */

#include <stdio.h>
#include <stdarg.h>

void Error (char * format, ...)
{
  char buffer[256];
  va_list args;
  va_start (args, format);
  vsnprintf (buffer, 255, format, args);


  //do something with the error

  va_end (args);
}

git ignore vim temporary files

sure,

just have to create a ".gitignore" on the home directory of your project and have to contain

*.swp

that's it

in one command

project-home-directory$ echo '*.swp' >> .gitignore

How can I initialise a static Map?

Now that Java 8 is out, this question warrants revisiting. I took a stab at it -- looks like maybe you can exploit lambda expression syntax to get a pretty nice and concise (but type-safe) map literal syntax that looks like this:

Map<String,Object> myMap = hashMap(
    bob -> 5,
    TheGimp -> 8,
    incredibleKoolAid -> "James Taylor",
    heyArnold -> new Date()
);

Map<String,Integer> typesafeMap = treeMap(
    a -> 5,
    bee -> 8,
    sea -> 13
    deep -> 21
);

Untested sample code at https://gist.github.com/galdosd/10823529 Would be curious about the opinions of others on this (it's mildly evil...)

Copy mysql database from remote server to local computer

Assuming the following command works successfully:

mysql -u username -p -h remote.site.com

The syntax for mysqldump is identical, and outputs the database dump to stdout. Redirect the output to a local file on the computer:

mysqldump -u username -p -h remote.site.com DBNAME > backup.sql

Replace DBNAME with the name of the database you'd like to download to your computer.

Converting a number with comma as decimal point to float

If you're using PHP5.3 or above, you can use numfmt_parse to do "a reversed number_format". If you're not, you stuck with replacing the occurrances with preg_replace/str_replace.

What are the differences between "=" and "<-" assignment operators in R?

Google's R style guide simplifies the issue by prohibiting the "=" for assignment. Not a bad choice.

https://google.github.io/styleguide/Rguide.xml

The R manual goes into nice detail on all 5 assignment operators.

http://stat.ethz.ch/R-manual/R-patched/library/base/html/assignOps.html

How to encrypt/decrypt data in php?

Foreword

Starting with your table definition:

- UserID
- Fname
- Lname
- Email
- Password
- IV

Here are the changes:

  1. The fields Fname, Lname and Email will be encrypted using a symmetric cipher, provided by OpenSSL,
  2. The IV field will store the initialisation vector used for encryption. The storage requirements depend on the cipher and mode used; more about this later.
  3. The Password field will be hashed using a one-way password hash,

Encryption

Cipher and mode

Choosing the best encryption cipher and mode is beyond the scope of this answer, but the final choice affects the size of both the encryption key and initialisation vector; for this post we will be using AES-256-CBC which has a fixed block size of 16 bytes and a key size of either 16, 24 or 32 bytes.

Encryption key

A good encryption key is a binary blob that's generated from a reliable random number generator. The following example would be recommended (>= 5.3):

$key_size = 32; // 256 bits
$encryption_key = openssl_random_pseudo_bytes($key_size, $strong);
// $strong will be true if the key is crypto safe

This can be done once or multiple times (if you wish to create a chain of encryption keys). Keep these as private as possible.

IV

The initialisation vector adds randomness to the encryption and required for CBC mode. These values should be ideally be used only once (technically once per encryption key), so an update to any part of a row should regenerate it.

A function is provided to help you generate the IV:

$iv_size = 16; // 128 bits
$iv = openssl_random_pseudo_bytes($iv_size, $strong);

Example

Let's encrypt the name field, using the earlier $encryption_key and $iv; to do this, we have to pad our data to the block size:

function pkcs7_pad($data, $size)
{
    $length = $size - strlen($data) % $size;
    return $data . str_repeat(chr($length), $length);
}

$name = 'Jack';
$enc_name = openssl_encrypt(
    pkcs7_pad($name, 16), // padded data
    'AES-256-CBC',        // cipher and mode
    $encryption_key,      // secret key
    0,                    // options (not used)
    $iv                   // initialisation vector
);

Storage requirements

The encrypted output, like the IV, is binary; storing these values in a database can be accomplished by using designated column types such as BINARY or VARBINARY.

The output value, like the IV, is binary; to store those values in MySQL, consider using BINARY or VARBINARY columns. If this is not an option, you can also convert the binary data into a textual representation using base64_encode() or bin2hex(), doing so requires between 33% to 100% more storage space.

Decryption

Decryption of the stored values is similar:

function pkcs7_unpad($data)
{
    return substr($data, 0, -ord($data[strlen($data) - 1]));
}

$row = $result->fetch(PDO::FETCH_ASSOC); // read from database result
// $enc_name = base64_decode($row['Name']);
// $enc_name = hex2bin($row['Name']);
$enc_name = $row['Name'];
// $iv = base64_decode($row['IV']);
// $iv = hex2bin($row['IV']);
$iv = $row['IV'];

$name = pkcs7_unpad(openssl_decrypt(
    $enc_name,
    'AES-256-CBC',
    $encryption_key,
    0,
    $iv
));

Authenticated encryption

You can further improve the integrity of the generated cipher text by appending a signature that's generated from a secret key (different from the encryption key) and the cipher text. Before the cipher text is decrypted, the signature is first verified (preferably with a constant-time comparison method).

Example

// generate once, keep safe
$auth_key = openssl_random_pseudo_bytes(32, $strong);

// authentication
$auth = hash_hmac('sha256', $enc_name, $auth_key, true);
$auth_enc_name = $auth . $enc_name;

// verification
$auth = substr($auth_enc_name, 0, 32);
$enc_name = substr($auth_enc_name, 32);
$actual_auth = hash_hmac('sha256', $enc_name, $auth_key, true);

if (hash_equals($auth, $actual_auth)) {
    // perform decryption
}

See also: hash_equals()

Hashing

Storing a reversible password in your database must be avoided as much as possible; you only wish to verify the password rather than knowing its contents. If a user loses their password, it's better to allow them to reset it rather than sending them their original one (make sure that password reset can only be done for a limited time).

Applying a hash function is a one-way operation; afterwards it can be safely used for verification without revealing the original data; for passwords, a brute force method is a feasible approach to uncover it due to its relatively short length and poor password choices of many people.

Hashing algorithms such as MD5 or SHA1 were made to verify file contents against a known hash value. They're greatly optimized to make this verification as fast as possible while still being accurate. Given their relatively limited output space it was easy to build a database with known passwords and their respective hash outputs, the rainbow tables.

Adding a salt to the password before hashing it would render a rainbow table useless, but recent hardware advancements made brute force lookups a viable approach. That's why you need a hashing algorithm that's deliberately slow and simply impossible to optimize. It should also be able to increase the load for faster hardware without affecting the ability to verify existing password hashes to make it future proof.

Currently there are two popular choices available:

  1. PBKDF2 (Password Based Key Derivation Function v2)
  2. bcrypt (aka Blowfish)

This answer will use an example with bcrypt.

Generation

A password hash can be generated like this:

$password = 'my password';
$random = openssl_random_pseudo_bytes(18);
$salt = sprintf('$2y$%02d$%s',
    13, // 2^n cost factor
    substr(strtr(base64_encode($random), '+', '.'), 0, 22)
);

$hash = crypt($password, $salt);

The salt is generated with openssl_random_pseudo_bytes() to form a random blob of data which is then run through base64_encode() and strtr() to match the required alphabet of [A-Za-z0-9/.].

The crypt() function performs the hashing based on the algorithm ($2y$ for Blowfish), the cost factor (a factor of 13 takes roughly 0.40s on a 3GHz machine) and the salt of 22 characters.

Validation

Once you have fetched the row containing the user information, you validate the password in this manner:

$given_password = $_POST['password']; // the submitted password
$db_hash = $row['Password']; // field with the password hash

$given_hash = crypt($given_password, $db_hash);

if (isEqual($given_hash, $db_hash)) {
    // user password verified
}

// constant time string compare
function isEqual($str1, $str2)
{
    $n1 = strlen($str1);
    if (strlen($str2) != $n1) {
        return false;
    }
    for ($i = 0, $diff = 0; $i != $n1; ++$i) {
        $diff |= ord($str1[$i]) ^ ord($str2[$i]);
    }
    return !$diff;
}

To verify a password, you call crypt() again but you pass the previously calculated hash as the salt value. The return value yields the same hash if the given password matches the hash. To verify the hash, it's often recommended to use a constant-time comparison function to avoid timing attacks.

Password hashing with PHP 5.5

PHP 5.5 introduced the password hashing functions that you can use to simplify the above method of hashing:

$hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => 13]);

And verifying:

if (password_verify($given_password, $db_hash)) {
    // password valid
}

See also: password_hash(), password_verify()

How do you cast a List of supertypes to a List of subtypes?

if you have an object of the class TestA, you can't cast it to TestB. every TestB is a TestA, but not the other way.

in the following code:

TestA a = new TestA();
TestB b = (TestB) a;

the second line would throw a ClassCastException.

you can only cast a TestA reference if the object itself is TestB. for example:

TestA a = new TestB();
TestB b = (TestB) a;

so, you may not always cast a list of TestA to a list of TestB.

Using NOT operator in IF conditions

As a general statement, its good to make your if conditionals as readable as possible. For your example, using ! is ok. the problem is when things look like

if ((a.b && c.d.e) || !f)

you might want to do something like

bool isOk = a.b;
bool isStillOk = c.d.e
bool alternateOk = !f

then your if statement is simplified to

if ( (isOk && isStillOk) || alternateOk)

It just makes the code more readable. And if you have to debug, you can debug the isOk set of vars instead of having to dig through the variables in scope. It is also helpful for dealing with NPEs -- breaking code out into simpler chunks is always good.

The content type application/xml;charset=utf-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8)

In WCF serive project this issue may be due to Reference of System.Web.Mvc.dll 's different version or may be any other DLL's different version issue. So this may be compatibility issue of DLL's different version

When I use

System.Web.Mvc.dll version 5.2.2.0 -> it thorows the Error The content type text/html; charset=utf-8 of the response message

but when I use

System.Web.Mvc.dll version 4.0.0.0 or lower -> That's works fine in my project and not have an Error.

I don't know the reason of this different version of DLL's issue but when I change the DLL's verison which is compatible with your WCF Project than it works fine.

This Error even generate when you add reference of other Project in your WCF Project and this reference project has different version of System.Web.Mvc DLL or could be any other DLL.

Getting the base url of the website and globally passing it to twig in Symfony 2

I tried all the options here but they didnt work for me. Eventually I got it working using

{{ site.url }}

Hope this helps someone who is still struggling.

What's the difference between RANK() and DENSE_RANK() functions in oracle?

The only difference between the RANK() and DENSE_RANK() functions is in cases where there is a “tie”; i.e., in cases where multiple values in a set have the same ranking. In such cases, RANK() will assign non-consecutive “ranks” to the values in the set (resulting in gaps between the integer ranking values when there is a tie), whereas DENSE_RANK() will assign consecutive ranks to the values in the set (so there will be no gaps between the integer ranking values in the case of a tie).

For example, consider the set {30, 30, 50, 75, 75, 100}. For such a set, RANK() will return {1, 1, 3, 4, 4, 6} (note that the values 2 and 5 are skipped), whereas DENSE_RANK() will return {1,1,2,3,3,4}.

RichTextBox (WPF) does not have string property "Text"

How about just doing the following:

_richTextBox.SelectAll();
string myText = _richTextBox.Selection.Text;

How to block users from closing a window in Javascript?

If your sending out an internal survey that requires 100% participation from your company's employees, then a better route would be to just have the form keep track of the responders ID/Username/email etc. Every few days or so just send a nice little email reminder to those in your organization to complete the survey...you could probably even automate this.

What generates the "text file busy" message in Unix?

If trying to build phpredis on a Linux box you might need to give it time to complete modifying the file permissions, with a sleep command, before running the file:

chmod a+x /usr/bin/php/scripts/phpize \
  && sleep 1 \
  && /usr/bin/php/scripts/phpize

Differences in boolean operators: & vs && and | vs ||

While the basic difference is that & is used for bitwise operations mostly on long, int or byte where it can be used for kind of a mask, the results can differ even if you use it instead of logical &&.

The difference is more noticeable in some scenarios:

  1. Evaluating some of the expressions is time consuming
  2. Evaluating one of the expression can be done only if the previous one was true
  3. The expressions have some side-effect (intended or not)

First point is quite straightforward, it causes no bugs, but it takes more time. If you have several different checks in one conditional statements, put those that are either cheaper or more likely to fail to the left.

For second point, see this example:

if ((a != null) & (a.isEmpty()))

This fails for null, as evaluating the second expression produces a NullPointerException. Logical operator && is lazy, if left operand is false, the result is false no matter what right operand is.

Example for the third point -- let's say we have an app that uses DB without any triggers or cascades. Before we remove a Building object, we must change a Department object's building to another one. Let's also say the operation status is returned as a boolean (true = success). Then:

if (departmentDao.update(department, newBuilding) & buildingDao.remove(building))

This evaluates both expressions and thus performs building removal even if the department update failed for some reason. With &&, it works as intended and it stops after first failure.

As for a || b, it is equivalent of !(!a && !b), it stops if a is true, no more explanation needed.

jQuery: set selected value of dropdown list?

You can select dropdown option value by name

jQuery("#option_id").find("option:contains('Monday')").each(function()
{
 if( jQuery(this).text() == 'Monday' )
 {
  jQuery(this).attr("selected","selected");
  }
});

How to handle command-line arguments in PowerShell

You are reinventing the wheel. Normal PowerShell scripts have parameters starting with -, like script.ps1 -server http://devserver

Then you handle them in param section in the beginning of the file.

You can also assign default values to your params, read them from console if not available or stop script execution:

 param (
    [string]$server = "http://defaultserver",
    [Parameter(Mandatory=$true)][string]$username,
    [string]$password = $( Read-Host "Input password, please" )
 )

Inside the script you can simply

write-output $server

since all parameters become variables available in script scope.

In this example, the $server gets a default value if the script is called without it, script stops if you omit the -username parameter and asks for terminal input if -password is omitted.

Update: You might also want to pass a "flag" (a boolean true/false parameter) to a PowerShell script. For instance, your script may accept a "force" where the script runs in a more careful mode when force is not used.

The keyword for that is [switch] parameter type:

 param (
    [string]$server = "http://defaultserver",
    [string]$password = $( Read-Host "Input password, please" ),
    [switch]$force = $false
 )

Inside the script then you would work with it like this:

if ($force) {
  //deletes a file or does something "bad"
}

Now, when calling the script you'd set the switch/flag parameter like this:

.\yourscript.ps1 -server "http://otherserver" -force

If you explicitly want to state that the flag is not set, there is a special syntax for that

.\yourscript.ps1 -server "http://otherserver" -force:$false

Links to relevant Microsoft documentation (for PowerShell 5.0; tho versions 3.0 and 4.0 are also available at the links):

React Native absolute positioning horizontal centre

You can center absolute items by providing the left property with the width of the device divided by two and subtracting out half of the element you'd like to center's width.

For example, your style might look something like this.

bottom: {
    position: 'absolute',
    left: (Dimensions.get('window').width / 2) - 25,
    top: height*0.93,
}

IE11 Document mode defaults to IE7. How to reset?

If you are a developer, this is what you need to do:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

Rename all files in directory from $filename_h to $filename_half?

I had a similar question: In the manual, it describes rename as

rename [option] expression replacement file

so you can use it in this way

rename _h _half *.png

In the code: '_h' is the expression that you are looking for. '_half' is the pattern that you want to replace with. '*.png' is the range of files that you are looking for your possible target files.

Hope this can help c:

How to make div background color transparent in CSS

It might be a little late to the discussion but inevitably someone will stumble onto this post like I did. I found the answer I was looking for and thought I'd post my own take on it. The following JSfiddle includes how to layer .PNG's with transparency. Jerska's mention of the transparency attribute for the div's CSS was the solution: http://jsfiddle.net/jyef3fqr/

HTML:

   <button id="toggle-box">toggle</button>
   <div id="box" style="display:none;" ><img src="x"></div>
   <button id="toggle-box2">toggle</button>
   <div id="box2" style="display:none;"><img src="xx"></div>
   <button id="toggle-box3">toggle</button>
   <div id="box3" style="display:none;" ><img src="xxx"></div>

CSS:

#box {
background-color: #ffffff;
height:400px;
width: 1200px;
position: absolute;
top:30px;
z-index:1;
}
#box2 {
background-color: #ffffff;
height:400px;
width: 1200px;
position: absolute;
top:30px;
z-index:2;
background-color : transparent;
      }
      #box3 {
background-color: #ffffff;
height:400px;
width: 1200px;
position: absolute;
top:30px;
z-index:2;
background-color : transparent;
      }
 body {background-color:#c0c0c0; }

JS:

$('#toggle-box').click().toggle(function() {
$('#box').animate({ width: 'show' });
}, function() {
$('#box').animate({ width: 'hide' });
});

$('#toggle-box2').click().toggle(function() {
$('#box2').animate({ width: 'show' });
}, function() {
$('#box2').animate({ width: 'hide' });
});
$('#toggle-box3').click().toggle(function() {
$('#box3').animate({ width: 'show' });
 }, function() {
$('#box3').animate({ width: 'hide' });
});

And my original inspiration:http://jsfiddle.net/5g1zwLe3/ I also used paint.net for creating the transparent PNG's, or rather the PNG's with transparent BG's.

What does $1 [QSA,L] mean in my .htaccess file?

If the following conditions are true, then rewrite the URL:
If the requested filename is not a directory,

RewriteCond %{REQUEST_FILENAME} !-d

and if the requested filename is not a regular file that exists,

RewriteCond %{REQUEST_FILENAME} !-f

and if the requested filename is not a symbolic link,

RewriteCond %{REQUEST_FILENAME} !-l

then rewrite the URL in the following way:
Take the whole request filename and provide it as the value of a "url" query parameter to index.php. Append any query string from the original URL as further query parameters (QSA), and stop processing this .htaccess file (L).

RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]

Apache docs #flag_qsa

Another Example:

RewriteRule "/pages/(.+)" "/page.php?page=$1" [QSA]

With the [QSA] flag, a request for

/pages/123?one=two

will be mapped to

/page.php?page=123&one=two

Maven not found in Mac OSX mavericks

I am not allowed to comment to pkyeck's response which did not work for a few people including me, so I am adding a separate comment in continuation to his response:

Basically try to add the variable which he has mentioned in the .profile file if the .bash_profile did not work. It is located in your home directory and then restart the terminal. that got it working for me.

The obvious blocker would be that you do not have an access to edit the .profile file, for which use the "touch" to check the access and the "sudo" command to get the access

  1. touch .profile

  2. vi .profile

Here are the variable pkyeck suggests that we added as a solution which worked with editing .profile for me:

  1. export M2_HOME=/apache-maven-3.3.3

  2. export PATH=$PATH:$M2_HOME/bin

How to get the last five characters of a string using Substring() in C#?

static void Main()
    {
        string input = "OneTwoThree";

            //Get last 5 characters
        string sub = input.Substring(6);
        Console.WriteLine("Substring: {0}", sub); // Output Three. 
    }
  • Substring(0, 3) - Returns substring of first 3 chars. //One

  • Substring(3, 3) - Returns substring of second 3 chars. //Two

  • Substring(6) - Returns substring of all chars after first 6. //Three

Check if year is leap year in javascript

A faster solution is provided by Kevin P. Rice here:https://stackoverflow.com/a/11595914/5535820 So here's the code:

function leapYear(year)
{
    return (year & 3) == 0 && ((year % 25) != 0 || (year & 15) == 0);
}

What is “2's Complement”?

Two's complement is a clever way of storing integers so that common math problems are very simple to implement.

To understand, you have to think of the numbers in binary.

It basically says,

  • for zero, use all 0's.
  • for positive integers, start counting up, with a maximum of 2(number of bits - 1)-1.
  • for negative integers, do exactly the same thing, but switch the role of 0's and 1's (so instead of starting with 0000, start with 1111 - that's the "complement" part).

Let's try it with a mini-byte of 4 bits (we'll call it a nibble - 1/2 a byte).

  • 0000 - zero
  • 0001 - one
  • 0010 - two
  • 0011 - three
  • 0100 to 0111 - four to seven

That's as far as we can go in positives. 23-1 = 7.

For negatives:

  • 1111 - negative one
  • 1110 - negative two
  • 1101 - negative three
  • 1100 to 1000 - negative four to negative eight

Note that you get one extra value for negatives (1000 = -8) that you don't for positives. This is because 0000 is used for zero. This can be considered as Number Line of computers.

Distinguishing between positive and negative numbers

Doing this, the first bit gets the role of the "sign" bit, as it can be used to distinguish between nonnegative and negative decimal values. If the most significant bit is 1, then the binary can be said to be negative, where as if the most significant bit (the leftmost) is 0, you can say the decimal value is nonnegative.

"Sign-magnitude" negative numbers just have the sign bit flipped of their positive counterparts, but this approach has to deal with interpreting 1000 (one 1 followed by all 0s) as "negative zero" which is confusing.

"Ones' complement" negative numbers are just the bit-complement of their positive counterparts, which also leads to a confusing "negative zero" with 1111 (all ones).

You will likely not have to deal with Ones' Complement or Sign-Magnitude integer representations unless you are working very close to the hardware.

How to view the current heap size that an application is using?

Attach with jvisualvm from Sun Java 6 JDK. Startup flags are listed.

Capturing image from webcam in java?

This kind of goes off of gt_ebuddy's answer using JavaCV, but my video output is at a much higher quality then his answer. I've also added some other random improvements (such as closing down the program when ESC and CTRL+C are pressed, and making sure to close down the resources the program uses properly).

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;

import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.KeyStroke;

import com.googlecode.javacv.CanvasFrame;
import com.googlecode.javacv.OpenCVFrameGrabber;
import com.googlecode.javacv.cpp.opencv_core.IplImage;

public class HighRes extends JComponent implements Runnable {
    private static final long serialVersionUID = 1L;

    private static CanvasFrame frame = new CanvasFrame("Web Cam");
    private static boolean running = false;
    private static int frameWidth = 800;
    private static int frameHeight = 600;
    private static OpenCVFrameGrabber grabber = new OpenCVFrameGrabber(0);
    private static BufferedImage bufImg;

    public HighRes()
    {
        // setup key bindings
        ActionMap actionMap = frame.getRootPane().getActionMap();
        InputMap inputMap = frame.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);

        for (Keys direction : Keys.values())
        {
            actionMap.put(direction.getText(), new KeyBinding(direction.getText()));
            inputMap.put(direction.getKeyStroke(), direction.getText());
        }

        frame.getRootPane().setActionMap(actionMap);
        frame.getRootPane().setInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW, inputMap);

        // setup window listener for close action
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.addWindowListener(new WindowAdapter()
        {
            public void windowClosing(WindowEvent e)
            {
                stop();
            }
        });
    }

    public static void main(String... args)
    {
        HighRes webcam = new HighRes();
        webcam.start();
    }

    @Override
    public void run()
    {
        try
        {

            grabber.setImageWidth(frameWidth);
            grabber.setImageHeight(frameHeight);
            grabber.start();
            while (running)
            {

                final IplImage cvimg = grabber.grab();
                if (cvimg != null)
                {

                    // cvFlip(cvimg, cvimg, 1); // mirror

                    // show image on window
                    bufImg = cvimg.getBufferedImage();
                    frame.showImage(bufImg);
                }
            }
            grabber.stop();
            grabber.release();
            frame.dispose();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public void start()
    {
        new Thread(this).start();
        running = true;
    }

    public void stop()
    {
        running = false;
    }

    private class KeyBinding extends AbstractAction {

        private static final long serialVersionUID = 1L;

        public KeyBinding(String text)
        {
            super(text);
            putValue(ACTION_COMMAND_KEY, text);
        }

        @Override
        public void actionPerformed(ActionEvent e)
        {
            String action = e.getActionCommand();
            if (action.equals(Keys.ESCAPE.toString()) || action.equals(Keys.CTRLC.toString())) stop();
            else System.out.println("Key Binding: " + action);
        }
    }
}

enum Keys
{
    ESCAPE("Escape", KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0)),
    CTRLC("Control-C", KeyStroke.getKeyStroke(KeyEvent.VK_C, KeyEvent.CTRL_DOWN_MASK)),
    UP("Up", KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0)),
    DOWN("Down", KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0)),
    LEFT("Left", KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0)),
    RIGHT("Right", KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0));

    private String text;
    private KeyStroke keyStroke;

    Keys(String text, KeyStroke keyStroke)
    {
        this.text = text;
        this.keyStroke = keyStroke;
    }

    public String getText()
    {
        return text;
    }

    public KeyStroke getKeyStroke()
    {
        return keyStroke;
    }

    @Override
    public String toString()
    {
        return text;
    }
}

Get the height and width of the browser viewport without scrollbars using jquery?

I wanted a different look of my website for width screen and small screen. I have made 2 CSS files. In Java I choose which of the 2 CSS file is used depending on the screen width. I use the PHP function echo with in the echo-function some javascript.

my code in the <header> section of my PHP-file:

<?php
echo "
<script>
    if ( window.innerWidth > 400)
            { document.write('<link href=\"kekemba_resort_stylesheetblog-jun2018.css\" rel=\"stylesheet\" type=\"text/css\">'); }
    else
            { document.write('<link href=\"kekemba_resort_stylesheetblog-jun2018small.css\" rel=\"stylesheet\" type=\"text/css\">'); }
</script>
"; 
?>

javascript onclick increment number

I know this is an old post but its relevant to what I'm working on currently.

What I'm aiming to do is create next/previous page buttons at the top of a html page, and say I'm on 'book.html', with the current 'display' ID content being 'page-1.html' through ajax, if i click the 'next' button it will load 'page-2.html' through ajax, WITHOUT reloading the page.

How would I go about doing this through AJAX as I have seen many examples but most of them are completely different, and most examples of using AJAX are for WordPress forms and stuff.

Currently using the below line will open the entire page, I want to know the best way to go about using AJAX instead if possible :) window.location(url);

I'm incorportating the below code as an example:

var i = 1;
var url = "pages/page-" + i + ".html";

    function incPage() {
    if (i < 10) {
        i++;
        window.location = url; 
        //load next page in body using AJAX request

    } else if (i = 10) {
        i = 0;
    }
    document.getElementById("display").innerHTML = i;
}

function decPage() {
    if (i > 0) {
        --i;
        window.location = url; 
        //load previous page in body using AJAX request
    } else if (i = 0) {
        i = 10;
    }
    document.getElementById("display").innerHTML = i;
}

Write to .txt file?

Well, you need to first get a good book on C and understand the language.

FILE *fp;
fp = fopen("c:\\test.txt", "wb");
if(fp == null)
   return;
char x[10]="ABCDEFGHIJ";
fwrite(x, sizeof(x[0]), sizeof(x)/sizeof(x[0]), fp);
fclose(fp);

Override console.log(); for production

Theres no a reason to let all that console.log all over your project in prod enviroment... If you want to do it on the proper way, add UglifyJS2 to your deployment process using "drop_console" option.

Remote JMX connection

In my testing with Tomcat and Java 8, the JVM was opening an ephemeral port in addition to the one specified for JMX. The following code fixed me up; give it a try if you are having issues where your JMX client (e.g. VisualVM is not connecting.

-Dcom.sun.management.jmxremote.port=8989
-Dcom.sun.management.jmxremote.rmi.port=8989

Also see Why Java opens 3 ports when JMX is configured?

What is this Javascript "require"?

Alright, so let's first start with making the distinction between Javascript in a web browser, and Javascript on a server (CommonJS and Node).

Javascript is a language traditionally confined to a web browser with a limited global context defined mostly by what came to be known as the Document Object Model (DOM) level 0 (the Netscape Navigator Javascript API).

Server-side Javascript eliminates that restriction and allows Javascript to call into various pieces of native code (like the Postgres library) and open sockets.

Now require() is a special function call defined as part of the CommonJS spec. In node, it resolves libraries and modules in the Node search path, now usually defined as node_modules in the same directory (or the directory of the invoked javascript file) or the system-wide search path.

To try to answer the rest of your question, we need to use a proxy between the code running in the the browser and the database server.

Since we are discussing Node and you are already familiar with how to run a query from there, it would make sense to use Node as that proxy.

As a simple example, we're going to make a URL that returns a few facts about a Beatle, given a name, as JSON.

/* your connection code */

var express = require('express');
var app = express.createServer();
app.get('/beatles/:name', function(req, res) {
    var name = req.params.name || '';
    name = name.replace(/[^a-zA_Z]/, '');
    if (!name.length) {
        res.send({});
    } else {
        var query = client.query('SELECT * FROM BEATLES WHERE name =\''+name+'\' LIMIT 1');
        var data = {};
        query.on('row', function(row) {
            data = row;
            res.send(data);
        });
    };
});
app.listen(80, '127.0.0.1');

Using BufferedReader to read Text File

You can assign the result of br.readLine() to a variable and use that both for processing and for checking, like so:

String line = br.readLine();
while (line != null) { // You might also want to check for empty?
    System.out.println(line);
    line = br.readLine();
}

List distinct values in a vector in R

another way would be to use dplyr package:

x = c(1,1,2,3,4,4,4)
dplyr::distinct(as.data.frame(x))

Error: "Adb connection Error:An existing connection was forcibly closed by the remote host"

Change to another USB port works for me. I tried reset ADB, but problem still there.

How to add a TextView to a LinearLayout dynamically in Android?

TextView rowTextView = (TextView)getLayoutInflater().inflate(R.layout.yourTextView, null);
        rowTextView.setText(text);
        layout.addView(rowTextView);

This is how I'm using this:

 private List<Tag> tags = new ArrayList<>();


if(tags.isEmpty()){
        Gson gson = new Gson();
        Type listType = new TypeToken<List<Tag>>() {
        }.getType();
        tags = gson.fromJson(tour.getTagsJSONArray(), listType);
    }



if (flowLayout != null) {
        if(!tags.isEmpty()) {
            Log.e(TAG, "setTags: "+ flowLayout.getChildCount() );
            flowLayout.removeAllViews();
            for (Tag tag : tags) {
                FlowLayout.LayoutParams lparams = new FlowLayout.LayoutParams(FlowLayout.LayoutParams.WRAP_CONTENT, FlowLayout.LayoutParams.WRAP_CONTENT);
                lparams.setMargins(PixelUtil.dpToPx(this, 0), PixelUtil.dpToPx(this, 5), PixelUtil.dpToPx(this, 10), PixelUtil.dpToPx(this, 5));// llp.setMargins(left, top, right, bottom);
                TextView rowTextView = (TextView) getLayoutInflater().inflate(R.layout.tag, null);
                rowTextView.setText(tag.getLabel());
                rowTextView.setLayoutParams(lparams);
                flowLayout.addView(rowTextView);
            }
        }
        Log.e(TAG, "setTags: after "+ flowLayout.getChildCount() );
    }

And this is my custom TextView named tag:

<?xml version="1.0" encoding="utf-8"?><TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"    
android:textSize="10dp"
android:textAllCaps="true"
fontPath="@string/font_light"
android:background="@drawable/tag_shape"
android:paddingLeft="11dp"
android:paddingTop="6dp"
android:paddingRight="11dp"
android:paddingBottom="6dp">

this is my tag_shape:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#f2f2f2" />
<corners android:radius="15dp" />
</shape>

efect:

enter image description here

In other place I'm adding textviews with language names from dialog with listview:

enter image description here

enter image description here

Importing modules from parent folder

For me the shortest and my favorite oneliner for accessing to the parent directory is:

sys.path.append(os.path.dirname(os.getcwd()))

or:

sys.path.insert(1, os.path.dirname(os.getcwd()))

os.getcwd() returns the name of the current working directory, os.path.dirname(directory_name) returns the directory name for the passed one.

Actually, in my opinion Python project architecture should be done the way where no one module from child directory will use any module from the parent directory. If something like this happens it is worth to rethink about the project tree.

Another way is to add parent directory to PYTHONPATH system environment variable.

Warning :-Presenting view controllers on detached view controllers is discouraged

Try this code

UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:<your ViewController object>];

[self.view.window.rootViewController presentViewController:navigationController animated:YES completion:nil];

System.BadImageFormatException An attempt was made to load a program with an incorrect format

It's possibly a 32 - 64 bits mismatch.

If you're running on a 64-bit OS, the Assembly RevitAPI may be compiled as 32-bit and your process as 64-bit or "Any CPU".

Or, the RevitAPI is compiled as 64-bit and your process is compiled as 32-bit or "Any CPU" and running on a 32-bit OS.

CSS Selector "(A or B) and C"?

If you have this:

<div class="a x">Foo</div>
<div class="b x">Bar</div>
<div class="c x">Baz</div>

And you only want to select the elements which have .x and (.a or .b), you could write:

.x:not(.c) { ... }

but that's convenient only when you have three "sub-classes" and you want to select two of them.

Selecting only one sub-class (for instance .a): .a.x

Selecting two sub-classes (for instance .a and .b): .x:not(.c)

Selecting all three sub-classes: .x

VBA Excel 2-Dimensional Arrays

Here's A generic VBA Array To Range function that writes an array to the sheet in a single 'hit' to the sheet. This is much faster than writing the data into the sheet one cell at a time in loops for the rows and columns... However, there's some housekeeping to do, as you must specify the size of the target range correctly.

This 'housekeeping' looks like a lot of work and it's probably rather slow: but this is 'last mile' code to write to the sheet, and everything is faster than writing to the worksheet. Or at least, so much faster that it's effectively instantaneous, compared with a read or write to the worksheet, even in VBA, and you should do everything you possibly can in code before you hit the sheet.

A major component of this is error-trapping that I used to see turning up everywhere . I hate repetitive coding: I've coded it all here, and - hopefully - you'll never have to write it again.

A VBA 'Array to Range' function

Public Sub ArrayToRange(rngTarget As Excel.Range, InputArray As Variant)
' Write an array to an Excel range in a single 'hit' to the sheet
' InputArray must be a 2-Dimensional structure of the form Variant(Rows, Columns)

' The target range is resized automatically to the dimensions of the array, with
' the top left cell used as the start point.

' This subroutine saves repetitive coding for a common VBA and Excel task.

' If you think you won't need the code that works around common errors (long strings
' and objects in the array, etc) then feel free to comment them out.

On Error Resume Next

'
' Author: Nigel Heffernan
' HTTP://Excellerando.blogspot.com
'
' This code is in te public domain: take care to mark it clearly, and segregate
' it from proprietary code if you intend to assert intellectual property rights
' or impose commercial confidentiality restrictions on that proprietary code

Dim rngOutput As Excel.Range

Dim iRowCount   As Long
Dim iColCount   As Long
Dim iRow        As Long
Dim iCol        As Long
Dim arrTemp     As Variant
Dim iDimensions As Integer

Dim iRowOffset  As Long
Dim iColOffset  As Long
Dim iStart      As Long


Application.EnableEvents = False
If rngTarget.Cells.Count > 1 Then
    rngTarget.ClearContents
End If
Application.EnableEvents = True

If IsEmpty(InputArray) Then
    Exit Sub
End If


If TypeName(InputArray) = "Range" Then
    InputArray = InputArray.Value
End If

' Is it actually an array? IsArray is sadly broken so...
If Not InStr(TypeName(InputArray), "(") Then
    rngTarget.Cells(1, 1).Value2 = InputArray
    Exit Sub
End If


iDimensions = ArrayDimensions(InputArray)

If iDimensions < 1 Then

    rngTarget.Value = CStr(InputArray)

ElseIf iDimensions = 1 Then

    iRowCount = UBound(InputArray) - LBound(InputArray)
    iStart = LBound(InputArray)
    iColCount = 1

    If iRowCount > (655354 - rngTarget.Row) Then
        iRowCount = 655354 + iStart - rngTarget.Row
        ReDim Preserve InputArray(iStart To iRowCount)
    End If

    iRowCount = UBound(InputArray) - LBound(InputArray)
    iColCount = 1

    ' It's a vector. Yes, I asked for a 2-Dimensional array. But I'm feeling generous.
    ' By convention, a vector is presented in Excel as an arry of 1 to n rows and 1 column.
    ReDim arrTemp(LBound(InputArray, 1) To UBound(InputArray, 1), 1 To 1)
    For iRow = LBound(InputArray, 1) To UBound(InputArray, 1)
        arrTemp(iRow, 1) = InputArray(iRow)
    Next

    With rngTarget.Worksheet
        Set rngOutput = .Range(rngTarget.Cells(1, 1), rngTarget.Cells(iRowCount + 1, iColCount))
        rngOutput.Value2 = arrTemp
        Set rngTarget = rngOutput
    End With

    Erase arrTemp

ElseIf iDimensions = 2 Then

    iRowCount = UBound(InputArray, 1) - LBound(InputArray, 1)
    iColCount = UBound(InputArray, 2) - LBound(InputArray, 2)

    iStart = LBound(InputArray, 1)

    If iRowCount > (65534 - rngTarget.Row) Then
        iRowCount = 65534 - rngTarget.Row
        InputArray = ArrayTranspose(InputArray)
        ReDim Preserve InputArray(LBound(InputArray, 1) To UBound(InputArray, 1), iStart To iRowCount)
        InputArray = ArrayTranspose(InputArray)
    End If


    iStart = LBound(InputArray, 2)
    If iColCount > (254 - rngTarget.Column) Then
        ReDim Preserve InputArray(LBound(InputArray, 1) To UBound(InputArray, 1), iStart To iColCount)
    End If



    With rngTarget.Worksheet

        Set rngOutput = .Range(rngTarget.Cells(1, 1), rngTarget.Cells(iRowCount + 1, iColCount + 1))

        Err.Clear
        Application.EnableEvents = False
        rngOutput.Value2 = InputArray
        Application.EnableEvents = True

        If Err.Number <> 0 Then
            For iRow = LBound(InputArray, 1) To UBound(InputArray, 1)
                For iCol = LBound(InputArray, 2) To UBound(InputArray, 2)
                    If IsNumeric(InputArray(iRow, iCol)) Then
                        ' no action
                    Else
                        InputArray(iRow, iCol) = "" & InputArray(iRow, iCol)
                        InputArray(iRow, iCol) = Trim(InputArray(iRow, iCol))
                    End If
                Next iCol
            Next iRow
            Err.Clear
            rngOutput.Formula = InputArray
        End If 'err<>0

        If Err <> 0 Then
            For iRow = LBound(InputArray, 1) To UBound(InputArray, 1)
                For iCol = LBound(InputArray, 2) To UBound(InputArray, 2)
                    If IsNumeric(InputArray(iRow, iCol)) Then
                        ' no action
                    Else
                        If Left(InputArray(iRow, iCol), 1) = "=" Then
                            InputArray(iRow, iCol) = "'" & InputArray(iRow, iCol)
                        End If
                        If Left(InputArray(iRow, iCol), 1) = "+" Then
                            InputArray(iRow, iCol) = "'" & InputArray(iRow, iCol)
                        End If
                        If Left(InputArray(iRow, iCol), 1) = "*" Then
                            InputArray(iRow, iCol) = "'" & InputArray(iRow, iCol)
                        End If
                    End If
                Next iCol
            Next iRow
            Err.Clear
            rngOutput.Value2 = InputArray
        End If 'err<>0

        If Err <> 0 Then
            For iRow = LBound(InputArray, 1) To UBound(InputArray, 1)
                For iCol = LBound(InputArray, 2) To UBound(InputArray, 2)

                    If IsObject(InputArray(iRow, iCol)) Then
                        InputArray(iRow, iCol) = "[OBJECT] " & TypeName(InputArray(iRow, iCol))
                    ElseIf IsArray(InputArray(iRow, iCol)) Then
                        InputArray(iRow, iCol) = Split(InputArray(iRow, iCol), ",")
                    ElseIf IsNumeric(InputArray(iRow, iCol)) Then
                        ' no action
                    Else
                        InputArray(iRow, iCol) = "" & InputArray(iRow, iCol)
                        If Len(InputArray(iRow, iCol)) > 255 Then
                            ' Block-write operations fail on strings exceeding 255 chars. You *have*
                            ' to go back and check, and write this masterpiece one cell at a time...
                            InputArray(iRow, iCol) = Left(Trim(InputArray(iRow, iCol)), 255)
                        End If
                    End If
                Next iCol
            Next iRow
            Err.Clear
            rngOutput.Text = InputArray
        End If 'err<>0

        If Err <> 0 Then
            Application.ScreenUpdating = False
            Application.Calculation = xlCalculationManual
            iRowOffset = LBound(InputArray, 1) - 1
            iColOffset = LBound(InputArray, 2) - 1
            For iRow = 1 To iRowCount
                If iRow Mod 100 = 0 Then
                    Application.StatusBar = "Filling range... " & CInt(100# * iRow / iRowCount) & "%"
                End If
                For iCol = 1 To iColCount
                    rngOutput.Cells(iRow, iCol) = InputArray(iRow + iRowOffset, iCol + iColOffset)
                Next iCol
            Next iRow
            Application.StatusBar = False
            Application.ScreenUpdating = True


        End If 'err<>0


        Set rngTarget = rngOutput   ' resizes the range This is useful, *most* of the time

    End With

End If

End Sub

You will need the source for ArrayDimensions:

This API declaration is required in the module header:

Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" _
                   (Destination As Any, _
                    Source As Any, _
                    ByVal Length As Long)

...And here's the function itself:

Private Function ArrayDimensions(arr As Variant) As Integer
  '-----------------------------------------------------------------
  ' will return:
  ' -1 if not an array
  ' 0  if an un-dimmed array
  ' 1  or more indicating the number of dimensions of a dimmed array
  '-----------------------------------------------------------------


  ' Retrieved from Chris Rae's VBA Code Archive - http://chrisrae.com/vba
  ' Code written by Chris Rae, 25/5/00

  ' Originally published by R. B. Smissaert.
  ' Additional credits to Bob Phillips, Rick Rothstein, and Thomas Eyde on VB2TheMax

  Dim ptr As Long
  Dim vType As Integer

  Const VT_BYREF = &H4000&

  'get the real VarType of the argument
  'this is similar to VarType(), but returns also the VT_BYREF bit
  CopyMemory vType, arr, 2

  'exit if not an array
  If (vType And vbArray) = 0 Then
    ArrayDimensions = -1
    Exit Function
  End If

  'get the address of the SAFEARRAY descriptor
  'this is stored in the second half of the
  'Variant parameter that has received the array
  CopyMemory ptr, ByVal VarPtr(arr) + 8, 4

  'see whether the routine was passed a Variant
  'that contains an array, rather than directly an array
  'in the former case ptr already points to the SA structure.
  'Thanks to Monte Hansen for this fix

  If (vType And VT_BYREF) Then
    ' ptr is a pointer to a pointer
    CopyMemory ptr, ByVal ptr, 4
  End If

  'get the address of the SAFEARRAY structure
  'this is stored in the descriptor

  'get the first word of the SAFEARRAY structure
  'which holds the number of dimensions
  '...but first check that saAddr is non-zero, otherwise
  'this routine bombs when the array is uninitialized

  If ptr Then
    CopyMemory ArrayDimensions, ByVal ptr, 2
  End If

End Function

Also: I would advise you to keep that declaration private. If you must make it a public Sub in another module, insert the Option Private Module statement in the module header. You really don't want your users calling any function with CopyMemoryoperations and pointer arithmetic.

What is the correct way to read from NetworkStream in .NET

Networking code is notoriously difficult to write, test and debug.

You often have lots of things to consider such as:

  • what "endian" will you use for the data that is exchanged (Intel x86/x64 is based on little-endian) - systems that use big-endian can still read data that is in little-endian (and vice versa), but they have to rearrange the data. When documenting your "protocol" just make it clear which one you are using.

  • are there any "settings" that have been set on the sockets which can affect how the "stream" behaves (e.g. SO_LINGER) - you might need to turn certain ones on or off if your code is very sensitive

  • how does congestion in the real world which causes delays in the stream affect your reading/writing logic

If the "message" being exchanged between a client and server (in either direction) can vary in size then often you need to use a strategy in order for that "message" to be exchanged in a reliable manner (aka Protocol).

Here are several different ways to handle the exchange:

  • have the message size encoded in a header that precedes the data - this could simply be a "number" in the first 2/4/8 bytes sent (dependent on your max message size), or could be a more exotic "header"

  • use a special "end of message" marker (sentinel), with the real data encoded/escaped if there is the possibility of real data being confused with an "end of marker"

  • use a timeout....i.e. a certain period of receiving no bytes means there is no more data for the message - however, this can be error prone with short timeouts, which can easily be hit on congested streams.

  • have a "command" and "data" channel on separate "connections"....this is the approach the FTP protocol uses (the advantage is clear separation of data from commands...at the expense of a 2nd connection)

Each approach has its pros and cons for "correctness".

The code below uses the "timeout" method, as that seems to be the one you want.

See http://msdn.microsoft.com/en-us/library/bk6w7hs8.aspx. You can get access to the NetworkStream on the TCPClient so you can change the ReadTimeout.

string SendCmd(string cmd, string ip, int port)
{
  var client = new TcpClient(ip, port);
  var data = Encoding.GetEncoding(1252).GetBytes(cmd);
  var stm = client.GetStream();
  // Set a 250 millisecond timeout for reading (instead of Infinite the default)
  stm.ReadTimeout = 250;
  stm.Write(data, 0, data.Length);
  byte[] resp = new byte[2048];
  var memStream = new MemoryStream();
  int bytesread = stm.Read(resp, 0, resp.Length);
  while (bytesread > 0)
  {
      memStream.Write(resp, 0, bytesread);
      bytesread = stm.Read(resp, 0, resp.Length);
  }
  return Encoding.GetEncoding(1252).GetString(memStream.ToArray());
}

As a footnote for other variations on this writing network code...when doing a Read where you want to avoid a "block", you can check the DataAvailable flag and then ONLY read what is in the buffer checking the .Length property e.g. stm.Read(resp, 0, stm.Length);

How does lock work exactly?

Locks will block other threads from executing the code contained in the lock block. The threads will have to wait until the thread inside the lock block has completed and the lock is released. This does have a negative impact on performance in a multithreaded environment. If you do need to do this you should make sure the code within the lock block can process very quickly. You should try to avoid expensive activities like accessing a database etc.

Repeat command automatically in Linux

If you want to avoid "drifting", meaning you want the command to execute every N seconds regardless of how long the command takes (assuming it takes less than N seconds), here's some bash that will repeat a command every 5 seconds with one-second accuracy (and will print out a warning if it can't keep up):

PERIOD=5

while [ 1 ]
do
    let lastup=`date +%s`
    # do command
    let diff=`date +%s`-$lastup
    if [ "$diff" -lt "$PERIOD" ]
    then
        sleep $(($PERIOD-$diff))
    elif [ "$diff" -gt "$PERIOD" ]
    then
        echo "Command took longer than iteration period of $PERIOD seconds!"
    fi
done

It may still drift a little since the sleep is only accurate to one second. You could improve this accuracy by creative use of the date command.

Remove grid, background color, and top and right borders from ggplot2

I followed Andrew's answer, but I also had to follow https://stackoverflow.com/a/35833548 and set the x and y axes separately due to a bug in my version of ggplot (v2.1.0).

Instead of

theme(axis.line = element_line(color = 'black'))

I used

theme(axis.line.x = element_line(color="black", size = 2),
    axis.line.y = element_line(color="black", size = 2))

Raise an error manually in T-SQL to jump to BEGIN CATCH block

You're looking for RAISERROR.

From MSDN:

Generates an error message and initiates error processing for the session. RAISERROR can either reference a user-defined message stored in the sys.messages catalog view or build a message dynamically. The message is returned as a server error message to the calling application or to an associated CATCH block of a TRY…CATCH construct.

CodeProject has a good article that also describes in-depth the details of how it works and how to use it.

how to view the contents of a .pem certificate

Use the -printcert command like this:

keytool -printcert -file certificate.pem

I can't find my git.exe file in my Github folder

The last update for "windows git" did move the git.exe file from the /bin folder to the /cmd folder. So, to use git with IDEs such as webStorm or Android Studio you can use the path :

C:\Users\<user>\AppData\Local\GitHub\PortableGit_<..numbers..>\cmd\git.exe

But if you want to have linux-like commands such as git, ssh, ls, cp under windows powerShell or cmd add to your windows PATH variables :

C:\Users\<user>\AppData\Local\GitHub\PortableGit_<...numbers...>\usr\bin

change <user> and <...numbers...> to your values and reboot!

Also, you will have to update this everytime git updates since it might change the portable folder name. If folder structure changes I will update this post.

Thx @dennisschagt for the comment above! ;)

Execute bash script from URL

Using wget, which is usually part of default system installation:

bash <(wget -qO- http://mywebsite.com/myscript.txt)

How to return a string from a C++ function?

Assign something to your strings. This will definitely help.

How to install libusb in Ubuntu

Usually to use the library you need to install the dev version.

Try

sudo apt-get install libusb-1.0-0-dev

Could not create work tree dir 'example.com'.: Permission denied

I was facing same issue then I read first few lines of this question and I realised that I was trying to run command at the root directory of my bash profile instead of CD/my work project folder. I switched back to my work folder and able to clone the project successfully

Swift: Convert enum value to String?

After try few different ways, i found that if you don't want to use:

let audience = Audience.Public.toRaw()

You can still archive it using a struct

struct Audience {
   static let Public  = "Public"
   static let Friends = "Friends"
   static let Private = "Private"
}

then your code:

let audience = Audience.Public

will work as expected. It isn't pretty and there are some downsides because you not using a "enum", you can't use the shortcut only adding .Private neither will work with switch cases.

How to revert a "git rm -r ."?

With Git 2.23+ (August 2019), the proper command to restore files (and the index) woud be to use... git restore (not reset --hard or the confusing git checkout command)

That is:

git restore -s=HEAD --staged --worktree -- .

Or its abbreviated form:

git restore -s@ -SW -- .

Time complexity of Euclid's Algorithm

At every step, there are two cases

b >= a / 2, then a, b = b, a % b will make b at most half of its previous value

b < a / 2, then a, b = b, a % b will make a at most half of its previous value, since b is less than a / 2

So at every step, the algorithm will reduce at least one number to at least half less.

In at most O(log a)+O(log b) step, this will be reduced to the simple cases. Which yield an O(log n) algorithm, where n is the upper limit of a and b.

I have found it here

How to convert all text to lowercase in Vim

Usually Vu (or VU for uppercase) is enough to turn the whole line into lowercase as V already selects the whole line to apply the action against.

Tilda (~) changes the case of the individual letter, resulting in camel case or the similar.

It is really great how Vim has many many different modes to deal with various occasions and how those modes are neatly organized.

For instance, v - the true visual mode, and the related V - visual line, and Ctrl+Q - visual block modes (what allows you to select blocks, a great feature some other advanced editors also offer usually by holding the Alt key and selecting the text).

SQL command to display history of queries

try

 cat ~/.mysql_history

this will show you all mysql commands ran on the system

Creating a jQuery object from a big HTML-string

There is also a great library called cheerio designed specifically for this.

Fast, flexible, and lean implementation of core jQuery designed specifically for the server.

var cheerio = require('cheerio'),
    $ = cheerio.load('<h2 class="title">Hello world</h2>');

$('h2.title').text('Hello there!');
$('h2').addClass('welcome');

$.html();
//=> <h2 class="title welcome">Hello there!</h2>

Unzipping files

If anyone's reading images or other binary files from a zip file hosted at a remote server, you can use following snippet to download and create zip object using the jszip library.

// this function just get the public url of zip file.
let url = await getStorageUrl(path) 
console.log('public url is', url)
//get the zip file to client
axios.get(url, { responseType: 'arraybuffer' }).then((res) => {
  console.log('zip download status ', res.status)
//load contents into jszip and create an object
  jszip.loadAsync(new Blob([res.data], { type: 'application/zip' })).then((zip) => {
    const zipObj = zip
    $.each(zip.files, function (index, zipEntry) {
    console.log('filename', zipEntry.name)
    })
  })

Now using the zipObj you can access the files and create a src url for it.

var fname = 'myImage.jpg'
zipObj.file(fname).async('blob').then((blob) => {
var blobUrl = URL.createObjectURL(blob)

"No such file or directory" error when executing a binary

readelf -a xxx

 INTERP         
  0x0000000000000238 0x0000000000400238 0x0000000000400238           
  0x000000000000001c 0x000000000000001c  R      1
  [Requesting program interpreter: /lib64/ld-linux-x86-64.so.2]

jquery find closest previous sibling with class

Try:

$('li.current_sub').prevAll("li.par_cat:first");

Tested it with your markup:

$('li.current_sub').prevAll("li.par_cat:first").text("woohoo");

will fill up the closest previous li.par_cat with "woohoo".

Does file_get_contents() have a timeout setting?

As @diyism mentioned, "default_socket_timeout, stream_set_timeout, and stream_context_create timeout are all the timeout of every line read/write, not the whole connection timeout." And the top answer by @stewe has failed me.

As an alternative to using file_get_contents, you can always use curl with a timeout.

So here's a working code that works for calling links.

$url='http://example.com/';
$ch=curl_init();
$timeout=5;

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);

$result=curl_exec($ch);
curl_close($ch);
echo $result;

How do I do a simple 'Find and Replace" in MsSQL?

This pointed me in the right direction, but I have a DB that originated in MSSQL 2000 and is still using the ntext data type for the column I was replacing on. When you try to run REPLACE on that type you get this error:

Argument data type ntext is invalid for argument 1 of replace function.

The simplest fix, if your column data fits within nvarchar, is to cast the column during replace. Borrowing the code from the accepted answer:

UPDATE YourTable
SET Column1 = REPLACE(cast(Column1 as nvarchar(max)),'a','b')
WHERE Column1 LIKE '%a%'

This worked perfectly for me. Thanks to this forum post I found for the fix. Hopefully this helps someone else!

Getting the source of a specific image element with jQuery

To select and element where you know only the attribute value you can use the below jQuery script

var src = $('.conversation_img[alt="example"]').attr('src');

Please refer the jQuery Documentation for attribute equals selectors

Please also refer to the example in Demo

Following is the code incase you are not able to access the demo..

HTML

<div>
    <img alt="example" src="\images\show.jpg" />
    <img  alt="exampleAll" src="\images\showAll.jpg" />  

</div>

SCRIPT JQUERY

var src = $('img[alt="example"]').attr('src');
alert("source of image with alternate text = example - " + src);


var srcAll = $('img[alt="exampleAll"]').attr('src');
alert("source of image with alternate text = exampleAll - " + srcAll );

Output will be

Two Alert messages each having values

  1. source of image with alternate text = example - \images\show.jpg
  2. source of image with alternate text = exampleAll - \images\showAll.jpg

How to print colored text to the terminal?

If you are using Django:

>>> from django.utils.termcolors import colorize
>>> print colorize("Hello, World!", fg="blue", bg='red',
...                 opts=('bold', 'blink', 'underscore',))
Hello World!
>>> help(colorize)

Snapshot:

Image

(I generally use colored output for debugging on runserver terminal, so I added it.)

You can test if it is installed in your machine: $ python -c "import django; print django.VERSION". To install it, check: How to install Django

Give it a try!!

Get the Id of current table row with Jquery

This:

<table id="test">
      <tr  id="TEST1" >
          <td align="left" valign="middle"><div align="right">Contact</div></td>
          <td colspan="4" align="left" valign="middle">
          <input type="text" id="contact1" size="20" />  Number 
          <input type="text" id="number1" size="20" /> 
          </td>
          <td>
          <input type="button"  value="Button 1" id="contact1" /></td>
      </tr>


      <tr id="TEST2" >
          <td align="left" valign="middle"><div align="right">Contact</div></td>
          <td colspan="4" align="left" valign="middle">
          <input type="text" id="contact2" size="20" />  Number 
          <input type="text" id="number2" size="20" /> 
          </td>
          <td>
          <input type="button"  value="Button 1"  id="contact2" />
          </td> 
      </tr>

      <tr id="TEST3" >
          <td align="left" valign="middle"><div align="right">Contact</div></td>
          <td colspan="4" align="left" valign="middle">
          <input type="text" id="contact3" size="20" />  Number 
          <input type="text" id="number3" size="20" /> 
          </td>
          <td>
          <input type="button"  value="Button 1"  id="contact2" />
          </td> 
</tr>

and javascript:

$(function() {
  var bid, trid;
  $('#test tr').click(function() {
       trid = $(this).attr('id'); // table row ID 
       alert(trid);
  });

});

It worked here!

How to iterate using ngFor loop Map containing key as string and values as map iteration

For Angular 6.1+ , you can use default pipe keyvalue ( Do review and upvote also ) :

<ul>
    <li *ngFor="let recipient of map | keyvalue">
        {{recipient.key}} --> {{recipient.value}}
    </li>
</ul>

WORKING DEMO


For the previous version :

One simple solution to this is convert map to array : Array.from

Component Side :

map = new Map<String, String>();

constructor(){
    this.map.set("sss","sss");
    this.map.set("aaa","sss");
    this.map.set("sass","sss");
    this.map.set("xxx","sss");
    this.map.set("ss","sss");
    this.map.forEach((value: string, key: string) => {
        console.log(key, value);
    });
}

getKeys(map){
    return Array.from(map.keys());
}

Template Side :

<ul>
  <li *ngFor="let recipient of getKeys(map)">
    {{recipient}}
   </li>
</ul>

WORKING DEMO

Are 2 dimensional Lists possible in c#?

You can also..do in this way,

List<List<Object>> Parent=new  List<List<Object>>();

List<Object> Child=new List<Object>();
child.Add(2349);
child.Add("Daft Punk");
child.Add("Human");
.
.
Parent.Add(child);

if you need another item(child), create a new instance of child,

Child=new List<Object>();
child.Add(2323);
child.Add("asds");
child.Add("jshds");
.
.
Parent.Add(child);

What is the difference between signed and unsigned int

Sometimes we know in advance that the value stored in a given integer variable will always be positive-when it is being used to only count things, for example. In such a case we can declare the variable to be unsigned, as in, unsigned int num student;. With such a declaration, the range of permissible integer values (for a 32-bit compiler) will shift from the range -2147483648 to +2147483647 to range 0 to 4294967295. Thus, declaring an integer as unsigned almost doubles the size of the largest possible value that it can otherwise hold.

Java: Add elements to arraylist with FOR loop where element name has increasing number

That can't be done with a for-loop, unless you use the Reflection API. However, you can use Arrays.asList instead to accomplish the same:

List<Answer> answers = Arrays.asList(answer1, answer2, answer3);

If using maven, usually you put log4j.properties under java or resources?

Just putting it in src/main/resources will bundle it inside the artifact. E.g. if your artifact is a JAR, you will have the log4j.properties file inside it, losing its initial point of making logging configurable.

I usually put it in src/main/resources, and set it to be output to target like so:

<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <targetPath>${project.build.directory}</targetPath>
            <includes>
                <include>log4j.properties</include>
            </includes>
        </resource>
    </resources>
</build>

Additionally, in order for log4j to actually see it, you have to add the output directory to the class path. If your artifact is an executable JAR, you probably used the maven-assembly-plugin to create it. Inside that plugin, you can add the current folder of the JAR to the class path by adding a Class-Path manifest entry like so:

<plugin>
    <artifactId>maven-assembly-plugin</artifactId>
    <configuration>
        <archive>
            <manifest>
                <mainClass>com.your-package.Main</mainClass>
            </manifest>
            <manifestEntries>
                <Class-Path>.</Class-Path>
            </manifestEntries>
        </archive>
        <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
        </descriptorRefs>
    </configuration>
    <executions>
        <execution>
            <id>make-assembly</id> <!-- this is used for inheritance merges -->
            <phase>package</phase> <!-- bind to the packaging phase -->
            <goals>
                <goal>single</goal>
            </goals>
        </execution>
    </executions>
</plugin>

Now the log4j.properties file will be right next to your JAR file, independently configurable.

To run your application directly from Eclipse, add the resources directory to your classpath in your run configuration: Run->Run Configurations...->Java Application->New select the Classpath tab, select Advanced and browse to your src/resources directory.

Java String array: is there a size of method?

Arrays are objects and they have a length field.

String[] haha = {"olle", "bulle"};

haha.length would be 2

How to convert milliseconds into human readable form?

This is a method I wrote. It takes an integer milliseconds value and returns a human-readable String:

public String convertMS(int ms) {
    int seconds = (int) ((ms / 1000) % 60);
    int minutes = (int) (((ms / 1000) / 60) % 60);
    int hours = (int) ((((ms / 1000) / 60) / 60) % 24);

    String sec, min, hrs;
    if(seconds<10)  sec="0"+seconds;
    else            sec= ""+seconds;
    if(minutes<10)  min="0"+minutes;
    else            min= ""+minutes;
    if(hours<10)    hrs="0"+hours;
    else            hrs= ""+hours;

    if(hours == 0)  return min+":"+sec;
    else    return hrs+":"+min+":"+sec;

}

PHP function use variable from outside

Just put in the function using GLOBAL keyword:

 global $site_url;

How to replace all dots in a string using JavaScript

You need to escape the . because it has the meaning of "an arbitrary character" in a regular expression.

mystring = mystring.replace(/\./g,' ')

How to Generate a random number of fixed length using JavaScript?


Only fully reliable answer that offers full randomness, without loss. The other ones prior to this answer all looses out depending on how many characters you want. The more you want, the more they lose randomness.

They achieve it by limiting the amount of numbers possible preceding the fixed length.

So for instance, a random number of fixed length 2 would be 10 - 99. For 3, 100 - 999. For 4, 1000 - 9999. For 5 10000 - 99999 and so on. As can be seen by the pattern, it suggests 10% loss of randomness because numbers prior to that are not possible. Why?

For really large numbers ( 18, 24, 48 ) 10% is still a lot of numbers to loose out on.

function generate(n) {
        var add = 1, max = 12 - add;   // 12 is the min safe number Math.random() can generate without it starting to pad the end with zeros.   

        if ( n > max ) {
                return generate(max) + generate(n - max);
        }

        max        = Math.pow(10, n+add);
        var min    = max/10; // Math.pow(10, n) basically
        var number = Math.floor( Math.random() * (max - min + 1) ) + min;

        return ("" + number).substring(add); 
}

The generator allows for ~infinite length without lossy precision and with minimal performance cost.

Example:

generate(2)
"03"
generate(2)
"72"
generate(2)
"20"
generate(3)
"301"
generate(3)
"436"
generate(3)
"015"

As you can see, even the zero are included initially which is an additional 10% loss just that, besides the fact that numbers prior to 10^n are not possible.

That's now a total of 20%.

Also, the other options have an upper limit on how many characters you can actually generate.

Example with cost:

var start = new Date(); var num = generate(1000); console.log('Time: ', new Date() - start, 'ms for', num)

Logs:

Time: 0 ms for 7884381040581542028523049580942716270617684062141718855897876833390671831652069714762698108211737288889182869856548142946579393971303478191296939612816492205372814129483213770914444439430297923875275475120712223308258993696422444618241506074080831777597175223850085606310877065533844577763231043780302367695330451000357920496047212646138908106805663879875404784849990477942580056343258756712280958474020627842245866908290819748829427029211991533809630060693336825924167793796369987750553539230834216505824880709596544701685608502486365633618424746636614437646240783649056696052311741095247677377387232206206230001648953246132624571185908487227730250573902216708727944082363775298758556612347564746106354407311558683595834088577220946790036272364740219788470832285646664462382109714500242379237782088931632873392735450875490295512846026376692233811845787949465417190308589695423418373731970944293954443996348633968914665773009376928939207861596826457540403314327582156399232931348229798533882278769760

More hardcore:

generate(100000).length === 100000 -> true

In Typescript, How to check if a string is Numeric

Simple answer: (watch for blank & null)

isNaN(+'111') = false;
isNaN(+'111r') = true;
isNaN(+'r') = true;
isNaN(+'') = false;   
isNaN(null) = false;   

https://codepen.io/CQCoder/pen/zYGEjxd?editors=1111

Appending an element to the end of a list in Scala

That's because you shouldn't do it (at least with an immutable list). If you really really need to append an element to the end of a data structure and this data structure really really needs to be a list and this list really really has to be immutable then do eiher this:

(4 :: List(1,2,3).reverse).reverse

or that:

List(1,2,3) ::: List(4)

How to printf uint64_t? Fails with: "spurious trailing ‘%’ in format"

When compiling memcached under Centos 5.x i got the same problem.

The solution is to upgrade gcc and g++ to version 4.4 at least.

Make sure your CC/CXX is set (exported) to right binaries before compiling.

How can I show a message box with two buttons?

You probably want to do something like this:

result = MsgBox ("Yes or No?", vbYesNo, "Yes No Example")

Select Case result
Case vbYes
    MsgBox("You chose Yes")
Case vbNo
    MsgBox("You chose No")
End Select

To add an icon:

result = MsgBox ("Yes or No?", vbYesNo + vbQuestion, "Yes No Example")

Other icon options:

vbCritical or vbExclamation

How to set UTF-8 encoding for a PHP file

header('Content-type: text/plain; charset=utf-8');

Deleting objects from an ArrayList in Java

I'm good with Mnementh's recommentation.
Just one caveat though,

 ConcurrentModificationException

Mind that you don't have more than one thread running. This exception could appear if more than one thread executes, and the threads are not well synchronized.

How can I get the source directory of a Bash script from within the script itself?

None of these other answers worked for a Bash script launched by Finder in OS X. I ended up using:

SCRIPT_LOC="`ps -p $$ | sed /PID/d | sed s:.*/Network/:/Network/: |
sed s:.*/Volumes/:/Volumes/:`"

It is not pretty, but it gets the job done.

Where are SQL Server connection attempts logged?

You can enable connection logging. For SQL Server 2008, you can enable Login Auditing. In SQL Server Management Studio, open SQL Server Properties > Security > Login Auditing select "Both failed and successful logins".

Make sure to restart the SQL Server service.

Once you've done that, connection attempts should be logged into SQL's error log. The physical logs location can be determined here.

How to do tag wrapping in VS code?

  1. Open Keyboard Shortcuts by typing ? Command+k ? Command+s or Code > Preferences > Keyboard Shortcuts
  2. Type emmet wrap
  3. Click the plus sign to the left of "Emmet: Wrap with Abbreviation"
  4. Type ? Option+w
  5. Press Enter

3 column layout HTML/CSS

This is less for @easwee and more for others that might have the same question:

If you do not require support for IE < 10, you can use Flexbox. It's an exciting CSS3 property that unfortunately was implemented in several different versions,; add in vendor prefixes, and getting good cross-browser support suddenly requires quite a few more properties than it should.

With the current, final standard, you would be done with

.container {
    display: flex;
}

.container div {
    flex: 1;
}

.column_center {
    order: 2;
}

That's it. If you want to support older implementations like iOS 6, Safari < 6, Firefox 19 or IE10, this blossoms into

.container {
    display: -webkit-box;      /* OLD - iOS 6-, Safari 3.1-6 */
    display: -moz-box;         /* OLD - Firefox 19- (buggy but mostly works) */
    display: -ms-flexbox;      /* TWEENER - IE 10 */
    display: -webkit-flex;     /* NEW - Chrome */
    display: flex;             /* NEW, Spec - Opera 12.1, Firefox 20+ */
}

.container div {
    -webkit-box-flex: 1;      /* OLD - iOS 6-, Safari 3.1-6 */
    -moz-box-flex: 1;         /* OLD - Firefox 19- */
    -webkit-flex: 1;          /* Chrome */
    -ms-flex: 1;              /* IE 10 */
    flex: 1;                  /* NEW, Spec - Opera 12.1, Firefox 20+ */
}

.column_center {
    -webkit-box-ordinal-group: 2;   /* OLD - iOS 6-, Safari 3.1-6 */
    -moz-box-ordinal-group: 2;      /* OLD - Firefox 19- */
    -ms-flex-order: 2;              /* TWEENER - IE 10 */
    -webkit-order: 2;               /* NEW - Chrome */
    order: 2;                       /* NEW, Spec - Opera 12.1, Firefox 20+ */
}

jsFiddle demo

Here is an excellent article about Flexbox cross-browser support: Using Flexbox: Mixing Old And New

Script to get the HTTP status code of a list of urls?

Due to https://mywiki.wooledge.org/BashPitfalls#Non-atomic_writes_with_xargs_-P (output from parallel jobs in xargs risks being mixed), I would use GNU Parallel instead of xargs to parallelize:

cat url.lst |
  parallel -P0 -q curl -o /dev/null --silent --head --write-out '%{url_effective}: %{http_code}\n' > outfile

In this particular case it may be safe to use xargs because the output is so short, so the problem with using xargs is rather that if someone later changes the code to do something bigger, it will no longer be safe. Or if someone reads this question and thinks he can replace curl with something else, then that may also not be safe.

How to hide a column (GridView) but still access its value?

If you do have a TemplateField inside the columns of your GridView and you have, say, a control named blah bound to it. Then place the outlook_id as a HiddenField there like this:

<asp:TemplateField HeaderText="OutlookID">
    <ItemTemplate>
        <asp:Label ID="blah" runat="server">Existing Control</asp:Label>
        <asp:HiddenField ID="HiddenOutlookID" runat="server" Value='<%#Eval("Outlook_ID") %>'/>
    </ItemTemplate>
</asp:TemplateField>

Now, grab the row in the event you want the outlook_id and then access the control.
For RowDataBound access it like:

string outlookid = ((HiddenField)e.Row.FindControl("HiddenOutlookID")).Value;

Do get back, if you have trouble accessing the clicked row. And don't forget to mention the event at which you would like to access that.

How do I get the coordinates of a mouse click on a canvas element?

Edit 2018: This answer is pretty old and it uses checks for old browsers that are not necessary anymore, as the clientX and clientY properties work in all current browsers. You might want to check out Patriques Answer for a simpler, more recent solution.

Original Answer:
As described in an article i found back then but exists no longer:

var x;
var y;
if (e.pageX || e.pageY) { 
  x = e.pageX;
  y = e.pageY;
}
else { 
  x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; 
  y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop; 
} 
x -= gCanvasElement.offsetLeft;
y -= gCanvasElement.offsetTop;

Worked perfectly fine for me.

Path of currently executing powershell script

Split-Path $MyInvocation.MyCommand.Path -Parent

How to use null in switch

switch (String.valueOf(value)){
    case "null":
    default: 
}

Move top 1000 lines from text file to a new file using Unix shell commands

Out of curiosity, I found a box with a GNU version of sed (v4.1.5) and tested the (uncached) performance of two approaches suggested so far, using an 11M line text file:

$ wc -l input
11771722 input

$ time head -1000 input > output; time tail -n +1000 input > input.tmp; time cp input.tmp input; time rm input.tmp

real    0m1.165s
user    0m0.030s
sys     0m1.130s

real    0m1.256s
user    0m0.062s
sys     0m1.162s

real    0m4.433s
user    0m0.033s
sys     0m1.282s

real    0m6.897s
user    0m0.000s
sys     0m0.159s

$ time head -1000 input > output && time sed -i '1,+999d' input

real    0m0.121s
user    0m0.000s
sys     0m0.121s

real    0m26.944s
user    0m0.227s
sys     0m26.624s

This is the Linux I was working with:

$ uname -a
Linux hostname 2.6.18-128.1.1.el5 #1 SMP Mon Jan 26 13:58:24 EST 2009 x86_64 x86_64 x86_64 GNU/Linux

For this test, at least, it looks like sed is slower than the tail approach (27 sec vs ~14 sec).

Using Java with Microsoft Visual Studio 2012

Using Visual Studio IDE for porting Java to C#:

Currently I am using Visual Studio IDE environment for porting codes from Java to C#. Why? Java has a huge libraries and C# enables the access to the UWP ecosystem.

For supporting editing and debugging as well as examining Java Bytecode (disassembly), you could try:

For supporting Android (Java/C++) development, you could try:

What is the best way to manage a user's session in React?

I would avoid using component state since this could be difficult to manage and prone to issues that can be difficult to troubleshoot.

You should use either cookies or localStorage for persisting a user's session data. You can also use a closure as a wrapper around your cookie or localStorage data.

Here is a simple example of a UserProfile closure that will hold the user's name.

var UserProfile = (function() {
  var full_name = "";

  var getName = function() {
    return full_name;    // Or pull this from cookie/localStorage
  };

  var setName = function(name) {
    full_name = name;     
    // Also set this in cookie/localStorage
  };

  return {
    getName: getName,
    setName: setName
  }

})();

export default UserProfile;

When a user logs in, you can populate this object with user name, email address etc.

import UserProfile from './UserProfile';

UserProfile.setName("Some Guy");

Then you can get this data from any component in your app when needed.

import UserProfile from './UserProfile';

UserProfile.getName();

Using a closure will keep data outside of the global namespace, and make it is easily accessible from anywhere in your app.

Find all controls in WPF Window by type

Small change to the recursion to so you can for example find the child tab control of a tab control.

    public static DependencyObject FindInVisualTreeDown(DependencyObject obj, Type type)
    {
        if (obj != null)
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(obj, i);

                if (child.GetType() == type)
                {
                    return child;
                }

                DependencyObject childReturn = FindInVisualTreeDown(child, type);
                if (childReturn != null)
                {
                    return childReturn;
                }
            }
        }

        return null;
    }

How to give ASP.NET access to a private key in a certificate in the certificate store?

If you are trying to load a cert from a .pfx file in IIS the solution may be as simple as enabling this option for the Application Pool.

Right click on the App Pool and select Advanced Settings.

Then enable Load User Profile


enter image description here

Excel VBA - select multiple columns not in sequential order

Working on a project I was stuck for some time on this concept - I ended up with a similar answer to Method 1 by @GSerg that worked great. Essentially I defined two formula ranges (using a few variables) and then used the Union concept. My example is from a larger project that I'm working on but hopefully the portion of code below can help some other people who might not know how to use the Union concept in conjunction with defined ranges and variables. I didn't include the entire code because at this point it's fairly long - if anyone wants more insight feel free to let me know.

First I declared all my variables as Public

Then I defined/set each variable

Lastly I set a new variable "SelectRanges" as the Union between the two other FormulaRanges

Public r As Long
Public c As Long
Public d As Long
Public FormulaRange3 As Range
Public FormulaRange4 As Range
Public SelectRanges As Range

With Sheet8




  c = pvt.DataBodyRange.Columns.Count + 1

  d = 3

  r = .Cells(.Rows.Count, 1).End(xlUp).Row

Set FormulaRange3 = .Range(.Cells(d, c + 2), .Cells(r - 1, c + 2))
    FormulaRange3.NumberFormat = "0"
    Set FormulaRange4 = .Range(.Cells(d, c + c + 2), .Cells(r - 1, c + c + 2))
    FormulaRange4.NumberFormat = "0"
    Set SelectRanges = Union(FormulaRange3, FormulaRange4)

How can I create a border around an Android LinearLayout?

Sure. You can add a border to any layout you want. Basically, you need to create a custom drawable and add it as a background to your layout. example:

Create a file called customborder.xml in your drawable folder:

<?xml version="1.0" encoding="UTF-8"?>
 <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
   <corners android:radius="20dp"/> 
   <padding android:left="10dp" android:right="10dp" android:top="10dp" android:bottom="10dp"/>
   <stroke android:width="1dp" android:color="#CCCCCC"/>
 </shape>

Now apply it as a background to your smaller layout:

<LinearLayout android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/customborder">

That should do the trick.

Also see:

How to scanf only integer and repeat reading if the user enters non-numeric characters?

char check1[10], check2[10];
int foo;

do{
  printf(">> ");
  scanf(" %s", check1);
  foo = strtol(check1, NULL, 10); // convert the string to decimal number
  sprintf(check2, "%d", foo); // re-convert "foo" to string for comparison
} while (!(strcmp(check1, check2) == 0 && 0 < foo && foo < 24)); // repeat if the input is not number

If the input is number, you can use foo as your input.

Random row selection in Pandas dataframe

With pandas version 0.16.1 and up, there is now a DataFrame.sample method built-in:

import pandas

df = pandas.DataFrame(pandas.np.random.random(100))

# Randomly sample 70% of your dataframe
df_percent = df.sample(frac=0.7)

# Randomly sample 7 elements from your dataframe
df_elements = df.sample(n=7)

For either approach above, you can get the rest of the rows by doing:

df_rest = df.loc[~df.index.isin(df_percent.index)]

Java regex capturing groups indexes

Capturing and grouping

Capturing group (pattern) creates a group that has capturing property.

A related one that you might often see (and use) is (?:pattern), which creates a group without capturing property, hence named non-capturing group.

A group is usually used when you need to repeat a sequence of patterns, e.g. (\.\w+)+, or to specify where alternation should take effect, e.g. ^(0*1|1*0)$ (^, then 0*1 or 1*0, then $) versus ^0*1|1*0$ (^0*1 or 1*0$).

A capturing group, apart from grouping, will also record the text matched by the pattern inside the capturing group (pattern). Using your example, (.*):, .* matches ABC and : matches :, and since .* is inside capturing group (.*), the text ABC is recorded for the capturing group 1.

Group number

The whole pattern is defined to be group number 0.

Any capturing group in the pattern start indexing from 1. The indices are defined by the order of the opening parentheses of the capturing groups. As an example, here are all 5 capturing groups in the below pattern:

(group)(?:non-capturing-group)(g(?:ro|u)p( (nested)inside)(another)group)(?=assertion)
|     |                       |          | |      |      ||       |     |
1-----1                       |          | 4------4      |5-------5     |
                              |          3---------------3              |
                              2-----------------------------------------2

The group numbers are used in back-reference \n in pattern and $n in replacement string.

In other regex flavors (PCRE, Perl), they can also be used in sub-routine calls.

You can access the text matched by certain group with Matcher.group(int group). The group numbers can be identified with the rule stated above.

In some regex flavors (PCRE, Perl), there is a branch reset feature which allows you to use the same number for capturing groups in different branches of alternation.

Group name

From Java 7, you can define a named capturing group (?<name>pattern), and you can access the content matched with Matcher.group(String name). The regex is longer, but the code is more meaningful, since it indicates what you are trying to match or extract with the regex.

The group names are used in back-reference \k<name> in pattern and ${name} in replacement string.

Named capturing groups are still numbered with the same numbering scheme, so they can also be accessed via Matcher.group(int group).

Internally, Java's implementation just maps from the name to the group number. Therefore, you cannot use the same name for 2 different capturing groups.