text:
Q: What is the definition of a set? From what I have been told, everything in mathematics has a definition and everything is based on the rules of logic. For example, whether or not $0^0$ is $1$ is a simple matter of definition.
My question is what the definition of a set is?
I have noticed that many other definitions start with a set and then something. A group is a set with an operation, an equivalence relation is a set, a function can be considered a set, even the natural numbers can be defined as sets of other sets containing the empty set.
I understand that there is a whole area of mathematics (and philosophy?) that deals with set theory. I have looked at a book about this and I understand next to nothing.
From what little I can get, it seems a sets are "anything" that satisfies the axioms of set theory. It isn't enough to just say that a set is any collection of elements because of various paradoxes. So is it, for example, a right definition to say that a set is anything that satisfies the ZFC list of axioms?

A: Formally speaking, sets are atomic in mathematics.1 They have no definition. They are just "basic objects". You can try and define a set as an object in the universe of a theory designated as "set theory". This reduces the definition as to what we call "set theory", and this is not really a mathematical definition anymore.
In naive settings, we say that sets are mathematical objects which are collections of mathematical objects, and that there is no meaning to order and repetition of the objects in the collection.
And when we move back to formal settings, like $\sf ZF,NBG,ETCS,NF$2 or other set theories, we try to formalize the properties we expect from sets to have. These may include, for example, the existence of power sets, or various comprehension schemata. But none of them is particularly canonical to the meaning of "set".
These are just ways to formalize, using a binary relation (or whatever you have in the language), the idea of membership, or inclusion, or whatever you think should be the atomic relation defining sets. But as for a right definition? In this aspect "set" is as Platonic as "chair" or "number" or "life".

Footnotes:

*

*This assumes that you take a foundational approach based on set theory. There are other approaches to mathematics, e.g. type theory, in which the notion of "type" is primitive, and sets are just a certain type of objects.
Sufficiently strong set theories can interpret these foundations as well, reducing them to sets if you choose to, or not if you choose not to.

*These are Zermelo-Fraenkel, von Neumann-Goedel-Bernays, Elementary Theory of Category of Sets, and New Foundations. These are not the only set theories, of course. And the point of the answer is that these just offer formal frameworks for the notion of "set" as a primitive object (in one way or another).

A: Note: According to OPs formulation in the bounty text this answer is aimed to give at least a glimpse of some aspects around the definition of set and set theories with focus on the axiom of choice. The top voted answers already contain the essential information.
On the definition of sets:

In modern times sets (and all other mathematical objects) are defined not in order to specify what they are but instead what we want to do with them. This led to different set theories which emerged essentially due to three different strands and common to all of them was the goal to develop a substantial mathematical theory.

*

*Set theory as a tool in understanding the infinite leading to the theory of cardinals and ordinals. We owe Georg Cantor the fundamentals of this theory who did it more or less single-handed and against all odds.

*Set theory as foundation of supplying the subject matter of mathematics. This claim reflects the mainstream and in many books we can find something like set theory is the foundation of mathematics.

*Set theory as supplier of a common mode of reasoning for diverse areas of mathematics. This is strongly related with the second strand and the axiom of choice is a famous set-theoretical principle of this type.

This reasoning from M. Potter's Set Theory and It's Philosophy is followed by

The history of such theories is now a century old ... - and yet there is, even now, no consensus in the literature about the form they should take.

Conclusion: There is no widely agreed single set theory which is favored by the mathematicians from which we could derive a right definition of a set. Instead depending on the area of research and the  richness of results within these areas different set theories like ZF, ZFC, etc. are taken as their basis.

Set theory today:
Presumably most of the daily work is explicitly or implicitely based upon ZF, ZFC or a somewhat weaker version in between. But we should be aware that each of these set theories has benefits as well as drawbacks.

U. Felgner writes in Models of ZF-Set theory
We believe that the ZF-axioms describe in a correct way our intuitive contemplations concerning the notion of sets. The axiom of choice (AC) is intuitively not so clear as the other ZF-axioms are, but we have learned to use it because it seems to be indispensible in proving mathematical theorems. On the other hand (AC) has strange consequences, such as every set can be well-ordered and we are unable to imagine a well-ordering of the set of real numbers.

Besides the well-order theorem (WOT) there are many other equivalents to the AC which are then also to accept.
Historical aspects around AC:
Some mathematicians had difficulties deciding for or against this axiom e.g. van der Waerden:

In 1930, van der Waerden published his Modern Algebra, detailing the exciting new applications of the axiom. The book was very influential, providing Zorn und Teichmüller with a proving ground for their versions of choice, but van der Waerden's Dutch colleagues persuaded him to abondon the axiom in the second edition of 1937. He did so, but the resulting limited version of abstract algebra brought such a strong protest from his fellow algebraists that he was moved to reinstate the axiom and all its consequences in the third edition of 1950. (P. Maddy, 1988)

H. Herrlich summarizes the historical development in his Axiom of Choice

After Gödel (1938) proved the relative consistency of the Axiom of Choice by constructing within a given model of ZF a model of ZFC, the proponents of AC gained ground. Most modern textbooks take AC for granted and the vast majority of methematicians use AC freely.
However, after Cohen (1963) proved the relative consistency of the negation of AC and, moreover, provided a method, called forcing, for producing a plethora of models of ZF that have or fail to have a wide range of specified properties, a growing number of mathematicians started to investigate the ZF world by substituting AC by a variety of possible alternatives, sometimes just by weaking AC and sometimes by replacing AC by axioms that contradict it.

And with respect to a true definition of sets he continues

All this work demonstrates how useful or convenient such axioms as AC and its possible alternatives are. But the question of the truth of AC is not touched, and Hilbert's First Problem remains unanswered. It is conceivable, even likely, that it will never be solved, despite Hilbert's optimistic slogan expressed in his Paris lecture: in mathematics there is no ignorabimus.

Pros and Cons of AC:
Herrlich's book is an interesting source of information around AC. He presents many equivalents of AC and some related concepts to AC. The main part are the chapters Disasters without Choice consisting of 11 sections organised by mathematical disciplines and the chapter Disaster with Choice consisting of 2 sections. To get a glimpse about such consequences I pick out two, three easy understandable examples:

From Section 4: Disasters without Choice
Section 4.4: Disasters in Algebra I: Vector Spaces
In ZFC every vector space is uniquely determined, up to isomorphism, by a single cardinal number, its dimension. Each of the two fundamental results which together enable us to associate dimension with a given vector space fail badly in ZF.
Disaster 4.42: The following can happen:

*

*Vector spaces may have no bases

*Vector spaces may have two bases with different cardinalities.

Theorem 4.44: Equivalent are:

*

*Every vector space has a basis

*AC

Section 4.6: Disasters in Elementary Analysis: The Reals and Continuity
Disaster 4.53: The following can happen

*

*$\mathbb{R}$ may fail to be Fréchet, i.e., not every accumulation point $x$ of a subset A may be reachable by a sequence $(a_n)$ in $A$.

... (9 more to follow)

Though the Axiom of Choice is responsible for many beautiful results, it is equally responsible for the existence of several dreadful monstrosities - unwelcome and unneeded.

From Section 5: Disasters with Choice
Section 5.1: Disasters in Elementary Analysis:
Definition 5.1: The equation $f(x+y)=f(x)+f(y)$ is called the Cauchy-equation
Consider a function $f:\mathbb{R}\rightarrow\mathbb{R}$ that satisfies the Cauchy-equation for all real $x$ and $y$. Then it is easily seen that

*

*$f(r\cdot x)=r\cdot f(x)$ for all rational $r$ and real $x$, i.e. $f$ is $\mathbb{Q}$-linear.

In particular:

*

*$f(r)=f(1)\cdot r$ for all rational $r$.

And continuity of $f$ would imply

*

*$f(x)=f(1)\cdot x$ for all $x\in \mathbb{R}$
Are there solutions of the Cauchy-equation that fail to be continuous? None has ever been constructed and in ZF none will ever be. However the Axiom of Choice guarantees the existence of such monsters; even worse, under AC there are far mor undesirable solutions of the Cauchy-equation than there are desirable ones:
Disaster 5.2: In ZFC there are

*

*$2^{\aleph_0}$ continuous solutions $f:\mathbb{R}\rightarrow\mathbb{R}$ and

*$2^{(2^{\aleph_0})}$ non-continuous solutions $f:\mathbb{R}\rightarrow\mathbb{R}$ of the Cauchy-equation.

Conclusion: It is good to be aware that there are benefits and drawbacks in ZF as well as ZFC and it's plausible that this is also the case for other set theories. So, there is no true definition of a set theory as framework for a true definition of a set.
Two hints:
A classic source to read and think about sets is Naive Set Theory by P. Halmos. It presumably covers most of the aspects around sets you might need for daily work.
On the other hand if you are curious, to see which functions in real analysis can be defined or not be defined according to underlying set theories, you may want to have a short look into Strange Functions in Real Analysis.

A:
"So is it, for example, a right definition to say that a set is
  anything that satisfies the ZFC list of axioms?"

Well, that can't be right, or it would make a sheer nonsense of the idea that there are alternative theories of sets which deviate from ZFC -- like NF, for example.
You might find this article on Alternative Axiomatic Set Theories interesting and illuminating.

A: I will be using the definition of a set most commonly used in mathematics and the real world.
A set is, simply put, a list. Anything is a set. One way to denote a set is to surround a list of elements separated with commas with brackets. A set of my favorite ice-cream types might be $\{Chocolate, Vanilla, Strawberry\}$. Sets can have one element: $\{5\}$ is an element where the only member is the number $5$. Sets can also be empty: $\{ \}$. The empty set is also denoted by $\emptyset$ (when written, it looks more like $\varnothing$). There are also infinite sets: $\{0,1,2,3,4\cdots\}$ is the set of whole numbers. Sets can even have sets as members, for example $\{\{1,2,3\},\{2,3,4\},\{3,4,5\}\}$ is also a set.
Some sets have a rule, for example if the member of our sets are all coordinates, and $y=x$, then we can call the locus of coordinates where $y=x$ a set of vertices. There are an infinite number of such coordinates, including $(0,0), (\pi,\pi), and (\sqrt2,\sqrt2)$. Another function might be: given the domain of Bob, Alice, and Charlie, the output is their favorite ice-cream types. This function can be considered a set: $\{(Bob,Vanilla), (Alice, Chocolate), (Charlie, Chocolate)\}$.
The ZFC list of axioms is just a list of rules that all sets have to follow - they don't really define a set. Sets have to follow the axioms, for example, one axiom claims the existence of a Power Set of a set - the Power Set of a set $S$ contains all subsets of $S$ including $\emptyset$ and $S$ itself, for example, the power set of $\{1,2\}$ is $\{\emptyset,\{1\},\{2\},\{1,2\}\}$. However, not all axioms apply, for example, one axiom claims the existence of one and only one empty set ($\emptyset$). A set can't really "satisfy" this axiom.
Hope this helps. (If I didn't completely answer your question, feel free to comment and I'll fix my answer).
EDIT: A set's order does not matter (this is one thing that distinguishes sets from sequences).

