Programs & Examples On #Stdcall

Anything related to the `stdcall` calling convention, i.e. one of the common subroutine calling conventions used on systems with x86 architecture.

stdcall and cdecl

Those things are Compiler- and Platform-specific. Neither the C nor the C++ standard say anything about calling conventions except for extern "C" in C++.

how does a caller know if it should free up the stack ?

The caller knows the calling convention of the function and handles the call accordingly.

At the call site, does the caller know if the function being called is a cdecl or a stdcall function ?

Yes.

How does it work ?

It is part of the function declaration.

How does the caller know if it should free up the stack or not ?

The caller knows the calling conventions and can act accordingly.

Or is it the linkers responsibility ?

No, the calling convention is part of a function's declaration so the compiler knows everything it needs to know.

If a function which is declared as stdcall calls a function(which has a calling convention as cdecl), or the other way round, would this be inappropriate ?

No. Why should it?

In general, can we say that which call will be faster - cdecl or stdcall ?

I don't know. Test it.

What is __stdcall?

I agree that all the answers so far are correct, but here is the reason. Microsoft's C and C++ compilers provide various calling conventions for (intended) speed of function calls within an application's C and C++ functions. In each case, the caller and callee must agree on which calling convention to use. Now, Windows itself provides functions (APIs), and those have already been compiled, so when you call them you must conform to them. Any calls to Windows APIs, and callbacks from Windows APIs, must use the __stdcall convention.

How to set value in @Html.TextBoxFor in Razor syntax?

This works for me, in MVC5:

@Html.TextBoxFor(m => m.Name, new { @class = "form-control", id = "theID" , @Value="test" })

Gridview row editing - dynamic binding to a DropDownList

You can use SelectedValue:

<EditItemTemplate>
    <asp:DropDownList ID="ddlPBXTypeNS"
                      runat="server"
                      Width="200px"
                      DataSourceID="YDS"
                      DataTextField="CaptionValue"
                      DataValueField="OID"
                      SelectedValue='<%# Bind("YourForeignKey") %>' />
    <asp:YourDataSource ID="YDS" ...../>
</EditItemTemplate>

Show a popup/message box from a Windows batch file

A better option

set my_message=Hello world&& start cmd /c "@echo off & mode con cols=15 lines=2 & echo %my_message% & pause>nul"


Description:
lines= amount of lines,plus 1
cols= amount of characters in the message, plus 3 (However, minimum must be 15)

Auto-calculated cols version:

set my_message=Hello world&& (echo %my_message%>EMPTY_FILE123 && FOR %? IN (EMPTY_FILE123 ) DO SET strlength=%~z? && del EMPTY_FILE123 ) && start cmd /c "@echo off && mode con lines=2 cols=%strlength% && echo %my_message% && pause>nul"

Rotating a two-dimensional array in Python

I've had this problem myself and I've found the great wikipedia page on the subject (in "Common rotations" paragraph:
https://en.wikipedia.org/wiki/Rotation_matrix#Ambiguities

Then I wrote the following code, super verbose in order to have a clear understanding of what is going on.

I hope that you'll find it useful to dig more in the very beautiful and clever one-liner you've posted.

To quickly test it you can copy / paste it here:
http://www.codeskulptor.org/

triangle = [[0,0],[5,0],[5,2]]
coordinates_a = triangle[0]
coordinates_b = triangle[1]
coordinates_c = triangle[2]

def rotate90ccw(coordinates):
    print "Start coordinates:"
    print coordinates
    old_x = coordinates[0]
    old_y = coordinates[1]
# Here we apply the matrix coming from Wikipedia
# for 90 ccw it looks like:
# 0,-1
# 1,0
# What does this mean?
#
# Basically this is how the calculation of the new_x and new_y is happening:
# new_x = (0)(old_x)+(-1)(old_y)
# new_y = (1)(old_x)+(0)(old_y)
#
# If you check the lonely numbers between parenthesis the Wikipedia matrix's numbers
# finally start making sense.
# All the rest is standard formula, the same behaviour will apply to other rotations, just
# remember to use the other rotation matrix values available on Wiki for 180ccw and 170ccw
    new_x = -old_y
    new_y = old_x
    print "End coordinates:"
    print [new_x, new_y]

def rotate180ccw(coordinates):
    print "Start coordinates:"
    print coordinates
    old_x = coordinates[0]
    old_y = coordinates[1] 
    new_x = -old_x
    new_y = -old_y
    print "End coordinates:"
    print [new_x, new_y]

def rotate270ccw(coordinates):
    print "Start coordinates:"
    print coordinates
    old_x = coordinates[0]
    old_y = coordinates[1]  
    new_x = -old_x
    new_y = -old_y
    print "End coordinates:"
    print [new_x, new_y]

print "Let's rotate point A 90 degrees ccw:"
rotate90ccw(coordinates_a)
print "Let's rotate point B 90 degrees ccw:"
rotate90ccw(coordinates_b)
print "Let's rotate point C 90 degrees ccw:"
rotate90ccw(coordinates_c)
print "=== === === === === === === === === "
print "Let's rotate point A 180 degrees ccw:"
rotate180ccw(coordinates_a)
print "Let's rotate point B 180 degrees ccw:"
rotate180ccw(coordinates_b)
print "Let's rotate point C 180 degrees ccw:"
rotate180ccw(coordinates_c)
print "=== === === === === === === === === "
print "Let's rotate point A 270 degrees ccw:"
rotate270ccw(coordinates_a)
print "Let's rotate point B 270 degrees ccw:"
rotate270ccw(coordinates_b)
print "Let's rotate point C 270 degrees ccw:"
rotate270ccw(coordinates_c)
print "=== === === === === === === === === "

How to prevent 'query timeout expired'? (SQLNCLI11 error '80040e31')

Turns out that the post (or rather the whole table) was locked by the very same connection that I tried to update the post with.

I had a opened record set of the post that was created by:

Set RecSet = Conn.Execute()

This type of recordset is supposed to be read-only and when I was using MS Access as database it did not lock anything. But apparently this type of record set did lock something on MS SQL Server 2012 because when I added these lines of code before executing the UPDATE SQL statement...

RecSet.Close
Set RecSet = Nothing

...everything worked just fine.

So bottom line is to be careful with opened record sets - even if they are read-only they could lock your table from updates.

CSS text-overflow: ellipsis; not working?

You just add one line css:

.app a {
   display: inline-block;
}

Colspan all columns

As a partial answer, here's a few points about colspan="0", which was mentioned in the question.

tl;dr version:

colspan="0" doesn't work in any browser whatsoever. W3Schools is wrong (as usual). HTML 4 said that colspan="0" should cause a column to span the whole table, but nobody implemented this and it was removed from the spec after HTML 4.

Some more detail and evidence:

  • All major browsers treat it as equivalent to colspan="1".

    Here's a demo showing this; try it on any browser you like.

    _x000D_
    _x000D_
    td {_x000D_
      border: 1px solid black;_x000D_
    }
    _x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>ay</td>_x000D_
        <td>bee</td>_x000D_
        <td>see</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td colspan="0">colspan="0"</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td colspan="1">colspan="1"</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td colspan="3">colspan="3"</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td colspan="1000">colspan="1000"</td>_x000D_
      </tr>_x000D_
    </table>
    _x000D_
    _x000D_
    _x000D_

  • The HTML 4 spec (now old and outdated, but current back when this question was asked) did indeed say that colspan="0" should be treated as spanning all columns:

    The value zero ("0") means that the cell spans all columns from the current column to the last column of the column group (COLGROUP) in which the cell is defined.

    However, most browsers never implemented this.

  • HTML 5.0 (made a candidate recommendation back in 2012), the WhatWG HTML living standard (the dominant standard today), and the latest W3 HTML 5 spec all do not contain the wording quoted from HTML 4 above, and unanimously agree that a colspan of 0 is not allowed, with this wording which appears in all three specs:

    The td and th elements may have a colspan content attribute specified, whose value must be a valid non-negative integer greater than zero ...

    Sources:

  • The following claims from the W3Schools page linked to in the question are - at least nowadays - completely false:

    Only Firefox supports colspan="0", which has a special meaning ... [It] tells the browser to span the cell to the last column of the column group (colgroup)

    and

    Differences Between HTML 4.01 and HTML5

    NONE.

    If you're not already aware that W3Schools is generally held in contempt by web developers for its frequent inaccuracies, consider this a lesson in why.

Android new Bottom Navigation bar or BottomNavigationView

You can create the layouts according to the above-mentioned answers If anyone wants to use this in kotlin:-

 private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
    when (item.itemId) {
        R.id.images -> {
          // do your work....
            return@OnNavigationItemSelectedListener true
        }
       R.id.videos ->
         {
          // do your work....
            return@OnNavigationItemSelectedListener true
        }
    }
    false
}

then in oncreate you can set the above listener to your view

   mDataBinding?.navigation?.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)

Check if table exists

If using jruby, here is a code snippet to return an array of all tables in a db.

require "rubygems"
require "jdbc/mysql"
Jdbc::MySQL.load_driver
require "java"

def get_database_tables(connection, db_name)
  md = connection.get_meta_data
  rs = md.get_tables(db_name, nil, '%',["TABLE"])

  tables = []
  count = 0
  while rs.next
    tables << rs.get_string(3)
  end #while
  return tables
end

Incompatible implicit declaration of built-in function ‘malloc’

The stdlib.h file contains the header information or prototype of the malloc, calloc, realloc and free functions.

So to avoid this warning in ANSI C, you should include the stdlib header file.

Examples for string find in Python

I'm not sure what you're looking for, do you mean find()?

>>> x = "Hello World"
>>> x.find('World')
6
>>> x.find('Aloha');
-1

Target WSGI script cannot be loaded as Python module

I had the same problem and at first I didn't realise I could scroll further down and see the actual error message. In my case, it was an import error:

ImportError: No module named bootstrap3

After installing it via pip (pip install django-bootstrap3), I restarted Apache and it worked.

How to make an Asynchronous Method return a value?

Use a BackgroundWorker. It will allow you to get callbacks on completion and allow you to track progress. You can set the Result value on the event arguments to the resulting value.

    public void UseBackgroundWorker()
    {
        var worker = new BackgroundWorker();
        worker.DoWork += DoWork;
        worker.RunWorkerCompleted += WorkDone;
        worker.RunWorkerAsync("input");
    }

    public void DoWork(object sender, DoWorkEventArgs e)
    {
        e.Result = e.Argument.Equals("input");
        Thread.Sleep(1000);
    }

    public void WorkDone(object sender, RunWorkerCompletedEventArgs e)
    {
        var result = (bool) e.Result;
    }

C# SQL Server - Passing a list to a stored procedure

No, arrays/lists can't be passed to SQL Server directly.

The following options are available:

  1. Passing a comma-delimited list and then having a function in SQL split the list. The comma delimited list will most likely be passed as an Nvarchar()
  2. Pass xml and have a function in SQL Server parse the XML for each value in the list
  3. Use the new defined User Defined table type (SQL 2008)
  4. Dynamically build the SQL and pass in the raw list as "1,2,3,4" and build the SQL statement. This is prone to SQL injection attacks, but it will work.

SQL Developer is returning only the date, not the time. How do I fix this?

To expand on some of the previous answers, I found that Oracle DATE objects behave different from Oracle TIMESTAMP objects. In particular, if you set your NLS_DATE_FORMAT to include fractional seconds, the entire time portion is omitted.

  • Format "YYYY-MM-DD HH24:MI:SS" works as expected, for DATE and TIMESTAMP
  • Format "YYYY-MM-DD HH24:MI:SSXFF" displays just the date portion for DATE, works as expected for TIMESTAMP

My personal preference is to set DATE to "YYYY-MM-DD HH24:MI:SS", and to set TIMESTAMP to "YYYY-MM-DD HH24:MI:SSXFF".

Java socket API: How to tell if a connection has been closed?

There is no TCP API that will tell you the current state of the connection. isConnected() and isClosed() tell you the current state of your socket. Not the same thing.

  1. isConnected() tells you whether you have connected this socket. You have, so it returns true.

  2. isClosed() tells you whether you have closed this socket. Until you have, it returns false.

  3. If the peer has closed the connection in an orderly way

    • read() returns -1
    • readLine() returns null
    • readXXX() throws EOFException for any other XXX.

    • A write will throw an IOException: 'connection reset by peer', eventually, subject to buffering delays.

  4. If the connection has dropped for any other reason, a write will throw an IOException, eventually, as above, and a read may do the same thing.

  5. If the peer is still connected but not using the connection, a read timeout can be used.

  6. Contrary to what you may read elsewhere, ClosedChannelException doesn't tell you this. [Neither does SocketException: socket closed.] It only tells you that you closed the channel, and then continued to use it. In other words, a programming error on your part. It does not indicate a closed connection.

  7. As a result of some experiments with Java 7 on Windows XP it also appears that if:

    • you're selecting on OP_READ
    • select() returns a value of greater than zero
    • the associated SelectionKey is already invalid (key.isValid() == false)

    it means the peer has reset the connection. However this may be peculiar to either the JRE version or platform.

Error in MySQL when setting default value for DATE or DATETIME

I've tested a fix as follow:

1). On the file "system/library/db/mysqli.php" search and comment the line: 
"$this->connection->query("SET SESSION sql_mode = 'NO_ZERO_IN_DATE,NO_ZERO_DATE,NO_ENGINE_SUBSTITUTION'");"

2) Add the following line above the one you just commented:
// Correction by Added by A.benkorich
$this->connection->query("SET SESSION sql_mode = 'ONLY_FULL_GROUP_BY'");

How do I count unique items in field in Access query?

Access-Engine does not support

SELECT count(DISTINCT....) FROM ...

You have to do it like this:

SELECT count(*) 
FROM
(SELECT DISTINCT Name FROM table1)

Its a little workaround... you're counting a DISTINCT selection.

What's the maximum value for an int in PHP?

(a little bit late, but could be useful)

Only trust PHP_INT_MAX and PHP_INT_SIZE, this value vary on your arch (32/64 bits) and your OS...

Any other "guess" or "hint" can be false.

How to change the background color of a UIButton while it's highlighted?

Here's an approach in Swift, using a UIButton extension to add an IBInspectable, called highlightedBackgroundColor. Similar to subclassing, without requiring a subclass.

private var HighlightedBackgroundColorKey = 0
private var NormalBackgroundColorKey = 0

extension UIButton {

    @IBInspectable var highlightedBackgroundColor: UIColor? {
        get {
            return objc_getAssociatedObject(self, &HighlightedBackgroundColorKey) as? UIColor
        }

        set(newValue) {
            objc_setAssociatedObject(self,
                &HighlightedBackgroundColorKey, newValue, UInt(OBJC_ASSOCIATION_RETAIN))
        }
    }

    private var normalBackgroundColor: UIColor? {
        get {
            return objc_getAssociatedObject(self, &NormalBackgroundColorKey) as? UIColor
        }

        set(newValue) {
            objc_setAssociatedObject(self,
                &NormalBackgroundColorKey, newValue, UInt(OBJC_ASSOCIATION_RETAIN))
        }
    }

