Programs & Examples On #Concrete syntax tree

How to quickly and conveniently create a one element arraylist

Collections.singletonList(object)

the list created by this method is immutable.

Iterating Over Dictionary Key Values Corresponding to List in Python

You have several options for iterating over a dictionary.

If you iterate over the dictionary itself (for team in league), you will be iterating over the keys of the dictionary. When looping with a for loop, the behavior will be the same whether you loop over the dict (league) itself, or league.keys():

for team in league.keys():
    runs_scored, runs_allowed = map(float, league[team])

You can also iterate over both the keys and the values at once by iterating over league.items():

for team, runs in league.items():
    runs_scored, runs_allowed = map(float, runs)

You can even perform your tuple unpacking while iterating:

for team, (runs_scored, runs_allowed) in league.items():
    runs_scored = float(runs_scored)
    runs_allowed = float(runs_allowed)

What does Statement.setFetchSize(nSize) method really do in SQL Server JDBC driver?

In JDBC, the setFetchSize(int) method is very important to performance and memory-management within the JVM as it controls the number of network calls from the JVM to the database and correspondingly the amount of RAM used for ResultSet processing.

Inherently if setFetchSize(10) is being called and the driver is ignoring it, there are probably only two options:

  1. Try a different JDBC driver that will honor the fetch-size hint.
  2. Look at driver-specific properties on the Connection (URL and/or property map when creating the Connection instance).

The RESULT-SET is the number of rows marshalled on the DB in response to the query. The ROW-SET is the chunk of rows that are fetched out of the RESULT-SET per call from the JVM to the DB. The number of these calls and resulting RAM required for processing is dependent on the fetch-size setting.

So if the RESULT-SET has 100 rows and the fetch-size is 10, there will be 10 network calls to retrieve all of the data, using roughly 10*{row-content-size} RAM at any given time.

The default fetch-size is 10, which is rather small. In the case posted, it would appear the driver is ignoring the fetch-size setting, retrieving all data in one call (large RAM requirement, optimum minimal network calls).

What happens underneath ResultSet.next() is that it doesn't actually fetch one row at a time from the RESULT-SET. It fetches that from the (local) ROW-SET and fetches the next ROW-SET (invisibly) from the server as it becomes exhausted on the local client.

All of this depends on the driver as the setting is just a 'hint' but in practice I have found this is how it works for many drivers and databases (verified in many versions of Oracle, DB2 and MySQL).

Changing selection in a select with the Chosen plugin

My answer is late, but i want to add some information that is missed in all above answers.

1) If you want to select single value in chosen select.

$('#select-id').val("22").trigger('chosen:updated');

2) If you are using multiple chosen select, then may you need to set multiple values at single time.

$('#documents').val(["22", "25", "27"]).trigger('chosen:updated');

Information gathered from following links:
1) Chosen Docs
2) Chosen Github Discussion

selecting an entire row based on a variable excel vba

I just tested the code at the bottom and it prints 16384 twice (I'm on Excel 2010) and the first row gets selected. Your problem seems to be somewhere else.

Have you tried to get rid of the selects:

Sheets("BOM").Rows(copyFromRow).Copy
With Sheets("Proposal")
    .Paste Destination:=.Rows(copyToRow)
    copyToRow = copyToRow + 1
    Application.CutCopyMode = False
    .Rows(copyToRow).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
End With

Test code to get convinced that the problem does not seem to be what you think it is.

Sub test()

  Dim r
  Dim i As Long

  i = 1

  r = Rows(i & ":" & i)
  Debug.Print UBound(r, 2)
  r = Rows(i)
  Debug.Print UBound(r, 2)
  Rows(i).Select

End Sub

Differences between JDK and Java SDK

From this wikipedia entry:

The JDK is a subset of what is loosely defined as a software development kit (SDK) in the general sense. In the descriptions which accompany their recent releases for Java SE, EE, and ME, Sun acknowledge that under their terminology, the JDK forms the subset of the SDK which is responsible for the writing and running of Java programs. The remainder of the SDK is composed of extra software, such as Application Servers, Debuggers, and Documentation.

The "extra software" seems to be Glassfish, MySQL, and NetBeans. This page gives a comparison of the various packages you can get for the Java EE SDK.

How can I make git show a list of the files that are being tracked?

You might want colored output with this.

I use this one-liner for listing the tracked files and directories in the current directory of the current branch:

ls --group-directories-first --color=auto -d $(git ls-tree $(git branch | grep \* | cut -d " " -f2) --name-only)

You might want to add it as an alias:

alias gl='ls --group-directories-first --color=auto -d $(git ls-tree $(git branch | grep \* | cut -d " " -f2) --name-only)'

If you want to recursively list files:

'ls' --color=auto -d $(git ls-tree -rt $(git branch | grep \* | cut -d " " -f2) --name-only)

And an alias:

alias glr="'ls' --color=auto -d \$(git ls-tree -rt \$(git branch | grep \\* | cut -d \" \" -f2) --name-only)"

Disable hover effects on mobile browsers

I take it from your question that your hover effect changes the content of your page. In that case, my advice is to:

  • Add hover effects on touchstart and mouseenter.
  • Remove hover effects on mouseleave, touchmove and click.

Alternatively, you can edit your page that there is no content change.

Background

In order to simulate a mouse, browsers such as Webkit mobile fire the following events if a user touches and releases a finger on touch screen (like iPad) (source: Touch And Mouse on html5rocks.com):

  1. touchstart
  2. touchmove
  3. touchend
  4. 300ms delay, where the browser makes sure this is a single tap, not a double tap
  5. mouseover
  6. mouseenter
    • Note: If a mouseover, mouseenter or mousemove event changes the page content, the following events are never fired.
  7. mousemove
  8. mousedown
  9. mouseup
  10. click

It does not seem possible to simply tell the webbrowser to skip the mouse events.

What's worse, if a mouseover event changes the page content, the click event is never fired, as explained on Safari Web Content Guide - Handling Events, in particular figure 6.4 in One-Finger Events. What exactly a "content change" is, will depend on browser and version. I've found that for iOS 7.0, a change in background color is not (or no longer?) a content change.

Solution Explained

To recap:

  • Add hover effects on touchstart and mouseenter.
  • Remove hover effects on mouseleave, touchmove and click.

Note that there is no action on touchend!

This clearly works for mouse events: mouseenter and mouseleave (slightly improved versions of mouseover and mouseout) are fired, and add and remove the hover.

If the user actually clicks a link, the hover effect is also removed. This ensure that it is removed if the user presses the back button in the web browser.

This also works for touch events: on touchstart the hover effect is added. It is '''not''' removed on touchend. It is added again on mouseenter, and since this causes no content changes (it was already added), the click event is also fired, and the link is followed without the need for the user to click again!

The 300ms delay that a browser has between a touchstart event and click is actually put in good use because the hover effect will be shown during this short time.

If the user decides to cancel the click, a move of the finger will do so just as normal. Normally, this is a problem since no mouseleave event is fired, and the hover effect remains in place. Thankfully, this can easily be fixed by removing the hover effect on touchmove.

That's it!

Note that it is possible to remove the 300ms delay, for example using the FastClick library, but this is out of scope for this question.

Alternative Solutions

I've found the following problems with the following alternatives:

  • browser detection: Extremely prone to errors. Assumes that a device has either mouse or touch, while a combination of both will become more and more common when touch displays prolifirate.
  • CSS media detection: The only CSS-only solution I'm aware of. Still prone to errors, and still assumes that a device has either mouse or touch, while both are possible.
  • Emulate the click event in touchend: This will incorrectly follow the link, even if the user only wanted to scroll or zoom, without the intention of actually clicking the link.
  • Use a variable to suppress mouse events: This set a variable in touchend that is used as a if-condition in subsequent mouse events to prevents state changes at that point in time. The variable is reset in the click event. See Walter Roman's answer on this page. This is a decent solution if you really don't want a hover effect on touch interfaces. Unfortunately, this does not work if a touchend is fired for another reason and no click event is fired (e.g. the user scrolled or zoomed), and is subsequently trying to following the link with a mouse (i.e on a device with both mouse and touch interface).

Further Reading

How to create a fix size list in python?

This is more of a warning than an answer.
Having seen in the other answers my_list = [None] * 10, I was tempted and set up an array like this speakers = [['','']] * 10 and came to regret it immensely as the resulting list did not behave as I thought it should.
I resorted to:

speakers = []
for i in range(10):
    speakers.append(['',''])

As [['','']] * 10 appears to create an list where subsequent elements are a copy of the first element.
for example:

>>> n=[['','']]*10
>>> n
[['', ''], ['', ''], ['', ''], ['', ''], ['', ''], ['', ''], ['', ''], ['', ''], ['', ''], ['', '']]
>>> n[0][0] = "abc"
>>> n
[['abc', ''], ['abc', ''], ['abc', ''], ['abc', ''], ['abc', ''], ['abc', ''], ['abc', ''], ['abc', ''], ['abc', ''], ['abc', '']]
>>> n[0][1] = "True"
>>> n
[['abc', 'True'], ['abc', 'True'], ['abc', 'True'], ['abc', 'True'], ['abc', 'True'], ['abc', 'True'], ['abc', 'True'], ['abc', 'True'], ['abc', 'True'], ['abc', 'True']]

Whereas with the .append option:

>>> n=[]
>>> for i in range(10):
...  n.append(['',''])
... 
>>> n
[['', ''], ['', ''], ['', ''], ['', ''], ['', ''], ['', ''], ['', ''], ['', ''], ['', ''], ['', '']]
>>> n[0][0] = "abc"
>>> n
[['abc', ''], ['', ''], ['', ''], ['', ''], ['', ''], ['', ''], ['', ''], ['', ''], ['', ''], ['', '']]
>>> n[0][1] = "True"
>>> n
[['abc', 'True'], ['', ''], ['', ''], ['', ''], ['', ''], ['', ''], ['', ''], ['', ''], ['', ''], ['', '']]

I'm sure that the accepted answer by ninjagecko does attempt to mention this, sadly I was too thick to understand.
Wrapping up, take care!

Using SUMIFS with multiple AND OR conditions

You can use SUMIFS like this

=SUM(SUMIFS(Quote_Value,Salesman,"JBloggs",Days_To_Close,"<=90",Quote_Month,{"Oct-13","Nov-13","Dec-13"}))

The SUMIFS function will return an "array" of 3 values (one total each for "Oct-13", "Nov-13" and "Dec-13"), so you need SUM to sum that array and give you the final result.

Be careful with this syntax, you can only have at most two criteria within the formula with "OR" conditions...and if there are two then in one you must separate the criteria with commas, in the other with semi-colons.

If you need more you might use SUMPRODUCT with MATCH, e.g. in your case

=SUMPRODUCT(Quote_Value,(Salesman="JBloggs")*(Days_To_Close<=90)*ISNUMBER(MATCH(Quote_Month,{"Oct-13","Nov-13","Dec-13"},0)))

In that version you can add any number of "OR" criteria using ISNUMBER/MATCH

Dynamically allocating an array of objects

I'd recommend using std::vector: something like

typedef std::vector<int> A;
typedef std::vector<A> AS;

There's nothing wrong with the slight overkill of STL, and you'll be able to spend more time implementing the specific features of your app instead of reinventing the bicycle.

How to give Jenkins more heap space when it´s started as a service under Windows?

If you are using Jenkins templates you could have additional VM settings defined in it and this might conflicting with your system VM settings

example your tempalate may have references such as these

 <mavenOpts>-Xms512m -Xmx1024m -Xss1024k -XX:MaxPermSize=1024m -Dmaven.test.failure.ignore=false</mavenOpts> 

Ensure to align these template entries with the VM setting of your system

How do you parse and process HTML/XML in PHP?

JSON and array from XML in three lines:

$xml = simplexml_load_string($xml_string);
$json = json_encode($xml);
$array = json_decode($json,TRUE);

Ta da!

Python: How exactly can you take a string, split it, reverse it and join it back together again?

I was asked to do so without using any inbuilt function. So I wrote three functions for these tasks. Here is the code-

def string_to_list(string):
'''function takes actual string and put each word of string in a list'''
list_ = []
x = 0 #Here x tracks the starting of word while y look after the end of word.
for y in range(len(string)):
    if string[y]==" ":
        list_.append(string[x:y])
        x = y+1
    elif y==len(string)-1:
        list_.append(string[x:y+1])
return list_

def list_to_reverse(list_):
'''Function takes the list of words and reverses that list'''
reversed_list = []
for element in list_[::-1]:
    reversed_list.append(element)
return reversed_list

def list_to_string(list_):
'''This function takes the list and put all the elements of the list to a string with 
space as a separator'''
final_string = str()
for element in list_:
    final_string += str(element) + " "
return final_string

#Output
text = "I love India"
list_ = string_to_list(text)
reverse_list = list_to_reverse(list_)
final_string = list_to_string(reverse_list)
print("Input is - {}; Output is - {}".format(text, final_string))
#op= Input is - I love India; Output is - India love I 

Please remember, This is one of a simpler solution. This can be optimized so try that. Thank you!

How do I check the difference, in seconds, between two dates?

We have function total_seconds() with Python 2.7 Please see below code for python 2.6

import datetime
import time  

def diffdates(d1, d2):
    #Date format: %Y-%m-%d %H:%M:%S
    return (time.mktime(time.strptime(d2,"%Y-%m-%d %H:%M:%S")) -
               time.mktime(time.strptime(d1, "%Y-%m-%d %H:%M:%S")))

d1 = datetime.now()
d2 = datetime.now() + timedelta(days=1)
diff = diffdates(d1, d2)

Sticky Header after scrolling down

I used jQuery .scroll() function to track the event of the toolbar scroll value using scrollTop. I then used a conditional to determine if it was greater than the value on what I wanted to replace. In the below example it was "Results". If the value was true then the results-label added a class 'fixedSimilarLabel' and the new styles were then taken into account.

    $('.toolbar').scroll(function (e) {
//console.info(e.currentTarget.scrollTop);
    if (e.currentTarget.scrollTop >= 130) {
        $('.results-label').addClass('fixedSimilarLabel');
    }
    else {      
        $('.results-label').removeClass('fixedSimilarLabel');
    }
});

http://codepen.io/franklynroth/pen/pjEzeK

How to detect DIV's dimension changed?

_x000D_
_x000D_
var div = document.getElementById('div');_x000D_
div.addEventListener('resize', (event) => console.log(event.detail));_x000D_
_x000D_
function checkResize (mutations) {_x000D_
    var el = mutations[0].target;_x000D_
    var w = el.clientWidth;_x000D_
    var h = el.clientHeight;_x000D_
    _x000D_
    var isChange = mutations_x000D_
      .map((m) => m.oldValue + '')_x000D_
      .some((prev) => prev.indexOf('width: ' + w + 'px') == -1 || prev.indexOf('height: ' + h + 'px') == -1);_x000D_
_x000D_
    if (!isChange)_x000D_
      return;_x000D_
_x000D_
    var event = new CustomEvent('resize', {detail: {width: w, height: h}});_x000D_
    el.dispatchEvent(event);_x000D_
}_x000D_
_x000D_
var observer = new MutationObserver(checkResize); _x000D_
observer.observe(div, {attributes: true, attributeOldValue: true, attributeFilter: ['style']});
_x000D_
#div {width: 100px; border: 1px solid #bbb; resize: both; overflow: hidden;}
_x000D_
<div id = "div">DIV</div>
_x000D_
_x000D_
_x000D_

Getting net::ERR_UNKNOWN_URL_SCHEME while calling telephone number from HTML page in Android

I had this issue occurring with mailto: and tel: links inside an iframe (in Chrome, not a webview). Clicking the links would show the grey "page not found" page and inspecting the page showed it had a ERR_UNKNOWN_URL_SCHEME error.

Adding target="_blank", as suggested by this discussion of the issue fixed the problem for me.

Store output of sed into a variable

line=`sed -n 2p myfile`
echo $line

How to merge two PDF files into one in Java?

A quick Google search returned this bug: "Bad file descriptor while saving a document w. imported PDFs".

It looks like you need to keep the PDFs to be merged open, until after you have saved and closed the combined PDF.

SQL TRUNCATE DATABASE ? How to TRUNCATE ALL TABLES

You can also use this stored procedure if you only want to truncate all tables in a specific schema:

-- =============================================
-- Author:      Ben de Ridder
-- Create date: 20160513
-- Description: Truncate all tables in schema
-- =============================================
CREATE PROCEDURE TruncateAllTablesInSchema
    @schema nvarchar(50)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    DECLARE @table nVARCHAR(255)

    DECLARE db_cursor CURSOR FOR 
        select t.name
          from sys.tables t inner join
               sys.schemas s on 
                    t.schema_id=s.schema_id
         where s.name=@schema
         order by 1

    OPEN db_cursor   

    FETCH NEXT FROM db_cursor INTO @table   

    WHILE @@FETCH_STATUS = 0   
    BEGIN   
           declare @sql nvarchar(1000)

           set @sql = 'truncate table [' + @schema + '].[' + @table + ']'

           exec sp_sqlexec @sql

           FETCH NEXT FROM db_cursor INTO @table   
    END   

    CLOSE db_cursor   
    DEALLOCATE db_cursor 

END
GO

C# Double - ToString() formatting with two decimal places but no rounding

Following can be used for display only which uses the property of String ..

double value = 123.456789;
String.Format("{0:0.00}", value);

Check if current date is between two dates Oracle SQL

SELECT to_char(emp_login_date,'DD-MON-YYYY HH24:MI:SS'),A.* 
FROM emp_log A
WHERE emp_login_date BETWEEN to_date(to_char('21-MAY-2015 11:50:14'),'DD-MON-YYYY HH24:MI:SS')
AND
to_date(to_char('22-MAY-2015 17:56:52'),'DD-MON-YYYY HH24:MI:SS') 
ORDER BY emp_login_date

How to layout multiple panels on a jFrame? (java)

You'll want to use a number of layout managers to help you achieve the basic results you want.

Check out A Visual Guide to Layout Managers for a comparision.

You could use a GridBagLayout but that's one of the most complex (and powerful) layout managers available in the JDK.

You could use a series of compound layout managers instead.

I'd place the graphics component and text area on a single JPanel, using a BorderLayout, with the graphics component in the CENTER and the text area in the SOUTH position.

I'd place the text field and button on a separate JPanel using a GridBagLayout (because it's the simplest I can think of to achieve the over result you want)

