SyntaxFix.com - Programming Questions & Answers Hub For Beginners


Some Of The Best Answers From Latest Asked Questions

Add 10 seconds to a Date

I have a couple of new variants

  1. var t = new Date(Date.now() + 10000);
  2. var t = new Date(+new Date() + 10000);

'tuple' object does not support item assignment

A tuple is immutable and thus you get the error you posted.

>>> pixels = [1, 2, 3]
>>> pixels[0] = 5
>>> pixels = (1, 2, 3)
>>> pixels[0] = 5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

In your specific case, as correctly pointed out in other answers, you should write:

pixel = (pixel[0] + 20, pixel[1], pixel[2])

Java: Array with loop

int[] nums = new int[100];

int sum = 0;

// Fill it with numbers using a for-loop for (int i = 0; i < nums.length; i++)

{ 
     nums[i] = i + 1;
    sum += n;
}

System.out.println(sum);

How can I add a custom HTTP header to ajax request with js or jQuery?

You can also do this without using jQuery. Override XMLHttpRequest's send method and add the header there:

XMLHttpRequest.prototype.realSend = XMLHttpRequest.prototype.send;
var newSend = function(vData) {
    this.setRequestHeader('x-my-custom-header', 'some value');
    this.realSend(vData);
};
XMLHttpRequest.prototype.send = newSend;

What can lead to "IOError: [Errno 9] Bad file descriptor" during os.system()?

You can get this error if you use wrong mode when opening the file. For example:

    with open(output, 'wb') as output_file:
        print output_file.read()

In that code, I want to read the file, but I use mode wb instead of r or r+

How to add dll in c# project

In the right hand column under your solution explorer, you can see next to the reference to "Science" its marked as a warning. Either that means it cant find it, or its objecting to it for some other reason. While this is the case and your code requires it (and its not just in the references list) it wont compile.

Please post the warning message, we can try help you further.

Regex pattern to match at least 1 number and 1 character in a string

Why not first apply the whole test, and then add individual tests for characters and numbers? Anyway, if you want to do it all in one regexp, use positive lookahead:

/^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$/

How to check if a file exists from a url

I've just found this solution:

if(@getimagesize($remoteImageURL)){
    //image exists!
}else{
    //image does not exist.
}

Source: http://www.dreamincode.net/forums/topic/11197-checking-if-file-exists-on-remote-server/

The 'packages' element is not declared

Change the node to and create a file, packages.xsd, in the same folder (and include it in the project) with the following contents:

<?xml version="1.0" encoding="utf-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"
      targetNamespace="urn:packages" xmlns="urn:packages">
  <xs:element name="packages">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="package" maxOccurs="unbounded">
          <xs:complexType>
            <xs:attribute name="id" type="xs:string" use="required" />
            <xs:attribute name="version" type="xs:string" use="required" />
            <xs:attribute name="targetFramework" type="xs:string" use="optional" />
            <xs:attribute name="allowedVersions" type="xs:string" use="optional" />
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

How to use nanosleep() in C? What are `tim.tv_sec` and `tim.tv_nsec`?

500000 microseconds are 500000000 nanoseconds. You only wait for 500 ns = 0.5 µs.

In java how to get substring from a string till a character c?

This could help:

public static String getCorporateID(String fileName) {

    String corporateId = null;

    try {
        corporateId = fileName.substring(0, fileName.indexOf("_"));
        // System.out.println(new Date() + ": " + "Corporate:
        // "+corporateId);
        return corporateId;
    } catch (Exception e) {
        corporateId = null;
        e.printStackTrace();
    }

    return corporateId;
}

How to change column datatype from character to numeric in PostgreSQL 8.4

Step 1: Add new column with integer or numeric as per your requirement

Step 2: Populate data from varchar column to numeric column

Step 3: drop varchar column

Step 4: change new numeric column name as per old varchar column

asp.net mvc3 return raw html to view

Simply create a property in your view model of type MvcHtmlString. You won't need to Html.Raw it then either.

What's the difference between subprocess Popen and call (how can I use them)?

There are two ways to do the redirect. Both apply to either subprocess.Popen or subprocess.call.

  1. Set the keyword argument shell = True or executable = /path/to/the/shell and specify the command just as you have it there.

  2. Since you're just redirecting the output to a file, set the keyword argument

    stdout = an_open_writeable_file_object
    

    where the object points to the output file.

subprocess.Popen is more general than subprocess.call.

Popen doesn't block, allowing you to interact with the process while it's running, or continue with other things in your Python program. The call to Popen returns a Popen object.

call does block. While it supports all the same arguments as the Popen constructor, so you can still set the process' output, environmental variables, etc., your script waits for the program to complete, and call returns a code representing the process' exit status.

returncode = call(*args, **kwargs) 

is basically the same as calling

returncode = Popen(*args, **kwargs).wait()

call is just a convenience function. It's implementation in CPython is in subprocess.py:

def call(*popenargs, timeout=None, **kwargs):
    """Run command with arguments.  Wait for command to complete or
    timeout, then return the returncode attribute.

    The arguments are the same as for the Popen constructor.  Example:

    retcode = call(["ls", "-l"])
    """
    with Popen(*popenargs, **kwargs) as p:
        try:
            return p.wait(timeout=timeout)
        except:
            p.kill()
            p.wait()
            raise

As you can see, it's a thin wrapper around Popen.

How do I get the entity that represents the current user in Symfony2?

Symfony 4+, 2019+ Approach

In symfony 4 (probably 3.3 also, but only real-tested in 4) you can inject the Security service via auto-wiring in the controller like this:

<?php

use Symfony\Component\Security\Core\Security;

class SomeClass
{
    /**
     * @var Security
     */
    private $security;

    public function __construct(Security $security)
    {
       $this->security = $security;
    }

    public function privatePage() : Response
    {
        $user = $this->security->getUser(); // null or UserInterface, if logged in
        // ... do whatever you want with $user
    }
}

Symfony 2- Approach

As @ktolis says, you first have to configure your /app/config/security.yml.

Then with

$user = $this->get('security.token_storage')->getToken()->getUser();
$user->getUsername();

should be enougth!

$user is your User Object! You don't need to query it again.

Find out the way to set up your providers in security.yml from Sf2 Documentation and try again.

Best luck!

Fatal error: Maximum execution time of 300 seconds exceeded

Try something like the following in your script:

set_time_limit(1200);

Should IBOutlets be strong or weak under ARC?

I don't see any problem with that. Pre-ARC, I've always made my IBOutlets assign, as they're already retained by their superviews. If you make them weak, you shouldn't have to nil them out in viewDidUnload, as you point out.

