Q:

How to create hollow shapes in JFreeChart Scatter Plot

JFreeChart version used: 1.5.0
I tried the following to obtain hollow shapes in a scatter plot:
PlotFrame.java file content:
package javaapplication1;

import javax.swing.JFrame;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;

/**
 *
 * @author tarik
 */
public class PlotFrame extends javax.swing.JFrame {
    public static void main(String[] argv) {
        PlotFrame plotFrame = new PlotFrame();
        plotFrame.setVisible(true);
    }

    /**
     * Creates new form PlotFrame
     */
    public PlotFrame() {
        this.setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JFreeChart chart = createChart();
        ChartPanel panel = new ChartPanel(chart);

        this.add(panel);
        pack();
    }

    private JFreeChart createChart() {
        // Create dataset
        XYDataset dataset = createDataset();

        // Create chart
        JFreeChart chart = ChartFactory.createScatterPlot(
                "Boys VS Girls weight comparison chart",
                "X-Axis", "Y-Axis", dataset);

        XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer();
        //renderer.setBaseShapesFilled(false);
        renderer.setUseFillPaint(false);

        return chart;
    }

    private XYDataset createDataset() {
        XYSeriesCollection dataset = new XYSeriesCollection();

        //Boys (Age,weight) series
        XYSeries series1 = new XYSeries("Boys");
        series1.add(1, 72.9);
        series1.add(2, 81.6);
        series1.add(3, 88.9);
        series1.add(4, 96);
        series1.add(5, 102.1);
        series1.add(6, 108.5);
        series1.add(7, 113.9);
        series1.add(8, 119.3);
        series1.add(9, 123.8);
        series1.add(10, 124.4);

        dataset.addSeries(series1);

        //Girls (Age,weight) series
        XYSeries series2 = new XYSeries("Girls");
        series2.add(1, 72.5);
        series2.add(2, 80.1);
        series2.add(3, 87.2);
        series2.add(4, 94.5);
        series2.add(5, 101.4);
        series2.add(6, 107.4);
        series2.add(7, 112.8);
        series2.add(8, 118.2);
        series2.add(9, 122.9);
        series2.add(10, 123.4);

        dataset.addSeries(series2);

        return dataset;
    }
}

It did not work, the shapes are still filled.

A:

Recall that Graphics2D can draw() the outline of a Shape as well as fill() its interior. By limiting rendering to draw(), @micro's approach is sound in this regard, but it assumes version 1.0.19. When migrating to version 1.5 and later, note that "many methods getBaseXXX()/setBaseXXX() have been renamed setDefaultXXX()/getDefaultXXX()." The correct formulation is illustrated below:
renderer.setDefaultShapesFilled(false);
renderer.setUseFillPaint(false);

Other changes:

Construct and manipulate Swing GUI objects only on the event dispatch thread.
Override getPreferredSize() to set the chart's initial preferred size.

As tested:
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JFrame;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;

/**
 * @see https://stackoverflow.com/q/58812592/230513
 * @author trashgod
 * @author tarik
 */
public class PlotFrame extends javax.swing.JFrame {
    public static void main(String[] argv) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                PlotFrame plotFrame = new PlotFrame();
                plotFrame.setLocationRelativeTo(null);
                plotFrame.setVisible(true);
            }
        });
    }

    /**
     * Creates new form PlotFrame
     */
    public PlotFrame() {
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JFreeChart chart = createChart();
        ChartPanel panel = new ChartPanel(chart){
            @Override
            public Dimension getPreferredSize() {
                return new Dimension(640, 480);
            }
        };
        this.add(panel);
        this.pack();
    }

    private JFreeChart createChart() {
        // Create dataset
        XYDataset dataset = createDataset();

        // Create chart
        JFreeChart chart = ChartFactory.createScatterPlot(
                "Boys VS Girls weight comparison chart",
                "X-Axis", "Y-Axis", dataset);

        XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer();
        renderer.setDefaultShapesFilled(false);
        renderer.setUseFillPaint(false);

        return chart;
    }

    private XYDataset createDataset() {
        XYSeriesCollection dataset = new XYSeriesCollection();

        //Boys (Age,weight) series
        XYSeries series1 = new XYSeries("Boys");
        series1.add(1, 72.9);
        series1.add(2, 81.6);
        series1.add(3, 88.9);
        series1.add(4, 96);
        series1.add(5, 102.1);
        series1.add(6, 108.5);
        series1.add(7, 113.9);
        series1.add(8, 119.3);
        series1.add(9, 123.8);
        series1.add(10, 124.4);

        dataset.addSeries(series1);

        //Girls (Age,weight) series
        XYSeries series2 = new XYSeries("Girls");
        series2.add(1, 72.5);
        series2.add(2, 80.1);
        series2.add(3, 87.2);
        series2.add(4, 94.5);
        series2.add(5, 101.4);
        series2.add(6, 107.4);
        series2.add(7, 112.8);
        series2.add(8, 118.2);
        series2.add(9, 122.9);
        series2.add(10, 123.4);

        dataset.addSeries(series2);

        return dataset;
    }
}

A:

From source code:
 if (getItemShapeFilled(series, item)) {
                if (this.useFillPaint) {
                    g2.setPaint(getItemFillPaint(series, item));
                }
                else {
                    g2.setPaint(getItemPaint(series, item));
                }
                g2.fill(shape);
   }

For the first if there is no else, so we need the getItemShapeFilled to return false. It looks like this:
      public boolean getItemShapeFilled(int series, int item) {
            Boolean flag = getSeriesShapesFilled(series);
            if (flag != null) {
                return flag;
            }
            return this.baseShapesFilled;
      }

Easiest way is to use this method:
       public void setBaseShapesFilled(boolean flag) {
              this.baseShapesFilled = flag;
              fireChangeEvent();
        }

So the actual code is:
import javax.swing.JFrame;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;

/**
 *
 * @author tarik
 */
public class PlotFrame extends javax.swing.JFrame {
    public static void main(String[] argv) {
        PlotFrame plotFrame = new PlotFrame();
        plotFrame.setVisible(true);
    }

    /**
     * Creates new form PlotFrame
     */
    public PlotFrame() {
        this.setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JFreeChart chart = createChart();
        ChartPanel panel = new ChartPanel(chart);

        this.add(panel);
        pack();
    }

    private JFreeChart createChart() {
        // Create dataset
        XYDataset dataset = createDataset();

        // Create chart
        JFreeChart chart = ChartFactory.createScatterPlot(
                "Boys VS Girls weight comparison chart",
                "X-Axis", "Y-Axis", dataset);

        XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer();
        renderer.setBaseShapesFilled(false);
        renderer.setUseFillPaint(false);

        return chart;
    }

    private XYDataset createDataset() {
        XYSeriesCollection dataset = new XYSeriesCollection();

        //Boys (Age,weight) series
        XYSeries series1 = new XYSeries("Boys");
        series1.add(1, 72.9);
        series1.add(2, 81.6);
        series1.add(3, 88.9);
        series1.add(4, 96);
        series1.add(5, 102.1);
        series1.add(6, 108.5);
        series1.add(7, 113.9);
        series1.add(8, 119.3);
        series1.add(9, 123.8);
        series1.add(10, 124.4);

        dataset.addSeries(series1);

        //Girls (Age,weight) series
        XYSeries series2 = new XYSeries("Girls");
        series2.add(1, 72.5);
        series2.add(2, 80.1);
        series2.add(3, 87.2);
        series2.add(4, 94.5);
        series2.add(5, 101.4);
        series2.add(6, 107.4);
        series2.add(7, 112.8);
        series2.add(8, 118.2);
        series2.add(9, 122.9);
        series2.add(10, 123.4);

        dataset.addSeries(series2);

        return dataset;
    }
}

My result is:

Isn't that what you meant?


Q:

CouchBase - JavaContext not found in Android Studio

I am following the instruction to set up CouchBase in Android Studio.
The problem is that JavaContext does not seem to exist. Any idea why ?
private void test(){
    // Enable logging
    Logger log = Logger.getLogger("app");
    log.setLevel(Level.ALL);
    JavaContext context = new JavaContext(); // THIS LINE DOES NOT COMPILE
    // Create a manager
            Manager manager = null;
            try {
                manager = new Manager(context, Manager.DEFAULT_OPTIONS);
            } catch (IOException e) {
                e.printStackTrace();
            }
    // Create or open the database named app
            Database database = null;
            try {
                database = manager.getDatabase("app");
            } catch (CouchbaseLiteException e) {
                e.printStackTrace();
            }
    // The properties that will be saved on the document
            Map<String, Object> properties = new HashMap<String, Object>();
            properties.put("title", "Couchbase Mobile");
            properties.put("sdk", "Java");
    // Create a new document
            Document document = database.createDocument();
    // Save the document to the database
            try {
                document.putProperties(properties);
            } catch (CouchbaseLiteException e) {
                e.printStackTrace();
            }
    // Log the document ID (generated by the database)
    // and properties
    log.info(String.format("Document ID :: %s", document.getId()));
    log.info(String.format("Learning %s with %s", (String) document.getProperty("title"), (String) document.getProperty("sdk")));
}

Here is my gradle:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.woxthebox.draglistview.sample"
        minSdkVersion 11
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    // workaround for "duplicate files during packaging of APK" issue
// see https://groups.google.com/d/msg/adt-dev/bl5Rc4Szpzg/wC8cylTWuIEJ
    packagingOptions {
        exclude 'META-INF/ASL2.0'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/NOTICE'
    }
}