A: Sets have members, and two sets are the same set if, and only if, they have the same members.
That is not quite enough to characterize what sets are.
For example, is the set of all sets that are not members of themselves a member of itself?  If so, you get a contradition, and if not, you get a contradiction.  The "class" of all sets is "too big to be a set", and that simply means you cannot apply to it all the operations you can with sets.  The same thing forbids the class of all groups to be a set of all groups: if it were a set, then the set of permutations of its members would be a group, and would therefore be a member of the set of all groups, and that leads to problems like those of the set of all sets that are not members of themselves.  Likewise, the class of all vector spaces is not a set, etc.  These "proper classes" differ from "sets" only it that they are not members of any other classes.
E. Kamke's Theory of Sets and Paul Halmos' Naive Set Theory are fairly gentle, if moderately onerous, introductions to "naive" set theory.  In "naive" set theory, sets are collections of things.  In "axiomatic" set theory, sets are whatever satifies the axioms.  Halmos inadvertenly coined the term "naive set theory" by naming his book that, when he mistakenly thought the term was already in standard use.

A:
So is it, for example, a right definition to say that a set is anything that satisfies the ZFC list of axioms?

That is almost correct, but not quite. A set on its own does not satisfy the ZFC axioms, any more than a vector on its own can satisfy the vector space axioms or a point on its own can satisfy the axioms of Euclidean geometry.
In school, especially early on, we tend to go from specific to general. First, you learn the numbers 1 through 10 as a young child. Later, you learn larger natural numbers. Finally, much later, you start to talk about the set of all natural numbers.
But things go the other way in advanced mathematics. The definition of a vector space does not start by saying what a "vector" is. The definition of a vector space just give properties that a set of vectors must have with respect to each other to make a vector space.
The same holds for set theory. Instead of saying "a set is anything that satisfies the ZFC list of axioms", you need to start with the entire model of set theory. Then, it does make sense to say, for example, that a ZFC-set is an object in a model of ZFC set theory. Of course, there are several axiom systems for set theory, which a priori have different kinds of "sets". (Of course, there are many vector spaces with different kinds of "vectors" as well.)
When we learn the definition of a vector space, we have some intuitive examples such as $\mathbb{R}^2$ and $\mathbb{R}^3$ to guide us. For set theory, we have examples such as subsets of $\mathbb{N}$ and $\mathbb{R}$, and pure sets such as $\{\emptyset, \{\emptyset\}\}$. These help us understand what the axioms are trying to say.

A:
Definition 0. A set is an $\infty$-groupoid in which every two parallel $1$-cells are equal.

Okay, but what the heck is an $\infty$-groupoid? Well, we can define it like so:

Definition 1. An $\infty$-groupoid is an $\infty$-category in which every $n$-cell is invertible, for all $n \in \mathbb{N}$.

But now the same problem asserts itself: after all, what in the world is an $\infty$-category?
At some point, you have to stop. You have to pick an object that is never defined, whether that be "natural number" or "set" or "$\infty$-groupoid" or "$\infty$-category" or whatever. And instead of defining the objects you wish to study, you instead specify a formal system that grants some ability to reason about those objects. Basically, a formal system consists of some strings of characters (called "axioms") together with inference methods that go something like so: "If the following strings of characters are written down.... $s_1,\ldots,s_n$, then you can write down the string $t$." A sufficiently powerful formal system can therefore provide a foundation for mathematics, by telling us how to reason about sets or $\infty$-groupoids or whatever. Often, we oversimplify by saying: "A foundation of mathematics is a list of axioms." This is an oversimplification, because without inference methods, we can't write down any further strings! Anyway, this is a handy way of talking, so it remains common.
If we wish to stop at "set" and list axioms that govern how sets behave (rather than trying to define what sets are), the most popular approach is ZFC. Basically, ZFC is a list of axioms about sets: for example, one of these axioms says: "If you have a set $X$, then the set of all subsets of $X$ exists." (Axiom of Powerset). Of course, these axioms alone are pretty useless; we need to combine them with some inference methods to get something interesting. But this is easy to do: just pick your favorite collection of inference methods for first-order logic, combine them with the ZFC axioms, and hey presto! You've founded mathematics on sets.
ZFC is the collection of axioms that most working mathematicians will turn to when they get into thorny set-theoretic issues that need a rigorous foundation to sort out. Furthermore, most professional set theorists today base their work on ZFC. However, there are other, competing approaches to reasoning about sets. These include ETCS, SEAR and Martin-Lof Type Theory. You may also be interested in Homotopy Type Theory, which (if I understand correctly) may one day allow us to take $\infty$-groupoids rather than sets as fundamental.

A: (Extensively edited)

So is it, for example, a right definition to say that a set is anything that satisfies the ZFC list of axioms?

In the ZFC axioms, there is no distinction made between objects that are sets and those that are not. Everything is a set. So it doesn't seem all that meaningful to say that some object is a set if and only if it satisfies these axioms.
There is no formal definition of a set in ZFC. Here is the best definition of a set that I have found:

A collection of distinct entities regarded as a unit, being either individually specified or (more usually) satisfying specified conditions.
  Oxford English Dictionary

To be able to write formal proofs about sets, you must do more than just define what a set is. You must compile a minimal list of essential formal properties of sets from which you can derive other formal properties and theorems as required. Using the above definition as a guide, one such property, for example, might be that, for every pair of sets, there exists a set that is their union. Expressed formally:
$$\forall x,y :\exists z :\forall a: [a\in z \iff a\in x \lor a\in y]$$
Here I assume, as in ZFC, that everything is a set. I make no use here of an "is a set" predicate.
Another essential property of sets might be that there exists an empty set that contains no elements. Expressed formally:
$$\exists \emptyset: \forall x: [x\notin \emptyset]$$
Note that neither of these proposed essential properties of sets could be used as a defining property of what a set might be.
Compiling such a list of essential properties can be tricky. The earliest attempt resulted in a system with internal inconsistencies. In that system, it was possible to both and disprove that (see Russell's Paradox):
$$\exists r:\forall x:[x\in r \iff x\notin x]$$
The most successful attempt to date is the Zermelo-Fraenkel axioms of set theory that list 8 essential properties of sets that were used, along with the axioms  of first-order logic, to develop the bulk of modern set theory. After over a century of intensive scrutiny by mathematicians and logicians, no internal inconsistencies have been found in the ZFC axioms.

A: Sets are self-defined; what you're asking here is equivalent to asking:
What is the definition of a definition?
In any case, here is the $\color{red}{\mathrm{old}}$ "definition" of a set:
A set is a collection of 'things'.

There are some who still accept this "definition".
However, suppose we have the set of all sets $S$ defined by $$S=\left\{x \mid x \space   \mathrm{is}\space\mathrm{a}\space\mathrm{set} \right\}$$ and $R$ the set  of all sets that do not have themselves as an element defined as $$R=\left\{x \mid x \space   \notin x \right\}$$ From this we can ask is $R$ an element of $R$?
If yes, then $R \in R \implies R \notin R$
If no, then $R \notin R \implies R \in R$
This is a contradiction and is known as Russell's Paradox.
This paradox was later resolved by Ernst Zermelo and Abraham Fraenkel and is known to be the Zermelo–Fraenkel set theory. Hence the $\color{blue}{\mathrm{new}}$ "definition" is the axiomatic set theory and is the most fundamental foundation of mathematics.
So to summarize:

There is no definition of a set. As a set is already a self-defined entity.

A: Long Comment to Asaf's answer, trying to add some more background.
We can compare the issue regarding the "definition" of set with Geometry.
Euclid's Elements opens with five definitions :

*

*A point is that which has no part.

*A line is breadthless length. [...]

*A surface is that which has length and breadth only.

They can be of some help in grasping the basic concepts, but hardly they can be conceived as real definitions at all.
In 1899 David Hilbert's published his groundbraking book on the axiomatization of geometry : Grundlagen der Geometrie, based on previous lectures. These are the first paragraphs (page 3) :

Let us consider three distinct systems of things. The things composing the first system, we will call points and designate them by the letters $A, B, C,\ldots$; those of the second, we will call straight lines and designate them by the letters $a, b, c,\ldots$; and those of the third system, we will call planes and designate them by the Greek letters $\alpha, \beta, \gamma, \ldots$. [...]
We think of these points, straight lines, and planes as having certain mutual relations, which we indicate by means of such words as "are situated," "between," "parallel," "congruent," "continuous," etc. The complete and exact description of these relations follows as a consequence of the axioms of geometry.

Hilbert's work on foundations of mathematics and logic has been called Formalism and it is still the prevailing philosophical view between "working" mathematicians.

For set we can consider Georg Cantor's mature definition of set in "Beiträge zur Begründung der transfiniten Mengenlehre", Mathematische Annalen (1895-97, Engl.transl.1915 - Dover reprint), §1, page 85 :

By an "aggregate" (Menge) we are to understand any collection into a whole (Zusammenfassung su einem Ganzen) $M$ of definite and separate objects $m$ of our intuition or our thought. These objects are called the "elements" of $M$.

Compare it with a modern textbook on set theory : Nicolas Bourbaki, Elements of Mathematics : Theory of sets (1968 - 1st French ed : 1939-57), page 65 :

From a "naive" point of view, many mathematical entities can be considered as collections or "sets" of objects. We do not seek to formalize this notion, and in the formalistic interpretation of what follows, the word "set" is to be considered as strictly synonymous with "term". In particular, phrases such as "let $X$ be a set" are, in principle, quite superfluous, since every letter is a term. Such phrases are introduced only to assist the intuitive interpretation of the text.

Thus, from a mathematical perspective, points and lines are "things" satisfying the axioms of geoemtry; in the same way, sets are "objects" satisfying the axioms of set theory.
Of course, also if a definition "inside" set theory of the notion of set is impossible, we can still have attempts to elucidate the notion of set from a philosophical perspective.
See e.g. Paul Benacerraf & Hilary Putnam (editors), Philosophy of Mathematics: Selected Readings, (2nd ed : 1983), Part IV. The concept of set.

A: The definition of set depends on what kind of set theory you're using. Here are two examples.
In the kind of set theory described in the appendix of John L. Kelley's General Topology (available at the Internet Archive), the so-called Morse-Kelley set theory, a set is is something which is an element of something else. (Element is undefined; you can't define everything.) In symbols:
$$x\text{ is a set }\iff\exists y\ (x\in y)$$
In the very popular Zermelo–Fraenkel set theory, set is not only not defined, it is not even an undefined term; there is no need to speak of sets because everything is a set. If you insist on defining such a useless term, you could use the same definition as in Morse-Kelley set theory, or more simply:
$$x\text{ is a set }\iff x=x$$

