Q:

main function - what is the point of a return value?

Possible Duplicate:
What should main() return in C/C++?
What does main return?

I've been wondering this for a while: what is the purpose of a return 0; statement at the end of the main() function?
I know that a return statement at the end most functions returns a value to the function which called it.  However, as I understand it, the main function is the starting and ending point of the program, so I'm a little confused as to why it has a return type at all?
main()
{
  //code goes here

  return 0; // <-- what is the point of this return statement?
}

edit:  I'm pretty new to programming (first year computer science student) and after looking at some of the answers it sounds like the return statement is used to tell the caller of the function if it has completed successfully.  Other than the OS and command line, is there anything else that can call a main function?  thanks for the quick answers =)

A:

It's used to tell the environment running the program whether or not it completed successfully. This is important for command-line tools if you want to run them from scripts.
You should return zero or EXIT_SUCCESS on success, or EXIT_FAILURE on failure - the constants are defined in <cstdlib>.
If you like, you can omit the return statement from the end of main - the result will be the same as returning zero. This is a special case for main only - you must still return a value from any other non-void function.

Other than the OS and command line, is there anything else that can call a main function?

No - C++ specifically prohibits calling main from within the program.


Q:

What's the meaning of "vor" in this sentence?

The sentences are

Was haben Sie für morgen vor?
  Für wann haben Sie einen Ausflug vor?

English Translation:

What do you have for tomorrow?
  When do you have an excursion?

Normally, vor means "before, in front of...".
I don't see any meaning of "vor" in these translations.

A:

The verb your are looking for is vorhaben. Look it up.


Q:

How to keep one field fixed in a formular when using auto-fill?

I want to autofill a formula to a bunch of fields in one column. I can do that by filling two fields manually then select them and drag down.
I want column B's cells to be =D1*A1 , =D1*A2,... Note D1 should not change.
When I drag the fields down or use (Edit > Fill...) it changes D1 to D2, D3,... How can I keep one field fixed for autofill?
Holding ctrl button down does not help.
Any idea?

A:

Make your "master" formula =D$1*A1. That flags the 1 in the D$1 part as being constant. You could also make the D part constant with =$D$1*A1, but since you stated this is a single column, it shouldn't matter in this case.
Note that this also works for Microsoft Excel, and I think that it's been a common feature of almost all spreadsheets since way back to supercalc on HDOS.

A:

