When is it appropriate to use a configuration manager (eg Puppet / Chef / Ansible)?

Question: At my current workplace, I look after two VMware host machines, an OpenBSD physical machine, three Debian VM's, and six Windows Server VM's (2008/2012).
I'm considering implementing a configuration management tool such as Puppet or Chef.  Is this reasonable, or will the overhead of learning the tool outweigh the benefits?  Where is the tipping point between manageability & implementation cost?
Comment: It's "appropriate" as soon as you ever need to manage a configuration - need to recover from a disaster? Need to move to a new data center? Need to expand horizontally? If you're doing by hand, you're doing it [wrong](http://antipaucity.com/2013/05/11/automating-or-automation/#.VSwoyBPF8nR). "[Doing it twice? Write it down.](http://buildacloud.org/blog/257-doing-it-twice-write-it-down.html)"
Comment: It depends on what you need to do to/with these systems.
Answer: IMHO it's worth learning even if you're only managing a single server,
Yes, there will be a learning curve. Yes, you will get frustrated. For those costs, though, you will be paid back in multiples through reliable, consistent, one-click deployments, version-controlled server configuration, ease of setting up test/dev environments, etc.
In addition to the benefits to your current job, being able to add a CM system to your resume is a big win. Modern sysadmins are now expected to have at least exposure to a config management system, if not proficiency.
(Sidenote: consider Ansible as well. It's my preferred CM, and is very easy to get up and running with - much easier than either Puppet or Chef. Additionally, windows support in Ansible is coming along nicely.)
Comment: Well said. I end up using Ansible on trivial things like setting up a raspberry pi at home because it's a convenient way for me to document the process.
Comment: Absolutely! Getting into Chef has been a huge career win for me. Here's the real thing: in a couple years CM will be just about required/expected for all but junior SysAd jobs.
Comment: Totally agreed. Too much focus is on automation of install which is only one part of CM systems. People forget what M stands for - management. How do you keep track of the various configuration changes you make to 1 server. The number of servers does not matter. When that 1 server dies, you're happy to be able to rebuild it exactly without a doubt.
Answer:
I'm considering implementing a configuration management tool such as Puppet or Chef. Is this reasonable, or will the overhead of learning the tool outweigh the benefits?

It is reasonable depending on how much time and money you have to burn, and whether or not it's your money that you are burning.
A configuration management tool (any of them) is becoming a valuable skill in todays market.
Spending the time to learn and implement a CM tool may not be the most efficient thing to do from the perspective of your business or environment, but from your skillset it may be worthwhile.

Where is the tipping point between manageability & implementation cost?

Most configuration management tools are available for free with the caveat that they are harder to install and get going.
This question is a little hard to answer since it really depends on what you are doing on a day to day basis to manage these servers. If you aren't required to do much at all, then a configuration management tool may be total overkill.
If you only really need to enforce your infrastructure into a predictable and basic state, then it may not do much harm to pick up the very basics of something like SaltStack or Ansible.
In my personal experience, Salt is very easy to get going and bootstrap onto servers, and can be used for very basic remote execution and reporting, which may come in handy if you don't have it already implemented in your environment.
Keep in mind, I am biased. You should evaluate each CM tool by yourself.
Answer: Just like @EEAA said - number of servers is irrelevant. You can reap benefits of using configuration management with a single machine:

documented setup (documented via CM scripts)
reliable deployment (you can [re]deploy youre setup over and over again
resilience of setup (current server croaks - spin up a new one)
reuse (when you get to a point of having a second server - you already have CM scripts you can recycle from first one)
upgrades (it's kind of like a new setup, just atop a different platform)

I can say that I had to implement CM for all my personal servers as I work there infrequently and forget all of the little details. Having CM scripts while may seem to be time-consuming (it is) the payback is well worth it. Long term you'll save much more time that you'll spend setting things up.
Answer: I have experience with Puppet and Ansible. Ansible is IMO simpler, as it's procedural, while Puppet is declarative. There are pros and cons to both, but I have pulled enough hair due to Puppet's cryptic errors.
Both require a lot of work if you want to create clean and reusable configuration. The costs start to really pay off if you have at least two very similar servers, e.g. clouds or clusters.
However, it has some use even for standalone servers - you can setup admin users, standard (with local variations) sshd, postfix or snmpd configs and also use them for a simple information gathering, like adherence to policy or test for shellshock vulnerability.
Also, as mentioned by EEAA, it has a value for documenting the setup if you verify that it really brings a server from base state to running state. It's good to combine it with version control system (git), so that the changes you make are versioned and documented. That is very valuable if you have a team of admins.
Answer: Puppet or any other management system bring great benefits which have all been highlighted by other answers here, but there is no silver bullet when it comes to management.
For example creating puppet classes for complex systems cost much time and effort and sometimes tears as there are many pitfalls, and error messages are not always 100% clear, and when the software upgrades you must invest time to adapt your puppetclasses to match any new specification or procedure and figure out which approach is best suited for this (puppet for example declarative and an upgrade is typically procedural)
Also you need to figure out how you plan to roll out changes made to your classes in a controlled manner, and how to maintain the different versions of your manifests.
You should also consider how to go about upgrading your management solution when the time comes for that.
If you spend a significant amount of time writing for example puppet classes then you'd  have to perform a lot of one-click installs to reap any real benefits.
I recommend exploring still and where appropriate, ie distribution of config files can be a good place to start, and take it from there.


How to evaluate integrals with infinite limits

Question: I am trying to evaluate the integral: $$\int_0^\infty\frac{dx}{4x^2+4x+5}$$ However, the upper limit of infinity is causing me some confusion (I have never encountered infinity in a definite integral before).
I want to use the substitution $x+\frac{1}{2} = \tan\theta$, so that the integral (ignoring limits) becomes:
$$\int\frac{dx}{4(x+\frac{1}{2})^2+4} = \int\frac{\sec^2\theta}{4(\tan^2\theta+1)} d\theta = \int\frac{1}{4} d\theta = \frac{\theta}{4} + c$$
However, I am unsure how to change limits. I can manage the lower one: $x = 0 \implies \theta = \arctan(\frac{1}{2})$. But for infinity, I don't know what to do. It seems to me that $\tan\theta = \infty$ has an infinite number of solutions ($\theta = \pm\frac{\pi}{2}, \pm\frac{3\pi}{2}, \pm\frac{5\pi}{2},...$), what does the upper limit become?
Answer: Please have a short look at the theorem for Substitution for single variable
I think your problem stems from the idea that your transformation function $\phi = \tan: \mathbb{R} \rightarrow \mathbb{R}$
However $\phi$ should be defined on some interval $I$ where it is differentiable. $\tan$ is not differentiable on whole $\mathbb{R}$ - it is if you choose just one section e.g. $(-0.5\pi, 0.5\pi)$
Answer: Hint. If one performs the change of variable
$$
\theta=\arctan \left(x+\frac12\right)
$$ then
$$
\theta(0)=\arctan \left(\frac12\right), \qquad \theta(\infty)=\arctan \left(\infty\right)=\frac{\pi}2,
$$ and, as wanted,
$$
x+\frac{1}{2} = \tan\theta,\qquad dx=\sec^2 \theta\:d\theta.
$$
Remark. We have made the change of variable
$$
\theta=\arctan \left(x+\frac12\right)
$$ rather than
$$
x+\frac{1}{2} = \tan\theta.
$$
Comment: The OP's question is not the change of variable. That was done correctly, the problem was to justify the choice of the upper limit. This does not answer that question.
Comment: My understanding of arctan(x) is that it chooses the value closest to zero - as π/2 and -π/2 are equidistant from 0, why do we choose the positive value? It seems to me that choosing -π/2 is equally valid, but would yield a different result.
Comment: @Adam That's not the *standard* understanding. We have $$ y={\arctan}\ x\iff\tan x=y\text{ et }y\in\left]-\frac{\pi}2,\frac{\pi}2\right[,$$see for example the table here: https://en.wikipedia.org/wiki/Inverse_function#Generalizations
Comment: @OlivierOloa Ah, okay then. In that case, I must just be remembering a technically inexact mnemonic or simplification that I was taught in school.
Comment: @Gregory Please I invite you to read *correctly* my answer.
Comment: Can the downvoter explain his downvote?
Comment: @Adam I'm glad you have understood my above answer. Please feel free to upvote it ;) (don't understand *why* someone has downvoted it...).
Answer: By definition:
$\int_0^\infty\frac{dx}{4x^2+4x+5}=\lim_{t \to \infty}\int_0^t\frac{dx}{4x^2+4x+5}$ , if this limit exists.


Meteor - downloading a pdf / restrict acces to file

Question: I'm trying to set up a mechanism for downloading a PDF file which is available only if a member logs in (restricted access)
So I'm looking on two options:
1) I already have a PDF and would like to add it in public folder but don't know how to restrict the access towards the same (if user logged then access)
2) Have the file on the server and actually make a Meteor.Call from the client to grab the pdf and get it back for download.
Which option is the simplest to implement and how should I do it. I have been crawling the web for the past day and I just can't figure it out how to implement either...
Answer: Store your items in Mongo as a collection using GridFS (see this answer for an example, it's no more difficult than inserting to any other collection really btw). Then you can control access to the file collection as with any other collection, by publishing correctly:
<code>Meteor.publish('fileCollection', function(){
    if (this.userId) return fileCollection.find();
});
</code>
By checking if the user has an ID, we'll know if they're a logged in user. Test the ID further for specific user interactions, add an array field of user IDs that have access to files (then do a .find() for collections where the users ID is in that array in your .publish()) or publish your file to all users as above just by checking if they have any non-empty ID.
Comment: Im trying to get it working with this example: https://github.com/VeliovGroup/Meteor-Files/tree/master/demo-simplest-download-button but it just keeps failing and I got eveyrthing c/p from the demo app


How to implement a panel similar to iphone's new schedule in flutter

Question: This panel includes a title and a listview. The listview can be scrolled. When the listview scrolls to the top, continue to slide down the list, and the entire panel will follow.
like this:

this panel include title (add event)and listview, now listview be scrolled。

Now, the list slides to the top, continuing to drop down the list, we can see the panel slide down
Answer: You can use draggableScrollableSheet in a stack to get this behaviour
<code>class HomePage extends StatelessWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('DraggableScrollableSheet'),
      ),
      body: SizedBox.expand(
        child: DraggableScrollableSheet(
          builder: (BuildContext context, ScrollController scrollController) {
            return Container(
              color: Colors.blue[100],
              child: ListView.builder(
                controller: scrollController,
                itemCount: 25,
                itemBuilder: (BuildContext context, int index) {
                  return ListTile(title: Text('Item $index'));
                },
              ),
            );
          },
        ),
      ),
    );
  }
}
</code>
More about draggableScrollableSheet
Comment: https://github.com/flutter/flutter/issues/90777
https://github.com/flutter/flutter/issues/60309
but, it not working when the lisview reverse
Comment: What's the error
Comment: when the listview is swiped to the top, the finger continues to slide, and the panel will not slide down, however, when the listview is swiped to the bottom, the finger continues to slide up, and the panel will drop. it is not expected
Comment: The list view should have enough items to do this behaviour. Try adding more items to it please


