How to get the Customer Group binded to a Sale rule in Magento?

Question: I've got a Shopping Cart Price Rule allowed for one Customer Group.
How can I get this Customer Group id programmatically?
Answer: Try below code to retrieve customer id which is allowed for customer group.
<code>$rules = Mage::getResourceModel('salesrule/rule_collection')->load();
 foreach ($rules as $rule) {
    if ($rule->getIsActive()) {
        $rule = Mage::getModel('salesrule/rule')->load($rule->getId());
        $customer_ids = $rule->getData('customer_group_ids');
    }
 }
</code>
You will have customer group id array.
Answer: Instead of $rule->getData('customer_group_ids') I would recommend to use $rule->getCustomerGroupIds().
In CE 1.8 "salesrule_customer_group" is a separate table and the class Mage_SalesRule_Model_Rule has an own function getCustomerGroupIds() to retrieve the customer group ids.
Answer: You can get customer group ids by using Dependency Injection:
<code>protected $_customerGroupIds;

public function __construct(

         ..........
         ........
         \Magento\Customer\Model\ResourceModel\Group\Collection $customerGroupIds,
         .....
) {

         $this->_customerGroupIds = $customerGroupIds;
}

public function getCustomerGroupIds()
{

         $groupIds = $this->_customerGroupIds->addFieldToSelect('customer_group_id')-
         >getData(); //Currently you are getting data as a multidimensional array.

         //Now I am converting this into single array
         $customerGroupIdsSingleArray = [];
         foreach($customerGroupIdsSingleArray as $childArray)
         {
            foreach ($childArray as $value)
             {
              $customerGroupIdsSingleArray[] = $value;
             }
         }
         $groupIds = array_values($customerGroupIdsSingleArray);

         return $groupIds;

}
</code>


Any PPAs for Google's Go Language?

Question: Do you know of any URLs for PPAs of Google's Go Language?
Comment: Does anybody know of binary packages (.deb) of gccgo 4.7 or later for Ubuntu Lucid?
Answer: 2023 answer: If you're using Ubuntu between 16.04 and 22.04 on amd64, arm64, armhf or i386, you can use the recommended ppa:longsleep/golang-backports.
It provides Golang from version 1.8 to 1.21
You can read more info on https://launchpad.net/~longsleep/+archive/ubuntu/golang-backports.
To sum it up:
sudo add-apt-repository ppa:longsleep/golang-backports
sudo apt update
sudo apt install golang-go

Note that golang-go installs latest Go as default Go. If you do not want that, install golang-1.19 instead and use the binaries from /usr/lib/go-1.19/bin for example.
Answer: Here's a PPA for Go. It worked for me, just now, and is maintained with golang versions for 10.04-12.04.

https://launchpad.net/~gophers/+archive/go
sudo add-apt-repository ppa:gophers/go
sudo apt-get update
sudo apt-get install golang-stable

Substitute golang-weekly or golang-tip if you want more up to date snapshots.
References:

https://wiki.ubuntu.com/Go
What are PPAs and how do I use them?

