Programs & Examples On #Application planning

How to implement a ConfigurationSection with a ConfigurationElementCollection

An easier alternative for those who would prefer not to write all that configuration boilerplate manually...

1) Install Nerdle.AutoConfig from NuGet

2) Define your ServiceConfig type (either a concrete class or just an interface, either will do)

public interface IServiceConfiguration
{
    int Port { get; }
    ReportType ReportType { get; }
}

3) You'll need a type to hold the collection, e.g.

public interface IServiceCollectionConfiguration
{
    IEnumerable<IServiceConfiguration> Services { get; } 
}

4) Add the config section like so (note camelCase naming)

<configSections>
  <section name="serviceCollection" type="Nerdle.AutoConfig.Section, Nerdle.AutoConfig"/>
</configSections>

<serviceCollection>
  <services>
    <service port="6996" reportType="File" />
    <service port="7001" reportType="Other" />
  </services>
</serviceCollection>

5) Map with AutoConfig

var services = AutoConfig.Map<IServiceCollectionConfiguration>();

Prompt Dialog in Windows Forms

Add reference to Microsoft.VisualBasic and use this into your C# code:

string input = Microsoft.VisualBasic.Interaction.InputBox("Prompt", 
                       "Title", 
                       "Default", 
                       0, 
                       0);

To add the refernce: right-click on the References in your Project Explorer window then on Add Reference, and check VisualBasic from that list.

Practical uses for AtomicInteger

The key is that they allow concurrent access and modification safely. They're commonly used as counters in a multithreaded environment - before their introduction this had to be a user written class that wrapped up the various methods in synchronized blocks.

Get and set position with jQuery .offset()

Here is an option. This is just for the x coordinates.

var div1Pos = $("#div1").offset();
var div1X = div1Pos.left;
$('#div2').css({left: div1X});

Omit rows containing specific column of NA

It is possible to use na.omit for data.table:

na.omit(data, cols = c("x", "z"))

What is duck typing?

Tree Traversal with duck typing technique

def traverse(t):
    try:
        t.label()
    except AttributeError:
        print(t, end=" ")
    else:
        # Now we know that t.node is defined
        print('(', t.label(), end=" ")
        for child in t:
            traverse(child)
        print(')', end=" ")

Converting between datetime and Pandas Timestamp objects

>>> pd.Timestamp('2014-01-23 00:00:00', tz=None).to_datetime()
datetime.datetime(2014, 1, 23, 0, 0)
>>> pd.Timestamp(datetime.date(2014, 3, 26))
Timestamp('2014-03-26 00:00:00')

Jquery .on('scroll') not firing the event while scrolling

$("body").on("custom-scroll", ".myDiv", function(){
    console.log("Scrolled :P");
})

$("#btn").on("click", function(){
    $("body").append('<div class="myDiv"><br><br><p>Content1<p><br><br><p>Content2<p><br><br></div>');
    listenForScrollEvent($(".myDiv"));
});


function listenForScrollEvent(el){
    el.on("scroll", function(){
        el.trigger("custom-scroll");
    })
}

see this post - Bind scroll Event To Dynamic DIV?

How to change value of a request parameter in laravel

It work for me

$request = new Request();
$request->headers->set('content-type', 'application/json');     
$request->initialize(['yourParam' => 2]);

check output

$queryParams = $request->query();
dd($queryParams['yourParam']); // 2

Javascript change date into format of (dd/mm/yyyy)

This will ensure you get a two-digit day and month.

function formattedDate(d = new Date) {
  let month = String(d.getMonth() + 1);
  let day = String(d.getDate());
  const year = String(d.getFullYear());

  if (month.length < 2) month = '0' + month;
  if (day.length < 2) day = '0' + day;

  return `${day}/${month}/${year}`;
}

Or terser:

function formattedDate(d = new Date) {
  return [d.getDate(), d.getMonth()+1, d.getFullYear()]
      .map(n => n < 10 ? `0${n}` : `${n}`).join('/');
}

What is a mutex?

In C#, the common mutex used is the Monitor. The type is 'System.Threading.Monitor'. It may also be used implicitly via the 'lock(Object)' statement. One example of its use is when constructing a Singleton class.

private static readonly Object instanceLock = new Object();
private static MySingleton instance;
public static MySingleton Instance
{
    lock(instanceLock)
    {
        if(instance == null)
        {
            instance = new MySingleton();
        }
        return instance;
    }
}

The lock statement using the private lock object creates a critical section. Requiring each thread to wait until the previous is finished. The first thread will enter the section and initialize the instance. The second thread will wait, get into the section, and get the initialized instance.

Any sort of synchronization of a static member may use the lock statement similarly.

How to cast or convert an unsigned int to int in C?

IMHO this question is an evergreen. As stated in various answers, the assignment of an unsigned value that is not in the range [0,INT_MAX] is implementation defined and might even raise a signal. If the unsigned value is considered to be a two's complement representation of a signed number, the probably most portable way is IMHO the way shown in the following code snippet:

#include <limits.h>
unsigned int u;
int i;

if (u <= (unsigned int)INT_MAX)
  i = (int)u; /*(1)*/
else if (u >= (unsigned int)INT_MIN)
  i = -(int)~u - 1; /*(2)*/
else
  i = INT_MIN; /*(3)*/
  • Branch (1) is obvious and cannot invoke overflow or traps, since it is value-preserving.

  • Branch (2) goes through some pains to avoid signed integer overflow by taking the one's complement of the value by bit-wise NOT, casts it to 'int' (which cannot overflow now), negates the value and subtracts one, which can also not overflow here.

  • Branch (3) provides the poison we have to take on one's complement or sign/magnitude targets, because the signed integer representation range is smaller than the two's complement representation range.

This is likely to boil down to a simple move on a two's complement target; at least I've observed such with GCC and CLANG. Also branch (3) is unreachable on such a target -- if one wants to limit the execution to two's complement targets, the code could be condensed to

#include <limits.h>
unsigned int u;
int i;

if (u <= (unsigned int)INT_MAX)
  i = (int)u; /*(1)*/
else
  i = -(int)~u - 1; /*(2)*/