I'd place these two panels onto a third, master, panel, using a BorderLayout, with the first panel in the CENTER and the second at the SOUTH position.

But that's me

What are the different NameID format used for?

It is just a hint for the Service Provider on what to expect from the NameID returned by the Identity Provider. It can be:

  1. unspecified
  2. emailAddress – e.g. [email protected]
  3. X509SubjectName – e.g. CN=john,O=Company Ltd.,C=US
  4. WindowsDomainQualifiedName – e.g. CompanyDomain\John
  5. kerberos– e.g. john@realm
  6. entity – this one in used to identify entities that provide SAML-based services and looks like a URI
  7. persistent – this is an opaque service-specific identifier which must include a pseudo-random value and must not be traceable to the actual user, so this is a privacy feature.
  8. transient – opaque identifier which should be treated as temporary.

Validate SSL certificates with Python

M2Crypto can do the validation. You can also use M2Crypto with Twisted if you like. The Chandler desktop client uses Twisted for networking and M2Crypto for SSL, including certificate validation.

Based on Glyphs comment it seems like M2Crypto does better certificate verification by default than what you can do with pyOpenSSL currently, because M2Crypto checks subjectAltName field too.

I've also blogged on how to get the certificates Mozilla Firefox ships with in Python and usable with Python SSL solutions.

foreach for JSON array , syntax

Sure, you can use JS's foreach.

for (var k in result) {
  something(result[k])
}

Removing whitespace between HTML elements when using line breaks

Instead of using to remove a CR/LF between elements, I use the SGML processing instruction because minifiers often remove the comments, but not the XML PI. When the PHP PI is processed by PHP, it has the additional benefit of removing the PI completely along with the CR/LF in between, thus saving at least 8 bytes. You can use any arbitrary valid instruction name such as and save two bytes in X(HT)ML.

transparent navigation bar ios

Add this in your did load

self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.0)
//adjust alpha according to your need 0 is transparent 1 is solid

Error when checking model input: expected convolution2d_input_1 to have 4 dimensions, but got array with shape (32, 32, 3)

Got the same problem, non of the answers worked for me. After a lot of debugging I found out that the size of one image was smaller than 32. This leads to a broken array with wrong dimensions and the above mentioned error.

To solve the problem, make sure that all images have the correct dimensions.

MySql ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

Just to confirm: You are sure you are running MySQL 5.7, and not MySQL 5.6 or earlier version. And the plugin column contains "mysql_native_password". (Before MySQL 5.7, the password hash was stored in a column named password. Starting in MySQL 5.7, the password column is removed, and the password has is stored in the authentication_string column.) And you've also verified the contents of authentication string matches the return from PASSWORD('mysecret'). Also, is there a reason we are using DML against the mysql.user table instead of using the SET PASSWORD FOR syntax? – spencer7593

So Basically Just make sure that the Plugin Column contains "mysql_native_password".

Not my work but I read comments and noticed that this was stated as the answer but was not posted as a possible answer yet.

NodeJS - What does "socket hang up" actually mean?

I was using nano, and it took me a long time to figure out this error. My problem was I was using the wrong port. I had port 5948 instead of 5984.

var nano = require('nano')('http://localhost:5984');
var db = nano.use('address');
var app = express();

Returning a value from thread?

I came across this thread when also trying to obtain the return value of a method that gets executed within a Thread. I thought I would post my solution that works.

This solution uses an class to store both the method to be executed (indirectly) and stores the returning value. The class can be used for any function and any return type. You just instantiate the object using the return value type and then pass the function to call via a lambda (or delegate).


C# 3.0 Implementation


public class ThreadedMethod<T>
{

    private T mResult;
    public T Result 
    {
        get { return mResult; }
        private set { mResult = value; }
    }

    public ThreadedMethod()
    {
    }

    //If supporting .net 3.5
    public void ExecuteMethod(Func<T> func)
    {
        Result = func.Invoke();
    }

    //If supporting only 2.0 use this and 
    //comment out the other overload
    public void ExecuteMethod(Delegate d)
    {
        Result = (T)d.DynamicInvoke();
    }
}

To use this code you can use a Lambda (or a delegate). Here is the example using lambdas:

ThreadedMethod<bool> threadedMethod = new ThreadedMethod<bool>();
Thread workerThread = new Thread((unused) => 
                            threadedMethod.ExecuteMethod(() => 
                                SomeMethod()));
workerThread.Start();
workerThread.Join();
if (threadedMethod.Result == false) 
{
    //do something about it...
}

VB.NET 2008 Implementation


Anyone using VB.NET 2008 can't use lambdas with non-value returning methods. This affects the ThreadedMethod class, so we'll make ExecuteMethod return the value of the function. This doesn't hurt anything.

Public Class ThreadedMethod(Of T)

    Private mResult As T
    Public Property Result() As T
        Get
            Return mResult
        End Get
        Private Set(ByVal value As T)
            mResult = value
        End Set
    End Property

    Sub New()
    End Sub

    'If supporting .net 3.5'
    Function ExecuteMethod(ByVal func As Func(Of T)) As T
        Result = func.Invoke()
        Return Result
    End Function

    'If supporting only 2.0 use this and' 
    'comment out the other overload'
    Function ExecuteMethod(ByVal d As [Delegate]) As T
        Result = DirectCast(d.DynamicInvoke(), T)
        Return Result
    End Function

End Class

How can I run PowerShell with the .NET 4 runtime?

If you don't want to modify the registry or app.config files, an alternate way is to create a simple .NET 4 console app that mimicks what PowerShell.exe does and hosts the PowerShell ConsoleShell.

See Option 2 – Hosting Windows PowerShell yourself

First, add a reference to the System.Management.Automation and Microsoft.PowerShell.ConsoleHost assemblies which can be found under %programfiles%\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0

Then use the following code:

using System;
using System.Management.Automation.Runspaces;
using Microsoft.PowerShell;

namespace PSHostCLRv4
{
    class Program
    {
        static int Main(string[] args)
        {
            var config = RunspaceConfiguration.Create();
                return ConsoleShell.Start(
                config,
                "Windows PowerShell - Hosted on CLR v4\nCopyright (C) 2010 Microsoft Corporation. All rights reserved.",
                "",
                args
            );
        }
    }
}

Converting PHP result array to JSON

$result = mysql_query($query) or die("Data not found."); 
$rows=array(); 
while($r=mysql_fetch_assoc($result))
{ 
$rows[]=$r;
}
header("Content-type:application/json"); 
echo json_encode($rows);

What is the role of "Flatten" in Keras?

enter image description here This is how Flatten works converting Matrix to single array.

Printing variables in Python 3.4

Try the format syntax:

print ("{0}. {1} appears {2} times.".format(1, 'b', 3.1415))

Outputs:

1. b appears 3.1415 times.

The print function is called just like any other function, with parenthesis around all its arguments.

How do I connect to mongodb with node.js (and authenticate)?

Here is new may to authenticate from "admin" and then switch to your desired DB for further operations:

   var MongoClient = require('mongodb').MongoClient;
var Db = require('mongodb').Db, Server = require('mongodb').Server ,
    assert = require('assert');

var user = 'user';
var password = 'password';

MongoClient.connect('mongodb://'+user+':'+password+'@localhost:27017/opsdb',{native_parser:true, authSource:'admin'}, function(err,db){
    if(err){
        console.log("Auth Failed");
        return;
    }
    console.log("Connected");
    db.collection("cols").find({loc:{ $eq: null } }, function(err, docs) {
        docs.each(function(err, doc) {
          if(doc) {
            console.log(doc['_id']);
          }
        });
    });

    db.close();

}); 

Is there an exponent operator in C#?

There is a blog post on MSDN about why an exponent operator does NOT exists from the C# team.

It would be possible to add a power operator to the language, but performing this operation is a fairly rare thing to do in most programs, and it doesn't seem justified to add an operator when calling Math.Pow() is simple.


You asked:

Do I have to write a loop or include another namespace to handle exponential operations? If so, how do I handle exponential operations using non-integers?

Math.Pow supports double parameters so there is no need for you to write your own.

R: how to label the x-axis of a boxplot

If you read the help file for ?boxplot, you'll see there is a names= parameter.

     boxplot(apple, banana, watermelon, names=c("apple","banana","watermelon"))

enter image description here

Set cellpadding and cellspacing in CSS?

You can easily set padding inside the table cells using the CSS padding property. It is a valid way to produce the same effect as the table's cellpadding attribute.

