Google Analytics Measurement Protocol Returned Gif

Question: I'm using the GA measurement protocol, and it's returning a gif file.
I'm a little unclear what this file is for - ideally I'd like to be able to send measurement protocol requests as fire and forgets to keep page load times at a minimum.
Is it important to render this gif on the page?
Comment: But if you are on the page, why are you sending hit using Measurement Protocol ?
Comment: @Tushar will capture 100% of visitors, we're losing ~30% due to adblockers.
Comment: I dont think so you will lose any traffic due to ad blocks... I am working with some of the biggest publishers across the world, and I would never recommend measurement protocol...no one lost traffic because of ad block. Please describe your problem statement why you think ad block is making your traffic to lose
Comment: @Tushar adblockers block Google Analytics, that's a pretty easily verifiable fact.  Different between Google Analytics Traffic and Cloudflare reported traffic is ~30%.
Comment: No, who so ever told you that Ad blocker blocks ga, its so not true. Only ads tags like floodlight get blocked by ad blocker. just open you stack overflow, inspect element-->network--> filter with collect. Put the ad blocker on and refresh...you will see the GA still getting fired ;) If ad blocker would have stopped GA, I would have been in stealth mode ;0
Comment: I am sure these are some kinds of bots as the GA filters them.  CloudFlare tracks all of your traffic by requests, so your CloudFlare visitor number is most likely higher.
Comment: https://www.quantable.com/analytics/how-many-users-block-google-analytics/

Says here that uBlock Origin, Purify, Adblock Browser all block by default.

Secondly, if you have JS disabled like some popular privacy plugins do, GA wont run.

CF is higher because it includes bots, people with JS disabled, and people with Adblockers.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/142909/discussion-between-tushar-and-tom-gullen).
Answer: That's simply a design decision by Google - calls to the GA endpoint return a 200 http status and a 1x1 transparent gif (regardless if your payload data is valid or not, so don't use that to ascertain if your hit has been recorded).
I presume a http 204 not content would have worked as well, but at least with the gif image you can stick you measurement protocol call into an image tag (as a tried and tested way to transmit data over domain boundaries from your domain to Google).
The browser needs to receive it know that the request is complete, but you do not need to render it.


Can't make ALB Health check working using @grpc/grpc-js NodeJS application deployed on ECS Fargate

Question: My gRPC NodeJS server uses @grpc/grpc-js and exposed the server using
const healthPackage = loadSync(path.join(__dirname, '/protos/health.proto'), {
  keepCase: true,
  longs: String,
  enums: String,
  defaults: true,
  oneofs: true,
});
const healthProto = grpc.loadPackageDefinition(healthPackage).grpc as any;
server.addService(healthProto.Health.service, {
  Check: checkHealth,
  Watch: watchHealth,
});

server.bindAsync(
  '127.0.0.1:50051',
  grpc.ServerCredentials.createInsecure(),
  () => {
    server.start();
    console.log('gRPC server started on 127.0.0.1:50051');
  },
);

I have defined health.proto that look like this
syntax = "proto3";

package grpc;

message HealthCheckRequest {
  string service = 1;
}

message HealthCheckResponse {
  enum ServingStatus {
    UNKNOWN = 0;
    SERVING = 1;
    NOT_SERVING = 2;
    SERVICE_UNKNOWN = 3;
  }
  ServingStatus status = 1;
}

service Health {
  rpc Check(HealthCheckRequest) returns (HealthCheckResponse);

  rpc Watch(HealthCheckRequest) returns (stream HealthCheckResponse);
}

I have tried setting the ALB group health check path /grpc.Health/Check, also set HTTPS listener rule to match that path and forward that to target group. The load balancer still fails and my grpc server not exposed. My server exposed on 50051 port. How can I resolve the health check path? Included the AWS settings screenshots.