I just found another way (that is not easier than twalberg's, but worth mentioning)...
You can define a name (Insert > Names... Define). Select a field and give it a name. Then the name in your formulas.


Q:

zipcodes within a specific radius

I'm looking for an SQL query to let me retrieve Zipcodes within a specific radius.
I have a table called tblZip with columns: Zipcode, Lat(latitude), Long(Longitude).
tblZip

Zipcode    | Lat    | Long
Short Text | Number | Number

I have checked few other answers that suggest use of Great-circle Distance but I don't seem to understand how it works.  I get a headache just seeing all the conversions from / to radians and degrees and I really tried to understand it, but I'm so bad with mathematics.
I appreciate your help and guidance.
PS: I'm using a Microsoft Access Database.

A:

Consider using the haversine distance formula in a VBA function (borrowed here). Then have it called in your SQL query. And even have your query filtered by distance with WHERE clause per your needs. Do note: this solution will only work inside the MSAccess.exe program. You will not be able to call it externally via ODBC/OLEDB.
And since you need comparison geocodes, SQL query below uses a cross join where each record is compared with every other record in table. Additionally, query avoids reverse duplicates and same-matched pairings reducing the size. But be careful if table is large as cross joins on self returns N2 records, that is before the filtering of duplicates.
SQL (Zipcode pairings with distance of 5 km or less)
SELECT z1.Zipcode, z2.Zipcode,
       GetDistance(z1.Lat, z1.Lon, z2.Lat, z2.Lon) As km_distance
FROM tblZip z1, tblZip z2
WHERE z1.Zipcode > z2.Zipcode
AND GetDistance(s1.lat, s1.lon, s1.lat, s2.lon) <= 5;

VBA (save in a standalone module)
Function GetDistance(lat1Degrees As Double, lon1Degrees As Double, lat2Degrees As Double, lon2Degrees As Double) As Double

    Dim earthSphereRadiusKilometers As Double
    Dim kilometerConversionToMilesFactor As Double
    Dim lat1Radians As Double
    Dim lon1Radians As Double
    Dim lat2Radians As Double
    Dim lon2Radians As Double
    Dim AsinBase As Double
    Dim DerivedAsin As Double

    'Mean radius of the earth (replace with 3443.89849 to get nautical miles)
    earthSphereRadiusKilometers = 6371

    'Convert kilometers into miles (replace 0.621371 with 1 to keep in kilometers)
    kilometerConversionToMilesFactor = 0.621371

    'Convert each decimal degree to radians
    lat1Radians = (lat1Degrees / 180) * (4 * ATN(1))
    lon1Radians = (lon1Degrees / 180) * (4 * ATN(1))
    lat2Radians = (lat2Degrees / 180) * (4 * ATN(1))
    lon2Radians = (lon2Degrees / 180) * (4 * ATN(1))

    AsinBase = Sin(Sqr(Sin((lat1Radians - lat2Radians) / 2) ^ 2 + Cos(lat1Radians) * Cos(lat2Radians) * Sin((lon1Radians - lon2Radians) / 2) ^ 2))
    DerivedAsin = (AsinBase / Sqr(-AsinBase * AsinBase + 1))

    'Get distance from [lat1,lon1] to [lat2,lon2]
    GetMiles = Round(2 * DerivedAsin * (earthSphereRadiusKilometers * kilometerConversionToMilesFactor), 2)

End Function


Q:

Invalidate pointer values inside a QMap

I'm having what seems to be a weird issue, but it could be a quirk of how QMap's work and I just don't understand it.  It's tough to summarize the problem, but I'll do my best.
I have a class A, with a QMap<QString, someType*> mySomeTypeMap;.  When I load a new file in my program, I want to delete all the contents of this QMap so I can repopulate it with new data.  I do that by doing the following:
foreach (QString key, mySomeTypeMap.keys())
{
    someType* toDelete = mySomeTypeMap.take(key);

    //Show me the original address of the pointer
    qDebug() << "toDelete: " << toDelete;

    delete toDelete;

    //Set the pointer to 0x0
    toDelete = NULL;
}

The qDebug() statement prints out the correct address of the value I want to delete, and when I look at toDelete in the debugger after it gets set to NULL, it says 0x0, which is what I want.
Then later, in a different class B, I have the following code...
void B::setSomeType(someType* blah)
{
    if (Blah != NULL)
    {
        //Calls a bunch of disconnect()'s
        disconnectAllSignals();

        Blah = blah;

        //Calls a bunch of connect()'s
        connectAllSignals();
    }
}

Now, what's really confusing is my program crashes when it gets to the disconnectAllSignals(); line.  The reason being it's trying to call disconnect() on Blah which was deleted and should have been set to 0x0 when I set it to NULL.  However, if it was actually set to NULL it never would have entered that if-block to begin with.  In a debugger, I see that the address of Blah is exactly the same as what I get when I print out qDebug() << "toDelete: " << toDelete; right before setting toDelete = NULL;.
TLDR; I don't know how my program is getting the orignal address of a pointer back after I delete the pointer and set the same pointer to NULL.  Since the pointer isn't set to NULL later in the execution it leads to a crash.

A:

Values in the map are stored by value even if in these case it means that the pointer (address which it points) is stored by value.
For example:
someType* toDelete1 = mySomeTypeMap.take(key);
someType* toDelete2 = mySomeTypeMap.take(key);
someType* toDelete3 = toDelete1;
toDelete1 = NULL;

toDelete2 & toDelete3 will still point to the original object
Instead of making the pointer null after delete you should either remove it from the map or set the value for that key to NULL.


Q:

How to remove second largest element in a list in haskell?

I have created a program to remove first smallest element but I dont how to do for second largest:
withoutBiggest (x:xs) =
   withoutBiggestImpl (biggest x xs) [] (x:xs)
     where
       biggest :: (Ord a) => a -> [a] -> a
       biggest big [] = big
       biggest big (x:xs) =
         if x < big then
           biggest x xs
         else
           biggest big xs
       withoutBiggestImpl :: (Eq a) => a -> [a] -> [a] -> [a]
       withoutBiggestImpl big before (x:xs) =
         if big == x then
           before ++ xs
         else
             withoutBiggestImpl big (before ++ [x]) xs

A:

Here is a simple solution.
Prelude> let list = [10,20,100,50,40,80]
Prelude> let secondLargest = maximum $ filter (/= (maximum list)) list
Prelude> let result = filter (/= secondLargest) list
Prelude> result
[10,20,100,50,40]
Prelude>


Q:

Checkstyle Multiline regex for specific methods

I'm working on java checkstyle configuration in Eclipse. I need to add warning for all public methods that don't consist specific code in the first line. Example:
public void doA(){
    blabla();
    //some code
}

public String doB(int i){
    blabla();
    //some code
}

public Boolean doC(String str){
    //some code
}

What I want from checkstyle is to mark the line or report error when there is method that has public modifier and doesn't start with calling  blabla() method. I tried to make some multiline regexp strings with /n as a newline but so far no success.
edit: so far I tried this but without success:
<module name="RegexpMultiline">
    <property name="format" value="(public)(\\s+)((?:[a-z][a-z0-9_]*))(\\s+)((?:[a-z][a-z0-9_]*))(\\(.*\\))(\\{)(/n)(blablabla)"/>
    <property name="message" value="Public method should have blablabla."/>
</module>

A:

Use Pattern.MULTILINE directive in the search pattern: "(?m)...\\s*...". This applies the pattern across lines.
Use Pattern.DOTALL directive in the search pattern: "(?s)...\\s*...". This captures '\nwith a.`.
Use it combined: "(?ms)...".


Q:

Windows Update under windows 10 - Very limited information, how to get more information?

I've installed Windows 10 on a PC, and I've noticed that the Windows Update process seems a lot like a black box, there is no information on how long updates will take if the PC needs to be restarted for an update to be installed etc.
Is there any way of getting a bit more information about whats going on with the updates outside of the "Settings app"?

A:

The short answer here is No.
The long answer:
The Windows Update section in the 'settings' app gives a decent amount of information.

The number of updates and their names
The progress bars for 'update downloading' and 'update installing'
Notification as to whether you system needs to restart after installing (since it checks afterwards if any important areas have been updated, which will require a restart).

An update will always need to be 'installed', this just how the system works.
If you are getting any less information than what I have highlighted above, then there is a problem with your system.


Q:

"There are" with or without additional "there"

When starting a sentence with "there are" is it necessary to put additional "THERE" in the sentence? Like in:
The Snieznik Mountains is situated in the East Sudets.  There are a lot of charming forest areas (there), with the richest world of plants and animals in southwest Poland.
Is there any rule that tells you when to use or not to use additional THERE in sentences of that type?

A:

There are a lot of charming forest areas there.

The first there and the second there are completely different. The first there has no meaning. We use it because the English verb BE has two spaces. It has a space for the Subject before the verb, and a space for a Complement after the verb. Both spaces must be full for the sentence to be grammatical:

Is a problem. (ungrammatical - empty Subject space)
A problem is. (ungrammatical - empty Complement space)
There is a problem. (grammatical  - both spaces are being used).

The last sentence is grammatical. But the Subject pronoun there has no meaning. It doesn't mean in that place. The sentence as a whole means something like a problem is or is a problem, but we aren't allowed to use those sentences in English. Some people say the sentence means something like A problem exists. This dummy Subject there does not mean in that place.
The second there is a preposition phrase. It tells us about the location of something. It means something like in that place.
The first there is obligatory. We have to use it. The second there meaning in that place is optional. We will only use it if we want to show that we are talking about something in that place.

There are a lot of charming forest areas.

... means something like:

A lot of charming forest areas exist

There are a lot of charming forest areas there.

... means something like:

A lot of charming forest areas are in that place / exist in that place.

You can choose which sentence you want to use based on the meaning. The difference is that the preposition there is optional in the grammar. (It might not be optional in terms of the meaning you want to communicate)


Q:

AWS Lambda copyObject "Process exited before completing request"

I am trying to copy files uploaded to an S3 bucket to create timestamped backups. (the 'live' file will overwritten periodically to maintain a perma-link)
AWScopyObject, however, does not seem to be executing. I am getting the following error
 {
       "errorMessage": "Process exited before completing request"
 }

The code that causes this error is as follows;
    console.log('Loading function');
var AWS = require('aws-sdk');
var s3 = new AWS.S3();

exports.handler = function(event, context) {
    var srcBucket = event.Records[0].s3.bucket.name;
    var srcKey    = event.Records[0].s3.object.key;
    var dstKey    = srcBucket+'/backup/'+ Date.now() + '-' +srcKey;

    console.log(srcKey);
    console.log(dstKey);

    var copyParams = {
        Bucket: srcBucket,
        CopySource : srcBucket + '/' + srcKey,
        Key: dstKey
    };

s3.copyObject(
    copyParams,
    function (err, data) {
        if (err) {
            console.log("ERROR copyObject");
            console.log(err);
        }
        else {
            console.log('SUCCESS copyObject');
        }
        context.done();
    });

};

What could be causing lambda to exit before the AWSCopyObject callback? According to https://aws.amazon.com/blogs/compute/container-reuse-in-lambda/ this error suggests context.done() is never hit.

A:

I was facing similar issue, seems issue i was getting only when i try to test using AWS Lambda console, But when i tried to execute test with real bucket(uploaded a test file) and Lambda function executed successfully.
Try to see 'Log output' you will get more detail about actual error which you are getting.
Thanks


Q:

Git: How to revert everything but current working head on to a previous commit

In git I already ran git add -u && git commit -a --amend to my working changes. I did not push the new commit to origin. I now found some previous git revision broke the build.
I want to keep my new commit, but go back to the last known 'good' git revision: say 04c06eb2acf154ba0e7f4e27044d1dffa6a42473.
I could run git reset --hard 04c06eb2acf154ba0e7f4e27044d1dffa6a42473 but that would lose my current revision
I also can't use git rebase -i HEAD~100 because the last good branch was a long time ago.
What is the best way to achieved my desired result?

A:

I would just "back up" your last commit with
git format-patch -1

then undo what "broke" the build. After this you might need to manually apply the patch file, but you wont have lost anything.


Q:

Sinatra app is not starting the internal webserver

I have a very simple Sinatra app to test.
ubuntu@ip:~/helloworld$ cat app.rb
# app.rb
require 'sinatra'

class HelloWorldApp < Sinatra::Base
  get '/' do
    "Hello, world!"
  end
end
ubuntu@:~/helloworld$ cat config.ru
# config.ru
require './app'
run HelloWorldApp

When I start it on Ubuntu, it runs like this. It is not starting the listener.
Or the webserver
$ rackup
[2016-03-18 22:23:58] INFO  WEBrick 1.3.1
[2016-03-18 22:23:58] INFO  ruby 2.2.3 (2015-08-18) [x86_64-linux]
[2016-03-18 22:23:58] INFO  WEBrick::HTTPServer#start: pid=18049 port=9292

Or this way
$ ruby app.rb
[2016-03-18 22:28:00] INFO  WEBrick 1.3.1
[2016-03-18 22:28:00] INFO  ruby 2.2.3 (2015-08-18) [x86_64-linux]
== Sinatra (v1.4.7) has taken the stage on 4567 for development with backup from WEBrick
[2016-03-18 22:28:00] INFO  WEBrick::HTTPServer#start: pid=18087 port=4567

Where as on a Mac, when I start the an app, it runs like this.
$ ruby app.rb
== Sinatra (v1.4.7) has taken the stage on 4567 for development with backup from Thin
>> Thin web server (v1.3.1 codename Triple Espresso)
>> Maximum connections set to 1024
>> Listening on localhost:4567, CTRL+C to stop

It is listening on Localhost. What's the problem with my Ubuntu that it is not able to start the internal webserver. Any troubleshooting instructions?

A:

I think there are a couple of things going on here.
First, Thin versus Webrick. Rack and Sinatra will both try to find a suitable webserver to use when starting. They will look for Thin, but if it is not available they will both fall back to using Webrick. The solution is to install Thin on your Ubuntu server with gem install thin. You might want to look into using Bundler and adding the thin gem to it to ensure you always have the same gems in development and production.
Second, accessing the server from another machine. By default, when starting up in development mode both rackup and Sinatra’s built in server will only listen to localhost. To bind to 0.0.0.0 you will either need to specify the host explicitly (either with the -o option to rackup or with set :bind '0.0.0.0' for the Sinatra built in sever), or start in production mode using the RACK_ENV environment variable.
One additional thing – in your current setup running ruby app.rb won’t actually start your application. It will run the default Sinatra::Application (which in this case is empty) rather than your HelloWorldApp, since you are using the modular style. To get this to run as you expect you should change your require line to
require 'sinatra/base'

and add
HelloWorldApp.run! if app_file == $0

to the end of the file.


Q:

Confusion as to the meaning of `cid` in webform.module

I'm working on a custom module that will return a single question at a time from an existing webform. For example, from the path mymodule/(webform_nid)/(question).
This is my first encounter with cid.
From the documentation on webform_components_form(), it appears that cid represents a component id. (Elsewhere in the Drupal API documentation and on forums, I have seen it referred to as comment id).
Quickly analyzing some test data, it appears that, as a child element of a webform nid, I can reliably use it to sequentially retrieve single questions from a given webform nid.
Am I correct that cids are unique and sequential per nid? I assume the implementation of cid was done to maintain variable name convention.
Or is a cid a unique value assigned to each 'component' across the entire site, as its implementation as comment id would suggest (because you can load an existing comment without loading its node, it would need to be a globally-unique value like nid)?

A:

A quick look at the webform_component table in the database, the description for that field is: "The identifier for this component within this node, starts at 0 for each node."
In my test, however, the first component has a cid of 1.  AND - keep in mind that if you delete a component, the next cid is incremental - so you can't assume 1 - 6 or whatever.


Q:

JavaScript & XML How to bring in more information?

I have the following JavaScript which brings in some data from a XML file:
function ajaxRequest(){
 var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"] //activeX versions to check for in IE
 if (window.ActiveXObject){ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
  for (var i=0; i<activexmodes.length; i++){
   try{
    return new ActiveXObject(activexmodes[i])
   }
   catch(e){
    //suppress error
   }
  }
 }
 else if (window.XMLHttpRequest) // if Mozilla, Safari etc
  return new XMLHttpRequest()
 else
  return false
}

var mygetrequest=new ajaxRequest()
if (mygetrequest.overrideMimeType)
 mygetrequest.overrideMimeType('text/xml')
mygetrequest.onreadystatechange=function(){
 if (mygetrequest.readyState==4){
  if (mygetrequest.status==200 || window.location.href.indexOf("http")==-1){
   var xmldata=mygetrequest.responseXML //retrieve result as an XML object
   var rssentries=xmldata.getElementsByTagName("TUTORIAL")
   var output='
'
   for (var i=0; i<rssentries.length; i++){
    output+='
'
    output+=''
    output+=rssentries[i].getElementsByTagName('TITLE')[0].firstChild.nodeValue+''
    output+='
'
   }
   output+='
'
   document.getElementById("result").innerHTML=output
  }
  else{
   alert("An error has occured making the request")
  }
 }
}

mygetrequest.open("GET", "../xml/tutorials.xml", true)
mygetrequest.send(null)

Here is the XML file:
<?xml version="1.0" encoding="ISO-8859-1"?>

<rss version="0.91">
<channel>
<title>Script Tutorials</title>
<link>http://www.script-tutorials.com</link>
<description>Web Topics Tutorials</description>
<language>en</language>

    <TUTORIAL>
        <DATE>19/08/2014</DATE>
        <CATEGORY>HTML/CSS</CATEGORY>
        <TITLE>Sliding single-level menu</TITLE>
        <DESCRIPTION>Menu is one of the important components of any site. Today it is difficult to find a website without the navigation menu. Today we have prepared a modern looking single-level menu. You might think  again, but the menu looks really interesting, its feature is a sliding panel which highlights the active elements.</DESCRIPTION>
        <LINK>http://www.script-tutorials.com/sliding-single-level-menu/</LINK>
    </TUTORIAL>
    <TUTORIAL>
        <DATE>01/11/2013</DATE>
        <CATEGORY>HTML/CSS</CATEGORY>
        <TITLE>Whirling CSS3 dropdown menu</TITLE>
        <DESCRIPTION>Various dropdown menus can be easily created with CSS3 with the help of selectors. Just connect your imagination  and you will create a truly new and unique design. In todays lesson, we will create a new CSS3 drop-down menu with new effect: when you hover on the upper menu items, the submenu items appear whirling. Just follow this tutorial to see the step by step process of building this menu.</DESCRIPTION>
        <LINK>http://www.script-tutorials.com/whirling-dropdown-menu/</LINK>
    </TUTORIAL>
    <TUTORIAL>
        <DATE>22/03/2012</DATE>
        <CATEGORY>HTML/CSS</CATEGORY>
        <TITLE>Pure CSS3 LavaLamp Menu</TITLE>
        <DESCRIPTION>I think that you have already seen animated menus with LavaLamp effect (based on jQuery plugin). Today I would like you to tell how to repeat same behavior only with CSS3 (without any javascript). I have to use CSS3 transitions in our menu (to animate elements). So, if you are ready, lets start.</DESCRIPTION>
        <LINK>http://www.script-tutorials.com/pure-css3-lavalamp-menu/</LINK>
    </TUTORIAL>
    <TUTORIAL>
        <DATE>13/03/2012</DATE>
        <CATEGORY>HTML/CSS</CATEGORY>
        <TITLE>CSS3 vertical multicolor 3D menu</TITLE>
        <DESCRIPTION>In our new tutorial well create new stylish vertical multicolor and crossbrowser CSS3 menu with 3D animation (I use css3 transition, perspective and transform properties) and pure css3 color switcher. This is UL-LI-based menu</DESCRIPTION>
        <LINK>http://www.script-tutorials.com/css3-vertical-multicolor-3d-menu/</LINK>
    </TUTORIAL>
    <TUTORIAL>
        <DATE>13/02/2012</DATE>
        <CATEGORY>HTML/CSS</CATEGORY>
        <TITLE>CSS3 multicolor menu</TITLE>
        <DESCRIPTION>In our new tutorial well create a new nice multicolor and crossbrowser CSS3 menu with sliding (I use css3 transition) and color pure css3 color switcher. This is UL-LI-based menu.</DESCRIPTION>
        <LINK>http://www.script-tutorials.com/css3-multicolor-menu/</LINK>
    </TUTORIAL>
    <TUTORIAL>
        <DATE>03/01/2012</DATE>
        <CATEGORY>HTML/CSS</CATEGORY>
        <TITLE>CSS3 multilevel menu with transition and animation</TITLE>
        <DESCRIPTION>In our new tutorial well create a new nice CSS3 menu with interesting behavior, where I use css3 transition and animation. This is UL-LI-based multilevel menu.</DESCRIPTION>
        <LINK>http://www.script-tutorials.com/css3-multilevel-menu-with-transition-and-animation/</LINK>
    </TUTORIAL>
    <TUTORIAL>
        <DATE>25/09/2013</DATE>
        <CATEGORY>AJAX</CATEGORY>
        <TITLE>PHP AJAX Calendar</TITLE>
        <DESCRIPTION>The calendar is an integral part of many websites, frequently, this is one of numerous jQuery calendar plugins, but it can also be implemented using php. Today I will show you how to create a monthly calendar with the ability to scroll (left and right arrows) through the months using AJAX technology. Besides of ajax, this calendar has another important advantage, it is mobile-ready calendar with the responsive layout. Before we start writing code, I recommend that you look at our demo to see what were going to do.</DESCRIPTION>
        <LINK>http://www.script-tutorials.com/php-ajax-calendar/</LINK>
    </TUTORIAL>
    <TUTORIAL>
        <DATE>16/11/2011</DATE>
        <CATEGORY>AJAX</CATEGORY>
        <TITLE>Creating Your Own Ajax Poll System</TITLE>
        <DESCRIPTION>Today I prepared new interesting tutorial  we will creating own Poll system (AJAX) for your projects with PHP. Polls, answers and results I going to keep in single SQL table. When we will vote for one of variants  jQuery will POST data, and then we will animate our results in realtime.</DESCRIPTION>
        <LINK>http://www.script-tutorials.com/creating-own-ajax-poll-system/</LINK>
    </TUTORIAL>
    <TUTORIAL>
        <DATE>11/10/2010</DATE>
        <CATEGORY>AJAX</CATEGORY>
        <TITLE>Autocomplete with PHP, jQuery, MySQL and XML</TITLE>
        <DESCRIPTION>Today I have new article for PHP. I will tell you about implementation autocomplete for your sites. Data can be located in different sources  directly in the JS code, in the database, and even in the XML file.</DESCRIPTION>
        <LINK>http://www.script-tutorials.com/autocomplete-with-php-jquery-mysql-and-xml/</LINK>
    </TUTORIAL>
    <TUTORIAL>
        <DATE>23/09/2010</DATE>
        <CATEGORY>AJAX</CATEGORY>
        <TITLE>Creating Ajax based file uploaders</TITLE>
        <DESCRIPTION>How to upload files without refreshing whole page during submitting. Hope this will interesting to you. Lets check 2 methods  using ordinary iframes and external library. Also I will using jQuery in work too (I like it).</DESCRIPTION>
        <LINK>http://www.script-tutorials.com/ajax-file-upload-methods/</LINK>
    </TUTORIAL>
    <TUTORIAL>
        <DATE>05/09/2013</DATE>
        <CATEGORY>JavaScript</CATEGORY>
        <TITLE>How to Create a Lightbox Ultra Using CSS and JavaScript</TITLE>
        <DESCRIPTION>The creation of CSS animation has brought an amazing feature for the web designers and coders to tinker on to show their own creativity. With the advent of Lightbox, they have a better tool to use in creating their own images with 3D animation effects as well as background dimming capability that removes the distraction of viewing the image better. Combining Lightbox with CSS and JavaScript does offer web coders a valuable tool to enhance their techniques in creating great 3D animation with Lightbox using the following concepts to use in your own coding design projects</DESCRIPTION>
        <LINK>http://www.script-tutorials.com/how-to-create-a-lightbox-ultra-using-css-and-javascript/</LINK>
    </TUTORIAL>
    <TUTORIAL>
        <DATE>23/10/2013</DATE>
        <CATEGORY>JavaScript</CATEGORY>
        <TITLE>HTML5 Audio player with playlist</TITLE>
        <DESCRIPTION>Many of you faced with the task of creating audio player at least once in your life. Quite often , you simply choose one of the available players, often it was the flash player. However, you may have already noticed, that these flash players do not work properly on mobile devices (iPhone / Android). Today I am going to tell you about how to create your own audio player (using HTML5 technology). This player consists of next elements: title, author, cover, basic controls (play / pause, rewind / forward) , two sliders (jQuery UI sliders): volume slider and and a song tracker, and even more: we will also have a playlist with a list of available songs.</DESCRIPTION>
        <LINK>http://www.script-tutorials.com/html5-audio-player-with-playlist/</LINK>
    </TUTORIAL>
    <TUTORIAL>
        <DATE>10/08/2012</DATE>
        <CATEGORY>JavaScript</CATEGORY>
        <TITLE>How to display twitter posts using javascript</TITLE>
        <DESCRIPTION>I think that displaying your Twitter posts on your website is a wonderful way to show people in-time news. This feature can be very useful for your project. Because it can can inspire your websites visitors to follow you on Twitter. I am going to create simple script which loads twitter posts and renders into HTML format using JsRender jQuery library. Everything is on the client side.</DESCRIPTION>
        <LINK>http://www.script-tutorials.com/how-to-display-twitter-posts-using-javascript/</LINK>
    </TUTORIAL>
    <TUTORIAL>
        <DATE>01/02/2012</DATE>
        <CATEGORY>JavaScript</CATEGORY>
        <TITLE>Form Validation with Javascript and PHP</TITLE>
        <DESCRIPTION>In this tutorial, we will show you how to create an attractive, pleasant to look form for your website, and then we will explain how to dynamically validate it using Javascript. The server-side validation with PHP will be covered too (to make everything 100% safe). This tutorial will help you to add more functionality to your forms that leads to better user experience and better website quality.</DESCRIPTION>
        <LINK>http://www.script-tutorials.com/form-validation-with-javascript-and-php/</LINK>
    </TUTORIAL>
    <TUTORIAL>
        <DATE>08/09/2010</DATE>
        <CATEGORY>JavaScript</CATEGORY>
        <TITLE>Easily Animate Web Buttons/Objects using jQuery</TITLE>
        <DESCRIPTION>Today I will tell you about animations in web using jQuery. As we know  jQuery offer us several default methods of effects: fade(In/Out/To), hide, show, slide(Down/Toggle/Up), toggle. This is ok, but what if we need more? So, animation will help us! It will help to slide between 2 states using really good effects. By default, easing is optional param, so to use extra effects we will use additional jquery.easing.js library.</DESCRIPTION>
        <LINK>http://www.script-tutorials.com/easily-animate-web-buttonsobjects-using-jquery/</LINK>
    </TUTORIAL>
    <TUTORIAL>
        <DATE>01/06/2010</DATE>
        <CATEGORY>JavaScript</CATEGORY>
        <TITLE>Import RSS Feeds using jFeed (jQuery)</TITLE>
        <DESCRIPTION>This simple tutorial will show you how to Import rss feeds of any site into your own custom area/block of website. It can be used as news imported from yahoo, bbc etc. As we know, RSS feeds are usually used to trasnfer some news for people. Today Ill tell you about RSS feeds and show you how to make an own RSS aggregator. In the result, you will be able to display various RSS feeds on your website with nite and modern design.</DESCRIPTION>
        <LINK>http://www.script-tutorials.com/import-rss-feeds-using-jfeed-jquery/</LINK>
    </TUTORIAL>
    <TUTORIAL>
        <DATE>04/08/2010</DATE>
        <CATEGORY>JavaScript</CATEGORY>
        <TITLE>Importing multiple RSS feeds  using newsWidget (jQuery)</TITLE>
        <DESCRIPTION>Some times ago I told how to display rss feed at our website. But some times ago my friend ask me how to display in single box feeds from multiple sources. I decided to investigate it and located NewsWidget library. Lets check its possibilities.
        </DESCRIPTION>
        <LINK>http://www.script-tutorials.com/importing-multiple-rss-feeds-using-newswidget-jquery/</LINK>
    </TUTORIAL>
    <TUTORIAL>
        <DATE>27/11/2014</DATE>
        <CATEGORY>Design</CATEGORY>
        <TITLE>Visual structure  A definitive guide for web UI designers</TITLE>
        <DESCRIPTION>Creativity works wonders when it comes to designing the UI(user interface) for a website or web application. Right from changing the composition, color and size to everything else that forms a crucial component of a web design UI; you can perform all this and much more by revealing the creative side of your personality. Visual hierarchy is something that can give the much needed push to your web UI designing initiative. By including the right type of visual elements into your web design, you can easily grab the attention of targeted audience within a very small period of time. Keep on reading this blog to find more about creating a visual structure of your web UI(user interface).</DESCRIPTION>
        <LINK>http://www.script-tutorials.com/visual-structure-a-definitive-guide-for-web-ui-designers/</LINK>
    </TUTORIAL>
    <TUTORIAL>
        <DATE>08/07/2014</DATE>
        <CATEGORY>Design</CATEGORY>
        <TITLE>How to design the site?</TITLE>
        <DESCRIPTION>In this article we will look at such aspects of website designing as: choosing an editor for preparing the site layout, defining sizes of the site, how to save sources, how to work with text and more. This article is mainly targeted for beginning web designers.</DESCRIPTION>
        <LINK>http://www.script-tutorials.com/how-to-design-the-site/</LINK>
    </TUTORIAL>
    <TUTORIAL>
        <DATE>14/05/2014</DATE>
        <CATEGORY>Design</CATEGORY>
        <TITLE>20 Tips and Examples for Creating the Perfect Design Portfolio</TITLE>
        <DESCRIPTION>Creating and managing a portfolio is the best way to market yourself. It is a reflection of the work you do and its essential for you to attract clients. As a designer, you must have a portfolio. If so, you need to ask yourself a few questions before you can actually begin to develop it further. How much time do you allow yourself in dedication to improving your portfolio? Do you think you have your best stuff on it? One thing is for sure  it does not matter whether your portfolio exists physically or digitally, the point is to keep improving i</DESCRIPTION>
        <LINK>http://www.script-tutorials.com/20-tips-and-examples-for-creating-the-perfect-design-portfolio/</LINK>
    </TUTORIAL>
    <TUTORIAL>
        <DATE>25/06/2014</DATE>
        <CATEGORY>Design</CATEGORY>
        <TITLE>What is a color model?</TITLE>
        <DESCRIPTION>Probably everyone who is engaged in advertising, had to hear such phrases as light model, print file should be in CMYK, and for posting on the site  RGB. Some may even know about the existence of such color models as GreyScale, LAB, HSB and HLS. But what exactly are these Color models? How is CMYK color model different from RGB or LAB?</DESCRIPTION>
        <LINK>http://www.script-tutorials.com/what-is-a-color-model/</LINK>
    </TUTORIAL>

</channel>
</rss>

And it outputs to HTML file like below:
http://www.imagebam.com/image/2787cc369647181
However, I also would like under each link .... the date, category and description. With a line break between each tutorial.
Any ideas?
I know how to turn off list style ... but I will need something like this for the other XML data do I not?
output+=rssentries[i].getElementsByTagName('DATE')[0].firstChild.nodeValue+

output+=rssentries[i].getElementsByTagName('CATEGORY')[0].firstChild.nodeValue+

output+=rssentries[i].getElementsByTagName('DESCRIPTION')[0].firstChild.nodeValue+

I have tried using these but I cannot get it to work.
I want it to look like this:

Sliding single-level menu
HTML/CSS
19/08/2014
Menu is one of the important components of any site. Today it is difficult to find a website without the navigation menu. Today we have prepared a modern looking single-level menu. You might think  again, but the menu looks really interesting, its feature is a sliding panel which highlights the active elements.

A:

If you want to create separation between groups of
s in your
 you can insert either   or
 or both between the groups
output+='
'
output+=''
output+=rssentries[i].getElementsByTagName('TITLE')[0].firstChild.nodeValue+''
output+='
'
output+='
'
output+='
< >
'

So if you are trying to make the second line look like an extension of the first line you can turn off the bullet with LIST-STYLE-TYPE: none;  So the whole effect would look like this:
Working example HERE

 Line 1

 Line 2

 </>

 Line 1

 Line 2

 </>


Q:

Hudson - job is stuck, how to kill it?

I have a job running under Hudson that has not progressed from "Started by user anonymous". How can I stop it? I tried restarting the Hudson server but it just resumed the job on startup.
It can't be killed by the normal cancel build button.
Thanks.

A:

Hudson was waiting for SVN to respond - SVN was waiting for the permission for my id to use the repository. Once this was there Hudson started working again.
I would presume that in this instance there would have been an SVN process I would have needed to kill in order to get Hudson to respond again.


Q:

Forces acting on a cylinder

In some amusement parks there is a ride which is effectively a hallow cylinder which can rotate about its vertical axis. The riders stand on horizontal base of the cylinder and in contact with the curved surface of the cylinder. When the angular speed reaches a certain value the floor is dropped but the riders remain in contact with the curved surface of the cylinder. The radius of the cylinder is 2.5m, and the speed of rotation is 30 revolutions per minute.
How do I draw the forces acting on this cylinder if people are modelled as a particle?
And how do I find the smallest possible coefficient of friction between the rider and the cylinder surface so that the ride works effectively?
I found the velocity but where do I go from here?

A:

Let $\omega$ be the angular speed so$$\omega=\frac{30\times2\pi}{60}$$ radians per second
Draw the normal reaction $N$ horizontally in the same direction as the acceleration $r\omega^2$. The limiting friction is $\mu N$ acting vertically upwards, and the weight is $mg$ vertically downwards.
So you then have $$\mu N=mg$$ and $$N=mr\omega^2$$
So you can solve to get $\mu$


Q:

Controller cannot insert into notification table in yii

So I have one primary table comment that has a number of fields. Then
I want to insert some fields into a notifications table whenever a new record is inserted into comment table.
In the controller, initially I had this and it worked for comment table:
public function actionCreate() {
    $model = new Comment;
    if (isset($_POST['Comment'])) {
        $model->attributes = $_POST['Comment'];
        if ($model->save())
            $this->redirect(array('view', 'id' => $model->comment_id));
    }
    $this->render('create', array(
        'model' => $model,
    ));
}

Then I put some more lines for the notification table. But it didn't work.
public function actionCreate() {
    $model = new Comment;
    $notif = new Notifications;
    if (isset($_POST['Comment'])) {
        $model->attributes = $_POST['Comment'];
        $notif->peg = 'nofriani';
        $notif->tanggal = new CDbExpression("NOW()");
        $notif->notif = ' mengirimkan berita ';
        $notif->isi = $_POST['Comment']['post_id'];
        $notif->link = 'links';
        $notif->save();
        if ($model->save())
            $this->redirect(array('view', 'id' => $model->comment_id));
    }
    $this->render('create', array(
        'model' => $model,
    ));
}

The function for comment table still works. But the one for notifications table doesn't. I tried to rearrange the positions but nothing happened. I also changed the $notif->save(); into $notif->insert(); but still nothing happened. What have I missed?
This is the table structure:
CREATE TABLE IF NOT EXISTS notifications (
   id_notif int(11) NOT NULL AUTO_INCREMENT,
   tanggal date NOT NULL,
   peg varchar(30) NOT NULL,
   notif text NOT NULL,
   isi varchar(30) NOT NULL,
   link varchar(255) NOT NULL,
   PRIMARY KEY (id_notif)
 ) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

A:

I could not find any mistakes in your code.
Bellow are my assumptions to debug above task

May be $_POST['Comment']['post_id'] is not supplying the value.
Print Post values and check whether you are getting all necessary values.
 print_r($_POST['Comment']);

Validate $notif model before save(). It will display the validation errors if your model has.
echo CActiveForm::validate($notif);

You can write above code in a better way as bellow.
    $model = new Comment;
    $notif = new Notifications;
    if (isset($_POST['Comment']))
    {
        $model->attributes = $_POST['Comment'];
        if ($model->validate() && $model->save())
        {
            $notif->peg = 'nofriani';
            $notif->tanggal = new CDbExpression("NOW()");
            $notif->notif = ' mengirimkan berita ';
            $notif->isi = $_POST['Comment']['post_id'];
            $notif->link = 'links';
            if($notif->validate() && $notif->save())
            {
                $this->redirect(array('view', 'id' => $model->comment_id));
            }
            else
            {
                echo CActiveForm::validate($notif);
                Yii::app()->end();
            }
        }
        else
        {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }


Q:

Django Select Related in Template Paginated Search Results to Reduce Queries?

I have a model (products) which is actually containing a number of many-to-many fields.
Ideally I am trying to reduce queries to the number of products themselves -- 25, but considering the depth of foreignkeys and m2ms, I understand this might not be possible. But still I'm shooting for best results.
Here is my view:
def index(request):
    products = Product.objects.select_related()
    paginator = Paginator(products, 25)
    page = request.GET.get('page')

    try:
        products = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        products = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        products = paginator.page(paginator.num_pages)

    print (len(connection.queries))
    return render(request, 'editor-index.html', {
        'products': products,
        'connection':connection,
        'csrf':csrf(request)
        })

How can I reduce the queries in this? It would be best to prefetch all data related to the product. Is such a thing possible?

A:

select_related only works for foreign keys. For many to many fields you can use prefetch_related. I think that with prefect related you have to specify the related models you want to fetch, and that you can't call it with no arguments like select_related.
Note that you shouldn't need 25 queries for 25 products. It should be possible to reduce it to one query for the products queryset, one additional query for each prefetch_related argument, and (because you are using a paginator) one for the total number of objects.


Q:

CloudBlob.OpenRead() is not reading all data

With windows Azure Storage Client Library, CloudBlob.OpenRead() method reads only 4 mb of data. How can I read full stream using OpenRead method.
CloudBlob blob = container.GetBlobReference(filename);
Stream stream = blob.OpenRead();

I must use OpenRead method. Can't use DownloadToFile or DownloadToStream.
EDIT :
The consumer code which is outside my scope calls
stream.CopyTo(readIntoStream);

CopyTo is an extension method.
public static int CopyTo(this Stream source, Stream destination)
        {
            byte[] buffer = new byte[BUFFER_SIZE];
            int bytesRead;
            int bytesCopied = 0;

            do
            {
                bytesRead = source.Read(buffer, 0, BUFFER_SIZE);
                if (bytesRead > 0)
                    destination.Write(buffer, 0, bytesRead);
                bytesCopied += bytesRead;
            }
            while (bytesRead > 0);

            return bytesCopied;
        }

EDIT 2 :
I have observed that when file is uploaded using blob.UploadText() method, it works fine but when blob is uploaded using OpenWrite method as done in following code sample, the OpenRead Method reads only 4194304 bytes (4 mb).
using(var input = File.OpenRead(@"C:\testFile.txt")) //5000000 bytes
using (var output = blob.OpenWrite())
{
       input.CopyTo(output);
}

EDIT 3 :
Complete code that produces the issue at my end.
 static void Main(string[] args)
    {
        var blobContainer = GetContainer("tier1");
        blobContainer.CreateIfNotExist();

        var containerPermissions = new BlobContainerPermissions();
        containerPermissions.PublicAccess = BlobContainerPublicAccessType.Blob;
        blobContainer.SetPermissions(containerPermissions);
        var blob = blobContainer.GetBlobReference("testfileWithOpenWrite1.txt");

        using (var input = File.OpenRead(@"C:\testFile.txt")) //5000000 bytes
        using (var output = blob.OpenWrite(new BlobRequestOptions()))
            input.CopyTo(output);

        Console.WriteLine("uploaded");

        int bytesDownloaded = 0;
        byte[] buffer = new byte[65536];

        using (BlobStream bs = blob.OpenRead())
        {
            int chunkLength;
            do
            {
                chunkLength = bs.Read(buffer, 0, buffer.Length);
                bytesDownloaded += chunkLength;
            } while (chunkLength > 0);
        }

        Console.WriteLine(bytesDownloaded);
    }

    public static int CopyTo(this Stream source, Stream destination)
    {
        int BUFFER_SIZE = 65536;
        byte[] buffer = new byte[BUFFER_SIZE];
        int bytesRead;
        int bytesCopied = 0;

        do
        {
            bytesRead = source.Read(buffer, 0, BUFFER_SIZE);
            if (bytesRead > 0)
                destination.Write(buffer, 0, bytesRead);
            bytesCopied += bytesRead;
        }
        while (bytesRead > 0);

        return bytesCopied;
    }

EDIT 4 - Conclusion:
This was probably a bug in Microsoft.WindowsAzure.StorageClient.dll (assembly version 6.0.6002.17043) that comes with SDK v1.2. It works with latest Microsoft.WindowsAzure.StorageClient.dll (assembly version 6.0.6002.18312 - SDK v1.4).
Thanks smarx :)

A:

I can't reproduce what you're seeing. Things seem to work as expected:
static void Main(string[] args)
{
    // I also tried a real cloud storage account. Same result.
    var container = CloudStorageAccount.DevelopmentStorageAccount.CreateCloudBlobClient().GetContainerReference("testcontainer");
    container.CreateIfNotExist();

    var blob = container.GetBlobReference("testblob.txt");

    blob.UploadText(new String('x', 5000000));

    var source = blob.OpenRead();

    int BUFFER_SIZE = 4000000;
    byte[] buffer = new byte[BUFFER_SIZE];
    int bytesRead;
    int bytesCopied = 0;
    do
    {
        bytesRead = source.Read(buffer, 0, BUFFER_SIZE);
        bytesCopied += bytesRead;
    } while (bytesRead > 0);

    Console.WriteLine(bytesCopied); // prints 5000000
}

EDIT:
I've also (in response to the edited question) now tried uploading the blob using OpenWrite, and the result is the same. (I get the full blob back.) I used this code in place of blob.UploadText(...):
using (var input = File.OpenRead(@"testblob.txt")) //5000000 bytes
using (var output = blob.OpenWrite())
{
    input.CopyTo(output);
}

The final WriteLine still prints 5000000.
EDIT 2:
This is getting a bit tiresome. Changing the BUFFER_SIZE to 65536 didn't change anything. The results still seem correct to me. Here's my full application for comparison:
static void Main(string[] args)
{
    // I also tried a real cloud storage account. Same result.
    var container = CloudStorageAccount.DevelopmentStorageAccount.CreateCloudBlobClient().GetContainerReference("testcontainer");
    container.CreateIfNotExist();

    var blob = container.GetBlobReference("testblob.txt");

    using (var input = File.OpenRead(@"testblob.txt")) //5000000 bytes
    using (var output = blob.OpenWrite())
    {
        input.CopyTo(output);
    }

    var source = blob.OpenRead();

    int BUFFER_SIZE = 65536;
    byte[] buffer = new byte[BUFFER_SIZE];
    int bytesRead;
    int bytesCopied = 0;
    do
    {
        bytesRead = source.Read(buffer, 0, BUFFER_SIZE);
        bytesCopied += bytesRead;
    } while (bytesRead > 0);

    Console.WriteLine(bytesCopied); // prints 5000000
}


Q:

Antlr left recursive

I'm trying to convert the postfix, infix and prefix rules from scala in EBNF form to ANTLR but am seeing an error relating to left-recursion on the infixExpression rule.
The rules in question are:
public symbolOrID
:   ID
|   Symbol
;

public postfixExpression
:   infixExpression symbolOrID? -> ^(R__PostfixExpression infixExpression symbolOrID?)
;

public infixExpression
:   prefixExpression
|   infixExpression (symbolOrID infixExpression)? -> ^(R__InfixExpression infixExpression symbolOrID? infixExpression?)
;

public prefixExpression
:   prefixCharacter? simpleExpression -> ^(R__PrefixExpression prefixCharacter? simpleExpression)
;

public prefixCharacter
:   '-' | '+' | '~' | '!' | '#'
;

public simpleExpression
:   constant
;

If I change the infixExpression rule to:
public infixExpression
:   prefixExpression (symbolOrID infixExpression)? -> ^(R__InfixExpression prefixExpression symbolOrID? infixExpression?)
;

Then it instead complains:
warning(200): Hydra.g3:108:26: Decision can match input such as "{ID, Symbol} {'!'..'#', '+', '-', '~'} String" using multiple alternatives: 1, 2
As a result, alternative(s) 2 were disabled for that input
warning(200): Hydra.g3:108:26: Decision can match input such as "{ID, Symbol} {'!'..'#', '+', '-', '~'} Number" using multiple alternatives: 1, 2
As a result, alternative(s) 2 were disabled for that input
warning(200): Hydra.g3:108:26: Decision can match input such as "{ID, Symbol} {'!'..'#', '+', '-', '~'} Boolean" using multiple alternatives: 1, 2
As a result, alternative(s) 2 were disabled for that input
warning(200): Hydra.g3:108:26: Decision can match input such as "{ID, Symbol} {'!'..'#', '+', '-', '~'} Regex" using multiple alternatives: 1, 2
As a result, alternative(s) 2 were disabled for that input
warning(200): Hydra.g3:108:26: Decision can match input such as "{ID, Symbol} {'!'..'#', '+', '-', '~'} Null" using multiple alternatives: 1, 2
As a result, alternative(s) 2 were disabled for that input

Lastly, is there a way to conditionally create the nodes in the AST so that if only the left part of the rule is true then it doesn't add that level in? E.g.:
conditional_or_expression:
    conditional_and_expression  ('||' conditional_or_expression)?
;

As in, lets say I create the grammar which follows a hierarchy like:
conditional_and_expression
  conditional_or_expression
    null_coalescing_expression

if the expresion that is parsed is a || b, currently the AST that is created is for this expression would be
conditional_and_expression
  conditional_or_expression

How could I get it so it just gets the conditional_or_expression part?
In JavaCC, you could just set the node arity, e.g.: #ConditionalOrExpression(>1)
EDIT: it was a bit late last night, infix expression is now propery modified!
Final edit: The way I got it to work in the end were the following rules:
public symbolOrID
:   ID
|   Symbol
;

public postfixExpression
:   infixExpression (symbolOrID^)?
;

public infixExpression
:   (prefixExpression symbolOrID)=> prefixExpression symbolOrID^ infixExpression
|   prefixExpression
;

public prefixExpression
:   prefixCharacter^ simpleExpression
|   simpleExpression
;

public prefixCharacter
:   '-' | '+' | '~' | '!' | '#'
;

public simpleExpression
:   constant
;

A:

Darkzaelus wrote:
I'm trying to convert the postfix, infix and prefix rules from scala in EBNF form to ANTLR but am seeing an error relating to left-recursion

As I said in my comment: there's no left recursion in the rules you posted.

Darkzaelus wrote:
How could I get it so it just gets the conditional_or_expression part?

I'm assuming you're using ANTLRWorks' interpreter or debugger, in which case the tree:
conditional_and_expression
            \
  conditional_or_expression

is only being displayed like that (the parse tree is shown, not the AST). If you properly transform your orExpression into an AST, the expression a || b will become:
  ||
 /  \
a    b

(i.e. || as root, and a and b as child nodes)
For example, take the following grammar:
grammar T;

options {
  output=AST;
}

parse
  :  expr EOF -> expr
  ;

expr
  :  or_expr
  ;

or_expr
  :  and_expr ('||'^ and_expr)*
  ;

and_expr
  :  add_expr ('&&'^ add_expr)*
  ;

add_expr
  :  atom (('+' | '-')^ atom)*
  ;

atom
  :  NUMBER
  |  '(' expr ')' -> expr
  ;

NUMBER : '0'..'9'+;

If you now parse 12+34 with a parser generated from the grammar above, ANTLRWorks (or the Eclipse ANTLR IDE) will show the following parse tree:

but this is not the AST the parser creates. The AST actually looks like:

(i.e. the or_expr, and_expr "layers" are not in there)

Darkzaelus wrote:
Unfortunately, this is a fairly critical but early stage for the language, so I'm forced to keep full details of the grammar secret.

No problem, but you must realize that people can't answer your questions properly if you withhold crucial information. You don't need to post the entire grammar, but if you want help with the left-recursion, you must post a (partial) grammar that actually causes the error(s) you mention. If I can't reproduce it, it doesn't exist! :)


