Programs & Examples On #Lpc

Refers to a line of ARM-based microcontrollers by NXP Semiconductors.

AWS CLI S3 A client error (403) occurred when calling the HeadObject operation: Forbidden

I got this error with a mis-configured test event. I changed the source buckets ARN but forgot to edit the default S3 bucket name.

I.e. make sure that in the bucket section of the test event both the ARN and bucket name are set correctly:

"bucket": {
  "arn": "arn:aws:s3:::your_bucket_name",
  "name": "your_bucket_name",
  "ownerIdentity": {
    "principalId": "EXAMPLE"
  }

Error LNK2019 unresolved external symbol _main referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ)

Old thread but for me it started working (after following all advise above) when i renamed int main(void) to int wmain(void) and removed WIN23 from cmake's add_executable().

DSO missing from command line

DSO here means Dynamic Shared Object; since the error message says it's missing from the command line, I guess you have to add it to the command line.

That is, try adding -lpthread to your command line.

Bootstrap 3 .img-responsive images are not responsive inside fieldset in FireFox

add condition only firefox in your custom css file.

/* only Firefox */
@-moz-document url-prefix() {
   .img-responsive, .thumbnail>img, .thumbnail a>img, .carousel-inner>.item>img, .carousel-inner>.item>a>img {
      width: 100%;
   }
}

json: cannot unmarshal object into Go value of type

Here's a fixed version of it: http://play.golang.org/p/w2ZcOzGHKR

The biggest fix that was needed is when Unmarshalling an array, that property needs to be an array/slice in the struct as well.

For example:

{ "things": ["a", "b", "c"] }

Would Unmarshal into a:

type Item struct {
    Things []string
}

And not into:

type Item struct {
    Things string
}

The other thing to watch out for when Unmarshaling is that the types line up exactly. It will fail when Unmarshalling a JSON string representation of a number into an int or float field -- "1" needs to Unmarshal into a string, not into an int like we saw with ShippingAdditionalCost int

Portable way to check if directory exists [Windows/Linux, C]

stat() works on Linux., UNIX and Windows as well:

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

struct stat info;

if( stat( pathname, &info ) != 0 )
    printf( "cannot access %s\n", pathname );
else if( info.st_mode & S_IFDIR )  // S_ISDIR() doesn't exist on my windows 
    printf( "%s is a directory\n", pathname );
else
    printf( "%s is no directory\n", pathname );

Losing scope when using ng-include

Instead of using this as the accepted answer suggests, use $parent instead. So in your partial1.htmlyou'll have:

<form ng-submit="$parent.addLine()">
    <input type="text" ng-model="$parent.lineText" size="30" placeholder="Type your message here">
</form>

If you want to learn more about the scope in ng-include or other directives, check this out: https://github.com/angular/angular.js/wiki/Understanding-Scopes#ng-include

Unable to begin a distributed transaction

If the servers are clustered and there is a clustered DTC you have to disable security on the clustered DTC not the local DTC.

Send Message in C#

It doesn't sound like a good idea to use send message. I think you should try to work around the problem that the DLLs can't reference each other...

How to use Python's "easy_install" on Windows ... it's not so easy

If you are using windows 7 64-bit version, then the solution is found here: http://pypi.python.org/pypi/setuptools

namely, you need to download a python script, run it, and then easy_install will work normally from commandline.

P.S. I agree with the original poster saying that this should work out of the box.

What's the best way to center your HTML email content in the browser window (or email client preview pane)?

table align="center" ... this aligns the table center of page.

Using td align="center" centers the content inside that td, useful for centered aligned text but you will have issues with some email clients centering content in sub level tables so using using td align as a top level method of centering your "container" table on the page is not the way to do it. Use table align instead.

Still use your 100% wrapper table too, purely as a wrapper for the body, as some email clients don't display body background colors but it will show it with the 100% table, so add your body color to both body and the 100% table.

I could go on and on for ages about all the quirks of html email dev. All I can say is test test and test again. Litmus.com is a great tool for testing emails.

The more you do the more you will learn about what works in what email clients.

Hope this helps.

What does LPCWSTR stand for and how should it be handled with?

LPCWSTR stands for "Long Pointer to Constant Wide String". The W stands for Wide and means that the string is stored in a 2 byte character vs. the normal char. Common for any C/C++ code that has to deal with non-ASCII only strings.=

To get a normal C literal string to assign to a LPCWSTR, you need to prefix it with L

LPCWSTR a = L"TestWindow";

What is exactly the base pointer and stack pointer? To what do they point?

You have it right. The stack pointer points to the top item on the stack and the base pointer points to the "previous" top of the stack before the function was called.

When you call a function, any local variable will be stored on the stack and the stack pointer will be incremented. When you return from the function, all the local variables on the stack go out of scope. You do this by setting the stack pointer back to the base pointer (which was the "previous" top before the function call).

Doing memory allocation this way is very, very fast and efficient.

How to convert std::string to LPCSTR?

The MultiByteToWideChar answer that Charles Bailey gave is the correct one. Because LPCWSTR is just a typedef for const WCHAR*, widestr in the example code there can be used wherever a LPWSTR is expected or where a LPCWSTR is expected.

One minor tweak would be to use std::vector<WCHAR> instead of a manually managed array:

// using vector, buffer is deallocated when function ends
std::vector<WCHAR> widestr(bufferlen + 1);

::MultiByteToWideChar(CP_ACP, 0, instr.c_str(), instr.size(), &widestr[0], bufferlen);

// Ensure wide string is null terminated
widestr[bufferlen] = 0;

// no need to delete; handled by vector

Also, if you need to work with wide strings to start with, you can use std::wstring instead of std::string. If you want to work with the Windows TCHAR type, you can use std::basic_string<TCHAR>. Converting from std::wstring to LPCWSTR or from std::basic_string<TCHAR> to LPCTSTR is just a matter of calling c_str. It's when you're changing between ANSI and UTF-16 characters that MultiByteToWideChar (and its inverse WideCharToMultiByte) comes into the picture.

Why can templates only be implemented in the header file?

Just to add something noteworthy here. One can define methods of a templated class just fine in the implementation file when they are not function templates.


myQueue.hpp:

template <class T> 
class QueueA {
    int size;
    ...
public:
    template <class T> T dequeue() {
       // implementation here
    }

    bool isEmpty();

    ...
}    

myQueue.cpp:

// implementation of regular methods goes like this:
template <class T> bool QueueA<T>::isEmpty() {
    return this->size == 0;
}


main()
{
    QueueA<char> Q;

    ...
}

LPCSTR, LPCTSTR and LPTSTR

Quick and dirty:

LP == Long Pointer. Just think pointer or char*

C = Const, in this case, I think they mean the character string is a const, not the pointer being const.

STR is string

the T is for a wide character or char (TCHAR) depending on compile options.

Internet Access in Ubuntu on VirtualBox

I could get away with the following solution (works with Ubuntu 14 guest VM on Windows 7 host or Ubuntu 9.10 Casper guest VM on host Windows XP x86):

  1. Go to network connections -> Virtual Box Host-Only Network -> Select "Properties"
  2. Check VirtualBox Bridged Networking Driver
  3. Come to VirtualBox Manager, choose the network adapter as Bridged Adapter and Name to the device in Step #1.
  4. Restart the VM.

How to convert std::string to LPCWSTR in C++ (Unicode)

If you are in an ATL/MFC environment, You can use the ATL conversion macro:

#include <atlbase.h>
#include <atlconv.h>

. . .

string myStr("My string");
CA2W unicodeStr(myStr);

You can then use unicodeStr as an LPCWSTR. The memory for the unicode string is created on the stack and released then the destructor for unicodeStr executes.

How to cast the size_t to double or int C++

You can use Boost numeric_cast.

This throws an exception if the source value is out of range of the destination type, but it doesn't detect loss of precision when converting to double.

Whatever function you use, though, you should decide what you want to happen in the case where the value in the size_t is greater than INT_MAX. If you want to detect it use numeric_cast or write your own code to check. If you somehow know that it cannot possibly happen then you could use static_cast to suppress the warning without the cost of a runtime check, but in most cases the cost doesn't matter anyway.

How to convert Rows to Columns in Oracle?

 select * FROM doc_tab
    PIVOT
    (
    Min(document_id)
    FOR document_type IN ('Voters ID','Pan card','Drivers licence')
    ) 

outputs as this

enter image description here

sql fiddle demo here

How do I keep a label centered in WinForms?

Some minor additional content for setting programmatically:

Label textLabel = new Label() { 
        AutoSize = false, 
        TextAlign = ContentAlignment.MiddleCenter, 
        Dock = DockStyle.None, 
        Left = 10, 
        Width = myDialog.Width - 10
};            

Dockstyle and Content alignment may differ from your needs. For example, for a simple label on a wpf form I use DockStyle.None.

Commit empty folder structure (with git)

Recursively create .gitkeep files

find . -type d -empty -not -path "./.git/*" -exec touch {}/.gitkeep \;

What's wrong with overridable method calls in constructors?

Here's an example which helps to understand this:

public class Main {
    static abstract class A {
        abstract void foo();
        A() {
            System.out.println("Constructing A");
            foo();
        }
    }

    static class C extends A {
        C() { 
            System.out.println("Constructing C");
        }
        void foo() { 
            System.out.println("Using C"); 
        }
    }

    public static void main(String[] args) {
        C c = new C(); 
    }
}

If you run this code, you get the following output:

Constructing A
Using C
Constructing C

You see? foo() makes use of C before C's constructor has been run. If foo() requires C to have a defined state (i.e. the constructor has finished), then it will encounter an undefined state in C and things might break. And since you can't know in A what the overwritten foo() expects, you get a warning.

dll missing in JDBC

Friends I had the same problem because of the different bit version Make sure following point * Your jdk bit 64 or 32 * Your Path for sqljdbc_4.0\enu\auth\x64 or x86 this directory depend on your jdk bit * sqljdbc_auth.dll select this file based on your bit x64 or x86 and put this in system32 folder and it will works for me

Allow Access-Control-Allow-Origin header using HTML5 fetch API

I know this is an older post, but I found what worked for me to fix this error was using the IP address of my server instead of using the domain name within my fetch request. So for example:

#(original) var request = new Request('https://davidwalsh.name/demo/arsenal.json');
#use IP instead
var request = new Request('https://0.0.0.0/demo/arsenal.json');

fetch(request).then(function(response) {
    // Convert to JSON
    return response.json();
}).then(function(j) {
    // Yay, `j` is a JavaScript object
    console.log(JSON.stringify(j));
}).catch(function(error) {
    console.log('Request failed', error)
});

Set opacity of background image without affecting child elements

You can put the image in the div:after or div:before and set the opacity on that "virtual div"

div:after {
  background: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/3/owl1.jpg);
  opacity: 0.25;
}

found here http://css-tricks.com/snippets/css/transparent-background-images/

Get current time in hours and minutes

date +%H:%M

Would be easier, I think :). If you really wanted to chop off the seconds, you could have done

date | sed 's/.* \([0-9]*:[0-9]*\):[0-9]*.*/\1/'

MongoDB query with an 'or' condition

Using a $where query will be slow, in part because it can't use indexes. For this sort of problem, I think it would be better to store a high value for the "expires" field that will naturally always be greater than Now(). You can either store a very high date millions of years in the future, or use a separate type to indicate never. The cross-type sort order is defined at here.

An empty Regex or MaxKey (if you language supports it) are both good choices.

What is the use of ObservableCollection in .net?

Explanation without Code

For those wanting an answer without any code behind it (boom-tish) with a story (to help you remember):

Normal Collections - No Notifications

Every now and then I go to NYC and my wife asks me to buy stuff. So I take a shopping list with me. The list has a lot of things on there like:

  1. Louis Vuitton handbag ($5000)
  2. Clive Christian’s Imperial Majesty Perfume ($215,000 )
  3. Gucci Sunglasses ($2000)

hahaha well I"m not buying that stuff. So I cross them off and remove them from the list and I add instead:

  1. 12 dozen Titleist golf balls.
  2. 12 lb bowling ball.

So I usually come home without the goods and she's never pleased. The thing is that she doesn't know about what i take off the list and what I add onto it; she gets no notifications.

The ObservableCollection - notifications when changes made

Now, whenever I remove something from the list: she get's a notification on her phone (i.e. sms / email etc)!

The observable collection works just the same way. If you add or remove something to or from it: someone is notified. And when they are notified, well then they call you and you'll get a ear-full. Of course the consequences are customisable via the event handler.

That sums it all up!

How to make android listview scrollable?

This is my working code. you may try with this.

row.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/listEmployeeDetails"
        android:layout_height="match_parent" 
        android:layout_width="match_parent"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="5dp"
        android:layout_gravity="center"
        android:background="#ffffff">

        <TextView android:id="@+id/tvEmpId"
                      android:layout_height="wrap_content"
                      android:textSize="12sp"
                      android:padding="2dp"
                      android:layout_width="0dp"
                      android:layout_weight="0.3"/>
            <TextView android:id="@+id/tvNameEmp"
                      android:layout_height="wrap_content"
                      android:textSize="12sp"                     
                      android:padding="2dp"
                      android:layout_width="0dp"
                      android:layout_weight="0.5"/>
             <TextView
                    android:layout_height="wrap_content"
                    android:id="@+id/tvStatusEmp"
                    android:textSize="12sp"
                    android:padding="2dp"
                    android:layout_width="0dp"
                    android:layout_weight="0.2"/>               
</LinearLayout> 

details.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/listEmployeeDetails"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/page_bg"
    android:orientation="vertical" >
    <LinearLayout
        android:id="@+id/lLayoutGrid"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/page_bg"
        android:orientation="vertical" >

        ................... others components here............................

        <ListView
            android:id="@+id/listView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:alwaysDrawnWithCache="true"
            android:dividerHeight="1dp"
            android:horizontalSpacing="3dp"
            android:scrollingCache="true"
            android:smoothScrollbar="true"
            android:stretchMode="columnWidth"
            android:verticalSpacing="3dp" 
            android:layout_marginBottom="30dp">
        </ListView>
    </LinearLayout>
</RelativeLayout>

Adapter class :

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class ListViewAdapter extends BaseAdapter {
    private Context context;
    private List<EmployeeBean> employeeList; 

    publicListViewAdapter(Context context, List<EmployeeBean> employeeList) {
            this.context = context;
            this.employeeList = employeeList;
        }

    public View getView(int position, View convertView, ViewGroup parent) {
            View row = convertView;
            EmployeeBeanHolder holder = null;
            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            row = inflater.inflate(R.layout.row, parent, false);

            holder = new EmployeeBeanHolder();
            holder.employeeBean = employeeList.get(position);
            holder.tvEmpId = (TextView) row.findViewById(R.id.tvEmpId);
            holder.tvName = (TextView) row.findViewById(R.id.tvNameEmp);
            holder.tvStatus = (TextView) row.findViewById(R.id.tvStatusEmp);

            row.setTag(holder);
            holder.tvEmpId.setText(holder.employeeBean.getEmpId());
            holder.tvName.setText(holder.employeeBean.getName());
            holder.tvStatus.setText(holder.employeeBean.getStatus());

             if (position % 2 == 0) {
                    row.setBackgroundColor(Color.rgb(213, 229, 241));
                } else {                    
                    row.setBackgroundColor(Color.rgb(255, 255, 255));
                }        

            return row;
        }

   public static class EmployeeBeanHolder {
        EmployeeBean employeeBean;
        TextView tvEmpId;
        TextView tvName;
        TextView tvStatus;
    }

    @Override
    public int getCount() {
            return employeeList.size();
        }

    @Override
    public Object getItem(int position) {
            return null;
        }

    @Override
    public long getItemId(int position) {
            return 0;
    }
}

employee bean class:

public class EmployeeBean {
    private String empId;
    private String name;
    private String status;

    public EmployeeBean(){      
    }

    public EmployeeBean(String empId, String name, String status) {
        this.empId= empId;
        this.name = name;
        this.status = status;
    }

    public String getEmpId() {
        return empId;
    }

    public void setEmpId(String empId) {
        this.empId= empId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status =status;
    }
}

in Activity class:

onCreate method:

public static List<EmployeeBean> EMPLOYEE_LIST = new ArrayList<EmployeeBean>();

//create emplyee data
for(int i=0;i<=10;i++) {
  EmployeeBean emplyee = new EmployeeBean("EmpId"+i,"Name "+i, "Active");
  EMPLOYEE_LIST .add(emplyee );
}