repositories {
    jcenter()
    maven {
        url "http://files.couchbase.com/maven2/"
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile project(':library')
    compile 'com.android.support:appcompat-v7:23.3.0'
    compile 'com.android.support:cardview-v7:23.3.0'
    compile fileTree(dir: 'libs', include: ['*.jar'])
    //compile 'com.android.support:appcompat-v7:22.1.1'
    compile 'com.couchbase.lite:couchbase-lite-android:1.3.0'
}

EDIT:
After some playing around I found that this code works:
    private void test(){
        // Enable logging
        Logger log = Logger.getLogger("app");
        log.setLevel(Level.ALL);
       // JavaContext context = new JavaContext();

        // Create a manager
                Manager manager = null;
                try {
                    manager = new Manager(new AndroidContext(getApplicationContext()), Manager.DEFAULT_OPTIONS);
                } catch (IOException e) {
                    e.printStackTrace();
                }
        // Create or open the database named app
                Database database = null;
                try {
                    database = manager.getDatabase("app");
                } catch (CouchbaseLiteException e) {
                    e.printStackTrace();
                }
        // The properties that will be saved on the document
                Map<String, Object> properties = new HashMap<String, Object>();
                properties.put("title", "Couchbase Mobile");
                properties.put("sdk", "Java");
        // Create a new document
                Document document = database.createDocument();
        // Save the document to the database
                try {
                    document.putProperties(properties);
                } catch (CouchbaseLiteException e) {
                    e.printStackTrace();
                }
        // Log the document ID (generated by the database)
        // and properties
        log.info(String.format("Document ID :: %s", document.getId()));
        log.info(String.format("Learning %s with %s", (String) document.getProperty("title"), (String) document.getProperty("sdk")));
    }

Can someone explain what was wrong with the original instructions ?

A:

Can someone explain what was wrong with the original instructions ?

Probably whoever wrote the documentation didn't know there was a AndroidContext for the Android Couchbase Lite.
Whereas, for a standard Java (embedded?) project, there actually is a JavaContext.
The Getting Started code on Github does actually use an AndroidContext too, so that page is just wrong.
See here for the (seemingly correct) Couchbase Android - Getting Started Guide


Q:

My teacher said a BJT phototransistor doesn't have a base

But I find it to be absolutely incorrect. How can a BJT transistor even work without a base? Shouldn't a transistor without base be just a semiconductor (PP, NN)? Does there exist some special NASA-army-grade experimental BJT transistor without a base?
So who is right, me or the teacher?

A:

I think you and your teacher are both right - you are just not using the same definitions and thus your wording disagrees.
From your description:

Shouldn't be transistor without base be just a semiconductor (PP,NN)?

You define the "base" to be the semiconductor in the middle of a normal BJT - the P-doped region in a NPN or the N-doped region of an PNP. In this regard you are right: A phototransistor still has this PNP or NPN structure.
Your teacher might define the base differently - the terminal you put current through to achieve a collector-emitter current. When you look at it this way, he is also right - most phototransistors (I know of none myself that break this rule, apart from some optocouplers) have no "base" lead. The only way to trigger a current flow is through photons hitting the base region, and causing the release of electrons by doing so, turning the device on.
Both make sense, although I would argue that you need to watch out when thinking that "no base" means "pp or nn" semiconductor. Many complex semiconductor structures exist that have many regions, yet have few leads. Look at Triacs or IGBTs!

A:

The base connection is often not used and would thus serve mostly to pick up noise.
You can find optocouplers (4-pin) which have no base connection and others (eg. 4N35) which bring the base connection out (where it is sometimes used).

Similarly, individual phototransistors are often packaged in an LED-like packages with lens and 2-pin leadframe.

A:

Clearly the source of confusion here is what base means: you assume it's "base region", and your teacher seems to assume "base terminal".
What defines a BJT transistor is the NPN or PNP structure. How many of these regions are exposed through terminals is irrelevant: most transistors will have three, but phototransistors may have only two, and parasitic transistor structures may not be exposed at all, but they still behave similarly and are considered to belong to the same device class.
Phototransistors are a bit special in that they have no base current in the strict sense, as carriers are generated in the base itself. But since the structure still behaves quite similarly to a regular BJT, this fact is usually ignored and photodiode current generated by light is considered to be base current.


Q:

Custom target URL for Views content pane exposed filter (block)

Here is the situation:
There are 2 pages in Page manager

Overridden page of the Taxonomy term (i.e. Path: /%term )
Page with Taxonomy term filters (i.e. Path: /%term/filter )

And a View with 2 displays (content panes) :

Show all from term
Show filtered (with exposed filters in block).

How to place the exposed filter block on /%term page but when the filter is submitted,  redirect and apply it to the /%term/filter path ?
Thank you

A:

Use form redirection in hook_form_alter.


Q:

How to send Verification Email after signup

I am using Firebase for user signup but I could not find any method to send verification email after signup.
auth = FirebaseAuth.getInstance();

auth.createUserWithEmailAndPassword(email, password)
    .addOnCompleteListener(SignupActivity.this, new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
            Toast.makeText(SignupActivity.this, "createUserWithEmail:onComplete:" + task.isSuccessful(), Toast.LENGTH_SHORT).show();
            progressBar.setVisibility(View.GONE);
            // If sign in fails, display a message to the user. If sign in succeeds
            // the auth state listener will be notified and logic to handle the
            // signed in user can be handled in the listener.
            if (!task.isSuccessful()) {
                Toast.makeText(SignupActivity.this, "Authentication failed." + task.getException(),
                        Toast.LENGTH_SHORT).show();
            } else {
                FirebaseUser user = auth.getCurrentUser()

                startActivity(new Intent(SignupActivity.this, MainActivity.class));
                finish();
            }
        }
    });

A:

You can send an address verification email to a user with the sendEmailVerification method. For example:
FirebaseAuth auth = FirebaseAuth.getInstance();
FirebaseUser user = auth.getCurrentUser();

user.sendEmailVerification()
    .addOnCompleteListener(new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull Task<Void> task) {
            if (task.isSuccessful()) {
                Log.d(TAG, "Email sent.");
            }
        }
    });

more info here: https://firebase.google.com/docs/auth/android/manage-users


Q:

Confusion regarding name hiding and virtual functions

Refering another so question
Consider the code :
class Base {
public:
    virtual void gogo(int a){
        printf(" Base :: gogo (int) \n");
    };

    virtual void gogo(int* a){
        printf(" Base :: gogo (int*) \n");
    };
};

class Derived : public Base{
public:
    virtual void gogo(int* a){
        printf(" Derived :: gogo (int*) \n");
    };
};

int main(){

    // 1)
    Derived * obj = new Derived ;
    obj->gogo(7);  // this is illegal because of name hiding

    // 2)
    Base* obj = new Derived ;
    obj->gogo(7); // this is legal
}

For case 2)
The call obj->gogo(7) is resolved at run time.
Since obj->gogo(7) is legal. It seems to imply that vtable of Derived contains
     ptr to
   virtual void gogo(int a) which should have been hidden.
My confusion is , since name hiding causes case 1) to be illegal, then how the call in 2) is resolved at run time
a) Does vtable of Derived contains pointer to gogo(int).
b) If a) is not True, Does call resolution for virtual functions proceeds to vtable of base class.

A:

You are confusing virtual functions calls and overload resolution.
All derived classes have vtables containing all virtual functions, from the base class and any additional own virtual functions. This is used to resolve calls at runtime, like in your case 2).
In case 1) you get an error from overload resolution at compile time. Due to name hiding, class Derived only has one callable function. Your only choice is to call that function, with an int*.


Q:

need something that is same as $_FILES from remote server download with php

Ok I have php code that handles the upload of images.
now I have remote post that handles this code:
$postheader = http_build_query($postarray);
$url = parse_url($uri);
$host = $url['host'];
$path = $url['path'];

$results = '';
if ($fp = fsockopen($host, 80, $errno, $errstr, 2))
{
    stream_set_timeout($fp, 30);

    $headers = "POST ". $path ." HTTP/1.0\r\n";
    $headers .= "User-Agent: \r\n";
    $headers .= "Host: ". $host ."\r\n";
    $headers .= "Accept: */*\r\n";
    $headers .= "Content-Type: application/x-www-form-urlencoded\r\n";
    $headers .= "Content-Length: " . strlen($postheader) . "\r\n";
    $headers .= "Connection: close\r\n\r\n";
    @fputs($fp, $headers . $postheader);
    while($currentHeader = fgets($fp, 4096))
    {
        if (preg_match("/^\r?\n$/", $currentHeader)) { break; }
    }

    while(!@feof($fp))
    {
        $results .= @fgets($fp, 1024);
    }
    @fclose($fp);

The thing is I get the url of the image from that post and it is stored like this:
$file = 'http://someurl.ll/image.jpg'

And script that handles image with: $_FILES['image']
Now if I can say $_FILES['image'] = $file it should go ferder, but it doesn't!
I thing that $_FILES['image'] needs not only url of data but also raw uploaded data
So I want to know what is equal to $_FILES['image'], that can can be make of $file = 'http://someurl.ll/image.jpg'?
UPDATE:
Hier is what I got as $_FILES['image'] as var_dump
array(5) { ["name"]=> string(17) "logo.png" ["type"]=> string(9) "image/png" ["tmp_name"]=> string(14) "/tmp/phpWUqC5c" ["error"]=> int(0) ["size"]=> int(5674) }

an I want to make the same but from $file = 'http://someurl.ll/image.jpg'
so the same array and then to say:
$_FILES['image'] = that array from http://someurl.ll/image.jpg

Because it is remote I would like to handle it as $_FILES['image'], but I cant
so the quick solution is to make that remote image same as $_FILES['image']

A:

Add this function to your source

/**
 * Add to $_FILES from external url
 * sample usage: addToFiles('google_favicon', 'http://google.com/favicon.ico');
 * @since 17.12.12 17:23
 * @author mekegi
 * @param string $key
 * @param string $url sample http://some.tld/path/to/file.ext
 */
function addToFiles($key, $url)
{
    $tempName = tempnam('/tmp', 'php_files');
    $originalName = basename(parse_url($url, PHP_URL_PATH));

    $imgRawData = file_get_contents($url);
    file_put_contents($tempName, $imgRawData);
    $_FILES[$key] = array(
        'name' => $originalName,
        'type' => mime_content_type($tempName),
        'tmp_name' => $tempName,
        'error' => 0,
        'size' => strlen($imgRawData),
    );
}

And use:

addToFiles('image', 'http://someurl.ll/image.jpg');


Q:

Different data structures result in huge different size in python

I'm trying using Facebook Graph API to get something by python, and there's no problem in my programs.
However, When outputting data to files, I found something strange. I change a structure in output, then my file would be several times bigger.
The original data look like this:
{
  "data": [
    {
      "id": "20531316728_10154835146021729",
      "created_time": "2016-07-21T16:00:00+0000"
    },
    {
      "id": "20531316728_10154833920726729",
      "created_time": "2016-07-21T03:02:11+0000"
    },
    {
      "id": "20531316728_10154729016861729",
      "created_time": "2016-06-14T00:04:45+0000"
    }
  ]
}

I used this before:
(I parsed the data above to a JSON format, and I call it jsonData)
for tuples in jsonData['data']:
    print(tuples, file=open('test.txt','a'))

It will output some strings in files and the output looks like:
{'keyA': 'something1', 'keyB': 'something2'}

{'keyA': 'something3', 'keyB': 'something4'}

{'keyA': 'something5', 'keyB': 'something6'}

Cause there's no structures, so I changed the tuples to jsonData['data'],
in order to make the return becoming an array:
for tuples in jsonData['data']:
    print(jsonData['data'], file=open('test.txt','a'))

The output would be:
 [
    {'keyA': 'something1', 'keyB': 'something2'},

   {'keyA': 'something3', 'keyB': 'something4'},

   {'keyA': 'something5', 'keyB': 'something6'} ]

But the file size is totally different! For instance, I got a 196KB file by using the tuples, and got a 18.9MB by using the jsonData['data']
I used python3, and I tested several times by only changing the statement.
Are the differences in files common and normal?

A:

The difference between these two for loops is that in the second one, you're printing out the entire structure each time the for loop body runs.
In the first loop, you are only printing out the current item (well appending it to the output file, but you know that bit already!).
Here's a tiny example that might illuminate it for you.
>>> x = [1, 2, 3, 4, 5]
>>> for i in x:
...     print(i)
...
1
2
3
4
5
>>> for i in x:
...     print(x)
...
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]


Q:

JPA NamedQuery get distinct column

I want to get an list of distinct City's from my User table. I thought the code below would work but gives an error:
User.java
@Entity
@Table(name="user_info")
...
@NamedQuery(name = "User.all.cities", query = "SELECT distinct u.city FROM User u"),
...
@embedded
private City city;

UserBusinessLogic.java:
...
TypedQuery<City> typedQuery = entityManager.createNamedQuery("User.all.cities",User.class);
List<City> names = typedQuery.getResultList();
...

It gives: type mismatch can not convert List to List. I tried two get first user then on getResult a City but same error one line below.
I see some examples but not really tell how to get it with correct code just the SQL syntax.
Thanks for your help
Jess

A:

The first thing which doesn't look good is that you ask for City objects but declare to get User's.
You have:
@NamedQuery(name = "User.all.cities",
            query = "SELECT distinct u.city FROM User u"),