Q:

Bug in numpy.shape()?

I am playing with day 10 of the 2019 advent of code challenge and found np.shape() behaving weirdly right at the start:
In [45]:
import numpy as np
file = open('Day10.data')
astermap = file.read()
print(astermap)
Out [46]:
##.##..#.####...#.#.####
##.###..##.#######..##..
..######.###.#.##.######
.#######.####.##.#.###.#
[..total of 25 lines]

# astermap is a str, which I make a list of lists

In [46]:
astermap = astermap.split('\n')
astermap = list(map(list, astermap))
Here I found some strange behavior for numpy.shape: the shape should be (25,24)

In [48]:
np.shape(astermap)
Out[48]:
(25,)

In [49]:
np.shape(astermap[0])
Out[49]:
(24,)

In [51]:
type(astermap)
Out[51]:
list

In [52]:
type(astermap[0])
Out[52]:
list

When I run the same code with a smaller example astermap = '.#..#\n.....\n#####\n....#\n...##', it works as expected and np.shape(astermap) returns (5, 5). So I strongly expect that the reason must lie in the format of the str after reading the file. However, I can't see a difference of types between the str I import and the str I create by hand.
Can somebody explain?

A:

When you convert a list of lists into a numpy array, it only makes it all a numpy array if the inner lists are of the same length. Otherwise, it makes an array of python lists.
Example:
Running np.array(list(map(list,(" asdf fdsa".split())))) returns:
array([['a', 's', 'd', 'f'],
       ['f', 'd', 's', 'a']], dtype='<U1')