Still reachable memory but tried freeing memory

Question: Im trying to learn how malloc works with pointers and such and i've tried freeing my memory of pointer but when I check for memory leaks using valgrind it still says I have 32 bytes that are reachable.
<code>#include <stdio.h>
#include <stdlib.h>

void fib2(int* a);

int main()
{
  int *pointer;

  //allocates space for 2 elements for pointer
  pointer = malloc(100 * sizeof(int));

  //prints first two fibonacci values
  printf("0 1 ");

  //calls fib2 func and apsses pointer into it
  fib2(pointer);

  //frees pointer memory
  free(pointer);

  printf("\n");

  return 0;
}

//generates fibonacci sequence
void fib2(int* a)
{
  int i;

  //initial fibonacci array initialized
  a[0] = 0;
  a[1] = 1;

  //generates and calculates fibonacci sequence and prints
  for(i = 2; i < 12; i++)
  {
    a[i] = a[i - 1] + a[i - 2];
    printf("%d ", a[i]);

  }
}
</code>
**edit Valgrind output in text form as requested earlier
<code>==5451== Memcheck, a memory error detector
==5451== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==5451== Using Valgrind-3.12.0 and LibVEX; rerun with -h for copyright info

==5451== Command: ./lab3
==5451==  0 1 1 2 3 5 8 13 21 34 55 89
==5451==
==5451== HEAP SUMMARY:
==5451==     in use at exit: 32 bytes in 1 blocks
==5451==   total heap usage: 50 allocs, 49 frees, 107,863 bytes allocated
==5451==
==5451== LEAK SUMMARY:
==5451==    definitely lost: 0 bytes in 0 blocks
==5451==    indirectly lost: 0 bytes in 0 blocks
==5451==      possibly lost: 0 bytes in 0 blocks
==5451==    still reachable: 32 bytes in 1 blocks
==5451==         suppressed: 0 bytes in 0 blocks
==5451== Rerun with --leak-check=full to see details of leaked memory
==5451==
==5451== For counts of detected and suppressed errors, rerun with: -v
==5451== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
</code>
Comment: But my general point is correct: it's coming from a library outside the programmer's control, so there's not much they can do about it.
Comment: https://stackoverflow.com/a/3857638/1216776
Comment: You freed your pointer. It's probably an internal pointer used by `stdio`.
Comment: Your pointer points to 400 bytes, so it's not what the warning message is talking about.
Comment: Please **[edit] your question** and add the output from valgrind **as text**.
Comment: @Barmar no, not stdio, that is something even sillier, seems to be a forced libGLdispatch OpenGL library that is dynamically linked to the executable.
Comment: @AnttiHaapala Right, I see that now in the report, but I don't see any code in the question that would be responsible for this.
Comment: @Barmar `LD_PRELOAD` maybe... :F
Comment: `Rerun with --leak-check=full to see details of leaked memory`
Answer: Ok figured it out it was an issue with my Valgrind
Comment: How did you fix this? I have the same problem.
Comment: No fix, it's just an issue with Valgrind, can't do anything about it.


JS Open new window and close new window after N seconds

Question: I want to open a new window using javascript(window.open("some_url")) and after some time i want to close that window. Is this possible using javascript?
Answer: Open the window, then use setTimeout to close after some interval.
var newWindow = window.open("some_url");
setTimeout(() => newWindow.close(), 1000);

Answer: Yes, it is. Try setTimeout for this task:
const windowGoogle = window.open('http://google.com', '_blank');

//This will close google's window after 3000 miliseconds
setTimeout(() => {
  windowGoogle.close()
}, 3000)

Comment: Is it right to remove "() => "? I'm sorry but I I don't understand what this code does.


Area of a regular hexagon via area of triangles

