What are multi-variable calculus pre-requisite for Machine Learning

Question: I wanted to complete calculus pre-requisites for machine learning class. I am doing an online course of multi-variable calculus. Can someone please suggest what lectures after Lecture 15 are relevant.
Like I know Lagrange Multipliers are used in SVM, but the lectures after I have no clue of application in ML.
I have searched through ML books, each one mentions Multi-variable calculus as a pre-requisite. But how much I am confused about that.
Comment: This is a great chat topic.  Since comments are not for extended discussion; this conversation has been [moved to chat](http://chat.stackexchange.com/rooms/41621/discussion-on-question-by-abhishek-bhatia-what-are-multi-variable-calculus-pre-r).
Answer: You can't have too much math in this business, so you need to balance your depth of understanding to the desire to get up and running quickly.
I agree with the commenters about Lagrange multipliers. You also, at a minimum, need enough calculus to fake your way through a Newton-Raphson optimization argument.
If you want to understand the theory behind kernel operators, their eigenvalue decompositions, and the Riesz Representation theorem, then you need to delve into functional analysis -- this is basically linear algebra for infinite dimensional vector spaces with convergence thrown in. But you can practise machine learning without knowing all of that theory.
Bear in mind that it's called machine learning (as distinct from human learning), so it's probably more important to understand the algorithms that compute the answer rather than the mathematical theory, which only indicates the existence of an answer.
TL:DR Ignore the math; take the machine learning course; and whenever you come across something you don't understand, do the mathematical backfill. What math you need will depend on how the ML course is taught. A lot of those guys hate calculus and avoid it where possible.


How I can select which main file I must build in flutter during a release of a desktop application?

Question: In flutter a made a linux application. Is consumes an endoint that varies depending the environment I need to build for. For each environment I have a different main file:

For production I have a main-prod.dart
For staging I have a main-staging.dart
For local development I have a main-dev.dart
All files are located into `./lib/ folder with the rest of source code

During building for desktop application via:

flutter build linux or
flutter build windows or
flutter build macos

During run I can provide via -t parameter for example for local development I run:
flutter run -t ./lib/main-dev.dart

But how on Chirst's sake I can do the same for buidling as well?
Answer: In you case you can build your application via:
flutter ^device^ -t ^main_file^

Where ^device^ are one of the following:

windows
linux
macos

And the ^main_file^ is the one you use during flutter run` in your case you have theese commands to select from:

environment
file
windows
linux
macos

production
main-prod.dart
flutter build windows -t ./lib/main-prod.dart
flutter build linux -t ./lib/main-prod.dart
flutter build macos -t ./lib/main-prod.dart

development
main-dev.dart
flutter build windows -t ./lib/main-dev.dart
flutter build linux -t ./lib/main-dev.dart
flutter build macos -t ./lib/main-dev.dart

staging
main-staging.dart
flutter build windows -t ./lib/main-staging.dart
flutter build linux -t ./lib/main-staging.dart
flutter build macos -t ./lib/main-staging.dart


Confusion on match_parent and wrap_content between parent and children element in xml

Question:
In line 4,in the parent tag the android:layout_width has been set to wrap_content. But in the child tags, the android:layout_width has been set to match_parent. Then what is the meaning of match_parent for the child tags when the parent tag itself has just the width to wrap_content.
My straight-forward question maybe is that, why the child tags cover up the whole screen when they must agree to the wrap_content attribute of the parent tag.
Answer: It's just an error of the xml viewer, I've put the code in android studio and it just work fine. If you use "wrap_content" for width and height in the parent layout every child with "match_parent" for width and hight will be large and tall as the parent. I just modify the first child but it is the same for the others.
Comment: This means that child width layout depends on parent tag and not the screen when we set attribute value to match_parent. Is this what you mean?
Comment: Thank You! Please answer my above question.
Comment: If you set the width on parent to wrap_content and the child on match parent yes. As in the example i did above. You are welcome


How to use Ava with Angular/CLI build typescript project

Question: As a part of a project I am building I currently have an angular/cli typescript project I have created. We are currently using the karma testing framework, but are extremely interested in switching to AVA if possible.
I've currently done a npm install --save-dev ava
And I've looked at the typescript setup in the ava documentation
https://github.com/avajs/ava/blob/master/docs/recipes/typescript.md
I've also followed the setup on the main page itself and added an "ava" section to my package.json
"ava": {
  "files": [
    "**/*.spec.ts"
  ],
  "source": [
    "**/*.ts"
  ],
  "match": [],
  "concurrency": 5,
  "failFast": true,
  "failWithoutAssertions": false,
  "tap": true,
  "powerAssert": false,
  "require": [
    "babel-register"
  ],
  "babel": "inherit"
}

I've hoped that somehow by default this would pick up our currently written spec.ts files that have been tailored and written for karma, but it would seem that this isn't so as I'm only given
# Couldn't find any files to test
not ok 1 - Couldn't find any files to test

1..0
# tests 0
# pass 0
# fail 1

I've also tried obliterating the default test.ts file that is currently put in place by Karma and changing it to
import test from 'ava';
test('BLA', t => {
  t.pass();
});

In the hopes that I could at least bootstrap something to work with that I could maybe use to add/implement the rest of our test files with later. So far I've had no luck with this either.
Can someone who has taken this path before tell me what needs to be done to get the Ava test runner up and working; and furthermore, what may need to be done to adapt our currently existing karma/jasmine based test framework to Ava?
Thank you very much in advance!
Answer: I ran into this answer while searching for something else, and realized it might be worth chiming in, even though it's been a bit since the question was asked.
There is a path to run AVA + TS via ts-node. Additionally, there's a tsconfig-paths package that aids in correctly mapping to tsconfig's paths property, if being used.
Below is what the AVA config would roughly look like. Of course, your paths may be different based on your Angular CLI project structure, but the same basic principles apply:
"ava": {
  "compileEnhancements": false,
  "extensions": [
    "ts"
  ],
  "require": [
    "ts-node/register",
    "tsconfig-paths/register"
  ],
  "files": [
    "src/**/*.spec.ts"
  ],
  "sources": [
    "src/**/*.ts",
    "src/index.ts"
  ],
  "failWithoutAssertions": true
}

Additionally, you may have a testing-specific tsconfig, in which case you'd need to point to it via a TS_NODE_PROJECT environment variable that ts-node will pick up on. So, for example, you're test task might look like this:
TS_NODE_PROJECT=tsconfig-spec.json node_modules/.bin/ava --verbose

Note that because Node natively consumes only CommonJS (at least at the time of this writing), your tsconfig will need to compile to that module format. So, continuing the example above, your tsconfig-spec.json might look like this, among other desired options:
{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "module": "commonjs",
    "target": "es2015",
    "sourceMap": true
  }
}

The API between AVA and Jasmine is not the same, but it's actually, in my experience, similar enough that the conversion isn't too painful—mostly mechanical. At the time of this writing, there's an issue open to create a codemod for the conversion; however, it looks like it hasn't had much traction yet.
Answer: AVA currently only supports test files with a .js extension. You should precompile your TypeScript test files and change the files pattern to match the tests inside your build directory.
Comment: Is there seriously no other way to do this without a pre-processor that converts the files? A few of the open issues on the AVA project seem to suggest that there are ways to do this where this isn't necessary.
Comment: There's a lot of people saying it should be easy for their use case, which is correct, but that makes other use cases more difficult. Hence no, currently there is no other way to do this. There's a plan, but there's only so many OSS-hours in a week.


party vs randomForest: large accuracy discrepancy

Question: I have a classification problem where the main aim is maximising classification accuracy. I am using a random forest, and would like to also use the variable importance in my analysis.
For this reason, I thought it best to use cforest from the party package in R since it has been shown Strobl et al. 2007 that it gives unbiased variable importance.
However, I found that it is giving +-20% less accuracy when compared to the randomForest package. To my understanding there is not much between the two implementations so I did not expect such a large difference. I also read that cforest is more aligned to ordinal dependent variables, so I was actually expecting an increase in accuracy!
Can someone familiar with random forests please tell me if this is normal behaviour or if there is something else I am missing?
df <- read.csv(url("https://raw.githubusercontent.com/allandf/r-funcs/master/data/testdata.csv"))
df$rating <- as.ordered(df$rating)

require(caret)
#Split data according to 80% training, 20% test
flds <- createFolds(df[,"rating"], k = 4, list = TRUE, returnTrain = FALSE)
test_data <- df[flds$Fold1,]
train_data <- df[flds$Fold2,]
train_data <- rbind(train_data,df[flds$Fold3,])
train_data <- rbind(train_data,df[flds$Fold4,])

require(party)
set.seed(1234)
my_cforest_control <- cforest_control(teststat = "quad",
    testtype = "Univ", mincriterion = 0, ntree = 500, mtry = 5,
    replace = FALSE)

my_cforest <- cforest(rating ~ ., data = train_data,
                      controls = my_cforest_control)
cforest_pred <- predict(object = my_cforest, newdata = test_data[,-9])
confusionMatrix(cforest_pred, test_data[,9])

require(randomForest)
set.seed(1234)
my_randomForest <- randomForest(rating ~ ., data = train_data,
                                importance = TRUE, ntree = 500,
                                mtry = 5, replace = FALSE)

randomforest_pred <- predict(object = my_randomForest, newdata = test_data[,-9])
confusionMatrix(randomforest_pred, test_data[,9])

I also tried first learning the parameter mtry using 10 fold cross validation, but it did not make a difference. I also tried all variations of teststat and testtype mentioned in the party documentation.
EDIT: I thought it might be a numerical issue, so I tried scaling the dataset first, unfortunately this didnt make a difference.
Comment: I had similar experience, seems Leo's random forest is really good in many data sets. other models, although the author may argue better, are not that good in may real world data.
Answer: The "problem" is that your response is an ordered categorical variable at many levels, and neither randomForest nor cforest were designed to deal with this case. cforest uses linear scores (which might or might not be appropriate). While tree induction and forest aggregation might work, variable importances (and model comparison) will break because misclassification error and its friends are telling the wrong story. These measures ignore the ordering and you want to take this information into account.
What can be done? In a nutshell, one can start with a proportional odds model and then use model-based trees (and the corresponding forests) to improve upon this initial unconditional model. The key point is that the proportional odds model gives you a likelihood and this is an appropriate way to assess risk in this situation. Here is some (still experimental and relatively slow) code for your dataset:
df <- read.csv(url("https://raw.githubusercontent.com/allandf/r-funcs/master/data/testdata.csv"))
df$rating <- as.ordered(df$rating)

require("caret")
#Split data according to 80% training, 20% test
set.seed(1234)
flds <- createFolds(df[,"rating"], k = 4, list = TRUE, returnTrain = FALSE)

