text:
Q: JQuery Autocomplete Widget - Up & Down Arrow Keys not working I am new to Jquery and was going through a snippet of code of a larger application (which we have outsourced). This snippet is a jquery widget to autocomplete results.
On the HTML page, we have a search box. When the user enters some keystrokes, a search is performed (for places and events) on our database and the results are shown in an un-ordered list. The results show up fine. However, I was hoping to scroll through the results using the down and up arrow key which does not seem to work.
Opening the Developer Tools in Chrome, when I press the Down key the following error is reported
Uncaught TypeError: Cannot read property 'value' of undefined  jquery-ui.min.js:8

The relevant Widget code is as follows
$.widget("custom.catcomplete", $.ui.autocomplete, {
    _renderMenu: function(ul, items) {
        ul.addClass('search-box');
        var that = this;
        var i = 0;
        var j = 0;
        var index = 0;
        $.each(items, function(index, item) {
            if (item.Space && i == 0) {
                ul.append('
 Parking Space
');
                i++;
            }
            if (item.Event && j == 0) {
                if (i > 0) {
                    ul.append('See All Result');
                }
                ul.append('
 Venues
');
                j++
            }
            that._renderItemData(ul, item);
        });
        if (j == 0 && items.value == 'error') {
            ul.append('See All Result');
        }
    }
});

$(function() {
// made on 01-07-2015
$("#search_new").catcomplete({
    delay: 0,
    //minLength: 2,
    zIndex: 9999,
    source: base_url + "searches/index.json",
    messages: {
        noResults: '',
        results: function() {}
    },
    select: function(event, ui) {
        window.location = (ui.item.url);
    }
}).off('blur').on('blur', function() {
    if(document.hasFocus()) {
        $('ul.ui-autocomplete').show();
    }
});
});

$.ui.autocomplete.prototype._renderItem = function(ul, item) {
if (item.Space) {
    var space_body = '';
    var address2 = (item.Space.address2 != null) ? item.Space.address2 : '';
    space_body = space_body + "
"+item.Space.name+" - "+item.City.name+"
"+item.Space.flat_apartment_number+", "+item.Space.address1+", "+address2+" "+item.City.name+"
";
    console.log("In _renderItem");
    return $(ul).append(space_body)
    .appendTo(ul);
}

if (item.Event) {
    var event_body = '';
    event_body = event_body + "
"+item.Event.event_name+"
"+item.EventAddress.address+" "+item.City.name+"
";

    return $(ul).append(event_body)

    .appendTo(ul);
}

if (!item.Space && !item.Event) {
    return $(ul).append("
No records found. Click here to get notification for your keyword.
")

    .appendTo(ul);
}

}
From my limited understanding of JQuery Widgets :
For each result received we are appending to a ul and calling renderItemData which in turn calls the renderItem
I am unable to understand which 'value' is the code referring to.


text:
Q: How can I make a convex catenoid (minimum surface of revolution that closes on -1 and 1? In Wolfram MathWorld I see the catenoid (minimum surface of revolution which is concave and open ended, but I want the one where the sides are convex and close on the long axis (say z) at -1 and 1.
I want to start with the "rope-hanging" catenary of the hyperbolic cosine and also show the exp functions for e that average on the cosh x, as if the catenoid function is defined in a 3d exp field forming a space around the axis.
Then I think there is an interesting relation between the surface area and volume, because of the interesting derivative properties on the cosh x function.
I'm hope this is simple modification of the concave equations. This figure shows my general idea. Here I moved the exp function to the endpoints because it is less confusing.

A: I am writing this answer to address a misconception you seem to have.
First, let us generate a general formula for your surface of revolution. The idea is to rotate the shifted catenary $y=k+\cosh x$ over the $x$-axis, with the shift $k$ determining the appearance of the surface of revolution:
catrev[k_, {x_, θ_}] := {x, (k + Cosh[x]) Cos[θ], (k + Cosh[x]) Sin[θ]}

In particular, the cigar-shaped surface you imply in the OP corresponds to the value k = -Cosh[1]:
ParametricPlot3D[catrev[-Cosh[1], {x, θ}], {x, -1, 1}, {θ, 0, 2 π}]

Let us determine the surface area and volume of a generalization of these "cigars", by first letting $k=-\cosh h$.
(* surface area *)
Assuming[h > 0,
         RegionMeasure[{x, (Cosh[x] - Cosh[h]) Cos[θ], (Cosh[x] - Cosh[h]) Sin[θ]},
                       {{x, -h, h}, {θ, 0, 2 π}}]]
   π (-2 h + Sinh[2 h])

(* volume *)
Assuming[h > 0,
         Volume[{x, c (Cosh[x] - Cosh[h]) Cos[θ], c (Cosh[x] - Cosh[h]) Sin[θ]},
                {c, 0, 1}, {x, -h, h}, {θ, 0, 2 π}]]
   π (2 h + h Cosh[2 h] - 3 Cosh[h] Sinh[h])

I think there is an interesting relation between the surface area and volume...

I'm not seeing a particularly simple one, myself.

Now, for your misconception. A minimal surface is a very specific concept in differential geometry; it refers to a surface with zero mean curvature. Qualitatively speaking, minimal surfaces will be either flat like the plane, or concave almost everywhere. Your proposed cigars fit neither of these appearances.
More concretely, let's determine the mean curvature of the surface of revolution constructed above:
MeanCurvature[f_?VectorQ, {u_, v_}] :=
  Simplify[(Det[{D[f, {u, 2}], D[f, u], D[f, v]}] D[f, v].D[f, v] -
            2 Det[{D[f, u, v], D[f, u], D[f, v]}] D[f, u].D[f, v] +
            Det[{D[f, {v, 2}], D[f, u], D[f, v]}] D[f, u].D[f, u])/
           (2 PowerExpand[Simplify[(D[f, u].D[f, u] D[f, v].D[f, v] -
                                    (D[f, u].D[f, v])^2)]^(3/2)])]

(definition taken from here)
With that,
MeanCurvature[catrev[k, {x, θ}], {x, θ}]
   -((k Sech[x]^2)/(2 (k + Cosh[x])))

and it is clear that this can only be zero if k == 0, which is exactly the catenoid case.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to list installed plugins & extensions in web browser using javascript? How to check extensions & plugins installed in client's browser?
I've tried chrome API, and also chrome extensions, but I wasn't able to get it...


text:
Q: Cocoa swift load ViewController and and storyboard view from AppDelegate I have created a SideBar() class which creates a NSView with various buttons.
I instantiate my sideBar() in my AppDelegate by doing
func applicationDidFinishLaunching(_ notification: Notification) {
    sideBarView.setupSideBarView()
    sideBarView.menuButton.action = #selector(self.NewMenuButton(_:))

}
@objc func NewMenuButton(_ sender: NSButton) {

}

In my Initial ViewController I then present my sideBar in the following way:
view.addSubview(sideBarView.getView())

With the press of menuButton I would like the function in the App Delegate to load and present a new storyboard view with its ViewController.
Can this be done?
Thanks.

A: I solved the issue giving my second ViewController a storyboard id.
Then, through the AppDelegate function:
 let storyboard = NSStoryboard(name: NSStoryboard.Name("Main"), bundle: Bundle.main)
 let mainPageController = storyboard.instantiateController(withIdentifier: "test") as! SecondViewController
 NSApplication.shared.mainWindow?.contentViewController = mainPageController


text:
Q: xcode distributing application with 2 project i have a problem to distributing application with 2 project (one project with sub-project include inside). When i try to make as usual "archive", i'm not able to send application.
Could someone help me?
Regards

A: I'm guessing the sub-project is a library? And when you do Build > Archive you get an .xcarchive file instead of a .ipa? If so, you need to set the Skip Install flag to No on your library (see this answer), then Build > Archive will generate a .ipa file.

A: The reason this is happening is because you have two projects.
For the sub-project you need to edit the Target > Build Settings and set the Skip Install setting to Yes.
Afterwards the "Archive" action will work as usual.


text:
Q: A Bernoulli differential equation The differential equation is
$$y'(x)=\alpha \, y(x)-\beta \, y^2(x)$$
If I understand this correctly, the condition is $y \ne 0$ means $y$ might be the parameter of another function like $\alpha$ here could be a $\sin$ function. Is my understanding correct?
This looks like it can be solved using Bernoulli's method. But I'm just quite unsure. Someone gives me a hint?

A: Hint:
Do separation of variables
$$\int \frac{dy}{ay-by^2}=\int dx$$

A: Consider letting $y = \frac{1}{f}$ in the differential equation
$$ y^{'} = \alpha \, y - \beta \, y^2 $$
to obtain the differential equation
$$ f^{'} + \alpha \, f = \beta. $$
This equation can then be seen to admit the following solution:
\begin{align}
f' + \alpha \, f &= \beta \\
e^{- \alpha \, x} \, \frac{d}{dx} \left( e^{\alpha x} \, f\right) &= \beta \\
e^{\alpha \, x} \, f &= \frac{\beta}{\alpha} \, e^{\alpha x} + c_{0} \\
f(x) &= \frac{\beta}{\alpha} + c_{0} \, e^{- \alpha \, x}.
\end{align}
This yields
$$ y(x) = \frac{\alpha}{\beta + c_{0} \, \alpha \, e^{- \alpha \, x}}. $$


text:
Q: SQL union seems to fail for me I haven't done any SQL queries in years.
I ran into an issue that looks to me pretty straightforward, but I cannot seem to solve it in reasonable time.
Let's say that I have two tables that I pull from the database using the select statement:
    table1:
    id name    status
    1  record1 ACTIVE
    2  record2 ACTIVE

    table2:
    id name    status
    1  record3 DELETED
    2  record1 DELETED

I would like to have the third table that looks like this:
    table3:
    id name    status
    1  record1 ACTIVE
    2  record2 ACTIVE
    3  record3 DELETED

So basically, if the column is present in the "ACTIVE" table, it must be shown in the third one (table3) as ACTIVE regardless of the column that has the same name in "DELETED" table. Also, if the column with specific name is present in the "DELETED" table, but not in the "ACTIVE", it should be shown too as DELETED.
I hope I've explained the issue clearly enough.
It's my first time posting on stackoverflow, and I hope I'll get some help from you guys.
Thanks! :-)

A: I think you want:
select a.*
from actives a
union all
select d.*
from deletes d
where not exists (select 1 from actives a where a.name = d.name);


text:
Q: Unknown error in C# when writing an If statement I am trying to write an If statement in C# where the user is asked to input the age, the program prints the age and if the user is eligible to cast the vote, where the age limit is 18.
When running the code in Visual Studio there are no errors, but on the platform where I am doing the exercise I have an error printed:

Incorrect output: your program printed "18", but should have printed "18"

It will be much appreciated if you could only point out the mistake (if any).
static void Main(string[] args)
{
    int age;
    Console.Write("Please input your age: ");
    age = Convert.ToInt32(Console.ReadLine());
    Console.Write(age);
    Console.Write("\n");

    if (age < 18)
    {
        Console.Write("You cannot cast your vote!");
    }
    else
        Console.Write("You can cast your vote!");
    {

    }
}

A: I don't think the error is with your code, it might be with the platform evaluating the answer.
That said, a few pointers:
The brackets after the else can be removed or the code needs to be moved between the brackets.
These 2 lines:
Console.Write(age);
Console.Write("\n");

can be changed to:
Console.WriteLine(age);

alternatively the line:
Console.Write("\n");

can be:
Console.Write("\r\n");

The error might be down to the platform that is evaluating the answer. (online ?)
I don't know how exactly those platforms work, but if you take the code below:
 TextReader tr = Console.In;
 char[] buffer = new char[4];
 tr.Read(buffer, 0, 4);
 string consoleOutput = new string(buffer);
 if (consoleOutput != 18.ToString())
 {
   Console.WriteLine($"Expected 18, you entered {consoleOutput}");
 }

When entering 18 the result comes back as 18/r/n as shown in this image:

and this will also give you the output Expected 18, you entered 18


text:
Q: mkdir function throw exception 'File exists' even after checking that directory doesn't exist I stumbled upon a every strange behaviour with mkdir function in PHP. Below is an example of my simple code.
$filepath = '/media/static/css/common.css';
if (!file_exists(dirname($filepath)))
{
   mkdir(dirname($filepath), 0777, TRUE);
}

'media' folder always exists. All folders into the 'media' folder have to be created. Before coping the common.css file I'd like to create a folder '/static/css'.
mkdir OCCASIONALLY throw  exception "File exists". I tried to create a folder if it doesn't exist. 'File exists' is a common error, I assume, so the folder exists.
I understand that there is a very little info I gave you and it is really strange error. Maybe you can give me any advice what I have to do and how I can test that bug and find the bottleneck.
Server: CentOS release 6.4
Thank you.

A: This is a race condition situation. You should do something like that :
$filepath = '/media/static/css/common.css';
// is_dir is more appropriate than file_exists here
if (!is_dir(dirname($filepath))) {
    if (true !== @mkdir(dirname($filepath), 0777, TRUE)) {
        if (is_dir(dirname($filepath))) {
            // The directory was created by a concurrent process, so do nothing, keep calm and carry on
        } else {
            // There is another problem, we manage it (you could manage it with exceptions as well)
            $error = error_get_last();
            trigger_error($error['message'], E_USER_WARNING);
        }
    }
}

ref :

*

*https://www.drupal.org/files/1642532-drush-mkdir-race-condition.patch

*https://github.com/KnpLabs/Gaufrette/blob/master/src/Gaufrette/Adapter/Local.php#L260

*https://github.com/symfony/symfony/commit/04834521f1298c8fee2704b1c4b1df43b655eb60


text:
Q: Cannot get link to display in js quiz results In the "explanation" section of the quiz answers, I'm trying to include a link but the html always gets stripped out.
This is at line 446 of the .js file:
$('#quiz-form').append('
Correct answer(s): ' + answer + ' » Explanation: ' + special + '
');

I've tried every variation of linking and escaping I can find but they all just show the title as plain text. Here's what I've tried, these are currently in the explanation sections for each of the first six questions:

*

*special: "title"

*special: "title"

*special: "title"

*special: "title"

*special: "title"

*special: "title"
Unfortunately, there's no way to link directly to the answer page - you have to get the first six questions wrong in order to see the explanation as shown in the screenshot.
ETA: Now I'm encoding the angle brackets and the entire a href string is showing as text.
special: "<a href='URL'>title</a>"

is showing as
Introductions

Progress?
https://www.lawlessfrench.com/quizzes-and-tests/proficiency-test-1/
https://www.lawlessfrench.com/wp-content/themes/cassie/js/proficiency-test-1.js

A: Hm, worked for me in a jsFiddle.  Maybe the problem is that your jQuery version is so old, or maybe the browser or jQuery are trying to prevent XSS attacks.
Try changing
special = value.special;

to
special = $('' + value.special + '').html();


text:
Q: insertion, selection, bubble sorting analysis with inversion Robert Sedgewick I am reading algorithms by Robertsedwick by C++ on sorting

Property 1: Insertion sort and bubble sort use a linear number of
  comparisions and exchanges for files with at most a constant number of
  inversions corresponding to each element.

In another type of partially sorted file, we perhaps have appended a few elements to a sorted file  or have edited a few elements in a sorted file to change their kesy. Insetion sort is efficient menthod for such files; bubble and selection sort are not.

Property 2: Insertion sort uses a linear number of comparisions and
  exchanges for files with atmost a constant number of elements having
  more than a constant number of corresponding inversions.

My questions on above properties are

*

*I am not able to get difference between property 1 and property 2? Can any one explain me here?

*On what basis above for property 2 author mentioned insertion sort is best and not bubble and selection sort?
It would be good if explained with example.
Thanks for your time and help

A: So, an inversion where the sort order is < is there i < j but a[i] > a[j].

*

*Property 1. Consider the sequence 2 1 4 3 6 5 8 7 10 9.... Every element is out of order with respect to its neighbor to the left or to the right, but is in order with respect to all other elements. So each element has a constant number of inversions, one, in this case. This property says that all the elements can be a little out of order.
Both bubble sort and insertion sort will run in linear time. Bubble sort will take just one pass to correct the order since it swaps neighboring elements and another pass to confirm. Insertion sort will only have to do one compare and swap per element.

*Property 2. This property is stronger. In addition to being able to have all the elements a little out of order, now you can have a few that are very out of order. Consider the same sequence as before, but the smallest element and largest elements moved to opposite ends: n 2 4 3 6 5 8 7 10 9...1. Now 1 and n are out of order with respect to all other elements.
Insertion sort will still perform in linear time. As before, most of the elements require only a few compare and swaps, but there are a few that can take order n compare and swaps. In this example, the first n-1 elements take a couple of compare and swaps (ok, so the 2 only takes one) to get into place and the last takes n-1 compare and swaps -- 2*(n-1) + 1*(n-1) is order n.
Bubble sort has a much harder time in this example. Each pass through can only move the 1 a single step backwards. Thus it will take at least (n-1) passes in which (n-1) comparisons are done before completion -- this is multiplicative (n-1)*(n-1) is order n^2. (You could also run bubble sort in the opposite direction, in which case the largest element at the beginning would slowly move to the other end instead.)


text:
Q: Is it possible to specifiy a sorting criteria within a kubernetes horizonal pod autoscaler to define which pods are chosen to terminate? I have some HPAs defined within a Kubernetes cluster and the scaling functionality works as expected. However, I've observed that the choice of specific pods that are chosen to be scaled down seems pretty arbitrary.
So the question is. Can I somewhere define criteria to choose which pods are preferred to be terminated when a scale-down event happens, but without explicitly defining that the pods are actively scaled on that criteria?
For example, I mainly care about CPU and scale such that the CPU percentage is maintained at 50% or less, but when scaling down would prefer that older pods are preferred to be terminated rather than newer ones, or pods consuming the most memory be terminated in preference to those consuming less memory.
I'm aware that I can explicitly scale on multiple criteria like CPU and memory, but this can be problematic and prevent downward scaling unnecessarily for example when memory is allocated to a cache but CPU usage has decreased.

A: As per this official doc  You can add the annotation controller.kubernetes.io/pod-deletion-cost with a value in the range [-2147483647, 2147483647] and this will cause pods with lower value to be killed first. Default is 0, so anything negative on one pod will cause a pod to get killed during downscaling.
Find this gitlink  about the implementation of this feature: Scale down a deployment by removing specific pods (PodDeletionCost) #2255.
You can also use Pod Priority and Preemption. Refer to this official doc for more information


text:
Q: How do I create a correctly scaled x-axis? I'm using HighCharts line plots where my x-axis data is unevenly distributed:
[4, 10, 40, 100, 400, 1000, etc.]

Currently the x-values are placed evenly.  I want the distance between x[5] and x[4] to be 10 times that between x[3] and x2.  How do I do this?

In the GoogleCharts lingo, I need a continuous axis.

In the docs, I only see "linear", "logarithmic", and "datetime" for the axis type.  ("linear" is the default and does not do what I want).

A: Since you didn't post your javascript generating the charts I'll have to guess, but I assume you are using categories within your xAxis. The categories are evenly distributed, so don't use them in this case.
If you change your series data block to specify x and y values (http://www.highcharts.com/ref/#series--data example 2) the xAxis will show correct proportions for your values. For example look at this fiddle.


text:
Q: Does perl have an internal function to unquote a variable? It is not uncommon that a parameter is passed a few times.
Here is an interesting example of losing the quote can actually helps.
The first abs() return a variable without quote, making the second abs return
the correct value.
My question is:
Does perl have an internal function to unquote a variable so that I do not have to code this way?
#!/usr/bin/perl -w
use strict;
my @nums = (
    '-0',
    '-0.0',
    "-0.000",
    qw(-0.000),
    sprintf("%.4f", "-0.0"),
);

print "***use single abs()\n";
foreach my $num(@nums){
    my $number = $num;
    my $abs = abs($number);
    print "<$num> abs <$abs>\n";
}

print "\n***use abs(abs())\n";
foreach my $num(@nums){
    my $abs_abs = abs(abs($num));
    print "<$num> double abs <$abs_abs>\n";
}

System information:
uname -r
2.6.32-573.12.1.el6.centos.plus.x86_64
This is perl, v5.10.1 (*) built for x86_64-linux-thread-multi

The screen output:
***use single abs()
<-0> abs <0>
<-0.0> abs <-0>
<-0.000> abs <-0>
<-0.000> abs <-0>
<-0.0000> abs <-0>

***use abs(abs())
<-0> double abs <0>
<-0.0> double abs <0>
<-0.000> double abs <0>
<-0.000> double abs <0>
<-0.0000> double abs <0>

A: That's not an issue with quotes -- the quotes are just Perl syntax to tell the interpreter where a string begins and ends. Perl knows that the value being stored is a string, but the quotes themselves are not stored in memory.
Rather, it's an artifact of the special floating point value "-0.0". For almost any use, it is equivalent to the value 0.0
perl -E ' $p = 0.0; $n = -0.0; say $p == $n '                    ==> 1
perl -E ' $p = 0.0; $n = -0.0; $x = 4.2; say $p+$x == $n+$x '    ==> 1

The two exceptions, as far as I can tell, are their binary representation and their string representation.
$ perl -e 'print pack "F",0.0' | od -c
0000000  \0  \0  \0  \0  \0  \0  \0  \0
0000010
$ perl -e 'print pack "F",-0.0' | od -c
0000000  \0  \0  \0  \0  \0  \0  \0 200
0000010

$ perl -MDevel::Peek -e 'Dump($n=-0.0),Dump($p=0.0)'
SV = NV(0x43523d8) at 0x434ff00
  REFCNT = 1
  FLAGS = (NOK,pNOK)
  NV = -0
SV = NV(0x43523e0) at 0x4329b58
  REFCNT = 1
  FLAGS = (NOK,pNOK)
  NV = 0

$ perl -E '$p=0.0; $n=-0.0; say for $p,$n'
0
-0

(actually, with Perl v5.12 I see 0,-0 but with v5.16 it is 0,0 -- maybe somebody noticed this and fixed it)
The integers 0 and -0 do not have this issue.
abs(-0.0) returns the integer 0, and so it really by accident that abs appears to resolve this "quoting" issue.


text:
Q: How do you fix Specflow "" issue in Visual Studio Background
I have been working on a project and noticed that one of my Specflow Scenarios needed updating.
I updated the Specflow Scenario by splitting it into two different scenarios (one for an invalid test and one for a valid test).
After this I then regenerated the feature.cs file, cleaned and rebuilt the solution.
(I am using Microsoft Visual Studio Enterprise 2019 Version 16.4.1)

Issue
This is when the "unknown project" appeared in my Test Explorer that consists of one test... the one I have changed. It cannot be run, however it cannot be removed either.
Here is what I am seeing:

The only way I have been able to get rid of this, for a brief period at least, is by deleting my entire solution and then pulling it back down again, which is less than ideal.
Here is a list of what I have tried to resolve this;

*

*Updated all Nuget packages within the solution to the latest versions.

*Restarted Test Explorer

*Restarted Visual Studios

*Deleted feature.cs files and regenerated

*Cleaned and rebuilt solution

*Updated Visual Studios (this seems to have made the situation appear more often)

*Deleted the solution and pulled it back down (this works until I have to change an existing test and then restarted Visual Studios)

Has anyone seen this before, or know how to fix this?

A: So after a day of trying to figure this out with my team we have finally resolved the issue.
The issue was caused by the cached (hidden) .vs file. When deleting this and restarting the solution the unknown project was gone.


text:
Q: Get states of a country in Android Is it possible to get a list of all states when the user selects a particular country from the Locale class of Java ? I was able to get the list of all countries from Locale class. But the Locale class does not provide the states. Is their any other way ? or is there a web service which I could make use of ?
Any help will be appreciated. Thanks in advance :)

A: Other than using a google maps API which would probably require you to have a full time connection... There is a dataset with all locals called GeoNames. Which you could use in a SqLite database.

A: Try this :
    import java.text.Collator;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.List;
    import java.util.Locale;

    public class Country  {

    public void getCountries{
    List<Country> countries = new ArrayList<Country>();

    Locale[] locales = Locale.getAvailableLocales();
    for (Locale locale : locales) {
      String iso = locale.getISO3Country();
      String code = locale.getCountry();
      String name = locale.getDisplayCountry();

      if (!"".equals(iso) && !"".equals(code) && !"".equals(name)) {
        countries.add(new Country(iso, code, name));
      }
    }

    Collections.sort(countries, new CountryComparator());
    for (Country country : countries) {
      System.out.println(country);
    }
  }
}

class CountryComparator implements Comparator<Country> {
  private Comparator comparator;

  CountryComparator() {
    comparator = Collator.getInstance();
  }

  public int compare(Country o1, Country o2) {
    return comparator.compare(o1.name, o2.name);
  }
}

class Country {
  private String iso;

  private String code;

  public String name;

  Country(String iso, String code, String name) {
    this.iso = iso;
    this.code = code;
    this.name = name;
  }

  public String toString() {
    return iso + " - " + code + " - " + name.toUpperCase();
  }
}


text:
Q: What is and is not a user story? I have an issue at work where we have just started using scrum as a development team. I am having some trouble with the user stories we are provided with in that they don't seem to fit what my interpretation of what a user story is.
Here is an actual example of the user stories we have been given for this sprint:

*

*As a website user I want to have a registration page so that I can register and supply my details.

*As a merchant user I want have validation on the registration form so that I provide the correct information. (This relates to Form Validation)

*As a merchant user I want support when registering so that any questions that i have about the required details are answered. (This relates to Tool tips on the form)
The first one in my mind is the user story. The second two seem to be traditional requirements of the first user story and I think they should probably be acceptance criteria of the first user story.
The other confusion I have is in the last sprint we had:

*

*As a user I want to be able to login to the website.

*As a user I want to be able to login to the website with a username.
The Product Owner says this is two different user stories which need to be tested separately.
My issue is that in creating test cases and acceptance criteria for the second two - it is difficult as they are so specific and so related to the first user story. It seems that we are just putting up traditional requirements on a card up on a board and calling it something else. I mainly just want to know if I am wrong about this / why?
It just seems to me that we are currently just letting the users create whatever they want as a user story and not helping them filter them from requirements into proper user stories. I am told we need to keep them all separate for reporting so we can keep a log of everything the user requests.

A:
User stories focus on customer value. ... The actual work being done is fleshed
out via collaboration revolving around the user story as system
development progresses. ... In order to limit scope, user stories have
collaboratively developed acceptance criteria which define when the
user story meets the stakeholder's expectations.  Test cases are often
developed as code (with test driven development) or documented as the
code is developed.

[Emphasis mine.]

As a user I want to be able to login to the website.
As a user I want to be able to login to the website with a username.

Since neither provides any customer value, neither are user stories.
You use application software to manage information, make decisions and (ultimately) take an action.  If the user story doesn't provide some hint as to what information, decision or action gets taken, there's no customer value, it's just technical folderol -- implementation details that a customer has to endure to get to the interesting part of the application.
Login, specifically, has zero customer value.  It's a roadblock that IT erects between customers and the valuable information they need to make decisions and take actions.  It's a security mechanism, and most people do not actually like security.  Security is imposed on customer by IT.  The most popular password (IIRC) is "aaaaaaaa".  Why?  Customers don't like security.
Detailed, microscopic login user stories may be a symptom of failing to see the real value to the customer.

It just seems to me that we are currently just letting the users create whatever they want as a user story

Good.

I am told we need to keep them all separate for reporting so we can keep a log of everything the user requests.

Not a bad plan, really.
The issue is to separate "crap the user happened to say" from "stuff that makes sense that we can build".  It's very, very important to allow the users to say any crap they want to say.  It's a good thing to let them ramble.
Periodically (before each sprint) you will prioritize crap the user said into a few things that (1) you might be able to build during the sprint, and (2) create the most significant and dramatic user value you can possibly create.  Some stories will get ignored.  Some will be low priority.  Some will  be combined and some will be split.  Some things the user said will be contradictory.  Some will be outright lies.  Some will be incomplete.  It's all good.  It's just crap the user happened to say.  Not divine directives from the mouths of the gods directly to you.
This revised set of user stories drives the sprint.  Now you start collaborating with the users to get the details, write test cases, define acceptance, etc., etc.
As you're sprinting toward delivery, the users can continue to say crap that will get appended to the backlog of unimplemented user stories.  It's very, very important to allow the users to say any crap they want to say.  It's a good thing to let them ramble.


text:
Q: executing (refreshing) a php file that is included on some page Suppose if I have a PHP file test.php which includes 2 other
<?php
include 'input.php';

include 'output.php';
?>

Input.php is a form with 1 button on it. Currently when clicking on that button I am executing the whole test.php file and output.php gives me the results I want.
I am using something similar to this:
<form action="test.php" method="POST">
.
.
.
</form>

But I don't want whole test.php to be executed, because that way I reset all input values in input.php.Can I execute just the output.php but display it on test.php?

A: You have to use the AJAX and then refresh only the snippets you want to refresh.
But you would have to have some handler which will solve the form submit and then will return the result.
AJAX example (using jQuery):
add id to the form
<form action="test.php" id="form" method="POST">

$('#form').onsubmit(function(event) {
  event.preventDefault();
  data = $(this).serialize()
  $.ajax({
    type: "POST",
    url: "handler.php",
    data: { data: data }
  })
  .done(function( data) {
    //refresh data snippet
  });
)};

Ref: http://api.jquery.com/jquery.ajax/


text:
Q: Ignore Sleep/Hibernate button press using C#/WPF Is there a way to stop system from going to sleep/hibernate mode when user presses e.g. laptop's or tablet's power button or chooses sleep/hibernate from Windows' menu? I've been trying to implement this by using WndProc and Windows' power messages but no luck. Here's the code that I've been using. I also tried to return BROADCAST_QUERY_DENY as IntPtr but no luck.
protected override void OnSourceInitialized(EventArgs e)
{
    base.OnSourceInitialized(e);
    HwndSource source = PresentationSource.FromVisual(this) as HwndSource;
    source.AddHook(WndProc);
}

private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
    if (msg == 0x218) // WM_POWERBROADCAST.
    {
        if (wParam.ToInt32() == 0x4) // PBT_APMSUSPEND.
        {
            handled = true;
        }
    }
    return IntPtr.Zero;
}

I've also tried PowerCreateRequest and PowerSetRequest but no luck there either.
I have managed to prevent Windows from shutting down by using Microsoft.Win32.SystemEvents.SessionEnding and I thought that this handles power management messages too but I was wrong. :)


text:
Q: Terminal based application with curl I'm planning to do website that is terminal-accessible only (through curl)
My plan is to make interface pretty much like wttr.in
So what exactly should my backend return to support curl command in terminal? Is it plaintext response? What should I focus on to support all types of terminals? (maybe with ommiting the powershell as I read that it has some problems with curl and wttr.in especially)


text:
Q: How to run an expression to a image collection in google earth engine // Convert the image List to an ImageCollection.
var lsCompCol = ee.ImageCollection.fromImages(lsCompList);
print('finaldataset',lsCompCol);
Map.setCenter(72.91,19.13);
var lsCompCol = lsCompCol.select(
    ['B2_median', 'B3_median', 'B4_median','B5_median','B6_median','B7_median']);

// A function to compute awei.
var awei =function(image) {
image = ee.Image(image)
return image.addBands(image.expression(
  '(4*(blue-swir1))'-'((0.25*nir)'+'(2.75*swir2))',{
  'blue':image.select(['B2_median']),
  'swir1':image.select(['B6_median']),
  'swir2':image.select(['B7_median']),
  'nir':image.select(['B5_median'])
}).rename (awei).clamp(0,1));
}
lsCompCol = lsCompCol.map(awei);
var check = ee.Image(lsCompCo.first());
Map.centerObject(check);
Map.addLayer(check);

I get an error as invalid argument specified for ee.List(): function awei(_0) {
   return newF.apply(this, arguments);

Please help me how I can put an expression on my image collection dataset to use it further. Thanx in advance.


text:
Q: How can you combine GeoJson features by their property value? TLDR: Can you join together GeoJSON features that have a common property, such that the final polygon is a combination of the smaller features?
I'm building a web application that requires me to modify some existing GeoJSON by removing lines between counties, essentially creating larger polygons out of smaller ones. Here's what the GeoJSON looks like:
{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "feature",
      "geometry": {
        "type": "MultiPolygon",
        "coordinates": [[[[ ..some coordinates ]]]],
      },
      "properties": {
        "joiner": 1,
        "PUMA": "Alameda County"
      }
    },
    {
      "type": "feature",
      "geometry": {
        "type": "MultiPolygon",
        "coordinates": [[[[ ..some coordinates ]]]],
      },
      "properties": {
        "joiner": 2,
        "PUMA": "San Jose County"
      }
    },
    {
      "type": "feature",
      "geometry": {
        "type": "MultiPolygon",
        "coordinates": [[[[ ..some coordinates ]]]],
      },
      "properties": {
        "joiner": 1,
        "PUMA": "Fremont West"
      }
    },
  ]
}

In this dummy example, I'd like to join together Alameda County and Fremont West, because they both contain the "joiner" property of 1 (they are next to each other, this is a given). Visually speaking, this would mean that certain adjacent polygons on the map would be joined into a single polygon.
This is what the data currently looks like when projected using MapboxGL:

The final projection would join together adjacent polygons with a common property and remove the dividing lines, creating larger ones:

A: You can use Turf's "dissolve" method, which does exactly this:
var dissolved = turf.dissolve(features, {propertyName: 'joiner'});

Documentation: http://turfjs.org/docs/#dissolve


text:
Q: Ubuntu 12.10 USB Graphics Compatibility I was looking at solutions to connect 2 monitors to 1 USB port and found these:
1) http://www.targus.com/us/productdetail.aspx?regionId=7&sku=ACA039US
2) http://www.startech.com/AV/USB-Video-Adapters/USB-3-to-HDMI-DVI-External-Video-Card~USB32HDDVII
These are both displaylink. I have heard that displaylink docks do not work but adapters do. Since these have 2 outputs, I wasn't sure if they are compatible with Ubuntu 12.10. Any Help? If these won't work what will?
Thanks

A: So, what I found when using a DisplayLink USB monitor is that I could start X on the monitor fine, because DisplayLink has support in the kernel, but I (1) couldn't use my graphics card's acceleration, (2) couldn't easily have the display extend from one regular monitor to the DisplayLink. I was able to eventually get it working, sort of, using screenclone but I couldn't move windows between monitors, get compositing to work, or use xrandr at all. See these questions for some details on setting it up:

*

*How do I use a DisplayLink monitor?

*How do I configure a displaylink USB monitor?
It looks like there is a project to get this working better called hybrid-screenclone which will make it easier to do some of the hacks I described.
Ultimately, I would advise against a DisplayLink setup unless you're willing to try some hacks and experimental proding, and still possibly be let down. Though the chances if you getting it working if you don't want to also use a regular monitor are much better.


text:
Q: AWS signed cookies authentication not working php (AccessDeniedAccess denied) I am trying to access static content from my s3 bucket using AWS CloudFront. I am able to access that content using signed URL but when I am trying to use AWS signed cookies authentication it is giving me AccessDeniedAccess denied error.
I have double check my CloudFront and S3 bucket configuration. But it seems perfect.
I am using Custom SSL certificate for my CloudFront and canned policy to access the content.
<?php
getSignature("http://cdn.******.ca", 300000);
echo '<html>
      <head></head>
      <body>
        <iframe src="https://cdn.****/file.pdf">
      </body>
      </html>';

function getSignature($resource = null, $expires = null, $policy = null)
    {

        $keyPairId = 'AP*****';

        $signatureHash = array();
         if ($policy) {
            $policy = preg_replace('/\s/s', '', $policy);
            $signatureHash['Policy'] = encode($policy);
            header ( "Set-Cookie: CloudFront-Policy=".$signatureHash['Policy']."; path=/; domain=***.ca; httpOnly", false );
            }
         elseif ($resource && $expires) {
            $policy = createCannedPolicy($resource, $expires);
            $signatureHash['Expires'] = $expires;
            header ( "Set-Cookie: CloudFront-Expires=".$signatureHash['Expires']."; path=/; domain=***.ca; httpOnly", false );
            }
         else {
           return false;
        }

        $signatureHash['Signature'] = encode(sign($policy));
        header ( "Set-Cookie: CloudFront-Signature=".$signatureHash['Signature']."; path=/; domain=***.ca; httpOnly", false );
        $signatureHash['Key-Pair-Id'] = $keyPairId;
        header ( "Set-Cookie: CloudFront-Key-Pair-Id=".$signatureHash['Key-Pair-Id']."; path=/; domain=***.ca; httpOnly", false );

        return $signatureHash;
    }

    function createCannedPolicy($resource, $expiration)
    {
        $json = '{"Statement":[{"Resource":"'.$resource.'","Condition":{"DateLessThan":{"AWS:EpochTime":'.$expiration.'}}}]}';
        return $json;
    }

    function sign($policy)
    {
    $signature = '';
        $privateKey = 'path/pk-APK***.pem';
        $fp=fopen($privateKey,"r");
        $priv_key=fread($fp,8192);
        fclose($fp);

        $key = openssl_get_privatekey($priv_key);
    openssl_sign($policy, $signature, $key);
        return $signature;
    }

    function encode($policy)
    {
        return strtr(base64_encode($policy), '+=/', '-_~');
    }
?>


text:
Q: PictureBox Drag and Drop to MS Word I have created an app with a flowlayoutpanel of pictureboxes. I have implemented drag and drop based on the original code found here:
https://social.msdn.microsoft.com/Forums/en-US/4436369c-eae2-4994-bb64-3c51ada96f07/dragn-drop-from-a-picturebox-to-word?forum=vblanguage
which is, in turn, based on:
http://groups.google.co.uk/group/microsoft.public.win32.programmer.gdi/browse_thread/thread/197b47c39f8ad2c8/e2e4b88de9f83d3a
 Private Sub P_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) Handles P.MouseDown
        ' see
        ' http://groups.google.co.uk/group/microsoft.public.win32.programmer.gdi/browse_thread/thread/197b47c39f8ad2c8/e2e4b88de9f83d3a
        Dim ms As New MemoryStream
        Dim ms2 As New MemoryStream
        Dim theformat As ImageFormat

        Dim pb = DirectCast(sender, PictureBox)

        Dim ext As String = Path.GetExtension(pb.Tag)

        Select Case ext

            Case ".png"
                theformat = ImageFormat.Png
            Case ".jpg"
                theformat = ImageFormat.Jpeg
            Case ".gif"
                theformat = ImageFormat.Gif
            Case Else
                Return
        End Select

        pb.Image.Save(ms, theformat)
        pb.DoDragDrop(pb.Image, DragDropEffects.Copy)
        Dim bytes() As Byte = ms.GetBuffer
        ms2.Write(bytes, 14, CInt(ms.Length - 14))
        ms.Position = 0
        Dim obj As New DataObject
        obj.SetData("DeviceIndependentBitmap", ms2)
        pb.DoDragDrop(obj, DragDropEffects.Copy)
        ms.Close()
        ms2.Close()
    End Sub

The routine works splendidly dropping images into MS Excel 2013, however, I need to use it with MS Word. When I drag an image to Word, the cursor shows the proper Arrow-box-plus-sign cursor, but releasing the mouse button doesn't drop the image. Nor does it throw any sort of error.
I'm at a loss to troubleshoot this issue. I've been googling for fixes, but mainly find VB Form-to-VB Form solutions.
If you can point me along to figuring this out or suggest a code change, I'd appreciate it.

A: I got this to work for me... You were saving as PNG/JPG/GIF, none of which are DIBs (or even bitmaps)
    Private Sub PictureBox1_MouseDown(sender As Object, e As MouseEventArgs) Handles PictureBox1.MouseDown

    ' see
    ' http://groups.google.co.uk/group/microsoft.public.win32.programmer.gdi/browse_thread/thread/197b47c39f8ad2c8/e2e4b88de9f83d3a
    Dim ms As New MemoryStream
    Dim ms2 As New MemoryStream

    Dim pb = DirectCast(sender, PictureBox)

    pb.Image.Save(ms, ImageFormat.Bmp)
    pb.DoDragDrop(pb.Image, DragDropEffects.Copy)
    Dim bytes() As Byte = ms.ToArray()
    ms2.Write(bytes, 14, CInt(ms.Length - 14))

    ms.Position = 0
    Dim obj As New DataObject
    obj.SetData("DeviceIndependentBitmap", ms2)
    pb.DoDragDrop(obj, DragDropEffects.Copy)
    ms.Close()

End Sub


text:
Q: Semantic-UI - Links / A Tags / URLs Inside Semantic Ui Dropdown Menu Do Not Work I am working with Semantic UI in a rails project and wanted to create a dropdown menu with items that would link to other view pages. Most of the problems i've seen with the dropdown stemmed from users not initializing the dropdown menu which I was able to do.
Here's my code:

    Course

      <% @topics.each { |topic|  %>
        <a class="item" href="articles/<%= topic.id %>">
           <%= topic.name %>

      <% } %>

Different things i've tried:

*

*Creating a separate hardcoded links / a tags like  outside of the dropdown menu. This creates a working link and directs me to the article show view page with the id of 4.

*Changed the wrapping 's class as "ui floating dropdown item" as well

I've also looked up other users' posts that shows they have the same exact problem. But when i try their solution, my dropdown menu items still do not work and i'm not sure what i'm doing wrong. Here are their posts:

*

*https://github.com/Semantic-Org/Semantic-UI/issues/3234

*https://github.com/Semantic-Org/Semantic-UI/issues/453
The two most important things seem to be:

*

*Not putting the dropdown class definition as part of an anchor tag (inserting an anchor tag inside an anchor tag in the dropdown menu)

*Not surrounding each anchor tags with their own
 tags but to integrate them into one line like  #
Can anyone help me understand what i might be overlooking? Let me know if i left out any critical information, would love to update the post with the relevant data right away, thank you!

A: After doing more and more research, I came to the conclusion that the links were not working in my semantic-ui dropdown menu because of some code, most likely Javascript, that i had inserted before.
Of course, i ruled this way out of the realm of possibility because there was no way i would forget about such code but i decided to go through all of my .js files just in case.
Lo and behold, i had a jQuery selector return false when a .item was being clicked...
I felt really silly and i didnt want to believe it at first but if you're having this problem and you've checked everything else like i have, it's probably your javascript!


text:
Q: How long a straw could Superman use? To suck water through a straw, you create a partial vacuum in your lungs.  Water rises through the straw until the pressure in the straw at the water level equals atmospheric pressure.  This corresponds to drinking water through a straw about ten meters long at maximum.
By taping several straws together, a friend and I drank through a $3.07m$ straw.  I think we may have had some leaking preventing us going higher.  Also, we were about to empty the red cup into the straw completely.

My question is about what would happen if Superman were to drink through a straw by creating a complete vacuum in the straw.  The water would rise to ten meters in the steady state, but if he created the vacuum suddenly, would the water's inertia carry it higher?  What would the motion of water up the straw be?  What is the highest height he could drink from?
Ignore thermodynamic effects like evaporation and assume the straw is stationary relative to the water and that there is no friction.

A: If I follow up on keenan pepper's suggestion, if the water is deep, and especially if you can mess with the topology of the straw you can go to almost unlimited height!
Consider a straw that is stuck very deeply into the ocean. Then coil the straw around at great depth many many times. I then blow very hard (I am superman afterall), and create a huge volume of airfilled straw at great depth. This configuration has a great deal of potential energy, so if we simply stop blowing we have the pressure at the great depth of the bottom of the straw accelerating water into and up the straw. Since by coiling the straw at great depth I can obtain an unlimited ratio of volume of the straw underwater to volume above water, the energy analysis allows me to reach an unlimited height. So the issue becomes if there is some other sort of limit. Can we get cavitation of water trying to enter the straw or something if the velocity gets too high? But, in any case you should be able to get really high, tens or hundreds of times the static limit, by preenergizing the system in this way. In the real world friction will limit how far you can take it.

A: Trick question, he'd use his super strength to bend the straw into an Archimedes' screw, then hold it at an angle to the surface of the water and rotate it about the axis.
This lets him draw it up to any height, and then he can drain the world's oceans to prove a point or do whatever other superdickery he's trying to do.

A: I am not fully convinced by this argument, but can't find a flaw in it.
Let's analyse a similar experiment, which I believe to be equivalent. Assume that initially, the water is already at the stable level $H=\frac{P_{atm}}{\rho g}$. The vacuum is already present.
Now, by some unimportant means, we lower the water to $h=0$, and then let it go up freely.
How much energy are we storing in the system by lowering the water? We can find out by calculating the work done. The work is done against pressure and in favour of gravity.
$$W= sP_{atm}H + \int^0_H{m(h)g\ \mathrm{d}h}$$
Substituting $H=\frac{P_{atm}}{\rho g}$, $m(h)=\rho s h$
$$W= \frac{sP_{atm}^2}{\rho g} + s\rho g\int^0_H{h\ \mathrm{d}h}$$
$$W= \frac{sP_{atm}^2}{\rho g} - \frac{1}{2}s\rho gH^2$$
$$W= \frac{sP_{atm}^2}{2\rho g}$$
Now when the water is released and allowed to rise, all this energy will used to make the water rise. No energy is assumed to be wasted on friction.
At the highest point, all the energy will be converted in gravitational potential energy. This can be expressed through the following formula:
$$U(h)=\frac{1}{2}s\rho gh^2$$
Therefore, at the top point, $W=U(h)$
$$\frac{sP_{atm}^2}{2\rho g} = \frac{1}{2}s\rho gh^2$$
Solving for $h$:
$$h^2=\frac{P_{atm}^2}{g^2\rho^2}$$
$$h = \frac{P_{atm}}{g\rho} = H$$
Therefore, the water will raise up to $H$, which it will reach with zero velocity.

A: I can not comment yet, so I will put it as an answer :-(   I like the energy approach, but why not to use Archimedes principle? First, substitute the air atmosphere by an extra ten meters of water around the straw, so that now the initial conditions are a vacuum straw inserted a lenght h in a fluid. The energy to produce such vacuum in the fluid you can see by Archimedes; and it is h/2 times g times the mass of the removed fluid. Let it move, and it can go up until filling a column of lenght h above the level, because the energy (now gravitational) of this column is, again, h/2 times its mass times g.

A: Superman is going to manipulate the air pressure in the straw. To get the water to go up, he must provide a reduction in the pressure. It's clear that if this reduction is provided at a very slow rate, then he will not be able to significantly exceed 10 meters or so (as limited by atmospheric pressure).
On the other hand, if he reduces the pressure quickly, it's at least possible that the water could reach a higher height. How high can the water go under this assumption? The idea is to use the momentum of the water to get the water higher, so the figure of merit will be the maximum speed of the water at surface level.
Reducing the pressure cannot move the water faster than the air and the air speed is limited by the speed of the gas molecules in the air or about 330 meters per second. By equating kinetic energy $0.5 m v^2$ with potential energy $mgh$, water with that initial speed can reach a height of $h = 0.5 v^2/g = $ 2775 meters. The height is small enough to justify the assumption that $g$ is a constant. Maybe you should add 10 meters for the usual vacuum effect.
Hmmm. Ah, what the heck, I ought to just do the fracking calculation for how high the water goes in a wide straw when a vacuum is applied to it.

A: If we are looking at this from a purely suction related problem then superman the maximum height sumperman could lift water in a straw would be equal to the pressure being exerted on the water he is drinking.  If drinking from sea level then he could lift or suck the water about 10 m.  Theoretically he could create a complete vacuum in his mouth then the amount of lift is merely the differential pressures.   We run into this limit all the time with vacuum pumps.  However, if he is able to suck really quickly then the velocity of the air could allow for water entrainment beyond the maximum lift.  He could not suck the water as one big slug but rather as droplets carried up the straw due to the wind velocity within the straw.  In a more practicle case, vacuum pumps have been shown to lift water from over a couple of hundred feet above static water level using this method.  But the rate of recharge within the well must be suffuciently low to ensure that the water does not "clog" your suction pipe.  To put another way you need to have far more air than water going up your straw.

A: I think we can most easily consider the problem from the perspective of energy. For a unit area column the external energy put in equals the volume of the column times the air pressure. The gravitational energy is the mass of water raised times the average height of the water. So
as we pull the water up, we the water is gaining kinetic energy until the water reaches the static limit (roughly 10meters), but at this point the average water in the tube has only risen by half that amount, so the rest is kinetic energy of (upward) water motion. So the vacuum energy in dimensionless units is $h$, while the gravitational energy is $\frac{1}{2}h^2$. The solution is $h=2$.
When we reach 2 times the static limit (20 meters) then the gravitational energy in the water matches the "vacuum" energy we put in, so that would represent the high point of the oscillation. So I think we would get 2 times the static limit. The water velocity will be messy to solve for, as the amount of water moving in the column depends upon height, so just look only at net energy as a function of water height... Of course he will only get a sip of water, then the column would start to fall........

A: I have an argument that the water in the straw will rise to twice the equilibrium height.
David and Martin's answers consider the system of water in the straw.  I will consider the system of the water in the straw plus the water in the reservoir.
As water goes into the straw, the water level in the reservoir drops, and the atmosphere does work on the system.  If a volume $V$ of water enters the straw, the work done on the system is $PV$, with $P$ the atmospheric pressure.  Assume that the reservoir has a large surface area so that the level the reservoir drops is negligible.
When the water is at its peak in the straw, the kinetic energy of the system is zero, so the potential energy is $PV$.  The potential energy is also $\rho g V h/2$.  So the maximum height of the water is
$$h = \frac{2P}{\rho g}$$
This answer is different from Martin and David's.  I think this might be because when the water starts moving, the pressure at the entrance to the straw may not be $P$ any more.

A: I went back and took a more careful look at this. I'm still not convinced it's correct, but I'm hoping this is at least better than what I had before.

Let $h$ be the height of the column of water inside the straw. As this height rises by an amount $\delta h$, the work done on the column is
$$\delta W = P A \delta h$$
where $A$ is the cross-sectional area. The change in potential energy is
$$\delta U = \rho A \delta h g h$$
so by conservation of energy,
$$\delta K = \delta W - \delta U = \left(P - \rho g h\right) A \delta h$$
This excess kinetic energy comes from two contributions: the added mass,
$$\delta K_1 = \frac{1}{2}mv^2 = \frac{1}{2}(\rho A \delta h)\dot{h}^2$$
and any change in speed of the column of water,
$$\delta K_2 = \frac{1}{2}m(2v\delta v) = (\rho A h)\dot{h} \delta\dot{h}$$
Putting it all together, we get
$$P A \delta h - \rho A g h \delta h = \frac{1}{2}\rho A \dot{h}^2 \delta h + \rho A h\dot{h}\delta\dot{h}$$
If you assume (or prove) that $P$ is dependent on $h$ through Bernoulli's theorem,
$$P + \frac{1}{2}\rho\dot{h}^2 = P_0$$
Substituting in (and canceling the common factor of $A$), you get
$$P_0 \delta h - \rho g h \delta h = \rho \dot{h}^2 \delta h + \rho h \dot{h}\delta\dot{h}$$
which at least accounts for the mysterious factor of $\frac{1}{2}$ that appeared in previous versions of my answer.
Now, I don't think we can simply assume that $\delta h \neq 0$ and divide it out, because if we do that, we get a factor of $\frac{\delta\dot{h}}{\delta h}$ which is undefined at the initial and maximum heights. (Roughly speaking, the variation $\delta h$ is second-order at those points whereas the variation $\delta\dot{h}$ is still first-order.) Instead, I'll divide by $\delta t$, which certainly should not produce any singularities, to get
$$P_0 \dot{h} - \rho g h \dot{h} = \rho \dot{h}^3 + \rho h \dot{h}\ddot{h}$$
At the initial and maximum heights, $\dot{h} = 0$, so the equation is trivially satisfied there. But consider the situation when displaced from either initial or maximum height by an arbitrarily small amount, such that $\dot{h}\neq 0$. Here we can cancel out $\dot{h}$ to get
$$P_0 - \rho g h = \rho \dot{h}^2 + \rho h \ddot{h}$$
Since $\dot{h}$ will be infinitesimally small around the maximum height, we can neglect the first term on the right, but not the second. So we're left with
$$P_0 - \rho g h = \rho h \ddot{h}$$
Note that this agrees with a simple analysis using Newton's second law. (The forces acting on the column of water at its maximum height are the pressure force $P_0 A$ acting upwards and gravity $\rho Ahg$ acting downwards, and the difference is equal to $ma = \rho Ah\ddot{h}$.) So the differential equation passes at least one basic consistency test.
Anyway, this equation no longer admits the solution $h = \frac{P_0}{\rho g}$. Instead we have
$$h = \frac{P_0}{\rho (g + \ddot{h})}$$
Unfortunately I can't think of a way to determine $\ddot{h}$ at maximum without solving the equation, so for now I'm limited to a numerical solution.
For a quick estimation, I plugged the full differential equation from above into Mathematica's NDSolve function. With boundary conditions $h(0) = 0$ and $\dot{h}(0) = 0$, it complained about undefined expressions, so I used boundary conditions at a nonzero time,
$$h(\epsilon_t) = \epsilon_h$$
and
$$\dot{h}(\epsilon_t) = \epsilon_{\dot{h}}$$
for values of the various $\epsilon$ constants ranging from $10^{-3}$ to $10^{-8}$. In my tests, I get this graph, seemingly independently of the values of $\{\epsilon\}$ or the ratios between them:

Mathematica indicates that the graph peaks at $15.5\,\mathrm{m}$, so if this analysis is correct, that would be the maximum height. (FWIW I am still very suspicious of this calculation though)

A: You can manipulate the vacuum suction limitation of maximum height of 33.9 feet or 10 meter (14.7 psia or 0.1 Mpa) by using oscillating blow and suct. Use longer straw submerged deep enough into the water, blow it until the air almost reach the bottom of the straw then suck it! You will get height boost!!

A: Unless I'm missing something, this is simply the height of a water-based barometer, since it is really the atmospheric pressure that is pushing the water up the straw. at STP, the answer is 33 1/2 feet. If he were sucking Hg up the straw (not recommended for non-superheros!), the height would be ~30 inches.

A: If you immerse the staw in 10m of water, while holding the end closed, and then release it, the water will accelerate upwards past the level point and it will overshoot up to a height of about 6m. No sucking needed. Add some suction to this and you can go higher. A square section straw should minimize the friction loss allowing for better "spring back". Overall you can help the suction, by immersing the straw deeper and deeper.
Note that it takes work do immerse the straw (displacing the water) and that is the energy conveted into ponetial energy that allows the water to rise. Close the end when the water reaches the maximum height and you can measure how high you can reach.


text:
Q: Autowiring Feign interface located in JAR I have a AttachmentApi service class that uses a feign interface both located inside a JAR file that i'm using as dependency in a client microservice.
The controller of that client microservice uses the AttachmentApi service to get data from db.
When I access some endpoint of that controller, the AttachmentApi service is
 successfully autowired but the feign interface isn't, and it gives me the following exception:
java.lang.NullPointerException: null
at ma.co.omnidata.framework.services.attachment.api.AttachmentApi.upload(AttachmentApi.java:26) ~[classes/:na]
at ma.co.omnidata.attachment.user.service.impl.AttachmentsUserService.uploadFile(AttachmentsUserService.java:21) ~[classes/:na]
at ma.co.omnidata.attachment.user.controllers.AttachmentUserController.uploadFile(AttachmentUserController.java:31) ~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_144]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_144]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_144]
at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_144]