The recipe works with any signed/unsigned type pair, and the code is best put into a macro or inline function so the compiler/optimizer can sort it out. (In which case rewriting the recipe with a ternary operator is helpful. But it's less readable and therefore not a good way to explain the strategy.)

And yes, some of the casts to 'unsigned int' are redundant, but

  • they might help the casual reader

  • some compilers issue warnings on signed/unsigned compares, because the implicit cast causes some non-intuitive behavior by language design

Replace a string in shell script using a variable

you can use the shell (bash/ksh).

$ var="12345678abc"
$ replace="test"
$ echo ${var//12345678/$replace}
testabc

SQL Server Format Date DD.MM.YYYY HH:MM:SS

CONVERT(VARCHAR,GETDATE(),120)

lambda expression for exists within list

var query = list.Where(r => listofIds.Any(id => id == r.Id));

Another approach, useful if the listOfIds array is large:

HashSet<int> hash = new HashSet<int>(listofIds);
var query = list.Where(r => hash.Contains(r.Id));

What are ODEX files in Android?

ART

According to the docs: http://web.archive.org/web/20170909233829/https://source.android.com/devices/tech/dalvik/configure an .odex file:

contains AOT compiled code for methods in the APK.

Furthermore, they appear to be regular shared libraries, since if you get any app, and check:

file /data/app/com.android.appname-*/oat/arm64/base.odex

it says:

base.odex: ELF shared object, 64-bit LSB arm64, stripped

and aarch64-linux-gnu-objdump -d base.odex seems to work and give some meaningful disassembly (but also some rubbish sections).

Difference between WebStorm and PHPStorm

PhpStorm supports all the features of WebStorm but some are not bundled so you might need to install the corresponding plugin for some framework via Settings > Plugins > Install JetBrains Plugin.

Official comment - jetbrains.com

Working with select using AngularJS's ng-options

The question is already answered (BTW, really good and comprehensive answer provided by Ben), but I would like to add another element for completeness, which may be also very handy.

In the example suggested by Ben:

<select ng-model="blah" ng-options="item.ID as item.Title for item in items"></select>

the following ngOptions form has been used: select as label for value in array.

Label is an expression, which result will be the label for <option> element. In that case you can perform certain string concatenations, in order to have more complex option labels.

Examples:

  • ng-options="item.ID as item.Title + ' - ' + item.ID for item in items" gives you labels like Title - ID
  • ng-options="item.ID as item.Title + ' (' + item.Title.length + ')' for item in items" gives you labels like Title (X), where X is length of Title string.

You can also use filters, for example,

  • ng-options="item.ID as item.Title + ' (' + (item.Title | uppercase) + ')' for item in items" gives you labels like Title (TITLE), where Title value of Title property and TITLE is the same value but converted to uppercase characters.
  • ng-options="item.ID as item.Title + ' (' + (item.SomeDate | date) + ')' for item in items" gives you labels like Title (27 Sep 2015), if your model has a property SomeDate

IndexError: too many indices for array

I think the problem is given in the error message, although it is not very easy to spot:

IndexError: too many indices for array
xs  = data[:, col["l1"     ]]

'Too many indices' means you've given too many index values. You've given 2 values as you're expecting data to be a 2D array. Numpy is complaining because data is not 2D (it's either 1D or None).

This is a bit of a guess - I wonder if one of the filenames you pass to loadfile() points to an empty file, or a badly formatted one? If so, you might get an array returned that is either 1D, or even empty (np.array(None) does not throw an Error, so you would never know...). If you want to guard against this failure, you can insert some error checking into your loadfile function.

I highly recommend in your for loop inserting:

print(data)

This will work in Python 2.x or 3.x and might reveal the source of the issue. You might well find it is only one value of your outputs_l1 list (i.e. one file) that is giving the issue.

Python - Get Yesterday's date as a string in YYYY-MM-DD format

You Just need to subtract one day from today's date. In Python datetime.timedelta object lets you create specific spans of time as a timedelta object.

datetime.timedelta(1) gives you the duration of "one day" and is subtractable from a datetime object. After you subtracted the objects you can use datetime.strftime in order to convert the result --which is a date object-- to string format based on your format of choice:

>>> from datetime import datetime, timedelta
>>> yesterday = datetime.now() - timedelta(1)

>>> type(yesterday)                                                                                                                                                                                    
>>> datetime.datetime    

>>> datetime.strftime(yesterday, '%Y-%m-%d')
'2015-05-26'

Note that instead of calling the datetime.strftime function, you can also directly use strftime method of datetime objects:

>>> (datetime.now() - timedelta(1)).strftime('%Y-%m-%d')
'2015-05-26'

As a function:

def yesterday(string=False):
    yesterday = datetime.now() - timedelta(1)
    if string:
        return yesterday.strftime('%Y-%m-%d')
    return yesterday

Where can I get a list of Ansible pre-defined variables?

There are 3 sources of variables in Ansible:

  1. Variables gathered from facts. You can get them by running command: ansible -m setup hostname

  2. Built-in (pre-defined) Ansible variables (AKA 'magic' variables). They are documented in Ansible documentation: http://docs.ansible.com/playbooks_variables.html#magic-variables-and-how-to-access-information-about-other-hosts
    Here is the list extracted from Ansible 1.9 documentation:

    • group_names
    • groups
    • inventory_hostname
    • ansible_hostname
    • inventory_hostname_short
    • play_hosts
    • delegate_to
    • inventory_dir
    • inventory_file
  3. Variables passed to ansible via command line. But obviously you know what they are

HTML: Changing colors of specific words in a string of text

You could use the HTML5 Tag <mark>:

<p>Enter the competition by 
<mark class="red">January 30, 2011</mark> and you could win up to $$$$ — including amazing 
<mark class="blue">summer</mark> trips!</p>

And use this in the CSS:

p {
    font-size:14px;
    color:#538b01;
    font-weight:bold;
    font-style:italic;
}

mark.red {
    color:#ff0000;
    background: none;
}

mark.blue {
    color:#0000A0;
    background: none;
}

The tag <mark> has a default background color...at least in Chrome.

Good tutorial for using HTML5 History API (Pushstate?)

The HTML5 history spec is quirky.

history.pushState() doesn't dispatch a popstate event or load a new page by itself. It was only meant to push state into history. This is an "undo" feature for single page applications. You have to manually dispatch a popstate event or use history.go() to navigate to the new state. The idea is that a router can listen to popstate events and do the navigation for you.

Some things to note:

  • history.pushState() and history.replaceState() don't dispatch popstate events.
  • history.back(), history.forward(), and the browser's back and forward buttons do dispatch popstate events.
  • history.go() and history.go(0) do a full page reload and don't dispatch popstate events.
  • history.go(-1) (back 1 page) and history.go(1) (forward 1 page) do dispatch popstate events.

You can use the history API like this to push a new state AND dispatch a popstate event.

history.pushState({message:'New State!'}, 'New Title', '/link'); window.dispatchEvent(new PopStateEvent('popstate', { bubbles: false, cancelable: false, state: history.state }));

Then listen for popstate events with a router.

PHP output showing little black diamonds with a question mark

That can be caused by unicode or other charset mismatch. Try changing charset in your browser, in of the settings the text will look OK. Then it's question of how to convert your database contents to charset you use for displaying. (Which can actually be just adding utf-8 charset statement to your output.)

How to set zoom level in google map

What you're looking for are the scales for each zoom level. The numbers are in metres. Use these:

20 : 1128.497220

19 : 2256.994440

18 : 4513.988880

17 : 9027.977761

16 : 18055.955520

15 : 36111.911040

14 : 72223.822090

13 : 144447.644200

12 : 288895.288400

11 : 577790.576700

10 : 1155581.153000

9 : 2311162.307000

8 : 4622324.614000

7 : 9244649.227000

6 : 18489298.450000

5 : 36978596.910000

4 : 73957193.820000

3 : 147914387.600000

2 : 295828775.300000

1 : 591657550.500000

Ruby: How to iterate over a range, but in set increments?

You can use Numeric#step.

0.step(30,5) do |num|
  puts "number is #{num}"
end
# >> number is 0
# >> number is 5
# >> number is 10
# >> number is 15
# >> number is 20
# >> number is 25
# >> number is 30

Best way to convert an ArrayList to a string

The below code may help you,

List list = new ArrayList();
list.add("1");
list.add("2");
list.add("3");
String str = list.toString();
System.out.println("Step-1 : " + str);
str = str.replaceAll("[\\[\\]]", "");
System.out.println("Step-2 : " + str);

Output:

Step-1 : [1, 2, 3]
Step-2 : 1, 2, 3

"google is not defined" when using Google Maps V3 in Firefox remotely

Another suggestion that helped me:

Here is what happent to me => My script was working once in 3 time I was loading the page and the error was the «google is not defined».

My function using the google map was in my jQuery document's ready function

$(function(){
   //Here was my logic
})

I simply added this code to make sure it works:

$(function(){
   $(window).load(function(){
       //Here is my logic now
   });
});

It works like a charm. If you want more details on difference between document ready and window load, here is a great post about it: window.onload vs $(document).ready()

The ready event occurs after the HTML document has been loaded, while the onload event occurs later, when all content (e.g. images) also has been loaded.

The onload event is a standard event in the DOM, while the ready event is specific to jQuery. The purpose of the ready event is that it should occur as early as possible after the document has loaded, so that code that adds functionality to the elements in the page doesn't have to wait for all content to load.

Password hash function for Excel VBA

Here is the MD5 code inserted in an Excel Module with the name "module_md5":

    Private Const BITS_TO_A_BYTE = 8
    Private Const BYTES_TO_A_WORD = 4
    Private Const BITS_TO_A_WORD = 32

    Private m_lOnBits(30)
    Private m_l2Power(30)

    Sub SetUpArrays()
        m_lOnBits(0) = CLng(1)
        m_lOnBits(1) = CLng(3)
        m_lOnBits(2) = CLng(7)
        m_lOnBits(3) = CLng(15)
        m_lOnBits(4) = CLng(31)
        m_lOnBits(5) = CLng(63)
        m_lOnBits(6) = CLng(127)
        m_lOnBits(7) = CLng(255)
        m_lOnBits(8) = CLng(511)
        m_lOnBits(9) = CLng(1023)
        m_lOnBits(10) = CLng(2047)
        m_lOnBits(11) = CLng(4095)
        m_lOnBits(12) = CLng(8191)
        m_lOnBits(13) = CLng(16383)
        m_lOnBits(14) = CLng(32767)
        m_lOnBits(15) = CLng(65535)
        m_lOnBits(16) = CLng(131071)
        m_lOnBits(17) = CLng(262143)
        m_lOnBits(18) = CLng(524287)
        m_lOnBits(19) = CLng(1048575)
        m_lOnBits(20) = CLng(2097151)
        m_lOnBits(21) = CLng(4194303)
        m_lOnBits(22) = CLng(8388607)
        m_lOnBits(23) = CLng(16777215)
        m_lOnBits(24) = CLng(33554431)
        m_lOnBits(25) = CLng(67108863)
        m_lOnBits(26) = CLng(134217727)
        m_lOnBits(27) = CLng(268435455)
        m_lOnBits(28) = CLng(536870911)
        m_lOnBits(29) = CLng(1073741823)
        m_lOnBits(30) = CLng(2147483647)

        m_l2Power(0) = CLng(1)
        m_l2Power(1) = CLng(2)
        m_l2Power(2) = CLng(4)
        m_l2Power(3) = CLng(8)
        m_l2Power(4) = CLng(16)
        m_l2Power(5) = CLng(32)
        m_l2Power(6) = CLng(64)
        m_l2Power(7) = CLng(128)
        m_l2Power(8) = CLng(256)
        m_l2Power(9) = CLng(512)
        m_l2Power(10) = CLng(1024)
        m_l2Power(11) = CLng(2048)
        m_l2Power(12) = CLng(4096)
        m_l2Power(13) = CLng(8192)
        m_l2Power(14) = CLng(16384)
        m_l2Power(15) = CLng(32768)
        m_l2Power(16) = CLng(65536)
        m_l2Power(17) = CLng(131072)
        m_l2Power(18) = CLng(262144)
        m_l2Power(19) = CLng(524288)
        m_l2Power(20) = CLng(1048576)
        m_l2Power(21) = CLng(2097152)
        m_l2Power(22) = CLng(4194304)
        m_l2Power(23) = CLng(8388608)
        m_l2Power(24) = CLng(16777216)
        m_l2Power(25) = CLng(33554432)
        m_l2Power(26) = CLng(67108864)
        m_l2Power(27) = CLng(134217728)
        m_l2Power(28) = CLng(268435456)
        m_l2Power(29) = CLng(536870912)
        m_l2Power(30) = CLng(1073741824)
    End Sub

    Private Function LShift(lValue, iShiftBits)
        If iShiftBits = 0 Then
            LShift = lValue
            Exit Function
        ElseIf iShiftBits = 31 Then
            If lValue And 1 Then
                LShift = &H80000000
            Else
                LShift = 0
            End If
            Exit Function
        ElseIf iShiftBits < 0 Or iShiftBits > 31 Then
            Err.Raise 6
        End If

        If (lValue And m_l2Power(31 - iShiftBits)) Then
            LShift = ((lValue And m_lOnBits(31 - (iShiftBits + 1))) * m_l2Power(iShiftBits)) Or &H80000000
        Else
            LShift = ((lValue And m_lOnBits(31 - iShiftBits)) * m_l2Power(iShiftBits))
        End If
    End Function

    Private Function RShift(lValue, iShiftBits)
        If iShiftBits = 0 Then
            RShift = lValue
            Exit Function
        ElseIf iShiftBits = 31 Then
            If lValue And &H80000000 Then
                RShift = 1
            Else
                RShift = 0
            End If
            Exit Function
        ElseIf iShiftBits < 0 Or iShiftBits > 31 Then
            Err.Raise 6
        End If

        RShift = (lValue And &H7FFFFFFE) \ m_l2Power(iShiftBits)

        If (lValue And &H80000000) Then
            RShift = (RShift Or (&H40000000 \ m_l2Power(iShiftBits - 1)))
        End If
    End Function

    Private Function RotateLeft(lValue, iShiftBits)
        RotateLeft = LShift(lValue, iShiftBits) Or RShift(lValue, (32 - iShiftBits))
    End Function

    Private Function AddUnsigned(lX, lY)
        Dim lX4
        Dim lY4
        Dim lX8
        Dim lY8
        Dim lResult

        lX8 = lX And &H80000000
        lY8 = lY And &H80000000
        lX4 = lX And &H40000000
        lY4 = lY And &H40000000

        lResult = (lX And &H3FFFFFFF) + (lY And &H3FFFFFFF)

        If lX4 And lY4 Then
            lResult = lResult Xor &H80000000 Xor lX8 Xor lY8
        ElseIf lX4 Or lY4 Then
            If lResult And &H40000000 Then
                lResult = lResult Xor &HC0000000 Xor lX8 Xor lY8
            Else
                lResult = lResult Xor &H40000000 Xor lX8 Xor lY8
            End If
        Else
            lResult = lResult Xor lX8 Xor lY8
        End If

        AddUnsigned = lResult
    End Function

    Private Function F(x, y, z)
        F = (x And y) Or ((Not x) And z)
    End Function

    Private Function G(x, y, z)
        G = (x And z) Or (y And (Not z))
    End Function

    Private Function H(x, y, z)
        H = (x Xor y Xor z)
    End Function

    Private Function I(x, y, z)
        I = (y Xor (x Or (Not z)))
    End Function

    Private Sub FF(a, b, c, d, x, s, ac)
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac))
        a = RotateLeft(a, s)
        a = AddUnsigned(a, b)
    End Sub

    Private Sub GG(a, b, c, d, x, s, ac)
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac))
        a = RotateLeft(a, s)
        a = AddUnsigned(a, b)
    End Sub

    Private Sub HH(a, b, c, d, x, s, ac)
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac))
        a = RotateLeft(a, s)
        a = AddUnsigned(a, b)
    End Sub

    Private Sub II(a, b, c, d, x, s, ac)
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac))
        a = RotateLeft(a, s)
        a = AddUnsigned(a, b)
    End Sub

    Private Function ConvertToWordArray(sMessage)
        Dim lMessageLength
        Dim lNumberOfWords
        Dim lWordArray()
        Dim lBytePosition
        Dim lByteCount
        Dim lWordCount

        Const MODULUS_BITS = 512
        Const CONGRUENT_BITS = 448

        lMessageLength = Len(sMessage)

        lNumberOfWords = (((lMessageLength + ((MODULUS_BITS - CONGRUENT_BITS) \ BITS_TO_A_BYTE)) \ (MODULUS_BITS \ BITS_TO_A_BYTE)) + 1) * (MODULUS_BITS \ BITS_TO_A_WORD)
        ReDim lWordArray(lNumberOfWords - 1)

        lBytePosition = 0
        lByteCount = 0
        Do Until lByteCount >= lMessageLength
            lWordCount = lByteCount \ BYTES_TO_A_WORD
            lBytePosition = (lByteCount Mod BYTES_TO_A_WORD) * BITS_TO_A_BYTE
            lWordArray(lWordCount) = lWordArray(lWordCount) Or LShift(Asc(Mid(sMessage, lByteCount + 1, 1)), lBytePosition)
            lByteCount = lByteCount + 1
        Loop

        lWordCount = lByteCount \ BYTES_TO_A_WORD
        lBytePosition = (lByteCount Mod BYTES_TO_A_WORD) * BITS_TO_A_BYTE

        lWordArray(lWordCount) = lWordArray(lWordCount) Or LShift(&H80, lBytePosition)

        lWordArray(lNumberOfWords - 2) = LShift(lMessageLength, 3)
        lWordArray(lNumberOfWords - 1) = RShift(lMessageLength, 29)

        ConvertToWordArray = lWordArray
    End Function

    Private Function WordToHex(lValue)
        Dim lByte
        Dim lCount

        For lCount = 0 To 3
            lByte = RShift(lValue, lCount * BITS_TO_A_BYTE) And m_lOnBits(BITS_TO_A_BYTE - 1)
            WordToHex = WordToHex & Right("0" & Hex(lByte), 2)
        Next
    End Function

    Public Function MD5(sMessage)

        module_md5.SetUpArrays

        Dim x
        Dim k
        Dim AA
        Dim BB
        Dim CC
        Dim DD
        Dim a
        Dim b
        Dim c
        Dim d

        Const S11 = 7
        Const S12 = 12
        Const S13 = 17
        Const S14 = 22
        Const S21 = 5
        Const S22 = 9
        Const S23 = 14
        Const S24 = 20
        Const S31 = 4
        Const S32 = 11
        Const S33 = 16
        Const S34 = 23
        Const S41 = 6
        Const S42 = 10
        Const S43 = 15
        Const S44 = 21

        x = ConvertToWordArray(sMessage)

        a = &H67452301
        b = &HEFCDAB89
        c = &H98BADCFE
        d = &H10325476

        For k = 0 To UBound(x) Step 16
            AA = a
            BB = b
            CC = c
            DD = d

            FF a, b, c, d, x(k + 0), S11, &HD76AA478
            FF d, a, b, c, x(k + 1), S12, &HE8C7B756
            FF c, d, a, b, x(k + 2), S13, &H242070DB
            FF b, c, d, a, x(k + 3), S14, &HC1BDCEEE
            FF a, b, c, d, x(k + 4), S11, &HF57C0FAF
            FF d, a, b, c, x(k + 5), S12, &H4787C62A
            FF c, d, a, b, x(k + 6), S13, &HA8304613
            FF b, c, d, a, x(k + 7), S14, &HFD469501
            FF a, b, c, d, x(k + 8), S11, &H698098D8
            FF d, a, b, c, x(k + 9), S12, &H8B44F7AF
            FF c, d, a, b, x(k + 10), S13, &HFFFF5BB1
            FF b, c, d, a, x(k + 11), S14, &H895CD7BE
            FF a, b, c, d, x(k + 12), S11, &H6B901122
            FF d, a, b, c, x(k + 13), S12, &HFD987193
            FF c, d, a, b, x(k + 14), S13, &HA679438E
            FF b, c, d, a, x(k + 15), S14, &H49B40821

            GG a, b, c, d, x(k + 1), S21, &HF61E2562
            GG d, a, b, c, x(k + 6), S22, &HC040B340
            GG c, d, a, b, x(k + 11), S23, &H265E5A51
            GG b, c, d, a, x(k + 0), S24, &HE9B6C7AA
            GG a, b, c, d, x(k + 5), S21, &HD62F105D
            GG d, a, b, c, x(k + 10), S22, &H2441453
            GG c, d, a, b, x(k + 15), S23, &HD8A1E681
            GG b, c, d, a, x(k + 4), S24, &HE7D3FBC8
            GG a, b, c, d, x(k + 9), S21, &H21E1CDE6
            GG d, a, b, c, x(k + 14), S22, &HC33707D6
            GG c, d, a, b, x(k + 3), S23, &HF4D50D87
            GG b, c, d, a, x(k + 8), S24, &H455A14ED
            GG a, b, c, d, x(k + 13), S21, &HA9E3E905
            GG d, a, b, c, x(k + 2), S22, &HFCEFA3F8
            GG c, d, a, b, x(k + 7), S23, &H676F02D9
            GG b, c, d, a, x(k + 12), S24, &H8D2A4C8A

            HH a, b, c, d, x(k + 5), S31, &HFFFA3942
            HH d, a, b, c, x(k + 8), S32, &H8771F681
            HH c, d, a, b, x(k + 11), S33, &H6D9D6122
            HH b, c, d, a, x(k + 14), S34, &HFDE5380C
            HH a, b, c, d, x(k + 1), S31, &HA4BEEA44
            HH d, a, b, c, x(k + 4), S32, &H4BDECFA9
            HH c, d, a, b, x(k + 7), S33, &HF6BB4B60
            HH b, c, d, a, x(k + 10), S34, &HBEBFBC70
            HH a, b, c, d, x(k + 13), S31, &H289B7EC6
            HH d, a, b, c, x(k + 0), S32, &HEAA127FA
            HH c, d, a, b, x(k + 3), S33, &HD4EF3085
            HH b, c, d, a, x(k + 6), S34, &H4881D05
            HH a, b, c, d, x(k + 9), S31, &HD9D4D039
            HH d, a, b, c, x(k + 12), S32, &HE6DB99E5
            HH c, d, a, b, x(k + 15), S33, &H1FA27CF8
            HH b, c, d, a, x(k + 2), S34, &HC4AC5665

            II a, b, c, d, x(k + 0), S41, &HF4292244
            II d, a, b, c, x(k + 7), S42, &H432AFF97
            II c, d, a, b, x(k + 14), S43, &HAB9423A7
            II b, c, d, a, x(k + 5), S44, &HFC93A039
            II a, b, c, d, x(k + 12), S41, &H655B59C3
            II d, a, b, c, x(k + 3), S42, &H8F0CCC92
            II c, d, a, b, x(k + 10), S43, &HFFEFF47D
            II b, c, d, a, x(k + 1), S44, &H85845DD1
            II a, b, c, d, x(k + 8), S41, &H6FA87E4F
            II d, a, b, c, x(k + 15), S42, &HFE2CE6E0
            II c, d, a, b, x(k + 6), S43, &HA3014314
            II b, c, d, a, x(k + 13), S44, &H4E0811A1
            II a, b, c, d, x(k + 4), S41, &HF7537E82
            II d, a, b, c, x(k + 11), S42, &HBD3AF235
            II c, d, a, b, x(k + 2), S43, &H2AD7D2BB
            II b, c, d, a, x(k + 9), S44, &HEB86D391

            a = AddUnsigned(a, AA)
            b = AddUnsigned(b, BB)
            c = AddUnsigned(c, CC)
            d = AddUnsigned(d, DD)
        Next

        MD5 = LCase(WordToHex(a) & WordToHex(b) & WordToHex(c) & WordToHex(d))
    End Function

Applications are expected to have a root view controller at the end of application launch

Make sure that your "Is Initial View Controller" is correctly set for your first scene.enter image description here

That's what's causing the error.

How to set up a cron job to run an executable every hour?

The solution to solve this is to find out why you're getting the segmentation fault, and fix that.

Convert array of indices to 1-hot encoded numpy array

Here is a function that converts a 1-D vector to a 2-D one-hot array.

#!/usr/bin/env python
import numpy as np

def convertToOneHot(vector, num_classes=None):
    """
    Converts an input 1-D vector of integers into an output
    2-D array of one-hot vectors, where an i'th input value
    of j will set a '1' in the i'th row, j'th column of the
    output array.

    Example:
        v = np.array((1, 0, 4))
        one_hot_v = convertToOneHot(v)
        print one_hot_v

        [[0 1 0 0 0]
         [1 0 0 0 0]
         [0 0 0 0 1]]
    """

    assert isinstance(vector, np.ndarray)
    assert len(vector) > 0

    if num_classes is None:
        num_classes = np.max(vector)+1
    else:
        assert num_classes > 0
        assert num_classes >= np.max(vector)

    result = np.zeros(shape=(len(vector), num_classes))
    result[np.arange(len(vector)), vector] = 1
    return result.astype(int)

Below is some example usage:

>>> a = np.array([1, 0, 3])

>>> convertToOneHot(a)
array([[0, 1, 0, 0],
       [1, 0, 0, 0],
       [0, 0, 0, 1]])

>>> convertToOneHot(a, num_classes=10)
array([[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
       [1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 1, 0, 0, 0, 0, 0, 0]])

How to wrap text in LaTeX tables?

Simple like a piece of CAKE!

You can define a new column type like (L in this case) while maintaining the current alignment (c, r or l):

\documentclass{article}
\usepackage{array}
\newcolumntype{L}{>{\centering\arraybackslash}m{3cm}}

\begin{document}

\begin{table}
    \begin{tabular}{|c|L|L|}
        \hline
        Title 1 & Title 2 & Title 3 \\
        \hline 
        one-liner & multi-line and centered & \multicolumn{1}{m{3cm}|}{multi-line piece of text to show case a multi-line and justified cell}   \\
        \hline
        apple & orange & banana \\
        \hline
        apple & orange & banana \\
        \hline
    \end{tabular}
\end{table}
\end{document}

enter image description here

Android and setting width and height programmatically in dp units

You'll have to convert it from dps to pixels using the display scale factor.

final float scale = getContext().getResources().getDisplayMetrics().density;
int pixels = (int) (dps * scale + 0.5f);

Convert a PHP script into a stand-alone windows executable

I tried most of solution given in the 1st answer, the only one that worked for me and is non-commercial is php-desktop.

I simply put my php files in the www/ folder, changed the name of .exe and was able to run my php as an exe !!

Also there is a complete documentation, up to date support, windows and linux (and soon mac) compatibility and options can easily be changed.

Absolute position of an element on the screen using jQuery

See .offset() here in the jQuery doc. It gives the position relative to the document, not to the parent. You perhaps have .offset() and .position() confused. If you want the position in the window instead of the position in the document, you can subtract off the .scrollTop() and .scrollLeft() values to account for the scrolled position.

Here's an excerpt from the doc:

The .offset() method allows us to retrieve the current position of an element relative to the document. Contrast this with .position(), which retrieves the current position relative to the offset parent. When positioning a new element on top of an existing one for global manipulation (in particular, for implementing drag-and-drop), .offset() is the more useful.

To combine these:

var offset = $("selector").offset();
var posY = offset.top - $(window).scrollTop();
var posX = offset.left - $(window).scrollLeft(); 

You can try it here (scroll to see the numbers change): http://jsfiddle.net/jfriend00/hxRPQ/

How to set a JavaScript breakpoint from code in Chrome?

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

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

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

VBA ADODB excel - read data from Recordset

I am surprised that the connection string works for you, because it is missing a semi-colon. Set is only used with objects, so you would not say Set strNaam.

Set cn = CreateObject("ADODB.Connection")
With cn
 .Provider = "Microsoft.Jet.OLEDB.4.0"
  .ConnectionString = "Data Source=D:\test.xls " & _
  ";Extended Properties=""Excel 8.0;HDR=Yes;"""
.Open
End With
strQuery = "SELECT * FROM [Sheet1$E36:E38]"
Set rs = cn.Execute(strQuery)
Do While Not rs.EOF
  For i = 0 To rs.Fields.Count - 1
    Debug.Print rs.Fields(i).Name, rs.Fields(i).Value
    strNaam = rs.Fields(0).Value
  Next
  rs.MoveNext
Loop
rs.Close

There are other ways, depending on what you want to do, such as GetString (GetString Method Description).

Angular 2: Can't bind to 'ngModel' since it isn't a known property of 'input'

In order to make ngModel work when using AppModules (NgModule ), you have to import FormsModule in your AppModule .

Like this:

import { NgModule } from '@angular/core';
import { BrowserModule  } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppComponent }   from './app.component';


