Programs & Examples On #Indefero

Unable to call the built in mb_internal_encoding method?

For OpenSUse (zypper package manager):

zypper install php5-mbstring

and:

zyper install php7-mbstring

In the other hand, you can search them through YaST Software manager.

Note that, you must restart apache http server:

systemctl restart apache2.service

How to copy Outlook mail message into excel using VBA or Macros

Since you have not mentioned what needs to be copied, I have left that section empty in the code below.

Also you don't need to move the email to the folder first and then run the macro in that folder. You can run the macro on the incoming mail and then move it to the folder at the same time.

This will get you started. I have commented the code so that you will not face any problem understanding it.

First paste the below mentioned code in the outlook module.

Then

  1. Click on Tools~~>Rules and Alerts
  2. Click on "New Rule"
  3. Click on "start from a blank rule"
  4. Select "Check messages When they arrive"
  5. Under conditions, click on "with specific words in the subject"
  6. Click on "specific words" under rules description.
  7. Type the word that you want to check in the dialog box that pops up and click on "add".
  8. Click "Ok" and click next
  9. Select "move it to specified folder" and also select "run a script" in the same box
  10. In the box below, specify the specific folder and also the script (the macro that you have in module) to run.
  11. Click on finish and you are done.

When the new email arrives not only will the email move to the folder that you specify but data from it will be exported to Excel as well.

UNTESTED

Const xlUp As Long = -4162

Sub ExportToExcel(MyMail As MailItem)
    Dim strID As String, olNS As Outlook.Namespace
    Dim olMail As Outlook.MailItem
    Dim strFileName As String

    '~~> Excel Variables
    Dim oXLApp As Object, oXLwb As Object, oXLws As Object
    Dim lRow As Long

    strID = MyMail.EntryID
    Set olNS = Application.GetNamespace("MAPI")
    Set olMail = olNS.GetItemFromID(strID)

    '~~> Establish an EXCEL application object
    On Error Resume Next
    Set oXLApp = GetObject(, "Excel.Application")

    '~~> If not found then create new instance
    If Err.Number <> 0 Then
        Set oXLApp = CreateObject("Excel.Application")
    End If
    Err.Clear
    On Error GoTo 0

    '~~> Show Excel
    oXLApp.Visible = True

    '~~> Open the relevant file
    Set oXLwb = oXLApp.Workbooks.Open("C:\Sample.xls")

    '~~> Set the relevant output sheet. Change as applicable
    Set oXLws = oXLwb.Sheets("Sheet1")

    lRow = oXLws.Range("A" & oXLApp.Rows.Count).End(xlUp).Row + 1

    '~~> Write to outlook
    With oXLws
        '
        '~~> Code here to output data from email to Excel File
        '~~> For example
        '
        .Range("A" & lRow).Value = olMail.Subject
        .Range("B" & lRow).Value = olMail.SenderName
        '
    End With

    '~~> Close and Clean up Excel
    oXLwb.Close (True)
    oXLApp.Quit
    Set oXLws = Nothing
    Set oXLwb = Nothing
    Set oXLApp = Nothing

    Set olMail = Nothing
    Set olNS = Nothing
End Sub

FOLLOWUP

To extract the contents from your email body, you can split it using SPLIT() and then parsing out the relevant information from it. See this example

Dim MyAr() As String

MyAr = Split(olMail.body, vbCrLf)

For i = LBound(MyAr) To UBound(MyAr)
    '~~> This will give you the contents of your email
    '~~> on separate lines
    Debug.Print MyAr(i)
Next i

How can I generate an MD5 hash?

You can generate MD5 hash for a given text by making use of the methods in the MessageDigest class in the java.security package. Below is the complete code snippet,

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.xml.bind.DatatypeConverter;

public class MD5HashGenerator 
{

   public static void main(String args[]) throws NoSuchAlgorithmException
   {
       String stringToHash = "MyJavaCode"; 
       MessageDigest messageDigest = MessageDigest.getInstance("MD5");
       messageDigest.update(stringToHash.getBytes());
       byte[] digiest = messageDigest.digest();
       String hashedOutput = DatatypeConverter.printHexBinary(digiest);
       System.out.println(hashedOutput);
   }
}

The output from the MD5 function is a 128 bit hash represented by 32 hexadecimal numbers.

In case, if you are using a database like MySQL, you can do this in a more simpler way as well. The query Select MD5(“text here”) will return the MD5 hash of the text in the bracket.

ToggleButton in C# WinForms

I ended up overriding the OnPaint and OnBackgroundPaint events and manually drawing the button exactly like I need it. It worked pretty well.

How do you replace double quotes with a blank space in Java?

You can do it like this:

string tmp = "Hello 'World'";
tmp.replace("'", "");

But that will just replace single quotes. To replace double quotes, you must first escape them, like so:

string tmp = "Hello, \"World\"";
tmp.replace("\"", "");

You can replace it with a space, or just leave it empty (I believe you wanted it to be left blank, but your question title implies otherwise.

How to give spacing between buttons using bootstrap

  1. Wrap your buttons in a div with class='col-xs-3' (for example).
  2. Add class="btn-block" to your buttons.

This will provide permanent spacing.

How to change screen resolution of Raspberry Pi

You can change the display resolution graphically (without using Terminal) on Raspbian GNU/Linux 8 (jessie) using following window.

Application Menu > Preferences > Raspberry Pi Configuration > System > Set Resolution.

Click to view screenshots

google-services.json for different productFlavors

I'm using the google-services.json file, created from here: https://developers.google.com/mobile/add?platform=android&cntapi=gcm&cnturl=https:%2F%2Fdevelopers.google.com%2Fcloud-messaging%2Fandroid%2Fclient&cntlbl=Continue%20Adding%20GCM%20Support&%3Fconfigured%3Dtrue

In the JSON-structure there is a JSON-array called clients. If you have multiple flavors, just add the different properties here.

{
  "project_info": {
    "project_id": "PRODJECT-ID",
    "project_number": "PROJECT-NUMBER",
    "name": "APPLICATION-NAME"
  },
  "client": [
    {
      "client_info": {
        "mobilesdk_app_id": "1:PROJECT-NUMBER:android:HASH-FOR-FLAVOR1",
        "client_id": "android:PACKAGE-NAME-1",
        "client_type": 1,
        "android_client_info": {
          "package_name": "PACKAGE-NAME-1"
        }
      },
      "oauth_client": [],
      "api_key": [],
      "services": {
        "analytics_service": {
          "status": 1
        },
        "cloud_messaging_service": {
          "status": 2,
          "apns_config": []
        },
        "appinvite_service": {
          "status": 1,
          "other_platform_oauth_client": []
        },
        "google_signin_service": {
          "status": 1
        },
        "ads_service": {
          "status": 1
        }
      }
    },
    {
      "client_info": {
        "mobilesdk_app_id": "1:PROJECT-NUMBER:android:HASH-FOR-FLAVOR2",
        "client_id": "android:PACKAGE-NAME-2",
        "client_type": 1,
        "android_client_info": {
          "package_name": "PACKAGE-NAME-2"
        }
      },
      "oauth_client": [],
      "api_key": [],
      "services": {
        "analytics_service": {
          "status": 1
        },
        "cloud_messaging_service": {
          "status": 2,
          "apns_config": []
        },
        "appinvite_service": {
          "status": 1,
          "other_platform_oauth_client": []
        },
        "google_signin_service": {
          "status": 1
        },
        "ads_service": {
          "status": 1
        }
      }
    }
  ],
  "client_info": [],
  "ARTIFACT_VERSION": "1"
}

In my project I'm using the same project-id and when I'm adding the second package-name in the above url, google provides me with a file containing multiple clients in the json-data.

Is there Unicode glyph Symbol to represent "Search"

There is U+1F50D LEFT-POINTING MAGNIFYING GLASS () and U+1F50E RIGHT-POINTING MAGNIFYING GLASS ().

You should use (in HTML) &#x1F50D; or &#x1F50E;

They are, however not supported by many fonts (fileformat.info only lists a few fonts as supporting the Codepoint with a proper glyph).

Also note that they are outside of the BMP, so some Unicode-capable software might have problems rendering them, even if they have fonts that support them.

Generally Unicode Glyphs can be searched using a site such as fileformat.info. This searches "only" in the names and properties of the Unicode glyphs, but they usually contain enough metadata to allow for good search results (for this answer I searched for "glass" and browsed the resulting list, for example)

Can I disable a CSS :hover effect via JavaScript?

There isn’t a pure JavaScript generic solution, I’m afraid. JavaScript isn’t able to turn off the CSS :hover state itself.

You could try the following alternative workaround though. If you don’t mind mucking about in your HTML and CSS a little bit, it saves you having to reset every CSS property manually via JavaScript.

HTML

<body class="nojQuery">

CSS

/* Limit the hover styles in your CSS so that they only apply when the nojQuery 
class is present */

body.nojQuery ul#mainFilter a:hover {
    /* CSS-only hover styles go here */
}

JavaScript

// When jQuery kicks in, remove the nojQuery class from the <body> element, thus
// making the CSS hover styles disappear.

$(function(){}
    $('body').removeClass('nojQuery');
)

Converting Numpy Array to OpenCV Array

This is what worked for me...

import cv2
import numpy as np

#Created an image (really an ndarray) with three channels 
new_image = np.ndarray((3, num_rows, num_cols), dtype=int)

#Did manipulations for my project where my array values went way over 255
#Eventually returned numbers to between 0 and 255

#Converted the datatype to np.uint8
new_image = new_image.astype(np.uint8)

#Separated the channels in my new image
new_image_red, new_image_green, new_image_blue = new_image

#Stacked the channels
new_rgb = np.dstack([new_image_red, new_image_green, new_image_blue])

#Displayed the image
cv2.imshow("WindowNameHere", new_rgbrgb)
cv2.waitKey(0)

Returning pointer from a function

Although returning a pointer to a local object is bad practice, it didn't cause the kaboom here. Here's why you got a segfault:

int *fun()
{
    int *point;
    *point=12;  <<<<<<  your program crashed here.
    return point;
}

The local pointer goes out of scope, but the real issue is dereferencing a pointer that was never initialized. What is the value of point? Who knows. If the value did not map to a valid memory location, you will get a SEGFAULT. If by luck it mapped to something valid, then you just corrupted memory by overwriting that place with your assignment to 12.

Since the pointer returned was immediately used, in this case you could get away with returning a local pointer. However, it is bad practice because if that pointer was reused after another function call reused that memory in the stack, the behavior of the program would be undefined.

int *fun()
{
    int point;
    point = 12;
    return (&point);
}

or almost identically:

int *fun()
{
    int point;
    int *point_ptr;
    point_ptr = &point;
    *point_ptr = 12;
    return (point_ptr);
}

Another bad practice but safer method would be to declare the integer value as a static variable, and it would then not be on the stack and would be safe from being used by another function:

int *fun()
{
    static int point;
    int *point_ptr;
    point_ptr = &point;
    *point_ptr = 12;
    return (point_ptr);
}

or

int *fun()
{
    static int point;
    point = 12;
    return (&point);
}

As others have mentioned, the "right" way to do this would be to allocate memory on the heap, via malloc.

Testing socket connection in Python

It seems that you catch not the exception you wanna catch out there :)

if the s is a socket.socket() object, then the right way to call .connect would be:

import socket
s = socket.socket()
address = '127.0.0.1'
port = 80  # port number is a number, not string
try:
    s.connect((address, port)) 
    # originally, it was 
    # except Exception, e: 
    # but this syntax is not supported anymore. 
except Exception as e: 
    print("something's wrong with %s:%d. Exception is %s" % (address, port, e))
finally:
    s.close()

Always try to see what kind of exception is what you're catching in a try-except loop.

You can check what types of exceptions in a socket module represent what kind of errors (timeout, unable to resolve address, etc) and make separate except statement for each one of them - this way you'll be able to react differently for different kind of problems.

TypeError: expected str, bytes or os.PathLike object, not _io.BufferedReader

I think it has to do with your second element in storbinary. You are trying to open file, but it is already a pointer to the file you opened in line file = open(local_path,'rb'). So, try to use ftp.storbinary("STOR " + i, file).

Test if number is odd or even

Check Even Or Odd Number Without Use Condition And Loop Statement.

This work for me..!