The null is due to the feign interface that does not get autowired !

Knowing that I use the following annotations in my springboot class
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients(basePackages= {"my.packages.including.the.feign.interface.package"})

Any advice would be appreciated
thanks!
UPDATE 1
Feign interface (Located in the JAR dependency)
@FeignClient(name="attachment-service", fallback=AttachmentHystrixFallback.class)
public interface AttachmentFeignClient {

@RequestMapping("attachment/{id}")
byte[] getAttachment(@PathVariable(name="id") String id);

@RequestMapping("attachments")
List<AttachmentDto> getAttachments(@RequestParam(name="attachableId") Long attachableId,
        @RequestParam(name="className") String className, @RequestParam(name="appName") String appName);

@RequestMapping("upload")
void upload(MultipartFile file, @RequestParam(name="attachableId") Long attachableId,
        @RequestParam(name="className") String className, @RequestParam(name="appName") String appName);

@RequestMapping("test")
String test();

}
The AttachmentApi (Located in the JAR dependency too)
@Service
public class AttachmentApi implements IAttachmentApi {

@Autowired
AttachmentFeignClient client;

@Override
public byte[] getAttachment(String id) {
    return client.getAttachment(id);
}

@Override
public void upload(IAttachable entity, MultipartFile file) {
    client.upload(file, entity.getAttachableId(), entity.getClassName(), entity.getAppName());
}

@Override
public List<AttachmentDto> getAttachments(IAttachable entity) {
    return client.getAttachments(entity.getAttachableId(), entity.getClassName(), entity.getAppName());
}

public String test() {
    return client.test();
}

}
NB : My client microservice cannot autowire any of the beans (neither the Feign interface nor the AttachmentApi class) located in the JAR dependency !