I tried setting diffrent code on health check path. My code was returning serving status. My server also have Reflection implemented.
Comment: Are you using SSL? If I'm not wrong ALB with GRPC use HTTP/2 and is sort of mandatory to configure SSL in the balancer
Comment: Yes. That is configured.
Comment: [`@grpc/grpc-js`](https://www.npmjs.com/package/@grpc/grpc-js) includes an implementation of [`grpc-health-check`](https://github.com/grpc/grpc-node/tree/master/packages/grpc-health-check) of the gRPC [Health Checking Protocol](https://github.com/grpc/grpc/blob/master/doc/health-checking.md), so you can save yourself some work.You don't show how you're implementing/adding the service. You don't clearly show how you're configuring the LB to access it.
Comment: Hello @DazWilkin I've added more details you asked for. Thanks for the info.
Comment: Your code doesn't work. You've not defined `server`, `checkHealth` etc. I encourage you to read the gRPC docs and maybe have a look at the [examples](https://github.com/grpc/grpc-node/tree/master/examples). You should not use localhost (`127.0.0.1`) as the endpoint (as this permits no external traffic).
Comment: I'll post an "answer" comprising working code for you to use as a basis.
Answer: I'm unfamiliar with AWS|ALB but your LB config looks OK.
Your code doesn't work.
Here's a working example:
const grpc = require("@grpc/grpc-js");
const protoLoader = require("@grpc/proto-loader");

const PROTO_PATH = `${__dirname}/protos/health.proto`;

const PORT = 50051;

const healthPackage = protoLoader.loadSync(
  PROTO_PATH, {
    keepCase: true,
    longs: String,
    enums: String,
    defaults: true,
    oneofs: true,
  },
);

const proto = grpc.loadPackageDefinition(healthPackage).grpc;

function checkHealth(call, callback) {
  console.log("[checkHealth] invoked");

  callback(null,{
    status: "SERVING",
  });
}

var server = new grpc.Server();
server.addService(proto.Health.service, {
  Check: checkHealth,
});

server.bindAsync(
  `0.0.0.0:${PORT}`,
  grpc.ServerCredentials.createInsecure(),
  () => {
    server.start();
    console.log(`gRPC server started on :${PORT}`);
  },
);

You can test this using gRPCurl:

Run the gRPC server

node index.js

gRPC server started on :50051

Test the Check method:

grpcurl \
-plaintext \
--proto health.proto \
:50051 \
grpc.Health/Check

{
  "status": "SERVING"
}

Comment: I didn't add checkHealth method to the question. The server is running fine and responding exactly the same as yours.
Comment: You would have saved us both time by including these facts in your question. There's a reasonable expectation that questions contain a minimally reproducible example of the issue.Since it appears that your application responds to health checks as expected, the issue appears to be with the LB config. Good luck!


How to disable or enable button from different page

Question: How to disable/enable button from admin page with PHP php.
page1 = button

admin page = disable / enable button in page 1

So we have a different page ( 2 page ) .
page1 and admin page .

How to disable/enable that button from admin page?
The point is just want disable and enable button from admin page ( 2 diffrent page )
<input type="submit"
       name="tebak"
       value="  TEBAK SCORE  "
       class="btn default"/>

Can any one help me?
Comment: Store the info ( whether the button is enabled or disabled ) in database.
Answer: Webpages are stateless. Do you mean control the state of a button using xmlHttpRequest? The long and short of it is if you add the attribute disabled="disabled" to the input tag, the button is disabled. However you need to have server-side scripting because disabling the button only prevents someone from submitting a form (or toggling a button) through a browser interface. Someone could still use CURL for instance, to programmatically submit a post to the url that processes your form submittal.
You can also control button enablement and disablement using JavaScript.
Comment: can u give me a sample ?
Answer: Use a flag in SQL. If Flag true then don't print a href-"" in the button an set the CSS to grey
ELSE
Load the button like usual
Answer: Maybe something like this will help? (NOT TESTED)
session_start();

$_SESSION["button_status"] = "disable";

if ($_SESSION["button_status"] = "disable"){
?>
<button type="button" disabled>Click Me!</button>
<?php
}else{
?>
<button type="button">Click Me!</button>
<?php
}

Reference sites:
https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_button_disabled
https://www.w3schools.com/php/php_sessions.asp
Comment: It was 'not tested', it was just a demo/example to give you a direction that you may be able to use, may also need to set this up on both pages, and I also suspect you may need to sort the sessions out in your php.ini or test that it actually is working. Do a phpinfo(); on your web server.


Minimum number of questions in a multiple choice assignment

Question: Consider a class of $N$ students. I give them an assignment containing $M$ multiple choice questions ($M>0$). Each question is either right or wrong. The students give me back the scripts with their answers. Thus, for each student, I have one script containing $M$ questions and answers.
I decide to mark them using the following method:

I shuffle the students' scripts randomly. This way I have a pile of unmarked scripts in a random order.
I mark the first question for the first student. I put it in a second pile. This is the pile of "marked" scripts (with regards to the first question, as the other questions have not been marked yet).
I mark the first question for the second student. The position of this script in the "marked" pile depends on the answer of this second student and the answer of the student whose script is at the top of the "marked" pile (in this case, the first student):

(the "one-position upgrade" case): I put the second student's script immediately below that of the first student if the answer of the previous student was incorrect and the answer of this second student is correct.
(the "keeping the same order" case): I put the second student's script above that of the first student if the answer of this second student is incorrect; or if the answer of both students is correct.

Continue the marking of this first question for the rest of the students. Note that a script can only move up one step per question. However, a script can move down several steps per question. For example, it can reach the bottom if the answer was incorrect, and that of all those students who follow is correct.
Once the first question is marked for all student (so the "unmarked" pile is empty), pick up the "marked" pile and turn it around. Thus, if the first student had the first question correct, s/he is still at the top in the next round of marking.
Repeat 3/4/5 for the second and subsequent questions, until the $M_{th}$ question is marked.
Keeping the final ordering of scripts, grade them, by counting the number of correct answers. Thus, minimum grade is 0, and maximum is $M$.

Question: which is the minimum number of questions ($M_{min}$) that ensures (i.e. with complete certainty) that the final ordering of students follow a monotonic ordering of grades?
UPDATE: as the existing answer indicates, without further assumptions, there is no assurance a minimum number of questions will allow a monotonic grading. This is because one question can be non-informative, in the sense that all students are either correct or wrong, meaning there is no re-sorting of scripts' order.
So, to move further, assume that the probability that all students get the same answer (either right or wrong) in a given question is $p$. For the moment, take this probability to be independent of $N$ (a simplification, for sure).
My intuition:

Naturally, $M_{min}$ will be a function of $N$, with positive partial derivative. I'm not sure about the second partial derivative. It might be constant.
$M_{min}$ might be a concave, non-linear function of $p$. If $p=0$, all questions are informative, so the convergence is faster. However, if $p=1$, students have the same marks, so the initial ordering is by definition monotonic. Thus, if $p=1$, it is clear that $M_{min}=1$.
However, for some $N$, $p$ is irrelevant. For example, it is clear that for $N \leq 2$, $M_{min}=1$, regardless of $p$.
Comment: Can you specify exactly what happens if the marked pile has more than one script already? Where does the new one go exactly?
Answer: If I understood correctly, without additional assumptions, there is no such $M$.
Consider the case when we have a single script with the highest grade, for which last answer is incorrect. And consider any number of questions $M$.
During last iteration this script will be put above the first in this iteration, thus after reverting the pile it will not be on top, so the ordering is incorrect, for any $M$.
EDIT: I did not consider another case when in last iteration the best script is already on top, but maybe someone can finish above reasoning for that case.
EDIT2: What if every script has grade $0$ except single one that has grade $1$ with last answer correct? If you start with this best script in the middle of the pile, in the last iteration it will move only 1 step, and won't be on top.
Comment: Well, if $N=2$, $M_{min}=1$. That is a counterexample.
Comment: Actually, it is perhaps possible to prove that such minimum exist. For instance, it seems "logical" that a number of questions equal to $N^{1000}$ would certainly provide a monotonic ordering. So, **if there exists a number of questions which gives** a monotonic ordering, maybe $N^{1000} - 1$ might also do. By some type of induction mechanism that I am not aware of, you can perhaps prove the existence of a minimum.
Comment: @luchonacho Think about scenario in my last edit with $N = 4$ and let the best script be 2nd from the bottom, it will never reach top regardless of $M$.
Comment: Ah, now I understand it. You are right. That is an example where there is no $M$, basically because all the other questions were redundant. So in effect, the "useful" question was just one -- the last one. So, to move forward, I see two options: (i) have a conditional solution, or (ii) consider questions where not everyone is either correct or incorrect (the "useful" questions). Maybe, assuming that in each question, there is at least one correct and incorrect. Something like assuming questions are not easy enough, given the training level of students.
Comment: Updated the question.


Cannot schedule task to run under domain user account other than current user

Question: On our Win 2008 machines I can't schedule tasks for domain users because the domain name does not resolve to network name but the AD dc name.
The "network name" looks like ABCDEFGE-HIJKLM and the "dc" / "name" would look like ABCDEFGE-HIJKLMN.
When selecting the domain user account the account qualifier will look like ABCDEFGE-HIJKLMN\task.user. This results in an "invalid account" error.
Entering the account name as firstname.lastname@example.com yields the same result.
When however keeping the currently logged in user it will display ABCDEFGE-HIJKLM\current.user.
Does this behaviour result from the presumable "illegal" domain name?
Is there a workaround for this?
update
I could of course log in as the desired domain account and create the task but since this account is a account used for running services I want to avoid creating a user profile on the machine.
Answer: Can you use the firstname.lastname@example.com format? (I am assuming that your domain is setup as ABCDEFGE-HIJKLMN.local in DNS.)
Comment: I tried that and it also resolves the account to ABCDEFGE-HIJKLMN\task.user resulting in the same error. Thanks for your suggestion nonetheless.
Answer: This just worked for me:
Select a local account
When clicking "ok" you get a prompt for the password
There you can change the user to the correct user eg. COMPANYNAME\username
source:  http://social.technet.microsoft.com/Forums/en-US/winserverManagement/thread/3d9e45be-0225-46f3-b1b6-504915896605
Comment: Exporting, editing and importing worked perfectly. Thanks a lot for the hint to this workaround.
Comment: I'll upvote as soon as my rep here allows.


Finger Picking Chords - Beats per bar

Question: When one is playing a 4/4 tune "finger picking style"
(Thumb base note, Index 3 string, Middle 2nd string and ring finger 1st string)  (Not coincidentally 4 "actions/picks")
My question is:
Would a bar be the above action ONCE or FOUR times?
Answer: If the time signature is 4/4, there are always 4 beats in every bar. But that doesn't have necessarily anything to do with how many "actions" you perform per bar, i.e. how many times you pick/finger a string or anything.
How many "actions per bar" you do depends on the rhythm pattern and how you realize it, and there are any number of different rhythms and ways to play them.
Here are a few example patterns. The first one is a boogie rhythm with a fast tempo, 200 beats per minute, and the guitar comping rhythm pattern has two rhythmic "actions" per every beat. In other words, it's a 1/8th note pulse, with swing. On every beat, there's a bass note, and the rest of the chord notes are fingered in between every beat. It's a fun little rhythm.

The next one is some kind of a ballad, with a very different feel between the bass notes and the higher notes. Again, the pulse is 1/8th notes with swing, but the tempo is much slower, 90 beats per minute.

The third one has the slowest beats-per-minute tempo, 80 bpm, but the guitar comping pulse is 1/16th notes (with swing). Even though there are fewer beats, there's more actions to do for the guitarist.

(Oops. All of them are missing a time signature marking. Oh well.)
Answer: It could be. And it could be doubled to play twice in a bar, the second time with a 5th of the chord instead of the 'base' note. It depends on what the song sounds better with, and how you want to play it anyway. It could be played as thumb on beat 1, 3 fingers simultaneously on beat 2, then repeated for the 2nd half of the bar. Don't get too hung up on 'correct fingering', as mentioned in my previous answer.
Answer: It's up to you!
If you're playing some song fingerpicking style, then you're the one making up the fingerpicked part anyway. Therefore, you can do it as fast or as slow as you want. You could play the whole thing twice per bar, once per bar, four times per bar, et cetera. If you're the one making up your part, why worry about how it's "supposed" to be played?
Answer: What you are describing is one of many fingering patterns. Numbering the fingers t,i,m,r like 1,2,3,4 your pattern will be 1,3,2,4. You can construct other patterns like 1,2,3,4 or 1,4,3,2 or any other sequence or combination.
Now your question:how many times this pattern can be played in a 4/4 bar?
This depends of the speed you want to play the pattern: 4/4  can be divided in 8/8 or even 16/16 (and even shorter units). When you play crotchets you play the  pattern once, 8th notes twice (as 8=2x4) 1 etc.

Finger Picking Chords - Beats per bar


How to test the relationship between variance of functional trait value (dependent variable) and elevation range of occurrence?

Question: I have a data set consisting of functional trait values for trees across an elevation gradient. Hence each functional trait value (dependent variable) has a corresponding elevation value (independent variable). How do I test if the variability in functional trait values corresponds to the elevation range?
Comment: What is your question?
Comment: Question - Does the variation in functional trait value correspond to range of occurence. I need a test for this questions specifically, or a test where I can at least infer this.
Comment: How many traits? Are they yes/no for each tree? A mixed species forest might have more conifers per acre at higher altitude but a probability of a tree disease, or tree height might vary within each tree species and altitude. So, if you show what your data looks like, maybe someone figure out exactly what information can be extracted from it.
Comment: Hi I have collected data on intra -speciifc trait variation. There are a total of three traits and 5 species for which I have collected functional trait data for individuals of the 5 species across a 1600 m elevation gradient.
Comment: You might then need to refine your question: (1) is it about variance across species, within species, across all individuals at a particular elevation (which would depend on the relative abundance of different species)? (2) are you interested in treating the traits as independent or modelling their covariance? The answer I provided below addresses only the simplest possibility of these.
Answer: This can be answered in a regression framework: regress variance in traits against elevation. If the relationship is nonlinear, you might want to try a GAM instead of a simple linear regression.
I suggest you do some reading on the topic before proceeding, though. It's impossible for us to foresee all the complications you may encounter in this analysis and a good grasp of the basics will help you.
Comment: Hi, thank you for the response. I have only 5 species and therefore only 5 datapoints for which I have values of total within species variance (I'm taking coefficient of variance as a measure) associated with an elevation range. Due to this low sample size, I don't think I will be able to regress variance of a trait with elevation range. Anything else that I can do?
Comment: @AshishNambiar Could you elaborate on your data in the question? 5 species, how many elevations, how many individuals per elevation per species? And again, what precisely is your question?


Prove that if $a_k \in [0, 1] $ then $\frac {1}{1+a_1} + \frac {1}{1+a_2} + \cdots +\frac {1}{1+a_n} \le \frac{n}{1+ \sqrt[n]{a_1a_2\cdots a_n}}$.

Question: One of my friends gave me this problem:

If $a_k \in [0, 1]$, Prove that:
  $$\frac {1}{1+a_1} + \frac {1}{1+a_2} + \cdots +\frac {1}{1+a_n} \le \frac{n}{1+ \sqrt[n]{a_1a_2\cdots a_n}}$$

I have been trying this all day trying to apply things from AM-GM to Cauchy to Chebyshev to Convex functions. Nothing worked.
Can anyone give a solution or help. Much thanks.
Comment: Essentially a duplicate of [Prove that $\frac{1}{1+x_1}+\frac{1}{1+x_2}+\cdots+\frac{1}{1+x_n} \geq \frac{n}{\sqrt[n]{x_1x_2\cdots x_n}+1}$](https://math.stackexchange.com/q/1600051/42969) – via the substitution $x_i = 1/a_i$
Comment: You shouldn't feel bad for not solving it. Most because it's false. $n=2, a_1 = 1, a_2 = 0$.
Comment: Im sorry I made a mistake but the RHS is less than. I edited the question. Sorry.
Answer: Suppose $a_i = e^{\lambda_{i}}$ for all $i$. Define $f$ : $x \mapsto \frac{1}{1+e^x}$. $f$ is concave on $]-\infty, 0]$, so $\frac{1}{1+e^{\frac{1}{n}\sum_{i=1}^n \lambda_i}} \geq \frac{1}{n}\sum_{i=1}^{n}\frac{1}{1+e^{\lambda_{i}}}$, which allows us to conclude.


Ignore bracket in csv file python

Question: I wrote a python script for a friend that:

takes a CSV of photos she's been cataloging that has the name of the photos in an ordered list
finds the image files on the filesystem
matches the files in the csv with files on the system
copies the images on the filesystem to a folder with a figure name in the order the files appear in the CSV

So essentially, it does:

INPUT: myphoto1.tiff, mypainting.jpeg, myphoto9.jpg, orderedlist.csv
OUTPUT: fig001.jpg, fig002.tiff, fig003.jpeg

This code is going to run on a mac. This works fine except we ran into an issue where some of the files (all by the same photographer) have 1 bracket in them, e.g.
myphoto[fromitaly.jpg

This seems to break my regular expression search:
The relevant code:
orderedpaths = [path for item in target for path in filenames if re.search(item, path)]

Where filenames is a list of the photo files on the system and target is the list from the CSV. This code is supposed to match the CSV file name (and it's subsequent order in the list) to the filename to give an ordered list of the filenames on the system.
The error:
Traceback (most recent call last):
  File "renameimages.py", line 43, in <module>
    orderedpaths = [path for item in target for path in filenames if re.search(item, path)]
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 142, in search
    return _compile(pattern, flags).search(string)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 244, in _compile
    raise error, v # invalid expression
sre_constants.error: unexpected end of regular expression

I tried or considered:

Changing the filenames/csv, but this isn't scalable and ideally her
department will be using this script more in the future
Investigating treating the files as "raw" -- but it didn't seem like
that was possible for input from CSV
Deleting the [ character from the input, but the problem is that
then the input won't match the actual files on the system.

I suppose I should mention I only suspect this was the issue: by printing out the progress of the code, it appears as if the code gets to the CSV item with the bracket and errors.
Comment: @drewk this is an error of mixing code and data, basically.
Comment: Try replacing all instances of `[` with `\[`.
Comment: consider doing `item.replace('[', '\[')`
Comment: @karthikr this will probably fix this specific problem, but not the general one.
Comment: Your problem is that you do not escape the regex meta characters. Why are you using regex for this anyway? What's in `target` exactly? Can we see some example `item`s. Is it just `myphoto[fromitaly.jpg`?
Comment: In order for you to see this traceback, the file name `myphoto[fromitaly.jpg` or another unbalance brace would need to be part of `item`. It is during the compilation of the pattern you are getting the exception. This is probably an error in your code.
Answer: The relevant code is the part where you buld a regular expression using a user input, without sanitizing it. You should not do that.
I believe you don't need to use RE at all. you can find matching string using if item in path or path.endswith(item) or something like that.
The best option is to use your library:
from os.path import basename
orderedpaths = [ ... if basename(path) == item]

If you insist on using REs, you should escape your input using re.escape():
orderedpaths = [path for item in target for path in filenames
                 if re.search(re.escape(item), path)]

Comment: +1, but: Why are you using `ntpath` instead of `os.path`? Especially on a Mac? Also, is the `path[:-3]` bit meant to remove extensions? If so, you'd want `path[:-4]`—but you don't want that, either, because it will fail on any extension that isn't 3 letter long (like half the OP's actual examples).
Comment: Thanks! Your latter suggestion did the trick:

orderedpaths = [path for item in target for path in filenames
                 if re.search(re.escape(item), path)]
Comment: @dantiston, it is the last thing I would do... please try using other ways, at least for production code.
Comment: Also: I tried your first suggestion (with os.path.basename), and it didn't catch as many as the regular expression. However, I did some more testing with the escaped RE and it seems to work well.
Comment: @abarnert - I saw in another question here that it's more portable, but if you are commenting, I assume I understood wrong. About the rest - you are right. (I didn't really recommend that - it was only an example).
Comment: @Elazar: It's not really about "portable". `os.path` handles native paths for your platform, so it's appropriate for when you're dealing with paths on the local machine (i.e., most use cases). `ntpath` handles Windows-style paths (with backslashes and drive letters) no matter what platform you're on, so it's appropriate if you're dealing with pathnames from a Windows machine (e.g., writing a log parser that has to run anywhere, but handles logs from a Windows server).
Comment: @Elazar: By the way, the safe way to remove extensions is `os.path.splitext(path)[0]` (or `ntpath.splitext` or `posixpath.splitext`, as appropriate).
Comment: @abarnert I understood all that. *After* I saw your comment. and you are welcome to improve my answer (or post a different one with corrections).
Comment: @Elazar: Nah, it's fine now. Your answer isn't at all confusing as it stands, and anyone who manages to get confused anyway should manage to figure things out from your comments and mine.

Ignore bracket in csv file python


Evaluation Functional Not Continuous in $L^p$

Question: The evaluation functional is defined as: $$A_t(f)=f(t)$$where $A_t : C[a,b] \to \Bbb R$ and $t\in\Bbb R$. One of the other exercises was to show that the same functional is continuous if the space of continuous functions on $[a,b]$ is equipped with the supremum norm, and that proof is clear to me. It is already stated that this does not hold when the same space has the $L^p$ norm. How does one show this?
Answer: It's because there are integrable functions that are still very spiky. Formally, the linear functional $A_t$ is bounded if
$$\sup_{\|f\| = 1} \|A_t(f)\| < \infty$$
where the norms are taken in appropriate spaces. In this case, this is the statement
$$\sup_{\|f\|_p = 1} |f(t)|$$
But if $p < \infty$, a small $L^p$ norm on a function doesn't imply a small bound on the function. I'll let you work out how to come up with counterexamples (think about, say, triangles).


Ploneboard conflict with AccessControl?

Question: i'm trying to install the latest Ploneboard (v3.6) on a Plone 4.2 site, but getting the error
The version, 2.13.11, is not consistent with the requirement, AccessControl>=3.0
i see that the most recent Ploneboard change log for this version mentions "Fixed dependency for AccessControl. Plone < 4.3 have an old version pinned [cekk]"
anyone see what is wrong in this picture?  thanks for any clues.
Comment: i guess i should also say that while i understand what 'pinning' versions means, i don't find any specification of any contraints on AccessControl any where in `buildout.cfg`, `versions.cfg`, etc?
Answer: Since version 3.6 PloneBoard requires AccessControl>=3.0.
The Problem in your case is, that Plone 4.2.x has an older version pinned:
Check: http://dist.plone.org/release/4.2-latest/
If you run ./bin/buildout annotate | grep -C 5 AccessControl.
You will see which buildout configuration pins the version of AccessControl.
...
[versions]
AccessControl= 2.13.13
    http://dist.plone.org/release/4.2-latest/versions.cfg
...

In your case you need to override this version pinning in your buildout.cfg (or versions.cfg).
[versions]
AccessControl = 3.0.8  # For example

I don't know which version of AccessControl works with Plone 4.2.x.
But 3.0.x seems suitable.
Comment: I can confirm, we are using AccessControl 3.0.8 in production on a Plone 4.2.4 site due to PloneBoard recent requirements.
Comment: @keul Thanks for confirmation!
Comment: pinning AccessControl = 3.0.8 works, thanks Mathias!  (and also thanks for the `annotate` argument to buildout; teach a person to fish...)   any clue why the Ploneboard changelog mentions this as fixed in v3.6?
Comment: No, probably they had security issues with AccessControl 2.13.x. Ask the contributor iteself (cekk - you can find him on github).

Ploneboard conflict with AccessControl?


Exogeneous regressors in auto.arima and using them in forecast function in R

Question: I'm trying to forecast a seasonal time series based on its historical values, and also two more time series (that are seasonal themselves.)
I'm trying to use an auto.arima, and I'm going to input the other two time series (the exogeneous regressors) as a contatenated list of dummy variables, in auto.arima's xreg parameter.
I am having difficulty how to use the forecast function after this point.  I've written up the following code, but I don't understand what I should put in the xreg and newxreg parameters of the forecast function.
tempfit<-auto.arima(dnew, xreg=dExt)
plot(forecast(tempfit, xreg=dnew1,newxreg=dExt1))

Also, my data points for these three series were all values per day that had a seven day seasonality. In order to let auto.arima calculate the (p,q,d) for seasonality, I converted them to time series with a frequency of 7. Now, after forecasting is done, the plot shows one unit for every seven days.  How can I covert this back to one unit per day?
Further, do you happen to know how we can input a set of external regressors to an ETS model?
EDIT:
I just saw the following page from Dr. Hyndman:
Time series modeling with dynamic regressors in SAS vs R
Is it safe to assume that I don't need to enter a newxreg parameter for my forecast?
Also, I want to know if it's statistically correct to use the two external regressors in xreg, but then also use a number of dummy variables in xreg that will represent the seasonality of these two variables.
Answer: If you fit an arima model with external regressions, you MUST provide newxreg to the predictions function.  This goes for arima, auto.arima, and Arima.  You cannot provide external regressors to ets.
xreg should contain the exogenous variables for the training set, and newxreg should contain those variables for the prediction set.  If the nexreg contains variables you do not know the future values of, you will either need to forecast these variables or exclude them from the model.
Comment: It can be helpful to define newxreg, just to differentiate between training (xreg) and testing (newxreg).  Then when using the forecast function, set xreg=newxreg.
Comment: Thank you!  I'm aware of newxreg in predict function, but I'm curious to know whether in forecast function this newxreg has been renamed to just xreg (using newxreg I get an error)
Comment: @user2370334 Good catch.  The argument is `xreg`.  Type `?forecast.Arima` for more info.


Retorno do pagseguro parou de ser recebido repentinamente

Question: Estou com um problema em um site que fiz a pouco tempo, nos primeiros dias, quando um cliente realizava um pagamento no PagSeguro eu recebia o retorno normalmente com as atualizações do status da compra, porém, cerca de duas semanas atrás parei de receber esse retorno repentinamente. Revirei meu código diversas vezes atrás de um possível erro, pesquisei de varias formas no Google, cheguei até mesmo a desabilitar o mod_security no servidor como alguns sites sugeriram e nada...
Código do arquivo de retorno
header('Access-Control-Allow-Origin: *');
require('../../PagSeguroLibrary/PagSeguroLibrary.php');

/* Tipo de notificação recebida */
$type = $_REQUEST['notificationType'];
LogPagSeguro::info("Uma Notificação do tipo '{$type}' chegou!");
/*
* Código da notificação recebida
* https://pagseguro.uol.com.br/v2/guia-de-integracao/api-de-notificacoes.html
*/
$code = $_REQUEST['notificationCode'];
/* Verificando tipo de notificação recebida */
if ($type == 'transaction') {
LogPagSeguro::info('Nova notificação retornada do PagSeguro');
$credencial = PagSeguroConfig::getAccountCredentials();
/* Obtendo o objeto PagSeguroTransaction a partir do código de notificação */
$transaction = PagSeguroNotificationService::checkTransaction(
    $credencial,
    $code
);
/* código do status da transação */
$status = (int) $transaction->getStatus()->getValue();
$requestId = (int) $transaction->getReference();
$statusNome = $transaction->getStatus()->getTypeFromValue();

if($status && $requestId){
    /*atualiza o status da compra

      Código adicional

      grava no log do pagseguro
    */
    if($qrUpdateInfo->affected_rows == 1) LogPagSeguro::info('Pedido "'.$requestId.'" atualizado com sucesso!');
    else LogPagSeguro::warning("Ocorreu um erro na atualização do status do pedido         '{$requestId}'! mysqli_errno({$qrUpdateInfo->errno})");
}
}else{
    LogPagSeguro::warning("Uma Notificação do tipo '{$type}' foi recusada!");
}

Estou usando $_REQUEST pois estranhamente ele não recebia os $_POSTs do PagSeguro.
Até aí nenhum mistério, acredito eu.
Porém no momento que faço a compra, ele me manda o retorno daquela compra e grava no arquivo de log normalmente, mas as atualizações do status da compra não estão chegando mais...
Log:
{2014/05/19 13:41:32} [Info] PagSeguroPaymentService.Register(PagSeguroPaymentRequest: array (
  'Reference' => 79,
  'SenderEmail' => 'null',
)) - begin
{2014/05/19 13:41:33} [Info] PagSeguroPaymentService.Register(PagSeguroPaymentRequest: array (
  'Reference' => 79,
  'SenderEmail' => 'null',
)) - end {1}13DC46D97171BB4444F60F81E8A4A98C
{2014/05/19 13:56:36} [Info] PagSeguroPaymentService.Register(PagSeguroPaymentRequest: array (
  'Reference' => 80,
  'SenderEmail' => 'null',
)) - begin
{2014/05/19 13:56:38} [Info] PagSeguroPaymentService.Register(PagSeguroPaymentRequest: array (
  'Reference' => 80,
  'SenderEmail' => 'null',
)) - end {1}E0E95A81EAEA5B2AA4C66F9C8806485E
{2014/05/19 14:28:02} [Info] PagSeguroPaymentService.Register(PagSeguroPaymentRequest: array (
  'Reference' => 84,
  'SenderEmail' => 'null',
)) - begin
{2014/05/19 14:28:04} [Info] PagSeguroPaymentService.Register(PagSeguroPaymentRequest: array (
  'Reference' => 84,
  'SenderEmail' => 'null',
)) - end {1}A864EE379C9C8FFCC4A48FBACABECBC3
{2014/05/19 14:30:57} [Info] PagSeguroPaymentService.Register(PagSeguroPaymentRequest: array (
  'Reference' => 85,
  'SenderEmail' => 'null',
)) - begin
{2014/05/19 14:30:59} [Info] PagSeguroPaymentService.Register(PagSeguroPaymentRequest: array (
  'Reference' => 85,
  'SenderEmail' => 'null',
)) - end {1}53AD3EF23F3F89A884559FBFBD464A36
{2014/05/19 14:56:27} [Info] PagSeguroPaymentService.Register(PagSeguroPaymentRequest: array (
  'Reference' => 86,
  'SenderEmail' => 'null',
)) - begin
{2014/05/19 14:56:28} [Info] PagSeguroPaymentService.Register(PagSeguroPaymentRequest: array (
  'Reference' => 86,
  'SenderEmail' => 'null',
)) - end {1}ABC65A77767683A774117FA5386D3C90
{2014/05/19 14:59:10} [Info] PagSeguroPaymentService.Register(PagSeguroPaymentRequest: array (
  'Reference' => 87,
  'SenderEmail' => 'null',
)) - begin
{2014/05/19 14:59:11} [Info] PagSeguroPaymentService.Register(PagSeguroPaymentRequest: array (
  'Reference' => 87,
  'SenderEmail' => 'null',
)) - end {1}27E7C9EE7F7F95E334BFDF9131FBDA3E
{2014/05/19 15:16:17} [Info] PagSeguroPaymentService.Register(PagSeguroPaymentRequest: array (
  'Reference' => 88,
  'SenderEmail' => 'null',
)) - begin
{2014/05/19 15:16:19} [Info] PagSeguroPaymentService.Register(PagSeguroPaymentRequest: array (
  'Reference' => 88,
  'SenderEmail' => 'null',
)) - end {1}D4E7C61FADAD6FF99403AFB16E1D0930

Outra dúvida, o firewall do servidor poderia estar bloqueando o retorno do PagSeguro?
Eu sinceramente já perdi as esperanças com o PagSeguro, mas já que não posso migrar esse cliente para o Moip tenho que dar um jeito de resolver.
Answer: Não analisei seu código, mas como não tinha respostas vou dar 2 caminhos que irá ajuda-lo a quem sabe solucionar;
1º - verifique se no pagseguro, na conta que esta utilizando para pagar, não desabilitou a página de retorno, se desabilitou por algum engano, ele não vai enviar nada para você.
2º - Faz um teste, essa página que recebe o retorno, faz ela criar um arquivo .txt caso ela seja acessada, faz uma compra de teste, e verifique se ela criou o arquivo. se ela não criar o arquivo por algum motivo ela não esta sendo executada.
Comment: ja verifiquei o retorno e está ativo, vou fazer o segundo teste agora
Comment: testei da segunda maneira e o arquivo nao foi acessado pelo pagseguro
Answer: Achei o problema, e mais algumas recomendações...

1 - Não basta setar no pagseguro a url de retorno, no momento que você manda para o pagseguro a compra você deve setar a url de retorno tambem

$pagSeguro->setNotificationURL('http://seudominio/arquivoderetorno');

2 - Libere os ips no seu firewall
126.96.36.199
126.96.36.199
184.108.40.206
188.8.131.52
18.104.22.168
18.104.22.168

3 - Desabilite seu mod_security

Fontes:
IMasters
Blog pag seguro
Comment: @Dorathoto mas é isso que aconteceu, eu recebia o retorno mesmo sem ter setado o retorno junto ao envio, até por que não fazia ideia de que isso era necessário, por isso foi tão difícil de arrumar dessa vez...
Comment: mas pelo que tinha entendido, seu código funcionava e derrepente parou. se vc não setou o retorno então ele nunca funcionou...bom o mais importante é ter corrigido. abraços


power play in T20 cricket

Question: In a T20 match, if a fielding side has only 10players(no substitutes also),then how many players can field outside the 30yrds in the first six overs.
Answer: The T20 international regulations are quite clear about this:
Section 41.2.2.c says that "During the Powerplay overs only two fieldsmen shall be permitted outside this fielding restriction area at the instant of delivery. "
Section 41.2.2.d says that "During the non Powerplay overs, no more than 5 fieldsmen shall be permitted outside the fielding restriction area referred to in clause 41.2.2 (b) above."
Comment: As an umpire tutor one of the things we stress to people around fielding regulations is that they always so no more than or no less than, and so regardless of the number of players in the team they apply

power play in T20 cricket


Is it possible to underline text without HTML syntax in Quarto?

Question: I was wondering if it is possible to underline text without HTML syntax in Quarto? You can strikethrough the text using ~~ syntax like this:
~~mytext~~

Output:

So I was wondering if it is possible to underline your text with somehow similar syntax like above?
Comment: Honestly, All I do using the search engine `google` and thanks to the quarto Devs, they have documented everything very nicely. Really.
Comment: @shafee, My bad! I mean underline of course ;)
Comment: Actually, the question is whether markdown supports it.
Comment: Master @shafee, you are right. Do you know if there is maybe a fancy CSS option instead of HTML?
Comment: Again, I am really baffled why are you calling me master? : )
Comment: @shafee, Because you know a lot about Quarto and Rmarkdown, that's why!
Answer: If you want just to use css, you may try the following,
---
format: html
---

## Quarto

[This text is underlined]{style="text-decoration: underline;"}

But the above approach will only work for html output format. If you want to get underlined text for html, pdf or docx output, try the following syntax, (which is handled by the pandoc itself)
---
format: html # pdf or docx
---

## Quarto

[This text is underlined]{.underline}

Comment: @Quinten, see the updated answer, which is I think a better approach.


turning urls into subdomains?

Question: i have this url
http://www.example.com/user.php?user=solomon
i want to convert this into
http://solomon.example.com
how can i do this!! thanks :))
p.s. im using plesk
Answer: I'm not familiar with Plesk's capabilities, but on a LAMP server, you need to use Apache's mod_rewrite module and have a wildcard DNS setup for *.example.com through your DNS provider (either your registrar or your hosting provider).
Your .htaccess for your virtual host will look like this:
  Options +FollowSymLinks
  RewriteEngine On
  RewriteBase /
  RewriteCond %{HTTP_HOST} !www.example.com$ [NC]
  RewriteCond %{HTTP_HOST} ^(www.)?([a-z0-9-]+).example.com [NC]
  RewriteRule (.*) user.php?user=%2 [NC,QSA]

