Programs & Examples On #Ushort

Error LNK2019: Unresolved External Symbol in Visual Studio

When you have everything #included, an unresolved external symbol is often a missing * or & in the declaration or definition of a function.

In PowerShell, how can I test if a variable holds a numeric value?

PS> Add-Type -Assembly Microsoft.VisualBasic
PS> [Microsoft.VisualBasic.Information]::IsNumeric(1.5)
True

http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.information.isnumeric.aspx

How to convert a structure to a byte array in C#?

Variant of the code of Vicent with one less memory allocation:

public static byte[] GetBytes<T>(T str)
{
    int size = Marshal.SizeOf(str);

    byte[] arr = new byte[size];

    GCHandle h = default(GCHandle);

    try
    {
        h = GCHandle.Alloc(arr, GCHandleType.Pinned);

        Marshal.StructureToPtr<T>(str, h.AddrOfPinnedObject(), false);
    }
    finally
    {
        if (h.IsAllocated)
        {
            h.Free();
        }
    }

    return arr;
}

public static T FromBytes<T>(byte[] arr) where T : struct
{
    T str = default(T);

    GCHandle h = default(GCHandle);

    try
    {
        h = GCHandle.Alloc(arr, GCHandleType.Pinned);

        str = Marshal.PtrToStructure<T>(h.AddrOfPinnedObject());

    }
    finally
    {
        if (h.IsAllocated)
        {
            h.Free();
        }
    }

    return str;
}

I use GCHandle to "pin" the memory and then I use directly its address with h.AddrOfPinnedObject().

How do I sort an observable collection?

What the heck, I'll throw in a quickly-cobbled-together answer as well...it looks a bit like some other implementations here, but I'll add it anywho:

(barely tested, hopefully I'm not embarassing myself)

Let's state some goals first (my assumptions):

1) Must sort ObservableCollection<T> in place, to maintain notifications, etc.

2) Must not be horribly inefficient (i.e., something close to standard "good" sorting efficiency)

public static class Ext
{
    public static void Sort<T>(this ObservableCollection<T> src)
        where T : IComparable<T>
    {
        // Some preliminary safety checks
        if(src == null) throw new ArgumentNullException("src");
        if(!src.Any()) return;

        // N for the select,
        // + ~ N log N, assuming "smart" sort implementation on the OrderBy
        // Total: N log N + N (est)
        var indexedPairs = src
            .Select((item,i) => Tuple.Create(i, item))
            .OrderBy(tup => tup.Item2);
        // N for another select
        var postIndexedPairs = indexedPairs
            .Select((item,i) => Tuple.Create(i, item.Item1, item.Item2));
        // N for a loop over every element
        var pairEnum = postIndexedPairs.GetEnumerator();
        pairEnum.MoveNext();
        for(int idx = 0; idx < src.Count; idx++, pairEnum.MoveNext())
        {
            src.RemoveAt(pairEnum.Current.Item1);
            src.Insert(idx, pairEnum.Current.Item3);            
        }
        // (very roughly) Estimated Complexity: 
        // N log N + N + N + N
        // == N log N + 3N
    }
}

How to create a thread?

The following ways work.

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

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

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

The Startup methods have following signature for these examples.

public void StartupA(object parameters);

public void StartupB(int port, string path);

Logical operators for boolean indexing in Pandas

When you say

(a['x']==1) and (a['y']==10)

You are implicitly asking Python to convert (a['x']==1) and (a['y']==10) to boolean values.

NumPy arrays (of length greater than 1) and Pandas objects such as Series do not have a boolean value -- in other words, they raise

ValueError: The truth value of an array is ambiguous. Use a.empty, a.any() or a.all().

when used as a boolean value. That's because its unclear when it should be True or False. Some users might assume they are True if they have non-zero length, like a Python list. Others might desire for it to be True only if all its elements are True. Others might want it to be True if any of its elements are True.

Because there are so many conflicting expectations, the designers of NumPy and Pandas refuse to guess, and instead raise a ValueError.

Instead, you must be explicit, by calling the empty(), all() or any() method to indicate which behavior you desire.

In this case, however, it looks like you do not want boolean evaluation, you want element-wise logical-and. That is what the & binary operator performs:

(a['x']==1) & (a['y']==10)

returns a boolean array.


By the way, as alexpmil notes, the parentheses are mandatory since & has a higher operator precedence than ==. Without the parentheses, a['x']==1 & a['y']==10 would be evaluated as a['x'] == (1 & a['y']) == 10 which would in turn be equivalent to the chained comparison (a['x'] == (1 & a['y'])) and ((1 & a['y']) == 10). That is an expression of the form Series and Series. The use of and with two Series would again trigger the same ValueError as above. That's why the parentheses are mandatory.

Creating a button in Android Toolbar

I was able to achieve that by wrapping Button with ConstraintLayout:

<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:elevation="0dp">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/top_toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/white_color">

            <androidx.constraintlayout.widget.ConstraintLayout
                android:layout_width="match_parent"
                android:layout_marginTop="10dp"
                android:layout_height="wrap_content">

                <TextView
                    android:id="@+id/cancel"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/cancel"
                    android:layout_marginStart="5dp"
                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintLeft_toLeftOf="parent"
                    app:layout_constraintTop_toTopOf="parent" />

                <Button
                    android:id="@+id/btn_publish"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/publish"
                    android:background="@drawable/button_publish_rounded"
                    app:layout_constraintTop_toTopOf="parent"
                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintEnd_toEndOf="parent"
                    android:layout_marginEnd="10dp"
                    app:layout_constraintLeft_toRightOf="@id/cancel"
                    tools:layout_editor_absoluteY="0dp" />

            </androidx.constraintlayout.widget.ConstraintLayout>

        </androidx.appcompat.widget.Toolbar>

    </com.google.android.material.appbar.AppBarLayout>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

You may create a drawable resourcebutton_publish_rounded, define the button properties and assign this file to button's android:background property:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/green" />
    <corners android:radius="100dp" />
</shape>

Tomcat 404 error: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

Problem solved, I've not added the index.html. Which is point out in the web.xml

enter image description here

Note: a project may have more than one web.xml file.

if there are another web.xml in

src/main/webapp/WEB-INF

Then you might need to add another index (this time index.jsp) to

src/main/webapp/WEB-INF/pages/

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");
  }
});

Is there a short contains function for lists?

In addition to what other have said, you may also be interested to know that what in does is to call the list.__contains__ method, that you can define on any class you write and can get extremely handy to use python at his full extent.  

A dumb use may be:

>>> class ContainsEverything:
    def __init__(self):
        return None
    def __contains__(self, *elem, **k):
        return True


>>> a = ContainsEverything()
>>> 3 in a
True
>>> a in a
True
>>> False in a
True
>>> False not in a
False
>>>         

Bad Request - Invalid Hostname IIS7

For Visual Studio 2017 and Visual Studio 2015, IIS Express settings is stored in the hidden .vs directory and the path is something like this .vs\config\applicationhost.config, add binding like below will work

<bindings>
    <binding protocol="http" bindingInformation="*:8802:localhost" />
    <binding protocol="http" bindingInformation="*:8802:127.0.0.1" />
</bindings>

Syntax: https://docs.microsoft.com/en-us/dotnet/api/microsoft.web.administration.binding.bindinginformation?view=iis-dotnet

Hexadecimal value 0x00 is a invalid character

I'm using IronPython here (same as .NET API) and reading the file as UTF-8 in order to properly handle the BOM fixed the problem for me:

xmlFile = Path.Combine(directory_str, 'file.xml')
doc = XPathDocument(XmlTextReader(StreamReader(xmlFile.ToString(), Encoding.UTF8)))

It would work as well with the XmlDocument:

doc = XmlDocument()
doc.Load(XmlTextReader(StreamReader(xmlFile.ToString(), Encoding.UTF8)))

Why does ASP.NET webforms need the Runat="Server" attribute?

My suspicion is that it has to do with how server-side controls are identified during processing. Rather than having to check every control at runtime by name to determine whether server-side processing needs to be done, it does a selection on the internal node representation by tag. The compiler checks to make sure that all controls that require server tags have them during the validation step.

Why has it failed to load main-class manifest attribute from a JAR file?

You can run with:

java -cp .;app.jar package.MainClass

It works for me if there is no manifest in the JAR file.

How do I free memory in C?

You actually can't manually "free" memory in C, in the sense that the memory is released from the process back to the OS ... when you call malloc(), the underlying libc-runtime will request from the OS a memory region. On Linux, this may be done though a relatively "heavy" call like mmap(). Once this memory region is mapped to your program, there is a linked-list setup called the "free store" that manages this allocated memory region. When you call malloc(), it quickly looks though the free-store for a free block of memory at the size requested. It then adjusts the linked list to reflect that there has been a chunk of memory taken out of the originally allocated memory pool. When you call free() the memory block is placed back in the free-store as a linked-list node that indicates its an available chunk of memory.

If you request more memory than what is located in the free-store, the libc-runtime will again request more memory from the OS up to the limit of the OS's ability to allocate memory for running processes. When you free memory though, it's not returned back to the OS ... it's typically recycled back into the free-store where it can be used again by another call to malloc(). Thus, if you make a lot of calls to malloc() and free() with varying memory size requests, it could, in theory, cause a condition called "memory fragmentation", where there is enough space in the free-store to allocate your requested memory block, but not enough contiguous space for the size of the block you've requested. Thus the call to malloc() fails, and you're effectively "out-of-memory" even though there may be plenty of memory available as a total amount of bytes in the free-store.

How to modify memory contents using GDB?

Expanding on the answers provided here.

You can just do set idx = 1 to set a variable, but that syntax is not recommended because the variable name may clash with a set sub-command. As an example set w=1 would not be valid.

This means that you should prefer the syntax: set variable idx = 1 or set var idx = 1.

Last but not least, you can just use your trusty old print command, since it evaluates an expression. The only difference being that he also prints the result of the expression.

(gdb) p idx = 1
$1 = 1

You can read more about gdb here.

Reason for Column is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause

Suppose I have the following table T:

a   b
--------
1   abc
1   def
1   ghi
2   jkl
2   mno
2   pqr

And I do the following query:

SELECT a, b
FROM T
GROUP BY a

The output should have two rows, one row where a=1 and a second row where a=2.

But what should the value of b show on each of these two rows? There are three possibilities in each case, and nothing in the query makes it clear which value to choose for b in each group. It's ambiguous.

This demonstrates the single-value rule, which prohibits the undefined results you get when you run a GROUP BY query, and you include any columns in the select-list that are neither part of the grouping criteria, nor appear in aggregate functions (SUM, MIN, MAX, etc.).

Fixing it might look like this:

SELECT a, MAX(b) AS x
FROM T
GROUP BY a

Now it's clear that you want the following result:

a   x
--------
1   ghi
2   pqr

What's an object file in C?

Object files are codes that are dependent on functions, symbols, and text to run the program. Just like old telex machines, which required teletyping to send signals to other telex machine.

In the same way processor's require binary code to run, object files are like binary code but not linked. Linking creates additional files so that the user does not have to have compile the C language themselves. Users can directly open the exe file once the object file is linked with some compiler like c language , or vb etc.

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.

What is a good naming convention for vars, methods, etc in C++?

consistency and readability (self-documenting code) are important. some clues (such as case) can and should be used to avoid collisions, and to indicate whether an instance is required.

one of the best practices i got into was the use of code formatters (astyle and uncrustify are 2 examples). code formatters can destroy your code formatting - configure the formatter, and let it do its job. seriously, forget about manual formatting and get into the practice of using them. they will save a ton of time.

as mentioned, be very descriptive with naming. also, be very specific with scoping (class types/data/namespaces/anonymous namespaces). in general, i really like much of java's common written form - that is a good reference and similar to c++.