A: Try this
@EnableFeignClients(clients = {AttachmentFeignClient.class})


text:
Q: $k$-regular and not complete graph and distance
Let $G$ be a connected, $k$-regular and not complete graph. Then, for
  any vertex, there exists another vertex with distance two from that.

I am not sure about a rigorous justification for that. I need to get more elaboration about that.

A: Suppose this is false. Then, take a vertex $A$ where this fails. Then, every vertex is at a distance of $1$ from $A$ as the graph is connected (if there exists any point at greater distance, then there exists a point of distance $2$). Then, there are $k$ other vertices in the graph by construction, which means that we have a $k$ regular graph on $k+1$ vertices, which is a complete graph.

A: Let $G$ be a connected, $k-$regular graph that is not complete. Suppose for a contradiction that there exists a vertex $v \in V(G)$ such that there are no vertices with distance $2$ to $v$. Notice that if there exists a vertex $u$ with distance more than $2$ to $v$, then we can simply take a vertex from the $uv$ path with distance $2$ to $v$. Then only possibility is every other vertex being distance $1$ to $v$. But then $v$ should be connected to every other vertex. Since $G$ is a regular graph, this means $G$ is complete, which is a contradiction.


text:
Q: How do I getting all values from a one panda.series row that correspond to s specific value in second row? I have a Dataframe that looks like this :
 name   age       occ   salary