library("tram")
library("trtf")
ll <- matrix(0, nrow = length(flds), ncol = 3)
colnames(ll) <- c("Polr", "Tree", "Forest")
for (i in 1:length(flds)) {
    fd <- flds[[i]]
    win <- as.numeric(!(1:NROW(df) %in% fd))

    ### fit unconditional proportional odds model
    ### see vignette("tram", package = "tram") and
    ### vignette("mlt", package = "mlt.docreg")
    m <- Polr(rating ~ 1, data = df, weights = win)
    ### out of sample log-likelihood
    ll[i, "Polr"] <- logLik(m, w = 1 - win)

    ### partition unconditional model the mob-way,
    ### see https://arxiv.org/abs/1701.02110 -- describes continuous case only,
    ### but DOI: 10.1111/sjos.12291 explains the ordered categorical case
    mt <- trafotree(m, formula = rating ~ ., data = df, weights = win,
                    control = ctree_control(alpha = .0001, minsplit = 100))
    ### out of sample log-likelihood
    ll[i, "Tree"] <- logLik(mt, w = 1 - win)

    ### corresponding forest
    mf <- traforest(m, formula = rating ~ ., data = df,
                    ntree = 50, weights = win, mtry = 5, trace = TRUE,
                    cores = 3)
    ### out of sample log-likelihood
    ll[i, "Forest"] <- logLik(mf, w = 1 - win)
    print(ll)
}

### (conditional) variable importance
mf <- traforest(m, formula = rating ~ ., data = df,
                ntree = 50, mtry = 5, trace = TRUE, cores = 3)
### likelihood-based variable importance
varimp(mf)
### likelihood-based conditional variable importance
varimp(mf, conditional = TRUE)
### predictions are conditional distribution functions
predict(mf, newdata = df[1:3,], type = "distribution")
### or densities
predict(mf, newdata = df[1:3,], type = "density")

One can speed-up things quite a bit by using a smooth basis function for your ordered response and some other tricks, but computing time is cheap these days and, especially in cases like this, worth the buck!
Best,
Torsten
ps. Please contact me by email if you have questions. I'm not following discussions on other channels.
Answer: You can also use ordinal forests. In this case it is not better than the standard random forest, at least for the test dataset. For a better evaluation you should use cross-validation (for example via mlr package) instead of a simple test dataset, which randomly can provide better results for the standard random forest.
Example code for ordinal forest:
library(ordinalForest)
ordforest <- ordfor(depvar="rating", data=train_data, nsets=1000, ntreeperdiv=100,
  ntreefinal=5000, perffunction = "equal")

ordforest_pred = predict(ordforest, newdata = test_data[,-9])
confusionMatrix(ordforest_pred$ypred, test_data[,9])


PHP SimpleHTMLDOM : how to get value from div by class name inside of another div?

Question: i have following HTML snippet:

cena: 11.30 CZK

              množství
              <input type="text" size="1" id="quantity_178" name="quantity" value="1" data-cip-id="quantity_178">

            <input type="hidden" name="parametersValue" value="">
            <input class="button pull-right" name="przyciskz" type="submit" value="Do košíku" onclick="ajax_cart_add(178, jQuery('#quantity_178').val(), 'cz', 0.115); return false;">

Zboží je k dispozici na skladě

I'm trying to get value inside the  div.
Div with same class is contained in the document a few times. So i need to get only this one inside of the div
If i tried this:
 //GET NETTO PRICE
    foreach($html->find('div[class=price-box szczeg_oper]') as $element){
        $itemPrice = $element->plaintext;
    }