One caveat: You can support iOS 4.x in an ARC project, but if you do, you can't use weak, so you'd have to make them assign, in which case you'd still want to nil the reference in viewDidUnload to avoid a dangling pointer. Here's an example of a dangling pointer bug I've experienced:

A UIViewController has a UITextField for zip code. It uses CLLocationManager to reverse geocode the user's location and set the zip code. Here's the delegate callback:

-(void)locationManager:(CLLocationManager *)manager
   didUpdateToLocation:(CLLocation *)newLocation
          fromLocation:(CLLocation *)oldLocation {
    Class geocoderClass = NSClassFromString(@"CLGeocoder");
    if (geocoderClass && IsEmpty(self.zip.text)) {
        id geocoder = [[geocoderClass alloc] init];
        [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
            if (self.zip && IsEmpty(self.zip.text)) {
                self.zip.text = [[placemarks objectAtIndex:0] postalCode];
            }
        }];    
    }
    [self.locationManager stopUpdatingLocation];
}

I found that if I dismissed this view at the right time and didn't nil self.zip in viewDidUnload, the delegate callback could throw a bad access exception on self.zip.text.

Where do I download JDBC drivers for DB2 that are compatible with JDK 1.5?

I know its late but i recently ran into this situation. After wasting entire day I finally found the solution. I am suprised that I got this info on oracle's website whereas this seems nowhere to be found on IBM's website.

If you want to use JDBC drivers for DB2 that are compatible with JDK 1.5 or 1.4 , you need to use the jar db2jcc.jar, which is available in SQLLIB/java/ folder of your db2 installation.

Git diff against a stash

She the list of stash

git stash list 
stash@{0}: WIP on feature/blabla: 830335224fa Name Commit
stash@{1}: WIP on feature/blabla2: 830335224fa Name Commit 2

So get the stash number and do:

You can do:

 git stash show -p stash@{1}

But if you want a diff (this is different to show the stash, that's why I write this answer. Diff consider the current code in your branch and show just show what you will apply)

You can use:

git diff stash@{0}

or

git diff stash@{0} <branch name>

Another interesting thing to do is:

git stash apply
git stash apply stash@{10}

This applies the stash without removing it from the list, you can git checkout . to remove those change or if you are happy git stash drop stash@{10} to remove a stash from the list.

From here I never recommend to use git stash pop and use a combination of git stash apply and git stash drop If you apply a stash in the wrong branch... well sometimes is difficult to recover your code.

How to put spacing between floating divs?

Is it not just a case of applying an appropriate class to each div?

For example:

.firstRowDiv { margin:0px 10px 10px 0px; }
.secondRowDiv { margin:0px 10px 0px 0px; }

This depends on if you know in advance which div to apply which class to.

Can Twitter Bootstrap alerts fade in as well as out?

None of the current answers worked for me. I'm using Bootstrap 3.

I liked what Rob Vermeer was doing and started from his response.

For a fade in and then fade out effect, I just used wrote the following function and used jQuery:

Html on my page to add the alert(s) to:

        <div class="alert-messages text-center">
        </div>

Javascript function to show and dismiss the alert.

function showAndDismissAlert(type, message) {
    var htmlAlert = '<div class="alert alert-' + type + '">' + message + '</div>';

    // Prepend so that alert is on top, could also append if we want new alerts to show below instead of on top.
    $(".alert-messages").prepend(htmlAlert);

    // Since we are prepending, take the first alert and tell it to fade in and then fade out.
    // Note: if we were appending, then should use last() instead of first()
    $(".alert-messages .alert").first().hide().fadeIn(200).delay(2000).fadeOut(1000, function () { $(this).remove(); });
}

Then, to show and dismiss the alert, just call the function like this:

    showAndDismissAlert('success', 'Saved Successfully!');
    showAndDismissAlert('danger', 'Error Encountered');
    showAndDismissAlert('info', 'Message Received');

As a side note, I styled the div.alert-messages fixed on top:

    <style>
    div.alert-messages {
        position: fixed;
        top: 50px;
        left: 25%;
        right: 25%;
        z-index: 7000;
    }
    </style>

How to wait for 2 seconds?

The documentation for WAITFOR() doesn't explicitly lay out the required string format.

This will wait for 2 seconds:

WAITFOR DELAY '00:00:02';

The format is hh:mi:ss.mmm.

How to use the read command in Bash?

Other bash alternatives that do not involve a subshell:

read str <<END             # here-doc
hello
END

read str <<< "hello"       # here-string

read str < <(echo hello)   # process substitution

Bundling data files with PyInstaller (--onefile)

I found the existing answers confusing, and took a long time to work out where the problem is. Here's a compilation of everything I found.

When I run my app, I get an error Failed to execute script foo (if foo.py is the main file). To troubleshoot this, don't run PyInstaller with --noconsole (or edit main.spec to change console=False => console=True). With this, run the executable from a command-line, and you'll see the failure.

The first thing to check is that it's packaging up your extra files correctly. You should add tuples like ('x', 'x') if you want the folder x to be included.

After it crashes, don't click OK. If you're on Windows, you can use Search Everything. Look for one of your files (eg. sword.png). You should find the temporary path where it unpacked the files (eg. C:\Users\ashes999\AppData\Local\Temp\_MEI157682\images\sword.png). You can browse this directory and make sure it included everything. If you can't find it this way, look for something like main.exe.manifest (Windows) or python35.dll (if you're using Python 3.5).

If the installer includes everything, the next likely problem is file I/O: your Python code is looking in the executable's directory, instead of the temp directory, for files.

To fix that, any of the answers on this question work. Personally, I found a mixture of them all to work: change directory conditionally first thing in your main entry-point file, and everything else works as-is:

if hasattr(sys, '_MEIPASS'): os.chdir(sys._MEIPASS)

How can I return pivot table output in MySQL?

For MySQL you can directly put conditions in SUM() function and it will be evaluated as Boolean 0 or 1 and thus you can have your count based on your criteria without using IF/CASE statements

SELECT
    company_name,  
    SUM(action = 'EMAIL')AS Email,
    SUM(action = 'PRINT' AND pagecount = 1)AS Print1Pages,
    SUM(action = 'PRINT' AND pagecount = 2)AS Print2Pages,
    SUM(action = 'PRINT' AND pagecount = 3)AS Print3Pages
FROM t
GROUP BY company_name

DEMO

Convert string to number and add one

a nice way from http://try.jquery.com/levels/4/challenges/16 :

adding a + before the string without using parseInt and parseFloat and radix and errors i faced for missing radix parameter

sample

var number= +$('#inputForm').val();

Return only string message from Spring MVC 3 Controller

Although, @Tomasz is absolutely right there is another way:

@RequestMapping(value="/controller", method=GET)
public void foo(HttpServletResponse res) {
    try {       
        PrintWriter out = res.getWriter();
        out.println("Hello, world!");
        out.close();
    } catch (IOException ex) { 
        ...
    }
}

but the first method is preferable. You can use this method if you want to return response with custom content type or return binary type (file, etc...);

How to get TimeZone from android mobile?

According to http://developer.android.com/reference/android/text/format/Time.html you should be using Time.getCurrentTimezone() to retrieve the current timezone of the device.

Find out free space on tablespace

Here is a query used by Oracle SQL Developer in its Tablespaces view

select a.tablespace_name as "Tablespace Name",
       round(a.bytes_alloc / 1024 / 1024) "Allocated (MB)",
       round(nvl(b.bytes_free, 0) / 1024 / 1024) "Free (MB)",
       round((a.bytes_alloc - nvl(b.bytes_free, 0)) / 1024 / 1024) "Used (MB)",
       round((nvl(b.bytes_free, 0) / a.bytes_alloc) * 100) "% Free",
       100 - round((nvl(b.bytes_free, 0) / a.bytes_alloc) * 100) "% Used",
       round(maxbytes/1024 / 1024) "Max. Bytes (MB)"
from  ( select  f.tablespace_name,
               sum(f.bytes) bytes_alloc,
               sum(decode(f.autoextensible, 'YES',f.maxbytes,'NO', f.bytes)) maxbytes
        from dba_data_files f
        group by tablespace_name) a,
      ( select  f.tablespace_name,
               sum(f.bytes)  bytes_free
        from dba_free_space f
        group by tablespace_name) b
where a.tablespace_name = b.tablespace_name (+)
union all
select 
       h.tablespace_name as tablespace_name,
       round(sum(h.bytes_free + h.bytes_used) / 1048576) megs_alloc,
       round(sum((h.bytes_free + h.bytes_used) - nvl(p.bytes_used, 0)) / 1048576) megs_free,
       round(sum(nvl(p.bytes_used, 0))/ 1048576) megs_used,
       round((sum((h.bytes_free + h.bytes_used) - nvl(p.bytes_used, 0)) / sum(h.bytes_used + h.bytes_free)) * 100) Pct_Free,
       100 - round((sum((h.bytes_free + h.bytes_used) - nvl(p.bytes_used, 0)) / sum(h.bytes_used + h.bytes_free)) * 100) pct_used,
       round(sum(f.maxbytes) / 1048576) max
from   sys.v_$TEMP_SPACE_HEADER h, sys.v_$Temp_extent_pool p, dba_temp_files f
where  p.file_id(+) = h.file_id
and    p.tablespace_name(+) = h.tablespace_name
and    f.file_id = h.file_id
and    f.tablespace_name = h.tablespace_name
group by h.tablespace_name
ORDER BY 2;

SVN change username

The easiest way to do this is to simply use the --username option on your next checkout or commit. For example:

svn commit --username newUser

or

svn co --username newUser

It will then be cached and will be used as the default username for future commands.

See also: In Subversion can I be a user other than my login name?

How do I change the default location for Git Bash on Windows?

After installing msysgit I have the Git Bash here option in the context menu in Windows Explorer. So I just simply navigate to the directory and then open Bash right there.

I also copied the default Git Bash shortcut to the desktop and edited its Start in property to point to my project directory. It works flawlessly.

Windows 7x64, msysgit.

How do you make Git work with IntelliJ?

Literally, just restarted IntelliJ after it kept showing this "install git" message after I have pressed and installed git, and it disappeared, and git works

How to take a first character from the string

Try this..

Dim S As String
S = "RAJAN"
Dim answer As Char
answer = S.Substring(0, 1)

How to get htaccess to work on MAMP

The problem I was having with the rewrite is that some .htaccess files for Codeigniter, etc come with

RewriteBase /

Which doesn't seem to work in MAMP...at least for me.

Convert Date/Time for given Timezone - java

Joda-Time

The java.util.Date/Calendar classes are a mess and should be avoided.

Update: The Joda-Time project is in maintenance mode. The team advises migration to the java.time classes.

Here's your answer using the Joda-Time 2.3 library. Very easy.

As noted in the example code, I suggest you use named time zones wherever possible so that your programming can handle Daylight Saving Time (DST) and other anomalies.

If you had placed a T in the middle of your string instead of a space, you could skip the first two lines of code, dealing with a formatter to parse the string. The DateTime constructor can take a string in ISO 8601 format.

// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;

// Parse string as a date-time in UTC (no time zone offset).
DateTimeFormatter formatter = org.joda.time.format.DateTimeFormat.forPattern( "yyyy-MM-dd' 'HH:mm:ss" );
DateTime dateTimeInUTC = formatter.withZoneUTC().parseDateTime( "2011-10-06 03:35:05" );

// Adjust for 13 hour offset from UTC/GMT.
DateTimeZone offsetThirteen = DateTimeZone.forOffsetHours( 13 );
DateTime thirteenDateTime = dateTimeInUTC.toDateTime( offsetThirteen );

// Hard-coded offsets should be avoided. Better to use a desired time zone for handling Daylight Saving Time (DST) and other anomalies.
// Time Zone list… http://joda-time.sourceforge.net/timezones.html
DateTimeZone timeZoneTongatapu = DateTimeZone.forID( "Pacific/Tongatapu" );
DateTime tongatapuDateTime = dateTimeInUTC.toDateTime( timeZoneTongatapu );

Dump those values…

System.out.println( "dateTimeInUTC: " + dateTimeInUTC );
System.out.println( "thirteenDateTime: " + thirteenDateTime );
System.out.println( "tongatapuDateTime: " + tongatapuDateTime );

When run…

dateTimeInUTC: 2011-10-06T03:35:05.000Z
thirteenDateTime: 2011-10-06T16:35:05.000+13:00
tongatapuDateTime: 2011-10-06T16:35:05.000+13:00

Purpose of #!/usr/bin/python3 shebang

That's called a hash-bang. If you run the script from the shell, it will inspect the first line to figure out what program should be started to interpret the script.

A non Unix based OS will use its own rules for figuring out how to run the script. Windows for example will use the filename extension and the # will cause the first line to be treated as a comment.

If the path to the Python executable is wrong, then naturally the script will fail. It is easy to create links to the actual executable from whatever location is specified by standard convention.

sqlite3.OperationalError: unable to open database file

This is definitely a permissions issue. If someone is getting this error on linux, make sure you're running the command with sudo as the file most likely is owned by root. Hope that helps!

How can I get a side-by-side diff when I do "git diff"?

I use colordiff.