Which has shape (2,4). But np.array(list(map(list,(" asdf fdsafda".split())))) returns:
array([list(['a', 's', 'd', 'f']),
       list(['f', 'd', 's', 'a', 'f', 'd', 'a'])], dtype=object)

Which has shape (2,).
Even if you convert the inner list to numpy arrays, they still won't display when taking np.shape(), because they're not all the same length.
I'd assume it's very likely one of your lists is a different length, which could be due to splitting by new lines '/n'. It's possible one of your line values is an empty string [''].


Q:

Globally associate file type with certain application

I don't need "Ubuntu-tweak" and i know about GUI method of associating certain files with certain applications using right click and "Open with". I am having problem setting filetype association globally in a file:
/usr/share/gnome/applications/defaults.list

E.g.:
image/x-psd=gimp.desktop

If i want to open all PSD's in a photoshop, i have created photoshop.desktop file and placed it under /usr/share/applications. Now when i press Super (windows) key and type Photoshop i see that icon, but i can't:

drag'n'drop that on my desktop. How can i do that?
if i change image/x-psd=gimp.desktop to image/x-psd=photoshop.desktop it still opens in a gimp. Why?

Thanks in advance.

A:

Solved my issue myself.
File /etc/gnome/defaults.list are overriden by ~/.local/share/applications/mimeapps.list, so all file association goes in to mimeapps.list file:
[Default Applications]
image/vnd.adobe.photoshop=wine-extension-8bs.desktop