Comment: Setting up a wildcard DNS for example.com (*.example.com) has to be done by whomever controls your DNS records.  i.e. in your WHOIS record for example.com, the nameserver records point to the DNS server(s) that control your DNS zone; this is likely the same place where you registered your domain (GoDaddy.com, networksolutions.com, etc.).
Comment: thanks,i have root access, how can i set a wildcard DNS thanks :))

turning urls into subdomains?


How to render a node field

Question: I can get the field using entity_metadata_wrapper like this
$node = node_load($nid);
$node_wrapper = entity_metadata_wrapper('node', $node, array(
    'langcode' => $GLOBALS['language'],
    'bundle' => 'unit'
     )
);

$field_value = $node_wrapper->field_photo->value();

And that returns an array which I don't know how to render. I tried drupal_render() but it seems that it doesn't do the job.
So how can I render this field ?
Comment: possible duplicate of [Question regarding rendering fields in node.tpl.php](http://drupal.stackexchange.com/questions/74200/question-regarding-rendering-fields-in-node-tpl-php)
Comment: I tried that solution and it works, but what if I want to render the field returned by entity_metadata_wrapper()
Answer: The photo field is an image field? The value() function returns an array which is actual file data linked to the image. To render (or to create a renderable build), you can for example use theme_image function, which prints out an  tag.
$node = node_load(43);
$node_wrapper = entity_metadata_wrapper('node', $node, array(
    'langcode' => $GLOBALS['language'],
    'bundle' => 'subject'
));

$field_value = $node_wrapper->field_teaser_image->value();
$build = array(
    '#theme' => 'image',
    '#path' => $field_value['uri'],
    '#alt' => $field_value['alt'],
    '#title' => $field_value['title'],
    '#width' => $field_value['width'],
    '#height' => $field_value['height'],
);

print drupal_render($build);

Comment: That works only for image fields. but I have other fields I want to render I just used that one as an example
Comment: This shows a huge shortcoming of metadata_wrappers in my opinion. I would hope that we could just do `$node_wrapper->field_teaser_image->render();`
Comment: Depending the type of field, the method for rendering is different ... (plain values, arrays, ...). Why don't you use `field_get_items` and `field_view_value` for the rendering?
Comment: I will only need this photo field for now after all, so I'll mark this as the accepted answer.

How to render a node field


SwiftUI Binding Edits Wrong TextField after Item Reordered

Question: Xcode 13 beta 5, iOS 14, macOS 11.6
I have a parent SwiftUI view that lists some children. Each child is bound to an NSViewRepresentable. Everything works and I can edit the values as expected. But once I reorder the items in the list and edit a field, it edits the wrong field. It appears that the binding remains intact from the previous item order.
Here's what that looks like:

Here's the parent:
struct ParentView: View {
  @StateObject var model = ThingModel.shared

  var body: some View {
    VStack{
      ForEach($model.things){ $thing in
        ChildView(thing: $thing)
        //Reorder
        .onDrag{
          model.draggedThing = thing
          return NSItemProvider(object: NSString())
        }
      }
      Text("Value: \(model.value)").font(.title)
    }
    .frame(width:300, height: 200)
  }
}

...and here's the child view:
struct ChildView: View {
  @Binding var thing: Thing
  @StateObject var model = ThingModel.shared

  var body: some View{
    HStack{
      GrowingField(text: $thing.text, submit: {
        model.value = thing.text
        print(thing.text)
      })
      Text(" = ")
        .opacity(0.4)
    }
    .padding(10)
    .onDrop(of: [UTType.text], delegate: ThingReorderDelegate(hoveredThing: thing))
  }
}

Last of all, here is the NSViewRepresentable which is called GrowingField. For simplicity, I have omitted the NSTextField subclass.
struct GrowingField: NSViewRepresentable{
  @Binding var text: String
  var submit:(() -> Void)? //Hit enter

  func makeNSView(context: Context) -> NSTextField {
    let textField = NSTextField()
    textField.delegate = context.coordinator
    textField.stringValue = text

    return textField
  }
  func updateNSView(_ nsView: NSTextField, context: Context) {
    nsView.stringValue = text
    context.coordinator.textBinding = $text
  }

  //Delegates
  func makeCoordinator() -> Coordinator {
    Coordinator(self)
  }

  class Coordinator: NSObject, NSTextFieldDelegate {
    let parent: GrowingField
    var textBinding : Binding<String>?

    init(_ field: GrowingField) {
      self.parent = field
    }

    func controlTextDidChange(_ obj: Notification) {
      guard let textField = obj.object as? NSTextField else { return }
      self.textBinding?.wrappedValue = textField.stringValue
    }

    //Listen for certain keyboard keys
    func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
      switch commandSelector{
        case #selector(NSStandardKeyBindingResponding.insertNewline(_:)):
        //- Enter -
        parent.submit?()
        textView.window?.makeFirstResponder(nil) //Blur cursor
        return true
      default:
        return false
      }
    }

  }
}