as for specific appearance/naming, this is a small sample similar to what i use (variables/arguments are lowerCamel and this only demonstrates a portion of the language's features):

/** MYC_BEGIN_FILE_ID::FD_Directory_nanotimer_FN_nanotimer_hpp_::MYC_BEGIN_FILE_DIR::Directory/nanotimer::MYC_BEGIN_FILE_FILE::nanotimer.hpp::Copyright... */
#ifndef FD_Directory_nanotimer_FN_nanotimer_hpp_
#define FD_Directory_nanotimer_FN_nanotimer_hpp_

/* typical commentary omitted -- comments detail notations/conventions. also, no defines/macros other than header guards */

namespace NamespaceName {

/* types prefixed with 't_' */
class t_nanotimer : public t_base_timer {
    /* private types */
    class t_thing {
        /*...*/
    };
public:
    /* public types */
    typedef uint64_t t_nanosecond;

    /* factory initializers -- UpperCamel */
    t_nanotimer* WithFloat(const float& arg);
    /* public/protected class interface -- UpperCamel */
    static float Uptime();
protected:
    /* static class data -- UpperCamel -- accessors, if needed, use Get/Set prefix */
    static const t_spoke Spoke;
public:
    /* enums in interface are labeled as static class data */
    enum { Granularity = 4 };
public:
    /* construction/destruction -- always use proper initialization list */
    explicit t_nanotimer(t_init);
    explicit t_nanotimer(const float& arg);

    virtual ~t_nanotimer();

    /*
       public and protected instance methods -- lowercaseCamel()
       - booleans prefer is/has
       - accessors use the form: getVariable() setVariable().
       const-correctness is important
     */
    const void* address() const;
    virtual uint64_t hashCode() const;
protected:
    /* interfaces/implementation of base pure virtuals (assume this was pure virtual in t_base_timer) */
    virtual bool hasExpired() const;
private:
    /* private methods and private static data */
    void invalidate();
private:
    /*
       instance variables
       - i tend to use underscore suffix, but d_ (for example) is another good alternative
       - note redundancy in visibility
     */
    t_thing ivar_;
private:
    /* prohibited stuff */
    explicit t_nanotimer();
    explicit t_nanotimer(const int&);
};
} /* << NamespaceName */
/* i often add a multiple include else block here, preferring package-style inclusions */    
#endif /* MYC_END_FILE::FD_Directory_nanotimer_FN_nanotimer_hpp_ */

Callback function for JSONP with jQuery AJAX

$.ajax({
        url: 'http://url.of.my.server/submit',
        dataType: "jsonp",
        jsonp: 'callback',
        jsonpCallback: 'jsonp_callback'
    });

jsonp is the querystring parameter name that is defined to be acceptable by the server while the jsonpCallback is the javascript function name to be executed at the client.
When you use such url:

url: 'http://url.of.my.server/submit?callback=?'

the question mark ? at the end instructs jQuery to generate a random function while the predfined behavior of the autogenerated function will just invoke the callback -the sucess function in this case- passing the json data as a parameter.

$.ajax({
        url: 'http://url.of.my.server/submit?callback=?',
        success: function (data, status) {
            mySurvey.closePopup();
        },
        error: function (xOptions, textStatus) {
            mySurvey.closePopup();
        }
    });


The same goes here if you are using $.getJSON with ? placeholder it will generate a random function while the predfined behavior of the autogenerated function will just invoke the callback:

$.getJSON('http://url.of.my.server/submit?callback=?',function(data){
//process data here
});

Check if checkbox is checked with jQuery

Something like this can help

togglecheckBoxs =  function( objCheckBox ) {

    var boolAllChecked = true;

    if( false == objCheckBox.checked ) {
        $('#checkAll').prop( 'checked',false );
    } else {
        $( 'input[id^="someIds_"]' ).each( function( chkboxIndex, chkbox ) {
            if( false == chkbox.checked ) {
                $('#checkAll').prop( 'checked',false );
                boolAllChecked = false;
            }
        });

        if( true == boolAllChecked ) {
            $('#checkAll').prop( 'checked',true );
        }
    }
}

What is the 'pythonic' equivalent to the 'fold' function from functional programming?

In Python 3, the reduce has been removed: Release notes. Nevertheless you can use the functools module

import operator, functools
def product(xs):
    return functools.reduce(operator.mul, xs, 1)

On the other hand, the documentation expresses preference towards for-loop instead of reduce, hence:

def product(xs):
    result = 1
    for i in xs:
        result *= i
    return result

how to pass data in an hidden field from one jsp page to another?

The code from Alex works great. Just note that when you use request.getParameter you must use a request dispatcher

//Pass results back to the client
RequestDispatcher dispatcher =   getServletContext().getRequestDispatcher("TestPages/ServiceServlet.jsp");
dispatcher.forward(request, response);

jQuery `.is(":visible")` not working in Chrome

There is a weird case where if the element is set to display: inline the jQuery check for visibility fails.

Example:

CSS

#myspan {display: inline;}

jQuery

$('#myspan').show(); // Our element is `inline` instead of `block`
$('#myspan').is(":visible"); // This is false

To fix it you can hide the element in jQuery and than show/hide or toggle() should work fine.

$('#myspan').hide()
$('#otherElement').on('click', function() {
    $('#myspan').toggle();
});

Get the current date and time

DateTimePicker1.value = Format(Date.Now)

NGINX - No input file specified. - php Fast/CGI

For localhost - I forgot to write in C:\Windows\System32\drivers\etc\hosts

127.0.0.1 localhost

Also removed proxy_pass http://127.0.0.1; from other server in ngnix.conf

Sql Server : How to use an aggregate function like MAX in a WHERE clause

As you've noticed, the WHERE clause doesn't allow you to use aggregates in it. That's what the HAVING clause is for.

HAVING t1.field3=MAX(t1.field3)

Format Date/Time in XAML in Silverlight

you can also use just

StringFormat=d

in your datagrid column for date time showing

finally it will be

   <sdk:DataGridTextColumn  Binding="{Binding Path=DeliveryDate,StringFormat=d}" Header="Delivery date" Width="*" />

the out put will look like

enter image description here

JQuery find first parent element with specific class prefix

Use .closest() with a selector:

var $div = $('#divid').closest('div[class^="div-a"]');

Opening a folder in explorer and selecting a file

Using Process.Start on explorer.exe with the /select argument oddly only works for paths less than 120 characters long.

I had to use a native windows method to get it to work in all cases:

[DllImport("shell32.dll", SetLastError = true)]
public static extern int SHOpenFolderAndSelectItems(IntPtr pidlFolder, uint cidl, [In, MarshalAs(UnmanagedType.LPArray)] IntPtr[] apidl, uint dwFlags);

[DllImport("shell32.dll", SetLastError = true)]
public static extern void SHParseDisplayName([MarshalAs(UnmanagedType.LPWStr)] string name, IntPtr bindingContext, [Out] out IntPtr pidl, uint sfgaoIn, [Out] out uint psfgaoOut);

public static void OpenFolderAndSelectItem(string folderPath, string file)
{
    IntPtr nativeFolder;
    uint psfgaoOut;
    SHParseDisplayName(folderPath, IntPtr.Zero, out nativeFolder, 0, out psfgaoOut);

    if (nativeFolder == IntPtr.Zero)
    {
        // Log error, can't find folder
        return;
    }

    IntPtr nativeFile;
    SHParseDisplayName(Path.Combine(folderPath, file), IntPtr.Zero, out nativeFile, 0, out psfgaoOut);

    IntPtr[] fileArray;
    if (nativeFile == IntPtr.Zero)
    {
        // Open the folder without the file selected if we can't find the file
        fileArray = new IntPtr[0];
    }
    else
    {
        fileArray = new IntPtr[] { nativeFile };
    }

    SHOpenFolderAndSelectItems(nativeFolder, (uint)fileArray.Length, fileArray, 0);

    Marshal.FreeCoTaskMem(nativeFolder);
    if (nativeFile != IntPtr.Zero)
    {
        Marshal.FreeCoTaskMem(nativeFile);
    }
}

Calling C++ class methods via a function pointer

typedef void (Dog::*memfun)();
memfun doSomething = &Dog::bark;
....
(pDog->*doSomething)(); // if pDog is a pointer
// (pDog.*doSomething)(); // if pDog is a reference

How to know whether refresh button or browser back button is clicked in Firefox

var keyCode = evt.keyCode;
if (keyCode==8)
alert('you pressed backspace');

if(keyCode==116)
alert('you pressed f5 to reload page')

Get URL of ASP.Net Page in code-behind

Using a js file you can capture the following, that can be used in the codebehind as well:

<script type="text/javascript">
    alert('Server: ' + window.location.hostname);
    alert('Full path: ' + window.location.href);
    alert('Virtual path: ' + window.location.pathname);
    alert('HTTP path: ' + 
        window.location.href.replace(window.location.pathname, ''));    
</script>

Spring MVC 4: "application/json" Content Type is not being set correctly

When I upgraded to Spring 4 I needed to update the jackson dependencies as follows:

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.5.1</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.5.1</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.5.1</version>
    </dependency>        

git: patch does not apply

My issue is that I ran git diff, then ran git reset --hard HEAD, then realized I wanted to undo, so I tried copying the output from git diff into a file and using git apply, but I got an error that "patch does not apply". After switching to patch and trying to use it, I realized that a chunk of the diff was repeated for some reason, and after removing the duplicate, patch (and presumably also git apply) worked.

How to use Angular4 to set focus by element id

This helped to me (in ionic, but idea is the same) https://mhartington.io/post/setting-input-focus/

in template:

<ion-item>
      <ion-label>Home</ion-label>
      <ion-input #input type="text"></ion-input>
</ion-item>
<button (click)="focusInput(input)">Focus</button>

in controller:

  focusInput(input) {
    input.setFocus();
  }

How to use Selenium with Python?

You just need to get selenium package imported, that you can do from command prompt using the command

pip install selenium

When you have to use it in any IDE just import this package, no other documentation required to be imported

For Eg :

import selenium 
print(selenium.__filepath__)

This is just a general command you may use in starting to check the filepath of selenium

Get value of Span Text

You need to change your code as below:

<html>
<body>

<span id="span_Id">Click the button to display the content.</span>

<button onclick="displayDate()">Click Me</button>

<script>
function displayDate() {
   var span_Text = document.getElementById("span_Id").innerText;
   alert (span_Text);
}
</script>
</body>
</html>

Accessing post variables using Java Servlets

The previous answers are correct but remember to use the name attribute in the input fields (html form) or you won't get anything. Example:

<input type="text" id="username" /> <!-- won't work --> <input type="text" name="username" /> <!-- will work --> <input type="text" name="username" id="username" /> <!-- will work too -->

All this code is HTML valid, but using getParameter(java.lang.String) you will need the name attribute been set in all parameters you want to receive.

svn over HTTP proxy

If you're using the standard SVN installation the svn:// connection will work on tcpip port 3690 and so it's basically impossible to connect unless you change your network configuration (you said only Http traffic is allowed) or you install the http module and Apache on the server hosting your SVN server.

Mips how to store user input string

# This code works fine in QtSpim simulator

.data
    buffer: .space 20
    str1:  .asciiz "Enter string"
    str2:  .asciiz "You wrote:\n"

.text

main:
    la $a0, str1    # Load and print string asking for string
    li $v0, 4
    syscall

    li $v0, 8       # take in input

    la $a0, buffer  # load byte space into address
    li $a1, 20      # allot the byte space for string

    move $t0, $a0   # save string to t0
    syscall

    la $a0, str2    # load and print "you wrote" string
    li $v0, 4
    syscall

    la $a0, buffer  # reload byte space to primary address
    move $a0, $t0   # primary address = t0 address (load pointer)
    li $v0, 4       # print string
    syscall

    li $v0, 10      # end program
    syscall

ES6 exporting/importing in index file

Install @babel/plugin-proposal-export-default-from via:

yarn add -D @babel/plugin-proposal-export-default-from

In your .babelrc.json or any of the Configuration File Types

module.exports = {
  //...
  plugins: [
     '@babel/plugin-proposal-export-default-from'
  ]
  //...
}

Now you can export directly from a file-path:

export Foo from './components/Foo'
export Bar from './components/Bar'

Good Luck...

How do you kill all current connections to a SQL Server 2005 database?

ALTER DATABASE [Test]
SET OFFLINE WITH ROLLBACK IMMEDIATE

ALTER DATABASE [Test]
SET ONLINE

Loading resources using getClass().getResource()

You can request a path in this format:

/package/path/to/the/resource.ext

Even the bytes for creating the classes in memory are found this way:

my.Class -> /my/Class.class

and getResource will give you a URL which can be used to retrieve an InputStream.

But... I'd recommend using directly getClass().getResourceAsStream(...) with the same argument, because it returns directly the InputStream and don't have to worry about creating a (probably complex) URL object that has to know how to create the InputStream.

In short: try using getResourceAsStream and some constructor of ImageIcon that uses an InputStream as an argument.

Classloaders

Be careful if your app has many classloaders. If you have a simple standalone application (no servers or complex things) you shouldn't worry. I don't think it's the case provided ImageIcon was capable of finding it.

Edit: classpath

getResource is—as mattb says—for loading resources from the classpath (from your .jar or classpath directory). If you are bundling an app it's nice to have altogether, so you could include the icon file inside the jar of your app and obtain it this way.

How to make gradient background in android

Or you can use in code whatever you might think of in PSD:

    private void FillCustomGradient(View v) {
        final View view = v;
        Drawable[] layers = new Drawable[1];

        ShapeDrawable.ShaderFactory sf = new ShapeDrawable.ShaderFactory() {
            @Override
            public Shader resize(int width, int height) {
                LinearGradient lg = new LinearGradient(
                        0,
                        0,
                        0,
                        view.getHeight(),
                        new int[] {
                                 getResources().getColor(R.color.color1), // please input your color from resource for color-4
                                 getResources().getColor(R.color.color2),
                                 getResources().getColor(R.color.color3),
                                 getResources().getColor(R.color.color4)},
                        new float[] { 0, 0.49f, 0.50f, 1 },
                        Shader.TileMode.CLAMP);
                return lg;
            }
        };
        PaintDrawable p = new PaintDrawable();
        p.setShape(new RectShape());
        p.setShaderFactory(sf);
        p.setCornerRadii(new float[] { 5, 5, 5, 5, 0, 0, 0, 0 });
        layers[0] = (Drawable) p;

        LayerDrawable composite = new LayerDrawable(layers);
        view.setBackgroundDrawable(composite);
    }

How to check Spark Version

Addition to @Binary Nerd

If you are using Spark, use the following to get the Spark version:

spark-submit --version

or

Login to the Cloudera Manager and goto Hosts page then run inspect hosts in cluster

Proper MIME type for .woff2 fonts

Apache

In Apache, you can add the woff2 mime type via your .htaccess file as stated by this link.

AddType  application/font-woff2  .woff2

IIS

In IIS, simply add the following mimeMap tag into your web.config file inside the staticContent tag.

<configuration>
  <system.webServer>
    <staticContent>
      <mimeMap fileExtension=".woff2" mimeType="application/font-woff2" />

how to fix groovy.lang.MissingMethodException: No signature of method:

Because you are passing three arguments to a four arguments method. Also, you are not using the passed closure.

If you want to specify the operations to be made on top of the source contents, then use a closure. It would be something like this:

def copyAndReplaceText(source, dest, closure){
    dest.write(closure( source.text ))
}

// And you can keep your usage as:
copyAndReplaceText(source, dest){
    it.replaceAll('Visa', 'Passport!!!!')
}

If you will always swap strings, pass both, as your method signature already states:

def copyAndReplaceText(source, dest, targetText, replaceText){
    dest.write(source.text.replaceAll(targetText, replaceText))
}

copyAndReplaceText(source, dest, 'Visa', 'Passport!!!!')

How to filter array in subdocument with MongoDB

Above solution works best if multiple matching sub documents are required. $elemMatch also comes in very use if single matching sub document is required as output

db.test.find({list: {$elemMatch: {a: 1}}}, {'list.$': 1})

Result:

{
  "_id": ObjectId("..."),
  "list": [{a: 1}]
}

Efficient method to generate UUID String in JAVA (UUID.randomUUID().toString() without the dashes)

Dashes don't need to be removed from HTTP request as you can see in URL of this thread. But if you want to prepare well-formed URL without dependency on data you should use URLEncoder.encode( String data, String encoding ) instead of changing standard form of you data. For UUID string representation dashes is normal.

gridview data export to excel in asp.net

I think it will help you

string filename = String.Format("Results_{0}_{1}.xls", DateTime.Today.Month.ToString(), DateTime.Today.Year.ToString());
        if (!string.IsNullOrEmpty(GRIDVIEWNAME.Page.Title))
            filename = GRIDVIEWNAME.Page.Title + ".xls";

        HttpContext.Current.Response.Clear();

        HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);


        HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
        HttpContext.Current.Response.Charset = "";

        System.IO.StringWriter stringWriter = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);



        System.Web.UI.HtmlControls.HtmlForm form = new System.Web.UI.HtmlControls.HtmlForm();
        GRIDVIEWNAME.Parent.Controls.Add(form);
        form.Controls.Add(GRIDVIEWNAME);
        form.RenderControl(htmlWriter);

        HttpContext.Current.Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
        HttpContext.Current.Response.Write(stringWriter.ToString());
        HttpContext.Current.Response.End();

What is the difference between '/' and '//' when used for division?

The double slash, //, is floor division:

>>> 7//3
2

Is there possibility of sum of ArrayList without looping

This link shows three different ways how to sum in java, there is one option that is not in previous answers using Apache Commons Math..

Example:

public static void main(String args []){
    List<Double> NUMBERS_FOR_SUM = new ArrayList<Double>(){
         {
            add(5D);
            add(3.2D);
            add(7D);
         }
    };
    double[] arrayToSume = ArrayUtils.toPrimitive(NUMBERS_FOR_SUM
            .toArray(new Double[NUMBERS_FOR_SUM.size()]));    
    System.out.println(StatUtils.sum(arrayToSume));

}

See StatUtils api

tsconfig.json: Build:No inputs were found in config file

Btw, just had the same problem.

If you had my case, then you probably have the tsconfig.json not in the same directory as the .ts file.

(In my case I stupidly had next to launch.json and tasks.json inside the .vscode folder :P)

How to create a HTTP server in Android?

This can be done using ServerSocket, same as on JavaSE. This class is available on Android. android.permission.INTERNET is required.

The only more tricky part, you need a separate thread wait on the ServerSocket, servicing sub-sockets that come from its accept method. You also need to stop and resume this thread as needed. The simplest approach seems to kill the waiting thread by closing the ServerSocket. If you only need a server while your activity is on the top, starting and stopping ServerSocket thread can be rather elegantly tied to the activity life cycle methods. Also, if the server has multiple users, it may be good to service requests in the forked threads. If there is only one user, this may not be necessary.

If you need to tell the user on which IP is the server listening,use NetworkInterface.getNetworkInterfaces(), this question may tell extra tricks.

Finally, here there is possibly the complete minimal Android server that is very short, simple and may be easier to understand than finished end user applications, recommended in other answers.

JUnit 4 compare Sets

Check this article. One example from there:

@Test  
public void listEquality() {  
    List<Integer> expected = new ArrayList<Integer>();  
    expected.add(5);  

    List<Integer> actual = new ArrayList<Integer>();  
    actual.add(5);  

    assertEquals(expected, actual);  
}  

What's the best UML diagramming tool?

In my practice i use Sequence Diagram Editor. it is really fast and helpful tool. the one thing i don't like about it is that it is commercial product, not free.

What is the difference between SAX and DOM?

You're comparing apples and pears. SAX is a parser that parses serialized DOM structures. There are many different parsers, and "event-based" refers to the parsing method.