On Mac OS X, install it with

$ sudo port install colordiff

On Linux is possibly apt get install colordiff or something like that, depending on your distro.

Then:

$ git difftool --extcmd="colordiff -ydw" HEAD^ HEAD

Or create an alias

$ git alias diffy "difftool --extcmd=\"colordiff -ydw\""

Then you can use it

$ git diffy HEAD^ HEAD

I called it "diffy" because diff -y is the side-by-side diff in unix. Colordiff also adds colors, that are nicer. In the option -ydw, the y is for the side-by-side, the w is to ignore whitespaces, and the d is to produce the minimal diff (usually you get a better result as diff)

How do I get information about an index and table owner in Oracle?

Below are two simple query using which you can check index created on a table in Oracle.

select index_name
  from dba_indexes
 where table_name='&TABLE_NAME'
   and owner='&TABLE_OWNER';
select index_name 
  from user_indexes 
 where table_name='&TABLE_NAME';

Please check for more details and index size below. Index on a table and its size in Oracle

Check with jquery if div has overflowing elements

You actually don't need any jQuery to check if there is an overflow happening or not. Using element.offsetHeight, element.offsetWidth , element.scrollHeight and element.scrollWidth you can determine if your element have content bigger than it's size:

if (element.offsetHeight < element.scrollHeight ||
    element.offsetWidth < element.scrollWidth) {
    // your element have overflow
} else {
    // your element doesn't have overflow
}

See example in action: Fiddle

But if you want to know what element inside your element is visible or not then you need to do more calculation. There is three states for a child element in terms of visibility:

enter image description here

If you want to count semi-visible items it would be the script you need:

var invisibleItems = [];
for(var i=0; i<element.childElementCount; i++){
  if (element.children[i].offsetTop + element.children[i].offsetHeight >
      element.offsetTop + element.offsetHeight ||
      element.children[i].offsetLeft + element.children[i].offsetWidth >
      element.offsetLeft + element.offsetWidth ){

        invisibleItems.push(element.children[i]);
    }

}

And if you don't want to count semi-visible you can calculate with a little difference.

error LNK2038: mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '0' doesn't match value '2' in main.obj

I make a little update on this issue, as I just had the same error today on an application which is linking against a static lib, after I migrated the old Visual 6 project to Visual Studio 2012.

In my case the error was that I mistakenly compiled the Release version of the static lib with /MDd instead of /MD, whereas the application is /MD in release. Setting the correct /MD in the static lib project solved the issue.

This is done in Project properties

  • Select Configuration Properties / C C++ / Code Generation in the tree
  • and the option Runtime Library set to the same on all your dependencies projects and application.

Add JVM options in Tomcat

if you want to set jvm args on eclipse you can use below:

see below two links to accomplish it:

  1. eclipse setting to pass jvm args to java
  2. eclipse setting to pass jvm args to java and adding to run config on eclipse

And for Tomcat you can create a setenv.bat file in bin folder of Tomcat and add below lines to it :

echo "hello im starting setenv"
set CATALINA_OPTS=-DNLP.home=${NLP.home} -Dhostname=${hostname}

How to keep :active css style after clicking an element

If you want to keep your links to look like they are :active class, you should define :visited class same as :active so if you have a links in .example then you do something like this:

a.example:active, a.example:visited {
/* Put your active state style code here */ }

The Link visited Pseudo Class is used to select visited links as says the name.

What does "restore purchases" in In-App purchases mean?

You typically restore purchases with this code:

[[SKPaymentQueue defaultQueue] restoreCompletedTransactions];

It will reinvoke -paymentQueue:updatedTransactions on the observer(s) for the purchased items. This is useful for users who reinstall the app after deletion or install it on a different device.

Not all types of In-App purchases can be restored.

HTML text-overflow ellipsis detection

Answer from italo is very good! However let me refine it a little:

function isEllipsisActive(e) {
   var tolerance = 2; // In px. Depends on the font you are using
   return e.offsetWidth + tolerance < e.scrollWidth;
}

Cross browser compatibility

If, in fact, you try the above code and use console.log to print out the values of e.offsetWidth and e.scrollWidth, you will notice, on IE, that, even when you have no text truncation, a value difference of 1px or 2px is experienced.

So, depending on the font size you use, allow a certain tolerance!

How to: Create trigger for auto update modified date with SQL Server 2008

My approach:

  • define a default constraint on the ModDate column with a value of GETDATE() - this handles the INSERT case

  • have a AFTER UPDATE trigger to update the ModDate column

Something like:

CREATE TRIGGER trg_UpdateTimeEntry
ON dbo.TimeEntry
AFTER UPDATE
AS
    UPDATE dbo.TimeEntry
    SET ModDate = GETDATE()
    WHERE ID IN (SELECT DISTINCT ID FROM Inserted)

Trying to get the average of a count resultset

You just can put your query as a subquery:

SELECT avg(count)
  FROM 
    (
    SELECT COUNT (*) AS Count
      FROM Table T
     WHERE T.Update_time =
               (SELECT MAX (B.Update_time )
                  FROM Table B
                 WHERE (B.Id = T.Id))
    GROUP BY T.Grouping
    ) as counts

Edit: I think this should be the same:

SELECT count(*) / count(distinct T.Grouping)
  FROM Table T
 WHERE T.Update_time =
           (SELECT MAX (B.Update_time)
              FROM Table B
             WHERE (B.Id = T.Id))

Maven plugin not using Eclipse's proxy settings

Eclipse by default does not know about your external Maven installation and uses the embedded one. Therefore in order for Eclipse to use your global settings you need to set it in menu Settings ? Maven ? Installations.

How can I change the default Django date template format?

Just use this:

{{you_date_field|date:'Y-m-d'}}

This will show something like 2016-10-16. You can use the format as you want.

How can I list the scheduled jobs running in my database?

Because the SCHEDULER_ADMIN role is a powerful role allowing a grantee to execute code as any user, you should consider granting individual Scheduler system privileges instead. Object and system privileges are granted using regular SQL grant syntax. An example is if the database administrator issues the following statement:

GRANT CREATE JOB TO scott;

After this statement is executed, scott can create jobs, schedules, or programs in his schema.

copied from http://docs.oracle.com/cd/B19306_01/server.102/b14231/schedadmin.htm#i1006239

TypeError: 'tuple' object does not support item assignment when swapping values

Evaluating "1,2,3" results in (1, 2, 3), a tuple. As you've discovered, tuples are immutable. Convert to a list before processing.

How to convert date format to milliseconds?

date.setTime(milliseconds);

this is for set milliseconds in date

long milli = date.getTime();

This is for get time in milliseconds.

Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT

Boolean.parseBoolean("1") = false...?

How about this?

boolean uses_votes =
  ( "|1|yes|on|true|"
      .indexOf("|"+o.get("uses_votes").toLowerCase()+"|")
      > -1
  );

MySQL - Replace Character in Columns

If you have "something" and need 'something', use replace(col, "\"", "\'") and viceversa.

How can you tell when a layout has been drawn?

To avoid deprecated code and warnings you can use:

view.getViewTreeObserver().addOnGlobalLayoutListener(
        new ViewTreeObserver.OnGlobalLayoutListener() {
            @SuppressWarnings("deprecation")
            @Override
            public void onGlobalLayout() {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    view.getViewTreeObserver()
                            .removeOnGlobalLayoutListener(this);
                } else {
                    view.getViewTreeObserver()
                            .removeGlobalOnLayoutListener(this);
                }
                yourFunctionHere();
            }
        });

Core dump file is not generated

Although this isn't going to be a problem for the person who asked the question, because they ran the program that was to produce the core file in a script with the ulimit command, I'd like to document that the ulimit command is specific to the shell in which you run it (like environment variables). I spent way too much time running ulimit and sysctl and stuff in one shell, and the command that I wanted to dump core in the other shell, and wondering why the core file was not produced.

I will be adding it to my bashrc. The sysctl works for all processes once it is issued, but the ulimit only works for the shell in which it is issued (maybe also the descendents too) - but not for other shells that happen to be running.

Clear text from textarea with selenium

In the most recent Selenium version, use:

driver.find_element_by_id('foo').clear()

Get query string parameters url values with jQuery / Javascript (querystring)

This isn't my code sample, but I've used it in the past.

//First Add this to extend jQuery

    $.extend({
      getUrlVars: function(){
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for(var i = 0; i < hashes.length; i++)
        {
          hash = hashes[i].split('=');
          vars.push(hash[0]);
          vars[hash[0]] = hash[1];
        }
        return vars;
      },
      getUrlVar: function(name){
        return $.getUrlVars()[name];
      }
    });

    //Second call with this:
    // Get object of URL parameters
    var allVars = $.getUrlVars();

    // Getting URL var by its name
    var byName = $.getUrlVar('name');

Text in Border CSS HTML

Text in Border with transparent text background

_x000D_
_x000D_
.box{
    background-image: url("https://i.stack.imgur.com/N39wV.jpg");
    width: 350px;
    padding: 10px;
}

/*begin first box*/
.first{
    width: 300px;
    height: 100px;
    margin: 10px;
    border-width: 0 2px 0 2px;
    border-color: #333;
    border-style: solid;
    position: relative;
}

.first span {
    position: absolute;
    display: flex;
    right: 0;
    left: 0;
    align-items: center;
}
.first .foo{
    top: -8px;
}
.first .bar{
    bottom: -8.5px;
}
.first span:before{
    margin-right: 15px;
}
.first span:after {
    margin-left: 15px;
}
.first span:before , .first span:after {
    content: ' ';
    height: 2px;
    background: #333;
    display: block;
    width: 50%;
}


/*begin second box*/
.second{
    width: 300px;
    height: 100px;
    margin: 10px;
    border-width: 2px 0 2px 0;
    border-color: #333;
    border-style: solid;
    position: relative;
}

.second span {
    position: absolute;
    top: 0;
    bottom: 0;
    display: flex;
    flex-direction: column;
    align-items: center;
}
.second .foo{
    left: -15px;
}
.second .bar{
    right: -15.5px;
}
.second span:before{
    margin-bottom: 15px;
}
.second span:after {
    margin-top: 15px;
}
.second span:before , .second span:after {
    content: ' ';
    width: 2px;
    background: #333;
    display: block;
    height: 50%;
}
_x000D_
<div class="box">
    <div class="first">
        <span class="foo">FOO</span>
        <span class="bar">BAR</span>
    </div>

   <br>

    <div class="second">
        <span class="foo">FOO</span>
        <span class="bar">BAR</span>
    </div>
</div>
_x000D_
_x000D_
_x000D_

What's the difference between disabled="disabled" and readonly="readonly" for HTML form input fields?

A readonly element is just not editable, but gets sent when the according form submits. A disabled element isn't editable and isn't sent on submit. Another difference is that readonly elements can be focused (and getting focused when "tabbing" through a form) while disabled elements can't.

Read more about this in this great article or the definition by w3c. To quote the important part:

Key Differences

The Disabled attribute

  • Values for disabled form elements are not passed to the processor method. The W3C calls this a successful element.(This works similar to form check boxes that are not checked.)
  • Some browsers may override or provide default styling for disabled form elements. (Gray out or emboss text) Internet Explorer 5.5 is particularly nasty about this.
  • Disabled form elements do not receive focus.
  • Disabled form elements are skipped in tabbing navigation.

The Read Only Attribute

  • Not all form elements have a readonly attribute. Most notable, the <SELECT> , <OPTION> , and <BUTTON> elements do not have readonly attributes (although they both have disabled attributes)
  • Browsers provide no default overridden visual feedback that the form element is read only. (This can be a problem… see below.)
  • Form elements with the readonly attribute set will get passed to the form processor.
  • Read only form elements can receive the focus
  • Read only form elements are included in tabbed navigation.

Pivoting rows into columns dynamically in Oracle

To deal with situations where there are a possibility of multiple values (v in your example), I use PIVOT and LISTAGG:

SELECT * FROM
(
  SELECT id, k, v
  FROM _kv 
)
PIVOT 
(
  LISTAGG(v ,',') 
  WITHIN GROUP (ORDER BY k) 
  FOR k IN ('name', 'age','gender','status')
)
ORDER BY id;

Since you want dynamic values, use dynamic SQL and pass in the values determined by running a select on the table data before calling the pivot statement.

How to position background image in bottom right corner? (CSS)

for more exactly positioning:

      background-position: bottom 5px right 7px;

How to read a file in Groovy into a string?

Here you can Find some other way to do the same.

Read file.

File file1 = new File("C:\Build\myfolder\myTestfile.txt");
def String yourData = file1.readLines();

Read Full file.

File file1 = new File("C:\Build\myfolder\myfile.txt");
def String yourData= file1.getText();

Read file Line Bye Line.

File file1 = new File("C:\Build\myfolder\myTestfile.txt");
for (def i=0;i<=30;i++) // specify how many line need to read eg.. 30
{
 log.info file1.readLines().get(i)

}

Create a new file.

new File("C:\Temp\FileName.txt").createNewFile();

Postgresql - change the size of a varchar column to lower length

Ok, I'm probably late to the party, BUT...