I got text of whole div.
How can i access into inner elements inside of the found div by class?
I tried to find solution in documentation, but without luck:
http://simplehtmldom.sourceforge.net/manual.htm
Many thanks for any advice
Comment: Yes, i need to use PHP
Comment: Do you NEED to use PHP for this? If you just want to get one of inner div's, you can use javascript's [GetElementsByClassName](http://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp)
Answer: I'm assuming you're after the price
foreach($html->find('div[class=price-box szczeg_oper]') as $element){
    $itemPrice = $element->find('.price',0)->plaintext;
}

Comment: Invalid argument supplied for foreach()
Comment: Edited my answer, if it's not correct please be more specific about exactly what data you are looking for in your html example


Value from dynamic table (Cypress)

Question: I need to take a value from a table that changes after every page refresh. For example CPU for Chrome
describe('test dynamic table and check Chrome CPU', () => {
  it('passes', () => {
    cy.visit('some url')
    cy.contains('span', 'CPU')
      .parent()
      .within(() => {
        cy.contains('[role=cell]', 'Chrome')
      })
  })
})

Table:

UPDATE:
FYI
After refreshing the page, you will get columns and row changing place:
enter image description here
Comment: What do you want to do with the CPU Value ?
Comment: I need to take value from the table and check it with constant value. I just can't understand how I can take value from table if columns and rows change their places
Answer: You can do like this:
cy.contains('span', 'Chrome')
  .parent()
  .within(() => {
    cy.contains('[role=cell]', '%')
      .invoke('text')
      .then((text) => {
        cy.log(text) //Logs 8.3%

        //removing % and converting into number and asserting
        expect(+text.replace(/%/g, '')).to.be.greaterThan(5)
        expect(+text.replace(/%/g, '')).to.be.lessThan(15)
        expect(+text.replace(/%/g, '')).to.eq(8.3)
      })
  })

Comment: it isn't work, because table change when you refresh page (row and columns change place too)
Comment: Can you add the HTML of the table after a refresh, so that it gives me an idea, of what changes?
Comment: Update my question

Value from dynamic table (Cypress)


Infinite number of regular exressions for a given language

Question: Took a Theory of Computation exam where one of the questions was :
Is there an infinite amount of regular expressions for the language $L=\{aa,bb\}$ ?
The proof requested was just an informal one.
My intuition was that if a set is countably infinite then it is infinite itself.
Then I thought that the following regular expressions are different :

$(aa)\ \cup \ (bb)$
$(aa)\ \cup \ (bb) \ \cup \ \emptyset$
$(aa)\ \cup \ (bb) \ \cup \ \emptyset \ \cup \ \emptyset$
$\dots$

So I can define a set of them that can be countably infinite.
To be clear I was taught some of the very basics of set theory so bare with me.
My questions are :

Are the regular expressions mentioned above different from one another?
Is a countably infinite set infinite itself?
Comment: @AndreaMarino a regular expression describes a regular language and $\{aa, bb\}$ is a regular one. As explained here : https://en.wikipedia.org/wiki/Regular_expression#Formal_language_theory.
Comment: What do you mean by "a regular expression for a language"? A regular expression defining the language? A regular expression built with symbols for the language? Also, what do you mean by the unione of expressions?
Answer: Your intuition is right. You could also write $aa$ as $a\varepsilon a$, $a\varepsilon \varepsilon a$, etc., to get another countable set of regular expressions.


Hands-separate piano practice doesn't seem to help with hands-together playing

Question: I'm a late starter with 'official' piano lessons and wondered if my learning experience is typical. As I'm sure many do, my piano teacher tells my to practice left and right hands separately. I can often manage to learn that quite easily and play each hand with minimal errors.
However, playing hands-together and all that separate practice seems for nought - my hands won't do what they are told. It's honestly like I have to learn the whole thing from scratch when I use both hands - and my error rate goes way up. I get disheartened because I can't seem to get rid of the errors. It takes me so long to get a piece anywhere near good I'm generally sick to the back teeth of playing it before I get it error free (if I ever do).
Is it like that for everyone?
Comment: Yes, it is. I'm considered a good piano player, and I can assure you that getting there involves *exactly* this road. The trick is to remember that while you struggle with hand coordination and feel like you're getting nowhere, you *are*, in fact, continuously getting somewhere, *even if you yourself don't notice yet*.
Comment: Learn to play hands together, having learned each hand separately is like solving a puzzle.
Learn to play hands together, without having learned each hand separately is like solving a puzzle, without the pieces of the puzzle!
Comment: One alternative is to learn one hand first and then both hands together.
Answer: Your experience is quite typical. Playing two hands at the same time is completely different than playing both separately.
But the point of learning parts separately is NOT about making it easier to play both hands together. It's about learning all the "other" stuff (like correct hand position, articulation etc.) without having the distraction of the second hand.
Comment: The second paragraph here makes this the best answer so far in my view.
Comment: @Bacs: Exactly. I'm an amateur, and it's actually easier to learn both hands at once. But that comes at the cost of suboptimal finger usage, hand position etc. Of course, you can correct that, but playing both hands demands more attention, and you might miss your own mistakes.
Comment: Yes, this is a good answer. It's easier to ensure good technique by focusing on one hand at a time initially, even though ultimately there will be another learning curve with them together
Answer: As a piano teacher for more than 50 years I can assure you that you are not alone!  Many students have the same experience, though quite a few do not.  Of the hundreds I have taught I would say it breaks about 60-40 toward having the problem.
As Brad said in his comment to the original question (a comment which has now strangely disappeared), the secret is to go slow.  When you first start putting hands together on a new piece you may find you have to go three to four times more slowly that when you are doing hands separate.  Incrase SLOWLY.  When you find yourself making lots of mistakes, slow down more.  Be patient with yourself.  You'll get there.
EDIT: I should add that it's better NOT to try to play through the whole piece at once at first.  Break it into "chunks."  For most pieces a four-measure 'chunk' is about right.  Some pieces 6 or even 8 is better.  Let your progress tell you.
Comment: Yes, going slowly is the key. You should pick a speed at which you can play the passage with no mistakes, even if that is *ludicrously* slowly. (On note every 5 seconds isn't too slow - there is no 'too slow'.) If necessary concentrate on just a few bars at a time. Gradually increase the speed, always keeping it slow enough that you are not starting to make mistakes again. People who don't slow down enough just end up practising their mistakes, which is counter-productive.
Comment: Also if you do scales at all, try practicing them on a two-notes-for-one basis: that is, two scale notes in one hand during one note in the other.  By the time one hand has gone one octave the other has gone two.  (Obviously if the faster hand is the left you have to start out two octaves apart.)
Comment: I might perhaps helpfully have added that I have the exact opposite problem.  Practicing hands separate does me no good at all and is often counterproductive, making my playing of the piece worse instead of better!  Depending on your teacher's personality you might try going against his or her suggestion on this issue!
Comment: @L3B Hi do you think it helps when i take a piece of a song and i learn to play the chorous for example with two hands repeatidly to absorb the learning of two hands techniq. I mean using only this method for that purpose...i cant read scores proparly.
Answer: Yes, playing both hands together is quite difficult for beginners, even if you feel like you have mastered each hand separately. You will likely hit another big bump when you move on from playing similar things in both hands (like two octaves of a scale) to playing two different things (like a bass line and a melody). There is yet another big bump when you start playing very different rhythms (like the straight bass and ragged melody of a ragtime piece).
You can solve most musical difficulties by playing slowly enough. Very slowly if necessary. As you start to master the basic skills of hand independence, you should be able to pick up new pieces more easily, although each new piece may still challenge you at first. Any time you find yourself making mistakes, go slower. Even after a couple years of adult piano study, I still need quite a bit of hand independence work for each new piece.
Comment: I agree with both comments. Piano learning is a lifetime journey full of obstacles that need to be conquered. The harder you work through these difficulties, the better you'll be. As all said, slow is the key. Breaking it down is another: sometimes, I practise only a few notes at the time on a piece where there's difficulty. The more you practise your basics, the better foundations. The better foundations, the easier it will be in the future obstacles. Good luck
Comment: Oddly, I do not have the same problem with pedal work! I find using the sustain pedal to be quite intuitive, perhaps because I have practiced tapping my foot in time for my whole life (and I drive a manual transmission).
Comment: "You can solve most musical difficulties by playing slowly enough" - slowly and consciously controlling the process of playing. When you find an error: stop, fix it and slowly play without an error several times. Consciousness and slow speed are very important.
Answer: Different strategies work for different pieces.  Learning to play a Bach fugue would of course be quite different from learning a piece where the left hand is just a bunch of chords.
People's brains work differently.  I have two kids, both of whom started learning piano at a young age, through the same method.  One of them has progressed marvellously.  The other one never got the hang of hands-together playing, and eventually gave up.  Perhaps the piano is just not the right instrument for him.
That said, there are intermediate steps you can take between hand-separate and hands-together practice:

You say you can play hands separately with minimal errors.  Are you sure that you can do so in rhythm?  If you can't play hands-separate correctly to a metronome, then it's going to be a mess when you put the hands together.
Can you play hands separately while not looking (or barely looking) at your fingers?  Because you won't have the luxury of looking at both hands — at best, you will be able to look at one.
Try humming the tune of one hand while playing the other.  Then switch.  The idea is to force your brain to think about the hands-together result before you actually try doing it.  Your hand signals and your vocal signals go through different neural channels and are less likely to get confounded than signals to your left and right hands.
Try pretending to play with both hands on a table.  The idea is to get a feel for how the hands fit together and get the rhythm right without worrying about the exact notes.
Comment: I think this is great advice. When learning to walk bass lines in the left hand and improvise in the right hand, I was told that the left hand must become so automatic that the brain can focus all of its attention on the right hand. I think the first few bullets are great ways to improve the each hand's automaticity.
Answer: I think some people have the wrong view about piano, and instruments that are similar, when the issue of "hand independence" is discussed. Cognitive science these days seems to indicate that humans never truly "multitask" in their conscious actions; they simply switch between individual tasks very quickly. While I can imagine a human with an unusual neurological feature (such as a severed corpus callosum) performing true multitasking (such as typing out a history paper while having an unrelated conversation), the overwhelming portion of humans are neurologically incapable of such an action. In fact, it is the hallmark of an unhealthy human that parts of their brain do not fire in a coordinated concert of individual (i.e., singular, sequential) neurological explosions, but instead fire independently of each other, of their own accord. This is actually what you see in the brain of a patient who is having a seizure. All the areas of the malfunctiong brain ignore each other and just fire at their own will; in other words, the areas of their brain act independently of each other.
Therefore, you do not want true "hand independence"; instead, you want hand coordination. Put another way, instrument playing is a conscious action, controlled by our executive function, and we only have one area of the brain that controls the executive function. Thus, homo sapiens's conscious control is, for better or worse, unitary, and we cannot do two independent tasks at once.
The same is true for the piano.
So...what you need to do is to try to not beat yourself up too much, and simply accept the fact that when you do hands-together play you really are learning a different skill. You cannot simply focus on the movement of one arm, wrist, hand and finger in isolation from any other. If you can't play it with hands together, go back, define every individual action you must take, treating both hands as a single mental unit, put them in sequence, practice them over and over again until you can do them in sequence, in time, perfectly, and then speed it up. Do not try to skip this simple process because you want your hands to "be independent", because you cannot neurologically do such a thing.
Comment: Good question. Hands together is for practicing PERFORMANCE, but hands separate is for LEARNING the music. Once you've learned each hand, then you're ready to learn how to merge them into one mental unit. You do want to move to hands together as quickly as possible, but you cannot do so until you can at least do each hand independently for whatever the target phrase is. Additionally, continuously practicing each individual hand will allow you, when you are practicing hands together, to focus on the coordination of both hands, rather than one hand or the other.
Comment: So what you are saying is that it is good to go dirctly to practice hands together and not seperately when i am studying a part?
Answer: I'm a late-intermediate-level piano player, coming from playing clarinet for about a decade. Take my opinion for what it's worth.
The thing about piano, unlike any other instrument that I've played, is that learning it requires isolation and precision of every little movement you're making. Not doing this could lead to you developing bad habits.
At this point in my piano playing, I've gotten to the point where I can sightread with both hands a lot of simple things without struggle, but I run into points where I need to practice more extensively. The brain is terrible at learning many new actions in parallel. The reason why you need to isolate your hands-together playing to hands-separate playing is that your brain needs to separately learn what both hands are doing well so that it's easier to execute both hands' actions in parallel.
When going from hands-separate to hands-together, make sure you're playing with a metronome at a very, very slow speed, and build the speed up.
Answer: Music comes from the mind, not just the fingers.  Since you are able to play separately, you probably don't have motoric problems.  Try this exercise: take a short fragment (one or a few bars), and carefully read the music.  Try to be observative about everything, the harmony, the rithms, the shape of the melody.  If possible, imagin how you think it will sound.  Then play each hand separately, from memory.  If you make errors, don't worry, just go back to the score, and look carefully at the places where you made a mistake.  Try to find the source of the mistake.  Was it a wrong finger?  A wrong harmony?  If this goes well, do the same for both hands together.  First read the score, observe which notes go together, how both hands relate to each other (is one hand accompaniment?   Does it play chords?  What are the chords?  Are the chords broken?  Perhaps the melody is in the left hand, and the accompaniment in the right).  Then try to play both hands together from memory.  If you make a mistake, don't worry, just go back to the score.  Try short fragments at first, then take longer fragments as you progress.  Don't forget to check with the score regularly, so you don't learn wrong notes!  Try this method, and you will find you progress much faster!
Also a note of caution: simply playing slow doesn't mean are learning anything. The secret is understanding. Each note doesn't have a meaning on itself.  You must be aware of its meaning in the melody (or harmony).  You must be aware of where it comes from, and where it goes to.  Listen to what happens in the music.  Don't just play articulations because you have to, but understand why they are there.  If your mind is confused, it will be still confused when playing slowly!  The reason for practicing slowly is not because you have to create automatic reflexes, it's because you want your mind to be clear and open to the music, to fully understand it, so you can master the music, not your reflexes mastering you.  If you allow yourself to be overwhelmed by the complexity, then you cannot master the music.  Find clarity and meaning, and everything goes easy!
Answer: That is quite normal since you underestimate how much effort it is to practice one hand until it occupies at most a third of your attention (you need another third for the other hand, and yet another third for the synchronization).
Basically, playing smoothly while paying some attention to the score rarely occupies less than a third of an attention when you are not used to it, and it is hard to simulate the distraction of the other hand and of putting things together without actually doing so.
So in the long run you need to realign how much focus a single hand may take with your way of practising.  It's like being able to run at a solid pace does only moderately prepare you for getting at maximum speed through a chest-deep mud pit.  Yes, you have trained for that in some manner, but in some manner you didn't yet.
At some point of time you'll be even able to afford the third of your focus needed for being aware of the audience.


iPhone iOS 8.2 with Xcode 6.1.1

Question: I just updated my phone to newest iOS version (8.2) and now I have in Xcode (6.1.1) my device under Ineligible devices. I don't use Xcode beta version but I guess I should started. I just update Xcode when Store notify me but I think I should download Beta now because it fix my problem. Or is there a fix where I can run my apps in device without updating to Beta Xcode?
Comment: Have you checked it with Xcode 6.2.The final version is released.
Comment: Oh, there is update for Xcode too. I didn't notice. I'll try.
Comment: This is the link for Xcode 6.2 in Mac Appstore [link](https://itunes.apple.com/us/app/xcode/id497799835?ls=1&mt=12)
Comment: refer this links http://stackoverflow.com/questions/27352568/ineligible-device-ipad-air2-os-version and http://stackoverflow.com/questions/27613083/ios-devices-do-not-show-up-on-xcode-6-1-1-until-after-rebooting-the-mac
Answer: Actually this is the problem as your device has the higher OS version 8.2 which is not supported by the current Xcode version 6.1.1 you have to update your Xcode version now.
So, Now you simply update your Xcode version to the latest version of Xcode using the following link.
Comment: And you have to download complate 2.6GB ide just for upgrading Xcode 6.1 to 6.2. Good job Apple :)
Comment: Actually Apple should update only the required things and that how it can save amount of data to be downloaded for user and instead of downloading 2.6GB it should be done in 200 to 250MB. Hope Apple will improve their update process soon.
Answer: Your options are upgrading Xcode to 6.2 or downgrading your phone to a version compatible with Xcode
try this: http://www.idownloadblog.com/downgrade/

iPhone iOS 8.2 with Xcode 6.1.1


Is it advisable for a beginner to wear finger guard?

Question: Is it advisable for a beginner to wear finger guard when playing the guitar or ukulele?

Picture taken from Google Images
Comment: Please don't try to learn how to play with those; they look only a little better than trying to learn to play while wearing mittens.
Comment: This looks like a bad idea all around.  Reminds me of the spring loaded finger machines that were popular in the 80s. People thought it would make their grip stringer.  Maybe it does but you don't need a string grip to play guitar.  Seems like the product is a red herring.  Just play and your fingers will adjust, that is necessary to get good and I think you will delay that process.
Answer: I would say no. Getting your fingers conditioned to playing is a necessary step. Unless you have some unique medical necessity, just play a little each day, and when your fingers get tired take a break. After a few weeks will find you will be able to play for longer periods without it feeling like the guitar hates your fingers.
Comment: commenting on my own answer here: just started playing bass and my plucking hand is NOT used to plucking the bass (i am a guitarist so no issue with the fretting hand) and i find that i want to play more than my fingers want me to play. in that case i just use a pick so i can play a little more and not develop (or make worse) any blisters. the first few days i played i played until my finger had a blister which caused a big cut and i had to stop playing. now i will play until i feel like it is becoming a problem and then use a pick. once my fingers are conditioned i will stop doing this.
Answer: Guessing it's either on your fretting fingers, or plucking fingers. Neither should be necessary. If it's a well set up guitar, and the strings are not too heavy, making them very difficult to press down. there won't be a problem there. Some will say you'll develop callouses - very hard skin - on fingertips. In the last 50 yrs or so, I've never had them. Maybe it's me, and the way the guitars/basses are set up.
If it's for the plucking fingers, again, no, as you use  the finger pads and/or the fingernails and anything worn on fingers/thumb will be detrimental. If you want to strum, use a pick. If you want to pick, slip-on finger  picks are available.
When you play, and you reach the point when your fingers ache or hurt, it's just God's way of saying 'have a rest'!
Answer: This may be more of the same, but here is my 2 cents.
I cannot tell what the purpose of the device is.  Ideally you want to develop a haptic connection with your instrument so it becomes an extension of yourself.  That being said my first reaction to these devices is that you will NEVER develop the right feeling using these things.  But then I am reminded of Tony Iommi of Black Sabbath who lost the ends of two of his fretting hand fingers early in his life in a work related accident.  He has prosthetic ends made of wood and leather.  So he cannot feel the tip touch the string but over time I would guess that he developed sensitivity of the wood touching the end of whatever skin is touching it.  That would evolve into a true haptic connection.
I can only imagine that these little devices "protect" you skin from getting sore when you play.  The problem with that is that you need to evolve past that to develop real chops with both hands.  If you are using these to allow yourself to play past an amount of time where you would feel your fingers getting bruised then I would say your actions are self defeating.  Here is why I think that.  Presumably, in time, you will take them off.  When you do this you will essentially be starting over and need to develop that haptic connection from scratch.  This happens to experienced player if they decide to change technique.  The evolution time is usually not as bad as starting over but can take several months is the change is drastic.  You are setting yourself up to not learn.  If, on the other hand, you intend to uses these forever I see no reason why you cannot develop a good tone and technique but now these pads will need to be part of your playing to get the feel you are used to.
In general I think devices like this are a marketing gimmick and serve no real purpose to beginners.  Similar gimmicks that have misleading arguments for use in guitar playing are (1) the spring loaded grip developer, and (2) the guitar with LED lights on the finger board to light up the correct spots to finger in any key or mode.  Neither of these helps in the learning process and can have negative effects over time.
Comment: Prefer this one over Tim's answer because of a sentence hidden in the middle of the 2nd paragraph: ".. Presumably, in time, you will take them off. When you do this you will essentially be starting over..."
Answer: Considering that your image is of an ukulele, let me share some of the ukulele playing perspective.
Generally, finger guards on the strumming hand of the ukulele is not really advised. You could, for sure, but I don't think you'll need them. If I may guess, I think that probably after playing a little while, the strings start to feel as though they are cutting your fingers or making them raw. I think that if your fingers start to hurt, the best way to handle it would be to stop and let your fingers heal. Eventually (for me this started to happen within 2 months of starting playing), I stopped feeling any pain. Especially on ukulele, with non-metal strings, finger guards shouldn't be necessary. If you want to use them, you can, but here are a few pros and cons:
Pros:

One's fingertips are protected from the pain
Possibly a better grip on the strings
Maybe a cleaner tone(?)
Vibrato and natural harmonics might be
easier
Playing with a slide is impossible
If you have medical complications from this, the  of course this will solve your problem

Cons:

Finger guards don't protect the rest of the finger, so barre chords will still be in contact with the skin
Slides might be affected/harder
Vibrato might be harder, and the possible benefit of natural harmonics won't apply to  artificial harmonics
Your fingers will effectively be larger, making cramped positions more difficult
It's an additional cost, as well as they will break over use/time
People will think you're weird (that's their fault, but still)
Pull-offs might accidentally pull the entire guard off of your finger

As for guards on the picking hand:
Let me just say that I learned to strum with the nail and skin of my index finger, which  did start to hurt when I first started to play. After a few months, though, it stopped being a problem. I'd say if it hurts and you're not bleeding, you just stop playing. If you're bleeding, you're playing too hard or too much or something. That aside, there are other better options, for example thumb strumming or using more than one finger, or of course fingerpicking. Here are some pros and cons of guards on the picking hand:
Pros:

Artificial harmonics also get easier
Less strumming pain
Better grip on the strings if fingerpicking
It will allow you to play much more forcefully, as it won't hurt to play louder

Cons:

You might even need one on the thumb, because thumbs are a big part of strumming
One can never vary their tone by using nails, because the nails never touch the strings
Different tone when strumming

If you start with guards, you're either going to have to eventually learn to play without them, in which case it's better to learn that now, or you'll use guards forever, which might be fine, depending on what you decide. It's your choice, but I can't say that they are necessary, as most ukulele players never use these. Also consider that guitarists and bassists also never usually use these, and they have to deal with metal strings and much thicker strings. String instruments also don't use these, and I can't think of any instrument that does use them.
Comment: None of those "pros" make sense.
Comment: @ggcg Do you have any good pros I could use? Or would you simply argue that ther are no advantages?
Comment: With all due respect I do not see any pros.  Please see my answer for details.
Comment: Okay, some of my claims are a little sketchy there, but I do believe that maybe they could be used for some novelty effect or something. I do agree that generally these sorts of devices are often made out to be much more useful than they really are, and I agree with your answer.
Answer: if your fingers hurt use smaller string size


Rodar App em background com phonegap

Question: Sou programador PHP e estou me aventurando no mundo mobile.
Preciso criar um app simples, irá apenas tocar uma radio especifica, o problema é: Como rodar o app em backgroud? Quando o app for minimizado a radio precisa continuar tocando.
Não preciso de código pronto, o caminho das pedras serve.
Comment: Vc já fez um código que toca uma rádio e quando vc minimiza ele para de tocar, é isso?
Answer: Desenvolvo para Android e se fosse usando código nativo iria te sugerir o uso de IntentService no Android (Service e create-service).
Pesquisando sobre o uso de Services no Phonegap, não sei se é possível ter um Service com código nativo Android e que executasse o seu código JavaScript para tocar a rádio.
Uma alternativa é buscar um plugin do PhoneGap (nunca usei, logo não posso indicar nenhum). Mas pesquisando por alto existem esses plugins: BackgroundService e Phonegap Android Background Service Plugin - Explained. Se alguém que já teve experiência puder dar mais detalhes seria perfeito.
Espero ter ajudado.

Rodar App em background com phonegap


Symfony\\Component\\Messenger\\Bridge\\Amqp\\Transport\\Connection::ack(): Return value must be of type bool, null returned

Question: I get this error when handling message, where is the problem? It works before restart. I can connect to rabbit.
I didn't change anything, composer update with that composer config. queue stop working.
This is response from component - my handler returns nothing...
Where search solution? Is this a problem with rabbit? Or the symfony rabbit library?
<code> Received message App\Message\RecalculateInventoryMessage {"class":"App\\Message\\RecalculateInventoryMessage"} []
[2024-01-26T10:33:55.699255+00:00] messenger.INFO: Message App\Message\RecalculateInventoryMessage handled by App\MessageHandler\RecalculateInventoryMessageHandler::__invoke {"class":"App\\Message\\RecalculateInventoryMessage","handler":"App\\MessageHandler\\RecalculateInventoryMessageHandler::__invoke"} []
[2024-01-26T10:33:55.701369+00:00] messenger.INFO: App\Message\RecalculateInventoryMessage was handled successfully (acknowledging to transport). {"class":"App\\Message\\RecalculateInventoryMessage"} []
[2024-01-26T10:33:55.705393+00:00] console.CRITICAL: Error thrown while running command "messenger:consume recalculate_inventory --time-limit=3600". Message: "Symfony\Component\Messenger\Bridge\Amqp\Transport\Connection::ack(): Return value must be of type bool, null returned" {"exception":"[object] (TypeError(code: 0): Symfony\\Component\\Messenger\\Bridge\\Amqp\\Transport\\Connection::ack(): Return value must be of type bool, null returned at /application/vendor/symfony/amqp-messenger/Transport/Connection.php:440)","command":"messenger:consume recalculate_inventory --time-limit=3600","message":"Symfony\\Component\\Messenger\\Bridge\\Amqp\\Transport\\Connection::ack(): Return value must be of type bool, null returned"} []
[2024-01-26T10:33:55.707673+00:00] console.DEBUG: Command "messenger:consume recalculate_inventory --time-limit=3600" exited with code "1" {"command":"messenger:consume recalculate_inventory --time-limit=3600","code":1} []
</code>
My composer
<code>"require": {
    "php": ">=8.2.3",
    "ext-ctype": "*",
    "ext-iconv": "*",
    "beberlei/doctrineextensions": "^1.3",
    "ccampbell/chromephp": "^4.1",
    "doctrine/annotations": "^2.0",
    "doctrine/dbal": "^3.6",
    "doctrine/doctrine-bundle": "*",
    "doctrine/doctrine-migrations-bundle": "^3.2",
    "doctrine/orm": "^2.14",
    "elliotjreed/royal-mail-tracking": "^3.0",
    "friendsofsymfony/ckeditor-bundle": "^2.4",
    "friendsofsymfony/jsrouting-bundle": "^3.2",
    "gnikyt/basic-shopify-api": "^11.0",
    "jms/serializer-bundle": "*",
    "knplabs/knp-paginator-bundle": "^6.2",
    "lcobucci/jwt": "^5.0",
    "moneyphp/money": "^3.3",
    "nesbot/carbon": "^2.66",
    "openai-php/client": "^0.6.1",
    "phpdocumentor/reflection-docblock": "^5.3",
    "phpstan/phpdoc-parser": "^1.16",
    "sensio/framework-extra-bundle": "^6.2",
    "setasign/fpdf": "^1.8",
    "setasign/fpdi": "^2.3",
    "shopify/shopify-api": "^4.2",
    "sonata-project/admin-bundle": "^4.27.1",
    "sonata-project/doctrine-orm-admin-bundle": "^4.10",
    "sonata-project/user-bundle": "^5.6",
    "stof/doctrine-extensions-bundle": "*",
    "symfony/amqp-messenger": "6.2.*",
    "symfony/asset": "6.2.*",
    "symfony/console": "6.2.*",
    "symfony/debug-bundle": "6.2.*",
    "symfony/doctrine-messenger": "6.2.*",
    "symfony/dotenv": "6.2.*",
    "symfony/expression-language": "6.2.*",
    "symfony/flex": "^2",
    "symfony/form": "6.2.*",
    "symfony/framework-bundle": "6.2.*",
    "symfony/http-client": "6.2.*",
    "symfony/intl": "6.2.*",
    "symfony/lock": "6.2.*",
    "symfony/mailer": "6.2.*",
    "symfony/mercure-bundle": "^0.3.6",
    "symfony/mime": "6.2.*",
    "symfony/monolog-bundle": "^3.0",
    "symfony/notifier": "6.2.*",
    "symfony/process": "6.2.*",
    "symfony/property-access": "6.2.*",
    "symfony/property-info": "6.2.*",
    "symfony/rate-limiter": "6.2.*",
    "symfony/runtime": "6.2.*",
    "symfony/security-bundle": "6.2.*",
    "symfony/serializer": "6.2.*",
    "symfony/string": "6.2.*",
    "symfony/translation": "6.2.*",
    "symfony/twig-bundle": "6.2.*",
    "symfony/validator": "6.2.*",
    "symfony/web-link": "6.2.*",
    "symfony/webpack-encore-bundle": "^1.16",
    "symfony/yaml": "6.2.*",
    "symfonycasts/verify-email-bundle": "^1.13",
    "tbbc/money-bundle": "^5.0",
    "twig/extra-bundle": "^2.12|^3.0",
    "twig/twig": "^2.12|^3.0",
    "vich/uploader-bundle": "2.1.1",
  "ext-bcmath": "*"
},
</code>
here is docker-compose config for rabbit
<code>  rabbit:
    image: "rabbitmq:3.8-management"
    hostname: "rabbit"
</code>
Answer: This is now fixed in "symfony/amqp-messenger". You have to update your dependency


Neighborhood in orthogonal group

Question: Let $A\in O(n)$. Assume that $|a_{i,i}|\neq 1$ for every $i$. Prove that in every neighborhood of $A$ there exists $B\in O(n)$ such that
$|b_{i,i}|>|a_{i,i}| \text{ for every } i \text{ and } |b_{i,j}|\leq |a_{i,j}| \text{ for every } i\neq j$.
I have thought about projecting $A+\epsilon I$ on $O(n)$ (wlog I assume $a_{ii}\geq 0$ here), but there doesn't seem to be a nice formula indicating whether this projection would work or not. Similarly I am not sure about Gram-Schmidt. Or maybe it's better to find a prove that doesn't use explicit constructions, but I don't know much about neighborhood in $O(n)$. Any suggestions?
Edit: the main difficulty I faced was that, if $a_{i,j}=0$ then we must force $b_{i,j}=0$, which prevents methods that involve 'small perturbation of every entry'.
Edit 2: As a counter-example is given below, I wonder whether the claim is true if $A$ is close to $I$, say if $A$ is closest to $I$ among all signed permutation matrices. (In the counter-example, $A\neq I$ itself is a signed permutation matrix).
Note that this claim is true is $A$ is close enough to $I$, as we can form a path $B_t=\text{exp}(t\log(A))$. Since the entries of $B_t$ is analytic on $t$, if $A$ is sufficiently close to $I$ every $B_t$ would satisfy the conditions for $t\in[0,1]$.
Answer: This is not always possible. As you have already discovered, a difficulty is that all off-diagonal zeroes in $A$ must be inherited by $B$. For instance, consider
$$
A=\pmatrix{\color{red}{0}&\color{red}{1}&0\\ 0&\color{red}{0}&\color{red}{1}\\ \color{red}{1}&0&\color{red}{0}}.
$$
Only the red elements are modifiable. As the rows and columns of $B$ are unit vectors, we must have
$$
B=\pmatrix{c&s&0\\ 0&\pm c&\pm s\\ \pm s&0&\pm c}
$$
for some real numbers $c$ and $s$ such that $c^2+s^2=1$. But then the first two columns of $B$ are orthogonal to each other only when $c=0$ or $s=0$ (so that $c=\pm1$). Therefore, $c$ cannot be a small nonzero number and $B$ does not exist in any small neighbourhood of $A$.
Comment: @ArcticChar You cannot. The rows of $B$ are unit vectors too. (Strictly speaking, you can have different angles -- just take $-\theta$ instead of $\theta$ for instance -- but the values of $|\sin\theta|$ and $|\cos\theta|$ must remain the same.)
Comment: You would have different angles for each column?
Comment: @user1551 Thanks for your answer! See the edits on the question.
Answer: Consider the case when $A$ is in canonical form:
$$
A = \left[\begin{array}{cccccc}R_{1} & & & & & \\ & \ddots & & & & 0 \\ & & R_{K} & & & \\ & & & \pm 1 & & \\ & 0 & & & & \ddots \\ & & & & & \pm 1\end{array}\right]
\qquad
R_k = \left[\begin{array}{rr}\cos(\theta_k) & -\sin(\theta_k) \\ \sin(\theta_k) & \cos(\theta_k)\end{array}\right]
$$
Here, the claim is obviously true: We can increase the size of the diagonal entries, while reducing the size of the off-diagonal entries by undoing the rotations. All that's left to is to extend this argument to the general case.
Comment: Thanks for your comment! But I have found two difficulties: first, finding paths envolves a change of basis, which I couldn't do since it would destroy the size of the entries; second, finding paths row by row would affect other rows' size of the entries, so it seems like I couldn't find some intermediate points and join them by paths.
Comment: So for a general $B\in O(n)$, there exists $P\in O(n)$ and $A$ in canonical form you gave such that $B=PAP^T$. Are you claiming that if we increase the size of the diagonal entries, while reducing the size of the off-diagonal entries, then such phenomenon also happens on $B$? Could you hint me why this is true? I can only see that the size of the diagonal entries of $B$ indeed increase.
Comment: @LoCelso, no I am not claiming that. Obviously this is not a complete answer but rather an idea of how to approach the question. The key ingredient is that you can apply Given's Rotations with small angle, which give you some control over the matrix entries while staying in an arbitrarily small neighbourhood. You could try to use this idea to construct a path from $A$ to a diagonal matrix, similarly as done here: https://math.stackexchange.com/a/1794563/99220. The hope would be that along the path, the magnitudes of the entries change monotonically.
Comment: @LoCelso Hey just a reminder: to avoid getting "wrong" answers like this, formulate your question properly! When you write `Prove that [...]` then I automatically presuppose that the statement is true and that you are looking for a way to prove it. When you don't know whether the statement is true or not then it is usually better to formulations like `Is it true that ...` or `Is it always possible to ...`

Neighborhood in orthogonal group


Undefined is not callable

Question: I'm writing a transaction which adds a participant and an asset to the network. Adding the participant to the network works, but when I try to access the Medical asset file registry the function returns undefined.

Error: TypeError: undefined not callable

The logic of the transaction:
return getParticipantRegistry(namespace + '.Patient')
        .then(function (patientRegistry) {
            return patientRegistry.add(newPatient);
        }).then(function() {
            return getAssetRegistry('nl.epd.blockchain.MedicalFile');
        }).then(function (registry) {
            var medicalFile = factory.newResource(namespace, 'MedicalFile', "test");
            medicalFile.id = "test";
            medicalFile.owner = newPatient.bsn;
            medicalFile.mentors = [];
            medicalFile.permissions = [];
            medicalFile.allergies = [];
            medicalFile.treatments = [];
            medicalFile.medicine = [];

            // registry is undefined
            return registry.add(medicalFile);
        });
}