A: One of the reasons mathematics is so useful is that it is applicable to so many different fields.  And the reason for that is that its logical structure starts with "undefined terms" that can then be given definitions appropriate to the field of application.  "Set" is one of the most basic "undefined terms".  Rather than defining it a-priori, we develop theories based on generic "properties" and allow those applying it to a particular field (another field of mathematics, or physics or chemistry, etc.) to use a definition appropriate to that field (as long as it has those "properties" of course).

A: I disagree with people who say that set is undefined.
I am also not very fond of definitions which describe set as an "object", a "list", or a "collection" of something.
Each of above approaches raise somewhat difficult questions, with "collection" being the least problematic of all, in my opinion.

*

*If we try to define set as an object, we inevitably run into discussion of what is object.
We end up defining set in terms of something, which is probably even more difficult to define.

*We cannot define set as list because we cannot list or even comprehend/recognize/operate every member of many sets arising in mathematics.

*Although the least contradictory one from my prospective, an attempt to define set as a collection of something has it disadvantages as well.
Dictionaries define "collection" either as a set, in which case we fall into a vicious circle, or as the act of collecting something, which is not very convenient in context of mathematics.
When talking about set of numbers, we do not mean that they "lie somewhere collected in a pile", or "gathered together" somehow.

We are on the right track with the last interpretation though.

According to Mathematical Analysis lecturer in my undergrad,

set is the way our brain groups abstract objects.

It is not an actual "group" (or "collection") of physical objects or even mental images, but rather a pattern in one's brain which connects (or puts together) certain ideas/images (of elements of set).
In a sense, set consisting of some "elements" is nothing more but a boundary our consciousness draws between the mental image of these "elements" and the rest of object in the minds.
This boundary can be based on anything our brains can operate – common features, resemblance, random assignment, etc.
Ultimately, my bottom line is:

set is a property of mental image(s) in someone's brain.

I know this definition is not mathy/rigorous at all, and perhaps contradicts some definitions you can find in the literature.
But this is the best answer to the question I kept asking myself for the longest time:
"what exactly do they mean when they say 'set'?"


text:
Q: area formula for integration on manifolds Let $g:\mathbb{R}^n\mapsto\mathbb{R}^n$ be a smooth function, $M$ be an $m$-dimensional manifold embedded in $\mathbb{R}^n$ ($m<n$) with a parameterization $f:U\mapsto M$, where $U\subset\mathbb{R}^m$. Let $h:\mathbb{R}^n\mapsto \mathbb{R}$ be a smooth function. Let $Df$ and $Dg$ be the Jacobian matrices and assume them to be nonsingular. I would like to understand how to correctly apply the area formula for $\int_{g(M)} h(x)dx$.
(a) Does the form of integration on $M$ exist for $\int_{g(M)} h(x)dx$ in general? I do not quite believe $\int_{g(M)} h(x)dx = \int_{M} h(g(x))|\text{det}[Dg(x)]|dx$ is correct.
(b) What about the integration on $U$? It seems $Dg(f(x))Df(x)$ is the Jacobian for $g\circ f$, so do we have $\int_{g(M)} h(x)dx = \int_{U} h(g(f(x)))\sqrt{|\text{det}[Df(x)^TDg(f(x))^TDg(f(x))Df(x)}]|dx$?

A: Welcome to MSE. Let me see if I can help get towards your answer.
First, integration is defined (for the kinds of things I'm guessing you're studying -- roughly "manifolds" at the level of Spivak's "Calculus on Manifolds," or maybe Guillemin and Pollack's book) only over manifolds. That is to say
$$
int_B w
$$
is defined only if $B$ is a manifold. And if $B$ is an $m$-dimensional manifold, then $w$ should be an $m$-form. Assuming $B$ is an orientable manifold with a volume-form $\omega$, I think that what you're trying to do is integrate $h\omega$. It's just that you've called $\omega$ by the name $dx$.
But the main point is that this all makes sense only if $B$ is a manifold. When you write
$$
\int_{g(M)} h(x) ~dx,
$$
you need to know that $g(M)$ is indeed a manifold, and has a volume form. For that, you probably need a restriction on $g$. You might, for instance, say that $g$ is a diffeomorphism, in which case $g(M)$ is sure to be a manifold.
Once you do that, things are relatively easy: if you have a parameterization $f: U \to M$ (one that resembles, say, latitude-longitude coordinates on a sphere, and hence is a diffeomorphism almost everywhere, and is surjective), then $g \circ f$ will be a parameterization of $g(M)$. And now your approach, in part "b", says how to compute the integral over the manifold by instead integrating over a nice open subset of $\Bbb R^n$.
I can never remember the exact formula for the part b thing, but it sure looks as if you have it right.
Just to go back to the earlier "is g(M) a manifold" issue, think of something like a nice mobius-band shaped thing, sitting on the $xy$ plane in 3-space. But instead of a half-twist, put in a full twist, so that this is really just an embedding of a cylinder in 3-space. Call that $M$.
Now let's let $g: \Bbb R^3 \to \Bbb R^3: (x, y, z) \to (x, y, 0)$. That's a smooth function, but $g(M)$ is not a smooth manifold: depending on how you oriented your Mobius band, it looks line an annulus pinched at a couple of points, or like a circle that fattens out at a couple of points. In either case, it's not a manifold, so integrating over it doesn't really make sense.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Rotation of a dipole in different situations I know that a dipole performs only rotational motion when placed in a uniform field, while it performs both rotational and translational when placed in a non-uniform electric field.
However, under what circumstances will it perform pure translational motion?

A: The dipole translates if there is a difference in field strength (in magnitude or direction) over the length of the dipole, and it rotates if it is not aligned with the electric field.
It follows that the dipole will purely rotate about its centre in a uniform field if it is not aligned with the field vector, and it will purely translate in a non-uniform field if it is aligned with the field vector.


text:
Q: How to organize different shipping and shipping cost methods in WooCommerce for different regions of the country? I need to arrange different shipping methods and shipping charges for different regions of the country. In this case, Israel. For example, there will be a fixed shipping price to Jerusalem. And if the user is in Tiberia, will be displayed local pickup option. I used this code for similar purposes before:
if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly
}

add_filter( 'woocommerce_states', 'states_for_israel' );
function states_for_israel( $states ) {
    $states['IL'] = array(
        "ACRE"                                      => " Acre",
        "AFULA"                                     => " Afula",
        "ARAD"                                      => " Arad",
        "ASHDOD"                                    => " Arraba",
        "ASHDOD"                                    => " Ashdod",
        "ASHKELON"                                  => " Ashkelon",
        "BAQA AL-GHARBIYYE"                         => " Baqa al-Gharbiyye",
        "BAT YAM"                                   => " Bat Yam",
        "BEERSHEBA"                                 => " Beersheba",
        "BEIT SHEAN"                               => " Beit She'an",
        "BEIT SHEMESH"                              => " Beit Shemesh",
        "BNEI BRAK"                                 => " Bnei Brak",
        "DIMONA"                                    => " Dimona",
        "EILAT"                                     => " Eilat",
        "EL AD"                                     => " El ad",
        "GIV AT SHMUEl"                             => " Giv'at Shmuel",
        "GIVATAYIM"                                 => " Givatayim",
        "HADERA"                                    => " Hadera",
        "HAIFA"                                     => " Haifa",
        "HERZLIYA"                                  => " Herzliya",
        "HOD HASHARON"                              => " Hod HaSharon",
        "HOLON"                                     => " Holon",
        "JERUSALEM"                                 => " Jerusalem",
        "KAFR QASIM"                                => " Kafr Qasim",
        "KARMIEL"                                   => " Karmiel",
        "KFAR SABA"                                 => " Kfar Saba",
        "KFAR YONA"                                 => " Kfar Yona",
        "KIRYAT ATA"                                => " Kiryat Ata",
        "KIRYAT BIALIK"                             => " Kiryat Bialik",
        "KIRYAT GAt"                                => " Kiryat Gat",
        "KIRYAT MALAKHI"                            => " Kiryat Malakhi",
        "KIRYAT MOTZKIN"                            => " Kiryat Motzkin",
        "KIRYAT ONO"                                => " Kiryat Ono",
        "KIRYAT SHMONA"                             => " Kiryat Shmona",
        "KIRYAT YAM"                                => " Kiryat Yam",
        "LOD"                                       => " Lod",
        "MA ALOT-TARSHIHA"                          => " Ma alot-Tarshiha",
        "MIGDAL HAEMEK"                             => " Migdal HaEmek",
        "MODI IN-MACCABIM-REUt"                     => " Modi in-Maccabim-Reut",
        "NAHARIYA"                                  => " Nahariya",
        "NAZARETH"                                  => " Nazareth",
        "NESHER"                                    => " Nesher",
        "NESS ZIONA"                                => " Ness Ziona",
        "NETANYA"                                   => " Netanya",
        "NETIVOT"                                   => " Netivot",
        "NOF HAGALIl"                               => " Nof HaGalil",
        "OFAKIM"                                    => " Ofakim",
        "OR AKIVA"                                  => " Or Akiva",
        "OR YEHUDA"                                 => " Or Yehuda",
        "PETAH TIKVA"                               => " Petah Tikva",
        "QALANSAWE"                                 => " Qalansawe",
        "RA ANANA"                                  => " Ra anana",
        "RAHAT"                                     => " Rahat",
        "RAMAT GAN"                                 => " Ramat Gan",
        "RAMAT HASHARON"                            => " Ramat HaSharon",
        "RAMLA"                                     => " Ramla",
        "REHOVOT"                                   => " Rehovot",
        "RISHON LEZION"                             => " Rishon LeZion",
        "ROSH HAAYIN"                               => " Rosh HaAyin",
        "SAFED"                                     => " Safed",
        "SAKHNIN"                                   => " Sakhnin",
        "SDEROT"                                    => " Sderot",
        "SHEFA-AMR"                                 => " Shefa-Amr",
        "TAMRA"                                     => " Tamra",
        "TEL AVIV"                                  => " Tel Aviv",
        "TIBERIAS"                                  => " Tiberias",
        "TIRA"                                      => " Tira",
        "TIRAT CARMEL"                              => " Tirat Carmel",
        "UMM AL-FAHM"                               => " Umm al-Fahm",
        "YAVNE"                                     => " Yavne",
        "YEHUD-MONOSSON"                            => " Yehud-Monosson",

        "JERUSALEM DISTRICT"                        => " Jerusalem District",
        "NORTHERN DISTRICT"                         => " Northern District",
        "HAIFA DISTRICT"                            => " Haifa District",
        "CENTRAL DISTRICT"                          => " Central District",
        "TEL AVIV DISTRICT"                         => " Tel Aviv District",
        "SOUTHERN DISTRICT"                         => " Southern District",
        "JUDEA AND SAMARIA AREA"                    => " Judea and Samaria Area",
    );

    return $states;
}

