text:
Q: Can I define an abstract method without the use of abstract keyword in Java? I know we can define abstract methods inside abstract class only. I also know we can't instantiate abstract class on its own, it must be inherited (extended).  And I know that abstract method forces subclasses to provide an implementation for that method.
My question is only if I can define that abstract method without the "abstract" keyword? Something like:
public abstract Animal
{
    public void makeNoise();
}

A: You can create an interface which is a set of abstract methods without using abstract keyword. If you create an abstract class, then every abstract method should have the abstract keyword.
Check the documentation for more info.

A:
My question is only if I can define that abstract method without the
  "abstract" keyword?

You cannot define abstract methods that way.
An abstract class can contain the implementation of a method. Because that, you have to mark which method is abstract and which is not.
If you create Animal class
public abstract class Animal {
    public void makeNoise();
}

Eclipse will suggest you either add body or change the method to abstract.

A: My question is only if I can define that abstract method without the "abstract" keyword?
No you can't on classes. That's only possible on interfaces.


text:
Q: Trying to re-project a folder of shapefiles using Python Script I am trying to reproject multiple shapefiles in a folder. When I run my program this is the error I am getting:
line 8221, in Project
    raise e
ExecuteError: Failed to execute. Parameters are not valid.
ERROR 000670: output Output Dataset or Feature Class is same as input Input Dataset or Feature Class
Failed to execute (Project).
I checked my code and I'm not seeing what Im doing wrong. What could be the issue here?
# Import system modules
import arcpy
import os

# Set environment settings
arcpy.env.workspace = "C:\\users\\data\\shapefile_roads"
arcpy.env.overwriteOutput = True
outWorkspace = "C:\\users\\data\\shapefile_roads"

for infc in arcpy.ListFeatureClasses():

        # Determine if the input has a defined coordinate system, can't project it if it does not
    dsc = arcpy.Describe(infc)

    if dsc.spatialReference.Name == "Unknown":
        print ('skipped this fc due to undefined coordinate system: ' + infc)
    else:
        # Determine the new output feature class path and name
        outfc = os.path.join(outWorkspace, infc)

        # Set output coordinate system
        outCS = arcpy.SpatialReference('WGS 1984')

        # run project tool
        arcpy.Project_management(infc, outfc, outCS)

        # check messages
        print(arcpy.GetMessages())

A: Your output dataset has the same name as your input dataset. Try setting a different workspace for the output, like:
outWorkspace = "C:\\users\\data\\shapefile_roads_projected"

A: Well, the error message is pretty straight forward:

ERROR 000670: output Output Dataset or Feature Class is same as input
  Input Dataset or Feature Class Failed to execute (Project).

The infc and outfc variables both point to the same feature class.
One easy fix would be to output into a different folder.
So, create a new folder called "projected" within the "shapefile_roads" folder, and change outWorkspace to:
outWorkspace = "C:\\users\\data\\shapefile_roads\\projected"

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python SafeConfigParser variable substitution, explanation of variable syntax? I just started using Python's ConfigFile.SafeConfigParser class to parse a config file that contains variable definitions and references. It works nicely, but I can't find an explanation for the weird syntax for a variable reference:
BASEPATH = C:\Users\me\x
SOME_FILE_PATH = %(BASEPATH)s\a
# Yields C:\Users\me\x\a

What's the 's' for? Are there other characters that make the variable behave differently?

A: The syntax comes from Python's string formatting syntax, which is based on C printf syntax.
In short, %s means "substitute with a string", %(abc)s means "substitute with a string named abc":
For example:
>>> print "Hello %s!" % 'world'
Hello world!
>>> print "Hello %(name)s!" % dict(name='world')
Hello world!


text:
Q: How to set Microphone vs Microphone Boost in Windows 7 I have a Windows 7 Desktop that I want to use a mic. I connected the mic to the pink input jack (mic in). But the volume is too soft. When I enter the properties menu, I see something like this:

What is the difference between the Microphone and Microphone Boost? How do I determine the optimal setting?
In addition, there is another Control Panel tool which is related to microphone setup. It makes me read a sentence "Peter dictates to his computer... blah blah blah". After that, it says it did not hear anything even though I clearly see the volume changes as I read. I read it again and it then told me my microphone is now set up! What does it really do?

A: I don't have a technical answer for you, but I can share my experience when testing different combinations of the two. I've found that the Boost level does a good job of making the microphone sound very close to me, when I move it further away - whereas the Volume becomes audibly 'distant' and quiet when it's moved away, and the alternative to turn it up, which literally picks up all the noise it senses, including background fuzz. Put the Volume too high and voices will begin to sound 'tinny'.
You can turn the Volume down then, but move the Boost up, and you will get a louder voice without that effect. Bear in mind that Boost will still pick up background noise to some extent, so trial and error is what's needed.


text:
Q: Android DatePicker fails on android 2.3.3 As I am new to Android development I am trying to display DatePicker dialog on Android 2.3.3 emulator,but while it is crashing. I am followed what am I missing to include in my code? But this code is working in Android 4.0.
DatePickerFragment class
public class DatePickerFragment extends DialogFragment implements OnDateSetListener{

 @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current date as the default date in the picker
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        // Create a new instance of DatePickerDialog and return it
        return new DatePickerDialog(getActivity(), this, year, month, day);
    }

    public void onDateSet(DatePicker view, int year, int month, int day) {
        // Do something with the date chosen by the user
    }

}
The activity class that starts the DatePicker Dialog:
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DialogFragment;

import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

@SuppressLint({ "NewApi", "NewApi", "NewApi" })
public class FormAnalysis extends FragmentActivity{

@Override

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fanalysis);
    //getActionBar().setDisplayHomeAsUpEnabled(true);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.fanalysis, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    //switch (item.getItemId()) {
      //  case android.R.id.home:
        //    NavUtils.navigateUpFromSameTask(this);
            return true;
    //}
    //return super.onOptionsItemSelected(item);
}

public void generate(View view){

}
  public void startDialog(View view){
  DialogFragment newFragment = new DatePickerFragment();
    newFragment.show(getSupportFragmentManager(), "datePicker");} }

Update
Here is the Stack Trace

[2012-11-16 00:31:55 - Food Security] ActivityManager: Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=kz.bimash.food.security/.Starter }
[2012-11-16 00:31:55 - Food Security] ActivityManager: Warning: Activity not started, its current task has been brought to the front

A: Your DialogFragment import is for the incorrect version of the class. It needs to be android.support.v4.app.DialogFragment instead of android.app.DialogFragment, otherwise it will not work correctly on 2.3.


text:
Q: I have an error on my code it says "size of an array has non-integral type double" but im confused i don't know what to do with my code ho # # `#include<iostream>
# # #include<cmath>
using namespace std;