ListView listView;
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(new ListViewAdapter(this, EMPLOYEE_LIST));

How to change the time format (12/24 hours) of an <input>?

Support of this type is still very poor. Opera shows it in a way you want. Chrome 23 shows it with seconds and AM/PM, in 24 version (dev branch at this moment) it will rid of seconds (if possible), but no information about AM/PM.
It's not want you possibly want, but at this point the only option I see to achieve your time picker format is usage of javascript.

Find a value anywhere in a database

Based on bnkdev's answer I modified Narayana's Code to search all columns even numeric ones.

It'll run slower, but this version actually finds all matches not just those found in text columns.

I can't thank this guy enough. Saved me days of searching by hand!

CREATE PROC SearchAllTables 
(
@SearchStr nvarchar(100)
)
AS
BEGIN

-- Copyright © 2002 Narayana Vyas Kondreddi. All rights reserved.
-- Purpose: To search all columns of all tables for a given search string
-- Written by: Narayana Vyas Kondreddi
-- Site: http://vyaskn.tripod.com
-- Tested on: SQL Server 7.0 and SQL Server 2000
-- Date modified: 28th July 2002 22:50 GMT


CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))

SET NOCOUNT ON

DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
SET  @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')

WHILE @TableName IS NOT NULL
BEGIN
    SET @ColumnName = ''
    SET @TableName = 
    (
        SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
        FROM    INFORMATION_SCHEMA.TABLES
        WHERE       TABLE_TYPE = 'BASE TABLE'
            AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
            AND OBJECTPROPERTY(
                    OBJECT_ID(
                        QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
                         ), 'IsMSShipped'
                           ) = 0
    )

    WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
    BEGIN
        SET @ColumnName =
        (
            SELECT MIN(QUOTENAME(COLUMN_NAME))
            FROM    INFORMATION_SCHEMA.COLUMNS
            WHERE       TABLE_SCHEMA    = PARSENAME(@TableName, 2)
                AND TABLE_NAME  = PARSENAME(@TableName, 1)                  
                AND QUOTENAME(COLUMN_NAME) > @ColumnName
        )

        IF @ColumnName IS NOT NULL
        BEGIN
            INSERT INTO #Results
            EXEC
            (
                'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(CONVERT(varchar(max), ' + @ColumnName + '), 3630) 
                FROM ' + @TableName + ' (NOLOCK) ' +
                ' WHERE CONVERT(varchar(max), ' + @ColumnName + ') LIKE ' + @SearchStr2
            )
        END
    END 
END

SELECT ColumnName, ColumnValue FROM #Results
END

Send response to all clients except sender

Here is a more complete answer about what has changed from 0.9.x to 1.x.

 // send to current request socket client
 socket.emit('message', "this is a test");// Hasn't changed

 // sending to all clients, include sender
 io.sockets.emit('message', "this is a test"); // Old way, still compatible
 io.emit('message', 'this is a test');// New way, works only in 1.x

 // sending to all clients except sender
 socket.broadcast.emit('message', "this is a test");// Hasn't changed

 // sending to all clients in 'game' room(channel) except sender
 socket.broadcast.to('game').emit('message', 'nice game');// Hasn't changed

 // sending to all clients in 'game' room(channel), include sender
 io.sockets.in('game').emit('message', 'cool game');// Old way, DOES NOT WORK ANYMORE
 io.in('game').emit('message', 'cool game');// New way
 io.to('game').emit('message', 'cool game');// New way, "in" or "to" are the exact same: "And then simply use to or in (they are the same) when broadcasting or emitting:" from http://socket.io/docs/rooms-and-namespaces/

 // sending to individual socketid, socketid is like a room
 io.sockets.socket(socketid).emit('message', 'for your eyes only');// Old way, DOES NOT WORK ANYMORE
 socket.broadcast.to(socketid).emit('message', 'for your eyes only');// New way

I wanted to edit the post of @soyuka but my edit was rejected by peer-review.

How can I stop Chrome from going into debug mode?

You have multiple Google Chrome browser tabs open for the same URL and developer toolbar.

In some other tab, you have set breakpoints which are showing up when you are debugging in the current tab.

Solution: Close the developer toolbar in the other tab or the tab itself.

GSON throwing "Expected BEGIN_OBJECT but was BEGIN_ARRAY"?

public ChannelSearchEnum[] getChannelSearchEnum(Response response) {
        return response.as(ChannelSearchEnum[].class, ObjectMapperType.GSON);
}

Above will solve and passing response will returned mapped object array of the class

How do I prevent and/or handle a StackOverflowException?

If you application depends on 3d-party code (in Xsl-scripts) then you have to decide first do you want to defend from bugs in them or not. If you really want to defend then I think you should execute your logic which prone to external errors in separate AppDomains. Catching StackOverflowException is not good.

Check also this question.

Maven error in eclipse (pom.xml) : Failure to transfer org.apache.maven.plugins:maven-surefire-plugin:pom:2.12.4

You need just to follow those steps:

  1. Right Click on your project: Run (As) -> Maven clean
  2. Right Click on your project: Run (As) -> Maven install

After which, if the build fails when you do Maven Install, it means there is no web.xml file under WEB-INF or some problem associated with it. it really works

How to move the layout up when the soft keyboard is shown android

I solve this by adding code into manifest:

<activity android:name=".Login"
        android:fitsSystemWindows="true"
        android:windowSoftInputMode="stateHidden|adjustPan"
</activity>

jQuery - find table row containing table cell containing specific text

I know this is an old post but I thought I could share an alternative [not as robust, but simpler] approach to searching for a string in a table.

$("tr:contains(needle)"); //where needle is the text you are searching for.

For example, if you are searching for the text 'box', that would be:

$("tr:contains('box')");

This would return all the elements with this text. Additional criteria could be used to narrow it down if it returns multiple elements

Rails: How can I rename a database column in a Ruby on Rails migration?

I'm on rails 5.2, and trying to rename a column on a devise User.

the rename_column bit worked for me, but the singular :table_name threw a "User table not found" error. Plural worked for me.

rails g RenameAgentinUser

Then change migration file to this:

rename_column :users, :agent?, :agent

Where :agent? is the old column name.

Overriding !important style

I believe the only way to do this it to add the style as a new CSS declaration with the '!important' suffix. The easiest way to do this is to append a new <style> element to the head of document:

function addNewStyle(newStyle) {
    var styleElement = document.getElementById('styles_js');
    if (!styleElement) {
        styleElement = document.createElement('style');
        styleElement.type = 'text/css';
        styleElement.id = 'styles_js';
        document.getElementsByTagName('head')[0].appendChild(styleElement);
    }
    styleElement.appendChild(document.createTextNode(newStyle));
}

addNewStyle('td.EvenRow a {display:inline !important;}')

The rules added with the above method will (if you use the !important suffix) override other previously set styling. If you're not using the suffix then make sure to take concepts like 'specificity' into account.

Create a 3D matrix

I use Octave, but Matlab has the same syntax.

Create 3d matrix:

octave:3> m = ones(2,3,2)
m =

ans(:,:,1) =

   1   1   1
   1   1   1

ans(:,:,2) =

   1   1   1
   1   1   1

Now, say I have a 2D matrix that I want to expand in a new dimension:

octave:4> Two_D = ones(2,3)
Two_D =
   1   1   1
   1   1   1

I can expand it by creating a 3D matrix, setting the first 2D in it to my old (here I have size two of the third dimension):

octave:11> Three_D = zeros(2,3,2)
Three_D =

ans(:,:,1) =

   0   0   0
   0   0   0

ans(:,:,2) =

   0   0   0
   0   0   0



octave:12> Three_D(:,:,1) = Two_D
Three_D =

ans(:,:,1) =

   1   1   1
   1   1   1

ans(:,:,2) =

   0   0   0
   0   0   0

How do I insert a drop-down menu for a simple Windows Forms app in Visual Studio 2008?

You can use a ComboBox with its ComboBoxStyle (appears as DropDownStyle in later versions) set to DropDownList. See: http://msdn.microsoft.com/en-us/library/system.windows.forms.comboboxstyle.aspx

SQL comment header examples

-------------------------------------------------------------------------------
-- Author       name
-- Created      date
-- Purpose      description of the business/technical purpose
--              using multiple lines as needed
-- Copyright © yyyy, Company Name, All Rights Reserved
-------------------------------------------------------------------------------
-- Modification History
--
-- 01/01/0000  developer full name  
--      A comprehensive description of the changes. The description may use as 
--      many lines as needed.
-------------------------------------------------------------------------------

How can I scroll a div to be visible in ReactJS?

I assume that you have some sort of List component and some sort of Item component. The way I did it in one project was to let the item know if it was active or not; the item would ask the list to scroll it into view if necessary. Consider the following pseudocode:

class List extends React.Component {
  render() {
    return <div>{this.props.items.map(this.renderItem)}</div>;
  }

  renderItem(item) {
    return <Item key={item.id} item={item}
                 active={item.id === this.props.activeId}
                 scrollIntoView={this.scrollElementIntoViewIfNeeded} />
  }

  scrollElementIntoViewIfNeeded(domNode) {
    var containerDomNode = React.findDOMNode(this);
    // Determine if `domNode` fully fits inside `containerDomNode`.
    // If not, set the container's scrollTop appropriately.
  }
}

class Item extends React.Component {
  render() {
    return <div>something...</div>;
  }

  componentDidMount() {
    this.ensureVisible();
  }

  componentDidUpdate() {
    this.ensureVisible();
  }

  ensureVisible() {
    if (this.props.active) {
      this.props.scrollIntoView(React.findDOMNode(this));
    }
  }
}

A better solution is probably to make the list responsible for scrolling the item into view (without the item being aware that it's even in a list). To do so, you could add a ref attribute to a certain item and find it with that:

class List extends React.Component {
  render() {
    return <div>{this.props.items.map(this.renderItem)}</div>;
  }

  renderItem(item) {
    var active = item.id === this.props.activeId;
    var props = {
      key: item.id,
      item: item,
      active: active
    };
    if (active) {
      props.ref = "activeItem";
    }
    return <Item {...props} />
  }

  componentDidUpdate(prevProps) {
    // only scroll into view if the active item changed last render
    if (this.props.activeId !== prevProps.activeId) {
      this.ensureActiveItemVisible();
    }
  }

  ensureActiveItemVisible() {
    var itemComponent = this.refs.activeItem;
    if (itemComponent) {
      var domNode = React.findDOMNode(itemComponent);
      this.scrollElementIntoViewIfNeeded(domNode);
    }
  }

  scrollElementIntoViewIfNeeded(domNode) {
    var containerDomNode = React.findDOMNode(this);
    // Determine if `domNode` fully fits inside `containerDomNode`.
    // If not, set the container's scrollTop appropriately.
  }
}

If you don't want to do the math to determine if the item is visible inside the list node, you could use the DOM method scrollIntoView() or the Webkit-specific scrollIntoViewIfNeeded, which has a polyfill available so you can use it in non-Webkit browsers.

In Python how should I test if a variable is None, True or False

Don't fear the Exception! Having your program just log and continue is as easy as:

try:
    result = simulate(open("myfile"))
except SimulationException as sim_exc:
    print "error parsing stream", sim_exc
else:
    if result:
        print "result pass"
    else:
        print "result fail"

# execution continues from here, regardless of exception or not

And now you can have a much richer type of notification from the simulate method as to what exactly went wrong, in case you find error/no-error not to be informative enough.

Should I use @EJB or @Inject

@Inject can inject any bean, while @EJB can only inject EJBs. You can use either to inject EJBs, but I'd prefer @Inject everywhere.

nuget 'packages' element is not declared warning

None of the answers will solve your problem permanently. If you go to the path of adding XSD (From Xml menu, select "Create schema"), you will end up having problems with the package manager as it will clean up your packages.config file when you add a new package.

The best solution is just ignore by closing the file when you don't use it.

What does "implements" do on a class?

Implements means that it takes on the designated behavior that the interface specifies. Consider the following interface:

public interface ISpeak
{
   public String talk();
}

public class Dog implements ISpeak
{
   public String talk()
   {
        return "bark!";
   }
}

public class Cat implements ISpeak
{
    public String talk()
    {
        return "meow!";
    }
}

Both the Cat and Dog class implement the ISpeak interface.

What's great about interfaces is that we can now refer to instances of this class through the ISpeak interface. Consider the following example:

  Dog dog = new Dog();
  Cat cat = new Cat();

  List<ISpeak> animalsThatTalk = new ArrayList<ISpeak>();

  animalsThatTalk.add(dog);
  animalsThatTalk.add(cat);

  for (ISpeak ispeak : animalsThatTalk)
  {
      System.out.println(ispeak.talk());
  }

The output for this loop would be:

bark!
meow!

Interface provide a means to interact with classes in a generic way based upon the things they do without exposing what the implementing classes are.

One of the most common interfaces used in Java, for example, is Comparable. If your object implements this interface, you can write an implementation that consumers can use to sort your objects.

For example:

public class Person implements Comparable<Person>
{
  private String firstName;
  private String lastName;

  // Getters/Setters

  public int compareTo(Person p)
  {
    return this.lastName.compareTo(p.getLastName());  
  }
}

Now consider this code:

//  Some code in other class

List<Person> people = getPeopleList();

Collections.sort(people);

What this code did was provide a natural ordering to the Person class. Because we implemented the Comparable interface, we were able to leverage the Collections.sort() method to sort our List of Person objects by its natural ordering, in this case, by last name.

Determine the type of an object?

type() is a better solution than isinstance(), particularly for booleans:

True and False are just keywords that mean 1 and 0 in python. Thus,

isinstance(True, int)

and

isinstance(False, int)

both return True. Both booleans are an instance of an integer. type(), however, is more clever:

type(True) == int

returns False.

How can I give access to a private GitHub repository?

If you are the owner it is simple:

  • Go to your repo and click the Settings button.
  • In the left menu click Collaborators
  • Then Add their name.

Then collaborator should visit this example repo link https://github.com/user/repo/invitations

Source: Github Docs.

What regular expression will match valid international phone numbers?

For iOS SWIFT I found this helpful,

let phoneRegEx = "^((\\+)|(00)|(\\*)|())[0-9]{3,14}((\\#)|())$"

Creating watermark using html and css

I would recommend everyone look into CSS grids. It has been supported by most browsers now since about 2017. Here is a link to some documentation: https://css-tricks.com/snippets/css/complete-guide-grid/ . It is so much easier to keep your page elements where you want them, especially when it comes to responsiveness. It took me all of 20 minutes to learn how to do it, and I'm a newbie!

<div class="grid-div">
    <p class="hello">Hello</p>
    <p class="world">World</p>
</div>


//begin css//

.grid-div {
    display: grid;
    grid-template-columns: 50% 50%;
    grid-template-rows: 50% 50%;
}

.hello {
    grid-column-start: 2;
    grid-row-start: 2;
}

.world {
    grid-column-start: 1;
    grid-row-start: 2;
}

This code will split the page into 4 equal quadrants, placing the "Hello" in the bottom right, and the "World" in the bottom left without having to change their positioning or playing with margins.

This can be extrapolated into very complex grid layouts with overlapping, infinite grids of all sizes, and even grids nested inside grids, without losing control of your elements every time something changes (MS Word I'm looking at you).

Hope this helps whoever still needs it!

Items in JSON object are out of order using "json.dumps"?

hey i know it is so late for this answer but add sort_keys and assign false to it as follows :

json.dumps({'****': ***},sort_keys=False)

this worked for me

Best dynamic JavaScript/JQuery Grid

you can try http://datatables.net/

DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, based upon the foundations of progressive enhancement, which will add advanced interaction controls to any HTML table. Key features:

  • Variable length pagination
  • On-the-fly filtering
  • Multi-column sorting with data type detection
  • Smart handling of column widths
  • Display data from almost any data source
  • DOM, Javascript array, Ajax file and server-side processing (PHP, C#, Perl, Ruby, AIR, Gears etc)
  • Scrolling options for table viewport
  • Fully internationalisable
  • jQuery UI ThemeRoller support
  • Rock solid - backed by a suite of 2600+ unit tests
  • Wide variety of plug-ins inc. TableTools, FixedColumns, KeyTable and more
  • It's free!
  • State saving
  • Hidden columns
  • Dynamic creation of tables
  • Ajax auto loading of data
  • Custom DOM positioning
  • Single column filtering
  • Alternative pagination types
  • Non-destructive DOM interaction
  • Sorting column(s) highlighting
  • Advanced data source options
  • Extensive plug-in support
  • Sorting, type detection, API functions, pagination and filtering
  • Fully themeable by CSS
  • Solid documentation
  • 110+ pre-built examples
  • Full support for Adobe AIR

How to get the current location latitude and longitude in android

You can use following class as service class to run your application in background

import java.util.Timer;
import java.util.TimerTask;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.widget.Toast;

public class MyService extends Service {

    private GPSTracker gpsTracker;
    private Handler handler= new Handler();
    private Timer timer = new Timer();
    private Distance pastDistance = new Distance();
     private Distance currentDistance = new Distance();
    public static double DISTANCE;
    boolean flag = true ;
    private double totalDistance ;
    @Override
    @Deprecated
    public void onStart(Intent intent, int startId) {

        super.onStart(intent, startId);
        gpsTracker = new GPSTracker(HomeFragment.HOMECONTEXT);
        TimerTask timerTask = new TimerTask() {

            @Override
            public void run() {
                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        if(flag){
                            pastDistance.setLatitude(gpsTracker.getLocation().getLatitude());
                            pastDistance.setLongitude(gpsTracker.getLocation().getLongitude());
                            flag = false;
                        }else{
                            currentDistance.setLatitude(gpsTracker.getLocation().getLatitude());
                            currentDistance.setLongitude(gpsTracker.getLocation().getLongitude());
                            flag = comapre_LatitudeLongitude();
                        }
                        Toast.makeText(HomeFragment.HOMECONTEXT, "latitude:"+gpsTracker.getLocation().getLatitude(), 4000).show();

                    }
                });


            }
        };

        timer.schedule(timerTask,0, 5000);

    }

    private double distance(double lat1, double lon1, double lat2, double lon2) {
          double theta = lon1 - lon2;
          double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
          dist = Math.acos(dist);
          dist = rad2deg(dist);
          dist = dist * 60 * 1.1515;
           return (dist);
        }

       private double deg2rad(double deg) {
          return (deg * Math.PI / 180.0);
        }
       private double rad2deg(double rad) {
          return (rad * 180.0 / Math.PI);
   }


    @Override
    public IBinder onBind(Intent intent) {

        return null;
    }



    @Override
    public void onDestroy() {

        super.onDestroy();
        System.out.println("--------------------------------onDestroy -stop service ");
        timer.cancel();
        DISTANCE = totalDistance ;
    }
    public boolean comapre_LatitudeLongitude(){

        if(pastDistance.getLatitude() == currentDistance.getLatitude() && pastDistance.getLongitude() == currentDistance.getLongitude()){
            return false;
        }else{

            final double distance = distance(pastDistance.getLatitude(),pastDistance.getLongitude(),currentDistance.getLatitude(),currentDistance.getLongitude());
            System.out.println("Distance in mile :"+distance);
            handler.post(new Runnable() {

                @Override
                public void run() {
                    float kilometer=1.609344f;

                    totalDistance = totalDistance +  distance * kilometer;
                    DISTANCE = totalDistance;
                    //Toast.makeText(HomeFragment.HOMECONTEXT, "distance in km:"+DISTANCE, 4000).show();

                }
            });

            return true;
        }

    }

}