0   Vinay  22.0  engineer  60000.0
1  Kushal   NaN    doctor  70000.0
2    Aman  24.0  engineer  80000.0
3   Rahul   NaN    doctor  65000.0
4  Ramesh  25.0    doctor  70000.0

and im trying to get all salary values that correspond to a specific occupation ,t o then compute the mean salary of that occ.

A: here is an answer with a few step
temp_df = df.loc[df['occ'] == 'engineer']
temp_df.salary.mean()

A: All averages at once:
df_averages = df[['occ', 'salary']].groupby('occ').mean()

                salary
occ
doctor    68333.333333
engineer  70000.000000


text:
Q: Outline/Border rendering issue in chrome I noticed a strange behaviour when animating a border/outline color change in chrome. The right border/outline of my element does not correctly animate from white to red and stays red after mouse leaves the element. Scrolling the page forces the border/outline to display correctly.
Standard state:

Broken hover state:

After mouse leaves:

Thin grey border right (after mouse leave, sometimes):

Desired result (working on IE, Firefox, Opera):

My CSS (LESS) for the element:
a {
    display: inline-block;

    padding: 1em 3em;

    outline-width: 1px;
    outline-style: solid;
    outline-color: white;
    color: @hue-red;
    background: white;

    text-decoration: none !important;
    text-align: center;

    transition: color 200ms, outline 200ms;

    .gfx(arrow-circled-right);

    &:before {
        font-size: 1.8em;
        margin-right: 0.5em;
    }

    &:hover, &:focus {
        color: darken(@hue-red, 5%);
        outline-color: darken(@hue-red, 5%);
    }
}