_x000D_
_x000D_
table,_x000D_
th,_x000D_
td {_x000D_
  border: 1px solid #666;_x000D_
}_x000D_
_x000D_
table th,_x000D_
table td {_x000D_
  padding: 10px;_x000D_
  /* Apply cell padding */_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
_x000D_
  <meta charset="utf-8">_x000D_
  <title>Set Cellpadding in CSS</title>_x000D_
_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
  <table>_x000D_
    <thead>_x000D_
      <tr>_x000D_
        <th>Row</th>_x000D_
        <th>First Name</th>_x000D_
        <th>Last Name</th>_x000D_
        <th>Email</th>_x000D_
      </tr>_x000D_
    </thead>_x000D_
    <tbody>_x000D_
      <tr>_x000D_
        <td>1</td>_x000D_
        <td>Clark</td>_x000D_
        <td>Kent</td>_x000D_
        <td>[email protected]</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>2</td>_x000D_
        <td>Peter</td>_x000D_
        <td>Parker</td>_x000D_
        <td>[email protected]</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>3</td>_x000D_
        <td>John</td>_x000D_
        <td>Rambo</td>_x000D_
        <td>[email protected]</td>_x000D_
      </tr>_x000D_
    </tbody>_x000D_
  </table>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Similarly, you can use the CSS border-spacing property to apply the spacing between adjacent table cell borders like the cellspacing attribute. However, in order to work border-spacing the value of border-collapse property muse be separate, which is default.

_x000D_
_x000D_
table {_x000D_
  border-collapse: separate;_x000D_
  border-spacing: 10px;_x000D_
  /* Apply cell spacing */_x000D_
}_x000D_
_x000D_
table,_x000D_
th,_x000D_
td {_x000D_
  border: 1px solid #666;_x000D_
}_x000D_
_x000D_
table th,_x000D_
table td {_x000D_
  padding: 5px;_x000D_
  /* Apply cell padding */_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
_x000D_
  <meta charset="utf-8">_x000D_
  <title>Set Cellspacing in CSS</title>_x000D_
_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
  <table>_x000D_
    <thead>_x000D_
      <tr>_x000D_
        <th>Row</th>_x000D_
        <th>First Name</th>_x000D_
        <th>Last Name</th>_x000D_
        <th>Email</th>_x000D_
      </tr>_x000D_
    </thead>_x000D_
    <tbody>_x000D_
      <tr>_x000D_
        <td>1</td>_x000D_
        <td>Clark</td>_x000D_
        <td>Kent</td>_x000D_
        <td>[email protected]</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>2</td>_x000D_
        <td>Peter</td>_x000D_
        <td>Parker</td>_x000D_
        <td>[email protected]</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>3</td>_x000D_
        <td>John</td>_x000D_
        <td>Rambo</td>_x000D_
        <td>[email protected]</td>_x000D_
      </tr>_x000D_
    </tbody>_x000D_
  </table>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How can I wait for a thread to finish with .NET?

When I want the UI to be able to update its display while waiting for a task to complete, I use a while-loop that tests IsAlive on the thread:

    Thread t = new Thread(() => someMethod(parameters));
    t.Start();
    while (t.IsAlive)
    {
        Thread.Sleep(500);
        Application.DoEvents();
    }

Find full path of the Python interpreter?

sys.executable contains full path of the currently running Python interpreter.

import sys

print(sys.executable)

which is now documented here

Convert int (number) to string with leading zeros? (4 digits)

Use String.PadLeft like this:

var result = input.ToString().PadLeft(length, '0');

validate a dropdownlist in asp.net mvc

For ListBox / DropDown in MVC5 - i've found this to work for me sofar:

in Model:

[Required(ErrorMessage = "- Select item -")]
 public List<string> SelectedItem { get; set; }
 public List<SelectListItem> AvailableItemsList { get; set; }

in View:

@Html.ListBoxFor(model => model.SelectedItem, Model.AvailableItemsList)
@Html.ValidationMessageFor(model => model.SelectedItem, "", new { @class = "text-danger" })

Comparing arrays in C#

"Why do i get that error?" - probably, you don't have "using System.Collections;" at the top of the file - only "using System.Collections.Generic;" - however, generics are probably safer - see below:

static bool ArraysEqual<T>(T[] a1, T[] a2)
{
    if (ReferenceEquals(a1,a2))
        return true;

    if (a1 == null || a2 == null)
        return false;

    if (a1.Length != a2.Length)
        return false;

    EqualityComparer<T> comparer = EqualityComparer<T>.Default;
    for (int i = 0; i < a1.Length; i++)
    {
        if (!comparer.Equals(a1[i], a2[i])) return false;
    }
    return true;
}

How to block calls in android

You can do it by listening to phone call events . You do it by having a BroadcastReceiver to PHONE_STATE and to NEW_OUTGOING_CALL. You find there what is the phone number.

Then when you decide to end the call, this is a bit tricky, because only from Android P it's guaranteed to work. Check here.

How to restart a node.js server

During development the best way to restart server for seeing changes made is to use nodemon

npm install nodemon -g

nodemon [your app name]

nodemon will watch the files in the directory that nodemon was started, and if they change, it will automatically restart your node application.

Check nodemon git repo: https://github.com/remy/nodemon

How do I use Apache tomcat 7 built in Host Manager gui?

Tomcat 8:

The following worked for me with tomcat 8.

Add these lines to apache-tomcat-8.0.9/conf/tomcat-users.xml

For Manager:

<role rolename="manager-gui"/>
<user username="admin" password="pass" roles="manager-gui"/>

For Host Manager:

<role rolename="admin-gui"/>
<user username="admin" password="pass" roles="admin-gui"/>

How to count the number of true elements in a NumPy bool array

boolarr.sum(axis=1 or axis=0)

axis = 1 will output number of trues in a row and axis = 0 will count number of trues in columns so

boolarr[[true,true,true],[false,false,true]]
print(boolarr.sum(axis=1))

will be (3,1)

Span inside anchor or anchor inside span or doesn't matter?

It is perfectly valid (at least by HTML 4.01 and XHTML 1.0 standards) to nest either a <span> inside an <a> or an <a> inside a <span>.

Just to prove it to yourself, you can always check it out an the W3C MarkUp Validation Service

I tried validating:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
  <html>
    <head>
      <title>Title</title>
    </head>
    <body>
       <p>
         <a href="http://www.google.com/"><span>Google</span></a>
       </p>
    </body>
  </html>

And also the same as above, but with the <a> inside the <span>

i.e.

<span><a href="http://www.google.com">Google</a></span>

with both HTML 4.01 and XHTML 1.0 doctypes, and both passed validation successfully!

Only thing to be aware of is to ensure that you close the tags in the correct order. So if you start with a <span> then an <a>, make sure you close the <a> tag first before closing the <span> and vice-versa.

Remove redundant paths from $PATH variable

Here is a one line code that cleans up the PATH

  • It does not disturb the order of the PATH, just removes duplicates
  • Treats : and empth PATH gracefully
  • No special characters used, so does not require escape
  • Uses /bin/awk so it works even when PATH is broken

    export PATH="$(echo "$PATH" |/bin/awk 'BEGIN{RS=":";}
    {sub(sprintf("%c$",10),"");if(A[$0]){}else{A[$0]=1;
    printf(((NR==1)?"":":")$0)}}')";
    

Extract substring using regexp in plain bash

If your string is

foo="US/Central - 10:26 PM (CST)"

then

echo "${foo}" | cut -d ' ' -f3

will do the job.

Determine if map contains a value for a key?

Does something along these lines exist?

No. With the stl map class, you use ::find() to search the map, and compare the returned iterator to std::map::end()

so

map<int,Bar>::iterator it = m.find('2');
Bar b3;
if(it != m.end())
{
   //element found;
   b3 = it->second;
}

Obviously you can write your own getValue() routine if you want (also in C++, there is no reason to use out), but I would suspect that once you get the hang of using std::map::find() you won't want to waste your time.

Also your code is slightly wrong:

m.find('2'); will search the map for a keyvalue that is '2'. IIRC the C++ compiler will implicitly convert '2' to an int, which results in the numeric value for the ASCII code for '2' which is not what you want.

Since your keytype in this example is int you want to search like this: m.find(2);

How to parse JSON boolean value?

A boolean is not an integer; 1 and 0 are not boolean values in Java. You'll need to convert them explicitly:

boolean multipleContacts = (1 == jsonObject.getInt("MultipleContacts"));

or serialize the ints as booleans from the start.

Using the HTML5 "required" attribute for a group of checkboxes?

Its a simple trick. This is jQuery code that can exploit the html5 validation by changing the required properties if any one is checked. Following is your html code (make sure that you add required for all the elements in the group.)

<input type="checkbox" name="option[]" id="option-1" value="option1" required/> Option 1
<input type="checkbox" name="option[]" id="option-2" value="option2" required/> Option 2
<input type="checkbox" name="option[]" id="option-3" value="option3" required/> Option 3
<input type="checkbox" name="option[]" id="option-4" value="option4" required/> Option 4
<input type="checkbox" name="option[]" id="option-5" value="option5" required/> Option 5

Following is jQuery script, which disables further validation check if any one is selected. Select using name element.

$cbx_group = $("input:checkbox[name='option[]']");
$cbx_group = $("input:checkbox[id^='option-']"); // name is not always helpful ;)

$cbx_group.prop('required', true);
if($cbx_group.is(":checked")){
  $cbx_group.prop('required', false);
}

Small gotcha here: Since you are using html5 validation, make sure you execute this before the it gets validated i.e. before form submit.

// but this might not work as expected
$('form').submit(function(){
  // code goes here
});

// So, better USE THIS INSTEAD:
$('button[type="submit"]').on('click', function() {
  // skipping validation part mentioned above
});

Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

This worked for me after trying several ways.

In the file node_modules\metro-config\src\defaults\blacklist.js

Replace :

var sharedBlacklist = [
  /node_modules[/\\]react[/\\]dist[/\\].*/,
  /website\/node_modules\/.*/,
  /heapCapture\/bundle\.js/,
  /.*\/__tests__\/.*/
];

with :

var sharedBlacklist = [
  /node_modules[\/\\]react[\/\\]dist[\/\\].*/,
  /website\/node_modules\/.*/,
  /heapCapture\/bundle\.js/,
  /.*\/__tests__\/.*/
];

hope this helps.

Why is division in Ruby returning an integer instead of decimal value?

You can include the ruby mathn module.

require 'mathn'

This way, you are going to be able to make the division normally.

1/2              #=> (1/2)
(1/2) ** 3       #=> (1/8)
1/3*3            #=> 1
Math.sin(1/2)    #=> 0.479425538604203

This way, you get exact division (class Rational) until you decide to apply an operation that cannot be expressed as a rational, for example Math.sin.

How To Convert A Number To an ASCII Character?

I was googling about how to convert an int to char, that got me here. But my question was to convert for example int of 6 to char of '6'. For those who came here like me, this is how to do it:

int num = 6;
num.ToString().ToCharArray()[0];

Regex to check with starts with http://, https:// or ftp://

test.matches() method checks all text.use test.find()

How to read a file into vector in C++?

Just a piece of advice. Instead of writing

for (int i=0; i=((Main.size())-1); i++) {
   cout << Main[i] << '\n';
}

as suggested above, write a:

for (vector<double>::iterator it=Main.begin(); it!=Main.end(); it++) {
   cout << *it << '\n';
}

to use iterators. If you have C++11 support, you can declare i as auto i=Main.begin() (just a handy shortcut though)

This avoids the nasty one-position-out-of-bound error caused by leaving out a -1 unintentionally.

What is difference between sleep() method and yield() method of multi threading?

sleep() causes the thread to definitely stop executing for a given amount of time; if no other thread or process needs to be run, the CPU will be idle (and probably enter a power saving mode).

yield() basically means that the thread is not doing anything particularly important and if any other threads or processes need to be run, they should. Otherwise, the current thread will continue to run.

TypeError: Cannot read property 'then' of undefined

TypeError: Cannot read property 'then' of undefined when calling a Django service using AngularJS.

If you are calling a Python service, the code will look like below:

this.updateTalentSupplier=function(supplierObj){
  var promise = $http({
    method: 'POST',
      url: bbConfig.BWS+'updateTalentSupplier/',
      data:supplierObj,
      withCredentials: false,
      contentType:'application/json',
      dataType:'json'
    });
    return promise; //Promise is returned 
}

We are using MongoDB as the database(I know it doesn't matter. But if someone is searching with MongoDB + Python (Django) + AngularJS the result should come.

Google Maps API v3: Can I setZoom after fitBounds?

Had the same problem, needed to fit many markers on the map. This solved my case:

  1. Declare bounds
  2. Use scheme provided by koderoid (for each marker set bounds.extend(objLatLng))
  3. Execute fitbounds AFTER map is completed:

    google.maps.event.addListenerOnce(map, 'idle', function() { 
        map.fitBounds( bounds );
    });
    

How to add parameters into a WebRequest?

Hope this works

webRequest.Credentials= new NetworkCredential("API_User","API_Password");

Java to Jackson JSON serialization: Money fields

Instead of setting the @JsonSerialize on each member or getter you can configure a module that use a custome serializer for a certain type:

SimpleModule module = new SimpleModule();
module.addSerializer(BigInteger.class, new ToStringSerializer());
objectMapper.registerModule(module);

In the above example, I used the to string serializer to serialize BigIntegers (since javascript can not handle such numeric values).

HttpServlet cannot be resolved to a type .... is this a bug in eclipse?

It means that servlet jar is missing .

check the libraries for your project. Configure your buildpath download **

servlet-api.jar

** and import it in your project.

How can I check if a string only contains letters in Python?

Actually, we're now in globalized world of 21st century and people no longer communicate using ASCII only so when anwering question about "is it letters only" you need to take into account letters from non-ASCII alphabets as well. Python has a pretty cool unicodedata library which among other things allows categorization of Unicode characters:

unicodedata.category('?')
'Lo'

unicodedata.category('A')
'Lu'

unicodedata.category('1')
'Nd'

unicodedata.category('a')
'Ll'

The categories and their abbreviations are defined in the Unicode standard. From here you can quite easily you can come up with a function like this:

def only_letters(s):
    for c in s:
        cat = unicodedata.category(c)
        if cat not in ('Ll','Lu','Lo'):
            return False
    return True

And then:

only_letters('Bzdrezylo')
True

only_letters('He7lo')
False

As you can see the whitelisted categories can be quite easily controlled by the tuple inside the function. See this article for a more detailed discussion.

iOS 7 - Failing to instantiate default view controller

1st option

if you want to set your custom storyboard instead of a default view controller.

Change this attribute from info.plist file

<key>UISceneStoryboardFile</key> <string>Onboarding</string>

Onboarding would be your storyboard name

to open this right-click on info.plist file and open as a source code

2nd option

1- Click on your project

2- Select your project from the target section

3- Move to Deployment interface section

4- Change your storyboard section from Main Interface field

Please remember set your storyboard initial view controller

Doctrine findBy 'does not equal'

I solved this rather easily (without adding a method) so i'll share:

use Doctrine\Common\Collections\Criteria;

$repository->matching( Criteria::create()->where( Criteria::expr()->neq('id', 1) ) );

By the way, i'm using the Doctrine ORM module from within Zend Framework 2 and i'm not sure whether this would be compatible in any other case.

In my case, i was using a form element configuration like this: to show all roles except "guest" in a radio button array.

$this->add(array(
    'type' => 'DoctrineModule\Form\Element\ObjectRadio',
        'name' => 'roles',
        'options' => array(
            'label' => _('Roles'),
            'object_manager' => $this->getEntityManager(),
            'target_class'   => 'Application\Entity\Role',
            'property' => 'roleId',
            'find_method'    => array(
                'name'   => 'matching',
                'params' => array(
                    'criteria' => Criteria::create()->where(
                        Criteria::expr()->neq('roleId', 'guest')
                ),
            ),
        ),
    ),
));

javax.crypto.IllegalBlockSizeException : Input length must be multiple of 16 when decrypting with padded cipher

A few comments:

import sun.misc.*; Don't do this. It is non-standard and not guaranteed to be the same between implementations. There are other libraries with Base64 conversion available.

byte[] encVal = c.doFinal(Data.getBytes()); You are relying on the default character encoding here. Always specify what character encoding you are using: byte[] encVal = c.doFinal(Data.getBytes("UTF-8")); Defaults might be different in different places.

As @thegrinner pointed out, you need to explicitly check the length of your byte arrays. If there is a discrepancy, then compare them byte by byte to see where the difference is creeping in.

How to check type of object in Python?

use isinstance(v, type_name) or type(v) is type_name or type(v) == type_name,

where type_name can be one of the following:

  • None
  • bool
  • int
  • float
  • complex
  • str
  • list
  • tuple
  • set
  • dict

and, of course,

  • custom types (classes)

How to check whether an object is a date?

The function is getMonth(), not GetMonth().

Anyway, you can check if the object has a getMonth property by doing this. It doesn't necessarily mean the object is a Date, just any object which has a getMonth property.

if (date.getMonth) {
    var month = date.getMonth();
}

Bootstrap carousel resizing image

replace your image tag with

<img src="http://localhost:6054/wp-content/themes/BLANK-Theme/images/material/images.jpg" alt="the-buzz-img3"  style="width:640px;height:360px" />

use style attribute and make sure there is no css class for image which set image height and width

How to measure time taken between lines of code in python?

If you want to measure CPU time, can use time.process_time() for Python 3.3 and above:

import time
start = time.process_time()
# your code here    
print(time.process_time() - start)

First call turns the timer on, and second call tells you how many seconds have elapsed.

There is also a function time.clock(), but it is deprecated since Python 3.3 and will be removed in Python 3.8.

There are better profiling tools like timeit and profile, however time.process_time() will measure the CPU time and this is what you're are asking about.

If you want to measure wall clock time instead, use time.time().

Notepad++ change text color?

A little late reply, but what I found in Notepad++ v7.8.6 is, on RMB (Right Mouse Button), on selection text, it gives an option called "Style token" where it shows "Using 1st/2nd/3rd/4th/5th style" to highlight the selected text in different pre-defined colors

limit text length in php and provide 'Read more' link

$num_words = 101;
$words = array();
$words = explode(" ", $original_string, $num_words);
$shown_string = "";

if(count($words) == 101){
   $words[100] = " ... ";
}

$shown_string = implode(" ", $words);

How can I redirect a php page to another php page?

<?php header('Location: /login.php'); ?>

The above php script redirects the user to login.php within the same site

Can clearInterval() be called inside setInterval()?

Yes you can. You can even test it:

_x000D_
_x000D_
var i = 0;_x000D_
var timer = setInterval(function() {_x000D_
  console.log(++i);_x000D_
  if (i === 5) clearInterval(timer);_x000D_
  console.log('post-interval'); //this will still run after clearing_x000D_
}, 200);
_x000D_
_x000D_
_x000D_

In this example, this timer clears when i reaches 5.

Setting the height of a SELECT in IE

Yes, you can.

I was able to set the height of my SELECT to exactly what I wanted in IE8 and 9. The trick is to set the box-sizing property to content-box. Doing so will set the content area of the SELECT to the height, but keep in mind that margin, border and padding values will not be calculated in the width/height of the SELECT, so adjust those values accordingly.

select {
    display: block;
    padding: 6px 4px;
    -moz-box-sizing: content-box;
    -webkit-box-sizing:content-box;
    box-sizing:content-box;
    height: 15px;
}

Here is a working jsFiddle. Would you mind confirming and marking the appropriate answer?

-XX:MaxPermSize with or without -XX:PermSize

-XX:PermSize specifies the initial size that will be allocated during startup of the JVM. If necessary, the JVM will allocate up to -XX:MaxPermSize.

Linq filter List<string> where it contains a string value from another List<string>

you can do that

var filteredFileList = fileList.Where(fl => filterList.Contains(fl.ToString()));

When does Git refresh the list of remote branches?

To update the local list of remote branches:

git remote update origin --prune

To show all local and remote branches that (local) Git knows about

git branch -a

Formatting a number with exactly two decimals in JavaScript

You could also use the .toPrecision() method and some custom code, and always round up to the nth decimal digit regardless the length of int part.

function glbfrmt (number, decimals, seperator) {
    return typeof number !== 'number' ? number : number.toPrecision( number.toString().split(seperator)[0].length + decimals);
}

You could also make it a plugin for a better use.

extract part of a string using bash/cut/split

Using a single Awk:

... | awk -F '[/:]' '{print $5}'

That is, using as field separator either / or :, the username is always in field 5.

To store it in a variable:

username=$(... | awk -F '[/:]' '{print $5}')

A more flexible implementation with sed that doesn't require username to be field 5:

... | sed -e s/:.*// -e s?.*/??

That is, delete everything from : and beyond, and then delete everything up until the last /. sed is probably faster too than awk, so this alternative is definitely better.

MD5 hashing in Android

The provided solutions for the Scala language (a little shorter):

def getMd5(content: Array[Byte]) =
    try {
        val md = MessageDigest.getInstance("MD5")
        val bytes = md.digest(content)
        bytes.map(b => Integer.toHexString((b + 0x100) % 0x100)).mkString
    } catch {
        case ex: Throwable => null
    }

How to write a simple Java program that finds the greatest common divisor between two numbers?

One way to do it is the code below:

        int gcd = 0;
        while (gcdNum2 !=0 && gcdNum1 != 0 ) {
        if(gcdNum1 % gcdNum2 == 0){
            gcd = gcdNum2;
        }
            int aux = gcdNum2; 
            gcdNum2 = gcdNum1 % gcdNum2;
            gcdNum1 = aux;
    }

You do not need recursion to do this.

And be careful, it says that when a number is zero, then the GCD is the number that is not zero.

    while (gcdNum1 == 0) {
    gcdNum1 = 0;
}

You should modify this to fulfill the requirement.

I am not going to tell you how to modify your code entirely, only how to calculate the gcd.

Using for loop inside of a JSP

Do this

    <% for(int i = 0; i < allFestivals.size(); i+=1) { %>
        <tr>      
            <td><%=allFestivals.get(i).getFestivalName()%></td>
        </tr>
    <% } %>

Better way is to use c:foreach see link jstl for each

Unable to set data attribute using jQuery Data() API

It is mentioned in the .data() documentation

The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery)

This was also covered on Why don't changes to jQuery $.fn.data() update the corresponding html 5 data-* attributes?

The demo on my original answer below doesn't seem to work any more.

Updated answer

Again, from the .data() documentation

The treatment of attributes with embedded dashes was changed in jQuery 1.6 to conform to the W3C HTML5 specification.

So for <div data-role="page"></div> the following is true $('div').data('role') === 'page'

I'm fairly sure that $('div').data('data-role') worked in the past but that doesn't seem to be the case any more. I've created a better showcase which logs to HTML rather than having to open up the Console and added an additional example of the multi-hyphen to camelCase data- attributes conversion.

Updated demo (2015-07-25)

Also see jQuery Data vs Attr?

HTML

<div id="changeMe" data-key="luke" data-another-key="vader"></div>
<a href="#" id="changeData"></a>
<table id="log">
    <tr><th>Setter</th><th>Getter</th><th>Result of calling getter</th><th>Notes</th></tr>
</table>

JavaScript (jQuery 1.6.2+)

var $changeMe = $('#changeMe');
var $log = $('#log');

var logger;
(logger = function(setter, getter, note) {
    note = note || '';
    eval('$changeMe' + setter);
    var result = eval('$changeMe' + getter);
    $log.append('<tr><td><code>' + setter + '</code></td><td><code>' + getter + '</code></td><td>' + result + '</td><td>' + note + '</td></tr>');
})('', ".data('key')", "Initial value");

$('#changeData').click(function() {
    // set data-key to new value
    logger(".data('key', 'leia')", ".data('key')", "expect leia on jQuery node object but DOM stays as luke");
    // try and set data-key via .attr and get via some methods
    logger(".attr('data-key', 'yoda')", ".data('key')", "expect leia (still) on jQuery object but DOM now yoda");
    logger("", ".attr('key')", "expect undefined (no attr <code>key</code>)");
    logger("", ".attr('data-key')", "expect yoda in DOM and on jQuery object");

    // bonus points
    logger('', ".data('data-key')", "expect undefined (cannot get via this method)");
    logger(".data('anotherKey')", ".data('anotherKey')", "jQuery 1.6+ get multi hyphen <code>data-another-key</code>");
    logger(".data('another-key')", ".data('another-key')", "jQuery < 1.6 get multi hyphen <code>data-another-key</code> (also supported in jQuery 1.6+)");

    return false;
});

$('#changeData').click();

Older demo


Original answer

For this HTML:

<div id="foo" data-helptext="bar"></div>
<a href="#" id="changeData">change data value</a>

and this JavaScript (with jQuery 1.6.2)

console.log($('#foo').data('helptext'));

$('#changeData').click(function() {
    $('#foo').data('helptext', 'Testing 123');
//  $('#foo').attr('data-helptext', 'Testing 123');
    console.log($('#foo').data('data-helptext'));
    return false;
});

See demo

Using the Chrome DevTools Console to inspect the DOM, the $('#foo').data('helptext', 'Testing 123'); does not update the value as seen in the Console but $('#foo').attr('data-helptext', 'Testing 123'); does.

How can I find the number of elements in an array?

I personally think that sizeof(a) / sizeof(*a) looks cleaner.

I also prefer to define it as a macro:

#define NUM(a) (sizeof(a) / sizeof(*a))

Then you can use it in for-loops, thusly:

for (i = 0; i < NUM(a); i++)

Segmentation fault on large array sizes

Also, if you are running in most UNIX & Linux systems you can temporarily increase the stack size by the following command:

ulimit -s unlimited

But be careful, memory is a limited resource and with great power come great responsibilities :)

How to rename a single column in a data.frame?

Let df be the dataframe you have with col names myDays and temp. If you want to rename "myDays" to "Date",

library(plyr)
rename(df,c("myDays" = "Date"))

or with pipe, you can

dfNew      <- df %>% 
  plyr::rename(c("myDays" = "Date"))

How to persist a property of type List<String> in JPA?

According to Java Persistence with Hibernate

mapping collections of value types with annotations [...]. At the time of writing it isn't part of the Java Persistence standard

If you were using Hibernate, you could do something like:

@org.hibernate.annotations.CollectionOfElements(
    targetElement = java.lang.String.class
)
@JoinTable(
    name = "foo",
    joinColumns = @JoinColumn(name = "foo_id")
)
@org.hibernate.annotations.IndexColumn(
    name = "POSITION", base = 1
)
@Column(name = "baz", nullable = false)
private List<String> arguments = new ArrayList<String>();

Update: Note, this is now available in JPA2.

PHP preg_match - only allow alphanumeric strings and - _ characters

Why to use regex? PHP has some built in functionality to do that

<?php
    $valid_symbols = array('-', '_');
    $string1 = "This is a string*";
    $string2 = "this_is-a-string";

    if(preg_match('/\s/',$string1) || !ctype_alnum(str_replace($valid_symbols, '', $string1))) {
        echo "String 1 not acceptable acceptable";
    }
?>

preg_match('/\s/',$username) will check for blank space

!ctype_alnum(str_replace($valid_symbols, '', $string1)) will check for valid_symbols

Firebase FCM force onTokenRefresh() to be called

This answer does not destroy instance id, instead it is able to get current one. It also store refreshed one in Shared preferences.

Strings.xml

<string name="pref_firebase_instance_id_key">pref_firebase_instance_id</string>
<string name="pref_firebase_instance_id_default_key">default</string>

Utility.java (any class where you want to set/get preferences)

public static void setFirebaseInstanceId(Context context, String InstanceId) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    SharedPreferences.Editor editor;
    editor = sharedPreferences.edit();
    editor.putString(context.getString(R.string.pref_firebase_instance_id_key),InstanceId);
    editor.apply();
}