TypedQuery<City> typedQuery =
                  entityManager.createNamedQuery("User.all.cities", User.class);

Where it should be:
TypedQuery<City> typedQuery =
                  entityManager.createNamedQuery("User.all.cities", City.class);


Q:

Ring of invariants of $\operatorname{SL}_6$ acting on $\Lambda^3 \mathbb C^6$

Let $G=\operatorname{SL}_6$ act on $V=\Lambda^3 \mathbb C^6$. I would like to find the ring of invariants $\mathbb C[V]^G$. There is an obvious invariant
$$Sq: V \to \mathbb C, \quad \omega \mapsto \omega^2 \in \Lambda^6 \mathbb C^6 \simeq \mathbb C,$$
with the last isomorphism $\operatorname{SL}_6$-invariant. Update: $Sq=0$, but there is a unique invariant $\alpha$ of degree $4$, not $2$ (see the comment of Robert Bryant below).
My idea how to prove $\mathbb C[V]^G = \mathbb C[\alpha]$ is to consider
$$W=\mathbb Cx_1 \wedge x_2 \wedge x_3 \oplus \mathbb Cx_4 \wedge x_5 \wedge x_6 \subset V.$$
If a general $G$-orbit intersects $W$, then a map $f: \mathbb C[V]^G \to \mathbb C[W]$ is injective. But the image lies in $\mathbb C[W]^{\mathbb C^* \rtimes \mathbb Z/2\mathbb Z}$, where the action of $\mathbb C^*$ on $W$ is given by
$$t(w_1 \cdot x_1 \wedge x_2 \wedge x_3 + w_2 \cdot x_4 \wedge x_5 \wedge x_6)=tw_1 \cdot x_1 \wedge x_2 \wedge x_3 + t^{-1}w_2 \cdot x_4 \wedge x_5 \wedge x_6,$$
and the action of $\mathbb Z/2\mathbb Z$ is given by
$$1(w_1 \cdot x_1 \wedge x_2 \wedge x_3 + w_2 \cdot x_4 \wedge x_5 \wedge x_6)=w_2 \cdot x_1 \wedge x_2 \wedge x_3 - w_1 \cdot x_4 \wedge x_5 \wedge x_6.$$
Now it is easy to check that $\mathbb C[W]^{\mathbb C^* \rtimes \mathbb Z/2\mathbb Z} \simeq \mathbb C[\beta]$, where $\beta=w_1^2 w_2^2$ is an invariant of degree $4$. Therefore the question is whether a general $G$-orbit intersects $W$ (and also how to construct $\alpha$ with $f(\alpha)=\beta$), and here I am stuck. Could you help me?

A:

The principal isotropy group is $H=SL(3)\times SL(3)$: it has the right dimension (namely 16) and occurs as an isotropy group (namely of a general element of $W$). Now it is a general result of Luna-Richardson that the restriction map $\mathbb C[V]^G\to\mathbb C[W]^N$ is an isomorphism where $W=V^H$ and $N=N_G(H)/H$.
For a concrete construction of $\alpha$ it might be easiest to consider $V$ as a symplectic vector space with symplectic form
$$\langle\omega_1,\omega_2\rangle:=\frac{\omega_1\wedge\omega_2}{x_1\wedge\ldots\wedge x_6}.$$
Then there is a moment map given by $$m:V\to\mathfrak g^*:\omega\mapsto[\xi\mapsto\langle\omega,\xi\omega\rangle].$$
Then $\alpha$ is the pullback of an invariant quadratic form on $\mathfrak g^*$. Concretely: Let $\xi_i$ be a basis of $\mathfrak g$ and let $\xi^i$ be its dual basis (i.e. with ${\rm tr}(\xi_i\xi^j)=\delta_{ij}$). Then
$$
\alpha(\omega)=\sum_i\langle\omega,\xi_i\omega\rangle\langle\omega,\xi^i\omega\rangle.$$

A:

Here's an alternate construction of the invariant $\alpha$ that seems a little simpler (and, besides, gets used in proving the normal forms for $3$-forms in $6$-variables). The details may be found in Nigel Hitchin The geometry of three-forms in six and seven dimensions, section 2.1.
Let $S$ be a vector space over $\mathbb{C}$ of dimension $6$, and fix an isomorphism $\Lambda^6(S^*)= \mathbb{C}$ (i.e., choose a volume form). Then there is an induced natural isomorphism
$$
S = S\otimes \Lambda^6(S^*) = \Lambda^5(S^*)  .\tag1
$$
Given $\phi\in\Lambda^3(S^*)$, define a mapping $J_\phi:S\to S$ by the rule
$$
J_\phi(s) = (\iota_s\phi)\wedge\phi
$$
where $\iota_s\phi\in\Lambda^2(S^*)$ is the interior product of $s\in S$ with $\phi$.  It is easy to see that the trace of $J_\phi\in \mathrm{End}(S,S) = S\otimes S^*$ vanishes identically.  However, if one sets
$$
\alpha(\phi) = \tfrac16\,\mathrm{tr}\bigl((J_\phi)^2\bigr),\tag2
$$
then one finds that $\alpha(\phi)$ does not vanish identically, and it is obviously a quartic polynomial in the coefficients of $\phi$.  In fact, one has the identity
$$
(J_\phi)^2 = \alpha(\phi)\,\mathrm{Id}_S\,,\tag3
$$
and this identity can be used to put $\phi$ in normal form with respect to the eigenspaces of $J_\phi$ when $\alpha(\phi)\not=0$.


Q:

Center steps in CSS and Bootstrap 4

I have this code:

    .progressbar li{
        float: left;
        width: 20%;
        position: relative;
        font-weight: 600;
        font-size: 15px;
        line-height: 22px;
    }

    .progressbar{
        counter-reset: step;
    }
    .progressbar li:before{
        content:counter(step);
        counter-increment: step;
        width: 24px;
        height: 24px;
        display: block;
        margin: 0 auto 10px auto;
        border-radius: 50%;
        background: #DCE1E6;
        color: #1F2226;
        font-weight: normal;
        font-size: 16px;
        line-height: 24px;
        text-align: center;
        float: left;
    }

    .progressbar > li:nth-child(2):before {
        background: #FFC700;
        color: #1F2226;
    }

Koszyk

Dostawa

Płatność

Podsumowanie

Preview: http://serwer1356363.home.pl/_nauka/
I need this effect: https://ibb.co/3zBV0vz

Center the steps / dots in the center of the screen
Add the distance between the dot / step and the text next to it

How can I make it?

A:

Don't use float but use flexbox instead.
UPDATE: grey border added on li elements except for the last one.

.progressbar li {
  width: 20%;
  font-weight: 600;
  font-size: 15px;
  line-height: 22px;
  display: flex;
  justify-content: center;
}

.progressbar {
  counter-reset: step;
  list-style: none;
  display: flex;
  justify-content: center;
}

.progressbar li:before {
  content: counter(step);
  counter-increment: step;
  width: 24px;
  height: 24px;
  display: block;
  margin-right: 10px;
  border-radius: 50%;
  background: #DCE1E6;
  color: #1F2226;
  font-weight: normal;
  font-size: 16px;
  line-height: 24px;
  text-align: center;
}

.progressbar li:not(:last-child) {
  border-right: 1px solid grey;
}

.progressbar>li:nth-child(2):before {
  background: #FFC700;
  color: #1F2226;
}

Koszyk

Dostawa

Płatność

Podsumowanie


Q:

Automatic MySQL backup on sharedhost

As I am not a coder so I should stop here but I am interested how far I could go to build an automatic SQL script.
Case:
A website is hosted on a shared host server which uses CPanel. The website use only one DB and one of the table is the log. Now the log table has reached 300k rows... (I might do something wrong here... it is a popular website?:))
So I need to reduce the log table but I would like to do a backup rather. So here is my idea:
Setup a backup DB and copy the old entries meanwhile use tables for only quarter years so the log from Jan-April would be stored in table_2012-q1 etc.
Method:
I would like to use cron and email alert.
Questions:

is there any better and easier solution to do the back up with this row num.
if I do a "move rows" by INSERT/DELETE rows how can I check which one is ready on time?
do I need to focus on the performance of this process as it should work in the background? In other words is it a select or a dump?

Sorry if it is too Dummy but I would like to learn! I also don't want to use too much processor for this.
Thanks Andras

A:

Since you are using shared hosting, I'm pretty sure you will not be able to access cron, so here is an alternative:
Since the database is filled with log data :
1. Create a new table, regardless of the name or time period
2. Move the files (from a certain id) from one table to the next

This link will explain better : mysqldump partial database
If this is active DB, I would clone it and then play around with the ways the data will be moved since you do not consider youreself a coder.
Hope this helps.


Q:

Using Extension Points: no configurable elements found

i created an extension point for one plugin(A). Another plugin(B) is setup as an extension to the ep from the first plugin.
When trying to use the extension point eclipse in A eclipse tells me that, it is not able to find configurable elements for the this extension point. The extension point itself is found.
I'm suspecting plugin B is not started at all. How can i check this?
Here is the code, where the extension point gets called:
IExtensionRegistry extensionRegistry = Platform.getExtensionRegistry();
        IExtensionPoint[] extensionPoints = extensionRegistry.getExtensionPoints("A.extensionpoints");
        //Prints both defined EP's
        for (IExtensionPoint iExtensionPoint : extensionPoints) {
            System.err.println(iExtensionPoint.getUniqueIdentifier());
            System.err.println(iExtensionPoint.getExtensions().length);
        }
        IExtensionPoint extensionPoint = extensionRegistry.getExtensionPoint("A.extensionpoints.HavingProblemsWith");
        System.err.println(extensionPoint.getLabel());//Prints the Label
        System.err.println(extensionPoint.getConfigurationElements().length);// => 0

A:

Fire up eclipse with the -console option. Then you have tools to view the status of the plugins and to start them, if you want so. It may give you some ideas on why the plugin hasn't been started.


Q:

Disable Enable unobtrusive validation for specific submit button

I have two submit buttons Back, Continue. What should I to do to disable client validation when I click on Back. I was trying to add cancel class to button attribute but It seams does not help.
UPD. Actually this is working cancel class. But It seams not working if you add it dynamically(by javascript).

A:

I attached an event handler to certain buttons, that altered the settings of the validator object on that particular form.
$(".jsCancel").click(function (e) {
    $(e.currentTarget).closest("form").validate().settings.ignore = "*"
});

This has worked like a charm for me in MVC3.
I don't know if this helps you in particular, but since I use ajax form, I had to attach the event to these buttons each time the contents of the ajax form was replaced, by using the event ajax success. The full code that reparses the form and attaches the event to the cancel buttons is:
$(document).ajaxSuccess(function (event, xhr, settings) {
    var $jQval = $.validator, adapters, data_validation = "unobtrusiveValidation";
    $jQval.unobtrusive.parse(document);
    $(".jsCancel").click(function (e) {
        $(e.currentTarget).closest("form").validate().settings.ignore = "*"
    });
});

A:

Hijack the button click for form submission using JavaScript.
Here is good example with jQuery:
$("#MyButton").click(function(e) {

    //submit your form manually here
    e.preventDefault();
});


Q:

Is LiOH a weaker base than NaOH?