I tried to switch from border to outline and back with the exact same result.
Edit: I cannot reproduce the error any more, so I'm closing the question.


text:
Q: Why objective-c's block cannot capture values dynamically? I wanna implement defer in objective-c. And here's my code:
/**
  RAII : ABC->~ABC
 */
@interface DeferImpl_ : NSObject
/**
 *  init with a callback
 *
 *  @return
 */
-(instancetype) initWithCallback:(void(^)())callback;
/**
 *  a callback
 */
@property(nonatomic, copy) void(^callback)();

@end

/**
 *  Defer
 *
 *  @param X { statement; statement; ... }
 *
 *  @return
 */
#define DEFER(X)  [[DeferImpl_ alloc] initWithCallback:^X]

#define SAFE_INVOKE(x) do{if(x){(x)();}}while(0)
@implementation DeferImpl_
/**
 *  invoke callback
 */
-(void) dealloc {
    SAFE_INVOKE(self.callback);
}

-(instancetype) initWithCallback:(void(^)())callback {
    self = [super init];
    self.callback = callback;
    return self;
}

@end

The implementation is simple and seems easy to use.
But it's buggy!.
Here comes what I feel frustrated.
int main(void)
{
    NSInteger count = 0;
    DEFER({
        NSLog(@"Defer: %@", @(count));
    });
    count = 123;
    NSLog(@"Before defer block!");
    return 0;
}