In this example i've set to open .psd in a Photoshop through Wine. If i go in to /etc/gnome/defaults.list and add:
image/vnd.adobe.photoshop=gimp.desktop

It won't open .psd in a gimp, because it got overriden by mimeapps.list. Spent few hours to figure that out lol.


Q:

ffmpeg on iphone

Has anyone used ffmpeg on iphone? How do I go about compiling ffmpeg on iphone? And on OS X?

A:

On OS X, it is as simple as running macports,
for the iphone the situation is a little more complex, you'll need to run the ./configure script your self and use the --cross-prefix option to build binaries for the arm processor, you'll also need to change the make file to build static libraries.
You'll also need to manage all the dependencies your self and repeat the same process for each required lib.
Finally keep in mind that ffmpeg is licensed under LGPL so if you statically link your iphone app to it you'll need to release your source code (under some interpretations of the LGPL)


Q:

I have IE9 on Windows 7, need to check browser compatibility in older IE versions...

I have windows 7 (64-bit) and just upgraded IE9 in my machine. I did some design in html, css and javascript and works all fine in IE9, chrome, firefox, opera but I have to check this in older versions of IE, that is possibly in IE8 and IE7. I tried to search to download IE8 but could not find it for Windows 7, 64-bit OS.
Is there any other solutions to check my html page in older versions of IE without installing IE8 and removing IE9 in my machine ?
Thanks