public static String getFirebaseInstanceId(Context context) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    String key = context.getString(R.string.pref_firebase_instance_id_key);
    String default_value = context.getString(R.string.pref_firebase_instance_id_default_key);
    return sharedPreferences.getString(key, default_value);
}

MyFirebaseInstanceIdService.java (extends FirebaseInstanceIdService)

@Override
public void onCreate()
{
    String CurrentToken = FirebaseInstanceId.getInstance().getToken();

    //Log.d(this.getClass().getSimpleName(),"Inside Instance on onCreate");
    String savedToken = Utility.getFirebaseInstanceId(getApplicationContext());
    String defaultToken = getApplication().getString(R.string.pref_firebase_instance_id_default_key);

    if(CurrentToken != null && !savedToken.equalsIgnoreCase(defaultToken))
    //currentToken is null when app is first installed and token is not available
    //also skip if token is already saved in preferences...
    {
        Utility.setFirebaseInstanceId(getApplicationContext(),CurrentToken);
    }
    super.onCreate();
}

@Override
public void onTokenRefresh() {
     .... prev code
      Utility.setFirebaseInstanceId(getApplicationContext(),refreshedToken);
     ....

}

Android 2.0 and above onCreate of service is not invoked when started automatically (source). Instead onStartCommand is overridden and used. But in actual FirebaseInstanceIdService it is declared as final and can't be overridden. However, when we start service using startService(), if service is already running, its original instance is used (which is good). Our onCreate() (defined above) also got invoked!.