Log is:

2017-01-12 17:31:32.401 test[73724:18571479] Defer: 0
2017-01-12 17:31:32.402 test[73724:18571479] Before defer block!

So is there anyone can tell me why count still 0 in the block?

A: You have hidden most of your work into macros (not a good programming style!) and your are missing the basic point - DEFER calls the block immediately, before even reaching count = 123.
If you don't assign the result of [DeferImpl_ alloc] to any variable, it will get released immediately, also immediately calling the block.
Your current code is the same as writing directly:
NSInteger count = 0;
NSLog(@"Defer: %@", @(count));
count = 123;
NSLog(@"Before defer block!");

If you change your code to:
NSInteger count = 0;
id x = DEFER({
    NSLog(@"Defer: %@", @(count));
});
count = 123;
NSLog(@"Before defer block!");

Your result will be:

Before defer block!
  Defer: 0

Now, why the value is still zero? Because blocks capture variables by value. To capture the reference, you will have to add __block:
__block NSInteger count = 0;
id x = DEFER({
    NSLog(@"Defer: %@", @(count));
});
count = 123;
NSLog(@"Before defer block!");

Before defer block!
  Defer: 123

See Blocks and Variables


text:
Q: JTextField input and output I'm trying to design a Mile to Nautical Mile calculator in Java.
I was able to create and run it okay through the console, but i'm having trouble learning how to do it in JFrames.
what im basically wanting to do is:
Have two text fields and a button, one text field miles and one for nautical miles, when you enter the amount into one then press the button the result will display in the other field.
I've pasted my code below
Not really sure what to do next
package Mile_Conversion;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

public class OwnWindow implements ActionListener{

    public static void main(String[] args) {
        MyJFrame();

    }

    public static void MyJFrame() {

        //JLabel
        JLabel start = new JLabel("Enter the amount below to calculate");
        start.setBounds(/*x*/70, -65/*Y*/, 270, 150); // x, y, width, height    x across, y down
        JLabel milecon = new JLabel("Miles");
        milecon.setBounds(154, 55, 50, 150);
        JLabel nautcon = new JLabel("Nautical Miles");
        nautcon.setBounds(135, -15, 150, 150);

        //JTextField
        JTextField miles = new JTextField();
        miles.setBounds(100, 140, 150, 25);
        JTextField nautical = new JTextField();
        nautical.setBounds(100, 70, 150, 25);

        double mile, nautmile;

    /*
            mile = nautmile * 0.868;

            nautmile = mile * 1.150;
    */

        //JButton
        JButton convert = new JButton("Convert");
        convert.setBounds(250, 200, 90, 25);

        //JFrame
        JFrame window = new JFrame("Milage Conversion");
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setSize(400, 300);
        window.setVisible(true);
        window.setLayout(null);
        window.setResizable(false);
        window.add(start);
        window.add(miles);
        window.add(nautical);
        window.add(convert);
        window.add(milecon);
        window.add(nautcon);

    }

    @Override
    public void actionPerformed(ActionEvent e) {

    }
}