Question: Problem: Find the area of a regular hexagon whose sides measures 5 cm
Sol'n 1: I can cut the hexagon into 6 small triangles, so the area of triangle times 6 will be equal to the area of the polygon. Since the triangles are equilateral I  can use the formula for it.
Area of triangle = $\frac{\sqrt{3}}{4}(5)^2= 10.83$
Area of hexagon = (6)(10.83) = 64.95
Sol'n 2: Using the formula $\frac{1}{2}(base)(height)$ for the area of triangle. The angle of triangle (angle at the radius) is equal to 60 degrees (From 360 / 6). Cutting the triangle into half (to get the base and height) will result to an angle of 30 degrees and base of 2.5.
To get the height: $tan(30) = \frac{2.5}{height} = 4.33$, so the area of the triangle: $\frac{1}{2}(2.5)(4.33) = 5.41$
Area of hexagon = (6)(5.41) = 32.475 which does not equal to the area in solution 1.
Question: I noticed that the area calculated on solution 2 is half the area calculated in solution 1. I don't know why. I don't think plugging in the original length of the base is right or logical? I have answered a related problem like this and I have gotten the polygon's area with 1/2(base)(height) and not plugging the original base length back to the formula of area after getting the height. Topic is easy but I don't get why I get so confused. :( Any help will be appreciated.
Answer:
You've created your diagram like this, calculated the area of the triangle I've labelled, and then multiplied that area by $6$. Notice however, by your divisions, we've split the hexagon into $12$ triangles, so we would need to multiply the area by $12$, not $6$, which explains why your area for Sol $2$ is half the area for Sol $1$ (which is correct)
The area of one triangle is given by $\frac 12\cdot2.5\cdot2.5\tan(60)=\frac{25\sqrt3}{8}$. Multiplying this area by $12$ (the amount of triangles) gives us $\frac{75\sqrt3}{2}\approx64.9519$
Comment: Please excuse the awful quality of the diagram but I hope that it is clear enough
Comment: I answered a similar problem. Find the area of a regular octagon inscribed in a circle whose radius is 12. I also dissected the octagon into 8 triangles and like in the problem above, I formed a right triangle with hypotenuse = 12, angle = 22.5 and base = x/2. The calculated area of the octagon using this method equals the calculated area using the other triangle formula: $absin\theta$ and I did not need to multiply the area by 16 but just by 8 which confuses me.
Comment: Typo on my comment above. Should be $\frac{1}{2}absin\theta$.
Comment: Octagons have a regular angle of $135^0$. When you divide the octagon into eight triangles, you get an angle of $45^0$ at the centre. Thus for the whole octagon you should use $8\cdot\frac{1}{2}\cdot12^2\cdot\sin45=288\sqrt2 \approx407.2935$
Comment: You are right. Try solving it via $\frac{1}{2}(base)(height)$. It will result to 407.29 even though the area is only multiplied by 8 which should be by 16 as per your explanation. I used 22.5 as the angle for the right triangle, "x/2" for the base and the hypotenuse, 12. Then Via "soh-cah-toa", base is 9.184 and height is 11.087. Plugging it in: $\frac{1}{2}(9.184)(11.087) = 50.911$ then multiplied by 8 which equals to 407.29, the same with $absin\theta$ but I only multiplied it by 8 and not by 16. I need an answer for this, so I can move on. :(
Comment: If you split those 8 triangles along the midpoints of the lines, you create triangles with a hypotenuse $12$ and an angle $67.5^0$. From this, the base side is $12\cos(67.5)\approx4.5922$, and the height side is $12\sin(67.5)\approx11.0866$. Then $16\cdot\frac 12 \cdot4.5922 \cdot 11.0866=407.2950$ (which is correct bar my rounding)
Comment: You did not divide the base in 2 when turning it into a right triangle. But since this is getting too long, thank you for the time and effort.
Answer: Solution 1 gives the correct answer.  In solution 2, the triangle that you're calculating is actually a right-angled triangle with interior angles $30°$, $60°$ and $90°$, and it is in fact half of the triangle calculated in solution 1.  This explains why the numerical result obtained in solution 2 is half of that in solution 1.
Comment: I answered a similar problem. Find the area of a regular octagon inscribed in a circle whose radius is 12. I used 2 formulas of triangle: $\frac{1}{2}absin\theta$ and $\frac{1}{2}(base)(height)$. For $\frac{1}{2}(base)(height)$, I did the same thing, I formed a right triangle to get the height then calculated the area then multiplied it by 8 to get the octagon area. This equals the area calculated using $\frac{1}{2}absin\theta$. It equals even though I multiplied it just by 8 which is supposed to be by 16 just like you explained. :(
Comment: The solution for the above, @The right triangle: angle = 22.5 (From 360/8 = 45/2 = 22.5), side = 12 (From the given radius) and base = x/2. Via "soh-cah-toa", base = 9.184 and height = 11.087. Plugging it into $8*[\frac{1}{2}(base)(height)] = 407.89$ which is the area of octagon.

Via $\frac{1}{2}absin\theta$ where a = b = 12 and angle = 45 (from 360/8). Plugging it in the formula and multiplying it by 8 to get the octagon area, we get 407.29.

The areas are equal even though in solution 1, I just multiplied it by 8.
Comment: @Jayce Sorry for late reply as I was outside.  It seems that another answerer is following your problem.  Please leave a comment if you need further help :-)


Webpacker rails 6 (loading Bloodhound and typeahead)

Question: I am trying to load Bloodhound and typeahead.query.js in webpacker of Ruby. I got Bloodhound working in the environment.rb file and I got rid of that error. But typeahead is still not working getting this error thrown.
Uncaught TypeError: $(...).typeahead is not a function
const { environment } = require('@rails/webpacker')

const webpack = require('webpack')
environment.plugins.append('Provide', new webpack.ProvidePlugin({
  $: 'jquery',
  jQuery: 'jquery',
  Popper: ['popper.js', 'default'],
  Typeahead: 'typeahead.js/dist/typeahead.jquery.js',
  Bloodhound: 'typeahead.js/dist/bloodhound.js'
}))

module.exports = environment

I tried loading it in my application.js folder in the webpack applicaton.js file but then Bloodhound and typeahead.js dont load in.
Answer: The config/webpack/environment.js needs to look as follows:
const { environment } = require('@rails/webpacker')

const webpack = require('webpack')
environment.plugins.append('Provide', new webpack.ProvidePlugin({
  $: 'jquery',
  jQuery: 'jquery',
  Popper: ['popper.js', 'default'],
  Bloodhound: 'typeahead.js/dist/bloodhound.js'
}))

const aliasConfig = {
  'typeahead': 'typeahead.js/dist/typeahead.jquery.js'
};

environment.config.set('resolve.alias', aliasConfig);

module.exports = environment

Comment: Hey @soniccool, I have the same problem. I added the above code to the config/webpack/environment.js but I still get this error `Uncaught TypeError: $(...).typeahead is not a function`. I wanted to ask did you also add this   `require("typeahead.js")` to the application.js file?


Is there a simple proof that there are no "off-by-1" solutions to Fermat's Last Theorem?

Question: $x^p + y^p = z^p$ has no integral solutions for $p>2$ due to the work of Andrew Wiles and others. My questions is: consider cases where $p>2$ and $y=x+1$ and $z=x+2$. We might call these "off-by-1" solutions. Is there any simple proof that there are no such off-by-1 solutions? (Admittedly, simple is somewhat subjective.)
Comment: From the title I thought you were looking for $x^p+y^p=z^p\pm1$, which _does_ have solutions (but probably finitely many).
Comment: $x=-1$ for an even $p$ gives $(-1)^p+(-1+1)^p=(-1+2)^p$ which is always true. This doesn't run counter to Fermat's last theorem, but it shows that simply working in $mod\ p$ or $mod\ x+1$ might not be enough for a simple proof.
Comment: Do you mean to restrict $p$ to be prime?  It matters here because of the restrictions on $x,y,z$, whereas in FLT the case where $p$ is prime (or $4$) implies the general case.
Answer: This is only a comment until I work out the even-$p$ case. Work modulo $x+1$ so $(-1)^p \equiv 1$. This refutes all cases with odd $p$. If $p$ is even $a=x^q,\,b:=(x+1)^q,\,c:=(x+2)^q$ is a Pythagorean triple with $q:=p/2$. I'm still trying to force a contradiction. Since $c-b>b-a$, $a^2=c^2-b^2>(c+b)(b-a)>(3b-a)(b-a)=a^2+4b(b-a)-b^2>a^2-b^2$.
Comment: $(3b-a)(b-a) = a^2 + 3b^2 - 4ab = a^2 + 4b(b-a) - b^2$. Should be salvageable, but needs a correction.
Comment: @DanielFischer Well-spotted. I'm still working out how to do it.
Comment: @Daniel Fischer . Does there exist an even $n\geq 4$ and an odd $ j $ with $1\leq j\leq n-1$ such that $\binom {n}{j}$ is odd? If not then the case of an even $p\geq 4$  is easy.
Comment: @DanielWainfleet No, if $n$ is even and $j$ odd, then there is always a carry in the [base-$2$] addition $j + (n -j)$, so $\binom{n}{j}$ is then even.
Comment: @Piquito Is it obvious that $x+1\nmid 3^p-2^p-1$?
Comment: @J. G. It is not for $x=1$
Comment: @Danie Fischer .I withdraw my claim that I have an easy proof when   $p$ is even . I made a mistake
Comment: @Daniel Wainfleet: In fact, it is not easy. Do not forget that just in 1977, Terjanian proved FLT for even exponent, which in implicitly would mean that the Pythagorean triples are useless in this. On the other hand,  we must not lose sight of the fact that we do not have properly a Diophantine equation here but a simple algebraic equation in one incognita.
Comment: @Piquito.  In my head I considered the Binomial expansions on the RHS of $y^{2n}=(y+1)^{2n}+(y-1)^{2n}$ and mis-calculated something.... I once read that some 19th-century professor received so many amateur attempts on FLT that he had a "form letter" for them: "You have an error on Page ___, Line ___ ."
Comment: @Piquito . I don't understand what result of Terjanian you are describing. To prove FLT it suffices to consider odd prime $n$  and the  elementary case $n=4,$  and I suppose you already know this.
Comment: @Daniel Wainfleet: Terjanian's paper "Sur l'équation $x^{2p}+y^{2p}=z^{2p}$" (Comptes Rendues, Academie des Sciences de Paris /1977) proves the first case ($n\nmid xyz$), less difficult than the second case ($n|xyz$) of theorem for even exponent. On the other hand the problem here could be the simplest particular case of a general proof, quite before Wiles, when x,y, z are in arithmetic
Comment: progression (successively discovered by K. Goldziber, by M. Mihaljinec and by D. Ramaver Rao). With these precedents and many others, it results from an almost soulful  ingenuity to try to use the Pythagorean triples in this problem (perhaps it could work but  because it is the simplest case of arithmetic progression already demonstrated in its generality before Wiles-Taylor. Actually it is a simple difficult equation in one unknown).
Answer: Let's anchor it at the middle term, so that we're looking for integers $p > 2$ and $y$ such that
$$(y - 1)^p + y^p = (y + 1)^p. \tag{1}$$
J.G. elegantly disposed of the case where $p$ is odd, then reducing $(1)$ modulo $y$ yields
$$-1 = (-1)^p \equiv (y - 1)^p + y^p = (y + 1)^p \equiv 1^p = 1 \pmod{y}\,.$$
This congruence is satisfied only for $y \mid 2$, i.e. $y \in \{ -2,-1,1,2\}$, and one easily checks that none of these options gives a solution of $(1)$.
For even $p$, $y = 0$ yields the only solution. For $y < 0$ and even $p$ we have
$$(y - 1)^p + y^p = (\lvert y\rvert + 1)^p + \lvert y\rvert^p > \lvert y\rvert^p > (\lvert y\rvert - 1)^p = (y + 1)^p,$$
so it remains to rule out positive $y$. For $y \in \{1,2\}$ and $p > 1$ we always have
$$(y - 1)^p + y^p < (y + 1)^p,$$
hence in the following we assume $y > 2$. If $(1)$ were satisfied, then by the binomial theorem
$$y^p = (y + 1)^p - (y - 1)^p = 2\sum_{k = 1}^{p/2} \binom{p}{2k-1} y^{2k-1} = 2py + y^3\sum_{k = 2}^{p/2} \binom{p}{2k-1}y^{2k-4}\,.$$
The left hand side is divisible by $y^3$ (since $p > 2$), and the right hand side is divisible by $y^3$ if and only if $y^2 \mid 2p$. We thus obtain the necessary condition $p \geqslant \frac{1}{2}y^2$. But then we have
$$\biggl(1 - \frac{1}{y}\biggr)^p + 1 < 2 < 1 + \frac{y}{2} \leqslant 1 + \frac{p}{y} \leqslant \biggl(1 + \frac{1}{y}\biggr)^p$$
by Bernoulli's inequality.
Thus for $p > 2$ the equation $x^p + y^p = z^p$ has no nontrivial solutions with $x,y,z$ being consecutive integers.
Comment: I have been studying the same approach to the problem but I have not come up with your last reasoning. I try to prove that the resulting equation do not have integer solution (the thing is going very well for $p = 4$ in that the single solution is close to 8.121). Regards.
Answer: It is easy (and nice!) to discard $p$ odd (look at the J.G.'s answer) because of $(-1)^p\equiv 1\mod{(x+1)}$ impossible for $x\gt1$ and because the equation $1+2^p=3^p$ can be easily discarded so we consider just $p=4n$ and $p=4n+2$.
It is well known the periodicity modulo $4$ of classes modulo $10$. We have modulo $10$ the following table
$$\begin{array}{|c|c|}\hline x & 1 & 2 & 3 & 4&5&6&7&8&9&0 \\\hline x^2  & 1 & 4 &9&6&5&6&9&4&1&0\\\hline x^4 &1 &6  &1&6&5&6&1&6&1&0\\\hline\end{array}$$ It follows
► for $p\equiv 2\pmod4$.
$$\begin{cases}1^2+2^2=3^2\Rightarrow5\equiv9\pmod{10}\\2^2+3^2=4^2\Rightarrow3\equiv6\pmod{10}\\3^2+4^2=5^2\Rightarrow5\equiv5\pmod{10}\\4^2+5^2=6^2\Rightarrow1\equiv6\pmod{10}\\5^2+6^2=7^2\Rightarrow1\equiv9\pmod{10}\\6^2+7^2=8^2\Rightarrow5\equiv4\pmod{10}\\7^2+8^2=9^2\Rightarrow3\equiv1\pmod{10}\\8^2+9^2=0^2\Rightarrow5\equiv0\pmod{10}\\0^2+1^2=2^2\Rightarrow1\equiv4\pmod{10}\end{cases}$$
(This can be written directly from the table but has been made explicit for beginners).
We see that WLG we can proved just the impossibility of
$$(10m+3)^{4n+2}+(10m+4)^{4n+2}=(10m+5)^{4n+2}.....\space\space (*)$$
►for $p\equiv 0\pmod4$.
Similarly we should try only the equation
$$(10m+5)^{4n}+(10m+6)^{4n}=(10m+7)^{4n}.....\space\space (**)$$
So we have reduced the problem to just proving  $(*)$ and $(**)$. I stop here until a new attempt and maybe someone can prove beforehand the impossibility of these two equations for which the Pythagorean triples could be perhaps a good way.


Setting App Engine mapreduce shard size

Question: Does the App Engine Mapreduce API decide compute shard size according to its own logic in the final reduce job?
I am using the App Engine mapreduce API and have supplied the shard_size
kwarg to set my mapreduce shard size.
The shard size is particularly important in my mapreduce job because I don't want to batch too many results into any one given execution of the final step of my reduce function.  In other words, I'm hardcoding the shard size to evenly divide the users up according to an external constraint on the system.
The map job seems to shard out just fine, but the reducer uses only a fraction of the shards I've designated.
Here is a rough outline of the sort of code I am dealing with:
SHARD_SIZE = 42

def map_fun(entity):
  shard_key = random.randint(1, SHARD_SIZE)
  yield (
    shard_key,
    db.model_to_protobuf(entity).SerializeToString().encode('base64')
  )

def reduce_fun(key, entities):
  batch = []
  for entity in entities:
    #check for stuff
    batch.append(entity)
  expensive_side_effect(batch)

class MyGreatPipeline(base_handler.PipelineBase):
  def run(self, *args, **kw):
    yield mapreduce_pipeline.MapreducePipeline(
      'label'
      'path.to.map_fun',
      'path.to.reduce_fun',
      'mapreduce.input_readers.DatastoreInputReader',
      'mapreduce.output_writers.BlobstoreOutputWriter',
      mapper_params={
        'entity_kind': 'path.to.entity',
        'queue_name': 'coolQueue'
      },
      reducer_params={},
      shard_size = SHARD_SIZE
    )

map_fun specifically assigns each entity a shard that is determined randomly according to the shard size.  I'm confused about why my reducer would have fewer shards than SHARD_SIZE given that there are many entities and it is exceedingly unlikely that the same integers were picked repeatedly.
Answer: I'm puzzling over what you're doing here. Using the map phase to group stuff onto a small, sharded key, later processing those keys at reduce time looks odd. You're going to end up with too much work to do per key, even if you do engage as many reduce workers as you do mapper workers.
The 'batch' being processing is randomly arbitrary, so I assume that expensive_side_effect() isn't dependent on the content of the batch. Why not do that work instead at map time, emitting something that a reduced could pass through to the output writer?

Setting App Engine mapreduce shard size


JavaScript runtime error Unable to get property 'value' of undefined or null reference

Question: I'm unable to access the variable in the JS file.
The Validation is working fine when written in the same page. But when I pasted the Validation code to a separate JS file, its not working.
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">

                    Update Details

                        Username :

                    <input type="text" runat="server" id="txtUsername" />

</asp:Content>

JS file:
function Validate() {

    var username= document.getElementById("txtUsername").value;

    if (username== "") {
        alert("username Required.");
        return false;
    }

    return true;

}

Error:JavaScript runtime error: Unable to get property 'value' of undefined or null reference
Comment: Are you calling validate function after the above content has been loaded ?
Answer: It means that the element with an id of txtUsername doesn't exist. You execute your script before the element is created.
You should either put your script at the bottom of the page or use a
window.onload = function() {}

in which you'll execute your code.
Comment: sorry...script at the bottom of the page doesn't work nor the window.load..any other idea..


What is the terminology for how we identify numbered notes like C4, E3, D6, etc?

Question: Does this system - where C3 is middle C - have a standard name? For instance, is there a wikipedia page which explains this system and if so how is it titled?
(note: As mentioned middle C is C4, my mistake... leaving it as written so the answer given doesn't end up confusing.)
Comment: http://en.m.wikipedia.org/wiki/Scientific_pitch_notation
Comment: So many keyboards and MIDI drivers use C3 for middle C that I *always* double check octaves when using new software or hardware. It's very confusing.
Answer: It's called scientific pitch notation. Here's an explanation of it:

Scientific pitch notation (also known as American Standard Pitch
  Notation) is one of several methods that name the notes of the
  standard Western chromatic scale by combining a letter name,
  accidentals, and a number identifying the pitch's octave. The
  definition of scientific pitch notation in this article is that
  proposed to the Acoustical Society of America in 1939,1 where C0 is
  in the region of about 16 Hz. - Wikipedia
Comment: I'd advertise using the name _American Standard Pitch_, because there really isn't much about this system that makes it particularly scientific.
Answer: I don't think there's a name we give to the note naming format of C4...
The last number is the octave.
By the way, C4 is middle C, not C3.
Not every piano manufacturer gets that right.
Some start on the wrong octave because their instrument doesn't have the full 88 keys and they start labeling octave 2 as 1.
Lowest note on the standard 88 key piano is A0.
Some pipe organs have lower keys that dip into octave "-1".
Comment: Oops, slip of the brain :) Although as it happens, my cheap keyboard, which labels all the keys, _does_ have them all one octave wrong which was _very_ confusing when I was using it to figure out my vocal range :)
Comment: Ah, @Dom's link even refers to this "For example, MIDI software and hardware often uses C5 or C3 to represent middle C"
Comment: I dunno.  It may say "scientific pitch notation" on that wikipedia page.  But I've never ever heard anyone else use that term.  I'm not Mr. Allknowing about musical terms, of course.  But don't expect everyone you meet to know what the heck you're talking about if you use that term.

Also, keep in mind that it makes more sense to specify the octave first as it qualifies WHICH C# you're talking about.  Things sort better in a text file if you use 4c for middle C, for example.  (Not that that matters a great deal.  And C4 is a standard way to say it).


Include \markup in define-music-function

Question: I want a custom \breathe sign that can be freely positioned, like:

I have some shortcut code for this:
place = #(define-music-function (parser location xy)
          (pair?)
          #{
            \once \override TextScript.extra-offset = #xy
          #})

comma = \markup \musicglyph "comma"

used as \place #'(2 . 0) a2-\comma.
However, it would be much nicer to be able to just write a2-\comma #'(2 . 0).
Is there a way to accomplish this?
Answer: The following works here:
comma = #(define-event-function (parser location xy)
          (pair?)
          #{
            \tweak extra-offset #xy ^ \markup \musicglyph "comma"
          #})

{ a2\comma #'(2 . 0) }


How should I organize a large JavaScript dialog object?

Question: I have a very large JavaScript object I'm using to store RPG dialog, containing several large top-level objects. The dialog is formatted similar to JSON.

When organizing the dialog, should I put each of those top level categories in their own function?
Or maybe their own separate javascript file?
Does keeping all the text in one javascript (var json =) object affect performance?

Any organization tips would be appreciated!
Comment: Use whichever way makes for the cleanest code. Optimize as you encounter bottlenecks. Don't worry about it until that time.
Comment: @meagar thanks for the post edit; sometimes I get carried away with my question and forget to simplify it.
Comment: Is this about JSON or JavaScript now? Those two are different things. Firs you mention JSON, then JavaScript files and JavaScript objects. Please be clear about your question.
Comment: @Growler Never use 5 paragraphs where a single sentence will suffice :)
Comment: @FelixKling It's about how to best organize JSON within the context of JavaScript. I also had that small question if putting them all in one JS object would have a performance hit.
Comment: I had a look at your original question with the code. It didn't contain any JSON, only a JavaScript object. So it seems to me that your question is more about JS objects than JSON (they are different things). Especially as there is no such thing as a "JSON function".
Comment: @FelixKling Does it matter if I store text as such in a JS variable similar to the format of JSON versus actually storing the JSON as a JSON text file then parsing it?
Comment: Maybe not, but describing your problem using JSON and JS object interchangeably is rather confusing.
Comment: @FelixKling Noted. I edited the question above accordingly. But, what are your thoughts on storing JSON in a JS variable versus as actual to-be-parsed JSON.txt file? What is the difference?
Answer:
You should generally try to limit coupling whenever possible.  Therefore it would make sense to separate these into separate functions, but see point #3 about databases.
You can separate them into separate javascript files if it gets too big to manage easily with one.  You can always have a build process that lumps them all together later (check the html5 boilerplate for more on this technique).
It probably isn't going to make much difference for performance at this point.  I might suggest using something like mongoDB in the future as you get more data though.  Take a look at meteor js to get some inspiration.  Using a database can simplify your code if you do it right.
Comment: Mentioning Meteor JS smacks of spam. How is that even tangentially related to organizing a JSON file? The server-side datastore is 100% irrelevant here.
Comment: @DrewR I didn't flag as spam, or downvote; I *am* giving jmh the benefit of the doubt. I still fail to see how this is relevant. It's just like saying "Oh by the way, you should consider using ASP.Net". **Totally** irrelevant. Name-dropping unrelated frameworks when we're talking about how to organize plain old JSON data.
Comment: I have no association with meteor.  I just think that it is a good example of going a step beyond storing all your data as a JSON file.
Comment: @meagar I disagree with "smacks of spam". Can we not give one another the benefit of the doubt on occasion so that we might help OP without fear of accusation?
There is plenty of other content to this answer I don't know why you have singled out a link that is almost an afterthought to the rest.
Comment: @meagar I appreciate your points. I just disagree that it is totally irrelevant. Maybe slightly tangential but not irrelevant. jmh suggests using MongoDB rather than storing flat JSON files and in my interpretation cites meteor as a demonstration of the code simplification it allows whether agreeable to me or not. IMO suggestion of an alternative approach with evidence of its benefits is as valid as suggesting a solution to the problem.
Comment: When somebody asks questions as general as this, I think maybe they are looking for something above just "how do I solve this particular problem."  So I suggested an approach that may scale better than his current approach.  If I was writing an RPG using javascript, I would want to use a DB like mongodb to organize my data.  Meteor is a project that uses mongodb and I thought it was a good example of binding data between client/server.
Answer: Addressing question 1, this sounds like JSONP? Slightly different.
I would suggest that performance differences would be negligible for parsing though if using JSONP and injecting


Usar RatingBar com numeração ao lado Android

Question: Alguém sabe como usar o Rating bar com a numeração ao lado? Da forma que o ifood utiliza.
Tentei inserir o ratingBar com apenas uma estrela mas não funciona, e como imagem dentro de um ArrayLista também não funcionou.

ListaDistribuidoresActivity.java
package com.pedido.meu.telas_meu_pedido;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;

public class ListaDistribuidoresActivity extends AppCompatActivity {

    ItemAdapter adapter;
    ArrayList<Integer> idImages;
    ArrayList<String> nameList;
    ArrayList<Integer> starImage;

    int ids[]={R.mipmap.ic_distribuidor};
    String names[]={"DISTRIBUIDOR"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lista_distribuidores);
        ListView listViewDistribuidores = findViewById(R.id.txtListViewDistribuidores);

        idImages = new ArrayList<>();
        idImages = getList();
        starImage = new ArrayList<>();
        starImage = getListStar();
        nameList = new ArrayList<>();
        nameList = getNameList();
        ItemAdapter adapter = new ItemAdapter(ListaDistribuidoresActivity.this, idImages,nameList, starImage);
        listViewDistribuidores.setAdapter(adapter);
        listViewDistribuidores.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id)
            {
                Toast.makeText(ListaDistribuidoresActivity.this, "Distribuidor " + nameList.get(position) + "selecionado", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private ArrayList<Integer> getListStar()
    {
        starImage = new ArrayList<>();
        starImage.add(R.mipmap.ic_star_round);
        return  starImage;
    }

    private ArrayList<String> getNameList()
    {
        nameList = new ArrayList<>();
        nameList.add("DISTRIBUIDOR 1");
        nameList.add("DISTRIBUIDOR 2");
        nameList.add("DISTRIBUIDOR 3");
        nameList.add("DISTRIBUIDOR 4");
        return  nameList;
    }

    private ArrayList<Integer> getList()
    {
        idImages = new ArrayList<>();
        idImages.add(R.mipmap.ic_distribuidor);
        idImages.add(R.mipmap.ic_distribuidor);
        idImages.add(R.mipmap.ic_distribuidor);
        idImages.add(R.mipmap.ic_distribuidor);
        return idImages;
    }

 /*   @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.activity_simple_list_distribuidores,menu);
        return super.onCreateOptionsMenu(menu);
    } */
}

ItemAdapter.java
package com.pedido.meu.telas_meu_pedido;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;

public class ItemAdapter extends BaseAdapter
{
    private Context context;
    private ArrayList<Integer> listaId;
    private ArrayList<String> listaNome;
    private ArrayList<Integer> listaStar;

    public ItemAdapter(Context context, ArrayList<Integer> listaId, ArrayList<String> listaNome, ArrayList<Integer> listaStar)
    {
        this.context = context;
        this.listaId = listaId;
        this.listaNome=listaNome;
        this.listaStar=listaStar;
    }

    public ItemAdapter(ListaProdutosActivity listaProdutosActivity, ArrayList<Integer> idImages, ArrayList<String> nameList)
    {
        this.context=listaProdutosActivity;
        this.listaId=idImages;
        this.listaNome=nameList;
    }

    @Override
    public int getCount()
    {
        return listaNome.size();
    }

    @Override
    public Object getItem(int position)
    {
        return listaNome.get(position);
    }

    @Override
    public long getItemId(int position)
    {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {

        if (convertView == null)
        {
            convertView = View.inflate(context, R.layout.list_item_produtos, null);
        }
        ImageView img = convertView.findViewById(R.id.imgListItemProduto);
        TextView tv =  convertView.findViewById(R.id.txtListItemProduto);
        img.setImageResource(listaId.get(position));
        tv.setText(listaNome.get(position));

        return convertView;
    }
}

Imagem.java
package com.pedido.meu.telas_meu_pedido;

public class Imagem
{
    private int imageId;
    private String imageName;

    public int getImageId() {
        return imageId;
    }

    public void setImageId(int imageId) {
        this.imageId = imageId;
    }

    public String getImageName() {
        return imageName;
    }

    public void setImageName(String imageName) {
        this.imageName = imageName;
    }
}

activity_lista_distribuidores.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_height="match_parent"
    android:layout_width="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.pedido.meu.telas_meu_pedido.ListaDistribuidoresActivity"
    >

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@mipmap/ic_distribuidor"
        android:layout_gravity="center"
        android:layout_marginTop="30dp"
        />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/txtTitleListaDistribuidores"
        android:gravity="center"
        android:textColor="@color/colorPrimary"
        android:textStyle="bold"
        android:textSize="14pt"
        android:layout_marginTop="15dp"
        android:layout_marginBottom="20dp"
        />

    <ListView
        android:id="@+id/txtListViewDistribuidores"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </ListView>

</LinearLayout>

list_item_distribuidor.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android" >

    <ImageView
        android:id="@+id/imgListaProdutos"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:background="@mipmap/ic_acai"
        android:layout_marginLeft="8dp"
        />

    <TextView
        android:id="@+id/txtDistribuidor"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="@+id/imgListaProdutos"
        />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@mipmap/ic_star_round"
        android:layout_alignParentTop="@+id/txtDistribuidor"
        />

</RelativeLayout>

Answer: Opa, blza!?
o ifood trabalha na seguinte forma: nessa imagem que vc mandou, é sempre uma estrela estática (um imageView mesmo), a numeração (TextView) é um retorno da API(que provavelmente retorna apenas um int pra eles setarem o texto). A estrela é sempre estatica.

Implementação detalhada com o Rating bar

Agora, clique na classificação e veja que e uma tela mais detalhada, com 5 estrelas, agora sim o número de estrelas será baseado no INT que retorna da API, sendo possível implementar pelo Rating bar.
Answer: Consegui implementar essa solução, e como O Leonardo falou acima, precisei de uma imagem estática e um TextView pra funcionar.
Segue código funcional abaixo:
ListaDistribuidoresActivity.java
package com.pedido.meu.telas_meu_pedido;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;

public class ListaDistribuidoresActivity extends AppCompatActivity {

    ItemAdapter adapter;
    ArrayList<Integer> idImages;
    ArrayList<String> nameList;
    ArrayList<Integer> starImage;

    int ids[]={R.mipmap.ic_distribuidor};
    String names[]={"DISTRIBUIDOR"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lista_distribuidores);
        ListView listViewDistribuidores = findViewById(R.id.txtListViewDistribuidores);
        idImages = new ArrayList<>();
        idImages = getList();
        starImage = new ArrayList<>();
        starImage = getListStar();
        nameList = new ArrayList<>();
        nameList = getNameList();
        ItemAdapter adapter = new ItemAdapter(ListaDistribuidoresActivity.this, idImages,nameList, starImage);
        listViewDistribuidores.setAdapter(adapter);
        listViewDistribuidores.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id)
            {
                Toast.makeText(ListaDistribuidoresActivity.this, "Distribuidor " + nameList.get(position) + "selecionado", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private ArrayList<Integer> getListStar()
    {
        starImage = new ArrayList<>();
        starImage.add(R.mipmap.ic_star_round);
        return  starImage;
    }

    private ArrayList<String> getNameList()
    {
        nameList = new ArrayList<>();
        nameList.add("DISTRIBUIDOR 1");
        nameList.add("DISTRIBUIDOR 2");
        nameList.add("DISTRIBUIDOR 3");
        nameList.add("DISTRIBUIDOR 4");
        return  nameList;
    }

    private ArrayList<Integer> getList()
    {
        idImages = new ArrayList<>();
        idImages.add(R.mipmap.ic_distribuidor);
        idImages.add(R.mipmap.ic_distribuidor);
        idImages.add(R.mipmap.ic_distribuidor);
        idImages.add(R.mipmap.ic_distribuidor);
        return idImages;
    }
}

ItemAdapter.java
package com.pedido.meu.telas_meu_pedido;

import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;

import java.util.ArrayList;

public class ItemAdapter extends BaseAdapter {
    private Context context;
    private ArrayList<Integer> listaId;
    private ArrayList<String> listaNome;
    private ArrayList<Integer> listaStar;

    public ItemAdapter(Context context, ArrayList<Integer> listaId, ArrayList<String> listaNome, ArrayList<Integer> listaStar) {
        this.context = context;
        this.listaId = listaId;
        this.listaNome = listaNome;
        this.listaStar = listaStar;
    }

    public ItemAdapter(ListaProdutosActivity listaProdutosActivity, ArrayList<Integer> idImages, ArrayList<String> nameList) {
        this.context = listaProdutosActivity;
        this.listaId = idImages;
        this.listaNome = nameList;
    }

    @Override
    public int getCount() {
        return listaNome.size();
    }

    @Override
    public Object getItem(int position) {
        return listaNome.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        int view = 0;

        if (convertView == null)
        {
            if(view == R.layout.list_item_produtos)
            {
                convertView = View.inflate(context, R.layout.list_item_produtos, null);
                ImageView imgProducts = convertView.findViewById(R.id.imgListItemProduto);
                TextView textViewProducts = convertView.findViewById(R.id.txtListItemProduto);
                imgProducts.setImageResource(listaId.get(position));
                textViewProducts.setText(listaNome.get(position));
            }
            else
            {
                convertView = View.inflate(context, R.layout.list_item_distribuidor, null);
                ImageView imgDistributor = convertView.findViewById(R.id.imgStarDistributor);
                TextView textDistribuidor = convertView.findViewById(R.id.txtDistribuidor);
                imgDistributor.setImageResource(listaStar.get(0));
                textDistribuidor.setText(listaNome.get(position));
            }
        }
        return convertView;
    }
}

Imagem.java
package com.pedido.meu.telas_meu_pedido;

public class Imagem
{
    private int imageId;
    private String imageName;

    public int getImageId() {
        return imageId;
    }

    public void setImageId(int imageId) {
        this.imageId = imageId;
    }

    public String getImageName() {
        return imageName;
    }

    public void setImageName(String imageName) {
        this.imageName = imageName;
    }
}

activity_lista_distribuidores.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_height="match_parent"
    android:layout_width="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.pedido.meu.telas_meu_pedido.ListaDistribuidoresActivity"
    >

    <ImageView
        android:id="@+id/imgTitleListDistributor"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@mipmap/ic_distribuidor"
        android:layout_gravity="center"
        android:layout_marginTop="30dp"
        android:contentDescription="@string/txtTitleListaDistribuidores"
        />

    <TextView
        android:id="@+id/txtTitleDistributor"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/txtTitleListaDistribuidores"
        android:gravity="center"
        android:textColor="@color/colorPrimary"
        android:textStyle="bold"
        android:textSize="14pt"
        android:layout_marginTop="15dp"
        android:layout_marginBottom="20dp"
        />

    <ListView
        android:id="@+id/txtListViewDistribuidores"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </ListView>

</LinearLayout>

list_item_distribuidor.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:android="http://schemas.android.com/apk/res/android"
    >

    <ImageView
        android:id="@+id/imgListaDistribuidor"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:background="@mipmap/ic_distribuidor"
        android:layout_marginLeft="15dp"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="10dp"
        />

    <TextView
        android:id="@+id/txtDistribuidor"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:layout_marginStart="122dp"
        android:layout_marginLeft="122dp"
        android:layout_marginRight="-150dp"
        android:textStyle="bold"/>

    <ImageView
        android:id="@+id/imgStarDistributor"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:background="@mipmap/ic_star_round"
        android:layout_marginLeft="295dp"
        android:layout_marginTop="35dp"
        />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="4.2"
        android:layout_marginLeft="320dp"
        android:layout_marginTop="35dp"
        android:textStyle="bold"
        />

</RelativeLayout>

Comment: Boaaaaa é isso ai


isgl3d sphere not rendered completely

Question: Trying to render a sphere using isgl3d. The problem is that only say 75% of the sphere is being rendered.
Here's the code:
[self.camera setPosition:iv3(0, 3, 7)];
_container = [self.scene createNode];

Isgl3dTextureMaterial * ballMaterial = [Isgl3dTextureMaterial materialWithTextureFile:@"balltext.jpg" shininess:0.7 precision:Isgl3dTexturePrecisionLow repeatX:YES repeatY:YES];

_sphere = [Isgl3dSphere meshWithGeometry:1 longs:40 lats:40];
node = [ _container createNodeWithMesh:_sphere andMaterial:ballMaterial];
[self.scene addChild:node];

Answer: Please check the image size. I think it should be 32x32, 64X64, 128x128 or 256x256. By changing image size you may be able to solve the issue.

isgl3d sphere not rendered completely


Simplification algebraic of a cube root.

Question: I am trying to simplify this:
$$\frac{1000}{\pi \cdot (\frac{500}{\pi})^{\frac{2}{3}}}$$
and I think it becomes:
$$2 \cdot \sqrt[3]{\frac{500}{\pi}}$$
I basically thought we cube root the $\frac{500}{\pi}$ and then multiply the denominator by $\frac{500}{\pi}$ which could cancel out some stuff. This is how I thought about it:
$$\frac{1000}{\pi \cdot \sqrt[3]{\frac{500}{\pi}} \cdot \frac{500}{\pi}}$$
$$ = \frac{1000 \cdot \pi}{\pi \cdot \sqrt[3]{\frac{500}{\pi}} \cdot 500}$$
Is there a better way to do this cancellation?
Comment: Hmm, $$\frac{1000}{\pi \cdot (\frac{500}{\pi})^{\frac{2}{3}}}$$ or $$\frac{1000}{\pi \cdot \left(\frac{500}{\pi}\right)^{\frac{2}{3}}}$$? They look about the same, right? Just thinking out loud, so to speak.
Answer: I would do it like this:
$$\dfrac{1000}{\pi\cdot\frac{\sqrt[3]{500^2}}{\sqrt[3]{\pi^2}}}=\dfrac{1000}{\pi\cdot\frac{\sqrt[3]{500^2}}{\sqrt[3]{\pi^2}}\cdot\dfrac{\sqrt[3]\pi}{\sqrt[3]{\pi}}}=\dfrac{1000}{\pi\cdot\frac{\sqrt[3]{250000\pi}}{\pi}}=\dfrac{1000}{\sqrt[3]{250000\pi}}=\dfrac{1000}{50\sqrt[3]{2\pi}}=\dfrac{20}{\sqrt[3]{2\pi}}\cdot\dfrac{\sqrt[3]{4\pi^2}}{\sqrt[3]{4\pi^2}}$$
$$=\dfrac{20\sqrt[3]{4\pi^2}}{2\pi}=\dfrac{10\sqrt[3]{4\pi^2}}{\pi}$$
The part where you are going wrong is where you are disregarding the square inside the cube root of $\frac {500}{\pi}$, and you are just "taking it out" of the cube root to the denominator.
This is the step where you have gone wrong:$$\dfrac{1000}{\pi\cdot \sqrt[3]{\frac{500}{\pi}}\cdot \frac {500}{\pi}}$$
Comment: maybe $500^2=250'000$?
Comment: there is something uncorrect at the end, you need a 2 more at the denominator
Comment: Now solutions match!
Answer: $$\frac{1000}{\pi \cdot (\frac{500}{\pi})^{\frac{2}{3}}}=$$
$$ 2 \frac {\frac {500}{\pi}}{(\frac {500}{\pi})^\frac {2}{3}}=$$
$$ 2(\frac {500}{\pi})^\frac {1}{3}=$$
$$10(\frac {4}{\pi})^\frac {1}{3}$$
Comment: How did you get to the last line from the second to last line?
Comment: $500=4\times 125$ and $125=5^3$ and $2\times 5=10.$
Answer: $$\frac{1000}{ \pi \cdot (\frac{500}{\pi})^{\frac{2}{3}} }
=\frac{1000}{\pi^{\frac{1}{3}}\cdot 2^{-\frac{2}{3}}\cdot 2^{\frac{2}{3}}\cdot 500^{\frac{2}{3}}}
=\frac{1000}{\pi^{\frac{1}{3}}\cdot 2^{-\frac{2}{3}}\cdot 1000^{\frac{2}{3}}}
=\frac{2\cdot 1000^{\frac{1}{3}}}{(2\pi)^{\frac{1}{3}}}
=\frac{20}{\sqrt[3] {2\pi} }=\frac{10\sqrt[3] {4\pi^2} }{\pi}=10\sqrt[3]{\frac{4}{\pi}}$$
Comment: Ok you check mine!


How to add both CORS headers and Browser expired header in same conf

Question: I need to add both expires headers AND allow cors in nginx
If I add
location ~*  \.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf|x-html|css|xml|js|woff|woff2|ttf|svg|eot)$ {
expires 30d;}

then the expired headers work fine.
If I add
location ~* \.(ogg|ogv|svg|svgz|eot|otf|woff|mp4|ttf|css|rss|atom|js|jpg|jpeg|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|ppt|tar|mid|midi|wav|bmp|rtf|html|txt|htm)$ {
    if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        #
        # Custom headers and headers various browsers *should* be OK with but aren't
        #
        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
        #
        # Tell client that this pre-flight info is valid for 20 days
        #
        add_header 'Access-Control-Max-Age' 1728000;
        add_header 'Content-Type' 'text/plain charset=UTF-8';
        add_header 'Content-Length' 0;
        return 204;
    }
    if ($request_method = 'POST') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
        add_header 'Access-Control-Expose-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
    }
    if ($request_method = 'GET') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
        add_header 'Access-Control-Expose-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
    }
}

then the CORS works fine.
But if I add them both together like this, then only the expired headers works and the cors stops working.
location ~*  \.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf|x-html|css|xml|js|woff|woff2|ttf|svg|eot)$ {
expires 30d;}