As a result, I could create different shipping options for different regions and cities of the country. But this code doesn't work right now. This happened after the Woocommerce updated.


text:
Q: Query nested IEnumerable model class - combined model for view has two classes I have a combined ViewModel that consists of two nested classes. One is IEnumerable the other isn't. The reason is I want to use both is so in the View I can use @foreach and @Html.DisplayNameFor.    The view is using @model Project.ViewModels.BlogCommentCombinedViewModel
I found a article on how to use nested models, however I'm getting a error trying to use IEnumerable nested class and my LINQ query is presenting "cannot implicity convert type BlogViewModel to Systems.Collections.Generic.IEnumerable<Project.ViewModels.BlogViewModel>
How do explicitly cast or is there a better way?
Controller
    var blogResult = from a in _db.Users
                              join b in _db.blog on a.Id equals b.userID
                              select new BlogCommentCombinedViewModel
                              {

                                 bvm = new BlogViewModel
                                 { GETTING ERROR HERE:
                                   "cannot implicity convert type BlogViewModel to Systems.Collections.Generic.IEnumerable<Project.ViewModels.BlogViewModel>" An explicit conversion exist - are you missing a cast
                                 }

                                 lcvm = new LeaveCommentViewModel
                                 {
                                   //binding data in here

                                 }

                              } ;