A:

Here's a bunch of free virutal machines that have all the IE browsers from 6 to 9
http://www.microsoft.com/download/en/details.aspx?id=11575
Here is the application to run those virtual machines... also free:
http://www.microsoft.com/download/en/details.aspx?id=4580


Q:

Clicar em um link e exibir o valor dentro de um input

Olá, alguém sabe como eu poderia fazer isso, tenho 10 link, cada link corresponde a um elemento tipo link 1 = :D, link 2 = :S, link 3 = :$ e assim por diante, ai eu tenho um input type="text" name="mensagem" placeholder="digite sua mensagem..."/>, minha dúvida é o seguinte, como eu faria pra quando a pessoa clicasse em um desses link o valor que é informado neles mostrasse no input? sem ser pelo value="", vou exemplificar melhor :D :S :$ ao clicar em um desses link quero que envie o valor correspondente ai link clicado para o input

A:

Crie um eventListener com click para cada , que ao ser clicado, o texto correspondente será concatenado ao texto do input:

document.addEventListener("DOMContentLoaded", function(){

   var els = document.body.querySelectorAll("a[href*='java']");

   for(var x=0; x<els.length; x++){

      els[x].addEventListener("click", function(){
         var a_txt = this.textContent,
              inpt = document.body.querySelector("#texto");

         inpt.value += " "+a_txt;
      });
   }

});
:D
:S
:$

<input id="texto" type="text" value="olá!" />


Q:

to locate div by coordinates

I need to draw a plan of the hall on a site. The hall is drawn in a third-party program. The program gives me a plan of the hall in the form of coordinates of each place:
Row Place  X    Y    Widht    Height
1    1     10   10    35       35

The plan in a editor looks like:

I have the following code to draw in the View:
 @foreach (var plan in Model.HallPlans)
{

@plan.Seat

}

This code generate the following:

I want to reduce the size of div block, for example  twice. If I divide Height and Width by 2 then it looks like:

The size of first three rows such as I wanted, but wide place in four row looks not properly(not till the end of the row.). How to correct?. And, How can I reduce the space between div ?
PS. some css:
div.place {
    display: block;
    text-indent: -9999px;
    margin: 0 0 1px 1px;
   position:absolute;
    float: left;
    border-radius: 2px 2px 2px 2px;
    -moz-border-radius: 2px 2px 2px 2px;
}

Thanks and sorry for my english.

A:

it's very simple, the fourth row is half the width that you want because you divided the Width by 2. Just for the forth row do not divide the Width by 2, but only the Height, and it will fill until the end of the row.

Alternatively have a look at this approach, I just realised this might be what you want:
Where you decide to divide the Width and the Height by 2, also divide the X and Y by 2, then output as regular. You will have an end result similar to the original image but half the size.


Q:

SQL Row with youngest DateStamp from Subselect in a Left Outer Join

On Patient could have one or more PrmryDiagnosis, there is also a DateStamp to every Diagnosis in the database. So I am trying to get out only the newest PrmryDiagnosis if there are more PrmryDiagnosis than one.
I already got a bunch of Left outer joins in my code, and this code snippet with the max-clause in the subquery does not join me the Diagnosis to my table! It selects the right one, but does not join me a new column Diagnosis! Please could u help me! Best Regards!
/*code snippets*/

SELECT di.DiagnosisCode,
       di.Description,
       di.DiagnosisType
       di.PatientSer
FROM dbo.Activity,dbo.ActivityInstance,dbo.ScheduledActivity sa
LEFT OUTER JOIN dbo.Patient pa ON sa.PatientSer = pa.PatientSer
LEFT OUTER JOIN dbo.Diagnosis di ON(sa.PatientSer = di.PatientSer AND
                                    di.DiagnosisType='PrmryDiagnosis' AND
                                    di.ObjectStatus='Active' AND
                                    di.DateStamp = (Select MAX(DateStamp)
                                                    from Diagnosis
                                                    where di.PatientSer = sa.PatientSer))

WHERE
    (YEAR(sa.ScheduledStartTime) = YEAR(CURRENT_TIMESTAMP)) AND
    (MONTH(sa.ScheduledStartTime) = MONTH(CURRENT_TIMESTAMP)) AND
    (DAY(sa.ScheduledStartTime) = DAY(CURRENT_TIMESTAMP))

A:

Consider use of row_number() as shown here to arrive at the "most recent record"
SELECT
      di.DiagnosisCode
    , di.Description
    , di.DiagnosisType
    , di.PatientSer
FROM (
            SELECT
                  DiagnosisCode
                , Description
                , DiagnosisType
                , PatientSer
                , ROW_NUMBER() OVER (PARTITION BY PatientSer
                                     ORDER BY DateStamp DESC) AS rn
            FROM dbo.Diagnosis
            WHERE DiagnosisType = 'PrmryDiagnosis'
                  AND ObjectStatus = 'Active'
      ) di
WHERE rn = 1;


Q:

Calibre: Difference between "Date" and "Published"

When editing the metadata of a book on Calibre, there are two fields that seem to have the same meaning: "Date" and "Published". What's the difference between the two?

A:

"The lookup names are pubdate (publication date) and date (calibre's "Date" column, usually the date you added the book to calibre)."
http://faq.calibrecompanion.co/index.php?action=artikel&cat=6&id=22&artlang=en


Q:

Unit Test a configuration class not working in Multi Maven Spring Boot project

I am working on multi module maven project with SpringBoot framework.
The project is divided in 4 modules: rest module,service module,repository module, domain module.
I am trying to write a unit test  for a configuration class in java which is located in the service module.
I have simplified the case to get rid of business logic complexity. The configuration class is like below:
@Configuration
@ConfigurationProperties(prefix = "x.y.feature", ignoreInvalidFields = false)
public class FeatureConfig {

        private String featureUrl;

        public String getFeatureUrl() {
            return featureUrl;
        }

        public void setFeatureUrl(String FeatureUrl) {
            this.featureUrl = featureUrl;
        }

}

The properties file is application.properties.
x.y.feature.featureUrl=featureUrl

And below is the unit test that is not working.
@RunWith(SpringRunner.class)
@SpringBootTest(classes = { FeatureConfigTest.class })
public class FeatureConfigTest {
    @Autowired
    private FeatureConfig featureConfig;

    @Test
    public void testgetFeatureUrl() {
        String expected ="featureUrl";
        assertEquals(expected,featureConfig.getFeatureUrl());
    }
}

When i run the unit test , it throws the exception below:
java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:108)

A:

The problem  is that you are trying to use object of FeatureConfig
from the application context. You haven't initialized the application context.
When you use the @Autowire annotation, you are mapping field 'featureConfig'
with instance of type FeatureConfig class located in the application context.
To bypass this error you need initialize the application context.
First thing , create static class inside the test class that will help us not to load the
whole application context. Because for this test case you don't need to load the whole application.
First thing , create static class inside the test class that will help us not to load the
whole application context. Because for this test case you don't need to load the whole application.
    @EnableConfigurationProperties(FeatureConfig.class)
    public static class TestConfiguration {
    }

After that you start the application context , but with passing as configuration the static class
you created. This is done not to load the whole application context.
@SpringBootTest(classes = { FeatureConfigTest.TestConfiguration class })
Copy and paste the changes below in your test class and everything should work ok.
@RunWith(SpringRunner.class)
@SpringBootTest(classes = { FeatureConfigTest.TestConfiguration class })
public class FeatureConfigTest {
    @Autowired
    private FeatureConfig featureConfig;

    @Test
    public void testgetFeatureUrl() {
        String expected ="featureUrl";
        assertEquals(expected,featureConfig.getFeatureUrl());
    }

    @EnableConfigurationProperties(FeatureConfig.class)
    public static class TestConfiguration {
    }
}


Q:

Shell commands work in Terminal but not in Automator service

I try to implement these two very simple commands in an Automator service to be run by a keyboard short (takes a screenshot and OCRs it):
screencapture -i /tmp/tesseract.png
tesseract /tmp/tesseract.png stdout|tr -d \\f|pbcopy

This works great when I execute these commands in the Terminal, but not when I make it an Automator service (sorry this is in German).

I don't understand: Why does it work in the one case and not in the other? Does it have anything to do with tesseract?

A:

Any executable that is not within the PATH passed to the Run Shell Script action, which is /usr/bin:/bin:/usr/sbin:/sbin, you must use the fully qualified pathname of the executable.
In this case, e.g. /path/to/tesseract
You should be able to get its path in Terminal using:
which tesseract

As tesseract is not a default of macOS, it may be in /usr/local/bin/, however which tesseract should report its fully qualified pathname.

Instead of using the fully qualified pathname, or in conjunction with, you can also add a PATH statement to the top of the Run Shell Script action, e.g. for a bash shell:
PATH="${PATH}:/usr/local/bin/"

You could also just substitute everything to the right of the = sign for what the output in Terminal, e.g. echo $PATH is. Then the Run Shell Script action has the same PATH as Terminal.


Q:

Retrieve Siebel data based on intersection table using SiebelDataBean

I have Siebel structure looking like this:
BusObj: Base
--BusComp: Category list
----BusComp: Product list
"Product list" is child component to "Category list", they have a link Category list/Product list by the means of intersection table 'S_CAT_PROD', that has CAT_ID for category and PROD_ID for product. This allows N-to-N linking of categories to products.
Now the problem is I have retrieved both SiebelBusComp from Java code, but have no idea how to make use of this intersection table to retrive all products for some category.
There are couple SiebelBusComp methods that return another SiebelBusComp, but I had no luck making them work. These are:
getAssocBusComp()
getMVGBusComp(java.lang.String fieldName)
getPicklistBusComp(java.lang.String fieldName)
parentBusComp()

Has anyone any experience using such logic in Java? Any help would be appreciated, thanks.

A:

I couldn't find the table S_CAT_PROD in Siebel, assuming it is custom made. Again, assuming you have a M:M link from Catalog to Products correctly configured using this intersection table , the link itself will take care of filtering the child records based on parent category.
//make variable instances
var BO = TheApplication().GetBusObject("Base");
var bcCat = BO.GetBusComp("Category list");
var bcProd = BO.GetBusComp("Product  list");

//search for category

bcCat.ClearToQuery();
bcCat.SetSearchSpec("Id", "1-234");
bcCat.ExecuteQuery(True);

// When using the ExecuteQuery method with Java Data Bean, use True for //ForwardOnly and False for ForwardBackward.