Models:
namespace nl.epd.blockchain

asset MedicalFile identified by id {
  o String                      id
  --> Patient                   owner
  --> Patient[]                 mentors
  o OrganisationPermission[]  permissions
  o Visit[]                   visits
  o String[]                  allergies
  o Treatment[]               treatments
  o Medicine[]                medicine
}

participant Patient identified by bsn {
  o String bsn
  o String firstName
  o String namePrefix optional
  o String lastName
  o String email
  o String telephoneNumber
  o String birthday
  o String gender
  o String city
  o String zipCode
  o String street
  o String houseNumber
  o String houseNumberExtra optional
}

NPM dependencies:
"dependencies": {
    "fabric-ca-client": "1.0.0-alpha.0",
    "fabric-client": "1.0.0-alpha",
    "homedir": "^0.6.0",
    "composer-client": "^0.7.0",
    "composer-rest-server": "^0.7.0"
  }

Any idea what's wrong?
Answer: The assumption that the registry was empty was incorrect. The problem was that the owner wasn't a relationship. It was just a string, I thought that was allowed.
This caused the error described above.
The fix:
medicalFile.owner = factory.newRelationship(namespace, 'Patient', newPatient.bsn);

Undefined is not callable


An strange triple integral I've never seen before

Question: This is one of the integrals I have for homework, But I've never seen anything like this before, I don't know what to do with it. Does anyone know?