Add One another class to get location

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

public class GPSTracker implements LocationListener {
private final Context mContext;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location = null; 
double latitude; 
double longitude; 

private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

protected LocationManager locationManager;
private Location m_Location;
 public GPSTracker(Context context) {
    this.mContext = context;
    m_Location = getLocation();
    System.out.println("location Latitude:"+m_Location.getLatitude());
    System.out.println("location Longitude:"+m_Location.getLongitude());
    System.out.println("getLocation():"+getLocation());
    }

public Location getLocation() {
    try {
        locationManager = (LocationManager) mContext
                .getSystemService(Context.LOCATION_SERVICE);

        isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) {
            // no network provider is enabled
        } 
        else {
            this.canGetLocation = true;
            if (isNetworkEnabled) {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network Enabled");
                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return location;
}

public void stopUsingGPS() {
    if (locationManager != null) {
        locationManager.removeUpdates(GPSTracker.this);
    }
}

public double getLatitude() {
    if (location != null) {
        latitude = location.getLatitude();
    }

    return latitude;
}

public double getLongitude() {
    if (location != null) {
        longitude = location.getLongitude();
    }

    return longitude;
}

public boolean canGetLocation() {
    return this.canGetLocation;
}

@Override
public void onLocationChanged(Location arg0) {
    // TODO Auto-generated method stub

}

@Override
public void onProviderDisabled(String arg0) {
    // TODO Auto-generated method stub

}

@Override
public void onProviderEnabled(String arg0) {
    // TODO Auto-generated method stub

}

@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
    // TODO Auto-generated method stub

}


}

// --------------Distance.java

 public class Distance  {
    private double latitude ;
    private double longitude;
        public double getLatitude() {
            return latitude;
        }
        public void setLatitude(double latitude) {
            this.latitude = latitude;
        }
        public double getLongitude() {
            return longitude;
        }
        public void setLongitude(double longitude) {
            this.longitude = longitude;
        }



}

file_put_contents: Failed to open stream, no such file or directory

I was also stuck on the same kind of problem and I followed the simple steps below.

Just get the exact url of the file to which you want to copy, for example:

http://www.test.com/test.txt (file to copy)

Then pass the exact absolute folder path with filename where you do want to write that file.

  1. If you are on a Windows machine then d:/xampp/htdocs/upload/test.txt

  2. If you are on a Linux machine then /var/www/html/upload/test.txt

You can get the document root with the PHP function $_SERVER['DOCUMENT_ROOT'].

iOS - UIImageView - how to handle UIImage image orientation

extension UIImage {
    func fixImageOrientation() -> UIImage {
        UIGraphicsBeginImageContext(self.size)
        self.draw(at: .zero)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage ?? self
    }
}
  1. Create extension like top example.
  2. Call it: imageView.image?.fixImageOrientation() or UIImage(named: "someImage").fixImageOrientation()

  3. Good luck all!

How to find NSDocumentDirectory in Swift?

Usually i prefer like below in swift 3, because i can add file name and create a file easily

let fileManager = FileManager.default
if let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first {
    let databasePath = documentsURL.appendingPathComponent("db.sqlite3").path
    print("directory path:", documentsURL.path)
    print("database path:", databasePath)
    if !fileManager.fileExists(atPath: databasePath) {
        fileManager.createFile(atPath: databasePath, contents: nil, attributes: nil)
    }
}

Calendar Recurring/Repeating Events - Best Storage Method

For all of you who are interested in this, now you can just copy and paste to get started within minutes. I took the advice in the comments as well as I could. Let me know if I'm missing something.

"COMPLEX VERSION":

events

+----------+----------------+
| ID       | NAME           | 
+----------+----------------+
| 1        | Sample event 1 |
| 2        | Second  event  |
| 3        | Third event    |
+----------+----------------+

events_meta

+----+----------+--------------+------------------+-------------+--------------+------------+-------------+----------------+
| ID | event_id | repeat_start | repeat_interval  | repeat_year | repeat_month | repeat_day | repeat_week | repeat_weekday |
+----+----------+--------------+------------------+-------------+--------------+------------+-------------+----------------+
| 1  | 1        | 2014-07-04   | 7                | NULL        | NULL         | NULL       | NULL        | NULL           |
| 2  | 2        | 2014-06-26   | NULL             | 2014        | *            | *          | 2           | 5              |
| 3  | 3        | 2014-07-04   | NULL             | *           | *            | *          | *           | 5              |
+----+----------+--------------+------------------+-------------+--------------+------------+-------------+----------------+

SQL code:

CREATE TABLE IF NOT EXISTS `events` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `NAME` varchar(255) NOT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=7 ;

--
-- Dumping data for table `events`
--

INSERT INTO `events` (`ID`, `NAME`) VALUES
(1, 'Sample event'),
(2, 'Another event'),
(3, 'Third event...');

CREATE TABLE IF NOT EXISTS `events_meta` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `event_id` int(11) NOT NULL,
  `repeat_start` date NOT NULL,
  `repeat_interval` varchar(255) NOT NULL,
  `repeat_year` varchar(255) NOT NULL,
  `repeat_month` varchar(255) NOT NULL,
  `repeat_day` varchar(255) NOT NULL,
  `repeat_week` varchar(255) NOT NULL,
  `repeat_weekday` varchar(255) NOT NULL,
  PRIMARY KEY (`ID`),
  UNIQUE KEY `ID` (`ID`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=6 ;

--
-- Dumping data for table `events_meta`
--

INSERT INTO `events_meta` (`ID`, `event_id`, `repeat_start`, `repeat_interval`, `repeat_year`, `repeat_month`, `repeat_day`, `repeat_week`, `repeat_weekday`) VALUES
(1, 1, '2014-07-04', '7', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL'),
(2, 2, '2014-06-26', 'NULL', '2014', '*', '*', '2', '5'),
(3, 3, '2014-07-04', 'NULL', '*', '*', '*', '*', '1');

also available as MySQL export (for easy access)

PHP example code index.php:

<?php
    require 'connect.php';    

    $now = strtotime("yesterday");

    $pushToFirst = -11;
    for($i = $pushToFirst; $i < $pushToFirst+30; $i++)
    {
        $now = strtotime("+".$i." day");
        $year = date("Y", $now);
        $month = date("m", $now);
        $day = date("d", $now);
        $nowString = $year . "-" . $month . "-" . $day;
        $week = (int) ((date('d', $now) - 1) / 7) + 1;
        $weekday = date("N", $now);

        echo $nowString . "<br />";
        echo $week . " " . $weekday . "<br />";



        $sql = "SELECT EV.*
                FROM `events` EV
                RIGHT JOIN `events_meta` EM1 ON EM1.`event_id` = EV.`id`
                WHERE ( DATEDIFF( '$nowString', repeat_start ) % repeat_interval = 0 )
                OR ( 
                    (repeat_year = $year OR repeat_year = '*' )
                    AND
                    (repeat_month = $month OR repeat_month = '*' )
                    AND
                    (repeat_day = $day OR repeat_day = '*' )
                    AND
                    (repeat_week = $week OR repeat_week = '*' )
                    AND
                    (repeat_weekday = $weekday OR repeat_weekday = '*' )
                    AND repeat_start <= DATE('$nowString')
                )";
        foreach ($dbConnect->query($sql) as $row) {
            print $row['ID'] . "\t";
            print $row['NAME'] . "<br />";
        }

        echo "<br /><br /><br />";
    }
?>

PHP example code connect.php:

<?
// ----------------------------------------------------------------------------------------------------
//                                       Connecting to database
// ----------------------------------------------------------------------------------------------------
// Database variables
$username = "";
$password = "";
$hostname = ""; 
$database = ""; 

// Try to connect to database and set charset to UTF8
try {
    $dbConnect = new PDO("mysql:host=$hostname;dbname=$database;charset=utf8", $username, $password);
    $dbConnect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}
// ----------------------------------------------------------------------------------------------------
//                                      / Connecting to database
// ----------------------------------------------------------------------------------------------------
?>

Also the php code is available here (for better readability):
index.php
and
connect.php
Now setting this up should take you minutes. Not hours. :)

System.Net.Http: missing from namespace? (using .net 4.5)

You need to have a Reference to the System.Web.Http assembly which has the HTTPClient class, your trying to use. Try adding the below line before your class declaration

using System.Web.Http;

If you still get the Error, try doing this in Visual Studio

  1. Right click on the References folder on your project.
  2. Select Add Reference.
  3. Select the .NET tab (or select the Browse button if it is not a .NET Framework assembly).
  4. Double-click the assembly containing the namespace in the error message (System.Web.Http.dll).
  5. Press the OK button.

How do I show/hide a UIBarButtonItem?

For Swift 3 and Swift 4 you can do this to hide the UIBarButtomItem:

self.deleteButton.isEnabled = false
self.deleteButton.tintColor = UIColor.clear

And to show the UIBarButtonItem:

self.deleteButton.isEnabled = true
self.deleteButton.tintColor = UIColor.blue

On the tintColor you must have to specify the origin color you are using for the UIBarButtomItem

How to register multiple servlets in web.xml in one Spring application

Use config something like this:

<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>

<listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet>
  <servlet-name>myservlet</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
</servlet>

<servlet>
  <servlet-name>user-webservice</servlet-name>
  <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
  <load-on-startup>2</load-on-startup>
</servlet>

and then you'll need three files:

  • applicationContext.xml;
  • myservlet-servlet.xml; and
  • user-webservice-servlet.xml.

The *-servlet.xml files are used automatically and each creates an application context for that servlet.

From the Spring documentation, 13.2. The DispatcherServlet:

The framework will, on initialization of a DispatcherServlet, look for a file named [servlet-name]-servlet.xml in the WEB-INF directory of your web application and create the beans defined there (overriding the definitions of any beans defined with the same name in the global scope).

Rank function in MySQL

@Sam, your point is excellent in concept but I think you misunderstood what the MySQL docs are saying on the referenced page -- or I misunderstand :-) -- and I just wanted to add this so that if someone feels uncomfortable with the @Daniel's answer they'll be more reassured or at least dig a little deeper.

You see the "@curRank := @curRank + 1 AS rank" inside the SELECT is not "one statement", it's one "atomic" part of the statement so it should be safe.

The document you reference goes on to show examples where the same user-defined variable in 2 (atomic) parts of the statement, for example, "SELECT @curRank, @curRank := @curRank + 1 AS rank".

One might argue that @curRank is used twice in @Daniel's answer: (1) the "@curRank := @curRank + 1 AS rank" and (2) the "(SELECT @curRank := 0) r" but since the second usage is part of the FROM clause, I'm pretty sure it is guaranteed to be evaluated first; essentially making it a second, and preceding, statement.

In fact, on that same MySQL docs page you referenced, you'll see the same solution in the comments -- it could be where @Daniel got it from; yeah, I know that it's the comments but it is comments on the official docs page and that does carry some weight.

Remove empty space before cells in UITableView

I had this same problem and I'm pretty sure I had a UIView in there at one point. Simply copying the entire table view, deleting it, and pasting it again fixed it for me.

recursively use scp but excluding some folders

This one works fine for me as the directories structure is not important for me.

scp -r USER@HOSTNAME:~/bench1/?cpu/p_?/image/ .

Assuming /bench1 is in the home directory of the current user. Also, change USER and HOSTNAME to the real values.

Error : Program type already present: android.support.design.widget.CoordinatorLayout$Behavior

It might be cause of a library, I faced it because of Glide.

It was

implementation 'com.github.bumptech.glide:glide:4.7.1'

So I added exclude group: "com.android.support" And it becomes

implementation ('com.github.bumptech.glide:glide:4.7.1') {
        exclude group: "com.android.support"
    }

JavaScript replace/regex

Your regex pattern should have the g modifier:

var pattern = /[somepattern]+/g;

notice the g at the end. it tells the replacer to do a global replace.

Also you dont need to use the RegExp object you can construct your pattern as above. Example pattern:

var pattern = /[0-9a-zA-Z]+/g;

a pattern is always surrounded by / on either side - with modifiers after the final /, the g modifier being the global.

EDIT: Why does it matter if pattern is a variable? In your case it would function like this (notice that pattern is still a variable):

var pattern = /[0-9a-zA-Z]+/g;
repeater.replace(pattern, "1234abc");

But you would need to change your replace function to this:

this.markup = this.markup.replace(pattern, value);

Error 'LINK : fatal error LNK1123: failure during conversion to COFF: file invalid or corrupt' after installing Visual Studio 2012 Release Preview

I had the same problem after updating of .NET: I uninstalled the .NET framework first, downloaded visual studio from visualstudio.com and selected "repair".

NET framework were installed automatically with visual studio -> and now it works fine!

How to set bot's status

Bumping this all the way from 2018, sorry not sorry. But the newer users questioning how to do this need to know that game does not work anymore for this task.

bot.user.setStatus('available')
bot.user.setPresence({
    game: {
        name: 'with depression',
        type: "STREAMING",
        url: "https://www.twitch.tv/monstercat"
    }
}

does not work anymore. You will now need to do this:

bot.user.setPresence({
    status: 'online',
    activity: {
        name: 'with depression',
        type: 'STREAMING',
        url: 'https://www.twitch.tv/monstercat'
    }
})

This is referenced here as "game" is not a valid property of setPresence anymore. Read the PresenceData Documentation for more information about this.

Spring JPA @Query with LIKE

List<User> findByUsernameContainingIgnoreCase(String username);

in order to ignore case issues

How to set Internet options for Android emulator?

I've seen various suggestions how code can find out whether it runs on the emulator, but none are quite satisfactory, or "future-proof". For the time being I've settled on reading the device ID, which is all zeros for the emulator:

TelephonyManager telmgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); boolean isEmulator = "000000000000000".equals(telmgr.getDeviceId());

But on a deployed app that requires the READ_PHONE_STATE permission

Python 3: ImportError "No Module named Setuptools"

The solution which worked for me was to upgrade my setuptools:

python3 -m pip install --upgrade pip setuptools wheel

Setting Margin Properties in code

Margin is returning a struct, which means that you are editing a copy. You will need something like:

var margin = MyControl.Margin;
margin.Left = 10;
MyControl.Margin = margin;

Check if AJAX response data is empty/blank/null/undefined/0

This worked form me.. PHP Code on page.php