Is $\ce{LiOH}$ a weaker base than $\ce{NaOH}$?
Note: I'm not interested in "why," but rather what the "real" $\mathrm{p}K_
\mathrm{b}$ values are.
$$
\begin{array}{lcc}
\text{Data for Alkali Metal Hydroxides} \\
\hline
\text{Cation} & \mathrm{p}K_\mathrm{b} & \text{Solubility} & \text{Solubility} \\
\text{} & \text{} & \pu{g/100 ml} \text{ at } \pu{20 ^\circ C} & \pu{moles/L} \text{ at } \pu{20 ^\circ C} \\
\hline
\ce{Li} & -0.36 & 12.8 & 5.34\\
\ce{Na} & 0.2 & 111 & 27.75\\
\ce{K} & 0.5 & 112 & 20.0  \\
\ce{Rb} & ? & 180 & 17.6\\
\ce{Cs} & -1.76 & 200? & 13.3?\\
\hline
\end{array}
$$
The $\mathrm{p}K_\mathrm{b}$ data is from Wikipedia ($\ce{Li}$, $\ce{Na}$, $\ce{K}$, and $\ce{Cs}$). Wikipedia doesn't have a value for $\ce{Rb}$ and I couldn't find one.
The solubility data is from the Wikipedia Solubility Table. Wikipedia doesn't have a solubility value for $\ce{CsOH}$ at $\pu{20 ^\circ C}$  and I couldn't find one, About $\pu{200 g}$ would be a reasonable guess, which would be $\pu{13.3M}$.
One point is that the Wikipedia article for lithium hydroxide says "It ... is the weakest base among the alkali metal hydroxides."
Another point is an earlier question "Why is $\ce{LiOH}$ a weaker base than $\ce{NaOH}$". User Lighthart references a paper "Ions in water: The microscopic structure of concentrated hydroxide solutions" by Imberti et al. but the abstract at least doesn't seem to address the strength of the alkali hydroxides directly (I don't have access to the paper itself since it is behind a paywall).
Is this one of the Bertrand Chord paradox problems where it depends on how we define "stronger"?

With a $\mathrm{p}K_\mathrm{b}$ of -0.36, $\ce{LiOH}$ would seem to be a stronger base than either $\ce{NaOH}$ or $\ce{KOH}$.
Certainly more moles of $\ce{NaOH}$ dissolve in a liter of solution at $\pu{20 ^\circ C}$ than any other alkali hydroxide.

EDIT 3/22/2016 11:31 pm
Found a different table of $\mathrm{pK}_\mathrm{b}$ data for the alkali hydroxides: Source-2
EDIT 3/23/2016 12:12 am
Source-3 CRC Handbook of Chemistry and Physics, 92nd edition, "Dissociation Constants of Inorganic Acids and Bases. Only $\ce{Li}$ $(\mathrm{p}K_\mathrm{a}= 13.8)$ and $\ce{Na}$ $(\mathrm{p}K_\mathrm{a}=14.8)$ are listed as $\mathrm{p}K_\mathrm{a}$ of the cations. It is the same data as in this pdf file which is from another edition.
$$
\begin{array}{lcc}
\hline
\text{Cation} & \text{Wikipedia} & \text{Source-2} & \text{CRC}\\
\hline
\ce{Li} & -0.36 & 0.18 & 0.2 \\
\ce{Na} & 0.2 & -0.56 & -0.8 \\
\ce{K} & 0.5 & -1.1 & \\
\ce{Rb} & ? & -1.4 & \\
\ce{Cs} & -1.76 & -1.76 & \\
\hline
\end{array}
$$

A:

In Proton Affinities of the Alkali Hydroxides J. Am. Chem. Soc., 1969, 91, pp 2810–2811, it is shown that gas phase affinities in $\pu{kcal/mol}$ are:

$\ce{LiOH}$: 240.7
$\ce{NaOH}$: 247.6
$\ce{KOH}$: 262.6
$\ce{CsOH}$: 269.2

So, yes, $\ce{LiOH}$ is weaker, at least in the gas phase.
In aqueous solution, ACIDITY FUNCTIONS FOR STRONGLY BASIC SOLUTIONS Chemical Reviews volume 66, pages 119-131:

the order of basicity for the same molarity of aqueous solution, $\ce{LiOH < NaOH < KOH}$.

For example, for a $\pu{1M}$ solution, the acidity function (H) is:

$\ce{LiOH}$: 13.48
$\ce{NaOH}$: 14.01, 14.16 (two different measurement techniques)
$\ce{KOH}$: 14.17

So in both the gas and aqueous phases, $\ce{LiOH}$ is a weaker base than $\ce{NaOH}$.


Q:

Click function doesn't work after ajax call in dynamic element (Backbone)

I've create dynamic popup in my Backbone.view by clicking button:
var Section = Backbone.View.extend({
className: 'sqs-frontend-overlay-editor-widget-section',
events:{
    'click .sqs--section--control__edit':           'Section_control'
},

initialize: function(){

},

render: function(){
    this.$el.append(_.template(_section).apply(this.options));
    return this.$el;
},

Section_control: function(){
    var me = this;
    require(['View/Popup/Section_control'], function(_Section_control){
        var sec     = new _Section_control({popup: popup, sec: me.options.section});
        var popup   = new Popup({content: sec.render()});
    });
}
});
return Section;

in the created dynamic popup i have button with trigger:
    events:{
        'click .module-invert-mode':    'invert'
    },

    invert: function(e){
            console.log('hello');

            if(this.options.sec.hasClass('.module-invert')) {
                console.log('yse');
            }

            this.options.sec.toggleClass('module-invert');
            this.options.sec.trigger('invertChange');

    },

and button invertChange trigger:
    el.on("invertChange", function(e){
        var section = el.parents('section');
        var index   = section.index();
        var model   = collection.at(index);
        model.set(Helper.sectionToObj(section),{doReload: true})
    });

take a look at the {doReload: true} function that i call in invertChange:
    change: function(model, options){
        me = this;

        if( model._changing && options.doReload ) {
            $.ajax({
                url: 'wp-admin/admin-ajax.php',
                type: 'post',
                data: {
                    action: 'getShortcode',
                    shortcode: model.attributes.shortcode
                },
                success: function (data) {
                    //var section = $(data);
                    me.$el.find('section:eq(' + model.collection.indexOf(model) + ')').replaceWith(data);
                    me.add( model, model.collection );
                    //me.collection.add({shortcode: model.attributes.shortcode}, {at: section.index()});
                }
            });
        }
    },

the problem is when I create dynamic popup and click on the button with invertChange trigger, ajax works only once, when I click on button in popup again, ajax doesn't works ( next ajax request works only if close and create dynamic popup again). How I can call ajax without constantly closing and opening my dynamic popup?

A:

The problem that you have code which overrides child views
me.$el.find('section:eq(' + model.collection.indexOf(model) + ')').replaceWith(data);