@NgModule({
    declarations: [AppComponent],
    imports: [BrowserModule, FormsModule],
    bootstrap: [AppComponent]
})
export class AppModule {}

SQL Server SELECT into existing table

SELECT ... INTO ... only works if the table specified in the INTO clause does not exist - otherwise, you have to use:

INSERT INTO dbo.TABLETWO
SELECT col1, col2
  FROM dbo.TABLEONE
 WHERE col3 LIKE @search_key

This assumes there's only two columns in dbo.TABLETWO - you need to specify the columns otherwise:

INSERT INTO dbo.TABLETWO
  (col1, col2)
SELECT col1, col2
  FROM dbo.TABLEONE
 WHERE col3 LIKE @search_key

Git vs Team Foundation Server

Original: @Rob, TFS has something called "Shelving" that addresses your concern about commiting work-in-progress without it affecting the official build. I realize you see central version control as a hindrance, but with respect to TFS, checking your code into the shelf can be viewed as a strength b/c then the central server has a copy of your work-in-progress in the rare event your local machine crashes or is lost/stolen or you need to switch gears quickly. My point is that TFS should be given proper praise in this area. Also, branching and merging in TFS2010 has been improved from prior versions, and it isn't clear what version you are referring to when you say "... from experience that branching and merging in TFS is not good." Disclaimer: I'm a moderate user of TFS2010.

Edit Dec-5-2011: To the OP, one thing that bothers me about TFS is that it insists on setting all your local files to "read-only" when you're not working on them. If you want to make a change, the flow is that you must "check-out" the file, which just clears the readonly attribute on the file so that TFS knows to keep an eye on it. That's an inconvenient workflow. The way I would prefer it to work is that is just automatically detects if I've made a change and doesn't worry/bother with the file attributes at all. That way, I can modify the file either in Visual Studio, or Notepad, or with whatever tool I please. The version control system should be as transparent as possible in this regard. There is a Windows Explorer Extension (TFS PowerTools) that allows you to work with your files in Windows Explorer, but that doesn't simplify the workflow very much.

What is the meaning of Bus: error 10 in C

string literals are non-modifiable in C

Programmatically Check an Item in Checkboxlist where text is equal to what I want