A: Welcome to the wonderful world of variable fonts, resolutions and DPI, where what it looks like on your screen will never match any one elses (okay, that's an exaggeration, but it feels like it :P)
In this world, layout managers are you friend.  They will save you many, many, many hours of frustration and torment.
I'd recommend you have a read through;

*

*Using Layout Managers

*A Visual Guide to Layout Managers
This is my take on what you are trying to do...
public class TestConvertDistance {

    public static void main(String[] args) {
        new TestConvertDistance();
    }

    public TestConvertDistance() {

        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new DistancePane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    protected class DistancePane extends JPanel {

        private JLabel lblInstruct;
        private JLabel lblMiles;
        private JLabel lblNauticalMiles;

        private JTextField fldMiles;
        private JTextField fldNauticalMiles;

        private JButton btnCalculate;

        public DistancePane() {

            lblInstruct = new JLabel("Enter the amount below to calculate");
            lblMiles = new JLabel("Miles");
            lblNauticalMiles = new JLabel("Nautical Miles");

            fldMiles = new JTextField(8);
            fldNauticalMiles = new JTextField(8);

            btnCalculate = new JButton("Convert");

            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.insets = new Insets(2, 2, 2, 2);
            gbc.anchor = GridBagConstraints.WEST;
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            add(lblInstruct, gbc);

            gbc.gridx = 0;
            gbc.gridy++;
            gbc.anchor = GridBagConstraints.WEST;
            gbc.gridwidth = 1;
            add(lblMiles, gbc);

            gbc.gridy++;
            add(lblNauticalMiles, gbc);

            gbc.gridx = 1;
            gbc.gridy = 1;
            add(fldMiles, gbc);

            gbc.gridy++;
            add(fldNauticalMiles, gbc);

            gbc.gridx = 0;
            gbc.gridy++;
            gbc.anchor = GridBagConstraints.CENTER;
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            add(btnCalculate, gbc);

            btnCalculate.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    // Do your calculation here...
                }
            });

        }

    }

}

Note, I've used GridBagLayout, this is one of the most powerful and complicated layout managers in the core API, so don't get worried if at first it seems confusion ;)

A: write your code for conversion inside actionPerformed method:

*

*Take input from first JTextField miles

*Parse it to int or float( as JTextFields getText() method returns String)

*Do the conversion

*set the converted value to the other JTextField nautical using nautical.setText(); method

A: Here is my version of it. It probably isn't perfect and doesn't have any exception handling:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

public class OwnWindow implements ActionListener
{

    JLabel start;
    JLabel milecon;
    JLabel nautcon;
    JTextField miles;
    JTextField nautical;
    JButton convert;
    JFrame window;

    double mile, nautmile;
    public static void main(String[] args)
    {
        OwnWindow obj = new OwnWindow();

    }
    public OwnWindow()
    {
        start = new JLabel("Enter the amount below to calculate");
        start.setBounds(/*x*/70, -65/*Y*/, 270, 150); // x, y, width, height    x across, y down

        milecon = new JLabel("Miles");
        milecon.setBounds(154, 55, 50, 150);

        nautcon = new JLabel("Nautical Miles");
        nautcon.setBounds(135, -15, 150, 150);

        miles = new JTextField();
        miles.setBounds(100, 140, 150, 25);

        nautical = new JTextField();
        nautical.setBounds(100, 70, 150, 25);

        convert = new JButton("Convert");
        convert.setBounds(250, 200, 90, 25);
        convert.addActionListener(this);

        window = new JFrame("Milage Conversion");
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setSize(400, 300);
        window.setVisible(true);
        window.setLayout(null);
        window.setResizable(false);
        window.add(start);
        window.add(miles);
        window.add(nautical);
        window.add(convert);
        window.add(milecon);
        window.add(nautcon);
    }

    @Override
    public void actionPerformed(ActionEvent e)
    {
        String strNaut = nautical.getText();
        String strMile = miles.getText();

        //this means the user wants to convert nautical to normal
        if(strNaut.length() > 0)
        {
            nautmile = Double.parseDouble(strNaut);
            miles.setText(nautmile*0.868 + "");
        }
        else if(strMile.length() > 0)
        {
            mile = Double.parseDouble(strMile);
            nautical.setText(mile*1.150 + "");
        }
    }
}


text:
Q: Find out the bottleneck for windows remote desktop server (Terminal server) I have Windows server 2008 R2 (SP1) installed on my VMware Host to work as RDS server. Sometimes my remote users can see the lagging/delay on RDS server. Can anyone tell me from their experience what are the best practices to find the bottleneck for this server?

A: As Chris S mentioned, there are several things that can contribute to poor remote desktop performance. From my experience, these are the main causes, in order of likelihood.
Bandwidth
The #1 cause of poor performance with remote desktop is lack of bandwidth. Depending on exactly what is being done, a session can use anywhere from a a few Kbps to a few Mbps of bandwidth. My own tests have shown that scrolling through a PDF will use up to 3 Mbps. As available bandwidth decreases, so does perceived performance.
You first need to determine the bandwidth needs of your application. This requires testing in a controlled LAN environment, then measuring the bandwidth use as you perform normal tasks. I personally had success with NetLimiter on my personal workstation. You can also approach the problem from another angle, and use NetLimiter to force your connection speed down to whatever your WAN connection is rated at. This should give a good indication of what your remote users are seeing.
Once you know how much bandwidth your application wants, you need to determine whether it is the limiting factor. First, measure the available bandwidth between the client and the server. An excellent tool for this is iperf. I'll assume that you have sufficient bandwidth available during a controlled test.
Next, you will want to set up some kind of bandwidth monitoring to see whether user-reported problems correlate with spikes in traffic or other undesirables. My preference is to dump traffic from a switch or router into ntop, as it provides useful realtime and historic reports on bandwidth usage.
If you're encountering bandwidth problems, one easy change is to change the "Experience" settings on the remote desktop connection. Disable visual styles and animations, and many desktop operations will seem magically faster.
Latency
Another common issue with remote desktop connections is latency. There needs to be a reasonably quick round-trip time between the client and server, or people will be able to perceive a delay. As a rule of thumb, most people start to notice problems between 50 and 100 ms ping times.
Luckily, this is usually easy to diagnose. You can set up monitoring tools like SmokePing or PRTG Network Monitor to provide reports on the latency between your monitoring server and any other arbitrary host. You can even just use the built-in ping -t command for short sessions. Normally you want to locate the monitoring server on the same LAN as your remote desktop server, then set up monitoring against both the server and your clients. Try to correlate problem reports with incidents of high ping time.
If you're having problems with high ping times, use traceroute to find out where the delay is being introduced. If you determine that the problem resides within your own network, consider introducing QoS filtering to prioritize realtime traffic like Remote Desktop.
Also, be wary of anybody who is connecting over a wireless medium, whether that is 802.11 (WiFi), or worse, a satellite connection. Wireless connections are prone to environmental interference that can cause extreme latency problems under various conditions, and for varying periods of time. And using remote desktop through a satellite always sucks.
Local CPU or memory
And finally, it's possible that your server is simply overburdened. Monitor the CPU and memory usage, especially during peak hours, to ensure that the server is capable of meeting requests in a timely fashion.
One of the tools mentioned above (PRTG) can be set up to monitor CPU and memory usage of a server over time, and can produce graphs that make it easy to correlate problem problem reports with specific faults.
Bonus tip: If your users are having trouble typing, especially with regard to modifier keys not applying properly, try changing your keyboard settings on the Remote Desktop connection shortcut so that Apply Windows key combinations is set to On the local computer.

A: Check out the RDS Best Practises Analyzer.


text:
Q: What are the pros and cons of using static function in header file
Possible Duplicate:
C/C++: Static function in header file, what does it mean?
When to put static function definitions in header files in C?

What are the pros and cons of using static function in header file?

A: Supposing you implement it in the header file, each time your header is included, the function is going to be duplicated. This means heavier produced binary, bad practice and overall nightmare to debug and maintain.
If you just define it in the header, you need to implement in each C file.
EDIT

*

*if it's not in the header, you have a function with a given name, implemented more than once, thus providing potentially different behaviours. Otherwise, don't make it static and implement once. Having more than one function with same name is a pitfall for maintainers (thus debug and maintenance hell)

*static function and inline functions are different matters. Static function are "locale" while inline function are "to be replaced by their body where they are called". In terms of overhead, calling a standard function or a static function is same "performance price".

EDIT 2
Here is the kind of pitfall you can run into
static.h
#ifndef _STATIC_H_
#define  _STATIC_H_
#include <stdio.h>

static void printer(void);
void nonStatic (void);

#endif

a.c
#include "static.h"

static void printer(void)
{
    printf ("half the truth : 21\n");
}

int main (void) {
    printer();
    nonStatic();
}

b.c
#include <stdio.h>
#include "static.h"

static void printer (void)
{
    printf("Truth : 42\n");
}

void nonStatic(void)
{
    printf ("Non static\n");
    printer();
}

Looking at this code, you call "printer" from 2 different locations, you got different behaviour:
D:\temp>gcc -o temp.exe a.c b.c && temp
half the truth : 21
Non static
Truth : 42

Obvious in this small example, really tricky when hidden in a big software