    override public var backgroundColor: UIColor? {
        didSet {
            if !highlighted {
                normalBackgroundColor = backgroundColor
            }
        }
    }

    override public var highlighted: Bool {
        didSet {
            if let highlightedBackgroundColor = self.highlightedBackgroundColor {
                if highlighted {
                    backgroundColor = highlightedBackgroundColor
                } else {
                    backgroundColor = normalBackgroundColor
                }
            }
        }
    }
}

I hope this helps.

Reporting Services export to Excel with Multiple Worksheets

I found a simple way around this in 2005. Here are my steps:

  1. Create a string parameter with values ‘Y’ and ‘N’ called ‘PageBreaks’.
  2. Add a group level above the group (value) which was used to split the data to the multiple sheets in Excel.
  3. Inserted into the first textbox field for this group, the expression for the ‘PageBreaks’ as such… =IIF(Parameters!PageBreaks.Value="Y",Fields!DISP_PROJECT.Value,"") Note: If the parameter =’Y’ then you will get the multiple sheets for each different value. Otherwise the field is NULL for every group record (which causes only one page break at the end).
  4. Change the visibility hidden value of the new grouping row to ‘True’.
  5. NOTE: When you do this it will also determine whether or not you have a page break in the view, but my users love it since they have the control.

How to convert a normal Git repository to a bare one?

Wow, it's simply amazing how many people chimed in on this, especially considering it doesn't seem that not a single on stopped to ask why this person is doing what he's doing.

The ONLY difference between a bare and non-bare git repository is that the non-bare version has a working copy. The main reason you would need a bare repo is if you wanted to make it available to a third party, you can't actually work on it directly so at some point you're going to have to clone it at which point you're right back to a regular working copy version.

That being said, to convert to a bare repo all you have to do is make sure you have no commits pending and then just :