_x000D_
_x000D_
$(document).ready(function(){_x000D_
    $("#btn_even_odd").click(function(){_x000D_
        var arr = ['Even','Odd'];_x000D_
        var num_even_odd = $("#num_even_odd").val();_x000D_
        $("#ans_even_odd").html(arr[num_even_odd % 2]);_x000D_
    });_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
    <title>Check Even Or Odd Number Without Use Condition And Loop Statement.</title>_x000D_
</head>_x000D_
<body>_x000D_
<h4>Check Even Or Odd Number Without Use Condition And Loop Statement.</h4>_x000D_
<table>_x000D_
    <tr>_x000D_
        <th>Enter A Number :</th>_x000D_
        <td><input type="text" name="num_even_odd" id="num_even_odd" placeholder="Enter Only Number"></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <th>Your Answer Is :</th>_x000D_
        <td id="ans_even_odd" style="font-size:15px;color:gray;font-weight:900;"></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td><input type="button" name="btn_even_odd" id="btn_even_odd" value="submit"></td>_x000D_
    </tr>_x000D_
</table>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to delete the first row of a dataframe in R?

I am not expert, but this may work as well,

dat <- dat[2:nrow(dat), ]

Reverse the ordering of words in a string

c# solution to reverse words in a sentence

using System;
class helloworld {
    public void ReverseString(String[] words) {
        int end = words.Length-1;
        for (int start = 0; start < end; start++) {
            String tempc;
            if (start < end ) {
                tempc = words[start];
                words[start] = words[end];
                words[end--] = tempc;
            }
        }
        foreach (String s1 in words) {
            Console.Write("{0} ",s1);
        }
    }
}
class reverse {
    static void Main() {
        string s= "beauty lies in the heart of the peaople";
        String[] sent_char=s.Split(' ');
        helloworld h1 = new helloworld();
        h1.ReverseString(sent_char);
    }
}

output: peaople the of heart the in lies beauty Press any key to continue . . .

Is there a C++ decompiler?

Depending on how large and how well-written the original code was, it might be worth starting again in your favourite language (which might still be C++) and learning from any mistakes made in the last version. Didn't someone once say about writing one to throw away?

n.b. Clearly if this is a huge product, then it may not be worth the time.

Vue v-on:click does not work on component

It's the @Neps' answer but with details.


Note: @Saurabh's answer is more suitable if you don't want to modify your component or don't have access to it.


Why can't @click just work?

Components are complicated. One component can be a small fancy button wrapper, and another one can be an entire table with bunch of logic inside. Vue doesn't know what exactly you expect when bind v-model or use v-on so all of that should be processed by component's creator.

How to handle click event

According to Vue docs, $emit passes events to parent. Example from docs:

Main file

<blog-post
  @enlarge-text="onEnlargeText"
/>

Component

<button @click="$emit('enlarge-text')">
  Enlarge text
</button>

(@ is the v-on shorthand)

Component handles native click event and emits parent's @enlarge-text="..."

enlarge-text can be replaced with click to make it look like we're handling a native click event:

<blog-post
  @click="onEnlargeText"
></blog-post>
<button @click="$emit('click')">
  Enlarge text
</button>

But that's not all. $emit allows to pass a specific value with an event. In the case of native click, the value is MouseEvent (JS event that has nothing to do with Vue).

Vue stores that event in a $event variable. So, it'd the best to emit $event with an event to create the impression of native event usage:

<button v-on:click="$emit('click', $event)">
  Enlarge text
</button>

How can I get the active screen dimensions?

This debugging code should do the trick well:

You can explore the properties of the Screen Class

Put all displays in an array or list using Screen.AllScreens then capture the index of the current display and its properties.

enter image description here

C# (Converted from VB by Telerik - Please double check)

        {
    List<Screen> arrAvailableDisplays = new List<Screen>();
    List<string> arrDisplayNames = new List<string>();

    foreach (Screen Display in Screen.AllScreens)
    {
        arrAvailableDisplays.Add(Display);
        arrDisplayNames.Add(Display.DeviceName);
    }

    Screen scrCurrentDisplayInfo = Screen.FromControl(this);
    string strDeviceName = Screen.FromControl(this).DeviceName;
    int idxDevice = arrDisplayNames.IndexOf(strDeviceName);

    MessageBox.Show(this, "Number of Displays Found: " + arrAvailableDisplays.Count.ToString() + Constants.vbCrLf + "ID: " + idxDevice.ToString() + Constants.vbCrLf + "Device Name: " + scrCurrentDisplayInfo.DeviceName.ToString + Constants.vbCrLf + "Primary: " + scrCurrentDisplayInfo.Primary.ToString + Constants.vbCrLf + "Bounds: " + scrCurrentDisplayInfo.Bounds.ToString + Constants.vbCrLf + "Working Area: " + scrCurrentDisplayInfo.WorkingArea.ToString + Constants.vbCrLf + "Bits per Pixel: " + scrCurrentDisplayInfo.BitsPerPixel.ToString + Constants.vbCrLf + "Width: " + scrCurrentDisplayInfo.Bounds.Width.ToString + Constants.vbCrLf + "Height: " + scrCurrentDisplayInfo.Bounds.Height.ToString + Constants.vbCrLf + "Work Area Width: " + scrCurrentDisplayInfo.WorkingArea.Width.ToString + Constants.vbCrLf + "Work Area Height: " + scrCurrentDisplayInfo.WorkingArea.Height.ToString, "Current Info for Display '" + scrCurrentDisplayInfo.DeviceName.ToString + "' - ID: " + idxDevice.ToString(), MessageBoxButtons.OK, MessageBoxIcon.Information);
}

VB (Original code)

 Dim arrAvailableDisplays As New List(Of Screen)()
    Dim arrDisplayNames As New List(Of String)()

    For Each Display As Screen In Screen.AllScreens
        arrAvailableDisplays.Add(Display)
        arrDisplayNames.Add(Display.DeviceName)
    Next

    Dim scrCurrentDisplayInfo As Screen = Screen.FromControl(Me)
    Dim strDeviceName As String = Screen.FromControl(Me).DeviceName
    Dim idxDevice As Integer = arrDisplayNames.IndexOf(strDeviceName)

    MessageBox.Show(Me,
                    "Number of Displays Found: " + arrAvailableDisplays.Count.ToString & vbCrLf &
                    "ID: " & idxDevice.ToString + vbCrLf &
                    "Device Name: " & scrCurrentDisplayInfo.DeviceName.ToString + vbCrLf &
                    "Primary: " & scrCurrentDisplayInfo.Primary.ToString + vbCrLf &
                    "Bounds: " & scrCurrentDisplayInfo.Bounds.ToString + vbCrLf &
                    "Working Area: " & scrCurrentDisplayInfo.WorkingArea.ToString + vbCrLf &
                    "Bits per Pixel: " & scrCurrentDisplayInfo.BitsPerPixel.ToString + vbCrLf &
                    "Width: " & scrCurrentDisplayInfo.Bounds.Width.ToString + vbCrLf &
                    "Height: " & scrCurrentDisplayInfo.Bounds.Height.ToString + vbCrLf &
                    "Work Area Width: " & scrCurrentDisplayInfo.WorkingArea.Width.ToString + vbCrLf &
                    "Work Area Height: " & scrCurrentDisplayInfo.WorkingArea.Height.ToString,
                    "Current Info for Display '" & scrCurrentDisplayInfo.DeviceName.ToString & "' - ID: " & idxDevice.ToString, MessageBoxButtons.OK, MessageBoxIcon.Information)

Screens List

Change hash without reload in jQuery

You could try catching the onload event. And stopping the propagation dependent on some flag.

var changeHash = false;

$('ul.questions li a').click(function(event) {
    var $this = $(this)
    $('.tab').hide();  //you can improve the speed of this selector.
    $($this.attr('href')).fadeIn('slow');
    StopEvent(event);  //notice I've changed this
    changeHash = true;
    window.location.hash = $this.attr('href');
});

$(window).onload(function(event){
    if (changeHash){
        changeHash = false;
        StopEvent(event);
    }
}

function StopEvent(event){
    event.preventDefault();
    event.stopPropagation();
    if ($.browser.msie) {
        event.originalEvent.keyCode = 0;
        event.originalEvent.cancelBubble = true;
        event.originalEvent.returnValue = false;
    }
}

Not tested, so can't say if it would work

Relative instead of Absolute paths in Excel VBA

You can provide more flexibility to your users by provide Browser Button to them

Private Sub btn_browser_file_Click()
Dim xRow As Long
Dim sh1 As Worksheet
Dim xl_app As Excel.Application
Dim xl_wk As Excel.Workbook
Dim WS As Workbook
Dim xDirect$, xFname$, InitialFoldr$
InitialFoldr$ = "C:\"
With Application.FileDialog(msoFileDialogFolderPicker)
    .InitialFileName = Application.DefaultFilePath & "\"
    .Title = "Please select a folder to list Files from"
    .InitialFileName = InitialFoldr$
    .Show
    Range("H13").Activate
    If .SelectedItems.Count <> 0 Then
        xDirect$ = .SelectedItems(1) & "\"
         Range("h12").Value = xDirect$
        xFname$ = Dir(xDirect$, 7)
        Do While xFname$ <> ""
         If (Format(FileDateTime(xDirect$ & "\" & xFname$), "MM/DD/YYYY") > Format(Range("H10").Value, "MM/DD/YYYY")) Then
            ActiveCell.Offset(xRow) = xFname$
            xRow = xRow + 1
            xFname$ = Dir
            Else
            xFname$ = Dir
            xRow = xRow
        End If
        Loop
    End If
End With

with this piece of code you can achieve this, easily. Tested code

sequelize findAll sort order in nodejs

If you want to sort data either in Ascending or Descending order based on particular column, using sequlize js, use the order method of sequlize as follows

// Will order the specified column by descending order
order: sequelize.literal('column_name order')
e.g. order: sequelize.literal('timestamp DESC')

Check array position for null/empty

If the array contains integers, the value cannot be NULL. NULL can be used if the array contains pointers.

SomeClass* myArray[2];
myArray[0] = new SomeClass();
myArray[1] = NULL;

if (myArray[0] != NULL) { // this will be executed }
if (myArray[1] != NULL) { // this will NOT be executed }

As http://en.cppreference.com/w/cpp/types/NULL states, NULL is a null pointer constant!

How do I remove accents from characters in a PHP string?

$unwanted_array = array(    '&amp;' => 'and', '&' => 'and', '@' => 'at', '©' => 'c', '®' => 'r', 
'°'=>'','¸'=>'','?'=>'','¯'=>'','_'=>'',
'Á'=>'a','á'=>'a','À'=>'a','à'=>'a','A'=>'a','a'=>'a','?'=>'a','?'=>'A','?'=>'A',
'?'=>'a','?'=>'a','?'=>'A','?'=>'a','?'=>'A','Â'=>'a','â'=>'a','?'=>'a','?'=>'A',
'?'=>'a','?'=>'a','?'=>'a','?'=>'A','A'=>'a','a'=>'a','Å'=>'a','å'=>'a','?'=>'a',
'?'=>'a','Ä'=>'a','ä'=>'a','ã'=>'a','Ã'=>'A','A'=>'a','a'=>'a','A'=>'a','a'=>'a',
'?'=>'a','?'=>'a','?'=>'A','?'=>'a','?'=>'a','?'=>'A','?'=>'a','?'=>'A','Æ'=>'ae',
'æ'=>'ae','?'=>'ae','?'=>'ae','?'=>'a','?'=>'A',
'C'=>'c','c'=>'c','C'=>'c','c'=>'c','C'=>'c','c'=>'c','C'=>'c','c'=>'c','Ç'=>'c','ç'=>'c',
'D'=>'d','d'=>'d','?'=>'D','?'=>'d','Ð'=>'d','d'=>'d','?'=>'D','?'=>'d','?'=>'D','?'=>'d','ð'=>'d','Ð'=>'D',
'É'=>'e','é'=>'e','È'=>'e','è'=>'e','E'=>'e','e'=>'e','ê'=>'e','?'=>'e','?'=>'E','?'=>'e',
'?'=>'E','E'=>'e','e'=>'e','Ë'=>'e','ë'=>'e','E'=>'e','e'=>'e','E'=>'e','e'=>'e','E'=>'e',
'e'=>'e','?'=>'e','?'=>'E','?'=>'e','?'=>'e','?'=>'e','?'=>'E','?'=>'e',
'?'=>'E','?'=>'e','?'=>'E','?'=>'e','?'=>'E','?'=>'e','?'=>'E',
'ƒ'=>'f',
'G'=>'g','g'=>'g','G'=>'g','g'=>'g','G'=>'G','g'=>'g','G'=>'g','g'=>'g','G'=>'g','g'=>'g',
'H_'=>'H','h_'=>'h','H'=>'h','h'=>'h','?'=>'H','?'=>'h','?'=>'H','?'=>'h','H'=>'h','h'=>'h','?'=>'H','?'=>'h',
'?'=>'I','Í'=>'i','í'=>'i','Ì'=>'i','ì'=>'i','I'=>'i','i'=>'i','Î'=>'i','î'=>'i','I'=>'i','i'=>'i',
'Ï'=>'i','ï'=>'i','?'=>'I','?'=>'i','I'=>'i','i'=>'i','I'=>'i','I'=>'i','i'=>'i','I'=>'i','i'=>'i',
'?'=>'I','?'=>'I','?'=>'i','?'=>'ij','?'=>'ij','i'=>'i',
'J'=>'j','j'=>'j',
'K'=>'k','k'=>'k','?'=>'K','?'=>'k',
'L'=>'l','l'=>'l','L'=>'l','l'=>'l','L'=>'l','l'=>'l','L'=>'l','l'=>'l','?'=>'l','?'=>'l',
'N'=>'n','n'=>'n','N'=>'n','n'=>'n','Ñ'=>'N','ñ'=>'n','N'=>'n','n'=>'n','?'=>'N','?'=>'n','?'=>'n','?'=>'n',
'Ó'=>'o','ó'=>'o','Ò'=>'o','ò'=>'o','O'=>'o','o'=>'o','Ô'=>'o','ô'=>'o','?'=>'o','?'=>'O','?'=>'o',
'?'=>'O','?'=>'o','?'=>'O','O'=>'o','o'=>'o','Ö'=>'o','ö'=>'o','O'=>'o','o'=>'o','Õ'=>'o','õ'=>'o',
'Ø'=>'o','ø'=>'o','?'=>'o','?'=>'o','O'=>'O','o'=>'o','O'=>'O','o'=>'o','O'=>'o','o'=>'o','?'=>'o',
'?'=>'O','O'=>'o','o'=>'o','?'=>'o','?'=>'O','?'=>'o','?'=>'O','?'=>'o','?'=>'O','?'=>'o','?'=>'O',
'?'=>'o','?'=>'O','?'=>'o','?'=>'O','?'=>'o','?'=>'O','?'=>'o','?'=>'O','?'=>'o','?'=>'O',
'Œ'=>'oe','œ'=>'oe',
'?'=>'k',
'R'=>'r','r'=>'r','R'=>'r','r'=>'r','?'=>'r','R'=>'r','r'=>'r','?'=>'R','?'=>'r','?'=>'R','?'=>'r',
'S_'=>'S','s_'=>'s','S'=>'s','s'=>'s','S'=>'s','s'=>'s','Š'=>'s','š'=>'s','S'=>'s','s'=>'s',
'?'=>'S','?'=>'s','?'=>'S','?'=>'s',
'?'=>'z','ß'=>'ss','T'=>'t','t'=>'t','T'=>'t','t'=>'t','?'=>'T','?'=>'t','?'=>'T',
'?'=>'t','?'=>'T','?'=>'t','™'=>'tm','T'=>'t','t'=>'t',
'Ú'=>'u','ú'=>'u','Ù'=>'u','ù'=>'u','U'=>'u','u'=>'u','Û'=>'u','û'=>'u','U'=>'u','u'=>'u','U'=>'u','u'=>'u',
'Ü'=>'u','ü'=>'u','U'=>'u','u'=>'u','U'=>'u','u'=>'u','U'=>'u','u'=>'u','U'=>'u','u'=>'u','U'=>'u','u'=>'u',
'U'=>'u','u'=>'u','U'=>'u','u'=>'u','U'=>'u','u'=>'u','U'=>'u','u'=>'u','?'=>'u','?'=>'U','?'=>'u','?'=>'U',
'?'=>'u','?'=>'U','?'=>'u','?'=>'U','?'=>'u','?'=>'U','?'=>'u','?'=>'U','?'=>'u','?'=>'U',
'W'=>'w','w'=>'w',
'Ý'=>'y','ý'=>'y','?'=>'y','?'=>'Y','Y'=>'y','y'=>'y','ÿ'=>'y','Ÿ'=>'y','?'=>'y','?'=>'Y','?'=>'y','?'=>'Y',
'Z_'=>'Z','z_'=>'z','Z'=>'z','z'=>'z','Ž'=>'z','ž'=>'z','Z'=>'z','z'=>'z','?'=>'Z','?'=>'z',
'þ'=>'p','?'=>'n','?'=>'a','?'=>'a','?'=>'b','?'=>'b','?'=>'v','?'=>'v','?'=>'g','?'=>'g','?'=>'g','?'=>'g',
'?'=>'d','?'=>'d','?'=>'e','?'=>'e','?'=>'jo','?'=>'jo','?'=>'e','?'=>'e','?'=>'zh','?'=>'zh','?'=>'z','?'=>'z',
'?'=>'i','?'=>'i','?'=>'i','?'=>'i','?'=>'i','?'=>'i','?'=>'j','?'=>'j','?'=>'k','?'=>'k','?'=>'l','?'=>'l',
'?'=>'m','?'=>'m','?'=>'n','?'=>'n','?'=>'o','?'=>'o','?'=>'p','?'=>'p','?'=>'r','?'=>'r','?'=>'s','?'=>'s',
'?'=>'t','?'=>'t','?'=>'u','?'=>'u','?'=>'f','?'=>'f','?'=>'h','?'=>'h','?'=>'c','?'=>'c','?'=>'ch','?'=>'ch',
'?'=>'sh','?'=>'sh','?'=>'sch','?'=>'sch','?'=>'-',
'?'=>'-','?'=>'y','?'=>'y','?'=>'-','?'=>'-',
'?'=>'je','?'=>'je','?'=>'ju','?'=>'ju','?'=>'ja','?'=>'ja','?'=>'a','?'=>'b','?'=>'g','?'=>'d','?'=>'h','?'=>'v',
'?'=>'z','?'=>'h','?'=>'t','?'=>'i','?'=>'k','?'=>'k','?'=>'l','?'=>'m','?'=>'m','?'=>'n','?'=>'n','?'=>'s','?'=>'e',
'?'=>'p','?'=>'p','?'=>'C','?'=>'c','?'=>'q','?'=>'r','?'=>'w','?'=>'t'
);

$accentsRemoved = strtr( $stringToRemoveAccents , $unwanted_array );

Questions every good Database/SQL developer should be able to answer

"Why should every SELECT always include DISTINCT ?"

WCF timeout exception detailed investigation

Are you closing the connection to the WCF service in between requests? If you don't, you'll see this exact timeout (eventually).

Build error, This project references NuGet

In my case, I deleted the Previous Project & created a new project with different name, when i was building the Project it shows me the same error.

I just edited the Project Name in csproj file of the Project & it Worked...!

Given a starting and ending indices, how can I copy part of a string in C?

Use strncpy

e.g.

strncpy(dest, src + beginIndex, endIndex - beginIndex);

This assumes you've

  1. Validated that dest is large enough.
  2. endIndex is greater than beginIndex
  3. beginIndex is less than strlen(src)
  4. endIndex is less than strlen(src)

bash string compare to multiple correct values

Maybe you should better use a case for such lists:

case "$cms" in
  wordpress|meganto|typo3)
    do_your_else_case
    ;;
  *)
    do_your_then_case
    ;;
esac

I think for long such lists this is better readable.

If you still prefer the if you can do it with single brackets in two ways:

if [ "$cms" != wordpress -a "$cms" != meganto -a "$cms" != typo3 ]; then

or

if [ "$cms" != wordpress ] && [ "$cms" != meganto ] && [ "$cms" != typo3 ]; then

C/C++ line number

Since i'm also facing this problem now and i cannot add an answer to a different but also valid question asked here, i'll provide an example solution for the problem of: getting only the line number of where the function has been called in C++ using templates.

Background: in C++ one can use non-type integer values as a template argument. This is different than the typical usage of data types as template arguments. So the idea is to use such integer values for a function call.

#include <iostream>

class Test{
    public:
        template<unsigned int L>
        int test(){
            std::cout << "the function has been called at line number: " << L << std::endl;
            return 0;
        }
        int test(){ return this->test<0>(); }
};

int main(int argc, char **argv){
    Test t;
    t.test();
    t.test<__LINE__>();
    return 0;
}

Output:

the function has been called at line number: 0

the function has been called at line number: 16

One thing to mention here is that in C++11 Standard it's possible to give default template values for functions using template. In pre C++11 default values for non-type arguments seem to only work for class template arguments. Thus, in C++11, there would be no need to have duplicate function definitions as above. In C++11 its also valid to have const char* template arguments but its not possible to use them with literals like __FILE__ or __func__ as mentioned here.

So in the end if you're using C++ or C++11 this might be a very interesting alternative than using macro's to get the calling line.

Why do I need to explicitly push a new branch?

At first check

Step-1: git remote -v
//if found git initialize then remove or skip step-2

Step-2: git remote rm origin
//Then configure your email address globally git

Step-3: git config --global user.email "[email protected]"

Step-4: git initial

Step-5: git commit -m "Initial Project"
//If already add project repo then skip step-6

Step-6: git remote add origin %repo link from bitbucket.org%

Step-7: git push -u origin master

How to order by with union in SQL?

Both other answers are correct, but I thought it worth noting that the place where I got stuck was not realizing that you'll need order by the alias and make sure that the alias is the same for both the selects... so

select 'foo'
union
select item as `foo`
from myTable
order by `foo`

notice that I'm using single quotes in the first select but backticks for the others.

That will get you the sorting you need.

The AWS Access Key Id does not exist in our records

Adding one more answer since all the above cases didn't work for me.

In AWS console, check your credentials(My Security Credentials) and see if you have entered the right credentials.

Thanks to this discussion: https://forums.aws.amazon.com/message.jspa?messageID=771815

How to display items side-by-side without using tables?

these days div is the new norm

<div style="float:left"><img.. ></div>
<div style="float:right">text</div>
<div style="clear:both"/>

How to get the employees with their managers

TRY THIS

SELECT E.ename,E.empno,ISNULL(E.ename,'NO MANAGER') AS MANAGER FROM emp e
INNER JOIN emp M
ON  M.empno=E.empno

Instaed of subquery use self join

jQuery UI 1.10: dialog and zIndex option

You don't tell it, but you are using jQuery UI 1.10.

In jQuery UI 1.10 the zIndex option is removed:

Removed zIndex option

Similar to the stack option, the zIndex option is unnecessary with a proper stacking implementation. The z-index is defined in CSS and stacking is now controlled by ensuring the focused dialog is the last "stacking" element in its parent.

you have to use pure css to set the dialog "on the top":

.ui-dialog { z-index: 1000 !important ;}

you need the key !important to override the default styling of the element; this affects all your dialogs if you need to set it only for a dialog use the dialogClass option and style it.

If you need a modal dialog set the modal: true option see the docs:

If set to true, the dialog will have modal behavior; other items on the page will be disabled, i.e., cannot be interacted with. Modal dialogs create an overlay below the dialog but above other page elements.

You need to set the modal overlay with an higher z-index to do so use:

.ui-front { z-index: 1000 !important; }

for this element too.

Quicker way to get all unique values of a column in VBA?

PowerShell is a very powerful and efficient tool. This is cheating a little, but shelling PowerShell via VBA opens up lots of options

The bulk of the code below is simply to save the current sheet as a csv file. The output is another csv file with just the unique values

Sub AnotherWay()
Dim strPath As String
Dim strPath2 As String

Application.DisplayAlerts = False
strPath = "C:\Temp\test.csv"
strPath2 = "C:\Temp\testout.csv"
ActiveWorkbook.SaveAs strPath, xlCSV
x = Shell("powershell.exe $csv = import-csv -Path """ & strPath & """ -Header A | Select-Object -Unique A | Export-Csv """ & strPath2 & """ -NoTypeInformation", 0)
Application.DisplayAlerts = True

End Sub

Usage of @see in JavaDoc?

The @see tag is a bit different than the @link tag,
limited in some ways and more flexible in others:

different JavaDoc link types Different JavaDoc link types

  1. Displays the member name for better learning, and is refactorable; the name will update when renaming by refactor
  2. Refactorable and customizable; your text is displayed instead of the member name
  3. Displays name, refactorable
  4. Refactorable, customizable
  5. A rather mediocre combination that is:
  • Refactorable, customizable, and stays in the See Also section
  • Displays nicely in the Eclipse hover
  • Displays the link tag and its formatting when generated
  • When using multiple @see items, commas in the description make the output confusing
  1. Completely illegal; causes unexpected content and illegal character errors in the generator

See the results below:

JavaDoc generation results with different link types JavaDoc generation results with different link types

Best regards.

Get data from php array - AJAX - jQuery

When you echo $array;, the result is Array, result[0] then represents the first character in Array which is A.

One way to handle this problem would be like this:

ajax.php

<?php
$array = array(1,2,3,4,5,6);
foreach($array as $a)
    echo $a.",";
?>

jquery code

$(function(){ /* short for $(document).ready(function(){ */

    $('#prev').click(function(){

        $.ajax({type:    'POST',
                 url:     'ajax.php',
                 data:    'id=testdata',
                 cache:   false,
                 success: function(data){
                     var tmp = data.split(",");
                     $('#content1').html(tmp[0]);
                 }
                });
    });

});

When to use an interface instead of an abstract class and vice versa?

When to do what is a very simple thing if you have the concept clear in your mind.

Abstract classes can be Derived whereas Interfaces can be Implemented. There is some difference between the two. When you derive an Abstract class, the relationship between the derived class and the base class is 'is a' relationship. e.g., a Dog is an Animal, a Sheep is an Animal which means that a Derived class is inheriting some properties from the base class.

Whereas for implementation of interfaces, the relationship is "can be". e.g., a Dog can be a spy dog. A dog can be a circus dog. A dog can be a race dog. Which means that you implement certain methods to acquire something.

I hope I am clear.

Bootstrap carousel width and height

I had the same problem.

My height changed to its original height while my slide was animating to the left, ( in a responsive website )

so I fixed it with CSS only :

.carousel .item.left img{
    width: 100% !important;
}

iOS - UIImageView - how to handle UIImage image orientation

Inspired from @Aqua Answer.....

in Objective C

- (UIImage *)fixImageOrientation:(UIImage *)img {

   UIGraphicsBeginImageContext(img.size);
   [img drawAtPoint:CGPointZero];

   UIImage *newImg = UIGraphicsGetImageFromCurrentImageContext();
   UIGraphicsEndImageContext();

   if (newImg) {
       return newImg;
   }

   return img;
}

Printing the correct number of decimal points with cout

With <iomanip>, you can use std::fixed and std::setprecision

Here is an example

#include <iostream>
#include <iomanip>

int main()
{
    double d = 122.345;

    std::cout << std::fixed;
    std::cout << std::setprecision(2);
    std::cout << d;
}

And you will get output

122.34

Matplotlib tight_layout() doesn't take into account figure suptitle

This website has a simple solution to this with an example that worked for me. The line of code that does the actual leaving of space for the title is the following:

plt.tight_layout(rect=[0, 0, 1, 0.95]) 

Here is an image of proof that it worked for me: Image Link

Android - How to get application name? (Not package name)

Okay guys another sleek option is

Application.Context.ApplicationInfo.NonLocalizedLabel

verified for hard coded android label on application element.

<application android:label="Big App"></application>

Reference: http://developer.android.com/reference/android/content/pm/PackageItemInfo.html#nonLocalizedLabel

How to detect a route change in Angular?

In the component, you might want to try this:

import {NavigationEnd, NavigationStart, Router} from '@angular/router';

constructor(private router: Router) {
router.events.subscribe(
        (event) => {
            if (event instanceof NavigationStart)
                // start loading pages
            if (event instanceof NavigationEnd) {
                // end of loading paegs
            }
        });
}

Bootstrap table striped: How do I change the stripe background colour?

If using SASS and Bootstrap 4, you can change the alternating background row color for both .table and .table-dark with:

$table-accent-bg: #990000;
$table-dark-accent-bg: #990000;

Error using eclipse for Android - No resource found that matches the given name

I resolved this kind of issue like this: I went into my XML layout file, cut the line of code that was generating the error. Then I saved the file, and pasted the code back in. The error was gone.

Convert unix time to readable date in pandas dataframe

Assuming we imported pandas as pd and df is our dataframe

pd.to_datetime(df['date'], unit='s')

works for me.

ORA-06550: line 1, column 7 (PL/SQL: Statement ignored) Error

If the value stored in PropertyLoader.RET_SECONDARY_V_ARRAY is not "V_ARRAY", then you are using different types; even if they are declared identically (e.g. both are table of number) this will not work.

You're hitting this data type compatibility restriction:

You can assign a collection to a collection variable only if they have the same data type. Having the same element type is not enough.

You're trying to call the procedure with a parameter that is a different type to the one it's expecting, which is what the error message is telling you.

How to Generate Barcode using PHP and Display it as an Image on the same page

There is a library for this BarCode PHP. You just need to include a few files:

require_once('class/BCGFontFile.php');
require_once('class/BCGColor.php');
require_once('class/BCGDrawing.php');

You can generate many types of barcodes, namely 1D or 2D. Add the required library:

require_once('class/BCGcode39.barcode.php');

Generate the colours:

// The arguments are R, G, and B for color.
$colorFront = new BCGColor(0, 0, 0);
$colorBack = new BCGColor(255, 255, 255);

After you have added all the codes, you will get this way:

Example

Since several have asked for an example here is what I was able to do to get it done

require_once('class/BCGFontFile.php');
require_once('class/BCGColor.php');
require_once('class/BCGDrawing.php');

require_once('class/BCGcode128.barcode.php');

header('Content-Type: image/png');

$color_white = new BCGColor(255, 255, 255);

$code = new BCGcode128();
$code->parse('HELLO');

$drawing = new BCGDrawing('', $color_white);
$drawing->setBarcode($code);

$drawing->draw();
$drawing->finish(BCGDrawing::IMG_FORMAT_PNG);

If you want to actually create the image file so you can save it then change

$drawing = new BCGDrawing('', $color_white);

to

$drawing = new BCGDrawing('image.png', $color_white);

Regex match everything after question mark?

Check out this site: http://rubular.com/ Basically the site allows you to enter some example text (what you would be looking for on your site) and then as you build the regular expression it will highlight what is being matched in real time.

iOS 7 UIBarButton back button arrow color

If you want to change only the Back Arrow BUT on the entire app, do this:

[[NSClassFromString(@"_UINavigationBarBackIndicatorView") appearance] 
  setTintColor:[UIColor colorWithHexString: @"#f00000"]];

How do I query between two dates using MySQL?

Just Cast date_field as date

SELECT * FROM `objects` 
WHERE (cast(date_field as date) BETWEEN '2010-09-29' AND 
'2010-01-30' )

Strip double quotes from a string in .NET

I think your first line would actually work but I think you need four quotation marks for a string containing a single one (in VB at least):

s = s.Replace("""", "")

for C# you'd have to escape the quotation mark using a backslash:

s = s.Replace("\"", "");

How to generate and auto increment Id with Entity Framework

You have a bad table design. You can't autoincrement a string, that doesn't make any sense. You have basically two options:

1.) change type of ID to int instead of string
2.) not recommended!!! - handle autoincrement by yourself. You first need to get the latest value from the database, parse it to the integer, increment it and attach it to the entity as a string again. VERY BAD idea

First option requires to change every table that has a reference to this table, BUT it's worth it.

How can I move HEAD back to a previous location? (Detached head) & Undo commits

First reset locally:

git reset 23b6772

To see if you're on the right position, verify with:

git status

You will see something like:

On branch master Your branch is behind 'origin/master' by 17 commits, and can be fast-forwarded.

Then rewrite history on your remote tracking branch to reflect the change:

git push --force-with-lease // a useful command @oktober mentions in comments

Using --force-with-lease instead of --force will raise an error if others have meanwhile committed to the remote branch, in which case you should fetch first. More info in this article.

Convert iterator to pointer?

A safe version to convert an iterator to a pointer (exactly what that means regardless of the implications) and by safe I mean no worries about having to dereference the iterator and cause possible exceptions / errors due to end() / other situations

#include <iostream>
#include <vector>
#include <string.h>

int main()
{
    std::vector<int> vec;

    char itPtr[25];
    long long itPtrDec;
    
    std::vector<int>::iterator it = vec.begin();
    memset(&itPtr, 0, 25);
    sprintf(itPtr, "%llu", it);
    itPtrDec = atoll(itPtr);
    printf("it = 0x%X\n", itPtrDec);
    
    vec.push_back(123);
    it = vec.begin();
    memset(&itPtr, 0, 25);
    sprintf(itPtr, "%llu", it);
    itPtrDec = atoll(itPtr);
    printf("it = 0x%X\n", itPtrDec);
}

will print something like

it = 0x0

it = 0x2202E10

It's an incredibly hacky way to do it, but if you need it, it does the job. You will receive some compiler warnings which, if really bothering you, can be removed with #pragma

Pip install - Python 2.7 - Windows 7

I've seen this issue before with 2.7.14. Fixed it by :

  1. Re-install python 2.7.14
  2. During the installation, select default path and put a check mark in the installation options to add python to windows path i.e. environmental variables.
  3. After installation is complete, go to System from the Control Panel, select Advanced system settings, and clicking Environment Variables.
  4. Verify that the system variable "path" has "C:\Python\;C:\Python\Scripts;" added to the list.
  5. In cmd, run "where python" and then "where pip". Which will show for example:

    ? where python
    C:\Python\python.exe
    
    ? where pip
    C:\Python\Scripts\pip.exe
    
  6. Run pip, then it should show different pip run command options.

Calculate summary statistics of columns in dataframe

Now there is the pandas_profiling package, which is a more complete alternative to df.describe().

If your pandas dataframe is df, the below will return a complete analysis including some warnings about missing values, skewness, etc. It presents histograms and correlation plots as well.

import pandas_profiling
pandas_profiling.ProfileReport(df)

See the example notebook detailing the usage.

How to send a model in jQuery $.ajax() post request to MVC controller method

In ajax call mention-

data:MakeModel(),

use the below function to bind data to model

function MakeModel() {

    var MyModel = {};

    MyModel.value = $('#input element id').val() or your value;

    return JSON.stringify(MyModel);
}

Attach [HttpPost] attribute to your controller action

on POST this data will get available

MySQL show status - active or total connections?

As per doc http://dev.mysql.com/doc/refman/5.0/en/server-status-variables.html#statvar_Connections

Connections

The number of connection attempts (successful or not) to the MySQL server.

How can I run code on a background thread on Android?

Remember Running Background, Running continuously are two different tasks.

For long-term background processes, Threads aren't optimal with Android. However, here's the code and do it at your own risk...

Remember Service or Thread will run in the background but our task needs to make trigger (call again and again) to get updates, i.e. once the task is completed we need to recall the function for next update.

Timer (periodic trigger), Alarm (Timebase trigger), Broadcast (Event base Trigger), recursion will awake our functions.

public static boolean isRecursionEnable = true;

void runInBackground() {
    if (!isRecursionEnable)
        // Handle not to start multiple parallel threads
        return;

    // isRecursionEnable = false; when u want to stop
    // on exception on thread make it true again  
    new Thread(new Runnable() {
        @Override
        public void run() {
            // DO your work here
            // get the data
            if (activity_is_not_in_background) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // update UI
                        runInBackground();
                    }
                });
            } else {
                runInBackground();
            }
        }
    }).start();
}

Using Service: If you launch a Service it will start, It will execute the task, and it will terminate itself. after the task execution. terminated might also be caused by exception, or user killed it manually from settings. START_STICKY (Sticky Service) is the option given by android that service will restart itself if service terminated.

Remember the question difference between multiprocessing and multithreading? Service is a background process (Just like activity without UI), The same way how you launch thread in the activity to avoid load on the main thread (Activity thread), the same way you need to launch threads(or async tasks) on service to avoid load on service.

In a single statement, if you want a run a background continues task, you need to launch a StickyService and run the thread in the service on event base

SSIS - Text was truncated or one or more characters had no match in the target code page - Special Characters

If you go to the Flat file connection manager under Advanced and Look at the "OutputColumnWidth" description's ToolTip It will tell you that Composit characters may use more spaces. So the "é" in "Société" most likely occupies more than one character.

EDIT: Here's something about it: http://en.wikipedia.org/wiki/Precomposed_character

What causes the error "_pickle.UnpicklingError: invalid load key, ' '."?

I am not completely sure what you're trying to achieve by seeking to a specific offset and attempting to load individual values manually, the typical usage of the pickle module is:

# save data to a file
with open('myfile.pickle','wb') as fout:
    pickle.dump([1,2,3],fout)

# read data from a file
with open('myfile.pickle') as fin:
    print pickle.load(fin)

# output
>> [1, 2, 3]

If you dumped a list, you'll load a list, there's no need to load each item individually.

you're saying that you got an error before you were seeking to the -5000 offset, maybe the file you're trying to read is corrupted.

If you have access to the original data, I suggest you try saving it to a new file and reading it as in the example.

"Uncaught TypeError: Illegal invocation" in Chrome

You can also use:

var obj = {
    alert: alert.bind(window)
};
obj.alert('I´m an alert!!');

How to list only files and not directories of a directory Bash?

{ find . -maxdepth 1 -type f | xargs ls -1t | less; }

added xargs to make it works, and used -1 instead of -l to show only filenames without additional ls info

awk partly string match (if column/word partly matches)

GNU sed

sed '/\s*\(\S\+\s\+\)\{2\}\bsnow\(man\)\?\b/!d' file

Input:

C1    C2    C3    
1     a     snow   
2     b     snowman 
snow     c     sowman
      snow     snow     snowmanx

..output:

1     a     snow
2     b     snowman

Location of ini/config files in linux/unix?

For user configuration I've noticed a tendency towards moving away from individual ~/.myprogramrc to a structure below ~/.config. For example, Qt 4 uses ~/.config/<vendor>/<programname> with the default settings of QSettings. The major desktop environments KDE and Gnome use a file structure below a specific folder too (not sure if KDE 4 uses ~/.config, XFCE does use ~/.config).

Using multiple property files (via PropertyPlaceholderConfigurer) in multiple projects/modules

I know that this is an old question, but the ignore-unresolvable property was not working for me and I didn't know why.

The problem was that I needed an external resource (something like location="file:${CATALINA_HOME}/conf/db-override.properties") and the ignore-unresolvable="true" does not do the job in this case.

What one needs to do for ignoring a missing external resource is:

ignore-resource-not-found="true"

Just in case anyone else bumps into this.

Read input from a JOptionPane.showInputDialog box

Your problem is that, if the user clicks cancel, operationType is null and thus throws a NullPointerException. I would suggest that you move

if (operationType.equalsIgnoreCase("Q")) 

to the beginning of the group of if statements, and then change it to

if(operationType==null||operationType.equalsIgnoreCase("Q")). 

This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.

Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.

Initialize 2D array

Shorter way is do it as follows:

private char[][] table = {{'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}};

MySQL integer field is returned as string in PHP

In my project I usually use an external function that "filters" data retrieved with mysql_fetch_assoc.

You can rename fields in your table so that is intuitive to understand which data type is stored.

For example, you can add a special suffix to each numeric field: if userid is an INT(11) you can rename it userid_i or if it is an UNSIGNED INT(11) you can rename userid_u. At this point, you can write a simple PHP function that receive as input the associative array (retrieved with mysql_fetch_assoc), and apply casting to the "value" stored with those special "keys".

Declare variable in table valued function

There are two flavors of table valued functions. One that is just a select statement and one that can have more rows than just a select statement.

This can not have a variable:

create function Func() returns table
as
return
select 10 as ColName

You have to do like this instead:

create function Func()
returns @T table(ColName int)
as
begin
  declare @Var int
  set @Var = 10
  insert into @T(ColName) values (@Var)
  return
end

input type=file show only button

<input type="file" id="selectedFile" style="display: none;" />
<input type="button" value="Browse..." onclick="document.getElementById('selectedFile').click();" />

This will surely work i have used it in my projects.I hope this helps :)

How to install the Sun Java JDK on Ubuntu 10.10 (Maverick Meerkat)?

This worked for me:

sudo add-apt-repository ppa:sun-java-community-team/sun-java6

sudo apt-get update

sudo apt-get install sun-java6-jre sun-java6-jdk

GridView must be placed inside a form tag with runat="server" even after the GridView is within a form tag

You are calling GridView.RenderControl(htmlTextWriter), hence the page raises an exception that a Server-Control was rendered outside of a Form.

You could avoid this execption by overriding VerifyRenderingInServerForm

public override void VerifyRenderingInServerForm(Control control)
{
  /* Confirms that an HtmlForm control is rendered for the specified ASP.NET
     server control at run time. */
}

See here and here.

SQL LEFT JOIN Subquery Alias

I recognize that the answer works and has been accepted but there is a much cleaner way to write that query. Tested on mysql and postgres.

SELECT wpoi.order_id As No_Commande
FROM  wp_woocommerce_order_items AS wpoi
LEFT JOIN wp_postmeta AS wpp ON wpoi.order_id = wpp.post_id 
                            AND wpp.meta_key = '_shipping_first_name'
WHERE  wpoi.order_id =2198 

How to use System.Net.HttpClient to post a complex type?

You should use the SendAsync method instead, this is a generic method, that serializes the input to the service

Widget widget = new Widget()
widget.Name = "test"
widget.Price = 1;

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:44268/api/test");
client.SendAsync(new HttpRequestMessage<Widget>(widget))
    .ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode() );

If you don't want to create the concrete class, you can make it with the FormUrlEncodedContent class

var client = new HttpClient();

// This is the postdata
var postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>("Name", "test"));
postData.Add(new KeyValuePair<string, string>("Price ", "100"));