All Credit to @Jim Scott -- just added one touch. (ASP.NET 4.5 & C#)

Refractoring this a little more... if you pass the CheckBoxList as an object to the method, you can reuse it for any CheckBoxList. Also you can use either the Text or the Value.

private void SelectCheckBoxList(string valueToSelect, CheckBoxList lst)
{
    ListItem listItem = lst.Items.FindByValue(valueToSelect);
    //ListItem listItem = lst.Items.FindByText(valueToSelect);
    if (listItem != null) listItem.Selected = true;
}

//How to call it -- in this case from a SQLDataReader and "chkRP" is my CheckBoxList`

SelectCheckBoxList(dr["kRPId"].ToString(), chkRP);`

Android Camera Preview Stretched

OK, so I think there is no sufficient answer for general camera preview stretching problem. Or at least I didn't find one. My app also suffered this stretching syndrome and it took me a while to puzzle together a solution from all the user answers on this portal and internet.

I tried @Hesam's solution but it didn't work and left my camera preview majorly distorted.

First I show the code of my solution (the important parts of the code) and then I explain why I took those steps. There is room for performance modifications.

Main activity xml layout:

<RelativeLayout 
    android:id="@+id/main_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <FrameLayout
        android:id="@+id/camera_preview"
        android:layout_centerInParent="true"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
    />
</RelativeLayout>

Camera Preview:

public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {

private SurfaceHolder prHolder;
private Camera prCamera;
public List<Camera.Size> prSupportedPreviewSizes;
private Camera.Size prPreviewSize;

@SuppressWarnings("deprecation")
public YoCameraPreview(Context context, Camera camera) {
    super(context);
    prCamera = camera;

    prSupportedPreviewSizes = prCamera.getParameters().getSupportedPreviewSizes();

    prHolder = getHolder();
    prHolder.addCallback(this);
    prHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}

public void surfaceCreated(SurfaceHolder holder) {
    try {
        prCamera.setPreviewDisplay(holder);
        prCamera.startPreview();
    } catch (IOException e) {
        Log.d("Yologram", "Error setting camera preview: " + e.getMessage());
    }
}

public void surfaceDestroyed(SurfaceHolder holder) {
}

public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
    if (prHolder.getSurface() == null){
      return;
    }

    try {
        prCamera.stopPreview();
    } catch (Exception e){
    }

    try {
        Camera.Parameters parameters = prCamera.getParameters();
        List<String> focusModes = parameters.getSupportedFocusModes();
        if (focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
            parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
        }
        parameters.setPreviewSize(prPreviewSize.width, prPreviewSize.height);

        prCamera.setParameters(parameters);
        prCamera.setPreviewDisplay(prHolder);
        prCamera.startPreview();

    } catch (Exception e){
        Log.d("Yologram", "Error starting camera preview: " + e.getMessage());
    }
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

    final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec);
    final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec);

    setMeasuredDimension(width, height);

    if (prSupportedPreviewSizes != null) {
        prPreviewSize = 
            getOptimalPreviewSize(prSupportedPreviewSizes, width, height);
    }    
}

public Camera.Size getOptimalPreviewSize(List<Camera.Size> sizes, int w, int h) {

    final double ASPECT_TOLERANCE = 0.1;
    double targetRatio = (double) h / w;

    if (sizes == null)
        return null;

    Camera.Size optimalSize = null;
    double minDiff = Double.MAX_VALUE;

    int targetHeight = h;

    for (Camera.Size size : sizes) {
        double ratio = (double) size.width / size.height;
        if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE)
            continue;

        if (Math.abs(size.height - targetHeight) < minDiff) {
            optimalSize = size;
            minDiff = Math.abs(size.height - targetHeight);
        }
    }

    if (optimalSize == null) {
        minDiff = Double.MAX_VALUE;
        for (Camera.Size size : sizes) {
            if (Math.abs(size.height - targetHeight) < minDiff) {
                optimalSize = size;
                minDiff = Math.abs(size.height - targetHeight);
            }
        }
    }

    return optimalSize;
}
}

Main activity:

public class MainActivity extends Activity {

...

@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);     
    setContentView(R.layout.activity_main);

        maCamera = getCameraInstance();

        maLayoutPreview = (FrameLayout) findViewById(R.id.camera_preview);

        maPreview = new CameraPreview(this, maCamera);

        Point displayDim = getDisplayWH();
        Point layoutPreviewDim = calcCamPrevDimensions(displayDim, 
                maPreview.getOptimalPreviewSize(maPreview.prSupportedPreviewSizes, 
                    displayDim.x, displayDim.y));
        if (layoutPreviewDim != null) {
            RelativeLayout.LayoutParams layoutPreviewParams = 
                (RelativeLayout.LayoutParams) maLayoutPreview.getLayoutParams();
            layoutPreviewParams.width = layoutPreviewDim.x;
            layoutPreviewParams.height = layoutPreviewDim.y;
            layoutPreviewParams.addRule(RelativeLayout.CENTER_IN_PARENT);
            maLayoutPreview.setLayoutParams(layoutPreviewParams);
        }
        maLayoutPreview.addView(maPreview);
}

@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
private Point getDisplayWH() {

    Display display = this.getWindowManager().getDefaultDisplay();
    Point displayWH = new Point();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
        display.getSize(displayWH);
        return displayWH;
    }
    displayWH.set(display.getWidth(), display.getHeight());
    return displayWH;
}

private Point calcCamPrevDimensions(Point disDim, Camera.Size camDim) {

    Point displayDim = disDim;
    Camera.Size cameraDim = camDim;

    double widthRatio = (double) displayDim.x / cameraDim.width;
    double heightRatio = (double) displayDim.y / cameraDim.height;

    // use ">" to zoom preview full screen
    if (widthRatio < heightRatio) {
        Point calcDimensions = new Point();
        calcDimensions.x = displayDim.x;
        calcDimensions.y = (displayDim.x * cameraDim.height) / cameraDim.width;
        return calcDimensions;
    }
    // use "<" to zoom preview full screen
    if (widthRatio > heightRatio) { 
        Point calcDimensions = new Point();
        calcDimensions.x = (displayDim.y * cameraDim.width) / cameraDim.height;
        calcDimensions.y = displayDim.y;
        return calcDimensions;
    }
    return null;
}   
}

My commentary:

The point of all this is, that although you calculate the optimal camera size in getOptimalPreviewSize() you only pick the closest ratio to fit your screen. So unless the ratio is exactly the same the preview will stretch.

Why will it stretch? Because your FrameLayout camera preview is set in layout.xml to match_parent in width and height. So that is why the preview will stretch to full screen.

What needs to be done is to set camera preview layout width and height to match the chosen camera size ratio, so the preview keeps its aspect ratio and won't distort.

I tried to use the CameraPreview class to do all the calculations and layout changes, but I couldn't figure it out. I tried to apply this solution, but SurfaceView doesn't recognize getChildCount () or getChildAt (int index). I think, I got it working eventually with a reference to maLayoutPreview, but it was misbehaving and applied the set ratio to my whole app and it did so after first picture was taken. So I let it go and moved the layout modifications to the MainActivity.

In CameraPreview I changed prSupportedPreviewSizes and getOptimalPreviewSize() to public so I can use it in MainActivity. Then I needed the display dimensions (minus the navigation/status bar if there is one) and chosen optimal camera size. I tried to get the RelativeLayout (or FrameLayout) size instead of display size, but it was returning zero value. This solution didn't work for me. The layout got it's value after onWindowFocusChanged (checked in the log).

So I have my methods for calculating the layout dimensions to match the aspect ratio of chosen camera size. Now you just need to set LayoutParams of your camera preview layout. Change the width, height and center it in parent.

There are two choices how to calculate the preview dimensions. Either you want it to fit the screen with black bars (if windowBackground is set to null) on the sides or top/bottom. Or you want the preview zoomed to full screen. I left comment with more information in calcCamPrevDimensions().

How to customise the Jackson JSON mapper implicitly used by Spring Boot?

I found the solution described above with :

spring.jackson.serialization-inclusion=non_null

To only work starting at the 1.4.0.RELEASE version of spring boot. In all other cases the config is ignored.

I verified this by experimenting with a modification of the spring boot sample "spring-boot-sample-jersey"

What are the benefits of using C# vs F# or F# vs C#?

To answer your question as I understand it: Why use C#? (You say you're already sold on F#.)

First off. It's not just "functional versus OO". It's "Functional+OO versus OO". C#'s functional features are pretty rudimentary. F#'s are not. Meanwhile, F# does almost all of C#'s OO features. For the most part, F# ends up as a superset of C#'s functionality.

However, there are a few cases where F# might not be the best choice:

  • Interop. There are plenty of libraries that just aren't going to be too comfortable from F#. Maybe they exploit certain C# OO things that F# doesn't do the same, or perhaps they rely on internals of the C# compiler. For example, Expression. While you can easily turn an F# quotation into an Expression, the result is not always exactly what C# would create. Certain libraries have a problem with this.

    • Yes, interop is a pretty big net and can result in a bit of friction with some libraries.

    • I consider interop to also include if you have a large existing codebase. It might not make sense to just start writing parts in F#.

  • Design tools. F# doesn't have any. Does not mean it couldn't have any, but just right now you can't whip up a WinForms app with F# codebehind. Even where it is supported, like in ASPX pages, you don't currently get IntelliSense. So, you need to carefully consider where your boundaries will be for generated code. On a really tiny project that almost exclusively uses the various designers, it might not be worth it to use F# for the "glue" or logic. On larger projects, this might become less of an issue.

    • This isn't an intrinsic problem. Unlike the Rex M's answer, I don't see anything intrinsic about C# or F# that make them better to do a UI with lots of mutable fields. Maybe he was referring to the extra overhead of having to write "mutable" and using <- instead of =.

    • Also depends on the library/designer used. We love using ASP.NET MVC with F# for all the controllers, then a C# web project to get the ASPX designers. We mix the actual ASPX "code inline" between C# and F#, depending on what we need on that page. (IntelliSense versus F# types.)

  • Other tools. They might just be expecting C# only and not know how to deal with F# projects or compiled code. Also, F#'s libraries don't ship as part of .NET, so you have a bit extra to ship around.

  • But the number one issue? People. If none of your developers want to learn F#, or worse, have severe difficulty comprehending certain aspects, then you're probably toast. (Although, I'd argue you're toast anyways in that case.) Oh, and if management says no, that might be an issue.

I wrote about this a while ago: Why NOT F#?

Counting array elements in Python

The method len() returns the number of elements in the list.

Syntax:

len(myArray)

Eg:

myArray = [1, 2, 3]
len(myArray)

Output:

3

What does "Failure [INSTALL_FAILED_OLDER_SDK]" mean in Android Studio?

Besides checking the right minSdkVersion in build.gradle, make sure you have installed all necessary tools and correct SDK Platform for your preferred Android Version in SDK Manager. In Android Studio klick on Tools -> Android -> SDK Manager. Then install at minimum (for Android 2.2 without emulator):

  • Android SDK Tools
  • Android SDK Platform-tools
  • Android SDK Build-tools (latest)
  • Android 2.2 (API 8)
    • SDK Platform
    • Google APIs

This is what worked for me.

How to center cards in bootstrap 4?

You can also use Bootstrap 4 flex classes

Like: .align-item-center and .justify-content-center

We can use these classes identically for all device view.

Like: .align-item-sm-center, .align-item-md-center, .justify-content-xl-center, .justify-content-lg-center, .justify-content-xs-center

.text-center class is used to align text in center.

z-index not working with position absolute

Old question but this answer might help someone.

If you are trying to display the contents of the container outside of the boundaries of the container, make sure that it doesn't have overflow:hidden, otherwise anything outside of it will be cut off.

Specify path to node_modules in package.json

Yarn supports this feature:

# .yarnrc file in project root
--modules-folder /node_modules

But your experience can vary depending on which packages you use. I'm not sure you'd want to go into that rabbit hole.

Strip spaces/tabs/newlines - python

Use str.split([sep[, maxsplit]]) with no sep or sep=None:

From docs:

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.

Demo:

>>> myString.split()
['I', 'want', 'to', 'Remove', 'all', 'white', 'spaces,', 'new', 'lines', 'and', 'tabs']

Use str.join on the returned list to get this output:

>>> ' '.join(myString.split())
'I want to Remove all white spaces, new lines and tabs'

How to get query string parameter from MVC Razor markup?

Noneof the answers worked for me, I was getting "'HttpRequestBase' does not contain a definition for 'Query'", but this did work:

HttpContext.Current.Request.QueryString["index"]

Switch statement fall-through...should it be allowed?

As with anything: if used with care, it can be an elegant tool.

However, I think the drawbacks more than justify not to use it, and finally not to allow it anymore (C#). Among the problems are:

  • it's easy to "forget" a break
  • it's not always obvious for code maintainers that an omitted break was intentional

Good use of a switch/case fall-through:

switch (x)
{
case 1:
case 2:
case 3:
 Do something
 break;
}

Baaaaad use of a switch/case fall-through:

switch (x)
{
case 1:
    Some code
case 2:
    Some more code
case 3:
    Even more code
    break;
}

This can be rewritten using if/else constructs with no loss at all in my opinion.

My final word: stay away from fall-through case labels as in the bad example, unless you are maintaining legacy code where this style is used and well understood.

Android - Get value from HashMap

HashMap<String, String> meMap=new HashMap<String, String>();
meMap.put("Color1","Red");
meMap.put("Color2","Blue");
meMap.put("Color3","Green");
meMap.put("Color4","White");
Iterator iterator = meMap.keySet().iterator();
while( iterator. hasNext() ){
    Toast.makeText(getBaseContext(), meMap.get(iterator.next().toString()), 
    Toast.LENGTH_SHORT).show();
}

Open JQuery Datepicker by clicking on an image w/ no input field

If you are using an input field and an icon (like this example):

<input name="hasta" id="Hasta"  type="text" readonly  />
<a href="#" id="Hasta_icono" ></a>

You can attach the datepicker to your icon (in my case inside the A tag via CSS) like this:

$("#Hasta").datepicker();
  $("#Hasta_icono").click(function() { 
   $("#Hasta").datepicker( "show" );
  });

Java and SQLite

When you compile and run the code, you should set the classpath options value. Just like the following:

javac -classpath .;sqlitejdbc-v056.jar Text.java

java -classpath .;sqlitejdbc-v056.jar Text

Please pay attention to "." and the sparate ";"(win, the linux is ":")

Load an image from a url into a PictureBox

Try this:

var request = WebRequest.Create("http://www.gravatar.com/avatar/6810d91caff032b202c50701dd3af745?d=identicon&r=PG");

using (var response = request.GetResponse())
using (var stream = response.GetResponseStream())
{
    pictureBox1.Image = Bitmap.FromStream(stream);
}

How to use a variable for the database name in T-SQL?

Put the entire script into a template string, with {SERVERNAME} placeholders. Then edit the string using:

SET @SQL_SCRIPT = REPLACE(@TEMPLATE, '{SERVERNAME}', @DBNAME)

and then run it with

EXECUTE (@SQL_SCRIPT)

It's hard to believe that, in the course of three years, nobody noticed that my code doesn't work!

You can't EXEC multiple batches. GO is a batch separator, not a T-SQL statement. It's necessary to build three separate strings, and then to EXEC each one after substitution.

I suppose one could do something "clever" by breaking the single template string into multiple rows by splitting on GO; I've done that in ADO.NET code.

And where did I get the word "SERVERNAME" from?

Here's some code that I just tested (and which works):

DECLARE @DBNAME VARCHAR(255)
SET @DBNAME = 'TestDB'

DECLARE @CREATE_TEMPLATE VARCHAR(MAX)
DECLARE @COMPAT_TEMPLATE VARCHAR(MAX)
DECLARE @RECOVERY_TEMPLATE VARCHAR(MAX)

SET @CREATE_TEMPLATE = 'CREATE DATABASE {DBNAME}'
SET @COMPAT_TEMPLATE='ALTER DATABASE {DBNAME} SET COMPATIBILITY_LEVEL = 90'
SET @RECOVERY_TEMPLATE='ALTER DATABASE {DBNAME} SET RECOVERY SIMPLE'

DECLARE @SQL_SCRIPT VARCHAR(MAX)

SET @SQL_SCRIPT = REPLACE(@CREATE_TEMPLATE, '{DBNAME}', @DBNAME)
EXECUTE (@SQL_SCRIPT)

SET @SQL_SCRIPT = REPLACE(@COMPAT_TEMPLATE, '{DBNAME}', @DBNAME)
EXECUTE (@SQL_SCRIPT)

SET @SQL_SCRIPT = REPLACE(@RECOVERY_TEMPLATE, '{DBNAME}', @DBNAME)
EXECUTE (@SQL_SCRIPT)

Laravel 5.1 API Enable Cors

Here is my CORS middleware:

<?php namespace App\Http\Middleware;

use Closure;

class CORS {

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        header("Access-Control-Allow-Origin: *");

        // ALLOW OPTIONS METHOD
        $headers = [
            'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
            'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin'
        ];
        if($request->getMethod() == "OPTIONS") {
            // The client-side application can set only headers allowed in Access-Control-Allow-Headers
            return Response::make('OK', 200, $headers);
        }

        $response = $next($request);
        foreach($headers as $key => $value)
            $response->header($key, $value);
        return $response;
    }

}

To use CORS middleware you have to register it first in your app\Http\Kernel.php file like this:

protected $routeMiddleware = [
        //other middlewares
        'cors' => 'App\Http\Middleware\CORS',
    ];

Then you can use it in your routes

Route::get('example', array('middleware' => 'cors', 'uses' => 'ExampleController@dummy'));

Multiple "order by" in LINQ

Using non-lambda, query-syntax LINQ, you can do this:

var movies = from row in _db.Movies 
             orderby row.Category, row.Name
             select row;

[EDIT to address comment] To control the sort order, use the keywords ascending (which is the default and therefore not particularly useful) or descending, like so:

var movies = from row in _db.Movies 
             orderby row.Category descending, row.Name
             select row;

How do I list all the files in a directory and subdirectories in reverse chronological order?

try this:

ls -ltraR |egrep -v '\.$|\.\.|\.:|\.\/|total' |sed '/^$/d'

How to get current local date and time in Kotlin

I use this to fetch data from API every 20 seconds

 private fun isFetchNeeded(savedAt: Long): Boolean {
        return savedAt + 20000 < System.currentTimeMillis()
    }

I can not find my.cnf on my windows computer

You can find the basedir (and within maybe your my.cnf) if you do the following query in your mysql-Client (e.g. phpmyadmin)

SHOW VARIABLES

Insert variable into Header Location PHP

You can add it like this

header('Location: http://linkhere.com/'.$url_endpoint);

Disable form autofill in Chrome without disabling autocomplete

Fix: prevent browser autofill in

 <input type="password" readonly onfocus="this.removeAttribute('readonly');"/>

Update: Mobile Safari sets cursor in the field, but does not show virtual keyboard. New Fix works like before but handles virtual keyboard:

<input id="email" readonly type="email" onfocus="if (this.hasAttribute('readonly')) {
    this.removeAttribute('readonly');
    // fix for mobile safari to show virtual keyboard
    this.blur();    this.focus();  }" />

Live Demo https://jsfiddle.net/danielsuess/n0scguv6/

// UpdateEnd

Explanation Instead of filling in whitespaces or window-on-load functions this snippet works by setting readonly-mode and changing to writable if user focuses this input field (focus contains mouse click and tabbing through fields).

No jQuery needed, pure JavaScript.

CentOS: Enabling GD Support in PHP Installation

Put the command

yum install php-gd

and restart the server (httpd, nginx, etc)

service httpd restart

"X does not name a type" error in C++

When the compiler compiles the class User and gets to the MyMessageBox line, MyMessageBox has not yet been defined. The compiler has no idea MyMessageBox exists, so cannot understand the meaning of your class member.

You need to make sure MyMessageBox is defined before you use it as a member. This is solved by reversing the definition order. However, you have a cyclic dependency: if you move MyMessageBox above User, then in the definition of MyMessageBox the name User won't be defined!

What you can do is forward declare User; that is, declare it but don't define it. During compilation, a type that is declared but not defined is called an incomplete type. Consider the simpler example:

struct foo; // foo is *declared* to be a struct, but that struct is not yet defined

struct bar
{
    // this is okay, it's just a pointer;
    // we can point to something without knowing how that something is defined
    foo* fp; 

    // likewise, we can form a reference to it
    void some_func(foo& fr);

    // but this would be an error, as before, because it requires a definition
    /* foo fooMember; */
};

struct foo // okay, now define foo!
{
    int fooInt;
    double fooDouble;
};

void bar::some_func(foo& fr)
{
    // now that foo is defined, we can read that reference:
    fr.fooInt = 111605;
    fr.foDouble = 123.456;
}

By forward declaring User, MyMessageBox can still form a pointer or reference to it:

class User; // let the compiler know such a class will be defined

class MyMessageBox
{
public:
    // this is ok, no definitions needed yet for User (or Message)
    void sendMessage(Message *msg, User *recvr); 

    Message receiveMessage();
    vector<Message>* dataMessageList;
};

class User
{
public:
    // also ok, since it's now defined
    MyMessageBox dataMsgBox;
};

You cannot do this the other way around: as mentioned, a class member needs to have a definition. (The reason is that the compiler needs to know how much memory User takes up, and to know that it needs to know the size of its members.) If you were to say:

class MyMessageBox;

class User
{
public:
    // size not available! it's an incomplete type
    MyMessageBox dataMsgBox;
};

It wouldn't work, since it doesn't know the size yet.


On a side note, this function:

 void sendMessage(Message *msg, User *recvr);

Probably shouldn't take either of those by pointer. You can't send a message without a message, nor can you send a message without a user to send it to. And both of those situations are expressible by passing null as an argument to either parameter (null is a perfectly valid pointer value!)

Rather, use a reference (possibly const):

 void sendMessage(const Message& msg, User& recvr);

Add Expires headers

The easiest way to add these headers is a .htaccess file that adds some configuration to your server. If the assets are hosted on a server that you don't control, there's nothing you can do about it.

Note that some hosting providers will not let you use .htaccess files, so check their terms if it doesn't seem to work.

The HTML5Boilerplate project has an excellent .htaccess file that covers the necessary settings. See the relevant part of the file at their Github repository

These are the important bits

# ----------------------------------------------------------------------
# Expires headers (for better cache control)
# ----------------------------------------------------------------------

# These are pretty far-future expires headers.
# They assume you control versioning with filename-based cache busting
# Additionally, consider that outdated proxies may miscache
# www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/

# If you don't use filenames to version, lower the CSS and JS to something like
# "access plus 1 week".

<IfModule mod_expires.c>
  ExpiresActive on

# Your document html
  ExpiresByType text/html "access plus 0 seconds"

# Media: images, video, audio
  ExpiresByType audio/ogg "access plus 1 month"
  ExpiresByType image/gif "access plus 1 month"
  ExpiresByType image/jpeg "access plus 1 month"
  ExpiresByType image/png "access plus 1 month"
  ExpiresByType video/mp4 "access plus 1 month"
  ExpiresByType video/ogg "access plus 1 month"
  ExpiresByType video/webm "access plus 1 month"

# CSS and JavaScript
  ExpiresByType application/javascript "access plus 1 year"
  ExpiresByType text/css "access plus 1 year"
</IfModule>

They have documented what that file does, the most important bit is that you need to rename your CSS and Javascript files whenever they change, because your visitor's browsers will not check them again for a year, once they are cached.

Insert multiple rows WITHOUT repeating the "INSERT INTO ..." part of the statement?

I've been using the following:

INSERT INTO [TableName] (ID, Name)
values (NEWID(), NEWID())
GO 10

It will add ten rows with unique GUIDs for ID and Name.

Note: do not end the last line (GO 10) with ';' because it will throw error: A fatal scripting error occurred. Incorrect syntax was encountered while parsing GO.

PHP Fatal error: Cannot access empty property

As I see in your code, it seems you are following an old documentation/tutorial about OOP in PHP based on PHP4 (OOP wasn't supported but adapted somehow to be used in a simple ways), since PHP5 an official support was added and the notation has been changed from what it was.

Please see this code review here:

<?php
class my_class{

    public $my_value = array();

    function __construct( $value ) { // the constructor name is __construct instead of the class name
        $this->my_value[] = $value;
    }
    function set_value ($value){
    // Error occurred from here as Undefined variable: my_value
        $this->my_value = $value; // remove the $ sign
    }

}

$a = new my_class ('a');
$a->my_value[] = 'b';
$a->set_value ('c'); // your array variable here will be replaced by a simple string 
// $a->my_class('d'); // you can call this if you mean calling the contructor 


// at this stage you can't loop on the variable since it have been replaced by a simple string ('c')
foreach ($a->my_value as &$value) { // look for foreach samples to know how to use it well
    echo $value;
}

?>

I hope it helps

How to convert latitude or longitude to meters?

The earth is an annoyingly irregular surface, so there is no simple formula to do this exactly. You have to live with an approximate model of the earth, and project your coordinates onto it. The model I typically see used for this is WGS 84. This is what GPS devices usually use to solve the exact same problem.

NOAA has some software you can download to help with this on their website.

Android OnClickListener - identify a button

Five Ways to Wire Up an Event Listener is a great article overviewing the various ways to set up a single event listener. Let me expand that here for multiple listeners.

1. Member Class

public class main extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //attach an instance of HandleClick to the Button
        HandleClick handleClick = new HandleClick();
        findViewById(R.id.button1).setOnClickListener(handleClick);
        findViewById(R.id.button2).setOnClickListener(handleClick);
    }    
    private class HandleClick implements OnClickListener{
        public void onClick(View view) {
            switch(view.getId()) {
            case R.id.button1:
                // do stuff
                break;
            case R.id.button2:
                // do stuff
                break;
            }
        }
    }
}

2. Interface Type

public class main extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        findViewById(R.id.button1).setOnClickListener(handleClick);
        findViewById(R.id.button2).setOnClickListener(handleClick);
    }
    private OnClickListener handleClick = new OnClickListener() {
        public void onClick(View view) {
            switch (view.getId()) {
            case R.id.button1:
                // do stuff
                break;
            case R.id.button2:
                // do stuff
                break;
            }
        }
    };
}

3. Anonymous Inner Class

public class main extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                // do stuff
            }
        });
        findViewById(R.id.button2).setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                // do stuff
            }
        });
    }
}

4. Implementation in Activity

public class main extends Activity implements OnClickListener {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        findViewById(R.id.button1).setOnClickListener(this);
        findViewById(R.id.button2).setOnClickListener(this);
    }
    public void onClick(View view) {
        switch (view.getId()) {
        case R.id.button1:
            // do stuff
            break;
        case R.id.button2:
            // do stuff
            break;
        }
    }
}

5. Attribute in View Layout for OnClick Events

public class main extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    public void HandleClick(View view) {
        switch (view.getId()) {
        case R.id.button1:
            // do stuff
            break;
        case R.id.button2:
            // do stuff
            break;
        }
    }
}

And in xml:

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="HandleClick" />
<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="HandleClick" />

Display Python datetime without time

For me, I needed to KEEP a timetime object because I was using UTC and it's a bit of a pain. So, this is what I ended up doing:

date = datetime.datetime.utcnow()

start_of_day = date - datetime.timedelta(
    hours=date.hour, 
    minutes=date.minute, 
    seconds=date.second, 
    microseconds=date.microsecond
)

end_of_day = start_of_day + datetime.timedelta(
    hours=23, 
    minutes=59, 
    seconds=59
)

Example output:

>>> date
datetime.datetime(2016, 10, 14, 17, 21, 5, 511600)
>>> start_of_day
datetime.datetime(2016, 10, 14, 0, 0)
>>> end_of_day
datetime.datetime(2016, 10, 14, 23, 59, 59)

TCP: can two different sockets share a port?

No. It is not possible to share the same port at a particular instant. But you can make your application such a way that it will make the port access at different instant.

The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. on deploying to tomcat

This issue can even occur when you try to run your project from controller page. Run your project from the jsp page. Go to your jsp page; right-click->Run As->Run on Server. I faced the same issue.I was running my project from the controller page. Run your project from jsp page.

How to join two tables by multiple columns in SQL?

SELECT E.CaseNum, E.FileNum, E.ActivityNum, E.Grade, V.Score
FROM Evaluation E
INNER JOIN Value V
ON E.CaseNum = V.CaseNum AND E.FileNum = V.FileNum AND E.ActivityNum = V.ActivityNum

QByteArray to QString

You can use:

QString::fromStdString(byteArray.toStdString())

How to round up value C# to the nearest integer?

It is simple. So follow this code.

decimal d = 10.5;
int roundNumber = (int)Math.Floor(d + 0.5);

Result is 11

Changing WPF title bar background color

You can also create a borderless window, and make the borders and title bar yourself

cannot be cast to java.lang.Comparable

  • the object which implements Comparable is Fegan.

The method compareTo you are overidding in it should have a Fegan object as a parameter whereas you are casting it to a FoodItems. Your compareTo implementation should describe how a Fegan compare to another Fegan.

  • To actually do your sorting, you might want to make your FoodItems implement Comparable aswell and copy paste your actual compareTo logic in it.

Should I write script in the body or the head of the html?

Head, or before closure of body tag. When DOM loads JS is then executed, that is exactly what jQuery document.ready does.

OnClick vs OnClientClick for an asp:CheckBox?

You are right this is inconsistent. What is happening is that CheckBox doesn't HAVE an server-side OnClick event, so your markup gets rendered to the browser. http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.checkbox_events.aspx

Whereas Button does have a OnClick - so ASP.NET expects a reference to an event in your OnClick markup.

Resize background image in div using css

Answer

You have multiple options:

  1. background-size: 100% 100%; - image gets stretched (aspect ratio may be preserved, depending on browser)
  2. background-size: contain; - image is stretched without cutting it while preserving aspect ratio
  3. background-size: cover; - image is completely covering the element while preserving aspect ratio (image can be cut off)

/edit: And now, there is even more: https://alligator.io/css/cropping-images-object-fit

Demo on Codepen

Update 2017: Preview

Here are screenshots for some browsers to show their differences.

Chrome

preview background types chrome


Firefox

preview background types firefox


Edge

preview background types edge


IE11

preview background types ie11

Takeaway Message

background-size: 100% 100%; produces the least predictable result.

Resources

Delete first character of a string in Javascript

_x000D_
_x000D_
String.prototype.trimStartWhile = function(predicate) {_x000D_
    if (typeof predicate !== "function") {_x000D_
     return this;_x000D_
    }_x000D_
    let len = this.length;_x000D_
    if (len === 0) {_x000D_
        return this;_x000D_
    }_x000D_
    let s = this, i = 0;_x000D_
    while (i < len && predicate(s[i])) {_x000D_
     i++;_x000D_
    }_x000D_
    return s.substr(i)_x000D_
}_x000D_
_x000D_
let str = "0000000000ABC",_x000D_
    r = str.trimStartWhile(c => c === '0');_x000D_
    _x000D_
console.log(r);
_x000D_
_x000D_
_x000D_

Calling @Html.Partial to display a partial view belonging to a different controller

That's no problem.

@Html.Partial("../Controller/View", model)

or

@Html.Partial("~/Views/Controller/View.cshtml", model)

Should do the trick.

If you want to pass through the (other) controller, you can use:

@Html.Action("action", "controller", parameters)

or any of the other overloads

What is difference between monolithic and micro kernel?

1.Monolithic Kernel (Pure Monolithic) :all

  • All Kernel Services From single component

    (-) addition/removal is not possible, less/Zero flexible

    (+) inter Component Communication is better

e.g. :- Traditional Unix

2.Micro Kernel :few

  • few services(Memory management ,CPU management,IPC etc) from core kernel, other services(File management,I/O management. etc.) from different layers/component

  • Split Approach [Some services is in privileged(kernel) mode and some are in Normal(user) mode]

    (+)flexible for changes/up-gradations

    (-)communication overhead

e.g.:- QNX etc.

3.Modular kernel(Modular Monolithic) :most

  • Combination of Micro and Monolithic kernel

  • Collection of Modules -- modules can be --> Static + Dynamic

  • Drivers come in the form of Modules

e.g. :- Linux Modern OS

How can I read a whole file into a string variable

Use ioutil.ReadFile:

func ReadFile(filename string) ([]byte, error)

ReadFile reads the file named by filename and returns the contents. A successful call returns err == nil, not err == EOF. Because ReadFile reads the whole file, it does not treat an EOF from Read as an error to be reported.

You will get a []byte instead of a string. It can be converted if really necessary:

s := string(buf)

Open links in new window using AngularJS

It works for me. Inject $window service in to your controller.

$window.open("somepath/", "_blank")

Postgresql - unable to drop database because of some auto connections to DB

You can prevent future connections:

REVOKE CONNECT ON DATABASE thedb FROM public;

(and possibly other users/roles; see \l+ in psql)

You can then terminate all connections to this db except your own:

SELECT pid, pg_terminate_backend(pid) 
FROM pg_stat_activity 
WHERE datname = current_database() AND pid <> pg_backend_pid();

On older versions pid was called procpid so you'll have to deal with that.

Since you've revoked CONNECT rights, whatever was trying to auto-connect should no longer be able to do so.

You'll now be able to drop the DB.

This won't work if you're using superuser connections for normal operations, but if you're doing that you need to fix that problem first.


After you're done dropping the database, if you create the database again, you can execute below command to restore the access

GRANT CONNECT ON DATABASE thedb TO public;

How to downgrade to older version of Gradle

Change your gradle version in project setting: If you are using mac,click File->Project structure,then change gradle version,here: enter image description here

And check your build.gradle of project,change dependency of gradle,like this:

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.0.1'
    }
}

Anonymous method in Invoke call

You need to create a delegate type. The keyword 'delegate' in the anonymous method creation is a bit misleading. You are not creating an anonymous delegate but an anonymous method. The method you created can be used in a delegate. Like this:

myControl.Invoke(new MethodInvoker(delegate() { (MyMethod(this, new MyEventArgs(someParameter)); }));

AngularJS : Factory and Service?

Factory and Service is a just wrapper of a provider.

Factory

Factory can return anything which can be a class(constructor function), instance of class, string, number or boolean. If you return a constructor function, you can instantiate in your controller.

 myApp.factory('myFactory', function () {

  // any logic here..

  // Return any thing. Here it is object
  return {
    name: 'Joe'
  }
}

Service

Service does not need to return anything. But you have to assign everything in this variable. Because service will create instance by default and use that as a base object.

myApp.service('myService', function () {

  // any logic here..

  this.name = 'Joe';
}

Actual angularjs code behind the service

function service(name, constructor) {
    return factory(name, ['$injector', function($injector) {
        return $injector.instantiate(constructor);
    }]);
}

It just a wrapper around the factory. If you return something from service, then it will behave like Factory.

IMPORTANT: The return result from Factory and Service will be cache and same will be returned for all controllers.

When should i use them?

Factory is mostly preferable in all cases. It can be used when you have constructor function which needs to be instantiated in different controllers.

Service is a kind of Singleton Object. The Object return from Service will be same for all controller. It can be used when you want to have single object for entire application. Eg: Authenticated user details.

For further understanding, read

http://iffycan.blogspot.in/2013/05/angular-service-or-factory.html

http://viralpatel.net/blogs/angularjs-service-factory-tutorial/

how to get rid of notification circle in right side of the screen?

This stuff comes from ES file explorer

Just go into this app > settings

Then there is an option that says logging floating window, you just need to disable that and you will get rid of this infernal bubble for good

How to continue the code on the next line in VBA

In VBA (and VB.NET) the line terminator (carriage return) is used to signal the end of a statement. To break long statements into several lines, you need to

Use the line-continuation character, which is an underscore (_), at the point at which you want the line to break. The underscore must be immediately preceded by a space and immediately followed by a line terminator (carriage return).

(From How to: Break and Combine Statements in Code)

In other words: Whenever the interpreter encounters the sequence <space>_<line terminator>, it is ignored and parsing continues on the next line. Note, that even when ignored, the line continuation still acts as a token separator, so it cannot be used in the middle of a variable name, for example. You also cannot continue a comment by using a line-continuation character.

To break the statement in your question into several lines you could do the following:

U_matrix(i, j, n + 1) = _
     k * b_xyt(xi, yi, tn) / (4 * hx * hy) * U_matrix(i + 1, j + 1, n) + _
     (k * (a_xyt(xi, yi, tn) / hx ^ 2 + d_xyt(xi, yi, tn) / (2 * hx)))

(Leading whitespaces are ignored.)

How to call a VbScript from a Batch File without opening an additional command prompt

rem This is the command line version
cscript "C:\Users\guest\Desktop\123\MyScript.vbs"

OR

rem This is the windowed version
wscript "C:\Users\guest\Desktop\123\MyScript.vbs"

You can also add the option //e:vbscript to make sure the scripting engine will recognize your script as a vbscript.

Windows/DOS batch files doesn't require escaping \ like *nix.

You can still use "C:\Users\guest\Desktop\123\MyScript.vbs", but this requires the user has *.vbs associated to wscript.

How to show Error & Warning Message Box in .NET/ How to Customize MessageBox

Try details: use any option..

    MessageBox.Show("your message",
    "window title", 
    MessageBoxButtons.OK, 
    MessageBoxIcon.Warning // for Warning  
    //MessageBoxIcon.Error // for Error 
    //MessageBoxIcon.Information  // for Information
    //MessageBoxIcon.Question // for Question
   );

C++ calling base class constructors

Why the base class' default constructor is called? Turns out it's not always be the case. Any constructor of the base class (with different signatures) can be invoked from the derived class' constructor. In your case, the default constructor is called because it has no parameters so it's default.

When a derived class is created, the order the constructors are called is always Base -> Derived in the hierarchy. If we have:

class A {..}
class B : A {...}
class C : B {...}
C c;

When c is create, the constructor for A is invoked first, and then the constructor for B, and then the constructor for C.

To guarantee that order, when a derived class' constructor is called, it always invokes the base class' constructor before the derived class' constructor can do anything else. For that reason, the programmer can manually invoke a base class' constructor in the only initialisation list of the derived class' constructor, with corresponding parameters. For instance, in the following code, Derived's default constructor will invoke Base's constructor Base::Base(int i) instead of the default constructor.

Derived() : Base(5)
{      
}

If there's no such constructor invoked in the initialisation list of the derived class' constructor, then the program assumes a base class' constructor with no parameters. That's the reason why a constructor with no parameters (i.e. the default constructor) is invoked.

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

When ever I get a new computer at work or switch jobs these are steps I follow setup github access. Mac or Windows

-Go to https://github.[yourWorkDomain].com. navigate to Settings ? Developer Settings ? Personal access tokens
-Generate a new token
-Set the token description and only check the “repo” box for scope (this will give you repo:status, repo_deployment, public_repo, repo:invite access)

-After your are given the token, copy it (don't navigate away yet, confirm the next two steps work)
-Try to clone the repo again(using “https”)
-For the username use your Username
-For the password, paste the token you copied
-All future requests should work now without asking for your username and password.

Find the last element of an array while using a foreach loop in PHP

You can dirctly get last index by:

$numItems = count($arr);

echo $arr[$numItems-1];

What are the differences between B trees and B+ trees?

One possible use of B+ trees is that it is suitable for situations where the tree grows so large that it does not fit into available memory. Thus, you'd generally expect to be doing multiple I/O's.
It does often happen that a B+ tree is used even when it in fact fits into memory, and then your cache manager might keep it there permanently. But this is a special case, not the general one, and caching policy is a separate from B+ tree maintenance as such.

Also, in a B+ tree, the leaf pages are linked together in a linked list (or doubly-linked list), which optimizes traversals (for range searches, sorting, etc.). So the number of pointers is a function of the specific algorithm that is used.

download a file from Spring boot rest service

Option 1 using an InputStreamResource

Resource implementation for a given InputStream.

Should only be used if no other specific Resource implementation is > applicable. In particular, prefer ByteArrayResource or any of the file-based Resource implementations where possible.

@RequestMapping(path = "/download", method = RequestMethod.GET)
public ResponseEntity<Resource> download(String param) throws IOException {

    // ...

    InputStreamResource resource = new InputStreamResource(new FileInputStream(file));

    return ResponseEntity.ok()
            .headers(headers)
            .contentLength(file.length())
            .contentType(MediaType.APPLICATION_OCTET_STREAM)
            .body(resource);
}

Option2 as the documentation of the InputStreamResource suggests - using a ByteArrayResource:

@RequestMapping(path = "/download", method = RequestMethod.GET)
public ResponseEntity<Resource> download(String param) throws IOException {

    // ...

    Path path = Paths.get(file.getAbsolutePath());
    ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(path));

    return ResponseEntity.ok()
            .headers(headers)
            .contentLength(file.length())
            .contentType(MediaType.APPLICATION_OCTET_STREAM)
            .body(resource);
}

How do I declare and initialize an array in Java?

I find it is helpful if you understand each part:

Type[] name = new Type[5];

Type[] is the type of the variable called name ("name" is called the identifier). The literal "Type" is the base type, and the brackets mean this is the array type of that base. Array types are in turn types of their own, which allows you to make multidimensional arrays like Type[][] (the array type of Type[]). The keyword new says to allocate memory for the new array. The number between the bracket says how large the new array will be and how much memory to allocate. For instance, if Java knows that the base type Type takes 32 bytes, and you want an array of size 5, it needs to internally allocate 32 * 5 = 160 bytes.

You can also create arrays with the values already there, such as

int[] name = {1, 2, 3, 4, 5};

which not only creates the empty space but fills it with those values. Java can tell that the primitives are integers and that there are 5 of them, so the size of the array can be determined implicitly.

Can anonymous class implement interface?

The best solution is just not to use anonymous classes.

public class Test
{
    class DummyInterfaceImplementor : IDummyInterface
    {
        public string A { get; set; }
        public string B { get; set; }
    }

    public void WillThisWork()
    {
        var source = new DummySource[0];
        var values = from value in source
                     select new DummyInterfaceImplementor()
                     {
                         A = value.A,
                         B = value.C + "_" + value.D
                     };

        DoSomethingWithDummyInterface(values.Cast<IDummyInterface>());

    }

    public void DoSomethingWithDummyInterface(IEnumerable<IDummyInterface> values)
    {
        foreach (var value in values)
        {
            Console.WriteLine("A = '{0}', B = '{1}'", value.A, value.B);
        }
    }
}

Note that you need to cast the result of the query to the type of the interface. There might be a better way to do it, but I couldn't find it.

Best way to check if MySQL results returned in PHP?

if (mysql_num_rows($result)==0) { PERFORM ACTION }

For PHP 5 and 7 and above use mysqli:

if (mysqli_num_rows($result)==0) { PERFORM ACTION }

This gets my vote.

OP assuming query is not returning any error, so this should be one of the way

C# winforms combobox dynamic autocomplete

This code is write on your form load. It display all the Tour in database when user type letter in combo box. This code automatically suggest and append the right choice as user want.

            con.Open();
            cmd = new SqlCommand("SELECT DISTINCT Tour FROM DetailsTB", con);
            SqlDataReader sdr = cmd.ExecuteReader();
            DataTable dt = new DataTable();
            dt.Load(sdr);
            combo_search2.DisplayMember = "Tour";
            combo_search2.DroppedDown = true;

            List<string> list = new List<string>();
            foreach (DataRow row in dt.Rows)
            {
                list.Add(row.Field<string>("Tour"));
            }
            this.combo_search2.Items.AddRange(list.ToArray<string>());
            combo_search2.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            combo_search2.AutoCompleteSource = AutoCompleteSource.ListItems;
            con.Close();

Kubernetes how to make Deployment to update image

Another option which is more suitable for debugging but worth mentioning is to check in revision history of your rollout:

$ kubectl rollout history deployment my-dep
deployment.apps/my-dep
 
REVISION  CHANGE-CAUSE
1         <none>
2         <none>
3         <none>

To see the details of each revision, run:

 kubectl rollout history deployment my-dep --revision=2

And then returning to the previous revision by running:

 $kubectl rollout undo deployment my-dep --to-revision=2

And then returning back to the new one.
Like running ctrl+z -> ctrl+y (:

(*) The CHANGE-CAUSE is <none> because you should run the updates with the --record flag - like mentioned here:

kubectl set image deployment/nginx-deployment nginx=nginx:1.16.1 --record

(**) There is a discussion regarding deprecating this flag.

Adding an .env file to React Project

So I'm myself new to React and I found a way to do it.

This solution does not require any extra packages.

Step 1 ReactDocs

In the above docs they mention export in Shell and other options, the one I'll attempt to explain is using .env file

1.1 create Root/.env

#.env file
REACT_APP_SECRET_NAME=secretvaluehere123

Important notes it MUST start with REACT_APP_

1.2 Access ENV variable

#App.js file or the file you need to access ENV
<p>print env secret to HTML</p>
<pre>{process.env.REACT_APP_SECRET_NAME}</pre>

handleFetchData() { // access in API call
  fetch(`https://awesome.api.io?api-key=${process.env.REACT_APP_SECRET_NAME}`)
    .then((res) => res.json())
    .then((data) => console.log(data))
}