Maybe a small recap is in order:

  • The document object model (DOM) is an abstract data model that describes a hierarchical, tree-based document structure; a document tree consists of nodes, namely element, attribute and text nodes (and some others). Nodes have parents, siblings and children and can be traversed, etc., all the stuff you're used to from doing JavaScript (which incidentally has nothing to do with the DOM).

  • A DOM structure may be serialized, i.e. written to a file, using a markup language like HTML or XML. An HTML or XML file thus contains a "written out" or "flattened out" version of an abstract document tree.

  • For a computer to manipulate, or even display, a DOM tree from a file, it has to deserialize, or parse, the file and reconstruct the abstract tree in memory. This is where parsing comes in.

Now we come to the nature of parsers. One way to parse would be to read in the entire document and recursively build up a tree structure in memory, and finally expose the entire result to the user. (I suppose you could call these parsers "DOM parsers".) That would be very handy for the user (I think that's what PHP's XML parser does), but it suffers from scalability problems and becomes very expensive for large documents.

On the other hand, event-based parsing, as done by SAX, looks at the file linearly and simply makes call-backs to the user whenever it encounters a structural piece of data, like "this element started", "that element ended", "some text here", etc. This has the benefit that it can go on forever without concern for the input file size, but it's a lot more low-level because it requires the user to do all the actual processing work (by providing call-backs). To return to your original question, the term "event-based" refers to those parsing events that the parser raises as it traverses the XML file.

The Wikipedia article has many details on the stages of SAX parsing.

Editor does not contain a main type

What you should do is, create a Java Project, but make sure you put this file in the package file of that project, otherwise you'll encounter same error.

enter image description here

Getting XML Node text value with Java DOM

I'd print out the result of an2.getNodeName() as well for debugging purposes. My guess is that your tree crawling code isn't crawling to the nodes that you think it is. That suspicion is enhanced by the lack of checking for node names in your code.

Other than that, the javadoc for Node defines "getNodeValue()" to return null for Nodes of type Element. Therefore, you really should be using getTextContent(). I'm not sure why that wouldn't give you the text that you want.

Perhaps iterate the children of your tag node and see what types are there?

Tried this code and it works for me:

String xml = "<add job=\"351\">\n" +
             "    <tag>foobar</tag>\n" +
             "    <tag>foobar2</tag>\n" +
             "</add>";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
ByteArrayInputStream bis = new ByteArrayInputStream(xml.getBytes());
Document doc = db.parse(bis);
Node n = doc.getFirstChild();
NodeList nl = n.getChildNodes();
Node an,an2;

for (int i=0; i < nl.getLength(); i++) {
    an = nl.item(i);
    if(an.getNodeType()==Node.ELEMENT_NODE) {
        NodeList nl2 = an.getChildNodes();

        for(int i2=0; i2<nl2.getLength(); i2++) {
            an2 = nl2.item(i2);
            // DEBUG PRINTS
            System.out.println(an2.getNodeName() + ": type (" + an2.getNodeType() + "):");
            if(an2.hasChildNodes()) System.out.println(an2.getFirstChild().getTextContent());
            if(an2.hasChildNodes()) System.out.println(an2.getFirstChild().getNodeValue());
            System.out.println(an2.getTextContent());
            System.out.println(an2.getNodeValue());
        }
    }
}

Output was:

#text: type (3): foobar foobar
#text: type (3): foobar2 foobar2

Make WPF Application Fullscreen (Cover startmenu)

If you want user to change between WindowStyle.SingleBorderWindow and WindowStyle.None at runtime you can bring this at code behind:

Make application fullscreen:

RootWindow.Visibility = Visibility.Collapsed;
RootWindow.WindowStyle = WindowStyle.None;
RootWindow.ResizeMode = ResizeMode.NoResize;
RootWindow.WindowState = WindowState.Maximized;
RootWindow.Topmost = true;
RootWindow.Visibility = Visibility.Visible;

Return to single border style:

RootWindow.WindowStyle = WindowStyle.SingleBorderWindow;
RootWindow.ResizeMode = ResizeMode.CanResize;
RootWindow.Topmost = false;

Note that without RootWindow.Visibility property your window will not cover start menu, however you can skip this step if you making application fullscreen once at startup.

How to run a JAR file

You have to add a manifest to the jar, which tells the java runtime what the main class is. Create a file 'Manifest.mf' with the following content:

Manifest-Version: 1.0
Main-Class: your.programs.MainClass

Change 'your.programs.MainClass' to your actual main class. Now put the file into the Jar-file, in a subfolder named 'META-INF'. You can use any ZIP-utility for that.

Import Python Script Into Another?

Following worked for me and it seems very simple as well:

Let's assume that we want to import a script ./data/get_my_file.py and want to access get_set1() function in it.

import sys
sys.path.insert(0, './data/')
import get_my_file as db

print (db.get_set1())

git ignore exception

The solution depends on the relation between the git ignore rule and the exception rule:

  1. Files/Files at the same level: use the @Skilldrick solution.
  2. Folders/Subfolders: use the @Matiss Jurgelis solution.
  3. Files/Files in different levels or Files/Subfolders: you can do this:

    *.suo
    *.user
    *.userosscache
    *.sln.docstates
    
    # ...
    
    # Exceptions for entire subfolders
    !SetupFiles/elasticsearch-5.0.0/**/*
    !SetupFiles/filebeat-5.0.0-windows-x86_64/**/*
    
    # Exceptions for files in different levels
    !SetupFiles/kibana-5.0.0-windows-x86/**/*.suo
    !SetupFiles/logstash-5.0.0/**/*.suo
    

how to add <script>alert('test');</script> inside a text box?

JQuery version:

$('yourInputSelectorHere').val("<script>alert('test');<\/script>")

How do I open a new window using jQuery?

It's not really something you need jQuery to do. There is a very simple plain old javascript method for doing this:

window.open('http://www.google.com','GoogleWindow', 'width=800, height=600');

That's it.

The first arg is the url, the second is the name of the window, this should be specified because IE will throw a fit about trying to use window.opener later if there was no window name specified (just a little FYI), and the last two params are width/height.

EDIT: Full specification can be found in the link mmmshuddup provided.

Unable to open a file with fopen()

Try using an absolute path for the filename. And if you are using Windows, use getlasterror() to see the actual error message.

Converting a string to a date in DB2

In format function your can use timestamp_format function. Example, if the format is YYYYMMDD you can do it :

select TIMESTAMP_FORMAT(yourcolumnchar, 'YYYYMMDD') as YouTimeStamp 
from yourtable

you can then adapt then format with elements format foundable here

What does it mean to bind a multicast (UDP) socket?

To bind a UDP socket when receiving multicast means to specify an address and port from which to receive data (NOT a local interface, as is the case for TCP acceptor bind). The address specified in this case has a filtering role, i.e. the socket will only receive datagrams sent to that multicast address & port, no matter what groups are subsequently joined by the socket. This explains why when binding to INADDR_ANY (0.0.0.0) I received datagrams sent to my multicast group, whereas when binding to any of the local interfaces I did not receive anything, even though the datagrams were being sent on the network to which that interface corresponded.

Quoting from UNIX® Network Programming Volume 1, Third Edition: The Sockets Networking API by W.R Stevens. 21.10. Sending and Receiving

[...] We want the receiving socket to bind the multicast group and port, say 239.255.1.2 port 8888. (Recall that we could just bind the wildcard IP address and port 8888, but binding the multicast address prevents the socket from receiving any other datagrams that might arrive destined for port 8888.) We then want the receiving socket to join the multicast group. The sending socket will send datagrams to this same multicast address and port, say 239.255.1.2 port 8888.

%Like% Query in spring JpaRepository

Try this.

@Query("Select c from Registration c where c.place like '%'||:place||'%'")

Difference between Static methods and Instance methods

Instance method vs Static method

  1. Instance method can access the instance methods and instance variables directly.

  2. Instance method can access static variables and static methods directly.

  3. Static methods can access the static variables and static methods directly.

  4. Static methods can’t access instance methods and instance variables directly. They must use reference to object. And static method can’t use this keyword as there is no instance for ‘this’ to refer to.

Angular - res.json() is not a function

Don't need to use this method:

 .map((res: Response) => res.json() );

Just use this simple method instead of the previous method. hopefully you'll get your result:

.map(res => res );

What is the difference between explicit and implicit cursors in Oracle?

Implicit cursor returns only one record and are called automatically. However, explicit cursors are called manually and can return more than one record.

select records from postgres where timestamp is in certain range

Another option to make PostgreSQL use an index for your original query, is to create an index on the expression you are using:

create index arrival_year on reservations ( extract(year from arrival) );

That will open PostgreSQL with the possibility to use an index for

select * 
FROM reservations 
WHERE extract(year from arrival) = 2012;

Note that the expression in the index must be exactly the same expression as used in the where clause to make this work.

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

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

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

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

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

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

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

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

Note:

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

  • From the help of wait:

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

regex match any whitespace

Your regex should work 'as-is'. Assuming that it is doing what you want it to.

wordA(\s*)wordB(?! wordc)

This means match wordA followed by 0 or more spaces followed by wordB, but do not match if followed by wordc. Note the single space between ?! and wordc which means that wordA wordB wordc will not match, but wordA wordB wordc will.

Here are some example matches and the associated replacement output:

enter image description here

Note that all matches are replaced no matter how many spaces. There are a couple of other points: -

  • (?! wordc) is a negative lookahead, so you wont match lines wordA wordB wordc which is assume is intended (and is why the last line is not matched). Currently you are relying on the space after ?! to match the whitespace. You may want to be more precise and use (?!\swordc). If you want to match against more than one space before wordc you can use (?!\s*wordc) for 0 or more spaces or (?!\s*+wordc) for 1 or more spaces depending on what your intention is. Of course, if you do want to match lines with wordc after wordB then you shouldn't use a negative lookahead.

  • * will match 0 or more spaces so it will match wordAwordB. You may want to consider + if you want at least one space.

  • (\s*) - the brackets indicate a capturing group. Are you capturing the whitespace to a group for a reason? If not you could just remove the brackets, i.e. just use \s.

Update based on comment

Hello the problem is not the expression but the HTML out put   that are not considered as whitespace. it's a Joomla website.

Preserving your original regex you can use:

wordA((?:\s|&nbsp;)*)wordB(?!(?:\s|&nbsp;)wordc)

The only difference is that not the regex matches whitespace OR &nbsp;. I replaced wordc with \swordc since that is more explicit. Note as I have already pointed out that the negative lookahead ?! will not match when wordB is followed by a single whitespace and wordc. If you want to match multiple whitespaces then see my comments above. I also preserved the capture group around the whitespace, if you don't want this then remove the brackets as already described above.

Example matches:

enter image description here

Hard reset of a single file

To revert to upstream/master do:

git checkout upstream/master -- myfile.txt

Copying data from one SQLite database to another

First scenario: DB1.sqlite and DB2.sqlite have the same table(t1), but DB1 is more "up to date" than DB2. If it's small, drop the table from DB2 and recreate it with the data:

> DROP TABLE IF EXISTS db2.t1; CREATE TABLE db2.t1 AS SELECT * FROM db1.t1;

Second scenario: If it's a large table, you may be better off with an INSERT if not exists type solution. If you have a Unique Key column it's more straight forward, otherwise you'd need to use a combination of fields (maybe every field) and at some point it's still faster to just drop and re-create the table; it's always more straight forward (less thinking required).


THE SETUP: open SQLite without a DB which creates a temporary in memory main database, then attach DB1.sqlite and DB2.sqlite

> sqlite3
sqlite> ATTACH "DB1.sqlite" AS db1
sqlite> ATTACH "DB2.sqlite" AS db2

and use .databases to see the attached databases and their files.

sqlite> .databases
main: 
db1: /db/DB1.sqlite
db2: /db/DB2.sqlite

How to take the nth digit of a number in python

I was curious about the relative speed of the two popular approaches - casting to string and using modular arithmetic - so I profiled them and was surprised to see how close they were in terms of performance.

(My use-case was slightly different, I wanted to get all digits in the number.)

The string approach gave:

         10000002 function calls in 1.113 seconds

   Ordered by: cumulative time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
 10000000    1.113    0.000    1.113    0.000 sandbox.py:1(get_digits_str)
        1    0.000    0.000    0.000    0.000 cProfile.py:133(__exit__)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

While the modular arithmetic approach gave:


         10000002 function calls in 1.102 seconds

   Ordered by: cumulative time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
 10000000    1.102    0.000    1.102    0.000 sandbox.py:6(get_digits_mod)
        1    0.000    0.000    0.000    0.000 cProfile.py:133(__exit__)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

There were 10^7 tests run with a max number size less than 10^28.

Code used for reference:

def get_digits_str(num):
    for n_str in str(num):
        yield int(n_str)


def get_digits_mod(num, radix=10):

    remaining = num
    yield remaining % radix

    while remaining := remaining // radix:
        yield remaining % radix


if __name__ == '__main__':

    import cProfile
    import random

    random_inputs = [random.randrange(0, 10000000000000000000000000000) for _ in range(10000000)]

    with cProfile.Profile() as str_profiler:
        for rand_num in random_inputs:
            get_digits_str(rand_num)

    str_profiler.print_stats(sort='cumtime')

    with cProfile.Profile() as mod_profiler:
        for rand_num in random_inputs:
            get_digits_mod(rand_num)

    mod_profiler.print_stats(sort='cumtime')

How can I include null values in a MIN or MAX?

Use the analytic function :

select case when 
    max(field) keep (dense_rank first order by datfin desc nulls first) is null then 1 
    else 0 end as flag 
from MYTABLE;

Unfortunately MyApp has stopped. How can I solve this?

In below showToast() method you have to pass another parameter for context or application context by doing so you can try it.

  public void showToast(String error, Context applicationContext){
        LayoutInflater inflater = getLayoutInflater();
        View view = inflater.inflate(R.layout.custom_toast, (ViewGroup)      
        findViewById(R.id.toast_root));
        TextView text = (TextView) findViewById(R.id.toast_error);
        text.setText(error);
        Toast toast = new Toast(applicationContext);
        toast.setGravity(Gravity.TOP | Gravity.FILL_HORIZONTAL, 0, 0);
        toast.setDuration(Toast.LENGTH_SHORT);
        toast.setView(view);
        toast.show();
}

How to specify "does not contain" in dplyr filter

Try putting the search condition in a bracket, as shown below. This returns the result of the conditional query inside the bracket. Then test its result to determine if it is negative (i.e. it does not belong to any of the options in the vector), by setting it to FALSE.

SE_CSVLinelist_filtered <- filter(SE_CSVLinelist_clean, 
(where_case_travelled_1 %in% c('Outside Canada','Outside province/territory of residence but within Canada')) == FALSE)

Stashing only staged changes in git - is it possible?

I haven't seen this solution that requires no use of git stash :

You don't even need to use git stash at all. You can work this out using a dedicated branch as covered here (branches are cheap).

Indeed, you can isolate separately un- and staged changes with a few consecutive commands that you could bundle together into a git alias :

Create and switch to an new branch where you'll commit separately staged and unstaged changes : see here

At any moment you can git cherry-pick -e one commit from the created branch to apply it where you want (-e to change its commit message).

When you don't need it anymore, you can delete this "stash branch". You may have to use the -D option to force deletion (instead of the -d normal option) because said branch is not merged and git might consider that you risk losing data if you delete it. That is true if you haven't cherry-picked commits that were on it before deletion :

git branch -D separated-stashes

You can also add an alias to your ~/.gitconfig in order to automate this behavior :

git config --global alias.bratisla '!git switch -c separated-stashes; git commit -m "staged changes"; git add -u; git commit -m "unstaged changes"; git switch -' # why this name ? : youtu.be/LpE1bJp8-4w