$$\int_0^1 dz \int_z^1 dx \int_0^x e^{x^2} dy.$$

UPDATE
although $$\int_0^x e^{x^2} dy$$ is easy to handle. But there is definitely something about this integral as the teacher has already mentioned it. If we have:

$$\int_0^1 dz \int_z^1 dxxe^{x^2}.$$

$$xe^{x^2}=\frac {d(\frac {e^{x^2}}{2})} {dx} \Rightarrow dx= \frac {d(\frac {e^{x^2}}{2})} {x{e^{x^2}}}\Rightarrow $$
$$\int_0^1 dz \int_z^1 dxxe^{x^2}=\int_0^1 dz \int_z^1 d(\frac {e^{x^2}}{2})=\int_0^1 dz(\frac {e}{2}-\frac {e^{z^2}}{2})...$$
could it be right?
Comment: @abiessu By the way, that notation is (horribile dictu) used by some to indicate nested integrals, it means $$\int_0^1 \left(\int_{z}^1 \left(\int_0^x e^{x^2}\,dy \right)\,dx \right)\,dz.$$
Comment: @nayrb: to me, $\int_0^xe^{x^2}dy$ is very easy: $xe^{x^2}$.  I'm not sure I understand your comment...
Comment: In which parts are you get stuck?
Comment: This looks like "the multiplication of $\int_0^1dz$ by $\int_z^1dx$ and $\int_0^xe^{x^2}dy$."  Do you have any examples of similar problems available to check against?
Comment: I think a pretty obvious difficulty with this integral is the difficulty of integrating $e^{x^2}$. The OP then probably doesn't realize he or she should try switching the order of integration.
Comment: @abiessu, whoops, misread the order of integration. I assume that this was a trickier integral than it is.
Comment: @DanielFischer: ah, that makes more sense now, and thus the obvious problem of $e^{x^2}$ is resolved easily.
Answer: $\int_0^1 dz \int_z^1 dx \int_0^x e^{x^2} dy = \int_0^1 dz \int_z^1 e^{x^2} dx \int_0^x dy $
= $\int_0^1 dz \int_z^1 e^{x^2} x$ dx
= $\int_0^1 (\frac{e}{2} - \frac{e^{z^2}}{2}) dz$
= $\int_0^1 \frac{e}{2} dz- \int_0^1\frac{e^{z^2}}{2}dz $
= $\frac{e}{2} - \frac{\sqrt{\pi}}{4}$


How do I figure out what field a question or problem belongs to?

Question: Are there guidelines somewhere? I have no significant background in math, but on my own I have come across some things that have really started to capture my imagination. I don't where to go from where I am now.
*note: I added the soft-question tag as I couldn't find a placeholder. I hope it suffices.
Comment: There are [various lists](https://en.wikipedia.org/wiki/Lists_of_mathematics_topics#Areas_of_advanced_mathematics), I suppose, though at the end of the day, it's a bit of a catch-22: by doing lots of maths you will become more familiar with the broad outlines of different areas of maths, which makes it much easier to formulate questions and research further.
Comment: https://en.m.wikipedia.org/wiki/Category:Mathematics
Comment: Thanks. That is a decent page.
Answer: Asking on math.stackexchange about a problem you have is a decent way to find out what branch of math your question lies in :)
To recieve a broad introduction to branches of pure math, I'd recommend:

An infinitely large napkin by Evan Chen --- this books sketches out a good chunk of pure math, with more of an algebraic flavour. It allows one to survey the "flavour" of a lot of math.
The princeton companion to mathematics is a rigorous introduction to many different branches of pure math
The art of computer programming --- a collection on all things algorithmic or computation related.
Course of theoretical Physics / Landau Lifschitz --- While these are technically physics books, they cover the mathematical ground quite well, and are good to learn most of the math that's used in "old-school" physics
Comment: Thanks. I'll give the second book a go. As for asking more detailed questions here, I'm just not up to describing some of these things without having read some related literature. If I were to, I'd just leave a lot of people guessing as to what I actually mean.


Possible bug when adding a newly created video to a playlist

Question: As of recently, a script has been reporting failures when trying to add a newly created youtube video to a playlist.
The flow is pretty simple:
<code>URL being requested: POST https://www.googleapis.com/upload/youtube/v3/videos?uploadType=resumable&alt=json&part=status%2Csnippet
Video id 'ABC123' was successfully uploaded.
Adding ABC123 to playlist MyPlaylistId
URL being requested: POST https://www.googleapis.com/youtube/v3/playlistItems?alt=json&part=snippet
Payload:
{"snippet": {"resourceId": {"kind": "youtube#video", "videoId": "ABC123"}, "playlistId": "MyPlaylistId"}}
Response:
{'status': '404', 'content-length': '226', 'x-xss-protection': '0', 'x-content-type-options': 'nosniff', 'transfer-encoding': 'chunked', 'vary': 'Origin, X-Origin, Referer', 'server': 'scaffolding on HTTPServer2', '-content-encoding': 'gzip', 'cache-control': 'private', 'date': 'Thu, 17 Sep 2020 12:13:36 GMT', 'x-frame-options': 'SAMEORIGIN', 'alt-svc': 'h3-Q050=":443"; ma=2592000,h3-29=":443"; ma=2592000,h3-27=":443"; ma=2592000,h3-T051=":443"; ma=2592000,h3-T050=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43"', 'content-type': 'application/json; charset=UTF-8'}
Response content:
{
 "error": {
   "code": 404,
   "message": "Video not found.",
   "errors": [
     {
       "message": "Video not found.",
       "domain": "youtube.playlistItem",
       "reason": "videoNotFound"
     }
   ]
  }
}
</code>
Now, the funny part is that the video is actually successfully added to the playlist. I have tested it several times and I get the same result.
Can anyone confirm this bug?
Comment: Note: I have reported this bug here as this seems to be the official support site for the google apis as stated here: https://developers.google.com/youtube/v3/support
Answer: It seems indeed a bug, but, as far as I know, the site for post about bugs with the YouTube APIs is: Issue Tracker1.
The following link allows you create an entry on Issue Tracker.
It is worth check first if entries exists with the similar issue you're facing and if you find related entries there, please "star" that issue to draw attention to it and track updates, if you'd like.

1 Issue Tracker is shown (alongside Stack Overflow) at the end of the page of YouTube Data API website.
Comment: Indeed, seems that I have misses that link at the footer. Thanks!


Integration of $\int_0^{2\pi}(e^{\cos x}\cos x\sin x) \,dx$

Question: Can anyone please help me with this integration:
$$\int_0^{2\pi}(e^{\cos x}\cos x\sin x)\,dx$$
I am getting the answer as $0$ by using simply the properties of definite integral
BUT the answer as told by my teacher is $2\pi$
Please help. Thanks!
Comment: The graphics of the integrand function is symmetric with respect to the point $(\pi,0)$, hence you are right, the integral is zero.
Answer: Using $$\int_a^bf(x)dx=\int_a^bf(a+b-x)dx$$
If $\displaystyle  f(x)=e^{\cos x}\sin x\cos x,$
$\displaystyle f(2\pi+0-x)=e^{\cos(2\pi+0-x)}\sin(2\pi+0-x)\cos(2\pi+0-x)=e^{\cos x}\cos x(-\sin x)=-f(x)$

Also putting $\cos x=u,$
$$\int_0^{2\pi}e^{\cos x}\sin x\cos x=-\int_1^1e^u\cdot u\ du$$
The indefinite part can be managed using integration by part.
But as both the upper & the lower bounds are same, the result has to be zero
Answer: Here's another way of looking at it:
$$\begin{align}
\int_{0}^{2\pi}e^{\cos{x}}\cos{x}\sin{x}\,\mathrm{d}x
&=\int_{-\pi}^{\pi}e^{\cos{x}}\cos{x}\sin{x}\,\mathrm{d}x\\
&=\int_{-\pi}^{\pi}e^{\cos{x}}\frac{\sin{(2x)}}{2}\,\mathrm{d}x
\end{align}$$
Comment: You really didn't need that last step.  $e^{\cos x} \cos x \sin x$ is an odd function.
Comment: @RobertIsrael True, that last step actually needed. I suppose I just tossed in that trig identity out of habit. ¯\_(ツ)_/¯
Answer: If you make the simple substitution $u = \mathrm{e}^{\cos x}$ then you'll find that $\mathrm{d}u = -\mathrm{e}^{\cos x}\sin x~\mathrm{d}x$. Moreover, $\cos x = \ln u$. When $x=0$, $u=\mathrm{e}^{\cos 0} = \mathrm{e}$ and when $x=2\pi$, $u=\mathrm{e}^{\cos 2\pi} = \mathrm{e}$. Hence
$$\int_0^{2\pi} \mathrm{e}^{\cos x}\sin x~\cos x ~ \mathrm{d}x = \int_0^0 - \ln u~\mathrm{d}u=0$$
You don't need to evaluate the integral because the upper and lower limits are the same, so the integral will evaluate to zero. If you wanted to evaluate the integral you'd see that
$$\int \mathrm{e}^{\cos x}\sin x~\cos x~\mathrm{dx} = \int - \ln u~\mathrm{d}u = u(1-\ln u) + C = \mathrm{e}^{\cos x}(1-\cos x)+C$$
Comment: I think we need to establish the existence of inetgral, that's why evaluation will be required
Comment: @labbhattacharjee Did you read all of my post? I found the indefinite integral.
Comment: I was referring to "You don't need to evaluate the integral because the upper and lower limits are the same". Sorry for the confusion.


How to download and extract apache tomcat using ansible and rename unzaip file

Question: I'm setting up a new setup for tomcat.
I wanna download and extract apache tomcat using ansible to several nodes of linux, but the thing is unzip file should be seen or rename as apache only. It doesn't matter what would be a version of tomcat?
<code>- name: variable check
  hosts: all
  become: yes
  vars:
    tomcat_url: 'http://mirrors.estointernet.in/apache/tomcat/tomcat-8/v8.5.45/bin/apache-tomcat-8.5.45.tar.gz'
  tasks:
  - name:
    get_url:
      url: "{{tomcat_url}}"
      dest: /opt
</code>
Answer: Here's complete working example:
<code>---
- hosts: all
  become: yes
  vars:
    tomcat_url: 'http://mirrors.estointernet.in/apache/tomcat/tomcat-8/v8.5.45/bin/apache-tomcat-8.5.45.tar.gz'

  tasks:
    - name: Download and Extract apache tomcat
      unarchive:
        src: "{{ tomcat_url }}"
        dest: "/opt/"
        remote_src: yes

    - name: Synchronize the "{{ tomcat_url.split('/')[-1].rstrip('.tar.gz') }}" directory to apache on one remote host
      synchronize:
        src: "/opt/{{ tomcat_url.split('/')[-1].rstrip('.tar.gz') }}"
        dest: "/opt/apache"
      delegate_to: "{{ inventory_hostname }}"

    - name: Remove the {{ tomcat_url.split('/')[-1].rstrip('.tar.gz') }} directory
      file:
        path: "/opt/{{ tomcat_url.split('/')[-1].rstrip('.tar.gz') }}"
        state: absent
</code>


Prove limsup equality with function of sequence

Question: Let $\{ y_{k}\}_{k}$ a positive sequence and
$\alpha$ a scalar continuous function s.t. $\alpha(0) =0$
and $\alpha(s) > s$ for every $s >0$.
I would like to prove the following equality:
$\limsup\limits_{k \rightarrow \infty} \alpha(y_k) = \alpha(\limsup\limits_{k \rightarrow \infty} y_k) $
Are there any other assumptions that I should take under consideration?
Thank you in advance!
Answer: I think you shoule add the condition : $\alpha(s)$ is monotone increasing .
W.L.G, we may assume the sequence $\{ y_{k}\}$ is bounded.
First, we prove
$$\limsup\limits_{k \to \infty} \alpha(y_k)\geq\alpha(\limsup\limits_{k \to \infty} y_k).$$
For the sequence $\{ y_{k}\}$, there exists subsequence $\{ y_{k_{j}}\}$ such that
 $$\lim_{j\to\infty}y_{k_{j}}=\limsup\limits_{k \to \infty} y_k:=y,$$
due to the continuity of $\alpha(s)$, we have
$$\lim_{j\to\infty}\alpha(y_{k_{j}})=\alpha(y),$$
obviously, $$\limsup\limits_{k \to \infty} \alpha(y_k)\geq\lim_{j\to\infty}\alpha(y_{k_{j}})=\alpha(y)=\alpha(\limsup\limits_{k \to \infty} y_k).$$
(because $\{\alpha(y_{k_{j}})\}$ is subsequence of $\{\alpha(y_{k})\}$.)
Then we show
$$\limsup\limits_{k \to \infty} \alpha(y_k)\leq\alpha(\limsup\limits_{k \to \infty} y_k).$$
For the sequence $\{\alpha(y_{k})\}$, there is a subsequence $\{\alpha(y_{k_{j}})\}$ such that $$\lim_{j\to \infty}\alpha(y_{k_{j}})=\limsup\limits_{k \to \infty} \alpha(y_k)=Y.$$
Then there is a convergent subsequence $\{y_{k_{j_i}\}}$of $\{y_{k_{j}}\}$ such that
$$\lim_{i\to \infty} y_{k_{j_i}}=y,$$
by the continuity of $\alpha(s)$, we get
$$\lim_{i\to \infty}\alpha(y_{k_{j_i}})=\alpha(y)=Y.$$
So $$\limsup\limits_{k \to \infty} \alpha(y_k)= Y={\color{red}{\alpha(y)\leq\alpha(\limsup\limits_{k \to \infty} y_k)}}.$$
The red part uses the monotonicity!


Há algum jeito de escrever esse código de forma mais didática?

