Set Theory as it Relates to Number Systems?

Question: I've been referred to this website, hopefully you have the
background in set theory to help me out here.
Got two questions, the first is on number systems arising out of set theory
and the second is a small one about functions. I've tried to be as clear as
possible but please bear with me; the only reason I'm posting this is because
I'm so confused.
I'm trying to get my bearings on the set-theoretic construction of the
natural numbers. Just as I was confused looking at the the way the reals
could be axiomatically defined, or constructed by Cantor or Dedekind, or
thinking that Cauchy, Weierstrass etc... all had different constructions so
now am I going through that with the various explanations of the natural
numbers as originating from set theory.
The Peano axioms can be taken as the starting point, but I found out that
they could be taken as a theorem in set theory, so I've been trying to do
that. It seems that one way is to look at the idea of an ordinal which is a
transitive set whose elements are also transitive. But there's also this
idea of equivalence classes that apparently lead to contradictions in ZFC.
Also there's the Axiom of Infinity method in the wiki link I've given below.
Perhaps there's even more, or these are the same in some way I can't
see?
A problem arises for me as I've come to believe that rational numbers are
defined as a set of equivalence classes, but Wikipedia says that
equivalence classes are ruled out of axiomatic set theory so what replaces
Q when dealing with ZFC? When you remove equivalence classes from the
picture what defines the rational numbers in ZFC? I'm sure whatever you
do will generalize to the reals.
I think the question could best be put as follows:
Starting from the most fundamentals, i.e., the axioms of a specific model of
set theory, what is the logical and linear progression of topics that leads to
the construction of  $\mathbb{N}$, then $\mathbb{Z}$, then $\mathbb{Q}$, then $\mathbb{R}$, then $\mathbb{C}$? It seems to me
that there are at least two possible methods this way, one using Von
Neumann ordinals (with an axiom of infinity?), while the other uses the ideas
of relations/equivalence classes etc... If you know anything about how to
do this & understand the distinctions between the various methods of
doing this could you just let me know, hopefully with a few analogies!
As an aside, I just read earlier that the difference between the Riemann &
Lebesgue integrals can be explained by the analogy of a shop taking in
money, the Riemann integral adds the money up as it comes in all through
the day while the Lebesgue integral separates the coins out at the end of
the day according to a certain scheme (i.e. the idea of measure).
I'm sure there exists a nice way to picture the two (or more) schemes for
constructing the number systems! (I read this earlier & I had to mention
it as it would just be so helpful!).
I think equivalence classes originated with Frege & Russell used them but
they run into contradictions which ZFC surmounts but Quine's set theory
removes the contradictions & allows the use of equivalence classes. I'm
sure there is more than just the use of equivalence classes that
distinguishes these two seperate constructions. Is it fair to group this
into Frege/Russell/Quine on one side & ZFC-Neumann on the other?
What about the axiom of infinity description in the wiki link below?
Also, I assume that the construction of the number systems in the
"Elementary Set Theory with a Universal Set" link below is just the
Frege-Quine idea right, I mean it's not another new one is it?
Some links might be helpful for reference of what I'm talking about:

Definition of ordinal number (from Wikipedia).
A Tour through Mathematical Logic by Robert S. Wolf. On page 77, notice at the top of the page they say that $\in$ is a "well-founded relation".
My knowledge of Naive set theory tells me that $\in$ is one of two undefinable constructs that you're supposed to take as given (I could quote the sources of this if needed), but here they call it a relation. Surely they don't mean relation in the subset of the cartesian product way do they? If it is a relation why would naive set theory call it undefinable when NST deals in defining what relations are?

Wikipedia's article on the set-theoretic definition of the natural numbers.
Wikipedia's article on the Axiom of Infinity. Notice here they've used something totally different (I think?) to
construct the natural numbers, the axiom of infinity. There is no
mention of ordinals in this link.
Elementary Set Theory with a Universal Set (in PDF format), by Holmes and Randall, 1988.  (Surely not a different construction, it's the Frege one right?).

So, that is the current state of my thoughts on this topic, it's taken me a
quite a while to figure this meagre stuff out & to find good sources which
aren't at the graduate level to learn properly. If I hadn't read all this
conflicting stuff I'd be happy to just use the following sources as my
main material:

Videos on the fundamentals of mathematics by Bernd Schröder.
Foundations of Mathematical Analysis by J.K. Truss (in Google Books).
Ali Nesin's Set Theory Notes.

Basically if you could help me clean up my thoughts as regards the above
stuff I've written, i.e. 3 different constructions 1) ZFC, 2) Frege
Equivalence Relations, 3) Axiom of Infinity & the ∈ relation statement
then I could move on to greener pastures!

My second question is brief, just on the topic of a function. First a function
is the idea of $y = f(x)$ in school. Then a function is the same thing with
domains and ranges. Then you see that a function is really a special case
of a mapping $f\colon A \to B$ defined by $f\colon a \mapsto f(a)$.
But the latest thing
I've read is that a function is really a set $(A,B,F)$ which is also written as
$((A,B),F)$, & I assume it's to indicate order, i.e. a Kuratowski ordered pair,
and $F$ is really $F \subseteq A \times B$. This is obviously a relation & it's dictated by
the rule [
$$\forall(a\in A)\exists(b\in B)\Bigl( (a,b)\in F\wedge \bigl(f(a)=b\bigr)\Rightarrow (a,b)\in F\Bigr).$$
I'll admit that's not exactly clear, if it's possible to clean this up & clarify it
please let me know. For example, where has the little $f$ come from?
The general idea here makes a lot of sense & seeing as math is always
employing set theory I wish they'd just use this notation from the
beginning in books.
So the question is, is this the final resting place for the definition of a
function? Could you clean this up for me? Could you give me some
references where this definition is explained more clearly, I can't find
anything other than a mention on wikipedia & the Ali Nesin set theory
notes in the link I've given above.
Thanks so much, I know it's asking a lot of your time!
Comment: @sponsoredwalk: Why are you concerned with these foundational technicalities? Only because they are mentioned in passing in Wikipedia? That's not the best place to look for solid expositions on number systems. Instead, see a good textbook, e.g. Ebbinghaus et. al. Numbers. The size considerations that are mentioned in Wikipedia are really of no concern when performing the "small" constructions of N,Z,Q,R. If your primary interest is the number systems  (vs. set-theory and associated foundational matters) then these technicalities can be safely ignored for the time being.
Comment: Given the length of what you wrote, it would help if you used formatting to make the actual questions more apparent. I stopped reading half-way without finding them...
Comment: Just as a comment, ZFC has no issues with equivalence relations, per se.  That is, ZFC can think of $\mathbb{Q}$ as equivalence classes of pairs elements of $\mathbb{Z}$, which is thinks of as equivalence classes of pairs of elements in $\mathbb{N}$.  The problem only arises when the "set" of elements in an equivalence class is not actually a set - it's too large or too pathological or whatever.
Comment: If you keep reading you'll see I sum up everything at the end.
The point is that I have to convey the confusion I feel with
regard to this issue because the various issues are exactly
what has me confused! If I could have boiled it down to an
easy question I'd understand it & not need to post lol,
if you re-read it all you need focus on is the last paragraph
and clarify the details in the body of the post should you
need to :)
Comment: The discussion of this topic in this link: ---

wikipedia.org/wiki/Ordinal_number#Definition_of_an_ordinal_as_an_equivalence_class

--- is what has me confused about the particular issue of equivalence classes. Am I to believe that equivalence relations/classes are used in both the Neumann/ZFC formulation as well as the Quine-Frege system? If so that takes away my worries about constructing Q & R from some unknown methods but I'm sure there is a characteristic distinction between both strutures, if anyone could clarify the details it would be extremely helpful!
Comment: I agree with Bill.  If you are really interested in this subject you should find a textbook.
Comment: @sponsoredwalk: You really should not have two disparate questions in the same question. The second half (about functions as triples) should have been posted as a separate question, though I've answered it here. If you really thought there should be some connection between the two, you could have linked to this question from the latter. Also: what you did with the links was ill done; if there is a limit to the links you can post, did you wonder why that is? As it was, you made it impossible for people to follow them easily, essentially forcing them to do the work you were not willing to do.
Comment: 1: I gave links as background material to the things I was saying just as an aid to the curious reader in case I'd confused them. It makes sense seeing as this question originates out of my confusion in the first place but the links are irrelevant if I am understood, the "access forbidden" link works fine for me.

2: The question about functions is not dispirate, I was asking about the set-theoretic definition of a function & since my question was asking about different models of set theory I just thought it was natural someone would point out any difference in the Frege use of a function to
Comment: the Neumann use, I see that I didn't make that explicitly clear, I thought it but should have put it in clearer.
I merely seperated that part off to highlight it's importance as an outgrowth of the possibly differing explanation of the usage of a function I was afraid existed, obviously not.