And this listener is not able to handle event
el.on("invertChange", function(e){

because your code
this.options.sec.trigger('invertChange');

doesn't trigger event on correct view, it has lost the reference to this view after replaceWith()
As a solution you need parse your data object and apply each changes locally to elements
something like this
$(data).find("* [attr]").each(function(i, el) {
    var $el = $(el),
        attr = $el.attr("attr"),
        $parent = me.$el.find('section:eq(' + model.collection.indexOf(model) + ')');
    if ($el.is("div, span")) {
        $parent.find('[attr=' + attr + ']').html($el.html());
    } else if ($el.is("img")) {
        $parent.find('[attr=' + attr + ']').attr("src", $el.attr("src"));
    } else if ($el.is("a")) {
        $parent.find('[attr=' + attr + ']').attr("href", $el.attr("href"));
    } else if (attr == "image_back_one") {
        $parent.find('[attr=' + attr + ']').attr("style", $el.attr("style"));
    } else {
        console.log($el);
    }
});


Q:

What is this thing?

Here is a riddle from my side. I think it's bit easy.
Clues

8 times a day.

Bent

97 of the cent useless.

It saves you from death but you can also die within it.

Might cause a war.

A:

This may provide a solution

 water

8 times a day

 There's a saying 'drink eight glasses of water a day'.

Bent

 The water molecule H-O-H is V-shaped or bent.

97 of the cent useless

 97% of the water on Earth is salty ocean water which is not good for drinking.

It saves you from death but you can also die within it

 You need water to survive, but may drown in it.

Might cause a war

  Water conflict is a serious concern.


Q:

alfresco webscript not executing code

im trying to run a java based-webscript in alfresco. In my first step I just want  to print "hello world" using the response output stream.The main problem I face is that the code is not being executed.I have tried to set breakpoints in the code but they dont trigger,I only get the plain ftl as a  result.
Shouldnt the abstratWebscript response priorize over the ftl?
Could someone tell me what im doing wrong or if this is the natural behavior of the abstractwebscript?
This is the java class:
package com.beam.gbsprocs.tag.webscript;
import java.io.IOException;
import java.io.PrintWriter;

import org.springframework.extensions.webscripts.AbstractWebScript;
import org.springframework.extensions.webscripts.WebScriptRequest;
import org.springframework.extensions.webscripts.WebScriptResponse;

public class GbsprocsTagWebscript extends AbstractWebScript {

  @Override
  public void execute(WebScriptRequest req, WebScriptResponse res)
        throws IOException {

    PrintWriter out = new PrintWriter(res.getOutputStream());

    out.println("hello world");
    out.close();

  }

}

This is the description file
<webscript>
<shortname>Perform GBSprocs  Tag completion</shortname>
<description>Export gives a json list of posible tag values </description>
<url>/gbsprocs/tag</url>
<authentication>user</authentication>
</webscript>

Bean declaration(added in edition):
  <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xmlns:util="http://www.springframework.org/schema/util"

   xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
   http://www.springframework.org/schema/util
  http://www.springframework.org/schema/util/spring-util-2.5.xsd">

 <bean id="com.beam.gbsprocs.tag.webscript.GbsprocsTagWebscript.get"
    class="com.beam.gbsprocs.tag.webscript.GbsprocsTagWebscript"
      parent="webscript">

 </bean>

</beans>

And the ftl looks like:
Hello from ftl.

Executing result:
rest client response

A:

Use org.springframework.extensions.webscripts.DeclarativeWebScript instead AbstractWebScript
and @override method
protected Map executeImpl(WebScriptRequest req, Status status, Cache cache) that returns your model to ftl
And also you need add bean deffenition on your class


Q:

fetch `then()` is executing even if api fails

Hi I have made a wrapper for fetch something like this, I'm importing this wrapper in components but on failure catch() of this wrapper is executing but in the component then() function is executing any idea!!
 import { SERVER_URL } from '../configs/serverConfig';

  export default function callApi(api_url: string, method = 'get', data = null) {

    opts = {
      method: method,
      headers: {
        Authorization: 'Basic VFM0NjA2Omsuc3ZpbTg4',
        Accept: 'application/json',
        'Content-Type': 'application/json'
      }
    };
    if (data) {
      opts.data = JSON.stringify(data);
    }
    return fetchWrapper(api_url, opts);
  }

  function fetchWrapper (api_url: string, opts: any){
    let requestParamObj= {};
    if(opts.method.toLocaleLowerCase() === 'get'){
      requestParamObj = {
        method:opts.method
      }
    }
    else if(opts.method.toLocaleLowerCase() === 'post'){
      requestParamObj = {
        method: opts.method,
        headers: opts.headers,
        body: opts.data
      }
    }

    return (
      fetch(api_url, requestParamObj)
        .then((resp) => resp.json())
        .then(response => {
          return response;
        })
        .catch(error => {
          console.log('request failed', error);
          return error;
        })
    )
  }

I'm calling this in a component something like this
    callApi('/someURl', 'GET')
        .then((res) => {
        console.log('this get called even if api fails', res)
    }).catch((err) => {
        //TODO :: error handling at global level
        console.log('Some err', err)
    })
    }

A:

This is because you're catching the error in the wrapper and returning a value, so the consumer will get the returned value instead of the error.
      fetch(api_url, requestParamObj)
        .then((resp) => resp.json())
        .then(response => {
          return response;
        })
        .catch(error => {
          console.log('request failed', error);
          throw error;
        })

if you replace return error with throw error the consumer catch will be returned as expected.
PS: Fetch API will resolve the promise even if you get an error status from the API, it will only trigger the catch on actual JavaScript errors, if you want the promise to be rejected on network/API error responses aswell. you might want to do something like this
function handleErrors (response) {
  if (!response.ok) {
    console.log('ERROR: ' + response)
    throw Error(response.statusText)
  }
  return response
}

and use
.then(handleErrors)


Q:

Flutter: Get number incoming call

I've been studying Flutter and I'm really enjoying it.
I want to make an application that identifies the phone number when receiving a call, is this possible in Flutter?
Thanks

A:

It seems possible though also quite difficult. There isn't official support for this and there aren't any packages that do what you need. The only way that I see is to create platform-specific implementations and use platform channels.
Possible android implementation
Possible iOS implementation
Platform channels


Q:

Fastest available Delaunay triangulation algorithm for GPU

Which is in your opinion the fastest available Delaunay triangulation algorithm for GPU? Or more general, in parallel

A:

2D Delaunay triangulation
GPU-DT is the fastest 2D Delaunay implementation for the GPU.
It constructs a digital Voronoi diagram in 2D using the GPU Parallel Banding Algorithm. Next it fixes and dualizes this to obtain a 2D triangulation. Finally, it performs edge-flipping in parallel on the GPU to obtain the 2D Delaunay triangulation.
3D Delaunay triangulation
gStar4D is a fast and robust implementation of 3D Delaunay for the GPU.
Similar to GPU-DT, this algorithm constructs the 3D digital Voronoi diagram first. However, in 3D this cannot be dualized to a triangulation due to topological and geometrical problems. Instead, gStar4D uses the neighborhood information from this diagram to create stars lifted to 4D and performs star splaying on them efficiently on the GPU. By extracting the lower hull from this, the 3D Delaunay triangulation is obtained.
A faster alternative is gDel3D, which is a hybrid GPU-CPU algorithm.
It performs parallel insertion and flipping on the GPU. The result is close to Delaunay. It then fixes this result using a conservative star splaying method on the CPU.
All these methods are robust, so they can handle any kind of degenerate input.

A:

Be careful with GPU's: Delaunay Triangulations require orientation tests. These do not work reliably with floating point arithmetic, and it might be hard to cope with that
problem using a GPU. Also the memory management is crucial.
You might want to try http://www.geom.at/fade2d/html/ which is among the fastest robust
single threaded implementations.


Q:

How to remove leading zero(s) from SQL

I want to remove leading zeros from SQL table. I'm joining 3 column as one column.
example
col1         col2        col3
00000        S           Gaskin Road
             N           Broad Street
00001                    John Rolfe Road

what i want the result to be:
1 0 S Gaskin Road or just S Gaskin Road
2   N Broad Street
3 1 John Rolfe Road

here is the script that i join 3 column
   ,COALESCE(CASE WHEN col1 = '' THEN '' ELSE col1 + ' ' END, '')  +
   COALESCE(CASE WHEN col2 = '' THEN '' ELSE col2 + ' ' END, '')  +
   COALESCE(CASE WHEN col3 = '' THEN '' ELSE col3 + ' ' END, '') as allCol

A:

cast col1 to int so the leading zeroes are removed and cast the int to varchar for concatenation.
COALESCE(CASE WHEN col1 = '' THEN '' ELSE cast(cast(col1 as int) as varchar(255))+ ' ' END, '')  +
COALESCE(CASE WHEN col2 = '' THEN '' ELSE col2 + ' ' END, '')  +
COALESCE(CASE WHEN col3 = '' THEN '' ELSE col3 + ' ' END, '')


Q:

QWebPage force to open link in same tab

I'm working on a one tab browser in Qt and I've encountered a problem:
The links on the web that lead to external websites are set to open in a new tab (using taget='_blank'). However, since my browser has just one tab those links are simply inactive.
I believe that it's possible to force the links to open in the same tab by injecting JavaScript (QWebFrame::eveluateJavaScript), by that seems like an inefficient solution.
Is there a native way in Qt to force all links to open in the same tab/window?
Edit:
I've come up with a native way by re-implementing loadFinished(bool) :
void MyBrowser::loadFinished(bool ok) {
    if (!ok) {
        return;
    }

    QWebFrame* frame = webView->page()->mainFrame();
    if (frame!=NULL) {
        QWebElementCollection collection = frame->findAllElements("a[target=_blank]");
        foreach (QWebElement element, collection) {
            element.setAttribute("target", "_self");
        }
    }
}

If there's an even better way I'd be glad to see it.

A:

Make QWebPage's subclass, and override createWindow(). Most simple way is as follows:
QWebPage* CustomWebPage::createWindow(WebWindowType type)
{
    return this;
}

And, set above webpage to webview like this:
// QWebView Setting
ui->webView->setPage(new CustomWebPage());
ui->webView->settings()->setAttribute(QWebSettings::JavascriptEnabled, true);
ui->webView->settings()->setAttribute(QWebSettings::JavascriptCanOpenWindows, true);


Q:

How to propose a new site on Area 51

I created an account on area 51 for a new proposal. But after I created and verified my account there is no option for propose a new site? Do we need more reputations to make proposals. How could i propose a new site?

A:

If you scroll to the bottom of the home page, you should see:

Can't find what you're looking for? Select a category listing to the left and propose your site there!

After selecting one and scrolling to the bottom of that page, I see:

Can't find what you're looking for? Propose a new <subject> site.

…where the latter sentence is a link. Clicking on that should bring you to a form where you can propose a new site.


Q:

Set Parameters of Screenshot taken by Python

I have used the following code to take the screen shot of the web page.
From the code I understand that first the complete page is loaded in the frame and then the frame is rendered in painter. The problem I am facing is that some web pages might be very very lengthy in terms of content, but I would just want the screen shot of the first page of website. Is there any way I can handle that?
def capture(self, url, output_file):
    self.load(QUrl(url))
    self.wait_load()
    # set to webpage size
    frame = self.page().mainFrame()
    self.page().setViewportSize(frame.contentsSize())
    # render image
    image = QImage(self.page().viewportSize(), QImage.Format_ARGB32)
    painter = QPainter(image)
    frame.render(painter)
    painter.end()
    print 'saving', output_file
    image.save(output_file)

I have tried to set Preferred size of frame with the help of QSize object, but it wont help either.
Or alternative, is there any way I can crop image?
Any help is highly appreciated, Thanks.

A:

There is no such thing as "the first page". It's entirely up to the application to decide how to divide up the content.
At the moment, your script explicitly sets the first division to be the entire contents of the page. To avoid that, you should simply decide how much of the content you want to capture, and then resize the viewport as appropriate.
The demo script below uses QPrinter to calculate an A4 page size:
usage: capture.py url > webpage.png

from PyQt4 import QtCore, QtGui, QtWebKit

class WebPage(QtWebKit.QWebPage):
    def __init__(self):
        QtWebKit.QWebPage.__init__(self)
        self.mainFrame().setScrollBarPolicy(
            QtCore.Qt.Horizontal, QtCore.Qt.ScrollBarAlwaysOff)
        self.mainFrame().setScrollBarPolicy(
            QtCore.Qt.Vertical, QtCore.Qt.ScrollBarAlwaysOff)
        self.mainFrame().loadFinished.connect(self.handleLoadFinished)
        printer = QtGui.QPrinter()
        printer.setPaperSize(QtGui.QPrinter.A4)
        self.setViewportSize(printer.paperSize(
            QtGui.QPrinter.DevicePixel).toSize())

    def capture(self, url):
        self._url = QtCore.QUrl(url)
        QtCore.QTimer.singleShot(0, self.handleLoad)

    def handleLoad(self):
        self.mainFrame().load(self._url)

    def handleLoadFinished(self):
        image = QtGui.QImage(self.viewportSize(),
                             QtGui.QImage.Format_ARGB32)
        painter = QtGui.QPainter(image)
        self.mainFrame().render(painter)
        painter.end()
        output = QtCore.QFile()
        output.open(1, QtCore.QIODevice.WriteOnly)
        image.save(output, 'PNG')
        sys.exit(0)

if __name__ == '__main__':

    import sys, signal
    app = QtGui.QApplication(sys.argv)
    signal.signal(signal.SIGINT, signal.SIG_DFL)
    page = WebPage()
    page.capture(sys.argv[1])
    sys.exit(app.exec_())


Q:

Show fixed columns on page load and when user clicks on symbol show remaining columns in html table

I want to show only first two columns when user loads the page, and near table header an arrow mark or some symbol should be displayed and when user clicks that symbol the remaining columns should be shown.Could not find any samples online. Can we achieve this using html, javascript, jquery.Please find the sample in http://jsfiddle.net/TweNm/2338/.
My requirement is to show column A and B when user loads the page and an arrow near header, when user clicks the arrows the remaining columns should be displayed. Please suggest.
Below is the sample CSS code:
#table-wrapper {
  position:relative;
}
#table-scroll {
  height:150px;
  overflow:auto;
  margin-top:20px;
}
#table-wrapper table {
  width:100%;

}
#table-wrapper table * {
  background:yellow;
  color:black;
}
#table-wrapper table thead th .text {
  position:absolute;
  top:-20px;
  z-index:2;
  height:20px;
  width:35%;
  border:1px solid red;
}

Thanks.

A:

Yeah, that's definitely doable!  You can hide all but the first two columns like this:
table.collapsed th:not(:nth-child(1)):not(:nth-child(2)),
table.collapsed td:not(:nth-child(1)):not(:nth-child(2)) {
    visibility: hidden;
}

And then just rig up some javascript to remove the collapes class from the table when you click the arrow.  Here is a very, very rough prototype based on the jsfiddle you provided:
http://jsfiddle.net/TweNm/2341/


Q:

Suggestions on improving this simple object pool class for Java?

I am currently writing a game for android where there are enemies that fly across the screen and then disappear, to be replaced by other enemies. Now, this happens very fast, and my code currently performs a lot of memory allocation and deallocation to create and delete these enemy objects, so I'm trying to find a way to optimize this. I got this Pool class implementation from a book on android game dev:
public class Pool<T> {
    public interface PoolObjectFactory<T> {
        public T createObject();
    }
    private final List<T>               freeObjects;
    private final PoolObjectFactory<T>  factory;
    private int                         maxObjects;

    public Pool(PoolObjectFactory<T> factory, int maxObjects) {
        this.maxObjects = maxObjects;
        this.factory = factory;
        freeObjects = new ArrayList<T>(maxObjects);
    }

    public T newObject() {
        T object = null;
        if (freeObjects.isEmpty()) {
            object = factory.createObject();
        } else {
            object = freeObjects.remove(freeObjects.size() - 1);
        }
        return object;
    }

    public void free(T object) {
        if (freeObjects.size() < maxObjects) freeObjects.add(object);
    }
}