before "stashing"
after "stashing"



Of course, you can also achieve the same result using two consecutive stashes

As stated in other answers, you have some ways to stash only unstaged or only staged changes using git stash (-k|--keep-index) in combination with other commands.

I personally find the -k option very confusing, as it stashes everything but keeps staged changes in staged state (that explains why "--keep-index"). Whereas stashing something usually moves it to a stash entry. With -k the unstaged changes are stashed normally, but staged ones are just copied to the same stash entry.


Step 0 : you have two things in your git status : a file containing staged changes, and another one containing unstaged changes.

Step 1 : stash unstaged + staged changes but keep the staged ones in the index :

git stash -k -m "all changes"

The -m "..." part is optional, git stash -k is actually an alias for git stash push -k (that does not push anything remotely btw don't worry) which accepts a -m option to label you stash entries for clarity (like a commit message or a tag but for a stash entry). It is the newer version of the deprecated git stash save.


Step 1bis (optional) :

git stash

Stash staged changes (that are still in the index). This step is not necessary for the following, but shows that you can put only staged changes in a stash entry if you want to. If you use this line you have to git stash (pop|apply) && git add -u before continuing on step 2.


Step 2 :

git commit -m "staged changes"

Makes a commit containing only staged changes from step 0, it contains the same thing as the stash entry from step 1bis.


Step 3 :

git stash (pop|apply)

Restores the stash from step 1. Note that this stash entry contained everything, but since you already committed staged changes, this stash will only add unstaged changes from step 0.

nb: "restore" here does NOT mean "git restore", which is a different command.


Step 4 :

git add -u

Adds the popped stash's content to the index


Step 5 :

git commit -m "unstaged changes"

"Unstaged" here, as "staged" in steps 2 and 3's comments, refers to step 0. You are actually staging and committing the "staged changes" from step 0.


Done ! You now have two separated commits containing (un)staged changes from step 0. You may want to amend/rebase them for either additional changes or to rename/drop/squash them. Depending on what you did with your stash's stack (pop or apply), you might also want to git stash (drop|clear) it. You can see you stash entries with git stash (list|show)

How to Display Selected Item in Bootstrap Button Dropdown Title

Further modified based on answer from @Kyle as $.text() returns exact string, so the caret tag is printed literally, than as a markup, just in case someone would like to keep the caret intact in dropdown.

$(".dropdown-menu li").click(function(){
  $(this).parents(".btn-group").find('.btn').html(
  $(this).text()+" <span class=\"caret\"></span>"
  );
});

Event handlers for Twitter Bootstrap dropdowns?

In Bootstrap 3 'dropdown.js' provides us with the various events that are triggered.

click.bs.dropdown
show.bs.dropdown
shown.bs.dropdown

etc

Remove first 4 characters of a string with PHP

You could use the substr function to return a substring starting from the 5th character:

$str = "The quick brown fox jumps over the lazy dog."
$str2 = substr($str, 4); // "quick brown fox jumps over the lazy dog."

Difference between objectForKey and valueForKey?

As said, the objectForKey: datatype is :(id)aKey whereas the valueForKey: datatype is :(NSString *)key.

For example:

 NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSArray arrayWithObject:@"123"],[NSNumber numberWithInteger:5], nil];

 NSLog(@"objectForKey : --- %@",[dict objectForKey:[NSNumber numberWithInteger:5]]);  
    //This will work fine and prints (    123    )  

 NSLog(@"valueForKey  : --- %@",[dict valueForKey:[NSNumber numberWithInteger:5]]); 
    //it gives warning "Incompatible pointer types sending 'NSNumber *' to parameter of type 'NSString *'"   ---- This will crash on runtime. 

So, valueForKey: will take only a string value and is a KVC method, whereas objectForKey: will take any type of object.

The value in objectForKey will be accessed by the same kind of object.

How can I install packages using pip according to the requirements.txt file from a local directory?

I work with a lot of systems that have been mucked by developers "following directions they found on the Internet". It is extremely common that your pip and your python are not looking at the same paths/site-packages. For this reason, when I encounter oddness I start by doing this:

$ python -c 'import sys; print(sys.path)'
['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu',
'/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old',
'/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages']

$ pip --version
pip 9.0.1 from /usr/local/lib/python2.7/dist-packages (python 2.7)

That is a happy system.

Below is an unhappy system. (Or at least it's a blissfully ignorant system that causes others to be unhappy.)

$ pip --version
pip 9.0.1 from /usr/local/lib/python3.6/site-packages (python 3.6)

$ python -c 'import sys; print(sys.path)'
['', '/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python27.zip',
'/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7',
'/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin',
'/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac',
'/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages',
'/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk',
'/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old',
'/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload',
'/usr/local/lib/python2.7/site-packages']

$ which pip pip2 pip3
/usr/local/bin/pip
/usr/local/bin/pip3

It is unhappy because pip is (python3.6 and) using /usr/local/lib/python3.6/site-packages while python is (python2.7 and) using /usr/local/lib/python2.7/site-packages

When I want to make sure I'm installing requirements to the right python, I do this:

$ which -a python python2 python3
/usr/local/bin/python
/usr/bin/python
/usr/local/bin/python2
/usr/local/bin/python3

$ /usr/bin/python -m pip install -r requirements.txt

You've heard, "If it ain't broke, don't try to fix it." The DevOps version of that is, "If you didn't break it and you can work around it, don't try to fix it."

Sending email in .NET through Gmail

Here is one method to send mail and getting credentials from web.config:

public static string SendEmail(string To, string Subject, string Msg, bool bodyHtml = false, bool test = false, Stream AttachmentStream = null, string AttachmentType = null, string AttachmentFileName = null)
{
    try
    {
        System.Net.Mail.MailMessage newMsg = new System.Net.Mail.MailMessage(System.Configuration.ConfigurationManager.AppSettings["mailCfg"], To, Subject, Msg);
        newMsg.BodyEncoding = System.Text.Encoding.UTF8;
        newMsg.HeadersEncoding = System.Text.Encoding.UTF8;
        newMsg.SubjectEncoding = System.Text.Encoding.UTF8;

        System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();
        if (AttachmentStream != null && AttachmentType != null && AttachmentFileName != null)
        {
            System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(AttachmentStream, AttachmentFileName);
            System.Net.Mime.ContentDisposition disposition = attachment.ContentDisposition;
            disposition.FileName = AttachmentFileName;
            disposition.DispositionType = System.Net.Mime.DispositionTypeNames.Attachment;

            newMsg.Attachments.Add(attachment);
        }
        if (test)
        {
            smtpClient.PickupDirectoryLocation = "C:\\TestEmail";
            smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.SpecifiedPickupDirectory;
        }
        else
        {
            //smtpClient.EnableSsl = true;
        }

        newMsg.IsBodyHtml = bodyHtml;
        smtpClient.Send(newMsg);
        return SENT_OK;
    }
    catch (Exception ex)
    {

        return "Error: " + ex.Message
             + "<br/><br/>Inner Exception: "
             + ex.InnerException;
    }

}

And the corresponding section in web.config:

<appSettings>
    <add key="mailCfg" value="[email protected]"/>
</appSettings>
<system.net>
  <mailSettings>
    <smtp deliveryMethod="Network" from="[email protected]">
      <network defaultCredentials="false" host="mail.exapmple.com" userName="[email protected]" password="your_password" port="25"/>
    </smtp>
  </mailSettings>
</system.net>

Compiling an application for use in highly radioactive environments

Someone mentioned using slower chips to prevent ions from flipping bits as easily. In a similar fashion perhaps use a specialized cpu/ram that actually uses multiple bits to store a single bit. Thus providing a hardware fault tolerance because it would be very unlikely that all of the bits would get flipped. So 1 = 1111 but would need to get hit 4 times to actually flipped. (4 might be a bad number since if 2 bits get flipped its already ambiguous). So if you go with 8, you get 8 times less ram and some fraction slower access time but a much more reliable data representation. You could probably do this both on the software level with a specialized compiler(allocate x amount more space for everything) or language implementation (write wrappers for data structures that allocate things this way). Or specialized hardware that has the same logical structure but does this in the firmware.

Possible to perform cross-database queries with PostgreSQL?

I have run into this before an came to the same conclusion about cross database queries as you. What I ended up doing was using schemas to divide the table space that way I could keep the tables grouped but still query them all.

C# Break out of foreach loop after X number of items

Just use break, like that:

int cont = 0;
foreach (ListViewItem lvi in listView.Items) {
   if(cont==50) { //if listViewItem reach 50 break out.
      break; 
   }
   cont++;   //increment cont.
}

Reverse ip, find domain names on ip address

From about section of Reverse IP Domain Check tool on yougetsignal:

A reverse IP domain check takes a domain name or IP address pointing to a web server and searches for other sites known to be hosted on that same web server. Data is gathered from search engine results, which are not guaranteed to be complete.

Add hover text without javascript like we hover on a user's reputation

You're looking for tooltip

For the basic tooltip, you want:

<div title="This is my tooltip">

For a fancier javascript version, you can look into:

http://www.designer-daily.com/jquery-prototype-mootool-tooltips-12632

The above link gives you 12 options for tooltips.

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

Found my solution on Apache/2.2.15 (Unix).

And Thanks for answer from @QuantumHive:

First: I finded all

Order allow,deny
Deny from all

instead of

Order allow,deny

Allow from all

and then:

I setted

#
# Control access to UserDir directories.  The following is an example
# for a site where these directories are restricted to read-only.
#
#<Directory /var/www/html>
#    AllowOverride FileInfo AuthConfig Limit
#    Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
#    <Limit GET POST OPTIONS>
#        Order allow,deny
#        Allow from all
#    </Limit>
#    <LimitExcept GET POST OPTIONS>
#        Order deny,allow
#        Deny from all
#    </LimitExcept>
#</Directory>

Remove the previous "#" annotation to

#
# Control access to UserDir directories.  The following is an example
# for a site where these directories are restricted to read-only.
#
<Directory /var/www/html>
    AllowOverride FileInfo AuthConfig Limit
    Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
    <Limit GET POST OPTIONS>
        Order allow,deny
        Allow from all
    </Limit>
    <LimitExcept GET POST OPTIONS>
        Order deny,allow
        Deny from all
    </LimitExcept>
</Directory>

ps. my WebDir is: /var/www/html

Error: Local workspace file ('angular.json') could not be found

If all sorts of updating commando's won't do it. Try deleting package-lock.json. And then run npm install. Did the trick for me after going through tons of update commando's.

Unsupported operation :not writeable python

file = open('ValidEmails.txt','wb')
file.write(email.encode('utf-8', 'ignore'))

This is solve your encode error also.

Hidden Features of Java

The type params for generic methods can be specified explicitly like so:

Collections.<String,Integer>emptyMap()

Jquery Date picker Default Date

$( ".selector" ).datepicker({ defaultDate: null });

and return empty string from backend

Confusing error in R: Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings, : line 1 did not have 42 elements)

To read characters try

scan("/PathTo/file.csv", "")

If you're reading numeric values, then just use

scan("/PathTo/file.csv")

scan by default will use white space as separator. The type of the second arg defines 'what' to read (defaults to double()).

Python convert object to float

I eventually used:

weather["Temp"] = weather["Temp"].convert_objects(convert_numeric=True)

It worked just fine, except that I got the following message.

C:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:3: FutureWarning:
convert_objects is deprecated.  Use the data-type specific converters pd.to_datetime, pd.to_timedelta and pd.to_numeric.

Xcode 6.1 - How to uninstall command line tools?

You can simply delete this folder

/Library/Developer/CommandLineTools

Please note: This is the root /Library, not user's ~/Library).

Convert to/from DateTime and Time in Ruby

Unfortunately, the DateTime.to_time, Time.to_datetime and Time.parse functions don't retain the timezone info. Everything is converted to local timezone during conversion. Date arithmetics still work but you won't be able to display the dates with their original timezones. That context information is often important. For example, if I want to see transactions performed during business hours in New York I probably prefer to see them displayed in their original timezones, not my local timezone in Australia (which 12 hrs ahead of New York).

The conversion methods below do keep that tz info.

For Ruby 1.8, look at Gordon Wilson's answer. It's from the good old reliable Ruby Cookbook.

For Ruby 1.9, it's slightly easier.

require 'date'

# Create a date in some foreign time zone (middle of the Atlantic)
d = DateTime.new(2010,01,01, 10,00,00, Rational(-2, 24))
puts d

# Convert DateTime to Time, keeping the original timezone
t = Time.new(d.year, d.month, d.day, d.hour, d.min, d.sec, d.zone)
puts t

# Convert Time to DateTime, keeping the original timezone
d = DateTime.new(t.year, t.month, t.day, t.hour, t.min, t.sec, Rational(t.gmt_offset / 3600, 24))
puts d

This prints the following

2010-01-01T10:00:00-02:00
2010-01-01 10:00:00 -0200
2010-01-01T10:00:00-02:00

The full original DateTime info including timezone is kept.

SQL join format - nested inner joins

Since you've already received help on the query, I'll take a poke at your syntax question:

The first query employs some lesser-known ANSI SQL syntax which allows you to nest joins between the join and on clauses. This allows you to scope/tier your joins and probably opens up a host of other evil, arcane things.

Now, while a nested join cannot refer any higher in the join hierarchy than its immediate parent, joins above it or outside of its branch can refer to it... which is precisely what this ugly little guy is doing:

select
 count(*)
from Table1 as t1
join Table2 as t2
    join Table3 as t3
    on t2.Key = t3.Key                   -- join #1
    and t2.Key2 = t3.Key2 
on t1.DifferentKey = t3.DifferentKey     -- join #2  

This looks a little confusing because join #2 is joining t1 to t2 without specifically referencing t2... however, it references t2 indirectly via t3 -as t3 is joined to t2 in join #1. While that may work, you may find the following a bit more (visually) linear and appealing:

select
 count(*)
from Table1 as t1
    join Table3 as t3
        join Table2 as t2
        on t2.Key = t3.Key                   -- join #1
        and t2.Key2 = t3.Key2   
    on t1.DifferentKey = t3.DifferentKey     -- join #2

Personally, I've found that nesting in this fashion keeps my statements tidy by outlining each tier of the relationship hierarchy. As a side note, you don't need to specify inner. join is implicitly inner unless explicitly marked otherwise.

How do I alias commands in git?

As others have said the appropriate way to add git aliases is in your global .gitconfig file either by editing ~/.gitconfig or by using the git config --global alias.<alias> <git-command> command

Below is a copy of the alias section of my ~/.gitconfig file:

[alias]
    st = status
    ci = commit
    co = checkout
    br = branch
    unstage = reset HEAD --
    last = log -1 HEAD

Also, if you're using bash, I would recommend setting up bash completion by copying git-completion.bash to your home directory and sourcing it from your ~/.bashrc. (I believe I learned about this from the Pro Git online book.) On Mac OS X, I accomplished this with the following commands:

# Copy git-completion.bash to home directory
cp usr/local/git/contrib/completion/git-completion.bash ~/

# Add the following lines to ~/.bashrc
if [ -x /usr/local/git/bin/git ]; then
    source ~/.git-completion.bash
fi

Note: The bash completion will work not only for the standard git commands but also for your git aliases.

Finally, to really cut down on the keystrokes, I added the following to my ~/.bash_aliases file, which is sourced from ~/.bashrc:

alias gst='git status'
alias gl='git pull'
alias gp='git push'
alias gd='git diff | mate'
alias gau='git add --update'
alias gc='git commit -v'
alias gca='git commit -v -a'
alias gb='git branch'
alias gba='git branch -a'
alias gco='git checkout'
alias gcob='git checkout -b'
alias gcot='git checkout -t'
alias gcotb='git checkout --track -b'
alias glog='git log'
alias glogp='git log --pretty=format:"%h %s" --graph'