location ~* \.(ogg|ogv|svg|svgz|eot|otf|woff|mp4|ttf|css|rss|atom|js|jpg|jpeg|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|ppt|tar|mid|midi|wav|bmp|rtf|html|txt|htm)$ {
    if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        #
        # Custom headers and headers various browsers *should* be OK with but aren't
        #
        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
        #
        # Tell client that this pre-flight info is valid for 20 days
        #
        add_header 'Access-Control-Max-Age' 1728000;
        add_header 'Content-Type' 'text/plain charset=UTF-8';
        add_header 'Content-Length' 0;
        return 204;
    }
    if ($request_method = 'POST') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
        add_header 'Access-Control-Expose-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
    }
    if ($request_method = 'GET') {
        add_header 'Access-Control-Allow-Origin' '$http_host';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
        add_header 'Access-Control-Expose-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
    }
}

What is wrong with above combination? How can I fix it?
Comment: Any request can only match one `location`.
Comment: I think it may be todo with having the same location twice, but I need guidance as to how to merge the tw parts together in same location, or create another location so that the result is as intended.  All help really appreciated
Comment: You just need to find out the extensions which need to have both headers, and either one of those headers, and then make appropriate location blocks. That is, three `location` blocks total.
Answer: The best answer in terms of the most efficient way to solve the problem you have is in my experience the one provided by Phillip -Zyan K Lee-Stockman.
However, to answer your specific question and to help you understand how the location blocks work in NGINX, I have amended your code. I have essentially created two location blocks, each applies to different file types. The first I have created to match the file types you wished to apply expired headers too this has instruction to send expires headers along with the same CORS code that you used. The second location block is used solely for the other file types you wanted to add CORS headers too, but did not want the expires headers added.
As each location block contains different file types there is no problem with NGINX choosing one or the other, and this achieves your goal.
However unless your using a very old version of NGINX (prior to 1.7.9, dec 2014) this method is unnecessarily cumbersome, usually it's better to use the http map module, as suggested in the answer I refer to above.
 location ~*  \.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf|x-html|css|xml|js|woff|woff2|ttf|svg|eot)$ {
expires 30d;

if ($request_method = 'OPTIONS') {
    add_header 'Access-Control-Allow-Origin' '*';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    #
    # Custom headers and headers various browsers *should* be OK with but aren't
    #
    add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
    #
    # Tell client that this pre-flight info is valid for 20 days
    #
    add_header 'Access-Control-Max-Age' 1728000;
    add_header 'Content-Type' 'text/plain charset=UTF-8';
    add_header 'Content-Length' 0;
    return 204;
}
if ($request_method = 'POST') {
    add_header 'Access-Control-Allow-Origin' '*';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
    add_header 'Access-Control-Expose-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
}
if ($request_method = 'GET') {
    add_header 'Access-Control-Allow-Origin' '*';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
    add_header 'Access-Control-Expose-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
}          }
location ~* \.(ogg|ogv|svg|svgz|eot|otf|mp4|rss|atom|zip|tgz|gz|rar|bz2|doc|xls|exe|ppt|tar|mid|midi|wav|bmp|rtf|html|txt|htm)$ {

    if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        #
        # Custom headers and headers various browsers *should* be OK with but aren't
        #
        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
        #
        # Tell client that this pre-flight info is valid for 20 days
        #
        add_header 'Access-Control-Max-Age' 1728000;
        add_header 'Content-Type' 'text/plain charset=UTF-8';
        add_header 'Content-Length' 0;
        return 204;
    }
    if ($request_method = 'POST') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
        add_header 'Access-Control-Expose-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
    }
    if ($request_method = 'GET') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
        add_header 'Access-Control-Expose-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
    }
}