HttpContent content = new FormUrlEncodedContent(postData); 

client.PostAsync("http://localhost:44268/api/test", content).ContinueWith(
    (postTask) =>
    {
        postTask.Result.EnsureSuccessStatusCode();
    });

Note: you need to make your id to a nullable int (int?)

Calculate mean and standard deviation from a vector of samples in C++ using Boost

2x faster than the versions before mentioned - mostly because transform() and inner_product() loops are joined. Sorry about my shortcut/typedefs/macro: Flo = float. CR const ref. VFlo - vector. Tested in VS2010

#define fe(EL, CONTAINER)   for each (auto EL in CONTAINER)  //VS2010
Flo stdDev(VFlo CR crVec) {
    SZ  n = crVec.size();               if (n < 2) return 0.0f;
    Flo fSqSum = 0.0f, fSum = 0.0f;
    fe(f, crVec) fSqSum += f * f;       // EDIT: was Cit(VFlo, crVec) {
    fe(f, crVec) fSum   += f;
    Flo fSumSq      = fSum * fSum;
    Flo fSumSqDivN  = fSumSq / n;
    Flo fSubSqSum   = fSqSum - fSumSqDivN;
    Flo fPreSqrt    = fSubSqSum / (n - 1);
    return sqrt(fPreSqrt);
}