rm -R * && mv .git/* . && rm -R .git

There ya go, bare repo.

CSS Box Shadow Bottom Only

Try this

-moz-box-shadow:0 5px 5px rgba(182, 182, 182, 0.75);
-webkit-box-shadow: 0 5px 5px rgba(182, 182, 182, 0.75);
box-shadow: 0 5px 5px rgba(182, 182, 182, 0.75);

You can see it in http://jsfiddle.net/wJ7qp/

Intellij idea cannot resolve anything in maven

If you have any dependencies in pom.xml specific to your organisation than you need to update path of setting.xml for your project which is by default set to your user directory in Ubuntu : /home/user/.m2/settings.xml -> (change it to your apache-maven conf path)

Update Setting.xml file Intellij

Sending multipart/formdata with jQuery.ajax

Look at my code, it does the job for me

$( '#formId' )
  .submit( function( e ) {
    $.ajax( {
      url: 'FormSubmitUrl',
      type: 'POST',
      data: new FormData( this ),
      processData: false,
      contentType: false
    } );
    e.preventDefault();
  } );

Convert string to boolean in C#

You must use some of the C # conversion systems:

string to boolean: True to true

string str = "True";
bool mybool = System.Convert.ToBoolean(str);

boolean to string: true to True

bool mybool = true;
string str = System.Convert.ToString(mybool);

//or

string str = mybool.ToString();

bool.Parse expects one parameter which in this case is str, even .

Convert.ToBoolean expects one parameter.

bool.TryParse expects two parameters, one entry (str) and one out (result).

If TryParse is true, then the conversion was correct, otherwise an error occurred

string str = "True";
bool MyBool = bool.Parse(str);

//Or

string str = "True";
if(bool.TryParse(str, out bool result))
{
   //Correct conversion
}
else
{
     //Incorrect, an error has occurred
}

Using GZIP compression with Spring Boot/MVC/JavaConfig with RESTful

Spring Boot 1.4 Use this for Javascript HTML Json all compressions.

server.compression.enabled: true
server.compression.mime-types: application/json,application/xml,text/html,text/xml,text/plain,text/css,application/javascript

Default value of function parameter

The first way would be preferred to the second.

This is because the header file will show that the parameter is optional and what its default value will be. Additionally, this will ensure that the default value will be the same, no matter the implementation of the corresponding .cpp file.

In the second way, there is no guarantee of a default value for the second parameter. The default value could change, depending on how the corresponding .cpp file is implemented.

What are the differences between C, C# and C++ in terms of real-world applications?

C is the bare-bones, simple, clean language that makes you do everything yourself. It doesn't hold your hand, it doesn't stop you from shooting yourself in the foot. But it has everything you need to do what you want.

C++ is C with classes added, and then a whole bunch of other things, and then some more stuff. It doesn't hold your hand, but it'll let you hold your own hand, with add-on GC, or RAII and smart-pointers. If there's something you want to accomplish, chances are there's a way to abuse the template system to give you a relatively easy syntax for it. (moreso with C++0x). This complexity also gives you the power to accidentally create a dozen instances of yourself and shoot them all in the foot.

C# is Microsoft's stab at improving on C++ and Java. Tons of syntactical features, but no where near the complexity of C++. It runs in a full managed environment, so memory management is done for you. It does let you "get dirty" and use unsafe code if you need to, but it's not the default, and you have to do some work to shoot yourself.

Should I test private methods or only public ones?

It's obviously language dependent. In the past with c++, I've declared the testing class to be a friend class. Unfortunately, this does require your production code to know about the testing class.

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

Try this

Option Explicit

Sub UniqueValues()
Dim ws As Worksheet
Dim uniqueRng As Range
Dim myCol As Long

myCol = 5 '<== set it as per your needs
Set ws = ThisWorkbook.Worksheets("unique") '<== set it as per your needs

Set uniqueRng = GetUniqueValues(ws, myCol)

End Sub


Function GetUniqueValues(ws As Worksheet, col As Long) As Range
Dim firstRow As Long

With ws
    .Columns(col).RemoveDuplicates Columns:=Array(1), header:=xlNo

    firstRow = 1
    If IsEmpty(.Cells(1, col)) Then firstRow = .Cells(1, col).End(xlDown).row

    Set GetUniqueValues = Range(.Cells(firstRow, col), .Cells(.Rows.Count, col).End(xlUp))
End With

End Function

it should be quite fast and without the drawback NeepNeepNeep told about

OwinStartup not firing

After converting a class library to a Web Application Project, I ran into this and became stubborn. Turned out, in my .csProj file, I had this:

<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
  <DebugSymbols>true</DebugSymbols>
  <DebugType>full</DebugType>
  <Optimize>false</Optimize>
  <OutputPath>bin\Debug\</OutputPath>
  <DefineConstants>DEBUG;TRACE</DefineConstants>
  <ErrorReport>prompt</ErrorReport>
  <WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
  <DebugType>pdbonly</DebugType>
  <Optimize>true</Optimize>
  <OutputPath>bin\Release\</OutputPath>
  <DefineConstants>TRACE</DefineConstants>
  <ErrorReport>prompt</ErrorReport>
  <WarningLevel>4</WarningLevel>
</PropertyGroup>
  • thus building the various dll's into a subfolder of the bin-folder (which ifc. won't work). Solution was to change both text-contents for OutputPath to just bin\.

Javascript date regex DD/MM/YYYY

This validates date like dd-mm-yyyy

([0-2][0-9]|(3)[0-1])(\-)(((0)[0-9])|((1)[0-2]))(\-)([0-9][0-9][0-9][0-9])

This can use with javascript like angular reactive forms

Hiding the scroll bar on an HTML page

I just thought I'd point out to anyone else reading this question that setting overflow: hidden (or overflow-y) on the body element didn't hide the scrollbars for me.

I had to use the html element.

Converting a String to Object

String extends Object, which means an Object. Object o = a; If you really want to get as Object, you may do like below.

String s = "Hi";

Object a =s;

Error creating bean with name 'entityManagerFactory

Adding dependencies didn't fix the issue at my end.

The issue was happening at my end because of "additional" fields that are part of the "@Entity" class and don't exist in the database.

I removed the additional fields from the @Entity class and it worked.

Insert ellipsis (...) into HTML tag if content too wide

you can do this much easier with css only, for example : sass mode

.truncatedText {
   font-size: 0.875em;
   line-height: 1.2em;
   height: 2.4em; // 2 lines * line-height
   &:after {
      content: " ...";
   }
}

and you have ellipsis ;)

Get the value for a listbox item by index

Here I can't see even a single correct answer for this question (in WinForms tag) and it's strange for such frequent question.

Items of a ListBox control may be DataRowView, Complex Objects, Anonymous types, primary types and other types. Underlying value of an item should be calculated base on ValueMember.

ListBox control has a GetItemText which helps you to get the item text regardless of the type of object you added as item. It really needs such GetItemValue method.

GetItemValue Extension Method

We can create GetItemValue Extension Method to get item value which works like GetItemText:

using System;
using System.Windows.Forms;
using System.ComponentModel;
public static class ListControlExtensions
{
    public static object GetItemValue(this ListControl list, object item)
    {
        if (item == null)
            throw new ArgumentNullException("item");

        if (string.IsNullOrEmpty(list.ValueMember))
            return item;

        var property = TypeDescriptor.GetProperties(item)[list.ValueMember];
        if (property == null)
            throw new ArgumentException(
                string.Format("item doesn't contain '{0}' property or column.",
                list.ValueMember));
        return property.GetValue(item);
    }
}

Using above method you don't need to worry about settings of ListBox and it will return expected Value for an item. It works with List<T>, Array, ArrayList, DataTable, List of Anonymous Types, list of primary types and all other lists which you can use as data source. Here is an example of usage:

//Gets underlying value at index 2 based on settings
this.listBox1.GetItemValue(this.listBox1.Items[2]);

Since we created the GetItemValue method as an extension method, when you want to use the method, don't forget to include the namespace which you put the class in.

This method is applicable on ComboBox and CheckedListBox too.

Get name of object or class

Example:

_x000D_
_x000D_
function Foo () { console.log('Foo function'); }_x000D_
var Bar = function () { console.log('Bar function'); };_x000D_
var Abc = function Xyz() { console.log('Abc function'); };_x000D_
_x000D_
var f = new Foo();_x000D_
var b = new Bar();_x000D_
var a = new Abc();_x000D_
_x000D_
console.log('f', f.constructor.name); // -> "Foo"_x000D_
console.log('b', b.constructor.name); // -> "Function"_x000D_
console.log('a', a.constructor.name); // -> "Xyz"
_x000D_
_x000D_
_x000D_

PHP, MySQL error: Column count doesn't match value count at row 1

Your query has 8 or possibly even 9 variables, ie. Name, Description etc. But the values, these things ---> '', '%s', '%s', '%s', '%s', '%s', '%s', '%s')", only total 7, the number of variables have to be the same as the values.

I had the same problem but I figured it out. Hopefully it will also work for you.

sqlite copy data from one table to another

If you have data already present in both the tables and you want to update a table column values based on some condition then use this

UPDATE Table1 set Name=(select t2.Name from Table2 t2 where t2.id=Table1.id)

Which Android phones out there do have a gyroscope?

Since I have recently developed an Android application using gyroscope data (steady compass), I tried to collect a list with such devices. This is not an exhaustive list at all, but it is what I have so far:

*** Phones:

  • HTC Sensation
  • HTC Sensation XL
  • HTC Evo 3D
  • HTC One S
  • HTC One X
  • Huawei Ascend P1
  • Huawei Ascend X (U9000)
  • Huawei Honor (U8860)
  • LG Nitro HD (P930)
  • LG Optimus 2x (P990)
  • LG Optimus Black (P970)
  • LG Optimus 3D (P920)
  • Samsung Galaxy S II (i9100)
  • Samsung Galaxy S III (i9300)
  • Samsung Galaxy R (i9103)
  • Samsung Google Nexus S (i9020)
  • Samsung Galaxy Nexus (i9250)
  • Samsung Galaxy J3 (2017) model
  • Samsung Galaxy Note (n7000)
  • Sony Xperia P (LT22i)
  • Sony Xperia S (LT26i)

*** Tablets:

  • Acer Iconia Tab A100 (7")
  • Acer Iconia Tab A500 (10.1")
  • Asus Eee Pad Transformer (TF101)
  • Asus Eee Pad Transformer Prime (TF201)
  • Motorola Xoom (mz604)
  • Samsung Galaxy Tab (p1000)
  • Samsung Galaxy Tab 7 plus (p6200)
  • Samsung Galaxy Tab 10.1 (p7100)
  • Sony Tablet P
  • Sony Tablet S
  • Toshiba Thrive 7"
  • Toshiba Trhive 10"

Hope the list keeps growing and hope that gyros will be soon available on mid and low price smartphones.

Specify the date format in XMLGregorianCalendar

There isn’t really an ideal conversion, but I would like to supply a couple of options.

java.time

First, you should use LocalDate from java.time, the modern Java date and time API, for parsing and holding your date. Avoid Date and SimpleDateFormat since they have design problems and also are long outdated. The latter in particular is notoriously troublesome.

    DateTimeFormatter originalDateFormatter = DateTimeFormatter.ofPattern("dd/MM/uuuu");

    String dateString = "13/06/1983";
    LocalDate date = LocalDate.parse(dateString, originalDateFormatter);
    System.out.println(date);

The output is:

1983-06-13

Do you need to go any further? LocalDate.toString() produces the format you asked about.

Format and parse

Assuming that you do require an XMLGregorianCalendar the first and easy option for converting is:

    XMLGregorianCalendar xmlDate = DatatypeFactory.newInstance()
            .newXMLGregorianCalendar(date.toString());
    System.out.println(xmlDate);

1983-06-13

Formatting to a string and parsing it back feels like a waste to me, but as I said, it’s easy and I don’t think that there are any surprises about the result being as expected.

Pass year, month and day of month individually

    XMLGregorianCalendar xmlDate = DatatypeFactory.newInstance()
            .newXMLGregorianCalendarDate(date.getYear(), date.getMonthValue(),
                    date.getDayOfMonth(), DatatypeConstants.FIELD_UNDEFINED);

The result is the same as before. We need to make explicit that we don’t want a time zone offset (this is what DatatypeConstants.FIELD_UNDEFINED specifies). In case someone is wondering, both LocalDate and XMLGregorianCalendar number months the way humans do, so there is no adding or subtracting 1.

Convert through GregorianCalendar

I only show you this option because I somehow consider it the official way: convert LocalDate to ZonedDateTime, then to GregorianCalendar and finally to XMLGregorianCalendar.

    ZonedDateTime dateTime = date.atStartOfDay(ZoneOffset.UTC);
    GregorianCalendar gregCal = GregorianCalendar.from(dateTime);
    XMLGregorianCalendar xmlDate = DatatypeFactory.newInstance()
            .newXMLGregorianCalendar(gregCal);
    xmlDate.setTime(DatatypeConstants.FIELD_UNDEFINED, DatatypeConstants.FIELD_UNDEFINED,
            DatatypeConstants.FIELD_UNDEFINED, DatatypeConstants.FIELD_UNDEFINED);
    xmlDate.setTimezone(DatatypeConstants.FIELD_UNDEFINED);

I like the conversion itself since we neither need to use strings nor need to pass individual fields (with care to do it in the right order). What I don’t like is that we have to pass a time of day and a time zone offset and then wipe out those fields manually afterwards.

while-else-loop

Wrap the "set" statement to mean "set if not set" and put it naked above the while loop.

You are correct, the language does not provide what you're looking for in exactly that syntax, but that's because there are programming paradigms like the one I just suggested so you don't need the syntax you are proposing.

ElasticSearch - Return Unique Values

I am looking for this kind of solution for my self as well. I found reference in terms aggregation.

So, according to that following is the proper solution.

{
"aggs" : {
    "langs" : {
        "terms" : { "field" : "language",  
                    "size" : 500 }
    }
}}

But if you ran into following error:

"error": {
        "root_cause": [
            {
                "type": "illegal_argument_exception",
                "reason": "Fielddata is disabled on text fields by default. Set fielddata=true on [fastest_method] in order to load fielddata in memory by uninverting the inverted index. Note that this can however use significant memory. Alternatively use a keyword field instead."
            }
        ]}

In that case, you have to add "KEYWORD" in the request, like following:

   {
    "aggs" : {
        "langs" : {
            "terms" : { "field" : "language.keyword",  
                        "size" : 500 }
        }
    }}

java.net.URLEncoder.encode(String) is deprecated, what should I use instead?

You should use:

URLEncoder.encode("NAME", "UTF-8");

Comparing boxed Long values 127 and 128

Java caches the primitive values from -128 to 127. When we compare two Long objects java internally type cast it to primitive value and compare it. But above 127 the Long object will not get type caste. Java caches the output by .valueOf() method.

This caching works for Byte, Short, Long from -128 to 127. For Integer caching works From -128 to java.lang.Integer.IntegerCache.high or 127, whichever is bigger.(We can set top level value upto which Integer values should get cached by using java.lang.Integer.IntegerCache.high).

 For example:
    If we set java.lang.Integer.IntegerCache.high=500;
    then values from -128 to 500 will get cached and 

    Integer a=498;
    Integer b=499;
    System.out.println(a==b)

    Output will be "true".

Float and Double objects never gets cached.

Character will get cache from 0 to 127

You are comparing two objects. so == operator will check equality of object references. There are following ways to do it.

1) type cast both objects into primitive values and compare

    (long)val3 == (long)val4

2) read value of object and compare

    val3.longValue() == val4.longValue()

3) Use equals() method on object comparison.

    val3.equals(val4);  

Disable back button in android

Disable back buttton in android

@Override
public void onBackPressed() {
    return;
}

What is SOA "in plain english"?

Well You see.. SOA stands for Service Oriented Architecture.... In simplest words, you write a piece of code that is very generic i.e. it does some thing that can be used in a lot of applications ... may be something like a address book or may be a calculator. and you launch this code on the IIS. So you provide a service through your code. So you are a service provider. Now someone wants to use a similar code then he does not have to write the code again. He simply uses your code maybe through a web service. Hence he becomes a service consumer. Hence making a program using such services is called SOA. And the loose coupling is there as the service provider and consumer may be interacting even if they are using diff programming languages. Hope you understand.

Tests not running in Test Explorer

I had a different solution to get my tests to run. My global packages folder didn't match what was in my .csproj This is what my .csproj looked like: UnitTest .csproj

I had to change my Version to 16.5.0 which i found was installed in my global packages folder. Now my tests are able to run: .nuget folder explorer

Using gradle to find dependency tree

In Android Studio (at least since v2.3.3) you can run the command directly from the UI:

Click on the Gradle tab and then double click on :yourmodule -> Tasks -> android -> androidDependencies

The tree will be displayed in the Gradle Console tab

An image is worth a thousand words

Adding rows to dataset

 DataSet ds = new DataSet();

 DataTable dt = new DataTable("MyTable");
 dt.Columns.Add(new DataColumn("id",typeof(int)));
 dt.Columns.Add(new DataColumn("name", typeof(string)));

 DataRow dr = dt.NewRow();
 dr["id"] = 123;
 dr["name"] = "John";
 dt.Rows.Add(dr);
 ds.Tables.Add(dt);

Spring CrudRepository findByInventoryIds(List<Long> inventoryIdList) - equivalent to IN clause

For any method in a Spring CrudRepository you should be able to specify the @Query yourself. Something like this should work:

@Query( "select o from MyObject o where inventoryId in :ids" )
List<MyObject> findByInventoryIds(@Param("ids") List<Long> inventoryIdList);

PHP - Merging two arrays into one array (also Remove Duplicates)

It will merger two array and remove duplicate

<?php
 $first = 'your first array';
 $second = 'your second array';
 $result = array_merge($first,$second);
 print_r($result);
 $result1= array_unique($result);
 print_r($result1);
 ?>

Try this link link1

Converting a Uniform Distribution to a Normal Distribution

The standard Python library module random has what you want:

normalvariate(mu, sigma)
Normal distribution. mu is the mean, and sigma is the standard deviation.

For the algorithm itself, take a look at the function in random.py in the Python library.

The manual entry is here

Counting duplicates in Excel

If you are not looking for Excel formula, Its easy from the Menu

Data Menu --> Remove Duplicates would alert, if there are no duplicates

Also, if you see the count and reduced after removing duplicates...

Convert ASCII TO UTF-8 Encoding

If you know for sure that your current encoding is pure ASCII, then you don't have to do anything because ASCII is already a valid UTF-8.

But if you still want to convert, just to be sure that its UTF-8, then you can use iconv

$string = iconv('ASCII', 'UTF-8//IGNORE', $string);

The IGNORE will discard any invalid characters just in case some were not valid ASCII.

Comparing two java.util.Dates to see if they are in the same day

Convert dates to Java 8 java.time.LocalDate as seen here.

LocalDate localDate1 = date1.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate localDate2 = date2.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

// compare dates
assertTrue("Not on the same day", localDate1.equals(localDate2));

Nginx location priority

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

What does "fatal: bad revision" mean?

I was getting this error in IntelliJ, and none of these answers helped me. So here's how I solved it.

Somehow one of my sub-modules added a .git directory. All git functionality returned after I deleted it.

How can I send JSON response in symfony2 controller

To complete @thecatontheflat answer I would recommend to also wrap your action inside of a try … catch block. This will prevent your JSON endpoint from breaking on exceptions. Here's the skeleton I use:

public function someAction()
{
    try {

        // Your logic here...

        return new JsonResponse([
            'success' => true,
            'data'    => [] // Your data here
        ]);

    } catch (\Exception $exception) {

        return new JsonResponse([
            'success' => false,
            'code'    => $exception->getCode(),
            'message' => $exception->getMessage(),
        ]);

    }
}

This way your endpoint will behave consistently even in case of errors and you will be able to treat them right on a client side.

One DbContext per web request... why?

NOTE: This answer talks about the Entity Framework's DbContext, but it is applicable to any sort of Unit of Work implementation, such as LINQ to SQL's DataContext, and NHibernate's ISession.

Let start by echoing Ian: Having a single DbContext for the whole application is a Bad Idea. The only situation where this makes sense is when you have a single-threaded application and a database that is solely used by that single application instance. The DbContext is not thread-safe and and since the DbContext caches data, it gets stale pretty soon. This will get you in all sorts of trouble when multiple users/applications work on that database simultaneously (which is very common of course). But I expect you already know that and just want to know why not to just inject a new instance (i.e. with a transient lifestyle) of the DbContext into anyone who needs it. (for more information about why a single DbContext -or even on context per thread- is bad, read this answer).

Let me start by saying that registering a DbContext as transient could work, but typically you want to have a single instance of such a unit of work within a certain scope. In a web application, it can be practical to define such a scope on the boundaries of a web request; thus a Per Web Request lifestyle. This allows you to let a whole set of objects operate within the same context. In other words, they operate within the same business transaction.

If you have no goal of having a set of operations operate inside the same context, in that case the transient lifestyle is fine, but there are a few things to watch:

  • Since every object gets its own instance, every class that changes the state of the system, needs to call _context.SaveChanges() (otherwise changes would get lost). This can complicate your code, and adds a second responsibility to the code (the responsibility of controlling the context), and is a violation of the Single Responsibility Principle.
  • You need to make sure that entities [loaded and saved by a DbContext] never leave the scope of such a class, because they can't be used in the context instance of another class. This can complicate your code enormously, because when you need those entities, you need to load them again by id, which could also cause performance problems.
  • Since DbContext implements IDisposable, you probably still want to Dispose all created instances. If you want to do this, you basically have two options. You need to dispose them in the same method right after calling context.SaveChanges(), but in that case the business logic takes ownership of an object it gets passed on from the outside. The second option is to Dispose all created instances on the boundary of the Http Request, but in that case you still need some sort of scoping to let the container know when those instances need to be Disposed.

Another option is to not inject a DbContext at all. Instead, you inject a DbContextFactory that is able to create a new instance (I used to use this approach in the past). This way the business logic controls the context explicitly. If might look like this:

public void SomeOperation()
{
    using (var context = this.contextFactory.CreateNew())
    {
        var entities = this.otherDependency.Operate(
            context, "some value");

        context.Entities.InsertOnSubmit(entities);

        context.SaveChanges();
    }
}

The plus side of this is that you manage the life of the DbContext explicitly and it is easy to set this up. It also allows you to use a single context in a certain scope, which has clear advantages, such as running code in a single business transaction, and being able to pass around entities, since they originate from the same DbContext.

The downside is that you will have to pass around the DbContext from method to method (which is termed Method Injection). Note that in a sense this solution is the same as the 'scoped' approach, but now the scope is controlled in the application code itself (and is possibly repeated many times). It is the application that is responsible for creating and disposing the unit of work. Since the DbContext is created after the dependency graph is constructed, Constructor Injection is out of the picture and you need to defer to Method Injection when you need to pass on the context from one class to the other.

Method Injection isn't that bad, but when the business logic gets more complex, and more classes get involved, you will have to pass it from method to method and class to class, which can complicate the code a lot (I've seen this in the past). For a simple application, this approach will do just fine though.

Because of the downsides, this factory approach has for bigger systems, another approach can be useful and that is the one where you let the container or the infrastructure code / Composition Root manage the unit of work. This is the style that your question is about.

By letting the container and/or the infrastructure handle this, your application code is not polluted by having to create, (optionally) commit and Dispose a UoW instance, which keeps the business logic simple and clean (just a Single Responsibility). There are some difficulties with this approach. For instance, were do you Commit and Dispose the instance?

Disposing a unit of work can be done at the end of the web request. Many people however, incorrectly assume that this is also the place to Commit the unit of work. However, at that point in the application, you simply can't determine for sure that the unit of work should actually be committed. e.g. If the business layer code threw an exception that was caught higher up the callstack, you definitely don't want to Commit.

The real solution is again to explicitly manage some sort of scope, but this time do it inside the Composition Root. Abstracting all business logic behind the command / handler pattern, you will be able to write a decorator that can be wrapped around each command handler that allows to do this. Example:

class TransactionalCommandHandlerDecorator<TCommand>
    : ICommandHandler<TCommand>
{
    readonly DbContext context;
    readonly ICommandHandler<TCommand> decorated;

    public TransactionCommandHandlerDecorator(
        DbContext context,
        ICommandHandler<TCommand> decorated)
    {
        this.context = context;
        this.decorated = decorated;
    }

    public void Handle(TCommand command)
    {
        this.decorated.Handle(command);

        context.SaveChanges();
    } 
}

This ensures that you only need to write this infrastructure code once. Any solid DI container allows you to configure such a decorator to be wrapped around all ICommandHandler<T> implementations in a consistent manner.

Animate scroll to ID on page load

Pure javascript solution with scrollIntoView() function:

_x000D_
_x000D_
document.getElementById('title1').scrollIntoView({block: 'start', behavior: 'smooth'});
_x000D_
<h2 id="title1">Some title</h2>
_x000D_
_x000D_
_x000D_

P.S. 'smooth' parameter now works from Chrome 61 as julien_c mentioned in the comments.

Prevent Sequelize from outputting SQL to the console on execution of query?

When you create your Sequelize object, pass false to the logging parameter:

var sequelize = new Sequelize('database', 'username', 'password', {
  
  // disable logging; default: console.log
  logging: false

});

For more options, check the docs.

Insert into ... values ( SELECT ... FROM ... )

Here's how to insert from multiple tables. This particular example is where you have a mapping table in a many to many scenario:

insert into StudentCourseMap (StudentId, CourseId) 
SELECT  Student.Id, Course.Id FROM Student, Course 
WHERE Student.Name = 'Paddy Murphy' AND Course.Name = 'Basket weaving for beginners'

(I realise matching on the student name might return more than one value but you get the idea. Matching on something other than an Id is necessary when the Id is an Identity column and is unknown.)

How to use particular CSS styles based on screen size / device

Use @media queries. They serve this exact purpose. Here's an example how they work:

@media (max-width: 800px) {
  /* CSS that should be displayed if width is equal to or less than 800px goes here */
}

This would work only on devices whose width is equal to or less than 800px.

Read up more about media queries on the Mozilla Developer Network.

How to run Gradle from the command line on Mac bash

./gradlew

Your directory with gradlew is not included in the PATH, so you must specify path to the gradlew. . means "current directory".

Unable to find the requested .Net Framework Data Provider in Visual Studio 2010 Professional

I like the other suggestions but I would rather not update the machine.config for a single application. I suggest that you just add it to the web.config / app.config. Here is what I needed to use the MySql Connector/NET that I "bin" deployed.

<system.data>
    <DbProviderFactories >
        <add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.6.4.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
    </DbProviderFactories>
</system.data>

How to add custom html attributes in JSX

Depending on what version of React you are using, you may need to use something like this. I know Facebook is thinking about deprecating string refs in the somewhat near future.

var Hello = React.createClass({
    componentDidMount: function() {
        ReactDOM.findDOMNode(this.test).setAttribute('custom-attribute', 'some value');
    },
    render: function() {
        return <div>
            <span ref={(ref) => this.test = ref}>Element with a custom attribute</span>
        </div>;
    }
});

React.render(<Hello />, document.getElementById('container'));

Facebook's ref documentation

Date format in dd/MM/yyyy hh:mm:ss

This can be done as follows :

select CONVERT(VARCHAR(10), GETDATE(), 103) + ' '  + convert(VARCHAR(8), GETDATE(), 14)

Hope it helps

socket.shutdown vs socket.close

Isn't this code above wrong?

The close call directly after the shutdown call might make the kernel discard all outgoing buffers anyway.

According to http://blog.netherlabs.nl/articles/2009/01/18/the-ultimate-so_linger-page-or-why-is-my-tcp-not-reliable one needs to wait between the shutdown and the close until read returns 0.

Removing a list of characters in string

Python 3, single line list comprehension implementation.