THERE'S NO NEED TO RESIZE THE COLUMN IN YOUR CASE!

Postgres, unlike some other databases, is smart enough to only use just enough space to fit the string (even using compression for longer strings), so even if your column is declared as VARCHAR(255) - if you store 40-character strings in the column, the space usage will be 40 bytes + 1 byte of overhead.

The storage requirement for a short string (up to 126 bytes) is 1 byte plus the actual string, which includes the space padding in the case of character. Longer strings have 4 bytes of overhead instead of 1. Long strings are compressed by the system automatically, so the physical requirement on disk might be less. Very long values are also stored in background tables so that they do not interfere with rapid access to shorter column values.

(http://www.postgresql.org/docs/9.0/interactive/datatype-character.html)

The size specification in VARCHAR is only used to check the size of the values which are inserted, it does not affect the disk layout. In fact, VARCHAR and TEXT fields are stored in the same way in Postgres.

How to add a new column to an existing sheet and name it?

Use insert method from range, for example

Sub InsertColumn()
        Columns("C:C").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
        Range("C1").Value = "Loc"
End Sub

What are the differences among grep, awk & sed?

Short definition:

grep: search for specific terms in a file

#usage
$ grep This file.txt
Every line containing "This"
Every line containing "This"
Every line containing "This"
Every line containing "This"

$ cat file.txt
Every line containing "This"
Every line containing "This"
Every line containing "That"
Every line containing "This"
Every line containing "This"

Now awk and sed are completly different than grep. awk and sed are text processors. Not only do they have the ability to find what you are looking for in text, they have the ability to remove, add and modify the text as well (and much more).

awk is mostly used for data extraction and reporting. sed is a stream editor
Each one of them has its own functionality and specialties.

Example
Sed

$ sed -i 's/cat/dog/' file.txt
# this will replace any occurrence of the characters 'cat' by 'dog'

Awk

$ awk '{print $2}' file.txt
# this will print the second column of file.txt

Basic awk usage:
Compute sum/average/max/min/etc. what ever you may need.

$ cat file.txt
A 10
B 20
C 60
$ awk 'BEGIN {sum=0; count=0; OFS="\t"} {sum+=$2; count++} END {print "Average:", sum/count}' file.txt
Average:    30

I recommend that you read this book: Sed & Awk: 2nd Ed.

It will help you become a proficient sed/awk user on any unix-like environment.

Batch command date and time in file name

Your question seems to be solved, but ...

I'm not sure if you take the right solution for your problem.
I suppose you try to compress each day the actual project code.

It's possible with ZIP and 1980 this was a good solution, but today you should use a repository system, like subversion or git or ..., but not a zip-file.

Ok, perhaps it could be that I'm wrong.

Remove tracking branches no longer on remote

git fetch -p

This will prune any branches that no longer exist on the remote.

CSS scrollbar style cross browser

Webkit's support for scrollbars is quite sophisticated. This CSS gives a very minimal scrollbar, with a light grey track and a darker thumb:

::-webkit-scrollbar
{
  width: 12px;  /* for vertical scrollbars */
  height: 12px; /* for horizontal scrollbars */
}

::-webkit-scrollbar-track
{
  background: rgba(0, 0, 0, 0.1);
}

::-webkit-scrollbar-thumb
{
  background: rgba(0, 0, 0, 0.5);
}

This answer is a fantastic source of additional information.

Python - Using regex to find multiple matches and print them out

Do not use regular expressions to parse HTML.

But if you ever need to find all regexp matches in a string, use the findall function.

import re
line = 'bla bla bla<form>Form 1</form> some text...<form>Form 2</form> more text?'
matches = re.findall('<form>(.*?)</form>', line, re.DOTALL)
print(matches)

# Output: ['Form 1', 'Form 2']

Debug vs Release in CMake

// CMakeLists.txt : release

set(CMAKE_CONFIGURATION_TYPES "Release" CACHE STRING "" FORCE)

// CMakeLists.txt : debug

set(CMAKE_CONFIGURATION_TYPES "Debug" CACHE STRING "" FORCE)

Max size of URL parameters in _GET

See What is the maximum length of a URL in different browsers?

The length of the url can't be changed in PHP. The linked question is about the URL size limit, you will find what you want.

Replace Fragment inside a ViewPager

As of November 13th 2012, repacing fragments in a ViewPager seems to have become a lot easier. Google released Android 4.2 with support for nested fragments, and it's also supported in the new Android Support Library v11 so this will work all the way back to 1.6

It's very similiar to the normal way of replacing a fragment except you use getChildFragmentManager. It seems to work except the nested fragment backstack isn't popped when the user clicks the back button. As per the solution in that linked question, you need to manually call the popBackStackImmediate() on the child manager of the fragment. So you need to override onBackPressed() of the ViewPager activity where you'll get the current fragment of the ViewPager and call getChildFragmentManager().popBackStackImmediate() on it.

Getting the Fragment currently being displayed is a bit hacky as well, I used this dirty "android:switcher:VIEWPAGER_ID:INDEX" solution but you can also keep track of all fragments of the ViewPager yourself as explained in the second solution on this page.

So here's my code for a ViewPager with 4 ListViews with a detail view shown in the ViewPager when the user clicks a row, and with the back button working. I tried to include just the relevant code for the sake of brevity so leave a comment if you want the full app uploaded to GitHub.

HomeActivity.java

 public class HomeActivity extends SherlockFragmentActivity {
FragmentAdapter mAdapter;
ViewPager mPager;
TabPageIndicator mIndicator;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    mAdapter = new FragmentAdapter(getSupportFragmentManager());
    mPager = (ViewPager)findViewById(R.id.pager);
    mPager.setAdapter(mAdapter);
    mIndicator = (TabPageIndicator)findViewById(R.id.indicator);
    mIndicator.setViewPager(mPager);
}

// This the important bit to make sure the back button works when you're nesting fragments. Very hacky, all it takes is some Google engineer to change that ViewPager view tag to break this in a future Android update.
@Override
public void onBackPressed() {
    Fragment fragment = (Fragment) getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.pager + ":"+mPager.getCurrentItem());
    if (fragment != null) // could be null if not instantiated yet
    {
        if (fragment.getView() != null) {
            // Pop the backstack on the ChildManager if there is any. If not, close this activity as normal.
            if (!fragment.getChildFragmentManager().popBackStackImmediate()) {
                finish();
            }
        }
    }
}

class FragmentAdapter extends FragmentPagerAdapter {        
    public FragmentAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        switch (position) {
        case 0:
            return ListProductsFragment.newInstance();
        case 1:
            return ListActiveSubstancesFragment.newInstance();
        case 2:
            return ListProductFunctionsFragment.newInstance();
        case 3:
            return ListCropsFragment.newInstance();
        default:
            return null;
        }
    }

    @Override
    public int getCount() {
        return 4;
    }

 }
}