int n;
double getAverage(double arr[], int size){
int sum=0;
double average;
for (int i=0; i<size; ++i)
# #        {
sum += arr[i];
# #        }
average=double(sum) / size;
return average;

double getLowest(double arr[], int size){
double lowest;
for(int i=0; i<n; i++){
if(arr[i]<lowest){
lowest=arr[i];

# #       }
return lowest;
# # }
double getHighest(double arr[], int size){
double highest;
for(int i=0; i<size; i++){
if(arr[i]>highest){
highest=arr[i];
# #         }
# #       }
return highest;
# # }

int main()
# # {
double fahrenheit, kelvin, celsius, average, lowest, highest,i;
double temp[1000];
cout<<"Enter the number of temperatures: ";
cin>>n;

for (int i=0; i<n; ++i) {
cout<<"\nEnter temperature : ";
cin>>temp[i];
# #     }
cout<<"\nTemperature in \t Fahrenheit \t Kelvin\n"<<endl;
for (int i = 0; i < n; ++i) {
fahrenheit=celsius*9/5+32;
kelvin=celsius+273.15;
cout<<temp[i]<< "\t"<< toCelsius(temp[i])<<"\t\t"<<toKelvin(toCelsius(temp[i]))<<endl;
# #     }
cout<<"Average temperature: "<<average<<endl;
cout<<"Lowest temperature: "<<lowest<<endl;
cout<<"Highest temperature: "<<highest<<endl;

return 0;
# # }`

Create a C++ program that will input n numbers of temperature in Celsius. Display the list of
temperatures inputted in the 1st column and its equivalent temperature in Fahrenheit in 2nd column and
temperature in Kelvin in 3rd Column. Display the average, the lowest and the highest temperature. Use
a function to return the average, the lowest and the highest temperature.


text:
Q: calling a method exactly after a delay I want a method to be exactly called after some time (1 min for example)
the code below is wrong implementation :
musicPlayer.setOnPlaylistAudioChangedListener((playlist , currentAudioIndex) -> {

        if(playlist.getCurrentIndex()%3 == 0 && playlist.getCurrentIndex()!=0  )
           new Handler().postDelayed(this::myMethod,60000);

I have listView that plays Audio and some callbacks to control events
lets say a user clicks the listView in position 6 shortly after position 3
then myMethod() will be called twice witout the 1 min delay
is there any way to enforce delay even if the user clicks listView in those exact same positions
Thank you

A: The problem is that for the second tap, you don't want it to have a 1min delay.  You want it to have a 2min delay.  SO you'll need to keep track of the number of sounds queued up, and delay the next tap for 60000*number_queued.  And when one plays you'll need to reduce the number queued.


text:
Q: How to solve http11.HeadersTooLargeException? I getting this error in my project while adding items in the cart:

org.apache.coyote.http11.HeadersTooLargeException: An attempt was made
  to    write more data to the response headers than there was room
  available in the buffer.  Increase maxHttpHeaderSize on the connector
  or write less data into the response headers.

A: I faced similar issue and found that it was due to large amount of cookies that got set in response headers.
Please try debugging the coyoteResponse object which has headers field for more information.
Also check: HeadersTooLargeException - response headers


text:
Q: Check if database is exists SQLite (UWP) I writing UWP app. I have PCL and UWP project.
I creating database like this:
public class CreatingBD
{
    private string path = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "db.sqlite");
    public void Create()
    {
        SQLite.Net.SQLiteConnection conn =
            new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), path);
    }

After this I call this method when I launch app. Like this:
public StartScreen()
{
    this.InitializeComponent();
    CreatingBD appdatabase = new CreatingBD();
    appdatabase.Create();
}

I need to check I have database oк no, how I can do this?

A: public class SQLiteDatabase
{

    private static string dbPath = string.Empty;
    private static string DBPath(string fileName)
    {
        if (string.IsNullOrEmpty(dbPath))
        {
            dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, fileName);
        }
        return dbPath;
    }
    /// <summary>
    /// Get fileName From LocalFolder. Please Create first a dataBase.
    /// </summary>
    /// <param name="fileName"></param>
    /// <returns></returns>
    public static SQLiteConnection DbConnection(string fileName)
    {
        return new SQLiteConnection(new SQLitePlatformWinRT(), DBPath(fileName));
    }

    //Installed Location.
    private static string dbPathStatic = string.Empty;
    private static string DBPathStatic(string path)
    {
        if (string.IsNullOrEmpty(dbPathStatic))
        {
            dbPathStatic = Path.Combine(Package.Current.InstalledLocation.Path, path);
        }
        return dbPathStatic;
    }
    /// <summary>
    /// Get fileName Path from Installed location. Note Add @ in path e.g( @"Data\Data.dta or (@"Shared\Data\Data.dta) if in Class Library), Make Data.dta Build to Content in Properties.
    /// </summary>
    /// <param name="fileName"></param>
    /// <returns></returns>
    public static SQLiteConnection DbConnectionPackage(string path)
    {
        return new SQLiteConnection(new SQLitePlatformWinRT(), DBPathStatic(path));
    }

    //Roaming Location
    private static string dbPathRoaming = string.Empty;
    private static string DBPathRoaming(string fileName)
    {
        if (string.IsNullOrEmpty(dbPathRoaming))
        {
            dbPathRoaming = Path.Combine(Windows.Storage.ApplicationData.Current.RoamingFolder.Path, fileName);
        }
        return dbPathRoaming;
    }
    /// <summary>
    /// Get fileName Path. Please Create first a dataBase.
    /// </summary>
    /// <param name="fileName"></param>
    /// <returns></returns>
    public static SQLiteConnection DbConnectionRoaming(string fileName)
    {
        return new SQLiteConnection(new SQLitePlatformWinRT(), DBPathRoaming(fileName));
    }

    //CustomFolder Location
    private static string dbPathCustomFolder = string.Empty;
    private static string DBPathCustomFolder(string fileName, StorageFolder CustomFolder)
    {
        if (string.IsNullOrEmpty(dbPathCustomFolder))
        {
            dbPathCustomFolder = Path.Combine(CustomFolder.Path, fileName);
        }
        return dbPathCustomFolder;
    }
    /// <summary>
    /// Get fileName Path. Please Create first a dataBase.
    /// </summary>
    /// <param name="fileName"></param>
    /// <returns></returns>
    public static SQLiteConnection DbConnectionCustomFolder(string fileName, StorageFolder knownFolder)
    {
        return new SQLiteConnection(new SQLitePlatformWinRT(), DBPathCustomFolder(fileName, knownFolder));
    }

Checking if file exist
 #region CheckFileExist
    public static async Task<bool> IsFileExistAsync(string fileName, StorageFolder folder)
    {
        try
        {
            var item = await folder.TryGetItemAsync(fileName);
            return item != null;
        }
        catch
        {
            return false;
        }
    }
    #endregion


text:
Q: How to use foreach() properly in PHP? It is my first time coding in PHP. I am trying to return an array which contains of the amount of each type of cash
public function test($a){
    $a = [];
        $cash = array(
            '20'   => 0,
            '30'   => 0,
            '40'   => 0,
            '50'  => 0,
            '60'  => 0,
            '70'  => 0,
            '80' => 0,
        );

        foreach($a as $k => $v) {
            if (array_key_exists("$k",$cash) && $v!= null ) {
                $cash[$k] += 1;
            }
        }

        return  $cash;
    }

When I try testing the code I get the error: Invalid argument supplied for foreach()

A: the 1st argument for foreach() must be an array.
$a is not an array
Also note that you are trying to use $count, which was not previously defined as an array. Either that "$cash" assignment should be "$count" or vice-versa.

A: Try calling with test(array('20' => 0)); and you will not get the error. You are probably calling it with something that is not an array?

A: $cash[$key] += 1;

should be
$cash[$k] += 1;

I have included the code that I used for testing here:-
<?php
function test($a){
  $cash = array(
    '20' => 0,
    '30' => 0,
    '40' => 0,
    '50' => 0,
    '60' => 0,
    '70' => 0,
    '80' => 0,
  );

  foreach($a as $k => $v) {
      if (array_key_exists("$k",$cash) && $v != NULL ) {
        $cash[$k] += 1;
      }
    }
  return  $cash;
}

// code that I have added to test the function from the post question
$testArray = array(
  '20' => 1,
  '30' => 2,
  '40' => 3,
  '50' => 4,
  '60' => 5,
  '70' => 6,
  '80' => 7,
);

$cash = test($testArray);

foreach($cash as $k => $v) {
  echo("\n$k : $v");
}

?>

Results:-
20 : 1
30 : 1
40 : 1
50 : 1
60 : 1
70 : 1
80 : 1

A: Maybe you can try removing the comma at the end of your array.
change:    '80' => 0,
to:  '80' => 0


text:
Q: How to make the for loop faster when comparing gridview rows with database? I am fetching a record set of 40k plus records. The requirement is to highlight the records that exists or doesn't exist in our database in a table.
So what we had done is to pick every record and compare with the database table using a procedure.
If exists(Select FunctionalLocation from EngineeringData where
                 FunctionalLocation = @Asset_Number
)
Begin
                 Select 1
End

                 Else
Begin

                 Select 0
End

END

but this is taking so much time and sometimes timeout.
Is there any way we can optimize this code?
For k = 0 To gv_InfoFunctionalLocation.Rows.Count - 1

    If k < 50000 Then    ' to test only

        Dim row = gv_InfoFunctionalLocation.Rows(k)

        Dim RowEffect As Integer
        Dim dSetReturn As New DataSet
        ParamValue(0) = row.Cells(1).Text
        ParamValue(1) = row.Cells(4).Text
        dSetReturn = Func.SP_ReturnDataset(con, "[dbo].[USP_Check_FunctionalLocations]", True, ParamName, ParamType, ParamValue)
        RowEffect = dSetReturn.Tables(0).Rows(0).Item(0)
        Dim gRow As GridViewRow = gv_InfoFunctionalLocation.Rows(k)
        Dim cBox As CheckBox = CType(gRow.FindControl("chkSelect"), CheckBox)

        If RowEffect = 0 Then
            'dtFL.Rows(k).Cells("Status").Value = True
            'dtFL.Rows(k).ReadOnly = True
            gv_InfoFunctionalLocation.Rows(k).BackColor = System.Drawing.Color.Tomato
            cBox.Checked = True

        Else

            gv_InfoFunctionalLocation.Rows(k).BackColor = System.Drawing.Color.YellowGreen
            cBox.Checked = False

        End If

        If cBox.Checked = True Then
            btnImportFL.Enabled = True
            btnImportFL.BackColor = Drawing.Color.Navy
        End If
    End If

Next

Is there quick fix since we are short on time and resources?

A: If the data set in the db is considerably larger than 40k, bulk  load the data's ID values into the db (temp table) and then inner join it, to download only the set of IDs already in the db. Download the results of the query into a HashSet
Otherwise if the db data set isn't orders of magnitude larger than 40k, just download every ID in the db and load them into a HashSet,
In either case you now can iterate the data asking the hashset if the ID is present


text:
Q: Is there a workaround to create multiple funnels for the same goal in Google Analytics? Background:
In Google Analytics, we have created a goal funnel showing each step towards the completion of a purchase on our website. There are several steps in our transaction process, and we are using a funnel to track where users dropoff. The transaction steps occur in modals where the URL does not change, so we are using virtual pageviews so that the funnel can track each modal screen as a step towards the destination goal.
The Problem:
The problem we are having is that there are three different pages on the site where a transaction can begin, and we want to understand how our conversion rate compares whether the transaction starts on page A, B, or C. We are trying to do this without having to create three separate goals with a funnel for each.
Is there a way to capture this in a single goal?
It doesn't seem like we can create multiple funnels for a single goal; but if we could filter to identify the page on which transactions began in a report after the fact, that would work.
Is there any way to do this, or will we need to create a separate goal for each page on which the transaction can begin? Note that the transaction process is the same irrespective of the starting page, it is just the starting page that is different.
Thank you very much for your help!


text:
Q: Is An Initial Query Required For An Entity Update With A Child Object I have an Album entity:
public class Album
{
    public Album() { }

    [Key]
    [Column("AlbumId")]
    public int Id { get; set; }
    public string Title { get; set; }
    public int ReleaseYear { get; set; }
    public int Rating { get; set; }
    public int ComposerId { get; set; }

    [ForeignKey("ComposerId")]
    public Composer Composer { get; set; }

}

Which contains Composer as a child object:
public class Composer
{
    [Key]
    [Column("ComposerId")]
    public int Id { get; set; }
    public string Name { get; set; }
}

In my update method for Album, I have the following code which works correctly:
public void UpdateAlbum(Album album)
{
    using (var context = new MusicCatelogContext())
    {
        try
        {
                Album albumEntity = context.Albums
                        .Where(a => a.Id.Equals(album.Id))
                        .Include(a => a.Composer)
                        .First();

                Composer composerEntity = context.Composers
                        .Where(c => c.Id.Equals(album.Composer.Id))
                        .First();

                context.Entry(albumEntity).CurrentValues.SetValues(album);
                albumEntity.Composer = composerEntity;

                context.SaveChanges();

        }

The above code, although working, required two queries to the database. I would have expected to be able to just attach the updated Album entity as below:
public void UpdateAlbum(Album album)
{
    using (var context = new MusicCatelogContext())
    {
        try
        {
            context.Entry(album).State = EntityState.Modified;
            context.SaveChanges();
        }

However, when I try this code, the follow exception is raised when I try to set the state:
A referential integrity constraint violation occurred: The property value(s) of 'Composer.Id' on one end of a relationship do not match the property value(s) of 'Album.ComposerId' on the other end.
I've done a lot of research and I'm still unsure why this is the case. I should note that the entire Composer object passed to UpdateAlbum in the album parameter is the new updated version.
Therefore, my questions are:

*

*Is the first version the only way to update an existing entity with a child object (i.e. an initial SELECT is required)?

*If not, what is wrong with the second version of the code that is causing the error?

Thanks.


text:
Q: Grouping sets columns in aggregate arguments and NULL replacement There are many grouping sets examples on the internet like query Q1 in the example below.  But query Q2 is different because A2 is a grouping column and it is used as the argument to SUM().
Which one of the following is correct for Q2 according to the SQL Standard (any version since 2003 that supports grouping sets)?  If (1) is correct, please explain why with reference to the Standard.

*

*A2 is replaced by NULL unless it is in an argument to an aggregate.  This interpretation would give results R1 below.  This is Oracle's behaviour (which seems more useful).

*A2 is replaced by NULL including where it is used in an aggregate: this means that the aggregate will return NULL.
This interpretation would give results R2 below.  This is how I have understood the SQL Standard (possibly incorrectly).
Example code:
-- Setup
create table A (A1 int, A2 int, A3 int);
insert into A values (1, 1, 100);
insert into A values (1, 2, 40);
insert into A values (2, 1, 70);
insert into A values (5, 1, 90);

-- Query Q1
-- Expected/Observed results:
--
--         A1         A2    SUM(A3)
-- ---------- ---------- ----------
--          1          -        140
--          2          -         70
--          5          -         90
--          -          1        260
--          -          2         40
--          -          -        300
select A1, A2, sum (A3)
from A
group by grouping sets ((A1), (A2), ())
order by 1, 2;

-- Query Q2
-- Results R1 (Oracle):
--         A1         A2    SUM(A2)
-- ---------- ---------- ----------
--          1          -          3
--          2          -          1
--          5          -          1
--          -          1          3
--          -          2          2
--          -          -          5
--
-- Results R2 (SQL Standard?):
--         A1         A2    SUM(A2)
-- ---------- ---------- ----------
--          1          -          -
--          2          -          -
--          5          -          -
--          -          1          3
--          -          2          2
--          -          -          -   -- NULL row
select A1, A2, sum (A2)
from A
group by grouping sets ((A1), (A2), ())
order by 1, 2;

I am aware of this from SQL 2003 7.9 Syntax 17, which describes how columns are replaced with NULLs.  However, I might have missed or misunderstood a rule elsewhere that excludes arguments to aggregates.
m) For each GS_i:
   iii) Case:
        1) If GS_i is an <ordinary grouping set>, then
           A) Transform SL2 to obtain SL3, and transform HC to obtain
              HC3, as follows:
              II) Replace each <column reference> in SL2 and HC that
                  references PC_k by "CAST(NULL AS DTPCk)"

A: As with many difficult SQL features, it can help to look at earlier versions of the standard where the phrasing might be simpler.  And it turns out that grouping sets were introduced in SQL 1999 and were then revised in SQL 2003.
SQL 1999
Syntax Rule 4 states:
Let SING be the <select list> constructed by removing from SL every <select
sublist> that is not a <derived column> that contains at least one <set
function specification>.

Then Syntax Rule 11 defines PC_k as the column references contained in the group by list.  It constructs a derived table projecting the union of GSQQL_i, which are query specifications projecting the PC_k or NULL as appropriate, the PCBIT_i grouping function indicators and SING.
Thus any  that contains a set function will not have its argument replaced, and its columns won't be replaced either.  So answer (1) is correct.
However, in the following query the GSQQL_i corresponding to the <grand total> doesn't group by C1 so I think it will give an error rather than replacing C1 with NULL for that grouping set.
select C1 + MAX(C2) from T group by grouping sets ((C1), ());

SQL 2003 - 2011
I still don't have a definitive answer for this.  It hinges on what they meant (or forgot to specify?) by "references" in the replacement rule.  It would be clearer if it said one of "immediately contained", "simply contained" or "directly contained", as defined in ISO 9075-1 (SQL Part 1: Framework).
The note (number 134 in SQL 2003) at the start of General Rules says "As a
result of the syntactic transformations specified in the Syntax Rules of this
Sub-clause, only primitive <group by clause>s are left to consider."  So the
aggregate argument either has or has not actually been replaced: we aren't
expected to evaluate aggregates in a special way (whereas if General Rule 3 were in effect applied before the NULL substitution of Syntax Rule 17 then answer (1) would be correct).
I found a draft of Technical Corrigendum 5 [pdf], which is a "diff" towards SQL 2003.  This includes the relevant changes to  on pages 80-87.  Unfortunately the bulk of the change has only the brief rationale "Provide a correct, unified treatment of CUBE and ROLLUP".  General Rule 3, quoted above, has the rationale "clarify the semantics of column references".


text:
Q: Iterate through multiple lists at the same time Is it possible to iterate through multiple lists and return arguments from different lists within the same loop?
I.e., Instead of -
For x in trees:
  Print(x)
For y in bushes:
  Print(y)

Something like -
For x,y in trees,bushes:
  Print(x +"\n"+ y)

A: You can simply use zip or itertools.izip:
for x, y in zip(trees, bushes):
  print x, y

A: You can use zip():
a=['1','2','2']
b=['3','4','5']

for x,y in zip(a,b):
     print(x,y)

output:
1 3
2 4
2 5


text:
Q: Why is my code repeating when it shouldn't? list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
num = int(input("Pick a number between 1-10 "))
while num != str(list):
    print("That is not an adaquate choice.")
    num = int(input("Pick a number between 1-10 "))
    if num == 1:
        file = open("external_files.txt", "w")
        hsname = input("Please enter your name. If it is over 5 letters, use your initials. ")
        if len(hsname) < 5:
            print("Your name has been added to the scoreboard.")
            file.write("\n")
            file.write(hsname)
            file.write(" - ")
            file.write(str(x))
            file.close()
        else:
            while len(hsname) > 5:
                print("Sorry, that name is too long.")
                hsname = input("Please enter your name. If it is over 5 letters, use your initials. ")
                if len(hsname) < 5:
                    print("Your name has been added to the scoreboard.")
                    file.write("\n")
                    file.write(hsname)
                    file.write(" - ")
                    file.write(str(x))
                    file.close()
                    break

This is only a little bit of the code to not bore you with repetetiveness, but the loop does break under the right condidtions.
My problem is that, further down in the code, it is mostly the same but without the while and other statements that would deny it from making sense if I enter a number that is not in that list. But when I run it it contstantly says "That is not an adaquate choice."

A: str(list) is returning the entire list as a single string which will never match the input.
Change this line:
while num != str(list):

To this:
while not num in list:

As a side note, you should not use list as a variable name since it is a type in Python.


text:
Q: GridView returns 2 new details rows on AddRow-function I have a strange and frustrating problem with my grid using Devexpress.
I have the following grid:

I have a master row (selected) row and I want the user to let it create dynamically based detail rows and fill them up. This is all linked to a sql db in the back.
My problem is as you can see in the picture, that when I press the 'create detail' button, 2 new rows are created instead of 1.
I have absolutely no idea why this is the case (since my master addrow -function does not have this behavior).
What am I doing wrong in my code?
public partial class Get_Recurring_Items : DevExpress.XtraBars.Ribbon.RibbonForm
    {
        int companyID;
        DataSet ds;
        SqlDataAdapter daRecurrentItems;
        SqlDataAdapter daRecurrentItemsDetails;
        public static SqlConnection conn;

        public Get_Recurring_Items(int _companyID)
        {
            companyID = _companyID;
            InitializeComponent();
            DisplayData();

            btn_CreateDetailRow.ItemClick += Btn_CreateDetailRow_ItemClick;
            gridView.RowUpdated += GridView_RowUpdated;
            btn_Save.ItemClick += Btn_Save_ItemClick;
            gridView.InitNewRow += GridView_InitNewRow;
            detailsView.InitNewRow += DetailsView_InitNewRow;
        }
        private DataSet GetMasterDetail()
        {
            ds = new DataSet();
            ds.Clear();
            ds.Tables.Add(CreateReccuringItemsTable());
            ds.Tables.Add(CreateDetailsTable());
            DataColumn keyColumn = ds.Tables["ReccuringItems"].Columns["ID"];
            DataColumn foreignKeyColumn = ds.Tables["ReccuringItemsDetails"].Columns["Recurring_Item_ID"];
            ds.Relations.Clear();

            ds.Relations.Add("ItemsDetails", keyColumn, foreignKeyColumn, false);

            gridControl.LevelTree.Nodes.Add("ItemsDetails", gridView);

            return ds;
        }

        private DataTable CreateReccuringItemsTable()
        {
            conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Database"].ConnectionString);
            DataTable tbl = new DataTable("ReccuringItems");

            daRecurrentItems = new SqlDataAdapter("SELECT DISTINCT * FROM Company_Recurring_Items WHERE companyID = @companyID", conn);

            daRecurrentItems.SelectCommand.Parameters.Add(new SqlParameter
            {
                ParameterName = "@companyID",
                Value = companyID,
                SqlDbType = SqlDbType.Int,
            });
            daRecurrentItems.Fill(tbl);
            return tbl;
        }

        private DataTable CreateDetailsTable()
        {
            conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Database"].ConnectionString);
            DataTable tbl = new DataTable("ReccuringItemsDetails");
            daRecurrentItemsDetails = new SqlDataAdapter("SELECT DISTINCT details.ID, details.Recurring_Item_ID, details.Description , details.Creation_Date FROM Company_Recurring_Items_Details as details", conn);
            daRecurrentItemsDetails.Fill(tbl);
            return tbl;
        }

        private DataSet getReccuringItems()
        {
            ds = new DataSet();
            ds.Clear();
            ds.Tables.Add(CreateReccuringItemsTable());
            return ds;
        }
        void DisplayData()
        {
            gridControl.DataSource = GetMasterDetail().Tables["ReccuringItems"];
            gridView.Columns[0].VisibleIndex = -1;
            gridView.Columns[1].VisibleIndex = -1;
            MessageBox.Show("count =  " + detailsView.Columns.Count.ToString());
            if (gridView.Columns.Count > 0)
            {

                detailsView.Columns.Clear();
                string[] fieldNames = new string[] { "ID", "Recurring_Item_ID", "Description", "Creation_Date" };
                DevExpress.XtraGrid.Columns.GridColumn column;
                detailsView.Columns.Clear();
                for (int i = 0; i < fieldNames.Length; i++)
                {
                    column = detailsView.Columns.AddField(fieldNames[i]);
                    column.VisibleIndex = i;
                }
            }
            try
            {
            }
            catch (Exception e3) { MessageBox.Show(e3.ToString()); }
            //gridView.CellValueChanged += GridView_CellValueChanged;
        }

        private void DetailsView_InitNewRow(object sender, InitNewRowEventArgs e)
        {
            detailsView.SetRowCellValue(e.RowHandle, "Description", "Description");
            detailsView.SetRowCellValue(e.RowHandle, "Creation_Date", DateTime.Now.ToString());
        }

        private void Btn_CreateDetailRow_ItemClick(object sender, ItemClickEventArgs e)
        {
            bool test = true;
            GridView view = gridView.GetDetailView(gridView.FocusedRowHandle, 0) as GridView;
            if (view != null && test == true)
            {
                view.AddNewRow();
                test = false;
            }else
            {
                MessageBox.Show("You must select a master row (item) to create a new detail!");
            }

        }

        private void GridView_InitNewRow(object sender, InitNewRowEventArgs e)
        {
            gridView.SetRowCellValue(e.RowHandle, "companyID", companyID);
        }

        private void GridView_CellValueChanged(object sender, CellValueChangedEventArgs e)
        {
            GridView currentView = sender as GridView;
            currentView.UpdateCurrentRow();
            //  btn_Save.PerformClick();
            if (ds.Tables["ReccuringItems"] != null)
            {
            //btn_Save.PerformClick();
            }
            else
            {
                MessageBox.Show("error");
            }

            gridView.RefreshData();

        }

        private void Btn_Save_ItemClick(object sender, ItemClickEventArgs e)
        {
            ColumnView View = (ColumnView)gridControl.FocusedView;
            if (!(View.PostEditor() && View.UpdateCurrentRow())) return;
            SqlCommandBuilder scb = new SqlCommandBuilder(daRecurrentItems);
            SqlCommandBuilder scb2 = new SqlCommandBuilder(daRecurrentItemsDetails);
            try
            {
                daRecurrentItems.AcceptChangesDuringUpdate = true;
                daRecurrentItemsDetails.AcceptChangesDuringUpdate = true;
                daRecurrentItems.Update(ds.Tables["ReccuringItems"]);
                daRecurrentItemsDetails.Update(ds.Tables["ReccuringItemsDetails"]);
            }
            catch (SqlException ex)
            {
                Debug.WriteLine(ex.Message);
                MessageBox.Show(ex.Message);
            }
        }

I tried using the following workaround (but just as I used a counter) without success:
  private void Btn_CreateDetailRow_ItemClick(object sender, ItemClickEventArgs e)
    {
        bool test = true;
        GridView view = gridView.GetDetailView(gridView.FocusedRowHandle, 0) as GridView;
        if (view != null && test == true)
        {
            view.AddNewRow();
            test = false;
        }else
        {
            MessageBox.Show("You must select a master row (item) to create a new detail!");
        }

    }

It still creates 2 detail rows on the button click...

A: To fix this issue, you need to set the
GridOptionsView.NewItemRowPosition Property

to None in order to hide the NewRow from the detail grid.
https://documentation.devexpress.com/WindowsForms/DevExpress.XtraGrid.Views.Grid.GridOptionsView.NewItemRowPosition.property
GridOptionsView.NewItemRowPosition = NewItemRowPosition.None;


text:
Q: Email sent from SharePoint Designer 2013 workflow not received After migration my SharePoint 2010 web application to 2013, I created a sample workflow in SP Designer 2013 by selecting SP 2010 platform for sending email alert whenever a new item is added in a SharePoint list.
After adding a new item in a list the workflow started and completed successfully but I didn't get the email, all remaining actions worked perfectly. I didn't see any error message in the workflow History List.
I logged the Email Id to the workflow history list using "current Item CreatedBy". It is getting the email id of current user and storing it in the Workflow History list without any issues.
I provided the SMTP mail server in Central Administration->Outgoing Email Settings and also provided in IIS - Default Website(80).
I installed SMTP server in Windows Server 2008 R2 using "Add Features".
But I didn't get email from my workflow. Are any additional configuration steps required?

A: As you mentioned that, Alerts even not working on the list. So, Most probably the issue is with your SMTP configuration rather your workflow.
I would recommend follow the instruction below technet and make sure you followed everything.
http://technet.microsoft.com/en-us/library/cc288949(v=office.14).aspx
http://www.experts-exchange.com/Networking/Protocols/Email/Q_28170459.html


text:
Q: put request in angular sends empty form data I am trying to make a put request.
The api requires an array of numbers as request parameter
    $http({

    'requestpath/putrequesturl',
    {
        categories: [categorylist]
    },
    {
        'method': 'PUT',
        'authToken': authToken,
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    }

});

the data is sent as
requestpath/putrequesturl?categories=%5B5,19,12%5D

the query string parameter shows correct data, but Form Data in chrome dev tools is empty.
I tried this without content-type too, but it does not work
How can i make this request to send data as Form Data (Request body)
Edit: this is what api requires to get sent (if this is necessary):
Parameter: categories type:array

A: This is how the method put should seems
 $http({
    method: 'PUT',
    url: uri,
    headers: {"Content-Type": "application/json;charset=UTF-8"},
    data: someData
});

or
$http.put(url, data, config)

A: Your $http params looks a little odd. Maybe you are trying to do something like this..
$http({
   method: "PUT",
   uri: 'requestpath/putrequesturl',
   headers: {
      "Content-Type": "application/json",
      "authToken": authToken // assuming this should be in the header
   },
   data: {
      categories: [categorylist]
   }
})


text:
Q: Is it possible to change the scrollbar to the left of a listview? I have a ListView, I want to scroll and I want the ScrollBar to appear on the left side of the ListView instead of the right side. Is there a straightforward way to do that?

A: Yes, in css you may try for the scrolling container: demo
  unicode-bidi: bidi-override;
  direction:rtl;

and then you need a reset for the children .
I tested this long ago and it did not work in every browsers, from update to updates, it change sometimes ... ... last safari for windows doesn't take it.

https://developer.mozilla.org/en-US/docs/Web/CSS/unicode-bidi
http://www.w3.org/TR/CSS2/visuren.html#propdef-unicode-bidi
https://drafts.csswg.org/css-writing-modes-3/#unicode-bidi

ul {
  height:100px;
  width:200px;
  overflow:auto;
  unicode-bidi: bidi-override;
  direction:rtl;
  border:solid;
}
li {
  text-align:left;
  unicode-bidi: bidi-override;
  direction:ltr;
  display:block;
}

list item.

list item

list item

list item

list item

list item

list item

list item

list item

list item

list item


text:
Q: Thread related issue I am trying my hand on thread with basic example. But facing force close.
Here's the code.
   public class ThreadExample extends Activity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Thread myThread=null;
        Runnable runnable=new CountDownRunner();
        myThread=new Thread(runnable);

        myThread.start();
    }
    public void Work(){runOnUiThread(new Runnable() {
        public void run() {

                try{
            EditText ed1= (EditText)findViewById(R.id.ed1);
                        Date dt = new Date(0);
                        int hours = dt.getHours();
                        int minutes = dt.getMinutes();
                        int seconds = dt.getSeconds();
                        String curTime = hours + ":"+minutes + ":"+ seconds;
                        ed1.setText(curTime);
            }catch (Exception e) {

            }
            }
    });
}
class CountDownRunner extends ThreadExample implements Runnable{
    @Override
    public void run() {
        // TODO Auto-generated method stub
        Work();
        Toast.makeText(getApplicationContext(), "PIyush", Toast.LENGTH_LONG).show();

    }
}

I checked the DDMS and getting this
03-25 00:51:44.145: DEBUG/dalvikvm(51): threadid=15: bogus mon 1+0>0; adjusting
03-25 00:54:59.515: DEBUG/dalvikvm(51): threadid=15: bogus mon 1+0>0; adjusting
03-25 00:55:44.586: DEBUG/dalvikvm(51): threadid=15: bogus mon 1+0>0; adjusting
03-25 00:57:47.935: DEBUG/dalvikvm(51): threadid=15: bogus mon 1+0>0; adjusting
03-25 01:01:22.805: DEBUG/dalvikvm(51): threadid=15: bogus mon 1+0>0; adjusting
03-25 01:02:00.255: DEBUG/dalvikvm(51): GC freed 16675 objects / 783752 bytes in 171ms
03-25 01:19:34.195: DEBUG/dalvikvm(51): threadid=15: bogus mon 1+0>0; adjusting
03-25 01:19:35.235: DEBUG/dalvikvm(51): threadid=15: bogus mon 1+0>0; adjusting
03-25 01:20:49.645: DEBUG/dalvikvm(51): threadid=15: bogus mon 1+0>0; adjusting
03-25 01:20:57.285: DEBUG/dalvikvm(51): threadid=15: bogus mon 1+0>0; adjusting
03-25 01:27:24.475: DEBUG/dalvikvm(51): threadid=15: bogus mon 1+0>0; adjusting
03-25 01:28:30.065: DEBUG/dalvikvm(51): threadid=15: bogus mon 1+0>0; adjusting
03-25 01:29:44.835: DEBUG/dalvikvm(51): threadid=15: bogus mon 1+0>0; adjusting
03-25 01:36:45.355: DEBUG/dalvikvm(51): threadid=15: bogus mon 1+0>0; adjusting
03-25 01:38:07.125: DEBUG/dalvikvm(51): threadid=15: bogus mon 1+0>0; adjusting
03-25 01:46:00.256: DEBUG/dalvikvm(51): GC freed 16800 objects / 782664 bytes in 205ms
03-25 01:46:58.495: DEBUG/dalvikvm(51): threadid=15: bogus mon 1+0>0; adjusting
03-25 01:50:45.075: DEBUG/dalvikvm(51): threadid=15: bogus mon 1+0>0; adjusting
03-25 01:58:26.595: DEBUG/dalvikvm(51): threadid=15: bogus mon 1+0>0; adjusting
03-25 01:58:43.965: DEBUG/dalvikvm(51): threadid=15: bogus mon 1+0>0; adjusting

A: This is a working version of your code, which should point you in the right direction for getting your edit control working:
public class ThreadExample extends Activity {
    EditText ed1;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ed1 = (EditText)findViewById(R.id.ed1);

        Thread myThread=null;
        Runnable runnable=new CountDownRunner();
        myThread=new Thread(runnable);

        myThread.start();
    }

    class CountDownRunner implements Runnable{
        @Override
        public void run() {
            try {
                Thread.sleep(10000);
            }
            catch (InterruptedException ex) {

            }// TODO Auto-generated method stub
            Work();
        }

        public void Work(){
            try{
                ed1.post(new Runnable() {
                    public void run() {
                        Date dt = new Date();
                        int hours = dt.getHours();
                        int minutes = dt.getMinutes();
                        int seconds = dt.getSeconds();
                        String curTime = hours + ":"+minutes + ":"+ seconds;
                        Toast.makeText(getApplicationContext(), "PIyush",
                                       Toast.LENGTH_LONG).show();
                        ed1.setText(curTime);
                    }
                });
            }
            catch (Exception e) {
                Log.d("test", e.toString());
            }
        }
    }
}

A few things I wasn't sure about:

*

*Your Countdown runner was extending ThreadExample.  I think this pushes all of your members from ThreadExample out of scope (which is why my version doesn't)

*Your thread doesn't loop, I'm not sure if you can post to the UI, before it's finished being created (which is why there's an extended sleep at the start of my run function).

A: The line EditText myText=(EditText)findViewById(R.id.ed1); is called before setContentView()  so you probably get a null pointer exception, instead, you can do it in this way:
public class ThreadExample extends Activity {
EditText myText;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    myText=(EditText)findViewById(R.id.ed1);
    ...

A: You are not allowed (and should not) to call findViewById or communicate with any view from another thread than the UI thread. The stack trace will say that as well.
Check how an asyncTask works or just use the use the runOnUIThread method.


text:
Q: Unity - Stop invoking objects when object is out of camera view I am developing an Android game using Unity and in my game I am instantiating objects which move in x direction visible to camera and when they leave camera view they are destroyed, to stop slowing the processing and taking memory. It works fine, but when my player moves in vertical direction there are objects which are instantiated but they are out of camera view, and then they are not destroyed. Therefore, when my objects are out of camera view I want to stop invokeRepeating. Here is the code which works only when objects are in view.
    public GameObject colorbar;
    public Vector2 velocity = new Vector2(-3, 0);

    void Start () {

        GetComponent<Rigidbody2D>().velocity = velocity;
        transform.position = new Vector3(transform.position.x, transform.position.y, 0);
        InvokeRepeating("CreateObstacle", 1f, 1.8f);

    }

    // Update is called once per frame
    void Update () {

    }
    public void OnBecameInvisible()
    {
        Destroy(colorbar);
        Debug.Log ("Color bar is Destroyed");
    }
    void CreateObstacle()
    {
        Instantiate(colorbar);
        Debug.Log ("Color bar instantiating");
    }

}

A: You can check if the renderer is visible when you create the object:
http://docs.unity3d.com/ScriptReference/Renderer-isVisible.html
void Awake(){
   if(GetComponent<Renderer>().isVisible == false){
       Destroy(this.gameObject);
    }
}

But best would be to avoid creation if not needed, so you could get the point where you object should be created, then convert to screen point:
http://docs.unity3d.com/ScriptReference/Camera.WorldToScreenPoint.html
if the value is within the boundaries of the screen, then you good. You could also linecast from position to camera and if there is nothing stopping the cast, you are double good to create.
Vector3 pos = ObjectPos;
Vector3 screenPos = Camera.main.WorldToScreenPoint(pos);
if(screenPos.x > 0 && screenPos.x < Camera.main.pixelWidth &&
   screenPos.y > 0 && screenPos.y < Camera.main.pixelHeight && screenPos.z > 0)
{
    if (Physics.Linecast(pos, Camera.main.transform.position) == false){
        // Create object
    }
}

Keep in mind this is using the position of the object. If your object is large, then the position may be outside while some edges would be inside. The best would be to check for each vertex of the mesh. But if you have a complex mesh, that might get expensive, if you deal with a cube then maybe.


text:
Q: What do these commands from a shell script do? I'm just starting to learn bash. I have the following script, and I would like to know what does the following commands do in order to start to understand a little bit this world.
if [ ! -w "." ]
then
echo "You need write permission in the directory"
exit 1
fi

firefoxGeditOpen=ps -d | grep -ic -e firefox -e gedit
if [[firefoxGeditOpen>0]]
then
echo "Firefox and Gedit must be closed to let the script work"
exit 1
fi

while(true)
do
firefox &
firefoxPid=$!
gedit &
geditPid=$!
echo "Firefox PID $firefoxPid Gedit PID $geditPid">>result.txt
wait
echo "You have closed all the processes. They will be re-opened">>result.txt
done

Thanks in advance!

A: As I mentioned in my comment there are some vital pieces missing here and these commands together don't quite make sense, but I will go over them.

*

*if [ ! -w "." ]: . represents the current directory. -w tests if it is writeable. ! negates the test (so the statement returns true if the directory is not writeable vs the other way around).

*ps -d | grep -ic -e firefox -e gedit: ps -d prints all processes minus session starters. grep searches the piped output from ps for patterns (which we'll get to in a minute). -i makes the search case insensitive. -c outputs a count of the matches instead of the actual matches. -e takes the search expressions. In this case firefox and gedit. So if neither FF nor gedit is running the command will output 0. If one of them is running it will output 1. If both are running it will output 2.

*firefox &: Start firefox. & forces the process into the background.

*firefoxPid=$!: In a bash shell script $! holds the job number of the last background command. firefoxPid is a variable. So what's happening here is the job number of the last background command (which happens to be firefox's) is stored to a variable named firefoxPid.


text:
Q: Display specific string Value of JS File in HTML I just want to display the first value 0.2 of Port01 in Html. The corresponding JavaScript code for this.

and in addition data123.js file
[{"name":"VVB001 (port01)","time":"2021-02-10 14:01:09","type":"a-Peak","value":0.2},{"name":"VVB001 (port02)","time":"2021-02-10 14:01:09","type":"a-Peak","value":0.2},{"name":"VVB001 (port03)","time":"2021-02-10 14:01:09","type":"a-Peak","value":0}]

Do you have any ideas?

A: loadFile takes some time to fetch the data and return the data, Promises can be used to return a value later.
Here's the code rewritten with promises. I also changed the way error/success handling is done in onreadystatechange according to the MDN docs.

P.S.
Fetch API is more modern, powerful and flexible API than XMLHttpRequest, try using it instead.
P.P.S.
Async/await syntax can be used to simplify working with Promises. Here is a good article about that.


text:
Q: GMap inside Jquery Mobile page with IScrollView I have a webapp created with JQuery Mobile v1.3.2 implementing IScrollView.
When I'm scrolling the map vertically the Scroll View scrolls also.
Is there a way to disable that behaviour, to cancel iscroll scrolling when scrolling the gmap?
Thanks in advance.

A: The problem is that the map still seems to propagate touch events to iscroll. Let's try to prevent this by stopPropagation();
Edit
Here is the working jQuery mobile fiddle
var map_canvas = $('#map_canvas')[0];
// "mousedown" should be "touchstart" on mobile device
$(map_canvas).bind('mousedown', function(e) {
    e.stopPropagation();
});

A fiddle with plain javascript here.
var map_canvas = document.getElementById('map_canvas');
// "mousedown" should be "touchstart" on mobile device
map_canvas.addEventListener('mousedown', function(e) {
    e.stopPropagation();
}, false);

P.S.
Find here The link to the stopPropagation docs, comes in very handy some times ;)


text:
Q: BibTex Style File for UWE Harvard In 2011 the University of the West of England developed its own version of the Harvard referencing system [1].
Unfortunately they do not officially support BibTex and therefore do not provide a bst file.
I was wondering if any former or current student has created such a file and is willing to share it.
[1] http://www1.uwe.ac.uk/students/studysupport/studyskills/referencing/uweharvard.aspx

A: With biblatex it is not too hard to define this citation style.
I was not to keen to implement all 95 (!) different entry types, but @book, @inbook, @collection, @incollection, @article and @online should work.
The basis is the standard authoryear style.
Load biblatex with \usepackage[backend=biber, style=authoryear, maxnames=999, maxcitenames=3, firstinits=true, urldate=long]{biblatex} and add this to your preamble
\DeclareNameAlias{sortname}{last-first}
\DeclareFieldFormat{edition}{%
  \ifinteger{#1}
    {\ifnumequal{#1}{1}%
     {}%
     {\mkbibordedition{#1}~\bibstring{edition}}%
    }
    {#1\isdot}}

\DeclareFieldFormat[article,inbook,incollection]{title}{#1\isdot}
\DeclareFieldFormat[article,inbook,incollection]{citetitle}{#1\isdot}

\newrobustcmd{\MakeTitleCase}[1]{%
  \ifboolexpr{test {\ifentrytype{article}} or test {\ifentrytype{inbook}} or test {\ifentrytype{incollection}}}
    {#1}
    {\MakeSentenceCase{#1}}}

\DeclareFieldFormat{urldate}{\bibsentence\mkbibbrackets{\bibstring{urlseen}\space#1}}
\DeclareFieldFormat{url}{\bibstring{urlfrom}\addcolon\space\url{#1}}

\renewbibmacro*{journal}{%
  \iffieldundef{journaltitle}
    {}
    {\printtext[journaltitle]{%
       \printfield[titlecase]{journaltitle}%
       \setunit{\subtitlepunct}%
       \printfield[titlecase]{journalsubtitle}}
       \ifboolexpr{
         not test {\iffieldundef{url}}
         or
         not test {\iffieldundef{urldate}}
         or
         not test {\iffieldundef{doi}}
         or
         not test {\iffieldundef{eprint}}
       }
         {\nopunct\bibstring[\mkbibbrackets]{online}}%
         {}}}

\newbibmacro*{journal+issuetitle}{%
  \usebibmacro{journal}%
  \setunit*{\addspace}%
  \iffieldundef{series}
    {}
    {\newunit
     \printfield{series}%
     \setunit{\addspace}}%
  \newunit
  \usebibmacro{volume+number+eid}%
  \setunit{\addspace}%
  \usebibmacro{issue+date}%
  \setunit{\addcolon\space}%
  \usebibmacro{issue}%
  \newunit}

\NewBibliographyString{online}
\DefineBibliographyStrings{english}{%
  urlseen    = {accessed},
  online     = {online},
}

Consider the MWE
\documentclass[british]{scrartcl}
\usepackage[utf8]{inputenc}
\usepackage{babel}
\usepackage{csquotes}
\usepackage[backend=biber, style=authoryear, maxnames=999, maxcitenames=3, firstinits=true, urldate=long]{biblatex}

\addbibresource{biblatex-examples.bib}
\addbibresource{\jobname.bib}

\DeclareNameAlias{sortname}{last-first}
\DeclareFieldFormat{edition}{%
  \ifinteger{#1}
    {\ifnumequal{#1}{1}%
     {}%
     {\mkbibordedition{#1}~\bibstring{edition}}%
    }
    {#1\isdot}}

\DeclareFieldFormat[article,inbook,incollection]{title}{#1\isdot}
\DeclareFieldFormat[article,inbook,incollection]{citetitle}{#1\isdot}

\newrobustcmd{\MakeTitleCase}[1]{%
  \ifboolexpr{test {\ifentrytype{article}} or test {\ifentrytype{inbook}} or test {\ifentrytype{incollection}}}
    {#1}
    {\MakeSentenceCase{#1}}}

\DeclareFieldFormat{urldate}{\bibsentence\mkbibbrackets{\bibstring{urlseen}\space#1}}
\DeclareFieldFormat{url}{\bibstring{urlfrom}\addcolon\space\url{#1}}

\renewbibmacro*{journal}{%
  \iffieldundef{journaltitle}
    {}
    {\printtext[journaltitle]{%
       \printfield[titlecase]{journaltitle}%
       \setunit{\subtitlepunct}%
       \printfield[titlecase]{journalsubtitle}}
       \ifboolexpr{
         not test {\iffieldundef{url}}
         or
         not test {\iffieldundef{urldate}}
         or
         not test {\iffieldundef{doi}}
         or
         not test {\iffieldundef{eprint}}
       }
         {\nopunct\bibstring[\mkbibbrackets]{online}}%
         {}}}

\newbibmacro*{journal+issuetitle}{%
  \usebibmacro{journal}%
  \setunit*{\addspace}%
  \iffieldundef{series}
    {}
    {\newunit
     \printfield{series}%
     \setunit{\addspace}}%
  \newunit
  \usebibmacro{volume+number+eid}%
  \setunit{\addspace}%
  \usebibmacro{issue+date}%
  \setunit{\addcolon\space}%
  \usebibmacro{issue}%
  \newunit}

\NewBibliographyString{online}
\DefineBibliographyStrings{english}{%
  urlseen    = {accessed},
  online     = {online},
}

\usepackage{filecontents}
\begin{filecontents*}{\jobname.bib}
@book{PearECP,
  author    = {Alan Pearson and John Field and Zoe Jordan},
  title     = {Evidence-Based Clinical Practice in Nursing and Health Care},
  subtitle  = {Assimilating Research, Experience and Expertise},
  year      = {2007},
  publisher = {Blackwell},
  address   = {Oxford},
  edition   = {2},
}
@article{LangLC,
  author    = {Langman, S. and Smith, J. and Athens, D.A. and Gibbs, Y.},
  title     = {Life cycles: manufacturing techniques in the new millennium},
  year      = {2000},
  journal   = {Manufacturing Weekly},
  volume    = {15},
  number    = {1},
  pages     = {12-18},
}
@article{KellTFAC,
  author    = {Bridget Kelly and Jason C.G. Halford and Emma J. Boyland and Kathy Chapman and Inmaculada Bautista-Castano and Christina Berg and Margherita Caroli and Brian Cook and Janine G. Coutinho and Tobias Effertz and Evangelia Grammatikaki and Kathleen Keller and Raymond Leung and Yannis Manios and Renata Monteiro and Claire Pedley and Hillevi Prell and Kim Raine and Elisabetta Recine and Lluis Serra-Majem and Sonia Singh and Carolyn Summerbell},
  title     = {Television Food Advertising to Children},
  subtitle  = {A Global Perspective},
  date      = {2010-09},
  journal   = {American Journal of Public Health},
  volume    = {100},
  number    = {9},
  pages     = {1730–-1736},
  doi       = {10.2105/AJPH.2009.179267},
  urldate   = {2013-09-28},
}
@online{RCN,
  author    = {{Royal College of Nursing}},
  title     = {Learning and Education},
  date      = {2009},
  url       = {http://www.rcn.org.uk/development/learning},
  urldate   = {2010-12-22},
}
@incollection{CarNaM,
  title     = {Nursing and Medicine},
  author    = {Havi Carel},
  editor    = {Sebastian Luft and Soren Overgaard},
  booktitle = {The Routledge Companion to Phenomenology},
  date      = {2011},
  publisher = {Routledge},
  location  = {London},
  chapter   = {57},
}
@collection{BoxSE,
  title     = {Sports Ethics},
  subtitle  = {An Anthology},
  editor    = {Jan Boxill},
  date      = {2003},
  publisher = {Blackwell},
  location  = {Oxford},
}
\end{filecontents*}

\begin{document}
  Citations \parencite{wilde}, \parencite{herrmann} and \parencite{baez/article}
  The Greek philosophers must have known something \parencite{aristotle:anima}.
  Again \parencite{westfahl:space} and \parencite{angenendt} and \parencite{companion}.
  \nocite{PearECP,LangLC,KellTFAC,RCN,CarNaM,knuth:ct,nietzsche:ksa,BoxSE}

  \printbibliography
\end{document}

A: I think using biblatex is a great idea in this case. That is why I accepted moewe's answer.
However, I have not yet confirmed whether or not his code produces the correct style.
In case somebody wants to stick with plain BibTex I tried creating a style via latex makebst. I uploaded the result with some commentary here.


text:
Q: how to write array object content in excel through selenium     int col = driver.findElements(By.xpath("//table[@id=\"transactionListData\"]/thead/tr/th")).size();
    int row =driver.findElements(By.xpath("//table[@id=\"transactionListData\"]/tbody/tr")).size();
    //ArrayList<Object[]> mydata = new ArrayList<Object[]>();
    Object [][] ob = new Object[row][col];
    for( int i=1; i<=row; i++)
    {
        for (int j=1; j<=col; j++)
        {
            String text =driver.findElement(By.xpath("//*[@id='transactionListData']/tbody/tr["+i+"]/td["+j+"]")).getText();
            //System.out.println("text " +text);
            ob[i][j] = text;

        }
    }
    try {
        String s = util.writeIntoExcel(ob, row, col);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    //return flag;
}

I have passed ob in below function to write its content in to excel file. but unable to print where ob is a object array Object [][] ob = new Object[row][col];. I am getting an error where i am trying  to write data in to excel regarding Object in to string conversion.

public static String writeIntoExcel(Object ob, int rowi,int colj ) throws IOException
{
    int rowcount =  rowi;
    int colcount = colj;
    Object oa[][]  = new Object[rowcount][colcount];
    oa =  (Object[][]) ob;
    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet sheet = workbook.createSheet("Transacton History");

    for (int i=1; i<=rowcount ; i++)
    {
        for (int j=1; j<=colcount ; j++)
        {
            String val = (String) oa[i][j];
            Row row = sheet.createRow(i);
            row.createCell(colj).setCellValue(val);
        }
    }
    FileOutputStream fileOut = new FileOutputStream("\"\\\\btfin.com\\filesrv\\User\\Offshore\\SG1\\L097117\\user\\My Documents\\workbook.xlsx");
    workbook.write(fileOut);
    fileOut.close();

    return "Data is written";
}

}

A: Answer to question above is :
    Object [][] ob = new Object[row][col];
    for( int i=1; i<=row; i++)
    {
        for (int j=1; j<=col; j++)
        {
            String text =driver.findElement(By.xpath("//*[@id='transactionListData']/tbody/tr["+i+"]/td["+j+"]")).getText();
            //System.out.println("text " +text);
            ob[i-1][j-1] = text;
        }
    }

// rest everything is fine..
public static String writeIntoExcel(Object[][] sob ) throws IOException
{

    //String oa[][]  = sob;
    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet sheet = workbook.createSheet("Transacton History");
    Object cellvalue = null;
    for (int i=0; i<=sob.length ; i++)
    {
        Row row = sheet.createRow(i + 1);
        for (int j=0; j<=sob[i].length ; j++)
        {
            Cell cell=row.createCell(j+1);
            cellvalue = sob[i][j];
            if (cellvalue instanceof String)
                cell.setCellValue((String)(cellvalue));
            else if (cellvalue instanceof Integer)
                cell.setCellValue((Integer)cellvalue);

            cell.setCellValue((String)cellvalue);
        }
    }
    FileOutputStream fileOut = new FileOutputStream("");
    workbook.write(fileOut);
    fileOut.close();
    workbook.close();

    return "Data is written";


text:
Q: Area enclosed between $2$ curves
Question: The area enclosed by the curves $$ y^2 = x \ \text{and} \ y^2 = \ 3x - 1, \ \ \ \ \  \text{where} \  \ 0\leq \  x\leq \frac{1}{2} \ $$

My work:
To begin with I re-arranged the curves in terms of $y$ to the power $1$
$$y_{1} = \sqrt{x}$$
and
$$y_{2} = \sqrt{3x-1}$$
and then proceeded to take the integral for both over the interval $0\leq \  x\leq \frac{1}{2}$
$$f(x_{1}) = \frac{1}{3\sqrt{2}}$$
and
$$f(x_{2}) = \frac{5^{\frac{3}{2}}}{9\sqrt{2}} - \frac{2}{9}$$
And therefore the area between the curves is $\displaystyle\int f(x_{1}) - f(x_{2})$ right?
Is this the correct method? Because the answer that was provided to me was $\frac{2\sqrt{2}}{9}$.

A: Say $A_1$ is area between parabola $y^2 = x$ and line $x = \frac{1}{2}$, which you write as $f(x_1)$ and $A_2$ is the area between parabola $y^2 = 3x-1$ and line $x = \frac{1}{2}$
You need to multiple $A_1$ by $2$ as the answer you have is only upper / lower half of the area.
Coming to $A_2$, your mistake is that you are integrating between $x = 0$ and $x = \frac{1}{2}$. The vertex of the second parabola is $(\frac{1}{3}, 0)$. So, you should integrate the second one between $x = \frac{1}{3}$ and $\frac{1}{2}$.
So the second integral should be,
$ \displaystyle 2 \int_{1/3}^{1/2} \int_{0}^{ \sqrt {3x-1}} dy ~dx$
That gives you $A = A_1 - A_2 = \frac{2}{3 \sqrt2} - \frac{2}{9\sqrt2} = \frac{2 \sqrt2}{9}$

Also note that you can directly integrate if you go with respect to $dx$ first. Keep the equations in the form $y^2 = x$ and $y^2 = 3x - 1 \implies x = \frac{y^2+1}{3} ~$.
At intersection $y^2 = x = 3x - 1 \implies x = \frac{1}{2}, y = \pm \frac{1}{\sqrt2}$
So the integral to find area between the curves is,
$\displaystyle \int_{- 1/\sqrt2}^{1/\sqrt2} \int_{y^2}^{ (y^2+1) / 3} ~ dx ~dy$

A: I would integrate with respect to y.
$x = y^2\\
x = \frac {y^2}{3} + \frac 13$
The curves intersect at $(\frac 12, \frac {\sqrt {2}}{2})$ and $(\frac 12, -\frac{\sqrt {2}}{2})$
$\int_{-\frac {\sqrt {2}}{2}}^{\frac {\sqrt 2}{2}} \frac {y^2}{3} + \frac 13 - y^2\ dy$


text:
Q: How to set absolute colour ranges in seaborn heatmap? All - I have the following code to plot a heat map:
import pandas as pd
pd.plotting.register_matplotlib_converters()
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns

data = pd.pivot_table(df.round({'DataA':1}), index='Position',columns='Start',  values='DataA', aggfunc= 'sum')
    data = data.fillna(0)
    import matplotlib.colors as colors

    cmap, norm = colors.from_levels_and_colors([-15000, -500, -10,10,500,10000,100000], ['red','orange','white','green', 'lime','blue'])

f, ax = plt.subplots(figsize=(16, 8))
ax = sns.heatmap(data, annot=True, fmt='g', linewidths=.5, ax=ax, cbar=True,cmap=cmap,norm=norm).set_title('Title')
plt.show()

Which produces:

You will see that in the second column there is an all blank cell which should show the value 11786.2 however I cant see it. How come all values over 10000 dont show and what am I doing wrong?
Any help would be much appreciated!


text:
Q: Save Count No of time records appear in the search results We have a job portal where jobs are being posted by employers. We want to show the employer that how many times their job(s) appear in the search result.
Can you please let us know how save the statics about the jobs fetched using the following query:
SELECT Id, JobTitle,JobDescription
FROM tblJobs
WHERE JobTitle LIKE '%ASP.NET%'.

We are using Sql Server 2008 and our application is in ASP.NET/C#

A: Create a stats table with jobid and search counter columns.. 2 columns.
everytime you run the above search SQL query, get the job ids and increment the search counter.
to optimize you can just get the job ids in a table variable first, update the stats and then do a select to return the title etc.
UPDATE jobstats
SET searchcounter = searchcounter + 1

WHERE jobid IN
(
 jobids from above query
)


text:
Q: not able to download files from azure blob Hi using fileUris in Azure extension of template, not able to download file in VM while launching VM from template.
It throws following error:

VM has reported a failure when processing extension 'customScript'. Error message: "Enable failed: processing file downloads failed: failed to download file[1]: failed to download file: unexpected status code: got=404 expected=200".

A: To get more insight about the issue, you check the following log files on your VM:
  - /var/log/azure/custom-script/handler.log
  - /var/log/waagent.log
enter code here

Your files are downloaded to a path like: /var/lib/waagent/custom-script/download/0/ and the command output is saved to stdout and stderr files in this directory. Please read these files to find out output from your script.
You can find the logs for the extension at /var/log/azure/custom-script/handler.log.
Please open an issue on this GitHub repository if you encounter problems that you could not debug with these log files.
Source: https://github.com/Azure/custom-script-extension-linux

A: Plese check weather your repository is private or public in github or any reposi.
Once you chenge it to public it let you download the repository

A: For storage private networking I needed to add the subnet of the VM to the firewall and enable the "Microsoft.Storage" services endpoint.

A: The message means that the waagent service was not able to download a file using the URL provided in the config file. There could be many reasons for that. I suggest that you need to test that URL manually from the VM to see if the URL can be downloaded at all.


text:
Q: JAVA PROGRAMMING - unDUPLICATOR error on logic I was doing this "Random number game" and have come up with the following code...
public void generate()
{
    for(int i=0; arr[i]!=arr[i+1]; i++)
    {
        for(int l=0; l<10; l++)
        {
            Random rdm=new Random();
            arr[l] = rdm.nextInt(range)+1;

        }
        lbtest.setText("Random Numbers: "+arr[0]+"-"+arr[1]+"-"+arr[2]+"-"+arr[3]+"-"+arr[4]+"-"+arr[5]+"-"+arr[6]+"-"+arr[7]+"-"+arr[8]+"-"+arr[9]);
        bgen.setEnabled(false);
        gametext.setText("");
    }

}

I made 3 different levels for this random number game which means the range of random numbers(1-20, 1-30, and 1-50). the 1-30 and 1-50 levels work. but when I click on 1-20, the code doesn't generate any numbers.
I tried debugging the program to see where this code has the error but JCreator doesn't help. It doesn't display the line with the error.

A: First off, Declare your random variable outside your loops, or else your numbers won't be random at all.
Secondly, the for(int i=0; arr[i]!=arr[i+1]; i++) loop looks very bizarre.  if the first 2 members of arr are the same, then the rest of the code you posted won't execute at all.  Also, if the last 2 members of arr are not the same, then your code will throw an exception.
The the condition arr[i]!=arr[i+1]; has the potential to produce the bug you describe.
If you elaborate a little bit on your requirements, I might be able to help you further.


text:
Q: Enabling Widgets By Default in Custom Theme Development In WP theme building, if a sidebar is not active, can I turn it on? Also, if the sidebar is active, and doesn't contain any widgets, can I add some?
I'm a theme and plugin developer, but this is something I haven't learned to do yet.

A: @Volomike,
When you register a sidebar in your themes functions it will be active in the dashboard.  If no widgets are added to your sidebars WordPress will add the default widgets.  You can prevent WordPress from adding the default widgets by unregistering them:
// Remove WP default Widgets
    // WP 2.8 function using $widget_class
    if (function_exists('unregister_widget')) {
        unregister_widget('WP_Widget_Meta');
        unregister_widget('WP_Widget_Search');
        unregister_widget('');

    // pre WP 2.8 function using $id
    } else {
        unregister_widget_control('meta');
        unregister_widget_control('search');
    }

You can also preset your own widgets.
// The following code sample is from The Thematic Theme which is licensed under the GPLv2

    register_sidebar_widget(__('Search', 'thematic'), 'widget_thematic_search', null, 'search');
    unregister_widget_control('search');
    register_sidebar_widget(__('Meta', 'thematic'), 'widget_thematic_meta', null, 'meta');
    unregister_widget_control('meta');
    register_sidebar_widget(array(__('RSS Links', 'thematic'), 'widgets'), 'widget_thematic_rsslinks');
    register_widget_control(array(__('RSS Links', 'thematic'), 'widgets'), 'widget_thematic_rsslinks_control', 300, 90);

    // Pre-set Widgets
    $preset_widgets = array (
        'primary-aside'  => array( 'search', 'pages', 'categories', 'archives' ),
        'secondary-aside'  => array( 'links', 'rss-links', 'meta' )
        );

    if ( isset( $_GET['activated'] ) ) {
        update_option( 'sidebars_widgets', apply_filters('thematic_preset_widgets',$preset_widgets ));
    }

Thematic is actually a great example of all the things that can be done with widgets.  Take a look at widgets.php and widgets-extensions.php


text:
Q: How to extract a float number from string using loop [python] I use this loop to extract integers, what changes should I make to this loop which will accept decimal numbers.
Here inputn is a string:
def numberseeker():
global i, inputn, number, num
while i < len(inputn):
    if inputn[i].isalnum() is True:
        num = float(inputn[i])
        if inputn[i] == 0:
            number += num
        else:
            number = (number * 10) + num
        i += 1
    elif inputn[i].isalnum() is False:
        ope = inputn[i]
        operator(ope)
        break

A: Since inputn is a string, what's your meaning of this statement?
...
if inputn[i] == 0:
...
Because inputn[i] is a char, not an integer, so
inputn[i] == 0
will always be false. Even this line doesn't make sense, your original codes still could work correctly. But it's still better to change it to only one line:
number = (number * 10) + num


text:
Q: Build complex layout in a dynamic list/grid I'm building a simple app with python3 and GTK3.0 looking for the correct element for display a layout like the following image

I need display N items this items are load from a database (can be 1000+) and can change (insert, delete, update, etc.) and each item have a complex layout inside (labels, buttons, etc.)
How I can build a layout with a list/grid that dynamically changes.
I've read about GtkTreeView and GtkCellRenderer but i dont know how and other people recommend use GtkBox but how handle a model and update dynamically like ListView/CursorAdapter in android or ListView/Bindings in C#/WPF.
documentation of GTK 3.0 is really poor and does not explain how to extend a widget. another point that the documentation does not explain or at least I have not seen is how to reuse the same element, how to make good use of the resources (memory) when dealing with lots of elements, for example I created a series of widget in glade and I can not use N times. also not possible to create items that are not windows. everything should be within a window. as I can create a different arbitrary element of a window that can be reused.
please when you point me any of the above points, this has an example code can be C #, Python or C + + but it is important to have an example

A: I've just create a project called 'sqlite-browser' using python3 and gtk.  When you display a large number of records in a database, you can use treeview, and add a pager (limit 100/200 records each page). Maybe this project can help you. And here it is: https://github.com/LiuLang/sqlite-browser
This is screenshot:


text:
Q: Posting links to facebook page without user authentication Basically I have a web app that will be posting links to a facebook page(not profile) wall.
As far as I know I need a permanent token to do this. Twitter gives me one straight off the account, so I was hoping facebook would have something similar. However the token I get with the manage_pages permission has an expiry.
From the authentication docs this is what I've been doing:
request token to manage pages:
https://www.facebook.com/dialog/oauth?client_id=123456789123&redirect_uri=http://myapp.com/fb&scope=manage_pages&response_type=token

get token back the url which I intend paste it into my apps config:
http://myapp.com/fb#access_token=123123123123123%7C2.18VYbalblablablaswhg__.3600.1304294400.1-615173155%7CTzb_U9ma0LIPJXNzqsZ_xUJpfn8&expires_in=4205
When I actually try to post to the page with this, I get an expired error.
$post_params = array(
'access_token' => self::$page_token,
'message' => $string
);
$response = $fb_app->api('/'.self::$page_id.'/feed','POST', $post_params);

A: You need the offline_access permission to get a permanent token.
If you intend to post as the page itself, you need to get the token from /USER_ID/accounts for that page, else you will post from your profile. If you don't intend to post as the page, you actually don't need the manage_pages permission, publish_stream for the user is enough. Good luck.


text:
Q: Time method execution in another thread and abort on timeout Hi im trying to run a method async in order to time the duration and cancel the method if a timeout is exceeded.
Ive tried to implement this using async and await. But with no luck. Perhaps im overengineering this, any inputs will be appreciated
It should be noted that i cannot change the interface "TheirInterface" (Hence the name)
Code so far:
using System;
using System.Diagnostics;

public interface TheirInterface
{
    void DoHeavyWork();
}

public class Result
{
    public TimeSpan Elapsed { get; set; }
    public Exception Exception { get; set; }

    public Result(TimeSpan elapsed, Exception exception)
    {
        Elapsed = elapsed;
        Exception = exception;
    }
}

public class TaskTest
{
    public void Start(TheirInterface impl)
    {
        int timeout = 10000;

        // TODO
        // Run HeavyWorkTimer(impl)
        //
        // Wait for timeout, will be > 0
        //
        // if timeout occurs abortheavy
    }

    public Result HeavyWorkTimer(TheirInterface impl)
    {
        var watch = new Stopwatch();

        try
        {
            watch.Start();
            impl.DoHeavyWork();
            watch.Stop();
        }
        catch (Exception ex)
        {
            watch.Stop();

            return new Result(watch.Elapsed, ex);
        }

        return new Result(watch.Elapsed, null);
    }
}

A: You want to create a timer that, when it expires, cancels the thread. Absent cooperative cancellation, you'll have to call Thread.Abort, which is less than ideal. I'll assume that you know of the dangers involved in aborting threads.
public Result HeavyWorkTimer(TheirInterface impl)
{
    var watch = new Stopwatch();
    Exception savedException = null;

    var workerThread = new Thread(() =>
    {
        try
        {
            watch.Start();
            impl.DoHeavyWork();
            watch.Stop();
        }
        catch (Exception ex)
        {
            watch.Stop();
            savedException = ex;
        }
    });

    // Create a timer to kill the worker thread after 5 seconds.
    var timeoutTimer = new System.Threading.Timer((s) =>
        {
            workerThread.Abort();
        }, null, TimeSpan.FromSeconds(5), TimeSpan.Infinite);

    workerThread.Start();

    workerThread.Join();

    return new Result(watch.Elapsed, savedException);
}

Note that if you abort the thread, the thread will get ThreadAbortException.
If you can convince the interface owner to add cooperative cancellation, then you can change the timer callback so that it requests cancellation on the token rather than calling Thread.Abort.


text:
Q: How to add frequency percentages to a ordered barplot in ggplot2 I need to build a horizontal barplot which is ordered and has the frequency counts (which i could get) as well as frequency percentages on top (side) of it.  The code I have so far looks something like this.  I have not been able to order the chart or add the percentages (in addition to the counts).  Any help is much appreciated.  I am sorry I am new here and do not have enough reputation to post an example picture.
event <- c("a","a","a","a","a","a","b","b","b","b","c","c","c","c","c")
dat <- data.frame(event)

ggplot(dat, aes(x=event)) + geom_bar(fill = "orange", width = 0.5) + coord_flip() +
  geom_text(stat='bin',aes(label=..count..,vjust=.75, hjust = 0))

Thanks for the help

A: Changing the order could be done by changing the factor beforehand:
dat$event <- factor(dat$event, levels = names(sort(table(dat$event)))).

And adding percentages works just like you did with absolute values:
geom_text(stat='bin',
      aes(label=paste0(..count..,
                       ", ",
                       round(..count../sum(..count..)*100, 1),
                       "%")))


text:
Q: Parsing json file: D:\Important\User\AppName\app\google-services.json Android Studio I am having the error
Task :app:processDebugGoogleServices
Parsing json file: D:\Important\Dheeraj\Pukaar\app\google-services.json

When I run the application. I am Android Studio using 3.5 Canary 12 ( I am having some problem in stable release) . I tried to rebuild, invalidate and restart, restart my computer, replacing my google-services.json file but nothing works.
Full Build

> Configure project :app
registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)
registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)

> Task :app:preBuild UP-TO-DATE
> Task :app:preDebugBuild UP-TO-DATE
> Task :app:compileDebugAidl NO-SOURCE
> Task :app:checkDebugManifest UP-TO-DATE
> Task :app:generateDebugBuildConfig UP-TO-DATE
> Task :app:compileDebugRenderscript NO-SOURCE
> Task :app:javaPreCompileDebug UP-TO-DATE
> Task :app:mainApkListPersistenceDebug UP-TO-DATE
> Task :app:mergeDebugShaders UP-TO-DATE
> Task :app:compileDebugShaders UP-TO-DATE
> Task :app:generateDebugAssets UP-TO-DATE
> Task :app:mergeDebugAssets UP-TO-DATE
> Task :app:writeDebugApplicationId UP-TO-DATE

> Task :app:processDebugGoogleServices
Parsing json file: D:\Important\Dheeraj\Pukaar\app\google-services.json

> Task :app:createDebugCompatibleScreenManifests UP-TO-DATE
> Task :app:generateDebugResValues UP-TO-DATE
> Task :app:generateDebugResources UP-TO-DATE
> Task :app:processDebugManifest
> Task :app:fabricGenerateResourcesDebug
> Task :app:processDebugJavaRes NO-SOURCE
> Task :app:mergeDebugResources FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:mergeDebugResources'.
> Multiple task action failures occurred:
   > A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
      > AAPT2 aapt2-3.5.0-alpha12-5342889-windows Daemon #0: Daemon startup failed
        This should not happen under normal circumstances, please file an issue if it does.
   > A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
      > AAPT2 aapt2-3.5.0-alpha12-5342889-windows Daemon #1: Daemon startup failed
        This should not happen under normal circumstances, please file an issue if it does.
   > A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
      > AAPT2 aapt2-3.5.0-alpha12-5342889-windows Daemon #2: Daemon startup failed
        This should not happen under normal circumstances, please file an issue if it does.
   > A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
      > AAPT2 aapt2-3.5.0-alpha12-5342889-windows Daemon #3: Daemon startup failed
        This should not happen under normal circumstances, please file an issue if it does.
   > A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
      > AAPT2 aapt2-3.5.0-alpha12-5342889-windows Daemon #4: Daemon startup failed
        This should not happen under normal circumstances, please file an issue if it does.
   > A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
      > AAPT2 aapt2-3.5.0-alpha12-5342889-windows Daemon #6: Daemon startup failed
        This should not happen under normal circumstances, please file an issue if it does.
   > A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
      > AAPT2 aapt2-3.5.0-alpha12-5342889-windows Daemon #5: Daemon startup failed
        This should not happen under normal circumstances, please file an issue if it does.
   > A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
      > AAPT2 aapt2-3.5.0-alpha12-5342889-windows Daemon #7: Daemon startup failed
        This should not happen under normal circumstances, please file an issue if it does.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 5s
14 actionable tasks: 4 executed, 10 up-to-date


text:
Q: Prevent ImageView from pushing views offscreen I have a linear layout which contains an imageview and another linear layout which is a bottom bar on the screen. I use the bottom bar elsewhere in my project and I dont think it is the problem.
The problem is that the imageview takes up the entire screen. The image itself doesn't, but the view does. I can't seem to figure this out. As you can see in my xml, I am not using fill_parent for the image view and I have tried every possible scaleType for the image.
Any suggestions? Also if it helps I am building to Android API 8
Edit: I have changed the xml below so that you can use exactly what I have written. (This is the image that I use in the image view: http://i.imgur.com/qN5aT.jpg)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#FFFFFF" >

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:scaleType="fitStart"
        android:src="@drawable/quote_sample_img" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="bottom"
        android:orientation="vertical" >

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="This is text" />
    </LinearLayout>

</LinearLayout>

http://i.imgur.com/m3msH.png
(Sorry not enough reputation to post the actual picture)

A: It's the wrap_content in the image - the source file is probably too tall.
Use this in your ImageView to cause the image area to reset to the image's new size after scaling:
android:adjustViewBounds="true"

I'd also change the height of the ImageView so it fills the screen and forces your bar to always be on the bottom:
android:layout_height="0dip" // faster than match_parent for weight
android:layout_weight="1.0"

A: Things seems to work if android:layout_weight="1.0" is added to the ImageView.
(I am unsure about what exactly is happening and in what order in the layout algorithm so can not explain why.)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="#FFFFFF" >

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1.0"
        android:scaleType="fitStart"
        android:src="@drawable/quote_sample_img" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="bottom"
        android:orientation="vertical" >

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="This is text" />
    </LinearLayout>

</LinearLayout>

A: I think the issue might be that the image you used is larger than the screen, so that ImageView has its height set to the height of the available space to best fit the image, leaving no room for anything else.
Additionally, if you want to always have the bottom bar visible, it's better to use a RelativeLayout instead like so:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    style="@style/Main"
    android:orientation="vertical" >
    <LinearLayout
        android:id="@+id/bottom_bar"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="bottom"
        android:layout_alignParentBottom="true"
        android:orientation="vertical" >
        <include layout="@layout/browse_bottom_bar" />
    </LinearLayout>

    <ImageView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_above="@id/bottom_bar"
        android:src="@drawable/quote_sample_img" />
</RelativeLayout>

A: I have a very similar issue, posted at https://stackoverflow.com/questions/9765401/imageview-with-adjustviewbounds-seems-to-ignore-following-elements
It seems that the ImageView does NOT shrink after scaling the image UNLESS you specify adjustviewbounds="true".
But, as you can see from my own post that's not the full answer: the imageview may still push items below off the display, or intrude into their space if the image is too large, which I'm working on trying to fix.


text:
Q: getting variable from drop down list I am banging my head against a wall here. Below, you will find the code I am working with, and I am trying to set a variable by using a drop down list. I have tried everything I can think of, and I know this is simple. However, I am missing something. A nudge in the right direction would be appreciated. I keep getting an alert of "null" on the first two variables, but the third one comes through alright.
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Homework 4 - Taxi Fare Calculator</title>

Taxi Fare Calculator by Christopher Lewis

    This calculator will look at a starting zone, ending zone, and total time of a drive.
    In the end, it calculates the fare.

Please Choose Starting Zone:

    <select name="start">
      <option value ="1">Zone 1</option>
      <option value ="2">Zone 2</option>
      <option value ="3">Zone 3</option>
    </select>

Please Choose Destination Zone:

    <select name="ending">
      <option value = "1">Zone 1</option>
      <option value = "2">Zone 2</option>
      <option value = "3">Zone 3</option>
    </select>

Please enter total time of ride:

    <input type="text" id="totalTime" size="5">

      <input type="button" id="button" value="Fare total" onclick="calculate()"

function calculate(){
  var startZone = document.getElementById("start");
  var endingZone = document.getElementById("ending");
  var time = parseFloat(document.getElementById("totalTime").value);
  alert(startZone);
  alert(endingZone);
  alert(time);
}

A: The reason why 'startZone' and 'endingZone' are returning 'null' is because you are querying a DOM element with IDs start and ending. There are no elements on the page with such IDs so document.getElementById returns null.
I edited your code. I added ID attribute to the <select> elements
<select name="start" id="start">
 <option value ="1">Zone 1</option>
 <option value ="2">Zone 2</option>
 <option value ="3">Zone 3</option>
</select>

<select name="ending" id="ending">
 <option value = "1">Zone 1</option>
 <option value = "2">Zone 2</option>
 <option value = "3">Zone 3</option>
</select>

A: Your selects have name instead of id set, so you won't find them with getElementById.

A: You can still get a return value from a "select" element, I made a simple JavaScript example to do this:
But you are trying to select the element by the id, which you are mistaking for the name attribute, in my example I left in the name attributes but added id attributes to select the element by Id via JavaScript
HTML
<select name="start" id="zone">
    <option value ="1">Zone 1</option>
    <option value ="2">Zone 2</option>
    <option value ="3">Zone 3</option>
</select>

The selected value is: none

JavaScript
document.getElementById("zone").onchange=function(){
  document.getElementById("return").innerHTML=document.getElementById("zone").value;
}

Here is a JSFiddle example

A: First of all, you didn't set an id for the select elements. Secondly, you also need to get the selected value of a select box with javascript like this:
document.getElementById('select-id').options[document.getElementById('select-id').selectedIndex].text;
Here is the correct code:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Homework 4 - Taxi Fare Calculator</title>

Taxi Fare Calculator by Christopher Lewis

This calculator will look at a starting zone, ending zone, and total time of a drive.
In the end, it calculates the fare.

Please Choose Starting Zone:

<select id="start" name="start">
    <option value ="1">Zone 1</option>
    <option value ="2">Zone 2</option>
    <option value ="3">Zone 3</option>
</select>

Please Choose Destination Zone:

<select id="ending"  name="ending">
    <option value = "1">Zone 1</option>
    <option value = "2">Zone 2</option>
    <option value = "3">Zone 3</option>
</select>

Please enter total time of ride:

    <input type="text" id="totalTime" size="5">

<input type="button" id="button" value="Fare total" onclick="calculate()" />

Javascript
function calculate(){
    var startZone = document.getElementById('start').options[document.getElementById('start').selectedIndex].text;
    var endingZone = document.getElementById('ending').options[document.getElementById('ending').selectedIndex].text;
    var time = parseFloat(document.getElementById("totalTime").value);
    alert(startZone);
    alert(endingZone);
    alert(time);
}

demo: http://jsfiddle.net/zUa7S/1/

A: if you want to query element by name then this might work:
var startZone = document.getElementsByName("start")[0].value;
var endingZone = document.getElementsByName("ending")[0].value;

since getElementsByName returns collection whereas getElementById returns an object.


text:
Q: Sending Request to JSP file based upon AJAX POST I am trying to send a post request to Java servlet, execute a query based upon this value, and send the information to a jsp file. The query in entered from a text box, and when the user hits enter, I need to jump to a new page to display the value of the query.
This is my post request to the servlet:
$.ajax({
    "type": "POST",
    // generate the request url from the query.
    // escape the query string to avoid errors caused by special characters
    "url": "Search",
    "data": {query : query},

    "success": function(data) {
        console.log("normal search successful");

    },
    "error": function(errorData) {
        console.log("lookup ajax error")
        console.log(errorData)
    }
})

I get the AJAX post with:
String title = request.getParameter("query");

//peform action to get results...
then forward request to JSP page with:
request.getRequestDispatcher("movielist.jsp").forward(request, response);

I am getting no errors but the screen doesn't redirect to the new page in my app...
Am I missing something major here?

A: Nothing happens because you do AJAX call - the request happens in the background of the page, and therefore when ajax receives response from JSP - it stays "in the background" - the success handler is triggered.
What you could do - is to do regular form submit - then navigate from JSP as you mentioned.
Otherwise - if you prefer to keep AJAX, you can do a redirect manually in the success handler with:
 "success": function(data) {
       window.location = "<your URL here>";
  ...

The URL to redirect to you can pass from JSP that can return json object with it. Hope this helps.

A: AJAX works correctly, if you look @ console it should be print a line. Do your redirect part in your success block.