Question: Basicamente o código faz um loop pelo banco buscando postagens, porém ele só postará caso a data agendada seja menor ou igual a data do momento. Ele busca pelo banco todas as postagens e lista, porém as que estão agendadas, ele não mostrará. E quando não há postagens agendadas ou não há nada no banco, ele diz que não tem postagens.
Ali tem dois elses. Daí vem a pergunta: Há como usar apenas um?
Tentei de várias formas e não consigo. Um else é para quando não há nada no banco, já o outro para quando não há postagens agendadas. Um else não reconhece o outro. Gostaria de um else apenas.

    <% var valor = "No posts!"; %>

    <% if(noticias.length > 0) { %>
        <% for(var i = 0; i < noticias.length; i++) { %>
            <% if(noticias[i].publicacao_agendada <= moment(new Date()).format('YYYY-MM-DD[T]H:mm')) { %>

                        <%= noticias[i].publicacao_agendada %>
                        <%=noticias[i].autor%>
                        <a href="noticia?id_noticia=<%= noticias[i].id_noticia %>" class="noticia_titulo"><%=noticias[i].titulo%>
                        <%= moment(noticias[i].data_noticia).format(data) %>

                            <%=noticias[i].noticia%>

            <% } else { %>

<%= valor %>

        <% } %>
    <% } %>
    <% } else { %>

<%= valor %>

        <% } %>

Para facilitar a compreensão, eu, @LeoCaracciolo, coloquei algo mais simples
if(noticias.length > 0) {
    for(var i = 0; i < noticias.length; i++) {
        if(noticias[i].publicacao_agendada <= moment(new Date()).format('YYYY-MM-DD[T]H:mm')) {

        } else {

        }
    }
} else {

}

Comment: Por que tantas tags? Afinal, sua dúvida é com PHP, JavaScript, Java, C# e Node.JS?
Comment: Isso aí definitivamente não é php.....
Comment: O `if` interno parece estar errado, porque diria que não tem *posts* em cada um que não atende a condição? Acho que deveria procurar saber o que significa a palavra didática, ela não cabe neste contexto.
Answer: Acho que assim melhora um pouco:

<%
var valor = "No posts!";

if (noticias.length <= 0)
{
%>

<%= valor %>

<%
} else {
    for(var i = 0; i < noticias.length; i++) {
        if (noticias[i].publicacao_agendada <= moment(new Date()).format('YYYY-MM-DD[T]H:mm'))
        {
        %>

                        <%= noticias[i].publicacao_agendada %>
                        <%=noticias[i].autor%>
                        <a href="noticia?id_noticia=<%= noticias[i].id_noticia %>" class="noticia_titulo"><%=noticias[i].titulo%>
                        <%= moment(noticias[i].data_noticia).format(data) %>

<%=noticias[i].noticia%>

        <%
        }
        else
        {
        %>

<%= valor %>

        <%
        }
    }
}
%>

O que eu fiz foi basicamente inverter o primeiro if, jogando o maior código pro final e tornando mais legível, e usei as chaves no mesmo nível, o que facilita a utilização das tags (porém acho que não é a convenção correta do PHP).
Este código aparenta ser de um template para renderização de html no PHP, onde geralmente vc não consegue fugir muito da bagunça de tags.
Agora se esse não é um código só pra gerar html, aconselho você desacoplar controle de visão e separar esta estrutura em métodos, o que facilita muito a leitura.
Veja:

MVC
CleanCode Seção 2. Extract Method


Jquery Scroll Smoth

Question: estou com o seguinte código JS: Ele esta aplicando um smooth ao scroll a todos os elementos com a referência "#" quando eu clico.
JS
$('a[href*=#]').click(function() {
        if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
        && location.hostname == this.hostname) {
                var $target = $(this.hash);
                $target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
                if ($target.length) {
                        var targetOffset = $target.offset().top;
                        $('html,body').animate({scrollTop: targetOffset}, 600);
                        return false;
                }
        }
    });

Só que eu não queria que ele aplicasse esse smooth nesse código:
HTML

Pills left

One

Two

Twee

Lorem ipsum dolor sit amet, charetra varius rci quis tortor imperdiet venenatis quam sit amet vulputate. Quisque mauris augue, molestie tincidunt condimentum vitae, gravida a libero.

Secondo sed ac orci quis tortor imperdiet venenatis. Duis elementum auctor accumsan. Aliquam in felis sit amet augue.

Thirdamuno, ipsum dolor sit amet, consectetur adipiscing elit. Duis elementum auctor accumsan. Duis pharetra
                varius quam sit amet vulputate. Quisque mauris augue, molestie tincidunt condimentum vitae.

Como posso fazer?
Answer: você pode criar alguma propriedade para informar que não quer que o efeito seja aplicado naquele elemento, no exemplo abaixo estou usando um data custom:
Twee

então você pode aplicar uma condição no seu click:
$('a[href*=#]').click(function() {
    if (this.dataset.ignoreSmoth) {
        return;
    }
    //seu script
});

ou até mesmo um filtro
$('a[href*=#]').not("[data-ignore-smoth]").click(function() {
    //seu script
});

Comment: Ficaria algo assim? https://jsfiddle.net/f5g335z9/

Jquery Scroll Smoth


How to get value from variable then copy to clipboard without using input?

Question: I am trying to copy value of a variable to clipboard which is coming from ajax response. I have searched about it and find lot of threads, but issue is everyone asking to use input for value selection using JavaScript select() function. Following script I am trying which does not works,
success:function(data)
{
    var copyText = data.geturl;
    document.execCommand("copy");
    alert("Copied the text: " + copyText);

    return false;
}