Combined View Model
 public class BlogCommentCombinedViewModel
    {
        public IEnumerable<BlogViewModel> bvm { get; set;}
        public LeaveCommentViewModel lcvm { get; set; }
    }

    public class BlogViewModel
    {
        [Key]
        public int blogID { get; set; }

        public string blogTitle { get; set; }
        public string blogContent { get; set; }
        public string userID { get; set; }

        public DateTime publishedDate { get; set; }

        [NotMapped]
        public string firstName { get; set; }
        [NotMapped]
        public string lastName { get; set; }
        [NotMapped]

 public class LeaveCommentViewModel
    {
        [Key]
        public int commentID { get; set; }
        [Display(Name = "Comment")]
        [MinLength(5, ErrorMessage = "Comment is too short")]
        public string comment { get; set; }
        public string reply { get; set; }
        public int blogID { get; set; }
        public string userID { get; set; }
    }

A: The issue is that IEnumerable<BlogViewModel> != BlogViewModel.  Even though you are only creating a single element, you need to wrap it in an IEnumerable<BlogViewModel> - or something which implements that interface, e.g. List<T>.
Instead try this:
// Definition
public class BlogCommentCombinedViewModel
{
    public IEnumerable<BlogViewModel> bvm { get; set;}
    public LeaveCommentViewModel lcvm { get; set; }
}

// Query
var blogResult = from a in _db.Users
                 join b in _db.blog on a.Id equals b.userID
                 select new BlogCommentCombinedViewModel
                 {
                     bvm = new[]
                     {
                         new BlogViewModel() // etc
                     },
                     lcvm = new LeaveCommentViewModel
                     {
                         // binding data in here
                     }
                 };

This creates an array of one BlogViewModel item - which can be implicitly converted to IEnumerable<T>.
Test code
This compiles and runs in LINQPad:
var users = new[] { new User(42) };
var blog = new[] { new Blog(42) };

var test = from u in users
           join b in blog on u.Id equals b.UserId
           select new BlogCommentCombinedViewModel
           {
               bvm = new[]
               {
                   new BlogViewModel() // etc
               },
               lcvm = new LeaveCommentViewModel
               {
                   // binding etc
               }
           };

test.Dump();

public record User(int Id);

public record Blog(int UserId);

public class BlogCommentCombinedViewModel
{
    public IEnumerable<BlogViewModel> bvm { get; set; }
    public LeaveCommentViewModel lcvm { get; set; }
}

public class BlogViewModel
{
    // etc
}

public class LeaveCommentViewModel
{
    // etc
}


text:
Q: Error assembling WAR: webxml attribute is required I'm using Maven for my web application but when I run mvn clean install I get
 ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 4.144 s
[INFO] Finished at: 2016-05-05T20:19:13+03:00
[INFO] Final Memory: 25M/271M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-war-plugin:2.2:war (default-war) on project HW-web-parent: Error assembling WA
R: webxml attribute is required (or pre-existing WEB-INF/web.xml if executing in update mode) -> [Help 1]

My main maven looks like these:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>shop.tryHW</groupId>
    <artifactId>tryHW-parent</artifactId>
    <version>1.0-SNAPSHOT</version>

    <packaging>pom</packaging>
    <modules>
        <module>tryHW-core</module>
        <module>tryHW-web</module>
    </modules>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>

                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <properties>
        <!-- Logging -->
        <slf4j.version>1.7.21</slf4j.version>
        <log4j.version>2.5</log4j.version>

        <!-- Testing -->
        <junit.version>4.11</junit.version>
        <mockito.version>1.9.5</mockito.version>
        <hamcrest-all.version>1.3</hamcrest-all.version>
        <dbunit.version>2.5.0</dbunit.version>

    </properties>

    <dependencyManagement>
        <dependencies>

            <!-- ======= -->
            <!-- Logging -->
            <!-- ======= -->
            <!-- SLF4J -->
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-api</artifactId>
                <version>${slf4j.version}</version>
            </dependency>
            <!-- Apache Log4j 2 -->
            <dependency>
                <groupId>org.apache.logging.log4j</groupId>
                <artifactId>log4j-slf4j-impl</artifactId>
                <version>${log4j.version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.logging.log4j</groupId>
                <artifactId>log4j-core</artifactId>
                <version>${log4j.version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.logging.log4j</groupId>
                <artifactId>log4j-1.2-api</artifactId>
                <version>${log4j.version}</version>
            </dependency>

            <!-- ======= -->
            <!-- Testing -->
            <!-- ======= -->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>${junit.version}</version>
                <scope>test</scope>
                <exclusions>
                    <exclusion>
                        <artifactId>hamcrest-core</artifactId>
                        <groupId>org.hamcrest</groupId>
                    </exclusion>
                </exclusions>
            </dependency>
            <dependency>
                <groupId>org.mockito</groupId>
                <artifactId>mockito-all</artifactId>
                <version>${mockito.version}</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.hamcrest</groupId>
                <artifactId>hamcrest-all</artifactId>
                <version>${hamcrest-all.version}</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.dbunit</groupId>
                <artifactId>dbunit</artifactId>
                <version>${dbunit.version}</version>
                <scope>test</scope>
                <exclusions>
                    <exclusion>
                        <artifactId>junit</artifactId>
                        <groupId>junit</groupId>
                    </exclusion>
                </exclusions>
            </dependency>

        </dependencies>
    </dependencyManagement>

    <dependencies>
        <!-- ======= -->
        <!-- Logging -->
        <!-- ======= -->
        <!-- SLF4J -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>
        <!-- Apache Log4j 2 -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-slf4j-impl</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
        </dependency>

        <!-- ======= -->
        <!-- Testing -->
        <!-- ======= -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-all</artifactId>
        </dependency>
    </dependencies>
</project>

I looked over solutions online and they were saying to add the  under configurations but it's not working. Any ideas? I already have a WEB-INF/web.xml with the path tryHW\tryHW-web\web\WEB-INF\web.xml


text:
Q: VBA-sort through mailbox and move duplicate subjects to folder I've run into an issue where i'm writing a macro in Outlook 2013 that goes through an inbox and whenever it comes across duplicate subject lines it moves the 2 emails to a different folder.
These "duplicates" have slight differences within the subject line, difference being a "new" prefix and a "closed" prefix.
I have a general idea on how I can achieve this, but i'm sure there would be a much cleaner and more efficient way to do so as there are 50 different subject lines (without prefix included) .
Currently my thoughts is to have something similar to below:
for i = 1 to inbox.items.count
    if inbox.items(i) = "new - example subject 1" then
        for x = 1 to inbox.items.count
            if inbox.items(x) = "closed - example subject 1" then
                inbox.items(x).unread = false
                inbox.items(x).move otherFolder
                inbox.items(i).unread = false
                inbox.items(i).move otherFolder
                exit for
            end if
        next x
     end if

    if inbox.items(i) = "new - example subject 2" then
        for x = 1 to inbox.items.count
            if inbox.items(x) = "closed - example subject 2" then
                inbox.items(x).unread = false
                inbox.items(x).move otherFolder
                inbox.items(i).unread = false
                inbox.items(i).move otherFolder
                exit for
            end if
        next x
     end if

'repeating 50 times'

next i

A: Firstly, do not use multiple dot notation: inbox.items(i).move otherFolder - each inbox.items(i) will return a brand new COM object.
Secondly, use Items.Find/FindNext or Items.Restrict insrtead of looping through all items in a folder.

A: You need to use the Find/FindNext or Restrict methods of the Items class instead of iterating through all items in the folder. For example:
Sub DemoFindNext()
 Dim myNameSpace As Outlook.NameSpace
 Dim tdystart As Date
 Dim tdyend As Date
 Dim myAppointments As Outlook.Items
 Dim currentAppointment As Outlook.AppointmentItem

 Set myNameSpace = Application.GetNamespace("MAPI")
 tdystart = VBA.Format(Now, "Short Date")
 tdyend = VBA.Format(Now + 1, "Short Date")
 Set myAppointments = myNameSpace.GetDefaultFolder(olFolderCalendar).Items
 Set currentAppointment = myAppointments.Find("[Start] >= """ & tdystart & """ and [Start] <= """ & tdyend & """")
 While TypeName(currentAppointment) <> "Nothing"
   MsgBox currentAppointment.Subject
   Set currentAppointment = myAppointments.FindNext
 Wend
End Sub

See the following articles for more information and sample code:

*

*How To: Use Find and FindNext methods to retrieve Outlook mail items from a folder (C#, VB.NET)

*How To: Use Restrict method to retrieve Outlook mail items from a folder
Also you may find the AdvancedSearch method of the Application class helpful. The key benefits of using the AdvancedSearch method are listed below:

*

*The search is performed in another thread. You don't need to run another thread manually since the AdvancedSearch method runs it automatically in the background.

*Possibility to search for any item types: mail, appointment, calendar, notes etc. in any location, i.e. beyond the scope of a certain folder. The Restrict and Find/FindNext methods can be applied to a particular Items collection (see the Items property of the Folder class in Outlook).

*Full support for DASL queries (custom properties can be used for searching too). You can read more about this in the Filtering article in MSDN. To improve the search performance, Instant Search keywords can be used if Instant Search is enabled for the store (see the IsInstantSearchEnabled property of the Store class).

*You can stop the search process at any moment using the Stop method of the Search class.


text:
Q: make all the fileds are required in html Is it possible by default make all the fileds in a div class as required fileds. I have a form and inside the form i have a div class.. why i am using the div class is by defalut the div class is hidden and when i clicked on some check box it will be visible.  SO i need all the elements in the div class should be required filed. I was trying required="required" on all the elements but it is not working. Any one has idea?
  Here is my html

     name
    <input required="required" type="text" name="name>

     age
    <input required="required type="text" name="age>

                  </form>

Any help will be appreciated

A: Syntax highlighting - probably the greatest tool at any coder's disposal. (It's even on Stack Overflow!)

 name
<input required="required" type="text" name="name>

 age
<input required="required type="text" name="age>

</form>

Attributes are red and their values are blue. So it should look more like this:

 name
<input required="required" type="text" name="name" />

 age
<input required="required" type="text" name="age" />

</form>

and FYI the required attribute doesn't need a value:
<input type="text" name="age" required />

A: Change your code as follow:
<input type="text" name="name" required>

and
<input name="age" required>

Just writing "required" make your fields as required. It works only in HTML5. So put  it before html tag starts.

A: if you want to use html5 you can do it with required(this only works on browsers that support html5), if not use a jquery plugin for validation like this:
http://bassistance.de/jquery-plugins/jquery-plugin-validation/


text:
Q: Counting the nonwhitespace in a String How would I count the nonwhitespace in String in Java?
Only thing I can declare is the int nonwhitespace = 0; That is all I can think of.

A: How about
int nonwhitespace = text.replaceAll("\\w","").length();

A: May be first replace all whitespaces and then count the length?
str.replaceAll("\\s+","") - to remove whitespaces..
str.length() -- to then count the number the nonwhite space chars

A: Code below should work.
int total = 0;

for(int i=0; i < str.length(); i++)
{

   if(!Character.isWhitespace(str.charAt(i)))
     total++;
}

System.out.println("total non-whitespace characters are " + total);


text:
Q: To calculate the order of the group of all invertible linear operators on a vector space Let $V$ be a finite dimensional vector space over a finite field $F$ , then how can we calculate the order of the group of all invertible linear operators on $V$  in terms of $|F|$ and $\dim V$ ?

A: Hint: take a small example e.g. $V = (\mathbb{Z} /2)^2$ over $F = \mathbb{Z} / 2$, then calculating the number of invertible $F$-linear operators on $V$ is the same as counting the number of $\dim(V) \times \dim(V)$ matrices with coefficients in $F$ whose determinant is nonzero (or equivalently, such that there is no $F$-linear relation between the columns of the matrix). In this case, we have $|F|^2 - 1$ choices for the first column and $|F|^2 - |F|$ choices for the second column. How might this generalize?


text:
Q: Scheduling Job in .NET using Threads & Timers This is the requirement.
I have job/task which takes one parameter as input and performs some function.
I need to execute the method DoWork at different schedule timings with different input parameter. Lets say,
at 1 PM, DoWork has to be triggered with input1.
at 1.30 PM, DoWork has to be triggered with input2.
at 3 PM, DoWork has to be triggered with input3.
....
Which is the best way to do this??
- Using System.Timer
- Using System.Threading.Timer
- Using TaskFactory & TaskScheduler
Whatever I tried so far, first of all there is a Windows Service:
public partial class MainJobExecWS : ServiceBase
{
    private Timer taskTimer;

    public MainJobExecWS()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        // Define Timer for MainJob
        TimeSpan dueTime = // define starting time of timer;
        TimeSpan repeatingPeriod = // define repeating interval of timer;
        MainJob jm = new MainJob();
        TimerCallback tcb = jm.executeMainJob;
        taskTimer = new Timer(tcb, null, dueTime, repeatingPeriod);
        base.OnStart(args);
    }

    protected override void OnStop()
    {
        if (taskTimer != null)
        {
            taskTimer.Dispose();
        }
        base.OnStop();
    }
}

Definition for the Main Job:
class MainJob
    {
        public void executeMainJob(object state)
        {
            // Main Job Definition
        }

        private void scheduleChildJob()
        {
            String childJobInput = "abc"; // How to pass this input to the child job????
            TimeSpan execTimeSpan = // define the timespan for triggering child job;
            ChildJobDef chdJob = new ChildJobDef();
            TimerCallback tcb = chdJob.executeChildJob;
            Timer timer = new Timer(tcb, null, execTimeSpan, ?); // How to specify that the child job should be triggered only once??
        }
    }

And finally the definition for Child Job Definition:
class ChildJobDef
{
    public void executeChildJob(object state)
    {
        // How to get the input sent to this job???
    }
}

A: I find the Reactive Extensions handle these scenarios best, as their IScheduler interface lets you to schedule actions to run at a specific, absolute time (as opposed to specifying a relative delay).  Their schedulers are fairly robust, and will compensate for clock drift, changes to system time, etc.
Using them is easy:
DateTimeOffset startTime = /* determine start time */;
Scheduler.Default.Schedule(startTime, () => RunTask1());

A: I was bored so I threw together a demo of using System.Timers.Timer to schedule a task to run at the next instance of a specific time:
public class ScheduledTask<T>
{
    private T _parameter;
    private Action<T> _action;
    private Timer _timer;

    public ScheduledTask( T parameter, Action<T> action, int hour, int minute, int second )
    {
        Debug.Assert( null != parameter && null != action, "Arg(s) == null" );

        _parameter = parameter;
        _action = action;

        _timer = new Timer( GetIntervalForTimeOfDay( hour, minute, second ) )
        {
            AutoReset = false
        };

        _timer.Elapsed += ( sender, e ) =>
            {
                if( null != TaskStarted )
                {
                    TaskStarted( this, new DateTimeEventArgs( DateTime.Now ) );
                }

                action( _parameter );

                if( null != TaskCompleted )
                {
                    TaskCompleted( this, new DateTimeEventArgs( DateTime.Now ) );
                }
            };

        _timer.Start();
    }

    public static double GetIntervalForTimeOfDay( int hour, int minute, int second )
    {
        Debug.Assert( hour <= 23 && hour >= 0 && minute <= 59 && minute >= 0 && second <= 59 && second >= 0, "Parameter(s) out of range" );

        var now = DateTime.Now;

        var interval = ( new DateTime( now.Year, now.Month, now.Day, hour, minute, second ) )
            .Subtract( now )
            .TotalMilliseconds;

        if( 0.0 > interval )
        {
            interval += 24.0 * 60.0 * 60.0 * 1000.0; // hours in day * minutes in hour * seconds in minute * milliseconds in minute
        }

        return interval;
    }

    public event EventHandler<DateTimeEventArgs> TaskStarted;
    public event EventHandler<DateTimeEventArgs> TaskCompleted;
}

public class DateTimeEventArgs : EventArgs
{
    public DateTime DateTime { get; private set; }

    public DateTimeEventArgs( DateTime dt )
    {
        DateTime = dt;
    }
}

Usage:
class Program
{
    static void Main()
    {
        Console.WriteLine( "App started: {0:yyyy-MM-dd HH:mm:ss}", DateTime.Now );

        var st1 = new ScheduledTask<int>( 1, i =>
            {
                System.Threading.Thread.Sleep( 1000 );
                Console.WriteLine( "{0}: {1:yyyy-MM-dd HH:mm:ss}", i, DateTime.Now );
            }, 15, 30, 0 ); // 3:30:00 PM

        st1.TaskStarted += ( sender, e ) => Console.WriteLine( "1 started: {0:yyyy-MM-dd HH:mm:ss}", DateTime.Now );
        st1.TaskCompleted += ( sender, e ) => Console.WriteLine( "1 completed: {0:yyyy-MM-dd HH:mm:ss}", DateTime.Now );

        var st2 = new ScheduledTask<int>( 2, i =>
            {
                System.Threading.Thread.Sleep( 1000 );
                Console.WriteLine( "{0}: {1:yyyy-MM-dd HH:mm:ss}", i, DateTime.Now );
            }, 15, 51, 7 ); // 3:51:07 PM

        st2.TaskStarted += ( sender, e ) => Console.WriteLine( "2 started: {0:yyyy-MM-dd HH:mm:ss}", DateTime.Now );
        st2.TaskCompleted += ( sender, e ) => Console.WriteLine( "2 completed: {0:yyyy-MM-dd HH:mm:ss}", DateTime.Now );

        Console.WriteLine( "App thread paused: {0:yyyy-MM-dd HH:mm:ss}", DateTime.Now );

        Console.ReadLine();
    }
}


text:
Q: Flyback transformer temperature rise - reasonable value I had build an flyback converter based on UC3845 and some high voltage mosfet - it works fine, however I've got one problem with it. (but i'm not sure if that actually is a problem)
The core for the transformer I used is taken out from laptop power adapter (19V @ 3,5A). From what I reserached - this is RM10 core:

I'm getting 24V @ 2,5A from it, the transistor and secondary diode heats up, but has resonable temperature on the heatsink (40degC), However the transformer is getting quite hot (65-70degC) after some time.
This is the primary current of the transformer - it shows no saturation.

Is it normal for this size of core to get to those temperatures at those powers? If not - What is causing the excessive heating?
EDIT:
Here is the schematic:

And there is the secondary waveform at rated power (24V @ 2,5A):

A:
Is it normal for this size of core to get to those temperatures at
those powers? If not - What is causing the excessive heating?

That is a pretty reasonable temperature to run at. In fact I'd say it's probably running cool compared to most flyback designs. If you generally look at ferrite data sheets they state how much the temperature will rise under certain conditions. I've just answered this question on a similar subject and, I'll use some of that information: -

What the above is telling you is that if the peak flux density in the core is 100 mT and you are switching at 100 kHz, that core-set will dissipate 9.5 watts and rise in temperature by 100 °C. It's a recommended limit value so it's not advisable to run at this level (unless you know what you are doing).

However the transformer is getting quite hot (65-70degC) after some
time.

That's fine!


text:
Q: How to install Node.js with PHP Curl? I'm trying to find how to install Node.js on my apache server, but I don't have access to the console (SSH) on my server. Is it possible to install Node with PHP Curl ?
I've already downloaded the source code and I put it on my server, but I don't know what to do with it.

A: It might be possible with PHP and some filthy system() calls, but if you can execute those Commands in a PHP context, why don't you have any access to the server otherwise?
I would ask someone to give you access to the server directly or let the admins install node.js for you.
Due to the fact that you're the admin of that server and you don't know how to enbale SSH and even not how to install node.js (which is pretty straightforward) I recommend you to read something about administering servers: this as well as this link might help you.
Furthermore, here's a tutorial on how to enable sshd on your server and here's a link on how to build and install node.js.
But I still ask myself how do you even work with the server if you have no access to it in a way...


text:
Q: matplotlib re position legend relative to pie chart and a pie chart like so.

code:
import matplotlib.pyplot as plt
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
sizes = [15, 30, 45, 10]
result = plt.pie(sizes, labels=labels )
plt.legend(result[0], sizes,  bbox_to_anchor=(0.00, 1))
plt.show()

This is just a demo example. But depending on the data I am using, the legend will get in the way of the pie chart.
My question: How do I position the pie chart further left, or add some padding between the pie chart and the legend.
I have spent a while googling this, but couldn't find the answer.
Thanks
Daniel


text:
Q: XSLT 1.0 Json Array I need convert json request and convert to XML. i can make simple tag and foreach with simple XSLT. but when i found case with json array with [], i got stock. i need help to handle with this case.
Request
{
    "Header" : {
        "SubHeader1" : {
            "SubHeaderInput1" : "",
            "SubHeaderInput2" : "",
            "SubHeaderInput3" : ""
        },
        "SubBody" : {
            "SubBody1" : {
                "SubBody1Side1" : {
                    "ValSubBody1Side1Input1" : "",
                    "ValSubBody1Side1Input2" : "",
                },
                "SubBody2Side2" : [{
                    "ValSubBody1Side2branch1" : {
                        "ValSubBody1Side2branch1Input1" : "",
                        "ValSubBody1Side2branch1Input2" : ""
                    },
                    "ValSubBody1Side2branch2" : {
                        "ValSubBody1Side2branch2Input1" : "",
                        "ValSubBody1Side2branch2Input2" : ""
                    }
                }]
            }
        }
    }
}

Expected Response result like this :
<Header>
    <SubHeader1>
        <SubHeaderInput1></SubHeaderInput1>
        <SubHeaderInput2></SubHeaderInput2>
        <SubHeaderInput3></SubHeaderInput3>
    </SubHeader1>
    <SubBody>
        <SubBody1>
            <SubBody1Side1>
                <ValSubBody1Side1Input1></ValSubBody1Side1Input1>
                <ValSubBody1Side1Input2></ValSubBody1Side1Input2>
            </SubBody1Side1>
            <SubBody1Side2>
                <ValSubBody1Side2branch1>
                    <ValSubBody1Side2branch1Input1></ValSubBody1Side2branch1Input1>
                    <ValSubBody1Side2branch1Input2></ValSubBody1Side2branch1Input2>
                </ValSubBody1Side2branch1>
                <ValSubBody1Side2branch2>
                    <ValSubBody1Side2branch2Input1></ValSubBody1Side2branch2Input1>
                    <ValSubBody1Side2branch2Input2></ValSubBody1Side2branch2Input2>
                </ValSubBody1Side2branch2>
            </SubBody1Side2>
        </SubBody1>
    </SubBody>
</Header>

Please help me about this


text:
Q: how to grep only lines that start with specific word in Mac? I have a text file.
I want to grep all lines that starts with specific word `"length="
which line in terminal \ using sublime can I run to get only these lines?
text:
   }, {
      "path" : "{\"segmentId\":22439323,\"nodeId\":18437268,\"x\":-71.205646,\"y\":42.38619}",
      "distance" : 2744,
      "length" : 73,
      "instruction" : {
        "opcode" : "CONTINUE"
      },
      "crossTime" : 5,
      "additionalInstruction" : null,
      "detourSavings" : 0,
      "isToll" : false,
      "knownDirection" : true
    }, {
      "path" : "{\"segmentId\":67031059,\"nodeId\":18404240,\"x\":-71.206302,\"y\":42.38574800000001}",
      "distance" : 2749,
      "length" : 9,
      "instruction" : {
        "opcode" : "CONTINUE"
      },
      "crossTime" : 1,
      "additionalInstruction" : null,
      "detourSavings" : 0,
      "isToll" : false,
      "knownDirection" : true
    }, {

A: Assuming you need to find the lines with "length" : this does the work:
 grep '^\s*"length" :' yourfile


text:
Q: How to spyOn to react custom hook returned value? Here is my custom hook:
useCustomModal.ts
export const useCustomModal = (modalType: string) => {
  const setModal = () => {
    // ... functionality here
  };

  const handleModalClose = (modalType: string) => {
    // ... functionality here
    setModal();
    // ...
  };

  return {
    handleModalClose,
    setModal,
  };
};

And here is my test:
useCustomModal.ts
import { act } from '@testing-library/react-hooks';

import { useCustomModal } from './useCustomModal';

describe('some', () => {
  it('a test', async () => {
    await act(async () => {
      const actions = useCustomModal('test');
      const spy = jest.spyOn(actions, 'setModal');
      actions.handleModalClose('test');
      expect(spy).toBeCalledTimes(1);
    });
  });
});

Test failed :
Expected number of calls: 1
Received number of calls: 0
How to properly spyOn on custom react hooks?

A: You need to use renderHook in conjunction with act. Something like this:
import { renderHook, act } from '@testing-library/react-hooks';

import { useCustomModal } from './useCustomModal';

describe('some', () => {
  it('a test', () => {
    const { result } = renderHook(() => useCustomModal('test'));
    const spy = jest.spyOn(result.current, 'setModal');
    act(() => {
      result.current.handleModalClose('test');
    });
    expect(spy).toBeCalledTimes(1);
  });
});


text:
Q: 'list' object has no attribute 'items' for saving list of array as mat file I want to save a list of NumPy array as a mat file but raised with error 'list' object has no attribute 'items'. You can see my try below:
import numpy as np
import scipy.io

output=[]
for i in range(10):
  a=np.random.randint(0,100,size=(60,60,4))
  output.append(a)
scipy.io.savemat('test.mat', output)

A: Here is the answer:
import numpy as np
import scipy.io

output=[]
for i in range(10):
  a=np.random.randint(0,100,size=(60,60,4))
  output.append(a)
scipy.io.savemat('test.mat',  mdict={'my_list': output})


text:
Q: Javascript game trouble I am making a game in Javascript with HTML5's canvas API and have hit a roadblock.
One of the games effects is a missile travelling upwards along the y axis, which is influenced by gusts of wind (emitted by turbines) which move it along the x-axis. I've had no problem with making one of these turbines, but when their number is increased to 3 I run into trouble.
Upon a new level, I instantiate these turbines as objects, which are then pushed into an array, as can be seen here:
function gameStateNewLevel(){

    for (var i = 0; i < 2; i++){
        turbine = {};
        turbine.width = 10;
        turbine.height = Math.floor(Math.random()*200); //turbine height
        turbine.y = Math.floor(Math.random()*600) //turbine y-axis
        if (Math.random()*10 > 5){ //indicates turbine side of canvas
            turbine.side = leftSide;
        }else{
            turbine.side = rightSide;
        }
        if(turbine.height <= 100){ //Increases turb. size if it's too small
            turbine.height += Math.floor(Math.random()*100);
        }

        turbines.push(turbine);

    }

    context.fillStyle = "#FFFFFF"
    switchGameState(GAME_STATE_PLAYER_START);
}

Now, before they are rendered, they are also updated through an updateTurbine function. All this function should do is make sure that the turbines are not overlapping each other and move them up or down the y axis as necessary (by cycling through the array and comparing each of the objects in it). I've given a go at making the function, but I'm completely lost between all the loops. This is about as far as I've got, and I have a feeling I'm on the wrong track:
function updateTurbines(){
    tempTurbine = {}
    turbinePositionTop = tempTurbine.y;
    turbinePositionBottom = tempTurbine.y + tempTurbine.height;
    for (var i = turbineArrayLength; i < 2; i++){
        tempTurbine = turbines[i];
        for (var i = turbineArrayLength; i < 2; i++){
            if (tempTurbine !== tempTurbines[i]){
                while (){

                }
            }
        }
    }
}

You can find source code and the furthest I got without this thing breaking at www.techgoldmine.com

A: There are errors in your code, see the comments here:
function updateTurbines(){
    tempTurbine = {}
    turbinePositionTop = tempTurbine.y; // tempTurbine is an empty object right now so .y is undefined
    turbinePositionBottom = tempTurbine.y + tempTurbine.height; // same problem here
    for (var i = turbineArrayLength; i < 2; i++){ // why am I starting at the end of the array? What's the 2 for?
        tempTurbine = turbines[i];
        for (var i = turbineArrayLength; i < 2; i++){ // why am I doing this twice? I'm also clobbering the value of "i"
            if (tempTurbine !== tempTurbines[i]){
                while (){

                }
            }
        }
    }
}

Here's how I'd rewrite that without knowing what its doing:
function updateTurbines(){
    var l = turbines[i].length; // get the turbine length directly from the array[1]
    for (var i = 0; i < l; i++){ // go through all of the turbines
        var tempTurbine = turbines[i];
        turbinePositionTop = tempTurbine.y; // now .y is defined because tempTurbine is not an empty object
        turbinePositionBottom = tempTurbine.y + tempTurbine.height;
        for (var j = 0; j < l; j++) { // NOT i but j here
            if (tempTurbine !== tempTurbines[j]){
                while (){
                     // ...
                }
            }
        }
    }
}

[1] this might cause errors if you modify the array. I'm assuming you only ever add to it for now.

A: Your problem is likely that the indexes are overlapping; the inner loop is changing the i value for the outer loop.
I changed i to j in the inner loop.
function updateTurbines(){
    tempTurbine = {}
    turbinePositionTop = tempTurbine.y;
    turbinePositionBottom = tempTurbine.y + tempTurbine.height;
    for (var i = turbineArrayLength; i < 2; i++){
        tempTurbine = turbines[i];
        for (var j = turbineArrayLength; j < 2; j++){
            if (tempTurbine !== tempTurbines[j]){
                while (){
                    //What the heck is going on here?
                }
            }
        }
    }
}

Let me know if that fixed it.

A: The replies were helpful, but none of them worked... this is the code I got in the end.
function updateTurbines(){
    var l = turbines.length;
    for (var i = 0; i < l; i++){ // go through all of the turbines
        var tempTurbine1 = turbines[i];
        tempTurbine1.PositionTop = tempTurbine1.y; // now .y is defined because tempTurbine is not an empty object
        tempTurbine1.PositionBottom = tempTurbine1.y + tempTurbine1.height;
        for (var j = 0; j < l; j++) { // NOT i but j here
            var tempTurbine2 = turbines[j];
            if (tempTurbine1 !== tempTurbine2 && tempTurbine1.PositionBottom >= tempTurbine2.PositionTop){

    }
   }
  }
 }


text:
Q: add and remove items from jQueryTools' scrollable I have a simple want.. to add to a scrollable from another.. so that means a add which was easy with the docs here.. but the remove.. no luck.. I can make the move but the scrollable doesn't reflect in in the nav or left rights.. this is what I have tried so far..
    $(function() {
          // initialize scrollable
          $("#Unused.scrollable").scrollable({easing: 'easeOutBack'});
          $("#Unused.scrollable").navigator();

          $("#Used.scrollable").scrollable({easing: 'easeOutBack'});
          $("#Used.scrollable").navigator();

          $(".scrollable input[type='checkbox']").live('click',function(){
                var package=$("input[name='multiInput-module-0-Selected']").val();
                $("input[name='multiInput-module-0-Selected']").val('');
                $(this).closest('.scrollable').find("input[type='checkbox']").each(function(index, Element) {
                  if($(this).attr("checked")==true){
                        if(package==''){var c=''}else{var c=','}
                        package+=c+$(this).val();
                  }
                });
                var api = $("#Used.scrollable").data("scrollable");
                api.addItem($(this).closest('.img').clone()).end();
                $(this).closest('.img').remove();
                $("#Unused.scrollable").removeData();
                $("#Unused.scrollable").scrollable().navigator();
                $("input[name='multiInput-module-0-Selected']").val($.trim(package));
          });
          $("ul.tabs").tabs("div.panels > div.panel");
    });

and the html

Used images

Add an image

Used

          <input type='checkbox' value='/uploads/siteTheme/headerimages/1.jpg' checked='checked'/>
          T

          <input type='checkbox' value='/uploads/siteTheme/headerimages/2.jpg' checked='checked'/>
          T

Unused

              <input type='checkbox' value='/uploads/siteTheme/headerimages/1 - Copy.jpg' />

              <input type='checkbox' value='/uploads/siteTheme/headerimages/2 - Copy.jpg' />

I'm sure it's something simple.. some workaround.. just not finding it or getting it yet :D  thanks for the help.. Cheers-Jeremy


text:
Q: Django - replace parts of urlfield I can now load single video URLs of youtube. But the problem now is to load the playlist videos of youtube. So my question is, how do I replace two same pattern, but both having different replacements of a url?
Eg:
Actual url:

Replace the pattern to become like this:

Here the first & changes to ? and the second & and its following contents i.e. &index=1 are stripped.
This is the models.py:
class Video(models.Model):
    title = models.CharField(max_length=100)
    video_url = models.URLField(max_length=100)

    def save(self, *args, **kwargs):
        new_url = (self.video_url.replace("watch?v=","v/"))
        super(Video, self).save(*args, **kwargs)
        if new_url:
            self.video_url = new_url

Edit:
def save(self, *args, **kwargs):
        new_url = re.sub('watch\?v=','embed/',self.video_url)
        new_url = re.sub(r'^(http:\/\/)([\w\W]+)\&list=([\w\W]+)(\&index=[\d]+)$', r'//\2?list=\3', new_url)
        if new_url:
            self.video_url = new_url
            super(Video, self).save(*args, **kwargs)

A: First of all, it seems to be that your url is encoded. Please check if you don't have |urlencode filter in your template (https://docs.djangoproject.com/en/dev/ref/templates/builtins/#urlencode).
To change video URL to playlist URL, you have to use regular expressions. You can create a method which will transform your video URL to playlist URL:
import re
...
def playlist_url(self):
    """
    Generates a playlist URL
    """
    new_url = re.sub(r'^(http:\/\/)([\w\W]+)&list=([\w\W]+)(\&index=[\d]+)$', r'//\2?list=\3', self.video_url)
    return new_url
...

A: You can use HTMLParser.unescape function for unescaping url:
>>> import HTMLParser
>>> h = HTMLParser.HTMLParser()
h.unescape("http://www.youtube.com/embed/1UiICgvrsFI&list=PLvAOICvbvsbnc5dLG0YR9Mq_tFfzAhQSp&index=1")
'http://www.youtube.com/embed/1UiICgvrsFI&list=PLvAOICvbvsbnc5dLG0YR9Mq_tFfzAhQSp&index=1'


text:
Q: chromium api c# doesent play local videos I have made a chromium based win form browser, and it works fine! i can watch youtube videos in it, browse face book, but i can not get the video tag working at all! it works if its on public websites, but not localy...
The html file containing the  tag works fine in chrome, just not on my chromium based browser... any ideas???
I have tried open source video players like after glow and video.js, and they dont work either...
here is my html file.
<!DOCTYPE html>
<html>
  <head>

  <style> html,body
    {
    width: 100%;
    height: 100%;
    margin: 0%;
    padding: 0%;

    }
    </style>
  </head>

  <body>
        <video autoplay="true" width="1920" height="1080" src="G:\StuffUsuallyOnTheCDrive\Videos\2018-05-18 09-35-57.mp4" type="video/mp4"></video>
  </body>
</html>

i mean, it works in chrome so i expect it to work in my broweser... but it doesent.

A: *

*For local files you need to use the file:// protocol (versus the http:// protocol for online files).

*If there is spaces in the URL (path) then you must signal that space with a %20 code.
Example: my video file.mp4 becomes this path in web environment my%20video%20file.mp4. Fix your video filename path 2018-05-18 09-35-57.mp4. It has a space...
Try:
<body>
    <video autoplay="true" width="1920" height="1080" src="file:///G:/StuffUsuallyOnTheCDrive/Videos/2018-05-18%2009-35-57.mp4" type="video/mp4"></video>
</body>


text:
Q: Laravel application homepage is under Public directory I have set up my first Larevel application on WampServer on my local machine under the directory 'laravel', When I type localhost/laravel it takes me to the file structure as shown below. I can only get to the homepage of the application when I type in localhost/laravel/public.

Here is my routes.php file:
Route::get('/', function () {
    return view('welcome');
});

Route::auth();

Route::get('/home', 'HomeController@index');

How do I configure my application to make the welcome page the root? Am I missing something here? Surely there is an easier way to do this than having to edit the .htaccess?

A: Try this:
/.htaccess
RewriteEngine on
RewriteRule (.*)$ /laravel/public$1 [R=301,L]

A: Somewhere in the apache config files you have a
<DocumentRoot "/path/to/laravel">

You should change this to
<DocumentRoot "/path/to/laravel/public">

For security reasons only a few files are 'put online', but public/index.php will still do everything you want.
After you have done this, make sure your .htaccess file is correct. If you don't your routes will not work properly.
Options +FollowSymLinks
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

As shown here in the laravel 5.1 doc's. Not sure why they left it out in 5.2...


text:
Q: Preventing QGIS to Add XYZ Tiled Layer I have created tiles of raster datasets using TileStache. After creating those tiles i have uploaded them in S3 Bucket, and now serving them in my web application as TiledLayer ({z}/{x}/{y}.png)
I have built CORS on the S3 Bucket as well. But the problem is QGIS does not take CORS headers into account, and i can simply create XYZ Tiled Layer with the bucket URL  of the Network from application.
How can i prevent QGIS to add my TiledLayer service. We can build the username and password on it, but that will be exposed in the network as well.


text:
Q: Sum up multiple excel rows I tried to sum up multiple rows excluding Hour and Date row, But i get the error as
"Value Error: cannot join with no overlapping index names"
Exact data
Hour    Input   Date    Total   DA  DB  CA  CB  X   Y   Z   Z1  Z2
0   A   9/23/2021   14570   6816    636 6821    297 14213   335 9   13  0
0   B   9/23/2021   147864  63746   10186   63746   10186   147821  0   42  1   0
1   A   9/23/2021   126681  63180   191 63178   132 126606  34  36  5   0
1   B   9/23/2021   33119   1   16558   1   16559   33106   0   13  0   0
2   A   9/23/2021   11550   5398    653 5395    104 10991   549 2   8   0
2   B   9/23/2021   25197   0   12599   0   12598   25176   0   21  0   0
3   A   9/23/2021   259 0   157 0   102 204 55  0   0   0
3   B   9/23/2021   14379   0   7189    0   7190    14347   0   32  0   0

Required output
Hour    Input   Date    Total   DA  DB  CA  CB  X   Y   Z   Z1  Z2
0   A   9/23/2021   162434  70562   10822   70567   10483   162034  335 51  14  0
1   A   9/23/2021   159800  63181   16749   63179   16691   159712  34  49  5   0
2   A   9/23/2021   36747   5398    13252   5395    12702   36167   549 23  8   0
3   A   9/23/2021   14638   0   7346    0   7292    14551   55  32  0   0

I used the following script:
column_list = list(df_output)

column_list.remove('Hour')

df_output = df[df_output].sum(axis=1)

A: IIUC use:
df_output = df.groupby(['Input','Date'], as_index=False).sum()


text:
Q: profile JavaScript in chrome? I am the first one in my office trying to profile java script. So there is no guidance for me.
The question may be present on StackOverflow already. But those answers are not satisfied me. That's why I made a new thread.
Can any one tell me how to profile the JavaScript in my java application in Chrome?
I found such links that how to profile JavaScript. But this is not clear for me to get a good start up. The URLs are:

*

*http://coding.smashingmagazine.com/2012/06/12/javascript-profiling-chrome-developer-tools/

*https://developers.google.com/chrome-developer-tools/
Can any one suggest me a good tutorial or blog to get better startup or you can say your own way to profile JavaScript in Chrome.
Good answers are definitely appreciated.Thanks .

A: Surprisingly, I've tested few profiling tools and I find IE profiler (inside the build-in dev tool) be the best to start. Its easy, quite reliable. Good thing about it is that IE engine is a lot slower than Chrome so it's easier to pinpoint slow and heavy code (since you will have seconds rather than milliseconds of execution time).
If you want sth more hardcore then I would advise Ajax DynaTrace
It's full-featured software (not free though).
Chrome profiler is just weird in my opinion and while a lot of people probably use it successfully I never get any satisfactory info from it.
To enable IE Profiler:

*

*Open IE browser.

*Press F12 (developer tool shows up)

*Go to Profiler Tab.

*Hit Start profiler (My browser is in polish, but it will say something
like it).

*Do something on your page.

*Hit Stop profiler.

Now you can either show results as all Functions or as Execution tree
The Tree is cool thing you want to use, because it will show you all separate (in context) execution stacks (like let's say a REST call). Now you can expand the tree and go to all the way down deep to see which functions on this stack take the most of the time.
Be aware that some functions (native) like .apply cannot be expanded to see whats inside (profiler will tell you that).
Functions view will just show all the functions that profiler found, their execution time and count (so you can which one is called the most time and what overall time it took).


text:
Q: python module variable not mutable as a function_default I need to unit-test a python module by changing a default in the head of the application module called process.py. The declared default is a fixed int. I could change it to use something else from os.environ, but I was hoping to simply assign the global, but clearly I am missing some comprehension around 'def'.
process.default_timeout_secs = 2

# --name: process

default_timeout_secs = 120

def call_process(cmd, timeout=default_timeout_secs):
    print 'run:', cmd, 'timeout:', timeout
    ...

# --name: test_process
from nose.tools import *
import process

@ raises(TimeoutExpired)
def test_process_run_modified_default():
    process.default_timeout_secs = 5
    run(sleep 10)

I understand from other posts, that the process.call_process.func_defaults value for default_timeout_secs is not the one in the top of the module when the module is imported. How do I change the default used in the function?

process.default_timeout_secs = 5
      process.call_process.func_globals['default_timeout']
          5
      process.call_process.func_defaults
          (120)

Out[21]: 5
>>> process.call_process(cmd)

Out[22]: call_process: cmd= sleep 2 timeout= 120       <----- 120?
         Executing cmd sleep 2 verbose=True

The output should show exception TimoutExpired.

A: Function defaults are evaluated at definition time, not call time (see "Least Astonishment" and the Mutable Default Argument).
The only way to access and modify the function defaults are through its __defaults__ property (func_defaults in older versions):
>>> def f(a=5):
...     return a
>>> f.__defaults__
(5,)
>>> f.__defaults__ = (99,)
>>> f()
99

Note that __defaults__ is a tuple so you cannot assign its members individually, but you can assign it as a whole.

A: d = list(process.call_process.func_defaults)

In [10]: d
Out[10]: [True, True, 120]

In [11]: d[-1] = 5

In [12]: d
Out[12]: [True, True, 5]

In [13]: t = tuple(d)

In [14]: t
Out[14]: (True, True, 5)

In [15]: process.call_process.func_defaults = t
process.call_process('sleep 8')

call_process(cmd, verbose, shell, timeout, **kwargs)
     94         except:
     95             print(str(c.getName()) + 'running cmd "'+ cmd+ '" could not be terminated')
---> 96         raise TimeoutExpired('calling '+cmd)
     97     else:
     98         return c.response

TimeoutExpired: calling sleep 8

In [17]: call_process result: 0 :--:-None-:

A: Concerning your original question about changing a default for testing purpose, you might want to use a dictionary which is a mutable object. See my answer there for details.


text:
Q: Remove the blank item from ListBox The ListBox/Dropdown list use a external datasource(sharepoint list) as a datasource to populate the items. But there is one problem, the first item is a blank item, can we remove it?
Best Regards,

A: I have solved this problem.
http://www.jdxyw.com/?p=590

A: If you are using .net 3.5 you could use some LINQ to filter out the empty ones:
var ds = from SPListItem item in GetListItemsCode()
         where item.Title != string.Empty
         select item;


text:
Q: Assembly Language:Can physical address be 16 bits in segmented memory model? I am working on a University assignment of Assembly language related to memory addressing.Can physical address be 16 bits? Following are the values provided by instructor.
BX=0x0000
SI=0x01A2
DS=0x0A2E

Effective Address:
EA = Base + Index + Offset
    = 0x0000+0x01A2+0xFF00
    =0x100A2
    = 0x00A2

Physical:
=Segment * 10 + EA
=0x0A2E * 10 + 0x00A2
= 0xA382 (16 bits)

Is it correct because physical memory address has to be 20 bits long.

A: Leading Zeros
A physical address in a x86 processor in 16-bit-mode is in fact 20 bit long. In your example the leading zeros have been cut away.
0x0A2E * 0x10   = 0x0A2E0
       + 0x00A2 = 0x0A382
                = 0xA382

So the address 0A2E:00A2 points to the same memory cell as 0000:A382.


text:
Q: Configure path to PowerShell console in Cygwin Emacs I have Emacs running via Cygwin istall. In Emacs I have installed (via package-install) powershell package; however, when I run M-x powershell I get the following error:

Searching for program: no such file or directory, c:\windows\system32\WindowsPowerShell\v1.0\powershell.exe

The problem here is that instead of c:\windows\system32\WindowsPowerShell\v1.0\powershell.exe the path to PowerShell.exe should be /cygdrive/c/windows/system32/WindowsPowerShell/v1.0/powershell.exe
My question is: how do I configure package powershell to point to the right path?

A: You can set the variable powershell-location-of-exe, either directly with setq in your .emacs file:
(setq powershell-location-of-exe "/cygdrive/c/windows/system32/WindowsPowerShell/v1.0/powershell.exe")

or through M-x customize-option.

A: Here is how I do it. It handles different cygwin drive prefixes (I have mine set to / in /etc/fstab):
(when (eq system-type 'cygwin)
  (setq powershell-location-of-exe
        (s-trim (shell-command-to-string "which powershell.exe"))))

s-trim is from the s.el library which is available on ELPA, you will need to add (require 's) at the top of your .emacs if you don't already have it. It is necessary because which seems to return a string with a trailing newline, though there is probably a built in Emacs function to get rid of that, I don't know it :-(


text:
Q: How to add line (manual min/max allowed value) to boxplot I'm trying out to visualize some measurement data in a boxplot using the: boxplot(x,g) command in MATLAB. There's a manual giving a minimum and maximum allowed value. How can I add this value to the boxplot like in the painted screenshot below?

A: You can do the following (after you use boxplot):
max_bounds = [2 3 2]; % set the maximum bound by category
min_bounds = [-1 -2 -1]; % set the minimum bound by category
x = repmat(1:numel(max_bounds),[2 1]); % make x values for all categories
x = bsxfun(@plus,x,[-0.1; 0.1]); % make the lines in length of 0.2
hold on
% plot it all:
plot(x,repmat(min_bounds,[2 1]),'r',x,repmat(max_bounds,[2 1]),'r')


text:
Q: Replace background image for retina ready devices I have a background image that looks fine in windows operating system but it looks cloudy and stretched in retina ready devices. Now I want to replace the background with a high resolution image in retina ready devices.
What is the best way to implement that? Either media queries or using javascript or anything else?

A: You can generally target high DPI (Dots Per Inch) displays using Media queries like this:
@media only screen and (min-device-pixel-ratio: 2) {
    /* high-DPI stuff here */
}

Just be aware that this will target anything that meets the ratio requirement.
If you want to target Retina displays specifically, you'd need to add something to make the media query more  specific. Here's how Chris Coyier does it:
@media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) {
    /* Retina-specific stuff here */
}

All these different targeting methods have different levels of support, so it's useful to know a few.
There may already be several devices that meet these conditions, so you could target it another way by using extra conditions to make it even more specific.
For example, to target the Retina iPhone 5/5S/5C for example, you could use this:
@media (-webkit-min-device-pixel-ratio: 2) and (width:640px) and (orientation:portrait) {
    /* Retina-specific stuff here */
}

@media (-webkit-min-device-pixel-ratio: 2) and (width:1136px) and (orientation:landscape) {
    /* Retina-specific stuff here */
}

But as always, it's not recommended to target specific devices, it's a never-ending workload.


text:
Q: É possível criar um serviço 100% na nuvem para assinar documentos com certificado digital? Minha ideia, bem resumida, é fazer upload de um arquivo no navegador, onde o navegador irá pedir para o usuário selecionar o certificado e, assim, o site retornará o documento assinado.
Li neste tópico uma forma de fazer com C# e asp.net usando o iTextSharp, que funciona dentro do Visual Studio em debug, mas quando coloco no servidor ele não funciona. Retornando o erro abaixo:

Message: A sessão atual não é interativa. | HResult: -2146233079

Entendo que é porque, no meu código, ele tenta abrir os certificados que estão instalados localmente na maquina, mas eu gostaria de usar o certificado do cliente que está acessando o site.
Tentei então, usar da maneira descrita abaixo, já que meu IIS exige um certificado SSL na conexão para ser acessado:
//Recuperar dados do certificado selecionado pelo cliente no handshake
var Certificate = Request.ClientCertificate.Certificate;
X509Certificate2 cert = new X509Certificate2(Certificate);

Porém, quando uso o método para assinar o documento, passando esse certificado como parâmetro, me é retornado o erro:

Message: No private key. | HResult: -2147024809

O que faz sentido, já que a chave privada não deve ser compartilhada na internet.
Enfim, tudo que li até agora indica que eu terei que ter pelo menos um plugin instalado no computador do cliente, para pegar a chave privada e fazer a assinatura.
Existe alguma alternativa? Qual seria a melhor forma de fazer?

A: Eu também tenho o mesmo problema. Estávamos usando applets, mas essa solução é horrível por várias  razões e a principal e mais recente é que a partir da plataforma Java 9 (SDK e JRE), as applets se tornaram obsoletas, principalmente porque empresas de navegadores como a Google e a Mozilla resolveram descontinuar o suporte a plugins NPAPI (flash, Java, etc.).
Para nossa sorte, existem muitas soluções em JavaScript que podem cobrir a distância entre um smartcard no computador do cliente (ou outro dispositivo do cliente) e o browser. No entanto, a principal solução é escrita em C++, o FireBreath.
Você pode dar uma olhada na WebCrypto API da W3C.
Existem recomendações sobre assinatura de documentos online no sentido de se evitar tal forma de assinatura, porque quando o navegador se conecta ao leitor de smartcard, abre algumas brechas de segurança.
Algumas aproximações para assinatura de documentos com o certificado do cliente envolvem a criação de aplicações nativas que rodam no dispositivo e não no navegador. Como exemplo da DigiCert.
Eu ainda estou estudando soluções, mas já tenho um ponto de partida.