Let me repeat, I said at the very start I was confused as hell about this particular topic & apologised IN ADVANCE for forcing anyone to due undue work, accusing me of not being willing to do the work just isn't fair seeing as I'd mentioned in advance that I was aware I'd written a confusing post.
Comment: I'm very greatful for the helpful responses & to you for cleaning up my post, I originally wrote it on another forum with clean links but couldn't do it on this site, nor figure out how to use LaTeX. I did wonder why there was a limit to the links but when you're asking a serious question that relies on 5-6 sources in those links what am I to do? If I hadn't linked to them I'd be goaded (again) for the size of my post or some other triviality, I didn't expect that on here. Accusing me of not being willing is just not fair, if I wasn't willing I wouldn't have posted this.
Comment: @sponsoredwalk: I have never encountered any problems with putting "too many links"; I suspect the problem is how you were trying to add them. The access problem seems fixed now, so I modified that. But the second question, about functions, *is* separate and independent from the first question. It should really have been done as a separate question; as I said, you can link to previous questions if you want to provide some background.
Comment: All excellent suggestions for texts on your list-particularly the Wolf book. His references will be more then adaquate to give you proper direction.
Answer: Your definition of function is incorrect.
The idea of a "function-as-an-ordered-triple" is the following: to describe a function, we must describe three things: the domain, the codomain, and the rule by which each element of the domain is assigned an element of the codomain. In this setting, we say two functions are equal if and only if they have the same domain, the same codomain, and the same value at every point in the domain.
(Note that we don't always abide by these conventions; for example, we often think of the functions $f\colon\mathbb{R}\to\mathbb{R}$ and $g\colon\mathbb{R}\to[0,\infty)$ given by $f(x)=g(x)=x^2$ as "the same", even though the have different codomain; but in order to be able to talk about "surjective functions", the codomain is important).
So a function requires you to specify three things: the domain, the codomain, and the rule. The rule is a special kind of relation between elements of the domain and elements of the codomain, so it is a subset of the cartesian product of the domain and the codomain. If the domain is $A$ and the codomain is $B$, then the function will be a subset $F\subseteq A\times B$. Not every relation will do, however. What are the two properties that distinguish a function from an arbitrary relation? They are:

Every element of the domain $A$ must have an image in $B$.
Each element of the domain $A$ has only one image in $B$.

Translating this into logical formulas, we have:

$\forall(a\in A)\exists(b\in B)\Bigl( (a,b)\in F\Bigr)$.
$\forall(a\in A)\forall(b,b'\in B)\Bigl( \bigl((a,b)\in F\wedge (a,b')\in F\bigr)\rightarrow (b=b')\Bigr)$.

When we write $F\colon A\to B$, we mean that we are looking at a triple of the form $(A,B,F)$ with $F\subseteq A\times B$ and which satisfies 1 and 2 above. When we write $F(a)=b$, we mean that $(a,b)\in F$.
The first condition says that every element of $A$ has at least one image; the second says that every element of $A$ has at most one image.
Given this, we can define "function from $A$ to $B$" as:
Definition. Let $A$ and $B$ be sets. A function $F$ from $A$ to $B$ is an ordered triple $(A,B,F)$, with $F\subseteq A\times B$ such that
$$\forall(a\in A)\exists(b\in B)\Bigl((a,b)\in F\Bigr)\wedge \forall(a\in A)\forall(b,b'\in B)\Bigl( \bigl((a,b)\in F\wedge (a,b')\in F\bigr)\rightarrow (b=b')\Bigr).$$
Under this definition, two functions $(A,B,F)$ and $(X,Y,G)$ are equal if and only if $A=X$ (same domain), $B=Y$ (same codomain), and $F=G$ (same pairs; hence, same value at every element of the domain).
Comment: This is a very clear explanation of the ordered triple & it's motivation, thank you. I must press you further if you'll allow me, in the definition of a binary relation I tend to think of the picture of a mapping going from elements in set A to elements in set B by an arrow mapping elements. When dealing with a binary operation • the set is written as (A,•). Seeing as the relation is defined as
• := { (a,a') | (a∈A) ⋀ (a'∈A)},
is it fair to think of the set (A,•) as being the ordered triple (A,A,•)?
Comment: I say this because when you think about the set {1} it is equal to the set {1,1,1} & it just seems to make sense to me that (A,A,•) = (A,•) & you can picture it in terms of two sets A with the arrows linking elements.
Is it ridiculous to picture two sets that are exactly the same being linked in the normal way you'd picture two sets being linked with a normal mapping?
Comment: @sponsoredwalk: A binary operation on $A$ is a function with domain $A\times A$ and codomain $A$: it takes as inputs **pairs** of elements, and returns elements. For example, $+$ is a binary operation on $\mathbb{N}$: you input two numbers (the summands), and the output is a number (their sum). So as a triple, it would be $(\mathbb{N}\times\mathbb{N},\mathbb{N},+)$. As a set of ordered pairs, $+$ consists of pairs with first entry a *pair* and second entry a number; e.g., $((2,3),5)\in +$, because $+(2,3)$ (what we usually write as "$2+3$") is $5$. (cont...)
Comment: @sponsoredwalk: (cont...) There is an important difference between sets and ordered tuples. By the Axiom of Extension, $\{1\}$ is the same as $\{1,1\}$. But the ordered 2-ple $(A,A)$ is not the same as the ordered $1$-tuple $(A)$; an ordered $n$-tuple of elements of $A$ is a function from $\{1,2,3,\ldots,n\}$ to $A$ (we define ordered pairs separately to begin with, then we can use this definition).
Answer:
A problem arises for me as I've come to believe that rational numbers are defined as a set of equivalence classes, but wikipedia says that equivalence classes are ruled out of axiomatic set theory so what replaces Q when dealing with ZFC? When you remove equivalence classes from the picture what defines the rational numbers in ZFC?

If ZFC weren't capable of talking about equivalence classes it would be a pretty terrible theory.  What you probably read is something like the fact that you can't define cardinals as equivalence classes of sets under bijection, and you can't define ordinals as equivalence classes of well-ordered sets under order-preserving bijection.  In both cases the problem is that the thing you're trying to take equivalence classes with respect to is too big to be a set, so you can't apply the usual operations of set theory to it.  But equivalence classes on sets are perfectly well-defined in the usual way.

(Page 77, notice at the top of the page they say that ∈ is a "well-founded relation". My knowledge of Naive set theory tells me that ∈ is one of two undefinable constructs that you're supposed to take as given (I could quote the sources of this if needed), but here they call it a relation. Surely they don't mean relation in the subset of the cartesian product way do they?

The word "relation" is being used externally here rather than internally.  Given a first-order theory $T$ (such as ZFC), models of $T$ are sets equipped with certain functions and relations specified by the theory $T$ satisfying the axioms of the theory, and in ZFC there are no functions and the only relation is $\in$.  So this is not naive set theory; this is just set theory.  In set theory (as opposed to naive set theory) one must carefully distinguish between "internal" and "external" notions, and the word "relation" here is being used externally.
Comment: Yes that makes sense, I quoted the paragraph that confused me in a response a few minutes ago. I didn't understand the distinction

@Bill Dubuque, I am using more than one book to learn this theory currently I've just asked the specific questions in my post which really are about the multiplicity of theories regarding the construction of the number systems & the post
contains my confusion about what goes where. I have no problem
learning the axiomatic theory from Suppes & Stoll & Truss but
none of these books, from my browsing, have answered the questions in my post above.
Answer: As regards your second question about the definition of a function: Not only is it true that for every a in A, there exists b in B s.t. (a,b) in F, it is more strongly the case that there exists a /unique/ b in B satisfying that constraint (hopefully this will work, I'm still learning the markup language here):
∀(a∈A)∃(b∈B) ((a,b)∈F ∧ ∀(x∈B)( (a,x)∈F ⇒ x=b)
This allows us to then use f(a) as well-defined notation for a unique b in B for each a in A.


No-ip works for non-internal clients, pinging works internally

Question: I'm having a really bizarre problem while using No-IP. I can access the server fine from clients not on the local network and local and remote clients can ping the server just fine. I get the same results using our No-IP name as well as the current IP address directly.
This has completely baffled me - any help would be greatly appreciated.
Answer: You're trying to access a server on your LAN by using a public IP address (or a name that resolves to a public IP address) that's assigned to your LAN's edge firewall. That fact that it's working from outside the firewall, but not inside, makes me think that your firewall's NAT implementation is probably to blame.
When that doesn't work, the usual cause is that the edge firewall doesn't support "hairpin NAT" or "hairpinning". This, basically, means that the edge firewall isn't capable of receiving a request from its LAN port bound for the IP address assigned to the WAN port and "turning it back around" to the LAN. Many NAT devices do support this, but many also don't. What kind of NAT / edge firewall device are you using?
If you determine that your edge firewall doesn't support hairpin NAT a second-best choice is to create a DNS zone on your LAN DNS server corresponding to the public name of the server, but resolving the server to a LAN IP address. Clients on the LAN will resolve the server's public name as a LAN IP address (since they're using the LAN DNS server), but Internet clients (who don't have access to your LAN DNS server or, indeed, even know about it) will continue to resolve the server's public name to the public IP address.
Comment: this is a known issue with most of the Cisco firewalls I've dealt with (PIX & ASA).
Comment: Thanks a lot - it's a [very] small office setup here, and we just have a home-style DSL modem at the edge, which fortunately has an option to add DNS entries.
Comment: @Shadow: If you've got a local server machine (or a PC that is powered-on in a stable and predicable manner) you might go the route of running a local DNS server (and possibly DHCP server if your edge firewall is doing DHCP and won't support passing out an DNS server IP address other than the ISP's DNS servers). There are several no-cost and open source DHCP and DNS server offerings that you could run (on Windows, even!). I *suppose* you could modify the HOSTS file on each PC, too, but I'd never actually recommend that...


Making a gulpfile: getting an error when call gulp.parallel

Question: I'm working through the book Getting Started With Gulp (which was published in January 2015) but I realize that because development with Gulp is moving quite fast it may be slightly out of date already.
Here is my gulpfile:
// Modules & Plugins
var gulp = require('gulp');
var concat = require('gulp-concat');
var myth = require('gulp-myth');
var uglify = require('gulp-uglify'); // newly added
var jshint = require('gulp-jshint'); // newly added
var imagemin = require('gulp-imagemin');
// let's add two node.js modules:
var connect = require('connect');
// var serve = require('serve-static');
var browsersync = require('browser-sync');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var plumber = require('gulp-plumber');

// Tasks
// styles task
gulp.task('styles', function(){
    return gulp.src('app/css/*.css')
    // now we add our pipes:
        .pipe(plumber())
        .pipe(concat('all.css'))
        .pipe(myth())
        .pipe(gulp.dest('dist'));
});

// scripts task
gulp.task('scripts', function() {
    return gulp.src('app/js/*.js')
        .pipe(jshint())
        .pipe(jshint.reporter('default'))
        .pipe(concat('all.js'))
        .pipe(uglify())
        .pipe(gulp.dest('dist'));
});

// images task
gulp.task('images', function() {
    return gulp.src('app/img/*')
      .pipe(imagemin())
      .pipe(gulp.dest('dist/img'));
});

// browsersync Task:
gulp.task('browsersync', function(cb) {
    return browsersync({
      server: {
        baseDir:'./'
      }
    }, cb);
});

// browserify Task:
gulp.task('browserify', function() {
    return browserify('./app/js/app.js')
      .bundle()
      .pipe(source('bundle.js'))
      .pipe(gulp.dest('dist'));
});

// watch task:
gulp.task('watch', function() {
  gulp.watch('app/css/*.css',
   gulp.series('styles', browsersync.reload));
  gulp.watch('app/js/*.js',
   gulp.series('scripts', browsersync.reload));
  gulp.watch('app/img/*',
   gulp.series('images', browsersync.reload));
});

// Default Task
gulp.task('default', ['styles', 'scripts', 'images', 'browsersync', 'browserify', 'watch']);

EDIT:  After changing the final gulp.task line, it runs but I still get the following error:
[13:51:21] Starting 'watch'...
[13:51:21] 'watch' errored after 146 μs
[13:51:21] TypeError: undefined is not a function
    at Gulp.<anonymous> (/Volumes/BigMan/Code/javascript/gulp-book/gulpfile.js:79:9)
    at module.exports (/Volumes/BigMan/Code/javascript/gulp-book/node_modules/gulp/node_modules/orchestrator/lib/runTask.js:34:7)
    at Gulp.Orchestrator._runTask (/Volumes/BigMan/Code/javascript/gulp-book/node_modules/gulp/node_modules/orchestrator/index.js:273:3)
    at Gulp.Orchestrator._runStep (/Volumes/BigMan/Code/javascript/gulp-book/node_modules/gulp/node_modules/orchestrator/index.js:214:10)
    at Gulp.Orchestrator.start (/Volumes/BigMan/Code/javascript/gulp-book/node_modules/gulp/node_modules/orchestrator/index.js:134:8)
    at /usr/local/lib/node_modules/gulp/bin/gulp.js:129:20
    at process._tickCallback (node.js:355:11)
    at Function.Module.runMain (module.js:503:11)
    at startup (node.js:129:16)
    at node.js:814:3

Comment: What version of gulp?
Comment: The version is 3.8.11
Answer: I'm reading the same book and found it extrange that it doesn't work. I noticed all you had to do was to update Gulp to 4.0
Why isn't it working
In order to accomplish the parallel and series feature from Gulp, you must install Gulp 4.0
How to install
Global installation
npm uninstall gulp -g
npm install gulpjs/gulp-cli#4.0 -g

or
yarn global add gulpjs/gulp.git#4.0

From within your project
npm uninstall gulp
npm install gulpjs/gulp.git#4.0 --save-dev

or
yarn add gulpjs/gulp.git#4.0

I also found a bunch of tutorials talking about the new features from Gulp 4.0
I'm assuming this is because the book was written with the upcoming features in mind. I think that sometimes it cannot be assumed that the project will move as fast. What I still don't understand is the difference between gulp.parallel and just passing an array.
http://fettblog.eu/gulp-4-parallel-and-series/
One more thing:
In gulp4 you must specify parallel/series for the watch task:
gulp.task('watch', function() {
    gulp.watch('app/css/*.css', gulp.parallel('styles'));
    gulp.watch('app/jss/*.js', gulp.parallel('scripts'));
    gulp.watch('app/img/*', gulp.parallel('images'));
})

Comment: Interesting.  Here is the [migration guide](https://github.com/gulpjs/gulp/issues/861) for version 3.x to 4.0 where you can read up more on the usage of `parallel`.
Comment: gulp-cli does not have 4.0 version, gulp does. We need upgrade only gulp. Rest of the comment is accurate.
Comment: I'm not sure there is any reference of gulp-cli in the comments or the request except for the npm install for gulpjs. Your comment can be confusing for other people trying to figure this out. For some reason at the time of writing this  gulpjs/gulp-cli#4.0 helped install the right version.
Answer: I'm not sure where the gulp.parallel or gulp.series is coming from but you should be able to accomplish the same thing by changing your code to this:
// watch task:
gulp.task('watch', function() {
    gulp.watch('app/css/*.css', ['styles', browsersync.reload]);
    gulp.watch('app/js/*.js', ['scripts', browsersync.reload]);
    gulp.watch('app/img/*', ['images', browsersync.reload]);
});

gulp.task('default', ['styles', 'scripts', 'images', 'browsersync', 'browserify', 'watch']);

As far as I can tell .series and .parallel don't exist. Once I made those updates it works.
If you need to run tasks in series, I have had good luck with this module: https://github.com/OverZealous/run-sequence. You would change your watch task to this:
var runSequence = require('run-sequence');

// watch task:
gulp.task('watch', function() {
  gulp.watch('app/css/*.css', runSequence('styles', browsersync.reload));
  gulp.watch('app/js/*.js', runSequence('scripts', browsersync.reload));
  gulp.watch('app/img/*', runSequence('images', browsersync.reload));
});

Comment: .series and .parellel are in Gulp version 4. These will render run-sequence obsolete.
Comment: It's a year and a half later and there's still no sign of Gulp 4 on npm.
Comment: I changed my code and while gulp runs, it is now giving me the error that is in my updated question.
Comment: Thank you.  I'm new to Gulp (node.js in general) and I really need to spend some time on streams


Convert MM:SS string to HH:MM:SS in C#

Question: I have this piece of code which works nicely to convert HH:MM:SS to seconds as an integer.
  for (int i = 0; i < nrdaily.Rows.Count; i++)
  {
      double NRT = TimeSpan.Parse(nrdaily.Rows[i][3].ToString()).TotalSeconds;
      nrdaily.Rows[i][3] = NRT;
  }

However, I have a CSV file I'm dealing with where a field has many values that are stored in MM:SS format and TotalSeconds seems to misinterpret it as HH:MM and gives a false result.
How could I check the string to see if it's in HH:MM:SS format, and if it is in MM:SS convert it to HH:MM:SS?
Answer: Use TimeSpan.ParseExact
Example:
var testString = "01:05";
TimeSpan.ParseExact(testString, "mm\\:ss", CultureInfo.InvariantCulture).TotalSeconds;
//TotalSeconds will be 65

Answer: You could check the string length for starters to identify the format.
for (int i = 0; i < nrdaily.Rows.Count; i++)
{
     string time = nrdaily.Rows[i][3].ToString();
     if (time.Length == 5)
          time = "00:" + time;
     double NRT = TimeSpan.Parse(time).TotalSeconds;
     nrdaily.Rows[i][3] = NRT;
}

Checking length is a very simplistic approach. To identify the format more accurately, you could use regular expressions.

Convert MM:SS string to HH:MM:SS in C#


how long is javascript cached by default

Question: We had a production release and there were issues due to javascript that we updated. The clients have an old cached version of the javascript file which is causing the issue. The workaround is to have them refresh their browser cache (hit F5) but Im trying to understand how long the javascript gets cached by default.
I do not see the cache-control headers or Expired header being set on the server side and I do not see those headers in the developer console in chrome. I DO see the below meta tags are set on the page. These meta tags would lead me to believe the JS is not cached - however we know it is because we have many users reporting issues and hitting F5 fixes it.
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">

So back to my original question - how long is the javascript going to be cached by default if we set no cache headers. I apologize since Im sure this question is asked elsewhere I just cant seem to find a concrete answer. Here are all the headers I can see being set:
Accept-Ranges:bytes
Connection:Keep-Alive
Content-Length:157271
Content-Type:application/x-javascript
Date:Tue, 23 Feb 2016 15:37:38 GMT
Keep-Alive:timeout=15, max=500
Last-Modified:Sat, 20 Feb 2016 10:57:45 GMT
Strict-Transport-Security:max-age=31536000; includeSubDomains
X-Content-Type-Options:nosniff

Comment: Note that the headers for the HTTP *page* that includes the `
Comment: http://stackoverflow.com/questions/2869800/how-long-are-files-usually-kept-in-a-browsers-cache your answer given here
Comment: If those are the response headers for the HTTP request made for the JavaScript source, then the browser might keep it forever. There are no headers to set an expiration date, no "if modified since" header, etc.
Comment: @Onur yes, though this OP might want to ask the more useful question, "How do I control how long JavaScript files are cached?", since (judging by those headers) nothing's being done right now.
Comment: you can use Cache-Control and Expires  headers for this
Comment: no my original question is the question I intended to ask. I know how to add cache headers. The problem is the old javascript is already cached on clients machines and need to find out how long since the old javascript is throwing exceptions.
Answer: Im aware of how to add cache headers. We have a production issue affecting many clients. For a large site its no small thing to migrate the fix to production.  I am trying to find out how long the browser cached by default because that is how long the issue will exist for our clients before the browser will naturally refetch the newer version of the javascript if we do not migrate the fix. For instance if it was 2 days then the issue would already have cleared itself up without us taking action.
Seems like the answer was right in front of me though. There are no cache headers but the below tag seems to be saying cache forever regardless of the no-cache meta tags right before it.
<meta http-equiv="expires" content="0">

So we have to do a production migration and add cache busters to all our javascript to fix the issue or keep telling every client to refresh the page.
Comment: That `` tag is not in your javascript files I presume? It only affects the HTML resource it is included in.
Comment: The first paragraph of your answer sounds like it should go in the question.


PHP class vs function

Question: Quando e por que devo usar uma class ao invés de uma function simples em PHP?
Por exemplo, eu tenho uma função que executa a inserção de um histórico no banco de dados, que é uma função comum a muitas outras.

funções.php
<?php
function insereHistorico($idUsuario, $descricao) {
    $sql = "INSERT INTO historico (id, descricao) VALUES ($idUsuario, $descricao)";
}

arquivo.php
<?php
function adicionaUsuario() {
    //Executa todo o processo aqui
    //...

    //Insere no log
    insereHistorico($idUsuario);
}

Mas também sei que a mesma função poderia ser uma classe, deste modo:
funções.php
<?php
class FuncaoClass {

    public function insereHistorico($idUsuario, $descricao) {
        $sql = "INSERT INTO historico (id, descricao) VALUES ($idUsuario, $descricao)";
    }
}

arquivo.php
<?php
function adicionaUsuario() {
    //Executa todo o processo aqui
    //...

    //Insere no log
    $funcao = new FuncaoClass;
    $funcao->insereHistorico($idUsuario, $descricao);
}

O que me parece ser vantagem no uso de classe é ter um código mais organizado, mas como não sou usuário avançado em PHP, não sei quais as principais diferenças ou considerados a respeito desse comparativo.
Apenas para dar o contexto, eu uso PHP para gerenciar o backend de WebSites/WebApps, onde uso AngularJS para chamar essas funções e gerenciar o banco de dados. Normalmente as funções semelhantes ao exemplo do arquivo.php me retornam dados (lista de usuários, notícias, pedidos, etc.) enquanto que as funções como a do exemplo do arquivo funções.php servem para fazer algum gerenciamento comum a múltiplas funções.
Answer: A principal caracteristica da orientação a objeto é juntar ou arramar, a estrutura de dados (geralmente um tipo definido pelo programador) classe, com comportamentos (métodos). Algumas linguagens forçam isso como por exemplo o java, onde não é possível definir uma método/função sem dono (classe), o php permite misturar classes/objeto com funções o que pode ser uma vantagem em alguns casos.
Vantagens da utilização de classes:

Permite de forma simples agrupar e compartilhar elementos (propriedades) entre métodos.
Métodos podem guardar o estado do objeto.
Oferece um escopo intermediário entre variáveis globais e locais, comparado a funções e um código estruturado.

Vantagens da utilização de funções:

A chamada de uma função tem sua execução atomica ou seja a ação é realizada ou não, geralmente não possui/guarda estado, o que é bom para códigos onde se tem acessos concorrentes pois não precisam lidar com sincronizações.
Comment: Outra e mais fácil de detectar são aquelas classes genéricas (práticamente um repositório de funções) que fazem de tudo ou seja falta coesão, uma classe deve apenas ter uma responsabilide (resolver um tipo de problema) e seus métodos devem fazer sentido no contexto. No php é possível agrupar funções por namespace.
Comment: @GuilhermeCostamilam acredito que não. Deve ter alguma diferença mas deve ser pequena no caso do PHP esse tipo de otimização não tem muitos ganhos. Quando você chama um método pode trabalhar com os atributos da classe/objeto (pegar/manipular seus valores atuais ou já acumulados)  e após isso os atribuidos ainda vão existir e ter valores. Já depois da chamada de uma função todas as suas variáveis locais serão destruidas.
Comment: Mas então usar um ou outro, ou até mesmo o uso de ambos em um mesmo projeto não teria nenhum impacto direto, correto? Seria mais relacionado a uma estrutura de código do que a um "melhor método" entre um ou outro. Lógico, sem levar em consideração os pequenos detalhes, como o que você mencionou, por exemplo `Métodos podem guardar o estado do objeto`.
Comment: @CelsomTrindade isso mesmo questão de estrutura, na hora de optar por um ou outra pode se perguntar: preciso guardar estado? isso trás algum benefício? ter um escopo (de váriavel) intermédiario trás algum benefício? é desejável? Uma situação estranha é quando vc tem um objeto e maioria dos métodos pedem argumentos e retorna algum valor mas não armazena estado (por algum motivo) esse é um bom motivo para resvisar a classe, será que utilizar funções não seria melhor e pq? continuar a classe pq? ... continua.
Comment: Compreendi. Hoje, no estado atual da minha aplicação, não tenho nenhum caso que seja necessário guardar estado, todas as funções executam algum processo e retornam um valor. Exemplo, criar um link a partir de um id e uma variável, então poderiam ser todos apenas funções. O que gostei do uso de classe é ter uma visão mais clara de onde aquela função está sendo chamada, pois teria algo assim: `ClientClass::carregaCliente()`, por exemplo.
Comment: @rray existe alguma diferença em relação a segurança (já que funciona como um encapsulamento, me corrija se estiver errado)? E de performance (criar uma classe deve gerar mais gastos de recursos do que apenas criar variáveis/funções)? E o que seria "guardar estado"?

PHP class vs function


UIAutomation script not running on device

Question: For some reason, UIAutomation doesn't want to run on my physical device. I've gotten to run once, but otherwise when I kick it off, it simply sits there reporting "Script has stopped".
I've checked the following:

Using a developer profile to code sign
Several different cables, including a first party Apple one
Restarting my Mac and the iPad
Cleaning and rebuilding

Other instruments work just fine, I can run allocations and leaks without any issue, automation just refuses to run.
Answer: I had the same problem and then (eventually) figured it out.
Turns out the build has to be a DEBUG build so that instruments can attach to it.  I edited the scheme build settings for "build for profiling" so that it would build a DEBUG build rather than a RELEASE build and things started working.


Intraweb for iphone, how to keep the webbrowser hidden

Question: I've just written my first app in intraweb (control pack for the iphone)
It works, but after several hours I still cannot get the iphone to not show safari.
I've added a link to my homescreen and I start the (web)app from there and things start out ok.
But when I change a page safari shows up and breaks the look I'm an iphone app® magic and eats up 25% of my screen.
The intraweb documentation says this is due to the fact that the webadres changes (parameters in the url), so I switched to hidden fields, but to no avail.
How do I make sure my iphone webapp stays full screen and never goes to safari?
Comment: You should consider asking this question to TMS.
Answer: It works for me, and I suggest you ask in the TMS Software newsgroups, with steps to reproduce this behaviour, so they can look into it (which will give you a better chance of solving the issue that asking here, to be honest)...


Não consigo extrair dados de uma coluna específica

Question: Meu DataFrame possui várias colunas e uma delas não está sendo lida quando eu tento usar a indexação (ex.: bar_0617 = media_0617['Bar']). Aparece o seguinte erro: KeyError: 'Bar'. Não sei o que fazer, pois eu já conferi no arquivo com meus dados e a coluna possui este nome, na hora de calcular a média também aparece o nome certinho, mas quando vou indexar para percorrer os seus dados dá erro. Agradeço desde já" Segue o código
<code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

file = r'C:\Users\Jonat\OneDrive\Documentos\Faculdade\LAMCE\dadostratados1718.csv'
table = pd.read_csv(file, sep = ';')

#2017
table_2017 = table.query('ANO==2017')

#Cada mês
table_0617 = table_2017.query('MES==6')
table_0717 = table_2017.query('MES==7')
table_0817 = table_2017.query('MES==8')
table_0917 = table_2017.query('MES==9')
table_1017 = table_2017.query('MES==10')
table_1117 = table_2017.query('MES==11')
table_1217 = table_2017.query('MES==12')

media_0617 = np.mean(table_0617)
media_0717 = np.mean(table_0717)
media_0817 = np.mean(table_0817)
media_0917 = np.mean(table_0917)
media_1017 = np.mean(table_1017)
media_1117 = np.mean(table_1117)
media_1217 = np.mean(table_1217)

time = ['0617', '0717', '0817', '0917', '1017', '1117', '1217']
time = pd.DataFrame({'Tempo': time})

bar_0617 = media_0617['Bar']
bar_0717 = media_0717['Bar']
bar_0817 = media_0817['Bar']
bar_0917 = media_0917['Bar']
bar_1017 = media_1017['Bar']
bar_1117 = media_1117['Bar']
bar_1217 = media_1217['Bar']

bar = [bar_0617, bar_0717, bar_0817, bar_0917, bar_1017, bar_1117, bar_1217, bar_0118, bar_0218, bar_0318, bar_0418, bar_0518, bar_0618, bar_0718, bar_0818, bar_0918, bar_1018, bar_1118, bar_1218]
bar = pd.DataFrame({'Bar': bar})

serie_bar = pd.concat([bar, time], axis=1, join='inner')   #Pressão

plt.plot(serie_bar['Tempo'], serie_bar['Bar'])        #Pressão
plt.title('Pressão x Tempo', fontsize = '20')
plt.ylabel('Pressão (hPa)')
plt.xlabel('tempo')
plt.rcParams['figure.figsize'] = (11,7)
plt.savefig(r"C:\Users\Jonat\OneDrive\Documentos\Faculdade\LAMCE\variáveis\serie_bar.png", dpi=None, facecolor='w', edgecolor='w',orientation='landscape')
plt.show()
</code>
Answer: Ele simplesmente não identificou a coluna Bar nas variáveis media... Você tem certeza que essa coluna existe? Tem como vc disponibilizar esse dataset ou usar um dataset.info() para ver como ele é composto?


com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.example.yehezkiel.eclassapp.DaftarTugas

Question: I already tried many solving code in the stack overflow but its still error yet. Please help me
firebase database structure :

This is tugas firebase structure, its doing well. But still dont have name from its parent. So i want to add them

error code:

E/UncaughtException: com.google.firebase.database.DatabaseException:
  Can't convert object of type java.lang.String to type
  com.example.yehezkiel.eclassapp.DaftarTugas
                           at com.google.android.gms.internal.zzelw.zzb(Unknown Source)
                           at com.google.android.gms.internal.zzelw.zza(Unknown Source)
                           at com.google.firebase.database.DataSnapshot.getValue(Unknown Source)
                           at com.example.yehezkiel.eclassapp.TwoFragment$1.onDataChange(TwoFragment.java:90)
                           at com.google.android.gms.internal.zzegf.zza(Unknown Source)
                           at com.google.android.gms.internal.zzeia.zzbyc(Unknown Source)
                           at com.google.android.gms.internal.zzeig.run(Unknown Source)
                           at android.os.Handler.handleCallback(Handler.java:742)
                           at android.os.Handler.dispatchMessage(Handler.java:95)
                           at android.os.Looper.loop(Looper.java:157)
                           at android.app.ActivityThread.main(ActivityThread.java:5555)
                           at java.lang.reflect.Method.invoke(Native Method)
                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:745)
                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:635)

DaftarTugas.java
package com.example.yehezkiel.eclassapp;

    /**
     * Created by Yehezkiel on 7/12/2018.
     */

    public class DaftarTugas{
        private String judul_tugas;
        private String deskripsi_tugas;
        private String tanggal_kumpul;
        private String tanggal_tugas;
        private String nama_matkul;

        public DaftarTugas(String nama_matkul,String judul_tugas, String deskripsi_tugas, String tanggal_kumpul, String tanggal_tugas) {
            this.nama_matkul = nama_matkul;
            this.judul_tugas = judul_tugas;
            this.deskripsi_tugas = deskripsi_tugas;
            this.tanggal_kumpul = tanggal_kumpul;
            this.tanggal_tugas = tanggal_tugas;
        }

        public DaftarTugas() {

        }

        public String getNama_matkul() {
            return nama_matkul;
        }

        public void setNama_matkul(String nama_matkul) {
            this.nama_matkul = nama_matkul;
        }

        public String getJudul_tugas() {
            return judul_tugas;
        }

        public void setJudul_tugas(String judul_tugas) {
            this.judul_tugas = judul_tugas;
        }

        public String getDeskripsi_tugas() {
            return deskripsi_tugas;
        }

        public void setDeskripsi_tugas(String deskripsi_tugas) {
            this.deskripsi_tugas = deskripsi_tugas;
        }

        public String getTanggal_kumpul() {
            return tanggal_kumpul;
        }

        public void setTanggal_kumpul(String tanggal_kumpul) {
            this.tanggal_kumpul = tanggal_kumpul;
        }

        public String getTanggal_tugas() {

            return tanggal_tugas;
        }

        public void setTanggal_tugas(String tanggal_tugas) {

            this.tanggal_tugas = tanggal_tugas;
        }
    }

my TwoFragment :
 for(int i = 0;i<obj2.size();i++){
            mataKuliahRef.child(obj2.get(i)).child("name").addValueEventListener(new ValueEventListener() {
                @Override

                public void onDataChange(DataSnapshot dataSnapshot1) {
                    tugas = dataSnapshot1.getValue(DaftarTugas.class);
                    mAdapter.notifyDataSetChanged();

                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });

            mataKuliahRef.child(obj2.get(i)).child("tugas").addValueEventListener(new ValueEventListener() {

                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    listTugas.clear();
                    if (dataSnapshot.exists()) {
                        for (DataSnapshot dataHasil : dataSnapshot.getChildren()) {
                            final String idTugas = dataHasil.getKey();

                            Log.e("Yhz2", idTugas);

                            daftarTugasRef.child(idTugas).addListenerForSingleValueEvent(new ValueEventListener() {
                                @Override
                                public void onDataChange(DataSnapshot dataSnapshot2) {
                                    tugas = dataSnapshot2.getValue(DaftarTugas.class);
                                    listTugas.add(tugas);
                                    mAdapter.notifyDataSetChanged();
                                }

                                @Override
                                public void onCancelled(DatabaseError databaseError) {

                                }
                            });

                        }

                }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
        }

I want to add 2 difference value to 1 adapter, this one got error when i add value from child.("name"). The main problem is here I think :
mataKuliahRef.child(obj2.get(i)).child("name").addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot1) {
        tugas = dataSnapshot1.getValue(DaftarTugas.class);
        mAdapter.notifyDataSetChanged();

    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});

Comment: Please add your database structure.
Comment: @AlexMamo done sir
Comment: So basically what are you looking for? You want to have a list of `DaftarTugas` objects? Or you want a list of string property like `name` or `day`?
Comment: I just want to add name to the DaftarTugas, daftar tugas have name, deskripsi_tugas,judul_tugas,tanggal_kumpul,tanggal_tugas. There are deskripsi_tugas,judul_tugas,tanggal_kumpul,tanggal_tugas already doing well. So i want to add 1 more to that java class which is name from another database
Comment: the main problem is the recycler view is doing well to populate data from tugas. But i want add 1 more child from its parrent which is name to the RecyclerView
Comment: Have you tried to add that `name` as a property of your `DaftarTugas`?
Comment: @AlexMamo Sure, i hv been update the code. Please check
Answer: the error message reads Can't convert object of type java.lang.String to type com.example.yehezkiel.eclassapp.DaftarTugas ...which might be the result of trying to parse .child("name") (which probably would return nothing but a String) into class DaftarTugas.
one can instance without parsing (difficult to tell while not knowing what is actually being returned):
DaftarTugas item = new DaftarTugas();
item.setName(tugas);
tugas.add(item);

or add one constructor, which accepts only the name.
Comment: that code itsnt encountered a problem. It doing well,and can apear in my recycler view. The problem is the one before that.
Comment: @YehezkielL updated the answer, hence I mistook to direction of the wrongful cast at first... and maybe check out https://developer.android.com/studio/debug/ once.
Comment: So what's the solution sir? I did log the datasnapshot1,and its gave me the correct result. But idk why it was not send to the daftartugas
Comment: you didnt give me the solution sir
Comment: @YehezkielL there's nothing to add.


Atualizar quantidade de like/deslike com JQuery

Question: Eu estou tentando atualizar o valor de um elemento span (aumentar ou diminuir) sempre que o botão de like é clicado.
Importante: O código a seguir cria outro elemento  só que com o id #unlikeBtn ao invés de #likeBtn quando o botão é clicado..
_create: ->
      self = this
      $(@element).css('display', 'block').css('width','100%').css('height', '36px').removeClass('like-button').addClass('like-button-widget')
      @templates =
        notLiked: '''

        '''
        liked: '''

          '''

Quero atualizar o valor da contagem automaticamente toda vez que o usuário clicar no botão para curtir ou descurtir, mas a função só funciona na primeira vez. Se eu der deslike em seguida, não funciona. Somente quando eu atualizo a página e clico para descurtir o valor é atualizado.

$(window).load(function() {

  $('#likeBtn').click(function() {
    $('#likesCounter').html(function(i, val) { return val*1+1 });
  });

  $('#unlikeBtn').click(function () {
    $('#likesCounter').html(function(i, val) { return val*1-1 });
  });

});

  click

1

Como faço para atualizar sempre sem ter que atualizar a página?
Comment: Executando o seu código no próprio site do Stack Overflow está funcionando.
Comment: O que acontece é que falta um pedaço de código em coffescript que cria outro elemento com o id #unlikeBtn, mas se eu clicar pela segunda vez nesse botão o valor da contagem não diminui.
Comment: Você poderia postar o código que está faltando?
Comment: Vou atualizar a pergunta.
Comment: Adicionando eventos em elementos criados dinamicamente não funciona mesmo. Já sofri bastante com isso. Adiciona o evento num elemento fixo e da foco no dinamico: assim $(body).on(''click", "#elementotal", function());
Comment: Cara não entendi a sua pergunta, ele está funcionando
Answer: Elementos dinamicamente carregados não aceitam a adição de um listener diretamente. Adicione o mesmo ao elemento pai, ou em qualquer outro fixo da tela da seguinte forma:
 $("body").on("click", "#Seuelemento" function(){
     //Faça o que quiser
})


Quero testar meu site teste no meu tablet e queria saber como

Question: Queria testar diretamente em um dispositivo mobile, para tirar minhas duvidas !
Comment: O chrome tem uma opção de testar como se estivesse em um dispositivo móvel. Mas se quiser testar diretamente no dispositivo, qual é o problema? Não é só abrir o site?
Comment: Dê mais de como está seu ambiente. Seu site está em uma rede local? Na internet? Que dificuldades está tendo?
Comment: acho que a pergunta está na fronteira do "fechar" ou "aceitar".. então marquei um positivo para equilibrar..
Comment: Rodrigo meu site está no wampserver !
Comment: Não precisa colocar resolvido no título, basta aceitar a resposta(marcar o sinal verde),  [Como e por que aceitar uma resposta?](http://meta.pt.stackoverflow.com/a/1079/91)
Comment: jeferson o meu site abre no navegador, mas queria testar diretamente no meu tablet.
Answer: Digite o IP da sua máquina.
MAC
Se sim, vai em Preferências de Sistema e Rede. Veja seu IP.
Digite o IP na barra de endereço do navegador no tablet.
http://192.168.1.4/nome_do_site
Windows
Entra no CMD (Prompt de Comando), digite ipconfig.
Procure seu IP.
Digite esse IP no navegador do tablet:
http://192.168.1.4/nome_do_site
Comment: Talvez seja necessario configuarar o apache para receber requests externos. A ideia é essa mesma, pois o servidor wamp e o tablet devem estar na mesma rede, acredito eu.
Comment: Então Mano... Isso que eu estou falando... Você vai acessar seu PC por IP...
Comment: @rray, eu acho que o **wamp** já vem assim... mas é verdade. Não falei nada da rede, acho que é o mínimo.
Comment: mas meu site está no servidor wampserver no meu pc
Comment: valeu, vou testar aqui
Answer: Você pode verificar o design responsivo diretamente no seu navegador chrome sem baixar nem acessar nenhuma aplicação especifica:
Com o seu site aberto:
Pressione F12 ou clique com o botão direito do mouse e depois selecione inspecionar elemento, note que logo acima na barra pequena existe um icone de um celular, clique nele e atualize a pagina. (em vermelho)
Apos fazer isso note que do lado esquerdo existe uma pequena lista de dispositivos para você testar, basta clicar no nome e selecionar o modelo do aparelho.(em verde)

se quiser verificar algum tamanho/aparelho exato que não esteja listado você pode clicar, segurar e arrastar as bordas para ajustar o tamanho.
Comment: @GilmarSantos se puder marque ao lado que a resposta ajudou e esta correta.
Comment: valeu pela ajuda
Answer: Olá pode ser feito pelo mas algumas vezes não fica perfeito.
Eu gosto muito de usar esse aqui, tem os dispositivos principais em termos de resolução..
http://mobiletest.me/ipad_mini_emulator/?u=http://papoinformal.com.br
Se precisar acessar do seu Wamp faz o seguinte.
Entendi agora. Nesse caso vamos lá. Conecte a mesma rede ( seu pc e seu tablet ), ou na mesma wifi. Quando você cria um Wamp server ele cria um IP na sua rede para o seu site ( APACHE ). Siga essas instruções para divulgar isso para outros dispositivos na mesma rede. (http://www.seucurso.com.br/index.php?option=com_content&view=article&id=343:como-configurar-o-wamp-para-receber-acessos-externos&catid=907:internet&Itemid=71 )
Tenha em mente que sua pasta c:/wamp/www é igual a localhost ou igual ao IP do seu computador. Então se colocar em uma pasta como /meusite no browser localhost/meusite
Comment: Entendi agora. Nesse caso vamos lá. Conecte a mesma rede ( seu pc e seu tablet ), ou na mesma wifi.

Quando você cria um Wamp server ele cria um IP na sua rede para o seu site ( APACHE ). Siga essas instruções para divulgar isso para outros dispositivos na mesma rede. (http://www.seucurso.com.br/index.php?option=com_content&view=article&id=343:como-configurar-o-wamp-para-receber-acessos-externos&catid=907:internet&Itemid=71)
Comment: Tenha em mente que sua pasta c:/wamp/www é igual a localhost ou igual ao IP do seu computador. Então se colocar em uma pasta como /meusite no browser http://localhost/meusite
Comment: Gilmar Ajuda o casta baixa aqui dá um up na minha resposta vou colocar informações adicionais.
Comment: Gostei desse site, mas, queria testar diretamente em meu tablete ! O meu site teste esta no server wampserver.
Comment: Valeu pela ajuda me ajudou muito !


Why are my Three.js objects displaying at the same time and not individually?

Question: I have two 3d models I'm trying to switch between. Currently I can click a button after the first page load to display either of the two 3d objects, but when I try to switch between them they always load both objects at the same time.
How do I fix this?
<code>$(".choice:not(a)").click(function(){

    // get the id of chosen item

    let id = $(".chosen").attr("id");
    id = id.match(/\d+$/)[0];

    let item;

        // change variables for id

        if(id == 1){

            item = 'first.mtl';
            objects = 'first.obj';

        }else if(id == 2){

            item = 'second.mtl';
            objects = 'second.obj';

        }

        // Problem is here they keep loading at the same time.

            new THREE.MTLLoader()
            .setPath( 'models/obj/' )
            .load( gun, function ( materials ) {
                materials.preload();
                new THREE.OBJLoader()
                    .setMaterials( materials )
                    .setPath( 'models/obj/' )
                    .load( objects, function ( object ) {
                        object.position.y = 0;
                        scene.add( object );

                            object.visible = botonsON;

                    }, onProgress, onError );

            } );

   });
</code>
Comment: if you want i can fix that for you but you have to provide a jsfiddle
Answer: Your code is working as intended. All visibility properties of your objects share the same boolean botonsON. If its true you are just displaying all of them. You are also loading models every time the user switches which is pointless. I suggest you load the objects once, add them to the scene and save to some variables. Make one of them not visible at the start. Whenever user clicks simply do
<code>object1.visible != object1.visible
object2.visible != object2.visible
</code>


Problema radius no Android

Question: Deixei o formato arredondado, porém quando Clico no botão ele retorna para o formato padrão:

após o click o botão fica quadrado novamente:
Comment: Bom dia. Você precisa incluir o código responsável por essa interação, apenas olhando assim não será possível te ajudar.
Answer: Boa! Está utilizando app:cornerRadius ? Utilizo desta forma e funciona da api 21 até a 28 (apis testadas no app em questão)
<code><Button
    android:id="@+id/btnEntrar"
    android:layout_width="280dp"
    android:layout_height="wrap_content"
    android:padding="12dp"
    android:text="@string/entrar"
    android:backgroundTint="@color/colorOrange"
    android:background="@color/colorOrange"
    android:textColor="@color/colorWhite"
    app:cornerRadius="20dp"
    style="@style/Widget.AppCompat.Button.Colored"
    android:theme="@style/AppTheme.Button"/>
</code>

Problema radius no Android


Jointly distributed random variables-Statistics

Question: Suppose that $X$, $Y$, and $Z$ are jointly distributed random variables, that is, they are defined on the same sample space. Suppose that we also have the following.
$$E(X)=5 $$
$$E(Y)=-3 $$
$$E(Z)=-7 $$
$$Var(X)=49 $$
$$Var(Y)=32 $$
$$Var(Z)= 47 $$
Compute the values of the expressions below.
E(-2Z-4)=
E((5z-3X)/4))=
Var(5Y+2)=
E(-5Z^2)=
I tried to substitute 1.$$E(-2Z-4)= -2(-7)-4=10$$ Is this format correct?
Please Help!
Comment: I tried one, is it correct or wrong?
Comment: @Naam2 For the formats: just put $ at the beginning and end of each expression. I did some for you.
Answer: $E(-2Z-4)= -2(-7)-4=10$ is right because
$$E(-2Z-4)= E(-2Z) +E(-4)$$
$$-2E(Z) +E(-4)$$
$$-2E(Z) +(-4)$$
$$-2E(Z) -4$$
$$ = -2(-7)-4=10$$
The other two that have only $E$ and not $Var$ are similar. For the $Var$, use the rule that
$$Var(aY+b) = a^2Var(Y)$$


Double-nested Routing

Question: Currently I have Steps which belong to Procedures:
map.resources :procedures, :has_many => :steps

And this works fine for me, I get URLs that look like /procedures/3/steps/5.
However, suppose I wanted to add one more layer, Figures that belong to steps, to get this: /procedures/3/steps/5/figures/1
That being a monster of a URL aside, how exactly would I do the routing for this?
Edit: Maybe I shouldn't put that aside, should I do this? Figures are simply containers for images which I will display in the Steps, so it's not like the user will actually "visit" any Figure, I just need to fetch the images from the Figures.
Comment: Just so you know, URI representations are orthogonal to REST. Furthermore, if you have a different URI for a subset of the same resource (and using the same media type) then you're probably violating a constraint of REST. For figures that belong to steps, something along the lines of /figures/1?step=5 might be better.
Answer: map.resources :procedures do |procedure|
  procedure.resources :steps do |step|
    step.resources :figures
  end
end

If you need routes like /figures/ then use:
map.resources :procedures, :shallow => true do |procedure|
  procedure.resources :steps do |step|
    step.resources :figures
  end
end

In your views it's something like:
<%= link_to "Figure", figure_url(@procedure, @step, @figure) -%>

Answer: This blog post explains it better than I can off the top of my head.  Basically, you can use the :name_prefix option when defining your routes to acheive what you're looking for.
Comment: According to that article I should simply not do this, and do something like this instead:  map.resources :steps, :has_many => :figures.

However, suppose that the user will never actually go to the Figure, but the Figures will simply be used by Steps. Should I still separate it out or is it okay to leave it as a massive double-nested thing?
Answer: From your comment, I think you're right: you won't ever need to route to the figures... and you never want to unnecessarily over-complicate your routes.
It sounds like the furthest you'll go will be the Show action for your steps... and you'll just ask ActiveRecord for the list of figures for that step. That is, you'll have
class Step < ActiveRecord::Base
  has_many :figures
end

and
class Figure < ActiveRecord::Base
  belongs_to :step
  has_many :images #perhaps?
end

but for routing you only need to care about resources that will be RESTfully requested - in this case it looks like your procedures, and their associated steps. The route you listed in the question looks spot-on to me!

Double-nested Routing


How to get LogLiklihood value from logistic regression in R

Question: Question:

Is it possible to get log liklihood values for my stepwise glms?

Context:
I am able to get a logliklihood value using lmer with the following model. My study involves unbalanced repeated females, two sites (females don't exchange between sites), 8 predictors, and a response.
    (glmfit1 <- lmer(Response ~ 1 + SITE + (1|SITE:FEMALE) + Variable A + Variable B +
                        Variable C, data = data))

Removing the repeated females and taking out the Site factor gives me this formula.
(lrfit1 <- glm(Response ~ 1+Variable A + Variable B + Variable C, data = data))
summary (lrfit1) #just gives me p values for my variables and an AIC but NO LOGLIK.

Answer: Have you tried logLik(lrfit1)?
Comment: Wow I can't believe it was that simple. Thanks... I checked this with other models that I knew the likelihood and it is correct.


Should one-hot output encoding be used in backpropagation?

Question: I'm going through the process of writing backpropagation for a neural network.
In particular I'm building a MNIST classifier.
I'm wondering if it is better to apply the cost function and backpropagation to the non-one-hot output activation.
The advantage I see is that this will encourage all would-be-non-hot values toward 0, rather than simply being marginally less than the maximum value. Likewise, it would encourage the would-be-hot value towards 1.
An additional one-hot output layer could be applied after training to clamp the values to either 0 or 1.
Andrew Ng's machine learning course wanted me to use one-hot encoding. Do my arguments for using the raw-non-hot encoding output carry any value?
Comment: what is meant by "non one hot output"? Like [0.6,0.2,0.2] which is converted to [1,0,0]?
Comment: @nan Yes, the first I would call the raw, non-one-hot values, and the second one-hot. Please let me know if there is better terminology.
Answer: I assume that what ever is backpropagated has to be a probability distribution (the vector sum = 1). I.e., it's already been through a softmax.
It would be interesting to see which works better empirically, but I think the raw output contains more information.
Consider raw output [0.01, 0.45, 0.54].  We then convert this to [0,0,1].  Say we have truth [0,0,1].  (We really want something like [1e-10,1e-10,1-2e-10].)
If we use the one hot [0,0,1], we don't change anything. The error is [0,0,0].
If we use the raw output, however, we end up changing the weights to increase the ouput's certainty (eg, we decrease the first and second and increase the third), with error [0.01,0.45,-0.44].
This might not even be evident if we only evaluated the accuracy or ROC area for a classifier, but perhaps you would see a difference in calibration (the ability to give accurate probability estimates)--I think that the raw output would lead to better calibrated models, because by one hot encoding you are essentially removing information about numerical probabilities.


How to redirecting add to cart form in drupal commerce programatically?

Question: I just wants to redirect the add to cart form to a different page. After click on add to cart button i do not wants to go cart page. i just want to go thank you page.
for that i am altering the form
 if($form_id == 'commerce_cart_add_to_cart_form_1'){
            $form['submit']['#value'] = t("Submit Event");
            $form['#submit'][]= 'post_event_save';
    }

by using the above code i am able to redirect to post event save page but it will not stop in that page again redirect cart page after executing this post_event_save function.
what i have tried post_event_save function
drupal_goto();
$form_state['redirect'] = false;
$form_state['rebuild'] = TRUE;

by printing the form_state variable
[#validate] => Array
                (
                    [0] => commerce_cart_add_to_cart_form_validate
                    [1] => tasteusa_commerce_add_to_cart_form_validate
                )

            [#submit] => Array
                (
                    [0] => commerce_cart_add_to_cart_form_submit
                    [1] => post_event_save
                )

            [#after_build] => Array
                (
                    [0] => commerce_cart_add_to_cart_form_after_build
                    [1] => context_form_alter_node_after_build
                    [2] => test_commerce_after_build
                )

Answer: Check if you have any redirect rules enabled under admin/config/workflow/rules, which is force redirecting you to cart page.
As a solution you can have your custom redirection rule and disable the existing redirection rule, an example redirection rule which redirects to node/2 path after adding product to cart.
{ "rules_add_product_to_cart_redirect" : {
    "LABEL" : "Add Product to Cart Redirect",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "add-to-cart-redirect" ],
    "REQUIRES" : [ "rules", "commerce_cart" ],
    "ON" : { "commerce_cart_product_add" : [] },
    "DO" : [ { "redirect" : { "url" : "node\/2" } } ]
  }
}

In case you import the above remember to change the redirect path from node/2 to your thank-you page.


Logging shell command executed by all users on Linux server

Question:
Possible Duplicate:
How to log every linux command to a logserver

I want to log the commands executed by all users on the server. Is there any better way than using script command?
Comment: Why are you looking to record all commands?
Answer: A possible application to do this is rootsh. see: http://sourceforge.net/projects/rootsh/
Be careful though, you will be capturing all sorts of passwords, confidential data and other things that need to be stored in the highest security you have available. Think of what could happen if this information was captured. Also, depending on the number of users on your system there could be a lot of data.
Answer: That should be contained under history for each of the users or under /home/$username/.bash_history where $username is the name of the actual user, of course if the user home directory is not under home that it will be like /path/to/homedir/.bash_history
Comment: history -c ; export HISTFILE=/dev/null; do stuff; exit. The information only gets written to $HISTFILE when the user exits cleanly.


I need to format data from a command in unix shell scripting and put it in an array/table.I have given my command below

Question: `grep 'MOVING_DATA Phase' /tmp/$$.status | awk '{print $11}'`

this is my command and I am getting result like
"database"."table1"
"database"."table2"
"database"."table3"
.....
.....
"database"."tablen"

I want to remove the double quotes and remove the delimeter '.' and store database name and table names in an array.I would appreciate if the result is displayed in the form of a table.I am new to Unix.Please help me.
Answer: You can get rid of grep and use gsub awk function to remove " and .:
awk '/MOVING_DATA Phase/{gsub(/["]/, "", $11);sub(/\./, " ", $11);print $11}'` /tmp/$$.status

To create BASH arrays:
#!/bin/bash

tabArr=()
dbArr=()

while read -r db table; do
   tabArr+=("$table")
   dbArr+=("$db")
done < <(awk '/MOVING_DATA Phase/{gsub(/["]/, "", $11);sub(/\./, " ", $11);print $11}'` /tmp/$$.status)

Comment: I have to send the details of this database name and table name in a mail in a table format.Could you please help me how to display it as a table while sending mail
Comment: Sure you can use: **`awk '/MOVING_DATA Phase/{gsub(/["]/, "", $11);sub(/\./, " ", $11);print $11}' /tmp/$$.status | column -t`**
Comment: with some modifications i was able to remove quotes and delimit the text.`grep 'MOVING_DATA Phase' /tmp/$$.status |awk '{gsub(/["]/, "", $11);sub(/\./, " ", $11);print $11}'` but loading data into table is not working.I am getting error as no such file or directory exists.once i load data into these columns..how do i display it?
Comment: Can you let me know what is your full she'll script. So that I can investigate and suggest.
Comment: sorry for late reply..Basically what I am trying to do is get some lines from output logs, split the data into different columns like DBname, table name, size of data moved etc...all the information for these 3 columns get can be obtained from our logs using grep 'MOVING_DATA Phase' this command results something like XXXXXXXX MOVVING DATA Phase completed for XXXX "databasename"."tablename" XXXX bytes moved : 12345. now I want to get the input for my columns from this line and create a table structure which I can send over mail
Comment: Position of "databasename.tablename" is 11th and 12345 (bytes moved) is 18th from the beginning of the line.
Comment: @ManasaJ: I think these requirements need to be posted as a new question so that you can get help from all the SO experts.
Comment: But do you think it is fair to delete or un-accept after someone invests lot of time helping you out? Someone else might get benefited by this answer someday.


Proper approach to two different address data sets on the system

Question: I have a certain design problem here. The web site I'm working on will need to have 2 sets of address details

under user account, as an indication of user's business address
at the commerce checkout, as billing address

For commerce checkout I've been using built-in customer billing profile and it works ok. But I'd like to maintain a similar format for user address. The plan is to populate the billing address form during checkout with user's business address by deafult but also allow to modify billing address without changing business one
At the moment I'm concerned that I'm mixing different structures too much. I have billing profile for commerce, profile2 for users but also couple of custom fields created under Account Settings. What approach would you suggest to setup the user account fields so it's clean, easily referrable to each other and not confusing?
Answer: I'd just use Commerce Addressbook, it would allow you to have a set of addresses in your user account, from project page:

Commerce Addressbook is a module that allows authenticated customers
  to reuse previously entered addresses during checkout. They can manage
  all entered addresses in their user panel (user/%user/addressbook).

Seems exactly what you're looking for and is way less complicated that dealing with the addresses and defaults yourself.
Comment: can I somehow integrate this module with profile2 or the actual signup page?
Comment: You can add a exact structure for the address in the profile2 signup than the one you've got in your billing/whatever information and use rules to copy them over to the structure that commerce addressbook has, check out a similar feature in http://vimeo.com/33921337


Getting at net.sf.saxon.dotnet.DotNetPullProvider.next() Error in C# with Saxon

Question: I am Using Saxon-9EE for XSLT2.0 transformation in C#(Visual studio 2012). but some times getting below error while loading source document(xml size have 25MB). i tried same code for other documents(less than 10 MB) it's working well. can you please help me how to resolve it. thanks
<code>Method >>    End Copy Directory >>   3/28/2013 3:22:36 AM:857
 >>         at net.sf.saxon.dotnet.DotNetPullProvider.next()
   at net.sf.saxon.pull.PullFilter.next()
   at net.sf.saxon.pull.PullPushTee.next()
   at net.sf.saxon.pull.PullConsumer.consume()
   at net.sf.saxon.pull.PullPushCopier.copy()
   at net.sf.saxon.event.Sender.sendPullSource(PullSource , Receiver , ParseOptions )
   at net.sf.saxon.event.Sender.send(Source source, Receiver receiver, ParseOptions options)
   at net.sf.saxon.Configuration.buildDocument(Source source, ParseOptions parse
Options)
   at net.sf.saxon.Configuration.buildDocument(Source source)
   **at Saxon.Api.DocumentBuilder.Build(XmlReader reader)**
   at DocxCreator_XSL.DocxCreator.CreateDocx() in c:\Users\velagasx\Documents\Vi
sual Studio 2012\Projects\SampleProjects\DocxCreator_XSL\DocxCreator.cs:line 99
>>       3/28/2013 3:22:42 AM:745
</code>
Comment: That looks like an exception stack trace, what is the message and type of the exception?
Comment: PS: it sometimes takes us a few days to spot a Saxon-specific enquiry on this list. If you report it directly at saxonica.plan.io you'll get a quicker response.
Answer: The most simple and obvious explanation is that (a) your XML isn't well-formed (or valid), and (b) the error handling in your application is inadequate. The routine at the top of your stack trace is calling the Microsoft XML parser asking for the next event, and testing for exceptions coming from the XML parser. If it gets an exception, this should emerge at the level of Saxon.Api.DocumentBuilder.Build() in the form of a Saxon.Api.Exception; there should be some basic information here about the nature of the error, which for some reason you haven't shown us.
It's possible you would get better diagnostics if you build the document using the Apache Xerces parser (which is built in to Saxon on .NET) rather than the Microsoft parser. This would also have the benefit that the XPath id() and idref() functions work properly - they don't in the case of documents built using the Microsoft parser, because the M$ parser doesn't supply enough information to the application about the DTD.


rock drumming (swing?) pattern

Question: I've been curious about the drumming in "Someday" by The Strokes for some time now. Are the kick and snare going in double time?  Or is the tempo actually that fast and the hi hats are played in half time?  What is this style of drumming called?  Are there other examples of it?  What is the difference between the verse pattern and the chorus pattern? This song has a sort of light, swing feeling to it.  Is that because of the drumming or because of the strumming pattern of the rhythm guitar?  This song uses great chord progressions, but would not be nearly as good if played with a straight 8th note feel.
Thanks!
-286642
Comment: Rhythm guitar is not swinging at all. He's playing straight eights.
Comment: @Tim are you sure?  Please check this video (orange guitar) https://www.youtube.com/watch?v=iRZm9lzlP_M
Comment: @Tim Isn't there some swing on the upbeats? And yes, everyone is accentuating the same things the hats and bass are, so that's a good candidate for the beat. It's not that fast though?
Comment: Still sounds like straight eights to me.
Comment: Definitely swung, not straight.
Answer: There are a lot of different questions in your post. But to try to answer your doubts, this is a very simple and standard rock beat. Snare on 2 & 4, hihat on each downbeat (1,2,3,4) and bass drum on 1, 2&, 4&.

To me it does sound like there is a noticeable swing to it.
You can play around with this online drum annotation tool, I transcribed the beat. You can move the swing factor and pick one where it feels right. (I transcribed in in half time because the tool needs it like that to apply the swing correctly).
https://gscribe.com/share/MCnkPbMEhWBm3qfw5

rock drumming (swing?) pattern


white page in taxonomy terms url

Question: I am using drupal 7, when I am going to path of  terms I see only white page, no error and nothing in another page I have not this problem,
 some php properties are :
error_reporting = E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED & ~E_WARNING
max_execution_time = 360
max_input_time = 120
memory_limit = 32M
upload_max_filesize = 32M
post_max_size = 32M
mbstring.func_overload = 2
mbstring.internal_encoding = UTF-8

where is the problem? and how can I solve it?
Comment: `memory_limit` seems to me too low. Set it to minimum of 64M and check if it works then.
Comment: Is there any custom module in your website?
Comment: @JayendraKainthola No,
Comment: @ЕлинЙ. I test with memory_limit=256M but nothing happened :(
Comment: Did you restarted apache?
Comment: There is a long list of possible causes and solutions for 'White Screen of Death': https://drupal.org/node/158043 You can scan them to find out what it could be in your case.
Comment: @ЕлинЙ. the blank white page is in all of pages, but my problem is only in term path :( . also my memry_limit taked efftect I test it by checking phpinfo
Comment: @zhilevan,  Have you checked if there is any `die` or `exit` in any module file?
Comment: @JayendraKainthola , I am working with ftp of site and searching in all of content for die need time,I suggest this but dont find any die. I go to call back of term function  in `/**
 * Menu callback; displays all nodes associated with a term.
 *
 * @param $term
 *   The taxonomy term.
 * @return
 *   The page content.
 */
function taxonomy_term_page($term) {
    die('in taxonomy call back term page ,inserted here by YM for debugging');`  but after put this dont see my die , I think the problem is before  hook_menu  $items['taxonomy/term/%taxonomy_term']  . really I am confused
Comment: @zhilevan, its very confused issue as there is not a simple solution for this.
Comment: @JayendraKainthola , yes I know, I should try every solution come to my mind :(. tnx for your attention (y)
Answer: One thing to do when you get the WSOD is to turn on all error reporting to see what led up to the failure to produce output.  The error_reporting setting you show is turning of a lot of reporting.
You'll get more runtime error reporting by adding this to the start of settings.php on your site (you add it just below <?php):
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

In addition, navigate to: Administration→ Configuration→ Development → logging and errors and select All messages. This sets $conf['error_level'] = 2;.
Also, check the logs (in particular most recent log messages).
If I should try to guess, I would say you're out of memory.  Having a 32M memory_limit when running Drupal 7 does sound like a source for trouble (I've no Drupal 7 site with less than 128M).
Comment: I test this , right now , but not see any error in white page,  this problem only in taxonomy term url :(
Comment: I  set memory_limit=256M and test ,but nothing happened :(.

white page in taxonomy terms url


C# Winforms Web Browser

Question: I have created a simple program which allows me to input a location and generate a google maps link which I can view on the Web Browser module wihtin visual studio. See code below:
<code>string InvoiceQueryLocation = BackgroundLabel1.Text + BackgroundLabel2.Text;
MapBrowser.Navigate("https://www.google.com/maps/search/" + InvoiceQueryLocation + "/");
MapBrowser.ScriptErrorsSuppressed = true;
</code>
However, until about a week ago, everything worked fine until the default web browser (Chrome I think) decided it needs updating within the "webbrowser" module. Now, the maps query runs, stops for a second and then the Chrome update tab appears over it.
I have tried setting "AllowNavigation" to False, however, this stops me from clearning the results and starting anew.
Does anyone know a solution around this? Or perhaps know what I have missed?
I have tried this on multiple PC's and the same issue occurs each time.
Fixes I have tried -

Updating windows
Updating Vis studio
Updating chrome
Setting "AllowNavigation" to False
Comment: Not exactly clear (to me) what problem you're referring to, but you're still using the old (deprecated) WebBrowser Control. You should move to [WebView2](https://learn.microsoft.com/en-us/microsoft-edge/webview2/)
Answer: I faced same problem and ended up replacing web browser control with Microsoft's new WebView2 control
https://learn.microsoft.com/en-us/microsoft-edge/webview2/get-started/winforms
I have a sample application based on the above link here....
Sample Application - Use address or lat long to find address

C# Winforms Web Browser


ler arquivos pdf com php diretamente no browser

Question: Colegas. É possível abrir um arquivo PDF diretamente dentro do navegador? Tentei o file_get_contents() e o fopen(), mas ele abriu de decodificado. Então tentei dessa forma, mas ele abriu no browser inteiro:
<code>$arquivo='0eb178d150b82f5536588fbfea5fa7bd.pdf';
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="0eb178d150b82f5536588fbfea5fa7bd.pdf"');
 @readfile($arquivo);
</code>
Comment: A primeira questão é: você mandou o mime-type correto nos headers? Como você já tem um tempo de site, deve saber que se postar seu código, fica mais fácil de localizarmos os possíveis problemas.
Comment: Experimente sem a @ pra ver se dá algum erro. E não se preocupe com negativo, pois não fecha a questão. Aliás, se vc deixasse sem o código, seria normal fecharem como "não estar clara", mas isso é diferente de negativo.
Comment: Olá Bacco, tem razão, esqueci de colocar o código. Editei a minha dúvida.
Comment: Só não acho certo darem ponto negativo antes de nos manifestarmos, pois isso é caráter de urgência e fechando o tópico, atrasará quem realmente precisa de ajuda. O certo é esperarem se quem postou a dúvida irá acatar o questionamento do colega antes de darem pontos negativos.
Comment: Certo Bacco. O problema é que ele abre no browser inteiro e só preciso abrir dentro de uma div...
Comment: Bom, no ultimo edit já mudou a questão completamente. Se vc quer que façam download, troque o application/pdf por application/octet-stream, se quer abrir numa div não dá, aí só com um IFRAME ou nova janela. No IFRAME nem sei se dá, pra falar a verdade.
Comment: Alterei, mas ele pede para alterar...
Comment: Entendi...vou tentar aqui com o iframe...
Answer: <code><?php
$file = './path/to/the.pdf';
$filename = 'Custom file name for the.pdf'; /* Note: Always use .pdf at the end. */

header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
header('Accept-Ranges: bytes');

@readfile($file);
?>
</code>
Fonte: https://stackoverflow.com/questions/4679756/
Código funcionando http://triviapw.hiperportal.blog.br/wesley/pdf_in_browser/pdf.php
Comment: Desculpe, só depois de responder, vi que precisa exibir dentro da dIv. Neste caso o iframe servirá.


HTML file is downloaded twice in one file

Question: I have the following code in my controller:
<code>$finfo = finfo_open(FILEINFO_MIME_TYPE);
$file = 'myfile.html';
$contentType = finfo_file($finfo, $file);
finfo_close($finfo);

$response = new Response();
$response->headers->set('Content-Description', 'File Transfer');
$response->headers->set('Content-Type', $contentType);
$response->headers->set('Content-Disposition', 'attachment; filename='.basename($file));
$response->headers->set('Content-Transfer-Encoding', 'binary');
$response->headers->set('Expires', '0');
$response->headers->set('Cache-Control', 'must-revalidate');
$response->headers->set('Pragma', 'public');
$response->headers->set('Content-Length', filesize($file));

$response->setContent(file_get_contents($file));
$response->send();
return $response;
</code>
When I run this code on my dev computer (Mac with PHP 5.3.15) I get the file I want with its content. But when I run it on my test server (Ubuntu 12.04 with PHP 5.3.10) I still get the file, but the content is doubled (I get twice the file in one single file).
I found a way to get it to work using <code>$contentType = 'application/octet-stream';</code>
What am I doing wrong?
Comment: Please sniff the network traffic and let us know if the files data is even transferred two times within the response body.
Comment: @hakre I just ran some tests with Wireshark and the file data is "encapsuled" twice in the server response...any idea?
Comment: Okay (wow), and how does the raw protocol interaction from the client side look like? Can you add it to your question? Also please add the HTTP request as seen in wireshark to the question (just the text), and for the response (sure you don't want to post all), somehow so that it is clear what that double-data looks like with the response.
Comment: From my nose: I'm not sure if you are reading the signs correctly here. Just saying. I have never seen a duplicate send of the response body. Check if the content-length response header matches with the length of the response body. If the server answers twice (here with a static HTML file?!), this *would* mean the server is awfully broken. Not that it's not possible, but would you consider that likely?
Comment: I might be wrong, but it looks to me like the data is actually being sent twice. First time with `$response->send();` and the second time with `return $response;` . What happens when you remove the `->send()` part?
Comment: @mogoman you are right! if you create an answer I can accept it.
Comment: @hakre thanks for your help. I don't know why the behavior is different on my dev computer but I tried the code on 2 different linux servers and the ouput was the same...
Answer: I believe that these two lines do the same thing (in Symfony)
<code>$response->send();
return $response;
</code>
I suggest removing the $response->send() line.


caixa de pesquisa dentro de um select com pesquisa em banco de dados

Question: colocar

<select class="form-control">
  <option value="" selected></option>
  <option><input type="text" class="form-control" placeholder="Procurar dentro do banco de dados" name="pesquisa" id="pesquisa"></option>
</select>

como coloco uma caixa de pesquisa dentro de um select e que ele fique invisivel ate eu clicar no select e ele aparecer pera poder pesquisar no banco de dados e os resultados aparecer como options no select
Comment: Vai ter que utilizar [chosen](https://harvesthq.github.io/chosen/) ou [select2](https://select2.github.io/). Eles vão emular visualmente um select com input dentro.
Comment: Não dá pra usar um `input` dentro de um `select`. Você pode exibir o `input` no mesmo lugar do `select` ao clicar, usando javascript, mas você está fazendo uma pergunta muito complexa, você quer fazer isso, ainda pesquisar no banco, preencher o `select`... melhor fazer uma pergunta mais específica de cada vez
Answer: Antes de tudo vou deixar bem claro que não sei se entendi bem o que você quer, mas lá vai.
A explicação detalhada é meio complicada mas posso tentar ajudar.
Você vai conseguir resolver isso com javascript/jQuery.
Primeiro crie o campo de texto para iniciar a pesquisa. No jQuery configure uma função que executa a pesquisa que você desejar a cada letra digitada no campo.
(Nisso você vai usar Ajax). Em outras palavras: quando uma letra for digitada no campo, essa função do javascript será executada. A função em questão vai enviar o valor atual do campo para um script PHP que vai montar e executar a query no banco, retornando os valores possíveis.
Ao pegar esses valores basta listá-los logo abaixo do campo de pesquisa. Para isso você pode imprimí-los como lista não ordenada (
 e
). Para que ele fique visualmente agradável, trabalhe com o CSS. Caso queira algo um pouco mais trabalhado, ao invés de sua função do jQuery apenas retornar o dado bruto, envie esses dados para uma outra função que monta a estrutura de um select e, em seguida, imprima na tela (mas acho desnecessário - e menos interessante que a primeira opção - esse trabalho todo).
Além de mostrar os dados como lista, precisa criar uma função para identificar caso alguma dessas opções for selecionada. Quando o usuário clicar em uma delas, você pega esse valor e preencha o campo.
Para ajudar com o pontapé inicial, vou deixar alguns snippets que podem te nortear. No caso, simulamos que estamos buscando um nome.
Este é o campo a preencher
<input type="text" id="field" name="fullName" placeholder="Full Name">
Em algum arquivo separado, coloque:
$('#field').change(function(){
    $.ajax({
        url : './findName.php',
        type : 'POST',
        data: 'name=' + $('#field').val(),
        dataType: 'json',
        success: function(data){
            if(data.success !== 1){
                return false;
            }
        }
    })
});

O código acima vai acionar o arquivo findName.php, que será o responsável por pegar o valor recebido e executar a query no banco.
O atributo url mostra o arquivo de destino.
O atributo type representa o método que você vai usar para enviar os dados.
"Data" é o dado a ser enviado.
"Success" indica o que vai acontecer quando a requisição acontecer com sucesso.
Os resultados retornados devem ser impressos no PHP mesmo usando algo do tipo echo json_encode($nomes);
Para pegar a variável no arquivo PHP (findName.php) é fácil. Como usamos o método POST para enviar os dados:
$name = $_POST['name'];
Enfim, acho que já dá pra começar.


Composer init, cria arquivo em diretórios diferente

Question: Instalei composer, git, github na partição C:, tenho servidor apache24 e php7 inatalado na partição D:, entrei pasta htdocs/SBFC meu site do servidor na linha de comando e fiz um composer init, transcorreu tudo certo mas executar o comando dir na pasta não havia nenhum arquivo, fiz uma procura no computador achei tudo em uma pasta oculta no diretório C:, chamada de C:\VTRoot\HarddiskVolume4\WebServer\Apache24\htdocs\SBFC  com os arquivos criados conforme imagem abaixo

alguém pode me explicar o que acontece, desde já agradeço a ajuda.
Comment: achei o que estava dando errado, era meu antivírus comodo, a instalação do activerecord ia pra outra pasta chamada VTRoot,  troquei de antivirus.
Answer: achei o que estava dando errado, era meu antivírus comodo, a instalação do activerecord ia pra outra pasta chamada VTRoot,  troquei de antivirus.


What is wrong with my Centos DNS server configuration?

Question: I need to configure an contos7 DNS server. We need to do with BIND.
To check if the server works I need to ping my DNS server on the address svr1.breda.ikdoeict.
This is the configuration of /var/named/breda.ikdoeict
@       IN SOA  @ breda.ikdoeict. (
                                        0       ; serial
                                        1D      ; refresh
                                        1H      ; retry
                                        1W      ; expire
                                        3H )    ; minimum
        IN      NS      @
@       IN      A       10.123.34.123
srv1    IN      A       10.129.34.123
www     IN      CNAME   srv1

this is the configuation of /etc/named.conf
options {
        listen-on port 53 { 127.0.0.1;10.129.34.123; };
        listen-on-v6 port 53 { ::1; };
        directory       "/var/named";
        dump-file       "/var/named/data/cache_dump.db";
        statistics-file "/var/named/data/named_stats.txt";
        memstatistics-file "/var/named/data/named_mem_stats.txt";
        recursing-file  "/var/named/data/named.recursing";
        secroots-file   "/var/named/data/named.secroots";
        allow-query     { localhost;10.129.32.0/21; };
        forwarders      { 10.129.28.230;10.129.28.232;};

        recursion yes;

        dnssec-enable no;
        dnssec-validation no;

        /* Path to ISC DLV key */
        bindkeys-file "/etc/named.iscdlv.key";

        managed-keys-directory "/var/named/dynamic";

        pid-file "/run/named/named.pid";
        session-keyfile "/run/named/session.key";
};

logging {
        channel default_debug {
                file "data/named.run";
                severity dynamic;
        };
};

zone "." IN {
        type hint;
        file "named.ca";
};

zone "breda.ikdoeict" IN{
        type master;
        file "breda.ikdoeict";
};

include "/etc/named.rfc1912.zones";
include "/etc/named.root.key"

Here you can see I added the DNS to my client
student@student-ubuntu:~$ nmcli device show ens160 | grep IP4.DNS
IP4.DNS[1]:                             10.132.1.5
IP4.DNS[2]:                             10.132.1.6
IP4.DNS[3]:                             10.129.34.123

when I trie to ping svr1.breda.ikdoeict it gives unknown host.
Comment: are you sure that you are using this domain name server to resolve domain names?
Answer: Check that the resolv.conf file on the client system you are pinging from is configured with suitable nameserver directives and that the specified name servers are accessible from your client.


Countability and surjective, injective mappings

Question: I am studying famous book "Introduction to Real analysis" by "Robert G. Bartle & Donald R. Sherbert".
I saw a theorem which states that:
The following three statements are equivalent:
a) $S$ is countable set
b) There exists surjection of $N$ onto $S$
c) There exists injection of $S$ into $N$.
I want to know if theorem holds true? Is it true even if we take $S  = ∅$ where $∅$ is the empty set?
If yes, please explain me why it is true?
If not then, do b) & c) imply a), but not conversely?
Answer: You are correct that we must assert $S \neq \emptyset$. In fact, for any set $A \neq \emptyset$, there exists no function from $A$ to $\emptyset$. This is because by the definition of a function, for each $x \in A$ there would be a $y \in \emptyset$ such that $(x, y) \in f$. This is impossible, since $\emptyset$ contains no elements.


How to assign users to a group

Question: How do I assign users to a group in Drupal 7? Basically I wanted to have following groups in my website.

Administrators
Content Writer and Publisher
Registered users

I wanted to assign all of the newly registered users to "Registered users" group automatically and I as a member of administrator should be able to assign some trusted users into "Content Writer and Publisher" group.
Each of these groups will have different-2 permissions as expected.
Answer: From a permission point of view, (instead of groups) these are called "roles" in Drupal. (From a content-user-access point of view there is the Organic groups module, but that's another story.)
You can administer roles at admin/people/permissions/roles. You can mass assign users to roles at admin/people (Update options - Add a role to selected users).
All registered users automatically have a role called "authenticated user", so there is no need to duplicate that functionality.
For more info check out "Managing access control with permissions and user roles" at
https://drupal.org/node/22275
Answer: Check out Registration Role:
From the module's project page:

Registration role lets an administrator select a role to automatically assign to new users. The selected role will be assigned to new registrants.

It assigns a selected role on signup of a new user.
Answer: I use - Role field, Rules. Create field role and assign this role from Rules module.

How to assign users to a group


Is the intermediate value theorem saying that if f is continuous, then it is onto?

Question: How can I prove
if $f:\mathbb{R}\to\mathbb{R}$ is continuous and $\overline{f(\mathbb{N})} = \mathbb{R}$, then $f$ is onto (surjective)
by the intermediate value theorem?
Comment: What do you mean by the second condition?
Comment: If $\overline{f(\mathbb N)}$ means "*closure* of $f(\mathbb N)$ is $\mathbb R$" then the statement holds, but this makes for quite a convoluted function $f$. (A good topic for another MSE post: find at least one such function!) On the other hand, if $\overline{f(\mathbb N)}$ is something like *range* in which $f(\mathbb N)$ takes values, i.e. the interval $(\inf f(\mathbb N),\sup f(\mathbb N))$, then the statement still holds, and it is altogether a more natural statement - but $\overline{f(\mathbb N)}$ is not the way to write that, as $\overline{X}$ is commonly used to mean *closure* of $X$.
Answer: Yes, if $y$ in $\mathbb{R}$, there exist $n_1,n_2\in\mathbb{N}$ such that $f(n_1)<y, f(n_2)>y$. IVT implies the existence of $x\in [n_1,n_2]$ or $[n_2,n_1]$ such that $f(x)=y$.
Comment: Thanks a lot for answering my question.