Can someone kindly guide me that is there any way to copy value of variable to clipboard without using input? I would like to appreciate.
Thank you so much.
Comment: i would advise to only copy to clipboard using user input. since usually you don't want to overwrite the clipboard without the users permission. I am interested in the answer tho.
Comment: Check out [this answer](https://stackoverflow.com/a/30810322/1139105) of all different ways to use the clipboard with JavaScript
Comment: Possible duplicate of [How do I copy to the clipboard in JavaScript?](https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript)
Comment: According to the [Moz Docs](https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand#Browser_compatibility) `document.execCommand("copy")` is deprecated. I believe you should be using the [clipboard API](https://developer.mozilla.org/en-US/docs/Web/API/Clipboard) instead - although support here looks even worse. Looks like implementation varies, safer to go with user initiated?
Comment: Just adding, here's an extensive discussion that may answer your question: https://developers.google.com/web/updates/2018/03/clipboardapi
Answer: After some research i think it is not possible to copy information to the clipboard without user input due to security restrictions imposed by browser vendors.
more information about this here
Answer: I tried this One
Copy to Cliboard
But this will not work for me. I thought you might be able to find something from this


Event Subscriptions and Source-level coupling

Question: When creating a pub/sub between service boundaries, the recommendation is to create a "Messages" or "Events" assembly.  The publisher publishes an event (interface) from that assembly.  The subscriber listens for that event (interface), which means there is at least source-level coupling in the subscriber to an assembly in the publisher's service boundary.
In an enterprise scenario with numerous pub/sub events, is it possible to publish the event in such a way that the subscriber can listen and deserialize the message without needing a reference to the publisher's message assembly?  What would be the drawbacks of such a approach?
With automated builds and these shared assemblies, if the team publishes a new event (adds an interface to the shared assembly), to which I do not wish to subscribe, my services will be queued to build.  This causes unnecessary work and potential confusion as to why my projects rebuilt and no action is necessary on my team's part (other than to investigate and find out that there is no action to take).
Here is a basic DotNetFiddle Example illustrating what I am trying to explain.  In essence, I am trying to avoid a project/assembly reference to Purchasing.Events.dll from Quoting.Backend.dll.
Answer: The third tenet of the four tenets of SOA is "Services share schema & contract, not class" but as it turns out the easiest way to exchange those schemas and contracts are via, well, classes, lest we get into WSDL hell like we do with SOAP-based web services.
So yes, if you abuse the implementation detail that the contracts are expressed as classes and have big monolithic solutions that reference all of the message assemblies, you will get all the problems you describe.
The solution is to pay more attention to 2 of the other tenets: Boundaries are explicit (#1) and Services are autonomous (#2).
What does this mean?

Especially in a big enterprise scenario like you describe, each service should be implemented in its own solution.
Each service should publish its own events assembly with events owned by the service, commonly called ServiceName.Events.dll or ServiceName.Contracts.dll

Only event classes (schema) should be included. No commands internal to the service. No commands at all, in fact, because autonomous services should only communicate via events.
A private NuGet server (or service like MyGet) would be optimal for the distribution of this assembly.

Each service's events should be versioned very explicitly, and preferably rigidly follow the rules of SemVer.

If you follow these guidelines, when a team publishes a new event that you don't want/need to subscribe to, no change is necessary. It will just continue to run. You can pay attention to the NuGet repository and make educated decisions about when and how to upgrade a different service's events assembly.
Comment: Thank you so much for taking the time to answer my question so thoroughly.  I particularly like the idea of NuGet/MyGet to manage the dependencies rather than pulling the project into the solution and making a project reference...


How to run NodeJS with ES6 classes?

Question: I want to use:
class FOO extends
    // do stuff
    constructor() {
        //do stuff
    }
}
module.exports = FOO;

Output of nodejs --version = v0.12.7
Also running nodejs --harmony script.js is not accepting the classes.
I keep getting a:
class TODORouter extends
^^^^^
SyntaxError: Unexpected reserved word

Comment: Your question may be answered here: http://stackoverflow.com/questions/27177485/node-js-es6-class-creation-syntaxerror-unexpected-reserved-word
Answer: You may either use IO.js or run noe with the harmony flag, eg
node --harmony app.js
This might help: What does `node --harmony` do?

How to run NodeJS with ES6 classes?


Not all symbols of an DLL-exported class is exported (VS9)

Question: I'm building a DLL from a group of static libraries and I'm having a problem where only parts of classes are exported.
What I'm doing is declaring all symbols I want to export with a preprocessor definition like:
#if defined(MYPROJ_BUILD_DLL)
//Build as a DLL
#   define MY_API __declspec(dllexport)
#elif defined(MYPROJ_USE_DLL)
//Use as a DLL
#   define MY_API __declspec(dllimport)
#else
//Build or use as a static lib
#   define MY_API
#endif

For example:
class MY_API Foo{
   ...
}

I then build static library with MYPROJ_BUILD_DLL & MYPROJ_USE_DLL undefined causing a static library to be built.
In another build I create a DLL from these static libraries. So I define MYPROJ_BUILD_DLL causing all symbols I want to export to be attributed with __declspec(dllexport) (this is done by including all static library headers in the DLL-project source file).
Edit:
Note on unrefenced symbols: Linker options Keep Unreferenced Data (/OPT:NOREF) and Do Not Remove Redundant COMDATs (/OPT:NOICF) is set so that no unreferenced symbols will be removed.
Ok, so now to the problem. When I use this new DLL I get unresolved externals because not all symbols of a class is exported. For example in a class like this:
class MY_API Foo{
public:
   Foo(char const* );
   int bar();
private:
   Foo( char const*, char const* );
};

Only Foo::Foo( char const*, char const*); and int Foo::bar(); is exported. How can that be? I can understand if the entire class was missing, due to e.g. I forgot to include the header in the DLL-build. But it's only partial missing.
Also, say if Foo::Foo( char const*) was not implemented; then the DLL build would have unresolved external errors. But the build is fine (I also double checked for declarations without implementation).
Note: The combined size of the static libraries I'm combining is in the region of 30MB, and the resulting DLL is 1.2MB.
I'm using Visual Studio 9.0 (2008) to build everything. And Depends to check for exported symbols.
Edit:
For the ones who wonder why I don't just build a DLL from each of the static libraries: I can't because they cross-reference each other (that's why I need to group them together in one a single DLL). I know, it's horrible I can't really understand the logic behind it.
Comment: what we (or at least I) am suggesting is that you take the source code for your static libraries, all of them, and add it to a single DLL project, and build a DLL. Remove the intermediary LIBs entirely, if possible. Have one DLL, and all the source files that *used* to live in your LIB/LIBs.
Answer: Remember that when you link against a static LIB, by default the linker is only pulling in the functions, classes, and data that the client (which in this case is your DLL) actually references.
So what happens is this:

You build your static LIB, and that's fine. This LIB is 100% valid.
You now build your static DLL around the original binary LIB. It pulls in only the stuff that it actually references. It doesn't pull in the entire class definition which is what it needs to do. This DLL, though it builds, is invalid.
A client then uses the DLL, and expects to see a complete binary definition for the exported class, because that's what the client sees in the accompanying header file.
However the class has only been partially imported, and this is why you're getting those link errors.

To fix:

If you're able to, don't build your DLL off your static LIB. Build your DLL off the original source code. And build your static LIB off the original source code.
Otherwise you can possibly fiddle with linker settings but I strongly recommend option 1 above. Note that OPT:NOREF won't work here as OPT:NOREF has no effect on static LIBs.

What wont't fix it:

High-level linker tweaks like OPT:NOREF, anything involving COMDATs, etc. If you want those functions present, you have to make sure they're referenced, either by referencing them, or by telling the linker explicitly, "hey, this Symbol X is referenced".

As a side note:

Anytime I build a DLL or LIB, I build both a DLL and a LIB, using exactly the technique you're using. Having a single code base that can generate either a DLL or a LIB by toggling a setting is ideal. But building a DLL off of a (binary) static LIB when you own the source code for both... I'm having a hard time imagining when such a scenario would be necessary.
Comment: You are right and I forgot to add that info to the question. I added a note about my linker settings that so that unreferenced symbols will not be removed. And the motivation why I don't build a DLL for each of the static libraries; I can't since they cross-reference each other.
Comment: Just a note (also added to my answer) that OPT:NOREF has no effect on static LIBs anyway. It defeats the entire purpose of having a static LIB. This makes sense. Just not very much.
Comment: The OPT:NOREF setting applied to the DLL linker setting not the static lib. But it should not matter. If a symbol is marked to export the linker would not optimize it away.
Answer: The problem is surely that you use the already-built static .lib in your DLL project.  That cannot work, you have to rebuild the .lib so that the functions get the __declspec(dllexport) declarator and will be exported by the linker.
At that point, it just isn't all that useful anymore to create the DLL compatible version of the .lib in the first place.  Just create two projects, one that creates the static .lib, another that creates the DLL.  Technically it is possible to still use the static .lib in your DLL project but you'll have to export the functions with a .def file.  That can be high maintenance if the library has a lot of exports.
Comment: You are right that the other option to __declspec(dllexport) is using a module definition file (.def). But is equally valid to use __declspec to export symbols.
Further, it's not possible to 'export' any symbols when building a static lib. A static library can be seen as a collection of object files that the compiler outputted.
Comment: No. What he's saying is that the linker is not marking those functions as exported. This is partially correct. The linker is not marking any of the class's PRIVATE methods as exported. The public methods are exported because they originated in a static .LIB. Your declspec that you build the *DLL* against has no effect. It happens to work in the case of *public* functions, because those are exported anyway.
Comment: In other word's, you're in one of those no-mans-land DLL/LIB scenarios that gave rise to the term "DLL Hell." Is there no way to simply make a DLL and be done with it?
Comment: When building a static library you never mark anything as exported. So how can marking it with __declspec make any difference? And when building a dll, marking a class with __declspec(dllexport) will export the all methods and static members (c.f. http://msdn.microsoft.com/en-us/library/81h27t8c.aspx). Further it's not private but public methods that are unresolved.
Comment: It makes a difference because the linker will see a reference to the function, necessary to assign a value to the export table slot.  The same thing will happen with a program that uses the static library, if no code in the main program ever has a reference to a function in the .lib then it will not be included into the final binary.  Don't forget that a .lib is *not* a final binary, it is just a bag of .obj files.  See this for yourself by writing a small program that uses just one function from the library.  The resulting .exe will be much smaller than the .lib
Comment: Exacly, and that's what I do when building the DLL. All headers of the static libraries are marked with __declspec(dllexport) when I include them in the DLL-project.
Comment: The declaration is not enough, the compiler must actually compile the definition with __declspec(dllexport) in effect.  That generates the metadata that the linker needs to build the export table.
Answer: This is probably years too late, but OP's complaint was that a private method (the destructor) was not exported from a dllexport'd class. Isn't that normal? No external user is allowed to call a private method.


Populate multiselect options onchange of dropdown using AJAX

Question: I have created a content type (Geological Locations) with 2 fields, Country and States.
The Country field is a select box, and States field is a multiselect. So if i select a Country, the States multiselect should be populated based on the selected Country using AJAX.
In my custom module, i used node_form_alter() to customize the node creation form.
I have tried the below code, but it is not working as expected.
function demo_form_geological_locations_node_form_alter(&$form, &$form_state, $form_id) {
    $form['additional_settings']['#access'] = false;
    $form['field_country']['und']['#options'] = array(''=>'Select', 'india'=>'India', 'usa'=>'USA');
    $selected = isset($form_state['values']['field_country']) ? $form_state['values']['field_country'] : '';

    $form['field_country']['und']['#ajax'] = array(
          'callback' => 'ajax_states_callback',
          'wrapper' => 'states-wrapper',
    );

    $form['field_states']['#prefix'] = '
';
    $form['field_states']['#suffix'] = '
';
    $form['field_states']['und']['#options'] = ajax_get_state_options($selected);

    return $form;
}

function ajax_states_callback($form, $form_state) {
    return $form['field_states'];
}

function ajax_get_state_options($key = '') {
    $options = array(
        t('usa') => drupal_map_assoc(
          array(
            t('Florida'),
            t('Georgia'),
            t('Atlanta')
          )
        ),
        t('india') => drupal_map_assoc(
          array(
            t('Maharashtra'),
            t('Gujarat'),
            t('Karnataka')
          )
        )
    );

    if (isset($options[$key])) {
        return $options[$key];
    }
    else {
        return array();
    }
}

Can anyone tell me where i am going wrong?
I am expecting the output like below screenshot, when i select the Country "India":
Comment: Have you considered an alternative method: Create your geo information as parent/child terms in a vocabulary, then use hierarchical select module in multi select mode.
Comment: Actually the data of Countries and States comes from an external API (hundreds of records) and i parse it to create custom arrays, so that i can use AJAX to populate States field, based on the selected Country.
Comment: Not sure if my code is not working, because i am using form_alter().
Comment: As an update, the solution by Naveen Valecha worked out well. And I have shifted to the Dev version of the multiselect module, as the original version is giving some warnings with AJAX onchange.
Answer: Have you tried one of the following modules?
Multiselect (this one suits the most)
Hierarchical Select (relatively easy to configure)
Conditional Fields (requires separate dropdown lists)
A combination of Multiselect and Hierarchical Select will mostly help you achieve what you have shown.
Regards,
Supriya Rajgopal
Comment: Can i use Hierarchical Select module with Form API to populate the Countries and States, using AJAX?
Comment: Yes shasi, I think you can use. Please read the README.txt in the module for more information.
Comment: Hierarchical select is broken in D7, maybe try [Simple Hierarchical Select](https://www.drupal.org/project/shs) instead.
Answer: Awesome question with full detail.After checking I tested it on my local dev box for its fix.
Use the below code for its fix. I have written the problem & its fix below.
    <?php

function demo_form_geological_locations_node_form_alter(&$form, &$form_state, $form_id) {

  $form['additional_settings']['#access'] = false;
  $form['field_country']['und']['#options'] = array(''=>'Select', 'india'=>'India', 'usa'=>'USA');
  $selected = isset($form_state['values']['field_country']) ? $form_state['values']['field_country']['und'][0]['value'] : '';
  $form['field_country']['und']['#ajax'] = array(
    'callback' => 'ajax_states_callback',
    'wrapper' => 'states-wrapper',
  );
  $form['field_states']['#prefix'] = '
';
  $form['field_states']['#suffix'] = '
';
  $form['field_states']['und']['#options'] = ajax_get_state_options($selected);
  return $form;
}

function ajax_states_callback($form, $form_state) {
  return $form['field_states'];
}

function ajax_get_state_options($key = '') {
    $options = array(
        t('usa') => drupal_map_assoc(
          array(
            t('Florida'),
            t('Georgia'),
            t('Atlanta')
          )
        ),
        t('india') => drupal_map_assoc(
          array(
            t('Maharashtra'),
            t('Gujarat'),
            t('Karnataka')
          )
        )
    );

    if (isset($options[$key])) {
        return $options[$key];
    }
    else {
        return array();
    }
}

?>

Problem was at line
$selected = isset($form_state['values']['field_country']) ? $form_state['values']['field_country'] : '';

you were passing the array to the selected value .i.e. countries array but the function ajax_get_state_options needs the key of selected country to return the array of states based on selected country.
I have tested this on php 5.3.27
Other suggestions :

you can also use the existing field api wrapper generated by field api.

P.S. : Double slap myself to track this small mistake in 1h 30 minutes.
Answer: You return $form['field_states'] wrapped in
 to replace content of
. Try removing wrapper when returning form element via AJAX like:
function ajax_states_callback($form, $form_state) {
    unset($form['field_states']['#prefix']);
    unset($form['field_states']['#suffix']);
    return $form['field_states'];
}

You should consider moving $form['field_states'] to a container.
Comment: I tried removing wrapper while returning AJAX response, but it did not work. Can you clarify how to use a container for the field?
Comment: I meant, something like `$form['field_states_container'] = array('#type' => 'container', '#prefix' => '', '#suffix' => '', 'field_states' => $form['field_states']); unset($form['field_states']);`, however I'm not sure it won't break anything in further form processing, since it's not a custom field. Anyway you can try it to check whether it is the reason.
Answer: Try  Reference Field Option Limit
Find the Documentation related to this module here Documentation