Now, the way to use this class is as follows:
PoolObjectFactory<Enemy> factory = new  PoolObjectFactory<Enemy>() {
    public Enemy createObject() {
        return  new  Enemy();
    }
};
Pool<Enemy> enemyPool = new  Pool<Enemy>(factory, 50);

The obvious problem with this method is that you can't input any parameters to the createObject() method, thus forcing you to use classes that take no arguments in their constructor. This will force me to rewrite a lot of code since the Enemy class I'm using takes several different parameters. I can think of a couple of workarounds, like this one:
PoolObjectFactory<Enemy> factory = new  PoolObjectFactory<Enemy>() {
    public Enemy createObject(Object... args) {
        return  new  Enemy((Float)args[0], (Float)args[1]);
    }
};
Pool<Enemy> enemyPool = new  Pool<Enemy>(factory, 50);

But it's error-prone and annoying to update. I could also initialize the Enemy object in the createObject() method with bogus values and then set them manually later, or I could create a Pool class for every single object but I would really prefer not doing that.
Any suggestions on how to improve this code? How do you fellow java game developers deal with pooling objects to avoid garbage collection? Thanks very much.

A:

1) You should override the createObject function in your PoolObjectFactory.
2) You will need a initialize() function that actually sets the parameters for each EnemyObject. Just have the constructor for the EnemyObject call the initialize function. Then, when you get the object out of the pool, you should just call initialize with your parameters and it should work perfectly.


Q:

Content Type can't be deleted

I have a content type that won't go away.  I've tried messing with the feature that installed it (reinstalling, deactivating, retracting, etc.), to no avail.  Finally, here is an attempt in PowerShell that illustrates the problem succinctly:
PS C:\Users\Administrator> $web = get-spweb http://cbaoth/sites/dev0
$ct = $web.ContentTypes["Timed Activity"]
$u = [Microsoft.SharePoint.SPContentTypeUsage]::GetUsages($ct)

if ($u.Count > 0) {
  foreach ($usage in $u) {
    Write-Output ("The content type is used here: {0}",$usage)
  }
} else {
  $ct.Delete()
  $web.Update()
}
Exception calling "Delete" with "0" argument(s): "The content type "Timed Activity" is part of an application feature."
At line:10 char:13
+   $ct.Delete <<<< ()
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

Anyone have any idea what I can do about this?  I'm developing a solution with content types in it, and I can't make changes because it fails to retract properly and the subsequent deployment fails.

A:

You need to check:

This content type is not being
references by a list or document
library
This content type is not
being references by a list or
document library that's in End User
Recycle bin
This content type is not
being references by a list or
document library that's in Site
Collection Recycle bin
If content
type was deployed via feature you
need to retract it

Update: The key to this is removing items from both recycle bins as clearing items from the end user recycle bin does not remove them entirely.
You still need to go to Site Settings > Recycle Bin (Under site collection administration) and then remove all items from the "Deleted from end user Recycle Bin" view.


Q:

How to connect command button to action handler in PrimeFaces mobile rendering mode?

I have a PrimeFaces page with following form:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:p="http://primefaces.org/ui"
      xmlns:pm="http://primefaces.org/mobile">

<f:view renderKitId="PRIMEFACES_MOBILE"/>

<h:head>

</h:head>

<h:body>

    <pm:page>
        <pm:header title="Test"></pm:header>

        <pm:content>
            <p:panel header="Login">
                <h:form>
                    <pm:field>
                        <p:outputLabel for="basic" value="User:"/>
                        <p:inputText id="basic"/>
                    </pm:field>

                    <pm:field>
                        <p:outputLabel for="password" value="Password:"/>
                        <p:password id="password"/>
                    </pm:field>

                    <p:commandButton value="Login" type="button"
                                     actionListener="#{index.loginButtonAction}"/>
                </h:form>
            </p:panel>
        </pm:content>
    </pm:page>
</h:body>

</html>

And I have the class IndexView defined as follows.
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

@ManagedBean(name = "index")
@RequestScoped
public class IndexView {
    public void loginButtonAction(ActionEvent actionEvent)
    {
        System.out.println("loginButtonAction");
        addMessage("loginButtonAction");
    }

    public void registerButtonAction(ActionEvent actionEvent)
    {
        System.out.println("registerButtonAction");
        addMessage("registerButtonAction");
    }

    public void addMessage(String summary) {
        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, summary,  null);
        FacesContext.getCurrentInstance().addMessage(null, message);
    }
}

When I press the Login button, nothing happens. I don't even see the message in the logs.
What do I need to change in order for loginButtonAction action to be called, when the button has been pressed?
The dependencies from my pom.xml file look are these:
<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.1</version>
        <scope>test</scope>
    </dependency>

    <!-- PrimeFaces (start) -->
    <dependency>
        <groupId>org.primefaces</groupId>
        <artifactId>primefaces</artifactId>
        <version>5.1</version>
    </dependency>
    <!-- PrimeFaces (end) -->

    <!-- JSF 2 (start) -->
    <dependency>
        <groupId>com.sun.faces</groupId>
        <artifactId>jsf-api</artifactId>
        <version>2.1.11</version>
    </dependency>
    <dependency>
        <groupId>com.sun.faces</groupId>
        <artifactId>jsf-impl</artifactId>
        <version>2.1.11</version>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
    </dependency>

    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.1</version>
    </dependency>
    <!-- JSF 2 (end) -->
</dependencies>

A:

Try removing
type="button"

From your commandButton. As long as its type is button it would only be clickable and won't send form data to the server.


Q:

Are questions with lots of parts on topic?

This question about the environment was posted recently. While no-one can doubt OP enthusiasm I personally don't like questions with loads of little parts that require separate answers. Is that just me? I notice this got upvoted
The reason I don't like them is

I think questions should be tightly focused so that it is obvious what is being asked. Ultimately we what people and search engine to find our content. With a sprawling question that is less likely.
If someone has got 3 questions why not make it a bit easier for people who would like to answer and ask them as three separate questions. Why oblige someone to answer everything you've ever wanted to know about Buddhism in one post? Give them a break.
If some one only knows the answer to some parts and another poster knows some other parts of the question- who get's the accepted answer (I know we are not great at awarding the accepted answer)?

In fairness - at least the above question was around a theme. I'm sure I've seem far looser agglomerations of queries before.
With these questions I would like to

Politely ask OP to split them up
Wait a bit
Ask again and inquire if they need any editing assistance
Cast close votes and ultimately put them on hold as been too broad

Is that a reasonable approach. Unreasonable? Grumpy? Hysterical?

A:

I think there's a lot of overlap. It's poorly written, I think, with no explanation. Better would be a couple of more general questions around stewardship and the environment. Most of the questions could be combined, I think.

A:

A couple of us did politely suggest to the OP this morning that this question be split up. There are some good questions there but answering it as it stands will be an undertaking along the lines of writing an entire term paper. It's unlikely there will be much of a response due to all of the information being requested.
I think your suggestions 1 - 4 are very reasonable.


Q:

Can't hide text in html/css with overflow:hidden

I've got this in the index(this is only a small portion of it)

        Mauris vulputate lorem ac nibh rhoncus, eu mattis lorem mattis. Maecenas metus dui, rhoncus eget erat quis, vehicula luctus justo. Aenean vel porta est, tristique mollis metus. Mauris gravida diam sit amet tellus pellentesque hendrerit. Maecenas ut suscipit metus. Nunc vel volutpat est, porta sodales nibh. Pellentesque varius ac massa nec varius.
        Mauris vulputate lorem ac nibh rhoncus, eu mattis lorem mattis. Maecenas metus dui, rhoncus eget erat quis, vehicula luctus justo. Aenean vel porta est, tristique mollis metus. Mauris gravida diam sit amet tellus pellentesque hendrerit. Maecenas ut suscipit metus. Nunc vel volutpat est, porta sodales nibh. Pellentesque varius ac massa nec varius.

And i've got this on the stylesheet:
#abms
    {
        overflow:hidden;
    }

Doesnt matter what I try, I can't get the text to hide, I want this text to hide with overflow:hidden because I want it to be visible when using overflow:visible in my jquery code sheet.
All of the files are linked correcty (i know this because all the other css and jquery effects are working) but I just can not make this hide.
I've seen tutorials doing this and it works, why won't it work for me? if some one could point the error out, that would be great.
Someone help me please
Thanks

A:

try adding width and hide the text will hide in it
http://jsfiddle.net/kKzyT/
like
#abms
    {
      width:400px;
     height:200px;
     overflow:hidden;
    }

here the text will hide in width:400px;and height:200px;


Q:

Grouping rows on the basis of row differences in R

I have a set of animal locations with different sampling intervals. What I want to do is group and seqences where the sampling interval matches a certain criteria (e.g. is below a certain value). Let me illustrate with some dummy data:
start <- Sys.time()
timediff <- c(rep(5,3),20,rep(5,2))
timediff <- cumsum(timediff)

# Set up a dataframe with a couple of time values
df <- data.frame(TimeDate = start + timediff)

# Calculate the time differences between the rows
df$TimeDiff <- c(as.integer(tail(df$TimeDate,-1) - head(df$TimeDate,-1)),NA)

# Define a criteria in order to form groups
df$TimeDiffSmall <- df$TimeDiff <= 5

             TimeDate TimeDiff TimeDiffSmall
1 2016-03-15 23:11:49        5          TRUE
2 2016-03-15 23:11:54        5          TRUE
3 2016-03-15 23:11:59       20         FALSE
4 2016-03-15 23:12:19        5          TRUE
5 2016-03-15 23:12:24        5          TRUE
6 2016-03-15 23:12:29       NA            NA