 $query_de="sql statements here";
 $sql_de = sqlsrv_query($conn,$query_de);
      if ($sql_de)
      {
        echo "SQLSuccess";
       }
         exit();

and then AJAX Code has bellow

jQuery.ajax({
                    url  : "page.php",
                    type : "POST",
                    data : {
                            buttonsave   : 1,
                            var1         : val1,
                            var2         : val2,
                              },
                  success:function(data)
                           {
                     if(jQuery.trim(data) === "SQLSuccess")
                                   {
                           alert("Se agrego correctamente");
                          // alert(data);
                                      } else { alert(data);}
                              },
                   error: function(error)
                           {
                    alert("Error AJAX not working: "+ error );
                              } 
               }); 

NOTE: the word 'SQLSuccess' must be received from PHP

Is the Scala 2.8 collections library a case of "the longest suicide note in history"?

It seems necessary to state ones degree here: B.A. in Political Science and B.ed in Computer Science.

To the point:

Is this going to put people off coming to Scala?

Scala is difficult, because its underlying programming paradigm is difficult. Functional programming scares a lot of people. It is possible to build closures in PHP but people rarely do. So no, not this signature but all the rest will put people off, if they do not have the specific education to make them value the power of the underlying paradigm.

If this education is available, everyone can do it. Last year I build a chess computer with a bunch of school kids in SCALA! They had their problems but they did fine in the end.

If you're using Scala commercially, are you worried about this? Are you planning to adopt 2.8 immediately or wait to see what happens?

I would not be worried.

Adding devices to team provisioning profile

Update for Xcode (Version 9.1). Please follow below steps for refreshing Provisioning profiles

Using Xcode Organizer

  • Select Export

enter image description here

  • Select desired distribution facility

enter image description here

  • Now Select Automatically Manage Signing Identity enter image description here
  • In next Screen Please click on Profile tag detail discloser button which will navigate you to Provisioning profile Folder

enter image description here

  • Select all profiles and trash them. Now in Xcode click on the Previous button and click again on Automatically Manage Signing, Now Xcode will create new signing identity for you with latest features (including new device id's)

In short, you can navigate to MobileDevice/Provisioning Profiles/ folder path and delete all profiles and then Archive. Now you can see there are new profiles for you. Cheers :)

@JasonH hope it will help you.

WSDL/SOAP Test With soapui

For anyone hitting this issue in the future: the specific situation here ("the server isn't sending back the WSDL properly") may or may not always be relevant, but two key aspects should always be:

  1. The message faultCode=INVALID_WSDL: Expected element '{http://schemas.xmlsoap.org/wsdl/}definitions' means that the actual content returned is not XML with a base element of "definitions" in the WSDL namespace.
  2. The message WSDLException (at /html) tells you an important clue about what it did find — for this example, /html strongly implies that a normal webpage was returned, rather than a WSDL. Another common situation is seeing something like /soapenv:Reason, which would indicate that the server was trying to treat it as a SOAP call — for example, this can happen if your URL is for the "base" service URL rather than the WSDL.

React-router urls don't work when refreshing or writing manually

If you are hosting your react app on IIS, just add a web.config file containing :

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <httpErrors errorMode="Custom" existingResponse="Replace">
        <remove statusCode="404" subStatusCode="-1" />
        <error statusCode="404" path="/" responseMode="ExecuteURL" />
    </httpErrors>
  </system.webServer>
</configuration>

This will tell IIS server to return the main page to the client instead of 404 error and no need to use hash history.

Create a variable name with "paste" in R?

You can use assign (doc) to change the value of perf.a1:

> assign(paste("perf.a", "1", sep=""),5)
> perf.a1
[1] 5

Javascript: Setting location.href versus location

Just to clarify, you can't do location.split('#'), location is an object, not a string. But you can do location.href.split('#'); because location.href is a string.

Call PHP function from jQuery?

Thanks all. I took bits of each of your solutions and made my own.

The final working solution is:

<script type="text/javascript">
    $(document).ready(function(){
        $.ajax({
            url: '<?php bloginfo('template_url'); ?>/functions/twitter.php',
            data: "tweets=<?php echo $ct_tweets; ?>&account=<?php echo $ct_twitter; ?>",
            success: function(data) {
                $('#twitter-loader').remove();
                $('#twitter-container').html(data);
            }
        });
   });
</script>

How to make a div with a circular shape?

Demo

css

div {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    background: red;
}

html

<div></div>

How to get the HTML's input element of "file" type to only accept pdf files?

To get the HTML file input form element to only accept PDFs, you can use the accept attribute in modern browsers such as Firefox 9+, Chrome 16+, Opera 11+ and IE10+ like such:

<input name="file1" type="file" accept="application/pdf">

You can string together multiple mime types with a comma.

The following string will accept JPG, PNG, GIF, PDF, and EPS files:

<input name="foo" type="file" accept="image/jpeg,image/gif,image/png,application/pdf,image/x-eps">

In older browsers the native OS file dialog cannot be restricted – you'd have to use Flash or a Java applet or something like that to handle the file transfer.

And of course it goes without saying that this doesn't do anything to verify the validity of the file type. You'll do that on the server-side once the file has uploaded.

A little update – with javascript and the FileReader API you could do more validation client-side before uploading huge files to your server and checking them again.

How to give environmental variable path for file appender in configuration file in log4j

you CAN give it environment variables. Just preppend env: before the variable name, like this:

value="${env:MY_HOME}/logs/message.log"

Disable beep of Linux Bash on Windows 10

To disable the beeps when ssh-ing in a remote machine, simply create the same ~/.inputrc and ~/.vimrc files on the remote machine to stop ssh itself from beeping.

See the answer from @Nemo for the contents of each file.

How to round the corners of a button

First set width=100 and Height=100 of button

Objective C Solution

YourBtn1.layer.cornerRadius=YourBtn1.Frame.size.width/2;
YourBtn1.layer.borderColor=[uicolor blackColor].CGColor;
YourBtn1.layer.borderWidth=1.0f;

Swift 4 Solution

YourBtn1.layer.cornerRadius = YourBtn1.Frame.size.width/2
YourBtn1.layer.borderColor = UIColor.black.cgColor
YourBtn1.layer.borderWidth = 1.0

How to permanently set $PATH on Linux/Unix?

There are multiple ways to do it. The actual solution depends on the purpose.

The variable values are usually stored in either a list of assignments or a shell script that is run at the start of the system or user session. In case of the shell script you must use a specific shell syntax and export or set commands.

System wide

  1. /etc/environment List of unique assignments, allows references. Perfect for adding system-wide directories like /usr/local/something/bin to PATH variable or defining JAVA_HOME. Used by PAM and SystemD.
  2. /etc/environment.d/*.conf List of unique assignments, allows references. Perfect for adding system-wide directories like /usr/local/something/bin to PATH variable or defining JAVA_HOME. The configuration can be split into multiple files, usually one per each tool (Java, Go, NodeJS). Used by SystemD that by design do not pass those values to user login shells.
  3. /etc/xprofile Shell script executed while starting X Window System session. This is run for every user that logs into X Window System. It is a good choice for PATH entries that are valid for every user like /usr/local/something/bin. The file is included by other script so use POSIX shell syntax not the syntax of your user shell.
  4. /etc/profile and /etc/profile.d/* Shell script. This is a good choice for shell-only systems. Those files are read only by shells in login mode.
  5. /etc/<shell>.<shell>rc. Shell script. This is a poor choice because it is single shell specific. Used in non-login mode.

User session

  1. ~/.pam_environment. List of unique assignments, no references allowed. Loaded by PAM at the start of every user session irrelevant if it is an X Window System session or shell. You cannot reference other variables including HOME or PATH so it has limited use. Used by PAM.
  2. ~/.xprofile Shell script. This is executed when the user logs into X Window System system. The variables defined here are visible to every X application. Perfect choice for extending PATH with values such as ~/bin or ~/go/bin or defining user specific GOPATH or NPM_HOME. The file is included by other script so use POSIX shell syntax not the syntax of your user shell. Your graphical text editor or IDE started by shortcut will see those values.
  3. ~/.profile, ~/.<shell>_profile, ~/.<shell>_login Shell script. It will be visible only for programs started from terminal or terminal emulator. It is a good choice for shell-only systems. Used by shells in login mode.
  4. ~/.<shell>rc. Shell script. This is a poor choice because it is single shell specific. Used by shells in non-login mode.

Notes

Gnome on Wayland starts user login shell to get the environment. It effectively uses login shell configurations ~/.profile, ~/.<shell>_profile, ~/.<shell>_login files.

Manuals

  • environment
  • environment.d
  • bash
  • dash

Distribution specific documentation

Related

Difference between Login Shell and Non-Login Shell?

How can I install a package with go get?

First, we need GOPATH

The $GOPATH is a folder (or set of folders) specified by its environment variable. We must notice that this is not the $GOROOT directory where Go is installed.

export GOPATH=$HOME/gocode
export PATH=$PATH:$GOPATH/bin

We used ~/gocode path in our computer to store the source of our application and its dependencies. The GOPATH directory will also store the binaries of their packages.

Then check Go env

You system must have $GOPATH and $GOROOT, below is my Env:

GOARCH="amd64"
GOBIN=""
GOCHAR="6"
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/home/elpsstu/gocode"
GORACE=""
GOROOT="/home/pravin/go"
GOTOOLDIR="/home/pravin/go/pkg/tool/linux_amd64"
CC="gcc"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0"
CXX="g++"
CGO_ENABLED="1"

Now, you run download go package:

go get [-d] [-f] [-fix] [-t] [-u] [build flags] [packages]

Get downloads and installs the packages named by the import paths, along with their dependencies. For more details you can look here.

CSS Positioning Elements Next to each other

If you want them to be displayed side by side, why is sideContent the child of mainContent? make them siblings then use:

float:left; display:inline; width: 49%;

on both of them.

#mainContent, #sideContent {float:left; display:inline; width: 49%;}

How do you get the current page number of a ViewPager for Android?

There is no any method getCurrentItem() in viewpager.i already checked the API

How to pick an image from gallery (SD Card) for my app?

Updated answer, nearly 5 years later:

The code in the original answer no longer works reliably, as images from various sources sometimes return with a different content URI, i.e. content:// rather than file://. A better solution is to simply use context.getContentResolver().openInputStream(intent.getData()), as that will return an InputStream that you can handle as you choose.

For example, BitmapFactory.decodeStream() works perfectly in this situation, as you can also then use the Options and inSampleSize field to downsample large images and avoid memory problems.

However, things like Google Drive return URIs to images which have not actually been downloaded yet. Therefore you need to perform the getContentResolver() code on a background thread.


Original answer:

The other answers explained how to send the intent, but they didn't explain well how to handle the response. Here's some sample code on how to do that:

protected void onActivityResult(int requestCode, int resultCode, 
       Intent imageReturnedIntent) {
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent); 

    switch(requestCode) { 
    case REQ_CODE_PICK_IMAGE:
        if(resultCode == RESULT_OK){  
            Uri selectedImage = imageReturnedIntent.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};

            Cursor cursor = getContentResolver().query(
                               selectedImage, filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String filePath = cursor.getString(columnIndex);
            cursor.close();


            Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
        }
    }
}

After this, you've got the selected image stored in "yourSelectedImage" to do whatever you want with. This code works by getting the location of the image in the ContentResolver database, but that on its own isn't enough. Each image has about 18 columns of information, ranging from its filepath to 'date last modified' to the GPS coordinates of where the photo was taken, though many of the fields aren't actually used.

To save time as you don't actually need the other fields, cursor search is done with a filter. The filter works by specifying the name of the column you want, MediaStore.Images.Media.DATA, which is the path, and then giving that string[] to the cursor query. The cursor query returns with the path, but you don't know which column it's in until you use the columnIndex code. That simply gets the number of the column based on its name, the same one used in the filtering process. Once you've got that, you're finally able to decode the image into a bitmap with the last line of code I gave.

Sync data between Android App and webserver

@Grantismo gives a great overview of Android sync components.

SyncManagerAndroid library provides a simple 2-way sync implementation to plug into the Android Sync framework (AbstractThreadedSyncAdapter.OnPerformSync).

https://github.com/sschendel/SyncManagerAndroid

Sort objects in an array alphabetically on one property of the array

var DepartmentFactory = function(data) {
    this.id = data.Id;
    this.name = data.DepartmentName;
    this.active = data.Active;
}

// use `new DepartmentFactory` as given below. `new` is imporatant

var objArray = [];
objArray.push(new DepartmentFactory({Id: 1, DepartmentName: 'Marketing', Active: true}));
objArray.push(new DepartmentFactory({Id: 2, DepartmentName: 'Sales', Active: true}));
objArray.push(new DepartmentFactory({Id: 3, DepartmentName: 'Development', Active: true}));
objArray.push(new DepartmentFactory({Id: 4, DepartmentName: 'Accounting', Active: true}));

function sortOn(property){
    return function(a, b){
        if(a[property] < b[property]){
            return -1;
        }else if(a[property] > b[property]){
            return 1;
        }else{
            return 0;   
        }
    }
}

//objArray.sort(sortOn("id")); // because `this.id = data.Id;`
objArray.sort(sortOn("name")); // because `this.name = data.DepartmentName;`
console.log(objArray);

demo: http://jsfiddle.net/diode/hdgeH/

Bootstrap date and time picker

If you are still interested in a javascript api to select both date and time data, have a look at these projects which are forks of bootstrap datepicker:

The first fork is a big refactor on the parsing/formatting codebase and besides providing all views to select date/time using mouse/touch, it also has a mask option (by default) which lets the user to quickly type the date/time based on a pre-specified format.

How to initialize a JavaScript Date to a particular time zone

I had the same problem but we can use the time zone we want
we use .toLocaleDateString()

eg:

_x000D_
_x000D_
var day=new Date();
const options= {day:'numeric', month:'long', year:"numeric", timeZone:"Asia/Kolkata"};
const today=day.toLocaleDateString("en-IN", options);
console.log(today);
_x000D_
_x000D_
_x000D_

JavaScript: Difference between .forEach() and .map()

+----------------------------------------------------------------------------------------------+
¦                ¦ foreach                             ¦ map                                   ¦
¦----------------+-------------------------------------+---------------------------------------¦
¦ Functionality  ¦ Performs given operation on each    ¦ Performs given "transformation" on    ¦
¦                ¦ element of the array                ¦ "copy" of each element                ¦
¦————————————————+—————————————————————————————————————+———————————————————————————————————————¦
¦ Return value   ¦ Returns undefined                   ¦ Returns new array with tranformed     ¦
¦                ¦                                     ¦ elements leaving back original array  ¦
¦                ¦                                     ¦ unchanged                             ¦
¦————————————————+—————————————————————————————————————+———————————————————————————————————————¦
¦ Preferrable    ¦ Performing non—transformation like  ¦ Obtaining array containing output of  ¦
¦ usage scenario ¦ processing on each element.         ¦ some processing done on each element  ¦
¦ and example    ¦                                     ¦ of the array.                         ¦
¦                ¦ For example, saving all elements in ¦                                       ¦
¦                ¦ the database                        ¦ For example, obtaining array of       ¦
¦                ¦                                     ¦ lengths of each string in the         ¦
¦                ¦                                     ¦ array                                 ¦
+----------------------------------------------------------------------------------------------+

Android Volley - BasicNetwork.performRequest: Unexpected response code 400

What I did was append an extra '/' to my url, e.g.:

String url = "http://www.google.com" 

to

String url = "http://www.google.com/"

JavaScript is in array

Depending on the version of JavaScript you have available, you can use indexOf:

Returns the first index at which a given element can be found in the array, or -1 if it is not present.

Or some:

Tests whether some element in the array passes the test implemented by the provided function.

But, if you're doing this sort of existence check a lot you'd be better of using an Object to store your strings (or perhaps an object as well as the Array depending on what you're doing with your data).

Example of Named Pipes

You can actually write to a named pipe using its name, btw.

Open a command shell as Administrator to get around the default "Access is denied" error:

echo Hello > \\.\pipe\PipeName

How to store and retrieve a dictionary with redis

HMSET is deprecated. You can now use HSET with a dictionary as follows:

import redis
r = redis.Redis('localhost')

key = "hashexample" 
queue_entry = { 
    "version":"1.2.3", 
    "tag":"main", 
    "status":"CREATED",  
    "timeout":"30"
    }
r.hset(key,None,None,queue_entry)

BackgroundWorker vs background Thread

A background worker is a class that works in a separate thread, but it provides additional functionality that you don't get with a simple Thread (like task progress report handling).

If you don't need the additional features given by a background worker - and it seems you don't - then a Thread would be more appropriate.

How do I get the number of elements in a list?

Answering your question as the examples also given previously:

items = []
items.append("apple")
items.append("orange")
items.append("banana")

print items.__len__()

How do I use Spring Boot to serve static content located in Dropbox folder?

You can place your folder in the root of the ServletContext.

Then specify a relative or absolute path to this directory in application.yml:

spring:
  resources:
    static-locations: file:some_temp_files/

The resources in this folder will be available (for downloading, for example) at:

http://<host>:<port>/<context>/your_file.csv

Checkboxes in web pages – how to make them bigger?

In case this can help anyone, here's simple CSS as a jumping off point. Turns it into a basic rounded square big enough for thumbs with a toggled background color.

_x000D_
_x000D_
input[type='checkbox'] {_x000D_
    -webkit-appearance:none;_x000D_
    width:30px;_x000D_
    height:30px;_x000D_
    background:white;_x000D_
    border-radius:5px;_x000D_
    border:2px solid #555;_x000D_
}_x000D_
input[type='checkbox']:checked {_x000D_
    background: #abd;_x000D_
}
_x000D_
<input type="checkbox" />
_x000D_
_x000D_
_x000D_

Importing Excel into a DataTable Quickly

In case anyone else is using EPPlus. This implementation is pretty naive, but there are comments that draw attention to such. If you were to layer one more method GetWorkbookAsDataSet() on top it would do what the OP is asking for.

    /// <summary>
    /// Assumption: Worksheet is in table format with no weird padding or blank column headers.
    /// 
    /// Assertion: Duplicate column names will be aliased by appending a sequence number (eg. Column, Column1, Column2)
    /// </summary>
    /// <param name="worksheet"></param>
    /// <returns></returns>
    public static DataTable GetWorksheetAsDataTable(ExcelWorksheet worksheet)
    {
        var dt = new DataTable(worksheet.Name);
        dt.Columns.AddRange(GetDataColumns(worksheet).ToArray());
        var headerOffset = 1; //have to skip header row
        var width = dt.Columns.Count;
        var depth = GetTableDepth(worksheet, headerOffset);
        for (var i = 1; i <= depth; i++)
        {
            var row = dt.NewRow();
            for (var j = 1; j <= width; j++)
            {
                var currentValue = worksheet.Cells[i + headerOffset, j].Value;

                //have to decrement b/c excel is 1 based and datatable is 0 based.
                row[j - 1] = currentValue == null ? null : currentValue.ToString();
            }

            dt.Rows.Add(row);
        }

        return dt;
    }

    /// <summary>
    /// Assumption: There are no null or empty cells in the first column
    /// </summary>
    /// <param name="worksheet"></param>
    /// <returns></returns>
    private static int GetTableDepth(ExcelWorksheet worksheet, int headerOffset)
    {
        var i = 1;
        var j = 1;
        var cellValue = worksheet.Cells[i + headerOffset, j].Value;
        while (cellValue != null)
        {
            i++;
            cellValue = worksheet.Cells[i + headerOffset, j].Value;
        }

        return i - 1; //subtract one because we're going from rownumber (1 based) to depth (0 based)
    }

    private static IEnumerable<DataColumn> GetDataColumns(ExcelWorksheet worksheet)
    {
        return GatherColumnNames(worksheet).Select(x => new DataColumn(x));
    }

    private static IEnumerable<string> GatherColumnNames(ExcelWorksheet worksheet)
    {
        var columns = new List<string>();

        var i = 1;
        var j = 1;
        var columnName = worksheet.Cells[i, j].Value;
        while (columnName != null)
        {
            columns.Add(GetUniqueColumnName(columns, columnName.ToString()));
            j++;
            columnName = worksheet.Cells[i, j].Value;
        }

        return columns;
    }

    private static string GetUniqueColumnName(IEnumerable<string> columnNames, string columnName)
    {
        var colName = columnName;
        var i = 1;
        while (columnNames.Contains(colName))
        {
            colName = columnName + i.ToString();
            i++;
        }

        return colName;
    }

Specify sudo password for Ansible

After five years, I can see this is still a very relevant subject. Somewhat mirroring leucos's answer which I find the best in my case, using ansible tools only (without any centralised authentication, tokens or whatever). This assumes you have the same username and the same public key on all servers. If you don't, of course you'd need to be more specific and add the corresponding variables next to the hosts:

[all:vars]
ansible_ssh_user=ansible
ansible_ssh_private_key_file=home/user/.ssh/mykey
[group]
192.168.0.50 ansible_sudo_pass='{{ myserver_sudo }}'

ansible-vault create mypasswd.yml
ansible-vault edit mypasswd.yml

Add:

myserver_sudo: mysecretpassword

Then:

ansible-playbook -i inv.ini my_role.yml --ask-vault --extra-vars '@passwd.yml'

At least this way you don't have to write more the variables which point to the passwords.

Using CSS for a fade-in effect on page load

In response to @A.M.K's question about how to do transitions without jQuery. A very simple example I threw together. If I had time to think this through some more, I might be able to eliminate the JavaScript code altogether:

<style>
    body {
        background-color: red;
        transition: background-color 2s ease-in;
    }
</style>

<script>
    window.onload = function() {
        document.body.style.backgroundColor = '#00f';
    }
</script>

<body>
    <p>test</p>
</body>

Oracle: is there a tool to trace queries, like Profiler for sql server?

alter system set timed_statistics=true

--or

alter session set timed_statistics=true --if want to trace your own session

-- must be big enough:

select value from v$parameter p
where name='max_dump_file_size' 

-- Find out sid and serial# of session you interested in:

 select sid, serial# from v$session
 where ...your_search_params...

--you can begin tracing with 10046 event, the fourth parameter sets the trace level(12 is the biggest):

 begin
    sys.dbms_system.set_ev(sid, serial#, 10046, 12, '');
 end;

--turn off tracing with setting zero level:

begin
   sys.dbms_system.set_ev(sid, serial#, 10046, 0, '');
end;

/*possible levels: 0 - turned off 1 - minimal level. Much like set sql_trace=true 4 - bind variables values are added to trace file 8 - waits are added 12 - both bind variable values and wait events are added */

--same if you want to trace your own session with bigger level:

alter session set events '10046 trace name context forever, level 12';

--turn off:

alter session set events '10046 trace name context off';

--file with raw trace information will be located:

 select value from v$parameter p
 where name='user_dump_dest'

--name of the file(*.trc) will contain spid:

 select p.spid from v$session s, v$process p
 where s.paddr=p.addr
 and ...your_search_params...

--also you can set the name by yourself:

alter session set tracefile_identifier='UniqueString'; 

--finally, use TKPROF to make trace file more readable:

C:\ORACLE\admin\databaseSID\udump>
C:\ORACLE\admin\databaseSID\udump>tkprof my_trace_file.trc output=my_file.prf
TKPROF: Release 9.2.0.1.0 - Production on Wed Sep 22 18:05:00 2004
Copyright (c) 1982, 2002, Oracle Corporation. All rights reserved.
C:\ORACLE\admin\databaseSID\udump>

--to view state of trace file use:

set serveroutput on size 30000;
declare
  ALevel binary_integer;
begin
  SYS.DBMS_SYSTEM.Read_Ev(10046, ALevel);
  if ALevel = 0 then
    DBMS_OUTPUT.Put_Line('sql_trace is off');
  else
    DBMS_OUTPUT.Put_Line('sql_trace is on');
  end if;
end;
/

Just kind of translated http://www.sql.ru/faq/faq_topic.aspx?fid=389 Original is fuller, but anyway this is better than what others posted IMHO

Why are elementwise additions much faster in separate loops than in a combined loop?

It's because the CPU doesn't have so many cache misses (where it has to wait for the array data to come from the RAM chips). It would be interesting for you to adjust the size of the arrays continually so that you exceed the sizes of the level 1 cache (L1), and then the level 2 cache (L2), of your CPU and plot the time taken for your code to execute against the sizes of the arrays. The graph shouldn't be a straight line like you'd expect.

how to create a Java Date object of midnight today and midnight tomorrow?

For sake of completeness, if you are using Java 8 you can also use the truncatedTo method of the Instant class to get midnight in UTC.

Instant.now().truncatedTo(ChronoUnit.DAYS);

As written in the Javadoc

For example, truncating with the MINUTES unit will round down to the nearest minute, setting the seconds and nanoseconds to zero.

Hope it helps.

How to determine the IP address of a Solaris system

There's also:

getent $HOSTNAME

or possibly:

getent `uname -n`

On Solaris 11 the ifconfig command is considered legacy and is being replaced by ipadm

ipadm show-addr

will show the IP addresses on the system for Solaris 11 and later.

Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

Little late, but this error can also be caused if you use a native application Client ID instead of a web application Client ID.

Adding a new SQL column with a default value

Another useful keyword is FIRST and AFTER if you want to add it in a specific spot in your table.

ALTER TABLE `table1` ADD COLUMN `foo` AFTER `bar` INT DEFAULT 0;

How to get the file-path of the currently executing javascript code

The accepted answer here does not work if you have inline scripts in your document. To avoid this you can use the following to only target <script> tags with a [src] attribute.

/**
 * Current Script Path
 *
 * Get the dir path to the currently executing script file
 * which is always the last one in the scripts array with
 * an [src] attr
 */
var currentScriptPath = function () {

    var scripts = document.querySelectorAll( 'script[src]' );
    var currentScript = scripts[ scripts.length - 1 ].src;
    var currentScriptChunks = currentScript.split( '/' );
    var currentScriptFile = currentScriptChunks[ currentScriptChunks.length - 1 ];

    return currentScript.replace( currentScriptFile, '' );
}

This effectively captures the last external .js file, solving some issues I encountered with inline JS templates.

What is the difference between C# and .NET?

Here I provided you a link where explain what is C# Language and the .NET Framework Platform Architecture. Remember that C# is a general-purpose, object-oriented programming language, and it runs on the .NET Framework.

.NET Framework includes a large class library named Framework Class Library (FCL) and provides user interface, data access, database connectivity, cryptography, web application development, numeric algorithms, and network communications.

.NET Framework was developed by Microsoft that runs primarily on Microsoft Windows.

Introduction to the C# Language and the .NET Framework from Microsoft Docs

Jackson how to transform JsonNode to ArrayNode without casting?

I would assume at the end of the day you want to consume the data in the ArrayNode by iterating it. For that:

Iterator<JsonNode> iterator = datasets.withArray("datasets").elements();
while (iterator.hasNext()) 
        System.out.print(iterator.next().toString() + " "); 

or if you're into streams and lambda functions:

import com.google.common.collect.Streams;
Streams.stream(datasets.withArray("datasets").elements())
    .forEach( item -> System.out.print(item.toString()) )

Create a custom event in Java

What you want is an implementation of the observer pattern. You can do it yourself completely, or use java classes like java.util.Observer and java.util.Observable

How to insert default values in SQL table?

The best way is:

insert your_table
default values

Cannot push to Git repository on Bitbucket

I had this issue and I thought I was crazy. I have been using SSH for 20 years. and git over SSH since 2012... but why couldn't I fetch my bitbucket repository on my home computer?

well, I have two bitbucket accounts and had 4 SSH keys loaded inside my agent. even if my .ssh/config was configured to use the right key. when ssh was initializing the connection, it was using them in order loaded into the agent. so I was getting logged into my personal bitbucket account.

then getting a Forbidden error trying to fetch the repo. makes sense.

I unloaded the key from the agent

ssh-add -d ~/.ssh/personal_rsa

then I could fetch the repos.

... Later I found out I can force it to use the specified identity only