if (bcCat.FirstRecord())
{
//the link will automatically filter and bring only those products for this //category

    bcProd.ClearToQuery();
    bcProd.ExecuteQuery(True);
}


Q:

Sublime Text Insert Guid

I've started using Sublime Text and it's great. But while editing Wix setup files I need to insert randomly generated GUID's in form like 52E47764-B722-4E8A-9BA8-DDA5B1500391.
The question: is there any snippet or hotkey or something else to insert GUID to text beeing edited

A:

There is a plugin for it: https://github.com/SublimeText/GenerateUUID


Q:

AngularJS Dropdown Multiselect Options not binding

I am using AngularJS Dropdown Multiselect - http://dotansimha.github.io/angularjs-dropdown-multiselect/
the problem I am facing is the option attribute that is not binding to the model

For example:
if model is :
    $scope.example1model = [];

    $scope.example1data = [ {id: 1, label: "David"}, {id: 2, label: "Jhon"}, {id: 3, label: "Danny"} ];

Issue:
the binding for options doesn't seems to work correctly as I am getting only Id(s) rest is working fine, if I check David and John ,the options binding with $scope.example1model  show only the id not the label
i.e : [{"id":1},{"id":2}
but what I want is
[
  {
    "id": 1,
    "label": "David"
  },
  {
    "id": 2,
    "label": "John"
  }
]

A:

Set externalIdProp as empty string
$scope.extraSettings = {
    externalIdProp: ''
  };

html

Works for me, I'm using ^1.11.8


Q:

to find number of divisor of $p^m$ times $q^n$ when $p$ and $q$ are primes

Am taking a intro discrete math course..it covers some number theory content
Euclidean algorithm,modular arithmetic, Euler's phi function, that's all
How can I  solve a question like this:
If $p$ and $q$ are distinct primes, find the number of distinct divisors of $p^mq^n$.
what I did is plugin some prime number and observed that the number of divisor is
$(m+1)(n+1）$
Is there a formal way to solve this based on the contents I mentioned?
Thanks for help!

A:

You want to produce a (positive) divisor of $p^mq^n$.  By the Unique Factorization Theorem, aka the Fundamental Theorem of Arithmetic, this will be a number $d$ of the shape $p^aq^b$, where $0 \le a\le m$ and $0 \le b \le n$.
Imagine that we have a box that contains $m$ $p$'s, and next to it a box that contains $n$ $q$'s.
First we stop in front of the $p$-box, and decide how many $p$'s our divisor $d$ shall have.  There are $m+1$ available options, namely $0, 1, \dots,m$.
Once we have decided on the number of $p$'s, move over to the $q$-box.  For every choice of how many $p$'s the divisor $d$ shall have, there are $n+1$ ways to decide how many $q$'s the divisor $d$ shall have. Thus the total number of choices is $(m+1)(n+1)$.
Comment: Let $N=p_1^{m_1}p_2^{m_2}\cdots p_k^{m_k}$, where the $p_i$ are distinct primes. Using basically the same argument, we can show that $N$ has $(p_1+1)(p_2+1)\cdots(p_k+1)$ positive divisors.


Q:

Changing multiple textboxes with dropdown knockout

I have the following HTML:
<select id="EmpName" data-bind="value: Employee.EmpName, event: { change: $root.updateEmployee }"></select>
<input disabled type="text" id="EmpNum" data-bind="value: Employee.EmpNum, valueUpdate: 'input'" />
<input disabled type="text" id="EmpClass" data-bind="value: Employee.EmpClass, valueUpdate: 'input'" />
<input disabled type="text" id="EmpDept" data-bind="value: Employee.EmpDept, valueUpdate: 'input' " />
<input disabled type="text" id="EmpStat" data-bind="value: Employee.EmpStat, valueUpdate: 'input'" />

And it's bound by the following ViewModel:
generalViewModel = function (thisData) {
        var self = this;

        this.Incident = ko.mapping.fromJS(thisData.Incident);
        this.Employee = ko.mapping.fromJS(thisData.Employee);

        this.updateEmployee = function () {
            var employeeName = self.Employee.EmpName;
            $.getJSON('/Incidents/GetEmployee', { EmployeeName: employeeName }, function (data, status, xhr) {
                    var newEmp = ko.mapping.fromJS(data);
                    self.Employee(newEmp);
                });
        }

        this.refreshData = function (incID) {
            GetIncidentGeneralInfo(incID, node);
        }

        this.savetoServer = function (incID, buttonID) {
            var incident = ko.toJSON(self.Incident);
            var employee = ko.toJSON(self.Employee);
            $.post('/Incidents/SaveIncident', { IncidentID: incID, JSONIncident: incident, JSONEmployee: employee, button: buttonID }, function (data, status, xhr) {
                self.refreshData(data);
            });
        }
    }

    ko.applyBindings(new generalViewModel(data), document.getElementById(node));

Everything is working quite nicely, with the exception of the updateEmployee function. The JSON is returning the new Employee information, but the textboxes aren't updating. I'm doing something silly incorrectly, and I can't quite figure out wat

A:

Instead of
var newEmp = ko.mapping.fromJS(data);
self.Employee(newEmp);

You should do
ko.mapping.fromJS(data, self.Employee);

This will update all of the observable properties on self.Employee that were created by the first call to ko.mapping.fromJS.


Q:

Animator is not playing an animation controller

My animator doesn't work: I set a bool variable from code:
animatedObject.myAnimator.SetBool("MyVariable", true);
animatedObject.SetActive(true);

But the animation isn't triggered. I'm sure that the animator's transition is correctly set to react with "MyVariable".
Looking at the output console, I see that I have a warning:

animator is not playing an animation controller

What does that mean?

A:

The warning is not really helpful but what it means is that the AnimationController is disabled, or is on an inactive object. It will not be able to set variable since it currently doesn't have a state.
Simply inverting the two lines, so that the animator is on an active object, will solve it:
animatedObject.SetActive(true);
animatedObject.myAnimator.SetBool("MyVariable", true);


Q:

Is there a way to auto scroll a listbox in C# WinForms

I an writing a program will display a list of number in serveral list boxes on a big monitor, my question is is there a way to auto scroll the list box to show all data in the boxes?

A:

Normally, I would do:
listBox.SelectedIndex = listBox.Items.Count - 1;
listBox.SelectedIndex = -1;

but you can also try
int nItems = (int)(listBox.Height / listBox.ItemHeight);
listBox.TopIndex = listBox.Items.Count - nItems;

Hope this helps :)

A:

To directly control the scrolling without selecting items, you need to use the Win32 SetScrollPos method from User32.dll. Here is a extended class which gives you basic support:
public class ScrollableListView : ListView
{
    private const int WM_VSCROLL = 0x115;

    private enum ScrollBar : int { Horizontal = 0x0, Vertical = 0x1 }

    public void SetScroll(int x, int y)
    {
        this.SetScroll(ScrollBar.Horizontal, x);
        this.SetScroll(ScrollBar.Vertical, y);
    }

    public void SetScrollX(int position)
    {
        this.SetScroll(ScrollBar.Horizontal, position);
    }

    public void SetScrollY(int position)
    {
        this.SetScroll(ScrollBar.Vertical, position);
    }

    [DllImport("User32.Dll", EntryPoint = "PostMessageA")]
    private static extern bool PostMessage(IntPtr hWnd, uint msg, int wParam, int lParam);

    [DllImport("user32.dll")]
    private static extern int SetScrollPos(IntPtr hWnd, int nBar, int nPos, bool bRedraw);

    private void SetScroll(ScrollBar bar, int position)
    {
        if (!this.IsDisposed)
        {
            ScrollableListView.SetScrollPos((IntPtr)this.Handle, (int)bar, position, true);
            ScrollableListView.PostMessage((IntPtr)this.Handle, ScrollableListView.WM_VSCROLL, 4 + 0x10000 * position, 0);
        }
    }
}

You can then set the X or Y scroll quickly and easily. This should work for other controls too.

If you want to make the control automatically scroll down and up, you would need to set up a recurring timer, with an interval of around 20 milliseconds. Keep track of the scroll position and direction, and increment or decrement it accordingly, sending the position to the control using these methods.

UPDATE:
I had a few problems with the SetScrollPos method posted above, primarily around the scrollbar moving, but the contents not. It's probably just a minor oversight, but in the meantime, here is a somewhat "outside the box" MarqueeListView solution..
First up, the enum representing which scrollbar to use. I used display names instead of the Win32 names for these (SB_HORIZ and SB_VERT) just to make things a little clearer.
public enum ScrollBarDirection : int { Horizontal = 0x0, Vertical = 0x1 }

Another enum for the scroll command codes themselves - I've trimmed out everything apart from Up (SB_LINEUP), Down (SB_LINEDOWN) and EndScroll (SB_ENDSCROLL). EndScroll is needed after the scroll message to inform the control to update.
public enum ScrollCommand : int { Up = 0x0, Down = 0x1, EndScroll = 0x8 }

Then finally the class itself. It basically starts by scrolling down, every 20ms (by default - note this is changeable via the MarqueeSpeed property). It then gets the scroll position, and compares it to last time. Once the scroll bar stops moving, it reverses the direction. This is to get around problems I was having with the GetScrollInfo method.
public class MarqueeListView : ListView
{
    protected const int WM_VSCROLL = 0x115;

    private ScrollCommand scrollCommand;
    private int scrollPositionOld;
    private Timer timer;

    public MarqueeListView()
        : base()
    {
        this.MarqueeSpeed = 20;

        this.scrollPositionOld = int.MinValue;
        this.scrollCommand = ScrollCommand.Down;

        this.timer = new Timer() { Interval = this.MarqueeSpeed };
        this.timer.Tick += (sender, e) =>
        {
            int scrollPosition = MarqueeListView.GetScrollPos((IntPtr)this.Handle, (int)ScrollBarDirection.Vertical);
            if (scrollPosition == this.scrollPositionOld)
            {
                if (this.scrollCommand == ScrollCommand.Down)
                {
                    this.scrollCommand = ScrollCommand.Up;
                }
                else
                {
                    this.scrollCommand = ScrollCommand.Down;
                }
            }
            this.scrollPositionOld = scrollPosition;

            MarqueeListView.SendMessage((IntPtr)this.Handle, MarqueeListView.WM_VSCROLL, (IntPtr)this.scrollCommand, IntPtr.Zero);
            MarqueeListView.SendMessage((IntPtr)this.Handle, MarqueeListView.WM_VSCROLL, (IntPtr)ScrollCommand.EndScroll, IntPtr.Zero);
        };
        this.timer.Start();
    }

    public int MarqueeSpeed
    {
        get
        {
            return this.timer.Interval;
        }
        set
        {
            this.timer.Interval = value;
        }
    }

    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    public static extern int GetScrollPos(IntPtr hWnd, int nBar);

    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    protected static extern int SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam);
}