Split string, convert ToList<int>() in one line

It is also possible to int array to direct assign value.

like this

int[] numbers = sNumbers.Split(',').Select(Int32.Parse).ToArray();

How to make button fill table cell

For starters:

<p align='center'>
<table width='100%'>
<tr>
<td align='center'><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>

Note, if the width of the input button is 100%, you wont need the attribute "align='center'" anymore.

This would be the optimal solution:

<p align='center'>
<table width='100%'>
<tr>
<td><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>

INSERT ... ON DUPLICATE KEY (do nothing)

Use ON DUPLICATE KEY UPDATE ...,
Negative : because the UPDATE uses resources for the second action.

Use INSERT IGNORE ...,
Negative : MySQL will not show any errors if something goes wrong, so you cannot handle the errors. Use it only if you don’t care about the query.

How to define a circle shape in an Android XML drawable file?

Set this as your view background

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <stroke
        android:width="1dp"
        android:color="#78d9ff"/>
</shape>

enter image description here

For solid circle use:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid
        android:color="#48b3ff"/>
</shape>

enter image description here

Solid with stroke:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid android:color="#199fff"/>
    <stroke
        android:width="2dp"
        android:color="#444444"/>
</shape>

enter image description here

Note: To make the oval shape appear as a circle, in these examples, either your view that you are using this shape as its background should be a square or you have to set the height and width properties of the shape tag to an equal value.

Python != operation vs "is not"