1.3 Build Env Issue

So after I did step 1.1|2 it was not working, then I found the above issue/solution. React read/creates env when is built so you need to npm run start every time you modify the .env file so the variables get updated.

How to use custom font in a project written in Android Studio

I think instead of downloading .ttf file we can use Google fonts. It's very easy to implements. only you have to follow these steps. step 1) Open layout.xml of your project and the select font family of text view in attributes (for reference screen shot is attached) enter image description here

step 2) The in font family select More fonts.. option if your font is not there. then you will see a new window will open, there you can type your required font & select the desired font from that list i.e) Regular, Bold, Italic etc.. as shown in below image. enter image description here

step 3) Then you will observe a font folder will be auto generated in /res folder having your selected fonts xml file.

enter image description here

Then you can directly use this font family in xml as

      android:fontFamily="@font/josefin_sans_bold"

or pro grammatically you can achieve this by using

  Typeface typeface = ResourcesCompat.getFont(this, R.font.app_font);
  fontText.setTypeface(typeface);

How do I convert a TimeSpan to a formatted string?

Thanks to Peter for the extension method. I modified it to work with longer time spans better:

namespace ExtensionMethods
{
    public static class TimeSpanExtensionMethods
    {
        public static string ToReadableString(this TimeSpan span)
        {
            string formatted = string.Format("{0}{1}{2}",
                (span.Days / 7) > 0 ? string.Format("{0:0} weeks, ", span.Days / 7) : string.Empty,
                span.Days % 7 > 0 ? string.Format("{0:0} days, ", span.Days % 7) : string.Empty,
                span.Hours > 0 ? string.Format("{0:0} hours, ", span.Hours) : string.Empty);

            if (formatted.EndsWith(", ")) formatted = formatted.Substring(0, formatted.Length - 2);

            return formatted;
        }
    }
}