Use this in begining of MainActivity or at whichever point you think you need instance id.

MyFirebaseInstanceIdService myFirebaseInstanceIdService = new MyFirebaseInstanceIdService();
Intent intent= new Intent(getApplicationContext(),myFirebaseInstanceIdService.getClass());
//Log.d(this.getClass().getSimpleName(),"Starting MyFirebaseInstanceIdService");
startService(intent); //invoke onCreate

And Finally,

Utility.getFirebaseInstanceId(getApplicationContext())

Note, you can futher enhance this by trying to move startservice() code to getFirebaseInstanceId method.

Quickest way to convert XML to JSON in Java

The only problem with JSON in Java is that if your XML has a single child, but is an array, it will convert it to an object instead of an array. This can cause problems if you dynamically always convert from XML to JSON, where if your example XML has only one element, you return an object, but if it has 2+, you return an array, which can cause parsing issues for people using the JSON.

Infoscoop's XML2JSON class has a way of tagging elements that are arrays before doing the conversion, so that arrays can be properly mapped, even if there is only one child in the XML.

Here is an example of using it (in a slightly different language, but you can also see how arrays is used from the nodelist2json() method of the XML2JSON link).

Does WhatsApp offer an open API?

1) It looks possible. This info on Github describes how to create a java program to send a message using the whatsapp encryption protocol from WhisperSystems.

2) No. See the whatsapp security white paper.

3) See #1.

Detect WebBrowser complete page loading

Using the DocumentCompleted event with a page with multiple nested frames didn't work for me.

I used the Interop.SHDocVW library to cast the WebBrowser control like this:

public class webControlWrapper
{
    private bool _complete;
    private WebBrowser _webBrowserControl;

    public webControlWrapper(WebBrowser webBrowserControl)
    {
        _webBrowserControl = webBrowserControl;
    }

    public void NavigateAndWaitForComplete(string url)
    {
        _complete = false;

        _webBrowserControl.Navigate(url);

        var webBrowser = (SHDocVw.WebBrowser) _webBrowserControl.ActiveXInstance;

        if (webBrowser != null)
            webBrowser.DocumentComplete += WebControl_DocumentComplete;

        //Wait until page is complete
        while (!_complete)
        {
            Application.DoEvents();
        }
    }

    private void WebControl_DocumentComplete(object pDisp, ref object URL)
    {
        // Test if it's the main frame who called the event.
        if (pDisp == _webBrowserControl.ActiveXInstance)
            _complete = true;
    }

This code works for me when navigating to a defined URL using the webBrowserControl.Navigate(url) method, but I don't know how to control page complete when a html button is clicked using the htmlElement.InvokeMember("click").

PUT and POST getting 405 Method Not Allowed Error for Restful Web Services

I'm not sure if I am correct, but from the request header that you post:

Request headers

Accept: Application/json

Origin: chrome-extension://hgmloofddffdnphfgcellkdfbfbjeloo

User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36

Content-Type: application/x-www-form-urlencoded

Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8

it seems like you didn't config your request body to JSON type.

Testing two JSON objects for equality ignoring child order in Java

Here is the code using Jackson ObjectMapper. To know more read this article.

import com.fasterxml.jackson.*

boolean compareJsonPojo(Object pojo1, Object pojo2) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            String str1 = mapper.writeValueAsString(pojo1);
            String str2 = mapper.writeValueAsString(pojo2);
            return mapper.readTree(str1).equals(mapper.readTree(str2));
        } catch (JsonProcessingException e) {
            throw new AssertionError("Error comparing JSON objects: " + e.getMessage());
        }
    }

Managing SSH keys within Jenkins for Git

It looks like the github.com host which jenkins tries to connect to is not listed under the Jenkins user's $HOME/.ssh/known_hosts. Jenkins runs on most distros as the user jenkins and hence has its own .ssh directory to store the list of public keys and known_hosts.

The easiest solution I can think of to fix this problem is:

# Login as the jenkins user and specify shell explicity,
# since the default shell is /bin/false for most
# jenkins installations.
sudo su jenkins -s /bin/bash

cd SOME_TMP_DIR
# git clone YOUR_GITHUB_URL

# Allow adding the SSH host key to your known_hosts

# Exit from su
exit

Difference between pre-increment and post-increment in a loop?

In C# there is no difference when used in a for loop.

for (int i = 0; i < 10; i++) { Console.WriteLine(i); }

outputs the same thing as

for (int i = 0; i < 10; ++i) { Console.WriteLine(i); }

As others have pointed out, when used in general i++ and ++i have a subtle yet significant difference:

int i = 0;
Console.WriteLine(i++);   // Prints 0
int j = 0;
Console.WriteLine(++j);   // Prints 1

i++ reads the value of i then increments it.

++i increments the value of i then reads it.

Including JavaScript class definition from another file in Node.js

Instead of myFile.js write your files like myFile.mjs. This extension comes with all the goodies of es6, but I mean I recommend you to you webpack and Babel

Auto logout with Angularjs based on idle user

View Demo which is using angularjs and see your's browser log

<!DOCTYPE html>
<html ng-app="Application_TimeOut">
<head>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min.js"></script>
</head>

<body>
</body>

<script>

var app = angular.module('Application_TimeOut', []);
app.run(function($rootScope, $timeout, $document) {    
    console.log('starting run');

    // Timeout timer value
    var TimeOutTimerValue = 5000;

    // Start a timeout
    var TimeOut_Thread = $timeout(function(){ LogoutByTimer() } , TimeOutTimerValue);
    var bodyElement = angular.element($document);

    /// Keyboard Events
    bodyElement.bind('keydown', function (e) { TimeOut_Resetter(e) });  
    bodyElement.bind('keyup', function (e) { TimeOut_Resetter(e) });    

    /// Mouse Events    
    bodyElement.bind('click', function (e) { TimeOut_Resetter(e) });
    bodyElement.bind('mousemove', function (e) { TimeOut_Resetter(e) });    
    bodyElement.bind('DOMMouseScroll', function (e) { TimeOut_Resetter(e) });
    bodyElement.bind('mousewheel', function (e) { TimeOut_Resetter(e) });   
    bodyElement.bind('mousedown', function (e) { TimeOut_Resetter(e) });        

    /// Touch Events
    bodyElement.bind('touchstart', function (e) { TimeOut_Resetter(e) });       
    bodyElement.bind('touchmove', function (e) { TimeOut_Resetter(e) });        

    /// Common Events
    bodyElement.bind('scroll', function (e) { TimeOut_Resetter(e) });       
    bodyElement.bind('focus', function (e) { TimeOut_Resetter(e) });    

    function LogoutByTimer()
    {
        console.log('Logout');

        ///////////////////////////////////////////////////
        /// redirect to another page(eg. Login.html) here
        ///////////////////////////////////////////////////
    }

    function TimeOut_Resetter(e)
    {
        console.log('' + e);

        /// Stop the pending timeout
        $timeout.cancel(TimeOut_Thread);

        /// Reset the timeout
        TimeOut_Thread = $timeout(function(){ LogoutByTimer() } , TimeOutTimerValue);
    }

})
</script>

</html>

Below code is pure javascript version

<html>
    <head>
        <script type="text/javascript">         
            function logout(){
                console.log('Logout');
            }

            function onInactive(millisecond, callback){
                var wait = setTimeout(callback, millisecond);               
                document.onmousemove = 
                document.mousedown = 
                document.mouseup = 
                document.onkeydown = 
                document.onkeyup = 
                document.focus = function(){
                    clearTimeout(wait);
                    wait = setTimeout(callback, millisecond);                       
                };
            }           
        </script>
    </head> 
    <body onload="onInactive(5000, logout);"></body>
</html>

UPDATE

I updated my solution as @Tom suggestion.

<!DOCTYPE html>
<html ng-app="Application_TimeOut">
<head>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min.js"></script>
</head>

<body>
</body>

<script>
var app = angular.module('Application_TimeOut', []);
app.run(function($rootScope, $timeout, $document) {    
    console.log('starting run');

    // Timeout timer value
    var TimeOutTimerValue = 5000;

    // Start a timeout
    var TimeOut_Thread = $timeout(function(){ LogoutByTimer() } , TimeOutTimerValue);
    var bodyElement = angular.element($document);

    angular.forEach(['keydown', 'keyup', 'click', 'mousemove', 'DOMMouseScroll', 'mousewheel', 'mousedown', 'touchstart', 'touchmove', 'scroll', 'focus'], 
    function(EventName) {
         bodyElement.bind(EventName, function (e) { TimeOut_Resetter(e) });  
    });

    function LogoutByTimer(){
        console.log('Logout');
        ///////////////////////////////////////////////////
        /// redirect to another page(eg. Login.html) here
        ///////////////////////////////////////////////////
    }

    function TimeOut_Resetter(e){
        console.log(' ' + e);

        /// Stop the pending timeout
        $timeout.cancel(TimeOut_Thread);

        /// Reset the timeout
        TimeOut_Thread = $timeout(function(){ LogoutByTimer() } , TimeOutTimerValue);
    }

})
</script>
</html>

Click here to see at Plunker for updated version

How to select an element by classname using jqLite?

angualr uses the lighter version of jquery called as jqlite which means it doesnt have all the features of jQuery. here is a reference in angularjs docs about what you can use from jquery. Angular Element docs

In your case you need to find a div with ID or class name. for class name you can use

var elems =$element.find('div') //returns all the div's in the $elements
    angular.forEach(elems,function(v,k)){
    if(angular.element(v).hasClass('class-name')){
     console.log(angular.element(v));
}}

or you can use much simpler way by query selector

angular.element(document.querySelector('#id'))

angular.element(elem.querySelector('.classname'))

it is not as flexible as jQuery but what

How can I delete one element from an array by value

I'm not sure if anyone has stated this, but Array.delete() and -= value will delete every instance of the value passed to it within the Array. In order to delete the first instance of the particular element you could do something like

arr = [1,3,2,44,5]
arr.delete_at(arr.index(44))

#=> [1,3,2,5]

There could be a simpler way. I'm not saying this is best practice, but it is something that should be recognized.

How can I send an email by Java application using GMail, Yahoo, or Hotmail?

Hi try this code....