 Host bitbucket.org-user2
     HostName bitbucket.org
     User git
     IdentityFile ~/.ssh/user2
     IdentitiesOnly yes

I didn't know about that last option IdentitiesOnly

from the bitbucket documentation itself

https://blog.developer.atlassian.com/different-ssh-keys-multiple-bitbucket-accounts/

JFrame.dispose() vs System.exit()

JFrame.dispose()

public void dispose()

Releases all of the native screen resources used by this Window, its subcomponents, and all of its owned children. That is, the resources for these Components will be destroyed, any memory they consume will be returned to the OS, and they will be marked as undisplayable. The Window and its subcomponents can be made displayable again by rebuilding the native resources with a subsequent call to pack or show. The states of the recreated Window and its subcomponents will be identical to the states of these objects at the point where the Window was disposed (not accounting for additional modifications between those actions).

Note: When the last displayable window within the Java virtual machine (VM) is disposed of, the VM may terminate. See AWT Threading Issues for more information.

System.exit()

public static void exit(int status)

Terminates the currently running Java Virtual Machine. The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination. This method calls the exit method in class Runtime. This method never returns normally.

The call System.exit(n) is effectively equivalent to the call:

Runtime.getRuntime().exit(n)

How to store arbitrary data for some HTML tags

You could use hidden input tags. I get no validation errors at w3.org with this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang='en' xml:lang='en' xmlns='http://www.w3.org/1999/xhtml'>
  <head>
    <meta content="text/html;charset=UTF-8" http-equiv="content-type" />
    <title>Hello</title>
  </head>
  <body>
    <div>
      <a class="article" href="link/for/non-js-users.html">
        <input style="display: none" name="articleid" type="hidden" value="5" />
      </a>
    </div>
  </body>
</html>

With jQuery you'd get the article ID with something like (not tested):

$('.article input[name=articleid]').val();

But I'd recommend HTML5 if that is an option.

How to read a file line-by-line into a list?

If you want the \n included:

with open(fname) as f:
    content = f.readlines()

If you do not want \n included:

with open(fname) as f:
    content = f.read().splitlines()

How can I find an element by CSS class with XPath?

Match against one class that has whitespace.

<div class="hello "></div>
//div[normalize-space(@class)="hello"]

Make anchor link go some pixels above where it's linked to

I had this same issue, and there's a really quick and simple solution without CSS of JS. Just create a separate unstyled div with an ID like "aboutMeAnchor and just place it well above the section you actually want to land on.

Python - abs vs fabs

abs() : Returns the absolute value as per the argument i.e. if argument is int then it returns int, if argument is float it returns float. Also it works on complex variable also i.e. abs(a+bj) also works and returns absolute value i.e.math.sqrt(((a)**2)+((b)**2)

math.fabs() : It only works on the integer or float values. Always returns the absolute float value no matter what is the argument type(except for the complex numbers).

Check if inputs form are empty jQuery

var empty = true;
$('input[type="text"]').each(function() {
   if ($(this).val() != "") {
      empty = false;
      return false;
   }
});

This should look all the input and set the empty var to false, if at least one is not empty.

EDIT:

To match the OP edit request, this can be used to filter input based on name substring.

$('input[name*="denominationcomune_"]').each(...

How can I autoplay a video using the new embed code style for Youtube?

Just add ?autoplay=1 after url in embed code, example :

<iframe width="420" height="315" src="http://www.youtube.com/embed/
oHg5SJYRHA0" frameborder="0"></iframe>

Change it to:

<iframe width="420" height="315" src="http://www.youtube.com/embed/
oHg5SJYRHA0?autoplay=1" frameborder="0"></iframe>

Center an item with position: relative

You can use calc to position element relative to center. For example if you want to position element 200px right from the center .. you can do this :

#your_element{
    position:absolute;
    left: calc(50% + 200px);
}

Dont forget this

When you use signs + and - you must have one blank space between sign and number, but when you use signs * and / there is no need for blank space.

CURL to pass SSL certifcate and password

I went through this when trying to get a clientcert and private key out of a keystore.

The link above posted by welsh was great, but there was an extra step on my redhat distribution. If curl is built with NSS ( run curl --version to see if you see NSS listed) then you need to import the keys into an NSS keystore. I went through a bunch of convoluted steps, so this may not be the cleanest way, but it got things working

So export the keys into .p12

keytool -importkeystore -srckeystore $jksfile -destkeystore $p12file \
        -srcstoretype JKS -deststoretype PKCS12 \
        -srcstorepass $jkspassword -deststorepass $p12password  
        -srcalias $myalias -destalias $myalias \
        -srckeypass $keypass -destkeypass $keypass -noprompt

And generate the pem file that holds only the key

 echo making ${fileroot}.key.pem
 openssl pkcs12 -in $p12 -out ${fileroot}.key.pem  \
         -passin pass:$p12password  \
         -passout pass:$p12password  -nocerts
  • Make an empty keystore:
mkdir ~/nss
chmod 700 ~/nss
certutil -N -d ~/nss
  • Import the keys into the keystore
pks12util -i <mykeys>.p12 -d ~/nss -W <password for cert >

Now curl should work.

curl --insecure --cert <client cert alias>:<password for cert> \
     --key ${fileroot}.key.pem  <URL>

As I mentioned, there may be other ways to do this, but at least this was repeatable for me. If curl is compiled with NSS support, I was not able to get it to pull the client cert from a file.

How can I stop the browser back button using JavaScript?

This article on jordanhollinger.com is the best option I feel. Similar to Razor's answer but a bit clearer. Code below; full credits to Jordan Hollinger:

Page before:

<a href="/page-of-no-return.htm#no-back>You can't go back from the next page</a>

Page of no return's JavaScript:

// It works without the History API, but will clutter up the history
var history_api = typeof history.pushState !== 'undefined'

// The previous page asks that it not be returned to
if ( location.hash == '#no-back' ) {
  // Push "#no-back" onto the history, making it the most recent "page"
  if ( history_api ) history.pushState(null, '', '#stay')
  else location.hash = '#stay'

  // When the back button is pressed, it will harmlessly change the url
  // hash from "#stay" to "#no-back", which triggers this function
  window.onhashchange = function() {
    // User tried to go back; warn user, rinse and repeat
    if ( location.hash == '#no-back' ) {
      alert("You shall not pass!")
      if ( history_api ) history.pushState(null, '', '#stay')
      else location.hash = '#stay'
    }
  }
}

Cannot implicitly convert type from Task<>

The main issue with your example that you can't implicitly convert Task<T> return types to the base T type. You need to use the Task.Result property. Note that Task.Result will block async code, and should be used carefully.

Try this instead:

public List<int> TestGetMethod()  
{  
    return GetIdList().Result;  
}

What is the difference between utf8mb4 and utf8 charsets in MySQL?

Taken from the MySQL 8.0 Reference Manual:

  • utf8mb4: A UTF-8 encoding of the Unicode character set using one to four bytes per character.

  • utf8mb3: A UTF-8 encoding of the Unicode character set using one to three bytes per character.

In MySQL utf8 is currently an alias for utf8mb3 which is deprecated and will be removed in a future MySQL release. At that point utf8 will become a reference to utf8mb4.

So regardless of this alias, you can consciously set yourself an utf8mb4 encoding.

To complete the answer, I'd like to add the @WilliamEntriken's comment below (also taken from the manual):

To avoid ambiguity about the meaning of utf8, consider specifying utf8mb4 explicitly for character set references instead of utf8.

Install mysql-python (Windows)

if you use the site http://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python , download the file:

  • mysqlclient-1.3.6-cp34-none-win32.whl or

  • mysqlclient-1.3.6-cp34-none-win_amd64.whl

depending on the version of python you have (these are for python 3.4) and the type of windows you have (x64 or x32)

extract this file into C:\Python34\Lib\site-packages and your project will work

How to call another controller Action From a controller in Mvc

Your sample looks like psuedo code. You need to return the result of RedirectToAction:

return RedirectToAction("B", 
                        "FileUploadMsgView",
                        new { FileUploadMsg = "File uploaded successfully" });

How to check size of a file using Bash?

ls -l $file | awk '{print $6}'

assuming that ls command reports filesize at column #6

HTTP authentication logout via PHP

Typically, once a browser has asked the user for credentials and supplied them to a particular web site, it will continue to do so without further prompting. Unlike the various ways you can clear cookies on the client side, I don't know of a similar way to ask the browser to forget its supplied authentication credentials.

Evaluate a string with a switch in C++

You can map the strings to enum values, then switch on the enum:

enum Options {
    Option_Invalid,
    Option1,
    Option2,
    //others...
};

Options resolveOption(string input);

//  ...later...

switch( resolveOption(input) )
{
    case Option1: {
        //...
        break;
    }
    case Option2: {
        //...
        break;
    }
    // handles Option_Invalid and any other missing/unmapped cases
    default: {
        //...
        break;
    }
}

Resolving the enum can be implemented as a series of if checks:

 Options resolveOption(std::string input) {
    if( input == "option1" ) return Option1;
    if( input == "option2" ) return Option2;
    //...
    return Option_Invalid;
 }

Or a map lookup:

 Options resolveOption(std::string input) {
    static const std::map<std::string, Option> optionStrings {
        { "option1", Option1 },
        { "option2", Option2 },
        //...
    };

    auto itr = optionStrings.find(input);
    if( itr != optionStrings.end() ) {
        return *itr;
    }
    return Option_Invalid; 
}

Read file from resources folder in Spring Boot

For me, the bug had two fixes.

  1. Xml file which was named as SAMPLE.XML which was causing even the below solution to fail when deployed to aws ec2. The fix was to rename it to new_sample.xml and apply the solution given below.
  2. Solution approach https://medium.com/@jonathan.henrique.smtp/reading-files-in-resource-path-from-jar-artifact-459ce00d2130

I was using Spring boot as jar and deployed to aws ec2 Java variant of the solution is as below :

package com.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.Resource;


public class XmlReader {

    private static Logger LOGGER = LoggerFactory.getLogger(XmlReader.class);

  public static void main(String[] args) {


      String fileLocation = "classpath:cbs_response.xml";
      String reponseXML = null;
      try (ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext()){

        Resource resource = appContext.getResource(fileLocation);
        if (resource.isReadable()) {
          BufferedReader reader =
              new BufferedReader(new InputStreamReader(resource.getInputStream()));
          Stream<String> lines = reader.lines();
          reponseXML = lines.collect(Collectors.joining("\n"));

        }      
      } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
      }
  }
}

How to convert unix timestamp to calendar date moment.js

Moment.js provides Localized formats which can be used.

Here is an example:

const moment = require('moment');

const timestamp = 1519482900000;
const formatted = moment(timestamp).format('L');

console.log(formatted); // "02/24/2018"

Replace all 0 values to NA

#Sample data
set.seed(1)
dat <- data.frame(x = sample(0:2, 5, TRUE), y = sample(0:2, 5, TRUE))
#-----
  x y
1 0 2
2 1 2
3 1 1
4 2 1
5 0 0

#replace zeros with NA
dat[dat==0] <- NA
#-----
   x  y
1 NA  2
2  1  2
3  1  1
4  2  1
5 NA NA

android download pdf from url then open it with a pdf reader

Hi the problem is in FileDownloader class

 urlConnection.setRequestMethod("GET");
    urlConnection.setDoOutput(true);

You need to remove the above two lines and everything will work fine. Please mark the question as answered if it is working as expected.

Latest solution for the same problem is updated Android PDF Write / Read using Android 9 (API level 28)

Attaching the working code with screenshots.

enter image description here

enter image description here

MainActivity.java

package com.example.downloadread;

import java.io.File;
import java.io.IOException;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    public void download(View v)
    {
        new DownloadFile().execute("http://maven.apache.org/maven-1.x/maven.pdf", "maven.pdf"); 
    }

    public void view(View v)
    {
        File pdfFile = new File(Environment.getExternalStorageDirectory() + "/testthreepdf/" + "maven.pdf");  // -> filename = maven.pdf
        Uri path = Uri.fromFile(pdfFile);
        Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
        pdfIntent.setDataAndType(path, "application/pdf");
        pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        try{
            startActivity(pdfIntent);
        }catch(ActivityNotFoundException e){
            Toast.makeText(MainActivity.this, "No Application available to view PDF", Toast.LENGTH_SHORT).show();
        }
    }

    private class DownloadFile extends AsyncTask<String, Void, Void>{

        @Override
        protected Void doInBackground(String... strings) {
            String fileUrl = strings[0];   // -> http://maven.apache.org/maven-1.x/maven.pdf
            String fileName = strings[1];  // -> maven.pdf
            String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
            File folder = new File(extStorageDirectory, "testthreepdf");
            folder.mkdir();

            File pdfFile = new File(folder, fileName);

            try{
                pdfFile.createNewFile();
            }catch (IOException e){
                e.printStackTrace();
            }
            FileDownloader.downloadFile(fileUrl, pdfFile);
            return null;
        }
    }


}

FileDownloader.java

package com.example.downloadread;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class FileDownloader {
    private static final int  MEGABYTE = 1024 * 1024;

    public static void downloadFile(String fileUrl, File directory){
        try {

            URL url = new URL(fileUrl);
            HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
            //urlConnection.setRequestMethod("GET");
            //urlConnection.setDoOutput(true);
            urlConnection.connect();

            InputStream inputStream = urlConnection.getInputStream();
            FileOutputStream fileOutputStream = new FileOutputStream(directory);
            int totalSize = urlConnection.getContentLength();

            byte[] buffer = new byte[MEGABYTE];
            int bufferLength = 0;
            while((bufferLength = inputStream.read(buffer))>0 ){
                fileOutputStream.write(buffer, 0, bufferLength);
            }
            fileOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.downloadread"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="18" />
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
    <uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.downloadread.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="15dp"
        android:text="download"
        android:onClick="download" />

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/button1"
        android:layout_marginTop="38dp"
        android:text="view"
        android:onClick="view" />

</RelativeLayout>

Update row values where certain condition is met in pandas

You can do the same with .ix, like this:

In [1]: df = pd.DataFrame(np.random.randn(5,4), columns=list('abcd'))

In [2]: df
Out[2]: 
          a         b         c         d
0 -0.323772  0.839542  0.173414 -1.341793
1 -1.001287  0.676910  0.465536  0.229544
2  0.963484 -0.905302 -0.435821  1.934512
3  0.266113 -0.034305 -0.110272 -0.720599
4 -0.522134 -0.913792  1.862832  0.314315

In [3]: df.ix[df.a>0, ['b','c']] = 0

In [4]: df
Out[4]: 
          a         b         c         d
0 -0.323772  0.839542  0.173414 -1.341793
1 -1.001287  0.676910  0.465536  0.229544
2  0.963484  0.000000  0.000000  1.934512
3  0.266113  0.000000  0.000000 -0.720599
4 -0.522134 -0.913792  1.862832  0.314315

EDIT

After the extra information, the following will return all columns - where some condition is met - with halved values:

>> condition = df.a > 0
>> df[condition][[i for i in df.columns.values if i not in ['a']]].apply(lambda x: x/2)

I hope this helps!

Inner text shadow with CSS

Building on the :before :after technique by web_designer, here is something that comes closer to your look:

First, make your text the color of the inner shadow (black-ish in the case of the OP).

Now, use an :after psuedo class to create a transparent duplicate of the original text, placed directly on top of it. Assign a regular text shadow to it with no offset. Assign the original text color to the shadow, and adjust alpha as needed.

http://dabblet.com/gist/2499892

You don't get complete control over spread, etc. of the shadow like you do in PS, but for smaller blur values it is quite passable. The shadow goes past the bounds of the text, so if you are working in an environment with a high contrast background-foreground, it will be obvious. For lower contrast items, especially ones with the same hue, it's not too noticeable. For example, I've been able to make very nice looking etched text in metal backgrounds using this technique.

XML Schema How to Restrict Attribute by Enumeration

The numerical value seems to be missing from your price definition. Try the following:

<xs:simpleType name="curr">
  <xs:restriction base="xs:string">
    <xs:enumeration value="pounds" />
    <xs:enumeration value="euros" />
    <xs:enumeration value="dollars" />
  </xs:restriction>
</xs:simpleType>



<xs:element name="price">
        <xs:complexType>
            <xs:extension base="xs:decimal">
              <xs:attribute name="currency" type="curr"/>
            </xs:extension>
        </xs:complexType>
</xs:element>

Clear Cache in Android Application programmatically

Try this

@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    clearApplicationData();
}

public void clearApplicationData() {
    File cache = getCacheDir();
    File appDir = new File(cache.getParent());
    if (appDir.exists()) {
        String[] children = appDir.list();
        for (String s : children) {
            if (!s.equals("lib")) {
                deleteDir(new File(appDir, s));
                Log.i("EEEEEERRRRRROOOOOOORRRR", "**************** File /data/data/APP_PACKAGE/" + s + " DELETED *******************");
            }
        }
    }
}

public static boolean deleteDir(File dir) {
    if (dir != null && dir.isDirectory()) {
        String[] children = dir.list();
        int i = 0;
        while (i < children.length) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
                return false;
            }
            i++;
        }
    }

    assert dir != null;
    return dir.delete();
}

Background blur with CSS

There is a simple and very common technique by using 2 background images: a crisp and a blurry one. You set the crisp image as a background for the body and the blurry one as a background image for your container. The blurry image must be set to fixed positioning and the alignment is 100% perfect. I used it before and it works.

body {
    background: url(yourCrispImage.jpg) no-repeat;
}

#container {
    background: url(yourBlurryImage.jpg) no-repeat fixed;
}

You can see a working example at the following fiddle: http://jsfiddle.net/jTUjT/5/. Try to resize the browser and see that the alignment never fails.


If only CSS element() was supported by other browsers other than Mozilla's -moz-element() you could create great effects. See this demo with Mozilla.

How to add Date Picker Bootstrap 3 on MVC 5 project using the Razor engine?

This answer simply applies the type=date attribute to the HTML input element and relies on the browser to supply a date picker. Note that even in 2017, not all browsers provide their own date picker, so you may want to provide a fall back.

All you have to do is add attributes to the property in the view model. Example for variable Ldate:

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
Public DateTime Ldate {get;set;}

Assuming you're using MVC 5 and Visual Studio 2013.

jQuery Ajax requests are getting cancelled without being sent

I had this error in a more spooky way: The network tab and the chrome://net-internals/#events did not show the request after the js was completed. When pausing the js in the error callcack the network tab did show the request as (cancelled). The was consistently called for exactly one (always the same) of several similar requests in a webpage. After restarting Chrome the error did not rise again!

"Unorderable types: int() < str()"

The issue here is that input() returns a string in Python 3.x, so when you do your comparison, you are comparing a string and an integer, which isn't well defined (what if the string is a word, how does one compare a string and a number?) - in this case Python doesn't guess, it throws an error.

To fix this, simply call int() to convert your string to an integer:

int(input(...))

As a note, if you want to deal with decimal numbers, you will want to use one of float() or decimal.Decimal() (depending on your accuracy and speed needs).

Note that the more pythonic way of looping over a series of numbers (as opposed to a while loop and counting) is to use range(). For example:

def main():
    print("Let me Retire Financial Calculator")
    deposit = float(input("Please input annual deposit in dollars: $"))
    rate = int(input ("Please input annual rate in percentage: %")) / 100
    time = int(input("How many years until retirement?"))
    value = 0
    for x in range(1, time+1):
        value = (value * rate) + deposit
        print("The value of your account after" + str(x) + "years will be $" + str(value))

how to read all files inside particular folder

Try this It is working for me..

The syntax is GetFiles(string path, string searchPattern);

var filePath = Server.MapPath("~/App_Data/");
string[] filePaths = Directory.GetFiles(@filePath, "*.*");