Delete multiple objects in django

You can delete any QuerySet you'd like. For example, to delete all blog posts with some Post model

Post.objects.all().delete()

and to delete any Post with a future publication date

Post.objects.filter(pub_date__gt=datetime.now()).delete()

You do, however, need to come up with a way to narrow down your QuerySet. If you just want a view to delete a particular object, look into the delete generic view.

EDIT:

Sorry for the misunderstanding. I think the answer is somewhere between. To implement your own, combine ModelForms and generic views. Otherwise, look into 3rd party apps that provide similar functionality. In a related question, the recommendation was django-filter.

What is "not assignable to parameter of type never" error in typescript?

I got the same error in ReactJS function component, using ReactJS useState hook. The solution was to declare the type of useState at initialisation:

const [items , setItems] = useState<IItem[]>([]); // replace IItem[] with your own typing: string, boolean...

UEFA/FIFA scores API

http://api.football-data.org/index is free and useful. The API is in active development, stable and recently the first versioned release called alpha was put online. Check the blog section to follow updates and changes.

Excel VBA date formats

Thanks for the input. I'm obviously seeing some issues that aren't being replicated on others machines. Based on Jean's answer I have come up with less elegant solution that seems to work.

Since if I pass the cell a value directly from cdate, or just format it as a number it leaves the cell value as a string I've had to pass the date value into a numerical variable before passing that number back to the cell.

Function CellContentCanBeInterpretedAsADate(cell As Range) As Boolean
    Dim d As Date
    On Error Resume Next
    d = CDate(cell.Value)
    If Err.Number <> 0 Then
        CellContentCanBeInterpretedAsADate = False
    Else
        CellContentCanBeInterpretedAsADate = True
    End If
    On Error GoTo 0
End Function

Example usage:

Dim cell As Range
dim cvalue as double
Set cell = Range("A1")

If CellContentCanBeInterpretedAsADate(cell) Then
    cvalue = cdate(cell.value)
    cell.value = cvalue
    cell.NumberFormat = "mm/dd/yyyy hh:mm"
Else
    cell.NumberFormat = "General"
End If

Creating threads - Task.Factory.StartNew vs new Thread()

There is a big difference. Tasks are scheduled on the ThreadPool and could even be executed synchronous if appropiate.

If you have a long running background work you should specify this by using the correct Task Option.

You should prefer Task Parallel Library over explicit thread handling, as it is more optimized. Also you have more features like Continuation.

Convert number of minutes into hours & minutes using PHP

Thanks to @Martin_Bean and @Mihail Velikov answers. I just took their answer snippet and added some modifications to check,

  1. If only Hours only available and minutes value empty, then it will display only hours.

  2. Same if only Minutes only available and hours value empty, then it will display only minutes.

  3. If minutes = 60, then it will display as 1 hour. Same if minute = 1, the output will be 1 minute.

Changes and edits are welcomed. Thanks. Here is the code.