clear form values after submission ajax

$("#cform")[0].reset();

or in plain javascript:

document.getElementById("cform").reset();

What is the difference between ELF files and bin files?

A bin file is just the bits and bytes that go into the rom or a particular address from which you will run the program. You can take this data and load it directly as is, you need to know what the base address is though as that is normally not in there.

An elf file contains the bin information but it is surrounded by lots of other information, possible debug info, symbols, can distinguish code from data within the binary. Allows for more than one chunk of binary data (when you dump one of these to a bin you get one big bin file with fill data to pad it to the next block). Tells you how much binary you have and how much bss data is there that wants to be initialised to zeros (gnu tools have problems creating bin files correctly).

The elf file format is a standard, arm publishes its enhancements/variations on the standard. I recommend everyone writes an elf parsing program to understand what is in there, dont bother with a library, it is quite simple to just use the information and structures in the spec. Helps to overcome gnu problems in general creating .bin files as well as debugging linker scripts and other things that can help to mess up your bin or elf output.

Formatting doubles for output in C#

Use

Console.WriteLine(String.Format("  {0:G17}", i));

That will give you all the 17 digits it have. By default, a Double value contains 15 decimal digits of precision, although a maximum of 17 digits is maintained internally. {0:R} will not always give you 17 digits, it will give 15 if the number can be represented with that precision.

which returns 15 digits if the number can be represented with that precision or 17 digits if the number can only be represented with maximum precision. There isn't any thing you can to do to make the the double return more digits that is the way it's implemented. If you don't like it do a new double class yourself...

.NET's double cant store any more digits than 17 so you cant see 6.89999999999999946709 in the debugger you would see 6.8999999999999995. Please provide an image to prove us wrong.

how to empty recyclebin through command prompt?

You can use a powershell script (this works for users with folder redirection as well to not have their recycle bins take up server storage space)

$Shell = New-Object -ComObject Shell.Application
$RecBin = $Shell.Namespace(0xA)
$RecBin.Items() | %{Remove-Item $_.Path -Recurse -Confirm:$false}

The above script is taken from here.

If you have windows 10 and powershell 5 there is the Clear-RecycleBin commandlet.

To use Clear-RecycleBin inside PowerShell without confirmation, you can use Clear-RecycleBin -Force. Official documentation can be found here

Package signatures do not match the previously installed version

This error happened to me when a previous build on my simulator / phone was being uploaded with different credentials. What I had to do was run:

adb uninstall com.exampleappname

Once I did that I was able to rerun the build and generate an APK.

Maven:Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:2.7:resources

What worked for me is to add include tag in order to specify exactly what I want to filter.

It seems the resource plugin has problems going through the whole src/main/resource folder, probably due to some specific files inside.

    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
            <includes>
                <include>application.yml</include>
            </includes>
        </resource>
    </resources>

Java, Check if integer is multiple of a number

//More Efficiently
public class Multiples {
    public static void main(String[]args) {

        int j = 5;

        System.out.println(j % 4 == 0);

    }
}

Chart.js v2 hide dataset labels

add:

Chart.defaults.global.legend.display = false;

in the starting of your script code;

Merge Two Lists in R

Here's some code that I ended up writing, based upon @Andrei's answer but without the elegancy/simplicity. The advantage is that it allows a more complex recursive merge and also differs between elements that should be connected with rbind and those that are just connected with c:

# Decided to move this outside the mapply, not sure this is 
# that important for speed but I imagine redefining the function
# might be somewhat time-consuming
mergeLists_internal <- function(o_element, n_element){
  if (is.list(n_element)){
    # Fill in non-existant element with NA elements
    if (length(n_element) != length(o_element)){
      n_unique <- names(n_element)[! names(n_element) %in% names(o_element)]
      if (length(n_unique) > 0){
        for (n in n_unique){
          if (is.matrix(n_element[[n]])){
            o_element[[n]] <- matrix(NA, 
                                     nrow=nrow(n_element[[n]]), 
                                     ncol=ncol(n_element[[n]]))
          }else{
            o_element[[n]] <- rep(NA, 
                                  times=length(n_element[[n]]))
          }
        }
      }

      o_unique <- names(o_element)[! names(o_element) %in% names(n_element)]
      if (length(o_unique) > 0){
        for (n in o_unique){
          if (is.matrix(n_element[[n]])){
            n_element[[n]] <- matrix(NA, 
                                     nrow=nrow(o_element[[n]]), 
                                     ncol=ncol(o_element[[n]]))
          }else{
            n_element[[n]] <- rep(NA, 
                                  times=length(o_element[[n]]))
          }
        }
      }
    }  

    # Now merge the two lists
    return(mergeLists(o_element, 
                      n_element))

  }
  if(length(n_element)>1){
    new_cols <- ifelse(is.matrix(n_element), ncol(n_element), length(n_element))
    old_cols <- ifelse(is.matrix(o_element), ncol(o_element), length(o_element))
    if (new_cols != old_cols)
      stop("Your length doesn't match on the elements,",
           " new element (", new_cols , ") !=",
           " old element (", old_cols , ")")
  }

  return(rbind(o_element, 
               n_element, 
               deparse.level=0))
  return(c(o_element, 
           n_element))
}
mergeLists <- function(old, new){
  if (is.null(old))
    return (new)

  m <- mapply(mergeLists_internal, old, new, SIMPLIFY=FALSE)
  return(m)
}

Here's my example:

v1 <- list("a"=c(1,2), b="test 1", sublist=list(one=20:21, two=21:22))
v2 <- list("a"=c(3,4), b="test 2", sublist=list(one=10:11, two=11:12, three=1:2))
mergeLists(v1, v2)

This results in:

$a
     [,1] [,2]
[1,]    1    2
[2,]    3    4

$b
[1] "test 1" "test 2"

$sublist
$sublist$one
     [,1] [,2]
[1,]   20   21
[2,]   10   11

$sublist$two
     [,1] [,2]
[1,]   21   22
[2,]   11   12

$sublist$three
     [,1] [,2]
[1,]   NA   NA
[2,]    1    2

Yeah, I know - perhaps not the most logical merge but I have a complex parallel loop that I had to generate a more customized .combine function for, and therefore I wrote this monster :-)

MVC Razor @foreach

a reply to @DarinDimitrov for a case where i have used foreach in a razor view.

<li><label for="category">Category</label>
        <select id="category">
            <option value="0">All</option>
            @foreach(Category c in Model.Categories)
            {
                <option title="@c.Description" value="@c.CategoryID">@c.Name</option>
            }
        </select>
</li>

Using Javascript can you get the value from a session attribute set by servlet in the HTML page

No, you can't. JavaScript is executed on the client side (browser), while the session data is stored on the server.

However, you can expose session variables for JavaScript in several ways:

  • a hidden input field storing the variable as its value and reading it through the DOM API
  • an HTML5 data attribute which you can read through the DOM
  • storing it as a cookie and accessing it through JavaScript
  • injecting it directly in the JS code, if you have it inline

In JSP you'd have something like:

<input type="hidden" name="pONumb" value="${sessionScope.pONumb} />

or:

<div id="product" data-prodnumber="${sessionScope.pONumb}" />

Then in JS:

// you can find a more efficient way to select the input you want
var inputs = document.getElementsByTagName("input"), len = inputs.length, i, pONumb;
for (i = 0; i < len; i++) {
    if (inputs[i].name == "pONumb") {
        pONumb = inputs[i].value;
        break;
    }
}

or:

var product = document.getElementById("product"), pONumb;
pONumb = product.getAttribute("data-prodnumber");

The inline example is the most straightforward, but if you then want to store your JavaScript code as an external resource (the recommended way) it won't be feasible.

<script>
    var pONumb = ${sessionScope.pONumb};
    [...]
</script>

Is there a max array length limit in C++?

One thing I don't think has been mentioned in the previous answers.

I'm always sensing a "bad smell" in the refactoring sense when people are using such things in their design.

That's a huge array and possibly not the best way to represent your data both from an efficiency point of view and a performance point of view.

cheers,

Rob

How to add an object to an ArrayList in Java

change Date to Object which is between parenthesis

PHP reindex array?

array_values does the job :

$myArray  = array_values($myArray);

Also some other php function do not preserve the keys, i.e. reset the index.

Closing Twitter Bootstrap Modal From Angular Controller

You can add data-dismiss="modal" to your button attributes which call angularjs funtion.

Such as;

<button type="button" class="btn btn-default" data-dismiss="modal">Send Form</button>

Plotting with ggplot2: "Error: Discrete value supplied to continuous scale" on categorical y-axis

In my case, you need to convert the column(you think this column is numeric, but actually not) to numeric

geom_segment(data=tmpp, 
   aes(x=start_pos, 
   y=lib.complexity, 
   xend=end_pos, 
   yend=lib.complexity)
)
# to 
geom_segment(data=tmpp, 
   aes(x=as.numeric(start_pos), 
   y=as.numeric(lib.complexity), 
   xend=as.numeric(end_pos), 
   yend=as.numeric(lib.complexity))
)

Left align block of equations

Try to use the fleqn document class option.

\documentclass[fleqn]{article}

(See also http://en.wikibooks.org/wiki/LaTeX/Basics for a list of other options.)

split string only on first instance - java

string.split("=", 2);

As String.split(java.lang.String regex, int limit) explains:

The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string. The substrings in the array are in the order in which they occur in this string. If the expression does not match any part of the input then the resulting array has just one element, namely this string.

The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter.

The string boo:and:foo, for example, yields the following results with these parameters:

Regex Limit    Result
:     2        { "boo", "and:foo" }
:     5        { "boo", "and", "foo" }
:    -2        { "boo", "and", "foo" }
o     5        { "b", "", ":and:f", "", "" }
o    -2        { "b", "", ":and:f", "", "" }
o     0        { "b", "", ":and:f" }

Arrays.asList() of an array

Let's consider the following simplified example:

public class Example {
    public static void main(String[] args) {
        int[] factors = {1, 2, 3};
        ArrayList<Integer> f = new ArrayList(Arrays.asList(factors));
        System.out.println(f);
    }
}

At the println line this prints something like "[[I@190d11]" which means that you have actually constructed an ArrayList that contains int arrays.

Your IDE and compiler should warn about unchecked assignments in that code. You should always use new ArrayList<Integer>() or new ArrayList<>() instead of new ArrayList(). If you had used it, there would have been a compile error because of trying to pass List<int[]> to the constructor.

There is no autoboxing from int[] to Integer[], and anyways autoboxing is only syntactic sugar in the compiler, so in this case you need to do the array copy manually:

public static int getTheNumber(int[] factors) {
    List<Integer> f = new ArrayList<Integer>();
    for (int factor : factors) {
        f.add(factor); // after autoboxing the same as: f.add(Integer.valueOf(factor));
    }
    Collections.sort(f);
    return f.get(0) * f.get(f.size() - 1);
}

Create a 3D matrix

If you want to define a 3D matrix containing all zeros, you write

A = zeros(8,4,20);

All ones uses ones, all NaN's uses NaN, all false uses false instead of zeros.

If you have an existing 2D matrix, you can assign an element in the "3rd dimension" and the matrix is augmented to contain the new element. All other new matrix elements that have to be added to do that are set to zero.

For example

B = magic(3); %# creates a 3x3 magic square
B(2,1,2) = 1; %# and you have a 3x3x2 array

In React Native, how do I put a view on top of another view, with part of it lying outside the bounds of the view behind?

You can use elevation property for Android if you don't mind the shadow.

{
  elevation:1
} 

Can an abstract class have a constructor?

Yes, Abstract Classes can have constructors !

Here is an example using constructor in abstract class:

abstract class Figure { 

    double dim1;        
    double dim2; 

    Figure(double a, double b) {         
        dim1 = a;         
        dim2 = b;         
    }

    // area is now an abstract method 

   abstract double area(); 

}


class Rectangle extends Figure { 
    Rectangle(double a, double b) { 
        super(a, b); 
    } 
    // override area for rectangle 
    double area() { 
        System.out.println("Inside Area for Rectangle."); 
        return dim1 * dim2; 
    } 
}

class Triangle extends Figure { 
    Triangle(double a, double b) { 
        super(a, b); 
    } 
    // override area for right triangle 
    double area() { 
        System.out.println("Inside Area for Triangle."); 
        return dim1 * dim2 / 2; 
    } 
}

class AbstractAreas { 
    public static void main(String args[]) { 
        // Figure f = new Figure(10, 10); // illegal now 
        Rectangle r = new Rectangle(9, 5); 
        Triangle t = new Triangle(10, 8); 
        Figure figref; // this is OK, no object is created 
        figref = r; 
        System.out.println("Area is " + figref.area()); 
        figref = t; 
        System.out.println("Area is " + figref.area()); 
    } 
}

So I think you got the answer.

Send File Attachment from Form Using phpMailer and PHP

Try:

if (isset($_FILES['uploaded_file']) &&
    $_FILES['uploaded_file']['error'] == UPLOAD_ERR_OK) {
    $mail->AddAttachment($_FILES['uploaded_file']['tmp_name'],
                         $_FILES['uploaded_file']['name']);
}

Basic example can also be found here.

The function definition for AddAttachment is:

public function AddAttachment($path,
                              $name = '',
                              $encoding = 'base64',
                              $type = 'application/octet-stream')

How to resize datagridview control when form resizes

In your form constructor you could create an event handler like this:

this.SizeChanged(frm_sizeChanged);

Then create an event handler that resizes the grid appropriately, example:

private void frm_sizeChanged(object sender, EventArgs e)
{
     dataGrid.Size = new Size(100, 200);
}

Replacing those numbers with whatever you'd like.

C# Return Different Types?

If there is no common base-type or interface, then public object GetAnything() {...} - but it would usually be preferable to have some kind of abstraction such as a common interface. For example if Hello, Computer and Radio all implemented IFoo, then it could return an IFoo.

Converting char[] to byte[]

Convert without creating String object:

import java.nio.CharBuffer;
import java.nio.ByteBuffer;
import java.util.Arrays;

byte[] toBytes(char[] chars) {
  CharBuffer charBuffer = CharBuffer.wrap(chars);
  ByteBuffer byteBuffer = Charset.forName("UTF-8").encode(charBuffer);
  byte[] bytes = Arrays.copyOfRange(byteBuffer.array(),
            byteBuffer.position(), byteBuffer.limit());
  Arrays.fill(byteBuffer.array(), (byte) 0); // clear sensitive data
  return bytes;
}

Usage:

char[] chars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
byte[] bytes = toBytes(chars);
/* do something with chars/bytes */
Arrays.fill(chars, '\u0000'); // clear sensitive data
Arrays.fill(bytes, (byte) 0); // clear sensitive data

Solution is inspired from Swing recommendation to store passwords in char[]. (See Why is char[] preferred over String for passwords?)

Remember not to write sensitive data to logs and ensure that JVM won't hold any references to it.


The code above is correct but not effective. If you don't need performance but want security you can use it. If security also not a goal then do simply String.getBytes. Code above is not effective if you look down of implementation of encode in JDK. Besides you need to copy arrays and create buffers. Another way to convert is inline all code behind encode (example for UTF-8):

val xs: Array[Char] = "A ß € ?  ".toArray
val len = xs.length
val ys: Array[Byte] = new Array(3 * len) // worst case
var i = 0; var j = 0 // i for chars; j for bytes
while (i < len) { // fill ys with bytes
  val c = xs(i)
  if (c < 0x80) {
    ys(j) = c.toByte
    i = i + 1
    j = j + 1
  } else if (c < 0x800) {
    ys(j) = (0xc0 | (c >> 6)).toByte
    ys(j + 1) = (0x80 | (c & 0x3f)).toByte
    i = i + 1
    j = j + 2
  } else if (Character.isHighSurrogate(c)) {
    if (len - i < 2) throw new Exception("overflow")
    val d = xs(i + 1)
    val uc: Int = 
      if (Character.isLowSurrogate(d)) {
        Character.toCodePoint(c, d)
      } else {
        throw new Exception("malformed")
      }
    ys(j) = (0xf0 | ((uc >> 18))).toByte
    ys(j + 1) = (0x80 | ((uc >> 12) & 0x3f)).toByte
    ys(j + 2) = (0x80 | ((uc >>  6) & 0x3f)).toByte
    ys(j + 3) = (0x80 | (uc & 0x3f)).toByte
    i = i + 2 // 2 chars
    j = j + 4
  } else if (Character.isLowSurrogate(c)) {
    throw new Exception("malformed")
  } else {
    ys(j) = (0xe0 | (c >> 12)).toByte
    ys(j + 1) = (0x80 | ((c >> 6) & 0x3f)).toByte
    ys(j + 2) = (0x80 | (c & 0x3f)).toByte
    i = i + 1
    j = j + 3
  }
}
// check
println(new String(ys, 0, j, "UTF-8"))

Excuse me for using Scala language. If you have problems with converting this code to Java I can rewrite it. What about performance always check on real data (with JMH for example). This code looks very similar to what you can see in JDK[2] and Protobuf[3].

converting CSV/XLS to JSON?

You can try this tool I made:

Mr. Data Converter

It converts to JSON, XML and others.

It's all client side, too, so your data never leaves your computer.

SQL Server convert select a column and convert it to a string

+------+----------------------+
| type |        names         |
+------+----------------------+
| cat  | Felon                |
| cat  | Purz                 |
| dog  | Fido                 |
| dog  | Beethoven            |
| dog  | Buddy                |
| bird | Tweety               |
+------+----------------------+

select group_concat(name) from Pets
group by type

Here you can easily get the answer in single SQL and by using group by in your SQL you can separate the result based on that column value. Also you can use your own custom separator for splitting values

Result:

+------+----------------------+
| type |        names         |
+------+----------------------+
| cat  | Felon,Purz           |
| dog  | Fido,Beethoven,Buddy |
| bird | Tweety               |
+------+----------------------+

Getting time span between two times in C#?

Another way ( longer ) In VB.net [ Say 2300 Start and 0700 Finish next day ]

If tsStart > tsFinish Then

                            ' Take Hours difference and adjust accordingly
                            tsDifference = New TimeSpan((24 - tsStart.Hours) + tsFinish.Hours, 0, 0)

                            ' Add Minutes to Difference
                            tsDifference = tsDifference.Add(New TimeSpan(0, Math.Abs(tsStart.Minutes - tsFinish.Minutes), 0))


                            ' Add Seonds to Difference
                            tsDifference = tsDifference.Add(New TimeSpan(0, 0, Math.Abs(tsStart.Seconds - tsFinish.Seconds)))

How can I replace newlines using PowerShell?

A CRLF is two characters, of course, the CR and the LF. However, `n consists of both. For example:

PS C:\> $x = "Hello
>> World"

PS C:\> $x
Hello
World
PS C:\> $x.contains("`n")
True
PS C:\> $x.contains("`r")
False
PS C:\> $x.replace("o`nW","o There`nThe W")
Hello There
The World
PS C:\>

I think you're running into problems with the `r. I was able to remove the `r from your example, use only `n, and it worked. Of course, I don't know exactly how you generated the original string so I don't know what's in there.

Insert Update trigger how to determine if insert or update

Declare @Type varchar(50)='';
IF EXISTS (SELECT * FROM inserted) and  EXISTS (SELECT * FROM deleted)
BEGIN
    SELECT @Type = 'UPDATE'
END
ELSE IF EXISTS(SELECT * FROM inserted)
BEGIN
    SELECT @Type = 'INSERT'
END
ElSE IF EXISTS(SELECT * FROM deleted)
BEGIN
    SELECT @Type = 'DELETE'
END

OpenSSL: PEM routines:PEM_read_bio:no start line:pem_lib.c:703:Expecting: TRUSTED CERTIFICATE

  1. Since you are on Windows, make sure that your certificate in Windows "compatible", most importantly that it doesn't have ^M in the end of each line

    If you open it it will look like this:

    -----BEGIN CERTIFICATE-----^M
    MIIDITCCAoqgAwIBAgIQL9+89q6RUm0PmqPfQDQ+mjANBgkqhkiG9w0BAQUFADBM^M
    

    To solve "this" open it with Write or Notepad++ and have it convert it to Windows "style"

  2. Try to run openssl x509 -text -inform DER -in server_cert.pem and see what the output is, it is unlikely that a private/secret key would be untrusted, trust only is needed if you exported the key from a keystore, did you?

MySQL: Error dropping database (errno 13; errno 17; errno 39)

In my case an additional file not belonging to the database was inside the database folder. Mysql found the folder not empty after dropping all tables which triggered the error. I remove the file and the drop database worked fine.

Getting an Embedded YouTube Video to Auto Play and Loop

Playlist hack didn't work for me either. Working workaround for September 2018 (bonus: set width and height by CSS for #yt-wrap instead of hard-coding it in JS):

<div id="yt-wrap">
    <!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
    <div id="ytplayer"></div>
</div>

<script>
  // 2. This code loads the IFrame Player API code asynchronously.
  var tag = document.createElement('script');
  tag.src = "https://www.youtube.com/player_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

  // 3. This function creates an <iframe> (and YouTube player)
  //    after the API code downloads.
  var player;
  function onYouTubePlayerAPIReady() {
    player = new YT.Player('ytplayer', {
      width: '100%',
      height: '100%',
      videoId: 'VIDEO_ID',
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }
    });
  }

  // 4. The API will call this function when the video player is ready.
  function onPlayerReady(event) {
    event.target.playVideo();
    player.mute(); // comment out if you don't want the auto played video muted
  }

  // 5. The API calls this function when the player's state changes.
  //    The function indicates that when playing a video (state=1),
  //    the player should play for six seconds and then stop.
  function onPlayerStateChange(event) {
    if (event.data == YT.PlayerState.ENDED) {
      player.seekTo(0);
      player.playVideo();
    }
  }
  function stopVideo() {
    player.stopVideo();
  }