ListProductsFragment.java

public class ListProductsFragment extends SherlockFragment {
private ListView list;

public static ListProductsFragment newInstance() {
    ListProductsFragment f = new ListProductsFragment();
    return f;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View V = inflater.inflate(R.layout.list, container, false);
    list = (ListView)V.findViewById(android.R.id.list);
    list.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
            int position, long id) {
          // This is important bit
          Fragment productDetailFragment = FragmentProductDetail.newInstance();
          FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
          transaction.addToBackStack(null);
          transaction.replace(R.id.products_list_linear, productDetailFragment).commit();
        }
      });       
    return V;
}
}

How to print exact sql query in zend framework ?

You can use Zend_Debug::Dump($select->assemble()); to get the SQL query.

Or you can enable Zend DB FirePHP profiler which will get you all queries in a neat format in Firebug (even UPDATE statements).

EDIT: Profiling with FirePHP also works also in FF6.0+ (not only in FF3.0 as suggested in link)

How do I convert an array object to a string in PowerShell?

$a = 'This', 'Is', 'a', 'cat'

Using double quotes (and optionally use the separator $ofs)

# This Is a cat
"$a"

# This-Is-a-cat
$ofs = '-' # after this all casts work this way until $ofs changes!
"$a"

Using operator join

# This-Is-a-cat
$a -join '-'

# ThisIsacat
-join $a

Using conversion to [string]

# This Is a cat
[string]$a

# This-Is-a-cat
$ofs = '-'
[string]$a

Getting and removing the first character of a string

Another alternative is to use capturing sub-expressions with the regular expression functions regmatches and regexec.

# the original example
x <- 'hello stackoverflow'

# grab the substrings
myStrings <- regmatches(x, regexec('(^.)(.*)', x))

This returns the entire string, the first character, and the "popped" result in a list of length 1.

myStrings
[[1]]
[1] "hello stackoverflow" "h"                   "ello stackoverflow" 

which is equivalent to list(c(x, substr(x, 1, 1), substr(x, 2, nchar(x)))). That is, it contains the super set of the desired elements as well as the full string.


Adding sapply will allow this method to work for a character vector of length > 1.

# a slightly more interesting example
xx <- c('hello stackoverflow', 'right back', 'at yah')

# grab the substrings
myStrings <- regmatches(x, regexec('(^.)(.*)', xx))

This returns a list with the matched full string as the first element and the matching subexpressions captured by () as the following elements. So in the regular expression '(^.)(.*)', (^.) matches the first character and (.*) matches the remaining characters.

myStrings
[[1]]
[1] "hello stackoverflow" "h"                   "ello stackoverflow" 

[[2]]
[1] "right back" "r"          "ight back" 

[[3]]
[1] "at yah" "a"      "t yah" 