EDIT: unfortunately the Gophers archive is now discontinued (see the PPA description and http://blog.labix.org/2013/06/15/in-flight-deb-packages-of-go), now replaced by a custom binary that can be used to generate Go deb packages from source.
However, the golang package currently in Trusty is relatively recent (1.2.1 at the time of this writing). If you are still on 12.04, you might want to use this backports PPA:

https://launchpad.net/~bcandrea/+archive/ubuntu/backports
 sudo add-apt-repository ppa:bcandrea/backports
 sudo apt-get update
 sudo apt-get install golang

which I maintain trying to keep up with stable updates in official Ubuntu repositories.
Comment: No support for `14.04`... :-(
Comment: ...aaaaand it's yet another dead PPA without packages for current versions of Ubuntu.
Comment: Please unmark this answer as the right one, it's no longer relevant.
Comment: I've installed this PPA and I seem to have all the relevant packages installed (stable version). But where are the executables? I'm trying the usual ones - 6g and 6l are not in the path.
Answer: Currently, there is no PPA for the latest upstream version of Go available. To install the current Go version you can use godeb, which automatically installs the latest upstream version as a .deb package:

Prepare the envorinment by creating a directory and setting the GOPATH and PATH variable:
mkdir -p ~/.go/bin
echo "GOPATH DEFAULT=\${HOME}/.go" >> ~/.pam_environment
echo "PATH DEFAULT=\${PATH}:\$GOPATH/bin" >> ~/.pam_environment
# Re-login your user so the variables are applied

Download, unpack and install the latest Go version with godeb:
wget -O /tmp/godeb-amd64.tar.gz https://godeb.s3.amazonaws.com/godeb-amd64.tar.gz
tar xfz /tmp/godeb-amd64.tar.gz -C ~/.go/bin
godeb install

Go is now ready to use. For more information, see godeb --help.
Comment: 2016 here. This is the correct answer.
Comment: Yes, just discovered this myself as the correct answer. You can read a blog post about it here. http://blog.labix.org/2013/06/15/in-flight-deb-packages-of-go
Comment: On Ubuntu Xenial, the "prepare environment" instructions don't work for me. The .pam_environment is executed, but `${HOME}` apparently is empty, so GOPATH ends up as `/.go`, which is a no-go.
Comment: See [my answer below](https://askubuntu.com/a/1130239/355438) for info on how to install go `v1.11` from the gophers archive PPA.
Answer: I've not been able to find a PPA, but the gccgo developer has posted .deb packages on his sourceforge site.
Individuals have been working on packaging upstream Go in Debian, see the WNPP bug for more info. You might be able to build a deb from the hg repo as folloows:
hg clone http://hg.debian.org/hg/collab-maint/golang/
cd golang
debuild -us -uc

I'm not terribly familiar with using hg to build debian packages, and keep in mind this is development packaging you're working with.
Comment: `abort: HTTP Error 404: Not Found`
Answer: I used this one ppa:ubuntu-lxc/lxd-stable that has the near to latest version
Comment: Why has this been downvoted? They actually provide a package of golang with version 1.6 beta. It worked well for me!
Comment: Corresponding Launchpad page: https://launchpad.net/~ubuntu-lxc/+archive/ubuntu/lxd-stable
Comment: This is what I have been using but they are currently lagging behind. Right now their version is 1.6.2, but 1.6.3 and 1.7 have been released.
Answer: gccgo has official .deb packages in Debian experimental now.
This should be all you need to compile go code into an executable.
More info and links here:

Go (golang) intro incl. availability of packages in main distributions

As latest Ubuntu is usually a pull from experimental, then it should certainly be in 11.04 Natty Narwhal.
If you want roll you own .deb for a previous Ubuntu version, then comment from @lfaraone will get you access to debianized selection of google's own source.
If you want to pull the source direct from Google then there is a recent article by @mirwing telling you how to do that.
Answer: Go versions 1.4 through 1.11 for Ubuntu Trusty, Xenial, Bionic, Cosmic and Disco can be installed from here:
https://launchpad.net/~gophers/+archive/ubuntu/archive
sudo add-apt-repository ppa:gophers/go
sudo apt-get update
sudo apt-get install golang-1.11-go

Note: After install, you will need to add /usr/lib/go-1.X/bin (or maybe /usr/lib/go-tip/bin) to your $PATH, or you can just invoke /usr/lib/go-1.X/bin/go directly.
Answer: I got gpg failure gpg: keyserver receive failed: No name
Interestingly it on snap, so snap user can easily type
sudo snap install go --classic but remember if you already have go you should apt remove go-lang before install go

in case someone faces 404

Any PPAs for Google's Go Language?


How Can I Make This Car Rotate Properly With or Without Merging Meshes(Three.js)?

Question: The problem that I have here is that I'm trying to make a car game here but the problem is that as you can see the wheel's are rotating but not along with the car, here is the code I have in my car.js file:

export function createCar(x, y, z, color) {
  const geometry = new THREE.BoxGeometry(0, 0, 0);
  const material = new THREE.MeshBasicMaterial();
  const carCenter = new THREE.Mesh(geometry, material);
  carCenter.position.set(x + 2.5, y, z + 1.25)
  let objects = [carCenter];

  function createWheel(x, y, z) {
    createTorus(0.5, 0.25, "#36353a", x, y, z);
    createTorus(0.25, 0.25, "gray", x, y, z);
  }

  function createBody() {
    createRectangle(5.5, 3, 1, color, x + 2.5, y + 1, z + 1.25);
    createRectangle(2.5, 3, 1, "#e1ebe3", x + 1.75, y + 2, z + 1.25)
  }

  function createTorus(radius, innerRadius, color, x, y, z) {
    const geometry = new THREE.TorusGeometry(radius, innerRadius, 16, 100);
    const material = new THREE.MeshLambertMaterial({ color: color });
    const torus = new THREE.Mesh(geometry, material);
    torus.position.set(x, y, z);

    objects.push(torus);
    return torus;
  }

  function createRectangle(length, width, height, color, x, y, z) {
    const geometry = new THREE.BoxGeometry(length, height, width);
    const material = new THREE.MeshLambertMaterial({ color: color });
    const rect = new THREE.Mesh(geometry, material);
    rect.position.set(x, y, z);

    objects.push(rect);
    return rect;
  }

  function createCylinder(radius, height, color, x, y, z) {
    const geometry = new THREE.CylinderGeometry(radius, radius, height, 32);
    const material = new THREE.MeshLambertMaterial({color: color});
    const cylinder = new THREE.Mesh(geometry, material);
    cylinder.position.set(x, y, z);

    objects.push(cylinder);
    return cylinder
  }

  createWheel(x, y, z);
  createWheel(x + 5, y, z);
  createWheel(x, y, z + 2.5);
  createWheel(x + 5, y, z + 2.5);
  createBody();

  function turnRight() {
    objects.forEach(part => {
      part.rotation.y += 0.1;
    })
  }

  return {
    objects,
    turnRight,
  }
}

I don't care if it uses sin or cosine or combining meshes(which I couldn't find a method that would work). I tried for hours and still couldn't find an answer for how to make the wheels kind of swing along with the corner of the car. I also tried to find a way to get the position in the corner of a box so I could set the wheel position to that. Is there another way to do it
Answer: THREE.Group
When you add meshes to a group, the meshes are local to that group. This means that the positions are always relative to the Group in which the Mesh.
For example, if you set your Mesh.position to (10, 0, 0), and then add it to a Group, and then set the Group.position to (20, 0, 0), then the Mesh's final world position is actually at (30, 0, 0).
With this in mind, you can create a Group for your vehicle, and place all the vehicle parts in the correct positions. Then moving and rotating the Group will cause all of the child meshes to move and rotate along with it.
Comment: Can you please help me because when I tried that I got a weird camera angle?
Comment: @KobyK If you are having a new problem, please create a new question with reproducible steps.


Django - runserver error

Question: beginner here. I have no clue how to solve it (errors are in attached image). Tried to implement solutions for similar errors posted, but none worked.
ERRORS
Comment: I can't understand how a question with no code, linking to a *picture* of errors on an external site, got an upvote.
Comment: btw got Windows 10, Python 3.5.1, Django 1.9.4
Comment: Can you include the image in your post?
Comment: Upvotes are serious business, right?

Also, all uploaded images are reuploaded to imgur via stack.
Answer: gethostbyaddr() throws an UnicodeDecodeError because your Windows hostname contains non-UTF-8 characters.
You'll have to remove those characters from your hostname to get Django running.

Django - runserver error


How do I speed up Ubuntu 16.04 on my laptop?

Question: My laptop is 2GB, 1.2GHz dual core, LUKS. I installed Ubuntu in place of Windows XP and I thought it would go faster, but it's dog slow. This is what I have to live with:
Comment: Xubuntu is a better choice for low end hardware. Generally, keep in mind that Windows XP is an OS from 2001.
Comment: Really? What does Ubuntu have that Xubuntu doesn't? I'd like to print and connect my iPhone and use Bluetooth (but Ubuntu bluetooth is broken anyways).
Comment: It could be media scanner 2.0
Comment: Well, it's actually easy to look up, read a review of something. The two have the same underlying system, but different DEs - Desktop Environments.
Comment: @Chloe there is Lubuntu. I  have it on a machine with half of yours parameters and it works good. It gives me much better performance than WinXP.
Comment: Using encryption will undoubtedly require more processing power than not. This is likely the root cause of perceived slowness.
Comment: @elder geek - That was on the back of my mind but I thought encryption was fast now and processors have special instructions for it? Mine is Intel Centrino. How do I tell how much time is spent on encryption? `top` doesn't show it - only apps like Firefox are on top. How do I turn encryption off to see if there is any difference?
Comment: @Chloe "Centrino" is a marketing term and honestly tells me very little. All processes use CPU cycles. As nothing is infinite everything you use for one purpose is unavailable for another purpose. This bit of logic is the source of my comment above.  [Encryption performance varies by Algorithm](http://www.cse.wustl.edu/~jain/cse567-06/ftp/encryption_perf/) <-This link will provide a comparison. Be that as it may,  turning off encryption is actually covered in several Q&A's here already.
Answer: First step: Decrease swap use. This is specially useful fow low RAM (2GB or less) systems.
You can check swap use by this command:
cat /proc/sys/vm/swappiness

This is generally set to 60.
To change the swappiness into a more sensible setting, type in the terminal
sudo nano /etc/sysctl.d/99-sysctl.conf

At the end of this file, append the following line.
vm.swappiness=10

Disable Unneeded Startup Applications.

launch startup application by typing startup in dash and to disable a startup application, simply uncheck it.
Disable Fancy Effects
 Use compizconfig-settings-manager to disable them

Install using
 sudo apt install compizconfig-settings-manager

and disable unwanted effects
Install preload
sudo apt install preload

This software memorize what applications you use most often and preload related libraries and binaries into memory so these applications can be launched faster.
Comment: Do I have to restart for `vm.swappiness` to take effect, or restart a service? I only had 3 startup items, Gnome, Indicator Application, and SSH cache. I also disabled `Alt-Tab` for Unity and enabled Static Application Switcher - much faster! I currently have Unity plugin disabled and it seems quite fast, but no task bar, window borders, or even menu bars so I guess I have to re-enable that. Neat!
Comment: @Chloe Yes you have to restart for `vm.swappiness` and also you can uncheck Gnome and SSH cache.  If disabling unity plugin causing some problem then re-enable it.


Truncated figure with plotly

Question: I am facing a problem with the Scatter3d from plotly: the figure is always truncated at the bottom:

I create the plot via plotly.express this way:
fig = px.scatter_3d(BFM_pcaFull, x=0, y=1, z=2, color=3)

with BFM_pcaFull being the pandas.DataFrame where the data are stored. I tried to create the plot via plotly.graph_object instead of plotly.epxress but the result is the same.
I tried to tweak the layout parameter via the update_layout() method of fig:

Padding
Auto margin
Scaling
scaleratio
constrain

of course without any change to the graph (which does surprise me and make me think I am doing something wrong, even if apparently the 3D surface seems to follow different rules somewhat).
An issue for the same problem is open on the Github repo of the project but has not been solved so far (https://github.com/plotly/plotly.py/issues/3785).
Has anybody faced the same problem and found a solution by any chance?
Thanks for your help
Comment: This is always a troubling event. It can be corrected by modifying the camera angle. See [here for details](https://plotly.com/python/3d-camera-controls/#changing-the-camera-position-by-setting-the-eye-parameter). Whether the result is satisfactory is another matter. Looking at the improved result, I thought that the 3D view was prioritized at the expense of cutting. `fig.update_layout(margin=dict(l=0,r=0,t=0,b=0), scene_camera=dict(eye=dict(x=2.0, y=2.0, z=0.75)))`
Comment: Perfect it absolutely solved the problem (thanks for the edit too). I guess you can put your comment as answer so I can up vote it. Thanks a lot
Answer: To avoid missing parts of the graph in a 3D graph, you can change the viewpoint angle. See here for more information. The following code can be used to deal with this problem.
import plotly.express as px
df = px.data.iris()
fig = px.scatter_3d(df, x='sepal_length',
                    y='sepal_width', z='petal_width',
                    color='species')
fig.show()

When the camera viewpoint is changed
fig.update_layout(margin=dict(l=0,r=0,t=0,b=0), scene_camera=dict(eye=dict(x=2.0, y=2.0, z=0.75)))

Answer: When I encountered a similar problem, it was helpful for me to vary the 'center' parameter as well as the 'eye' parameter (see this example on the plotly website, and the corresponding section of the api reference).
The parameters eye=dict(x=1.3, y=1.3, z=1), center=dict(x=0, y=0, z=-0.2), worked well for me.
The eye parameter determines the position of the camera (eye), relative to the coordinates of the 3D domain (center (0,0,0), and extending to $\pm 1$ in each coordinate I believe).
The center parameter determines 'where the eye looks' so a value of -0.2 will shift the plot upwards.
I hope this helps complement the answer above.

Truncated figure with plotly


Django template large data pagination link issue

Question: I am using the django paginator in my template. Its working ok with less data, but not working good when there's large numbers of pages.
Pagination links code is given bellow:

        {% if match_list.paginator.num_pages > 1 %}

            {% if match_list.has_previous %}

            {% endif %}
            {% for j in match_list.paginator.page_range %}
            {% if match_list.number == j %}

{{ j }}

            {% else %}

{{ j }}

            {% endif %}
            {% endfor %}

            {% if match_list.has_next %}

            {% endif %}

        {% endif %}

After this i am gettin the links in my template like :

what i actually want is i want to display only 10 links after that ... to show more can anyone please help me relatred this i am stuck here
Answer: https://docs.djangoproject.com/en/3.1/topics/pagination/#paginating-a-listview
try this
{% load core %}   // core here is template tag
{% if match_list.paginator.num_pages > 1 %}

            {% if match_list.has_previous %}

                        First

            {% else %}

                        First

            {% endif %}
            {% if match_list.has_previous %}

                        «

            {% else %}

                        «

            {% endif %}
            {% for i in match_list.paginator.page_range %}
                {% if match_list.number == i %}

                        {{ i }} (current)

                {% elif match_list.number > i|add:"-5" and match_list.number < i|add:"+5"%}

{{ i }}

                {% endif %}
            {% endfor %}
            {% if match_list.has_next %}

                        »

            {% else %}

                        »

            {% endif %}
            {% if match_list.paginator.num_pages != match_list.number %}

                        Last

            {% else %}

Last

            {% endif %}

{% endif %}

custom template tag
@register.simple_tag(takes_context=True)
def param_replace(context, **kwargs):
    """

    """
    d = context['request'].GET.copy()
    for k, v in kwargs.items():
        d[k] = v
    for k in [k for k, v in d.items() if not v]:
        del d[k]
    return d.urlencode()

output
Comment: not working error  : Invalid block tag on line 77: 'param_replace', expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag?
  and one more thing cant you edit my design ?? cos i dont want to compromise with design
Comment: This is not working  my bad .can you please update my html code with your logic ?? because i need that design only and i am passing the querystring as p in url. please update my html with your conditions
Comment: @Pankhuri you can try this https://stackoverflow.com/a/46329564/5600452
Comment: same i tried before but that is not working with my design help me out @c.grey i am really stuck here
Comment: Thanks @c.grey it working now thanks a lot


What percent of Attack Speed would max Evelyn with her ult on?

Question: Trying to create an AD carry build but cant figure out the best items due to not knowing the exact %AS to use as to not waste it with her ultimate being on.
Answer: Her base attack speed is 0.658 +3.84% per level. At level 18 her attack speed is 1.087. Her ulti gives her  75% attack speed increase(of her base attack speed.) That puts her at 1.90225.  Attack speed caps at 2.5 so we need to increase the attack speed approximately .6
An additional 55% attack speed from items will allow it to cap.


Ubuntu 12.04 - can't detect 2 displays

Question: I'm running ubuntu 12.04, my graphic card is:
VGA compatible controller: Intel Corporation Haswell Integrated Graphics Controller (rev 06)
I have 2 Display but the desktop is not extended, both displays show the same screen. If I go to display settings, it says that a laptop display is detected, but not 2 Displays.
How can I use both Displays for an extended view?
Comment: what is the output of `xrandr -q` command
Answer: Same sort of problem occurred on my system(i5-4570s).
And I found this page..
But I have just solved this probrem, NOW!
Just Try It!
My vga is

00:02.0 VGA compatible controller: Intel Corporation Xeon E3-1200 v3/4th Gen Core Processor Integrated Graphics Controller (rev 06)

/var/log/Xorg.0.log showed fbdev modules was loaded and
 Display was detected as Single Virtual Monitor.
There are some new intel driver modules packages,
 but old xserver packages on 12.04 is not suitable to install those.
Finally, I found newer xserver package distributor.
<code>https://launchpad.net/~xorg-edgers/+archive/ppa

sudo apt-add-repository ppa:xorg-edgers/ppa
sudo apt-get update && sudo apt-get dist-upgrade
</code>
After that, new intel driver module is loaded and
 2 displays are also detected.

Ubuntu 12.04 - can't detect 2 displays


How can I remove stubborn nails from baseboard?

Question: I have tried pounding the nails out through the front, they don't budge.  I have tried pulling the nails through the back with pliers, they break off. The baseboard is a laminate from old laminate flooring.  The nails were obviously put in with a pneumatic nailer.
Any suggestions for removing the nails so I can replace the baseboards would be appreciated.
Answer: I usually use a pair of end cutting pliers, to pull the nails out the back.

The face of the tool is slightly rounded, which allows for a good rocking motion.
Just grab the nail gently with the pliers, as close to the work piece as possible. Rocking the tool on it's rounded face generates quite a bit of leverage, allowing you to pull most nails out. Just remember not to squeeze too hard, or you'll simply cut the nail off.
Comment: This is my usual method. I've heard them referred to commonly as "end nippers."
Comment: @Doresoom That's how I usually refer to them, but I try to use the proper term in answers.
Comment: Channel lock pliers work well in the same way - one side is curved, and you don't have to worry so much about cutting the nail.
Comment: They're also often called carpenter's pincers. Some designed specifically for nail pulling (not as sharp, longer handles) are also available.
Answer: You could also use a claw hammer.
An also if you needed you can put a block under the pliers/hammer for more leverage an to protect what ever it is
Can make it a little easier.
Or cut/snap the nails off and punch them out with a nail punch.
Comment: A paint stick behind pliers was enough for me.


Integrate CMS like Umbraco in existing application

Question: We develop very business-case specific applications, but all applications have something in common: some pages or some parts of pages need to be freely content-managed. We often rebuild the same functionality in each application: display and editing of CMS pages.
There must be a better way! Is there any .NET CMS that can be plugged in the way we can in the main application iterate on the available pages and display them using a simple API which outputs HTML, and management of those pages is done in the backoffice / administrative pages of the CMS application.
I would imagine, for example Umbraco, which offers an extensive backoffice. You would in the backoffice be able to add, remove and edit pages. The developer would in code simply use an API like:
<code>UmbracoCms.Core.PageManager.GetPage('CONTENTBLOCK-HOME')
</code>
This would for example retrieve the HTML content for a content block on the home page.
Does anything like this exist in the .NET ecosystem, or are there alternative solutions? The basic question is here: How would you add CMS functionality (by preference, already from a well-known CMS like Orchard or Umbraco) into an existing web application without rebuilding and reinventing a wheel each time over and which solutions already exist? What solution would allow plugging in the CMS into the existing application instead of trying to get an existing application to work in a new CMS application?
Answer: If you have properly separated application, there would be no problem to integrate it with Orchard as module.
Modules in Orchard are like MVC area so it is like subapplication.
Separate business logic, domain entities and data access to separate libraries which will know nothing about Orchard. Create Orchard module just as presentation layer and as point for registering all your dependencies in Autofac IoC which is used by Orchard.
If your application is improperly designed ... ex .. all business logic is in controller, then you are in trouble.
Comment: And what about the part in the 'main application', how to let content be rendered by Orchard?
Comment: Treat it as usual controller with layout (like master page) delivered by Orchard with Orchard's widgets around. Orchard puts result from your controller into zone Content. It is enough to decorate action with Orchards [Themed] attribute.


Does Lagrange Multipliers method provide a way to classify relative minimum and maximum points?

Question: In all the problems I've seen about Lagrange's multipliers method they always ask for absolute minimum and maximum points, but what about relative ones?
In this example:
$f(x,y)=x^2+3y$ subject to the restriction $x^2+y^2=5$
the method provides the following points $ P=(0, \sqrt{5})$
$ Q=(0, -\sqrt{5})$, $ R=(\frac{\sqrt{11}}{2}, \frac{3}{2})$
$ S=(-\frac{\sqrt{11}}{2}, \frac{3}{2})$
so
$f(P)= 3\sqrt{5} \approx6.69$
$f(Q)= -3\sqrt{5}\approx-6.69$
$f(R)= \frac{29}{4}=7.25$
$f(S)= \frac{29}{4}=7.25$
So one concludes that Q is a minimum point and R and S are maximum points
but how do I determine the nature of P: relative maximum, relative minimum ?
A graph of the function tells me it should be a relative minimum (the intersection curve bends down in a neighbordhood of point P):

Besides I tried solving it by studying the single-variable function $h(y)=
5-y^2+3y$  which I got by plugging in the restriction into f. By making $h'(y)=0$ I found $y=3/2$  and considering $-\sqrt{5}\leq y \leq \sqrt{5}$
to be it's domain to stay in the restriction,  $y=\sqrt{5}$ and $y=-\sqrt{5}$ are also possible extrema points.
Plugging in this values into the restriction $x^2+y^2=5$, yields the corresponding x-components, so the same P,Q ,R and S points found with the first method.
Then, comparing the values of h(y) in the y-components of these  points:
$h(\sqrt{5})=3\sqrt{5}=f(P)$
$h(-\sqrt{5})=-3\sqrt{5}=f(Q)$
$h(\frac{3}{2})= \frac{29}{4}=f(R)=f(S)$
Q is found again to be a minimum point and R ans S to be maximum points.
But now I could use second-derivative test for P:
 $h''(y)=-2 < 0$ ,  for any $y$ and so $P$ should be a local maximum, in contradiction with graph that shows it to be local minimum, What is this second method not working and how do both  methods determine P is a  relative minimum?
Comment: by the way, You've written $f(x,y)$ so are we to assume $f$ is defined on $\Bbb{R}^2$? because if this is the case, then your picture is $3$-dimensional and hence doesn't match up with what you said. But if you do indeed consider $f$ as a function of $3$ variables $f: \Bbb{R}^3 \to \Bbb{R}$, $f(x,y,z) = x^2 + 3y$ then your picture is correct, but you haven't found all the critical points. Because your work only determines the $x,y$ coordinates of the critical point, but it doesn't constrain the $z$-coordinate. So, in $3$ dimensions, you will have in addition, one critical point for each $z$
Comment: yes on R^2, I just draw the cylinder , to see the points of the surface f , to which it is restricted
Comment: by the way, an alternative approach to this problem is to simply parametrize the circle by $t \mapsto (\sqrt{5} \cos t, \sqrt{5} \sin t)$. If you were asked explicitly to solve using Lagrange multipliers, then of course this is not the way. But if you have the freedom to use any method, I believe this parametrization will give a very quick method of finding critical points of $f$ (when restricted to the circle) and classify them
Answer: The second derivative test tells you about the type of critical point on the interior of the search interval.  Let's temporarily set aside the source of the equation and just try to solve

Extremize $h(y) = 5 - y^2 + 3y$ on $[-\sqrt{5},\sqrt{5}]$.

The second derivative tells you whether an interior critical point, the one at $y = 3/2$ is a local minimum, local maximum, neither, or unresolved.  It cannot speak to the endpoints because the first derivative is not (generally) zero at the endpoints.  As far as the first derivative is concerned we could find even lower points by pushing just outside the search interval.
Additionally, notice that you are looking at the first and second derivatives in the $y$ direction.  The $y$-axis in your diagram is the green one.  At the points $P$ and $Q$, infinitesimal displacements in the $y$ direction leave the surface of the cylinder.  It may well be that the second derivative in a direction that is disallowed by the constraint is negative, but the intersection curve you see on the constraint cylinder is running in the $x$ direction at $P$ and $Q$.  To understand their behaviour, you need to be taking derivatives in the $x$-direction, which means eliminating $y$ between the objective function and the constraint and extremizing this new single variable objective function.
Expanding on this last.  From the constraint, either $y = \sqrt{5 - x^2}$ or $y = - \sqrt{5 - x^2}$.  In the first case, $h_1(x) = x^2 + 3\sqrt{5 - x^2}$,

$h_1'(x) = 2x - \frac{3x}{\sqrt{5-x^2}}$, and $h_1'(x) = 0$ when $x \in \{ -\sqrt{11}/2, 0, \sqrt{11}/2 \}$ where $h_1'(\pm \sqrt{11}/2) < 0$ and $h'(0) > 0$.  This finds your points $R$, $P$, and $S$ and assigns the correct local extremization to each of them.  Switching to $h_2(x) = x^2 - 3\sqrt{5 - x^2}$,

only $h_2'(0) = 0$ and $h_2''(0) > 0$, correctly identifying $Q$ as a local minimum.    We should also check $h_1(\pm \sqrt{5})$ and $h_2(\pm \sqrt{5})$ because calculus does not generally tell you about the endpoints (consider the extremization of a nonconstant line -- the derivative is never zero and the extrema occur at the endpoints of the search interval).  The first derivative is mute on these points because infinitesimal displacement from these points in the $x$ direction (along the red axis in your picture) leaves the constraint cylinder, so the first and second derivatives in $x$ tell you nothing about these points.
Comment: Just a clarification, you said..." the intersection curve you see on the constraint cylinder is running in the x direction at P and Q", if I consider a neighborhood of the instersection curve, it has a component in both the x and y direction, so you can't say it is running in the x direction, can you?
Comment: This is an excellent answer which addresses the need to be careful with boundary points. I realized that this was the issue with OP's work, but I just didn't know exactly how to phrase it properly. +1
Comment: @juancarlosvegaoliver : The tangent to the intersection curve at $P$ is parallel to the red ($x$) axis.  Likewise, the tangent to the intersection curve at $Q$.  The derivatives live in the tangents.
Answer: There is a second derivative test for constrained problems, based on the bordered Hessian matrix. You can find the statement in my book Multivariable Mathematics: Linear Algebra, Multivariable Calculus, and Manifolds in problem 34 on p. 225. This handout which I found with a search may do the trick for you.
Comment: thanks for the handout


Are these blue spots on stove coil cups poisonous Verdigris?

Question: I live in the USA and have one of these stoves:

For me who comes from Europe, the design of these stove tops always baffles me compared to flat (metal or glass) stove tops seen across Europe (it seems to be losing a more energy, the materials rust easily, and it's always so hard to clean!). Today, I met with this strange situation where the cup under the coil, after I cleaned it, started showing scary blue spots:

Although these marks are very photogenic, I am afraid that they might be Verdigris.
Is it possible that the material used in stove cups would be that easily corroded that it actually produces poisonous substances such as Verdigris when cleaned?
Obviously this one is a bit old and might need changing - probably for one that is made out of a material that doesn't corrode that easily (I love spending money on this stuff! ❤ ), but if someone can confirm that these stains are not dangerous, I'll try and make it last a little longer. At least till I find a really cheap one that is rustproof on eBay (since I'm not really keen on giving to this "bad design makes the end user waste money having to fix stuff" philosophy).
Thank you for your help!
Comment: Not dangerous, unless you scrape that stuff off and snort it or eat it,. Just scrub the things with steel wool and hot soapy water and put them back on. The food you *actually eat* is probably more dangerous.
Comment: These are for rental units.  Tenants tend to treat glasstops roughly (not least by using the wrong pots and pans).  These are easy to keep nice: change the drip pans ($3-5 each) and any nasty heating elements, and the stove is "good as new".  A tenant in a hurry to get his deposit back will often run out and buy cheap or ill-fitting ones like the above.  Homeowners do typically get glasstops.  Anyway, yours are chrome plated steel - they're rusted. Rust only happens to iron and steel (more the latter).  Just buy new ones. http://amzn.to/1rmtWZf
Comment: Right, it's just the lowest-end electric range. There are better ones. You can buy one if you're the owner. If you;re the renter, you can always ask the landlord. It's possible they'll give you a break on rent that month if you buy one.
Comment: No one makes drip pans out of copper. The stuff is too expensive, and its heat conductivity would just be a waste there. Plus, it bends easily. You've probably got some funny colored steel or chrome oxides there.
Comment: A break on rent, you mean allow me to deduce the price of what I paid for it from the rent, right, I don't think they'd have me not pay the rent because I bought a $5 stove cup lol
Answer: Try a magnet - dollars to doughnuts, those are somewhat peeled and rusted chrome plated steel, and the blue is a normal steel oxidation color, and not toxic (also, were you planning to drip food down there, scrape it off and then eat it? If not, nothing to worry about regardless.) They are stunningly unlikely to be copper, though there may be a minuscule amount of copper plating as part of the chrome plating process
This is reinforced by the purple color, which is a slightly different temperature in the steel oxidation colors (we use them for determining temperature when tempering hardened steel.)

Image from Maille Artisans International League website
While you could waste money and effort replacing them, you could also make them more efficient (reflect heat better) and easier to clean by applying aluminum foil to them (shiny side up - you want to reflect as much heat as possible.) As a side effect this would also contain the non-toxic steel oxidation. When something is too badly burnt onto the aluminum foil, remove it and replace with new foil.  Mold the foil to the pan, wrapping over the edges - cut stars in the openings and fold the cut parts onto the backside.
FYI - stainless steel will also blue, at slightly different temperatures.
Comment: Hahah, well of course I wasn't gonna eat food that touched this, but sometimes when you're busy in the kitchen it's better to have a free mindset and go about preparing the food rather than be worried because you might or might not have touched something toxic prior to peeling carrots :P

Thanks for the great tip, although wrapping aluminium foil around the cups seems it would produce a less than aesthetic result :D
Comment: Looks perfectly nice if you mold it to the reflector (not too difficult to do.) If you want to do a bad job I'm sure you can make it look bad, but it looks (and more importantly, as a heat reflector, **functions**) much better than rusty, crusty chrome (and actually functions better than chrome, period, even if the chrome is shiny and new.)
Comment: Ok, I get it. Thanks for the input. We're not here to debate, but I just thought questionable the quality of a design that implies that to make it function better, the user should tinker with it, wrapping parts of it with foil. Seems user-unfriendly, if not a bit archaic [considering this design, used in many other countries](http://image.darty.com/gros_electromenager/cuisinieres/cuisiniere_electrique/brandt_ke900w_k0109173204456a_1267173498413.jpg).
Answer: Edit3: Bleach will react with copper to produce copper hydroxychloride and as wikipedia says, is commonly found in metal corrosion products. Iron (II) chloride is often greenish colored. Iron and copper chloride will react to produce iron chloride.
Looks like bornite (Cu5FeS4) (yes, bornite is toxic too). But it's unlikley, unless someone spilled some sulfur in the mix. It's definitely a copper mineral of some kind... copper is very commonly used when plating chrome.

Revised answer:
The cups are chrome plated steel. Usually chrome plating starts with copper plated to to steel, then chrome is attached to the copper layer. There may also be other trace metals including nickel, cobalt, tungsten, and zinc.
Why do they plate the cups with chrome? Because chrome plating is shiny (and shiny means it reflects heat better than stainless steel; and chrome is more resistant to corrosion and heat discoloration than steel (actually stainless steel has chrome and other minerals to impart the "stainless" qualities).
Steel will easily discolor (especially stainless steel) when it is heated (like Ecnerwal showed in the picture). However, the discoloration that I see in the picture of your cup is not at all similar to the discoloration of heated steel. The colors of your cup look like distinct "minerals" thact could be scraped off into a bag and analysed by a laboratory.
The brightness of the blue completely suggests a mineral comprised of copper. The location of the colored minerals is another strong indicator that this is a chemical reaction; the minerals were formed in areas of corrosion/oxidation where copper and iron, and possibly nickel and zinc are present. The "peacock" coloration suggests sulfur is/was also present. Sulfur may have come from garlic and onions, or possibly residues from sulfuric acid were present from the plating process, if nickel was used as well.
Edit2 - Other acids will also combine with copper to form other minerals. Many cleaners or "rust emovers" contain phosphoric acid, which could make a form of cornetite (a copper phosphorous mineral) which is darker blue and purple.

Azurite (a copper carbon mineral) is usually more blue than purplish. Malachite (another copper carbon) has just a couple extra % copper than azurite

Cuprite + delefossite (CuFeO2 or Cu1+Fe3+O2) can also yield purples and blues.

So in essence what I'm saying is that this is that copper imparts the blue and or green, and it can combine with iron to make purples, but sulfur really brings out the "peacock" colors. The blue is copper that has oxidized most likely from acidic cleaners.
Comment: @fabriced I made some edits to my post. the reason that stainless is not used is because stainless doesn't reflect heat as well as chrome, and stainless will discolor an lose integrity too quickly. Chrome is much more more resiliant.
Comment: @fabriced I know chemistry. It's copper oxidation, but I wouldn't call it verdigris - which better known as, patina. Copper has been exposed and now it is reacting with iron, oxygen and other trace minerals from food and cleaners. The purplish colors are comming primarily from the iron. But you have a hodgepode of minerals there- which the normal way that it happens- as minerals form. Pure minerals are prized (in part) for their rarity. Hopefully my post above will convince you that you have mineral formation, most lilkey caused by an acid cleaner, in the presence of heat.
Comment: Great job with the iconography! Now I want to go and buy beautiful blue stones... No need making tests I'm sure you could reproduce this oxydation with your own stove cups and after damaging them with maybe oily water that boiled on them once and then cleaning them with peroxided bleach-type household products (can give you the precise ingredients if you need!)
Comment: Well, I cleaned it using some sort of bleach / peroxyde. Anything's possible... Why don't they just make them stainless steel beats me.
Comment: @fabriced I actually have the tools and equipment to analyze this... and give a perfectly precise answer, but I wouldn't dare give my address on a public forum. It's a shame.
Answer: I'm a little skeptical because of how purple those stains are, but if these drip pans are made of copper then it could well be Verdigris. This is likely happening because the plates were not sealed properly and vegetable oil was spilled and not cleaned off as heat was applied over time.
If I were you I'd scrape some off (it's OK if some powder comes into contact with your skin once or twice) and set it on a paper towel somewhere. It should turn brilliant forest green over the next couple of weeks if that's the case. While you wait, you can take aluminum foil and wrap the drip pans in them; this is a common technique to help with keeping them clean/protected. The foil wont burn and can be unwrapped and tossed in the trash when you get marks or tears in it.
The danger is really up to your level of tolerance: you'd probably be safe by just cleaning them and the putting them back in; it's only toxic if you ingest the actual substance over time or once in large quantities. You'd almost definitely be safe if you wrapped them in aluminum foil. But if 100% peace of mind is what you're after, I'd ditch them and get new ones; it won't cost you much to get four new Chrome drip pans (maybe $10 to $15).
As far as I know, most drip pans are made of Chrome these days and are not susceptible to the same problem.
If you're up for some more reading, you can check out this ISCA Report on copper and its toxicity.


How to make jQuery rendered content editable in Sitecore experience editor

Question: We have a Sitecore project and the code/files are from an ASP.NET web application.
The HTML for the products section is as follows

Product 1

Product 2

Product Name

     Description

This is how it works for an end user.
EU will click on a Product tab (eg: Product 1), which will change the content inside
, without postback.
For the author, this section must be editable from the Experience editor. Usually, I would use asp:Repeater with sc:Text,sc:Image to render it.
But, here the data has to be retrieved using ajax calls, which means no Repeater or Sitecore controls.
In such case, how can I make the content editable from Experience editor.
The only ideas I came up with:

Get data of all the products in Page_Load, bind it using Repeater and then use jQuery to Show/Hide the respective divs. (doesn't seem a nice way though)
Tell the content author, that this section can only be edited from Content editor and not from the experience editor :)

What are my options here.
Comment: Why close this? Isn't this a common scenario for sitecore devs. If there is something else that needs to be mentioned, please let me know.
Answer: One option could be to render your page differently when in the experience editor. Check the mode in your code and use a repeater when editing, otherwise use the jquery output.
You can use Views to easily display/hide the output you want.
<asp:MultiView runat="server" ID="ProductsView">
  <asp:View runat="server" ID="StandardView">

     ...

  </asp:View>
  <asp:View runat="server" ID="EditorView">
    <asp:Repeater..>
       ...
    </asp:Repeater>
  </asp:View>
</asp:MultiView>

In your code behind:
ProductsView.SetActiveView((Sitecore.Context.PageMode.IsExperienceEditor || Sitecore.Context.PageMode.IsExperienceEditorEditing) ? EditorView : StandardView)

Based on the active view, you can decide to attach data to the repeater or not (don't do that when the StandardView is active, for performance)
Comment: Whilst this may theoretically answer the question, [it would be preferable](//meta.stackoverflow.com/q/8259) to include the essential parts of the answer here, and provide the link for reference.
Comment: @Gatogordo. Please provide some more insight, pointers to help me get started.
Answer: I'm not sure why would an end user interact with Experience Editor as Experience editor is used by Content Authors for authoring the site and updating the content on the Page itself.
But if this is a requirement for a Content Author you can use the sitecore services client api for updating the content using ajax call.
Use this document to see how ssc works.
Let me know if you have a different ask.
Comment: @Qwerty : Is it WebForms? I think in Webforms also you can use the server tags <%={your condition}%> and then use below condition to render the code
Use `if (Sitecore.Context.PageMode.IsPageEditorEditing) or
 if (Sitecore.Context.PageMode.IsPageEditor

let me know if that helps.
Comment: Also you can try this link which shows how to use PageEditor mode but this talks about Razor view so you would need to use it as i mentioned above using server tags in WebForms - [Link](http://www.sitecore.net/learn/blogs/technical-blogs/martina-welander-sitecore-blog/posts/2013/07/improving-the-page-editor-experience-part-3-detecting-page-mode.aspx)
let me know if that helps.
Comment: My post doesn't say EU will edit ! It was only to explain how it works for the EU. The content of course should be updated by ajax, but at the same time the author, should be able to edit via Experience editor. Appreciate. if you can point to an example instead. If you did not get the question, please let me know.
Comment: I think you should create another view for the Experience editor mode and render it based on the display mode. And for doing that you can extend the MVC display mode and extend the controllerrendering and viewrendering to be able to handle the PageEditor views.
Comment: Can you please provide any link for reference. Also, this is an ASP.NET and not MVC. Will it work


Send audio buffer in parts to a server from an iOS device's microphone

Question: I am trying to build an iOS application that streams audio coming directly from the input (or mic) of a device. What I am thinking is that every certain period of time, I'd have to send the audio buffer to the server, so that the server sends it to another client that might want to listen. I am planning to use WebSockets for the server-side implementation.
Is there a way to grab just a specific stream of buffer from the input (mic) of the iOS device and send it to the server while the user speaks another bit and so on and so forth? I am thinking that if I could start an AVAudioRecorder perhaps with AVAudioEngine and record every 1 second or half a second, but I think that that would create too much of a delay and possibly lost streams in the transition process.
Is there a better way to accomplish this? I am really interested in understanding the science behind it. If this is not the best approach please tell me which one it is and maybe a basic idea for its implementation or something that could point me in the right direction.
Answer: I found the answer to my own question!! The answer lies in the AVFoundation framework, specifically AVCaptureAudioDataOutput and its delegate that will send you a buffer as soon as the input source captures it.


Cast double to int, but only if exact conversion

Question: I'm getting a value of type double from an API which, in my specific case, should always return a whole number in a range well within int's — any non-whole number will mean something went very wrong inside that API call. I do want to know when this happens.
I know I can do a post-conversion check like, let say:
double value = …;
int whole_number = (int) value;
if(value != whole_number) throw …;

Is there any shorter idiom to "Convert a double to int only if it is an exact conversion, and raise an exception if not"?
Comment: Yes ... but 1) it involves a **major** overhead of converting the `double` to a `BigDecimal`, and 2) it is not clear that it will give the same answer in all cases because of the difference between base 2 and base 10 representations.
Comment: This question reminds me **strongly** of one I answered in...2008? May have to go looking...
Comment: @T.J.Crowder feel free to make it a duplicate, then. I couldn't find anything.
Comment: https://stackoverflow.com/a/9909417/3182664 (ignore the accepted answer there)
Comment: @Marco13 Still not exactly an answer to his
Comment: @liori - It's such a vague memory... It was probably something else. :-)
Comment: @YassinHajaj I don't want to argue. Feel free to add a reopen vote. But if the point of the question is whether you can or have to wrap 3 lines of code into a `doMyStuff` utility method, then this should be pointed out more clearly. There's certainly no built-in functionality for that in the standard API.
Comment: @Marco13, I thought I made it clear with asking for "any shorter idiom".
Comment: The answer to this question is No.  There isn't a shorter idiom ... apart from the obvious one of "make it a method and call it".   I agree that this is a dup.
Comment: @liori You can check my answer in which I have used `intExactValue()` provided in `BigDecimal` class. It's a short and concise solution.
Comment: @StephenC You're right. If we see the implementation of `intExactValue()` method, it's not that much short. And I think we should use their implementation rather than writing the logic to check these conditions ourselves.
Comment: @StephenC, if this is a dup, then how come none of the answers there answer my question? If the answer to my question is "no", then how about just writing an answer of "No" as an actual answer here?
Comment: Please read [The "reasonable user" theory of duplicate questions](https://meta.stackoverflow.com/questions/384711/the-reasonable-user-theory-of-duplicate-questions/384792#384792).  It applies to this case ... in my opinion.
Comment: @StephenC it would be if the decomposition was the answer. Not if the question is about *avoiding* decomposition.
Answer: Your solution seems simplest to me. You can do it as a one-liner:
if (value != (int)value)) throw ...

but if you want the exception to be thrown for you, the only thing I can think of is to go through a String, which seems really convoluted, especially since you can't just use String.valueOf(value) to get the string:
// Seems really convoluted
Integer.parseInt(new DecimalFormat("##.###").format(d));

Answer: You can use the following check if needed
if (value % 1 != 0) {
    throw...
}

Using an Optional<Double> you could use the following logic
Integer result = Optional.of(value)
                         .filter(d -> d % 1 == 0)
                         .filter(this::isInRange)
                         .map(Integer::parseInt)
                         .orElseThrow(...);

Comment: You aren't checking the `int` range here.
Comment: @ernest_k I didn't see it anywhere mentioned in the question explicitly but here it is :)
Answer: You can use BigDecimal::intValueExact():
int wholeNumber = BigDecimal.valueOf(value).intValueExact();

It will automatically throw an exception: if it has a nonzero fractional part or it is outside the range of int
Comment: So essentially what I wrote in my question, just with a different condition.
Comment: @liori now check the updated solution.


NullPointerException when running application

Question: Everytime I run or debug my application in java blackberry on simulator, I have a null pointer exception.
Thread [net_rim_bb_feeds_lib(230)id=27277312] (Suspended (exception NullPointerException))
ViewManager.insertTopLevelView(ViewImpl) line: 738
I can't know the cause of the problem, could you please help me to solve this error.
Thank you in advance.
Comment: Without seeing any code it might be difficult to help you.
Comment: The cause of the problem is obviously a null pointer. You basically have a null refrence which you are using for something (we can't tell a lot without a code snippet). You should debug line by line, and look out for where you have the null (this exception is a fundamental part of the programming learning curve IMO)
Comment: This sounds like a task for an IDE with a debugger!
Answer: I clean the simulator and no more null pointer.
My problem is solved.


How to count records of particular id in spring boot and hibernate

Question: I am working on a project using Spring boot and hibernate. I want to count records against an id in table. I can count all records of the table but unable to count records against a foreign key.
Here is my controller code
@RequestMapping("/rating/{id}")
@ResponseBody
 public long getRatingInfo(@PathVariable("id") long id, HttpServletRequest req, HttpServletResponse res) throws Exception {

long postobj = myDao.count();
return postobj;
}

Here i am passing an id in url but there is no method of count to pass this id to find records.
And here is my Dao Interface
@Transactional
public interface MyDaoInterface extends CrudRepository<Rating, Long>{
}

Comment: Do you want to count of `rating` for a given `id`?
Comment: Actually i have rating table in my db. In this table i have post_id, user_id and rating_points columns . post_id can be multiple and i want to count all rows of a given post_id
Answer: Add this to your DAO:
@Query(countByPostId)
Integer countByPostId(Long post_id);

final String countByPostId= "SELECT COUNT(ra) FROM Rating ra WHERE ra.post_id = ?1"

And call it likewise:
@RequestMapping("/rating/{id}")
@ResponseBody
public long getRatingInfo(@PathVariable("id") long id, HttpServletRequest req, HttpServletResponse res) throws Exception {

long postobj = myDao.countByPostId(id);
return postobj;
}

EDIT: the second question in the comments:
@Transactional
public interface MyDaoInterface extends CrudRepository<Rating, Long>{
   List<Rating> findByPostId(Long id);
}

and your caller:
@RequestMapping("/rating/{id}")
@ResponseBody
public long getRatingInfo(@PathVariable("id") long id, HttpServletRequest req, HttpServletResponse res) throws Exception {

 List<Rating> ratings = myDao.findByPostId(id);
 long postobj = ratings.size() //use this code where you effectively need the # of entires.

 return ratings;
}

Comment: I am running this query...  "select count(r.id),points from Rating r where r.postId=?1 group by points";   And i am using List as return type.. i am getting results but not getting column name in result
Comment: what should i do here can you tell me?
Comment: Try: `select count(r.id), r.points from Rating r where r.post_id=?1 group by r.points`
Comment: same result... not getting column names
Comment: i am unable to understand which column value is it
Comment: Usually in hibernate you expect an Entity-Annotated-Object or a Collection of it as a result. In your case the following would make sense: `List findByPostId(Long id);` So you get all matching `rating` records. For the count you can use the List.size() method.
Comment: I added a `second question` comment.
Comment: getting same results :(
Comment: Could you open a new question? with the exact problem, what you expect and your stacktrace?
Comment: I have posted a new question here is the link..   http://stackoverflow.com/questions/32310204/not-getting-column-names-in-the-result-of-hql-query
Comment: for this `@Query(value="SELECT a.tagid, a.tagName, count(*) FROM articletaglist a GROUP BY a.tagName" , nativeQuery=true)
 public List findTagCount();`  im getting `No converter found capable of converting from type` ERROR
Answer: @RequestMapping("/rating/{id}")
@ResponseBody
public long getRatingInfo(@PathVariable("id") long id, HttpServletRequest req, HttpServletResponse res) throws Exception {

 List<Rating> ratings = myDao.findByPostId(id);
 long postobj = ratings.size() //use this code where you effectively need the # of entires.

 return ratings;
}


iOS Xode : AVAudioPlayer is not playing WAV file correctly

Question: I have a WAV file with tones at around 18kHz. The audio is 16-bit PCM mono.
I am using the following function to play the file:
func playSound(name: String) {
        let documents = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let path = documents.appending("/").appending(name)

        let url = NSURL.fileURL(withPath: path)

        do {
            player = try AVAudioPlayer(contentsOf: url)
            guard let player = player else { return }

            player.prepareToPlay()
            player.play()
        } catch let error {
            print(error.localizedDescription)
        }
    }

When I play it on my iOS 10.2 device I hear a series of tones between 1000Hz to 10000Hz. I've analyzed the rendered audio by capturing it and a frequency plot shows that the original content at 18kHz is there, but there are also tones present between 1000Hz to 10000Hz. When I play the same WAV file with VLC or any other desktop audio player, I don't hear the tones (which is expected since they're located around 18kHz). I suspect that the code above isn't loading the data correctly or that the player isn't properly initialized, so I need a seasoned iOS veteran who can tell me what I'm doing wrong.
Thank you in advance.
Answer: Check the following code it might work for you
import UIKit
import AVFoundation

class ViewController: UIViewController {

    var audioPlayer = AVAudioPlayer()

    override func viewDidLoad() {
        super.viewDidLoad()

        var alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("button-09", ofType: "wav"))
        println(alertSound)

        // Removed deprecated use of AVAudioSessionDelegate protocol
        AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
        AVAudioSession.sharedInstance().setActive(true, error: nil)

        var error:NSError?
        audioPlayer = AVAudioPlayer(contentsOfURL: alertSound, error: &error)
        audioPlayer.prepareToPlay()
        audioPlayer.play()
    }

}

Comment: thank you, but I was hoping for an answer to what i might be doing wrong


Why reduce is affected by floating point issue and for loop not?

Question: When I write following code with reduce method, values are imprecise:
return bytes.reduce((accumulator, currentValue, index) => {
                 return accumulator + (currentValue * Math.pow(256,(bytes.length - 2) - index));
    }
)

eg. output numbers 5.99609375, 10.99609375, 7.99609375, 14.99609375
But when I write following code result is precise:
let result = 0.0;
for (let i = 0; i < bytes.length - 1; ++i) {
                result = result + (bytes[i] * Math.pow(256, (bytes.length - 2) - i));
    }
return result

eg. output numbers 5, 10, 7, 14
Input byte arrays are:
Uint8Array(4) [0, 0, 5, 255]
Uint8Array(4) [0, 0, 10, 255]
Uint8Array(4) [0, 0, 7, 255]
Uint8Array(4) [0, 0, 14, 255]

Why is that? Is there a way to make reduce method work precisely?

const res = document.getElementById('result');
const res2 = document.getElementById('result2');
const arr = a = [
  [0, 0, 5, 255],
  [0, 0, 10, 255],
  [0, 0, 7, 255],
  [0, 0, 14, 255]
];
const fn = (bytes) => {
  let result = 0.0;
  for (let i = 0; i < bytes.length - 1; ++i) {
    result = result + (bytes[i] * Math.pow(256, (bytes.length - 2) - i));
  }
  return result
}
fn2 = (bytes) => {
  return bytes.reduce((accumulator, currentValue, index) => {
    return accumulator + (currentValue * Math.pow(256, (bytes.length - 2) - index));
  })
}
res.innerText += `${arr.map(fn)}`;
res2.innerText += `${arr.map(fn2)}`;

Comment: both code snippets produce a single number and not several. Also, give a sample input to reproduce said behavior.
Comment: You have not provided the initial value of the accumulator in the array#reduce.
Comment: I do not see the initial `0` accumulator in the call of Array#reduce(fx, accumulator)
Comment: @MihaiAlexandru-Ionut Everything on stackoverflow must be upvoted - for properly formatted and solvable questions like this i don't get mad, unlike other questions for which i could write a bot to post within a day.
Comment: Riht, but these are eg. output numbers, not eg. output Arrays.
Comment: Also, please provide the bytes array.
Comment: The default is the first array element, i actually thought it was plain summation but that comment is the answer very likely.
Comment: Please provide real [mcve]s, preferably as [a live demo](https://stackoverflow.blog/2014/09/16/introducing-runnable-javascript-css-and-html-code-snippets/).
Comment: The two iteration methods are not equivalent, since the `for` loop misses the final element. If you change that, you will get the same result in both cases.
Comment: @vlaz You are right, but the question is why, and how to do same in reduce.
Comment: You cannot easily do it. This is because `reduce` is designed to run through the whole array - you could basically check if you've reached the last element and then exclude it but it might just be easier to just remove the last element before running `reduce` on the array. Something like `arr.slice(0, arr.length - 1).reduce( /* ... */ )` can do it.
Comment: @vlaz in my case `bytes.slice(0.3).reduce...` was the answer. I see now also, it was wrong question, but it solved something, I spend too much time thinking, so thank you.
Answer: The for condition is wrong
Should be
 for (let i = 0; i < bytes.length ; ++i) {

Answer:
Why reduce is affected by floating point issue and for loop not? When I write following code with reduce method, values are imprecise

That is not a case of floating point issue. If you look at the results you will see something like this:
5.99609375

When you have floating point precision is something like this
0.020000000000000004

The problem is in the for loop because you're iterating only the first n-1 items from bytes array.
for (let i = 0; i < bytes.length - 1; ++i) {

Just iterate all the array items.
for (let i = 0; i < bytes.length; ++i) {

You are seeing two values because reduce method run through all the array items, and for loop run through first n-1 items.
Unfortunately, there is no way, of course, to get the built-in version of reduce to exit prematurely.
But you can use slice method.
return bytes.slice(0, -1).reduce((accumulator, currentValue, index) => {
    return accumulator + (currentValue * Math.pow(256,(bytes.length - 2) - index));
})

Comment: @Zydnar, you are getting a floating number because it's reached a step when you have `Math.pow(256, -1)` which is `1/256`. But in reduce method you cannot use `break` method or something like this: https://stackoverflow.com/questions/36144406/how-to-break-on-reduce-method
Comment: Good answer but in for loop NOT in reduce I get expected output, so problem is not in for loop.
Comment: You are seeing two values because `reduce` method run through all the array items, and `for` loop run through first `n-1` items.
Comment: Ok, I see it now.


$L^p$-norms for the case of $\mathbb{R}^n$

Question: Let $\mathbb{R}^2$, $1 < p <\infty$ and $\theta\in (0,\infty)$. We consider the mapping
$$
\Gamma : \mathbb{R}^2\rightarrow [0,\infty)
$$
defined by $\Gamma(x) = (|x_1|^p + \theta\cdot |x_2|^p)^{1/p}$ with $x = (x_1,x_2)$. My question is whether or not this mapping is strictly convex, that is
$$
\Gamma(\lambda\cdot x + (1-\lambda)\cdot y) < \lambda\cdot\Gamma(x)+(1-\lambda)\cdot\Gamma(y)
$$
for every $x,y\in\mathbb{R}^2$ and $\lambda\in [0,1]$.
If we remove the term $\theta$ in the definition of $\theta$ is the common $p$-norm or $L^p$-norm, which is strictly convex whenever $p > 1$. ç
I have the intuition that it is true, but I am stuck in that problem.
Comment: What is $ \theta $? Is it just a real number or a positive real number or the theta function from number theory?
Comment: @P.Lawrence I quote " $ \theta \in (0,\infty) $ ".
Answer: We can equivalently prove that set $S_\alpha$ defined as $\{x:\Gamma(x)\le \alpha\}$ are convex for $\alpha>0$. Note that this set is symmetric w.r.t. both $x_1$ and $x_2$, which implies that the convexity of $S_\alpha$ is equivalent to that of set $T_\alpha=\{x:x_1\ge 0,x_2\ge 0,x_1^p+\theta x_2^p\le \alpha^p\}$. We can rewrite $T_\alpha$ as
$$
T_\alpha=\left\{x:0\le x_1\le \alpha ,0\le x_2\le \frac{1}{\theta}(\alpha^p-x_1^p)^\frac{1}{p}\right\}.
$$The convexity of $T_\alpha$ then follows from the concavity of $y=\frac{1}{\theta}(\alpha^p-x^p)^\frac{1}{p}$ for $x\in[0,\alpha]$. Since $y\in C^\infty (0,\alpha)$, we have
$$
y''=-\frac{1}{\theta}(p-1)\alpha^p\left(\alpha^px^{-p}-1\right)^{\frac{1}{p}-1}x^{-p-1},
$$we easily conclude that $y$ is concave for $x\in [0,\alpha]$ and the conjecture is proved $\blacksquare$


what is probability of throwing $n$ dice $m$ times to get at least one 6 for each dice

Question: We have $n$, 6-face fair dice. At each time $n$ dice are thrown independently. I want to calculate the probability of number of times we should throw dices before having at least one 6 from each of the dice.
We know that for one die to have one 6, the probability of $k$ failures obeys a Geometric Distribution with $p=1/6$ and expectation of 6.
How should I extend this to $n$ dices?
Answer: Label the dice $1$ to $n$. Let $X_1$ be the number of throws of the first die until we get a $6$. Define random variables $X_2, X_3,\dots, X_n$ analogously.
Let $Y=\max(X_1,X_2,\dots,X_n)$. Your question asks for an expression for $\Pr(Y=y)$.
It is easier to find $\Pr(Y\le y)$. That will do it, because
$$\Pr(Y=y)=\Pr(Y\le y)-\Pr(Y\le y-1).\tag{$1$}$$
Now we go after $\Pr(Y\le y)$. We have $Y\le y$ iff we have at least one $6$ on all the dice by time $y$.
The probability that there was at least one $6$ on die $1$ by time $y$ is $1$ minus the probability of no $6$, so it is
$$1-\left(\frac{5}{6}\right)^y.$$
For $n$ dice, take the $n$-th power. We get
$$\Pr(Y\le y)= \left(1-\left(\frac{5}{6}\right)^y\right)^n.$$
Now use $(1)$.
Comment: Thank you @Andre. This seems correct. I tried using Negative Binomial and calculating P(X1 + X2 + ... + Xn > N). Actually your method is much more simpler!
Comment: I think the sum of my $X_i$ does not lead to a solution of the problem.


Posting a (ASP) Form with text area and onClick=Java... via CURL

Question: I'm trying to pass some info to an ASP webpage.
The form on the page looks as following:
<form name=onlineform  method=post onSubmit="javascript:return false;">
<input type=hidden name="form" value="">
<textarea name=item rows=5 cols=33 onBlur="this.value=removeSpaces(this.value);" tabindex="1"></textarea>
<input type="text" name="Email" size="26" tabindex="2">
<input type="image" src="resetButton.gif" width="60" height="30" border="0" onClick="javascript:onlineform.reset();" align="bottom"  tabindex="3">
<input type="image"src="SubmitButton.gif" name="Submit" width="60" height="30" border="0" onClick=javascript:check_input() align="bottom" tabindex="4">
</form>

The email section is optional so I would only like to fill the text area and submit the form, capturing the return to be displayed later.
Problem 1 I have is the text area, problem 2 is the submit (onClick=javascript:.....).
Can anyone help?
Thanks !!!
Answer: What that onsubmit="return false;" does is prevent the form from submitting without going through validation (the function check_input(), which is attached to the onclick handler). The textarea just has to execute the function removeSpaces() to its contents (whatever that does) once it loses focus.
So really, if you are creating the input on PHP you just have to make sure your input passes validation (check_input()) and your textarea input has "applied" the removeSpaces() function (you might have to rewrite that in PHP).
Then you can post to the ASP script and it won't be able to tell if the form has been actually submitted via the form or not`.

Also, if you are having any difficulties, first try to post exactly the same thing as the browser would. To know/see that, you can use something like LiveHTTPHeaders and make cURL post the same fields and values as the browser. Then tweak it to your needs.


Loading new form within a navigation tab in ms Access 2010

Question: I have created the following navigation structure in a Microsoft access 2010 database:

You can see that there are two tabs, and the data for the tabs is populated with information linked to the ClientID, which is stored in an un-editable textbox at the top of the form.  When the Communications Forms tab is selected, a list of communications forms that have been completed for the specific ClientID is shown.  And there is a button to create a new form.  My question is how do I write the macro so that clicking on the Create New Form button will cause a blank new form to be loaded in the space that is currently occupied by the List of Forms?
Below is what I have so far.  It sends the user to a new form instead of embedding the new form underneath the Communication Forms tab in the current form.  How can I change the below so that the blank new form is loaded under the Communication Forms tab in the current form, so that all the navigation controls remain visible/usable?

EDIT:
To address HK1's assumptions below, I am adding the following description of the steps I took to create the form in the screenshot above:
1.) I created a blank form in design view.
2.) I added a listbox to list client fullname and id, and a textbox to filter the listbox.
3.) I added the clientid and fullname textboxes to the form, and set them to change based on
    what the user selects from the listbox
4.) I dragged a navigation control onto the form next to the listbox
5.) I dragged a form called "ListOfForms" onto a new tab in the navigation control to create the tab
6.) I added the CreateNewForm command button to the ListOfForms form while embedded in the main form

Here is the result of HK1's suggested code:

While I appreciate it, it does not do what I need.  You can see that it just adds an additional row to the list in ListOfForms. Instead, I need the code to place a blank MyForm in the place of MainForm where ListOfForms is currently located.  Thus, under the CommunicationsForms tab, all the user would see would be a blank MyForm object, which is a different form than ListOfForms.
When I click on the place where ListOfForms is located in Layout View, I see that it is called NavigationSubForm in the Property Sheet.  Thus, NavigationSubForm would swap in MyForm in place of ListOfForms when the user clicks on the Create New Form command button. But if the user clicks on CommunicationForms tab again, ListOfForms would again be placed in NavigationSubForm.
I tried the following:
Private Sub cmdCreateNewForm_Click()
    Forms!MainForm!NavigationSubform = MyForm
End Sub

But it generates a Runtime Error '438': Object doesn't support this property or method.
Next, I tried:
Private Sub cmdCreateNewForm_Click()
    Forms!MainForm.NavigationSubform.SourceObject = MyForm
End Sub

This causes the NavigationSubForm to go blank, so that ListOfForms disappears.  This seems like I am on the correct track, but what do I need to do to get it to put a blank MyForm in the NavigationSubForm instead of just an empty space?
Comment: Does it have to be a macro? Would you consider using VBA instead?
Comment: With vba this should be relatively easy?
Comment: Yes, in fact, it appears if you would just set your form's AllowAdditions to Yes/True you wouldn't even need this. Also, I think you're using the word "form" incorrectly. In most cases when you say form you actually mean record.
Comment: @HK1 Thank you.  Can you show me how it would look?  I am new to access.
Comment: @TheLaurens Thank you.  Can you show me how to do it in VBA?  I am new to VBA, but code samples help me learn quickly because I know how to code in other languages.
Comment: Whether or not a form is blank has everything to do with how you set it's recordsource or it's filter. It's a little difficult to understand what you're trying to do here. It's as though you are using MS Access forms as though they are PDF Forms. There's simply no comparison between an Access Form and the old Fillable Paper Forms. They are two completely different things.
Answer: The form you have labeled as "List of Forms" appears to be what's called a continuous form, and I'm guessing it's inside a subform control located on a another form. I'm also guessing that your Create New Form button is probably located on the header section of your continuous form. I'm also making the assumption that your continuous form/subform is bound to an editable recordset/recordsource but there's no way I can tell this by looking at the screenshot.
With these assumptions in place, the code for your Create New Form button would probably be something like this:
Private Sub cmdCreateNewForm_Click()
    Me.AllowAdditions = True
    DoCmd.GoToRecord, , acNewRec
End Sub

If any of my assumptions above are incorrect than it's likely this code won't work as expected.
Be aware that New Records in continuous forms (and datasheet forms) always appear at the bottom of the list. I'm not aware of any easy way of making them appear anywhere else.
Comment: Thank you.  +1 for trying to help.  I tried your code and it adds another row in ListOfForms.  That is not what I want.  Instead, I want a MyForm to display where ListOfForms is (INSTEAD OF ListOfForms), so that users can use their familiar GUI to create a form.  MyForm is rather long and involved, and cannot be summarized with a row in a datasheet.  Also, I added a description of how I created this whole thing in an edit to my original posting above, if that helps you.  Are you able to show how to answer my clarified question?


porting libcurl on android with ssl support

Question: I am trying to port libCurl to android with SSL support,
step one would be to port the curl without ssl support I guess so I started doing that. but I run into a problem.
as I read on the dev website and in the Android.mk file, the hard part is configuring the make first. so what I did is :

Download Android Source code (and compile it! since some of the intermediate libs are needed)
Download cURL
unpack curl under : {android_src}/external/curl
make the configure script for curl by creating a sh file in the external/curl folder with this content.

`
export A=/home/user/Development/AOSP/2.3.3
export CC=$A/prebuilt/linux-x86/toolchain/arm-eabi-4.2.1/bin/arm-eabi-gcc
export NDK=/home/user/Development/Tools/sdk/android/ndk
export NDKLIBS=$NDK/platforms/android-4/arch-arm/usr/include
export SYSROOT=$A/ndk/build/platforms/android-4/arch-arm
export CPPFLAGS="-I $A/system/core/include"
export LDFLAGS="-L$A/out/target/product/generic/obj/lib/ -L$A/out/target/product/generic/system/lib/-L$SYSROOT/usr/lib -Wl,--gc-sections -nostdlib -lc -lm -ldl -llog -lgcc -Wl,--no-undefined,-z,nocopyreloc -Wl,-dynamic-linker,/system/bin/linker -L$NDK/out/target/product/generic/obj/lib/"
export CFLAGS="-fno-exceptions -Wno-multichar -mthumb -mthumb-interwork -nostdlib -lc -ldl -lm -march=armv5te -mtune=xscale -msoft-float -mandroid -fPIC -mthumb-interwork -mthumb -mlong-calls -ffunction-sections -fstack-protector  -fno-short-enums -fomit-frame-pointer -fno-strict-aliasing -finline-limit=64 -D__ARM_ARCH_5__ -D__ARM_ARCH_5T__ -D__ARM_ARCH_5E__ -D__ARM_ARCH_5TE__ -DANDROID -DOS_ANDROID -D__NEW__ -D__SGI_STL_INTERNAL_PAIR_H -I$SYSROOT/usr/include -I $A/system/core/include -I $NDKLIBS"

./configure --host=arm-eabi --with-ssl=$A/external/openssl

`
And the output summary is this one :
configure: Configured to build curl/libcurl:
  curl version:     7.26.0
  Host setup:       arm-unknown-eabi
  Install prefix:   /usr/local
  Compiler:         /home/tanco/Development/AOSP/2.3.3/prebuilt/linux-x86/toolchain/arm-eabi-4.2.1/bin/arm-eabi-gcc
  SSL support:      no      (--with-{ssl,gnutls,nss,polarssl,cyassl,axtls} )
  SSH support:      no      (--with-libssh2)
  zlib support:     enabled
  krb4 support:     no      (--with-krb4*)
  GSSAPI support:   no      (--with-gssapi)
  SPNEGO support:   no      (--with-spnego)
  TLS-SRP support:  no      (--enable-tls-srp)
  resolver:         default (--enable-ares / --enable-threaded-resolver)
  ipv6 support:     no      (--enable-ipv6)
  IDN support:      no      (--with-libidn)
  Build libcurl:    Shared=no, Static=yes
  Built-in manual:  enabled
  --libcurl option: enabled (--disable-libcurl-option)
  Verbose errors:   enabled (--disable-verbose)
  SSPI support:     no      (--enable-sspi)
  ca cert bundle:   /etc/ssl/certs/ca-certificates.crt
  ca cert path:     no
  LDAP support:     no      (--enable-ldap / --with-ldap-lib / --with-lber-lib)
  LDAPS support:    no      (--enable-ldaps)
  RTSP support:     enabled
  RTMP support:     no      (--with-librtmp)
  Protocols:        DICT FILE FTP GOPHER HTTP IMAP POP3 RTSP SMTP TELNET TFTP

  SONAME bump:     yes - WARNING: this library will be built with the SONAME
                   number bumped due to (a detected) ABI breakage.
                   See lib/README.curl_off_t for details on this.

First strange thing that comes to mind is why is SSL not included in the config since the linker shows to the intermediate libs and ssl support flag is called, but after when I use the same curl_config.h file in the jni project which I created for the build (since it has a standalone Android.mk file it can be compiled simply by unzipping in the jni folder of a android project, copying the config file created in the AOSP source and calling ndk-build)
so I compile and I get :
$ ndk-build
Compile thumb  : curl <= url.c
In file included from /Projects/temp/testNDK/jni/lib/url.c:32:0:
/Tools/sdk/android/ndk/platforms/android-14/arch-arm/usr/include/unistd.h: In function 'getpagesize':
/Tools/sdk/android/ndk/platforms/android-14/arch-arm/usr/include/unistd.h:171:3: warning: nested extern declaration of '__page_size' [-Wnested-externs]
/Tools/sdk/android/ndk/platforms/android-14/arch-arm/usr/include/unistd.h: In function '__getpageshift':
/Tools/sdk/android/ndk/platforms/android-14/arch-arm/usr/include/unistd.h:175:3: warning: nested extern declaration of '__page_shift' [-Wnested-externs]
/Projects/temp/testNDK/jni/lib/url.c: At top level:
/Projects/temp/testNDK/jni/lib/url.c:57:2: error: #error "We can't compile without socket() support!"
make: *** [/Projects/temp/testNDK/obj/local/armeabi/objs/curl/lib/url.o] Error 1

Answer: Here is the solution, updated to NDK8c
step zero: download and fix the Android NDK
I don't know how but the ndk has a very interesting flaw, which (in my oppinion) doesn't allow you to compile lot's of stuff, so to be able to compile OpenSSL you need to make a small fix, extract the ndk8c whereever you keep your tools, and then edit the file :
android-ndk-r8c/build/gmsl/__gmsl
line 512 :
change line
int_encode = $(__gmsl_tr1)$(wordlist 1,$1,$(__gmsl_input_int))

with line
int_encode = $(__gmsl_tr1)$(wordlist 1,$(words $1),$(__gmsl_input_int))

And you're good to go!
step one : Download OpenSSL and compile for Android :
either compile a ported version found here
or Download the official 1.0.0c version of OpenSSL and then compile it for android using the manual provided in the github I linked for the Android compatible version
So the next step is to get the libssl.so and libcrypto.so
and put the them in the NDK folder for easy access, so copy them from
openssl-folder/libs/armeabi/

to
android-ndk-r8c/platforms/android-8/arch-arm/usr/lib

this way when compiling you can include the libs using a simple linker switch -lssl -lcrypto
Step two : get Curl's latest source for here
Open the file in Docs/INSTALL and follow the steps needed to make the standalone toolchain and put in your desired folder, and then the tricky part, I needed to have android's source code for the config to continue, even though I have a standalone compiled openssl you can include the header files from there too, in anycase this is the more complicated version so you choose what you do,  I did not choose to evade them so you can go to Google AOSP site and go trough the steps to build and initialize the environment.
so it would be something like :
1.download,

go to root of the source code and run :
~: build/envsetup.sh; lunch 1; make;

So finally we need to compile curl with SSL support, so,
Step three
extract curl to the desired folder
(I have a specific desire of disabling everything except http/s to keep the library as small as possible meaning about ~300k, if you want more protocols in your lib, remove the --disable-protocol for the desired protocol)
run the following :
make clean

export PATH=/opt/arm-linux-androideabi-4.4.3/bin:$PATH

export LDFLAGS="\
-lssl \
-lcrypto \
-L/home/user/Development/Tools/sdk/android/ndk/platforms/android-8/arch-arm/usr/lib"

export CFLAGS="\
-I/home/user/Development/AOSP/2.3.7/system/core/include \
-I/home/user/Development/Tools/sdk/android/ndk/platforms/android-8/arch-arm/usr/include"

./configure --host=arm-linux-androideabi \
--with-ssl=/home/user/Development/Projects/portingLibs/openssl-android-master \
--disable-ftp \
--disable-gopher \
--disable-file \
--disable-imap \
--disable-ldap \
--disable-ldaps \
--disable-pop3 \
--disable-proxy \
--disable-rtsp \
--disable-smtp \
--disable-telnet \
--disable-tftp \
--without-gnutls \
--without-libidn \
--without-librtmp \
--disable-dict

make

Note that in the block above, if you don't want to use the AOSP source, you could switch

-I/home/user/Development/AOSP/2.3.7/system/core/include \

with the include folder for your ssl distribution.

So finally you have :
static :
curl-7.28.1/lib/.libs/libcurl.a

and shared :
curl-7.28.1/lib/.libs/libcurl.so.5.3

So that's it.. take the file, and compile away :)
Comment: Thanks a lot for your Work. I've taken your advice but instead of the full sdk, only used the standalone toochain as adviced in the cURL Installation guide. Then I copied the openssl headers and .so files to the folders in the toolchain and set LDFLAGS and CPPFLAGS respectively. A simple --with-ssl did the trick, once set up correcly. So for future reference: You don't have to use the full Android SDK, the toolchain is a possible way aswell.
Comment: that's the case now,two+ years ago it wasn't compilable outside of the AOSP
Comment: I had to modify the commands here to http://pastebin.com/qzxzc592 not sure if that is needed for everyone though
Comment: "put the them in the NDK folder for easy access" This is totally not recommended, you should use LOCAL_STATIC_LIBRARIES and NDK-Build modules to link any libraries you use in Android NDK projects.
Comment: You seem like an expert on curl hehe, can you please take a look at my question about cURL usage? I already have it set up. http://stackoverflow.com/questions/34268036/curl-library-for-android?noredirect=1#comment56277446_34268036 @Tancho
Answer: I like the way to use Docker for building such static libs. There is full script here - you just run it and grab the result. Sample: https://gist.github.com/VictorLaskin/1c45245d4cdeab033956
Such script will:

setup compilation tools / utils download sdk/ndk
create custom cross-compilation toolchain download source code for libs (zlib, openssl, curl)
setup environment settings for cross compilation
configure and make libs
gather output at one folder and create the way to get
compiled libs

This specific version is using latest NDK 10e and clang toolchain.
There is post with more details here: http://vitiy.info/dockerfile-example-to-compile-libcurl-for-android-inside-docker-container/
I hope this will help someone to not waste precious time.
Answer: Steps for compiling libcurl.so with ssl support for android jni could be found here :
http://ieroot.com/2015/03/29/1728.html
I struggled for a week for figuring out it.
Ask if any questions. I'll reply as soon as possible.
Comment: I've tried just now and find it works. Maybe, you need try again. Contact me if still can not connect.


How to ignore a character in split method

Question: My file has the data in this format:
Name,Sal,Address,Location
Mike,"£10,732",xxxxxx,GBR
Bob,"£6,450",xxxxxxx,Fra
Arthur,"£8,320",xxxxx,Spa
James,"£7,423",xxxxxxxxxxxx,IRE

I need to read this data into a string array. In my new file I need to write Name,Sal and Location columns only. Here is my code:
    Dim ioReader As New System.IO.Streamreader("C:\old.csv")
    ioLines="Name,Sal,Location"
    Dim ioWriter As New System.IO.StreamWriter("C:\new.csv")
    While Not ioLine = ""
        ioLine = ioFile.ReadLine
        Dim values As String()
        If ioLine <> "" Then
            values = ioLine.Split(",")
            Dim outPut as string=values(0) & values(1) & values(3)
            ioLines += System.Environment.NewLine & outPut
        EndIf

When I am splitting the above data, the sal column values which already contains "," is splitting into 2 cells. I want to keep the sal column value as a single cell by ignoring "," in between numbers. Any suggestions please?
Comment: That CSV is invalid. It should be escaped to `Mike,"£10,732",xxxxxx,GBR` - otherwise it is ambiguous. What if I have £10 and in the next column (unrelated) I have the value 723?
Comment: You should understand then that this is **not** a CSV file then.
Comment: the source file is not well formed. Is it possible to change the source file ? To be more precise, you have to wrap the strings between `"` delimiters in order to avoid the inner `,` to be considered as a separator. You also have to update your code to handle string delimiters
Comment: or you can also use fixed width columns, again if you can change the source file. it's eaysier to parse, because you can substring, instead of walking in the file looking for tokens
Comment: No I should not format the source file. My output file should looks like
Comment: Name,Sal,Address,Location
Mike,10,732,GBR
Bob,6,450,Fra
Arthur,8,320,Spa
James,7,423,IRE    I can takeoff £ symbol using substring. But only problem is "," in the sal string values
Comment: Why can't you use a normal csv file using quoting or escaping?
Comment: If sal value is in double quotes like "10,732" , how can i escape the "," in between the numbers
Comment: The whole point is that you don't need to escape the `,` as the field is already escaped (by surrounding it with `"`).
Comment: If sal value is in double quotes "£10,732", how can i remove the £ symbol from the value?
Comment: Even though the value is like "£10.732", values(1) is appearing as "£10 and values(2) is appearing as 732".
Answer: Looks like you are parsing CSV, if yes you can use
Microsoft.VisualBasic.FileIO.TextFieldParser

e.g.
Using MyReader As New Microsoft.VisualBasic.FileIO.
    TextFieldParser("c:\logs\bigfile")
MyReader.TextFieldType =
    Microsoft.VisualBasic.FileIO.FieldType.Delimited
MyReader.Delimiters = New String() {","c}
        MyReader.HasFieldsEnclosedInQuotes = True
Dim currentRow As String()
'Loop through all of the fields in the file.
'If any lines are corrupt, report an error and continue parsing.
While Not MyReader.EndOfData
    Try
        currentRow = MyReader.ReadFields()
        ' Include code here to handle the row.
    Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
        MsgBox("Line " & ex.Message &
        " is invalid.  Skipping")
    End Try
End While
End Using

Answer: Quick and dirty solution:
Dim outPut as string=values(0) & values(1) & "," & values(2) & values(5)

The input file is not proper CSV - the fields with , should be escaped (surrounded with "):
Name,Sal,Address,Location
Mike,"£10,732",xxxxxx,GBR
Bob,"£6,450",xxxxxxx,Fra
Arthur,"£8,320",xxxxx,Spa
James,"£7,423",xxxxxxxxxxxx,IRE

And I wouldn't use string.Split but a CSV parser - you could use the TextFieldParser class.
Answer: Another quick and dirty...
using System.Text.RegularExpressions;

private void Test(){
    Regex rex = new Regex(@"(?<!£\d*),");
    string[] s = rex.Split(@"Name,Sal,Address,Location Mike,£10,732,xxxxxx,GBR Bob,£6,450,xxxxxxx,Fra Arthur,£8,320,xxxxx,Spa James,£7,423,xxxxxxxxxxxx,IRE");
}

The regex will not split on comma preceeded by a pound-sign and digits. However this will only allow for one comma in the currency and so £10,342,234 will break it...


How can I combine constant and switched power circuits to power a security light

Question: I've searched round the forum and web, and found others asking similar, but slightly different questions.
I have a security light currently wired to a constant circuit so that it trips whenever there is motion.  Which is a good thing.
However, I also want the light to turn on and stay on, when I turn on two other light in the front of the house that are on a switch.
I know that these lights generally have a flicker over-ride that would work, if I were to hook them up to the same switched circuit the other lights are on.
But how can I also wire the light to a constant source as well?
Please excuse me if I am lacking the correct terminology.
Thanks in advance.
Comment: Can you give us the make and model of said security light?
Comment: It's just a simple security light.... like http://www.heath-zenith.com/products/par-300w-150-sen-gr?taxon_id=4
Comment: Are the two other lights on a simple switch, or some sort of three-way circuit?
Answer: You might be able to accomplish this by replacing the existing front light switch with a three way (SPDT) switch and running a new 3-wire plus ground cable from that switch to the back lights.
It's basically a three way switch with a two way switch in series on one leg, where the motion detector is the two way switch.
This would only work if the motion detector in the back is OK with this type of connection.  You'd have to consult with the manufacturer of the motion detector about that.  It's never come up for me so I have no idea if that runs afoul of the listing of those devices.
At the back light, splice the black on the light, the red from the new cable, and the red from the motion detector.  Splice the black from the new cable to the black from the motion detector.  Splice all three whites.  Ground wires as usual.
In the switch box, connect the black going to the front lights and the red from the new cable to the "up" position traveler terminal on the SPDT switch with a red pigtail.  Connect the "down" position traveler terminal on the SPDT switch to the black wire from the new cable.  Connect the common terminal on the SPDT switch to the black wire feeding the switch box.  Splice all three whites.  Ground wires as usual.
When the three way switch is on, there will be 120V on the motion detector's red wire and 0V on the black.  That is not how it is usually wired, and may not be OK for the device, that's why I mention checking with the manufacturer above.
EDIT:
I gave this some more thought because I think it's an interesting problem / exercise.  I thought of another alternative that may or may not be worth the trouble.
If you can't find a motion detector that's manufacturer approved / listed for parallel wiring, you could sidestep that by using a DPDT switch rather than a SPDT switch.  The second pole would be to disconnect the motion detector from the light and the parallel power when the front lights are turned on.  You'd have to run an additional 14/2 or 12/2 from the front switch to the light.  You probably see where I'm going with this but I'd have to make a sketch to explain it any better.
That may be more trouble that you'd want to bother with.  Complicated is never good.  You may have to install a bigger switch box up front and / or a bigger box / second box in the back.
Comment: These are existing lights.  I think they are these: http://www.heath-zenith.com/products/par-300w-150-sen-gr?taxon_id=4     and the instructions only address a very basic wiring scenario.  But what you say makes sense...
Comment: Unfortunately, these instructions don't work in the OPs case, as it appears the sensor on his security light is integral to the fixture.
Comment: The light and sensor are currently combined, yes.  However, if by installing a separate sensor and light, I can solve this issue, I will probably do that.  Can one of you confirm that the above solution would work with separate components?
Comment: You'd still need to confirm with the manufacturer that the standalone sensor would be OK wired in parallel, but I would think you can find one that is.  Might be expensive though - a good quality sensor is pretty expensive, more than a whole fixture / sensor set at the big box stores.
Comment: I was thinking about this and you could actually sidestep the issue of whether it's OK to wire the sensor in parallel with a DPDT swtich, I am going to edit my answer with details.


How can I replace a custom tag in string?

Question: Are there som parsers available that will replace a custom tag for example:
    [myTag]Some Content[/myTag] with for example

Some Content

I have tried html agilitypack for this but it doesnt seem to work
I have tried
string test = "[myTag]this text is superspecial[/myTag]";
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(test);
var output = doc.DocumentNode.SelectNodes("[myTag]");

but it doesnt seems like valid xpathexpression
Comment: Showing your efforts so far with HTML Agility Pack, the specific input you were dealing with and the exact code you have written would definitely help us figuring out what might be wrong with your code. With this information missing, your question is pretty much deprived of any context, and meaning. Chances are that if it stays at this state it will get closed pretty fast.
Comment: Do you really have square brackets in your code? `[myTag]` is not a valid HTML tag.
Comment: No this text [myTag]content[myTag] comes from TinyMce and I must parse it. It's like a shortcode in wordpress
Answer: You can use String.Replace for every tag you want to change:
string s = "[myTag]Some Content[/myTag]";
string newStr = s.Replace("[myTag]", "
");
string result = newStr.Replace("[/myTag]", "
");

Console.WriteLine(result); // output:
Some Content

http://msdn.microsoft.com/en-us/library/fk49wtc1(v=vs.110).aspx