</script>

Property 'catch' does not exist on type 'Observable<any>'

With RxJS 5.5+, the catch operator is now deprecated. You should now use the catchError operator in conjunction with pipe.

RxJS v5.5.2 is the default dependency version for Angular 5.

For each RxJS Operator you import, including catchError you should now import from 'rxjs/operators' and use the pipe operator.

Example of catching error for an Http request Observable

import { Observable } from 'rxjs';
import { catchError } from 'rxjs/operators';
...

export class ExampleClass {
  constructor(private http: HttpClient) {
    this.http.request(method, url, options).pipe(
      catchError((err: HttpErrorResponse) => {
        ...
      }
    )
  }
  ...
}

Notice here that catch is replaced with catchError and the pipe operator is used to compose the operators in similar manner to what you're used to with dot-chaining.


See the rxjs documentation on pipable (previously known as lettable) operators for more info.

Java keytool easy way to add server cert from url/port

There were a few ways I found to do this:

    java InstallCert [host]:[port] 
    keytool -exportcert -keystore jssecacerts -storepass changeit -file output.cert
    keytool -importcert -keystore [DESTINATION_KEYSTORE] -file output.cert

Error to run Android Studio

For me, running Fedora 22 with Gnome 16.2, this solution helped me. In short, you should install the java-1.8.0-openjdk-devel, the development files of the JDK.

Open the Terminal and search for the latest version of the JDK development package:

$ dnf search jdk-devel
Last metadata expiration check performed 12:44:51 ago on Mon Aug  3 22:20:24 2015.
============================ N/S Matched: jdk-devel ============================
java-1.8.0-openjdk-devel.x86_64 : OpenJDK Development Environment
java-1.8.0-openjdk-devel-debug.x86_64 : OpenJDK Development Environment with
                                      : full debug on
$ sudo dnf install java-1.8.0-openjdk-devel

Insert node at a certain position in a linked list C++

Just have something like this where you traverse till the given position and then insert:

void addNodeAtPos(int data, int pos)
{
  Node* prev = new Node();
  Node* curr = new Node();
  Node* newNode = new Node();
  newNode->data = data;

  int tempPos = 0;   // Traverses through the list

  curr = head;      // Initialize current to head;
  if(head != NULL)
  {
    while(curr->next != NULL && tempPos != pos)
    {
        prev = curr;
        curr = curr->next;
        tempPos++;
    }
    if(pos==0)
    {
       cout << "Adding at Head! " << endl;
       // Call function to addNode from head;
    }
    else if(curr->next == NULL && pos == tempPos+1)
    {
      cout << "Adding at Tail! " << endl;
      // Call function to addNode at tail;
    }
    else if(pos > tempPos+1)
      cout << " Position is out of bounds " << endl;
     //Position not valid

    else
    {
        prev->next = newNode;
        newNode->next = curr;
        cout << "Node added at position: " << pos << endl;
    }
 }
 else
 {
    head = newNode;
    newNode->next=NULL;
    cout << "Added at head as list is empty! " << endl;
 }
}

scrollable div inside container

Adding position: relative to the parent, and a max-height:100%; on div2 works.

_x000D_
_x000D_
<body>_x000D_
  <div id="div1" style="height: 500px;position:relative;">_x000D_
    <div id="div2" style="max-height:100%;overflow:auto;border:1px solid red;">_x000D_
      <div id="div3" style="height:1500px;border:5px solid yellow;">hello</div>_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
</body>?
_x000D_
_x000D_
_x000D_


Update: The following shows the "updated" example and answer. http://jsfiddle.net/Wcgvt/181/

The secret there is to use box-sizing: border-box, and some padding to make the second div height 100%, but move it's content down 50px. Then wrap the content in a div with overflow: auto to contain the scrollbar. Pay attention to z-indexes to keep all the text selectable - hope this helps, several years later.

Types in Objective-C on iOS

Update for the new 64bit arch

Ranges:
CHAR_MIN:   -128
CHAR_MAX:   127
SHRT_MIN:   -32768
SHRT_MAX:   32767
INT_MIN:    -2147483648
INT_MAX:    2147483647
LONG_MIN:   -9223372036854775808
LONG_MAX:   9223372036854775807
ULONG_MAX:  18446744073709551615
LLONG_MIN:  -9223372036854775808
LLONG_MAX:  9223372036854775807
ULLONG_MAX: 18446744073709551615

How to PUT a json object with an array using curl

The only thing that helped is to use a file of JSON instead of json body text. Based on How to send file contents as body entity using cURL

SQL Left Join first match only

Try this

 SELECT *
 FROM people P 
 where P.IDNo in (SELECT DISTINCT IDNo
              FROM people)

JPG vs. JPEG image formats

There is no difference between them, it just a file extension for image/jpeg mime type. In fact file extension for image/jpeg is .jpg, .jpeg, .jpe .jif, .jfif, .jfi

sed: print only matching group

The cut command is designed for this exact situation. It will "cut" on any delimiter and then you can specify which chunks should be output.

For instance: echo "foo bar <foo> bla 1 2 3.4" | cut -d " " -f 6-7

Will result in output of: 2 3.4

-d sets the delimiter

-f selects the range of 'fields' to output, in this case, it's the 6th through 7th chunks of the original string. You can also specify the range as a list, such as 6,7.

force css grid container to fill full screen of device

If you want the .wrapper to be fullscreen, just add the following in the wrapper class:

position: absolute; width: 100%; height: 100%;

You can also add top: 0 and left:0

How do I read input character-by-character in Java?

This will print 1 character per line from the file.

    try {

        FileInputStream inputStream = new FileInputStream(theFile);
        while (inputStream.available() > 0) {
            inputData = inputStream.read();
            System.out.println((char) inputData);

        }
        inputStream.close();
    } catch (IOException ioe) {
        System.out.println("Trouble reading from the file: " + ioe.getMessage());
    }

How to update the constant height constraint of a UIView programmatically?

If the above method does not work then make sure you update it in Dispatch.main.async{} block. You do not need to call layoutIfNeeded() method then.

sklearn plot confusion matrix with labels

    from sklearn.metrics import confusion_matrix
    import seaborn as sns
    import matplotlib.pyplot as plt
    model.fit(train_x, train_y,validation_split = 0.1, epochs=50, batch_size=4)
    y_pred=model.predict(test_x,batch_size=15)
    cm =confusion_matrix(test_y.argmax(axis=1), y_pred.argmax(axis=1))  
    index = ['neutral','happy','sad']  
    columns = ['neutral','happy','sad']  
    cm_df = pd.DataFrame(cm,columns,index)                      
    plt.figure(figsize=(10,6))  
    sns.heatmap(cm_df, annot=True)

Confusion matrix

Stack smashing detected

You could try to debug the problem using valgrind:

The Valgrind distribution currently includes six production-quality tools: a memory error detector, two thread error detectors, a cache and branch-prediction profiler, a call-graph generating cache profiler, and a heap profiler. It also includes two experimental tools: a heap/stack/global array overrun detector, and a SimPoint basic block vector generator. It runs on the following platforms: X86/Linux, AMD64/Linux, PPC32/Linux, PPC64/Linux, and X86/Darwin (Mac OS X).

Spring schemaLocation fails when there is no internet connection

Remove jars you added recently in the web-inf ->lib. for example jstl jars.

No String-argument constructor/factory method to deserialize from String value ('')

This exception says that you are trying to deserialize the object "Address" from string "\"\"" instead of an object description like "{…}". The deserializer can't find a constructor of Address with String argument. You have to replace "" by {} to avoid this error.

Java better way to delete file if exists

There's also the Java 7 solution, using the new(ish) Path abstraction:

Path fileToDeletePath = Paths.get("fileToDelete_jdk7.txt");
Files.delete(fileToDeletePath);

Hope this helps.

Best way to compare dates in Android

You could try this

Calendar today = Calendar.getInstance (); 
today.add(Calendar.DAY_OF_YEAR, 0); 
today.set(Calendar.HOUR_OF_DAY, hrs); 
today.set(Calendar.MINUTE, mins ); 
today.set(Calendar.SECOND, 0); 

and you could use today.getTime() to retrieve value and compare.

Bootstrap Modal sitting behind backdrop

i encountred this problem, and after investigating my css, the main container (direct child of the body) had:

position: relative
z-index: 1

the backdrop worked well after i removed those two properties. You may also encounter this problem if the main wraper have a position: fixed

Datanode process not running in Hadoop

Run Below Commands in Line:-

  1. stop-all.sh (Run Stop All to Stop all the hadoop process)
  2. rm -r /usr/local/hadoop/tmp/ (Your Hadoop tmp directory which you configured in hadoop/conf/core-site.xml)
  3. sudo mkdir /usr/local/hadoop/tmp (Make the same directory again)
  4. hadoop namenode -format (Format your namenode)
  5. start-all.sh (Run Start All to start all the hadoop process)
  6. JPS (It will show the running processes)

JPanel vs JFrame in Java

You should not extend the JFrame class unnecessarily (only if you are adding extra functionality to the JFrame class)

JFrame:

JFrame extends Component and Container.

It is a top level container used to represent the minimum requirements for a window. This includes Borders, resizability (is the JFrame resizeable?), title bar, controls (minimize/maximize allowed?), and event handlers for various Events like windowClose, windowOpened etc.

JPanel:

JPanel extends Component, Container and JComponent

It is a generic class used to group other Components together.

  • It is useful when working with LayoutManagers e.g. GridLayout f.i adding components to different JPanels which will then be added to the JFrame to create the gui. It will be more manageable in terms of Layout and re-usability.

  • It is also useful for when painting/drawing in Swing, you would override paintComponent(..) and of course have the full joys of double buffering.

A Swing GUI cannot exist without a top level container like (JWindow, Window, JFrame Frame or Applet), while it may exist without JPanels.

How to run multiple Python versions on Windows

Using a batch file to switch, easy and efficient on windows 7. I use this:

In the environment variable dialog (C:\Windows\System32\SystemPropertiesAdvanced.exe),

In the section user variables

  1. added %pathpython% to the path environment variable

  2. removed any references to python pathes

In the section system variables

  1. removed any references to python pathes

I created batch files for every python installation (exmple for 3.4 x64

Name = SetPathPython34x64 !!! ToExecuteAsAdmin.bat ;-) just to remember.

Content of the file =