Consider the following:

class Bad(object):
    def __eq__(self, other):
        return True

c = Bad()
c is None # False, equivalent to id(c) == id(None)
c == None # True, equivalent to c.__eq__(None)

SELECT list is not in GROUP BY clause and contains nonaggregated column

country.code is not in your group by statement, and is not an aggregate (wrapped in an aggregate function).

https://www.w3schools.com/sql/sql_ref_sqlserver.asp

In C#, how to check whether a string contains an integer?

Sorry, didn't quite get your question. So something like this?

str.ToCharArray().Any(char.IsDigit);

Or does the value have to be an integer completely, without any additional strings?

if(str.ToCharArray().All(char.IsDigit(c));

SQL Server 2008: how do I grant privileges to a username?

If you really want them to have ALL rights:

use YourDatabase
go
exec sp_addrolemember 'db_owner', 'UserName'
go

Difference between web reference and service reference?

The service reference is the newer interface for adding references to all manner of WCF services (they may not be web services) whereas Web reference is specifically concerned with ASMX web references.

You can access web references via the advanced options in add service reference (if I recall correctly).

I'd use service reference because as I understand it, it's the newer mechanism of the two.

Working copy locked error in tortoise svn while committing

I had no idea what file was having the lock so what I did to get out of this issue was:

  1. Went to the highest level folder
  2. Click clean-up and also ticked from the cleaning-up methods --> Break locks

This worked for me.

Convert a python UTC datetime to a local datetime using only python standard library?

I think I figured it out: computes number of seconds since epoch, then converts to a local timzeone using time.localtime, and then converts the time struct back into a datetime...

EPOCH_DATETIME = datetime.datetime(1970,1,1)
SECONDS_PER_DAY = 24*60*60

def utc_to_local_datetime( utc_datetime ):
    delta = utc_datetime - EPOCH_DATETIME
    utc_epoch = SECONDS_PER_DAY * delta.days + delta.seconds
    time_struct = time.localtime( utc_epoch )
    dt_args = time_struct[:6] + (delta.microseconds,)
    return datetime.datetime( *dt_args )

It applies the summer/winter DST correctly:

>>> utc_to_local_datetime( datetime.datetime(2010, 6, 6, 17, 29, 7, 730000) )
datetime.datetime(2010, 6, 6, 19, 29, 7, 730000)
>>> utc_to_local_datetime( datetime.datetime(2010, 12, 6, 17, 29, 7, 730000) )
datetime.datetime(2010, 12, 6, 18, 29, 7, 730000)

Setting PATH environment variable in OSX permanently

You have to add it to /etc/paths.

Reference (which works for me) : Here

Missing styles. Is the correct theme chosen for this layout?

Try switching the theme in the design view to one of the options in "Manifest Themes". I'm guessing this is Because you are inheriting the theme from the manifest to support multiple api levels. It worked for me anyway.

What is String pool in Java?

I don't think it actually does much, it looks like it's just a cache for string literals. If you have multiple Strings who's values are the same, they'll all point to the same string literal in the string pool.

String s1 = "Arul"; //case 1 
String s2 = "Arul"; //case 2 

In case 1, literal s1 is created newly and kept in the pool. But in case 2, literal s2 refer the s1, it will not create new one instead.

if(s1 == s2) System.out.println("equal"); //Prints equal. 

String n1 = new String("Arul"); 
String n2 = new String("Arul"); 
if(n1 == n2) System.out.println("equal"); //No output.  

http://p2p.wrox.com/java-espanol/29312-string-pooling.html

How to check if any Checkbox is checked in Angular

You can do something like:

function ChckbxsCtrl($scope, $filter) {
    $scope.chkbxs = [{
        label: "Led Zeppelin",
        val: false
    }, {
        label: "Electric Light Orchestra",
        val: false
    }, {
        label: "Mark Almond",
        val: false
    }];

    $scope.$watch("chkbxs", function(n, o) {
        var trues = $filter("filter")(n, {
            val: true
        });
        $scope.flag = trues.length;
    }, true);
}

And a template:

<div ng-controller="ChckbxsCtrl">
    <div ng-repeat="chk in chkbxs">
        <input type="checkbox" ng-model="chk.val" />
        <label>{{chk.label}}</label>
    </div>
    <div ng-show="flag">I'm ON when band choosed</div>
</div>

Working: http://jsfiddle.net/cherniv/JBwmA/

UPDATE: Or you can go little bit different way , without using $scope's $watch() method, like:

$scope.bandChoosed = function() {
    var trues = $filter("filter")($scope.chkbxs, {
        val: true
    });
    return trues.length;
}

And in a template do:

<div ng-show="bandChoosed()">I'm ON when band choosed</div>

Fiddle: http://jsfiddle.net/uzs4sgnp/

Get screen width and height in Android

Just use the function below that returns width and height of the screen size as an array of integers

private int[] getScreenSIze(){
        DisplayMetrics displaymetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        int h = displaymetrics.heightPixels;
        int w = displaymetrics.widthPixels;

        int[] size={w,h};
        return size;

    }

On your onCreate function or button click add the following code to output the screen sizes as shown below

 int[] screenSize= getScreenSIze();
        int width=screenSize[0];
        int height=screenSize[1];
        screenSizes.setText("Phone Screen sizes \n\n  width = "+width+" \n Height = "+height);

Netbeans 8.0.2 The module has not been deployed

Try to change Tomcat version, in my case tomcat "8.0.41" and "8.5.8" didn't work. But "8.5.37" worked fine.

Setting a max height on a table

You can do this by using the following css.

.scroll-thead{
    width: 100%;
    display: inline-table;
}

.scroll-tbody-y
{
    display: block;
    overflow-y: scroll;
}

.table-body{
    height: /*fix height here*/;
}

Following is the HTML.

<table>
 <thead class="scroll-thead">
          <tr> 
           <th>Key</th>
           <th>Value</th>
          </tr> 
         </thead>
         <tbody class="scroll-tbody-y table-body">
          <tr> 
          <td>Blah</td> 
          <td>Blah</td> 
          </tr> 
</tbody>
</table>

JSFiddle

Error checking for NULL in VBScript

I see lots of confusion in the comments. Null, IsNull() and vbNull are mainly used for database handling and normally not used in VBScript. If it is not explicitly stated in the documentation of the calling object/data, do not use it.

To test if a variable is uninitialized, use IsEmpty(). To test if a variable is uninitialized or contains "", test on "" or Empty. To test if a variable is an object, use IsObject and to see if this object has no reference test on Is Nothing.

In your case, you first want to test if the variable is an object, and then see if that variable is Nothing, because if it isn't an object, you get the "Object Required" error when you test on Nothing.

snippet to mix and match in your code:

If IsObject(provider) Then
    If Not provider Is Nothing Then
        ' Code to handle a NOT empty object / valid reference
    Else
        ' Code to handle an empty object / null reference
    End If
Else
    If IsEmpty(provider) Then
        ' Code to handle a not initialized variable or a variable explicitly set to empty
    ElseIf provider = "" Then
        ' Code to handle an empty variable (but initialized and set to "")
    Else
        ' Code to handle handle a filled variable
    End If
End If

How to remove an unpushed outgoing commit in Visual Studio?

Try to rebase your local master branch onto your remote/origin master branch and resolve any conflicts in the process.

Bootstrap Modal Backdrop Remaining

Using the code below continuously adds 7px padding on the body element every time you open and close a modal.

$('modalId').modal('hide');
$('body').removeClass('modal-open');
$('.modal-backdrop').remove();`

For those who still use Bootstrap 3, here is a hack'ish workaround.

$('#modalid').modal('hide');
$('.modal-backdrop').hide();
document.body.style.paddingRight = '0'
document.getElementsByTagName("body")[0].style.overflowY = "auto";

How to install PIP on Python 3.6?

I Used these commands in Centos 7

yum install python36
yum install python36-devel
yum install python36-pip
yum install python36-setuptools
easy_install-3.6 pip

to check the pip version:

pip3 -V
pip 18.0 from /usr/local/lib/python3.6/site-packages/pip-18.0-py3.6.egg/pip (python 3.6)

How to use shared memory with Linux in C

Here's a mmap example:

#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

/*
 * pvtmMmapAlloc - creates a memory mapped file area.  
 * The return value is a page-aligned memory value, or NULL if there is a failure.
 * Here's the list of arguments:
 * @mmapFileName - the name of the memory mapped file
 * @size - the size of the memory mapped file (should be a multiple of the system page for best performance)
 * @create - determines whether or not the area should be created.
 */
void* pvtmMmapAlloc (char * mmapFileName, size_t size, char create)  
{      
  void * retv = NULL;                                                                                              
  if (create)                                                                                         
  {                                                                                                   
    mode_t origMask = umask(0);                                                                       
    int mmapFd = open(mmapFileName, O_CREAT|O_RDWR, 00666);                                           
    umask(origMask);                                                                                  
    if (mmapFd < 0)                                                                                   
    {                                                                                                 
      perror("open mmapFd failed");                                                                   
      return NULL;                                                                                    
    }                                                                                                 
    if ((ftruncate(mmapFd, size) == 0))               
    {                                                                                                 
      int result = lseek(mmapFd, size - 1, SEEK_SET);               
      if (result == -1)                                                                               
      {                                                                                               
        perror("lseek mmapFd failed");                                                                
        close(mmapFd);                                                                                
        return NULL;                                                                                  
      }                                                                                               

      /* Something needs to be written at the end of the file to                                      
       * have the file actually have the new size.                                                    
       * Just writing an empty string at the current file position will do.                           
       * Note:                                                                                        
       *  - The current position in the file is at the end of the stretched                           
       *    file due to the call to lseek().  
              *  - The current position in the file is at the end of the stretched                    
       *    file due to the call to lseek().                                                          
       *  - An empty string is actually a single '\0' character, so a zero-byte                       
       *    will be written at the last byte of the file.                                             
       */                                                                                             
      result = write(mmapFd, "", 1);                                                                  
      if (result != 1)                                                                                
      {                                                                                               
        perror("write mmapFd failed");                                                                
        close(mmapFd);                                                                                
        return NULL;                                                                                  
      }                                                                                               
      retv  =  mmap(NULL, size,   
                  PROT_READ | PROT_WRITE, MAP_SHARED, mmapFd, 0);                                     

      if (retv == MAP_FAILED || retv == NULL)                                                         
      {                                                                                               
        perror("mmap");                                                                               
        close(mmapFd);                                                                                
        return NULL;                                                                                  
      }                                                                                               
    }                                                                                                 
  }                                                                                                   
  else                                                                                                
  {                                                                                                   
    int mmapFd = open(mmapFileName, O_RDWR, 00666);                                                   
    if (mmapFd < 0)                                                                                   
    {                                                                                                 
      return NULL;                                                                                    
    }                                                                                                 
    int result = lseek(mmapFd, 0, SEEK_END);                                                          
    if (result == -1)                                                                                 
    {                                                                                                 
      perror("lseek mmapFd failed");                  
      close(mmapFd);                                                                                  
      return NULL;                                                                                    
    }                                                                                                 
    if (result == 0)                                                                                  
    {                                                                                                 
      perror("The file has 0 bytes");                           
      close(mmapFd);                                                                                  
      return NULL;                                                                                    
    }                                                                                              
    retv  =  mmap(NULL, size,     
                PROT_READ | PROT_WRITE, MAP_SHARED, mmapFd, 0);                                       

    if (retv == MAP_FAILED || retv == NULL)                                                           
    {                                                                                                 
      perror("mmap");                                                                                 
      close(mmapFd);                                                                                  
      return NULL;                                                                                    
    }                                                                                                 

    close(mmapFd);                                                                                    

  }                                                                                                   
  return retv;                                                                                        
}                                                                                                     

Typescript Type 'string' is not assignable to type

I had a similar issue when passing props to a React Component.

Reason: My type inference on myArray wasn't working correctly

https://codesandbox.io/s/type-string-issue-fixed-z9jth?file=/src/App.tsx

Special thanks to Brady from Reactiflux for helping with this issue.

How to change the background color of the options menu?

This is how i solved mine. I just specified the background color and text color in styles. ie res > values > styles.xml file.

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:itemBackground">#ffffff</item>
    <item name="android:textColor">#000000</item>
</style>

Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' } js-bson: Failed to load c++ bson extension, using pure JS version

I've tried bson = require('../browser_build/bson'); but end up running into another error

Cannot set property 'BSON_BINARY_SUBTYPE_DEFAULT' of undefined

Finally I fixed this issue simply by npm update, this will fix the bson module in mongoose.

How to get jQuery dropdown value onchange event

$('#drop').change(
    function() {
        var val1 = $('#pick option:selected').val();
        var val2 = $('#drop option:selected').val();

        // Do something with val1 and val2 ...
    }
);

Update MongoDB field using value of another field

Apparently there is a way to do this efficiently since MongoDB 3.4, see styvane's answer.


Obsolete answer below

You cannot refer to the document itself in an update (yet). You'll need to iterate through the documents and update each document using a function. See this answer for an example, or this one for server-side eval().

How do I grep recursively?

ag is my favorite way to do this now github.com/ggreer/the_silver_searcher . It's basically the same thing as ack but with a few more optimizations.

Here's a short benchmark. I clear the cache before each test (cf https://askubuntu.com/questions/155768/how-do-i-clean-or-disable-the-memory-cache )

ryan@3G08$ sync && echo 3 | sudo tee /proc/sys/vm/drop_caches
3
ryan@3G08$ time grep -r "hey ya" .

real    0m9.458s
user    0m0.368s
sys 0m3.788s
ryan@3G08:$ sync && echo 3 | sudo tee /proc/sys/vm/drop_caches
3
ryan@3G08$ time ack-grep "hey ya" .

real    0m6.296s
user    0m0.716s
sys 0m1.056s
ryan@3G08$ sync && echo 3 | sudo tee /proc/sys/vm/drop_caches
3
ryan@3G08$ time ag "hey ya" .

real    0m5.641s
user    0m0.356s
sys 0m3.444s
ryan@3G08$ time ag "hey ya" . #test without first clearing cache

real    0m0.154s
user    0m0.224s
sys 0m0.172s

Disable keyboard on EditText

// only if you completely want to disable keyboard for 
// that particular edit text
your_edit_text = (EditText) findViewById(R.id.editText_1);
your_edit_text.setInputType(InputType.TYPE_NULL);

C++ for each, pulling from vector elements

C++ does not have the for_each loop feature in its syntax. You have to use c++11 or use the template function std::for_each.

struct Function {
    int input;
    Function(int input): input(input) {}
    void operator()(Attack& attack) {
        if(attack->m_num == input) attack->makeDamage();
    }
};
Function f(input);
std::for_each(m_attack.begin(), m_attack.end(), f);

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

Unfortunately, this is not currently possible in the latest version of DataContractJsonSerializer. See: http://connect.microsoft.com/VisualStudio/feedback/details/558686/datacontractjsonserializer-should-serialize-dictionary-k-v-as-a-json-associative-array

The current suggested workaround is to use the JavaScriptSerializer as Mark suggested above.

Good luck!

Spring - applicationContext.xml cannot be opened because it does not exist

I got the same error. I solved it moving the file applicationContext.xmlin a

sub-folder of the srcfolder. e.g:

context = new ClassPathXmlApplicationContext("/com/ejemplo/dao/applicationContext.xml");

Using :: in C++

The :: are used to dereference scopes.

const int x = 5;

namespace foo {
  const int x = 0;
}

int bar() {
  int x = 1;
  return x;
}

struct Meh {
  static const int x = 2;
}

int main() {
  std::cout << x; // => 5
  {
    int x = 4;
    std::cout << x; // => 4
    std::cout << ::x; // => 5, this one looks for x outside the current scope
  }
  std::cout << Meh::x; // => 2, use the definition of x inside the scope of Meh
  std::cout << foo::x; // => 0, use the definition of x inside foo
  std::cout << bar(); // => 1, use the definition of x inside bar (returned by bar)
}

unrelated: cout and cin are not functions, but instances of stream objects.

EDIT fixed as Keine Lust suggested

SyntaxError: Non-ASCII character '\xa3' in file when function returns '£'

Adding the following two lines at the top of my .py script worked for me (first line was necessary):

#!/usr/bin/env python
# -*- coding: utf-8 -*- 

Is there a simple way to remove unused dependencies from a maven pom.xml?

The Maven Dependency Plugin will help, especially the dependency:analyze goal:

dependency:analyze analyzes the dependencies of this project and determines which are: used and declared; used and undeclared; unused and declared.

Another thing that might help to do some cleanup is the Dependency Convergence report from the Maven Project Info Reports Plugin.

How to remove all .svn directories from my application directories

Alternatively, if you want to export a copy without modifying the working copy, you can use rsync:

rsync -a --exclude .svn path/to/working/copy path/to/export

PHP/MySQL Insert null values

For fields where NULL is acceptable, you could use var_export($var, true) to output the string, integer, or NULL literal. Note that you would not surround the output with quotes because they will be automatically added or omitted.

For example:

mysql_query("insert into table2 (f1, f2) values ('{$row['string_field']}', ".var_export($row['null_field'], true).")");

Android intent for playing video?

from the debug info, it seems that the VideoIntent from the MainActivity cannot send the path of the video to VideoActivity. It gives a NullPointerException error from the uriString. I think some of that code from VideoActivity:

Intent myIntent = getIntent();
String uri = myIntent.getStringExtra("uri");
Bundle b = myIntent.getExtras();

startVideo(b.getString(uri));

Cannot receive the uri from here:

public void playsquirrelmp4(View v) {
    Intent VideoIntent = (new Intent(this, VideoActivity.class));
    VideoIntent.putExtra("android.resource://" + getPackageName()
        + "/"+   R.raw.squirrel, uri);
    startActivity(VideoIntent);
}

IE8 css selector

I have a solution that I use only when I have to, after I build my html & css valid and working in most browsers, I do the occasional hack with this amazing piece of javascript from Rafael Lima. http://rafael.adm.br/css_browser_selector/

It keeps my CSS & HTML valid and clean, I know it's not the ideal solution, using javascript to fix hacks, but as long as your code is originally as close as possible (silly IE just breaks things sometimes) then moving something a few px with javascript isn't as big of a deal as some people think. Plus for time/cost reasons is a quick & easy fix.

How to printf a 64-bit integer as hex?

The warning from your compiler is telling you that your format specifier doesn't match the data type you're passing to it.

Try using %lx or %llx. For more portability, include inttypes.h and use the PRIx64 macro.

For example: printf("val = 0x%" PRIx64 "\n", val); (note that it's string concatenation)

How can I parse a local JSON file from assets folder into a ListView?

Using OKIO

public static String readJsonFromAssets(Context context, String filePath) {
    
        try {
            InputStream input = context.getAssets().open(filePath);
            BufferedSource source = Okio.buffer(Okio.source(input));
            return source.readByteString().string(Charset.forName("utf-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    
        return null;
}

and then...

String data = readJsonFromAssets(context, "json/some.json"); //here is my file inside the folder assets/json/some.json

Type reviewType = new TypeToken<List<Object>>() {}.getType();

if (data != null) {
    Object object = new Gson().fromJson(data, reviewType);
}

How to check if a python module exists without importing it

You can also use importlib directly

import importlib

try:
    importlib.import_module(module_name)
except ImportError:
    # Handle error

Notepad++: Multiple words search in a file (may be in different lines)?

<shameless-plug>

Search+ is a notepad++ plugin that does exactly this. You can download it from here and install it following the steps mentioned here

Feel free to post any issues/suggestions here.

</shameless-plug>

What is the list of valid @SuppressWarnings warning names in Java?

And this seems to be a much more complete list, where I found some warnings specific to Android-Studio that I couldn't find elsewhere (e.g. SynchronizeOnNonFinalField)

https://jazzy.id.au/2008/10/30/list_of_suppresswarnings_arguments.html

Oh, now SO's guidelines contraddict SO's restrictions. On one hand, I am supposed to copy the list rather than providing only the link. But on the other hand, this would exceed the maximum allowed number of characters. So let's just hope the link won't break.

Submitting a multidimensional array via POST with php

On submitting, you would get an array as if created like this:

$_POST['topdiameter'] = array( 'first value', 'second value' );
$_POST['bottomdiameter'] = array( 'first value', 'second value' );

However, I would suggest changing your form names to this format instead:

name="diameters[0][top]"
name="diameters[0][bottom]"
name="diameters[1][top]"
name="diameters[1][bottom]"
...

Using that format, it's much easier to loop through the values.

if ( isset( $_POST['diameters'] ) )
{
    echo '<table>';
    foreach ( $_POST['diameters'] as $diam )
    {
        // here you have access to $diam['top'] and $diam['bottom']
        echo '<tr>';
        echo '  <td>', $diam['top'], '</td>';
        echo '  <td>', $diam['bottom'], '</td>';
        echo '</tr>';
    }
    echo '</table>';
}

What is the keyguard in Android?

Yes, I also found it here: http://developer.android.com/tools/testing/activity_testing.html It's seems a key-input protection mechanism which includes the screen-lock, but not only includes it. According to this webpage, it also defines some key-input restriction for auto-test framework in Android.

Passing variable number of arguments around

You can try macro also.

#define NONE    0x00
#define DBG     0x1F
#define INFO    0x0F
#define ERR     0x07
#define EMR     0x03
#define CRIT    0x01

#define DEBUG_LEVEL ERR

#define WHERESTR "[FILE : %s, FUNC : %s, LINE : %d]: "
#define WHEREARG __FILE__,__func__,__LINE__
#define DEBUG(...)  fprintf(stderr, __VA_ARGS__)
#define DEBUG_PRINT(X, _fmt, ...)  if((DEBUG_LEVEL & X) == X) \
                                      DEBUG(WHERESTR _fmt, WHEREARG,__VA_ARGS__)

int main()
{
    int x=10;
    DEBUG_PRINT(DBG, "i am x %d\n", x);
    return 0;
}

How to convert NUM to INT in R?

Use as.integer:

set.seed(1)
x <- runif(5, 0, 100)
x
[1] 26.55087 37.21239 57.28534 90.82078 20.16819


as.integer(x)
[1] 26 37 57 90 20

Test for class:

xx <- as.integer(x)
str(xx)
 int [1:5] 26 37 57 90 20

Call a Subroutine from a different Module in VBA

Prefix the call with Module2 (ex. Module2.IDLE). I'm assuming since you asked this that you have IDLE defined multiple times in the project, otherwise this shouldn't be necessary.

How to apply a function to two columns of Pandas dataframe

I'm going to put in a vote for np.vectorize. It allows you to just shoot over x number of columns and not deal with the dataframe in the function, so it's great for functions you don't control or doing something like sending 2 columns and a constant into a function (i.e. col_1, col_2, 'foo').

import numpy as np
import pandas as pd

df = pd.DataFrame({'ID':['1','2','3'], 'col_1': [0,2,3], 'col_2':[1,4,5]})
mylist = ['a','b','c','d','e','f']

def get_sublist(sta,end):
    return mylist[sta:end+1]

#df['col_3'] = df[['col_1','col_2']].apply(get_sublist,axis=1)
# expect above to output df as below 

df.loc[:,'col_3'] = np.vectorize(get_sublist, otypes=["O"]) (df['col_1'], df['col_2'])


df

ID  col_1   col_2   col_3
0   1   0   1   [a, b]
1   2   2   4   [c, d, e]
2   3   3   5   [d, e, f]

How to use confirm using sweet alert?

inside your save button click add this code :

$("#btnSave").click(function (e) {
  e.preventDefault();
  swal("Are you sure?", {
    buttons: {
      yes: {
        text: "Yes",
        value: "yes"
      },
      no: {
        text: "No",
        value: "no"
      }
    }
  }).then((value) => {
    if (value === "yes") {
      // Add Your Custom Code for CRUD
    }
    return false;
  });
});

Python Dictionary contains List as Value - How to update?

Probably something like this:

original_list = dictionary.get('C1')
new_list = []
for item in original_list:
  new_list.append(item+10)
dictionary['C1'] = new_list

Can't install laravel installer via composer

For PHP7.1 install this

sudo apt-get install php7.1-zip

What dependency is missing for org.springframework.web.bind.annotation.RequestMapping?

This solution WORKS , I had the same issue and after hours I came up to this:

(1) Go to your pom.xml

(2) Add this Dependency :

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>4.1.6.RELEASE</version>
    </dependency>


(3) Run your Project

Xcode5 "No matching provisioning profiles found issue" (but good at xcode4)

Don't forget to change profile in Provision Profile sections: enter image description here

Ideally you should see Automatic in Code Signing Identity after you choose provision profile you need. If you don't see any option that's mean you don't have private key for current provision profile.

Calculate execution time of a SQL query?

Please use

-- turn on statistics IO for IO related 
SET STATISTICS IO ON 
GO

and for time calculation use

SET STATISTICS TIME ON
GO

then It will give result for every query . In messages window near query input window.

Building a fat jar using maven

You can use the maven-shade-plugin.

After configuring the shade plugin in your build the command mvn package will create one single jar with all dependencies merged into it.

String's Maximum length in Java - calling length() method

java.io.DataInput.readUTF() and java.io.DataOutput.writeUTF(String) say that a String object is represented by two bytes of length information and the modified UTF-8 representation of every character in the string. This concludes that the length of String is limited by the number of bytes of the modified UTF-8 representation of the string when used with DataInput and DataOutput.

In addition, The specification of CONSTANT_Utf8_info found in the Java virtual machine specification defines the structure as follows.

CONSTANT_Utf8_info {
    u1 tag;
    u2 length;
    u1 bytes[length];
}

You can find that the size of 'length' is two bytes.

That the return type of a certain method (e.g. String.length()) is int does not always mean that its allowed maximum value is Integer.MAX_VALUE. Instead, in most cases, int is chosen just for performance reasons. The Java language specification says that integers whose size is smaller than that of int are converted to int before calculation (if my memory serves me correctly) and it is one reason to choose int when there is no special reason.

The maximum length at compilation time is at most 65536. Note again that the length is the number of bytes of the modified UTF-8 representation, not the number of characters in a String object.

String objects may be able to have much more characters at runtime. However, if you want to use String objects with DataInput and DataOutput interfaces, it is better to avoid using too long String objects. I found this limitation when I implemented Objective-C equivalents of DataInput.readUTF() and DataOutput.writeUTF(String).

creating batch script to unzip a file without additional zip tools

Here's my overview about built-in zi/unzip (compress/decompress) capabilities in windows - How can I compress (/ zip ) and uncompress (/ unzip ) files and folders with batch file without using any external tools?

To unzip file you can use this script :

zipjs.bat unzip -source C:\myDir\myZip.zip -destination C:\MyDir -keep yes -force no

Send form data using ajax

you can use serialize method of jquery to get form values. Try like this

<form action="target.php" method="post" >
<input type="text" name="lname" />
<input type="text" name="fname" />
<input type="buttom" name ="send" onclick="return f(this.form) " >
</form>

function f( form ){
    var formData = $(form).serialize();
    att=form.attr("action") ;
    $.post(att, formData).done(function(data){
        alert(data);
    });
    return true;
}

JPA OneToMany not deleting child

You can try this:

@OneToOne(cascade = CascadeType.REFRESH) 

or

@OneToMany(cascade = CascadeType.REFRESH)

Javascript can't find element by id?

The script is performed before the DOM of the body is built. Put it all into a function and call it from the onload of the body-element.

Getting Git to work with a proxy server - fails with "Request timed out"

Setting git proxy on terminal

if

  • you do not want set proxy for each of your git projects manually, one by one
  • always want to use same proxy for all your projects

Set it globally once

git config --global http.proxy username:password@proxy_url:proxy_port
git config --global https.proxy username:password@proxy_url:proxy_port

if you want to set proxy for only one git project (there may be some situations where you may not want to use same proxy or any proxy at all for some git connections)

//go to project root
cd /bla_bla/project_root
//set proxy for both http and https
git config http.proxy username:password@proxy_url:proxy_port
git config https.proxy username:password@proxy_url:proxy_port

if you want to display current proxy settings

git config --list 

if you want to remove proxy globally

git config --global --unset http.proxy
git config --global --unset https.proxy

if you want to remove proxy for only one git root

//go to project root
cd /bla-bla/project_root
git config --unset http.proxy
git config --unset https.proxy

Set background color of WPF Textbox in C# code

You can use hex colors:

your_contorl.Color = DirectCast(ColorConverter.ConvertFromString("#D8E0A627"), Color)

how to write an array to a file Java

private static void saveArrayToFile(String fileName, int[] array) throws IOException {
    Files.write( // write to file
        Paths.get(fileName), // get path from file
        Collections.singleton(Arrays.toString(array)), // transform array to collection using singleton
        Charset.forName("UTF-8") // formatting
    );
}

jquery to loop through table rows and cells, where checkob is checked, concatenate

Try this:

function createcodes() {

    $('.authors-list tr').each(function () {
        //processing this row
        //how to process each cell(table td) where there is checkbox
        $(this).find('td input:checked').each(function () {

             // it is checked, your code here...
        });
    });
}

Attach the Source in Eclipse of a jar

Eclipse is showing no source found because there is no source available . Your jar only has the compiled classes.

You need to import the project from jar and add the Project as dependency .

Other option is to go to the

Go to Properties (for the Project) -> Java Build Path -> Libraries , select your jar file and click on the source , there will be option to attach the source and Javadocs.

How can I capitalize the first letter of each word in a string?

In case you want to downsize

# Assuming you are opening a new file
with open(input_file) as file:
    lines = [x for x in reader(file) if x]

# for loop to parse the file by line
for line in lines:
    name = [x.strip().lower() for x in line if x]
    print(name) # Check the result

How can I create a "Please Wait, Loading..." animation using jQuery?

You could do this various different ways. It could be a subtle as a small status on the page saying "Loading...", or as loud as an entire element graying out the page while the new data is loading. The approach I'm taking below will show you how to accomplish both methods.

The Setup

Let's start by getting us a nice "loading" animation from http://ajaxload.info I'll be using enter image description here

Let's create an element that we can show/hide anytime we're making an ajax request:

<div class="modal"><!-- Place at bottom of page --></div>

The CSS

Next let's give it some flair:

/* Start by setting display:none to make this hidden.
   Then we position it in relation to the viewport window
   with position:fixed. Width, height, top and left speak
   for themselves. Background we set to 80% white with
   our animation centered, and no-repeating */
.modal {
    display:    none;
    position:   fixed;
    z-index:    1000;
    top:        0;
    left:       0;
    height:     100%;
    width:      100%;
    background: rgba( 255, 255, 255, .8 ) 
                url('http://i.stack.imgur.com/FhHRx.gif') 
                50% 50% 
                no-repeat;
}

/* When the body has the loading class, we turn
   the scrollbar off with overflow:hidden */
body.loading .modal {
    overflow: hidden;   
}

/* Anytime the body has the loading class, our
   modal element will be visible */
body.loading .modal {
    display: block;
}

And finally, the jQuery

Alright, on to the jQuery. This next part is actually really simple:

$body = $("body");

$(document).on({
    ajaxStart: function() { $body.addClass("loading");    },
     ajaxStop: function() { $body.removeClass("loading"); }    
});

That's it! We're attaching some events to the body element anytime the ajaxStart or ajaxStop events are fired. When an ajax event starts, we add the "loading" class to the body. and when events are done, we remove the "loading" class from the body.

See it in action: http://jsfiddle.net/VpDUG/4952/

Using CSS to insert text

Just code it like this:

.OwnerJoe {
  //other things here
  &:before{
    content: "Joe's Task: ";
  }
}

Playing m3u8 Files with HTML Video Tag

You can use video js library for easily play HLS video's. It allows to directly play videos

<!-- CSS  -->
 <link href="https://vjs.zencdn.net/7.2.3/video-js.css" rel="stylesheet">


<!-- HTML -->
<video id='hls-example'  class="video-js vjs-default-skin" width="400" height="300" controls>
<source type="application/x-mpegURL" src="http://www.streambox.fr/playlists/test_001/stream.m3u8">
</video>


<!-- JS code -->
<!-- If you'd like to support IE8 (for Video.js versions prior to v7) -->
<script src="https://vjs.zencdn.net/ie8/ie8-version/videojs-ie8.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/videojs-contrib-hls/5.14.1/videojs-contrib-hls.js"></script>
<script src="https://vjs.zencdn.net/7.2.3/video.js"></script>

<script>
var player = videojs('hls-example');
player.play();
</script>

GitHub Video Js

R: Print list to a text file

I solve this problem by mixing the solutions above.

sink("/Users/my/myTest.dat")
writeLines(unlist(lapply(k, paste, collapse=" ")))
sink()

I think it works well

How do I localize the jQuery UI Datepicker?

just in case anyone is STILL stuck on this, despite the other answers, I solved this with:

$.datepicker.setDefaults($.datepicker.regional['en-GB']);

note the extra 'GB'. After that it worked fine.

How to check for palindrome using Python logic

import string

word = input('Please select a word to test \n')
word = word.lower()
num = len(word)

x = round((len(word)-1)/2)
#defines first half of string
first = word[:x]

#reverse second half of string
def reverse_odd(text):
    lst = []
    count = 1
    for i in range(x+1, len(text)):

        lst.append(text[len(text)-count])
        count += 1
    lst = ''.join(lst)
    return lst

#reverse second half of string
def reverse_even(text):
    lst = []
    count = 1
    for i in range(x, len(text)):
        lst.append(text[len(text)-count])
        count += 1
    lst = ''.join(lst)
    return lst


if reverse_odd(word) == first or reverse_even(word) == first:
    print(string.capwords(word), 'is a palindrome')
else:
    print(string.capwords(word), 'is not a palindrome')

Maven artifact and groupId naming

Consider this to get a fully unique jar file:

  • GroupID - com.companyname.project
  • ArtifactId - com-companyname-project
  • Package - com.companyname.project

Rename Oracle Table or View

To rename a table you can use:

RENAME mytable TO othertable;

or

ALTER TABLE mytable RENAME TO othertable;

or, if owned by another schema:

ALTER TABLE owner.mytable RENAME TO othertable;

Interestingly, ALTER VIEW does not support renaming a view. You can, however:

RENAME myview TO otherview;

The RENAME command works for tables, views, sequences and private synonyms, for your own schema only.

If the view is not in your schema, you can recompile the view with the new name and then drop the old view.

(tested in Oracle 10g)

Visual Studio 2010 always thinks project is out of date, but nothing has changed

For me it was the presence of a non-existing header file on "Header Files" inside the project. After removing this entry (right-click > Exclude from Project) first time recompiled, then directly

========== Build: 0 succeeded, 0 failed, 5 up-to-date, 0 skipped ==========

and no attempt of rebuilding without modification was done. I think is a check-before-build implemented by VS2010 (not sure if documented, could be) which triggers the "AlwaysCreate" flag.

Storing integer values as constants in Enum manner in java

The most common valid reason for wanting an integer constant associated with each enum value is to interoperate with some other component which still expects those integers (e.g. a serialization protocol which you can't change, or the enums represent columns in a table, etc).

In almost all cases I suggest using an EnumMap instead. It decouples the components more completely, if that was the concern, or if the enums represent column indices or something similar, you can easily make changes later on (or even at runtime if need be).

 private final EnumMap<Page, Integer> pageIndexes = new EnumMap<Page, Integer>(Page.class);
 pageIndexes.put(Page.SIGN_CREATE, 1);
 //etc., ...

 int createIndex = pageIndexes.get(Page.SIGN_CREATE);

It's typically incredibly efficient, too.

Adding data like this to the enum instance itself can be very powerful, but is more often than not abused.

Edit: Just realized Bloch addressed this in Effective Java / 2nd edition, in Item 33: Use EnumMap instead of ordinal indexing.

Sort a list of lists with a custom compare function

You need to slightly modify your compare function and use functools.cmp_to_key to pass it to sorted. Example code:

import functools

lst = [list(range(i, i+5)) for i in range(5, 1, -1)]

def fitness(item):
    return item[0]+item[1]+item[2]+item[3]+item[4]
def compare(item1, item2):
    return fitness(item1) - fitness(item2)

sorted(lst, key=functools.cmp_to_key(compare))

Output:

[[2, 3, 4, 5, 6], [3, 4, 5, 6, 7], [4, 5, 6, 7, 8], [5, 6, 7, 8, 9]]

Works :)

Filtering a list of strings based on contents

mylist = ['a', 'ab', 'abc']
assert 'ab' in mylist

Else clause on Python while statement

In reply to Is there a specific reason?, here is one interesting application: breaking out of multiple levels of looping.

Here is how it works: the outer loop has a break at the end, so it would only be executed once. However, if the inner loop completes (finds no divisor), then it reaches the else statement and the outer break is never reached. This way, a break in the inner loop will break out of both loops, rather than just one.

for k in [2, 3, 5, 7, 11, 13, 17, 25]:
    for m in range(2, 10):
        if k == m:
            continue
        print 'trying %s %% %s' % (k, m)
        if k % m == 0:
            print 'found a divisor: %d %% %d; breaking out of loop' % (k, m)
            break
    else:
        continue
    print 'breaking another level of loop'
    break
else:
    print 'no divisor could be found!'

For both while and for loops, the else statement is executed at the end, unless break was used.

In most cases there are better ways to do this (wrapping it into a function or raising an exception), but this works!

What does if __name__ == "__main__": do?

Consider:

if __name__ == "__main__":
    main()

It checks if the __name__ attribute of the Python script is "__main__". In other words, if the program itself is executed, the attribute will be __main__, so the program will be executed (in this case the main() function).

However, if your Python script is used by a module, any code outside of the if statement will be executed, so if \__name__ == "\__main__" is used just to check if the program is used as a module or not, and therefore decides whether to run the code.

XPath to select multiple tags

Not sure if this helps, but with XSL, I'd do something like:

<xsl:for-each select="a/b">
    <xsl:value-of select="c"/>
    <xsl:value-of select="d"/>
    <xsl:value-of select="e"/>
</xsl:for-each>

and won't this XPath select all children of B nodes:

a/b/*

How can I exclude a directory from Visual Studio Code "Explore" tab?

There's this Explorer Exclude extension that exactly does this. https://marketplace.visualstudio.com/items?itemName=RedVanWorkshop.explorer-exclude-vscode-extension

It adds an option to hide current folder/file to the right click menu. It also adds a vertical tab Hidden Items to explorer menu where you can see currently hidden files & folders and can toggle them easily.


enter image description here

How to specify maven's distributionManagement organisation wide?

The best solution for this is to create a simple parent pom file project (with packaging 'pom') generically for all projects from your organization.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>your.company</groupId>
    <artifactId>company-parent</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>pom</packaging>

    <distributionManagement>
        <repository>
            <id>nexus-site</id>
            <url>http://central_nexus/server</url>
        </repository>
    </distributionManagement>

</project>

This can be built, released, and deployed to your local nexus so everyone has access to its artifact.

Now for all projects which you wish to use it, simply include this section:

<parent>
  <groupId>your.company</groupId>
  <artifactId>company-parent</artifactId>
  <version>1.0.0</version>
</parent>

This solution will allow you to easily add other common things to all your company's projects. For instance if you wanted to standardize your JUnit usage to a specific version, this would be the perfect place for that.

If you have projects that use multi-module structures that have their own parent, Maven also supports chaining inheritance so it is perfectly acceptable to make your project's parent pom file refer to your company's parent pom and have the project's child modules not even aware of your company's parent.

I see from your example project structure that you are attempting to put your parent project at the same level as your aggregator pom. If your project needs its own parent, the best approach I have found is to include the parent at the same level as the rest of the modules and have your aggregator pom.xml file at the root of where all your modules' directories exist.

- pom.xml (aggregator)
    - project-parent
    - project-module1
    - project-module2

What you do with this structure is include your parent module in the aggregator and build everything with a mvn install from the root directory.

We use this exact solution at my organization and it has stood the test of time and worked quite well for us.

How do I find the distance between two points?

dist = sqrt( (x2 - x1)**2 + (y2 - y1)**2 )

As others have pointed out, you can also use the equivalent built-in math.hypot():

dist = math.hypot(x2 - x1, y2 - y1)

How to use && in EL boolean expressions in Facelets?

In addition to the answer of BalusC, use the following Java RegExp to replace && with and:

Search:  (#\{[^\}]*)(&&)([^\}]*\})
Replace: $1and$3

You have run this regular expression replacement multiple times to find all occurences in case you are using >2 literals in your EL expressions. Mind to replace the leading # by $ if your EL expression syntax differs.

How to create an empty array in Swift?

you can remove the array content with passing the array index or you can remove all

    var array = [String]()
    print(array)
    array.append("MY NAME")
    print(array)
    array.removeFirst()
    print(array)
    array.append("MY NAME")
    array.removeLast()
    array.append("MY NAME1")
    array.append("MY NAME2")
    print(array)
    array.removeAll()
    print(array)

How to get multiple counts with one SQL query?

One way which works for sure

SELECT a.distributor_id,
    (SELECT COUNT(*) FROM myTable WHERE level='personal' and distributor_id = a.distributor_id) as PersonalCount,
    (SELECT COUNT(*) FROM myTable WHERE level='exec' and distributor_id = a.distributor_id) as ExecCount,
    (SELECT COUNT(*) FROM myTable WHERE distributor_id = a.distributor_id) as TotalCount
FROM (SELECT DISTINCT distributor_id FROM myTable) a ;

EDIT:
See @KevinBalmforth's break down of performance for why you likely don't want to use this method and instead should opt for @Taryn?'s answer. I'm leaving this so people can understand their options.

How to delete multiple values from a vector?

First we can define a new operator,

"%ni%" = Negate( "%in%" )

Then, its like x not in remove

x <- 1:10
remove <- c(2,3,5)
x <- x[ x %ni% remove ]

or why to go for remove, go directly

x <- x[ x %ni% c(2,3,5)]

How to return 2 values from a Java method?

you have to use collections to return more then one return values

in your case you write your code as

public static List something(){
        List<Integer> list = new ArrayList<Integer>();
        int number1 = 1;
        int number2 = 2;
        list.add(number1);
        list.add(number2);
        return list;
    }

    // Main class code
    public static void main(String[] args) {
      something();
      List<Integer> numList = something();
    }

ASP.NET MVC on IIS 7.5

I was also receiving this error and discovered that "HTTP Redirection" was not turned on in Windows Server. This blog post points this out as well: http://blogs.msdn.com/b/rjacobs/archive/2010/06/30/system-web-routing-routetable-not-working-with-iis.aspx

Timestamp to human readable format

var newDate = new Date();
newDate.setTime(unixtime*1000);
dateString = newDate.toUTCString();

Where unixtime is the time returned by your sql db. Here is a fiddle if it helps.

For example, using it for the current time:

_x000D_
_x000D_
document.write( new Date().toUTCString() );
_x000D_
_x000D_
_x000D_

Multi-line strings in PHP

$xml="l\rn";
$xml.="vv";

echo $xml;

But you should really look into http://us3.php.net/simplexml

How do you loop through each line in a text file using a windows batch file?

The accepted answer is good, but has two limitations.
It drops empty lines and lines beginning with ;

To read lines of any content, you need the delayed expansion toggling technic.

@echo off
SETLOCAL DisableDelayedExpansion
FOR /F "usebackq delims=" %%a in (`"findstr /n ^^ text.txt"`) do (
    set "var=%%a"
    SETLOCAL EnableDelayedExpansion
    set "var=!var:*:=!"
    echo(!var!
    ENDLOCAL
)

Findstr is used to prefix each line with the line number and a colon, so empty lines aren't empty anymore.

DelayedExpansion needs to be disabled, when accessing the %%a parameter, else exclamation marks ! and carets ^ will be lost, as they have special meanings in that mode.

But to remove the line number from the line, the delayed expansion needs to be enabled.
set "var=!var:*:=!" removes all up to the first colon (using delims=: would remove also all colons at the beginning of a line, not only the one from findstr).
The endlocal disables the delayed expansion again for the next line.

The only limitation is now the line length limit of ~8191, but there seems no way to overcome this.

How do I bind Twitter Bootstrap tooltips to dynamically created elements?

Try this one:

$('body').tooltip({
    selector: '[rel=tooltip]'
});

Order a List (C#) by many fields?

Your object should implement the IComparable interface.

With it your class becomes a new function called CompareTo(T other). Within this function you can make any comparison between the current and the other object and return an integer value about if the first is greater, smaller or equal to the second one.

Open popup and refresh parent page on close popup

If your app runs on an HTML5 enabled browser. You can use postMessage. The example given there is quite similar to yours.

How to remove focus around buttons on click

Another possible solution is to add a class using a Javascript listener when the user clicks on the button and then remove that class on focus with another listener. This maintains accessibility (visible tabbing) while also preventing Chrome's quirky behaviour of considering a button focused when clicked.

JS:

$('button').click(function(){
    $(this).addClass('clicked');
});
$('button').focus(function(){
    $(this).removeClass('clicked');
});

CSS:

button:focus {
    outline: 1px dotted #000;
}
button.clicked {
    outline: none;
}

Full example here: https://jsfiddle.net/4bbb37fh/

Get everything after the dash in a string in JavaScript

var the_string = "sometext-20202";
var parts = the_string.split('-', 2);

// After calling split(), 'parts' is an array with two elements:
// parts[0] is 'sometext'
// parts[1] is '20202'

var the_text = parts[0];
var the_num  = parts[1];

How can I multiply and divide using only bit shifting and adding?

A procedure for dividing integers that uses shifts and adds can be derived in straightforward fashion from decimal longhand division as taught in elementary school. The selection of each quotient digit is simplified, as the digit is either 0 and 1: if the current remainder is greater than or equal to the divisor, the least significant bit of the partial quotient is 1.

Just as with decimal longhand division, the digits of the dividend are considered from most significant to least significant, one digit at a time. This is easily accomplished by a left shift in binary division. Also, quotient bits are gathered by left shifting the current quotient bits by one position, then appending the new quotient bit.

In a classical arrangement, these two left shifts are combined into left shifting of one register pair. The upper half holds the current remainder, the lower half initial holds the dividend. As the dividend bits are transferred to the remainder register by left shift, the unused least significant bits of the lower half are used to accumulate the quotient bits.

Below is x86 assembly language and C implementations of this algorithm. This particular variant of a shift & add division is sometimes referred to as the "no-performing" variant, as the subtraction of the divisor from the current remainder is not performed unless the remainder is greater than or equal to the divisor. In C, there is no notion of the carry flag used by the assembly version in the register pair left shift. Instead, it is emulated, based on the observation that the result of an addition modulo 2n can be smaller that either addend only if there was a carry out.

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

#define USE_ASM 0

#if USE_ASM
uint32_t bitwise_division (uint32_t dividend, uint32_t divisor)
{
    uint32_t quot;
    __asm {
        mov  eax, [dividend];// quot = dividend
        mov  ecx, [divisor]; // divisor
        mov  edx, 32;        // bits_left
        mov  ebx, 0;         // rem
    $div_loop:
        add  eax, eax;       // (rem:quot) << 1
        adc  ebx, ebx;       //  ...
        cmp  ebx, ecx;       // rem >= divisor ?
        jb  $quot_bit_is_0;  // if (rem < divisor)
    $quot_bit_is_1:          // 
        sub  ebx, ecx;       // rem = rem - divisor
        add  eax, 1;         // quot++
    $quot_bit_is_0:
        dec  edx;            // bits_left--
        jnz  $div_loop;      // while (bits_left)
        mov  [quot], eax;    // quot
    }            
    return quot;
}
#else
uint32_t bitwise_division (uint32_t dividend, uint32_t divisor)
{
    uint32_t quot, rem, t;
    int bits_left = CHAR_BIT * sizeof (uint32_t);

    quot = dividend;
    rem = 0;
    do {
            // (rem:quot) << 1
            t = quot;
            quot = quot + quot;
            rem = rem + rem + (quot < t);

            if (rem >= divisor) {
                rem = rem - divisor;
                quot = quot + 1;
            }
            bits_left--;
    } while (bits_left);
    return quot;
}
#endif

CSS horizontal centering of a fixed div?

Here's a flexbox solution when using a full screen wrapper div. justify-content centers it's child div horizontally and align-items centers it vertically.

<div class="full-screen-wrapper">
    <div class="center"> //... content</div>
</div>

.full-screen-wrapper { 
  position: fixed;
  display: flex;
  justify-content: center;
  width: 100vw;
  height: 100vh;
  top: 0;
  align-items: center;
}

.center {
  // your styles
}

What is a difference between unsigned int and signed int in C?

The C standard specifies that unsigned numbers will be stored in binary. (With optional padding bits). Signed numbers can be stored in one of three formats: Magnitude and sign; two's complement or one's complement. Interestingly that rules out certain other representations like Excess-n or Base -2.

However on most machines and compilers store signed numbers in 2's complement.

int is normally 16 or 32 bits. The standard says that int should be whatever is most efficient for the underlying processor, as long as it is >= short and <= long then it is allowed by the standard.

On some machines and OSs history has causes int not to be the best size for the current iteration of hardware however.

convert:not authorized `aaaa` @ error/constitute.c/ReadImage/453

I use many times the ImageMagic convert command to convert *.tif files to *.pdf files.

I don't know why but today I began to receive the following error:

convert: not authorized `a.pdf' @ error/constitute.c/WriteImage/1028.

After issuing the command:

convert a.tif a.pdf

After reading the above answers I edited the file /etc/ImageMagick-6/policy.xml

and changed the line:

policy domain="coder" rights="none" pattern="PDF" 

to

policy domain="coder" rights="read|write" pattern="PDF"

and now everything works fine.

I have "ImageMagick 6.8.9-9 Q16 x86_64 2018-09-28" on "Ubuntu 16.04.5 LTS".

Determine whether a key is present in a dictionary

if 'name' in mydict:

is the preferred, pythonic version. Use of has_key() is discouraged, and this method has been removed in Python 3.

Serializing/deserializing with memory stream

This code works for me:

public void Run()
{
    Dog myDog = new Dog();
    myDog.Name= "Foo";
    myDog.Color = DogColor.Brown;

    System.Console.WriteLine("{0}", myDog.ToString());

    MemoryStream stream = SerializeToStream(myDog);

    Dog newDog = (Dog)DeserializeFromStream(stream);

    System.Console.WriteLine("{0}", newDog.ToString());
}

Where the types are like this:

[Serializable]
public enum DogColor
{
    Brown,
    Black,
    Mottled
}

[Serializable]
public class Dog
{
    public String Name
    {
        get; set;
    }

    public DogColor Color
    {
        get;set;
    }

    public override String ToString()
    {
        return String.Format("Dog: {0}/{1}", Name, Color);
    }
}

and the utility methods are:

public static MemoryStream SerializeToStream(object o)
{
    MemoryStream stream = new MemoryStream();
    IFormatter formatter = new BinaryFormatter();
    formatter.Serialize(stream, o);
    return stream;
}

public static object DeserializeFromStream(MemoryStream stream)
{
    IFormatter formatter = new BinaryFormatter();
    stream.Seek(0, SeekOrigin.Begin);
    object o = formatter.Deserialize(stream);
    return o;
}

Is there a way to use SVG as content in a pseudo element :before or :after

.myDiv {
  display: flex;
  align-items: center;
}

.myDiv:before {
  display: inline-block;
  content: url(./dog.svg);
  margin-right: 15px;
  width: 10px;
}

How can I do an OrderBy with a dynamic string parameter?

In one answer above:

The simplest & the best solution:

mylist.OrderBy(s => s.GetType().GetProperty("PropertyName").GetValue(s));

There is an syntax error, ,null must be added:

mylist.OrderBy(s => s.GetType().GetProperty("PropertyName").GetValue(s,null));

The type or namespace name does not exist in the namespace 'System.Web.Mvc'

I have a project that does this whenever I build with the View open. As soon as I closed the view, the error goes away and the build succeeds. Very strange.

Create a data.frame with m columns and 2 rows

Does m really need to be a data.frame() or will a matrix() suffice?

m <- matrix(0, ncol = 30, nrow = 2)

You can wrap a data.frame() around that if you need to:

m <- data.frame(m)

or all in one line: m <- data.frame(matrix(0, ncol = 30, nrow = 2))

Jquery and HTML FormData returns "Uncaught TypeError: Illegal invocation"

I had the same problem

I fixed that by using two options

contentType: false
processData: false

Actually I Added these two command to my $.ajax({}) function

Run Button is Disabled in Android Studio

If your IDE is in power save mode, then the run button etc. are also disabled.

You can verify this via the file -> power save mode, make sure it is disabled.

Disable power save mode to enable the run button

Python logging: use milliseconds in time format

If you are using arrow or if you don't mind using arrow. You can substitute python's time formatting for arrow's one.

import logging

from arrow.arrow import Arrow


class ArrowTimeFormatter(logging.Formatter):

    def formatTime(self, record, datefmt=None):
        arrow_time = Arrow.fromtimestamp(record.created)

        if datefmt:
            arrow_time = arrow_time.format(datefmt)

        return str(arrow_time)


logger = logging.getLogger(__name__)

default_handler = logging.StreamHandler()
default_handler.setFormatter(ArrowTimeFormatter(
    fmt='%(asctime)s',
    datefmt='YYYY-MM-DD HH:mm:ss.SSS'
))

logger.setLevel(logging.DEBUG)
logger.addHandler(default_handler)

Now you can use all of arrow's time formatting in datefmt attribute.

Local dependency in package.json

npm >= 2.0.0

This feature was implemented in the version 2.0.0 of npm. Example:

{
  "name": "baz",
  "dependencies": {
    "bar": "file:../foo/bar"
  }
}

Any of the following paths are also valid:

../foo/bar
~/foo/bar
./foo/bar
/foo/bar

The local package will be copied to the prefix (./node-modules).

npm < 2.0.0

Put somelocallib as dependency in your package.json as normal:

"dependencies": {
  "somelocallib": "0.0.x"
}

Then run npm link ../somelocallib and npm will install the version you're working on as a symlink.

[email protected] /private/tmp/app
+-- [email protected] -> /private/tmp/somelocallib

Reference: link(1)

Intercept and override HTTP requests from WebView

Here is my solution I use for my app.

I have several asset folder with css / js / img anf font files.

The application gets all filenames and looks if a file with this name is requested. If yes, it loads it from asset folder.

//get list of files of specific asset folder
        private ArrayList listAssetFiles(String path) {

            List myArrayList = new ArrayList();
            String [] list;
            try {
                list = getAssets().list(path);
                for(String f1 : list){
                    myArrayList.add(f1);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return (ArrayList) myArrayList;
        }

        //get mime type by url
        public String getMimeType(String url) {
            String type = null;
            String extension = MimeTypeMap.getFileExtensionFromUrl(url);
            if (extension != null) {
                if (extension.equals("js")) {
                    return "text/javascript";
                }
                else if (extension.equals("woff")) {
                    return "application/font-woff";
                }
                else if (extension.equals("woff2")) {
                    return "application/font-woff2";
                }
                else if (extension.equals("ttf")) {
                    return "application/x-font-ttf";
                }
                else if (extension.equals("eot")) {
                    return "application/vnd.ms-fontobject";
                }
                else if (extension.equals("svg")) {
                    return "image/svg+xml";
                }
                type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
            }
            return type;
        }

        //return webresourceresponse
        public WebResourceResponse loadFilesFromAssetFolder (String folder, String url) {
            List myArrayList = listAssetFiles(folder);
            for (Object str : myArrayList) {
                if (url.contains((CharSequence) str)) {
                    try {
                        Log.i(TAG2, "File:" + str);
                        Log.i(TAG2, "MIME:" + getMimeType(url));
                        return new WebResourceResponse(getMimeType(url), "UTF-8", getAssets().open(String.valueOf(folder+"/" + str)));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return null;
        }

        //@TargetApi(Build.VERSION_CODES.LOLLIPOP)
        @SuppressLint("NewApi")
        @Override
        public WebResourceResponse shouldInterceptRequest(final WebView view, String url) {
            //Log.i(TAG2, "SHOULD OVERRIDE INIT");
            //String url = webResourceRequest.getUrl().toString();
            String extension = MimeTypeMap.getFileExtensionFromUrl(url);
            //I have some folders for files with the same extension
            if (extension.equals("css") || extension.equals("js") || extension.equals("img")) {
                return loadFilesFromAssetFolder(extension, url);
            }
            //more possible extensions for font folder
            if (extension.equals("woff") || extension.equals("woff2") || extension.equals("ttf") || extension.equals("svg") || extension.equals("eot")) {
                return loadFilesFromAssetFolder("font", url);
            }

            return null;
        }

Where is Java Installed on Mac OS X?

You could use echo $(/usr/libexec/java_home) command in your terminal to know the path where Java being installed.

Renaming files in a folder to sequential numbers

Sorted by time, limited to jpg, leading zeroes and a basename (in case you likely want one):

ls -t *.jpg | cat -n |                                           \
while read n f; do mv "$f" "$(printf thumb_%04d.jpg $n)"; done

(all on one line, without the \)