Why does the binding to the NSViewRepresentable not follow the field after it is reordered?
Here is a sample project to download and try it out.
Answer: I believe the issue (bug?) is with the ForEach-generated binding.
If you forego the generated binding and create your own, everything seems to work as expected.
Added to the ThingModel:
func bindingForThing(id: String) -> Binding<Thing> {
    .init {
        self.things.first { $0.id == id }!
    } set: { newThing in
        self.things = self.things.map { $0.id == id ? newThing : $0 }
    }
}

And the ParentView:
ForEach(model.things){ thing in
    ChildView(thing: model.bindingForThing(id: thing.id))

Comment: Hmm... interesting! Thank you. I kept looking for an issue with my `NSViewRepresentable` because if I replace my `GrowingField` inside `ChildView` with a regular, stock `TextView()`, then the binding works as it should.


Advanced menu theming in Drupal 7

Question: I've cruised around the web and it is not at all obvious how to theme custom menus.  I've looked for hours and have not found one single post that illustrates the process, from start to finish, of creating a menu and customizing its output.  It seems like this is a multi-stage process:

Create the menu through the Drupal interface.
Create a theme function in your template.php file to theme the output.
Expose this menu to a template file (somehow) by adding it as a variable.
Call the theme function on the menu in the template file.

1 is easy enough to do, the problems I run into are with 2, 3, and 4.  Looking at the default page template, I see that it exposes the main menu in the variable $main_menu.  Later down the page you can see the function theme('links__system_main_menu', array('links' => $main_menu..., which means it's looking for an appropriately named theme function somewhere and using it to generate the output.
I know if I place function theme_links__system_main_menu(&$variables) {...} in my template.php file Drupal will use that function as opposed to function theme_menu_links(&$variables) {...}.
What I don't know is how Drupal links the custom menu I created with that function.  Let's say for example that I created a menu called My Menu.  Could I create the following function in my template.php file and theme the output for that menu? function theme_links__system_my_menu(&$variables) {...}
Also, how does one make that custom menu available to a template file?  How does Drupal expose the $main_menu variable to page.tpl.php?
I think the key I'm missing here is how to embed the variable that represents my custom menu into a template page.  For the most part though I'm completely lost with what to do after having created the menu.
Thanks for the help.
EDIT: Probably should post what I'm doing.  Per my comment to BetaRide below, I need to inject customized HTML into the
 elements of the menu items. Specifically, I'm adding Twitter Bootstrap icons.
Answer: Drupal's implementation of menus is a bit special, It doesn't always work the way it seems it should.
You can take a look at the core implementation of template_preprocess_page() to how the Main Menu links are added as a variable to the page template. You have to drill down a bit in the API docs, but the function you want to call in your implementation of theme_preprocess_page() is menu_navigation_links(), which will return an array of links in the menu.
Looking at line 106 of Drupal core's page.tpl.php file, you can see how the main menu links are themed in the template by calling the theme() function with a hook of 'links__system_main_menu'.
Theoretically, this implementation should be able to be duplicated with a custom menu by following the standard naming conventions. So, in template.php, you could have:
function THEMENAME_preprocess_page(&$variables){
  $variables['custom_menu'] = menu_navigation_links('menu-custom-menu');
}

function THEMENAME_links__menu_custom_menu(&$variables){
 //custom theme function here
}

and in page.tpl.php, you would add something like this:
<?php print theme('links__menu_custom_menu', array('links' => $custom_menu, 'attributes' => array('id' => 'custom-menu', 'class' => array('links', 'inline', 'clearfix')), 'heading' => t('Custom menu'))); ?>

However, adding the custom menu as a variable on your page template is not necessary. You could easily place the custom menu's block into a desired region via the Drupal admin interface.  Also, you could change the site's settings for the Main Menu source, effectively replacing the default $main_menu variable in page.tpl.php with your custom menu.
EDIT: I am just seeing your addition about your end goal being to just add some custom html to the menu items for icons. Depending on how you are adding these icons, there are a couple different Drupal module options.
Menu Icons - allows you to upload an image via the Menu item's settings and automatically generates CSS (customizable via a template) that adds the image as a background on the menu item.
Menu Attributes - allows you to add a custom class to each menu item via its settings in the admin. Once a unique class is added to each menu item, you could use CSS to add an icon to the menu item or use javascript to inject the additional HTML into the menu item.
Comment: It worked, but I took everyone's unanimous opinion to heart and I didn't use this method.  I used the Menu Attributes module that you suggested and assigned unique IDs to the specific menu items, and then used jQuery to inject the HTML directly where I needed it to be.  Thanks for the tips. +1
Comment: This seems to answer all of my questions perfectly.  This is a great answer.  I'll try this out immediately.
Comment: "You could easily place the custom menu's block into a desired region via the Drupal admin interface" ++ . I find this solution to be way simpler.
Answer: You may want to look into the Nice Menus module. Here is a quote about it (from the module's project page):

... enables drop-down/right/left expandable menus. It uses only CSS for most browsers, with minimal Javascript for IE6. (Version 2 uses the Superfish jQuery plugin for all browsers, with an option to disable JS, and falls back to CSS-only for browsers that can handle it.)
Three styles/types of menus are currently possible: horizontal, menus drop down; vertical, menus fly to the left; vertical, menus fly to the right. There is a handbook page that provides a list of sites that use Nice menus.
Nice Menus creates blocks that may be associated with any existing site menu which can be placed wherever normal blocks can be placed in a theme. For themers, it is also possible to theme a menu as a Nice Menu directly by using the provided theme functions so a block is not necessary. A specific theme function for the Primary Links menu is available. The theme functions also allow a developer to pass in a custom menu tree of their making (i.e. not using a Drupal menu.) There is more information on how to use theme functions in the documentation.
The module comes with a simple, generic color scheme which can be fully overridden either by adding the override CSS to the theme's normal stylesheet or by creating a Nice Menus CSS file and telling Nice Menus to use that rather than its own default one through the global theme configuration. Several CSS override examples are provided in the included README.txt file and in the handbook.
Comment: I didn't vote it down, but I will say that this does not address the heart of the question(s) I asked, which is how to dig into the core of Drupal theming for menu items.  This is why these questions never get answered fully, because there is always some module that someone name drops.  I don't care about modules, I want to do template coding.
Comment: I didn't down vote either, but want to add to what Lester said. When you suggest a module in your answer you should also explain why you are suggesting it and how it can be used to solve the OP's issue. Without those details, your answer can be seen as not very helpful and potentially be down voted. I made that mistake on my first few answers here, too.
Comment: I don't see why somebody voted this answer down. With Nice Menus, you can target an individual menu item since it has its own class. Then you can use a graphic as the background for that individual class. I have done it before on a couple of major projects.
Answer: Depending on what you want to customize, your approach is much to havy. Usually I create the menu through the Drupal interface as you sugested. The I take the theme developer module and Firebug to find out whicht templates, hooks and CSS directives I have to overwrite to tweak it to my needs.
It's worth considering creating a sub theme of the base theme you are using befor you start tweaking. This makes it much easier to update your base theme.
Comment: I need to inject customized HTML into the  elements of the menu items.  Specifically, I'm adding Twitter Bootstrap icons.
Answer: here is a smart code that can access to all menu items for any level 2 or 3 or more
place this code inside your tpl file don't forget to call boostrap js and css last versions :

        <?php

          # get menu with all levels
          menu_tree_all_data('main-menu');
          $menu = menu_build_tree('main-menu');

          # help function for listing submenus for each link
          function sub_menu_links($var){
           $submenu ='
';

              foreach ($var as $sub) {

                $path = str_replace("<front>",'' ,$sub["link"]["link_path"]);

                 if(count($sub["below"]) > 0 ){
                      $submenu .= '
'.$sub["link"]["link_title"].'';
                      $submenu .=  sub_menu_links($sub["below"]);
                      $submenu .= '
';
                  }else{
                      $submenu .= '
'.$sub["link"]["link_title"].'';
                      $submenu .= '
';
                   }

              }
            $submenu .= '
';

            return $submenu;

          }

          # help function for more than 2 levels
          function menu_links($menu){

             $links = '
';
             foreach ($menu as $link) {

              if(count($link["below"]) > 0 ){

                $path = str_replace("<front>",'' ,$link["link"]["link_path"]);

                $links .=  '
';
                $links .= ''.$link["link"]["link_title"].'';
                      /* print "
";
                      var_dump( $link["below"]);
                       print "
";*/
                $links .= sub_menu_links($link["below"]);

                $links .= '
' ;

              }else{
                  $links .= '
';
                  $links .= ''.$link["link"]["link_title"].'';
                  $links .= '
' ;
              }

              }
              $links .= '
';
              return  $links ;
          }

          print menu_links($menu);

           ?>

this code will return the menu for css classes you can use your own i'm using bootstrap with some custom css

this code is after a hard work it can save your time and it's tested on drupal 7.x and works fine for main-menu you can change the menu as you like

Advanced menu theming in Drupal 7


Drupal 8 allow only listed languages

Question: Is there a way on Drupal 8 to remove "Not specified" and "Not applicable" languages from list and to display only listed Languages?
Answer: Go to Manage form display of a content type and click on settings cog on right corner of Language field. There you will see a checkbox Include locked languages such as Not specified and Not applicable uncheck it to remove options like Not specified and Not applicable.

Drupal 8 allow only listed languages


Real Life Optimization Problem

Question: You are given a set $A$ of integers of size $n$ and a common divisor $r$ called the "anchor", which isn't in $A$ and isn't necessarily the greatest common divisor, either. Let $M$ be the least common multiple of all elements in $A$. The cost of $A$ is then defined as $\frac{M}{r} \cdot n$.
For example, if $A = \{25, 30, 50\}$ and $5$ is the anchor, the cost will be $\frac{150}{5} \cdot 3 = 90$.
You want to minimize the cost of $A$. In order to reduce the cost of $A$, you can "spin off" $A$ by creating a set $S$ and moving $k$ elements from $A$ there, which must be divisible by some element $a\in A$ where $a > r$. The element $a$ becomes the anchor of $S$, which cannot be in $S$. The cost of $S$ is then $\frac{M}{a} \cdot k$. $S$ and $A$ after spin-off must be mutually exclusive. The cost of $A$ after spin-off is the sum of the costs of $A$ and all of its spin off sets.
For example, if you spin off $A$ by defining $S$ to be $\{50\}$, $A$ would be left with just $\{25, 30\}$. The cost of $A$ after spin-off would be $\frac{150}{5} \cdot (3 - 1) = 60$ and the cost of $S$ would be $\frac{150}{25} \cdot 1 = 6$. The total cost of $A$ would be $60 + 6 = 66$, which is smaller than $A$ before spin-off.
You can spin off $S$ and in turn spin off its own spin-off sets and so on. You can also add an element to a set to serve as the anchor of its spin-off set.
For example, if $A = \{20, 30, 50\}$ and $5$ is the anchor, the cost will be $\frac{300}{5} \cdot 3 = 180$. However, if you spin $A$ off by adding $10$ and moving the rest, you will have $A = \{10\}$ and $S = \{20, 30, 50\}$. The cost of $A$ after spin-off is $\frac{300}{5} \cdot 1 = 60$ and $S$ is $\frac{300}{10} \cdot 3 = 90$, for a total of $150$.
The goal is to minimize the total cost of $A$ by spinning it off, recursively if necessary.
How do you go about doing this? Is this a non-linear optimization problem?
This is not homework. I'm a programmer and this is actually for my work which I've abstracted. I've taken a few university level math courses like $10$ years ago, but I barely remember high-school math now...
Thank you in advance.
Comment: There are some things which are not clear. In your second example, you are adding the element 10 and then spinning off the set S. Are there any conditions or constraints on this operation? In your first example you don't add any elements and that might make a big difference. Also, how is the anchor value selected for the spin-off subsets? Can you explain how the set S has an anchor of 25 in example 1 and 10 in case 2?
Comment: The only constraint to adding an element is that it must be a common divisor of the spin-off set. You're right that I could've added an element in the first example, but I didn't just to show how to calculate the cost of A without spinning off. An anchor should be selected to reduce the total cost of A. The larger, the better normally. I chose 25 as the anchor of the spin-off set in the first example because it happens to lead to the optimal cost of A. The same with the second example. 10 would give you the optimal total cost of A. Thanks.
Comment: "The question is widely applicable to a large audience."?!
Comment: You seem to define many operations... your notion of "spinning" is very vague ; it seems there are many ways to do it. Is there any way you can make things more clear or perhaps tell us where does your intuition come from to define such operations on those sets? The choice of word "spinning" seems vague, also.
Comment: I'm confused by just the first sentence. "a common divisor r called the "anchor", which isn't in A and isn't necessarily the greatest common divisor, either." Are you trying to define a *function*, namely: $f(r)=\frac{Mn}{r}$ where $r$ has to be a divisor which isn't in set A and can be, but is not restricted to being, the common greatest common divisor? If you wish to minimize $f(r)$ (the cost of $A$), the math begs that you restrict $r$ to being the greatest common divisor.

I apologize, but this is the most help (if I am helping) that I can give. You lost me entirely in the 2nd paragraph.
Answer: If I understand the question correctly, a solution to the problem will have
the form of a (rooted) tree.  Each vertex of the tree will be labeled with a
set of positive integers, which is either what remains of $A$, at the
root, or a spin-off of $A$, a spin-off of a spin-off of $A$, etc. at vertices
which are not the root.  The sets of positive integers must fulfill the
following constraints:
(1) They are nonempty and disjoint;
(2) All integers in all sets divide the original lcm, $M$;
(3) The union of the sets contains the original set $A$;
(4) For each set, its gcd is divisible by its anchor, which is a member
of the set at its parent vertex (if the set is not at the root) or
a fixed, given, number $r$ not appearing in any set (if the set is at the root.)
Given such a tree, its cost is $M \sum_v (\#S_v)/a_v$, where $v$ ranges over
the vertices of the tree, $S_v$ is the set at vertex $v$, and $a_v$ is the
anchor of the set at vertex $v$.
First, observe that if a vertex is labeled with a set of size larger than 1,
$\{c_1,\ldots,c_t\}$, say, we can split it into $t$ vertices, labeled
with $\{c_1\}$, $\{c_2\}$, $\dots$, $\{c_t\}$, and reapportion its child vertices
among these vertices so that each child set is beneath its anchor.  This does
not change the cost of the tree, so after doing this repeatedly,
we may assume that all sets have size 1, i.e., each
vertex is labeled with a single number.  Second, observe that we may add
a vertex above the root labeled with the original anchor.  These two steps
reduce the problem to the problem of finding a rooted tree whose vertices
are labeled with distinct positive integers which satisfies
(a) All labels divide $M$;
(b) The root is labeled with $r$, the original anchor;
(c) The set of labels contains the original set $A$; and
(d) the label at the top of each edge divides the label at the bottom,
and which has minimum cost,  where the cost is now $M$ times
the sum over all edges of the reciprocal of the label at the top of the edge.
Also, we may now allow $r$ to be a member of $A$, and we observe that there is
no need to require the vertex labels to be distinct, since if we had two
vertices with the same label, we could construct a cheaper tree by deleting one of them and reapportioning all its children to the other.
Let $T$ be an minimum-cost tree for $r$, $M$ and $A$.
Observe that:
(i) Each of the leaves of $T$ must be
labeled with a member of $A$, since otherwise we could construct a
cheaper tree by removing a leaf.
(ii) If a vertex other than the root has exactly 1 child, it must be labeled
with a member of $A$, since otherwise it would be cheaper to remove the vertex
and reapportion its child to its parent.
(iii) If a vertex other than the root has 2 or more children and is not
labeled with a member of $A$, we can assume that its label equals the gcd of the labels of its children, since otherwise we could make a
cheaper tree by relabeling it with the gcd of the labels of its children.
(iv) Fix some parent vertex $v$ of leaves, and let it have label $l$ and leaf children
$w_1$, $\ldots$, $w_t$ with
labels $s_1$, $\ldots$, $s_t$.  Then if we delete $w_1$, $\ldots$, $w_t$ from $T$, the remaining tree, $T'$, must be minimum-cost
for $r$, $M$, and the set $A\cup\{l\}\setminus\{s_1,\ldots,s_t\}$, since if
there was a cheaper tree, $T''$, say, for this set, we could make a tree cheaper
than $T$ for $A$ by attaching the children $w_1$, $\ldots$, $w_t$
to the vertex labeled $l$ in $T''$.
Rules (i)-(iv) give us a recursive algorithm for finding an optimal tree $T$.
If $A$ is empty or $A=\{r\}$, we are done since the optimal tree consists of only the
root vertex and has cost 0.  Otherwise, $T$ must have at least one
leaf, and since, by (i), all leaves are labeled with a member of $A$,
there must be some subset $\emptyset\ne S\subseteq A$ and some vertex $v$
such that $v$ has only leaf children and $S$ contains
the set of labels of the set of leaves, $W$, which are children of $v$.  Then, by (ii) and (iii), the label of $v$, $l$, must be either
$r$, some member of $A$, or $\gcd(S)$. Now,
let $T'$ be $T$ with the vertices in $W$ removed; by (iv), we can
compute $T'$ by calling the algorithm again to find an optimal tree for
$A\cup\{l\}\setminus S$, and then $T$ can be reconstructed by reattaching
the children $W$ to $v$.  Performing this step for all possible choices of $S$ and $l$ will give a set of possibilities for $T$ from
which we can take the best possible answer.
Comment: For your answer to be worth something, the question needs to be made more clear... I can't tell if what you're doing is right or wrong because I can't understand the question. Sorry

Real Life Optimization Problem


Não consigo usar o estilo donut e pie com chartjs!

Question: Então galera estou usando o chartjs num sistema aqui, mas o estilo pie e donut não exibe no sistema. Eu importei os CDN's:

E fiz um arquivo graph.js para colocar os codigos do chatjs e importo ele no meu head:
var ctx = document.getElementById("ChartDonut");
var myDoughnutChart = new Chart(ctx, {
    type: 'doughnut',
    data: {
        labels: ["Pagos","Pendentes"],
        datasets: [{
            data: [200, 137],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)'
            ]
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true
                }
            }]
        }
    }
});

O no meu html eu chamo o CANVAS normalmente:
<canvas id="chartDonut"></canvas>

Mas nem DOUGHNUT e nem PIE funcionam. Alguém sabe o pq?
Comment: Cara, leia bem a documentação do Chart.JS.. você tem o Nugget instalado? ta referenciado no seu projeto? em geral todos os gráficos funcionam de forma igual, precisa de um options e de um data..
Answer: Você possui dois problemas em seu código.
O primeiro é que o id do canvas é chartDonut e no seu script você está usando ChartDonut.
O segundo são seus options. Veja a lista do que você pode utilizar. para esse tipo de gráfico.
Veja abaixo o exemplo do seu código corrigido:

var ctx = document.getElementById("chartDonut");
var myDoughnutChart = new Chart(ctx, {
  type: 'doughnut',
  data: {
    labels: ["Pagos", "Pendentes"],
    datasets: [{
      data: [200, 137],
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(54, 162, 235, 0.2)'
      ]
    }]
  }
});