Now, we can use the trusty sapply + [ method to pull out the desired substrings.

myFirstStrings <- sapply(myStrings, "[", 2)
myFirstStrings
[1] "h" "r" "a"
mySecondStrings <- sapply(myStrings, "[", 3)
mySecondStrings
[1] "ello stackoverflow" "ight back"          "t yah"

What properties can I use with event.target?

event.target returns the node that was targeted by the function. This means you can do anything you want to do with any other node like one you'd get from document.getElementById

I'm tried with jQuery

var _target = e.target;
console.log(_target.attr('href'));

Return an error :

.attr not function

But _target.attributes.href.value was works.

How to delete all data from solr and hbase

fire this in the browser

http://localhost:8983/solr/update?stream.body=<delete><query>*:*</query></delete>&commit=true this commmand will delete all the documents in index in solr

How can I represent a range in Java?

You could use java.time.temporal.ValueRange which accepts long and would also work with int:

int a = 2147;

//Use java 8 java.time.temporal.ValueRange. The range defined
//is inclusive of both min and max 
ValueRange range = ValueRange.of(0, 2147483647);

if(range.isValidValue(a)) {
    System.out.println("in range");
}else {
    System.out.println("not in range");
}

PHP post_max_size overrides upload_max_filesize

change in php.ini max_input_vars 1000

PHP preg_match - only allow alphanumeric strings and - _ characters

if(!preg_match('/^[\w-]+$/', $string1)) {
   echo "String 1 not acceptable acceptable";
   // String2 acceptable
}

Python regex findall

Your question is not 100% clear, but I'm assuming you want to find every piece of text inside [P][/P] tags:

>>> import re
>>> line = "President [P] Barack Obama [/P] met Microsoft founder [P] Bill Gates [/P], yesterday."
>>> re.findall('\[P\]\s?(.+?)\s?\[\/P\]', line)
['Barack Obama', 'Bill Gates']

FormData.append("key", "value") is not working

New in Chrome 50+ and Firefox 39+ (resp. 44+):

  • formdata.entries() (combine with Array.from() for debugability)
  • formdata.get(key)
  • and more very useful methods

Original answer:

What I usually do to 'debug' a FormData object, is just send it (anywhere!) and check the browser logs (eg. Chrome devtools' Network tab).

You don't need a/the same Ajax framework. You don't need any details. Just send it:

var xhr = new XMLHttpRequest;
xhr.open('POST', '/', true);
xhr.send(data);

Easy.

How to resolve git stash conflict without commit?

git checkout stash -- .

worked for me.

Note: this can be dangerous since it doesn't try to merge the changes from the stash into your working copy, but overwrites it with the stashed files instead. So you can lose your uncommitted changes.

how to "execute" make file

As paxdiablo said make -f pax.mk would execute the pax.mk makefile, if you directly execute it by typing ./pax.mk, then you would get syntax error.

Also you can just type make if your file name is makefile/Makefile.

Suppose you have two files named makefile and Makefile in the same directory then makefile is executed if make alone is given. You can even pass arguments to makefile.

Check out more about makefile at this Tutorial : Basic understanding of Makefile

How do I get JSON data from RESTful service using Python?

I would give the requests library a try for this. Essentially just a much easier to use wrapper around the standard library modules (i.e. urllib2, httplib2, etc.) you would use for the same thing. For example, to fetch json data from a url that requires basic authentication would look like this:

import requests

response = requests.get('http://thedataishere.com',
                         auth=('user', 'password'))
data = response.json()

For kerberos authentication the requests project has the reqests-kerberos library which provides a kerberos authentication class that you can use with requests:

import requests
from requests_kerberos import HTTPKerberosAuth

response = requests.get('http://thedataishere.com',
                         auth=HTTPKerberosAuth())
data = response.json()

What are .dex files in Android?

.dex file

Compiled Android application code file.

Android programs are compiled into .dex (Dalvik Executable) files, which are in turn zipped into a single .apk file on the device. .dex files can be created automatically by Android, by translating the compiled applications written in the Java programming language.

What's the difference between a word and byte?

In fact, in common usage, word has become synonymous with 16 bits, much like byte has with 8 bits. Can get a little confusing since the "word size" on a 32-bit CPU is 32-bits, but when talking about a word of data, one would mean 16-bits. Microcontrollers with a 32-bit word size have taken to calling their instructions "longs" (supposedly to try and avoid the word/doubleword confusion).

Check whether a variable is a string in Ruby

I think a better way is to create some predicate methods. This will also save your "Single Point of Control".

class Object
 def is_string?
   false
 end
end

class String
 def is_string?
   true
 end
end

print "test".is_string? #=> true
print 1.is_string?      #=> false

The more duck typing way ;)

Basic Python client socket example

It looks like your client is trying to connect to a non-existent server. In a shell window, run:

$ nc -l 5000

before running your Python code. It will act as a server listening on port 5000 for you to connect to. Then you can play with typing into your Python window and seeing it appear in the other terminal and vice versa.

How can I truncate a double to only two decimal places in Java?

If, for whatever reason, you don't want to use a BigDecimal you can cast your double to an int to truncate it.

If you want to truncate to the Ones place:

  • simply cast to int

To the Tenths place:

  • multiply by ten
  • cast to int
  • cast back to double
  • and divide by ten.

Hundreths place

  • multiply and divide by 100 etc.

Example:

static double truncateTo( double unroundedNumber, int decimalPlaces ){
    int truncatedNumberInt = (int)( unroundedNumber * Math.pow( 10, decimalPlaces ) );
    double truncatedNumber = (double)( truncatedNumberInt / Math.pow( 10, decimalPlaces ) );
    return truncatedNumber;
}

In this example, decimalPlaces would be the number of places PAST the ones place you wish to go, so 1 would round to the tenths place, 2 to the hundredths, and so on (0 rounds to the ones place, and negative one to the tens, etc.)

SQL RANK() versus ROW_NUMBER()

Simple query without partition clause:

select 
    sal, 
    RANK() over(order by sal desc) as Rank,
    DENSE_RANK() over(order by sal desc) as DenseRank,
    ROW_NUMBER() over(order by sal desc) as RowNumber
from employee 

Output:

    --------|-------|-----------|----------
    sal     |Rank   |DenseRank  |RowNumber
    --------|-------|-----------|----------
    5000    |1      |1          |1
    3000    |2      |2          |2
    3000    |2      |2          |3
    2975    |4      |3          |4
    2850    |5      |4          |5
    --------|-------|-----------|----------

Android webview launches browser when calling loadurl

Answering my question based on the suggestions from Maudicus and Hit.

Check the WebView tutorial here. Just implement the web client and set it before loadUrl. The simplest way is:

myWebView.setWebViewClient(new WebViewClient());

For more advanced processing for the web content, consider the ChromeClient.

How to expand a list to function arguments in Python

You should use the * operator, like foo(*values) Read the Python doc unpackaging argument lists.

Also, do read this: http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/

def foo(x,y,z):
   return "%d, %d, %d" % (x,y,z)

values = [1,2,3]

# the solution.
foo(*values)

Better naming in Tuple classes than "Item1", "Item2"

You Can write a class that contains the Tuple.

You need to override the Equals and GetHashCode functions

and the == and != operators.

class Program
{
    public class MyTuple
    {
        private Tuple<int, int> t;

        public MyTuple(int a, int b)
        {
            t = new Tuple<int, int>(a, b);
        }

        public int A
        {
            get
            {
                return t.Item1;
            }
        }

        public int B
        {
            get
            {
                return t.Item2;
            }
        }

        public override bool Equals(object obj)
        {
            return t.Equals(((MyTuple)obj).t);
        }

        public override int GetHashCode()
        {
            return t.GetHashCode();
        }

        public static bool operator ==(MyTuple m1, MyTuple m2)
        {
            return m1.Equals(m2);
        }

        public static bool operator !=(MyTuple m1, MyTuple m2)
        {
            return !m1.Equals(m2);
        }
    }

    static void Main(string[] args)
    {
        var v1 = new MyTuple(1, 2);
        var v2 = new MyTuple(1, 2);

        Console.WriteLine(v1 == v2);

        Dictionary<MyTuple, int> d = new Dictionary<MyTuple, int>();
        d.Add(v1, 1);

        Console.WriteLine(d.ContainsKey(v2));
    }
}

will return:

True

True

log4j logging hierarchy order

Hierarchy order

  1. ALL
  2. TRACE
  3. DEBUG
  4. INFO
  5. WARN
  6. ERROR
  7. FATAL
  8. OFF

How do you get the cursor position in a textarea?

Here is code to get line number and column position

function getLineNumber(tArea) {

    return tArea.value.substr(0, tArea.selectionStart).split("\n").length;
}

function getCursorPos() {
    var me = $("textarea[name='documenttext']")[0];
    var el = $(me).get(0);
    var pos = 0;
    if ('selectionStart' in el) {
        pos = el.selectionStart;
    } else if ('selection' in document) {
        el.focus();
        var Sel = document.selection.createRange();
        var SelLength = document.selection.createRange().text.length;
        Sel.moveStart('character', -el.value.length);
        pos = Sel.text.length - SelLength;
    }
    var ret = pos - prevLine(me);
    alert(ret);

    return ret; 
}

function prevLine(me) {
    var lineArr = me.value.substr(0, me.selectionStart).split("\n");

    var numChars = 0;

    for (var i = 0; i < lineArr.length-1; i++) {
        numChars += lineArr[i].length+1;
    }

    return numChars;
}

tArea is the text area DOM element

SQL select only rows with max value on a column

I am flabbergasted that no answer offered SQL window function solution:

SELECT a.id, a.rev, a.contents
  FROM (SELECT id, rev, contents,
               ROW_NUMBER() OVER (PARTITION BY id ORDER BY rev DESC) rank
          FROM YourTable) a
 WHERE a.rank = 1 

Added in SQL standard ANSI/ISO Standard SQL:2003 and later extended with ANSI/ISO Standard SQL:2008, window (or windowing) functions are available with all major vendors now. There are more types of rank functions available to deal with a tie issue: RANK, DENSE_RANK, PERSENT_RANK.

Appending to 2D lists in Python

[[]]*3 is not the same as [[], [], []].

It's as if you'd said

a = []
listy = [a, a, a]

In other words, all three list references refer to the same list instance.