from string import ascii_lowercase # 'abcdefghijklmnopqrstuvwxyz'
def remove_chars(input_string, removable):
  return ''.join([_ for _ in input_string if _ not in removable])

print(remove_chars(input_string="Stack Overflow", removable=ascii_lowercase))
>>> 'S O'

Android Device Chooser -- device not showing up

If you select Android Application in the Debug As dialog, you should be able to attach the debugger to the device directly. Make sure you run adb devices on your shell and see your device listed. If not, you will need to re-install the driver for the device. You can uninstall the drivers you have using USBdeview and then download and re-install the drivers until you see the serial number for the device listed when you run adb devices. - Arunabh Das

How do I replace whitespaces with underscore?

OP is using python, but in javascript (something to be careful of since the syntaxes are similar.

// only replaces the first instance of ' ' with '_'
"one two three".replace(' ', '_'); 
=> "one_two three"

// replaces all instances of ' ' with '_'
"one two three".replace(/\s/g, '_');
=> "one_two_three"

Correct way to detach from a container without stopping it

Type Ctrl+p then Ctrl+q. It will help you to turn interactive mode to daemon mode.

See https://docs.docker.com/v1.7/articles/basics/#running-an-interactive-shell.

# To detach the tty without exiting the shell,
# use the escape sequence Ctrl-p + Ctrl-q
# note: This will continue to exist in a stopped state once exited (see "docker ps -a")

How do I alias commands in git?

You need the git config alias command. Execute the following in a Git repository:

git config alias.ci commit

For global alias:

git config --global alias.ci commit

How to install the current version of Go in Ubuntu Precise

  1. If you have ubuntu-mate, you can install latest go by:

    umake go

  2. I have a script to download and install the last go from official website

     # Change these varialbe to where ever you feel comfortable
     DOWNLOAD_DIR=${HOME}/Downloads/GoLang
     INSTALL_DIR=${HOME}/App
     function install {
        mkdir -p ${DOWNLOAD_DIR}
        cd ${DOWNLOAD_DIR}
    
        echo "Fetching latest Go version..."
        typeset VER=`curl -s https://golang.org/dl/ | grep -m 1 -o 'go\([0-9]\)\+\(\.[0-9]\)\+'`
        if uname -m | grep 64 > /dev/null; then
            typeset ARCH=amd64
        else
            typeset ARCH=386
        fi
        typeset FILE=$VER.linux-$ARCH
    
        if [[ ! -e ${FILE}.tar.gz ]]; then
             echo "Downloading '$FILE' ..."
             wget https://storage.googleapis.com/golang/${FILE}.tar.gz
        fi
    
        echo "Installing ${FILE} ..."
        tar zxfC ${FILE}.tar.gz ${INSTALL_DIR}
        echo "Go is installed"
    }
    
    install
    

Setup your GOROOT, GOPATH and PATH:

export GOROOT=${INSTALL_DIR}/go
export GOPATH=<your go path>
export PATH=${PATH}:${GOROOT}/bin:${GOPATH}/bin

Return a `struct` from a function in C

struct var e2 address pushed as arg to callee stack and values gets assigned there. In fact, get() returns e2's address in eax reg. This works like call by reference.

Forward declaration of a typedef in C++

For those of you like me, who are looking to forward declare a C-style struct that was defined using typedef, in some c++ code, I have found a solution that goes as follows...

// a.h
 typedef struct _bah {
    int a;
    int b;
 } bah;

// b.h
 struct _bah;
 typedef _bah bah;

 class foo {
   foo(bah * b);
   foo(bah b);
   bah * mBah;
 };

// b.cpp
 #include "b.h"
 #include "a.h"

 foo::foo(bah * b) {
   mBah = b;
 }

 foo::foo(bah b) {
   mBah = &b;
 }

Trigger event when user scroll to specific element - with jQuery

Combining this question with the best answer from jQuery trigger action when a user scrolls past a certain part of the page

var element_position = $('#scroll-to').offset().top;

$(window).on('scroll', function() {
    var y_scroll_pos = window.pageYOffset;
    var scroll_pos_test = element_position;

    if(y_scroll_pos > scroll_pos_test) {
        //do stuff
    }
});

UPDATE

I've improved the code so that it will trigger when the element is half way up the screen rather than at the very top. It will also trigger the code if the user hits the bottom of the screen and the function hasn't fired yet.

var element_position = $('#scroll-to').offset().top;
var screen_height = $(window).height();
var activation_offset = 0.5;//determines how far up the the page the element needs to be before triggering the function
var activation_point = element_position - (screen_height * activation_offset);
var max_scroll_height = $('body').height() - screen_height - 5;//-5 for a little bit of buffer

//Does something when user scrolls to it OR
//Does it when user has reached the bottom of the page and hasn't triggered the function yet
$(window).on('scroll', function() {
    var y_scroll_pos = window.pageYOffset;

    var element_in_view = y_scroll_pos > activation_point;
    var has_reached_bottom_of_page = max_scroll_height <= y_scroll_pos && !element_in_view;

    if(element_in_view || has_reached_bottom_of_page) {
        //Do something
    }
});

How to remove a row from JTable?

A JTable normally forms the View part of an MVC implementation. You'll want to remove rows from your model. The JTable, which should be listening for these changes, will update to reflect this removal. Hence you won't find removeRow() or similar as a method on JTable.

'Invalid update: invalid number of rows in section 0

Here is some code from above added with actual action code (point 1 and 2);

func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    let deleteAction = UIContextualAction(style: .destructive, title: "Delete") { _, _, completionHandler in

        // 1. remove object from your array
        scannedItems.remove(at: indexPath.row)
        // 2. reload the table, otherwise you get an index out of bounds crash
        self.tableView.reloadData()

        completionHandler(true)
    }
    deleteAction.backgroundColor = .systemOrange
    let configuration = UISwipeActionsConfiguration(actions: [deleteAction])
    configuration.performsFirstActionWithFullSwipe = true
    return configuration
}

C# compiler error: "not all code paths return a value"

The compiler doesn't get the intricate logic where you return in the last iteration of the loop, so it thinks that you could exit out of the loop and end up not returning anything at all.

Instead of returning in the last iteration, just return true after the loop:

public static bool isTwenty(int num) {
  for(int j = 1; j <= 20; j++) {
    if(num % j != 0) {
      return false;
    }
  }
  return true;
}

Side note, there is a logical error in the original code. You are checking if num == 20 in the last condition, but you should have checked if j == 20. Also checking if num % j == 0 was superflous, as that is always true when you get there.

How do I catch an Ajax query post error?

A simple way is to implement ajaxError:

Whenever an Ajax request completes with an error, jQuery triggers the ajaxError event. Any and all handlers that have been registered with the .ajaxError() method are executed at this time.

For example:

$('.log').ajaxError(function() {
  $(this).text('Triggered ajaxError handler.');
});

I would suggest reading the ajaxError documentation. It does more than the simple use-case demonstrated above - mainly its callback accepts a number of parameters:

$('.log').ajaxError(function(e, xhr, settings, exception) {
  if (settings.url == 'ajax/missing.html') {
    $(this).text('Triggered ajaxError handler.');
  }
});

How can I delete derived data in Xcode 8?

It may differ between versions of xcodes. Best approach is to go xcode preference page and from tab "Locations", directly open "Derived Data" directory.

Initializing a static std::map<int, int> in C++

This is similar to PierreBdR, without copying the map.

#include <map>

using namespace std;

bool create_map(map<int,int> &m)
{
  m[1] = 2;
  m[3] = 4;
  m[5] = 6;
  return true;
}

static map<int,int> m;
static bool _dummy = create_map (m);

How do I clone a single branch in Git?

Note: the git1.7.10 (April 2012) actually allows you to clone only one branch:

# clone only the remote primary HEAD (default: origin/master)
git clone <url> --single-branch

# as in:
git clone <url> --branch <branch> --single-branch [<folder>]

You can see it in t5500-fetch-pack.sh:

test_expect_success 'single branch clone' '
  git clone --single-branch "file://$(pwd)/." singlebranch
'

Tobu comments that:

This is implicit when doing a shallow clone.
This makes git clone --depth 1 the easiest way to save bandwidth.

And since Git 1.9.0 (February 2014), shallow clones support data transfer (push/pull), so that option is even more useful now.
See more at "Is git clone --depth 1 (shallow clone) more useful than it makes out?".


"Undoing" a shallow clone is detailed at "Convert shallow clone to full clone" (git 1.8.3+)

# unshallow the current branch
git fetch --unshallow