This code will return all the files inside App_Data folder.

The second parameter . indicates the searchPattern with File Extension where the first * is for file name and second is for format of the file or File Extension like (*.png - any file name with .png format.

MySQL: ignore errors when importing?

Use the --force (-f) flag on your mysql import. Rather than stopping on the offending statement, MySQL will continue and just log the errors to the console.

For example:

mysql -u userName -p -f -D dbName < script.sql

I want to remove double quotes from a String

If you're trying to remove the double quotes try following

  var Stringstr = "\"I am here\"";
  var mystring = String(Stringstr);
  mystring = mystring.substring(1, mystring.length - 1);
  alert(mystring);

Best Practice: Initialize JUnit class fields in setUp() or at declaration?

If you're wondering specifically about the examples in the JUnit FAQ, such as the basic test template, I think the best practice being shown off there is that the class under test should be instantiated in your setUp method (or in a test method).

When the JUnit examples create an ArrayList in the setUp method, they all go on to test the behavior of that ArrayList, with cases like testIndexOutOfBoundException, testEmptyCollection, and the like. The perspective there is of someone writing a class and making sure it works right.

You should probably do the same when testing your own classes: create your object in setUp or in a test method, so that you'll be able to get reasonable output if you break it later.

On the other hand, if you use a Java collection class (or other library class, for that matter) in your test code, it's probably not because you want to test it--it's just part of the test fixture. In this case, you can safely assume it works as intended, so initializing it in the declaration won't be a problem.

For what it's worth, I work on a reasonably large, several-year-old, TDD-developed code base. We habitually initialize things in their declarations in test code, and in the year and a half that I've been on this project, it has never caused a problem. So there's at least some anecdotal evidence that it's a reasonable thing to do.

Uncaught SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode

This means that you must declare strict mode by writing "use strict" at the beginning of the file or the function to use block-scope declarations.

EX:

function test(){
    "use strict";
    let a = 1;
} 

LINQ to SQL using GROUP BY and COUNT(DISTINCT)

This is how you do a distinct count query. Note that you have to filter out the nulls.

var useranswercount = (from a in tpoll_answer
where user_nbr != null && answer_nbr != null
select user_nbr).Distinct().Count();

If you combine this with into your current grouping code, I think you'll have your solution.

addEventListener, "change" and option selection

The problem is that you used the select option, this is where you went wrong. Select signifies that a textbox or textArea has a focus. What you need to do is use change. "Fires when a new choice is made in a select element", also used like blur when moving away from a textbox or textArea.

function start(){
      document.getElementById("activitySelector").addEventListener("change", addActivityItem, false);
      }

function addActivityItem(){
      //option is selected
      alert("yeah");
}

window.addEventListener("load", start, false);

What are the new features in C++17?

Language features:

Templates and Generic Code

Lambda

Attributes

Syntax cleanup

Cleaner multi-return and flow control

  • Structured bindings

    • Basically, first-class std::tie with auto
    • Example:
      • const auto [it, inserted] = map.insert( {"foo", bar} );
      • Creates variables it and inserted with deduced type from the pair that map::insert returns.
    • Works with tuple/pair-likes & std::arrays and relatively flat structs
    • Actually named structured bindings in standard
  • if (init; condition) and switch (init; condition)

    • if (const auto [it, inserted] = map.insert( {"foo", bar} ); inserted)
    • Extends the if(decl) to cases where decl isn't convertible-to-bool sensibly.
  • Generalizing range-based for loops

    • Appears to be mostly support for sentinels, or end iterators that are not the same type as begin iterators, which helps with null-terminated loops and the like.
  • if constexpr

    • Much requested feature to simplify almost-generic code.

Misc

Library additions:

Data types

Invoke stuff

File System TS v1

New algorithms

  • for_each_n

  • reduce

  • transform_reduce

  • exclusive_scan

  • inclusive_scan

  • transform_exclusive_scan

  • transform_inclusive_scan

  • Added for threading purposes, exposed even if you aren't using them threaded

Threading

(parts of) Library Fundamentals TS v1 not covered above or below

Container Improvements

Smart pointer changes

Other std datatype improvements:

Misc

Traits

Deprecated

Isocpp.org has has an independent list of changes since C++14; it has been partly pillaged.

Naturally TS work continues in parallel, so there are some TS that are not-quite-ripe that will have to wait for the next iteration. The target for the next iteration is C++20 as previously planned, not C++19 as some rumors implied. C++1O has been avoided.

Initial list taken from this reddit post and this reddit post, with links added via googling or from the above isocpp.org page.

Additional entries pillaged from SD-6 feature-test list.

clang's feature list and library feature list are next to be pillaged. This doesn't seem to be reliable, as it is C++1z, not C++17.

these slides had some features missing elsewhere.

While "what was removed" was not asked, here is a short list of a few things ((mostly?) previous deprecated) that are removed in C++17 from C++:

Removed:

There were rewordings. I am unsure if these have any impact on code, or if they are just cleanups in the standard:

Papers not yet integrated into above:

  • P0505R0 (constexpr chrono)

  • P0418R2 (atomic tweaks)

  • P0512R0 (template argument deduction tweaks)

  • P0490R0 (structured binding tweaks)

  • P0513R0 (changes to std::hash)

  • P0502R0 (parallel exceptions)

  • P0509R1 (updating restrictions on exception handling)

  • P0012R1 (make exception specifications be part of the type system)

  • P0510R0 (restrictions on variants)

  • P0504R0 (tags for optional/variant/any)

  • P0497R0 (shared ptr tweaks)

  • P0508R0 (structured bindings node handles)

  • P0521R0 (shared pointer use count and unique changes?)

Spec changes:

Further reference:

How to sort a List of objects by their date (java collections, List<Object>)

In your compare method, o1 and o2 are already elements in the movieItems list. So, you should do something like this:

Collections.sort(movieItems, new Comparator<Movie>() {
    public int compare(Movie m1, Movie m2) {
        return m1.getDate().compareTo(m2.getDate());
    }
});

Does Visual Studio Code have box select/multi-line edit?

On Windows it's holding down Alt while box selecting. Once you have your selection then attempt your edit.

Apache VirtualHost 403 Forbidden

This works on Linux Fedora for VirtualHost : ( Lampp/Xampp )

Go to : /opt/lampp/etc/extra

Open : httpd-vhosts.conf

Insert this in httpd-vhosts.conf

<VirtualHost *:80>
ServerAdmin [email protected]
DocumentRoot "/opt/lampp/APPS/My_App"
ServerName votemo.test
ServerAlias www.votemo.test
ErrorLog "logs/votemo.test-error_log"
CustomLog "logs/votemo.test-access_log" common
<Directory "/opt/lampp/APPS/My_App">
    Options FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>

p.s. : Don't forget to comment the previous exemple already present in httpd-vhosts.conf

Set your hosts system file :

Go to : /etc/ folder find hosts file ( /etc/hosts )

I insert this : (but not sure to 100% if this good)

127.0.0.1       votemo.test

::1         votemo.test

-> Open or Restart Apache.

Open a console and paste this command for open a XAMPP graphic interface :

sudo /opt/lampp/manager-linux-x64.run

Note : Adjust path how you want to your app folder

ex: DocumentRoot "/home/USER/Desktop/My_Project"

and set directory path too :

ex : ... <Directory "/home/USER/Desktop/My_Project"> ...

But this should be tested, comment if this work ...

Additionnal notes :

  • Localisation Lampp folder : (Path) /opt/lampp

  • Start Lampp : sudo /opt/lampp/lampp start

  • Adjust rights if needed : sudo chmod o+w /opt/lampp/manager-linux-x64.run

  • Path to hosts file : /etc/hosts

How to pass an array to a function in VBA?

Your function worked for me after changing its declaration to this ...

Function processArr(Arr As Variant) As String

You could also consider a ParamArray like this ...

Function processArr(ParamArray Arr() As Variant) As String
    'Dim N As Variant
    Dim N As Long
    Dim finalStr As String
    For N = LBound(Arr) To UBound(Arr)
        finalStr = finalStr & Arr(N)
    Next N
    processArr = finalStr
End Function

And then call the function like this ...

processArr("foo", "bar")

Read file line by line using ifstream in C++

Since your coordinates belong together as pairs, why not write a struct for them?

struct CoordinatePair
{
    int x;
    int y;
};

Then you can write an overloaded extraction operator for istreams:

std::istream& operator>>(std::istream& is, CoordinatePair& coordinates)
{
    is >> coordinates.x >> coordinates.y;

    return is;
}

And then you can read a file of coordinates straight into a vector like this:

#include <fstream>
#include <iterator>
#include <vector>

int main()
{
    char filename[] = "coordinates.txt";
    std::vector<CoordinatePair> v;
    std::ifstream ifs(filename);
    if (ifs) {
        std::copy(std::istream_iterator<CoordinatePair>(ifs), 
                std::istream_iterator<CoordinatePair>(),
                std::back_inserter(v));
    }
    else {
        std::cerr << "Couldn't open " << filename << " for reading\n";
    }
    // Now you can work with the contents of v
}

Arrow operator (->) usage in C

Dot is a dereference operator and used to connect the structure variable for a particular record of structure. Eg :

struct student
    {
      int s.no;
      Char name [];
      int age;
    } s1,s2;

main()
    {
      s1.name;
      s2.name;
    }

In such way we can use a dot operator to access the structure variable

How to style the option of an html "select" element?

Bootstrap allows you to use styling via data-content:

<select class="selectpicker">
  <option data-content="<span class='label label-success'>Relish</span>">Relish</option>
</select>

Example: https://silviomoreto.github.io/bootstrap-select/examples/

javascript: get a function's variable's value within another function

you need a return statement in your first function.

function first(){
    var nameContent = document.getElementById('full_name').value;
    return nameContent;
}

and then in your second function can be:

function second(){
    alert(first());
}

how to drop database in sqlite?

From http://www.sqlite.org/cvstrac/wiki?p=UnsupportedSql

To create a new database, just do sqlite_open(). To drop a database, delete the file.

Android: Quit application when press back button

try this

Intent a = new Intent(Intent.ACTION_MAIN);
a.addCategory(Intent.CATEGORY_HOME);
a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(a);

More than 1 row in <Input type="textarea" />

The "input" tag doesn't support rows and cols attributes. This is why the best alternative is to use a textarea with rows and cols attributes. You can still add a "name" attribute and also there is a useful "wrap" attribute which can serve pretty well in various situations.

Can't access Tomcat using IP address

I was also facing same problem on Amazon windows EC2 instance ( Windows Server 2012 R2 ) Then I figured out , it was local windows firewall preventing it . I opened port 80 ( defined port for website ) using windows Firewall with Advance Security .

It resolved the issue .

How to install a node.js module without using npm?

Download the code from github into the node_modules directory

var moduleName = require("<name of directory>")

that should do it.

if the module has dependancies and has a package.json, open the module and enter npm install.

Hope this helps

Android Support Design TabLayout: Gravity Center and Mode Scrollable

I solved this using following

if(tabLayout_chemistCategory.getTabCount()<4)
    {
        tabLayout_chemistCategory.setTabGravity(TabLayout.GRAVITY_FILL);
    }else
    {
        tabLayout_chemistCategory.setTabMode(TabLayout.MODE_SCROLLABLE);

    }

Disable/Enable button in Excel/VBA

too good !!! it's working and resolved my one day old problem easily

Dim b1 As Button

Set b1 = ActiveSheet.Buttons("Button 1")


b1.Enabled = False

Split string with string as delimiter

Try this:

for /F "tokens=1,3 delims=. " %%a in ("%string%") do (
   echo %%a
   echo %%b
)

that is, take the first and third tokens delimited by space or point...

How to add hours to current time in python

from datetime import datetime, timedelta

nine_hours_from_now = datetime.now() + timedelta(hours=9)
#datetime.datetime(2012, 12, 3, 23, 24, 31, 774118)

And then use string formatting to get the relevant pieces:

>>> '{:%H:%M:%S}'.format(nine_hours_from_now)
'23:24:31'

If you're only formatting the datetime then you can use:

>>> format(nine_hours_from_now, '%H:%M:%S')
'23:24:31'

Or, as @eumiro has pointed out in comments - strftime

How to HTML encode/escape a string? Is there a built-in?

In Ruby on Rails 3 HTML will be escaped by default.

For non-escaped strings use:

<%= raw "<p>hello world!</p>" %>

How to make the window full screen with Javascript (stretching all over the screen)

Here is my full solution for Full Screen and Exit Full Screen both (many thanks to help from tower's answer above):

$(document).ready(function(){
$.is_fs = false;
$.requestFullScreen = function(calr)
{
    var element = document.body;

    // Supports most browsers and their versions.
    var requestMethod = element.requestFullScreen || element.webkitRequestFullScreen || element.mozRequestFullScreen || element.msRequestFullScreen;

    if (requestMethod) { // Native full screen.
        requestMethod.call(element);
    } else if (typeof window.ActiveXObject !== "undefined") { // Older IE.
        var wscript = new ActiveXObject("WScript.Shell");
        if (wscript !== null) {
            wscript.SendKeys("{F11}");
        }
    }

    $.is_fs = true;    
    $(calr).val('Exit Full Screen');
}

$.cancel_fs = function(calr)
{
    var element = document; //and NOT document.body!!
    var requestMethod = element.exitFullScreen || element.mozCancelFullScreen || element.webkitExitFullScreen || element.mozExitFullScreen || element.msExitFullScreen || element.webkitCancelFullScreen;

    if (requestMethod) { // Native full screen.
    requestMethod.call(element);
    } else if (typeof window.ActiveXObject !== "undefined") { // Older IE.
        var wscript = new ActiveXObject("WScript.Shell");
        if (wscript !== null) {
            wscript.SendKeys("{F11}");
        }
    }    

    $(calr).val('Full Screen');    
    $.is_fs = false;
}

$.toggleFS = function(calr)
{    
    $.is_fs == true? $.cancel_fs(calr):$.requestFullScreen(calr);
}

});

// CALLING:

<input type="button" value="Full Screen" onclick="$.toggleFS(this);" />

BOOLEAN or TINYINT confusion

As of MySql 5.1 version reference

BIT(M) =  approximately (M+7)/8 bytes, 
BIT(1) =  (1+7)/8 = 1 bytes (8 bits)

=========================================================================

TINYINT(1) take 8 bits.

https://dev.mysql.com/doc/refman/5.7/en/storage-requirements.html#data-types-storage-reqs-numeric

Can I simultaneously declare and assign a variable in VBA?

You can sort-of do that with objects, as in the following.

Dim w As New Widget

But not with strings or variants.

Contains method for a slice

Currently there's Contains function in slice package. You can read the docs here.

Sample usage :

if !slice.Contains(sliceVar, valueToFind) {
    //code here
}

How to access the GET parameters after "?" in Express?

In my case with the given code, I was able to parse the value of the passed parameter in this way.

_x000D_
_x000D_
const express = require('express');
const bodyParser = require('body-parser');

const app = express(); 
app.use(bodyParser.urlencoded({ extended: false }));
//url/par1=val1&par2=val2 
let val1= req.body.par1;
let val2 = req.body.par2;
_x000D_
_x000D_
_x000D_

How to return a boolean method in java?

public boolean verifyPwd(){
        if (!(pword.equals(pwdRetypePwd.getText()))){
                  txtaError.setEditable(true);
                  txtaError.setText("*Password didn't match!");
                  txtaError.setForeground(Color.red);
                  txtaError.setEditable(false);
                  return false;
           }
        else {
            addNewUser();
            return true;
        }
}

HTML5 video won't play in Chrome only

Have you tried by setting the MIME type of your .m4v to "video/m4v" or "video/x-m4v" ?

Browsers might use the canPlayType method internally to check if a <source> is candidate to playback.

In Chrome, I have these results:

document.createElement("video").canPlayType("video/mp4"); // "maybe"
document.createElement("video").canPlayType("video/m4v"); // ""
document.createElement("video").canPlayType("video/x-m4v"); // "maybe"

What does OpenCV's cvWaitKey( ) function do?

The cvWaitKey simply provides something of a delay. For example:

char c = cvWaitKey(33);
if( c == 27 ) break;

Tis was apart of my code in which a video was loaded into openCV and the frames outputted. The 33 number in the code means that after 33ms, a new frame would be shown. Hence, the was a dely or time interval of 33ms between each frame being shown on the screen. Hope this helps.

WCF error: The caller was not authenticated by the service

I got it.

If you want to use wshttpbinding, u need to add windows credentials as below.

svc.ClientCredentials.Windows.ClientCredential.UserName = "abc";
svc.ClientCredentials.Windows.ClientCredential.Password = "xxx";

thanks

How to comment multiple lines in Visual Studio Code?

For windows, the default key for multi-line comment is Alt + Shift + A

For windows, the default key for single line comment is Ctrl + /

what is trailing whitespace and how can I handle this?

I have got similar pep8 warning W291 trailing whitespace

long_text = '''Lorem Ipsum is simply dummy text  <-remove whitespace
of the printing and typesetting industry.'''

Try to explore trailing whitespaces and remove them. ex: two whitespaces at the end of Lorem Ipsum is simply dummy text

Oracle JDBC intermittent Connection Issue

Just to clarify - at least from what we found on our side! It is an issue with the setup of the randomizer for Linux in the JDK distribution - and we found it in Java6, not sure about Java7. The syntax for linux for the randomizer is file:///dev/urandom, but the entry in the file is (probably left/copied from Windows) as file:/dev/urandom. So then Java probably falls back on the default, which happens to be /dev/random. And which doesn't work on a headless machine!!!

Example: Communication between Activity and Service using Messaging

Great tutorial, fantastic presentation. Neat, simple, short and very explanatory. Although, notification.setLatestEventInfo(this, getText(R.string.service_label), text, contentIntent); method is no more. As trante stated here, good approach would be:

private static final int NOTIFICATION_ID = 45349;

private void showNotification() {
    NotificationCompat.Builder builder =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("My Notification Title")
                    .setContentText("Something interesting happened");

    Intent targetIntent = new Intent(this, MainActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, targetIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(contentIntent);
    _nManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    _nManager.notify(NOTIFICATION_ID, builder.build());
}

@Override
public void onDestroy() {
    super.onDestroy();
    if (_timer != null) {_timer.cancel();}
    _counter=0;
    _nManager.cancel(NOTIFICATION_ID); // Cancel the persistent notification.
    Log.i("PlaybackService", "Service Stopped.");
    _isRunning = false;
}

Checked myself, everything works like a charm (activity and service names may differ from original).

Stop/Close webcam stream which is opened by navigator.mediaDevices.getUserMedia

Have a reference of stream form successHandle

var streamRef;

var handleVideo = function (stream) {
    streamRef = stream;
}

//this will stop video and audio both track
streamRef.getTracks().map(function (val) {
    val.stop();
});

Why compile Python code?

There's certainly a performance difference when running a compiled script. If you run normal .py scripts, the machine compiles it every time it is run and this takes time. On modern machines this is hardly noticeable but as the script grows it may become more of an issue.

Zoom to fit: PDF Embedded in HTML

This method uses "object", it also has "embed". Either method works:

<div id="pdf">
    <object id="pdf_content" width="100%" height="1500px" type="application/pdf" trusted="yes" application="yes" title="Assembly" data="Assembly.pdf?#zoom=100&scrollbar=1&toolbar=1&navpanes=1">
    <!-- <embed src="Assembly.pdf" width="100%" height="100%" type="application/x-pdf" trusted="yes" application="yes" title="Assembly">
    </embed> -->
    <p>System Error - This PDF cannot be displayed, please contact IT.</p>
    </object>
</div>

Stopping a JavaScript function when a certain condition is met

Use a try...catch statement in your main function and whenever you want to stop the function just use:

throw new Error("Stopping the function!");

how to exit a python script in an if statement

This works fine for me:

while True:
   answer = input('Do you want to continue?:')
   if answer.lower().startswith("y"):
      print("ok, carry on then")
   elif answer.lower().startswith("n"):
      print("sayonara, Robocop")
      exit()

edit: use input in python 3.2 instead of raw_input

What is a NullPointerException, and how do I fix it?

When you declare a reference variable (i.e., an object), you are really creating a pointer to an object. Consider the following code where you declare a variable of primitive type int:

int x;
x = 10;

In this example, the variable x is an int and Java will initialize it to 0 for you. When you assign the value of 10 on the second line, your value of 10 is written into the memory location referred to by x.

But, when you try to declare a reference type, something different happens. Take the following code:

Integer num;
num = new Integer(10);

The first line declares a variable named num, but it does not actually contain a primitive value yet. Instead, it contains a pointer (because the type is Integer which is a reference type). Since you have not yet said what to point to, Java sets it to null, which means "I am pointing to nothing".

In the second line, the new keyword is used to instantiate (or create) an object of type Integer, and the pointer variable num is assigned to that Integer object.

The NullPointerException (NPE) occurs when you declare a variable but did not create an object and assign it to the variable before trying to use the contents of the variable (called dereferencing). So you are pointing to something that does not actually exist.

Dereferencing usually happens when using . to access a method or field, or using [ to index an array.

If you attempt to dereference num before creating the object you get a NullPointerException. In the most trivial cases, the compiler will catch the problem and let you know that "num may not have been initialized," but sometimes you may write code that does not directly create the object.

For instance, you may have a method as follows:

public void doSomething(SomeObject obj) {
   // Do something to obj, assumes obj is not null
   obj.myMethod();
}

In which case, you are not creating the object obj, but rather assuming that it was created before the doSomething() method was called. Note, it is possible to call the method like this:

doSomething(null);

In which case, obj is null, and the statement obj.myMethod() will throw a NullPointerException.

If the method is intended to do something to the passed-in object as the above method does, it is appropriate to throw the NullPointerException because it's a programmer error and the programmer will need that information for debugging purposes.

In addition to NullPointerExceptions thrown as a result of the method's logic, you can also check the method arguments for null values and throw NPEs explicitly by adding something like the following near the beginning of a method:

// Throws an NPE with a custom error message if obj is null
Objects.requireNonNull(obj, "obj must not be null");

Note that it's helpful to say in your error message clearly which object cannot be null. The advantage of validating this is that 1) you can return your own clearer error messages and 2) for the rest of the method you know that unless obj is reassigned, it is not null and can be dereferenced safely.

Alternatively, there may be cases where the purpose of the method is not solely to operate on the passed in object, and therefore a null parameter may be acceptable. In this case, you would need to check for a null parameter and behave differently. You should also explain this in the documentation. For example, doSomething() could be written as:

/**
  * @param obj An optional foo for ____. May be null, in which case
  *  the result will be ____.
  */
public void doSomething(SomeObject obj) {
    if(obj == null) {
       // Do something
    } else {
       // Do something else
    }
}

Finally, How to pinpoint the exception & cause using Stack Trace

What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely?

Sonar with find bugs can detect NPE. Can sonar catch null pointer exceptions caused by JVM Dynamically

Now Java 14 has added a new language feature to show the root cause of NullPointerException. This language feature has been part of SAP commercial JVM since 2006. The following is 2 minutes read to understand this amazing language feature.

https://jfeatures.com/blog/NullPointerException

In Java 14, the following is a sample NullPointerException Exception message:

in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.List.size()" because "list" is null

SQL set values of one column equal to values of another column in the same table

Sounds like you're working in just one table so something like this:

update your_table
set B = A
where B is null

Form Submit Execute JavaScript Best Practice?

Attach an event handler to the submit event of the form. Make sure it cancels the default action.

Quirks Mode has a guide to event handlers, but you would probably be better off using a library to simplify the code and iron out the differences between browsers. All the major ones (such as YUI and jQuery) include event handling features, and there is a large collection of tiny event libraries.

Here is how you would do it in YUI 3:

<script src="http://yui.yahooapis.com/3.4.1/build/yui/yui-min.js"></script>
<script>
    YUI().use('event', function (Y) {
        Y.one('form').on('submit', function (e) {
            // Whatever else you want to do goes here
            e.preventDefault();
        });
    });
</script>

Make sure that the server will pick up the slack if the JavaScript fails for any reason.

Get sum of MySQL column in PHP

$row['Value'] is probably a string. Try using intval($row['Value']).

Also, make sure you set $sum = 0 before the loop.

Or, better yet, add SUM(Value) AS Val_Sum to your SQL query.

Can I send a ctrl-C (SIGINT) to an application on Windows?

Yes. The windows-kill project does exactly what you want:

windows-kill -SIGINT 1234

Get the current file name in gulp.src()

I found this plugin to be doing what I was expecting: gulp-using

Simple usage example: Search all files in project with .jsx extension

gulp.task('reactify', function(){
        gulp.src(['../**/*.jsx']) 
            .pipe(using({}));
        ....
    });

Output:

[gulp] Using gulpfile /app/build/gulpfile.js
[gulp] Starting 'reactify'...
[gulp] Finished 'reactify' after 2.92 ms
[gulp] Using file /app/staging/web/content/view/logon.jsx
[gulp] Using file /app/staging/web/content/view/components/rauth.jsx

AVD Manager - No system image installed for this target

you should android sdk manager install 4.2 api 17 -> ARM EABI v7a System Image

if not installed ARM EABI v7a System Image, you should install all.

HTTP 400 (bad request) for logical error, not malformed request syntax

Status 422 (RFC 4918, Section 11.2) comes to mind:

The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.

Scroll RecyclerView to show selected item on top

//Scroll item pos

linearLayoutManager.scrollToPositionWithOffset(pos, 0);

PHP/Apache: PHP Fatal error: Call to undefined function mysql_connect()

The Apache module PHP version might for some odd reason not be picking up the php.ini file as the CLI version I'd suggest having a good look at:

  • Any differences in the .ini files that differ between php -i and phpinfo() via a web page*
  • If there are no differences then to look at the permissions of mysql.so and the .ini files but I think that Apache parses these as the root user

To be really clear here, don't go searching for php.ini files on the file system, have a look at what PHP says that it's looking at

Setting a max character length in CSS

With Chrome you can set the number of lines displayed with "-webkit-line-clamp" :

     display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 3;  /* Number of lines displayed before it truncate */
     overflow: hidden;

So for me it is to use in an extension so it is perfect, more information here: https://medium.com/mofed/css-line-clamp-the-good-the-bad-and-the-straight-up-broken-865413f16e5

JavaScript - Get minutes between two dates

You may checkout this code:

_x000D_
_x000D_
var today = new Date();_x000D_
var Christmas = new Date("2012-12-25");_x000D_
var diffMs = (Christmas - today); // milliseconds between now & Christmas_x000D_
var diffDays = Math.floor(diffMs / 86400000); // days_x000D_
var diffHrs = Math.floor((diffMs % 86400000) / 3600000); // hours_x000D_
var diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000); // minutes_x000D_
alert(diffDays + " days, " + diffHrs + " hours, " + diffMins + " minutes until Christmas 2009 =)");
_x000D_
_x000D_
_x000D_

or var diffMins = Math.floor((... to discard seconds if you don't want to round minutes.

java.lang.IllegalAccessError: tried to access method

In my case the problem was that a method was defined in some Interface A as default, while its sub-class overrode it as private. Then when the method was called, the java Runtime realized it was calling a private method.

I am still puzzled as to why the compiler didn't complain about the private override..

public interface A {
     default void doStuff() {
         // doing stuff
     }
}

public class B {
     private void doStuff() {
         // do other stuff instead
     }
}

public static final main(String... args) {
    A someB = new B();
    someB.doStuff();
}

Concatenating variables in Bash

Try doing this, there's no special character to concatenate in bash :

mystring="${arg1}12${arg2}endoffile"

explanations

If you don't put brackets, you will ask to concatenate $arg112 + $argendoffile (I guess that's not what you asked) like in the following example :

mystring="$arg112$arg2endoffile"

The brackets are delimiters for the variables when needed. When not needed, you can use it or not.

another solution

(less portable : require bash > 3.1)

$ arg1=foo
$ arg2=bar
$ mystring="$arg1"
$ mystring+="12"
$ mystring+="$arg2"
$ mystring+="endoffile"
$ echo "$mystring"
foo12barendoffile

See http://mywiki.wooledge.org/BashFAQ/013

Eclipse Bug: Unhandled event loop exception No more handles

I had DisplayFusion running, which is a special Windows program used to manage multiple monitors. Turning it off seemed to fix this issue for me.

What is the best way to create a string array in python?

The simple answer is, "You don't." At the point where you need something to be of fixed length, you're either stuck on old habits or writing for a very specific problem with its own unique set of constraints.

How do I increase the RAM and set up host-only networking in Vagrant?

You can modify various VM properties by adding the following configuration (see the Vagrant docs for a bit more info):

  # Configure VM Ram usage
  config.vm.customize [
                        "modifyvm", :id,
                        "--name", "Test_Environment",
                        "--memory", "1024"
                      ]

You can obtain the properties that you want to change from the documents for VirtualBox command-line options:

The vagrant documentation has the section on how to change IP address:

Vagrant::Config.run do |config|
  config.vm.network :hostonly, "192.168.50.4"
end

Also you can restructure the configuration like this, ending is do with end without nesting it. This is simpler.

config.vm.define :web do |web_config|
    web_config.vm.box = "lucid32"
    web_config.vm.forward_port 80, 8080
end
web_config.vm.provision :puppet do |puppet|
    puppet.manifests_path = "manifests"
    puppet.manifest_file = "lucid32.pp"
end

plot.new has not been called yet

plot.new() error occurs when only part of the function is ran.

Please find the attachment for an example to correct error With error....When abline is ran without plot() above enter image description here Error-free ...When both plot and abline ran together enter image description here

Write single CSV file using spark-csv

I'm using this in Python to get a single file:

df.toPandas().to_csv("/tmp/my.csv", sep=',', header=True, index=False)

Using a PagedList with a ViewModel ASP.Net MVC

I modified the code as follow:

ViewModel

using System.Collections.Generic;
using ContosoUniversity.Models;

namespace ContosoUniversity.ViewModels
{
    public class InstructorIndexData
    {
     public PagedList.IPagedList<Instructor> Instructors { get; set; }
     public PagedList.IPagedList<Course> Courses { get; set; }
     public PagedList.IPagedList<Enrollment> Enrollments { get; set; }
    }
}

Controller

public ActionResult Index(int? id, int? courseID,int? InstructorPage,int? CoursePage,int? EnrollmentPage)
{
 int instructPageNumber = (InstructorPage?? 1);
 int CoursePageNumber = (CoursePage?? 1);
 int EnrollmentPageNumber = (EnrollmentPage?? 1);
 var viewModel = new InstructorIndexData();
 viewModel.Instructors = db.Instructors
    .Include(i => i.OfficeAssignment)
    .Include(i => i.Courses.Select(c => c.Department))
    .OrderBy(i => i.LastName).ToPagedList(instructPageNumber,5);

 if (id != null)
 {
    ViewBag.InstructorID = id.Value;
    viewModel.Courses = viewModel.Instructors.Where(
        i => i.ID == id.Value).Single().Courses.ToPagedList(CoursePageNumber,5);
 }

 if (courseID != null)
 {
    ViewBag.CourseID = courseID.Value;
    viewModel.Enrollments = viewModel.Courses.Where(
        x => x.CourseID == courseID).Single().Enrollments.ToPagedList(EnrollmentPageNumber,5);
 }

 return View(viewModel);
}

View

<div>
   Page @(Model.Instructors.PageCount < Model.Instructors.PageNumber ? 0 : Model.Instructors.PageNumber) of @Model.Instructors.PageCount

   @Html.PagedListPager(Model.Instructors, page => Url.Action("Index", new {InstructorPage=page}))

</div>

I hope this would help you!!

Is there a way to add/remove several classes in one single instruction with classList?

Here is a work around for IE 10 and 11 users that seemed pretty straight forward.

_x000D_
_x000D_
var elem = document.getElementById('elem');

['first','second','third'].forEach(item => elem.classList.add(item));
_x000D_
<div id="elem">Hello World!</div>
_x000D_
_x000D_
_x000D_

Or

_x000D_
_x000D_
var elem = document.getElementById('elem'),
    classes = ['first','second','third'];

classes.forEach(function(item) {
    return elem.classList.add(item);
});
_x000D_
<div id="elem">Hello World!</div>
_x000D_
_x000D_
_x000D_

How do you get the current text contents of a QComboBox?

Getting the Text of ComboBox when the item is changed

     self.ui.comboBox.activated.connect(self.pass_Net_Adap)

  def pass_Net_Adap(self):
      print str(self.ui.comboBox.currentText())