package my.test.service;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Message;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class Sample {
    public static void main(String args[]) {
        final String SMTP_HOST = "smtp.gmail.com";
        final String SMTP_PORT = "587";
        final String GMAIL_USERNAME = "[email protected]";
        final String GMAIL_PASSWORD = "xxxxxxxxxx";

        System.out.println("Process Started");

        Properties prop = System.getProperties();
        prop.setProperty("mail.smtp.starttls.enable", "true");
        prop.setProperty("mail.smtp.host", SMTP_HOST);
        prop.setProperty("mail.smtp.user", GMAIL_USERNAME);
        prop.setProperty("mail.smtp.password", GMAIL_PASSWORD);
        prop.setProperty("mail.smtp.port", SMTP_PORT);
        prop.setProperty("mail.smtp.auth", "true");
        System.out.println("Props : " + prop);

        Session session = Session.getInstance(prop, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(GMAIL_USERNAME,
                        GMAIL_PASSWORD);
            }
        });

        System.out.println("Got Session : " + session);

        MimeMessage message = new MimeMessage(session);
        try {
            System.out.println("before sending");
            message.setFrom(new InternetAddress(GMAIL_USERNAME));
            message.addRecipients(Message.RecipientType.TO,
                    InternetAddress.parse(GMAIL_USERNAME));
            message.setSubject("My First Email Attempt from Java");
            message.setText("Hi, This mail came from Java Application.");
            message.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse(GMAIL_USERNAME));
            Transport transport = session.getTransport("smtp");
            System.out.println("Got Transport" + transport);
            transport.connect(SMTP_HOST, GMAIL_USERNAME, GMAIL_PASSWORD);
            transport.sendMessage(message, message.getAllRecipients());
            System.out.println("message Object : " + message);
            System.out.println("Email Sent Successfully");
        } catch (AddressException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MessagingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Make A List Item Clickable (HTML/CSS)

The li element supports an onclick event.

<ul>
<li onclick="location.href = 'http://stackoverflow.com/questions/3486110/make-a-list-item-clickable-html-css';">Make A List Item Clickable</li>
</ul>

How to set an environment variable in a running docker container

You wrote that you do not want to migrate the old volumes. So I assume either the Dockerfile that you used to build the spencercooley/wordpress image has VOLUMEs defined or you specified them on command line with the -v switch.

You could simply start a new container which imports the volumes from the old one with the --volumes-from switch like:

$ docker run --name my-new-wordpress --volumes-from my-wordpress -e VIRTUAL_HOST=domain.com --link my-mysql:mysql -d spencercooley/wordpres

So you will have a fresh container but you do not loose the old data. You do not even need to touch or migrate it.

A well-done container is always stateless. That means its process is supposed to add or modify only files on defined volumes. That can be verified with a simple docker diff <containerId> after the container ran a while.

In that case it is not dangerous when you re-create the container with the same parameters (in your case slightly modified ones). Assuming you create it from exactly the same image from which the old one was created and you re-use the same volumes with the above mentioned switch.

After the new container has started successfully and you verified that everything runs correctly you can delete the old wordpress container. The old volumes are then referred from the new container and will not be deleted.

ssh: The authenticity of host 'hostname' can't be established

I solve the issue which gives below written error:
Error:
The authenticity of host 'XXX.XXX.XXX' can't be established.
RSA key fingerprint is 09:6c:ef:cd:55:c4:4f:ss:5a:88:46:0a:a9:27:83:89.

Solution:
1. install any openSSH tool.
2. run command ssh
3. it will ask for do u add this host like. accept YES.
4. This host will add in the known host list.
5. Now you are able to connect with this host.

This solution is working now......

Creating a .dll file in C#.Net

Console Application is an application (.exe), not a Library (.dll). To make a library, create a new project, select "Class Library" in type of project, then copy the logic of your first code into this new project.

Or you can edit the Project Properties and select Class Library instead of Console Application in Output type.

As some code can be "console" dependant, I think first solution is better if you check your logic when you copy it.

T-SQL substring - separating first and last name

You may have problems if the Fullname doesn't contain a space. Assuming the whole of FullName goes to Surname if there is no space and FirstName becomes an empty string, then you can use this:

SELECT
  RTRIM(LEFT(FullName, CHARINDEX(' ', FullName))) AS FirstName,
  SUBSTRING(FullName, CHARINDEX(' ', FullName) + 1, 8000) AS LastName
FROM
  MyNameTable;

Check if EditText is empty.

You could call this function for each of the edit texts:

public boolean isEmpty(EditText editText) {
    boolean isEmptyResult = false;
    if (editText.getText().length() == 0) {
        isEmptyResult = true;
    }
    return isEmptyResult;
}

Remove blank values from array using C#

I prefer to use two options, white spaces and empty:

test = test.Where(x => !string.IsNullOrEmpty(x)).ToArray();
test = test.Where(x => !string.IsNullOrWhiteSpace(x)).ToArray();

Is it possible to have empty RequestParam values use the defaultValue?

You could change the @RequestParam type to an Integer and make it not required. This would allow your request to succeed, but it would then be null. You could explicitly set it to your default value in the controller method:

@RequestMapping(value = "/test", method = RequestMethod.POST)
@ResponseBody
public void test(@RequestParam(value = "i", required=false) Integer i) {
    if(i == null) {
        i = 10;
    }
    // ...
}

I have removed the defaultValue from the example above, but you may want to include it if you expect to receive requests where it isn't set at all:

http://example.com/test

Get Date in YYYYMMDD format in windows batch file

You can try this ! This should work on windows machines.

for /F "usebackq tokens=1,2,3 delims=-" %%I IN (`echo %date%`) do echo "%%I" "%%J" "%%K"

PHP removing a character in a string

$str = preg_replace('/\?\//', '?', $str);

Edit: See CMS' answer. It's late, I should know better.

What is the difference between a schema and a table and a database?

A schema is not a plan for the entire database. It is a plan/container for a subset of objects (ex.tables) inside a a database.

This goes to say that you can have multiple objects(ex. tables) inside one database which don't neccessarily fall under the same functional category. So you can group them under various schemas and give them different user access permissions.

That said, I am unsure whether you can have one table under multiple schemas. The Management Studio UI gives a dropdown to assign a schema to a table, and hence making it possible to choose only one schema. I guess if you do it with TSQL, it might create 2 (or multiple) different objects with different object Ids.

In git how is fetch different than pull and how is merge different than rebase?

Fetch vs Pull

Git fetch just updates your repo data, but a git pull will basically perform a fetch and then merge the branch pulled

What is the difference between 'git pull' and 'git fetch'?


Merge vs Rebase

from Atlassian SourceTree Blog, Merge or Rebase:

Merging brings two lines of development together while preserving the ancestry of each commit history.

In contrast, rebasing unifies the lines of development by re-writing changes from the source branch so that they appear as children of the destination branch – effectively pretending that those commits were written on top of the destination branch all along.

Also, check out Learn Git Branching, which is a nice game that has just been posted to HackerNews (link to post) and teaches a lot of branching and merging tricks. I believe it will be very helpful in this matter.

Where does R store packages?

You do not want the '='

Use .libPaths("C:/R/library") in you Rprofile.site file

And make sure you have correct " symbol (Shift-2)

PHP php_network_getaddresses: getaddrinfo failed: No such host is known

IMO it's the different way to resolve a name from the OS and PHP.

Try:

echo gethostbyname("host.name.tld");

and

var_export (dns_get_record ( "host.name.tld") );

or

$dns=array("8.8.8.8","8.8.4.4");
var_export (dns_get_record ( "host.name.tld" ,  DNS_ALL , $dns ));

You should found some DNS/resolver error.

Is the NOLOCK (Sql Server hint) bad practice?

As a professional Developer I'd say it depends. But I definitely follow GATS and OMG Ponies advice. Know What You are doing, know when it helps and when it hurts and

read hints and other poor ideas

what might make You understand the sql server deeper. I generally follow the rule that SQL Hints are EVIL, but unfortunately I use them every now and then when I get fed up with forcing SQL server do things... But these are rare cases.

luke

Android statusbar icons color

@eOnOe has answered how we can change status bar tint through xml. But we can also change it dynamically in code:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    View decor = getWindow().getDecorView();
    if (shouldChangeStatusBarTintToDark) {
        decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
    } else {
        // We want to change tint color to white again.
        // You can also record the flags in advance so that you can turn UI back completely if
        // you have set other flags before, such as translucent or full screen.
        decor.setSystemUiVisibility(0);
    }
}

Cannot open output file, permission denied

I had the same Problem. Just rename your .CPP file to other name and try it again. It worked for me.

C# Creating an array of arrays

What you need to do is this:

int[] list1 = new int[4] { 1, 2, 3, 4};
int[] list2 = new int[4] { 5, 6, 7, 8};
int[] list3 = new int[4] { 1, 3, 2, 1 };
int[] list4 = new int[4] { 5, 4, 3, 2 };

int[][] lists = new int[][] {  list1 ,  list2 ,  list3 ,  list4  };

Another alternative would be to create a List<int[]> type:

List<int[]> data=new List<int[]>(){list1,list2,list3,list4};

Why does Python code use len() function instead of a length method?

Strings do have a length method: __len__()

The protocol in Python is to implement this method on objects which have a length and use the built-in len() function, which calls it for you, similar to the way you would implement __iter__() and use the built-in iter() function (or have the method called behind the scenes for you) on objects which are iterable.

See Emulating container types for more information.

Here's a good read on the subject of protocols in Python: Python and the Principle of Least Astonishment

Visual Studio: Relative Assembly References Paths

To expand upon Pavel Minaev's original comment - The GUI for Visual Studio supports relative references with the assumption that your .sln is the root of the relative reference. So if you have a solution C:\myProj\myProj.sln, any references you add in subfolders of C:\myProj\ are automatically added as relative references.

To add a relative reference in a separate directory, such as C:/myReferences/myDLL.dll, do the following:

  1. Add the reference in Visual Studio GUI by right-clicking the project in Solution Explorer and selecting Add Reference...
  2. Find the *.csproj where this reference exist and open it in a text editor
  3. Edit the < HintPath > to be equal to

    <HintPath>..\..\myReferences\myDLL.dll</HintPath>

This now references C:\myReferences\myDLL.dll.

Hope this helps.

pip installs packages successfully, but executables not found from command line

In addition to adding python's bin directory to $PATH variable, I also had to change the owner of that directory, to make it work. No idea why I wasn't the owner already.

chown -R ~/Library/Python/

Resolve build errors due to circular dependency amongst classes

Unfortunately, all the previous answers are missing some details. The correct solution is a little bit cumbersome, but this is the only way to do it properly. And it scales easily, handles more complex dependencies as well.

Here's how you can do this, exactly retaining all the details, and usability:

  • the solution is exactly the same as originally intended
  • inline functions still inline
  • users of A and B can include A.h and B.h in any order

Create two files, A_def.h, B_def.h. These will contain only A's and B's definition:

// A_def.h
#ifndef A_DEF_H
#define A_DEF_H

class B;
class A
{
    int _val;
    B *_b;

public:
    A(int val);
    void SetB(B *b);
    void Print();
};
#endif

// B_def.h
#ifndef B_DEF_H
#define B_DEF_H

class A;
class B
{
    double _val;
    A* _a;

public:
    B(double val);
    void SetA(A *a);
    void Print();
};
#endif

And then, A.h and B.h will contain this:

// A.h
#ifndef A_H
#define A_H

#include "A_def.h"
#include "B_def.h"

inline A::A(int val) :_val(val)
{
}

inline void A::SetB(B *b)
{
    _b = b;
    _b->Print();
}

inline void A::Print()
{
    cout<<"Type:A val="<<_val<<endl;
}

#endif

// B.h
#ifndef B_H
#define B_H

#include "A_def.h"
#include "B_def.h"

inline B::B(double val) :_val(val)
{
}

inline void B::SetA(A *a)
{
    _a = a;
    _a->Print();
}

inline void B::Print()
{
    cout<<"Type:B val="<<_val<<endl;
}

#endif

Note that A_def.h and B_def.h are "private" headers, users of A and B should not use them. The public header is A.h and B.h.

Resize font-size according to div size

I was looking for the same funcionality and found this answer. However, I wanted to give you guys a quick update. It's CSS3's vmin unit.

p, li
{
  font-size: 1.2vmin;
}

vmin means 'whichever is smaller between the 1% of the ViewPort's height and the 1% of the ViewPort's width'.

More info on SitePoint

No Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator

I could resolve this problem in Kotlin with help of @JacksonProperty annotation. Usage example for above case would be:

import com.fasterxml.jackson.annotation.JsonProperty
...
data class Station(
     @JacksonProperty("repsol_id") val repsol_id: String,
     @JacksonProperty("name") val name: String,
...

Strip / trim all strings of a dataframe

You can try:

df[0] = df[0].str.strip()

or more specifically for all string columns

non_numeric_columns = list(set(df.columns)-set(df._get_numeric_data().columns))
df[non_numeric_columns] = df[non_numeric_columns].apply(lambda x : str(x).strip())

Heatmap in matplotlib with pcolor?

Someone edited this question to remove the code I used, so I was forced to add it as an answer. Thanks to all who participated in answering this question! I think most of the other answers are better than this code, I'm just leaving this here for reference purposes.

With thanks to Paul H, and unutbu (who answered this question), I have some pretty nice-looking output:

import matplotlib.pyplot as plt
import numpy as np
column_labels = list('ABCD')
row_labels = list('WXYZ')
data = np.random.rand(4,4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data, cmap=plt.cm.Blues)

# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[0])+0.5, minor=False)
ax.set_yticks(np.arange(data.shape[1])+0.5, minor=False)

# want a more natural, table-like display
ax.invert_yaxis()
ax.xaxis.tick_top()

ax.set_xticklabels(row_labels, minor=False)
ax.set_yticklabels(column_labels, minor=False)
plt.show()

And here's the output:

Matplotlib HeatMap

Rails server says port already used, how to kill that process?

For anyone stumbling across this question that is not on a Mac: assuming you know that your server is running on port 3000, you can do this in one shot by executing the following:

fuser -k 3000/tcp

But as Toby has mentioned, the implementation of fuser in Mac OS is rather primitive and this command will not work on mac.

Visual Studio Copy Project

If you want a copy, the fastest way of doing this would be to save the project. Then make a copy of the entire thing on the File System. Go back into Visual Studio and open the copy. From there, I would most likely recommend re-naming the project/solution so that you don't have two of the same name, but that is the fastest way to make a copy.

Oracle - Why does the leading zero of a number disappear when converting it TO_CHAR

Below format try if number is like

ex 1 suppose number like 10.1 if apply below format it will be come as 10.10

ex 2 suppose number like .02 if apply below format it will be come as 0.02

ex 3 suppose number like 0.2 if apply below format it will be come as 0.20

to_char(round(to_number(column_name)/10000000,2),'999999999990D99') as column_name

Python Pandas User Warning: Sorting because non-concatenation axis is not aligned

jezrael's answer is good, but did not answer a question I had: Will getting the "sort" flag wrong mess up my data in any way? The answer is apparently "no", you are fine either way.

from pandas import DataFrame, concat

a = DataFrame([{'a':1,      'c':2,'d':3      }])
b = DataFrame([{'a':4,'b':5,      'd':6,'e':7}])

>>> concat([a,b],sort=False)
   a    c  d    b    e
0  1  2.0  3  NaN  NaN
0  4  NaN  6  5.0  7.0

>>> concat([a,b],sort=True)
   a    b    c  d    e
0  1  NaN  2.0  3  NaN
0  4  5.0  NaN  6  7.0

Why doesn't importing java.util.* include Arrays and Lists?

I have just compile it and it compiles fine without the implicit import, probably you're seeing a stale cache or something of your IDE.

Have you tried compiling from the command line?

I have the exact same version:

here it is

Probably you're thinking the warning is an error.

UPDATE

It looks like you have a Arrays.class file in the directory where you're trying to compile ( probably created before ). That's why the explicit import solves the problem. Try copying your source code to a clean new directory and try again. You'll see there is no error this time. Or, clean up your working directory and remove the Arrays.class

SQL Combine Two Columns in Select Statement

I think this is what you are looking for -

select Address1+Address2 as CompleteAddress from YourTable
where Address1+Address2 like '%YourSearchString%'

To prevent a compound word being created when we append address1 with address2, you can use this -

select Address1 + ' ' + Address2 as CompleteAddress from YourTable 
where Address1 + ' ' + Address2 like '%YourSearchString%'

So, '123 Center St' and 'Apt 3B' will not be '123 Center StApt 3B' but will be '123 Center St Apt 3B'.

Calculate difference in keys contained in two Python dictionaries

Try this to find de intersection, the keys that is in both dictionarie, if you want the keys not found on second dictionarie, just use the not in...

intersect = filter(lambda x, dictB=dictB.keys(): x in dictB, dictA.keys())

Java - using System.getProperty("user.dir") to get the home directory

"user.dir" is the current working directory, not the home directory It is all described here.

http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html

Also, by using \\ instead of File.separator, you will lose portability with *nix system which uses / for file separator.

Python Sets vs Lists

tl;dr

Data structures (DS) are important because they are used to perform operations on data which basically implies: take some input, process it, and give back the output.

Some data structures are more useful than others in some particular cases. Therefore, it is quite unfair to ask which (DS) is more efficient/speedy. It is like asking which tool is more efficient between a knife and fork. I mean all depends on the situation.

Lists

A list is mutable sequence, typically used to store collections of homogeneous items.

Sets

A set object is an unordered collection of distinct hashable objects. It is commonly used to test membership, remove duplicates from a sequence, and compute mathematical operations such as intersection, union, difference, and symmetric difference.

Usage

From some of the answers, it is clear that a list is quite faster than a set when iterating over the values. On the other hand, a set is faster than a list when checking if an item is contained within it. Therefore, the only thing you can say is that a list is better than a set for some particular operations and vice-versa.

How to install lxml on Ubuntu

Since you're on Ubuntu, don't bother with those source packages. Just install those development packages using apt-get.

apt-get install libxml2-dev libxslt1-dev python-dev

If you're happy with a possibly older version of lxml altogether though, you could try

apt-get install python-lxml

and be done with it. :)