I hope this helps.
Answer: nginx evaluates locations on a specific pattern, which is described in its manual.
in summary: on the first match it stops, as you inserted similar locations twice, it evaluates them from top to bottom and stops after the first location that matches (which depending on the file type you choose for testing incidentally was the expire location).
Have a look at the http headers module which might solve your problem using http map module and the mime type:
map $sent_http_content_type $expires {
    default         off;
    application/pdf 42d;
    ~image/         max;
}

expires $expires;

so you would have only the location for CORS and a map for the content types you need to expire after 30d.


How to write a property callback for a custom field to use with the Entity module

Question: I have a custom field with multiple values. I would like it to work with the Entity module. I need to create the correct property_callbacks in hook_field_info(). My field schema looks like this:
'ref' => array(
  'type' => 'varchar',
  'length' => 32,
  'not null' => TRUE,
),
'title' => array(
  'type' => 'varchar',
  'length' => 255,
  'not null' => TRUE,
  'default' => '',
),
'description' => array(
  'type' => 'text',
  'not null' => TRUE,
  'size' => 'big',
),
'weight' => array(
  'type' => 'int',
  'unsigned' => TRUE,
  'not null' => TRUE,
  'default' => 0,
),
'status' => array(
  'type' => 'int',
  'unsigned' => TRUE,
  'not null' => TRUE,
  'default' => 1,
),