In this dummy data, rows 1:3 belong to one group, since the time difference between them is <= 5 seconds. 4 - 6 belong to the second group, but hypothetically there could be a number of rows in between the two groups that dont belong to any group (TimeDiffSmall equals to FALSE).
Combining the information from two multiple SO answers (e.g. part 1), I've create a function that solves this problem.
number.groups <- function(input){
  # part 1: numbering successive TRUE values
  input[is.na(input)] <- F
  x.gr <- ifelse(x <- input == TRUE, cumsum(c(head(x, 1), tail(x, -1) - head(x, -1) == 1)),NA)
  # part 2: including last value into group
  items <- which(!is.na(x.gr))
  items.plus <- c(1,items+1)
  sel <- !(items.plus %in% items)
  sel.idx <- items.plus[sel]
  x.gr[sel.idx] <- x.gr[sel.idx-1]
  return(x.gr)

 # Apply the function to create groups
 df$Group <- number.groups(df$TimeDiffSmall)

             TimeDate TimeDiff TimeDiffSmall Group
1 2016-03-15 23:11:49        5          TRUE     1
2 2016-03-15 23:11:54        5          TRUE     1
3 2016-03-15 23:11:59       20         FALSE     1
4 2016-03-15 23:12:19        5          TRUE     2
5 2016-03-15 23:12:24        5          TRUE     2
6 2016-03-15 23:12:29       NA            NA     2

This function actually works to solve my problem. This this is, it seems like a crazy and rookie way to go about this. Is there a function that could solve my problem more professionally?

A:

Like @thelatemail, I'd use the following to get the group IDs. It works because cumsum() will end up incrementing the group count each time it reaches an element preceded by a greater-than-5-second time interval.
df$Group <- cumsum(c(TRUE, diff(df$TimeDate) > 5))
df$Group
# [1] 1 1 1 2 2 2


Q:

Sum of sum of binomial coefficients $\sum_{j=1}^{n}{\sum_{k=0}^{j}{{n}\choose{k}}}$

I know there is no simple way to solve the sum:
$$\sum_{k=0}^{j}{{n}\choose{k}}$$
But what about the equation:
$$\sum_{j=1}^{n}{\sum_{k=0}^{j}{{n}\choose{k}}}$$
Are there any simplifications or good approximations for this equation?

A:

Basically it’s just a matter of reversing the order of summation, much as you might reverse the order of integration of a double integral, though the lower limit of $1$ on the outer summation requires a little adjustment.
$$\begin{align*}
\sum_{j=1}^n\sum_{k=0}^j\binom{n}k&=\sum_{j=0}^n\sum_{k=0}^j\binom{n}k-\binom{n}0\\
&=\sum_{k=0}^n\sum_{j=k}^n\binom{n}k-1\\
&=\sum_{k=0}^n(n-k+1)\binom{n}k-1\\
&=(n+1)\sum_{k=0}^n\binom{n}k-\sum_{k=0}^nk\binom{n}k-1\\
&=(n+1)2^n-\sum_{k=0}^nn\binom{n-1}{k-1}-1\\
&=(n+1)2^n-1-n\sum_{k=0}^{n-1}\binom{n-1}k\\
&=(n+1)2^n-1-n2^{n-1}\\
&=(n+2)2^{n-1}-1
\end{align*}$$

A:

Let's see.
$\begin{array}\\
s(n)
&=\sum_{j=1}^{n}{\sum_{k=0}^{j}{{n}\choose{k}}}\\
&=-1+\sum_{j=0}^{n}{\sum_{k=0}^{j}{{n}\choose{k}}}\\
&=-1+\sum_{k=0}^{n}\sum_{j=k}^{n}{{n}\choose{k}}\\
&=-1+\sum_{k=0}^{n}(n-k+1){{n}\choose{k}}\\
&=-1+\sum_{k=0}^{n}(n+1){{n}\choose{k}}-\sum_{k=0}^{n}k{{n}\choose{k}}\\
&=-1+(n+1)2^n-\sum_{k=0}^{n}k\dfrac{n!}{k!(n-k)!}\\
&=-1+(n+1)2^n-\sum_{k=1}^{n}\dfrac{n!}{(k-1)!(n-k)!}\\
&=-1+(n+1)2^n-n\sum_{k=1}^{n}\dfrac{(n-1)!}{(k-1)!(n-k)!}\\
&=-1+(n+1)2^n-n\sum_{k=1}^{n}\binom{n-1}{k-1}\\
&=-1+(n+1)2^n-n\sum_{k=0}^{n-1}\binom{n-1}{k}\\
&=-1+(n+1)2^n-n2^{n-1}\\
&=-1+2^{n-1}(2(n+1)-n)\\
&=-1+2^{n-1}(n+2)\\
\end{array}
$
A pleasant surprise.

A:

There are. Start rewriting the double sum as
$$\begin{align}
\sum_{j=1}^n \sum_{k=0}^j \binom{n}{k}
&= \sum_{j=1}^n \sum_{k=0}^n \binom{n}{k} \mathbb{1}_{k\leq j}
= \sum_{k=0}^n \sum_{j=1}^n \binom{n}{k} \mathbb{1}_{k\leq j}
= \sum_{k=0}^n \sum_{j=k}^n \binom{n}{k} - 1
= \sum_{k=0}^n \binom{n}{k} \sum_{j=k}^n 1 = 1 \\
&= \sum_{k=0}^n \binom{n}{k} (n-k+1) -1
= (n+1)\sum_{k=0}^n \binom{n}{k} -  \sum_{k=0}^n k \binom{n}{k} -1
\end{align}$$
Now, this becomes easy to compute -- both sums have closed forms.


Q:

Why does holding an electrical switch in between on and off states cause sparks?

If air is a bad conductor, then why do sparks develop when an
electrical switch is held in between on and off states?
Why are sparks generated when cables carrying heavy electric current
are brought too close? Is it because the electrons are jumping from
the live cable to the other due to the presence of high voltage?

A:

The switch really has 2 positions: on and off.
However, when you move the switch very slowly, it may leave the closed position slowly. When the switch is just barely open, the field may cause the air to break down and start conducting, to form a spark (as @anna v explained). To rephrase, the reason why sparks happen is because the switch may only be open a tiny amount, not enough to stop current from flowing through the air. If the gap then increases further, the spark may persist because the air is now acting like a conductor rather than an insulator.
Switches are usually designed to prevent this from happening. They have built-in springs that act to open the contacts quickly and completely, thus preventing sparks. However, with many switches, moving the toggle very slowly may cause the contacts to separate a tiny bit, before they fly completely apart. Older designs are likely to suffer more from this.
Switch design is easier for low-voltage switches, because high voltages are more likely to cause the air to break down and cause a spark. It is the voltage that causes electrons to jump across the gap and create the spark. For that reason, high voltage switches are also larger: they have to be large enough to keep the contacts far enough apart when the switch is open. Remember that high enough voltages can cause electrons to jump between clouds and the ground - that's called lightning.


Q:

How to put x button to clear content in input field using angular 5 and bootstrap

I am trying to put a 'x' button inside an input field using angular 5 and bootstrap but was not successful.
By clicking on 'x' button the content in that input field should get cleared
I tried using
<input type="search" id = "search">

In CSS:
 input[type="search"]::-webkit-search-cancel-button {
-webkit-appearance: searchfield-cancel-button;
}
input[type="search"]::-ms-clear {
  color: red;
}

However, I have a problem with this implementation as the webkit-apperance has the compatibility issue with IE11 (even firefox dont support it) and the 'x' is not showing.
can any one help me to find if there is any solution with Angular 5/6/7 and Bootstrap 4.
I have a solution to work with Jquery and Javascript
https://codepen.io/frosdqy/pen/grbxGW
but looking for pure typescript(Angular) or bootstrap solution.
If someone can help with angular5 it would be a great help!

A:

its all about illusion. you create a div. inside that div create a input and button with x. set the input background transparent and border 0. and you will see it.


Q:

jquery autocomplete for rails application

I need a to use an autocomplete in rails application. Which use the combobox as source. I used jquery autocomplete and combobox.
But i need an extra feature. Suppose we type "Apple" and it is not available in auto-complete search it shows a new item in the list named "Create New Apple", if we select it triggers a JavaScript event. so that we can open some dialog to add it.
Moreover the autocomplete can also be updated after rendering. Means if we add new record, it can also be populated in the list.
Hope to get good stuff from you guys.

A:

I full filled my scenario with this code. I modified the code from the jquery site, refactor the change event to.
 auto_obj.change = function(event, ui) {
       if (!ui.item) {
      var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val()) + "$", "i"),
                    valid = false;
      select.children("option").each(function() {
         if ($(this).text().match(matcher)) {
            this.selected = valid = true;
               return false;
         }
      });
      if (!valid) {
          // Trigger the event for value not found
          $(select).trigger('autocompletenotfound', $(this).val());

          // remove invalid value, as it didn't match anything
          $(this).val("");
          select.val("");
          input.data("autocomplete").term = "";
          return false;
      }
  }
}

and in the source function
auto_obj.source = function(request, response) {
                var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
                var match = false;

                response(select.children("option").map(function(i, value) {
                    var text = $(this).text();
                    if (this.value && ( !request.term || matcher.test(text) )) {
                        match = true;
                        return {
                            label: text.replace(
                                    new RegExp(
                                            "(?![^&;]+;)(?!<[^<>]*)(" +
                                                    $.ui.autocomplete.escapeRegex(request.term) +
                                                    ")(?![^<>]*>)(?![^&;]+;)", "gi"
                                            ), "$1"),
                            value: text,
                            option: this
                        };
                    }
                    if (!match && i == select.children("option").size() -1 && self.options.allow_new ) {
                        return {
                            label:'Create new '+ input.val() +'',
                            value: input.val(),
                            option: null
                        };
                    }
                }));
            };

This fulfilled my requirement. Hope will be help full for some one else.


Q:

What is "narrow" mean as in "Narrow Decision"?

In Narrow Decision, Supreme Court Sides With Baker Who Turned Away Gay Couple

The court’s decision was narrow, and it left open the larger question
  of whether a business can discriminate against gay men and lesbians
  based on rights protected by the First Amendment.

I think it maybe means the article of the decision being very short.
Or maybe means the narrow-minded.

A:

Normally a narrow decision means the judges ruled by a narrow majority, like 5-4.  However, in this case narrow refers instead to the scope of the decision, specifically targeted against what the court determined was discrimination by a government official.
The SCOTUS decision means that government agency's action is now invalid, but only because their reasons for the action violated the U.S. Constitution.  It does not address the constitutionality of the underlying issue, so it only affects a very narrow set of circumstances.
From the article:

“The court reversed the Masterpiece Cakeshop decision based on concerns unique to the case but reaffirmed its longstanding rule that states can prevent the harms of discrimination in the marketplace, including against L.G.B.T. people,” said Louise Melling, the group’s deputy legal director.

It is unlikely that a New York Times news article would call any decision or person "narrow-minded", since the Journalist's Code of Ethics, among other things, requires that journalists, "Seek truth and report it", and, "Support the open and civil exchange of views, even views they find repugnant."
Such subjective statements would be acceptable in the Opinion / Editorial section, however.


Q:

Counting the number of multiply-add operations (MAC) in Caffe CNN's architecture

Lately I've been benchmarking some CNNs regarding time, # of multiply-add operations (MAC), # of parameters and model size. I have seen some similar SO questions (here and here) and in the latter, they suggest using Netscope CNN Analyzer. This tool allows me to calculate most of the things I need just by inputing my Caffe network definition.
However, the number of multiply-add operations of some architectures I've seen in papers and over the internet doesn't match what Netscope is outputting, whereas other architectures match. I'm always comparing either FLOPs or MAC with the MACC column in netscope, but there a ~10x factor that I'm forgetting at some point (check table bellow for more detail).
Architecture  ----  MAC (paper/internet) ---- macc column in netscope
VGG 16                    ~15.5G                       ~157G
GoogLeNet                 ~1.55G                       ~16G

Reference about GoogLeNet macc number and VGG16 macc number in Netscope.
Does anybody that used that tool could point me out on what mistake I'm doing while reading Netscope output?

A:

I've found what was causing the discrepancy between Netscope and the information I'd found in papers. Most preset architectures in Nestcope were using a batch size of 10 (this is the case for VGG and GoogLeNet, for example), therefore the x10 factor that multiplied the number of mult-add operations.


Q:

Insert unique strings of 8 random characters

I'm using PHP and MySQL and
I have a table with 3 fields ((ID, Username, PID)).
I want the PID field to contain strings of 8 unique characters.
My solution is to generate the random string in PHP and check if it exists. If it exists then it will generate another string.
Is there any better solution that will save processing time, like a MySQL trigger or something like that?

A:

This will give you a random 8 character string:
substr(str_pad(dechex(mt_rand()), 8, '0', STR_PAD_LEFT), -8);

Found here: http://www.richardlord.net/blog/php-password-security
Or if the username field is unique you could also use:
substr(md5('username value'), 0, 8);

Though it's extremely unlikely, particularly for the md5, neither case guarantees a unique string, so I would probably do something like this:
// Handle user registration or whatever...