function convertToHoursMins($time) {

            $hours    = floor($time / 60);
            $minutes  = ($time % 60);


            if($minutes == 0){

                if($hours == 1){

                    $output_format = '%02d hour ';

                }else{

                    $output_format = '%02d hours ';
                }


                $hoursToMinutes = sprintf($output_format, $hours);

            }else if($hours == 0){

                if ($minutes < 10) {
                        $minutes = '0' . $minutes;
                }

                if($minutes == 1){

                    $output_format  = ' %02d minute ';

                }else{

                    $output_format  = ' %02d minutes ';
                }

                $hoursToMinutes = sprintf($output_format,  $minutes);

            }else {

                if($hours == 1){

                    $output_format = '%02d hour %02d minutes';

                }else{

                    $output_format = '%02d hours %02d minutes';
                }

                $hoursToMinutes = sprintf($output_format, $hours, $minutes);
            }

            return $hoursToMinutes;
        }`

How to add external library in IntelliJ IDEA?

Easier procedure on latest versions:

  • Copy jar to libs directory in the app (you can create the directory it if not there)
  • Refresh project so libs show up in the structure (right click on project top level, refresh/synchronize)
  • Expand libs and right click on the jar
  • Select "Add as Library"

Done

Indent multiple lines quickly in vi

>} or >{ indent from current line up to next paragraph

<} or <{ same un-indent

Postgresql - select something where date = "01/01/11"

I think you want to cast your dt to a date and fix the format of your date literal:

SELECT *
FROM table
WHERE dt::date = '2011-01-01' -- This should be ISO-8601 format, YYYY-MM-DD

Or the standard version:

SELECT *
FROM table
WHERE CAST(dt AS DATE) = '2011-01-01' -- This should be ISO-8601 format, YYYY-MM-DD

The extract function doesn't understand "date" and it returns a number.

Django: Model Form "object has no attribute 'cleaned_data'"

For some reason, you're re-instantiating the form after you check is_valid(). Forms only get a cleaned_data attribute when is_valid() has been called, and you haven't called it on this new, second instance.

Just get rid of the second form = SearchForm(request.POST) and all should be well.

ionic build Android | error: No installed build tools found. Please install the Android build tools

For me, the problem was that ANDROID_HOME was pointing to an old Android SDK path. After installing Android Studio, I had to update ~/.bash_profile accordingly for MAC (El Capitan)

export ANDROID_HOME="/Users/corneliusparkin/Library/Android/sdk"

Remember to re-start terminal or run this command after updating ~/.bash_profile

source ~/.bash_profile

Assert an object is a specific type

Solution for JUnit 5

The documentation says:

However, JUnit Jupiter’s org.junit.jupiter.Assertions class does not provide an assertThat() method like the one found in JUnit 4’s org.junit.Assert class which accepts a Hamcrest Matcher. Instead, developers are encouraged to use the built-in support for matchers provided by third-party assertion libraries.

Example for Hamcrest:

import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;

import org.junit.jupiter.api.Test;

class HamcrestAssertionDemo {

    @Test
    void assertWithHamcrestMatcher() {
        SubClass subClass = new SubClass();
        assertThat(subClass, instanceOf(BaseClass.class));
    }

}

Example for AssertJ:

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.jupiter.api.Test;

class AssertJDemo {

    @Test
    void assertWithAssertJ() {
        SubClass subClass = new SubClass();
        assertThat(subClass).isInstanceOf(BaseClass.class);
    }

}

Note that this assumes you want to test behaviors similar to instanceof (which accepts subclasses). If you want exact equal type, I don’t see a better way than asserting the two class to be equal like you mentioned in the question.

How To Save Canvas As An Image With canvas.toDataURL()?

You cannot use the methods previously mentioned to download an image when running in Cordova. You will need to use the Cordova File Plugin. This will allow you to pick where to save it and leverage different persistence settings. Details here: https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file/

Alternatively, you can convert the image to base64 then store the string in localStorage but this will fill your quota pretty quickly if you have many images or high-res.

Limiting number of displayed results when using ngRepeat

store all your data initially

function PhoneListCtrl($scope, $http) {
  $http.get('phones/phones.json').success(function(data) {
    $scope.phones = data.splice(0, 5);
    $scope.allPhones = data;
  });

  $scope.orderProp = 'age';
  $scope.howMany = 5;
  //then here watch the howMany variable on the scope and update the phones array accordingly
  $scope.$watch("howMany", function(newValue, oldValue){
    $scope.phones = $scope.allPhones.splice(0,newValue)
  });
}

EDIT had accidentally put the watch outside the controller it should have been inside.

Find when a file was deleted in Git

I've just added a solution here (is there a way in git to list all deleted files in the repository?) for finding the commits of deleted files by using a regexp:

git log --diff-filter=D --summary | sed -n '/^commit/h;/\/some_dir\//{G;s/\ncommit \(.*\)/ \1/gp}'

This returns everything deleted within a directory named some_dir (cascading). Any sed regexp there where \/some_dir\/ is will do.

OSX (thanks to @triplee and @keif)

git log --diff-filter=D --summary | sed -n -e '/^commit/h' -e '\:/:{' -e G -e 's/\ncommit \(.*\)/ \1/gp' -e }

"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]

How can I convert an image into a Base64 string?

byte[] decodedString = Base64.decode(result.getBytes(), Base64.DEFAULT);

How to create RecyclerView with multiple view type?

Yes, it is possible. In your adapter getItemViewType Layout like this ....

  public class MultiViewTypeAdapter extends RecyclerView.Adapter {

        private ArrayList<Model>dataSet;
        Context mContext;
        int total_types;
        MediaPlayer mPlayer;
        private boolean fabStateVolume = false;

        public static class TextTypeViewHolder extends RecyclerView.ViewHolder {

            TextView txtType;
            CardView cardView;

            public TextTypeViewHolder(View itemView) {
                super(itemView);

                this.txtType = (TextView) itemView.findViewById(R.id.type);
                this.cardView = (CardView) itemView.findViewById(R.id.card_view);
            }
        }

        public static class ImageTypeViewHolder extends RecyclerView.ViewHolder {

            TextView txtType;
            ImageView image;

            public ImageTypeViewHolder(View itemView) {
                super(itemView);

                this.txtType = (TextView) itemView.findViewById(R.id.type);
                this.image = (ImageView) itemView.findViewById(R.id.background);
            }
        }

        public static class AudioTypeViewHolder extends RecyclerView.ViewHolder {

            TextView txtType;
            FloatingActionButton fab;

            public AudioTypeViewHolder(View itemView) {
                super(itemView);

                this.txtType = (TextView) itemView.findViewById(R.id.type);
                this.fab = (FloatingActionButton) itemView.findViewById(R.id.fab);
            }
        }

        public MultiViewTypeAdapter(ArrayList<Model>data, Context context) {
            this.dataSet = data;
            this.mContext = context;
            total_types = dataSet.size();
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

            View view;
            switch (viewType) {
                case Model.TEXT_TYPE:
                    view = LayoutInflater.from(parent.getContext()).inflate(R.layout.text_type, parent, false);
                    return new TextTypeViewHolder(view);
                case Model.IMAGE_TYPE:
                    view = LayoutInflater.from(parent.getContext()).inflate(R.layout.image_type, parent, false);
                    return new ImageTypeViewHolder(view);
                case Model.AUDIO_TYPE:
                    view = LayoutInflater.from(parent.getContext()).inflate(R.layout.audio_type, parent, false);
                    return new AudioTypeViewHolder(view);
            }
            return null;
        }

        @Override
        public int getItemViewType(int position) {

            switch (dataSet.get(position).type) {
                case 0:
                    return Model.TEXT_TYPE;
                case 1:
                    return Model.IMAGE_TYPE;
                case 2:
                    return Model.AUDIO_TYPE;
                default:
                    return -1;
            }
        }

        @Override
        public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int listPosition) {

            Model object = dataSet.get(listPosition);
            if (object != null) {
                switch (object.type) {
                    case Model.TEXT_TYPE:
                        ((TextTypeViewHolder) holder).txtType.setText(object.text);

                        break;
                    case Model.IMAGE_TYPE:
                        ((ImageTypeViewHolder) holder).txtType.setText(object.text);
                        ((ImageTypeViewHolder) holder).image.setImageResource(object.data);
                        break;
                    case Model.AUDIO_TYPE:

                        ((AudioTypeViewHolder) holder).txtType.setText(object.text);

                }
            }
        }

        @Override
        public int getItemCount() {
            return dataSet.size();
        }
    }

for reference link : https://www.journaldev.com/12372/android-recyclerview-example

Error: EPERM: operation not permitted, unlink 'D:\Sources\**\node_modules\fsevents\node_modules\abbrev\package.json'

I had the same issue and all I needed to do was login to npm

npm login

or alternatively

npm add user // consult the documentation for the params  

Adding days to a date in Java

Calendar cal = Calendar.getInstance();    
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.MONTH, 1);
cal.set(Calendar.YEAR, 2012);
cal.add(Calendar.DAY_OF_MONTH, 5);

You can also substract days like Calendar.add(Calendar.DAY_OF_MONTH, -5);

Properly Handling Errors in VBA (Excel)

I definitely wouldn't use Block1. It doesn't seem right having the Error block in an IF statement unrelated to Errors.

Blocks 2,3 & 4 I guess are variations of a theme. I prefer the use of Blocks 3 & 4 over 2 only because of a dislike of the GOTO statement; I generally use the Block4 method. This is one example of code I use to check if the Microsoft ActiveX Data Objects 2.8 Library is added and if not add or use an earlier version if 2.8 is not available.

Option Explicit
Public booRefAdded As Boolean 'one time check for references

Public Sub Add_References()
Dim lngDLLmsadoFIND As Long

If Not booRefAdded Then
    lngDLLmsadoFIND = 28 ' load msado28.tlb, if cannot find step down versions until found

        On Error GoTo RefErr:
            'Add Microsoft ActiveX Data Objects 2.8
            Application.VBE.ActiveVBProject.references.AddFromFile _
            Environ("CommonProgramFiles") + "\System\ado\msado" & lngDLLmsadoFIND & ".tlb"

        On Error GoTo 0

    Exit Sub

RefErr:
        Select Case Err.Number
            Case 0
                'no error
            Case 1004
                 'Enable Trust Centre Settings
                 MsgBox ("Certain VBA References are not available, to allow access follow these steps" & Chr(10) & _
                 "Goto Excel Options/Trust Centre/Trust Centre Security/Macro Settings" & Chr(10) & _
                 "1. Tick - 'Disable all macros with notification'" & Chr(10) & _
                 "2. Tick - 'Trust access to the VBA project objects model'")
                 End
            Case 32813
                 'Err.Number 32813 means reference already added
            Case 48
                 'Reference doesn't exist
                 If lngDLLmsadoFIND = 0 Then
                    MsgBox ("Cannot Find Required Reference")
                    End
                Else
                    For lngDLLmsadoFIND = lngDLLmsadoFIND - 1 To 0 Step -1
                           Resume
                    Next lngDLLmsadoFIND
                End If

            Case Else
                 MsgBox Err.Number & vbCrLf & Err.Description, vbCritical, "Error!"
                End
        End Select

        On Error GoTo 0
End If
booRefAdded = TRUE
End Sub

SMTP error 554

Can be caused by a miss configured SPF record on the senders end.

MySQL INSERT INTO table VALUES.. vs INSERT INTO table SET

I think the extension is intended to allow a similar syntax for inserts and updates. In Oracle, a similar syntactical trick is:

UPDATE table SET (col1, col2) = (SELECT val1, val2 FROM dual)

Ubuntu: OpenJDK 8 - Unable to locate package

After adding the JDK repo, before Installing you might want to run an update first so the repo can be added run apt update

an then continue with your installation sudo apt install adoptopenjdk-8-hotspot

JavaScript seconds to time string with format hh:mm:ss

You can manage to do this without any external JS library with the help of JS Date method like following:

_x000D_
_x000D_
var date = new Date(0);_x000D_
date.setSeconds(45); // specify value for SECONDS here_x000D_
var timeString = date.toISOString().substr(11, 8);_x000D_
console.log(timeString)
_x000D_
_x000D_
_x000D_

android: changing option menu items programmatically

you can accomplish your task simply by implementing as below:

private Menu menu;

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

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    this.menu = menu;
    return super.onPrepareOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == R.id.action_toggle_grid) {
        handleMenuOption(id);
        return true;

    } else if(id == R.id.action_toggle_list){
        handleMenuOption(id);
        return true;
    }

    return super.onOptionsItemSelected(item);
}

private void handleMenuOption(int id) {
    MenuItem item = menu.findItem(id);
    if (id == R.id.action_toggle_grid){
        item.setVisible(false);
        menu.findItem(R.id.action_toggle_list).setVisible(true);
    }else if (id == R.id.action_toggle_list){
        item.setVisible(false);
        menu.findItem(R.id.action_toggle_grid).setVisible(true);
    }
}

What does value & 0xff do in Java?

It sets result to the (unsigned) value resulting from putting the 8 bits of value in the lowest 8 bits of result.

The reason something like this is necessary is that byte is a signed type in Java. If you just wrote:

int result = value;

then result would end up with the value ff ff ff fe instead of 00 00 00 fe. A further subtlety is that the & is defined to operate only on int values1, so what happens is:

  1. value is promoted to an int (ff ff ff fe).
  2. 0xff is an int literal (00 00 00 ff).
  3. The & is applied to yield the desired value for result.

(The point is that conversion to int happens before the & operator is applied.)

1Well, not quite. The & operator works on long values as well, if either operand is a long. But not on byte. See the Java Language Specification, sections 15.22.1 and 5.6.2.

Java foreach loop: for (Integer i : list) { ... }

Another way, you can use a pass-through object to capture the last value and then do something with it:

List<Integer> list = new ArrayList<Integer>();
Integer lastValue = null;
for (Integer i : list) {
    // do stuff
    lastValue = i;
}
// do stuff with last value

How to execute a java .class from the command line

You have no valid main method... The signature should be: public static void main(String[] args);

Hence, in your case the code should look like this:

public class Echo {
    public static void main (String[] arg) {

            System.out.println(arg[0]);
    }
}

Edit: Please note that Oscar is also right in that you are missing . in your classpath, you would run into the problem I solve after you have dealt with that error.

Twitter Bootstrap carousel different height images cause bouncing arrows

In case someone is feverishly googling to solve the bouncing images carousel thing, this helped me:

.fusion-carousel .fusion-carousel-item img {
    width: auto;
    height: 146px;
    max-height: 146px;
    object-fit: contain;
}

How to pass a textbox value from view to a controller in MVC 4?

Try the following in your view to check the output from each. The first one updates when the view is called a second time. My controller uses the key ShowCreateButton and has the optional parameter _createAction with a default value - you can change this to your key/parameter

@Html.TextBox("_createAction", null, new { Value = (string)ViewBag.ShowCreateButton })
@Html.TextBox("_createAction", ViewBag.ShowCreateButton )
@ViewBag.ShowCreateButton

How to get directory size in PHP

Even though there are already many many answers to this post, I feel I have to add another option for unix hosts that only returns the sum of all file sizes in the directory (recursively).

If you look at Jonathan's answer he uses the du command. This command will return the total directory size but the pure PHP solutions posted by others here will return the sum of all file sizes. Big difference!

What to look out for

When running du on a newly created directory, it may return 4K instead of 0. This may even get more confusing after having deleted files from the directory in question, having du reporting a total directory size that does not correspond to the sum of the sizes of the files within it. Why? The command du returns a report based on some file settings, as Hermann Ingjaldsson commented on this post.

The solution

To form a solution that behaves like some of the PHP-only scripts posted here, you can use ls command and pipe it to awk like this:

ls -ltrR /path/to/dir |awk '{print \$5}'|awk 'BEGIN{sum=0} {sum=sum+\$1} END {print sum}'

As a PHP function you could use something like this:

function getDirectorySize( $path )
{
    if( !is_dir( $path ) ) {
        return 0;
    }

    $path   = strval( $path );
    $io     = popen( "ls -ltrR {$path} |awk '{print \$5}'|awk 'BEGIN{sum=0} {sum=sum+\$1} END {print sum}'", 'r' );
    $size   = intval( fgets( $io, 80 ) );
    pclose( $io );

    return $size;
}

How to get PID by process name?

For posix (Linux, BSD, etc... only need /proc directory to be mounted) it's easier to work with os files in /proc. It's pure python, no need to call shell programs outside.

Works on python 2 and 3 ( The only difference (2to3) is the Exception tree, therefore the "except Exception", which I dislike but kept to maintain compatibility. Also could've created a custom exception.)

#!/usr/bin/env python

import os
import sys


for dirname in os.listdir('/proc'):
    if dirname == 'curproc':
        continue

    try:
        with open('/proc/{}/cmdline'.format(dirname), mode='rb') as fd:
            content = fd.read().decode().split('\x00')
    except Exception:
        continue

    for i in sys.argv[1:]:
        if i in content[0]:
            print('{0:<12} : {1}'.format(dirname, ' '.join(content)))

Sample Output (it works like pgrep):

phoemur ~/python $ ./pgrep.py bash
1487         : -bash 
1779         : /bin/bash

Codeigniter unset session

$this->session->unset_userdata('session_value');

How to preview selected image in input type="file" in popup using jQuery?

Just check my scripts it's working well:

  function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object

    // Loop through the FileList and render image files as thumbnails.
    for (var i = 0, f; f = files[i]; i++) {

      // Only process image files.
      if (!f.type.match('image.*')) {
        continue;
      }

      var reader = new FileReader();

      // Closure to capture the file information.
      reader.onload = (function(theFile) {
        return function(e) {
          // Render thumbnail.
          var span = document.createElement('span');
          span.innerHTML = ['<img class="thumb" src="', e.target.result,
                            '" title="', escape(theFile.name), '"/>'].join('');
          document.getElementById('list').insertBefore(span, null);
        };
      })(f);

      // Read in the image file as a data URL.
      reader.readAsDataURL(f);
    }
  }

  document.getElementById('files').addEventListener('change', handleFileSelect, false);
#list img{
  width: auto;
  height: 100px;
  margin: 10px ;
}

SQL Server 2005 How Create a Unique Constraint?

ALTER TABLE dbo.<tablename> ADD CONSTRAINT
            <namingconventionconstraint> UNIQUE NONCLUSTERED
    (
                <columnname>
    ) ON [PRIMARY]

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

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

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

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

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

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

"Untrusted App Developer" message when installing enterprise iOS Application

You cannot avoid this unless you distribute an application via the App Store.

You get this message because the application is signed via an enterprise certificate that has not yet been trusted by the user. Apple force this prompt to appear because the application that is being installed hasn't gone through the App Store review process so is technically untrusted.

Once the user has accepted the prompt, the certificate will be marked as trusted and the application can be installed (along with any other future applications that you wish to install that have been signed with the same certificate)

Note: As pointed out in the comments, as of iOS 8, uninstalling all applications from a specific certificate will cause the prompt to be shown again once an application from said certificate is re-installed.

Here is the link to Apple website that confirms this info: https://support.apple.com/en-us/HT204460

ERROR 1044 (42000): Access denied for user ''@'localhost' to database 'db'

You might want to try the full login command:

mysql -h host -u root -p 

where host would be 127.0.0.1.

Do this just to make sure cooperation exists.

Using mysql -u root -p allows me to do a a lot of database searching, but refuses any database creation due to a path setting.

The remote server returned an error: (403) Forbidden

We should access the website using the name given in the certificate.enter image description here

Get a worksheet name using Excel VBA

i need to change the sheet name by the name of the file was opened

Sub Get_Data_From_File5()
    Dim FileToOpen As Variant
    Dim OpenBook As Workbook
    Dim currentName As String
    currentName = ActiveSheet.Name
    Application.ScreenUpdating = False
    FileToOpen = Application.GetOpenFilename(Title:="Browse for your File & Import Range", FileFilter:="Excel Files (*.csv*),*csv*")
    If FileToOpen <> False Then
        Set OpenBook = Application.Workbooks.Open(FileToOpen)
        OpenBook.Sheets(1).Range("A1:g5000").Copy
        ThisWorkbook.Worksheets(currentName).Range("Aw1:bc5000").PasteSpecial xlPasteValues
        OpenBook.Close False
       
        
    End If
    Application.ScreenUpdating = True
End Sub

assign multiple variables to the same value in Javascript

There is another option that does not introduce global gotchas when trying to initialize multiple variables to the same value. Whether or not it is preferable to the long way is a judgement call. It will likely be slower and may or may not be more readable. In your specific case, I think that the long way is probably more readable and maintainable as well as being faster.

The other way utilizes Destructuring assignment.

_x000D_
_x000D_
let [moveUp, moveDown,_x000D_
     moveLeft, moveRight,_x000D_
     mouseDown, touchDown] = Array(6).fill(false);_x000D_
_x000D_
console.log(JSON.stringify({_x000D_
    moveUp, moveDown,_x000D_
    moveLeft, moveRight,_x000D_
    mouseDown, touchDown_x000D_
}, null, '  '));_x000D_
_x000D_
// NOTE: If you want to do this with objects, you would be safer doing this_x000D_
let [obj1, obj2, obj3] = Array(3).fill(null).map(() => ({}));_x000D_
console.log(JSON.stringify({_x000D_
    obj1, obj2, obj3_x000D_
}, null, '  '));_x000D_
// So that each array element is a unique object_x000D_
_x000D_
// Or another cool trick would be to use an infinite generator_x000D_
let [a, b, c, d] = (function*() { while (true) yield {x: 0, y: 0} })();_x000D_
console.log(JSON.stringify({_x000D_
    a, b, c, d_x000D_
}, null, '  '));_x000D_
_x000D_
// Or generic fixed generator function_x000D_
function* nTimes(n, f) {_x000D_
    for(let i = 0; i < n; i++) {_x000D_
        yield f();_x000D_
    }_x000D_
}_x000D_
let [p1, p2, p3] = [...nTimes(3, () => ({ x: 0, y: 0 }))];_x000D_
console.log(JSON.stringify({_x000D_
    p1, p2, p3_x000D_
}, null, '  '));
_x000D_
_x000D_
_x000D_

This allows you to initialize a set of var, let, or const variables to the same value on a single line all with the same expected scope.

References:

Animate change of view background color on Android

You can use ArgbEvaluatorCompat class above API 11.

implementation 'com.google.android.material:material:1.0.0' 


ValueAnimator colorAnim = ValueAnimator.ofObject(new ArgbEvaluatorCompat(), startColor, endColor);
colorAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
            mTargetColor = (int) animation.getAnimatedValue();
        }
    });
colorAnim.start();

Limiting floats to two decimal points

What about a lambda function like this:

arred = lambda x,n : x*(10**n)//1/(10**n)

This way you could just do:

arred(3.141591657,2)

and get

3.14

How to read a text-file resource into Java unit test?

Right to the point :

ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("file/test.xml").getFile());

.NET End vs Form.Close() vs Application.Exit Cleaner way to close one's app

The situation you describe is pretty fishy. Whenever you close your program's startup form, the entire application should quit automatically, including closing all other open forms. Make sure that you're closing the correct form, and you should not experience any problems.

The other possibility is that you've changed your project (using its Properties page) not to close until all open windows have been closed. In this mode, your application will not exit until the last remaining open form has been closed. If you've chosen this setting, you have to make sure that you call the Close method of all forms that you've shown during the course of application, not just the startup/main form.

The first setting is the default for a reason, and if you've changed it, you probably want to go fix it back.
It is by far the most intuitive model for normal applications, and it prevents exactly the situation you describe. For it to work properly, make sure that you have specified your main form as the "Startup form" (rather than a splash screen or log-in form).

The settings I'm talking about are highlighted here:

   Visual Studio Project Properties

But primarily, note that you should never have to call Application.Exit in a properly-designed application. If you find yourself having to do this in order for your program to close completely, then you are doing something wrong. Doing it is not a bad practice in itself, as long as you have a good reason. The other two answers fail to explain that, and thus I feel are incomplete at best.

Error when trying to access XAMPP from a network

This solution worked well for me: http://www.apachefriends.org/f/viewtopic.php?f=17&t=50902&p=196185#p196185

Edit /opt/lampp/etc/extra/httpd-xampp.conf and adding Require all granted line at bottom of block <Directory "/opt/lampp/phpmyadmin"> to have the following code:

<Directory "/opt/lampp/phpmyadmin">
  AllowOverride AuthConfig Limit
  Order allow,deny
  Allow from all
  Require all granted
</Directory>

how to set active class to nav menu from twitter bootstrap

I had the same problem... solved it by adding the code shown below to the Into "$(document).ready" part of my "functions.js" file which is included in every page footer. It's pretty simple. It gets the full current URL of the displayed page and compares it to the full anchor href URL. If they are the same, set anchor (li) parent as active. And do this only if anchor href value is not "#", then the bootstrap will solve it.

$(document).ready(function () {         
    $(function(){
        var current_page_URL = location.href;

        $( "a" ).each(function() {

            if ($(this).attr("href") !== "#") {

                var target_URL = $(this).prop("href");

                    if (target_URL == current_page_URL) {
                        $('nav a').parents('li, ul').removeClass('active');
                        $(this).parent('li').addClass('active');

                        return false;
                    }
            }
        }); }); });

Using FolderBrowserDialog in WPF application

If I'm not mistaken you're looking for the FolderBrowserDialog (hence the naming):

var dialog = new System.Windows.Forms.FolderBrowserDialog();
System.Windows.Forms.DialogResult result = dialog.ShowDialog();

Also see this SO thread: Open directory dialog

Django: OperationalError No Such Table

It looks like there was an issue with my migration.

I ran ./manage.py schemamigration research --auto and found that many of the fields didn't have a default specified.

So, I ran ./manage.py schemamigration research --init followed by ./manage.py migrate research

Rerunning the server from there did the trick!

Is it possible to sort a ES6 map object?

One way is to get the entries array, sort it, and then create a new Map with the sorted array:

let ar = [...myMap.entries()];
sortedArray = ar.sort();
sortedMap = new Map(sortedArray);

But if you don't want to create a new object, but to work on the same one, you can do something like this:

// Get an array of the keys and sort them
let keys = [...myMap.keys()];
sortedKeys = keys.sort();

sortedKeys.forEach((key)=>{
  // Delete the element and set it again at the end
  const value = this.get(key);
  this.delete(key);
  this.set(key,value);
})

Is there a need for range(len(a))?

It's nice to have when you need to use the index for some kind of manipulation and having the current element doesn't suffice. Take for instance a binary tree that's stored in an array. If you have a method that asks you to return a list of tuples that contains each nodes direct children then you need the index.

#0 -> 1,2 : 1 -> 3,4 : 2 -> 5,6 : 3 -> 7,8 ...
nodes = [0,1,2,3,4,5,6,7,8,9,10]
children = []
for i in range(len(nodes)):
  leftNode = None
  rightNode = None
  if i*2 + 1 < len(nodes):
    leftNode = nodes[i*2 + 1]
  if i*2 + 2 < len(nodes):
    rightNode = nodes[i*2 + 2]
  children.append((leftNode,rightNode))
return children

Of course if the element you're working on is an object, you can just call a get children method. But yea, you only really need the index if you're doing some sort of manipulation.

What is the best way to add options to a select from a JavaScript object with jQuery?

jQuery

var list = $("#selectList");
$.each(items, function(index, item) {
  list.append(new Option(item.text, item.value));
});

Vanilla JavaScript

var list = document.getElementById("selectList");
for(var i in items) {
  list.add(new Option(items[i].text, items[i].value));
}

How to iterate a loop with index and element in Swift

For those who want to use forEach.

Swift 4

extension Array {
  func forEachWithIndex(_ body: (Int, Element) throws -> Void) rethrows {
    try zip((startIndex ..< endIndex), self).forEach(body)
  }
}

Or

array.enumerated().forEach { ... }

jQuery toggle animation

I dont think adding dual functions inside the toggle function works for a registered click event (Unless I'm missing something)

For example:

$('.btnName').click(function() {
 top.$('#panel').toggle(function() {
   $(this).animate({ 
     // style change
   }, 500);
   },
   function() {
   $(this).animate({ 
     // style change back
   }, 500);
 });

Java: Calculating the angle between two points in degrees

I started with johncarls solution, but needed to adjust it to get exactly what I needed. Mainly, I needed it to rotate clockwise when the angle increased. I also needed 0 degrees to point NORTH. His solution got me close, but I decided to post my solution as well in case it helps anyone else.

I've added some additional comments to help explain my understanding of the function in case you need to make simple modifications.

/**
 * Calculates the angle from centerPt to targetPt in degrees.
 * The return should range from [0,360), rotating CLOCKWISE, 
 * 0 and 360 degrees represents NORTH,
 * 90 degrees represents EAST, etc...
 *
 * Assumes all points are in the same coordinate space.  If they are not, 
 * you will need to call SwingUtilities.convertPointToScreen or equivalent 
 * on all arguments before passing them  to this function.
 *
 * @param centerPt   Point we are rotating around.
 * @param targetPt   Point we want to calcuate the angle to.  
 * @return angle in degrees.  This is the angle from centerPt to targetPt.
 */
public static double calcRotationAngleInDegrees(Point centerPt, Point targetPt)
{
    // calculate the angle theta from the deltaY and deltaX values
    // (atan2 returns radians values from [-PI,PI])
    // 0 currently points EAST.  
    // NOTE: By preserving Y and X param order to atan2,  we are expecting 
    // a CLOCKWISE angle direction.  
    double theta = Math.atan2(targetPt.y - centerPt.y, targetPt.x - centerPt.x);

    // rotate the theta angle clockwise by 90 degrees 
    // (this makes 0 point NORTH)
    // NOTE: adding to an angle rotates it clockwise.  
    // subtracting would rotate it counter-clockwise
    theta += Math.PI/2.0;

    // convert from radians to degrees
    // this will give you an angle from [0->270],[-180,0]
    double angle = Math.toDegrees(theta);

    // convert to positive range [0-360)
    // since we want to prevent negative angles, adjust them now.
    // we can assume that atan2 will not return a negative value
    // greater than one partial rotation
    if (angle < 0) {
        angle += 360;
    }

    return angle;
}

changing permission for files and folder recursively using shell command in mac

The issue is that the * is getting interpreted by your shell and is expanding to a file named TEST_FILE that happens to be in your current working directory, so you're telling find to execute the command named TEST_FILE which doesn't exist. I'm not sure what you're trying to accomplish with that *, you should just remove it.

Furthermore, you should use the idiom -exec program '{}' \+ instead of -exec program '{}' \; so that find doesn't fork a new process for each file. With ;, a new process is forked for each file, whereas with +, it only forks one process and passes all of the files on a single command line, which for simple programs like chmod is much more efficient.

Lastly, chmod can do recursive changes on its own with the -R flag, so unless you need to search for specific files, just do this:

chmod -R 777 /Users/Test/Desktop/PATH

How can I read and manipulate CSV file data in C++?

Here is some code you can use. The data from the csv is stored inside an array of rows. Each row is an array of strings. Hope this helps.

#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <vector>
typedef std::string String;
typedef std::vector<String> CSVRow;
typedef CSVRow::const_iterator CSVRowCI;
typedef std::vector<CSVRow> CSVDatabase;
typedef CSVDatabase::const_iterator CSVDatabaseCI;
void readCSV(std::istream &input, CSVDatabase &db);
void display(const CSVRow&);
void display(const CSVDatabase&);
int main(){
  std::fstream file("file.csv", std::ios::in);
  if(!file.is_open()){
    std::cout << "File not found!\n";
    return 1;
  }
  CSVDatabase db;
  readCSV(file, db);
  display(db);
}
void readCSV(std::istream &input, CSVDatabase &db){
  String csvLine;
  // read every line from the stream
  while( std::getline(input, csvLine) ){
    std::istringstream csvStream(csvLine);
    CSVRow csvRow;
    String csvCol;
    // read every element from the line that is seperated by commas
    // and put it into the vector or strings
    while( std::getline(csvStream, csvCol, ',') )
      csvRow.push_back(csvCol);
    db.push_back(csvRow);
  }
}
void display(const CSVRow& row){
  if(!row.size())
    return;
  CSVRowCI i=row.begin();
  std::cout<<*(i++);
  for(;i != row.end();++i)
    std::cout<<','<<*i;
}
void display(const CSVDatabase& db){
  if(!db.size())
    return;
  CSVDatabaseCI i=db.begin();
  for(; i != db.end(); ++i){
    display(*i);
    std::cout<<std::endl;
  }
}

tomcat - CATALINA_BASE and CATALINA_HOME variables

Pointing CATALINA_BASE to a different directory from CATALINA_HOME allows you to separate the configuration directory from the binaries directory.

By default, CATALINA_BASE (configurations) and CATALINA_HOME (binaries) point to the same folder, but separating the configurations from the binaries can help you to run multiple instances of Tomcat side by side without duplicating the binaries.

It is also useful when you want to update the binaries, without modifying, or needing to backup/restore your configuration files for Tomcat.

Update 2018

There is an easier way to set CATALINA_BASE now with the makebase utility. I have posted a tutorial that covers this subject at http://blog.rasia.io/blog/how-to-easily-setup-lucee-in-tomcat.html along with a video tutorial at https://youtu.be/nuugoG5c-7M

Original answer continued below

To take advantage of this feature, simply create the config directory and point to it with the CATALINA_BASE environment variable. You will have to put some files in that directory:

  • Copy the conf directory from the original Tomcat installation directory, including its contents, and ensure that Tomcat has read permissions to it. Edit the configuration files according to your needs.
  • Create a logs directory if conf/logging.properties points to ${catalina.base}/logs, and ensure that Tomcat has read/write permissions to it.
  • Create a temp directory if you are not overriding the default of $CATALINA_TMPDIR which points to ${CATALINA_BASE}/temp, and ensure that Tomcat has write permissions to it.
  • Create a work directory which defaults to ${CATALINA_BASE}/work, and ensure that Tomcat has write permissions to it.

Increment a Integer's int value?

As Grodriguez says, Integer objects are immutable. The problem here is that you're trying to increment the int value of the player ID rather than the ID itself. In Java 5+, you can just write playerID++.

As a side note, never ever call Integer's constructor. Take advantage of autoboxing by just assigning ints to Integers directly, like Integer foo = 5. This will use Integer.valueOf(int) transparently, which is superior to the constructor because it doesn't always have to create a new object.

Install Windows Service created in Visual Studio

Stealth Change in VS 2010 and .NET 4.0 and Later

No public installers with the RunInstallerAttribute.Yes attribute could be found

There is an alias change or compiler cleanup in .NET that may reveal this little tweak for your specific case.

If you have the following code …

RunInstaller(true)   // old alias  

You may need to update it to

RunInstallerAttribute(true)  // new property spelling

It is like an alias changed under the covers at compile time or at runtime and you will get this error behavior. The above explicit change to RunInstallerAttribute(true) fixed it in all of our install scenarios on all machines.

After you add project or service installer then check for the “old” RunInstaller(true) and change it to the new RunInstallerAttribute(true)

PHP Session timeout

<script type="text/javascript">
window.setTimeout("location=('timeout_session.htm');",900000);
</script>

In the header of every page has been working for me during site tests(the site is not yet in production). The HTML page it falls to ends the session and just informs the user of the need to log in again. This seems an easier way than playing with PHP logic. I'd love some comments on the idea. Any traps I havent seen in it ?

Bootstrap 3: Text overlay on image

You need to set the thumbnail class to position relative then the post-content to absolute.

Check this fiddle

.post-content {
    top:0;
    left:0;
    position: absolute;
}

.thumbnail{
    position:relative;

}

Giving it top and left 0 will make it appear in the top left corner.

URL encoding the space character: + or %20?

This confusion is because URLs are still 'broken' to this day.

Take "http://www.google.com" for instance. This is a URL. A URL is a Uniform Resource Locator and is really a pointer to a web page (in most cases). URLs actually have a very well-defined structure since the first specification in 1994.

We can extract detailed information about the "http://www.google.com" URL:

+---------------+-------------------+
|      Part     |      Data         |
+---------------+-------------------+
|  Scheme       | http              |
|  Host         | www.google.com    |
+---------------+-------------------+

If we look at a more complex URL such as:

"https://bob:[email protected]:8080/file;p=1?q=2#third"

we can extract the following information:

+-------------------+---------------------+
|        Part       |       Data          |
+-------------------+---------------------+
|  Scheme           | https               |
|  User             | bob                 |
|  Password         | bobby               |
|  Host             | www.lunatech.com    |
|  Port             | 8080                |
|  Path             | /file;p=1           |
|  Path parameter   | p=1                 |
|  Query            | q=2                 |
|  Fragment         | third               |
+-------------------+---------------------+

https://bob:[email protected]:8080/file;p=1?q=2#third
\___/   \_/ \___/ \______________/ \__/\_______/ \_/ \___/
  |      |    |          |          |      | \_/  |    |
Scheme User Password    Host       Port  Path |   | Fragment
        \_____________________________/       | Query
                       |               Path parameter
                   Authority

The reserved characters are different for each part.

For HTTP URLs, a space in a path fragment part has to be encoded to "%20" (not, absolutely not "+"), while the "+" character in the path fragment part can be left unencoded.

Now in the query part, spaces may be encoded to either "+" (for backwards compatibility: do not try to search for it in the URI standard) or "%20" while the "+" character (as a result of this ambiguity) has to be escaped to "%2B".

This means that the "blue+light blue" string has to be encoded differently in the path and query parts:

"http://example.com/blue+light%20blue?blue%2Blight+blue".

From there you can deduce that encoding a fully constructed URL is impossible without a syntactical awareness of the URL structure.

This boils down to:

You should have %20 before the ? and + after.

Source

MySQL error 1241: Operand should contain 1 column(s)

Another way to make the parser raise the same exception is the following incorrect clause.

SELECT r.name
FROM roles r
WHERE id IN ( SELECT role_id ,
                     system_user_id
                 FROM role_members m
                 WHERE r.id = m.role_id
                 AND m.system_user_id = intIdSystemUser
             )

The nested SELECT statement in the IN clause returns two columns, which the parser sees as operands, which is technically correct, since the id column matches values from but one column (role_id) in the result returned by the nested select statement, which is expected to return a list.

For sake of completeness, the correct syntax is as follows.

SELECT r.name
FROM roles r
WHERE id IN ( SELECT role_id
                 FROM role_members m
                 WHERE r.id = m.role_id
                 AND m.system_user_id = intIdSystemUser
             )

The stored procedure of which this query is a portion not only parsed, but returned the expected result.

How to convert integer timestamp to Python datetime

datetime.datetime.fromtimestamp() is correct, except you are probably having timestamp in miliseconds (like in JavaScript), but fromtimestamp() expects Unix timestamp, in seconds.

Do it like that:

>>> import datetime
>>> your_timestamp = 1331856000000
>>> date = datetime.datetime.fromtimestamp(your_timestamp / 1e3)

and the result is:

>>> date
datetime.datetime(2012, 3, 16, 1, 0)

Does it answer your question?

EDIT: J.F. Sebastian correctly suggested to use true division by 1e3 (float 1000). The difference is significant, if you would like to get precise results, thus I changed my answer. The difference results from the default behaviour of Python 2.x, which always returns int when dividing (using / operator) int by int (this is called floor division). By replacing the divisor 1000 (being an int) with the 1e3 divisor (being representation of 1000 as float) or with float(1000) (or 1000. etc.), the division becomes true division. Python 2.x returns float when dividing int by float, float by int, float by float etc. And when there is some fractional part in the timestamp passed to fromtimestamp() method, this method's result also contains information about that fractional part (as the number of microseconds).

How do I create an Excel chart that pulls data from multiple sheets?

Here's some code from Excel 2010 that may work. It has a couple specifics (like filtering bad-encode characters from titles) but it was designed to create multiple multi-series graphs from 4-dimensional data having both absolute and percentage-based data. Modify it how you like:

Sub createAllGraphs()

Const chartWidth As Integer = 260
Const chartHeight As Integer = 200




If Sheets.Count = 1 Then
    Sheets.Add , Sheets(1)
    Sheets(2).Name = "AllCharts"
ElseIf Sheets("AllCharts").ChartObjects.Count > 0 Then
    Sheets("AllCharts").ChartObjects.Delete
End If
Dim c As Variant
Dim c2 As Variant
Dim cs As Object
Set cs = Sheets("AllCharts")
Dim s As Object
Set s = Sheets(1)

Dim i As Integer


Dim chartX As Integer
Dim chartY As Integer

Dim r As Integer
r = 2

Dim curA As String
curA = s.Range("A" & r)
Dim curB As String
Dim curC As String
Dim startR As Integer
startR = 2

Dim lastTime As Boolean
lastTime = False

Do While s.Range("A" & r) <> ""

    If curC <> s.Range("C" & r) Then

        If r <> 2 Then
seriesAdd:
            c.SeriesCollection.Add s.Range("D" & startR & ":E" & (r - 1)), , False, True
            c.SeriesCollection(c.SeriesCollection.Count).Name = Replace(s.Range("C" & startR), "Â", "")
            c.SeriesCollection(c.SeriesCollection.Count).XValues = "='" & s.Name & "'!$D$" & startR & ":$D$" & (r - 1)
            c.SeriesCollection(c.SeriesCollection.Count).Values = "='" & s.Name & "'!$E$" & startR & ":$E$" & (r - 1)
            c.SeriesCollection(c.SeriesCollection.Count).HasErrorBars = True
            c.SeriesCollection(c.SeriesCollection.Count).ErrorBars.Select
            c.SeriesCollection(c.SeriesCollection.Count).ErrorBar Direction:=xlY, Include:=xlBoth, Type:=xlCustom, Amount:="='" & s.Name & "'!$F$" & startR & ":$F$" & (r - 1), minusvalues:="='" & s.Name & "'!$F$" & startR & ":$F$" & (r - 1)
            c.SeriesCollection(c.SeriesCollection.Count).ErrorBar Direction:=xlX, Include:=xlBoth, Type:=xlFixedValue, Amount:=0

            c2.SeriesCollection.Add s.Range("D" & startR & ":D" & (r - 1) & ",G" & startR & ":G" & (r - 1)), , False, True
            c2.SeriesCollection(c2.SeriesCollection.Count).Name = Replace(s.Range("C" & startR), "Â", "")
            c2.SeriesCollection(c2.SeriesCollection.Count).XValues = "='" & s.Name & "'!$D$" & startR & ":$D$" & (r - 1)
            c2.SeriesCollection(c2.SeriesCollection.Count).Values = "='" & s.Name & "'!$G$" & startR & ":$G$" & (r - 1)
            c2.SeriesCollection(c2.SeriesCollection.Count).HasErrorBars = True
            c2.SeriesCollection(c2.SeriesCollection.Count).ErrorBars.Select
            c2.SeriesCollection(c2.SeriesCollection.Count).ErrorBar Direction:=xlY, Include:=xlBoth, Type:=xlCustom, Amount:="='" & s.Name & "'!$H$" & startR & ":$H$" & (r - 1), minusvalues:="='" & s.Name & "'!$H$" & startR & ":$H$" & (r - 1)
            c2.SeriesCollection(c2.SeriesCollection.Count).ErrorBar Direction:=xlX, Include:=xlBoth, Type:=xlFixedValue, Amount:=0
            If lastTime = True Then GoTo postLoop
        End If

        If curB <> s.Range("B" & r).Value Then

            If curA <> s.Range("A" & r).Value Then
                chartX = chartX + chartWidth * 2
                chartY = 0
                curA = s.Range("A" & r)
            End If

            Set c = cs.ChartObjects.Add(chartX, chartY, chartWidth, chartHeight)
            Set c = c.Chart
            c.ChartWizard , xlXYScatterSmooth, , , , , True, Replace(s.Range("B" & r), "Â", "") & " " & s.Range("A" & r), s.Range("D1"), s.Range("E1")

            Set c2 = cs.ChartObjects.Add(chartX + chartWidth, chartY, chartWidth, chartHeight)
            Set c2 = c2.Chart
            c2.ChartWizard , xlXYScatterSmooth, , , , , True, Replace(s.Range("B" & r), "Â", "") & " " & s.Range("A" & r) & " (%)", s.Range("D1"), s.Range("G1")

            chartY = chartY + chartHeight
            curB = s.Range("B" & r)
            curC = s.Range("C" & r)
        End If

        curC = s.Range("C" & r)
        startR = r
    End If

    If s.Range("A" & r) <> "" Then oneMoreTime = False ' end the loop for real this time
    r = r + 1
Loop

lastTime = True
GoTo seriesAdd
postLoop:
cs.Activate

End Sub

How to get to Model or Viewbag Variables in a Script Tag

try this method

<script type="text/javascript">

    function set(value) {
        return value;
    }

    alert(set(@Html.Raw(Json.Encode(Model.Message)))); // Message set from controller
    alert(set(@Html.Raw(Json.Encode(ViewBag.UrMessage))));

</script>

Thanks

Copy folder recursively, excluding some folders

you can use tar, with --exclude option , and then untar it in destination. eg

cd /source_directory
tar cvf test.tar --exclude=dir_to_exclude *
mv test.tar /destination 
cd /destination  
tar xvf test.tar

see the man page of tar for more info

How to remove components created with Angular-CLI

This is the NPM known Issue for windows that NPM is pretty much unusable under Windows. This is of course related to the path size limitations.

https://github.com/npm/npm/issues/5641

My main concern here is that there are no mention of these issues when installing node or npm via the website. Not being able to install prime packages makes npm fundamentally unusable for windows.

Package name does not correspond to the file path - IntelliJ

Add this to pom.xml(inside the project tag)

<build>
  <sourceDirectory>src/main/java</sourceDirectory>
</build>

src/main/java is the source folder you want to set. If you already have this line in your pom.xml file, check if it's correct.

Hashcode and Equals for Hashset

  1. There's no need to call equals if hashCode differs.
  2. There's no need to call hashCode if (obj1 == obj2).
  3. There's no need for hashCode and/or equals just to iterate - you're not comparing objects
  4. When needed to distinguish in between objects.

Nginx location priority

There is a handy online tool for testing location priority now:
location priority testing online

How to add new contacts in android

This is working fine for me:

ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
            int rawContactInsertIndex = ops.size();

            ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
                    .withValue(RawContacts.ACCOUNT_TYPE, null)
                    .withValue(RawContacts.ACCOUNT_NAME, null).build());
            ops.add(ContentProviderOperation
                    .newInsert(Data.CONTENT_URI)
                    .withValueBackReference(Data.RAW_CONTACT_ID,rawContactInsertIndex)
                    .withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
                    .withValue(StructuredName.DISPLAY_NAME, "Vikas Patidar") // Name of the person
                    .build());
            ops.add(ContentProviderOperation
                    .newInsert(Data.CONTENT_URI)
                    .withValueBackReference(
                            ContactsContract.Data.RAW_CONTACT_ID,   rawContactInsertIndex)
                    .withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)
                    .withValue(Phone.NUMBER, "9999999999") // Number of the person
                    .withValue(Phone.TYPE, Phone.TYPE_MOBILE).build()); // Type of mobile number                    
            try
            {
                ContentProviderResult[] res = getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
            }
            catch (RemoteException e)
            { 
                // error
            }
            catch (OperationApplicationException e) 
            {
                // error
            }       

DOS: find a string, if found then run another script

C:\test>find /c "string" file | find ": 0" 1>nul && echo "execute command here"

JBoss default password

I suggest visit Add digest auth in jmx-console and read oficial documentation for Configure admin consoles, you can add more security to your JBoss AS console and at these link explains where are the role and user/pass files that you need to change this information for your server and how you can change them. Also I recommend you quit all consoles that you don't use because they can affect to application server's performance. Also there are others links about securing jmx-console that could help you, search in jboss as community site for them (I can't put them here for my actual reputation,sorry). Never you should has the password in plain text over conf/props/ files.

Sorry for my bad English and I hope my answer be useful for you.

How to view the committed files you have not pushed yet?

git diff HEAD origin/master

Where origin is the remote repository and master is the default branch where you will push. Also, do a git fetch before the diff so that you are not diffing against a stale origin/master.

P.S. I am also new to git, so in case the above is wrong, please rectify.

Angular 2 optional route parameter

The suggested answers here, including the accepted answer from rerezz which suggest adding multiple route entries work fine.

However the component will be recreated when changing between the route entries, i.e. between the route entry with the parameter and the entry without the parameter.

If you want to avoid this, you can create your own route matcher which will match both routes:

export function userPageMatcher(segments: UrlSegment[]): UrlMatchResult {
    if (segments.length > 0 && segments[0].path === 'user') {
        if (segments.length === 1) {
            return {
                consumed: segments,
                posParams: {},
            };
        }
        if (segments.length === 2) {
            return {
                consumed: segments,
                posParams: { id: segments[1] },
            };
        }
        return <UrlMatchResult>(null as any);
    }
    return <UrlMatchResult>(null as any);
 }

Then use the matcher in your route config:

const routes: Routes = [
    {
        matcher: userPageMatcher,
        component: User,
    }
];

How to make child divs always fit inside parent div?

There are two techniques commonly used for this:

  1. Absolute Positioning
  2. Table Styles

Given the HTML you provided here is the solution using Absolute positioning:

_x000D_
_x000D_
body #one {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  bottom: 0;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  width: auto;_x000D_
  height: auto;_x000D_
}_x000D_
body #two {_x000D_
  width: auto;  _x000D_
}_x000D_
body #three {_x000D_
  position: absolute;_x000D_
  top: 60px;_x000D_
  bottom: 0;_x000D_
  height: auto;_x000D_
}
_x000D_
<html>_x000D_
<head>_x000D_
<style>_x000D_
html, body {width:100%;height:100%;margin:0;padding:0;}_x000D_
.border {border:1px solid black;}_x000D_
.margin { margin:5px;}_x000D_
#one {width:100%;height:100%;}_x000D_
#two {width:100%;height:50px;}_x000D_
#three {width:100px;height:100%;}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
 <div id="one" class="border">_x000D_
  <div id="two" class="border margin"></div>_x000D_
  <div id="three" class="border margin"></div>_x000D_
 </div>_x000D_
</body
_x000D_
_x000D_
_x000D_

You can always just use the table, tr, and td elements directly despite common criticisms as it will get the job done. If you prefer to use CSS there is no equivalent for colspan so you will likely end up with nested tables. Here is an example:

_x000D_
_x000D_
html, body {_x000D_
  height: 100%;_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
  width: 100%;_x000D_
}_x000D_
#one {_x000D_
  box-sizing: border-box;_x000D_
  display: table;_x000D_
  height: 100%;_x000D_
  overflow: hidden;_x000D_
  width: 100%;_x000D_
  border: 1px solid black;_x000D_
}_x000D_
#two {_x000D_
    box-sizing: border-box;_x000D_
    display: table;_x000D_
    height: 50px;_x000D_
    padding: 5px;_x000D_
    width: 100%;_x000D_
}_x000D_
#three {_x000D_
  box-sizing: border-box;_x000D_
  display: table;_x000D_
  height: 100%;_x000D_
  padding-bottom: 60px;_x000D_
  padding-left: 5px;_x000D_
  _x000D_
}_x000D_
#four {_x000D_
  display: table-cell;_x000D_
  border: 1px solid black;_x000D_
}_x000D_
#five {_x000D_
  display: table-cell;_x000D_
  width: 100px;_x000D_
  border: 1px solid black;_x000D_
}_x000D_
#six {_x000D_
  display: table-cell;  _x000D_
}
_x000D_
<html>_x000D_
 <div id="one">_x000D_
     <div id="two">_x000D_
            <div id="four"></div>_x000D_
        </div>_x000D_
        <div id="three">_x000D_
            <div id="five"></div>_x000D_
            <div id="six"></div>_x000D_
        </div>_x000D_
 </div>_x000D_
  </html>
_x000D_
_x000D_
_x000D_

iOS detect if user is on an iPad

You can check the rangeOfString to see of the word iPad exists like this.

NSString *deviceModel = (NSString*)[UIDevice currentDevice].model;

if ([deviceModel rangeOfString:@"iPad"].location != NSNotFound)  {
NSLog(@"I am an iPad");
} else {
NSLog(@"I am not an iPad");
}

In HTML I can make a checkmark with &#x2713; . Is there a corresponding X-mark?

A corresponding cross for ✓ &#x2713; would be ✗ &#x2717; I think (Dingbats).

how to overlap two div in css?

I edited you fiddle you just need to add z-index to the front element and position it accordingly.

How do I convert a Python program to a runnable .exe Windows program?

If it is a simple py script refer here

Else for GUI :

$ pip3 install cx_Freeze

1) Create a setup.py file and put in the same directory as of the .py file you want to convert.

2)Copy paste the following lines in the setup.py and do change the "filename.py" into the filename you specified.

from cx_Freeze import setup, Executable
setup(
    name="GUI PROGRAM",
    version="0.1",
    description="MyEXE",
    executables=[Executable("filename.py", base="Win32GUI")],
    )

3) Run the setup.py "$python setup.py build"

4)A new directory will be there there called "build". Inside it you will get your .exe file to be ready to launced directly. (Make sure you copy paste the images files and other external files into the build directory)

How to do an INNER JOIN on multiple columns

If you want to search on both FROM and TO airports, you'll want to join on the Airports table twice - then you can use both from and to tables in your results set:

SELECT
   Flights.*,fromAirports.*,toAirports.*
FROM
   Flights
INNER JOIN 
   Airports fromAirports on Flights.fairport = fromAirports.code
INNER JOIN 
   Airports toAirports on Flights.tairport = toAirports.code
WHERE
 ...

Mix Razor and Javascript code

you can use the <text> tag for both cshtml code with javascript

iOS: Multi-line UILabel in Auto Layout

None of the different solutions found in the many topics on the subject worked perfectly for my case (x dynamic multiline labels in dynamic table view cells) .

I found a way to do it :

After having set the constraints on your label and set its multiline property to 0, make a subclass of UILabel ; I called mine AutoLayoutLabel :

@implementation AutoLayoutLabel

- (void)layoutSubviews{
    [self setNeedsUpdateConstraints];
    [super layoutSubviews];
    self.preferredMaxLayoutWidth = CGRectGetWidth(self.bounds);
}

@end

How to convert float number to Binary?

void transfer(double x) {
unsigned long long* p = (unsigned long long*)&x;
for (int i = sizeof(unsigned long long) * 8 - 1; i >= 0; i--) {cout<< ((*p) >>i & 1);}}

Swift add icon/image in UITextField

let image = UIImage(systemName: "envelope")
let textField = UITextField()
textField.leftView = UIImageView(image: image)
textField.leftView?.frame = CGRect(x: 5, y: 5, width: 20 , height:20)
textField.leftViewMode = .always

Move an item inside a list?

A solution very simple, but you have to know the index of the original position and the index of the new position:

list1[index1],list1[index2]=list1[index2],list1[index1]

Replace Both Double and Single Quotes in Javascript String

mystring = mystring.replace(/["']/g, "");

Add text to Existing PDF using Python

Example for [Python 2.7]:

from pyPdf import PdfFileWriter, PdfFileReader
import StringIO
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter

packet = StringIO.StringIO()
# create a new PDF with Reportlab
can = canvas.Canvas(packet, pagesize=letter)
can.drawString(10, 100, "Hello world")
can.save()

#move to the beginning of the StringIO buffer
packet.seek(0)
new_pdf = PdfFileReader(packet)
# read your existing PDF
existing_pdf = PdfFileReader(file("original.pdf", "rb"))
output = PdfFileWriter()
# add the "watermark" (which is the new pdf) on the existing page
page = existing_pdf.getPage(0)
page.mergePage(new_pdf.getPage(0))
output.addPage(page)
# finally, write "output" to a real file
outputStream = file("destination.pdf", "wb")
output.write(outputStream)
outputStream.close()

Example for Python 3.x:


from PyPDF2 import PdfFileWriter, PdfFileReader
import io
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter

packet = io.BytesIO()
# create a new PDF with Reportlab
can = canvas.Canvas(packet, pagesize=letter)
can.drawString(10, 100, "Hello world")
can.save()

#move to the beginning of the StringIO buffer
packet.seek(0)
new_pdf = PdfFileReader(packet)
# read your existing PDF
existing_pdf = PdfFileReader(open("original.pdf", "rb"))
output = PdfFileWriter()
# add the "watermark" (which is the new pdf) on the existing page
page = existing_pdf.getPage(0)
page.mergePage(new_pdf.getPage(0))
output.addPage(page)
# finally, write "output" to a real file
outputStream = open("destination.pdf", "wb")
output.write(outputStream)
outputStream.close()

Type datetime for input parameter in procedure

You should use the ISO-8601 format for string representations of dates - anything else is dependent on the SQL Server language and dateformat settings.

The ISO-8601 format for a DATETIME when using only the date is: YYYYMMDD (no dashes or antyhing!)

For a DATETIME with the time portion, it's YYYY-MM-DDTHH:MM:SS (with dashes, and a T in the middle to separate date and time portions).

If you want to convert a string to a DATE for SQL Server 2008 or newer, you can use YYYY-MM-DD (with the dashes) to achieve the same result. And don't ask me why this is so inconsistent and confusing - it just is, and you'll have to work with that for now.

So in your case, you should try:

declare @a datetime
declare @b datetime 

set @a = '2012-04-06T12:23:45'   -- 6th of April, 2012
set @b = '2012-08-06T21:10:12'   -- 6th of August, 2012

exec LogProcedure 'AccountLog', N'test', @a, @b

Furthermore - your stored proc has problem, since you're concatenating together datetime and string into a string, but you're not converting the datetime to string first, and also, you're forgetting the close quotes in your statement after both dates.

So change this line here to this:

IF @DateFirst <> '' and @DateLast <> ''
   SET @FinalSQL  = @FinalSQL + '  OR CONVERT(Date, DateLog) >= ''' + 
                    CONVERT(VARCHAR(50), @DateFirst, 126) +   -- convert @DateFirst to string for concatenation!
                    ''' AND CONVERT(Date, DateLog) <=''' +  -- you need closing quotes after @DateFirst!
                    CONVERT(VARCHAR(50), @DateLast, 126) + ''''      -- convert @DateLast to string and also: closing tags after that missing!

With these settings, and once you've fixed your stored procedure which contains problems right now, it will work.

Convert array of JSON object strings to array of JS objects

If you have a JS array of JSON objects:

var s=['{"Select":"11","PhotoCount":"12"}','{"Select":"21","PhotoCount":"22"}'];

and you want an array of objects:

// JavaScript array of JavaScript objects
var objs = s.map(JSON.parse);

// ...or for older browsers
var objs=[];
for (var i=s.length;i--;) objs[i]=JSON.parse(s[i]);

// ...or for maximum speed:
var objs = JSON.parse('['+s.join(',')+']');

See the speed tests for browser comparisons.


If you have a single JSON string representing an array of objects:

var s='[{"Select":"11","PhotoCount":"12"},{"Select":"21","PhotoCount":"22"}]';

and you want an array of objects:

// JavaScript array of JavaScript objects
var objs = JSON.parse(s);

If you have an array of objects:

// A JavaScript array of JavaScript objects
var s = [{"Select":"11", "PhotoCount":"12"},{"Select":"21", "PhotoCount":"22"}];

…and you want JSON representation for it, then:

// JSON string representing an array of objects
var json = JSON.stringify(s);

…or if you want a JavaScript array of JSON strings, then:

// JavaScript array of strings (that are each a JSON object)
var jsons = s.map(JSON.stringify);

// ...or for older browsers
var jsons=[];
for (var i=s.length;i--;) jsons[i]=JSON.stringify(s[i]);