Does anyone know how to actually do this? There is very little documentation around for it.
Answer: Kind of :) ... if its just numbers and strings you can cheat a little. I added some basic integer columns to the User table and wanted EntityAPI and views etc to be aware of them and did the following:
/**
 * Implementation of hook_entity_property_info(). This dpeends on the EntityAPI.
 *
 * This defines the properties/attributes/"fields" of our Entity regardless of
 * whether they are drupal Fields or custom data (in the base table).
 */
function dew_nagging_entity_property_info_alter(&$info) {
  $properties = &$info['user']['properties'];
  $properties['dew_survey_count_to_complete'] = array(
    'label' => t('Number of Surveys to Complete'),
    'type' => 'integer',
    'description' => 'When a student logs in the system derives how many surveys they must complete. We store this value to make sending the nag email business logic easier.',
    'schema field' => 'dew_survey_count_to_complete',
    'getter callback' => 'entity_property_verbatim_get',
    'setter callback' => 'entity_property_verbatim_set',
  );
  $properties['dew_survey_completed_count'] = array(
    'label' => t('Number of Completed Surveys to Date'),
    'type' => 'integer',
    'description' => 'This is a count of the completed surveys completed by a student in real-time. We store this value to make sending the nag email business logic easier.',
    'schema field' => 'dew_survey_completed_count',
    'getter callback' => 'entity_property_verbatim_get',
    'setter callback' => 'entity_property_verbatim_set',
  );
  $properties['dew_surveys_all_completed'] = array(
    'label' => t('Has the student completed all their Surveys?'),
    'type' => 'integer',
    'description' => 'This is a boolean indictator (0,1) of whether or not a student has completed their surveys. We store this value to make sending the nag email business logic easier.',
    'schema field' => 'dew_surveys_all_completed',
    'getter callback' => 'entity_property_verbatim_get',
    'setter callback' => 'entity_property_verbatim_set',
  );
  return $info;
}