text:
Q: Question about divisors and compact Riemann surfaces I am trying to solve the following but not getting anywhere.
Let $f:\Sigma_{1}\rightarrow \Sigma_{2}$ be a non-constant holomorphic map between compact Riemann surfaces $\Sigma_{i},i=1,2$.
(a) Prove that for any $p\in \Sigma_{2},f^{-1}(p)$ is a finite set and hence defines a positive divisor $D_p$ on $\Sigma_{1}$ of degree $deg(D_{p})=deg(f)$.
(b) If $\Sigma_{2}=\overline{\mathbb{C}}$ prove that the linear equivalence class of $D_{p}$ is independent of the choice of $p$.
(c) If $\Sigma_{2}\neq \overline{\mathbb{C}}$ is the linear equivalence of $D_{p}$ independent of the choice of $p$?.
I understand that (a) comes from the fact that the degree of such a map is finite and that the sum of multiplicities in the preimage must equal to the degree.
(b) I don't really know what to do. I would need to show for $p\neq p'\in \overline{\mathbb{C}}$ that there exists a meromorphic function $q$ on $\Sigma_{1}$ such that $D_{p}=D_{p'}+(q)$. Here $(q)$ is the divisor associated with the meromorphic function $q$. If $\Sigma_{1}$ was also the Riemann sphere then finding such a $q$ would be easy, one could just choose an appropiate function of the form $q(z)=(z-a_1)\dots (z-a_l)/((z-b_1)\dots (z-b_k))$...but for arbitrary $\Sigma_{1}$ it is a lot more difficult.
(c) I trust that knowing (b) would enlighten one as to how to approach (c). Please give at most a hint for this last part.

A: Not sure this is the expected method but there is one

*

*See your $f : \Sigma_1 \to \overline{\mathbb{C}}$ as a meromorphic function $f : \Sigma_1 \to \mathbb{C}$. Write
$f^{-1}(0) =\{a_i\}_{i=1}^d$, $f^{-1}(\infty)=\{c_i\}_{i=1}^d$ and for a $p \in \mathbb{C}$, $\ f^{-1}(p)=\{b_i\}_{i=1}^d$ (the zeros of $f(z),f(z)-p,\frac{1}{f(z)}$ counted with multiplicity) so that $div(f(z)) = \sum_{i=1}^d a_i-c_i,div(f(z)-p) = \sum_{i=1}^d b_i-c_i$ and with $g(z) = \frac{f(z)}{f(z)-p}$ then $div(g(z)) = \sum_{i=1}^d a_i-b_i=D_0-D_p$

*In other words $\overline{\mathbb{C}}$ works because for any two points $p,q \ne \infty$ there exists $\phi \in Aut(\overline{\mathbb{C}})$ such that $\phi(p) = q, \phi(\infty) = \phi(\infty)$ and there exists $z \mapsto \frac{1}{z}$ exchanging $0,\infty$.


text:
Q: How to make a class with 'dynamic' data types? In the C++ standard library, there is std::vector, and you can specify the type you want to put into a vector while declaring it.
I want to create a class which would contain a vector of either strings, or ints, or whatever I would ever need. Is it possible to do this in an easy way, or would I have to write thousands of lines in C and assembly?

A: If you put the data type in the declaration, you can instantiate different kinds of vectors: vector<int> myint_v; vector<string> mystring_v; etc.... but I think your asking about how to make a Generic class and GeeksForGeeks has a really good article on this.
#include <iostream>
using namespace std;

template <typename T>
class Array {
private:
    T* ptr;
    int size;

public:
    Array(T arr[], int s);
    void print();
};

template <typename T>
Array<T>::Array(T arr[], int s)
{
    ptr = new T[s];
    size = s;
    for (int i = 0; i < size; i++)
        ptr[i] = arr[i];
}

template <typename T>
void Array<T>::print()
{
    for (int i = 0; i < size; i++)
        cout << " " << *(ptr + i);
    cout << endl;
}

int main()
{
    int arr[5] = { 1, 2, 3, 4, 5 };
    Array<int> a(arr, 5);
    a.print();
    return 0;
}

That's just an example of using a template to declare a methods in a class. Hopefully that helps. Let me know.

A: C++ has variant and any.  Variant supports a fixed list of alternative types; any supports any type of object that can be copied.
Now, any is really tricky to use right; in order to get back your data, you have to know what type of data (exactly) is in the any.  And often variant is all you need.
If your goal is something akin to a json structure, well there are plenty of implementations of that.

A: I want to add a major difference. std::variant is a compile time feature where std::any is runtime.
Generally, what you want is std::any. Variant is a type safe union which somehow breaks what the original union was designed for (to overlook types at runtime as well).
The benefit of std::any is that your don't have to change often a type which can contain a std::any instead of constantly changing the data (and, for example, to recompile the entire precompilation headers). The drawback is that you have to ensure that it contains the type you want, or you get an exception when using std::any_cast. There is added overhead as well.
The final advice is to avoid using any of the two, unless there is a good reason. There are safer ways to use multiple types (polymorphism). As said, your can also put your data inside an object like json or XML.

A: Yes you can do via some sort of manipulation. Easiest method so far i have would be using std::pair<type1,type2> method. I will initiliaze with string and double which would be able to hold most of the things you need. String can hold single character to whole text and double pretty much same thing for the number.
Easiest way is,
vector<pair<type1,type2>> vector_name;

Then push each value via make_pair method
vector_name.push_back(make_pair(type1 Value, type2 Value));

When accessing it .first is for type1 and .second would be for type2. You can see more in the code below
#include <iostream>
#include <vector>
#include <utility>
#include <string>
using namespace std;

int main(){
     vector<pair<string, double>> mypair;
     mypair.push_back(make_pair("HelloWorld!", 8.2021));
     mypair.push_back(make_pair("!", 8));
     for(auto &&i:mypair){
         cout << i.first << " " << i.second << "\n";
     }
     return 0;
 }


text:
Q: Pass javascript data from view into coffeescript function I have a view that generates a map for a specific district (available in @district). My map plotting code is coffeescript available to every page but it needs data available as a set of json files (district1.json, district2.json, etc). The first way I got this working was to load this variable in my view, making it globally available.

# in my view
<script type="text/javascript">
    var d_data = <%= render file: "#{Rails.root}/data/district_data/#{@district}.json" %>
&lt/script>

Then I use the following coffeescript accepting this global variable:

$(document).ready ->
  if $("#users-district-display")
    myLatLng = new google.maps.LatLng(d_data.centroid.lat,d_data.centroid.lon)

This works well for this page, but I now throw errors on all pages that don't define d_data. Also, I made these json files available at mysite.com/district_data and was thinking of using .get to bring in the data from ajax (and let the view load quickly), but I still have to the the @district parameter in there.
I know I could just render the js as a partial, and am going to do that unless I can find a way to make this coffeescript work.
Any thoughts appreciated.
Regards,
Tim

A: Why don't you just check to see if the data was defined?
$(document).ready ->
  if $("#users-district-display") and d_data
    myLatLng = new google.maps.LatLng(d_data.centroid.lat,d_data.centroid.lon)

Also, if you want to create a new LatLng object with zero parameters, you can always use the existential operator (?):
$(document).ready ->
  if $("#users-district-display")
    myLatLng = new google.maps.LatLng(
      d_data?.centroid.lat || 0
      d_data?.centroid.lon || 0
    )


text:
Q: Codeigniter form_validation does not validate I'm currently working on my login form. Yesterday when I logged in, even though the credentials are wrong it logs me in so I changed the = to == of this code in my model.
public function can_log_in() {

    $sql ="SELECT * FROM tbl_users WHERE USERNAME = ? AND PASSWORD = ?";
    $data1 = array(
        'USERNAME' => $this->input->post('USERNAME'),
        'PASSWORD' => $this->input->post('PASSWORD')
    );
    $query = $this->db->query($sql, $data1);

    if ($query->num_rows == 1) {
        return true;
    } else {
        return false;
    }
}

Now even if the credentials are right it doesnt log-in. Here are my controllers:
public function loginValidate() {

    $this->load->library('form_validation');

    $this->form_validation->set_rules('USERNAME','Username','required|trim|callback_validateCreds');
    $this->form_validation->set_rules('PASSWORD','Password','required|trim');

    if ($this->form_validation->run() == FALSE) {
        $this->index();
    } else {
        $data = array(
            'USERNAME' => $this->input->post('USERNAME'),
            'is_logged_in' => 1
        );
        $this->session->set_userdata($data);

        redirect('login/adminIndex');
    }
}

public function validateCreds() {

    $this->load->library('form_validation');
    $this->load->model('login_model');

    if($this->login_model->can_log_in()) { // can_log_in() model
        return true;
    } else {
        $this->form_validation->set_message('validateCreds','Username and password did not match.');  //return message to validateCreds

        return false;
    }
}

A: in Problem Model function near if($query->num_rows==1)
you change like this if($query->num_rows()==1)
full code in model function
public function can_log_in(){

$sql ="SELECT * FROM tbl_users WHERE USERNAME = ? AND PASSWORD = ?";
$data1 = array(
    'USERNAME' => $this->input->post('USERNAME'),
    'PASSWORD' => $this->input->post('PASSWORD')
    );

$this->db
$query = $this->db->query($sql, $data1);

if ($query->num_rows() == 1){

    return true;

}else{

    return false;
}


text:
Q: Need to fetch one-to-many model within a Queryset such that the Queryset has same record repeated, one for each child/nested model I am working with Django 1.6 and have a problem statement as follows:

*

*Suppose there are 2 models, Author and Book, so there is obvious one-to-many relation for the author and book model.

*Now, I need to display the Author's data such that, there is one row for each Book he has written.

*As the UI part is in backbone js, its hard for me to iterate/display by modifying things in js.

*So, would like to have this being done at the backend itself.
Data to be displayed like:
Authors name|Authors Qualification|Authors age|Book|Price

So, I have a Queryset which has , and within this, if i fetch the Books he has published, it gives me all the books published by him. Instead i want them one by one.

A: Just focus on the Books and use .select_related(..) to fetch the Authors as well. For example we can print something like:
books = Book.objects.select_related('author').order_by('author__name')
for book in books:
    print(book.author.name, book.author.qualification, book.author.age, book.title, book.price)

I am working with Django 1.6.

django-1.6 is no longer supported since April 1, 2015. Please try to upgrade as soon as possible.


text:
Q: How to add a   with jquery dynamically? Changed value of <select> on success response from API with:
jQuery('#vat').val(response);

With this returned value can be placed into a textbox, but need to change the selected value of a combobox.
How to realize this?
Here is jQuery:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
  function getVat() { // Do an Ajax request to retrieve the product price
    console.log("getVat before ajax", jQuery('#product_name').val());
    jQuery.ajax({
      url: './get/vat/get1.php',
      method: 'POST',
      data: {'id' : jQuery('#product_name').val()},
      success: function(response){
        console.log("getPrice after ajax", jQuery('#product_name').val());
        jQuery('#vat').val(response);
      },
      error: function (request, status, error) {
        alert(request.responseText);
      },
    });
  }
</script>

The script works when #vat is a textbox but not when #vat is a combobox.
Update:
Here is the script been using for the combobox:
<?php
  $dbname = 'db';
  $dbuser = 'root';
  $dbpass = 'pass';

  $db = new mysqli('localhost', $dbuser, $dbpass, $dbname);
  if (!$db) {
    exit('Connect Error (' . mysqli_connect_errno() . ') '
    . mysqli_connect_error());
  }
?>

<select style="width:100%" id="vat" name="vat">
  <option value = "0">No VAT</option>
  <?php
    $queryusers = "SELECT id, internal_id, name FROM vat";
    $db = mysqli_query($db, $queryusers);
    while ( $d=mysqli_fetch_assoc($db)) {
      echo "<option value='".$d['id']."'>".$d['internal_id']." | ".$d['name']."</option>";
    }
  ?>
</select>

Update 2:
The selected value is changed to '1'. But the script still shows <option value = "0">No VAT</option>. Does someone know how I can update the data that is shown.
Update 3:
I just get a extra option when I run the following script. The value that is represented as the selected value is still the same:
          <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
          <script>
            function getVat() { // Do an Ajax request to retrieve the product price
            console.log("getVat before ajax", jQuery('#product_name').val());
            jQuery.ajax({
                url: './get/vat/get1.php',
                method: 'POST',
                data: {'id' : jQuery('#product_name').val()},
                success: function(response){
            // and put the price in text field
                    var newOption = "<option value=" + response + ">" + response + "</option>";

                    $("#vat").append(newOption);
                    $("#vat").val(response);

                    getPrice();
                    },
                error: function (request, status, error) {
                    alert(request.responseText);
                    },
                });
            }
          </script>

A: You are right <select> value will be changed with $("#vat").val(1). However this will not create a new <option>. If there would be an <option value="1"> then this option would have been shown. Since it doesn't exist thus HTML have nothing to show and showing default <option> of <select>.
You need to create a <option> and append it to <select>.
Here's jQuery on success:
var newOption = `<option value=` + response + `>` + response + `</option>`;

$("#vat").append(newOption);
$("#vat").val(response);