Finally, here's a quick Main method to test it:
    private static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        Form form = new Form() { StartPosition = FormStartPosition.CenterScreen, Width = 1280, Height = 720 };
        MarqueeListView list = new MarqueeListView() { View = View.Tile, Dock = DockStyle.Fill };
        for (int i = 0; i < 1000; i++) { list.Items.Add(Guid.NewGuid().ToString()); }
        form.Controls.Add(list);

        Application.Run(form);
    }

Please bear in mind, this isn't necessarily the "proper" or best way of doing things, but I figured a different approach might give you some ideas!
I was hoping to use SetScrollPos which would give a much better, smoother effect. You can then easily include acceleration and deceleration - possibly optionally slowing to a halt on mouse over, then accelerating away on mouse out etc. It's just not playing ball at present though - I've got a working scroll update method in an old project somewhere, so I'll update this if I get it working again.
Hope that helps!


Q:

GoogleApiClient: hide GPS icon on status bar when a service is in the background

I'm using GoogleApiClient to implement a location listener service, but the GPS icon is always being displayed, even with the service in background. How to disable the GPS icon when the service is in the background?

Follow the sources below:
Activity
public class ShowDistanceActivity extends AppCompatActivity implements ILocationConstants {

protected static final String TAG = ShowDistanceActivity.class.getSimpleName();

@Bind(R.id.tvLocationData)
TextView tvLocationData;

@Bind(R.id.toolbar)
Toolbar toolbar;

/**
 * Receiver listening to Location updates and updating UI in activity
 */
private LocationReceiver locationReceiver;

/**
 * Permission util with callback mechanism to avoid boilerplate code
 * <p/>
 * https://github.com/kayvannj/PermissionUtil
 */
private PermissionUtil.PermissionRequestObject mBothPermissionRequest;

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

    ButterKnife.bind(this);

    setSupportActionBar(toolbar);

    locationReceiver = new LocationReceiver();

}

private void startLocationService() {

    Intent serviceIntent = new Intent(this, LocationService.class);
    startService(serviceIntent);

}

@Override
protected void onStart() {
    super.onStart();

    LocalBroadcastManager.getInstance(this).registerReceiver(locationReceiver, new IntentFilter(LOACTION_ACTION));

    /**
     * Runtime permissions are required on Android M and above to access User's location
     */
    if (AppUtils.hasM() && !(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
            && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)) {

        askPermissions();

    } else {

        startLocationService();

    }

}

/**
 * Ask user for permissions to access GPS location on Android M
 */
public void askPermissions() {

    mBothPermissionRequest =
            PermissionUtil.with(this).request(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION).onResult(
                    new Func2() {
                        @Override
                        protected void call(int requestCode, String[] permissions, int[] grantResults) {

                            if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {

                                startLocationService();

                            } else {

                                Toast.makeText(ShowDistanceActivity.this, R.string.permission_denied, Toast.LENGTH_LONG).show();
                            }
                        }

                    }).ask(PERMISSION_ACCESS_LOCATION_CODE);

}

@Override
protected void onStop() {
    super.onStop();

    LocalBroadcastManager.getInstance(this).unregisterReceiver(locationReceiver);
}

private class LocationReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        if (null != intent && intent.getAction().equals(LOACTION_ACTION)) {

            String locationData = intent.getStringExtra(LOCATION_MESSAGE);

            tvLocationData.setText(locationData);
        }

    }
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

    if (null != mBothPermissionRequest) {
        mBothPermissionRequest.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}

}
Service
public class LocationService extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener, ILocationConstants, IPreferenceConstants {

private static final String TAG = LocationService.class.getSimpleName();

/**
 * Provides the entry point to Google Play services.
 */
protected GoogleApiClient mGoogleApiClient;

/**
 * Stores parameters for requests to the FusedLocationProviderApi.
 */
protected LocationRequest mLocationRequest;

/**
 * Represents a geographical location.
 */
protected Location mCurrentLocation;

private String mLatitudeLabel;
private String mLongitudeLabel;
private String mLastUpdateTimeLabel;
private String mDistance;

/**
 * Time when the location was updated represented as a String.
 */
protected String mLastUpdateTime;

private Location oldLocation;

private Location newLocation;

private AppPreferences appPreferences;

/**
 * Total distance covered
 */
private float distance;

@Override
public void onCreate() {
    super.onCreate();

    Log.d(TAG, "onCreate() called");

    appPreferences = new AppPreferences(this);

    oldLocation = new Location("Point A");
    newLocation = new Location("Point B");

    mLatitudeLabel = getString(R.string.latitude_label);
    mLongitudeLabel = getString(R.string.longitude_label);
    mLastUpdateTimeLabel = getString(R.string.last_update_time_label);
    mDistance = getString(R.string.distance);

    mLastUpdateTime = "";

    distance = appPreferences.getFloat(PREF_DISTANCE, 0);

    Log.d(TAG, "onCreate Distance: " + distance);

}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    Log.d(TAG, "onStartCommand called");

    buildGoogleApiClient();

    mGoogleApiClient.connect();

    if (mGoogleApiClient.isConnected()) {
        startLocationUpdates();
    }

    return Service.START_STICKY;

}

/**
 * Builds a GoogleApiClient. Uses the {@code #addApi} method to request the
 * LocationServices API.
 */
protected synchronized void buildGoogleApiClient() {

    Log.d(TAG, "buildGoogleApiClient() called");

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    createLocationRequest();
}

protected void createLocationRequest() {

    Log.d(TAG, "createLocationRequest() called");

    mLocationRequest = new LocationRequest();

    mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);

    mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);

    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
}

/**
 * Requests location updates from the FusedLocationApi.
 */
protected void startLocationUpdates() {

    try {

        Log.d(TAG, "startLocationUpdates called");

        LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, this);

    } catch (SecurityException ex) {

        ex.printStackTrace();
    }
}

/**
 * Updates the latitude, the longitude, and the last location time in the UI.
 */
private void updateUI() {

    if (null != mCurrentLocation) {

        StringBuilder sbLocationData = new StringBuilder();
        sbLocationData.append(mLatitudeLabel)
                .append(" ")
                .append(mCurrentLocation.getLatitude())
                .append("\n")
                .append(mLongitudeLabel)
                .append(" ")
                .append(mCurrentLocation.getLongitude())
                .append("\n")
                .append(mLastUpdateTimeLabel)
                .append(" ")
                .append(mLastUpdateTime)
                .append("\n")
                .append(mDistance)
                .append(" ")
                .append(getUpdatedDistance())
                .append(" meters");

        /*
         * update preference with latest value of distance
         */
        appPreferences.putFloat(PREF_DISTANCE, distance);

        Log.d(TAG, "Location Data:\n" + sbLocationData.toString());

        sendLocationBroadcast(sbLocationData.toString());
    } else {

        Toast.makeText(this, R.string.unable_to_find_location, Toast.LENGTH_SHORT).show();
    }
}

/**
 * Send broadcast using LocalBroadcastManager to update UI in activity
 *
 * @param sbLocationData
 */
private void sendLocationBroadcast(String sbLocationData) {

    Log.d(TAG, "sendLocationBroadcast() called");

    Intent locationIntent = new Intent();
    locationIntent.setAction(LOACTION_ACTION);
    locationIntent.putExtra(LOCATION_MESSAGE, sbLocationData);

    LocalBroadcastManager.getInstance(this).sendBroadcast(locationIntent);

}

/**
 * Removes location updates from the FusedLocationApi.
 */
protected void stopLocationUpdates() {

    Log.d(TAG, "stopLocationUpdates() called");

    LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}

@Override
public void onDestroy() {

    Log.d(TAG, "onDestroy() called");

    appPreferences.putFloat(PREF_DISTANCE, distance);

    stopLocationUpdates();

    mGoogleApiClient.disconnect();

    Log.d(TAG, "onDestroy Distance " + distance);

    super.onDestroy();
}

/**
 * Runs when a GoogleApiClient object successfully connects.
 */
@Override
public void onConnected(Bundle connectionHint) throws SecurityException {
    Log.i(TAG, "Connected to GoogleApiClient");

    if (mCurrentLocation == null) {
        mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
        updateUI();
    }

    startLocationUpdates();

}

/**
 * Callback that fires when the location changes.
 */
@Override
public void onLocationChanged(Location location) {

    Log.d(TAG, "onLocationChanged() called");

    mCurrentLocation = location;
    mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
    updateUI();
}

@Override
public void onConnectionSuspended(int cause) {

    Log.d(TAG, "onConnectionSuspended() called");

    mGoogleApiClient.connect();
}

@Override
public void onConnectionFailed(ConnectionResult result) {

    Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
}

private float getUpdatedDistance() {

    /**
     * There is 68% chance that user is with in 100m from this location.
     * So neglect location updates with poor accuracy
     */

    if (mCurrentLocation.getAccuracy() > ACCURACY_THRESHOLD) {

        Log.d(TAG, "getUpdatedDistance() called");

        return distance;
    }

    if (oldLocation.getLatitude() == 0 && oldLocation.getLongitude() == 0) {

        oldLocation.setLatitude(mCurrentLocation.getLatitude());
        oldLocation.setLongitude(mCurrentLocation.getLongitude());

        newLocation.setLatitude(mCurrentLocation.getLatitude());
        newLocation.setLongitude(mCurrentLocation.getLongitude());

        return distance;
    } else {

        oldLocation.setLatitude(newLocation.getLatitude());
        oldLocation.setLongitude(newLocation.getLongitude());

        newLocation.setLatitude(mCurrentLocation.getLatitude());
        newLocation.setLongitude(mCurrentLocation.getLongitude());

    }

    /**
     * Calculate distance between last two geo locations
     */
    distance += newLocation.distanceTo(oldLocation);

    return distance;
}

@Override
public IBinder onBind(Intent intent) {

    throw new UnsupportedOperationException("Not yet implemented");
}

}
Manifest
Android Manifest declaration
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.technosavy.showmedistance">
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".ShowDistanceActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <service
            android:name=".service.LocationService"
            android:enabled="true"
            android:exported="true"></service>

    </application>

</manifest>

Please, any help is welcome.

A:

To remove the GPS icon you need to use cached and wi-fi location settings (from memory). In your code make the following changes.
In Manifest, remove:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

In Service, change the following:
mLocationRequest.setInterval(10000L);
mLocationRequest.setFastestInterval(5000L);
// Do NOT use LocationRequest.PRIORITY_HIGH_ACCURACY here
// Instead use one of the other option.
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
//mLocationRequest.setPriority(LocationRequest.PRIORITY_LOW_POWER);
//mLocationRequest.setPriority(LocationRequest.PRIORITY_NO_POWER);
// Remove setSmallestDisplacement() as it should not be used
// unless you are using a GPS / PRIORITY_HIGH_ACCURACY
//mLocationRequest.setSmallestDisplacement(DISPLACEMENT);

Pretty sure this is will remove the GPS icon but you will also only get the FusedLocationApi.getLastLocation() values when the onConnected() method is called (very possible this will be low accuracy).
The onLocationChanged() method may never trigger until another application makes a location request at a higher priority or with more accuracy.