     Set PathPython=C:\Python36AMD64\Scripts\;C:\Python36AMD64\;C:\Tcl\bin

     setx PathPython %PathPython%

To switch between versions, I execute the batch file in admin mode.

!!!!! The changes are effective for the SUBSEQUENT command prompt windows OPENED. !!!

So I have exact control on it.

What is the difference between Visual Studio Express 2013 for Windows and Visual Studio Express 2013 for Windows Desktop?

Visual Studio for Windows Apps is meant to be used to build Windows Store Apps using HTML & Javascript or WinRT and XAML. These can also run on the Windows tablet that run Windows RT.

Visual Studio for Windows Desktop is meant to build applications using Windows Forms or Windows Presentation Foundation, these can run on Windows 8.1 on a normal desktop or on a tablet device like the Surface Pro in desktop mode (like a classic windows application).

WHERE clause on SQL Server "Text" data type

If you can't change the datatype on the table itself to use varchar(max), then change your query to this:

SELECT *
FROM   [Village]
WHERE  CONVERT(VARCHAR(MAX), [CastleType]) = 'foo'

Javascript receipt printing using POS Printer

If you are talking about a browser based POS app then it basically can't be done out of the box. There are a number of alternatives.

  1. Use an applet like Scott Selby says
  2. Print from the server. If this is a cloud server, ie not connectable to the receipt printer then what you can do is
    • From the server generate it as a pdf which can be made to popup a print dialog in the browser
    • Use something like Google Cloud Print which will allow connecting printers to a cloud service

How to kill a nodejs process in Linux?

if you want to kill a specific node process , you can go to command line route and type:

ps aux | grep node

to get a list of all node process ids. now you can get your process id(pid), then do:

kill -9 PID

and if you want to kill all node processes then do:

killall -9 node

-9 switch is like end task on windows. it will force the process to end. you can do:

kill -l

to see all switches of kill command and their comments.

Continue For loop

I sometimes do a double do loop:

Do

    Do

        If I_Don't_Want_to_Finish_This_Loop Then Exit Do

        Exit Do

    Loop

Loop Until Done

This avoids having "goto spaghetti"

SharePoint : How can I programmatically add items to a custom list instance

To put it simple you will need to follow the step.

  1. You need to reference the Microsoft.SharePoint.dll to the application.
  2. Assuming the List Name is Test and it has only one Field "Title" here is the code.

            using (SPSite oSite=new SPSite("http://mysharepoint"))
        {
            using (SPWeb oWeb=oSite.RootWeb)
            {
                SPList oList = oWeb.Lists["Test"];
                SPListItem oSPListItem = oList.Items.Add();
                oSPListItem["Title"] = "Hello SharePoint";
                oSPListItem.Update();
            }
    
        }
    
  3. Note that you need to run this application in the Same server where the SharePoint is installed.

  4. You dont need to create a Custom Class for Custom Content Type

How to increase memory limit for PHP over 2GB?

For unlimited memory limit set -1 in memory_limit variable:

ini_set('memory_limit', '-1');

vector vs. list in STL

One special capability of std::list is splicing (linking or moving part of or a whole list into a different list).

Or perhaps if your contents are very expensive to copy. In such a case it might be cheaper, for example, to sort the collection with a list.

Also note that if the collection is small (and the contents are not particularly expensive to copy), a vector might still outperform a list, even if you insert and erase anywhere. A list allocates each node individually, and that might be much more costly than moving a few simple objects around.

I don't think there are very hard rules. It depends on what you mostly want to do with the container, as well as on how large you expect the container to be and the contained type. A vector generally trumps a list, because it allocates its contents as a single contiguous block (it is basically a dynamically allocated array, and in most circumstances an array is the most efficient way to hold a bunch of things).

How can I count the number of elements of a given value in a matrix?

Use nnz instead of sum. No need for the double call to collapse matrices to vectors and it is likely faster than sum.

nnz(your_matrix == 5)

Doc

Trying to mock datetime.date.today(), but not working

I guess I came a little late for this but I think the main problem here is that you're patching datetime.date.today directly and, according to the documentation, this is wrong.

You should patch the reference imported in the file where the tested function is, for example.

Let's say you have a functions.py file where you have the following:

import datetime

def get_today():
    return datetime.date.today()

then, in your test, you should have something like this

import datetime
import unittest

from functions import get_today
from mock import patch, Mock

class GetTodayTest(unittest.TestCase):

    @patch('functions.datetime')
    def test_get_today(self, datetime_mock):
        datetime_mock.date.today = Mock(return_value=datetime.strptime('Jun 1 2005', '%b %d %Y'))
        value = get_today()
        # then assert your thing...

Hope this helps a little bit.

Calling a JSON API with Node.js

Unirest library simplifies this a lot. If you want to use it, you have to install unirest npm package. Then your code could look like this:

unirest.get("http://graph.facebook.com/517267866/?fields=picture")
  .send()
  .end(response=> {
    if (response.ok) {
      console.log("Got a response: ", response.body.picture)
    } else {
      console.log("Got an error: ", response.error)
    }
  })

csv.Error: iterator should return strings, not bytes

In Python3, csv.reader expects, that passed iterable returns strings, not bytes. Here is one more solution to this problem, that uses codecs module:

import csv
import codecs
ifile  = open('sample.csv', "rb")
read = csv.reader(codecs.iterdecode(ifile, 'utf-8'))
for row in read :
    print (row) 

Vue v-on:click does not work on component

As mentioned by Chris Fritz (Vue.js Core Team Emeriti) in VueCONF US 2019

if we had Kia enter .native and then the root element of the base input changed from an input to a label suddenly this component is broken and it's not obvious and in fact, you might not even catch it right away unless you have a really good test. Instead by avoiding the use of the .native modifier which I currently consider an anti-pattern will be removed in Vue 3 you'll be able to explicitly define that the parent might care about which element listeners are added to...

With Vue 2

Using $listeners:

So, if you are using Vue 2 a better option to resolve this issue would be to use a fully transparent wrapper logic. For this Vue provides a $listeners property containing an object of listeners being used on the component. For example:

{
  focus: function (event) { /* ... */ }
  input: function (value) { /* ... */ },
}

and then we just need to add v-on="$listeners" to the test component like:

Test.vue (child component)

<template>
  <div v-on="$listeners">
    click here
  </div>
</template>

Now the <test> component is a fully transparent wrapper, meaning it can be used exactly like a normal <div> element: all the listeners will work, without the .native modifier.

Demo:

_x000D_
_x000D_
Vue.component('test', {_x000D_
  template: `_x000D_
    <div class="child" v-on="$listeners">_x000D_
      Click here_x000D_
    </div>`_x000D_
})_x000D_
_x000D_
new Vue({_x000D_
  el: "#myApp",_x000D_
  data: {},_x000D_
  methods: {_x000D_
    testFunction: function(event) {_x000D_
      console.log('test clicked')_x000D_
    }_x000D_
  }_x000D_
})
_x000D_
div.child{border:5px dotted orange; padding:20px;}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>_x000D_
<div id="myApp">_x000D_
  <test @click="testFunction"></test>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Using $emit method:

We can also use $emit method for this purpose, which helps us to listen to child components events in parent component. For this, we first need to emit a custom event from child component like:

Test.vue (child component)

<test @click="$emit('my-event')"></test>

Important: Always use kebab-case for event names. For more information and demo regading this point please check out this answer: VueJS passing computed value from component to parent.

Now, we just need to listen to this emitted custom event in parent component like:

App.vue

<test @my-event="testFunction"></test>

So, basically instead of v-on:click or the shorthand @click we will simply use v-on:my-event or just @my-event.

Demo:

_x000D_
_x000D_
Vue.component('test', {_x000D_
  template: `_x000D_
    <div class="child" @click="$emit('my-event')">_x000D_
      Click here_x000D_
    </div>`_x000D_
})_x000D_
_x000D_
new Vue({_x000D_
  el: "#myApp",_x000D_
  data: {},_x000D_
  methods: {_x000D_
    testFunction: function(event) {_x000D_
      console.log('test clicked')_x000D_
    }_x000D_
  }_x000D_
})
_x000D_
div.child{border:5px dotted orange; padding:20px;}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>_x000D_
<div id="myApp">_x000D_
  <test @my-event="testFunction"></test>_x000D_
</div>
_x000D_
_x000D_
_x000D_


With Vue 3

Using v-bind="$attrs":

Vue 3 is going to make our life much easier in many ways. One of the examples for it is that it will help us to create a simpler transparent wrapper with very less config by just using v-bind="$attrs". By using this on child components not only our listener will work directly from the parent but also any other attribute will also work just like it a normal <div> only.

So, with respect to this question, we will not need to update anything in Vue 3 and your code will still work fine as <div> is the root element here and it will automatically listen to all child events.

Demo #1:

_x000D_
_x000D_
const { createApp } = Vue;_x000D_
_x000D_
const Test = {_x000D_
  template: `_x000D_
    <div class="child">_x000D_
      Click here_x000D_
    </div>`_x000D_
};_x000D_
_x000D_
const App = {_x000D_
  components: { Test },_x000D_
  setup() {_x000D_
    const testFunction = event => {_x000D_
      console.log("test clicked");_x000D_
    };_x000D_
    return { testFunction };_x000D_
  }_x000D_
};_x000D_
_x000D_
createApp(App).mount("#myApp");
_x000D_
div.child{border:5px dotted orange; padding:20px;}
_x000D_
<script src="//unpkg.com/vue@next"></script>_x000D_
<div id="myApp">_x000D_
  <test v-on:click="testFunction"></test>_x000D_
</div>
_x000D_
_x000D_
_x000D_

But for complex components with nested elements where we need to apply attributes and events to main <input /> instead of the parent label we can simply use v-bind="$attrs"

Demo #2:

_x000D_
_x000D_
const { createApp } = Vue;_x000D_
_x000D_
const BaseInput = {_x000D_
  props: ['label', 'value'],_x000D_
  template: `_x000D_
    <label>_x000D_
      {{ label }}_x000D_
      <input v-bind="$attrs">_x000D_
    </label>`_x000D_
};_x000D_
_x000D_
const App = {_x000D_
  components: { BaseInput },_x000D_
  setup() {_x000D_
    const search = event => {_x000D_
      console.clear();_x000D_
      console.log("Searching...", event.target.value);_x000D_
    };_x000D_
    return { search };_x000D_
  }_x000D_
};_x000D_
_x000D_
createApp(App).mount("#myApp");
_x000D_
input{padding:8px;}
_x000D_
<script src="//unpkg.com/vue@next"></script>_x000D_
<div id="myApp">_x000D_
  <base-input _x000D_
    label="Search: "_x000D_
    placeholder="Search"_x000D_
    @keyup="search">_x000D_
  </base-input><br/>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Permission denied when launch python script via bash

Okay, so first of all check if you are in the correct directory where your python script is located.
On the net, they say to run the command :

python3 your_file_name.py

But it doesn't work.
What worked for me however was:

python -u my_file_name.py

Authentication plugin 'caching_sha2_password' cannot be loaded

Ok, wasted a lot of time on this so here is a summary as of 19 March 2019

If you are specifically trying to use a Docker image with MySql 8+, and then use SequelPro to access your database(s) running on that docker container, you are out of luck.

See the sequelpro issue 2699

My setup is sequelpro 1.1.2 using docker desktop 2.0.3.0 (mac - mojave), and tried using mysql:latest (v8.0.15).

As others have reported, using mysql 5.7 works with nothing required:

docker run -p 3306:3306 --name mysql1 -e MYSQL_ROOT_PASSWORD=secret -d mysql:5.7

Of course, it is possible to use MySql 8+ on docker, and in that situation (if needed), other answers provided here for caching_sha2_password type issues do work. But sequelpro is a NO GO with MySql 8+

Finally, I abandoned sequelpro (a trusted friend from back in 2013-2014) and instead installed DBeaver. Everything worked out of the box. For docker, I used:

docker run -p 3306:3306 --name mysql1 -e MYSQL_ROOT_PASSWORD=secret -d mysql:latest --default-authentication-plugin=mysql_native_password

You can quickly peek at the mysql databases using:

docker exec -it mysql1 bash

mysql -u root -p

show databases;

Join two data frames, select all columns from one and some columns from the other

I got an error: 'a not found' using the suggested code:

from pyspark.sql.functions import col df1.alias('a').join(df2.alias('b'),col('b.id') == col('a.id')).select([col('a.'+xx) for xx in a.columns] + [col('b.other1'),col('b.other2')])

I changed a.columns to df1.columns and it worked out.

How can I decode HTML characters in C#?

As @CQ says, you need to use HttpUtility.HtmlDecode, but it's not available in a non-ASP .NET project by default.

For a non-ASP .NET application, you need to add a reference to System.Web.dll. Right-click your project in Solution Explorer, select "Add Reference", then browse the list for System.Web.dll.

Now that the reference is added, you should be able to access the method using the fully-qualified name System.Web.HttpUtility.HtmlDecode or insert a using statement for System.Web to make things easier.

How do the major C# DI/IoC frameworks compare?

Just read this great .Net DI container comparison blog by Philip Mat.

He does some thorough performance comparison tests on;

He recommends Autofac as it is small, fast, and easy to use ... I agree. It appears that Unity and Ninject are the slowest in his tests.

Overflow Scroll css is not working in the div

in my case, only height: 100vh fix the problem with the expected behavior

Calculate cosine similarity given 2 sentence strings

Thanks @vpekar for your implementation. It helped a lot. I just found that it misses the tf-idf weight while calculating the cosine similarity. The Counter(word) returns a dictionary which has the list of words along with their occurence.

cos(q, d) = sim(q, d) = (q · d)/(|q||d|) = (sum(qi, di)/(sqrt(sum(qi2)))*(sqrt(sum(vi2))) where i = 1 to v)

  • qi is the tf-idf weight of term i in the query.
  • di is the tf-idf
  • weight of term i in the document. |q| and |d| are the lengths of q and d.
  • This is the cosine similarity of q and d . . . . . . or, equivalently, the cosine of the angle between q and d.

Please feel free to view my code here. But first you will have to download the anaconda package. It will automatically set you python path in Windows. Add this python interpreter in Eclipse.

HTML5 textarea placeholder not appearing

Delete all spaces and line breaks between <textarea> opening and closing </textarea> tags.

<textarea placeholder="YOUR TEXT"></textarea>  ///Correct one

<textarea placeholder="YOUR TEXT"> </textarea>  ///Bad one It's treats as a value so browser won't display the Placeholder value

<textarea placeholder="YOUR TEXT"> 
</textarea>  ///Bad one 

HTTP response code for POST when resource already exists

My feeling is 409 Conflict is the most appropriate, however, seldom seen in the wild of course:

The request could not be completed due to a conflict with the current state of the resource. This code is only allowed in situations where it is expected that the user might be able to resolve the conflict and resubmit the request. The response body SHOULD include enough information for the user to recognize the source of the conflict. Ideally, the response entity would include enough information for the user or user agent to fix the problem; however, that might not be possible and is not required.

Conflicts are most likely to occur in response to a PUT request. For example, if versioning were being used and the entity being PUT included changes to a resource which conflict with those made by an earlier (third-party) request, the server might use the 409 response to indicate that it can't complete the request. In this case, the response entity would likely contain a list of the differences between the two versions in a format defined by the response Content-Type.

Is there a better way to compare dictionary values

If the dicts have identical sets of keys and you need all those prints for any value difference, there isn't much you can do; maybe something like:

diffkeys = [k for k in dict1 if dict1[k] != dict2[k]]
for k in diffkeys:
  print k, ':', dict1[k], '->', dict2[k]

pretty much equivalent to what you have, but you might get nicer presentation for example by sorting diffkeys before you loop on it.

Setting up Eclipse with JRE Path

You are most probably missing PATH entries in your windows. Follow this instruction : How do I set or change the PATH system variable?

Javascript swap array elements

what about Destructuring_assignment

var arr = [1, 2, 3, 4]
[arr[index1], arr[index2]] = [arr[index2], arr[index1]]

which can also be extended to

[src order elements] => [dest order elements]

Set value of hidden input with jquery

This worked for me:

$('input[name="sort_order"]').attr('value','XXX');

Adding double quote delimiters into csv file

This is actually pretty easy in Excel (or any spreadsheet application).

You'll want to use the =CONCATENATE() function as shown in the formula bar in the following screenshot:

Step 1 involves adding quotes in column B,

Step 2 involves specifying the function and then copying it down column C (by now your spreadsheet should look like the screenshot),

enter image description here

Step 3 (if you need the text outside of the formula) involves copying column C, right-clicking on column D, choosing Paste Special >> Paste Values. Column D should then contain the text that was calculated in column C.