Is $V$ under ZFC really a proper class?

Question: Is $V$, the union of the von Neumann hierarchy, necessarily a proper class? Or is it only a proper class after you assume that it contains every set? (In that case, $V$ can't be a "set of all sets" because the foundation axiom implies a "set of all sets" can't exist.)
Restated as an analogy: Is it actually more like $V_\omega$, whose existence can't be proved or disproved until you assume the infinity axiom?
Or am I misunderstanding the meaning of "proper class" or something more fundamental?
(I have similar questions about the collection of all ordinals.)
Comment: How do you propose to construct $V$ internally? Unions can only be taken over collections indexed by a set, and $V$ is a "union" over a collection indexed by the ordinals, which do not form a set (the Burali-Forti paradox: http://en.wikipedia.org/wiki/Burali-Forti_paradox).
Comment: @Asaf: yes, I am aware of this. The question is about all of $V$, not $V_{\alpha}$ for any particular ordinal $\alpha$.
Comment: @Qiaochu: While you are essentially correct, due to the well foundedness of the $\in$ relation one can approximate "as high rank as you want" internally, sort of how you can approximate an unbounded sequence by finite numbers high as you want. Furthermore, I think there might be something to say about that in the context of $V=L$, but I'm not completely sure and would rather to wait until Andres or Joel (or someone else who is more knowledgeable on the topic) find their way around here.
Comment: @Qiaochu: I did not doubt that for a single moment, I did mention that because other readers might not be aware of this.
Comment: @Qiaochu: Can't I postulate its existence using a first-order statement? And in that case, wouldn't I discover that the formula can be neither proved nor disproved in ZFC?
Comment: Also, I'm starting to wonder whether my question really comes down to the precise definitions of "proper class" and "not a set". By "not a set" do we usually mean "can't be proved or disproved a set", or "can be proved to not exist in first-order set theory"? By "proper class" do we mean "not a set" in the first sense, or in the second?
Comment: @Neil: no, you would disprove it. $V$ cannot be a set because it would contradict foundation (otherwise we run into Russell's paradox).
Answer: Asaf has already given a good answer to your question but I'll add a second perspective.
You don't need to assume that every set belongs to the von Neumann hierarchy, since you can prove it.  Suppose there were some set that didn't belong to this hierarchy.  Then by Foundation, there is an $\in$-minimal such set, let's call it $x$.  Every element of $x$ belongs to the von Neumann hierarchy, but $x$ itself (supposedly) does not.  But if we let $\alpha = \sup \{ \mathrm{rank}(y)+1 : y \in x \}$, it's clear that $x \subset V_{\alpha}$ and so $x \in V_{\alpha + 1}$, meaning it does belong to the hierarchy after all.
In fact, if $M$ is any transitive model of $ZFC$, it has what it thinks are the operations of power set and union, and what it thinks is the class of all ordinals, and so $M$ can construct what it thinks is the von Neumann hierarchy, and this resulting hierarchy will equal $M$.  So in particular, it'll think that its version of the von Neumann hierarchy forms a proper class.
But if $M$ were, say, the $\kappa ^{\mathrm{th}}$ level in the von Neumann hierarchy of some bigger model $N$ of set theory, where $\kappa$ is inaccessible in $N$, then $N$ will think of $M$ as a set whereas $M$ thinks of itself as a proper class.  Along these same lines, $N$ will think of $\kappa$ as some ordinal whereas $M$ will think of $\kappa$ as the class of all ordinals.  More interestingly, there will be subcollections of $M$ belonging to $N$ which aren't definable over $M$ (by a counting argument), thus they will be subcollections of $M$ which are neither sets in $M$ nor are they what $M$ would consider proper classes.
The moral is that, generally speaking, what gets considered a proper class and what doesn't depends on the context.  Given a transitive model $M$ of ZFC, a proper class in $M$ is technically a formula $\phi (x, p)$ with parameters $p$ from $M$ such that there is no member of $M$ consisting of precisely all those members of $M$ which satisfy the given formula (according to $M$), i.e.
$$M \not \vDash \exists y (x \in y \leftrightarrow \phi (x, p))$$
and informally it's the collection of those things in $M$ satisfying that formula, i.e.
$$\{x \in M | M \vDash \phi (x,p)\}$$
but this collection may exist as a member of some larger model, or it may not.
Answer: The thing is that a proper class is a collection of elements in a universe of set theory which is not a set, i.e. not an element of the universe.
It follows from the Russell's paradox that the collection of all sets is not a set, therefore a proper class.
However, suppose $V$ is a model of set theory, and $\langle M,E\rangle\in V$ is such that $M$ can be a model of set theory when thinking of $E$ as the epsilon relation for this model, then $M$ sees itself as a proper class, but $V$ - the larger universe - sees $M$ as a set.
On the other hand, consider $V$ is a model of set theory, it think of itself as a class, and consider its inner model $L$, the Godel universe of $V$, then $V$ thinks $L$ is a class as well, simply by the fact that the class of ordinals is embedded into $L$.
To conclude - a model of set theory always sees itself as a proper class. The way it sees other models, and they see it can be either as a set or as a class.
As for the collection of the ordinals this is simpler, as this is a well-ordered collection, so it must be isomorphic to some ordinal if it was a set, but then you have that it is a set which is a member of itself, therefore the collection of all ordinals is a proper class.
One more addendum: $V_\omega$ is indeed a model of $\mbox{ZFC}-\mbox{Infinity}$, however its existence as a set cannot be proved without the axiom of infinity, if you assume the existence of the empty set then you can build $V_\omega$ (by reiterating the power set operation) and have a model for the set theory of finitely-hereditary sets, which thinks of itself as a class, for the same reasons as above.

Is $V$ under ZFC really a proper class?


Retornar uma tabela entre um periodo de datas inicial e final , php + json

Question: Estou tentando retornar uma tabela de um dashboard de relatórios entre uma data especifica em, porém quando eu clico em pesquisar ele apenas me retorna

Error: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data.
Segue meus códigos:

selectdata.js

$(document).ready( function(){

$("#dataselecionada").click(function() {
    $('#tabeladht22').empty(); //Limpando a tabela
    var dataInicial = $('#datainicial').val();
    var dataFinal = $('#datafinal').val();

    //debugger;

    var postData = {
    "dataInicial": "dataInicial",
    "dataFinal": "dataFinal"
    };

                    alert(dataInicial);
            alert(dataFinal);
    $.ajax({
        type: 'post',
        data: JSON.parse(postData),//JSON.parse(d),//jQuery.param({ dataInicial: dataInicial, dataFinal: dataFinal}),
        contentType: 'application/json',
        //contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
        dataType: 'json',
        url: 'read_dht22.1.data.php',
        success: function(d) {
            var dados = JSON.parse(d);
            debugger;
            for (var i = 0; dados.length > i; i++) {
                $('#tabeladht22').append('
' + dados[i].temperatura + '	' + dados[i].umidade + '	' + dados[i].data + '
');
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            debugger;
                alert("Status: " + textStatus); alert("Error: " + errorThrown);
            }
    });
});
   });

read_dht22.1.data.php

`
    <?php
    $con = new mysqli("localhost", "root", "", "aquarium");
    if (mysqli_connect_errno()) trigger_error(mysqli_connect_error());

    $dataInicial = $_GET['dataInicial'];
    $dataFinal = $_GET['dataFinal'];

if ($con->connect_error) {
    die("Connection failed: " . $con->connect_error);
}

//$sql = "SELECT *,DATE_FORMAT(sysdate(), '%d/%m/%Y') as data FROM dht22 WHERE data BETWEEN '%".$dataInicial."%' AND '%".$dataFinal."%' ";
//$sql = "SELECT *,DATE_FORMAT(data,'%d-%m-%Y' ' %H:%i:%s') as data FROM dht22 WHERE data = '".$dataInicial."' AND data='".$dataFinal."' ";
$sql = "SELECT * FROM dht22 ";
$result = $con->query($sql);

if ($result = $con->query($sql)) {

    while ($row = $result->fetch_assoc()) {
        printf ("Temperatura: %s Umidade: %s Data: %s
\n", $row["temperatura"], $row["umidade"], $row["data"]);

    }
    $result->free();
}

$con->close();

?>

relatorio.php

Últimos dados

                                Temperatura
                                Umidade
                                Data

Answer: Consegui resolver o erro de Syntax.
while($row = mysqli_fetch_assoc($result)){
    $json[] = $row;
}
  $data['data'] = $json;
  $result =  mysqli_query($con,$sql);
  $data['total'] = mysqli_num_rows($result);

Porém agora não estou conseguindo realizar o retorno quando é selecionada a data é retornado em branco a tabela e no console fica "null".

Apaguei o dataType do $.ajax agora minha tabela retorna dessa maneira:


Do songs written in certain modes not have keys?

Question: Up until recently I thought that if a song was written in a mode with a major 3rd, then it was in a major key, and if it was in a mode with a minor 3rd, then it was in a minor key. But I read an article that said for a song to be in a minor key, it must have a leading 7th, i.e. one semitone lower than the root note, which none of the minor modes have. So basically, this means that if a song's written in the A Aeolian mode, then it's not actually in A minor, just in the A Aeolian mode. At least that's what the article said.
My question is basically, is this true? If a song is written in a mode with a flat 7th, can you not say that it's in a key?
The reason I thought of this is because of the RHCP song 'Mellowship Slinky in B Major.' People in comment sections are always arguing whether it's actually in B major or not. I know that the bassline uses the B Mixolydian mode, so I always thought that it was in B major, but since it has a flat 7th, is it not in B major?
Edit: here's the link http://garyewer.wordpress.com/2009/10/29/dorian-mode-aeolian-mode-minor-key-whats-the-difference/
Comment: The guy is saying that Aeolian is a mode rather than a minor key. To most of the Western world it's both. If ABRSM can include the natural minors amongst its scales, surely it can be recognised as a minor key.
Comment: @Fergus - we now know what are NOT keys - what's your definition OF a key?
Comment: Each and every answer has been down marked. Will the downmarkers be brave enough to explain why they think each answer is not good ?
Comment: I have commented on both Brad and your answers. I'd be grateful if whoever down voted my answer would do the same.
Comment: I think this is a strange question to ask, therefore I'm upvoting it. :-)  From my lack of understanding, I thought that all the modes can be played on a C major (or A minor) key signature?  (i.e. no sharps, no flats).  So... what's the question again?  Is it an apples and oranges thing?
Comment: @LeeKowalkowski - that's the basis. Of course there are 11 other sets of modes, one spawned from each key.And there are other modes, but let's not go there with this question - it's thorny enough by the look of it.
Comment: I think much of the confusion is arising from poor definitions: A scale is not a key. A tonal centre is not a key. A key signature is not a key. A mode is not a key.
Comment: Somewhat related, you may also want to check out http://music.stackexchange.com/questions/16248/understanding-minor-key-harmony.
Comment: I'm trying hard to accept one of these answers, but it seems like they're all right to a certain extent. Just looking for some more clarity.
Answer: The basic point that Mr. Ewer makes is correct: a mode is not the same as a key, just as a mode is not the same as a scale. However, he then confuses things by using a different definition of "key" than the one commonly used in modern Western music.
Some minor scales have a major 7th, like the harmonic minor and melodic minor ascending. Other minor scales have a minor 7th, like the natural minor (Aeolian mode), the Dorian, and the Phrygian mode. The only universal feature of minor scales is the minor third, from which all minor scales get their name. Of these many minor scales, we would normally only call the Aeolian, Dorian, and Phrygian scales minor modes, and the natural minor scale is the only that's the basis of a minor key.
In modern Western music, there are 12* minor keys. Each establishes a specific tonic center with a minor quality. Each has a relative major key starting a minor third higher. These relative keys are also called the Aeolian and Ionian mode, or the natural minor and major scale. While there are many other modes and scales, there are only these 24 common keys.
Mr. Ewer uses a different context for his examples, a harmonic theory where the minor key is a bit different from modern minor keys. I'm not personally familiar with that theory, but it sounds a lot like the modern harmonic minor scale. If you don't keep that in mind his whole article will be confusing at best.
For a little more context: A big part of establishing a key melodically and harmonically is using tension (dissonance) and release (consonance) to drive the music toward the tonic center. Traditionally, that relies heavily on the V chord and specifically the major 7th (the leading tone). That's the idea underlying the harmonic and melodic minor scales, and probably what Mr. Ewer is talking about. However, there are other ways of establishing a minor tonic center, such as a blues turnaround or a chromatic descending leading tone (creating a Phrygian feel). These are mainly small alterations to the natural minor scale, which serves as the starting point for the minor key.
To address your question about "Mellowship Slinky in B Major": The B Mixolydian mode is not the same as the B major key, and you shouldn't use the two names interchangeably. On the other hand, a bassline with a Mixolydian feel doesn't necessarily mean that the piece isn't in B major – Flea could simply be playing with the key a bit for added color.

* Using common key signatures; more are possible with enharmonic spellings.
Comment: Your answer says otherwise; "the natural minor scale is the only that's a minor key." a minor scale is not a minor key. Scale and key are not interchangeable terms. A scale is a pitch set, a key is established by functional harmony. The key sig. does not always define the key of the piece, the harmony does.
Comment: In your wiki link: "The methods by which the key is established for a particular piece are not easy to explain, as they vary considerably over the period of music history; however, the chords most often used in a piece in a particular key are those containing the notes in the corresponding scale, and conventional progressions of these chords, particularly cadences, serve to orient the listener around the tonic." Conventional progression and cadences = Functional harmony.
Comment: I can't see where it describes key in your way? In fact it states this "Although many musicians confuse key with scale, a scale is an ordered set of notes typically used in a key, while the key is the center of gravity, established by particular chord progressions." Which is exactly the point I'm trying to make. your answer confuse key with scale and equate using a scale to meaning being in a key here; "the natural minor scale is the only that's a minor key" That it why I keep whipping this dead horse.
Comment: Related: http://music.stackexchange.com/q/19033/6556
Comment: I'm aware of that, but that doesn't really answer my question at all...
Comment: Okay, so you're saying that my initial assumption is right, and that if a song is written using A Aeolian then it's in A minor, if it's written using B mixolydian then it's in B major?
Comment: So if it's in B mixolydian, then it's not in B major...? Would you just say it's in the key of B?
Comment: B Mixolydian will never be B major.Only part of each is the same. There will always be a bit of Mixolydian which sounds 'not quite right' if we're expecting the tune to be made up from the scale notes of a pure major. B major key sig. is 5#, B mixolydian needs 4#. For someone to play along or jam, it's important to be aware of the difference.Otherwise, every so often a bum note will appear.
Comment: This answer is totally wrong. The opening line of the article is "In TRADITIONAL harmony..." See my answer for more info.
Comment: The Wikipedia article is interesting. It seems that there is some ambiguity around the topic.
Comment: @BraddSzonye - the natural minor scale exists - it's the same notes as the relative major, but going 6-6.
Comment: @BraddSzonye - it didn't imply, it said ! But the only basis for a 'minor key' is the key signature of that relative minor, or is that what you meant? As both the melodic and harmonic have notes that need accidentals - as the notes used are not actually in the key sig. Strange !
Comment: The natural minor scale is not the basis for minor keys! Any number of scales may appear in a minor key song (see link below for ex.). What makes it a minor key song as opposed to a modal song is the western (functional) harmony. http://music.stackexchange.com/questions/16248/understanding-minor-key-harmony
Comment: @Fergus Yes, I'm familiar with that, but ultimately *A minor* means the natural minor unless the accidentals indicate otherwise. That's what I mean by *basis.* You can read *basis* as *baseline* or *default* if it makes more sense.
Comment: Also from the wiki link: "The key signature is not a reliable guide to the key of a written piece". Your usage of "key" may be common, but it is not the one used by wiki or any theory texts and I don't think your misconceptions should be shared as correct.
Comment: I expanded a bit on the importance of establishing a tonic center, and why the major 7th leading tone has a less central role in it these days. Hopefully that will alleviate some more of the concerns expressed in comments.
Comment: Also, I cleaned up all of my comments related to things that have been edited into the answer.
Answer: The opening sentence in the linked article states:

""In traditional harmony (i.e., the kind you'd learn in a Classical
  music school), being in a minor key has a particular definition that
  gets confused with being in a minor mode.""

He is right. Any good (traditional) theory book will confirm this along with everything else the article states.
The OP's question:

My question is basically, is this true? If a song is written in a mode
  with a flat 7th, can you not say that it's in a key?

Yes, to both. If the leading tone is not present a key cannot be established.
Modal music cannot establish 'a key' in the traditional sense.
Wikipedia's Aeolian page has examples of songs that employ the Aeolian mode:

Songs that use Aeolian mode
  Aeolian mode as a scale is identical with
  the natural minor scale. Thus, it is ubiquitous in minor-key music.
  The following is a list of some examples that are distinguishable from
  ordinary minor tonality.
Bob Dylan - "All Along the Watchtower"   R.E.M - "Losing My Religion"

Those song do not establish a key (in the traditional sense). They are Modal songs.
Modal music is widespread in contemporary music (rock, pop etc). Many songs mix modal sections with key based (functional harmony) sections, for example:
the Beatles "Norwegian Wood" spends 16 bars on E mixolydian, then moves to E dorian for 12 bars (Em-A-Em); then the last 4 bars are a ii-V in E major, then to the mixolydian groove.
Many songs have mixolydian verses, going into major key choruses. for example:
Guns and Roses Sweet Child o Mine.
The Rolling Stones Sympathy for the Devil.
The Beatles Hard Days Night.
For simplicity (or ignorance, or brevity) many do not bother to differentiates between a piece with a "key" and a modal piece, they simply state the tonal centre and get on with it, as the RHCP have done.
This has lead to the terms "Key" losing it's more precise definition and to come to also mean "tonal centre of a modal piece" and also "Tonic of a scale" in many circles.
This is fine most of the time but those with formal harmony education such as the author of the article still use "key" as it was defined hundreds of years ago rather than the more vague definition it has gained recently (last 50 years or so).
Comment: I think you may be confusing two issues. Whether the 3 or b3 is present is a separate issue to your OP about whether a key is established. eg Phyrgian dominant, lydian, Mixolydian, major pentatonic and Ionian are all major scales or modes, all of them can establish a major tonality but only one can establish a key: Ionian. Saying a song is in B major implies the song is in the key of B major (and not modal). Saying a song is B Mixolydian implies the song is modal (and also tells you it has a major tonality in you are familiar with Mixo). So yes, slinky in B mixolydian is more correct.
Comment: The key (no pun intended) part of my comment was 'when speaking of contemporary music.' I get that it's wrong when talking about classical music, but in contemporary music is it "acceptable" to say the song is in B Major?
Comment: "His opening sentence" - Whose opening sentence? I guess it's from the link in the question, but it doesn't become crystal clear when there are other lengthy answers in between. Better to reference it directly.
Comment: So what I gather is, it's okay to refer to a modal piece as major or minor depending on its 3rd when speaking of contemporary music, but if RHCP were proper music theorists, they would have called it 'Mellowhsip Slinky in B Mixolydian'?
Comment: The term "key" applies to all music that employs functional harmony, this isn't restricted to classical music, much contemporary music is key based (jazz, pop, country etc). It does not apply to modal music (eg indian ragas and nearly all other eastern music, modal jazz, static harmony funk such as mellowship etc etc). It may be common practice among those without formal theory education to say, for example "'So What' in the key of D minor" but you will not find any harmony text (including contemporary texts) that consider it correct or acceptable.
Answer: There's some confusion about scales, modes and keys here. Major keys will have a major 3 and minor keys a minor 3. In harmonic, natural and melodic minors, the first 5 notes are the same.Dorian mode also has the same 5 notes. What happens in the remaining two defines which scale/mode is being used. Some songs will stray from one to another, and the classical melodic moves in an unusual way, with the 6 and 7 being 'major' in upward moves, but natural coming down.
The flat 7 or not doesn't in itself distinguish a major or minor key. The 3 does that. It could be argued that a flat 7 actually is an acceptable note with reference to the next part of the tune, as , for instance, in C, a Bb used usually leads to F, which HAS a Bb anyway.
In an earlier question, I stated that there were 3 minor keys, I was wrong - 3 (or more) minor scales, but not keys. Strictly speaking, a mode will probably have the key signature of its parent, as in E Dorian needs 2# as it's the Dorian OF D. That's always a good clue as to what key a piece is in.
In addition, after some more thought, the answer is yes and no. A key is usually thought of as referring to the 'home' note, thus, in F# maj. or min., the pull is towards F#. Otherwise it wouldn't be in F#. HOWEVER, with modes, there is a double pull - there is the set of notes used, which refer to the parent key, call it F# again. To me , at least, a lot of modal stuff still sounds unresolved, say it's G# Dorian, which feels (to me) that only when I hear F# gives finality. But, if it's in G# Dorian, it will end (and probably start) on G#, which certainly establishes its Dorian modality - as G# could be considered as the 'home' note/chord.
Comment: In traditional harmony the key is not simply the tonal centre. to establish a key criteria must be met, not simply establishing of a tonal centre. I understand that many non-classical musicians use key, scale and tonal centre ('home note') interchangeably but in traditional harmony (which the OP's link is about) they have very distinct meanings which makes Brad and your answer wrong.
Answer: Any mode (or modal piece of music) can be played/sung in any key - if by 'key' you mean 'key signature'. I do not know the piece you refer to, but if it's really in (the key of) B major, it cannot equally be in B Mixolydian - which would have the same key signature as E major!
Answer: There is also certain composers who adhered to a very loose definition of scale. Debussy did this a lot. You would see a piece that you would feel is in E and then suddenly you are confronted with accidentals that make you wonder what exactly is going on.
There is also the fact that modulations occur and they are not always defined to the dominant or relative minor / Major.
Comment: Did you mean confined rather than defined?


Editing database with dropdown list in asp.net

Question: I am using asp.net with vb.net code behind.  I have a database that contains a list of names.  I use an asp:dropdownlist databound with SqlDataSourceID and it works fine to get the list from the database to the dropdownlist and display it.
However, I want to use the dropdownlist to also allow the user to add unique values to the dropdownlist and therefore edit the database.
How do I do this? I cannot enter unique values in the dropdownlist now.  Below is the asp snippet.
Thanks for the help.
<asp:DropDownList ID="OEMDropDownLst" runat="server" AutoPostBack="true"
                CssClass="NwDrpDwnFmt" DataSourceID="SqlDataSource1" DataValueField="CustomerName"
                AppendDataBoundItems="True">
</aso:DropDownList>

Answer: If I understand correctly you want users to type directly into your dropdownlist? As far as I know that can't be done.  If you want users to add new options to that dropdownlist then you have to create the fields needed and have an update button so then you rebind the dropdownlist after changes have been saved.
Comment: That is what I was afraid of.  Thanks for the help.
Answer: </aso:DropDownList></asp:DropDownList> Spelling mistake brother.


What is the mean of this error?

Question: My application is working very well for first time in the sumilator, when I rerun my app in simulator and press some button, I get this type of error. I am using Local DB, so I thought maybe it is reason for taking this error message?

* Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: 'NSBundle  (loaded)' with name 'UIViewController-Lat-JX-Ucy' and directory 'MainStoryboard_iPad.storyboardc''
* First throw call stack:
  (0x1bdc012 0x18e9e7e 0x1bdbdeb 0xa49ef9 0xc7554a 0xc75b43 0xc75c14 0x18fd705 0x8312c0 0x831258 0x8f2021 0x8f257f 0x8f16e8 0x860cef 0x860f02 0x83ed4a 0x830698 0x27bedf9 0x27bead0 0x1b51bf5 0x1b51962 0x1b82bb6 0x1b81f44 0x1b81e1b 0x27bd7e3 0x27bd668 0x82dffc 0x2d9d 0x2cc5)
  libc++abi.dylib: terminate called throwing an exception
Comment: Is there any other context in the log like "The class MyViewController is not key value coding compliant ..."
Answer: It simply means that Xcode was not able find a nib file named "UIViewController-Lat-JX-Ucy" in your project. Make sure that you have a nib file named like that.
Comment: This is a file that's generated while compiling a storyboard, it will be in the output of the build inside of the '*.storyboardc' file, but won't be in the project.
Answer: The issue is not related with your DB, it is saying that it has a problem loading the UIViewController-Lat-JX-Ucy view from the MainStoryboard_iPad storyboard. How are you loading it?
Answer: I had the same issue when I was loading a new bundle that contained almost the same storyboards as the previous bundle.
In my case in original storyboard there was an OriginalViewController in one container, but in updated bundle that container had NewViewController. When trying to open this container using new storyboard I had a crash because no view controller with previous id (Lat-JX-Ucy in your case) was found in new storyboard - it was in the old storyboard.
My solution was to clear cache of the previously loaded bundle before loading a new one. Everything is well explained here

What is the mean of this error?


formatting html in c#

Question: i am having a variable in c# holding some string like this
string myText="my text  which contains
i am text inside div
";

now i want to replace all "\n" (new line character) with "
" for this variable's data except for text inside div.
How do i do this??
Comment: will the string contain only one div? or any number of divs in any position?
Comment: I assume the 2nd `` should be `` ?
Answer: For something like this you will need to parse the HTML in order to distinguish the parts that you do want to make the replacement in from the ones you don't.
I suggest looking at the HTML agility pack - it can parse HTML fragments as well as malformed HTML. You can then query the resulting parse tree using XPath notation and do your replacement on the selected nodes.
Answer: Others have suggested using libraries such as HTMLAgilityPack. The former is indeed a nice tool, but if you don't need HTML parsing functionality beyond what you have requested, a simple parser should suffice:
    string ReplaceNewLinesWithBrIfNotInsideDiv(string input) {

        int divNestingLevel = 0;
        StringBuilder output = new StringBuilder();
        StringComparison comp = StringComparison.InvariantCultureIgnoreCase;

        for (int i = 0; i < input.Length; i++) {
            if (input[i] == '<') {
                if (i < (input.Length - 3) && input.Substring(i, 4).Equals("<div", comp)){
                    divNestingLevel++;
                } else if (divNestingLevel != 0 && i < (input.Length - 5) && input.Substring(i, 6).Equals("
", comp)) {
                    divNestingLevel--;
                }
            }

            if (input[i] == '\n' && divNestingLevel == 0) {
                output.Append("
");
            } else {
                output.Append(input[i]);
            }
        }

        return output.ToString();
    }

This should handle nested divs as well.
Comment: Nice... I was in the process of writing such an example you just got done first...
This text worked just fine with it by the way...

 string test = "My text !\n which contains i am text !\n" +
                          "insidenested div!\n div" +
                          " outside of div !\nDid this work";
Answer: That would require some fairly complicated RegEx, out of my league.
But you could try splitting the string:
string[] parts = myText.Split("
", "
");

for (int i = 0; i < parts.Length; i += 2)  // only the even parts
  parts[i] = string.Replace(...);

And then use a StringBuilder to re-assemble the parts.
Comment: I remember an answer on HTML and RegEx: http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454
Comment: @gvs: And that is why Oded has the right answer, in principle. But Praveen might find it a bit overwhelming for 'just' replacing a few newlines.
Comment: myText.Split("", ""); // accepts characters array only to split,
unable to split  string with it!!
Comment: @Praveen, I think the `param strings` overload os Split() may be new in Fx4.
Answer: I would split the string on div then look at the tokens if it starts with "div" then don't replace \n with BR if it does start with div then you need to find the closing div and split on that.. then take the 2nd token and do what you just did... of course as you are going to have to keep appending the tokens to a master string... I'll code up a sample here in a few minutes...
Comment: You need to escape Html tags here.
Comment: I have the same problem with my basic idea... you have to deal with nested divs and make sure you know what nesting level you are at to determine when you are back outside of the div...
Answer: Use the string.Replace() method like this:
 myText = myText.Replace("\n", "
")

You could consider using the Environment.NewLine property to find the newline chars. Are you sure they are not \n\r or \r\n etc...
You may have to pull the text inside the div out first if you dont want to parse that. Use a regex to find it and remove it then do the Replace() as above, then put the strings backtogether.
Comment: That would also replace inside the `` blocks.
Comment: i too thinking for a regex solution, but i am too weak in regex  thing, please suggest its regex.

formatting html in c#


Ficar mostrando a data e hora no browser com javascript

Question: Olá.
Quero exibir na página a data e hora. Para isso, comecei fazendo o pequeno teste para exibir uma contagem regressiva:

var tempo=60;
function session(time) {
  time=this.tempo;
  if (this.tempo>0) {
    tempo--;
    document.write(tempo);
  }
}
function pegaSession() {
  setInterval(session, 10000);
}
session(tempo);

Não tratei o tempo ainda, pois quero mostrar decrescente, depois que resolver este detalhe, trabalho com a função parseInt e ParseFloat().
Comment: Obs: o correto seria `parseInt`
Comment: @Silvio Andorinha já corrigido.
Answer: Acontece que nesse caso a função session() é chamada apenas uma vez na ultima linha do código session(tempo); e depois em nenhum momento você chama a função pegaSession() que é a que da inicio no setInterval
Faça a seguinte alteração

var tempo=60;
var interval;

function session(time) {
time=this.tempo;
if (this.tempo>0) {
    tempo--;
    document.body.innerHTML='';
    document.write(tempo);
}
else
{
    clearInterval(interval)
}
}

function pegaSession() {
interval = setInterval(session, 1000);
}
pegaSession();

Como pode notar no final do código eu chamo o pegaSession() para assim ele iniciar o setInterval

Obs: 10000 milissegundos é equivalente a 10 segundos, se for usar esse setInterval para marcação de segundos o correto seria 1000 equivalente a 1 segundo

E limpando o intervalo como sugerido pelo nosso amigo @TobyMosque ;)
Comment: Silvio, a resposta é muito boa, mas acredito que seja interresante limpar este Intervalo quando o tempo for igual ou menor que zero, afinal não é legal deixar uma função que não faz nada rodando a toa ;D. https://jsfiddle.net/uz2qyrg2/
Comment: Na verdade, mesmo chamando a pegaSession(), não resolve. Dá o erro: wyciwyg://36/http://localhost/objeto/principal.php
Comment: @AndréNascimento execute esse código exatamente como está na resposta, e poderá ver que está funcionando normalmente
Comment: @TobyMosque editei lá ;)
Answer: André nascimento, se tudo que deseja é mostrar a Data e Hora no Browser, aconselho ignorar este contador e pega a Hora do Sistema, como acredito que você deseja mostrar quando tempo falta para a Sessão do usuario expirar, vou colocar um exemplo onde o tempo se esgota em 15 segundos:

var interval = 1000;
var dataValidade = new Date();
var countdown = document.getElementById("countdown");

dataValidade.setSeconds(dataValidade.getSeconds() + 15);
//dataValidade.setHours(dataValidade.getHours() + 1);

var verificarSessao = function () {
  var dataAtual = new Date();
  var tempoRestante = new Date(dataValidade.getTime() - dataAtual.getTime());

  if (tempoRestante.getTime() < 0)
  {
    countdown.textContent = "O seu tempo acabou"
  }
  else
  {
    tempoRestante.setMinutes(tempoRestante.getMinutes() + tempoRestante.getTimezoneOffset())
    countdown.textContent = "O tempo se esgota em " +  tempoRestante.toTimeString().substring(0, 8) + ".";
    setTimeout(verificarSessao, interval);
  }
}

verificarSessao();

caso queira aumentar o tempo, basta adicionar mais tempo a variavel dataValidade.
Answer: Se você quer apenas um relógio, basta você fazer uma saída desse tipo:

Se for um contador regressivo, você pode fazer isso de duas maneiras:
Em javascript puro:
http://jsfiddle.net/fk2unkb9/31/
Ou em AngularJS: http://jsfiddle.net/fk2unkb9/29/
Comment: copiei, colei no eclipse, mas não exibiu. Li superficialmente o código, não parei para analisá-lo e estudar com calma.
Comment: Não entendi? Qual o problema?
Comment: Não mostra nenhum erro. Como foram me passadas várias soluções, vou estudá-las, pois não posso falar muito sem conhecer e qualquer coisa, comento, até evita comentários meu, como leigo.
Answer: Caso queira mostrar a hora atual mesmo, use o objeto Date() do javascript.
Observação
Como os meses são retornados em números e o dia da semana também, eu criei um array para os meses e um para os dias da semana e usei o número retornado pelo objeto para selecionar o dia e mês certos nos Arrays.

window.onload = setInterval(horario, 1000);

function horario() {
  var relogio = document.querySelector("#relogio");
  var d = new Date();
  var seg = d.getSeconds();
  var min = d.getMinutes();
  var hr = d.getHours();
  var dia = d.getDate();
  var mes = d.getMonth();
  var meses = ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"];
  var diaSem = d.getDay();
  var diasSemana = ["Domingo","Segunda-Feira","Terça-Feira","Quarta-Feira","Quinta-Feira","Sexta-Feira","Sábado"];

  relogio.innerHTML = diasSemana[diaSem] + ", " + dia + " de " + meses[mes] + ", " + hr + ":" + min + ":" + seg;
}

Comment: no lugar de montar a string na mão, pq não usa o [Date.prototype.toLocaleString](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString)? um exemplo: `relogio.innerHTML = new Date().toLocaleString();`
Comment: Ainda não conhecia esse método, mas muito obrigado, fui tentar ajudar e acabei aprendendo rs.
Answer: function DataHora() {
        var data = new Date();
        tempo.innerHTML = data;
        var dataBr = tempo.toLocaleString();
        setTimeout("DataHora()", 1000);
    }


How to use minipanels in a menu

Question: I tried to install the module Menu Minipanels, without success. I tried both the 1.x and 2.x version but the minipanel don't show up in the menu. After half a day I gave up.
I do like the idea of a megamenu using minipanels, so this question is:
How to use minipanels in a menu, without the 'Menu Minipanels' module?
EDIT: I got Menu Minipanels working at last, but it has a major bug that anonymous users can't see the minipanels in the menu! Back to square one.
So again the same question..
Comment: How did you try to implement it? I don't think that module actually uses the menu system...
Answer: I now used a workaround, instead of the 'menu minipanels' module, i am using 'Menu Attach block' which simply allows to insert minipanels too since they are available as blocks.

How to use minipanels in a menu


Property of the field of fractions

Question:
Let $K$ be a field and $A$ a subring of $K$ with the following
  property: for every finite family $(\xi_i)_{1\leq i\leq n}$ of
  elements of $K$ there exists $\gamma\in A-\{0\}$ such that
  $\gamma\xi_i\in A$ for $1\leq i\leq n$ (a hypothesis which is always
  satisfied when $A$ is abelian and $K$ is the field of fractions of
  $A$).

First of all, if $A$ is only nonzero and abelian, then it is not necessarily an integral domain; therefore, how can it possess a field of fractions $K$? Surely they mean that $A$ is an integral domain and not only an abelian and nonzero ring, correct?
Now, if $K$ is the field of fractions of $A$, then $A$ can be identified a with its image in $K$: i.e. $A$ is a nonzero subring of the abelian field $K$. Therefore there exist $\gamma\in A$ such that $\gamma\ne0$. But why does it follow that $\gamma\xi_i\in A$ for all $1\leq i\leq n$?
Comment: It says "subring of a field" and that trivially cannot have nonzero zero divisors..
Comment: Right, so $A$ is necessarily an integral domain.
Comment: clarification: are fields necessarily abelian in your text?
Comment: @HagenvonEitzen they are not.
Comment: Then perhaps the part in parentheses is less confusing when formulated like this: "(a condtion that is always satisfied when the subring $A$ is abelien and there is no proper subfield of $K$ that contains $A$)"
Comment: Hint: the hypothesis is equivalent to: $\gamma$ is a common denominator for the fractions (which always exists for a finite set of fractions, e.g the product of the denominators).
Comment: Thank you all for your help. I just don't understand why $\gamma\xi_i$ are elements of $A$.
Answer: Notational Reminder: "field" here means "skew field", i.e., multiplication need not be abelian. Also, "ring" means "ring with $1$" (or at least "ring with more than one element").
Claim. Let $K$ be a field, $A$ a an abelian subring and assume that there is no field $L$ with $A\subseteq L\subsetneq K$.
Let $\xi_1,\ldots,\xi_n\in K$. Then there exists $\gamma\in A\setminus\{0\}$ with $\gamma \xi_i\in A$ for $1\le i\le n$.
Proof. Let $$L=\{\,\xi\in K\mid\exists \gamma\in A\setminus\{0\}\colon \gamma\xi\in A\,\}.$$
Clearly, $A\subseteq  L$ (here we use $A\setminus\{0\}\ne\emptyset$).
Assume $\xi_1,\xi_2\in L$. Let $\gamma_1,\gamma_2\in A\setminus\{0\}$ with $\gamma_1\xi_1,\gamma_1\xi_2\in A$.
Then $\gamma:=\gamma_1\gamma_2\in A\setminus\{0\}$ and
$$ \gamma(\xi_1-\xi_2)=\gamma_2\gamma_1\xi_1-\gamma_1\gamma_2\xi_2\in A$$
so that $L$ is a subgroup of $K$ under addition.
Also,
$$\gamma\xi_1\xi_2=\gamma_2\gamma_1\xi_1\xi_2=\gamma_1\xi_1\gamma_2\xi_2\in A$$
so that $L$ is closed under multiplication.
Finally, if $\xi_1\ne 0$, then $\gamma_1\xi_1\in A\setminus\{0\}$ and
$$ \gamma_1\xi\cdot\xi_1^{-1}=\gamma_1\in A.$$
It follows that $L$ is a subfield of $K$ and contains $A$. By assumption $L=K$. This solves the claim for $n=1$.
Now let $\xi_1,\ldots,\xi_n\in K$. As just seen, there exist $\gamma_1,\ldots,\gamma_n\in A\setminus\{0\}$ with $\gamma_i\xi_i\in A$ for  $1\le i\le n$. Then $\gamma:=\gamma_1\cdots\gamma_n\in A\setminus\{0\}$ and
$$ \gamma\xi_i=\gamma_1\cdots\gamma_{i-1}\gamma_{i+1}\cdots\gamma_n\cdot\gamma_i\xi_i\in A,$$
as was to be shown. $\square$

Property of the field of fractions


Binomial Theorem - Proving

Question: The viscosity $\eta$ of a liquid is given by;
$$\eta = \frac{kr^4}{v*l}$$
Where $k$ is a constant.
If there is an error in $r$ of $+2%$, in $v$ of $+4%$ and $l$ of $-3%$, what is the resultant error in $\eta$?
Comment: Hello, Andre. It's considered bad form to just post a homework question and expect someone else to do all the work for you. Please see [this](http://meta.math.stackexchange.com/questions/1803/how-to-ask-a-homework-question) post about how to ask for help with homework. Also, very good advice on how to ask a good question in general can be found [here](http://meta.math.stackexchange.com/questions/9959/how-to-ask-a-good-question/9960#9960).
Comment: I don't see the meaning of $binomial$ $theorem$ in the title of your post.
Comment: Hello. Sorry I ought to explain myself after reading the post 'homework' as I am new to the website. I have been working my way through the book 'Higher Engineering Mathematics' by John Bird, which I found extremely useful. However after following the binomial series chapter I attempted to complete the exercises for practical problems involving the binomial theorem. I have struggled completing the question posted here. Therefore guidance on such question would be much appreciated! For assistance do I post within the homework section? Thank you.
Answer: Hint
I do not know how they teached you the problem of errors; so forgive me if it does not match what you have been told.
The easiest way (at least to me) is to consider the logarithm of $\eta$ and to take the derivatives with respect to each properties, each derivative being weighted by its error (this is equivalent to a total differentiation).
I shall only give you the answer, assuming that the errors you give are in percents : your viscosity would be in error by $15$ percent.
I am sure that you can take from here and establish the proper formula, valid for any error on any of the terms.
Added later
I realize now that I did not see the sign assigned to errors (I am almost blind). What I assumed is that you were given relative errors (accuracies) for each quantity. If they are what you wrote, my answer is an overall error of $7$ percent for viscosity.
If you want me to elaborate more, just post. We could go into more details.
Comment: Thank you. Therefore if I assign the relative errors (accuracies) for each quantity; r= (1+2%)r or r= (0.98r) and repeat this for the other respective quantities, I can substitute all of the quantities  i.e.(0.98r) into the equation to calculate the viscosity?
Comment: Not at all ! I shall write a more detailed answer.
Answer: Let me start again with your model as a good illustration. You have $$\eta = \frac{kr^4}{v*l}$$
where $k$ is a constant.
Now, you want to consider the impact of a small change for any parameter. So, you consider the total derivative with respect to all parameters. This then leads in your case to $$d\eta=-\frac{k r^4 dl}{l^2 v}-\frac{k r^4 dv}{l v^2}+\frac{4 k r^3 dr}{l v}$$
Now you change the $d$'s by $\Delta$'s which are not more infinitesimal and so  $$\Delta \eta =-\frac{\text{$\Delta $l} k r^4}{l^2 v}-\frac{\text{$\Delta $v} k r^4}{l
   v^2}+\frac{4 \text{$\Delta $r} k r^3}{l v}$$ So, for any $\Delta l$,  $\Delta v$ or  $\Delta r$, you have the analytical expression of $\Delta \eta$.
In the case where your function is a product, it is much easier to go to logarithms before differentiating. So, for your problem, we shall have  $$\frac{\Delta \eta }{\eta }=-\frac{\text{$\Delta $l}}{l}+\frac{4 \text{$\Delta $r}}{r}-\frac{\text{$\Delta
   $v}}{v}$$
In the case of the product, you immediately see that a $1$% increase of $r$ will induce a  $4$% increase of $\eta$, while a $2$% increase of $l$ will induce a  $2$% decrease of $\eta$. If you have multiple changes, you just add them up.
In general, we do not know the sign of errors (we are given accuracies). In that case, you add up all the absolute values. Your case would then lead to   $$\frac{\Delta \eta }{\eta }=\frac{\text{$\Delta $l}}{l}+\frac{4 \text{$\Delta $r}}{r}+\frac{\text{$\Delta
   $v}}{v}$$
Do you see the difference between both situations ?
Comment: Therefore I could use one of the two equations, being; $$\Delta \eta =-\frac{\text{$\Delta $l} k r^4}{l^2 v}-\frac{\text{$\Delta $v} k r^4}{l
   v^2}+\frac{4 \text{$\Delta $r} k r^3}{l v}$$ or  $$\frac{\Delta \eta }{\eta }=\frac{\text{$\Delta $l}}{l}+\frac{4 \text{$\Delta $r}}{r}+\frac{\text{$\Delta
   $v}}{v}$$
Comment: Sorry I am slightly confused I haven't seen/used this method before. I know that the Viscosity is 7%. However I am finding a Viscosity of 6%. From the following Calculations.. .$$\frac{\Delta \eta }{\eta }=\frac{\text{$\Delta $0.03}}{0.03}+\frac{4 \text{$\Delta $0.02}}{0.02}+\frac{\text{$\Delta
   $0.04}}{0.04}$$
Comment: @Andre. If we speak about errors, the relative error on viscosity is 0.03 + 4 0.02 + 0.04 = 0.15 (so 15%). If we speak about signed changes, the relative error on viscosity is 0.03 + 4 0.02 - 0.04 = 0.07 (so 7%).
Comment: Brilliant! Additionally I am also struggling with another problem which you may be able to assist one with?  http://math.stackexchange.com/questions/660952/engineering-mathematics
Comment: @Andre. I do not see where is the problem; the comments are quite clear. Could you elaborate ? I shall be happy to help (if I can). Cheers.
Comment: Firstly, to show the equation for instantaneous power, I take it that the instantaneous voltage (v) has been simplified and shown. Therefore to let one prove the equation, do I have to simplify the instantaneous current (i) to prove the equation?
Comment: Replace $i$ and $v$ in $P$. You have the formula. Now use the relation for cosine of double angle as a function of sine of the angle and you are done. By the way, you could accept my answer if you wish.
Comment: Therefore, considering the double angled formula and compound angles;                                                                                cos 2x = cos^2 x - sin^2x,  cos^2 x + sin^2x = 1,              Substitution of:-  cos^2x = 1 - sin^2x, cos2x = (1 - sin^2x) -  sin^2x, cos2x = (1 - 2*sin^2x), 2*sin^2x = 1 - cos2x, sin^2x = (1/2)*(1 - cos2x)
Comment: Would I be correct in saying this?

Binomial Theorem - Proving


Converter HTML em PNG

Question: Como converter, via código javascript ou php, o html (DOM) da página que está sendo exibida para uma imagem?
Preciso que a página mostrada ao usuário seja convertida em um arquivo de imagem no formato png para o mesmo fazer download e que este seja iniciado automaticamente.
Answer: Eu usaria a biblioteca: dom-to-image Você pode ler a documentação sobre o uso dela aqui
Aí vai um exemplo:
var node = document.getElementById('my-node');

domtoimage.toPng(node)
    .then (function (dataUrl) {
        var img = new Image();
        img.src = dataUrl;
        document.body.appendChild(img); //esse método exibe a imagem na própria pagina
    })
    .catch(function (error) {
        console.error('erro exibido caso falhe', error);
    });

Como faço para abrir a imagem em outra pagina?

Simples, refira uma pagina em branco como o valor de document a ser usado.

Como faço para que a imagem seja transformada e seu download iniciado altomaticamente?

domtoimage.toPng(document.getElementById('my-node'), { quality: 1 })
    .then(function (dataUrl) {
        var link = document.createElement('a');
        link.download = 'NomeDaImagem.png';
        link.href = dataUrl;
        link.click();
    });

Comment: @lucaswmolin isso, o método appendChild irá exibir a imagem na própria pagina. Você pode abrir em outra mudando a url referente ao document e abri-la via código JS. Para fazer o download automaticamente eu sugeriria transformar a imagem em um arquivo BLOB  e utilizar uma biblioteca como o FileSaver (link -
 https://github.com/eligrey/FileSaver.js/) existem alguns exemplos na documentação, é bem simples.
Comment: @lucaswmolin na documentação existe uma menção de um recurso de compressão para evitar esse tipo de erro, você também pode alcançar isso com meu segundo código ao diminuir a quality de 1 para algo menor :)
Comment: document.appendChild(img); faz com que a imagem seja exibida na mesma página? Como faço para abrir em outra? Ou fazer o download dela  automaticamente?
Comment: quer que eu incorpore suas perguntas na minhas resposta? @lucaswmolin
Comment: Sim, por favor.
Comment: @lucaswmolin editado, espero que fique satisfeito com o resultado :D
Comment: Uma dúvida simples: my-node é qual elemento? ,...?
Comment: É o elemento body
Comment: No download, aparece "Falha - Erro na rede".
Comment: @lucaswmolin isso se dá por uma configuração no chrome, veja esse link https://www.google.com.br/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0ahUKEwj_56O7idrWAhUJQpAKHbtxDfYQFggnMAA&url=https%3A%2F%2Fproductforums.google.com%2Fd%2Ftopic%2Fchrome%2F7XBU6g6_Ktc&usg=AOvVaw3S05AkdtqqRd_aiCG-tLmS
Comment: @lucaswmolin quando obtiver sucesso usando o que indiquei na resposta peço que marque como correta, ajuda os outros usuários que estão com o mesmo problema a saberem que conseguiu dessa maneira.
Comment: Aparentemente funciona, porém com páginas pequenas, que geram imagens de poucos KB. Estou lidando com imagens de alguns MB, que dão erro no download.
Answer: Creio não ser possível salvar um screenshot com Javascript. Mas uma alternativa interessante é você desenhar o html que quer em um elemento canvas, e depois usar o método toDataURL() para pegar os dados em base 64, e salvar em imagem

document.getElementById('desenhar').onclick = function (){
  var c = document.getElementById("teste");
  var ctx = c.getContext("2d");
  ctx.beginPath();
  ctx.arc(95,50,40,0,2*Math.PI);
  ctx.stroke();
}

document.getElementById('salvar').onclick = function (){
  console.log(document.getElementById('teste').toDataURL());
}
<canvas id="teste"></canvas>

<button id="desenhar">Desenhar</button>
<button id="salvar">Salvar</button>
Comment: sensacional, não tinha pensado nessa alternativa +1
Comment: @Paz :) mas eu ainda iria pela sua, caso o OP possa usar lib de terceiros
Comment: vamos torcer para que possa rs
Answer: Você pode usar a função imagegrabscreen() e imagegrabwindow(), que permite que você crie "screenshots" do navegador.
Veja os comentários no manual para saber como omitir o Chrome do navegador. Com DCOM habilitado, isso também funcionaria com máquinas remotas do Windows que foram configuradas para permitir o acesso através do DCOM.
Links:

http://php.net/manual/de/function.imagegrabscreen.php
http://www.php.net/manual/de/function.imagegrabwindow.php
Comment: Bem, caso o autor da pergunta queria utilizar essa solução em php é bom se atentar ao primeiro comentário: `For this to work your Apache service must be set to 'Allow service to interact with desktop' otherwise you will just get a blank image.`
Answer: Tem uma biblioteca JS para isso também:
http://html2canvas.hertzen.com/examples.html

Converter HTML em PNG


How can I see which Column A entries do not appear in Column B?

Question: I am trying to see which Column A entries are not in Column B and then print these entries in Column C, and the corresponding B entries in Column D.
This code keeps giving me "Run time error '13': Type mismatch".

Option Explicit

 Sub Test()

  Dim LR As Long, i As Long
  LR = 8

For i = 2 To LR
If WorksheetFunction.CountIf(Range("A" & i), Range("B:B")) = 0 Then
    Debug.Print Range("A" & i)
End If
Next i

End Sub

Comment: why not use a vlookup instead ? this sounds like a case for it.
Comment: You've got the argument order within `CountIf` flipped. The first argument is the range, and the second is the criterion.
Comment: @BigBen thanks, spot on
Answer: You could try:
Answer with  For Each Loop:
Option Explicit

Sub test()

    Dim LastRowC As Long
    Dim rngA As Range, rngB As Range, cell

    With ThisWorkbook.Worksheets("Sheet1")

        Set rngA = .Range("A2:A" & .Cells(.Rows.Count, "A").End(xlUp).Row)
        Set rngB = .Range("B2:B" & .Cells(.Rows.Count, "B").End(xlUp).Row)

        For Each cell In rngA

            If Application.WorksheetFunction.CountIf(rngB, cell) Then
            Else
                .Range("C" & .Cells(.Rows.Count, "C").End(xlUp).Row + 1).Value = cell.Value
            End If
        Next

    End With

End Sub

Answer with Arrays:
Option Explicit

Sub test()

    Dim LastRowC As Long
    Dim arrA As Variant, arrB As Variant, i As Long, y As Long
    Dim strA As String, strB As String
    Dim Appears As Boolean

    With ThisWorkbook.Worksheets("Sheet1")

        arrA = Application.Transpose(.Range("A2:A" & .Cells(.Rows.Count, "A").End(xlUp).Row))
        arrB = Application.Transpose(.Range("B2:B" & .Cells(.Rows.Count, "B").End(xlUp).Row))

        For i = 1 To UBound(arrA)

            strA = arrA(i)

            Appears = False

            For y = 1 To UBound(arrB)

                strB = arrB(y)

                If strA = strB Then
                    Appears = True
                    Exit For
                Else
                    Appears = False
                End If
            Next y

            If Appears = False Then
                .Range("C" & .Cells(.Rows.Count, "C").End(xlUp).Row + 1).Value = arrA(i)
            End If

        Next i

    End With

End Sub

Answer with Dictionaries:
Sub tesqt()

    Dim dictA As Object, dictB As Object
    Dim i As Long
    Dim cell As Range
    Dim key As Variant

    Set dictA = CreateObject("Scripting.Dictionary")
    Set dictB = CreateObject("Scripting.Dictionary")

    With ThisWorkbook.Worksheets("Sheet1")

        For Each cell In .Range("A2:A" & .Cells(.Rows.Count, "A").End(xlUp).Row)
            If Not dictA.Exists(cell.Value) Then
                dictA.Add key:=cell.Value, item:=dictA.Count + 1
            End If
        Next

        For Each cell In .Range("B2:B" & .Cells(.Rows.Count, "B").End(xlUp).Row)
            If Not dictB.Exists(cell.Value) Then
                dictB.Add key:=cell.Value, item:=dictB.Count + 1
            End If
        Next

        For Each key In dictA.keys

            If Not dictB.Exists(key) Then
                 .Range("C" & .Cells(.Rows.Count, "C").End(xlUp).Row + 1).Value = key
            End If

        Next

    End With

End Sub

Results:


Initial guess of a GARCH-DCC model?

Question: I'm trying to fit an ECM-GARCH-DCC model for 2 time series, the whole 3 in the same time using log-likelihood estimation. It has 14 parameters to estimate:

ECM has 2 gammas and 1 lambda per time series, this gives 4 gamma and 2 lambda for 2 TS.
GARCH has 2 alpha, 2 betas, 2 omega for our 2 TS.
DCC has only alpha and beta regardless of the number of TS (thanks to Engle 2002 variance targeting which gives a formula of conditional correlation given CCC matrix, getting rid of correlation omega)

To avoid problem of explosive GARCH or values out of bounds, I "crop" the tried params to their bounds in my loss function and add a huge penalty (proportional to the distance from closest bound ** 2) to the -log-likelihood loss to tell the optimizer not to cross the bounds or constraints (GARCH params positive and alpha+beta < 1)
I tested my fit function by feeding the optimizer with a random realisation (2 TS) of this model with known parameters. Its goal is to find these same parameters.
It looks like BFGS is having a hard time finding these 14 parameters in the same time : ECM params are retrieved pretty fast though, but GARCH and DCC keep being completely different from expected params (or maybe there are several solutions with low loss?).
So what I'd like is to "help" my fit function by setting initial param values with a smart initial guess, especially for the GARCH and DCC params that it struggles to retrieve.
Is there some well known smart initial guess for GARCH or DCC models ?
Comment: Check out the implementations in `rugarch` and `rmgarch` in R or some other packages in R or other programming languages. They should specify what the initial parameters are. If not, you can open the code and see for yourself. I think $(\alpha,\beta)=(0.10,0.85)$ or $(0.05,0.90)$ is reasonable for the GARCH part. Maybe try something similar for the two DCC parameters?
Comment: Thank you I'll check this out :) Yeah that's what I thought for alpha and beta, but what about omega ? It appears that it can find low loss for lower omega and higher alpha/beta (if you set omega = 4 and alpha,beta = 0, it can find omega = 2 and beta = 0.8, like if it wanted to set a high beta at all times by itself)
Answer: GARCH: I think reasonable starting values for $(\alpha,\beta)$ are  $(\hat\alpha^0,\hat\beta^0)=(0.10,0.85)$ or $(0.05,0.90)$. Since the unconditional variance $\sigma^2=\frac{\omega}{1-(\alpha+\beta)}$, the starting value for $\omega$ should be $\hat\omega^0=(1-(\hat\alpha^0+\hat\beta^0))\hat\sigma^2$ where $\hat\sigma^2$ is the empirical (unconditional) variance of the residual from the ECM equation. You can obtain the latter by estimating the ECM without the DCC-GARCH part; the estimates will not be efficient but still consistent.
DCC: I am less sure what starting values might be reasonable, but I would try something similar as with GARCH.
Another option is to check out the implementations in rugarch or fGarch and rmgarch in R or some other packages in R or other programming languages. They should specify what the initial parameters are. If not, you can open the code and see for yourself (unless the implementation is not open source).
Comment: @JeremLachkar, good point. I have updated my answer accordingly.
Comment: I understand you on the GARCH alpha and beta, but for omega, what we have from the TS is ECM unconditional variances (i.e, delta_x unconditional variance), which is not the same variance as the ECM *residual* unconditional variance, that we can't have unless we fix ECM params, but since we want initial guess, we don't have ECM params yet. Do I miss something in my understanding here in your opinion?
Comment: Here is the implementation of starting value for rugarch : https://github.com/alexiosg/rugarch/blob/master/R/rugarch-startpars.R
From what I understand, it looks like they take initial parameters depending on the underlying model (ARIMA, etc.)
Comment: Excellent thank you :)
Comment: @JeremLachkar, I am glad I could help!

Initial guess of a GARCH-DCC model?


Why do I only iterate up to sqrt(N) in the problem below?

Question: Summary of problem

Suppose there are five men and a monkey on an island. During the
  night, one man woke up and divided gathered coconuts into five piles
  and took his share and hid it. One coconut was left over and was given to the
  monkey.
A second man woke up and did the same thing. After dividing the
  coconuts into five piles, he hid his share and one coconut was left over which he gave to
  the monkey. The third, fourth, and fifth man followed exactly the same
  procedure. The next morning, they divided the remaining coconuts into
  five equal shares. This time no coconuts were leftover.
If we know the number of coconuts that were gathered, what is the
  maximum number of persons (and one monkey) that could have been in the
  island if the same procedure occurs?

Note that the above is my personal abstraction. The full problem is available here.
Summary of my solution
I will apply the following procedure: (N is the number of coconuts gathered and d is the maximum number of people possible to do the above procedure in the problem summary)

Set number d = sqrt(N - 1) + 1
Given number d, calculate N-1 and get the new value of N, which can be gotten using this formula: N = (N-1)/((N-1)/d) only if (N-1)%d == 0. Repeat calculating this formula d times
If in step 2, the condition (N-1)%d == 0 is not fulfilled, set number d = d - 1 and repeat step 2
If step 2 succeeds repeating d times, check the final N whether or not it is divisible by d, i.e. N % d == 0. If yes, then the number d that was used is the solution
If d == 2 and is still not a solution, then there is no solution

My full solution is available here and it has been accepted as answer.
Question
Why did I have to only pick d up to sqrt(N - 1) + 1 or ceil(sqrt(N))? How do I know that numbers beyond ceil(sqrt(N)) won't fulfill the condition? What's the theory behind it? (I know that I only have to repeat until ceil(sqrt(N)) because the book said so. I tried a solution that involves picking all possible ds above the square root threshold but still smaller than N and I got TLE [time limit error].)
Comment: You shouldn't link to an external site for the problem. Please add at least a reduced version in quer question.
Comment: @MrSmith42 I've added the important parts of the problem.
Comment: perhaps you should also say what is `d` and `N` with respect to the problem.
Comment: @norok2 Added the info.
Answer: OK, the reason is simple and it is inherent to the procedure.
Let's assume that you have d = 10 people and m = 1 monkeys.
What is the minimum number of coconuts that the last person waking up has to find to get his fair share? The answer is d + m = 11.
What is the minimum number of coconuts that the one but last person waking up has to find to get his fair share? Now the answer is a bit trickier if we want to get exact numbers, but in general it has to be at least (d + m) + (d + m) = 22 = 2 * (d + m) so that the last one can get his fair share after him.
Since this goes on for the number of persons, the multiplying factor in front of (d + m) for the first person has to be d.
Hence N >= d * (d + m), and for m > 0 this also holds N >= d * d.
Now you take sqrt() both sides and you get your answer.
Comment: Okay, thank you. I understand now. I'm kinda curious how you came up with that reason though. Reading it makes me understand, but thinking the **how** before getting an explanation is kinda hard for me.
Comment: What's the difference between the third paragraph's and fourth paragraph's questions? Did you mistype something?
Comment: @Richard sorry, corrected, one is last person, the other one is last but one.
Comment: I just started writing down the equations and realized that the integer constraint was easier to see bottom-up. In principle, you can come up with a similar equation starting from the first person, but it is less explicit to realize that you have to get a factor `d` for each iteration.


Get all products of user in Bugzilla

Question: I want to get all products from "products" table for a particular user.
Something like:
<code>"select product_name from products where user='user_email'";
</code>
Can anybody help me to understand the relationship between the "products" and "profiles" tables in Bugzilla?
Answer: Not exactly an answer but I got very useful help from this link.

Get all products of user in Bugzilla


Windows 2008 Boot DVD

Question: I am looking to create a custom boot DVD to run my unattended installs of windows 2008. I would like to have a menu system that lets the tech select what version of the OS they would like to install and version (x86/x64).  I know you can run the windows 2008 setup, and exit to command prompt, but I would like there to just be a menu that will kick off whichever script needed.
What would be the best way to do this?
Thanks
Comment: After researching a bit, I am going to use a PE disk and inject the OS files into that.  Then I will have a batch file on the disk that I will call that will call each unattended file.
Answer: On a related note - using a flash drive instead of a DVD for this has multiple advantages.

Speed
Rewritable
Ease of use (not all servers have built in DVD players)
You can keep the drive updated with other drivers, software and tools

This is the way I use to prep the USB stick.
I use this for client installs because we're a rather small operation and everyone are local admins and are allowed to have their latptops the way they want. I find it is far easier than to try to keep a distro server updated with drivers and software. A bit more manual, but totally flexible.
You could of course do zero or light touch install from a USB just as well as from a DVD, if that is your preference. It still has the speed and rewrite advantages over a DVD.
Hope this helps.
Answer: What you're looking for is HTA files "HTML Application".  The feature is built into WinPE and lets you script similar to vbscript a menu system much like a HTML file that can autostart with your WinPE disk and let you do just about anything you can imagine.
I've made one that:
logged you into AD
mapped drives
launch batch files
formatted hard drives
copy drivers file and edit ini files on drive
pulled user data off drive
let you choose the OS (.wim) to imagex to the drive
etc.
To get HTA files to work on WinPE you need to add it to your WinPE image, similar to this:
peimg /install=HTA c:\winpe_x86\mount\Windows
HTA is frustrating to code as it's not a common scripting language and not well documented but it works.  Our solution was pure Windows Deployment Toolkit and WinPE 2.0 based for over dozens of different hardware setups to over 3000 computers all done via DVD or USB stick.
Google "winpe script hta" for all the help you need.

Windows 2008 Boot DVD


Facebook Wall Status

Question: Let me first thank you for allowing me to ask some question here. I hope you can help me with the following question.
I want to post some message on User's Facebook status. It is successful with the following code:
$params = array('access_token'=>$access_token, 'message'=>$message);
        $url = "https://graph.facebook.com/".$fbuserid."/feed";
        $ch = curl_init();
        curl_setopt_array($ch, array(
        CURLOPT_URL => $url,
        CURLOPT_POSTFIELDS => $params,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_VERBOSE => true
        ));
        $result = curl_exec($ch);

What do I need to add or do to post image and/or link affiliate to this post msg? Thank you!
Answer: In order to publish a photo to a user's album, you must have the publish_stream permission. With that grantedd, you can upload a photo by issuing an HTTP POST request with the photo content and an optional description to one these to Graph API connections:

https://graph.facebook.com/USER_ID/photos - The photo will be published to an album created for your app. We automatically create an album for your app if it does not already exist. All photos uploaded this way will then be added to this same album.
https://graph.facebook.com/ALBUM_ID/photos - The photo will be published to a specific, existing photo album, represented by the ALBUM_ID.

Example:
<?php
       $app_id = "YOUR_APP_ID";
       $app_secret = "YOUR_APP_SECRET";
       $post_login_url = "YOUR_POST_LOGIN_URL";

       $code = $_REQUEST["code"];

       //Obtain the access_token with publish_stream permission
       if(empty($code)){
          $dialog_url= "http://www.facebook.com/dialog/oauth?"
           . "client_id=" .  $app_id
           . "&redirect_uri=" . urlencode( $post_login_url)
           .  "&scope=publish_stream";
          echo("");
         }
        else {
          $token_url="https://graph.facebook.com/oauth/access_token?"
           . "client_id=" . $app_id
           . "&redirect_uri=" . urlencode( $post_login_url)
           . "&client_secret=" . $app_secret
           . "&code=" . $code;
          $response = file_get_contents($token_url);
          $params = null;
          parse_str($response, $params);
          $access_token = $params['access_token'];

         // Show photo upload form to user and post to the Graph URL
         $graph_url= "https://graph.facebook.com/me/photos?"
         . "access_token=" .$access_token;

         echo '';
         echo '<form enctype="multipart/form-data" action="'
         .$graph_url .' "method="POST">';
         echo 'Please choose a photo: ';
         echo '<input name="source" type="file">

';
         echo 'Say something about this photo: ';
         echo '<input name="message"
             type="text" value="">

';
         echo '<input type="submit" value="Upload"/>
';
         echo '</form>';
         echo '';
      }
?>

Sample Output:
{
   "id": "1001207389476"
}

Documentation: https://developers.facebook.com/docs/reference/api/photo/
Hope this helps!
Comment: Can you help me by explaining? I do have the access token and image link already.. How do I post to user timeline?

Facebook Wall Status


What is the sql query to join command to join 2 tables from 2 different schemas

Question: What is the sql query to join command to join 2 tables from 2 different schemas,but which are present in single database.
Answer: In your query, you have to prefix tables with schema name (schema_A.table1 and schema_B.table1). Be sure to have read-access on these schemas when executing the query.


Is friction necessary for a Tractrix Curve?

Question: Is friction necessary for a
Tractrix Curve? (ANSWERED)
1.If friction is necessary, *what curve will the particle trace if friction is not present?*
(NOT ANSWERED)
2.If friction is not necessary, *what curve will the particle trace if friction is present?*(ANSWERED)
3.Does the setup have a string or a rigid rod attached to the tractor?
(ANSWERED)
I have asked this on a Math forum because here friction is to be viewed Mathematically, and not Physically.
NOTE This came when a question was asked on a WhatsApp group on physics I was part of. My level of physics is nowhere near to solve this problem, but the person who solved on the group did it by assuming friction was not present. But Wikipedia said friction is present. I was confused, hence this question.
Comment: Don't rely on Wikipedia for accurate mathematical definitions. The same paragraph that mentions friction also mentions an "infinitesimal speed," which appears to be a garbled account of the motion of the "tractor." (At an infinitesimal speed, it would take an infinite amount of time for the tractor to move one unit's distance.)
Comment: You can't view the friction mathematically, or you can, but you have to say what a "tug on a cord" is etc.
Comment: Hi @Prasanth My hunch is that you may have got confused between the the circles whose radii are tangents of tractrix and the tractrix itself. But I may be entirely off-track also..
Comment: @ Prasant Gokhale Please provide links to the work referred to.
Comment: @Narasimham Pls click on the "Tractrix" i the question.
Answer: The mathematical description of a tractrix does not even mention friction.
The tractrix is defined as a curve with the property that the distance from any point on the curve to a fixed straight line measured along the tangent of the curve is constant.
This can be interpreted in classical mechanics as the path of an object that is pulled by a string in certain circumstances -- and for this interpretation one probably needs to assume that the intertia of the object is negligible compared to the friction, such that its direction of movement at any point is exactly the direction of the string that pulls it. However, this is purely a matter of interpretation and not part of the definition of the curve, which is entirely independent of such physical concepts.
Comment: In mathematics it definitely is defined mathematically. We then leave it to applied fields to argue that this abstract definition defines a curve that is relevant to one of their problems.
Comment: Ahh! Thats a new perspective. So what you are saying is that a tractrix is defined using a mathematical setup and not some "tractor pulling dog" setup?
Comment: A different interpretation would be to imagine a two-wheeled cart with a long drawbar fixed rigidly to it. When the end of the drawbar is forced to move in a straight line, the center of the cart (defined as the point where a perpendicular line from the draw point meets the wheel axle) moves along a tractrix, unless the wheels skid sideways.
Answer: The only book I came across friction in relation to the pseudosphere revolution surface from tractrix is E.H. Lockwood's  A Book of curves, Cambridge 1961 that too on a single line. may be there are other references.
It has the property of constant tangent (red line) length $a$ defined as
$$ \frac {\sin \phi}{r} = \frac{1}{a} $$
Unless you draw the force/vector diagram you are not connecting physics and maths. So try to draw one. Perhaps it is without friction, ( iirc) the shape does not change with wear out of grinding stone.
A rudimentary situation could be depicted thus: If $F_N$ is normal force at interface we have friction force
$$ \tan \phi = \frac{F_{horiz}}{F_{vert}}$$
then the horizontal grinding force that is frictional force creating wear on a stone of given width $w$ approximately could be $ \dfrac{F \,\sin \phi}{2 \pi r w} $ constant on projected area for grinding stone shaped as a tractrix.

EDIT1:
I am trying to figure out another context of how OP may have imagined tractrix generation. It has to do with the orthogonal trajectories of circles whose rolling/dragging on a line which he appears to assume creates a tractrix locus. The tractrix is produced as tangent envelope but not as a locus of a point on a rolling circle in any manner.
This is a drag curve without rolling. There is no rolling at all, but only dragging , so circles slip  severely everywhere except at at cusp when circle contacts x-axis, a situation locally like the cycloid with zero x-axis speed, no drag. Otherwise friction is unnecessary and no reference need be made for this scenario.
The variable drag as a parameter $h$ is valid for the pushed circles ( please note, not tractices!) :
$$ (x-h)^2  +(y-a)^2 = a^2 \tag1$$
with parametric equations
$$ x= (h - a \cos \phi),\, y= a ( 1 -\sin \phi) \tag2$$
They produce an orthogonal trajectory of tractrices I sketched roughly here. The envelope of cranks (green line) $PC = a $ touches the tractrix at $P$. The tractrix is one in a set of orthogonal trajectories of above displaced/sliding circles, along lines parallel to x-axis.

Parametric  equations of orthogonal trajectories tally with standard tractrix as:
$$ y = a (1-\sin \phi) ,\, -x = a ( \cos \phi + log(tan (\phi/2))) ,\, \tag3 $$
where slope $ \phi$ is an arbitrary constant (single parameter) associating to constant length $a$.
EDIT 2:
Derivation of orthogonal trajectories
Differentiate (1)
$$ 2 (x-h) +  2 ( y-a) y^{\prime} =0 \tag4 $$
For Orthogonal Trajectories take negative reciprocal slope
$$ \frac{dy}{y-a}=  \frac{dx}{x-h} \tag5 $$
Next integrate using $\phi$ for arbitrary constant slope as generating parameter
$$ \frac{y-a}{x-h}=  \tan \phi \tag6 $$
or this is same thing as
$$ \frac{(y-a)}{\sqrt{(x-h)^2 + (y-a)^2}}=\frac{(y-a)}{a}=\sin \phi \tag7 $$
which is the ODE of standard tractrix (upto$\pm$ sign of radical) for this chosen axes direction resulting in (3).
EDIT3:
Drawing a tractrix is not so difficult. No need of modelling with friction and all, need not complicate more than necessary.
Assuming we have a  dragged object weight $W$ on a flat table of coefficient of friction  $\mu$ then force or tension in weightless string should be more than $\mu W$ for motion to ensue at all.
Dragging a magnet on a vertical plane I include  a simple demo ( magnet force instead of gravity, magnet pulled by a length of paper).
Tractrix followed but without trace
Errors in Wiki of reference. The arc length should be $ a \log \dfrac {y_2}{y_1}$.


r shiny slider range to graph

Question: edit: to clarify, the function to make my choropleth graph require "region" (state) and "value" columns, and simply color codes the region based on where value falls on the scale.
I want to make the "value" column dynamic and have the graph reference the dynamic column
I am not sure if I can read from an output object
I have a slider range from 2000-2014, and columns x2000-x2014.
I want the slider to change the data being graphed, so if I choose 2002-2010 it shows that data, etc.
It's a choropleth graph showing % change between the two years, so if I choose 2004 and 2007 on the slider I want it to pull (x2007-x2004)/x2004. I can get it to change to X2004 (low<- paste0("X", input$range[1])) but I cant really do df$low.
Answer: If I read the question correctly then you are able to create a character string with the name of the column in the data frame that you want to access (low is the name of the column in data frame df), but your attempts to access that column using df$low is not working.  Is that correct?
If so, then there is actually a fortune about this:
> library(fortunes)
> fortune('toad')

The problem here is that the $ notation is a magical shortcut and
like any other magic if used incorrectly is likely to do the
programmatic equivalent of turning yourself into a toad.
   -- Greg Snow (in response to a user that wanted to access a
      column whose name is stored in y via x$y rather than x[[y]])
      R-help (February 2012)

The answer to your question is in the bottom part of that quote and is detailed on the help page help('$') and in section 6.1 of An Introduction to R.

r shiny slider range to graph


Get the local IP address in sub Application_OnStart of global.asa?

Question: While it seems that this has been asked many times before, but there's a nasty twist here...
First, I'm working on a desktop application which calls a webpage on the same local system. This web application then calls upon a second server (in the local network) and needs to pass it's own IP address to the other server. Easy, of course: Request.ServerVariables("LOCAL_ADDR") and I'm done...
It won't work in this case... The code for the local web application is written in classic ASP and almost every sourcefile is encrypted, thus I cannot modify it's code. All I can fix is the global.asa file. In the Application_OnStart event of global.asa is the line Application("InternalIp") = "172.22.14.59" and indeed, that's the local IP address, hard-coded... And this application setting is used in the rest of the code to refer to the IP address.
However, my IP address in our local network tends to change every day, so every day I need to modify global.asa to contain my new IP address. I could write a small application which will modify global.asa for me every day on startup but I'd rather see a solution where global.asa would be smart enough to detect this IP address itself!
Unfortunately, the IP address must be known on the start of the application, not at the start of the session, else I could have used Application("InternalIp") = Request.ServerVariables("LOCAL_ADDR") in the Session_OnStart event. Tried this, application crashed, so it won't work.
But that line of code in Application_OnStart won't work, since Request is unknown at that moment, thus that would crash too. (Tried it, didn't work...)
So, my limitation is that I need to get the IP address within the Application_OnStart event of global.asa in a reliable way. And no, using DNS names don't work either. (Tried that too, didn't work.) What options do I have?
Answer: you could use the commandline (wscript.shell) and ipconfig?
or write your ip address in a textfile (with the help of another tool) and then read out that text file
you could also add an asp page to your application, call that asp page from your desktop application. on the new asp page you could everything you want (e.g. set the application var with the help of request.servervariables...) then at the end do a redirect to the "original" (encrypted) asp page...
Answer: I'm not sure about Application_Onstart(), but in your Session_onStart() it should be possible to get the servervariables.
I work on a classic ASP application that does just that. I'm currently on a linux machine, so I can't run the code, only look at it over the network, but what we do is use an include in the Global.asa, just above the script tag:


Why can't code inside unit tests find bundle resources?

Question: Some code I am unit testing needs to load a resource file. It contains the following line:
NSString *path = [[NSBundle mainBundle] pathForResource:@"foo" ofType:@"txt"];

In the app it runs just fine, but when run by the unit testing framework pathForResource: returns nil, meaning it could not locate foo.txt.
I've made sure that foo.txt is included in the Copy Bundle Resources build phase of the unit test target, so why can't it find the file?
Answer: When the unit test harness runs your code, your unit test bundle is NOT the main bundle.
Even though you are running tests, not your application, your application bundle is still the main bundle. (Presumably, this prevents the code you are testing from searching the wrong bundle.) Thus, if you add a resource file to the unit test bundle, you won't find it if search the main bundle. If you replace the above line with:
NSBundle *bundle = [NSBundle bundleForClass:[self class]];
NSString *path = [bundle pathForResource:@"foo" ofType:@"txt"];

Then your code will search the bundle that your unit test class is in, and everything will be fine.
Comment: @Chris I made a mistake with my previous edit, and edited the answer again. At test time, the app bundle is still the main bundle. If you want to load a resource file that is in the unit test bundle, you need to use `bundleForClass:` with a class in the unit test bundle. You should get the path of the file in your unit test code, then pass the path string along to your other code.
Comment: @Chris In the sample line I'm assuming `self` refers to a class in the main bundle, not the test case class. Replace `[self class]` with any class in your main bundle. I'll edit my example.
Comment: Does not work for me. Still the build bundle and not the test bundle.
Comment: @benzado The bundle is still the same (build), which is correct I think. Because when I am using self or the AppDelegate, both are located in the main bundle. When I check the Build Phases of the main target both files are in. But what I want to differ between main and test bundle at run time. The code where I need the bundle is in the main bundle. I have the following a problem. I am loading a png file. Normally this file is not in the main bundle due the user downloads it from a server. But for a test I want to use a file from the test bundle without copying it into the main bundle.
Comment: This works but how can I distinguish between a run-deploy and a test-deploy? Based on the fact if it is a test I need a resource from the test bundle in a class in the main bundle. If it is a regular 'run' I need a resource from the main bundle and not the test bundle. Any idea?
Comment: @Chris No idea. You should open a new Stack Overflow question.
Comment: @Chris - You should write your main classes so that they are testable, not so that they behave differently based on whether they're being tested or not. You'll end up writing new code which only runs in your tests and verifying that works without actually verifying that the code you run outside of your tests works.
Comment: @ArtOfWarfare Firstly, of course, you're right! ;) Secondly, this post is 2 years old. At that time I was learning objective-C. :)
Comment: This  answer also fixes that problem without changing code http://stackoverflow.com/a/24330617/468868
Answer: A Swift implementation:
Swift 2
let testBundle = NSBundle(forClass: self.dynamicType)
let fileURL = testBundle.URLForResource("imageName", withExtension: "png")
XCTAssertNotNil(fileURL)

Swift 3, Swift 4
let testBundle = Bundle(for: type(of: self))
let filePath = testBundle.path(forResource: "imageName", ofType: "png")
XCTAssertNotNil(filePath)

Bundle provides ways to discover the main and test paths for your configuration:
@testable import Example

class ExampleTests: XCTestCase {

    func testExample() {
        let bundleMain = Bundle.main
        let bundleDoingTest = Bundle(for: type(of: self ))
        let bundleBeingTested = Bundle(identifier: "com.example.Example")!

        print("bundleMain.bundlePath : \(bundleMain.bundlePath)")
        // …/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/Library/Xcode/Agents
        print("bundleDoingTest.bundlePath : \(bundleDoingTest.bundlePath)")
        // …/PATH/TO/Debug/ExampleTests.xctest
        print("bundleBeingTested.bundlePath : \(bundleBeingTested.bundlePath)")
        // …/PATH/TO/Debug/Example.app

        print("bundleMain = " + bundleMain.description) // Xcode Test Agent
        print("bundleDoingTest = " + bundleDoingTest.description) // Test Case Bundle
        print("bundleUnderTest = " + bundleBeingTested.description) // App Bundle

In Xcode 6|7|8|9, a unit-test bundle path will be in Developer/Xcode/DerivedData something like ...
/Users/
  UserName/
    Library/
      Developer/
        Xcode/
          DerivedData/
            App-qwertyuiop.../
              Build/
                Products/
                  Debug-iphonesimulator/
                    AppTests.xctest/
                      foo.txt

... which is separate from the Developer/CoreSimulator/Devices regular (non-unit-test) bundle path:
/Users/
  UserName/
    Library/
    Developer/
      CoreSimulator/
        Devices/
          _UUID_/
            data/
              Containers/
                Bundle/
                  Application/
                    _UUID_/
                      App.app/

Also note the unit test executable is, by default, linked with the application code.  However, the unit test code should only have Target Membership in just the test bundle. The application code should only have Target Membership in the application bundle. At runtime, the unit test target bundle is injected into the application bundle for execution.
Swift Package Manager (SPM) 4:
let testBundle = Bundle(for: type(of: self))
print("testBundle.bundlePath = \(testBundle.bundlePath) ")

Note: By default, the command line swift test will create a MyProjectPackageTests.xctest test bundle. And, the swift package generate-xcodeproj will create a MyProjectTests.xctest test bundle.  These different test bundles have different paths. Also, the different test bundles may have some internal directory structure and content differences.
In either case, the .bundlePath and .bundleURL will return the path of test bundle currently being run on macOS. However, Bundle is not currently implemented for Ubuntu Linux.
Also, command line swift build and swift test do not currently provide a mechanism for copying resources.
However, with some effort, it is possible to set up processes for using the Swift Package Manger with resources in the macOS Xcode, macOS command line, and Ubuntu command line environments.  One example can be found here: 004.4'2 SW Dev Swift Package Manager (SPM) With Resources Qref
See also: Use resources in unit tests with Swift Package Manager
Swift Package Manager (SwiftPM) 5.3+
Swift 5.3 includes Package Manager Resources SE-0271 evolution proposal with "Status: Implemented (Swift 5.3)". :-)

Resources aren't always intended for use by clients of the package; one use of resources might include test fixtures that are only needed by unit tests. Such resources would not be incorporated into clients of the package along with the library code, but would only be used while running the package's tests.

Add a new resources parameter in target and testTarget APIs to allow declaring resource files explicitly.

SwiftPM uses file system conventions for determining the set of source files that belongs to each target in a package: specifically, a target's source files are those that are located underneath the designated "target directory" for the target. By default this is a directory that has the same name as the target and is located in "Sources" (for a regular target) or "Tests" (for a test target), but this location can be customized in the package manifest.

// Get path to DefaultSettings.plist file.
let path = Bundle.module.path(forResource: "DefaultSettings", ofType: "plist")

// Load an image that can be in an asset archive in a bundle.
let image = UIImage(named: "MyIcon", in: Bundle.module, compatibleWith: UITraitCollection(userInterfaceStyle: .dark))

// Find a vertex function in a compiled Metal shader library.
let shader = try mtlDevice.makeDefaultLibrary(bundle: Bundle.module).makeFunction(name: "vertexShader")

// Load a texture.
let texture = MTKTextureLoader(device: mtlDevice).newTexture(name: "Grass", scaleFactor: 1.0, bundle: Bundle.module, options: options)

Example
// swift-tools-version:5.3
import PackageDescription

  targets: [
    .target(
      name: "CLIQuickstartLib",
      dependencies: [],
      resources: [
        // Apply platform-specific rules.
        // For example, images might be optimized per specific platform rule.
        // If path is a directory, the rule is applied recursively.
        // By default, a file will be copied if no rule applies.
        .process("Resources"),
      ]),
    .testTarget(
      name: "CLIQuickstartLibTests",
      dependencies: [],
      resources: [
        // Copy directories as-is.
        // Use to retain directory structure.
        // Will be at top level in bundle.
        .copy("Resources"),
      ]),

Current Issue

Swift 5.3 SPM Resources in tests uses wrong bundle path?
Swift Package Manager - Resources in test targets

Xcode
Bundle.module is generated by SwiftPM (see Build/BuildPlan.swift SwiftTargetBuildDescription generateResourceAccessor()) and thus not present in Foundation.Bundle when built by Xcode.
A comparable approach in Xcode would be to manually add a Resources reference folder to the module, add an Xcode build  phase copy to put the Resource into some *.bundle directory, and add a #ifdef Xcode compiler directive for the Xcode build to work with the resources.
#if Xcode
extension Foundation.Bundle {

  /// Returns resource bundle as a `Bundle`.
  /// Requires Xcode copy phase to locate files into `*.bundle`
  /// or `ExecutableNameTests.bundle` for test resources
  static var module: Bundle = {
    var thisModuleName = "CLIQuickstartLib"
    var url = Bundle.main.bundleURL

    for bundle in Bundle.allBundles
      where bundle.bundlePath.hasSuffix(".xctest") {
      url = bundle.bundleURL.deletingLastPathComponent()
      thisModuleName = thisModuleName.appending("Tests")
    }

    url = url.appendingPathComponent("\(thisModuleName).bundle")

    guard let bundle = Bundle(url: url) else {
      fatalError("Bundle.module could not load: \(url.path)")
    }

    return bundle
  }()

  /// Directory containing resource bundle
  static var moduleDir: URL = {
    var url = Bundle.main.bundleURL
    for bundle in Bundle.allBundles
      where bundle.bundlePath.hasSuffix(".xctest") {
      // remove 'ExecutableNameTests.xctest' path component
      url = bundle.bundleURL.deletingLastPathComponent()
    }
    return url
  }()

}
#endif

Comment: For Swift 4 as well,  you can use Bundle(for: type(of: self))
Answer: With swift Swift 3 the syntax self.dynamicType has been deprecated, use this instead
let testBundle = Bundle(for: type(of: self))
let fooTxtPath = testBundle.path(forResource: "foo", ofType: "txt")

or
let fooTxtURL = testBundle.url(forResource: "foo", withExtension: "txt")

Answer: Confirm that the resource is added to the test target.
Comment: Adding resources to the test bundle makes the test results largely invalid.  After all, a resource could easily be in the test target but not in the app target, and your tests would all pass, but the app would burst into flames.
Comment: What @dgatwood said. It also doesn't fix the problem
Answer: if you have multiple target in your project then you need to add resources between different target available in the Target Membership and you may need to switch between different Target as 3 steps shown in the figure below
Answer: I had to ensure this General Testing checkbox was set
Answer: Just for people like me, that missed this point in the original post:
Make sure that foo.md is included in the Copy Bundle Resources build phase of the unit test target
Answer: There is a code which finds the file in :
How to check if a file exists in the Documents directory in Swift?
I used it in a test as follows, which tests that my file is created and gives its location for further testing.
        let fileFound = XCTestExpectation (description: "Checking for DB File Found")

    let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
    let url = NSURL(fileURLWithPath: path)
    if let pathComponent = url.appendingPathComponent("filename.ext") {
        let filePath = pathComponent.path
        let fileManager = FileManager.default
        if fileManager.fileExists(atPath: filePath) {
            fileFound.fulfill()
            print("DB FILE AVAILABLE")
        } else {
            print("DB FILE NOT AVAILABLE")
        }
    } else {
        print("DB FILE PATH NOT AVAILABLE")
    }

    wait(for: [fileFound], timeout: 5)

This is not testing that the file is created in the right place, only that it is created.


Python Unicode %HH-escaping

Question: All,
I am working on an application that has a mixture of standard latin-1 characters and other languages. I would like to convert everything to the same "format" so that the Bing translator can understand it. There are two articles that I've looked at.

https://dev.laptop.org/ticket/2327 I actually want to do the reverse of this and convert this http://ar.wikipedia.org/wiki/حاسوب to this http://ar.wikipedia.org/wiki/%D8%AD%D8%A7%D8%B3%D9%88%D8%A8
Similar article but not quite what I was looking for. How to unquote a urlencoded unicode string in python?

My method is quite simple...
<code>    for w in wiki:
        q = (w[0])
        u = unicode(q, 'utf=8', errors='ignore')
        h = ''
        for c in u:
            h += do something amazing

        doTranslate(h)
</code>
Can anyone help to shed some light on what I am missing here?
Answer: urllib might help. At least this snippet works:
<code>#! /usr/bin/env python
# -*- coding: utf-8 -*-

import urllib

w = 'ar.wikipedia.org/wiki/حاسوب'
print urllib.quote (w)
</code>
Output is
<code>ar.wikipedia.org/wiki/%D8%AD%D8%A7%D8%B3%D9%88%D8%A8
</code>
Depending which encoding your input strings have you might need to call encode ('utf-8') prior to passing it to quote()
Comment: Thanks a lot! Now what if my string is part arabic and part latin like this. 'وب (ar)' How do I get around that?
Comment: But my input string is half latin and half arabic.
Comment: Very good point ;-) I am trying to translate some data using the bing translator and it can automatically detect the language. I am just having a hard time figuring out how to translate a string that is in two languages...

Python Unicode %HH-escaping