<canvas id="chartDonut"></canvas>

Dicas de leitura:

Existem vantagens objetivas em uma linguagem ser "case sensitive" ou não?
Documentação Chart.js
Comment: Cara valeu mesmo! não tava conseguindo enxergar isso! @Randrade


Stop header footer from loosing position:fixed with click - Jquery Mobile

Question: I'm using jquery mobile in a Cordova -3 application. A simple page with header and footer having data-position:fixed attribute.

Page 1 header

Page 1

Page 1

Page 1 Footer

It works fine. But when I'm clicking any blank part of body the header footer goes away off the screen. I think it looses data-position:fixed attribute. Again at that time if I click again in any blank place header footer comes back as fixed. Strange behavior. I want the header footer to be fixed no matter where I touch in screen.
You can see the problem in this JSFiddle Click in any part of the body and scroll. You will see it isn't fixed anymore with respect to screen.
Please help......
Comment: possible duplicate of [Disabled button hides header when clicked](http://stackoverflow.com/questions/16401324/disabled-button-hides-header-when-clicked)
Answer: You have to set data-tap-toggle to false like this:

Page 1 Footer


SQL Query work from Oracle SQL Developer but not from code

Question: i have the following SQL query that works fine when i run it from Oracle's SQL developer tool:
SELECT inn.TABLE_NAME, inn.COLUMN_NAME, inn.data_scale, inn.data_length,
inn.CONSTRAINT_TYPE
FROM
(SELECT t.TABLE_NAME,  c.COLUMN_NAME, c.data_scale, c.data_length,
cons.CONSTRAINT_TYPE,
   ROW_NUMBER() OVER(PARTITION BY t.TABLE_NAME, c.COLUMN_NAME ORDER BY
cons.CONSTRAINT_TYPE desc) num
 from user_tables t join user_tab_cols c on c.table_name = t.table_name
left join all_cons_columns cols on cols.TABLE_NAME = t.TABLE_NAME and
cols.COLUMN_NAME = c.COLUMN_NAME
left join all_constraints cons on cons.constraint_name =
cols.constraint_name
WHERE t.tablespace_name = 'name') inn
WHERE inn.num=1
order by inn.TABLE_NAME, inn.COLUMN_NAME asc;

But when I run it in the code I get error:
"ORA-00933: SQL command not properly ended"
Any Idea?
Thanks for advance.
[Edit]
OK, this is my code:
cmd.CommandText = Utilities.renderMethodFunc(command, commandParameters);
using (OracleDataReader dr = cmd.ExecuteReader())
{...}

and you can see in the picture the value of command - it's exactly like what I wrote.
command
Comment: Please edit your question to include the C# code you are using to run this query.  The error is almost certainly in how you are constructing the query in a C# string literal.
Comment: "in the code"? **What** code? You have problem in your code, but you don't post it. The query works OK from SQL Developer, so the error is NOT in the SQL code. And yet that's the ONLY code you show? How do you expect to get help?
Comment: have you noticed the 'quotation marks' around sql, or semicolumn(;) at the end of sql in your code?
Comment: @user2992143: Please edit your question and add your erroneous C# code in it.
Answer: OK, I found it.
The problem was the ';' at the end...


Terraform plan --refresh-only return False Drift with empty tags in deployed resources

Question: While using terraform plan --refresh-only to detect drifted resources, the command returns a plan where 1 or more resources are changed externally. All of them mark the tags attribute with an empty map {}
  # aws_iam_role.lalala_poweruser has changed
  ~ resource "aws_iam_role" "lalala_poweruser" {
        id                    = "lalala_poweruser"
        name                  = "lalala_poweruser"
      + tags                  = {}
        # (11 unchanged attributes hidden)
    }

To make emphasis, the + tags = {} shouldn't be marked with a + symbol as no one changed this property in the deployed infrastructure.
What I've tried so far:

Adding the attribute with an empty map {} to each resource
Adding the attribute with real tags to each resource
Adding the defaults_tags to the provider configuration

The endgame of detecting drift using this command is to programmatically detect any change in a CICD pipeline before deploying new changes. If there is a real drift, we want to know, and we want to stop this deployment. Also, something helpful about this command is when a real drift is detected, it returns the diff so we can log the information and take action.
More info about this process from the Terraform docs:
Manage Resource Drift
Comment: That's been a long-standing bug in Terraform. Lately I updated to the newest version of the AWS Terraform provider, and Terraform 1.3, and that bug went away for me, so you might try that.
Comment: updating the provider / terraform to their latest -V didn't solve the issue. Thanks for the suggestion though @MarkB
Answer: In Terraform's architecture, one of the responsibilities for a provider is to read the current state of each remote object already under management, to compare it with the result of the most recent apply, and produce a new object which reconciles the two.
Part of that responsibility is to deal with situations where values might appear different in Terraform but are effectively the same as far as the remote system is concerned. For each detected change, the provider must broadly place it into one of the following two categories:

"Drift": the remote system state is different from the previous run state in a way that is functionally significant.
"Normalization": the remote system returned some data in a slightly different shape than was previously returned, but it still means the same thing. Some typical examples of this are: case-insensitive strings where the remote API always returns them in lowercase, or JSON strings where the remote API always returns them minified regardless of the input.

In the case you've shown here, it seems like this provider is not making a correct classification: there is no functional difference between tags = {} and omitting that argument altogether, and so the provider should've classified this as normalization and preserved the fact that you didn't set it, rather than reporting this as drift.
You mentioned that you've already tried setting tags = {} explicitly in your configuration but that didn't fix the problem. Unfortunately that suggests a second opposite bug in the provider: during its create/update step it seems to be normalizing an empty map to be the same as null and so the provider disagrees with itself about what is the normalized form for this argument. If that is true then I don't think there will be anything you can do within your Terraform module to avoid the problem; the only recourse will be to fix the bug in the provider codebase.
The AWS provider team is tracking various bugs of this type. That issue says that provider release v3.70.0 fixed a number of these bugs and so I would suggest making sure you're running at least that version as a first step. However there is a comment describing a similar problem with aws_iam_policy, and these two resource types are closely related and so probably share the same bugs in this regard. If you are already running the latest version of the provider then I think the best thing to do here is to report this by adding another comment to that same GitHub issue, so the provider team will be aware of it.
I'm sorry I don't  have an answer that can be implemented only within your Terraform module.


Generating a Lottery Number Generator in Python

Question: I am an amateur and I need some help in my making of a lottery number generator.
I have got going a while loop where I make a variable set that variable to 0 then I tell python that while that variable is less than 6 it needs to create a random number within a range of 1,49 and I then tell it to add 1 to my variable this then creates 6 numbers within the range of 1,49 although what I need is for these numbers to be in ascending order and with no doubles, so no repeating numbers.
Comment: What code have you tried to write already? Stack Overflow questions require code of your own, and examples make it a lot clearer to us what you're trying to accomplish.
Comment: Are you able to write the basic version (not dealing with ascending order and doubles)?  It sounds as if you are describing the steps quite logically so it is just a matter of writing each step.  Can you get a single random number?  If you can do any of the steps then let us know what you have done and what you are stuck with.
Answer: Are you allowed to use Python's random library? If so, this is trivial.
The random.sample function takes a population (in your case the numbers 1 to 49), and number of samples to draw (in your case 6). Then you can use the sorted function to get the numbers in ascending order.
>>> import random
>>> sorted(random.sample(range(1,50), 6))
[2, 9, 20, 30, 33, 46]

A few more just to show that it is indeed random
>>> sorted(random.sample(range(1,50), 6))
[12, 22, 24, 28, 34, 39]
>>> sorted(random.sample(range(1,50), 6))
[1, 11, 20, 21, 24, 37]
>>> sorted(random.sample(range(1,50), 6))
[2, 4, 7, 21, 32, 48]
>>> sorted(random.sample(range(1,50), 6))
[10, 20, 26, 41, 44, 49]
>>> sorted(random.sample(range(1,50), 6))
[4, 5, 6, 21, 33, 41]


How to deal with missing data in d3.js

Question: I've successfully created several plots with d3 by parsing XML files such as this one.
Now I'm wondering how to deal with incomplete datasets. In my particular example, some sub-elements are missing in some elements. In that case I want d3 to discard the element and not display anything. At the moment, I am applying a filter to the dataset before feeding it into d3's data() function.
Is there a smarter of way of doing this on the fly? Ideally I'd just like to return null when setting an attribute and the required sub-element turns out not to exist.
Full disclaimer: I'm just starting to learn d3.js.
Answer: This can be obtained by setting the display property on the data joined DOM elements:
elemSelection.style("display", function (d) {
    return is_data_NA(d) ? "none" : null;
});

Here is a short mock example: http://jsfiddle.net/rU4XL/
Note that by default, the function which accept value as a function such as .attr, .style, etc., will remove the attribute or content from the selection if the value function returns null. Hence, in this case, the display attribute would be removed from the elements in the elemSelection which have valid data.

How to deal with missing data in d3.js


What type of piano was used in the intro of this song?

Question: I'm listening to this music for about a couple of months. But I can't find a piano with similar texture and fullness.
It will be better if some can tell me where can I find a VST piano which sounds close to this piano.

Also Please provide the piano chords too. It'll help. Thank you so much.
Link to song:
Comment: Please take the time to take the [Tour](https://music.stackexchange.com/tour) and read the [Help pages](https://music.stackexchange.com/help), especially [What topics can I ask about here?](https://music.stackexchange.com/help/on-topic) and [What types of questions should I avoid asking?](https://music.stackexchange.com/help/dont-ask)
Comment: Actually I'm a developer. So I'm used to asking these kind of questions on stackoverflow. Anyway sorry about that man! I'll try my best to maintain the community rules.
Comment: Both questions fall foul of this site's remit, for reasons given on the help section.
Answer: It sounds like 2 sounds stacked on each other. The base sounds like a very mellow grand piano, while the upper portion could be a rhodes or a synth pad.


Drupal Commerce - Out of Stock, customer clicks to notify store owner to order more

Question: When a product is out of stock, the store owner wants customers to have the ability to pre-order, without paying.
Similar to stock notify, but the store owner will manually email back customers once the stock arrives.
Something like'This product is out of stock, notify us, and we will order it in for you within 1 week.'
So it needs to collect: customer email and product SKU.
As many customers will be non-registered users, what would be the best way of capturing this data, and emailing it to the store owner?
I was thinking flags/rules module, or do you think a custom module would be simpler?
Thanks in advance.
Comment: I have a custom module doing the same for me. It collects the same info which you require & send the alert mail on cron job when stock resume. I had a github repo for it, which can help you doing it by custom module - https://github.com/drupler/commerce-stock-notify
Comment: https://www.drupal.org/project/commerce_stock_notifications
Answer: There are two similar kind of sandbox module for this particular functionality.
One was started by me - Commerce Stock Notify
Another by itamar - Commerce Stocklist.
Both can be starting point for further development. As I left doing anything else for this as he started it before me, but my module do what you want except mail template which I was supposed to do later.
But now I think, I will spend some time on it & try to release stable soon :)


Show a Cubic Polynomial over $\Bbb C$ can be factored as a product of linear terms

Question: The title says it all: I want to show that an arbitrary cubic polynomial can be factored as a product of linear terms without appealing to the fundamental theorem of algebra and (preferably) without appealing to the general formula for solving a cubic equation. This is exercise $2.11$ from Ian Stewart's Galois Theory text. Explicitly, it says

Prove, without using the winding number, that every cubic polynomial over $\Bbb C$ can be expressed as a product of linear factors over $\Bbb C$.

In the exercise before, he asks us to show that a cubic polynomial over $\Bbb R$ can be factored as a product of linear terms over $\Bbb C$. This is pretty much immediate since it necessarily tends to $-\infty$ in one direction and $\infty$ in the other direction, hence by the IVT it has a zero. The remainder theorem says that we can factor this linear term out, and then we just use the quadratic formula and we're done. I've been thinking about how we can show something similar for a polynomial over $\Bbb C$ and I haven't figured anything out. Is there a method besides appealing to the formula for cubic polynomials?
The proof of the FTA in this book uses the winding number and presents the general formula for a cubic, so I'm not inclined the solution for this problem relies on either of these results.
Comment: You can prove the fundamental theorem of algebra without winding numbers, but it seems rather unnatural to me to prove the result for cubics without showing it for all polynomials at once, i.e. without proving the whole fundamental theorem of algebra.
Comment: I think that the answer to this question depends on the way the fundamental theorem of algebra is proved in Stewart's book - or if it is proved at all.

Even though this feels like cheating, the proof of the fundamental theorem that I thought was the standard proof does something similar to the (real) case you describe and invokes Liouville's theorem. This may well be what you're looking for (in the case of a degree-three polynomial, if you want to). I'm curious now about the intended solution. Could you post it, when you know it?
Comment: In the book, Stewart uses something about winding numbers to prove the fundamental theorem of algebra. I've read it pretty closely, but I don't understand winding numbers fluently enough to think that I've completely grasped the proof. I've been thinking about this, though. I'll post it when I know.
Comment: @EwanDelanoy: The problem is starred (indicating it is slightly more difficult than the average problem), but it doesn't seem like the author would leave it as an exercise to prove the FTA in a different manner. It would seem there is some straightforward approach as in $\Bbb R$, but without the use of IVT.
Comment: There's a [related question](http://math.stackexchange.com/questions/283009/closure-of-a-number-field-with-respect-to-roots-of-a-cubic)
Answer: For what it's worth here's a trick method for cubics specifically.
Preliminaries:
Define complex exponential. Can use $e^{(x+iy)}=e^x(\cos(y)+i\sin(y))$ or the power series. From this first definition it's clear that this is onto as map from $\mathbb{C}$ to $\mathbb{C}\setminus{0}$. Note that $e^{(z_1+z_2)}=e^{z_1}e^{z_2}$.
Now define complex sine by $\sin z= \frac{1}{2i} (e^{iz}-e^{-iz})$. We can check that this is onto by solving $\sin z=w$- namely, $u=e^{iz}$ gives $u-\frac{1}{u}=2iw$ which is quadratic, and we solve for (non-zero) $u$ and $iz$ in turn.
Finally, note that $\sin(3z)=3\sin z -4 \sin^3 z$ either because this is true for real $z$ and hence always, or by checking explicitly from definitions (using the fact $(u-\frac{1}{u})^3=u^3-\frac{1}{u^3}-3(u-\frac{1}{u})$ this is easy).
Main part:
If $z^3+az^2+cz+d=0$ we can sub $w=z-a/3$ to get rid of the quadratic term, getting $w^3+kw+l=0$. Now sub $w=k^{1/2}u$ and divide out by $k^{3/2}$ to get $u^3+u+p=0$. Finally, let $u=(-4/3)^{1/2}t$, which gives $-4t^3+3t=q$. We are done: there exists $z$ with $\sin 3z =q$, and $t=\sin z$ is a solution.
Comment: To add to this, if you wanted to recover the formula for the roots in terms of the coefficients of your original polynomial, this is possible from this approach, because finding $\sin z$ from $\sin 3z$ reduces to computing cubic and square roots, using the complex exponential representation.
Comment: The case $k=0$ is left as exercise for the reader :)
Comment: That was a typo. I edited it out. Hope it makes sense now - just plug in and simplify.
Comment: Yes, it makes perfect sense now. Thanks!
Answer: This is probably not what you want, but for the record here is a proof that does not use the winding number.
(as you can see, the problem is that it can be obviously  modified to show the whole fundamental theorem of algebra).
Let $f(z)=a_3z^3+a_2z^2+a_1z+a_0$ be a cubic polynomial : $a_3\neq 0$. Since you already have
the quadratic formula, it suffices to show that $f$ has a root.
The closed ball with center $0$ and radius $M$ (let us call it $K$) is compact, so $|f|$ attains a minimum $\rho$ on $K$.  There is a $z_0\in K$ such that $|f(z_0)|=\rho$. Replacing $f$ with $g(z)=f(z_0+z)$, we may assume that $z_0=0$. Let $k$ be the smallest value in $\lbrace 1,2,3 \rbrace$ such that $a_k\neq 0$.
Then we can write $f(z)=a_0+a_kz^k+z^{k+1}h(z)$, where $h$ is another polynomial. There is a constant $C$ such that $|h(z)| \leq C$ whenever $|z| \leq M$. Then we have
$$
|f(z)| \leq |a_0+a_kz^k| + C |z|^{k+1} \tag{1}
$$
Suppose by contradiction that $\rho=|a_0|\neq 0$. Write $a_0=\rho e^{i\theta}$ with $\theta\in {\mathbb R}$,
and $a_k=\rho_ke^{i\theta_k}$ with $\rho_k>0$ and $\theta_k \in {\mathbb R}$. For small $\varepsilon >0$, put
$$
z_{\varepsilon}=\big(\frac{\varepsilon}{r_k}\big)^{\frac{1}{k}} e^{i\frac{\pi+\theta-\theta_k}{k}} \tag{2}
$$
Then $a_0+a_kz^k=(\rho-\varepsilon)e^{i\theta}$ and $|z|=\big(\frac{\varepsilon}{r_k}\big)^{\frac{1}{k}}
$. So  by (1), we have
$$
|f(z_{\varepsilon})| \leq \rho-\varepsilon + C \big(\frac{\varepsilon}{r_k}\big)^{\frac{k+1}{k}}
$$
This will be $\lt \rho$ for small enough $\varepsilon$, contradicting the minimality of $\rho$. So $\rho=0$, $f$ has a root and we are done.
Comment: I like the answer, but it does seem perhaps too difficult, if that is possible. The text seems to be aimed very low for undergraduates, so I don't think it would involve some of the more difficult aspects here... If at the end of the week, I haven't received any better answers, I'll be sure to accept your solution!
Comment: I tend to think that if such an elementary proof existed, everybody would know about it. Perhaps the location of this exercice in Stewart's book is an error.
Comment: By the way, I seem to remember that a "completely explicit", computer-checkable proof of the FTA is an active research project in computer science today.
Comment: I can't say I would find that too hard to believe. Well, we'll see, I suppose. It's not that I dislike the answer, please don't misunderstand me. It just seems much more difficult than even the other starred problems.
Answer: If using a complex-analytical proof of the fundamental theorem of algebra specifically for cubic polynomials is allowed (which I pointed out earlier I don't expect to be the case), the following might be a bit easier.
We will assume that $f(z)$ is a complex polynomial without zeroes in $\mathbb{C}$. This has two relevant consequences:
(1) There exists a real $R>0$ such that $|f(z)|\geq R$ for all $z\in\mathbb{C}$. (This may take a bit of effort to prove.)
(2) The function $\phi:=\frac{1}{f(z)}$ is entire, i.e. holomorphic on all of $\mathbb{C}$.
Due to observation (1), we know that $|\phi(z)|\leq \frac{1}{R}$, hence the function $\phi$ is bounded. It therefore is bounded and entire, so by Liouville's theorem (link), it is constant. But, if $\phi$ is constant and nowhere zero, then $\frac{1}{\phi}=f$ is also constant. So if $f$ where a complex polynomial without zeroes, it most certainly wouldn't be a cubic polynomial. It follows that every cubic polynomial has a zero.


python (sympy) implicit function: get values instead of plot?

Question: I am new to sympy but I already get a nice output when I plot the implicit function (actually the formula for Cassini's ovals) using sympy:
from sympy import plot_implicit, symbols, Eq, solve
x, y = symbols('x y')
k=2.7
a=3
eq = Eq((x**2 + y**2)**2-2*a**2*(x**2-y**2), k**4-a**4)
plot_implicit(eq)

Now is it actually possible to somehow get the x and y values corresponding to the plot? or alternatively solve the implicit equation without plotting at all?
thanks! :-)
Answer: This is an answer addressing your

is it actually possible to somehow get the x and y values corresponding to the plot?

and I say "addressing" because it's not possible to get the x and y values  used to draw the curves — because the curves are not drawn using a sequenc of 2D points… more on this later,

TL;DR
pli = plot_implicit(...)
series = pli[0]
data, action = series.get_points()
data = np.array([(x_int.mid, y_int.mid) for x_int, y_int in data])

Let's start with your code
from sympy import plot_implicit, symbols, Eq, solve
x, y = symbols('x y')
k=2.7
a=3
eq = Eq((x**2 + y**2)**2-2*a**2*(x**2-y**2), k**4-a**4)

and plot it, with a twist: we save the Plot object and print it
pli = plot_implicit(eq)
print(pli)

to get
Plot object containing:
[0]: Implicit equation: Eq(-18*x**2 + 18*y**2 + (x**2 + y**2)**2, -27.8559000000000) for x over (-5.0, 5.0) and y over (-5.0, 5.0)

We are interested in this object indexed by 0,
ob = pli[0]
print(dir(ob))

that gives (ellipsis are mine)
['__class__', …, get_points, …, 'var_y']

The name get_points sounds full of promise, doesn't it?
 print(ob.get_points())

that gives (edited for clarity and with a big cut)
([
  [interval(-3.759774, -3.750008), interval(-0.791016, -0.781250)],
  [interval(-3.876961, -3.867195), interval(-0.634768, -0.625003)],
  [interval(-3.837898, -3.828133), interval(-0.693361, -0.683596)],
  [interval(-3.847664, -3.837898), interval(-0.673830, -0.664065)],
  ...
  [interval(3.837895, 3.847661), interval(0.664064, 0.673830)],
  [interval(3.828130, 3.837895), interval(0.683596, 0.693362)],
  [interval(3.867192, 3.876958), interval(0.625001, 0.634766)],
  [interval(3.750005, 3.759770), interval(0.781255, 0.791021)]
  ], 'fill')

What is this? the documentation of plot_implicit has

plot_implicit, by default, uses interval arithmetic to plot functions.

Following the source code of plot_implicit.py and plot,py one realizes that, in this case, the actual plotting (speaking of the matpolotlib backend) is just a line of code
 self.ax.fill(x, y, facecolor=s.line_color, edgecolor='None')

where x and y are constructed from the list of intervals, as returned from .get_points(), as follows
x, y = [], []
for intervals in interval_list:
    intervalx = intervals[0]
    intervaly = intervals[1]
    x.extend([intervalx.start, intervalx.start,
                  intervalx.end, intervalx.end, None])
    y.extend([intervaly.start, intervaly.end,
                  intervaly.end, intervaly.start, None])

so that for each couple of intervals matplotlib is directed to draw a filled rectangle, small enough that the eye sees a continuous line (note the use of None to have disjoint rectangles).
We can conclude that the list of couples of intervals
l_xy_intervals = ((pli[0]).get_points())[0]

represents rectangular areas where the implicit expression you are plotting is
"true enough"
Comment: Forgot to mention, the interval couples in the big list, being produced by an adaptive procedure, are not guaranteed to come out in any particular order,
Answer: You can do this, even with interval math, if you try getting the mid point of each interval. Starting from your code, and slightly change it, by saving the plot_implicit object in a variable called g we have:
from sympy import plot_implicit, symbols, Eq, solve
x, y = symbols('x y')
k=2.7
a=3
eq = Eq((x**2 + y**2)**2-2*a**2*(x**2-y**2), k**4-a**4)
g = plot_implicit(eq)

Now let's save in a variable named ptos the intervals that were used to draw the plot.
ptos = g[0].get_points()[0]

This way ptos[0][0] will be the first interval in the x axis and ptos[0][1] will be its pair in the y axis. The intervals have a property called mid which gives the middle point of the interval. So you can suppose that ptos[0][0].mid, ptos[0][1].mid will be a pair x,y "true enough" to be one of our numerical solutions.
This way, a data frame composed of this middle point pairs can be generated with:
intervs = np.array(dtype='object')
meio = lambda x0:x0.mid
px = list(map(meio, intervs[:,0]))
py = list(map(meio, intervs[:,1]))
import pandas as pd
dados = pd.DataFrame({'x':px, 'y':px})
dados.head()

Which in this example would give us:
           x         y
 0 -1.177733  0.598826
 1 -1.175389  0.596483
 2 -1.175389  0.598826
 3 -1.173045  0.596483
 4 -1.173045  0.598826

This idea of getting the intervals middle points can be used whenever one needs to move from "interval math" to "standard" point level math. Hope this helps. Regards.