# for getting back all the branches (see Peter Cordes' comment)
git config remote.origin.fetch refs/heads/*:refs/remotes/origin/*
git fetch --unshallow

As Chris comments:

the magic line for getting missing branches to reverse --single-branch is (git v2.1.4):

git config remote.origin.fetch +refs/heads/*:refs/remotes/origin/*
git fetch --unshallow  

With Git 2.26 (Q1 2020), "git clone --recurse-submodules --single-branch" now uses the same single-branch option when cloning the submodules.

See commit 132f600, commit 4731957 (21 Feb 2020) by Emily Shaffer (nasamuffin).
(Merged by Junio C Hamano -- gitster -- in commit b22db26, 05 Mar 2020)

clone: pass --single-branch during --recurse-submodules

Signed-off-by: Emily Shaffer
Acked-by: Jeff King

Previously, performing "git clone --recurse-submodules --single-branch" resulted in submodules cloning all branches even though the superproject cloned only one branch.

Pipe --single-branch through the submodule helper framework to make it to 'clone' later on.

How do I test a private function or a class that has private methods, fields or inner classes?

Please see below for an example;

The following import statement should be added:

import org.powermock.reflect.Whitebox;

Now you can directly pass the object which has the private method, method name to be called, and additional parameters as below.

Whitebox.invokeMethod(obj, "privateMethod", "param1");

Remove an array element and shift the remaining ones

std::copy does the job as far as moving elements is concerned:

 #include <algorithm>

 std::copy(array+3, array+5, array+2);

Note that the precondition for copy is that the destination must not be in the source range. It's permissible for the ranges to overlap.

Also, because of the way arrays work in C++, this doesn't "shorten" the array. It just shifts elements around within it. There is no way to change the size of an array, but if you're using a separate integer to track its "size" meaning the size of the part you care about, then you can of course decrement that.

So, the array you'll end up with will be as if it were initialized with:

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

How can I check for IsPostBack in JavaScript?

There is an even easier way that does not involve writing anything in the code behind: Just add this line to your javascript:

if(<%=(Not Page.IsPostBack).ToString().ToLower()%>){//Your JavaScript goodies here}

or

if(<%=(Page.IsPostBack).ToString().ToLower()%>){//Your JavaScript goodies here}

Base64 String throwing invalid character error

If removing \0 from the end of string is impossible, you can add your own character for each string you encode, and remove it on decode.

Git: How configure KDiff3 as merge tool and diff tool

Well, the problem is that Git can't find KDiff3 in the %PATH%.

In a typical Unix installation all executables reside in several well-known locations (/bin/, /usr/bin/, /usr/local/bin/, etc.), and one can invoke a program by simply typing its name in a shell processor (e.g. cmd.exe :) ).

In Microsoft Windows, programs are usually installed in dedicated paths so you can't simply type kdiff3 in a cmd session and get KDiff3 running.

The hard solution: you should tell Git where to find KDiff3 by specifying the full path to kdiff3.exe. Unfortunately, Git doesn't like spaces in the path specification in its config, so the last time I needed this, I ended up with those ancient "C:\Progra~1...\kdiff3.exe" as if it was late 1990s :)

The simple solution: Edit your computer settings and include the directory with kdiff3.exe in %PATH%. Then test if you can invoke it from cmd.exe by its name and then run Git.

Undefined function mysql_connect()

I was getting this error because the project I was working on was developed on php 5.6 and after install, the project was unable to run on php7.1.

Just for anyone that uses Vagrant with ubuntu/nginx, in the nginx directory(/etc/nginx/), there is a directory named "sites-available" which contains a file named like the url configured for the vagrant maschine. In my case was homestead.app. Within this file there is a line that says something like

    fastcgi_pass unix:/var/run/php/php7.1-fpm.sock;

There you can change the php version to the desired for that particular site.

Googled this but wasnt really able to find a simple answer that said where to look and what to change.

Hope that this helps anyone. Thanks.

How to check if a specified key exists in a given S3 bucket using Java

The other answers are for AWS SDK v1. Here is a method for AWS SDK v2 (currently 2.3.9).

Note that getObjectMetadata and doesObjectExist methods are not currently in the v2 SDK! So those are no longer options. We are forced to use either getObject or listObjects.

listObjects calls are currently 12.5 times more expensive to make than getObject. But AWS also charges for any data downloaded, which raises the price of getObject if the file exists. As long as the file is very unlikely to exist (for example, you have generated a new UUID key randomly and just need to double-check that it isn't taken) then calling getObject is significantly cheaper by my calculation.

Just to be on the safe side though, I added a range() specification to ask AWS to only send a few bytes of the file. As far as I know the SDK will always respect this and not charge you for downloading the whole file. But I haven't verified that so rely on that behavior at your own risk! (Also, I'm not sure what how range behaves if the S3 object is 0 bytes long.)

    private boolean sanityCheckNewS3Key(String bucket, String key) {

        ResponseInputStream<GetObjectResponse> resp = null;
        try {
            resp = s3client.getObject(GetObjectRequest.builder()
                .bucket(bucket)
                .key(key)
                .range("bytes=0-3")
                .build());
        }
        catch (NoSuchKeyException e) {
            return false;
        }
        catch (AwsServiceException se) {
            throw se;
        }
        finally {
            if (resp != null) {
                try {
                    resp.close();
                } catch (IOException e) {
                    log.warn("Exception while attempting to close S3 input stream", e);
                }
            }
        }
        return true;
    }
}

Note: this code assumes s3Client and log are declared and initialized elsewhere. Method returns a boolean, but can throw exceptions.

Embedding Windows Media Player for all browsers

May I suggest the jQuery Media Plugin? Provides embed code for all kinds of video, not just WMV and does browser detection, keeping all that messy switch/case statements out of your templates.

Batch file to run a command in cmd within a directory

CMD.EXE will not execute internal commands contained inside the string. Only actual files can be launched with that string.

You will need to actually call a batch file to do what you want.

BAT1.bat

start cmd.exe /k bat2.bat

BAT2.bat

cd C:\activiti-5.9\setup
ant demo.start

You may want to create a folder called BAT, and add it's location to your path. So if you create C:\BAT, add C:\BAT\; to the path. The path is located at:

    click -> Start -> right-click Computer -> Properties ->
    click -> Avanced System Settings -> Environment Variables
   select -> Path (From either list. User Variables are specific to 
                   your profile, System Variables are, duh, system-wide.)
    Click -> Edit
Press the -> the [END] or [HOME] key.
     Type -> C:\BAT\;
    Click -> OK -> OK

Now place all your batch files in C:\BAT and they will be found, regardless of the current directory.

How can I add an item to a IEnumerable<T> collection?

You cannot, because IEnumerable<T> does not necessarily represent a collection to which items can be added. In fact, it does not necessarily represent a collection at all! For example:

IEnumerable<string> ReadLines()
{
     string s;
     do
     {
          s = Console.ReadLine();
          yield return s;
     } while (!string.IsNullOrEmpty(s));
}

IEnumerable<string> lines = ReadLines();
lines.Add("foo") // so what is this supposed to do??

What you can do, however, is create a new IEnumerable object (of unspecified type), which, when enumerated, will provide all items of the old one, plus some of your own. You use Enumerable.Concat for that:

 items = items.Concat(new[] { "foo" });

This will not change the array object (you cannot insert items into to arrays, anyway). But it will create a new object that will list all items in the array, and then "Foo". Furthermore, that new object will keep track of changes in the array (i.e. whenever you enumerate it, you'll see the current values of items).

Add User to Role ASP.NET Identity

This one works for me. You can see this code on AccountController -> Register

var user = new JobUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
    //add this to add role to user
     await UserManager.AddToRoleAsync(user.Id, "Name of your role");
}

but the role name must exist in your AspNetRoles table.

Use own username/password with git and bitbucket

The prompt:

Password for 'https://[email protected]':

suggests, that you are using https not ssh. SSH urls start with git@, for example:

[email protected]:beginninggit/alias.git

Even if you work alone, with a single repo that you own, the operation:

git push

will cause:

Password for 'https://[email protected]':

if the remote origin starts with https.

Check your remote with:

git remote -v

The remote depends on git clone. If you want to use ssh clone the repo using its ssh url, for example:

git clone [email protected]:user/repo.git

I suggest you to start with git push and git pull for your private repo.

If that works, you have two joices suggested by Lazy Badger:

  • Pull requests
  • Team work

What is the way of declaring an array in JavaScript?

In your first example, you are making a blank array, same as doing var x = []. The 2nd example makes an array of size 3 (with all elements undefined). The 3rd and 4th examples are the same, they both make arrays with those elements.

Be careful when using new Array().

var x = new Array(10); // array of size 10, all elements undefined
var y = new Array(10, 5); // array of size 2: [10, 5]

The preferred way is using the [] syntax.

var x = []; // array of size 0
var y = [10] // array of size 1: [1]

var z = []; // array of size 0
z[2] = 12;  // z is now size 3: [undefined, undefined, 12]

Why does Java have transient fields?

To allow you to define variables that you don't want to serialize.

In an object you may have information that you don't want to serialize/persist (perhaps a reference to a parent factory object), or perhaps it doesn't make sense to serialize. Marking these as 'transient' means the serialization mechanism will ignore these fields.

system("pause"); - Why is it wrong?

In summary, it has to pause the programs execution and make a system call and allocate unnecessary resources when you could be using something as simple as cin.get(). People use System("PAUSE") because they want the program to wait until they hit enter to they can see their output. If you want a program to wait for input, there are built in functions for that which are also cross platform and less demanding.

Further explanation in this article.

Errno 13 Permission denied Python

Your user don't have the right permissions to read the file, since you used open() without specifying a mode.

Since you're using Windows, you should read a little more about File and Folder Permissions.

Also, if you want to play with your file permissions, you should right-click it, choose Properties and select Security tab.

Or if you want to be a little more hardcore, you can run your script as admin.

SO Related Questions:

Using cut command to remove multiple columns

The same could be done with Perl
Because it uses 0-based-indexing instead of 1-based-indexing, the field values are offset by 1

perl -F, -lane 'print join ",", @F[1..3,5..9,11..19]'    

is equivalent to:

cut -d, -f2-4,6-10,12-20

If the commas are not needed in the output:

perl -F, -lane 'print "@F[1..3,5..9,11..19]"'

R memory management / cannot allocate vector of size n Mb

The save/load method mentioned above works for me. I am not sure how/if gc() defrags the memory but this seems to work.

# defrag memory 
save.image(file="temp.RData")
rm(list=ls())
load(file="temp.RData")

How to iterate over associative arrays in Bash

declare -a arr
echo "-------------------------------------"
echo "Here another example with arr numeric"
echo "-------------------------------------"
arr=( 10 200 3000 40000 500000 60 700 8000 90000 100000 )

echo -e "\n Elements in arr are:\n ${arr[0]} \n ${arr[1]} \n ${arr[2]} \n ${arr[3]} \n ${arr[4]} \n ${arr[5]} \n ${arr[6]} \n ${arr[7]} \n ${arr[8]} \n ${arr[9]}"

echo -e " \n Total elements in arr are : ${arr[*]} \n"

echo -e " \n Total lenght of arr is : ${#arr[@]} \n"

for (( i=0; i<10; i++ ))
do      echo "The value in position $i for arr is [ ${arr[i]} ]"
done

for (( j=0; j<10; j++ ))
do      echo "The length in element $j is ${#arr[j]}"
done

for z in "${!arr[@]}"
do      echo "The key ID is $z"
done
~

What does void do in java?

Void: the type modifier void states that the main method does not return any value. All parameters to a method are declared inside a prior of parenthesis. Here String args[ ] declares a parameter named args which contains an array of objects of the class type string.

Simple Deadlock Examples

Here is my detailed example for deadlock, after spending lots of time. Hope it helps :)

package deadlock;

public class DeadlockApp {

    String s1 = "hello";
    String s2 = "world";

    Thread th1 = new Thread() {
        public void run() {
            System.out.println("Thread th1 has started");
            synchronized (s1) { //A lock is created internally (holds access of s1), lock will be released or unlocked for s1, only when it exits the block Line #23
                System.out.println("Executing first synchronized block of th1!");
                try {
                    Thread.sleep(1000);
                } catch(InterruptedException ex) {
                    System.out.println("Exception is caught in th1");
                }
                System.out.println("Waiting for the lock to be released from parrallel thread th1");
                synchronized (s2) { //As another has runned parallely Line #32, lock has been created for s2
                    System.out.println(s1 + s2);
                }

            }
            System.out.println("Thread th1 has executed");
        }
    };


    Thread th2 = new Thread() {
        public void run() {
            System.out.println("Thread th2 has started");
            synchronized (s2) { //A lock is created internally (holds access of s2), lock will be released or unlocked for s2, only when it exits the block Line #44
                System.out.println("Executing first synchronized block of th2!");
                try {
                    Thread.sleep(1000);
                } catch(InterruptedException ex) {
                    System.out.println("Exception is caught in th2");
                }
                System.out.println("Waiting for the lock to be released from parrallel thread th2");
                synchronized (s1) { //As another has runned parallely Line #11, lock has been created for s1
                    System.out.println(s1 + s2);
                }

            }
            System.out.println("Thread th2 has executed");
        }
    };

    public static void main(String[] args) {
        DeadlockApp deadLock = new DeadlockApp();
        deadLock.th1.start();
        deadLock.th2.start();
        //Line #51 and #52 runs parallely on executing the program, a lock is created inside synchronized method
        //A lock is nothing but, something like a blocker or wall, which holds access of the variable from being used by others.
        //Locked object is accessible, only when it is unlocked (i.e exiting  the synchronized block)
        //Lock cannot be created for primitive types (ex: int, float, double)
        //Dont forget to add thread.sleep(time) because if not added, then object access will not be at same time for both threads to create Deadlock (not actual runtime with lots of threads) 
        //This is a simple program, so we added sleep90 to create Deadlock, it will execute successfully, if it is removed. 
    }

    //Happy coding -- Parthasarathy S
}

List passed by ref - help me explain this behaviour

You are passing a reference to the list, but your aren't passing the list variable by reference - so when you call ChangeList the value of the variable (i.e. the reference - think "pointer") is copied - and changes to the value of the parameter inside ChangeList aren't seen by TestMethod.

try:

private void ChangeList(ref List<int> myList) {...}
...
ChangeList(ref myList);

This then passes a reference to the local-variable myRef (as declared in TestMethod); now, if you reassign the parameter inside ChangeList you are also reassigning the variable inside TestMethod.

Java, How to add values to Array List used as value in HashMap

String courseID = "Comp-101";
List<String> scores = new ArrayList<String> ();
scores.add("100");
scores.add("90");
scores.add("80");
scores.add("97");

Map<String, ArrayList<String>> myMap = new HashMap<String, ArrayList<String>>();
myMap.put(courseID, scores);

Hope this helps!

VS 2012: Scroll Solution Explorer to current file

If you don't have ReSharper installed and still want to use the shortcut Shift+Alt+L to move focus to the current file in Solution Explorer in Visual Studio 2013 then please follow these steps:

  1. Go to Tools->Options and search for "Keyboard" in the Search Options textbox:

enter image description here

  1. In the Show commands containing box type "solutionexplorer" and then in the list below look for the SyncWithActiveDocument command: enter image description here

  2. Click in textbox under "Press short keys" label and press: Shift+Alt+L and click the Assign button and you are done: enter image description here

To verify open any file in Visual Studio and press the shortcut keys Shift+Alt+L and you'll see the file in the solution explorer. Enjoy!

How do I set the figure title and axes labels font size in Matplotlib?

Per the official guide, use of pylab is no longer recommended. matplotlib.pyplot should be used directly instead.

Globally setting font sizes via rcParams should be done with

import matplotlib.pyplot as plt
plt.rcParams['axes.labelsize'] = 16
plt.rcParams['axes.titlesize'] = 16

# or

params = {'axes.labelsize': 16,
          'axes.titlesize': 16}
plt.rcParams.update(params)

# or

import matplotlib as mpl
mpl.rc('axes', labelsize=16, titlesize=16)

# or 

axes = {'labelsize': 16,
        'titlesize': 16}
mpl.rc('axes', **axes)

The defaults can be restored using

plt.rcParams.update(plt.rcParamsDefault)

You can also do this by creating a style sheet in the stylelib directory under the matplotlib configuration directory (you can get your configuration directory from matplotlib.get_configdir()). The style sheet format is

axes.labelsize: 16
axes.titlesize: 16

If you have a style sheet at /path/to/mpl_configdir/stylelib/mystyle.mplstyle then you can use it via

plt.style.use('mystyle')

# or, for a single section

with plt.style.context('mystyle'):
    # ...

You can also create (or modify) a matplotlibrc file which shares the format

axes.labelsize = 16
axes.titlesize = 16

Depending on which matplotlibrc file you modify these changes will be used for only the current working directory, for all working directories which do not have a matplotlibrc file, or for all working directories which do not have a matplotlibrc file and where no other matplotlibrc file has been specified. See this section of the customizing matplotlib page for more details.

A complete list of the rcParams keys can be retrieved via plt.rcParams.keys(), but for adjusting font sizes you have (italics quoted from here)

  • axes.labelsize - Fontsize of the x and y labels
  • axes.titlesize - Fontsize of the axes title
  • figure.titlesize - Size of the figure title (Figure.suptitle())
  • xtick.labelsize - Fontsize of the tick labels
  • ytick.labelsize - Fontsize of the tick labels
  • legend.fontsize - Fontsize for legends (plt.legend(), fig.legend())
  • legend.title_fontsize - Fontsize for legend titles, None sets to the same as the default axes. See this answer for usage example.

all of which accept string sizes {'xx-small', 'x-small', 'smaller', 'small', 'medium', 'large', 'larger', 'x-large', 'xxlarge'} or a float in pt. The string sizes are defined relative to the default font size which is specified by

  • font.size - the default font size for text, given in pts. 10 pt is the standard value

Additionally, the weight can be specified (though only for the default it appears) by

  • font.weight - The default weight of the font used by text.Text. Accepts {100, 200, 300, 400, 500, 600, 700, 800, 900} or 'normal' (400), 'bold' (700), 'lighter', and 'bolder' (relative with respect to current weight).

opening html from google drive

Steps:

  1. Upload html file to the google drive and share it as "Public on the web" after uploading just make sure that the content of your html is not modified in the drive.
  2. Right click on the shared file and click on 'Get link' and save it to notepad it will look something like 'https://drive.google.com/open?id=0B55nkHvMDw18T3VaYjY3NEE4SEE'
  3. Take the code (about 28 character alphanumeric) after '=' sign from the above link and paste it after 'https://googledrive.com/host/' now 'https://googledrive.com/host/0B55nkHvMDw18T3VaYjY3NEE4SEE' is your actual sharable url link, open the html file from address bar of the browser using this url.

Blocking device rotation on mobile web pages

With the new CSS3 features, you could rotate the page the opposite orientation that they rotated. Sorry, no IE7- support. :(.

var rotate = 0 - window.orientation;
setAttribute("transform:rotate("+rotate+"deg);-ms-transform:rotate("+rotate+"deg);-webkit-transform:rotate("+rotate+"deg)", "style");

Calling C++ class methods via a function pointer

I don't think anyone has explained here that one issue is that you need "member pointers" rather than normal function pointers.

Member pointers to functions are not simply function pointers. In implementation terms, the compiler cannot use a simple function address because, in general, you don't know the address to call until you know which object to dereference for (think virtual functions). You also need to know the object in order to provide the this implicit parameter, of course.

Having said that you need them, now I'll say that you really need to avoid them. Seriously, member pointers are a pain. It is much more sane to look at object-oriented design patterns that achieve the same goal, or to use a boost::function or whatever as mentioned above - assuming you get to make that choice, that is.

If you are supplying that function pointer to existing code, so you really need a simple function pointer, you should write a function as a static member of the class. A static member function doesn't understand this, so you'll need to pass the object in as an explicit parameter. There was once a not-that-unusual idiom along these lines for working with old C code that needs function pointers

class myclass
{
  public:
    virtual void myrealmethod () = 0;

    static void myfunction (myclass *p);
}

void myclass::myfunction (myclass *p)
{
  p->myrealmethod ();
}

Since myfunction is really just a normal function (scope issues aside), a function pointer can be found in the normal C way.

EDIT - this kind of method is called a "class method" or a "static member function". The main difference from a non-member function is that, if you reference it from outside the class, you must specify the scope using the :: scope resolution operator. For example, to get the function pointer, use &myclass::myfunction and to call it use myclass::myfunction (arg);.

This kind of thing is fairly common when using the old Win32 APIs, which were originally designed for C rather than C++. Of course in that case, the parameter is normally LPARAM or similar rather than a pointer, and some casting is needed.

How can I restart a Java application?

Similar to Yoda's 'improved' answer, but with further improvements (both functional, readability, and testability). It's now safe to run, and restarts for as as many times as the amount of program arguments given.

  • No accumulation of JAVA_TOOL_OPTIONS options.
  • Automatically finds main class.
  • Inherits current stdout/stderr.

public static void main(String[] args) throws Exception {
    if (args.length == 0)
        return;
    else
        args = Arrays.copyOf(args, args.length - 1);

    List<String> command = new ArrayList<>(32);
    appendJavaExecutable(command);
    appendVMArgs(command);
    appendClassPath(command);
    appendEntryPoint(command);
    appendArgs(command, args);

    System.out.println(command);
    try {
        new ProcessBuilder(command).inheritIO().start();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

private static void appendJavaExecutable(List<String> cmd) {
    cmd.add(System.getProperty("java.home") + File.separator + "bin" + File.separator + "java");
}

private static void appendVMArgs(Collection<String> cmd) {
    Collection<String> vmArguments = ManagementFactory.getRuntimeMXBean().getInputArguments();

    String javaToolOptions = System.getenv("JAVA_TOOL_OPTIONS");
    if (javaToolOptions != null) {
        Collection<String> javaToolOptionsList = Arrays.asList(javaToolOptions.split(" "));
        vmArguments = new ArrayList<>(vmArguments);
        vmArguments.removeAll(javaToolOptionsList);
    }

    cmd.addAll(vmArguments);
}

private static void appendClassPath(List<String> cmd) {
    cmd.add("-cp");
    cmd.add(ManagementFactory.getRuntimeMXBean().getClassPath());
}

    private static void appendEntryPoint(List<String> cmd) {
    StackTraceElement[] stackTrace          = new Throwable().getStackTrace();
    StackTraceElement   stackTraceElement   = stackTrace[stackTrace.length - 1];
    String              fullyQualifiedClass = stackTraceElement.getClassName();
    String              entryMethod         = stackTraceElement.getMethodName();
    if (!entryMethod.equals("main"))
        throw new AssertionError("Entry point is not a 'main()': " + fullyQualifiedClass + '.' + entryMethod);

    cmd.add(fullyQualifiedClass);
}

private static void appendArgs(List<String> cmd, String[] args) {
    cmd.addAll(Arrays.asList(args));
}

V1.1 Bugfix: null pointer if JAVA_TOOL_OPTIONS is not set


Example:

$ java -cp Temp.jar Temp a b c d e
[/usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java, -cp, Temp.jar, Temp, a, b, c, d]
[/usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java, -cp, Temp.jar, Temp, a, b, c]
[/usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java, -cp, Temp.jar, Temp, a, b]
[/usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java, -cp, Temp.jar, Temp, a]
[/usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java, -cp, Temp.jar, Temp]
$

Parse json string to find and element (key / value)

Use a JSON parser, like JSON.NET

string json = "{ \"Atlantic/Canary\": \"GMT Standard Time\", \"Europe/Lisbon\": \"GMT Standard Time\", \"Antarctica/Mawson\": \"West Asia Standard Time\", \"Etc/GMT+3\": \"SA Eastern Standard Time\", \"Etc/GMT+2\": \"UTC-02\", \"Etc/GMT+1\": \"Cape Verde Standard Time\", \"Etc/GMT+7\": \"US Mountain Standard Time\", \"Etc/GMT+6\": \"Central America Standard Time\", \"Etc/GMT+5\": \"SA Pacific Standard Time\", \"Etc/GMT+4\": \"SA Western Standard Time\", \"Pacific/Wallis\": \"UTC+12\", \"Europe/Skopje\": \"Central European Standard Time\", \"America/Coral_Harbour\": \"SA Pacific Standard Time\", \"Asia/Dhaka\": \"Bangladesh Standard Time\", \"America/St_Lucia\": \"SA Western Standard Time\", \"Asia/Kashgar\": \"China Standard Time\", \"America/Phoenix\": \"US Mountain Standard Time\", \"Asia/Kuwait\": \"Arab Standard Time\" }";
var data = (JObject)JsonConvert.DeserializeObject(json);
string timeZone = data["Atlantic/Canary"].Value<string>();

At least one JAR was scanned for TLDs yet contained no TLDs

(tomcat 8.0.28) Above method did not work for me. This is what worked:

  1. Add this line to the end of your {CATALINA-HOME}/conf/logging.properties:

    org.apache.jasper.level = FINEST
    
  2. Shut down the server (if started).

  3. Open console and run (in case of Windows):

    %CATALINA_HOME%\bin\catalina.bat run
    
  4. Enjoy logs, e.g. (again, for Windows):

    {CATALINA-HOME}/logs/catalina.2015-12-28.log
    

I gave up on integrating this with Eclipse launch configuration so be aware that this works only from console, launching the server from Eclipse won't produce additional log messages.

Get String in YYYYMMDD format from JS date object?

I hope this function will be useful

function formatDate(dDate,sMode){       
        var today = dDate;
        var dd = today.getDate();
        var mm = today.getMonth()+1; //January is 0!
        var yyyy = today.getFullYear();
        if(dd<10) {
            dd = '0'+dd
        } 
        if(mm<10) {
            mm = '0'+mm
        } 
        if (sMode+""==""){
            sMode = "dd/mm/yyyy";
        }
        if (sMode == "yyyy-mm-dd"){
            return  yyyy + "-" + mm + "-" + dd + "";
        }
        if (sMode == "dd/mm/yyyy"){
            return  dd + "/" + mm + "/" + yyyy;
        }

    }

message box in jquery

What is [Serializable] and when should I use it?

Serialization

Serialization is the process of converting an object or a set of objects graph into a stream, it is a byte array in the case of binary serialization

Uses of Serialization

  1. To save the state of an object into a file, database etc. and use it latter.
  2. To send an object from one process to another (App Domain) on the same machine and also send it over wire to a process running on another machine.
  3. To create a clone of the original object as a backup while working on the main object.
  4. A set of objects can easily be copied to the system’s clipboard and then pasted into the same or another application

Below are some useful custom attributes that are used during serialization of an object

[Serializable] -> It is used when we mark an object’s serializable [NonSerialized] -> It is used when we do not want to serialize an object’s field. [OnSerializing] -> It is used when we want to perform some action while serializing an object [OnSerialized] -> It is used when we want to perform some action after serialized an object into stream.

Below is the example of serialization

[Serializable]
    internal class DemoForSerializable
    {
        internal string Fname = string.Empty;
        internal string Lname = string.Empty;

        internal Stream SerializeToMS(DemoForSerializable demo)
        {
            DemoForSerializable objSer = new DemoForSerializable();
            MemoryStream ms = new MemoryStream();
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(ms, objSer);
            return ms;
        }

        [OnSerializing]
        private void OnSerializing(StreamingContext context) {
            Fname = "sheo";
            Lname = "Dayal";
        }
        [OnSerialized]
        private void OnSerialized(StreamingContext context)
        {
       // Do some work after serialized object
        }

    }

Here is the calling code

class Program
    {
        string fname = string.Empty;
        string Lname = string.Empty; 

       static void Main(string[] args)
        {
            DemoForSerializable demo = new DemoForSerializable();

            Stream ms = demo.SerializeToMS(demo);
            ms.Position = 0;

            DemoForSerializable demo1 = new BinaryFormatter().Deserialize(ms) as DemoForSerializable;

            Console.WriteLine(demo1.Fname);
            Console.WriteLine(demo1.Lname);
            Console.ReadLine();
        }

    }

java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader

Please note that there's a naming convention. Your lib needs to be called libexample.so .

LoadLibrary("example") will look for libexample.so.

The .so library needs to be inside the apk under the lib folder (since you are developing for Android, it needs to be under the lib/armeabi and lib/armeabi-v7a folders - why both folders ? some versions of Android look under lib/armeabi and some look under lib/armeabi-v7a ... se what works for you ).

Other things to look for :

  • make sure you compile for the correct architecture (if you compile for armeabi v5 it won't work on armeabiv7 or armeabiv7s ).

  • make sure your exported prototypes are used in the correct class (check the hello jni example. Your exposed functions need to look something like Java_mypackagename_myjavabridgeclass_myfunction).

For example the function Java_com_example_sample_hello will translate in the java class com.example.sample , function hello.

Convert String to double in Java

Used this to convert any String number to double when u need int just convert the data type from num and num2 to int ; took all the cases for any string double with Eng:"Bader Qandeel"

public static double str2doubel(String str) {
    double num = 0;
    double num2 = 0;
    int idForDot = str.indexOf('.');
    boolean isNeg = false;
    String st;
    int start = 0;
    int end = str.length();

    if (idForDot != -1) {
        st = str.substring(0, idForDot);
        for (int i = str.length() - 1; i >= idForDot + 1; i--) {
            num2 = (num2 + str.charAt(i) - '0') / 10;
        }
    } else {
        st = str;
    }

    if (st.charAt(0) == '-') {
        isNeg = true;
        start++;
    } else if (st.charAt(0) == '+') {
        start++;
    }

    for (int i = start; i < st.length(); i++) {
        if (st.charAt(i) == ',') {
            continue;
        }
        num *= 10;
        num += st.charAt(i) - '0';
    }

    num = num + num2;
    if (isNeg) {
        num = -1 * num;
    }
    return num;
}

Is there a typescript List<> and/or Map<> class/library?

It's very easy to write that yourself, and that way you have more control over things.. As the other answers say, TypeScript is not aimed at adding runtime types or functionality.

Map:

class Map<T> {
    private items: { [key: string]: T };

    constructor() {
        this.items = {};
    }

    add(key: string, value: T): void {
        this.items[key] = value;
    }

    has(key: string): boolean {
        return key in this.items;
    }

    get(key: string): T {
        return this.items[key];
    }
}

List:

class List<T> {
    private items: Array<T>;

    constructor() {
        this.items = [];
    }

    size(): number {
        return this.items.length;
    }

    add(value: T): void {
        this.items.push(value);
    }

    get(index: number): T {
        return this.items[index];
    }
}

I haven't tested (or even tried to compile) this code, but it should give you a starting point.. you can of course then change what ever you want and add the functionality that YOU need...

As for your "special needs" from the List, I see no reason why to implement a linked list, since the javascript array lets you add and remove items.
Here's a modified version of the List to handle the get prev/next from the element itself:

class ListItem<T> {
    private list: List<T>;
    private index: number;

    public value: T;

    constructor(list: List<T>, value: T, index: number) {
        this.list = list;
        this.index = index;
        this.value = value;
    }

    prev(): ListItem<T> {
        return this.list.get(this.index - 1);
    }

    next(): ListItem<T> {
        return this.list.get(this.index + 1);   
    }
}

class List<T> {
    private items: Array<ListItem<T>>;

    constructor() {
        this.items = [];
    }

    size(): number {
        return this.items.length;
    }

    add(value: T): void {
        this.items.push(new ListItem<T>(this, value, this.size()));
    }

    get(index: number): ListItem<T> {
        return this.items[index];
    }
}

Here too you're looking at untested code..

Hope this helps.


Edit - as this answer still gets some attention

Javascript has a native Map object so there's no need to create your own:

let map = new Map();
map.set("key1", "value1");
console.log(map.get("key1")); // value1

setOnItemClickListener on custom ListView

If in the listener you get the root layout of the item (say itemLayout), and you gave some id's to the textviews, you can then get them with something like itemLayout.findViewById(R.id.textView1).

PHP move_uploaded_file() error?

Edit the code to be as follows:

// Upload file
$moved = move_uploaded_file($_FILES["file"]["tmp_name"], "images/" . "myFile.txt" );

if( $moved ) {
  echo "Successfully uploaded";         
} else {
  echo "Not uploaded because of error #".$_FILES["file"]["error"];
}

It will give you one of the following error code values 1 to 8:

UPLOAD_ERR_INI_SIZE = Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini.

UPLOAD_ERR_FORM_SIZE = Value: 2; The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.

UPLOAD_ERR_PARTIAL = Value: 3; The uploaded file was only partially uploaded.

UPLOAD_ERR_NO_FILE = Value: 4; No file was uploaded.

UPLOAD_ERR_NO_TMP_DIR = Value: 6; Missing a temporary folder. Introduced in PHP 5.0.3.

UPLOAD_ERR_CANT_WRITE = Value: 7; Failed to write file to disk. Introduced in PHP 5.1.0.

UPLOAD_ERR_EXTENSION = Value: 8; A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo() may help.

Naming Classes - How to avoid calling everything a "<WhatEver>Manager"?

I think the most important thing to keep in mind is: is the name descriptive enough? Can you tell by looking at the name what the Class is supposed to do? Using words like "Manager", "Service" or "Handler" in your class names can be considered too generic, but since a lot of programmers use them it also helps understanding what the class is for.

I myself have been using the facade-pattern a lot (at least, I think that's what it is called). I could have a User class that describes just one user, and a Users class that keeps track of my "collection of users". I don't call the class a UserManager because I don't like managers in real-life and I don't want to be reminded of them :) Simply using the plural form helps me understand what the class does.

How to send value attribute from radio button in PHP

Should be :

HTML :

<form method="post" action="">
    <input id="name" name="name" type="text" size="40"/>
    <input type="radio" name="radio" value="test"/>Test
    <input type="submit" name="submit" value="submit"/>
</form>

PHP Code :

if(isset($_POST['submit']))
{

    echo $radio_value = $_POST["radio"];
}

How to force garbage collector to run?

I think that .Net Framework does this automatically but just in case. First, make sure to select what you want to erase, and then call the garbage collector:

randomClass object1 = new randomClass
...
...
// Give a null value to the code you want to delete
object1 = null;
// Then call the garbage collector to erase what you gave the null value
GC.Collect();

I think that's it.. Hope I help someone.

PHP order array by date?

I recommend using DateTime objects instead of strings, because you cannot easily compare strings, which is required for sorting. You also get additional advantages for working with dates.

Once you have the DateTime objects, sorting is quite easy:

usort($array, function($a, $b) {
  return ($a['date'] < $b['date']) ? -1 : 1;
});

How to create a DB link between two oracle instances

as a simple example:

CREATE DATABASE LINK _dblink_name_
  CONNECT TO _username_
    IDENTIFIED BY _passwd_
      USING '$_ORACLE_SID_'

for more info: http://docs.oracle.com/cd/B19306_01/server.102/b14200/statements_5005.htm

The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead

  1. Why is this happening?

    The entire ext/mysql PHP extension, which provides all functions named with the prefix mysql_, was officially deprecated in PHP v5.5.0 and removed in PHP v7.

    It was originally introduced in PHP v2.0 (November 1997) for MySQL v3.20, and no new features have been added since 2006. Coupled with the lack of new features are difficulties in maintaining such old code amidst complex security vulnerabilities.

    The manual has contained warnings against its use in new code since June 2011.

  2. How can I fix it?

    As the error message suggests, there are two other MySQL extensions that you can consider: MySQLi and PDO_MySQL, either of which can be used instead of ext/mysql. Both have been in PHP core since v5.0, so if you're using a version that is throwing these deprecation errors then you can almost certainly just start using them right away—i.e. without any installation effort.

    They differ slightly, but offer a number of advantages over the old extension including API support for transactions, stored procedures and prepared statements (thereby providing the best way to defeat SQL injection attacks). PHP developer Ulf Wendel has written a thorough comparison of the features.

    Hashphp.org has an excellent tutorial on migrating from ext/mysql to PDO.

  3. I understand that it's possible to suppress deprecation errors by setting error_reporting in php.ini to exclude E_DEPRECATED:

    error_reporting = E_ALL ^ E_DEPRECATED
    

    What will happen if I do that?

    Yes, it is possible to suppress such error messages and continue using the old ext/mysql extension for the time being. But you really shouldn't do this—this is a final warning from the developers that the extension may not be bundled with future versions of PHP (indeed, as already mentioned, it has been removed from PHP v7). Instead, you should take this opportunity to migrate your application now, before it's too late.

    Note also that this technique will suppress all E_DEPRECATED messages, not just those to do with the ext/mysql extension: therefore you may be unaware of other upcoming changes to PHP that would affect your application code. It is, of course, possible to only suppress errors that arise on the expression at issue by using PHP's error control operator—i.e. prepending the relevant line with @—however this will suppress all errors raised by that expression, not just E_DEPRECATED ones.


What should you do?

  • You are starting a new project.

    There is absolutely no reason to use ext/mysql—choose one of the other, more modern, extensions instead and reap the rewards of the benefits they offer.

  • You have (your own) legacy codebase that currently depends upon ext/mysql.

    It would be wise to perform regression testing: you really shouldn't be changing anything (especially upgrading PHP) until you have identified all of the potential areas of impact, planned around each of them and then thoroughly tested your solution in a staging environment.

    • Following good coding practice, your application was developed in a loosely integrated/modular fashion and the database access methods are all self-contained in one place that can easily be swapped out for one of the new extensions.

      Spend half an hour rewriting this module to use one of the other, more modern, extensions; test thoroughly. You can later introduce further refinements to reap the rewards of the benefits they offer.

    • The database access methods are scattered all over the place and cannot easily be swapped out for one of the new extensions.

      Consider whether you really need to upgrade to PHP v5.5 at this time.

      You should begin planning to replace ext/mysql with one of the other, more modern, extensions in order that you can reap the rewards of the benefits they offer; you might also use it as an opportunity to refactor your database access methods into a more modular structure.

      However, if you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.

  • You are using a third party project that depends upon ext/mysql.

    Consider whether you really need to upgrade to PHP v5.5 at this time.

    Check whether the developer has released any fixes, workarounds or guidance in relation to this specific issue; or, if not, pressure them to do so by bringing this matter to their attention. If you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.

    It is absolutely essential to perform regression testing.

Selecting Folder Destination in Java?

Oracles Java Tutorial for File Choosers: http://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html

Note getSelectedFile() returns the selected folder, despite the name. getCurrentDirectory() returns the directory of the selected folder.

import javax.swing.*;

public class Example
{
    public static void main(String[] args)
    {
        JFileChooser f = new JFileChooser();
        f.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); 
        f.showSaveDialog(null);

        System.out.println(f.getCurrentDirectory());
        System.out.println(f.getSelectedFile());
    }      
}

Kill detached screen session

"kill" will only kill one screen window. To "kill" the complete session, use quit.

Example

$ screen -X -S [session # you want to kill] quit

For dead sessions use: $ screen -wipe

password for postgres

Set the default password in the .pgpass file. If the server does not save the password, it is because it is not set in the .pgpass file, or the permissions are open and the file is therefore ignored.

Read more about the password file here.

Also, be sure to check the permissions: on *nix systems the permissions on .pgpass must disallow any access to world or group; achieve this by the command chmod 0600 ~/.pgpass. If the permissions are less strict than this, the file will be ignored.

Have you tried logging-in using PGAdmin? You can save the password there, and modify the pgpass file.

Adding headers to requests module

From http://docs.python-requests.org/en/latest/user/quickstart/

url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
headers = {'content-type': 'application/json'}

r = requests.post(url, data=json.dumps(payload), headers=headers)

You just need to create a dict with your headers (key: value pairs where the key is the name of the header and the value is, well, the value of the pair) and pass that dict to the headers parameter on the .get or .post method.

So more specific to your question:

headers = {'foobar': 'raboof'}
requests.get('http://himom.com', headers=headers)

How to set the height of table header in UITableView?

In Xcode 10 you can set header and footer of section hight from "Size Inspector" tab

Size Inspector header

Truncating all tables in a Postgres database

Could you use dynamic SQL to execute each statement in turn? You would probably have to write a PL/pgSQL script to do this.

http://www.postgresql.org/docs/8.3/static/plpgsql-statements.html (section 38.5.4. Executing Dynamic Commands)

Sleep function in ORACLE

If Java is installed on your 11G then you can do it in a java class and call it from your PL/SQL, but I am not sure that it does not require also a specific grant to call java.

A tool to convert MATLAB code to Python

There are several tools for converting Matlab to Python code.

The only one that's seen recent activity (last commit from June 2018) is Small Matlab to Python compiler (also developed here: SMOP@chiselapp).

Other options include:

  • LiberMate: translate from Matlab to Python and SciPy (Requires Python 2, last update 4 years ago).
  • OMPC: Matlab to Python (a bit outdated).

Also, for those interested in an interface between the two languages and not conversion:

  • pymatlab: communicate from Python by sending data to the MATLAB workspace, operating on them with scripts and pulling back the resulting data.
  • Python-Matlab wormholes: both directions of interaction supported.
  • Python-Matlab bridge: use Matlab from within Python, offers matlab_magic for iPython, to execute normal matlab code from within ipython.
  • PyMat: Control Matlab session from Python.
  • pymat2: continuation of the seemingly abandoned PyMat.
  • mlabwrap, mlabwrap-purepy: make Matlab look like Python library (based on PyMat).
  • oct2py: run GNU Octave commands from within Python.
  • pymex: Embeds the Python Interpreter in Matlab, also on File Exchange.
  • matpy: Access MATLAB in various ways: create variables, access .mat files, direct interface to MATLAB engine (requires MATLAB be installed).
  • MatPy: Python package for numerical linear algebra and plotting with a MatLab-like interface.

Btw might be helpful to look here for other migration tips:

On a different note, though I'm not a fortran fan at all, for people who might find it useful there is:

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

How to get UTF-8 working in Java webapps?

Nice detailed answer. just wanted to add one more thing which will definitely help others to see the UTF-8 encoding on URLs in action .

Follow the steps below to enable UTF-8 encoding on URLs in firefox.

  1. type "about:config" in the address bar.

  2. Use the filter input type to search for "network.standard-url.encode-query-utf8" property.

  3. the above property will be false by default, turn that to TRUE.
  4. restart the browser.

UTF-8 encoding on URLs works by default in IE6/7/8 and chrome.

MySQL select with CONCAT condition

The aliases you give are for the output of the query - they are not available within the query itself.

You can either repeat the expression:

SELECT neededfield, CONCAT(firstname, ' ', lastname) as firstlast 
FROM users
WHERE CONCAT(firstname, ' ', lastname) = "Bob Michael Jones"

or wrap the query

SELECT * FROM (
  SELECT neededfield, CONCAT(firstname, ' ', lastname) as firstlast 
  FROM users) base 
WHERE firstLast = "Bob Michael Jones"

Python try-else

Try-except-else is great for combining the EAFP pattern with duck-typing:

try:
  cs = x.cleanupSet
except AttributeError:
  pass
else:
  for v in cs:
    v.cleanup()

You might thing this naïve code is fine:

try:
  for v in x.cleanupSet:
    v.clenaup()
except AttributeError:
  pass

This is a great way of accidentally hiding severe bugs in your code. I typo-ed cleanup there, but the AttributeError that would let me know is being swallowed. Worse, what if I'd written it correctly, but the cleanup method was occasionally being passed a user type that had a misnamed attribute, causing it to silently fail half-way through and leave a file unclosed? Good luck debugging that one.

How do you get the magnitude of a vector in Numpy?

The function you're after is numpy.linalg.norm. (I reckon it should be in base numpy as a property of an array -- say x.norm() -- but oh well).

import numpy as np
x = np.array([1,2,3,4,5])
np.linalg.norm(x)

You can also feed in an optional ord for the nth order norm you want. Say you wanted the 1-norm:

np.linalg.norm(x,ord=1)

And so on.

How to set auto increment primary key in PostgreSQL?

Try this command:

ALTER TABLE your_table ADD COLUMN key_column BIGSERIAL PRIMARY KEY;

Try it with the same DB-user as the one you have created the table.

How to enable multidexing with the new Android Multidex support library

Add to AndroidManifest.xml:

android:name="android.support.multidex.MultiDexApplication" 

OR

MultiDex.install(this);

in your custom Application's attachBaseContext method

or your custom Application extend MultiDexApplication

add multiDexEnabled = true in your build.gradle

defaultConfig {
    multiDexEnabled true
}

dependencies {
    compile 'com.android.support:multidex:1.0.0'
    }
}

Char array to hex string C++

You could use std::hex

Eg.

std::cout << std::hex << packet;

Convert line endings

Doing this with POSIX is tricky:

  • POSIX Sed does not support \r or \15. Even if it did, the in place option -i is not POSIX

  • POSIX Awk does support \r and \15, however the -i inplace option is not POSIX

  • d2u and dos2unix are not POSIX utilities, but ex is

  • POSIX ex does not support \r, \15, \n or \12

To remove carriage returns:

awk 'BEGIN{RS="^$";ORS="";getline;gsub("\r","");print>ARGV[1]}' file

To add carriage returns:

awk 'BEGIN{RS="^$";ORS="";getline;gsub("\n","\r&");print>ARGV[1]}' file

How to sign in kubernetes dashboard?

All the previous answers are good to me. But a straight forward answer on my side would come from https://github.com/kubernetes/dashboard/wiki/Creating-sample-user#bearer-token. Just use kubectl -n kube-system describe secret $(kubectl -n kube-system get secret | grep admin-user | awk '{print $1}'). You will have many values for some keys (Name, Namespace, Labels, ..., token). The most important is the token that corresponds to your name. copy that token and paste it in the token box. Hope this helps.

Bash script plugin for Eclipse?

There exists now a dedicated bash script plugin called "Bash editor". It's available at eclipse market place:

Bash editor log

You can find it at https://marketplace.eclipse.org/content/bash-editor or by marketplace client when searching for "bash".

The plugin does also provide a debugger. Inisde official Bash Editor YouTube playlist you can find some tutorials about usage etc.

PS: I am the author of the mentioned plugin.

How to use css style in php

You can also embed it in the php. E.g.

<?php
    echo "<p style='color:blue; border:2px red solid;'>CSS Styling in php</p>";
?>

hope this help for anyone in the future.

Smart cast to 'Type' is impossible, because 'variable' is a mutable property that could have been changed by this time

1) Also you can use lateinit If you sure do your initialization later on onCreate() or elsewhere.

Use this

lateinit var left: Node

Instead of this

var left: Node? = null

2) And there is other way that use !! end of variable when you use it like this

queue.add(left!!) // add !!

How to echo print statements while executing a sql script

I don't know if this helps:

suppose you want to run a sql script (test.sql) from the command line:

mysql < test.sql

and the contents of test.sql is something like:

SELECT * FROM information_schema.SCHEMATA;
\! echo "I like to party...";

The console will show something like:

CATALOG_NAME    SCHEMA_NAME            DEFAULT_CHARACTER_SET_NAME      
         def    information_schema     utf8
         def    mysql                  utf8
         def    performance_schema     utf8
         def    sys                    utf8
I like to party...

So you can execute terminal commands inside an sql statement by just using \!, provided the script is run via a command line.

\! #terminal_commands

Truncate to three decimals in Python

You can also use:

import math

nValeur = format(float(input('Quelle valeur ?    ')), '.3f')

In Python 3.6 it would work.

Execute SQL script to create tables and rows

If you have password for your dB then

mysql -u <username> -p <DBName> < yourfile.sql

How do you add an array to another array in Ruby and not end up with a multi-dimensional result?

Here are two ways, notice in this case that the first way assigns a new array ( translates to somearray = somearray + anotherarray )

somearray = ["some", "thing"]

anotherarray = ["another", "thing"]

somearray += anotherarray # => ["some", "thing", "another", "thing"]

somearray = ["some", "thing"]
somearray.concat anotherarray # => ["some", "thing", "another", "thing"]

Correct way to load a Nib for a UIView subclass

In Swift:

For example, name of your custom class is InfoView

At first, you create files InfoView.xib and InfoView.swiftlike this:

import Foundation
import UIKit

class InfoView: UIView {
    class func instanceFromNib() -> UIView {
    return UINib(nibName: "InfoView", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as! UIView
}

Then set File's Owner to UIViewController like this:

enter image description here

Rename your View to InfoView:

enter image description here

Right-click to File's Owner and connect your view field with your InfoView:

enter image description here

Make sure that class name is InfoView:

enter image description here

And after this you can add the action to button in your custom class without any problem:

enter image description here

And usage of this custom class in your MainViewController:

func someMethod() {
    var v = InfoView.instanceFromNib()
    v.frame = self.view.bounds
    self.view.addSubview(v)
}

How do I enumerate through a JObject?

For people like me, linq addicts, and based on svick's answer, here a linq approach:

using System.Linq;
//...
//make it linq iterable. 
var obj_linq = Response.Cast<KeyValuePair<string, JToken>>();

Now you can make linq expressions like:

JToken x = obj_linq
          .Where( d => d.Key == "my_key")
          .Select(v => v)
          .FirstOrDefault()
          .Value;
string y = ((JValue)x).Value;

Or just:

var y = obj_linq
       .Where(d => d.Key == "my_key")
       .Select(v => ((JValue)v.Value).Value)
       .FirstOrDefault();

Or this one to iterate over all data:

obj_linq.ToList().ForEach( x => { do stuff } ); 

javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25

It is very clear from your exception that it is trying to connect to localhost and not to 10.101.3.229

exception snippet : Could not connect to SMTP host: localhost, port: 25;

1.) Please check if there are any null check which is setting localhost as default value

2.) After restarting, if it is working fine, then it means that only at first-run, the proper value is been taken from Properties and from next run the value is set to default. So keep the property-object as a singleton one and use it all-over your project

Javascript (+) sign concatenates instead of giving sum of variables

The reason you get that is the order of precendence of the operators, and the fact that + is used to both concatenate strings as well as perform numeric addition.

In your case, the concatenation of "question-" and i is happening first giving the string "question=1". Then another string concatenation with "1" giving "question-11".

You just simply need to give the interpreter a hint as to what order of prec endence you want.

divID = "question-" + (i+1);

How to check a not-defined variable in JavaScript

The only way to truly test if a variable is undefined is to do the following. Remember, undefined is an object in JavaScript.

if (typeof someVar === 'undefined') {
  // Your variable is undefined
}

Some of the other solutions in this thread will lead you to believe a variable is undefined even though it has been defined (with a value of NULL or 0, for instance).

CSS3 Continuous Rotate Animation (Just like a loading sundial)

Your issue here is that you've supplied a -webkit-TRANSITION-timing-function when you want a -webkit-ANIMATION-timing-function. Your values of 0 to 360 will work properly.

How to log a method's execution time exactly in milliseconds?

I use very minimal, one page class implementation inspired by code from this blog post:

#import <mach/mach_time.h>

@interface DBGStopwatch : NSObject

+ (void)start:(NSString *)name;
+ (void)stop:(NSString *)name;

@end

@implementation DBGStopwatch

+ (NSMutableDictionary *)watches {
    static NSMutableDictionary *Watches = nil;
    static dispatch_once_t OnceToken;
    dispatch_once(&OnceToken, ^{
        Watches = @{}.mutableCopy;
    });
    return Watches;
}

+ (double)secondsFromMachTime:(uint64_t)time {
    mach_timebase_info_data_t timebase;
    mach_timebase_info(&timebase);
    return (double)time * (double)timebase.numer /
        (double)timebase.denom / 1e9;
}

+ (void)start:(NSString *)name {
    uint64_t begin = mach_absolute_time();
    self.watches[name] = @(begin);
}

+ (void)stop:(NSString *)name {
    uint64_t end = mach_absolute_time();
    uint64_t begin = [self.watches[name] unsignedLongLongValue];
    DDLogInfo(@"Time taken for %@ %g s",
              name, [self secondsFromMachTime:(end - begin)]);
    [self.watches removeObjectForKey:name];
}

@end

The usage of it is very simple:

  • just call [DBGStopwatch start:@"slow-operation"]; at the beginning
  • and then [DBGStopwatch stop:@"slow-operation"]; after the finish, to get the time

How to simulate a real mouse click using java?

it works in Linux. perhaps there are system settings which can be changed in Windows to allow it.

jcomeau@aspire:/tmp$ cat test.java; javac test.java; java test
import java.awt.event.*;
import java.awt.Robot;
public class test {
 public static void main(String args[]) {
  Robot bot = null;
  try {
   bot = new Robot();
  } catch (Exception failed) {
   System.err.println("Failed instantiating Robot: " + failed);
  }
  int mask = InputEvent.BUTTON1_DOWN_MASK;
  bot.mouseMove(100, 100);
  bot.mousePress(mask);
  bot.mouseRelease(mask);
 }
}

I'm assuming InputEvent.MOUSE_BUTTON1_DOWN in your version of Java is the same thing as InputEvent.BUTTON1_DOWN_MASK in mine; I'm using 1.6.

otherwise, that could be your problem. I can tell it worked because my Chrome browser was open to http://docs.oracle.com/javase/7/docs/api/java/awt/Robot.html when I ran the program, and it changed to Debian.org because that was the link in the bookmarks bar at (100, 100).

[added later after cogitating on it today] it might be necessary to trick the listening program by simulating a smoother mouse movement. see the answer here: How to move a mouse smoothly throughout the screen by using java?

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

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

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

Good luck!

How to import an Excel file into SQL Server?

You can also use OPENROWSET to import excel file in sql server.

SELECT * INTO Your_Table FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
                        'Excel 12.0;Database=C:\temp\MySpreadsheet.xlsx',
                        'SELECT * FROM [Data$]')

How to update Android Studio automatically?

If you go to help>>check for updates it will tell you if there's an update.

You don't have to change from the stable channel. If you aren't offered an update and restart button, kindly close the window and try again. After about 4 or 5 checks like this, it will eventually show you update and restart button.

Why? because google.

Is <div style="width: ;height: ;background: "> CSS?

For example :

_x000D_
_x000D_
<div style="height:100px; width:100px; background:#000000"></div>
_x000D_
_x000D_
_x000D_

here.

you give css to div of height and width having 100px and background as black.

PS : try to avoid inline-css you can make external CSS and import in your html file.

you can refer here for CSS

hope this helps.

Passing multiple argument through CommandArgument of Button in Asp.net

My approach is using the attributes collection to add HTML data- attributes from code behind. This is more inline with jquery and client side scripting.

// This would likely be done with findControl in your grid OnItemCreated handler
LinkButton targetBtn = new LinkButton();


// Add attributes
targetBtn.Attributes.Add("data-{your data name here}", value.ToString() );
targetBtn.Attributes.Add("data-{your data name 2 here}", value2.ToString() );

Then retrieve the values through the attribute collection

string val = targetBtn.Attributes["data-{your data name here}"].ToString();

Selenium 2.53 not working on Firefox 47

Firefox 47.0 stopped working with Webdriver.

Easiest solution is to switch to Firefox 47.0.1 and Webdriver 2.53.1. This combination again works. In fact, restoring Webdriver compatibility was the main reason behind the 47.0.1 release, according to https://www.mozilla.org/en-US/firefox/47.0.1/releasenotes/.

Maven home (M2_HOME) not being picked up by IntelliJ IDEA

Got to this answer ? probably the answers above are to long ...

just type in :

echo "setenv M2_HOME $M2_HOME" | sudo tee -a /etc/launchd.conf

and restart your mac (thats it!)

restarting is annoying ? just use the command :

grep -E "^setenv" /etc/launchd.conf | xargs -t -L 1 launchctl

and restart IntelliJ IDEA

How can I use threading in Python?

import threading
import requests

def send():

  r = requests.get('https://www.stackoverlow.com')

thread = []
t = threading.Thread(target=send())
thread.append(t)
t.start()

dyld: Library not loaded: /usr/local/lib/libpng16.16.dylib with anything php related

I had this error that wasn't solved by brew update && brew upgrade. For some reason I needed to install it from scratch:

$ brew install libpng

My prerelease app has been "processing" for over a week in iTunes Connect, what gives?

Same issue for me... Upload app archives from Xcode (7.3.1). Connect to iTunesCo with both Chrome and Safari...

  • 20 august: v0.1.3 | b0.0.1 -> upload done -> never appeared on iTunesCo
  • 23 august: v0.1.4 | b0.0.1 -> upload done -> processing on iTunesCo
  • 23 august: v0.1.4 | b0.0.2 -> upload done -> processing on iTunesCo
  • 23 august: v0.1.4 | b0.0.3 -> upload done -> never appeared on iTunesCo
  • 24 august: v0.1.5 | b0.0.1 -> upload done -> available 5min later

The way it works has no logic... So I agree with @teapen:

...don't wait for Apple, just increase build and upload again...

Batch script to delete files

There's multiple ways of doing things in batch, so if escaping with a double percent %% isn't working for you, then you could try something like this:

set olddir=%CD%
cd /d "path of folder"
del "file name/ or *.txt etc..."
cd /d "%olddir%"

How this works:

set olddir=%CD% sets the variable "olddir" or any other variable name you like to the directory your batch file was launched from.

cd /d "path of folder" changes the current directory the batch will be looking at. keep the quotations and change path of folder to which ever path you aiming for.

del "file name/ or *.txt etc..." will delete the file in the current directory your batch is looking at, just don't add a directory path before the file name and just have the full file name or, to delete multiple files with the same extension with *.txt or whatever extension you need.

cd /d "%olddir%" takes the variable saved with your old path and goes back to the directory you started the batch with, its not important if you don't want the batch going back to its previous directory path, and like stated before the variable name can be changed to whatever you wish by changing the set olddir=%CD% line.

How to set -source 1.7 in Android Studio and Gradle

At current, Android doesn't support Java 7, only Java 6. New features in Java 7 such as the diamond syntax are therefore not currently supported. Finding sources to support this isn't easy, but I could find that the Dalvic engine is built upon a subset of Apache Harmony which only ever supported Java up to version 6. And if you check the system requirements for developing Android apps it also states that at least JDK 6 is needed (though this of course isn't real proof, just an indication). And this says pretty much the same as I have. If I find anything more substancial, I'll add it.

Edit: It seems Java 7 support has been added since I originally wrote this answer; check the answer by Sergii Pechenizkyi.

Div side by side without float

You can also use CSS3 flexbox layout, which is well supported nowadays.

.container {
    display: flex;
    flex-flow: row nowrap;
    justify-content: space-between;
    background:black;
    height:400px;
    width:450px;
}

.left {
    flex: 0 0 300px;
    background:blue;
    height:200px;
}

.right {
    flex: 0 1 100px;
    background:green;
    height:300px;
}

See Example (with legacy styles for maximum compatiblity) & Learn more about flexbox.

Vim: insert the same characters across multiple lines

  1. Select the lines you want to modify using CtrlV.
  2. Press:

    • I: Insert before what's selected.
    • A: Append after what's selected.
    • c: Replace what's selected.
  3. Type the new text.

  4. Press Esc to apply the changes to all selected lines.

Oracle "SQL Error: Missing IN or OUT parameter at index:: 1"

I got the same error and found the cause to be a wrong or missing foreign key. (Using JDBC)

How can I INSERT data into two tables simultaneously in SQL Server?

Create table #temp1
(
 id int identity(1,1),
 name varchar(50),
 profession varchar(50)
)

Create table #temp2
(
 id int identity(1,1),
 name varchar(50),
 profession varchar(50)
)

-----main query ------

insert into #temp1(name,profession)

output inserted.name,inserted.profession into #temp2

select 'Shekhar','IT'

Import SQL dump into PostgreSQL database

Postgresql12

from sql file: pg_restore -d database < file.sql

from custom format file: pg_restore -Fc database < file.dump

C++ alignment when printing cout <<

See also: Which C I/O library should be used in C++ code?

struct Item
{
   std::string     artist;
   std::string     c;
   integer         price;  // in cents (as floating point is not acurate)
   std::string     Genre;
   integer         disc;
   integer         sale;
   integer         tax;
};

std::cout << "Sales Report for September 15, 2010\n"
          << "Artist  Title   Price   Genre   Disc    Sale    Tax Cash\n";
FOREACH(Item loop,data)
{
    fprintf(stdout,"%8s%8s%8.2f%7s%1s%8.2f%8.2f\n",
          , loop.artist
          , loop.title
          , loop.price / 100.0
          , loop.Genre
          , loop.disc , "%"
          , loop.sale / 100.0
          , loop.tax / 100.0);

   // or

    std::cout << std::setw(8) << loop.artist
              << std::setw(8) << loop.title
              << std::setw(8) << fixed << setprecision(2) << loop.price / 100.0
              << std::setw(8) << loop.Genre
              << std::setw(7) << loop.disc << std::setw(1) << "%"
              << std::setw(8) << fixed << setprecision(2) << loop.sale / 100.0
              << std::setw(8) << fixed << setprecision(2) << loop.tax / 100.0
              << "\n";

    // or

    std::cout << boost::format("%8s%8s%8.2f%7s%1s%8.2f%8.2f\n")
              % loop.artist
              % loop.title
              % loop.price / 100.0
              % loop.Genre
              % loop.disc % "%"
              % loop.sale / 100.0
              % loop.tax / 100.0;
}

Firebase: how to generate a unique numeric ID for key?

As explained above, you can use the Firebase default push id.

If you want something numeric you can do something based on the timestamp to avoid collisions

f.e. something based on date,hour,second,ms, and some random int at the end

01612061353136799031

Which translates to:

016-12-06 13:53:13:679 9031

It all depends on the precision you need (social security numbers do the same with some random characters at the end of the date). Like how many transactions will be expected during the day, hour or second. You may want to lower precision to favor ease of typing.

You can also do a transaction that increments the number id, and on success you will have a unique consecutive number for that user. These can be done on the client or server side.

(https://firebase.google.com/docs/database/android/read-and-write)

Generate PDF from Swagger API documentation

I created a web site https://www.swdoc.org/ that specifically addresses the problem. So it automates swagger.json -> Asciidoc, Asciidoc -> pdf transformation as suggested in the answers. Benefit of this is that you dont need to go through the installation procedures. It accepts a spec document in form of url or just a raw json. Project is written in C# and its page is https://github.com/Irdis/SwDoc

EDIT

It might be a good idea to validate your json specs here: http://editor.swagger.io/ if you are having any problems with SwDoc, like the pdf being generated incomplete.

How to disable a link using only CSS?

I searched over internet and found no better than this. Basically to disable button click functionality, just add CSS style using jQuery like so:

$("#myLink").css({ 'pointer-events': 'none' });

Then to enable it again do this

$("#myLink").css({ 'pointer-events': '' });

Checked on Firefox and IE 11, it worked.

ngFor with index as value in attribute

Try this

<div *ngFor="let piece of allPieces; let i=index">
{{i}} // this will give index
</div>

How to declare a Fixed length Array in TypeScript

The javascript array has a constructor that accepts the length of the array:

let arr = new Array<number>(3);
console.log(arr); // [undefined × 3]

However, this is just the initial size, there's no restriction on changing that:

arr.push(5);
console.log(arr); // [undefined × 3, 5]

Typescript has tuple types which let you define an array with a specific length and types:

let arr: [number, number, number];

arr = [1, 2, 3]; // ok
arr = [1, 2]; // Type '[number, number]' is not assignable to type '[number, number, number]'
arr = [1, 2, "3"]; // Type '[number, number, string]' is not assignable to type '[number, number, number]'

MySQL: Cloning a MySQL database on the same MySql instance

You can do something like the following:

mysqldump -u[username] -p[password] database_name_for_clone 
 | mysql -u[username] -p[password] new_database_name

Clear image on picturebox

if (pictureBox1.Image != null)
{
    pictureBox1.Image.Dispose();
    pictureBox1.Image = null;
}

How do I find the absolute position of an element using jQuery?

.offset() will return the offset position of an element as a simple object, eg:

var position = $(element).offset(); // position = { left: 42, top: 567 }

You can use this return value to position other elements at the same spot:

$(anotherElement).css(position)

casting Object array to Integer array error

When casting is done in Java, Java compiler as well as Java run-time check whether the casting is possible or not and throws errors in case not.

When casting of Object types is involved, the instanceof test should pass in order for the assignment to go through. In your example it results
Object[] a = new Object[1]; boolean isIntegerArr = a instanceof Integer[]
If you do a sysout of the above line, it would return false;
So trying an instance of check before casting would help. So, to fix the error, you can either add 'instanceof' check
OR
use following line of code:
(Arrays.asList(a)).toArray(c);

Please do note that the above code would fail, if the Object array contains any entry that is other than Integer.

Pull new updates from original GitHub repository into forked GitHub repository

If there is nothing to lose you could also just delete your fork just go to settings... go to danger zone section below and click delete repository. It will ask you to input the repository name and your password after. After that you just fork the original again.

How to add multiple classes to a ReactJS Component?


Create a function like this

function cssClass(...c) {
  return c.join(" ")
}

Call it when needed.

<div className={cssClass("head",Style.element,"black")}><div>

How do I install Python 3 on an AWS EC2 instance?

EC2 (on the Amazon Linux AMI) currently supports python3.4 and python3.5.

sudo yum install python35
sudo yum install python35-pip

How do check if a PHP session is empty?

You could use the count() function to see how many entries there are in the $_SESSION array. This is not good practice. You should instead set the id of the user (or something similar) to check wheter the session was initialised or not.

if( !isset($_SESSION['uid']) )
    die( "Login required." );

(Assuming you want to check if someone is logged in)

Setting size for icon in CSS

The better way is using 'background-size'.

.pnx-msg-icon .pnx-icon-msg-warning{
background-image: url("../pics/edit.png");
background-repeat: no-repeat;
background-size: 10px;
width: 10px;
height: 10px;
cursor: pointer;
}

even if your icon dimensions is bigger than 10px it will be 10px.