entity_property_verbatim_set and *_get just pull the field from the database if $info['schema field'] is defined.
I also had to make the DB changes in my .install file with db_add_field() for each database column. I also had to notify EntityAPI of my schema changes to the user table via hook_schema_alter(). All these DB schema fields and EntityAPI meta data field defintions must correlate properly.

if its more complicated, you do something like found in Ubercart products, you're just returning the item from the given Node and Field.
See http://api.ubercart.me/api/drupal/ubercart%21uc_order%21uc_order.module/function/uc_order_uc_order_get_properties/7.
EDIT
Apparently the entity_metadata_* functions have been deprecated and you should call entity_property_verbatim_get(), or entity_property_verbatim_set().
Comment: Thanks for the reply. Do you know if I should be doing the following:

$property['getter callback'] = 'entity_metadata_field_verbatim_get';

$property['setter callback'] = 'entity_metadata_field_verbatim_set';

unset($property['query callback']);
Comment: I dont know what function you're trying to put that in. the "property getter" and setters go in hook_property_info() or hook_property_info_alter(), hook_field_info() is the Core drupal API hook_property_* is the EntityAPI. I have no other advice at this time.
Comment: I'm using hook_field_info and property_callbacks. I've just seen it in other examples so I guess I should add it. Either way, I've now tested the wrapper and it's saving correctly and getting the data as expected.
Answer: Here is simpler example:
/**
 * Callback to alter the property info of custom field.
 */
function MYMODULE_property_info_callback(&$info, $entity_type, $field, $instance, $field_type) {
  $name = $field['field_name'];
  $property = &$info[$entity_type]['bundles'][$instance['bundle']]['properties'][$name];

  $property['type'] = 'MYFIELD';
  $property['getter callback'] = 'entity_metadata_field_verbatim_get';
  $property['setter callback'] = 'entity_metadata_field_verbatim_set';

  unset($property['query callback']);
}

This should be called from property_callbacks in your hook_field_info and it should automatically store your values per each property.


VLAN not working on PFSense (SG 1100) with HP switch (HP E3500-48G-PoE yl)