function generatePID($sUsername) {
    return substr(md5($sUsername), 0, 8);
}

$bUnique = false;
$iAttempts = 0;

while (!$bUnique && $iAttempts < 10) {
    $aCheck = $oDB->findByPID(generatePID("username value")); // Query the database for a PID matching whats generated
    if (!$aCheck) { // If nothing is found, exit the loop
        $bUnique = true;
    } else {
        $iAttempts++;
    }
}

// Save PID and such...

... which would probably only yield 1 'check' query, maybe 2 in unique cases, and would ensure a unique string.


Q:

How do pilots stay disciplined and use checklists, even after they have become routine?

I originally asked the same question on Space Exploration but will repeat it also here:
Before every takeoff and every landing, there are several routine checks which need to be done in order to provide the highest maximum safety to passengers.
But after certain number of repetitions, these tasks can feel as tedious especially if you are flying a plane which goes in "turns"
(Real example of what I mean is commercial line between Prague (PRG) and Frankfurt (FRA) where plane lands, people go out, new people go in and plane goes back. And so on)
How do pilots and other personnel make sure that they actually do go through the check every single time without "It was OK last time, so it will be ok this time. Skip it and say it is ok" ?

A:

You stay vigilant by having seen things go wrong.
Like Jamiec mentioned the importance of a proper preflight is drilled into you by your primary instructor from day one in light aircraft, and that mentality carries through all the way up to heavy transport-category aircraft: You want to find any problems you can while you're on the ground, because if you take a problem into the air with you it's a decision you can quickly come to regret.
Personally I've found all sorts of "interesting" things on preflight inspections of light aircraft, including (but not limited to):

Mud wasps building a nest in the pitot tube
Mud wasps building a nest in the fuel drain
(still don't know what was up with that)
Missing screws from a fairing
Flat-spot on a tire
A tennis ball stuffed in between two cylinders
(a common flight instructor trick to see if students are doing a thorough preflight)
Position light lenses installed backwards
(another common CFI trick, but this one was actually a maintenance shop screw-up)
Various light bulbs burned out
Water in the fuel after a heavy storm.

I've also heard some scary stories:

Migrating colony of bees hanging out on the tail of the aircraft
(described as "The tail was literally dripping bees")
Flight controls rigged backwards
Big gouge in the wingtip
(acquired by the previous pilot scraping the tip against another plane's tail taxiing in on the ramp)
The ever-classic "ran out of fuel because you didn't visually check the tanks"

A:

In commercial operations the vigilance to avoid complacency is derived from multiple reinforcing actions.
Checklists are often preceded by flows in which you take a logical route through the aircraft panels and perform your checks from memory.  These flows are then backed up by the checklist.  Checklists vary in usage. One one end of the spectrum you have silent checks performed by one pilot (e.g. the after takeoff checklist may be a silent checklist) and on the other end you have challenge and response checklists where one pilot reads each item and the pilot who accomplished that action reads the status of that system (e.g. you look at the button/light/etc and call its status rather than calling the response from rote memorization).
In an airline cockpit you might fly with the same pilot all month or you may change pilots every trip or sometimes multiple times during a trip.  Flying with many different people helps you standardize on these actions as you cannot "get comfortable" with a specific person.  Everyone expects everyone else to do the checklists properly and if you don't do it you will get called out.  Particularly as a new first officer if you are not doing checklists you are going end up explaining why to the chief pilot and/or training department.
You might then ask why we care so much about policing eachother to maintain checklist usage.  The FAA (in the USA) has made a big deal about checklist usage on every checkride you've taken to get into an airline cockpit (at least if you've done your training in the last decade).  It has been drilled into you from the beginning of your training.  In an airlne environment you will have recurrent checkrides every 6-12 months and captains will have line checks every year and proper checklist usage is among the most basic requirement to pass these checks.
Lastly, every year we sit through a day of crew resource management training and part of that day involves looking at past accidents and understanding what the first thing was that set the accident events in motion (pilot error!).  These often serve as vivid examples of how bad things can get if you start ignoring the checklists (among other things).

A:

I can't speak for commercial operations, but from a GA point of view, the pre-flight checks and their importance are drilled in to you from your very first lesson. Its is stressed that the Pilot in Command is 100% responsible for verifying that the aircraft is fit for flight before even climbing in to the cabin.
There are a few tricks that are used to stop you falling in to that "Yeah, everything will be fine" mindset and just skipping the checks

Not doing the checks from memory, but actually doing them in reference to a physical check list.
A prescribed order of checks, starting at a point on the aircraft and moving around methodically
The fear of missing something, such as engine oil levels, which gets very serious once airborne.
Once carrying passengers, especially nervous ones, they tend to feel safer when they've seen you PHYSICALLY checking the aircraft before flying it.


Q:

is rails like scaffolding possible in django? to perform list, view, edit and delete on database collections

i'm a newbie django developer, trying to build demo pages for my cpp and python programs. i have used ruby-on-rails some years ago.
i wish to know if there is any easy way to display the contents of a database collection on a django application. i'm using mongodb but any other example is fine too. i remember ruby-on-rails, using its scaffolds, provides a readymade solution to manipulate (list, view, edit etc) a database collection. is there a django equivalent?
i have gone through the django_mongodb tutorial to perform such manipulation myself. i mean, by writing the model, view and the template. but wondering how more experienced developers automate this process.
thanks for your help.

A:

If you go through the django tutorial you'll find the answer to your question.


Q:

Error while importing the Java-1.7 project libraries into Android

I've asked a lot of questions the last days, because I couldn't include a .jar-File in my android-project (working with ant).
Today, I switched the Java-Version of this Common-Project to 1.6 and created a new .jar-File.
And noooow, it works!!
Can someone tell me, why Android (2.2) doesn't support Java 1.7?
Thank you!

A:

Because when Android 2.2 was created, there was no Java 1.7.
Compare http://en.wikipedia.org/wiki/Android_version_history against http://en.wikipedia.org/wiki/Java_version_history


Q:

Suggestions for returning memory from a class

I have a class which is supposed to keep pixel data (floats for the position, floats for the color). I'm trying to use a C++ style in data members (the data is kept in std::array<float, N> instead of plain C arrays). The class has other getters, setters and functions meant to be "helpers" to populate these fields.
Now I need to create an OpenGL vertex data buffer where I should write out
  4 floats for xyzw
  4 floats for rgba
  2 floats for UV coords

in this order. I'm wondering how should I do this.. I tried doing
class MyVertexData {
  std::array<float, 4> pos;
  std::array<float, 4> rgba;
  std::array<float, 2> uv;
public:
  void writeData(float *ptrToMemory) {
    if(ptrToMemory == nullptr)
      throw std::runtime_exception("Null pointer");

    std::array<float, 10> output;

    output= {
      pos[0], pos[1], pos[2], pos[3],
      rgba[0], rgba[1], rgba[2], rgba[3],
      uv[0], uv[1]
    };

    memcpy(memory, out.data(), 10 * sizeof(float));
  }
};

// Caller code
std::vector<float[10]> buffer(4);
vertex0.writeElements(buffer[0]);
vertex1.writeElements(buffer[1]);
vertex2.writeElements(buffer[2]);
vertex3.writeElements(buffer[3]);

but this approach has two problems:

I need to trust the caller to have allocated memory to store 10 floats
No C++11+ signature, I just get a float pointer

I can't just return a std::unique_ptr since I need a contiguous memory area (buffer) where the elements are to be stored, but I also need a distinction between the different elements (that would also make the code more readable).
It would be nice to return a smart pointer or something similar whose memory I can easily "concatenate" to other elements so I can safely pass this stuff to OpenGL.

A:

CppCoreGuidelines introduces span which is a view of contiguous element, so you may use something like:
void writeData(gsl::span<float, 10> ptrToMemory)

to express the intend.


Q:

Extracting datetime info from yeardatescalendar in python

import calendar
calendar.Calendar().yeardatescalendar(2014)

>>> [[[[datetime.date(2013, 12, 30), datetime.date(2013, 12, 31),...

The above code returns datetimes for calendar year 2014. However, it also includes the last 2 days of 2013 and firs couple of days for 2015. Is there any way I can just extract the 2014 info?

A:

You can find first and last week and remove datetimes not contains year 2014:
import calendar

c = calendar.Calendar().yeardatescalendar(2014)
#print c

#first week
print c[0][0][0]
[datetime.date(2013, 12, 30), datetime.date(2013, 12, 31), datetime.date(2014, 1, 1), datetime.date(2014, 1, 2), datetime.date(2014, 1, 3), datetime.date(2014, 1, 4), datetime.date(2014, 1, 5)]

#last week
print c[-1][-1][-1]
[datetime.date(2014, 12, 29), datetime.date(2014, 12, 30), datetime.date(2014, 12, 31), datetime.date(2015, 1, 1), datetime.date(2015, 1, 2), datetime.date(2015, 1, 3), datetime.date(2015, 1, 4)]

#filter datetimes by list comprehension
print [x for x in c[0][0][0] if x.year == 2014]
[datetime.date(2014, 1, 1), datetime.date(2014, 1, 2), datetime.date(2014, 1, 3), datetime.date(2014, 1, 4), datetime.date(2014, 1, 5)]

print [x for x in c[-1][-1][-1] if x.year == 2014]
[datetime.date(2014, 12, 29), datetime.date(2014, 12, 30), datetime.date(2014, 12, 31)]

#replace first and last week
c[0][0][0] = [x for x in c[0][0][0] if x.year == 2014]
c[-1][-1][-1] = [x for x in c[-1][-1][-1] if x.year == 2014]

print c[0][0][0]
[datetime.date(2014, 1, 1), datetime.date(2014, 1, 2), datetime.date(2014, 1, 3), datetime.date(2014, 1, 4), datetime.date(2014, 1, 5)]

print c[-1][-1][-1]
[datetime.date(2014, 12, 29), datetime.date(2014, 12, 30), datetime.date(2014, 12, 31)]


Q:

show indexOfObject in UILabel

I am trying to show the number of objects in an NSArray in a UILabel as part of a UITabelViewCell:
UILabel *numberLabel = (UILabel *)[cell viewWithTag:103];
numberLabel.numberOfLines = [self.inputValues indexOfObject:inputValue];
NSLog(@"rownumber is: %d", numberLabel.numberOfLines);

The NSLoggives me the right number, but the label shows just the default title value. What am I missing here? No errors are thrown.

A:

You need to set the label's text property.  Example:
NSUInteger index = [self.inputValues indexOfObject:inputValue];
numberLabel.text = [NSString stringWithFormat:@"Row %lu", (unsigned long)index];

However, it seems likely that you could just use the row from the cell's index path, like this:
numberLabel.text = [NSString stringWithFormat:@"Row %ld", (long)indexPath.row];


Q:

stringByReplacingOccurrencesOfString not working perfectly for Arabic numbers

Its not replacing comma, in case of Arabic language.
    NSString *strAfterReplacingComma = @"٢٠٠٫٠٠";//100.00
    NSString *strAfterReplacing = [strAfterReplacingComma  stringByReplacingOccurrencesOfString:@"," withString:@"."];

    NSLog(@"%@", strAfterReplacing);

Can anyone please help me in solving this?

A:

The comma in your Arabic text (٫) has a unicode number U+002C. It is the arabic decimal separator. Not a comma. The english Comma(,) has a unicode number U+066B. Hence the replace fails.
Use this ٫ instead of , in you stringByReplacingOccurrencesOfString.