ipynb import another ipynb file

It is really simple in newer Jupyter:

%run MyOtherNotebook.ipynb

How does one use the onerror attribute of an img element

This is actually tricky, especially if you plan on returning an image url for use cases where you need to concatenate strings with the onerror condition image URL, e.g. you might want to programatically set the url parameter in CSS.

The trick is that image loading is asynchronous by nature so the onerror doesn't happen sunchronously, i.e. if you call returnPhotoURL it immediately returns undefined bcs the asynchronous method of loading/handling the image load just began.

So, you really need to wrap your script in a Promise then call it like below. NOTE: my sample script does some other things but shows the general concept:

returnPhotoURL().then(function(value){
    doc.getElementById("account-section-image").style.backgroundImage = "url('" + value + "')";
}); 


function returnPhotoURL(){
    return new Promise(function(resolve, reject){
        var img = new Image();
        //if the user does not have a photoURL let's try and get one from gravatar
        if (!firebase.auth().currentUser.photoURL) {
            //first we have to see if user han an email
            if(firebase.auth().currentUser.email){
                //set sign-in-button background image to gravatar url
                img.addEventListener('load', function() {
                    resolve (getGravatar(firebase.auth().currentUser.email, 48));
                }, false);
                img.addEventListener('error', function() {
                    resolve ('//rack.pub/media/fallbackImage.png');
                }, false);            
                img.src = getGravatar(firebase.auth().currentUser.email, 48);
            } else {
                resolve ('//rack.pub/media/fallbackImage.png');
            }
        } else {
            img.addEventListener('load', function() {
                resolve (firebase.auth().currentUser.photoURL);
            }, false);
            img.addEventListener('error', function() {
                resolve ('https://rack.pub/media/fallbackImage.png');
            }, false);      
            img.src = firebase.auth().currentUser.photoURL;
        }
    });
}

Get rid of "The value for annotation attribute must be a constant expression" message

This is what a constant expression in Java looks like:

package com.mycompany.mypackage;

public class MyLinks {
  // constant expression
  public static final String GUESTBOOK_URL = "/guestbook";
}

You can use it with annotations as following:

import com.mycompany.mypackage.MyLinks;

@WebServlet(urlPatterns = {MyLinks.GUESTBOOK_URL})
public class GuestbookServlet extends HttpServlet {
  // ...
}

html cellpadding the left side of a cell

I would suggest using inline CSS styling.

<table border="1" style="padding-right: 10px;">
<tr>
<td>Content</td>
</tr>
</table>

or

<table border="1">
<tr style="padding-right: 10px;">
<td>Content</td>
</tr>
</table>

or

<table border="1">
<tr>
<td style="padding-right: 10px;">Content</td>
</tr>
</table>

I don't quite follow what you need, but this is what I would do, assuming I understand you needs.

How to print like printf in Python3?

A simpler one.

def printf(format, *values):
    print(format % values )

Then:

printf("Hello, this is my name %s and my age %d", "Martin", 20)

Can two Java methods have same name with different return types?

Only, if they accept different parameters. If there are no parameters, then you must have different names.

int doSomething(String s);
String doSomething(int); // this is fine


int doSomething(String s);
String doSomething(String s); // this is not

How to send multiple data fields via Ajax?

I am new to AJAX and I have tried this and it works well.

function q1mrks(country,m) {
  // alert("hellow");
  if (country.length==0) {
    //alert("hellow");
    document.getElementById("q1mrks").innerHTML="";
    return;
  }
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else {
    // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
      document.getElementById("q1mrks").innerHTML=xmlhttp.responseText;
    }
  }
  xmlhttp.open("GET","../location/cal_marks.php?q1mrks="+country+"&marks="+m,true);
  //mygetrequest.open("GET", "basicform.php?name="+namevalue+"&age="+agevalue, true)
  xmlhttp.send();
}

How to play or open *.mp3 or *.wav sound file in c++ program?

Use a library to (a) read the sound file(s) and (b) play them back. (I'd recommend trying both yourself at some point in your spare time, but...)

Perhaps (*nix):

Windows: DirectX.

How does numpy.newaxis work and when to use it?

newaxis object in the selection tuple serves to expand the dimensions of the resulting selection by one unit-length dimension.

It is not just conversion of row matrix to column matrix.

Consider the example below:

In [1]:x1 = np.arange(1,10).reshape(3,3)
       print(x1)
Out[1]: array([[1, 2, 3],
               [4, 5, 6],
               [7, 8, 9]])

Now lets add new dimension to our data,

In [2]:x1_new = x1[:,np.newaxis]
       print(x1_new)
Out[2]:array([[[1, 2, 3]],

              [[4, 5, 6]],

              [[7, 8, 9]]])

You can see that newaxis added the extra dimension here, x1 had dimension (3,3) and X1_new has dimension (3,1,3).

How our new dimension enables us to different operations:

In [3]:x2 = np.arange(11,20).reshape(3,3)
       print(x2)
Out[3]:array([[11, 12, 13],
              [14, 15, 16],
              [17, 18, 19]]) 

Adding x1_new and x2, we get:

In [4]:x1_new+x2
Out[4]:array([[[12, 14, 16],
               [15, 17, 19],
               [18, 20, 22]],

              [[15, 17, 19],
               [18, 20, 22],
               [21, 23, 25]],

              [[18, 20, 22],
               [21, 23, 25],
               [24, 26, 28]]])

Thus, newaxis is not just conversion of row to column matrix. It increases the dimension of matrix, thus enabling us to do more operations on it.

Could not reserve enough space for object heap to start JVM

It looks like the machine you're trying to run this on has only 256 MB memory.

Maybe the JVM tries to allocate a large, contiguous block of 64 MB memory. The 192 MB that you have free might be fragmented into smaller pieces, so that there is no contiguous block of 64 MB free to allocate.

Try starting your Java program with a smaller heap size, for example:

java -Xms16m ...

Warning about `$HTTP_RAW_POST_DATA` being deprecated

Well, if there's anyone out there on a shared hosting and with no access to php.ini file, you can set this line of code at the very top of your PHP files:

ini_set('always_populate_raw_post_data', -1);

Works more of the same. I hope it saves someone some debugging time :)

Get a JSON object from a HTTP response

Do this to get the JSON

String json = EntityUtils.toString(response.getEntity());

More details here : get json from HttpResponse

Tools: replace not replacing in Android manifest

 tools:replace="android:supportsRtl,android:allowBackup,icon,label">

Is there a better way to refresh WebView?

try this :

mWebView.loadUrl(mWebView.getUrl().toString());

Cannot connect to repo with TortoiseSVN

I faced similar issue while doing svn update.

The approach which worked for me is to rename C:\Users\user\AppData\Roaming\TortoiseSVN folder to TortoiseSVN_bkp folder and then tried svn update again. This time I was able to connect to repository and it got updated.

How do I determine if a port is open on a Windows server?

Assuming that it's a TCP (rather than UDP) port that you're trying to use:

  1. On the server itself, use netstat -an to check to see which ports are listening.

  2. From outside, just use telnet host port (or telnet host:port on Unix systems) to see if the connection is refused, accepted, or timeouts.

On that latter test, then in general:

  • connection refused means that nothing is running on that port
  • accepted means that something is running on that port
  • timeout means that a firewall is blocking access

On Windows 7 or Windows Vista the default option 'telnet' is not recognized as an internal or external command, operable program or batch file. To solve this, just enable it: Click *Start** → Control PanelProgramsTurn Windows Features on or off. In the list, scroll down and select Telnet Client and click OK.

Electron: jQuery is not defined

I face the same issue and this worked for me!

Install jQuery using npm

$ npm install jquery

Then include jQuery in one of the following ways.

Using script tag

<script>window.$ = window.jQuery = require('jquery');</script>

Using Babel

import $ from 'jquery';

Using Webpack

const $ = require('jquery');

Table 'mysql.user' doesn't exist:ERROR

Looks like something is messed up with your MySQL installation. The mysql.user table should definitely exist. Try running the command below on your server to create the tables in the database called mysql:

mysql_install_db

If that doesn't work, maybe the permissions on your MySQL data directory are messed up. Look at a "known good" installation as a reference for what the permissions should be.

You could also try re-installing MySQL completely.

JFrame Maximize window

I ended up using this code:

public void setMaximized(boolean maximized){
    if(maximized){
        DisplayMode mode = this.getGraphicsConfiguration().getDevice().getDisplayMode();
        Insets insets = Toolkit.getDefaultToolkit().getScreenInsets(this.getGraphicsConfiguration());
        this.setMaximizedBounds(new Rectangle(
                mode.getWidth() - insets.right - insets.left, 
                mode.getHeight() - insets.top - insets.bottom
        ));
        this.setExtendedState(this.getExtendedState() | JFrame.MAXIMIZED_BOTH);
    }else{
        this.setExtendedState(JFrame.NORMAL);
    }
}

This options worked the best of all the options, including multiple monitor support. The only flaw this has is that the taskbar offset is used on all monitors is some configurations.

Fatal error: Call to a member function prepare() on null

@delato468 comment must be listed as a solution as it worked for me.

In addition to defining the parameter, the user must pass it too at the time of calling the function

fetch_data(PDO $pdo, $cat_id)

Check if a value is in an array or not with Excel VBA

Use Match() function in excel VBA to check whether the value exists in an array.

Sub test()
    Dim x As Long

    vars1 = Array("Abc", "Xyz", "Examples")
    vars2 = Array("Def", "IJK", "MNO")

    If IsNumeric(Application.Match(Range("A1").Value, vars1, 0)) Then
        x = 1
    ElseIf IsNumeric(Application.Match(Range("A1").Value, vars2, 0)) Then
        x = 1
    End If

    MsgBox x
End Sub

What are the lengths of Location Coordinates, latitude and longitude?

If the latitude coordinate is reported as -6.3572375290155 or -63.572375290155 in decimal degrees then you could round-off and store up to 6 decimal places for 10 cm (or 0.1 meters) precision.

Overview

The valid range of latitude in degrees is -90 and +90 for the southern and northern hemisphere respectively. Longitude is in the range -180 and +180 specifying coordinates west and east of the Prime Meridian, respectively.

For reference, the Equator has a latitude of 0°, the North pole has a latitude of 90° north (written 90° N or +90°), and the South pole has a latitude of -90°.

The Prime Meridian has a longitude of 0° that goes through Greenwich, England. The International Date Line (IDL) roughly follows the 180° longitude. A longitude with a positive value falls in the eastern hemisphere and the negative value falls in the western hemisphere.

Decimal degrees precision

Six (6) decimal places precision in coordinates using decimal degrees notation is at a 10 cm (or 0.1 meters) resolution. Each .000001 difference in coordinate decimal degree is approximately 10 cm in length. For example, the imagery of Google Earth and Google Maps is typically at the 1-meter resolution, and some places have a higher resolution of 1 inch per pixel. One meter resolution can be represented using 5 decimal places so more than 6 decimal places are extraneous for that resolution. The distance between longitudes at the equator is the same as latitude, but the distance between longitudes reaches zero at the poles as the lines of meridian converge at that point.

For millimeter (mm) precision then represent lat/lon with 8 decimal places in decimal degrees format. Since most applications don't need that level of precision 6 decimal places is sufficient for most cases.

In the other direction, whole decimal degrees represent a distance of ~111 km (or 60 nautical miles) and a 0.1 decimal degree difference represents a ~11 km distance.

Here is a table of # decimal places difference in latitude with the delta degrees and the estimated distance in meters using 0,0 as the starting point.

Decimal places Decimal degrees Distance (meters)
1 0.10000000 11,057.43 11 km
2 0.01000000 1,105.74 1 km
3 0.00100000 110.57
4 0.00010000 11.06
5 0.00001000 1.11
6 0.00000100 0.11 11 cm
7 0.00000010 0.01 1 cm
8 0.00000001 0.001 1 mm

Degrees-minute-second (DMS) representation

For DMS notation 1 arc second = 1/60/60 degree = ~30 meter length and 0.1 arc sec delta is ~3 meters.

Example:

  • 0° 0' 0" W, 0° 0' 0" N ? 0° 0' 0" W, 0° 0' 1" N ? 30.715 meters
  • 0° 0' 0" W, 0° 0' 0" N ? 0° 0' 0" W, 0° 0' 0.1" N ? 3.0715 meters

1 arc minute = 1/60 degree = ~2000m (2km)


Update:

Here is an amusing comic strip about coordinate precision.

Where can I view Tomcat log files in Eclipse?

I'm not sure if you were after catalina.out or one of the other logs produced by Tomcat.

But, if you're after the catalina.out log file then follow the directions below:

  • In the servers tab, double-click on the Tomcat Server. You will get a screen called Overview.

  • Click on "Open launch configuration". Click on the "Common" tab.

  • Towards the bottom of the screen you can check the "File" checkbox and then specify a file that can be used to log your console (catalina.out) output.

  • Finally, restart the Tomcat server.

Creating stored procedure and SQLite?

SQLite has had to sacrifice other characteristics that some people find useful, such as high concurrency, fine-grained access control, a rich set of built-in functions, stored procedures, esoteric SQL language features, XML and/or Java extensions, tera- or peta-byte scalability, and so forth

Source : Appropriate Uses For SQLite

How to disable anchor "jump" when loading a page?

I used dave1010's solution, but it was a bit jumpy when I put it inside the $().ready function. So I did this: (not inside the $().ready)

    if (location.hash) {               // do the test straight away
        window.scrollTo(0, 0);         // execute it straight away
        setTimeout(function() {
            window.scrollTo(0, 0);     // run it a bit later also for browser compatibility
        }, 1);
    }