Question: Recently I bought a PFSense server (SG 1100) and a HP switch (HP E3500-48G-PoE yl). My idea is to create VLANs on the PFSense server, and use them on the connected HP switch.
I have found a tutorial which helped me set up (https://www.youtube.com/watch?v=b2w1Ywt081o). However if I connect a device to the port which I configured as the VLAN it does not get an IP lease.
PFSense configuration:
Created VLAN under interfaces > VLANs

Added the appropriate interface under interfaces > assignments

Enabled the DHCP server for the VLAN interface

Added the firewall rules, in order for it to have internet access

Since I was not 100% sure, I also added the VLAN to the switch section under interfaces > switches (I copied the configuration of LAN since that is the port where the switch is connected to)

HP Switch configuration:
<code>Running configuration:

; J8693A Configuration Editor; Created on release #K.16.02.0026
; Ver #10:08.03.81.30.02.34.59.2c.6b.ff.f7.fc.7f.ff.3f.ef:26
hostname "HP-Switch-3500yl-48G"
module 1 type j86yya
module 2 type j86xxa
trunk 1 trk1 trunk
snmp-server community "public" unrestricted
vlan 1
   name "DEFAULT_VLAN"
   no untagged 33
   untagged 2-32,34-48,Trk1
   ip address dhcp-bootp
   exit
vlan 2
   name "VTest"
   untagged 33
   no ip address
   exit
spanning-tree Trk1 priority 4
</code>
I also tried to set the IP config of vlan 2 to dhcp but that didn't work either.
If I connect a PC to port 2-32 / 34-48 it gets an IP address of the LAN configuration of PFSense. However if I connect a PC to port 33 it won't get an IP address assigned. I hope somebody can help me with this issue.
Answer: After lots of debugging, I contacted Netgate, who helped me out. All the settings are correct except the part I was not sure about.
You have to go to interfaces > switches > VLANs tab, and add your VLAN and tag both 0 (default) and 2 (LAN).
Comment: this was exactly what I needed. Thank you. No tutorial videos even show this step. Must be something specific to the SG-1100
Comment: I concur - I've had the _exact_ same experience with an SG-1100 and HP ProCurve 1810g-24 J9803A, and had performed the exact same steps before finding this. Adding the extra switch tag solved the issue.

I'd appreciate an explanation of what this is doing if anyone reading this happens to know? I've performed this same task on an SG-3100 and virtualised pfSense instance (neither of which have the switch options) and this wasn't necessary.


How to organize location directives in nginx config

Question: I have a bunch of URLs which share a common parent directory, e.g.
/content/a/.../...
/content/b/.../...
/content/c/.../...

What I'm currently doing is having a separate location block for each of them, but the actions performed inside the block are the same.
I wonder if it is more optimal to just have a single location directive for /content/, e.g.
location ^~ /content/ {
    proxy_pass       http://127.0.0.1:8080;
    proxy_redirect   off;
}

But how should I deal with invalid requests such as /content/d/..., /content/blah/, etc?
Comment: how do you check if the request is invalid or valid?
Comment: @AndreiMikhaltsov, by invalid, I mean there is no resource (e.g. handlers, static files, etc) available for the requested url.
Answer: You can use try_file directive inside content location like:
location /content {
   try_files $uri $uri/ @pass =404;
}
location @pass {
  proxy_pass       http://127.0.0.1:8080;
      proxy_redirect   off;
}

it will check file, @pass location and then return 404 if nothing found;
Answer: If the list of valid resources is known and small, how about a regex match? Something like:
location ~ ^/content/(a|b|c|etc)/ {
    proxy_pass       http://127.0.0.1:8080;
    proxy_redirect   off;
}


locking views in Xcode storyboard

Question: coming from a design background myself, I like to use the storyboard as much as I can before I jump into code. That being said, I was wondering if there is a feature in Xcode that enables locking some views while adjusting other views.
Let me explain by an example.. the currently selected view is a tiny 1x60px image.. that is on top of several other images.. unfortuantely Xcode doesn't allow you to zoom in more than this level (that would have solved it). I was wondering if I can lock the other images (ie SliderContainer, blackcab_comb, funryde_com, train_comp so that they're not affected by what I do with the view.. what's happening right now is that when I try to drag the small view around, I keep on dragging the views behind it.
the way I currently deal with this is just simply updating the x,y values of the view until I get it right.. There must be a better way.
Answer: You really shouldn't drag views around. For one, because of what you just said. Another reason being, if you're working with auto layout, you add constraints after an hour of work, then you decide do drag something, instead of changing it's X/Y value, it will mess up all the constraints.
To answer your question, I don't think there is such a feature.
Comment: i usually add my constraints after i've done all my dragging.. frankly there are many other `illustrator` uses that can really help w/ storyboard.. for example grouping of objects.. supposed i wanted to treat the bus, car and faces as one unit and center all three of those within the containing view.. anyways..

locking views in Xcode storyboard


Memorizar "não mostrar novamente" com localStorage

Question: Eu tenho uma div que pode ser oculta ao clicar em um botão:

$(".fechar").click(function(){
    $("#mensagem").hide();
});

(...)

  <button class="fechar">Fechar e não mostrar novamente</button>

O que preciso é que ela não volte mais a aparecer após ser oculta pela primeira vez.
Encontrei uma forma com o Jquery dialog, mas ele não me permite personalizar direito, pelo menos não de forma simples, então preciso e prefiro que seja assim.
Como faço para memorizar esta ação no localStorage?
Comment: Mas este código que colocou já faz  exatamente isto.
Comment: Não, @LeAndrade... eu preciso que seja memorizado no localStorage para que, mesmo atualizando a página, esta div não apareça novamente...
Comment: @ThiagoSoubra, veja minha resposta sobre
Comment: Nossa verdade, não prestei atenção!
Answer: Simples, primeiro você precisa capturar no seu evento click que a div foi clicada, poderia ser algo como:
$(".fechar").click(function(){
    $("#mensagem").hide();
    //definindo que foi clicado
    window.localStorage.setItem('clicado', 'clicado');
});

E no seu document.ready(), verifique se clicado está definido, caso estiver, oculte a div:
$(document).ready(function(){
   if(window.localStorage.getItem('clicado')) {
        $("#mensagem").hide();
   }
});

Seu código final:
$(".fechar").click(function(){
    $("#mensagem").hide();
    window.localStorage.setItem('clicado', 'clicado');
});

$(document).ready(function(){
   if(window.localStorage.getItem('clicado')) {
        $("#mensagem").hide();
        console.log('clicado definido')
   }
});

Veja funcionando no Jsfiddle: https://jsfiddle.net/x43n7fsu/2/
Comment: Muito obrigado pela resposta, amigo! Mas eu fiquei meio perdido... colei esse teu código lá e a função não funcionou. Deve ser porque não estou sabendo usar. Será que você pode por pra mim aqui nesse Fiddle? [link](https://jsfiddle.net/hc51vb9d/)
Comment: @ThiagoSoubra  Editei a resposta, olhe agora.
Comment: Perfeito! muito agradecido!!
Comment: Por nada, amigo :D


How can i withdraw from FTX exchange using the REST API in Python?

Question: i have check their REST API and couldn't found the way to withdraw for example ( ETH ) .
i found only function for withdraw with Fiat but there is no function to withdraw cryptocurrencies coin .
i am using the Python version ( REST API ) .
Comment: I think you're better off asking the FTX exchange itself. You are not encountering any issues that we can help with here.
Answer: You might check this ftx official docs for help.
Also check ccxt which is a helpful toolkit for writing crypto exchange scripts.


How do I know if I adequately/correctly preprocessed my PCA/PCR data?

Question: I'm an engineer with an interest in statistics, and my company sent me to a 1 week training in PCA/PCR (principal component analysis/regression) using The Unscrambler. I'm starting to apply these analyses to data sets in my work, but I'm the most experienced person my company has in this analysis.
I understand that most data requires some amount of pre-processing, and what the different methods and types are, but how do I know if I've done a good job of preprocessing? Are there diagnostics for preprocessing? How do I tell an over-processed data set versus an under-processed set?
The pre-processing I was taught includes things like transformations, mean centering, variable scaling, normalization, derivatives, MSC/eMSC that are performed on the data set before the PCA or PCR is performed.
The first data set I'm working on is continuous process data for a PCR (how can we predict the outcome variable based on these (correlated) input variables). The second data set will be classification of different spectra (if the type of problem matters).
Answer: One thing is that the data entering into the PCA should typically be standardized (zero mean, unit standard deviation) or else different scaling among variables might greatly influence your results.
And you should make sure that your data are reliable, as in any type of analysis. This seems obvious, but is too often overlooked. (It's not unusual to spend as much or more time doing quality control on data as on the analyses per se.)
Beyond that, think about what any linear modeling is trying to accomplish: fit a reasonable first-order approximation to the relation of your dependent variable to your independent variables. Any pre-PCA data transformation (or before any linear model) should be done with that in mind. As an example, for necessarily positive data with skew, a log transform prior to analysis often will provide a better model. Such transformations and other pre-processing should be done with that goal in mind, informed by your understanding of the subject matter. For the purposes you have in mind, don't be afraid to try different pre-processing approaches.
Ultimately, the test will be whether your prediction/classification models work adequately.


30% difference on accuracy between cross-validation and testing with a test set in weka? is it normal?

Question: I'm new with weka and I have a problem with my text classification project using it.
I have a train dataset with 1000 instances and one of 200 for testing. The problem is that when I try to test the accuracy of some algorithms (like randomforest, naive bayes...) with weka, the number given by cross-validation and test set is too different.
Here is an example with cross-validation
<code>=== Run information ===

Scheme:weka.classifiers.trees.RandomForest -I 100 -K 0 -S 1
Relation:     testData-weka.filters.unsupervised.attribute.StringToWordVector-R1-W10000000-prune-rate-1.0-T-I-N0-L-stemmerweka.core.stemmers.IteratedLovinsStemmer-M1-O-tokenizerweka.core.tokenizers.WordTokenizer -delimiters " \r\n\t.,;:\"\'()?!--+-í+*&#$\\/=<>[]_`@"-weka.filters.supervised.attribute.AttributeSelection-Eweka.attributeSelection.InfoGainAttributeEval-Sweka.attributeSelection.Ranker -T 0.0 -N -1
Instances:    1000
Attributes:   276
[list of attributes omitted]
Test mode:10-fold cross-validation

=== Classifier model (full training set) ===

Random forest of 100 trees, each constructed while considering 9 random features.
Out of bag error: 0.269

Time taken to build model: 4.9 seconds

=== Stratified cross-validation ===
=== Summary ===

Correctly Classified Instances         740               74      %
Incorrectly Classified Instances       260               26      %
Kappa statistic                          0.5674
Mean absolute error                      0.2554
Root mean squared error                  0.3552
Relative absolute error                 60.623  %
Root relative squared error             77.4053 %
Total Number of Instances             1000

=== Detailed Accuracy By Class ===

               TP Rate   FP Rate   Precision   Recall  F-Measure   ROC Area  Class
                 0.479     0.083      0.723     0.479     0.576      0.795    I
                 0.941     0.352      0.707     0.941     0.808      0.894    E
                 0.673     0.023      0.889     0.673     0.766      0.964    R
Weighted Avg.    0.74      0.198      0.751     0.74      0.727      0.878

=== Confusion Matrix ===

   a   b   c   <-- classified as
 149 148  14 |   a = I
  24 447   4 |   b = E
  33  37 144 |   c = R
</code>
74% , it's something...
But now if I try with a my test set of 200 instances...
<code>=== Run information ===

Scheme:weka.classifiers.trees.RandomForest -I 100 -K 0 -S 1
Relation:     testData-weka.filters.unsupervised.attribute.StringToWordVector-R1-W10000000-prune-rate-1.0-T-I-N0-L-stemmerweka.core.stemmers.IteratedLovinsStemmer-M1-O-tokenizerweka.core.tokenizers.WordTokenizer -delimiters " \r\n\t.,;:\"\'()?!--+-í+*&#$\\/=<>[]_`@"-weka.filters.supervised.attribute.AttributeSelection-Eweka.attributeSelection.InfoGainAttributeEval-Sweka.attributeSelection.Ranker -T 0.0 -N -1
Instances:    1000
Attributes:   276
[list of attributes omitted]
Test mode:user supplied test set: size unknown (reading incrementally)

=== Classifier model (full training set) ===

Random forest of 100 trees, each constructed while considering 9 random features.
Out of bag error: 0.269

Time taken to build model: 4.72 seconds

=== Evaluation on test set ===
=== Summary ===

Correctly Classified Instances          86               43      %
Incorrectly Classified Instances       114               57      %
Kappa statistic                          0.2061
Mean absolute error                      0.3829
Root mean squared error                  0.4868
Relative absolute error                 84.8628 %
Root relative squared error             99.2642 %
Total Number of Instances              200

=== Detailed Accuracy By Class ===

               TP Rate   FP Rate   Precision   Recall  F-Measure   ROC Area  Class
                 0.17      0.071      0.652     0.17      0.27       0.596    I
                 0.941     0.711      0.312     0.941     0.468      0.796    E
                 0.377     0          1         0.377     0.548      0.958    R
Weighted Avg.    0.43      0.213      0.671     0.43      0.405      0.758

=== Confusion Matrix ===

  a  b  c   <-- classified as
 15 73  0 |  a = I
  3 48  0 |  b = E
  5 33 23 |  c = R
</code>
43% ... obviously, something is really wrong, I used batch filtering with test set
What am I doing wrong? I manually classified the test and train set using the same criteria, so I find strange that differences.
I think I got the concept behind CV, that's why I don't understand that big gap.
Excuse my english and thanks, any help will be appreciated.
Answer: The problem is that the distribution of classes in your training dataset is dramatically different than the distribution of your classes in your testing dataset. In your training dataset if you were to always predict class B, then you would have about a 50 percent accuracy; however, in your testing dataset notice that class B is very under represented as compared to the training dataset. The algorithm predicts the vast majority of your observations are going to be class B but it's wrong.
The general solution is to shuffle your dataset before splitting off a final validation set. This will help ensure the distributions of both data sets are similar.
If your data changes dramatically through time, then you should not shuffle your dataset. Having a final validation set that has observations that were recorded after your training dataset is ideal to understand how well a final model trained on all of the data will predict subsequent future observations.
Comment: This answer isn't talking about balance, it's talking about similarity between the train and test sets. Try it again with a different train/test split. That's all cross validation is doing anyway: making several train/test splits and averaging the test error. It will also be helpful to look at the _distribution_ of errors instead of just their average, to get a sense of how likely or unlikely you are to get a "bad" split like this one
Comment: the class distribution in test set is random, and it needs to be(the main goal is to know if brands post in social networks can be categorizeda..well..something similar to sentiment analysis, and if it can, doing it with a trained model, so I get 200 post and then I classiticated them to know the accuracy with already labeled instances)
About the distribution in trainset...it's: 31.1% - class I, 47.5% - E, 21.4% R . It's really imbalanced? (the R class should be the easiest one to be classified) there is no overfitting here?
What can I do to improve the accuracy with random test sets?
Thanks


Finding a probability on an infinite set of numbers

Question: I have $\Omega={1,2,3,...}$ and the possibility of each number is $P(A) = 2^{-n}$, $n=1,2,3...$
I have to prove $P(\Omega) = 1$ . I can understand that from the graph, but how do I actually prove it?
Answer: Just use the Geometric Series formula.
$P(\Omega)= \sum_{n=1}^ \infty \frac{1}{2^n}= \frac { \frac{1}{2}}{1- \frac{1}{2}}= 1$
Comment: @CnewbieWannabePro: $P(\Omega)= \sum_{n=1}^ \infty \frac{1}{2^n} = \frac12 + \sum_{n=2}^ \infty \frac{1}{2^n} = \frac12 +\frac12 P(\Omega)$ which is easy to solve
Comment: thank you. I knew this is the solution, dont understand how to solve it, Ill search it now, maybe, if u can, u can give me some links to understand it.
Comment: Which part are you not understanding?
Comment: I dont know how to actually solve the formula. How do I get this result?
Comment: @CnewbieWannabePro If you want to read further, https://en.wikipedia.org/wiki/Geometric_series#Formula
Answer: $P(Ω) = \sum_{n=1}^{\infty} P(n) = \sum_{n=1}^{\infty} 2^{-n} = \frac{1}{2}+\frac{1}{2^2}+\frac{1}{2^3} + ..... = \frac{1/2}{1-1/2} =1 $
Answer: Summation of 1/2^k as k goes to infinity is 1..


Why doesn't code insight in PHPEd work with the Zend Framework?

Question: I am currently working with the Zend Framework and I use PHPEd as my favourite PHP editor. I have already seen that the IDE can trace my own functions and libraries and display them in the code insight. How can I add the libraries of Zend Framework to the code insight?
They are loaded with a internal autoload function of the Zend Framework, so PHPEd can't find the points where they are included and doesn't show them in the list of functions.
Is there a possibility to tell PHPEd always to show the Zend Framework functions and classes in the code insight?
Comment: I don't know the answer to your question but I can tell you that Aptana which I use for ZF application development generates these links and auto-completion works fine, even if you use the Loader.
Answer: Okay, after reinstalling NuSphere a third time it finally works. I have no clue why...
Answer: It worked fine for me in PhpED when I tried ZF code, from the beginning.
To have any 3rd party code appeared in Code Insight, you need to either include corresponding directory into the project list of additional directories or just place the directory with code as a project subdirectory. Then open Code Explorer and check for the framework classes. If they don't appear (for any reason) for longer than 5-6sec, just press refresh in the popup.
Comment: Just look at the date of the post... it was 2009. And it seems to have been just some bug in my installation.
Answer: They (NuSphere) just released PhpED V11.0 which has full support for ZF etc. - http://www.nusphere.com/products/php_frameworks.htm