How can I format a nullable DateTime with ToString()?

Seeing that you actually want to provide the format I'd suggest to add the IFormattable interface to Smalls extension method like so, that way you don't have the nasty string format concatenation.

public static string ToString<T>(this T? variable, string format, string nullValue = null)
where T: struct, IFormattable
{
  return (variable.HasValue) 
         ? variable.Value.ToString(format, null) 
         : nullValue;          //variable was null so return this value instead   
}

Finding the length of an integer in C

The most efficient way could possibly be to use a fast logarithm based approach, similar to those used to determine the highest bit set in an integer.

size_t printed_length ( int32_t x )
{
    size_t count = x < 0 ? 2 : 1;

    if ( x < 0 ) x = -x;

    if ( x >= 100000000 ) {
        count += 8;
        x /= 100000000;
    }

    if ( x >= 10000 ) {
        count += 4;
        x /= 10000;
    }

    if ( x >= 100 ) {
        count += 2;
        x /= 100;
    }

    if ( x >= 10 )
        ++count;

    return count;
}

This (possibly premature) optimisation takes 0.65s for 20 million calls on my netbook; iterative division like zed_0xff has takes 1.6s, recursive division like Kangkan takes 1.8s, and using floating point functions (Jordan Lewis' code) takes a whopping 6.6s. Using snprintf takes 11.5s, but will give you the size that snprintf requires for any format, not just integers. Jordan reports that the ordering of the timings are not maintained on his processor, which does floating point faster than mine.

The easiest is probably to ask snprintf for the printed length:

#include <stdio.h>

size_t printed_length ( int x )
{
    return snprintf ( NULL, 0, "%d", x );
}

int main ()
{
    int x[] = { 1, 25, 12512, 0, -15 };

    for ( int i = 0; i < sizeof ( x ) / sizeof ( x[0] ); ++i )
        printf ( "%d -> %d\n", x[i], printed_length ( x[i] ) );

    return 0;
}

How to add url parameter to the current url?

function currentUrl() {
    $protocol = strpos(strtolower($_SERVER['SERVER_PROTOCOL']),'https') === FALSE ? 'http' : 'https';
    $host     = $_SERVER['HTTP_HOST'];
    $script   = $_SERVER['SCRIPT_NAME'];
    $params   = $_SERVER['QUERY_STRING'];

    return $protocol . '://' . $host . $script . '?' . $params;
}

Then add your value with something like;

echo currentUrl().'&value=myVal';

"Continue" (to next iteration) on VBScript

Try use While/Wend and Do While / Loop statements...

i = 1
While i < N + 1
Do While true
    [Code]
    If Condition1 Then
       Exit Do
    End If

    [MoreCode]
    If Condition2 Then
       Exit Do
    End If

    [...]

    Exit Do
Loop
Wend

Displaying the Indian currency symbol on a website

JQUERY INR v1.2

A simple jQuery plug-in for convert Rs. to standard Indian rupee symbol through out the web page. Simple to use and simple instillation

The Indian Rupee sign is the currency sign: ? for the Indian Rupee, the official currency of India. Designed by D. Udaya Kumar, it was presented to the public by the Government of India on 15 July 2010,[1] following its selection through an “open” competition among Indian residents. Before its adoption, the most commonly used symbols for the rupee were Rs, Re or, if the text was in an Indian language, an appropriate abbreviation in that language. The new sign relates solely to the Indian rupee; other countries that use a rupee, such as Sri Lanka, Pakistan and Nepal, still use the generic U+20A8 ? rupee sign character. The design resembles both the Devanagari letter "?" (ra) and the Latin capital letter "R", with a double horizontal line at the top.

Instillation:

  1. Download the “jQueryINR_v1.2.zip” and extract.
  2. copy images (“rupee.svg, rupee.gif”) to your images folder.
  3. cope scripts folder to your project path or else copy the .js files to your script folder.
  4. Download the “jQueryINR_v1.2.zip” and extract.
  5. copy images (“rupee.svg, rupee.gif”) to your images folder.
  6. cope scripts folder to your project path or else copy the .js files to your script folder.
  7. Include jQuery min and jQuery Ui to your page first

    eg: NB: use jQuery stable version only

  8. include the “indianRupee_v1.2.js” and “indianRupee_ctrl.js” after the jQuery library eg:

  9. Use Span tag to wrap Rs through out the web it will replace with the symbol eg: Rs 1280000/-

Source:

Pay Him Rs 1280000/-

Pay Him Rs 528500/-

Pay Him Rs 1250/-

Pay Him Rs 1280000/-

Result:

   http://romy.theqtl.com/rupeePlugin/

Plug-in Options:

$("body").indianRupee({ targets:"span",// use as default we can also use [p, div, h1 , li etc...] vector:"on"//[on/off] of [true/false] NB: {vector not support in Internet Explore } });

Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

If you're running on a macOS it's just easier to first check go to 'System Preferences' and see if MySQL is running or not.

Add a UIView above all, even the navigation bar

[self.navigationController.navigationBar.layer setZPosition:-0.1];
UIView *view = [[UIView alloc]initWithFrame:CGRectMake(10, 20, 35, 35)];
[view setBackgroundColor:[UIColor redColor]];
[self.navigationController.view addSubview:view];
[self.navigationController.view bringSubviewToFront:view];
self.navigationController.view.clipsToBounds = NO;
[self.navigationController.navigationBar.layer setZPosition:0.0];

enter image description here

How to create a collapsing tree table in html/css/js?

HTML 5 allows summary tag, details element. That can be used to view or hide (collapse/expand) a section. Link

Node.js Error: Cannot find module express

Digging up an old thread here BUT I had this same error and I resolved by navigating to the directory my NodeApp resides in and running npm install -d

How do I convert from int to String?

Normal ways would be Integer.toString(i) or String.valueOf(i).

The concatenation will work, but it is unconventional and could be a bad smell as it suggests the author doesn't know about the two methods above (what else might they not know?).

Java has special support for the + operator when used with strings (see the documentation) which translates the code you posted into:

StringBuilder sb = new StringBuilder();
sb.append("");
sb.append(i);
String strI = sb.toString();

at compile-time. It's slightly less efficient (sb.append() ends up calling Integer.getChars(), which is what Integer.toString() would've done anyway), but it works.

To answer Grodriguez's comment: ** No, the compiler doesn't optimise out the empty string in this case - look:

simon@lucifer:~$ cat TestClass.java
public class TestClass {
  public static void main(String[] args) {
    int i = 5;
    String strI = "" + i;
  }
}
simon@lucifer:~$ javac TestClass.java && javap -c TestClass
Compiled from "TestClass.java"
public class TestClass extends java.lang.Object{
public TestClass();
  Code:
   0:    aload_0
   1:    invokespecial    #1; //Method java/lang/Object."<init>":()V
   4:    return

public static void main(java.lang.String[]);
  Code:
   0:    iconst_5
   1:    istore_1

Initialise the StringBuilder:

   2:    new    #2; //class java/lang/StringBuilder
   5:    dup
   6:    invokespecial    #3; //Method java/lang/StringBuilder."<init>":()V

Append the empty string:

   9:    ldc    #4; //String
   11:    invokevirtual    #5; //Method java/lang/StringBuilder.append:
(Ljava/lang/String;)Ljava/lang/StringBuilder;

Append the integer:

   14:    iload_1
   15:    invokevirtual    #6; //Method java/lang/StringBuilder.append:
(I)Ljava/lang/StringBuilder;

Extract the final string:

   18:    invokevirtual    #7; //Method java/lang/StringBuilder.toString:
()Ljava/lang/String;
   21:    astore_2
   22:    return
}

There's a proposal and ongoing work to change this behaviour, targetted for JDK 9.

Find out how much memory is being used by an object in Python

This must be used with care because an override on the objects __sizeof__ might be misleading.

Using the bregman.suite, some tests with sys.getsizeof output a copy of an array object (data) in an object instance as being bigger than the object itself (mfcc).

>>> mfcc = MelFrequencyCepstrum(filepath, params)
>>> data = mfcc.X[:]
>>> sys.getsizeof(mfcc)
64
>>> sys.getsizeof(mfcc.X)
>>>80
>>> sys.getsizeof(data)
80
>>> mfcc
<bregman.features.MelFrequencyCepstrum object at 0x104ad3e90>

Regex empty string or email

I prefer /^\s+$|^$/gi to match empty and empty spaces.

_x000D_
_x000D_
console.log("  ".match(/^\s+$|^$/gi));_x000D_
console.log("".match(/^\s+$|^$/gi));
_x000D_
_x000D_
_x000D_

JavaScript open in a new window, not tab

Interestingly, I found that if you pass in an empty string (as opposed to a null string, or a list of properties) for the third attribute of window.open, it would open in a new tab for Chrome, Firefox, and IE. If absent, the behavior was different.

So, this is my new call:

 window.open(url, windowName, '');

Powershell's Get-date: How to get Yesterday at 22:00 in a variable?

When I was to get yesterday with just the date in the format Year/Month/Day I use:

$Variable = Get-Date((get-date ).AddDays(-1))  -Format "yyyy-MM-dd"

How to provide shadow to Button

Sample 9 patch image with shadow

After a lots of research I found an easy method.

Create a 9 patch image and apply it as button or any other view's background.

You can create a 9 patch image with shadow using this website.

Put the 9 patch image in your drawable directory and apply it as the background for the button.

mButton.setBackground(ContextCompat.getDrawable(mContext, R.drawable.your_9_patch_image);

Matplotlib (pyplot) savefig outputs blank image

let's me give a more detail example:

import numpy as np
import matplotlib.pyplot as plt


def draw_result(lst_iter, lst_loss, lst_acc, title):
    plt.plot(lst_iter, lst_loss, '-b', label='loss')
    plt.plot(lst_iter, lst_acc, '-r', label='accuracy')

    plt.xlabel("n iteration")
    plt.legend(loc='upper left')
    plt.title(title)
    plt.savefig(title+".png")  # should before plt.show method

    plt.show()


def test_draw():
    lst_iter = range(100)
    lst_loss = [0.01 * i + 0.01 * i ** 2 for i in xrange(100)]
    # lst_loss = np.random.randn(1, 100).reshape((100, ))
    lst_acc = [0.01 * i - 0.01 * i ** 2 for i in xrange(100)]
    # lst_acc = np.random.randn(1, 100).reshape((100, ))
    draw_result(lst_iter, lst_loss, lst_acc, "sgd_method")


if __name__ == '__main__':
    test_draw()

enter image description here

Rails - Could not find a JavaScript runtime?

Installing a javascript runtime library such as nodejs solves this

To install nodejs on ubuntu, you can type the following command in the terminal:

sudo apt-get install nodejs

To install nodejs on systems using yum, type the following in the terminal:

yum -y install nodejs

How can I save application settings in a Windows Forms application?

As far as I can tell, .NET does support persisting settings using the built-in application settings facility:

The Application Settings feature of Windows Forms makes it easy to create, store, and maintain custom application and user preferences on the client computer. With Windows Forms application settings, you can store not only application data such as database connection strings, but also user-specific data, such as user application preferences. Using Visual Studio or custom managed code, you can create new settings, read them from and write them to disk, bind them to properties on your forms, and validate settings data prior to loading and saving. - http://msdn.microsoft.com/en-us/library/k4s6c3a0.aspx

How can I make a float top with CSS?

You might be able to do something with sibling selectors e.g.:

div + div + div + div{
float: left
}

Not tried it but this might float the 4th div left perhaps doing what you want. Again not fully supported.

Interfaces with static fields in java for sharing 'constants'

According to JVM specification, fields and methods in a Interface can have only Public, Static, Final and Abstract. Ref from Inside Java VM

By default, all the methods in interface is abstract even tough you didn't mention it explicitly.

Interfaces are meant to give only specification. It can not contain any implementations. So To avoid implementing classes to change the specification, it is made final. Since Interface cannot be instantiated, they are made static to access the field using interface name.

How to switch from POST to GET in PHP CURL

CURL request by default is GET, you don't have to set any options to make a GET CURL request.

Access the css ":after" selector with jQuery

You can't manipulate :after, because it's not technically part of the DOM and therefore is inaccessible by any JavaScript. But you can add a new class with a new :after specified.

CSS:

.pageMenu .active.changed:after { 
/* this selector is more specific, so it takes precedence over the other :after */
    border-top-width: 22px;
    border-left-width: 22px;
    border-right-width: 22px;
}

JS:

$('.pageMenu .active').toggleClass('changed');

UPDATE: while it's impossible to directly modify the :after content, there are ways to read and/or override it using JavaScript. See "Manipulating CSS pseudo-elements using jQuery (e.g. :before and :after)" for a comprehensive list of techniques.

git error: failed to push some refs to remote

do these

git rm --cached *
git add .
git commit -m"upload"
git push --set-upstream origin master

Happy coding!

Get file content from URL?

$url = "https://chart.googleapis....";
$json = file_get_contents($url);

Now you can either echo the $json variable, if you just want to display the output, or you can decode it, and do something with it, like so:

$data = json_decode($json);
var_dump($data);

set default schema for a sql query

For Oracle, please use this simple command:

ALTER SESSION SET current_schema = your-schema-without-quotes;

VBA Excel Provide current Date in Text box

The easy way to do this is to put the Date function you want to use in a Cell, and link to that cell from the textbox with the LinkedCell property.

From VBA you might try using:

textbox.Value = Format(Date(),"mm/dd/yy")

Handling multiple IDs in jQuery

Solution:

To your secondary question

var elem1 = $('#elem1'),
    elem2 = $('#elem2'),
    elem3 = $('#elem3');

You can use the variable as the replacement of selector.

elem1.css({'display':'none'}); //will work

In the below case selector is already stored in a variable.

$(elem1,elem2,elem3).css({'display':'none'}); // will not work

How to change date format in JavaScript

Use your mydate object and call getMonth() and getFullYear()

See this for more info: http://www.w3schools.com/jsref/jsref_obj_date.asp