How do I record zither, harp etc. with a pickup?

Question: Is there a way to record stringed instruments like zither, harp, piano via a pickup, similar to an electric guitar?
Of course, these instruments can all be recorded via microphones, but what's preventing me from using a pickup?
Unfortunately, I don't know too much about the technology of electric guitars, so I don't know if there are fundamental differences. Do the strings have to be magnetic? Does each string need its own coil? Can I also use it to pick up brass strings? How wide can a single pickup be, can you build it wide enough to fit a whole harp at once?
The idea behind this was: the generation of sound with a harp or zither is comparable to that of a guitar. Could you build an "electric harp" that sounds similar to an electric guitar?
Comment: Keyboard instruments with pickups have existed for close to a hundred years. The twanging rhythm part in Stevie Wonder's "Superstition" is an electric clavichord. Billy Joel uses an electric piano on "Just the Way You Are".
Answer: You can record almost anything with a piezoelectric ("piezo" for short) pickup.
A piezo pickup works by generating a small electric current when it is moved or flexed. There are contact piezo pickups that you can essentially stick or glue on to any sound board and then when properly amplified (a mic preamp usually works well), you get a signal from the instrument you can record without using a mic.
People rarely actually do this because piezo pickups have a brittle sound quality that is hard to make musically pleasing. That said, if you have a lot of ambient noise and you must have a direct sound, this is one option. For larger sound boards, like piano or grand harp, multiple pickups would help capture the full range. That means each pickup has to be amplified, processed, and mixed, but this is done in special circumstances.
One very popular way to use piezo pickups on instruments with strings and soundboards is to combine a piezo pickup with a small, clip-on microphone that basically attaches to the instrument somewhere very close to the sound board. Mic distance is a great way to get signal isolation so even though there is a mic involved, it's so close to the source that the ambient noise is drowned out. The piezo pickup compliments the mic nicely because the mic is so close that it can't pick up all of the nuances. The combination works quite well and is used by professionals in live and recording situations all the time.
Regarding an electric harp or zither, there are some serious challenges. Magnetic pickups as used in electric guitars have to create a magnetic field that includes all of the strings and the field has to be very close to the strings. So designing such a pickup, or really several pickups, to capture all of the strings of a harp or zither would be a challenge and somewhat expensive. You could tack several guitar pickups to a board and arrange them to cover all of the strings (if they would all fit) at least as a prototype. The next problem is finding strings made from magnetic alloys of metal that are available in the gauges and lengths necessary for the instrument. For a zither you might be able to cobble together various electric guitar strings. For harp it might get tricky because I think the largest harps have strings that are longer than electric bass strings. But maybe you could custom make a smaller harp that uses a combination of electric guitar and electric bass strings. There would be lots of math to sort out the gauges and pitches and the resulting tensions. But it very likely could be done.
Comment: Would the technique of using a small, close microphone in addition to a piezo work well for violins? I use just a piezoelectric mic on my violin (mostly in jazz contexts) and sometimes am dissatisfied with the tonal quality.
Comment: @ElizaWilson Absolutely. I believe DPA is the most respected brand for these applications and they make a mic just for that: https://www.sweetwater.com/store/detail/VO4099CoreV--dpa-dvote-core-4099-instrument-microphone-with-violin-mounting-clip Looks like Audio-Technica and Countryman also make similar products
Comment: "*People rarely actually do this*" True for harps.  But it's worth noting that it's very rare (as in substantially less than 1%) to find an acoustic guitar using anything other than a piezo pickup on its own; and ditto electric violins, mandolins, and other similar instruments.  No major manufacturer fits them as standard, so they are always custom fits, either with a high-end luthier-built instrument or as an aftermarket add-on. Harps are a small enough market that there is no financial incentive for anyone to produce a dedicated solution.
Comment: 'Brittle', and 'hard to make musically pleasing' isn't my experience at all.  My first mandolin had magnetic-coil pick-ups, which I found harsh and unnatural (though no doubt suited to some styles of music).  Now I have one with a piezo pick-up; it's close to the acoustic sound, and works great for amplification and recording.  (It came fitted as standard, despite being an Ashbury which I very much doubt counts as high-end (even though I love it!).)
Comment: @Graham That doesn't match my experience with acoustic guitars. I see a lot of guitars both in the wild and for sale with factory installed pickup systems - some are just piezo systems but many (particularly Taylor's Expression System and Martin's two different systems) include multiple pickups with signal processing in the preamp to improve the raw piezo tone. I see a lot of pros playing mandolins and violins with combined piezo and mic systems. The fishman blender system was popular for many years.
Comment: @ToddWilcox At the really high end, I wouldn't disagree. Still though, I'm betting on 100 of Crafter, Godin, Takamine, Yamaha, Ovation and all the rest going through folk clubs for every dual-pickup Taylor or Martin doing properly paid gigs.
Comment: A few decades ago I remember seeing crimp on ferrous sleeves for using magnetic pickups with classic nylon strings, so there are approaches which mean you don't need to have the whole strings ferrous. Though I can't seem to find any reference to them searching the web, so maybe they didn't work that well.
Answer: It's not just theoretically possible to make an electric harp.  You can buy them from at least three manufacturers, and I have one.  It has piezo electric pickups, one per string.  These are wired in parallel, and can be fed to any normal instrument pickup input.
Pickups can be added to an acoustic harp.  These are normally glued to the soundboard.  The post by Tetsujin links to Dusty Strings, who offer a kit with multiple pick-ups, to better cover the range of the instrument.
Answer: Contrary to what some of the other answers have implied, there are actually a whole bunch of keyboard instruments with magnetic pickups, essentially analogous to electric guitar PUs. They all sound significantly different from their acoustic pendants, but that's in a sense a feature – some of these sounds have become legendary and now feature in almost any digital keyboard!

The Clavinet is almost the same as the baroque acoustic clavichord (a string instrument with a different hammer mechanism from piano), and indeed in single notes you can hear the semblance – but while the clavichord is infamously quiet and only useful for very delicate chamber music, the Clavinet benefits from the amplification option and has become famous for a relentlessly bright, highly rhythmic sound, best associated with funk songs like Stevie Wonder's Superstition.
The two most famous models of electric piano, the Rhodes and the Wurlitzer, both use magnetic pickup. However they do not have strings – the vibrating elements are solid metal plates. A Rhodes is actually rather an electric Celesta, rather than -piano, and that's the main reason these instruments sound very different from piano.
The Yamaha CP-80 (and its siblings) is an almost fully-featured grand piano, but built with the intention to be played amplified with its magnetic PUs, not acoustically.These sound much closer to an acoustic piano than Rhodes or Wurlitzer do, but still strangely sterile in the dry signal. Not too surprising – a completely clean electric guitar also doesn't have the depth / resonance of a mic-recorded acoustic guitar.
The Hammond organ uses magnetic PUs on tone wheels. This does not have an acoustic pendant.

In summary, it is absolutely possible to use electric-guitar-style pickups on non-guitar string instruments, but it doesn't make a lot of sense to retrofit an acoustic instrument with such PUs. They are mostly useful for processed, loud, possibly distorted sounds, in which case it anyway sounds basically like a different instrument. Indeed, even the "standard clean" sound people associate with the above instrument is actually result of amplifying them with a nonlinear, possibly tube amp without HF tweeter – again, like you do with guitar.
The only requirement for magnetic PUs is that the strings (or otherwise vibrating elements) are magnetic – which of course isn't the case for example for harps! However, instruments with non-magnetic strings could generally be redesigned to use steel strings, though that might again make a lot of difference to playing feel and certainly to the sound.
Piëzo pickups tend to reproduce the acoustic sound more closely than magnetic ones do, as well as not making any demands on the string material. Contrary to popular opinion the characteristic "magnetic sound" actually has less to do with the magnetic design per se, but rather with the fact that such PUs typically have very many windings, causing a high inductance which together with a passively-driven cable to the amp makes for a resonant low-pass filter. An active magnetic PU can be designed to reproduce the original spectrum quite well, though it will not pick up much of the body resonances. Therefore, to get an acoustic-like tone, you'll always need to combine it with reverb and/or additional microphones.
Comment: This doesn't seem to answer the question, which is partly about zithers and harps
Comment: Well, it gives examples for very different instruments, demostrating that magnetic PUs can be used in versatile ways. And that it would be possible to design even a harp with steel strings and magnetic PUs, though how useful that would be I can't say.
Answer: You can't really do that as you imagine.
Yes, the strings must be steel - not only steel but magnetic steel [some steel  isn't magnetic]
You don't need one coil per string, but it's useful if you have one pole piece from the magnet.
Your coil is going to be really, really difficult to wind for a curved zither, or a huge harp or piano…
… which is why we use piezo pickups on this type of instrument, if we can't mic them.
 These are not recommendations, just the ones I found first
Zither - https://www.thomann.de/gb/shadow_sh_z1nfx.htm
Harp - https://manufacturing.dustystrings.com/harps/accessories-hardware/amplification/dusty-harp-pickup
Piano - https://www.yamahiko.info/en/products-2/piano-pickup
After comments - sure you can do this if you design the instrument from the ground up to work this way, but retrofitting is nowhere near as easy ;)
Comment: \[Expanded my comment into [a separate answer](https://music.stackexchange.com/a/115255/932)\]
Answer: An electric guitar pickup works by magnetic interaction between metal strings and a coil of wire.
What are sold as 'pickups' for stringed instruments other than metal-stringed guitars are generally contact microphones.
The Rhodes 'electric piano' used hammers striking a sort of tuning fork, each with its own pickup coil.  That's about the nearest to a magnetic guitar pickup in a mainstream instrument.


Skewed Response Variable a lot zeroes

Question: I am trying to build a non-parametric model to predict pure premium of an insurance policy. Pure premium is simply the expected claim amount of an insurance policy.The problem is, most insurance policies do not result in claims and so the data set has a lot of zeroes in the response variable: over 90% of the observations made no claim. Existing methods to this prediction specifies a tweedie distribution for the response and uses GLM. But I do want to use non parametric methods to do this.
Is there anything that I can do to a response variable like this one since all the machine learning algorithms I have tried so far are giving me horrible results.
Comment: How correlated your predictors are to the response?
Comment: Why don't you want to use the Tweedie distribution?
Answer: And why do you want to use non-parametric methods?
I'm not an economist/econometrician, but they do have a bunch of statistical models that handle insurance claims where there are a bunch of 0s. A logical one might be a hurdle model, which employ a binary probability (logit or probit) model for the 0 cases and a truncated count model (i.e. Poisson or negative binomial) for the positive cases. Presumably you are in R, so here's an example package (I use Stata, so I am not familiar with which R packages are best for this model):
https://artax.karlin.mff.cuni.cz/r-help/library/pscl/html/hurdle.html
Healthcare claims tend to have a lot of 0s, but usually nowhere near 90% 0s. People tend to default to GLM or GEE with a gamma distribution and a log link, which I understand is a special case of the tweedie family of distributions. It's not a perfect model but it's a generally accepted one. But, it may also not apply to your case.
Comment: Thank you. The reason why I want to use non-parametric methods is just to investigate how they will do on data sets like this one.
Comment: Fair enough. But, without assuming a parametric distribution, how are you going to predict premiums?
Comment: use some sort of learning algoritm to do it

Skewed Response Variable a lot zeroes


Discrepancy between log likelihood Harrell's C Index and brier score for the evaluation of a Cox regression

Question: I am evaluating a dataset of ~400 subjects and 10 covariates trying to fit a Cox ph model for predicting survival in AML patients.
To evaluate the models I am using a bootstrapping procedure of 50 iterations (sampling with replacement). Models are built on the training set and tested on the test set. For each model I calculate Harrell's C-Index (using rcorr.cens from the Hmisc package) and the Brier score (using the peperr package). I then average the results over the 50 iterations. I get an average C Index of 0.70 and a Brier score of 0.08.
My problem:
When I check the p values of the likelihood ratio test / Wald test of each individual model they are non-significant. Of note, this is a subset analysis. When I build models using other covariates in the dataset I get similar CIndex/Brier scores as well as highly significant likelihood ratio test/Wald tests.
Questions:

What could be the reason for the discrepancy between the evaluation on the testset (CIndex and Brier) and the evaluation on the training set (Likelihood ratio/Wald)
Some covariates are found to be significant in the Cox models (though the model itself is not). Is there any meaning for these covariate considering I can merge these results across 50 iterations ?

p.s. - I am aware that I am using the LASSO regularization (glmnet) for feature selection which is prone to overstating my covariates. This is a limitation of my analysis which I am attempting to minimize by the bootstrapping procedure. Regardless, I would like to figure out what is the reason for the discrepancy in my results.
I am attaching my code. Unfortunately the data are PHI and cannot be shared.
library("survival")
library ("glmnet")
library ("c060")
library ("peperr")
library ("Hmisc")
##-----------------------------------------------------------------------------------
##                                    Accessory Functions
##-----------------------------------------------------------------------------------
##
## This function takes a predictor matrix and a Surv obj and uses the glmnet lasso
## regularization method to select the most predictive features and create a coxph
## object predict_matrix is the 'dataset' reformated to replace categorical variables
## to binary with dummy

dataset2predictmatrix <- function (dataset,nonzero.coef=NULL) {
  #creat Y (survival matrix) for glmnet
  surv_obj <- Surv(dataset$time,dataset$status)

  ## tranform categorical variables into binary variables with dummy for dataset
  predict_matrix <- model.matrix(~ ., data=dataset,
                     contrasts.arg=lapply(dataset[,sapply(dataset, is.factor)],
                                          contrasts))

  ## remove the statu/time variables from the predictor matrix (x) for glmnet
  predict_matrix <- subset (predict_matrix, select=c(-time,-status))

  if (!is.null(nonzero.coef)){
    predict_matrix<-predict_matrix[,nonzero.coef]
  }

  list (predict_matrix=predict_matrix,surv_obj=surv_obj)
}

glmnetfun<-function (predict_matrix,surv_obj){

  ## create a glmnet cox object using lasso regularization and cross validation
  glmnet.cv <- cv.glmnet (predict_matrix, surv_obj, family="cox")

  ## get the glmnet model
  glmnet.obj <- glmnet.cv$glmnet.fit

  # find lambda index for the models with least partial likelihood deviance (by cv.glmnet)
  optimal.lambda <- glmnet.cv$lambda.min    # For a more parsimoneous model use lambda.1se
  lambda.index <- which(glmnet.obj$lambda==optimal.lambda)

  # take beta for optimal lambda
  optimal.beta  <- glmnet.obj$beta[,lambda.index]

  # find non zero beta coef
  nonzero.coef <- abs(optimal.beta)>0
  selectedBeta <- optimal.beta[nonzero.coef]

  # take only covariates for which beta is not zero
  selectedVar   <- predict_matrix[,nonzero.coef]

  # create a dataframe for trainSet with time, status and selected variables in binary representation for evaluation in pec
  reformat_dataSet <- as.data.frame(cbind(surv_obj,selectedVar))

  # create coxph object with pre-defined coefficients
  glmnet.cox <- coxph(Surv(time,status) ~ .,data=reformat_dataSet,init=selectedBeta,iter=200)

#   # glmnet.cox only with meaningful features selected by stepwise bidirectional AIC feature selection
#   glmnet.cox.meaningful <- step(coxph(Surv(time,status) ~ .,data=reformat_dataSet),direction="both")
#
#   selectedVarCox<- selectedVar [,attr(glmnet.cox.meaningful$terms,"term.labels")]
#
  # Returned object -> list with glmnet.cv glmnet.obj selectecVar reformat_dataSet
  list(glmnet.cv=glmnet.cv, glmnet.obj=glmnet.obj, glmnet.cox=glmnet.cox,
       nonzero.coef=nonzero.coef, selectedVar=selectedVar,
       reformat_dataSet=reformat_dataSet
#         , glmnet.cox.meaningful=glmnet.cox.meaningful, selectedVarCox=selectedVarCox
        )

}

## This function takes as input a surv_obj (testdate Surv object) and a testdata prediction matrix. Calculates a Brier score
## for either a cox model or a glmnet. Returns an ipec object which is the Brier score (requires peperr and c060)

brier_calc <- function (surv_obj, predict_matrix, model=c("cox","glmnet")){
  if (model=="cox"){
    peperr <- peperr.cox <- peperr(response=surv_obj, x=predict_matrix,
                                   fit.fun=fit.coxph, load.all=TRUE,
                                   indices=resample.indices(n=nrow(surv_obj), method="boot", sample.n=50))
  } else if (model=="glmnet"){
    peperr <- peperr(response=surv_obj, x=predict_matrix,
                     fit.fun=fit.glmnet, args.fit=list(family="cox"),
                     complexity=complexity.glmnet,args.complexity=list(family="cox"),load.all=TRUE,
                     indices=resample.indices(n=nrow(surv_obj), method="boot", sample.n=50))
  }

      # Get error predictions from peperr
      prederr <- perr(peperr)

      # Integrated prediction error Brier score calculation
      ipec<-ipec(prederr, eval.times=peperr$attribute, response=surv_obj)

      list (peperr=peperr,ipec=ipec)
    }

  trainset<-dataset2predictmatrix (dataset)
  models<-glmnetfun (trainset$predict_matrix,trainset$surv_obj)
#   rfsrc<-rfsrcfunc (dataset)
  briercox<-brier_calc (trainset$surv_obj,models$selectedVar,model="cox")
  # requires c060 package which doesn't work on Linux
  brierglmnet<-brier_calc (trainset$surv_obj,trainset$predict_matrix,model="glmnet")
  # briermeaningful <- brier_calc (trainset$surv_obj,models$selectedVarCox,model="cox")
#   brierRFSRC <-pec_calc(rfsrc$obj,dataset)
#   brierRfit<-pec_calc(rfsrc$rfit ,rfsrc$selectedDataset)
  # calculate brier score for coxph with feature selection based on rfsrc
#   selectedDataset<-dataset2predictmatrix (rfsrc$selectedDataset)
#   brierCox.rfsrc<-brier_calc(selectedDataset$surv_obj,selectedDataset$predict_matrix ,model="cox")

  # save image of the workspace after each iteration
  save.image(file)

  ## C-Index calculation 50 iter bootstrapping

  ## initialization of lists for various outputs
  cIndexCox<- list ()
  cIndexglmnet<- list ()
#   cIndexCoxAIC<- list ()
#   cIndexRFSRC<- list()
#   cIndexRfit<- list ()
#   cIndexCox.rfsrc<- list ()

  i<-1
#   pb <- txtProgressBar(min = 1, max = 50, style = 3) ## initialize a progress bar

  train_results_list<-list()
#   rfsrc_train_list<- list ()

  while (i < 51){
    print (paste("Iteration:",i))
#     setTxtProgressBar(pb, i)## run progress bar

    train <- sample(1:nrow(dataset), nrow(dataset), replace = TRUE) ## random sampling with replacement
    # create a dataframe for trainSet with time, status and selected variables in binary representation for evaluation in pec
    trainset <- dataset [train,]
    testset<- dataset [-train,]
    train_matrix <- dataset2predictmatrix (trainset)

    train_results<-glmnetfun(train_matrix$predict_matrix,train_matrix$surv_obj) #runs the sequence of glmnet.cv->glmnet.obj->glmnet.cox
    train_results_list<-c(train_results_list,list(train_results)) #create a list of results of all runs

    #     compute c-index (Harrell's) for cox-glmnet models
    if (!is.null(train_results$glmnet.cox)){
      # creates a matrix of only the variables identified by the glmnet
      test_matrix <- dataset2predictmatrix(testset, nonzero.coef=train_results$nonzero.coef)
      reformat_testSet <- as.data.frame(cbind(test_matrix$surv_obj,test_matrix$predict_matrix)) #casts matrix to dataframe
      cIndexCox <- c(cIndexCox,
                     1-rcorr.cens(predict(train_results$glmnet.cox, reformat_testSet),test_matrix$surv_obj)[1])
      i=i+1

      # compute c-index (Harrell's) for glmnet models
      test_matrix<- dataset2predictmatrix (testset) # create matrix of the entire testset for glmnet evaluation
      cIndexglmnet <- c(cIndexglmnet,
                        1-rcorr.cens(predict(train_results$glmnet.cv, test_matrix$predict_matrix),test_matrix$surv_obj)[1])

      save.image(file)

    }

  }

 meanCICox<- c(mean (unlist(cIndexCox),na.rm=TRUE),std.error(unlist(cIndexCox)))
  meanCIglmnet<- c(mean (unlist(cIndexglmnet),na.rm=TRUE),std.error(unlist(cIndexglmnet)))
#

Answer: When using the Brier score (for which you have to use a special version to account for censoring - I assume you did that) or the $c$-index, the corresponding log-likelihood-based statistic is the likelihood ratio $\chi^2$ statistic for the full model.  Do not look at partial $\chi^2$.  Note that except for the Brier score, the R rms package validate function does the calculations and bootstrapping you need, automatically.
Comment: Thank you. Oddly the likelihood ratio statistic for the full model is still insignificant. I will try implementing the rms/validate function in case this is a problem with my bootstrapping and validation procedures.
Comment: If the original model LR $\chi^2$ test is insignificant, you are on shaky ground to do anything.
Comment: That's what I thought. What puzzles me is how come I get "good" C-Index/Brier scores.
Comment: That is a mystery, as long as "good" is from an unbiased estimate (e.g., separate sample or bootstrap bias-corrected).


[routerLink]="" VS href="javascript:void(0);"

Question: If I want to add a dead link to an anchor tag because I want to use (click) instead then I can use either [routerLink]="" or href="javascript:void(0);". Both has the same effect and I see no difference in browser compatibility.
Which one is prefered to use? Is there any difference?
Comment: If it's a deadlink on which you bind `click` event, you don't need both.
Comment: I weren't using both - just one or the other. The question states which would be prefered to use.
Comment: What i'm saying is that none is needed. ;)
Comment: So you mean "you don't need any" then? ;) But I agree - unless you want the styling for an anchor which is only added if you add the href or routerLink attribute to the tag. I know you can just create your own stylings but keeping the default styling just by adding one of the attributes makes perfect sense to me. :)
Comment: This is what i mean. But making styling based on `href` attribute (or routerLink) is a bad practice. One should use `class` attribute or other kind of selector. ;)
Comment: So you suggest not to add href or routerLink, manually duplicating the default link styling af an anchor and add it as a class to every anchor tag?
Comment: Exactly. It will not cause side effects like with adding `href` or `routerLink`. It will require to redefine default link style but, imho, it's simpler to deal with css than trying to compensate side effects with these attributes in Angular.
Answer: [routerLink]=""

What this line does it, It will redirect to your home route/root route, whereas
href="javascript:void(0);"

The void operator evaluates the given expression and then returns undefined.

for more information read out here -
* What does "javascript:void(0)" mean?
Apart from this if you want to make it a as deadlink just pass event through the click event and use event.preventDefault() which will stop default action of anchor tag will execute what you want to do.


Parent term suggestion on entering the child term in term reference field?

Question: I have a term reference field which has the widget Autocomplete term widget (tagging).
I want the functionality like, when a user type a child term in that autocomplete field, the system should return a suggestion of the parent term that did you mean [parent term].
Suppose A is a parent term and its child term is B. So when a user type B in the field, it should show a suggestion of did you mean A?
Answer: I think you'll need to override the taxonomy autocomplete path. Here's what you will need:

hook_menu_alter() implementation, so your custom module takes over the taxonomy autocomplete suggestions. See hook_menu() implementation, specifically $item['taxonomy/autocomplete'] item in /modules/taxonomy/taxonomy.module for more information.
You'll need to re-create the core taxonomy_autocomplete() function, which is in /modules/taxonomy/taxonomy.pages.inc.
You'll have to perform a check and see for which vocabulary you need to show suggestions:

If it's the vocabulary where you want to have child -> parent functionality, add the code for fetching the parent term and provide additional suggestions.
If it's some other vocabulary, make sure you return the same output as the core function would.

You'll need to add this in a custom module.
function YOUR_MODULE_menu_alter(&$items) {
  // This will re-route this path to your custom module, so you can have any
  // additional logic.
  $items['taxonomy/autocomplete']['page callback'] = 'YOUR_MODULE_taxonomy_autocomplete';
}

function YOUR_MODULE_taxonomy_autocomplete($field_name = '', $tags_typed = '') {
  // Copy the content of taxonomy_autocomplete() function here, and add necessary
  // modifications at the end of it.
}

Hope this helps.
Comment: I'm already here :-). But doesn't know what to do hear :-(
Answer: You can use below code for computing the parent.
function demo_pane_taxonomy_autocomplete($field_name = '', $tags_typed = '') {
  // Copy the content of taxonomy_autocomplete() function here, and add necessary
  // modifications at the end of it.

  // If the request has a '/' in the search text, then the menu system will have
  // split it into multiple arguments, recover the intended $tags_typed.
  $args = func_get_args();
  // Shift off the $field_name argument.
  array_shift($args);
  $tags_typed = implode('/', $args);

  // Make sure the field exists and is a taxonomy field.
  if (!($field = field_info_field($field_name)) || $field['type'] !== 'taxonomy_term_reference') {
    // Error string. The JavaScript handler will realize this is not JSON and
    // will display it as debugging information.
    print t('Taxonomy field @field_name not found.', array('@field_name' => $field_name));
    exit;
  }

  // The user enters a comma-separated list of tags. We only autocomplete the last tag.
  $tags_typed = drupal_explode_tags($tags_typed);
  $tag_last = drupal_strtolower(array_pop($tags_typed));

  $term_matches = array();
  if ($tag_last != '') {

    // Part of the criteria for the query come from the field's own settings.
    $vids = array();
    $vocabularies = taxonomy_vocabulary_get_names();
    foreach ($field['settings']['allowed_values'] as $tree) {
      $vids[] = $vocabularies[$tree['vocabulary']]->vid;
    }

    $query = db_select('taxonomy_term_data', 't');
    $query->join('taxonomy_term_hierarchy', 'h', 't.tid=h.tid');
    $query->addTag('translatable');
    $query->addTag('term_access');

    // Do not select already entered terms.
    if (!empty($tags_typed)) {
      $query->condition('t.name', $tags_typed, 'NOT IN');
    }
    // Select rows that match by term name.
    $tags_return = $query
      ->fields('t', array('tid', 'name'))
      ->fields('h', array('parent'))
      ->condition('t.vid', $vids)
      ->condition('t.name', '%' . db_like($tag_last) . '%', 'LIKE')
      ->range(0, 10)
      ->execute()
      ->fetchAll();

      $tags_new_return = array();
      $parent_array = array();

      foreach($tags_return as $tag_key=>$tag_val) {
        if($tag_val->parent != 0) {
          $parent_array[] = $tag_val->parent;
        }
      }

      unset($tags_return);
    $query_1 = db_select('taxonomy_term_data', 't1');
    $query_1->addTag('translatable');
    $query_1->addTag('term_access');

    // Do not select already entered terms.
    if (!empty($tags_typed)) {
      $query->condition('t.name', $tags_typed, 'NOT IN');
    }
    // Select rows that match by term name.
    $tags_return = $query_1
      ->fields('t1', array('tid', 'name'))
      ->condition('t1.tid', $parent_array, 'IN')
      ->range(0, 10)
      ->execute()
      ->fetchAllKeyed();

    $prefix = count($tags_typed) ? drupal_implode_tags($tags_typed) . ', ' : '';

    foreach ($tags_return as $tid => $name) {
      $n = $name;
      // Term names containing commas or quotes must be wrapped in quotes.
      if (strpos($name, ',') !== FALSE || strpos($name, '"') !== FALSE) {
        $n = '"' . str_replace('"', '""', $name) . '"';
      }
      $term_matches[$prefix . $n] = check_plain($name);
    }
  }

  drupal_json_output($term_matches);
}

Be sure to apply the check of field_name in it, I have not applied that check.


Need to find and disable an email that may be coming from a module

Question: Drupal 7 question: There is an email that goes to users that seems to be produced by a module (on a role change) that is confusing to a specific client's users. They would like me to disable that specific email, but I have not been able to figure out where to do that.
I've gone through the users and roles and configuration for the module. I've done a search on the text in the site files (the snippets of text that do not have field-specific data) and come up empty.
So, generically, I'm wondering about how to disable emails from being sent if there doesn't seem to be a setting to do so in the dashboard. I would be happy to add more information here that is about the module specifically, but it seems that it would be helpful to have some generic pointers of where to look, in case the situation comes up in other modules, as well.
Answer: If you have the Rules module enabled, go and check the rules
<code>/admin/config/workflow/rules
</code>
It's very likely that there is a rule that is sending the emails. So just disable it.
Comment: To the benefit of the OP understanding: Doesn't the Rules module use `drupal_mail()` to send emails?
Comment: I'm sure it does, but it's better to disable it through rules, if its using rules, than having to hack the module (^_^)
Comment: Revisiting Rules. I had checked rules before and there were no Rules listed. That didn't make sense because the related modules have rules. On further investigation, I found that Rules UI was not enabled, but Rules were!
Answer: Search the module code for usages of 'drupal_mail'.
Comment: That did come up with one instance in a related module, but it was not relevant to the specific situation.


Fatal error: Out of memory PHP

Question: I am not sure why this was working fine last night and this morning I am getting

Fatal error: Out of memory (allocated 1611137024) (tried to allocate
  1610350592 bytes) in /home/twitcast/public_html/system/index.php on
  line 121

The section of code being ran is as follows
function podcast()
  {
            $fetch = new server();
            $fetch->connect("TCaster");
            $collection = $fetch->db->shows;

            // find everything in the collection
            $cursor = $collection->find();

            if($cursor->count() > 0)
            {
                $test = array();
                // iterate through the results
                while( $cursor->hasNext() ) {
                    $test[] = ($cursor->getNext());
                }
                $i = 0;
                foreach($test as $d) {

                for ( $i = 0; $i <= 3; $i ++) {
                $url = $d["streams"][$i];
                $xml = file_get_contents( $url );
                $doc = new DOMDocument();
                $doc->preserveWhiteSpace = false;
                $doc->loadXML( $xml); // $xml = file_get_contents( "http://www.c3carlingford.org.au/podcast/C3CiTunesFeed.xml")

                // Initialize XPath
                $xpath = new DOMXpath( $doc);
                // Register the itunes namespace
                $xpath->registerNamespace( 'itunes', 'http://www.itunes.com/dtds/podcast-1.0.dtd');

                $items = $doc->getElementsByTagName('item');
                    foreach( $items as $item) {
                        $title = $xpath->query( 'title', $item)->item(0)->nodeValue;
                        $published = strtotime($xpath->query( 'pubDate', $item)->item(0)->nodeValue);
                        $author = $xpath->query( 'itunes:author', $item)->item(0)->nodeValue;
                        $summary = $xpath->query( 'itunes:summary', $item)->item(0)->nodeValue;
                        $enclosure = $xpath->query( 'enclosure', $item)->item(0);
                        $url = $enclosure->attributes->getNamedItem('url')->value;

                    $fname = basename($url);
                    $collection = $fetch->db->shows_episodes;

                    $cursorfind = $collection->find(array("internal_url"=>"http://twitcatcher.russellharrower.com/videos/$fname"));
                    if($cursorfind->count() < 1)
                    {

                        $copydir = "/home/twt/public_html/videos/";
                        $data = file_get_contents($url);
                        $file = fopen($copydir . $fname, "w+");

                        fputs($file, $data);

                        fclose($file);
                        $collection->insert(array("show_id"=> new MongoId($d["_id"]),"stream"=>$i,"episode_title"=>$title, "episode_summary"=>$summary,"published"=>$published,"internal_url"=>"http://twitcatcher.russellharrower.com/videos/$fname"));

                        echo "$title
 $published
 $summary
 $url

\n\n";
                    }

                }

            }
            }
            }

line 121 is
$data = file_get_contents($url);

Comment: @khanahk $data = file_get_contents($url);
Answer: Memory Limit - take a look at this directive. Suppose that is what you need.
or you may try to use copy instead of reading file to memory (which is video file, as I understand so there is nothing strange that it takes a lot of memory):
$copydir = "/home/twt/public_html/videos/";
copy($url, $copydir . $fname);

Looks like last night opened file were smaller)
Comment: @RussellHarrower suppose copy will work good enough. Or wget. Basically, anything that will not read a file to memory. I just translated those bytes into something human readable and appears that you are reading a file which takes more than 1.6GB - putting whole that file into a memory (file_get_contents do this) is not what you need for sure)
Comment: strange cos they are all HD files I will give that a go and see what happens, atm i am trying wget
Answer: You want to add 1.6GB of memory usage for a single PHP thread? While you can increase the memory limit, my strong advice is to look at another way of doing what you want.
Probably the easiest solution: you can use CURL to request a byte range of the source file (using Curl is wiser than get_file_contents anyway, for remote files). You can get 100K ata  time, write to the local file then got the next 100k and appeand to the file etc, until the entire file is pulled in.
You may also do something with streams, but it gets a little more complex. This may be your only option if the remote server won't let you get part of a file by bytes.
Finally there's Linux commands such as wget, run through exec(), if your server has permissions.

Fatal error: Out of memory PHP


Change JVM params for Solr

Question: How do I specify another type of garbage collector for a dockerized Solr7?
My docker startup command is as follows:
docker run -d --restart always --name solrcloud \
-p 8983:8983 --net host myrepo/my-fusion-solr-image:latest \
bin/solr -c -f -a -javaagent:/opt/newrelic/newrelic.jar \
-Dnewrelic.environment=dev -Ddisable.configEdit=true \
-z dev-fusion-zk.aws.myhost.net:2181/dev-fusion -m 30g

I'm trying to follow this article: https://wiki.apache.org/solr/ShawnHeisey
Where exactly should I specify -XX:+UseG1GC ?
Comment: results in "conflicting collector settings" message at startup and app not being able to start. I figured the answer, will post shortly.
Comment: `-e JAVA_OPTS='-XX:+UseG1GC'` may do
Comment: tried that, to no avail
Comment: How about `-XX:+UseG1GC` right before `-javaagent`, which is a JVM argument as well?
Answer: In Dockerfile for Solr image, add following step:
# Use G1GC garbage collector
# https://wiki.apache.org/solr/ShawnHeisey
RUN sed -i -e 's/^#GC_TUNE.*/GC_TUNE=" \
-XX:+UseG1GC \
-XX:+PerfDisableSharedMem \
-XX:+ParallelRefProcEnabled \
-XX:G1HeapRegionSize=8m \
-XX:MaxGCPauseMillis=250 \
-XX:InitiatingHeapOccupancyPercent=75 \
-XX:+UseLargePages \
-XX:+AggressiveOpts \
"/' /opt/solr/solr-$SOLR_VERSION/bin/solr.in.sh

Solr 7.2.1 has this file bin/solr.in.sh that looks like it was added specifically to override some configs in bin/solr. There in bin/solr.in.sh is a commented out line starting with #GC_TUNE=. If we uncomment this line, it will override GC_TUNE variable in bin/solr.
sed command in the snippet above replaces that line with desired settings. Note that sed can act differently in different environments and may require some modifications to work for your case. Please test it before plugging it into your dockerfile. Above snippet works for centos.

Change JVM params for Solr


How to calculate regularization parameter in ridge regression given degrees of freedom and input matrix?

Question: Let A be $n \times p$ matrix of independent variables and B be the corresponding $n \times 1$ matrix of the dependent  values. In ridge regression, we define a parameter $\lambda$ so that: $\beta=(A^\mathrm{T}A+\lambda I)^{-1}A^\mathrm{T}B$ .
Now let [u s v]=svd(A) and $d_{i}=i^{th}$ diagonal entry of 's'. we define degrees of freedom (df)= $\sum_{i=1}^{n} \frac{(d_{i})^2}{(d_{i})^2+\lambda}$ . Ridge regression shrinks the coefficients of low-variance components and hence the parameter $\lambda$ controls the degrees of freedom.So for $\lambda=0$, which is the case of normal regression, df=n, and hence all the independent variables will be considered. The problem I am facing is to find the value of $\lambda$ given 'df' and the matrix 's'. I have tried to re-arrange the above equation but was not getting a closed form solution. Please provide any helpful pointers.
Comment: Well I need time to answer this (probably others will be quicker to aid you), but most insights may be taken from http://www.stat.lsa.umich.edu/~kshedden/Courses/Stat600/Notes/prediction.pdf And what is $k$ in definition of degrees of freedom, since I do miss $\lambda$ somehow.
Comment: @Dmitrij: Thnx for the reply, I have updated the questions, and replaced 'k' with $\lambda$
Comment: Hi Amit, how can you know what the degrees of freedom are before calculating the regularization parameter?
Answer: A Newton-Raphson/Fisher-scoring/Taylor-series algorithm would be suited to this.
You have the equation to solve for $\lambda$
$$h(\lambda)=\sum_{i=1}^{p}\frac{d_{i}^{2}}{d_{i}^{2}+\lambda}-df=0$$
with derivative
$$\frac{\partial h}{\partial \lambda}=-\sum_{i=1}^{p}\frac{d_{i}^{2}}{(d_{i}^{2}+\lambda)^{2}}$$
You then get:
$$h(\lambda)\approx h(\lambda^{(0)})+(\lambda-\lambda^{(0)})\frac{\partial h}{\partial \lambda}|_{\lambda=\lambda^{(0)}}=0$$
re-arranging for $\lambda$ you get:
$$\lambda=\lambda^{(0)}-\left[\frac{\partial h}{\partial \lambda}|_{\lambda=\lambda^{(0)}}\right]^{-1}h(\lambda^{(0)})$$
This sets up the iterative search.  For initial starting values, assume $d^{2}_{i}=1$ in the summation, then you get $\lambda^{(0)}=\frac{p-df}{df}$.
$$\lambda^{(j+1)}=\lambda^{(j)}+\left[\sum_{i=1}^{p}\frac{d_{i}^{2}}{(d_{i}^{2}+\lambda^{(j)})^{2}}\right]^{-1}\left[\sum_{i=1}^{p}\frac{d_{i}^{2}}{d_{i}^{2}+\lambda^{(j)}}-df\right]$$
This "goes" in the right direction (increase $\lambda$ when summation is too big, decrease it when too small), and typically only takes a few iterations to solve.  Further the function is monotonic (an increase/decrease in $\lambda$ will always decrease/increase the summation), so that it will converge uniquely (no local maxima).
Comment: The assumption is just to get the initial value of $\lambda^{(0)}$ "close enough" to the correct value.  If you have a better guess, then start with that.  You could even just set $\lambda^{(0)}=0$, as long as your d's are greater than zero.  The d's are not assumed 1 in the iterations, just to get the algorithm started.
Comment: thnx a lot , but I have a doubt why do we need to assume $d_{i}^2=1$, since we have their correct values already...I have checked this formula by writing a matlab code and have not taken that assumption, but it works fine and gives correct solution
Comment: (+1) I would give the same numerical solution anyway.
Answer: Here is the small Matlab code based on the formula proved by probabilityislogic:
<code>function [lamda] = calculate_labda(Xnormalised,df)
    [n,p] = size(Xnormalised);

    %Finding SVD of data
    [u s v]=svd(Xnormalised);
    Di=diag(s);
    Dsq=Di.^2;

    %Newton-rapson method to solve for lamda
    lamdaPrev=(p-df)/df;
    lamdaCur=Inf;%random large value
    diff=lamdaCur-lamdaPrev;
    threshold=eps(class(XstdArray));
    while (diff>threshold)
        numerator=(sum(Dsq ./ (Dsq+lamdaPrev))-df);
        denominator=sum(Dsq./((Dsq+lamdaPrev).^2));
        lamdaCur=lamdaPrev+(numerator/denominator);
        diff=lamdaCur-lamdaPrev;
        lamdaPrev=lamdaCur;
    end
    lamda=lamdaCur;
end
</code>
Comment: Go team!
Comment: An attempted editor argues that the while condition should be `while ( abs(diff)>threshold )`.
Comment: I am posting this as an alternative answer to the code posted by @Amit. I am suggesting that comparison to threshold in the `while( abs(diff) > threshold )` because the tolerance for the difference should be reachable from both the left and the right. For example let's say diff = $-100$ and threshold = $1e^{-16}$ then the loop condition is false, but clearly the solution has not converged.


how to open custom form in popup onclick in menu link drupal

Question: I made a custom form in drupal. I just want to open that form on popup form when user click on menu.
Here is my code
function acoma_extra_divide_element_horizontaly($form, &$form_state) {
  $form['description'] = array(
    '#type' => 'item',
    '#title' => t('At which height should the element be divided? (distance
    from cupboard floor)'),
  );

  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Divide draw up horizontally'),
    '#suffix' => 'cm',
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'OK',
  );

  return $form;
}

Menu code is:

Divide element horizontally

Divide element vertically

Reset element

I just want when use click on menu this form loads in popup. I used the popup module.
Any help would be appreciated.
Answer: There are many ways to do this.
You can use  Popup forms module. Its configuration is in documentation of module
or Modal Frame API module.


Removing second copy of ctools module from filesystem

Question: I have a site where two version of ctools are on the filesystem.
The first version is in sites/all/modules - this is correct and where I want it
The second version is in sites/all/modules/contrib - this isn't correct and was placed there by custom formatters make file.
The registered path in the system table is sites/all/modules/contrib. I want to remove the contrib folder as it shouldn't exist and is causing issues when I want to upgrade ctools using make files.
Removing the folder gives an undeclared function error as drupal expects it in that contrib folder. Using drush registry rebuild isn't an option as the error still appears because ctools is embedded so deep.
Changing the paths in the system table still brings up the undeclared function error, this could be caused by APC caching though.
Is there a simple way of removing references to this folder and using the copy of the module in sites/all/modules without causing such a huge impact?
Answer: Unless you have apc.stat = 0, then APC caching is likely not the problem.  You can always set apc.enabled = 0 as a temporary measure until you get the problem fixed.
What version of Drupal?
If you are on Drupal 7, you could try deleting the extra copy and then running Registry Rebuild via drush.  Follow the instructions on the project page.
The other method that should work for Drupal 6 and 7 would be to take a database backup, and then hand edit the {system} table.  If it has both "sites/all/modules/coots" and  "sites/all/modules/contrib/coots" in it, delete out the contrib entries.  If it just has the "sites/all/modules/coots" entries, edit them to take out contrib.  Then manually clear out all of the cache tables.
Make sure you backup your database no matter what you do.  Both of these are dangerous operations.
Comment: Thanks for the reply added the 7 tag, I've switched some wording around to make it clearer as well, I've tried using drush rr to rebuild but as stated in my question it doesn't have an effect. I've also tried the editing of the system table as well. Will take a look at the APC settings though.


Modify label on view exposed filter

Question: I have a view with exposed filter to a field as follows :

I want to change the text 'Deployment date from' and 'And' to 'From' and 'To'
Can i do this with hook_views_query_alter or hook_views_pre_render
Answer: You can easily change the first label with the views editor, by setting it in Filter criteria part. But for the "And" i think you have it because you selected the "is between" operator.
So the easiest way to change it is to use hook_form_alter() our hook_form_FORM_ID_alter() and change the '#title' of that second form field.
If you inspect the html of your field in front, you will see that it is in a  tag. So get the id of that form, for example
<form id="views-exposed-form-activities-page-1" ></form>

then in your_module.module file implements hook_form_FORM_ID_alter():
<?php

/**
 * @file
 * This is your_module.
 */

use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_FORM_ID_alter().
 */
function YOURMODULE_form_views_exposed_form_activities_page_1_alter(array &$form, FormStateInterface $form_state, $form_id) {
  $form['your_annoying_field']['#title'] = t('To'); //Instead of "And".
}

Comment: Yea i changed the first label from the view itself . For the second i didnt get the point you said . How can i access a view field in hook_form_alter ?
Comment: Ok, t did just update my answer, hope it helps :)
Comment: Its not working !! , am taking the id of the field (**'edit-created-min'**). Is that right or need to take the name ?
Comment: I will add as an answer , there was a mistake in taking the form_id from inspection
Comment: Yep, be carrefull with that id, i didn't test it but that was the idea. If you are not sure about the form'id then use `YOURMODULE_form_alter(array &$form, FormStateInterface $form_state, $form_id)` and make `var_dump($form_id)`, this way you can maybe target it easily.
Answer: Finally i got the answer . Actually it should be used like YOURMODULE_form_views_exposed_form_alter only . No need of activities_page_1_ as expected . Am adding the answer below :
/**
 * Implements hook_form_FORM_ID_alter().
 */
function module_name_form_views_exposed_form_alter(&$form, $form_state, $form_id) {
  $form['created']['min']['#title'] = t('From');
  $form['created']['max']['#title'] = t('To');
}

Answer: The easiest way to do this is with the String Overrides module. It's still under heavy development for Drupal 8 but MegaChriz (maintainer of the Feeds module a.o.) made a pretty stable version that you can download here:
https://www.drupal.org/files/issues/stringoverrides.zip
More information:
https://www.drupal.org/node/2236791#comment-8783307
Answer: I was able to do this with the following code.
Note that my field is actually called field_date, but to access the label I had to add "_value" to the end of my field to make it field_date_value.
Also note that $form_id for an exposed form is going to be generic. To check for a unique form ID, check $form['#id'].
/**
 * Implements hook_form_FORM_ID_alter().
 */
function MY_MODULE_form_views_exposed_form_alter(&$form, $form_state, $form_id) {
  if($form['#id'] == 'views-exposed-form-my-unique-form-id') {
    $form['field_date_value']['min']['#title'] = t('From');
    $form['field_date_value']['max']['#title'] = t('To');
  }
}

Comment: Worked a charm to bring custom sort order of date ranges in an exposed filter.

Modify label on view exposed filter


Can you get a non-principal ultrafilter on N using Choice but 'avoiding' Zorn's Lemma?

Question: This question is not about the logical relationships between Choice, Zorn's and the Ultrafilter Lemma, but pedagogical. I am teaching a class and want to go as directly as possible from Choice to a non-principal ultrafilter on $\mathbf{N}$.
The Axiom of Choice is much easier to understand than Zorn's Lemma and the definition of a non-principal ultrafilter on the natural numbers is also pretty easy to understand. However, the proof of Zorn's Lemma using the axiom of choice is relatively technical and introducing partially ordered sets and chains just for this purpose feels a little time-consuming.
Question. Is there a sneaky construction of a non-principal ultrafilter on $\mathbf{N}$ that directly uses the axiom of choice but avoids introducing the statement of Zorn's Lemma?
Comment: I always find it amusing to read "*construction* that uses AoC"
Comment: @Hagen: Well, that's a standard usage, though. Modulo the choice function you *are* constructing something (via transfinite recursion usually).
Answer: Of course.

Fix a choice function on $\mathcal{P(P(\Bbb N))}$.
Start with a non-principal filter, say the co-finite filter.
By transfinite induction, each time choose a set not in the filter constructed thus far which can be added to the filter; at limit steps take unions. If no such set exists, you have an ultrafilter.
Namely, if $\cal F_\alpha$ was defined, either $\{A\subseteq\Bbb N\mid A\cup\mathcal F_\alpha\text{ can be extended to a filter}\}$ is empty, in which case we have an ultrafilter on our hands; or we can use our fixed choice function to choose a set from there, and define $\cal F_{\alpha+1}$ to be the filter extending $\cal F_\alpha$ and the chosen set.
Argue that the construction must stabilize at some point.
Celebrate by having a beer, or some tea if you prefer.

One key lemma here is that if $\cal F$ is a filter on $X$, and $A\subseteq X$, the $\mathcal F\cup\{A\}$ generates a filter if and only if for all $B\in\cal F$, $A\cap B$ is non-empty.

One important remark here is that the axiom of choice "by itself" is nearly useless. It is mostly with transfinite recursion that we can actually use it to construct something.
Comment: You use it to choose a set from those eligible to be added to the filter at each step. And yes, this is "somewhat like the Zorn's lemma proof" because all these proofs are essentially the same.
Comment: I'm not sure how exactly you are using the choice function. Are you well-ordering your set in order to induct? If so, doesn't this basically involve the proof of Zorn's Lemma?
Comment: I don't know what you already covered with your students. Have you covered compactness of first-order logic? Have you covered Tychonoff's theorem? There are other proofs that you can use. You asked for one specifically using AC. This is how you do it. There's a reason AC and Zorn's lemma are equivalent, and you are correct to claim that this proof is essentially a proof of Zorn's lemma inside the proof that every chain of filters has an upper bound. Because, well, again, these things are more-or-less the same.
Comment: Well, do they know about ordinals? They should, because that's how you'd prove that there are only $2^{\aleph_0}$ Borel sets, so "most sets" are not Borel, even the Lebesgue measurable ones. If they know a bit about transfinite recursion, this should be a breeze even by handwaving standards. If ordinals are unavailable either, then you're in for a pickle. You can still handwave your way through, but it might not catch properly (in which case, you can give them this as an axiom: every filter can be extended to an ultrafilter, and as an exercise prove that an ultrafilter is non-principal ...
Comment: ... if and only if it extends the cofinite filter). If they already took some topology class, there are topological proofs that you can give them. If they took a logic class, there are logic-based proofs that you can give them as well. It might be reasonable to expect measure theory students to have some rudimentary knowledge in topology, but I guess that very much depends on the university.
Comment: @David: Not saying that you're wrong; but generalized well-founded recursion is miles ahead transfinite recursion in my experience.
Comment: I see you've clarified; thanks. The thing I didn't really explain is that it's not a set theory class/logic/topology class at all; it's a measure theory class. And I want to construct various non-measurable sets. Choice is OK for most but some more advanced examples it pays to have a non-princ. ultrafilter or Zorn's Lemma. But this may work for at least a slightly hand-wavy explanation that avoids introducing new terminology beyond filters.
Comment: Ordinals are not needed to count the Borel sets. One can encode Borel sets as labeled well-founded countable trees which in turn can be encoded as reals.
Comment: @David: How do you do that without some understanding of ordinals (which is usually the first step before understanding well-founded trees)?
Comment: Oh, I see. Choice is employed in the last bulleted step. :)  Nice answer.
Comment: @Asaf: Define well-founded as lack of infinite branches. Recursively define labels of non-leaf nodes in terms of labels of children nodes. If a student is skeptical, argue that if some label is undefined, then it has a child with undefined label, which in turn has a child with undefined label, as so on, contradicting the definition of well-founded.
Answer: Such a sneaky construction will presumably smuggle in the essence of a proof of either (1) Zermelo's well-ordering theorem or (2) Zorn's Lemma. Let's go with option (1), and let's assume as little prerequisite knowledge as possible.
Given a set of sets $\mathcal{S}$ and $A\in\mathcal{S}$, let $A\downarrow\mathcal{S}$ denote the union of all $B\in\mathcal{S}$ that are proper subsets of $A$.
Given a choice function c on $X=\mathcal{P}(\mathcal{P}(\mathbb{N}))$, call a set $\mathcal{W}$ of filters on $\mathbb{N}$ "well" if every $F\in\mathcal{W}$ has the property that $F$ is the smallest (proper) filter containing $$(F\downarrow\mathcal{W})\cup \{c(X\setminus(F\downarrow\mathcal{W}))\},$$ if such a filter exists. If it does not exist, we instead require $F$ to be the smallest filter containing $$(F\downarrow\mathcal{W})\cup \{\mathbb{N}\setminus c(X\setminus(F\downarrow\mathcal{W}))\}.$$
An example well set of size 3 should clarify to your students the meaning of this definition. Follow up with example well sets of "length" $\omega$ and $\omega+1$.
Now let $\mathbb{W}$ denote the set of all well sets of filters. Assert that $U=\bigcup\bigcup\mathbb{W}$ is an ultrafilter on $\mathbb{N}$. Give the easy proof that $U$ is an ultrafilter if it is a filter. It's not so easy to prove that $U$ is a filter; hand wave and leave the details an as optional or extra-credit project. This will not be completely satisfying, but at least you've given an explicit definition of $U$.
Answer: A free ultrafilter gives a non-measurable subset of the Cantor set in a standard way. There are models of ZF with DC where all subsets of the Cantor set are measurable. In such models no free ultrafilter can exist. So some form of (uncountable) choice is needed to "construct" (via recursion) a free ultrafilter.
Asaf's construction is also how would go about it: enumerate all (infinite) subsets of $\mathbb{N}$ in a well-ordered sequence and check them sequentially.
I don't think it's really more intuitive than Zorn though. If you're teaching a set theory course, Zorn will probably be useful more generally (e.g. to extend bases in linear spaces, construct algebraic completions etc.)
Comment: I don't think this really answers the question - the OP isn't asking whether choice is needed to construct a free ultrafilter, but rather whether there is a more intuitive argument than via Zorn's lemma.


Div aparecer no bottom (Superscrollorama)

Question: Estou com um problema no Scrollorama. Gostaria que a div começasse a aparecer já no bottom, mas ela só está aparecendo quando já estou na metade do site.
A classe:
<code>$(document).ready(function() {
   var controller = $.superscrollorama();
   var scrollDuration = 200;
   controller.addTween('#fade', TweenMax.from( $('#fade'), .50, {css:{opacity:0}, ease:Quad.easeInOut}), scrollDuration);
});
</code>
Comment: É possível fazer um jsFiddle com um exemplo? ou dar um link para ver o problema live?
Comment: Eu usava essas classes do Greensock no Flash, em Action Script 3, nem sabia que tinham feito uma versão em Javascript! Como o Sergio mencionou, tente reproduzir o problema num [jsfiddle](http://jsfiddle.net/), porque é muito difícil imaginar o que está acontecendo. Note que no jsfiddle existe uma aba "*External Resources*" onde é possível acrescentar bibliotecas externas, além do jQuery, então é possível fazer um exemplo funcional.
Comment: Coloca o HTML + Javascript aqui para vermos o que houve.
Answer: Poderia tentar como no exemplo abaixo, apenas passando o posição via CSS.
<code>controller.addTween(
    '#fade',
    TweenMax.from( $('#fade'), .50,
     { css:{opacity:0},
       css:{left: '0px'},
       css:{top: '0px'},
        ease:Quad.easeInOut
     } ),
     scrollDuration );
</code>
Referência: http://www.princiweb.com.br/blog/front-end/ferramentas/o-tal-do-parallax.html


Startup.cs in ASP.NET 5 class library

Question: I created a ASP.NET class library in my ASP.NET5 application. I wanted to add Startup.cs file in order to load some configuration from .json (ConnectionString) file to use it in project and add it to DI. Then I wanted to inject AppSettings into my DbContext which is in the same project. But this is not working, it seems code in Startup class is never executed.
Injecting AppSettings into DbContext throws Exception
InvalidOperationException: Unable to resolve service for type 'Beo.Dal.Properties.AppSettings' while attempting to activate 'Beo.Dal.DataContexts.ApplicationDbContext'.

DbContext
private static bool IsCreated;
private AppSettings AppSettings;

public ApplicationDbContext(AppSettings settings)
{
    AppSettings = settings;
    if (!IsCreated)
    {
        Database.AsRelational().ApplyMigrations();
        IsCreated = true;
     }
 }

Did I miss somthing or I got it all wrong? I already got one Startup.cs in MVC project and it works fine. Can I use it in class library at all? If not how should I load this .json?
This is what I was actually doing inside:
public class Startup
{
    public AppSettings Settings { get; set; }
    public IConfiguration Configuration { get; set; }

    public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
    {
        var builder = new ConfigurationBuilder(appEnv.ApplicationBasePath)
            .AddJsonFile("config.json")
            .AddJsonFile($"config.{env.EnvironmentName}.json", optional: true);

        builder.AddEnvironmentVariables();
        Configuration = builder.Build();

        Settings = new AppSettings();
    }

    public void Configure(IApplicationBuilder app)
    {
        string connectionString;
        if (Configuration.TryGet("Data:DefaultConnection:ConnectionString", out connectionString))
        {
            Settings.ConnectionString = connectionString;
        }
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddInstance(Settings);
    }
}

Comment: Did you find any answer for this? I am having the same problem
Comment: Are you getting any errors at all?
Comment: @KnightFox Yes, I updated the question
Comment: Where are you putting up your DI? ConfigureServices is never called.
Comment: You can only have one Startup class in your Solution.
Answer: You can't have a second Startup.cs file because a class library is not a project that can startup. What you should do is take advantage of the dependency injection and add your DbContext to the services. Now when you need the DbContext for your repositories it'll be ready to go.
There is an example in the DI docs for Core http://docs.asp.net/en/latest/fundamentals/dependency-injection.html#using-framework-provided-services

Startup.cs in ASP.NET 5 class library


Preciso de um novo número random a cada linha em uma consulta sql(server)

Question: Utilizo o sql server. Preciso usar um número random em várias colunas diferentes(o mesmo número random) porém quero um novo numero random a cada linha...
por exemplo, vamos supor que a TABELAX possui apenas 5 linhas e eu faço uma consulta do gênero...
select numeroRandom,numeroRandom2 from TABELAX

eu quero  obter como resultado algo do gênero..
| numeroRandom | numeroRandom2 |
|______________|_______________|
|    1         |      1        |
|    5         |      5        |
|    8         |      8        |
|    2         |      2        |
|    1         |      1        |

Por favor, alguém me ajuda!!
Comment: Você quer um número de linha randômico? No seu exemplo seria de 1 a 5, é nesse intervalo que você quer?
Answer: Você pode utilizar a função row_number que atribui um número de linha baseado em agregação ou ordenação, e utilizar a função newid como ordenação, que gera um valor único para cada linha a cada vez que a query é executada:
select row_number() over(order by newid()) as randomico1,
       row_number() over(order by newid()) as randomico2,
       ra
  from saluno
 order by ra

A query acima não funciona utilizando a cláusula top. Caso seja necessário utiliza-la, deve-se realizar uma subquery com o top antes de gerar a coluna randômica da seguinte forma:
select row_number() over(order by newid()) as randomico1,
       row_number() over(order by newid()) as randomico2,
       x.ra
 from (select top(10) tb.*
         from saluno tb) x
order by x.ra

Caso queira utilizar mais de uma vez o mesmo valor para outra coluna você também pode utilizar uma subquery:
select x.randomico1,
       x.randomico1 as randomico2,
       x.ra
  from (select row_number() over(order by newid()) as randomico1,
               tb.*
          from saluno tb) x
 order by x.ra

Ou:
select row_number() over(order by x.aleatorio) as randomico1,
       row_number() over(order by x.aleatorio) as randomico2,
       x.ra
  from (select newid() as aleatorio,
               tb.*
          from saluno tb) x
 order by x.ra

Caso queira um número randômico que não tenha relação com a quantidade de linhas, utilize a seguinte query em que o número após o %é o máximo:
select abs(checksum(newid()) % 10) + 1 as randomico1,
       ra
  from saluno

Ou utilizando para as duas colunas randômicas:
select x.aleatorio as randomico1,
       x.aleatorio as randomico2
  from (select cast(rand(checksum(newid())) * 10 as int) + 1 as aleatorio,
               tb.*
          from saluno tb) x
 order by x.ra

Answer: select
       x.aleatorio as randomico1,
       x.aleatorio as randomico2
  from (select CAST(RAND(CHECKSUM(NEWID())) * 10 as INT) + 1  as aleatorio,
               tb.*
          from saluno tb) x
 order by x.ra


Get return value in custom annotation spring aop

Question: I have write a simple custom annotation to set HttpHeaders to ResponseEntity because of duplicating the code every where .
Annotation Interface and Class.
<code>@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface JsonHeader {}

@Component
@Aspect
public class JsonHeaderAspect {
    private final Log logger = LogFactory.getLog(getClass());

    @Around(value = "@annotation(JsonHeader)")
    public Object aroundServiceResponse(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
        return proceedingJoinPoint.proceed(new Object[] {headers});
    }
}
</code>
RestController Class
<code>@RestController
@RequestMapping(path = "/login")
public class LoginRestController {
    private final Log logger = LogFactory.getLog(getClass());

    @Autowired
    LoginServiceImpl loginService;

    @JsonHeader
    @RequestMapping(value = "/user",consumes = MediaType.APPLICATION_JSON_VALUE,produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<ResponseBean> postCheckUser(@RequestBody LoginBean loginBean) {
        ResponseBean responseBean = loginService.checkUser(loginBean);
        return new ResponseEntity<ResponseBean>(responseBean,headers, HttpStatus.OK);
    }
}
</code>
Now I want to get the return HttpHeaders value annotaion to rest controller class.
Is any one can describe why it happen and how to fix this issue it will be great helpful. Thanks in advance
Answer: You can do this simply by modifying your advice like this. You don't need to do anything in the controller.
<code>@Around(value = "@annotation(requestMapping)")
public Object aroundServiceResponse(ProceedingJoinPoint proceedingJoinPoint,RequestMapping requestMapping) throws Throwable {

   String[] consumes = requestMapping.consumes();

        consumes[consumes.length] = MediaType.APPLICATION_JSON_VALUE;

    String[] produces = requestMapping.produces();

        produces[produces.length] = MediaType.APPLICATION_JSON_VALUE;

    return proceedingJoinPoint.proceed();
}
</code>
Comment: I have use requestMapping in controller classes.How it can be use to only for restcontroller classes ?


Emulate shell command line in C

Question: I want to emulate the following shell command line in C, with execl():
find . -type f -ls | cut -d " " -f 3- | sort -n -k 6 >file.txt ; less <file.txt

I wrote each of them as:
execl("/usr/bin/find", "find", ".", "-type", "f", "-ls", (char *)NULL);
execl("/usr/bin/cut", "cut", "-d", "" "", "-f", "3-", (char *)NULL);
execl("/usr/bin/sort", "sort", "-n", "-k", "6", ">file.txt", (char *)NULL);
execl("/usr/bin/less", "less", "<file.txt", (char *)NULL);

I also implemented the pipelines but I am getting an error:
cut: cut: -: Input/Output error -: Input/output error

Any idea what it means?
Thanks
Answer: All redirections, be them pipes (|) or redirection to files (<, <<, >, >>, etc.) are only processed by the shell. When you pass them in an execx call, they are simply passed as an additional argument to the new program.
And anyway, execl replaces the original program by the new one, so anything after execl in never executed unless execl returned an error. The correct way is to setup pipes for the inter process communications, fork to get the number of processes, redirect standard io to the pipes, and only then exec the new programs.
Comment: Each execl is running in its own process, and the pipes are being used as IPC mechanisms. My problem now is an error saying: the delimiter (in cut) must be a single character
Comment: @Vylst: And how could I guess that? Could you please show  code reproducing the problem?
Answer: This:
 "" ""

does not create a string holding a double-quoted string. It creates an empty string, by concatenating one empty string (the first "" pair) with another empty string (the second "" pair). Remember that C automatically concatenates adjacent double-quoted string literals ("foo" "bar" is the same as "foobar").
The quotes shouldn't be passed to cut, anyways. You meant:
" "

Update: On the other hand, it's quite possible that you shouldn't be quoting this space after all. The exec() family of functions don't go through a shell by default, and the quoting is for the shell. You really want to pass a space to cut, so you should do so directly with " ".

Emulate shell command line in C


Relation between expectations of two random variables

Question: I have two random variable X and Y. I know that
$$E_X\left[X \log \frac{X}{e}\right] < E_Y\left[Y \log \frac{Y}{e}\right]$$
Using the above relation can I say anything about the relation between $E_X[X]$ and $E_Y[Y]$ ?
Comment: Is that all you know about these random variables?
Comment: If needed, we can assume that the random variables X and Y are independent.
Comment: Since you only ask about marginal expectations, independence is irrelevant.
Answer: I will only give some hints.
Clearly, $X>0$ is a positive random variable for this to make sense. Note that $x \log(x/e) = x\log x - x\log e = x\log x -x$.  Define $f(x) = x\log x -x$.  So your claim becomes $\DeclareMathOperator{\E}{\mathbb{E}}  \E_X f(X) < \E_Y f(Y)$.  Calculate the two first derivatives of $f$, and conclude that $f$ is convex.  Then: Jensen inequality:  https://en.wikipedia.org/wiki/Jensen%27s_inequality


How do I calculate the mean and SEM of different measured parameters in a table using data organized into subcategories?

Question: I am new to R, so I apologize if this has been asked before, but I was wondering how I can get R to take my data like this:
Tissue  Strain  Mouse  Parameter1  Parameter 2
 1       1       1      80.10       93.60
 1       1       2      86.70       91.30
 1       1       3      80.10       89.20
 1       1       4      82.30       90.70
 1       1       5      83.60       93.30
 1       2       6      79.60       88.20
 1       2       7      84.00       91.50
 1       2       8      73.80       93.10
 1       2       9      83.70       93.20
 1       2       10     83.90       92.40
 2       1       1      84.40       53.80
 2       1       2      88.40       47.30
 2       1       3      88.70       45.70
 2       1       4      83.90       48.80
 2       1       5      81.90       56.80
 2       2       6      87.00       44.80
 2       2       7      87.50       43.20
 2       2       8      88.30       49.80
 2       2       9      89.20       41.60
 2       2       10     89.80       39.30

and produce a table that looks like this:
                Parameter 1 Parameter 2
Tissue  Strain  Mean  SEM   Mean  SEM
1       1       82.56 1.23  91.62 0.82
2       1       81.00 1.98  91.68 0.92
3       1       85.46 1.33  50.48 2.08
1       2       87.28 0.52  43.74 1.77
2       2       83.92 0.75  57.06 3.14
3       2       86.16 0.76  56.38 2.85

I saw previous threads using aggregate and dplyr but they don't quite look like what I need (or maybe I am not understanding it well). Any help would be greatly appreciated!
Comment: You can't have grouped columns in a data frame if that is what you are after. You might get by with *param1.Mean*, *param1.SEM* and alike. Everything else is formatting and depends where you want all that and how badly you want it that way. Also usually you would have a column *Parameter* that would have either 1 or 2 values...and just 2 columns for Mean and SEM. This is called long/molten(from melt), stacked, or unpivoted representation. Many graphing functions would prefer that over wide/cast/unstacked/pivoted form.
Answer: One straight-forward way is using dplyr:
library(dplyr)

dat %>%
  group_by(Tissue, Strain) %>%
  summarize_at(
    vars(Parameter1, Parameter2),
    funs(mean, sem=sd(.)/sqrt(length(.)))
  )
# Source: local data frame [4 x 6]
# Groups: Tissue [?]
#   Tissue Strain Parameter1_mean Parameter2_mean Parameter1_sem Parameter2_sem
#    <int>  <int>           <dbl>           <dbl>          <dbl>          <dbl>
# 1      1      1           82.56           91.62      1.2327206      0.8230431
# 2      1      2           81.00           91.68      1.9811613      0.9216290
# 3      2      1           85.46           50.48      1.3298872      2.0826426
# 4      2      2           88.36           43.74      0.5182663      1.7668050

Data:
dat <- read.table(header=TRUE, text='
Tissue  Strain  Mouse  Parameter1  Parameter2
 1       1       1      80.10       93.60
 1       1       2      86.70       91.30
 1       1       3      80.10       89.20
 1       1       4      82.30       90.70
 1       1       5      83.60       93.30
 1       2       6      79.60       88.20
 1       2       7      84.00       91.50
 1       2       8      73.80       93.10
 1       2       9      83.70       93.20
 1       2       10     83.90       92.40
 2       1       1      84.40       53.80
 2       1       2      88.40       47.30
 2       1       3      88.70       45.70
 2       1       4      83.90       48.80
 2       1       5      81.90       56.80
 2       2       6      87.00       44.80
 2       2       7      87.50       43.20
 2       2       8      88.30       49.80
 2       2       9      89.20       41.60
 2       2       10     89.80       39.30')

Answer: Shortly, you can do it in one line with the plyr package as follows. This is an example using the iris dataset:
ddply(iris, .(Species), summarise, MeanLength = mean(Sepal.Length), SdLength = sd(Sepal.Length))

Which returns:
 Species MeanLength  SdLength
1     setosa      5.006 0.3524897
2 versicolor      5.936 0.5161711
3  virginica      6.588 0.6358796


I can't access to a file even with read permission

Question: This is my problem:
I get permission from the user to access storage in my app (READ/WRITE_EXTERNAL_STORAGE permission), my app saves a backup file on internal storage. My app can read that backup and restore it without any problems.
The problem is that if the user uninstalls and reinstalls the app , even if the app receives READ/WRITE_EXTERNAL_STORAGE permissions,my app can not restore that file anymore! because that file has not saved with the current version of the app. I know I can solve it by getting MANAGE_EXTERNAL_STORAGE permission, But because this is a sensitive permission, Google does not allow my application to have this permission and they will reject my app update with this permission.
Is there a way to solve this problem?  It does not seem logical at all that my program can not be backed up and restored
Comment: Use the Storage Access Framework (`ACTION_CREATE_DOCUMENT` / `ActivityResultContracts.CreateDocument` and `ACTION_OPEN_DOCUMENT` / `ActivityResultContracts.OpenDocument`). This allows the user to specify where on the user's device you should place the backup. It also requires no permissions.
Comment: https://stackoverflow.com/questions/71725859/store-files-in-android-app-targeting-api-31-and-above-which-is-retained-even-a/71727689#71727689
Answer: I find the answer, I should uses Storage Access Framework, It doesn't need any permission
Imagine we have saved JSON to a text file, here is the steps to restore data from it:
1- We need a method that displays a dialog to the user, so he/she can choose saved file:
private void openFile() {
    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.setType("text/*");
    someActivityResultLauncher.launch(intent);
}

2- We should implement onActivityResult to get the uri of the file that user has selected, so add someActivityResultLauncher to activity class:
    ActivityResultLauncher<Intent> someActivityResultLauncher;

3- Add following methods to Activity class:
 private void registerActivityResult()
{
    someActivityResultLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            new ActivityResultCallback<ActivityResult>() {
                @Override
                public void onActivityResult(ActivityResult result) {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        // There are no request codes
                        Intent data = result.getData();
                        Uri uri = data.getData();
                            // Perform operations on the document using its URI.
                            try {
                                String txt = readTextFromUri(Setting_Activity.this, uri);
                                dorestore(txt);
                            }catch (Exception e){}

                    }
                }
            });
}

4- Call the above method in onCreate() method of activity:
@Override
protected void onCreate(Bundle savedInstanceState) {
    //......
    registerActivityResult();
    //.....
 }

5- Implement the readTextFromUri() method we used in step 3:
public static String readTextFromUri(Context context, Uri uri) throws IOException {
    StringBuilder stringBuilder = new StringBuilder();
    try (InputStream inputStream =
                 context.getContentResolver().openInputStream(uri);
         BufferedReader reader = new BufferedReader(
                 new InputStreamReader(Objects.requireNonNull(inputStream)))) {
        String line;
        while ((line = reader.readLine()) != null) {
            stringBuilder.append(line);
        }
    }
    return stringBuilder.toString();
}

That's all, just implement the dorestore() method we used in step 3 to restore your json data.
in mycase it looke something like this:
private void dorestore(String data)
{
    ArrayList<dbObject_user> messages = new ArrayList<>();
    try {
           JSONArray jsonArray = new JSONArray(data);
           //....
           //parsing json and saving it to app db....
           //....
     }
    catch (Exception e)
    {}
  }

just call the openFile() in step 1. That's all.


I want to invoke C# script in my aspx webpage, help me implement it

Question: I want to invoke a C# code into my aspx webpage. Can someone please show me how to do this? C# code is very long, I saved it in a .cs file and put it into the web directory along with the web page files, but when I try calling it into my webpage, some server error happens on the page.
Here is the code, kindly help me implement it properly.
Thanks
<%@ language="C#" %>

    <%

Comment: @YasirMehmoodButt: "Is the above code correct?" What is it supposed to do? It could have bugs in it but we don't know the logic do we? As per the exception you are getting, unless you specify that, nobody can help you.
Comment: It would help immensely if you would describe the error you are getting.
Comment: Have you installed ASP.NET on your computer?
Comment: well error details are not enabled on webpage but it shows some runtime error, i am running IIS7 with all necessary programs. can you tell me how to implement this script properly showing example code? i simply read it from forums to implement this code, i know nothing except implement javascripts.
Comment: What error do you get if you display the exception? You should have some information as how to enable it on your page (adding a `` in your web.config). I think if you view the page on localhost you should see errors though
Comment: listen, i removed the install code, i have the code in .cs file in web directory. i used this call code, you can correct this one if this is wrong.
Comment: <%@ Page language="C#" Inherits="System.Web.UI.Page" runat="server" CodeFile="~/somecode.cs" %>
Comment: is the above code correct????
Comment: @YasirMehmoodButt: Have you tried debugging to see what exception you're thrown?
Answer: If you want invoke method in your aspx, you can use <% %> symbol.
<% =vservADRequest("test", "test", "test", true) %>


Como compartilhar uma foto android

Question: Tenho este drawable:
String nome_foto = itens.get(pos).nome_foto;
        int drawableId = getResources().getIdentifier(nome_foto, "drawable", getPackageName());
        Drawable drawable = getDrawable(drawableId);

tenho este drawable com a foto, como posso usá-la no compartilhar do Android.
Pensei em algo assim:
Intent sendIntent = new Intent();
        sendIntent.setAction(Intent.ACTION_SEND);
        sendIntent.putExtra(Intent.EXTRA_STREAM,Aki precisa de um uri );
        sendIntent.setType("image/jpg");
        startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.compartilhar)));

Porém precisa de um uri que não sei como fazer?
Answer: Você pode utilizar o share Action Provider, basicamente é um mecanismos de compartilhamento ajuda a você compartilhar conteúdo. Para maiores informações documentação do Android que ele ira de ajudar.
Answer: Você pode compartilhar uma foto desde que haja um caminho para ela. E a URI identifica este caminho, quando atribuído um valor em string.

Busca a imagem no seu dispositivo através do caminho dado na URI]:

Uri imgUri=Uri.parse("file:///data/data/MINHA_PASTA_ANDROID/minhaimage.png");
imgview.setImageUri(imgUri);

Agora você tem uma URI chamada: imgUri
...

sendIntent.putExtra(Intent.EXTRA_STREAM,imgUri );

...

No entanto, as vezes você pode querer pegar da pasta drawable:

Uri imgUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" +
                getResources().getResourcePackageName(R.drawable.ic_launcher) + '/' +
                getResources().getResourceTypeName(R.drawable.ic_launcher) + '/' +
                getResources().getResourceEntryName(R.drawable.ic_launcher) );

//Testando
imageView.setImageURI(imageUri);

Answer: Tente desta forma:
Uri uri = Uri.parse("android.resource://your.package.here/drawable/image_name");

Como compartilhar uma foto android


Make $2$ cubes out of $1729$ unit cubes, expected number of times you have to paint

Question: I'm trying to solve question 6 from the PuMac 2007 Combinatorics A competition:

Joe has $1729$ randomly oriented randomly arranged unit cubes, which are initially unpainted. He makes two cubes of sidelengths $9$ and $10$ or of sidelengths $1$ and $12$ (randomly chosen). These cubes are dipped into white paint. Then two more cubes of sidelengths $1$ and $12$ or $9$ and $10$ are formed from the same unit cubes, again randomly oriented and randomly arranged, and dipped into paint. Joe continues this process until every side of every unit cube is painted. After how many times of doing this is the expected number of painted faces closest to half of the total?

Here's what I got so far:

${1\over2}$ chance of this happening: If you make two cubes of side lengths $9$ and $10$, then $16$ cubes will have $3$ faces sharing a vertex painted, $12(8 + 7) = 180$ cubes will have $2$ faces sharing an edge painted, $6(8^2 + 7^2) = 678$ cubes will have $1$ face painted, and the remaining $7^3 + 8^3 = 855$ cubes will have no faces painted.

${1\over2}$ chance of this happening: If you make two cubes of side lengths $1$ and $12$, then $1$ cube will have all $6$ faces painted, $8$ cubes will have $3$ faces sharing a vertex painted, $12(10) = 120$ cubes will have $2$ faces sharing an edge painted, $6(10^2) = 600$ cubes will have $1$ face painted, and the remaining $10^3 = 1000$ cubes will have no faces painted.

But I'm stuck as this point, and don't know what to do next. Any help would be well-appreciated.
Comment: Probably off-topic, but I can't help noticing that 1729 is Ramanujan's number, which is the smallest number that can be written as the sum of two cubes.
Comment: @AritroShome In two different ways. And positive cubes only.
Answer: Thankfully we are being asked about the expected value of this random variable, the random variable is a sum of simpler random variables, namely whether each unit face remains unpainted or not, so we can exploit linearity of expectation.
If we are able to find a good expression for the expected value after $k$ steps then we must simply find which $k$ yields the value closest to $6\times 1729/2$
First note all $6\times 1729$ of the faces are identical. The expected number of painted faces after $k$ steps is equal to the probability $p_k$ that a face remains unpainted after $k$ steps multiplied by $6\times 1729$.
Hence we are simply asked to find the value of $k$ for which $p_k$ is closest to $\frac{1}{2}$.
Now, since every step is independent we begin by finding the probability $q$ that a face is painted in a single step. Assume we are in the $9,10$ case and notice that each possible location and orientation of the unit cube of our face is equally likely, so the probability that it is on the outside (and hence gets painted) is $\frac{6\times9^2 + 6\times 10^2}{6\times1729}$. For the other case we get $\frac{6\times 1^2 + 6\times 12^2}{6\times 1729}$, so $q = \frac{1}{2}\frac{6\times9^2 + 6\times 10^2}{6\times 1729} + \frac{1}{2}\frac{6\times 1^2 + 6\times 12^2}{6\times 1729} = \frac{7^2 + 10^2 + 1^2 +12^2}{2\times 1729} = 21/247 \approx 0.085$
Since $p_k$ is the probability that a face is never colored we have $p_k =  (1-q)^k$, so we must solve for $\frac{1}{2} = (1-q)^k$ which yields a solution of 7.8. The integer value that gives the closest result to $\frac{1}{2}$ is $8$.
Comment: Yes, the random variable $F_k$ that gives the number of painted faces after $k$ steps is not a sum of $6\times 1729$ independent indicator variables, that would just make it a binomial distribution. But we can still calculate its expected value via linearity of expectation.
Comment: Independence does play a role, but with respect to whether a (randomly oriented, randomly formed) face would get painted (possibly not for the first time) in step $j$ versus in step $k$, not with respect to the painted status of two distinct faces.
Comment: I think you need to be careful here because whether two arbitrary faces are painted will not be independent. If one face is painted, then the opposite face of the same cube will not be painted. And cubes on the edge or the corner of a big cube behave differently.


Object doesn't support this property or method error in IE7 jQuery

Question: IE7 is showing this error message: (no other browser is showing any error except ie7)
Message: Object doesn't support this property or method
Line: 97
Char: 2

And line 97 has this:
$('.megamenu').megaMenuCompleteSet({

The complete javascript code is this:

Can somebody advice me what is wrong with line 97?
Thanks!

UPDATE SOLVED:
i was using the latest one, i fixed it myself, it was all my fault, i had the jquery lib loaded two times with different versions, it was not making any trouble on other browsers except IE7. But after debugging i found the multiple lib loading and removed and there were no errors :)
Thank you everyone!
Comment: Try `alert(jQuery().megaMenuCompleteSet);` to see if the plugin has been loaded.
Comment: Thank you @brandon-boone
Error was multiple lib loading :(
Answer: What version of the MegaMenu script are you using? I can see this in their changelog:
06/23/2012 – Version 2.11
Fixed an issue occurring under IE7 in megamenu.js

Comment: Thank you @sergiu
I was using the latest build of megamenu.js
Error was multiple lib loading :(
Answer: I am not sure if this is the issue but you don't need to pass JQuery as an argument since it is global so:
$(document).ready(function($){

should be:
$(document).ready(function(){

This may be the issue since your JQuery plugin appears to be what is not working properly.
Comment: You're right, this isn't necessary, but it's certainly not invalid. See ["Aliasing the jQuery Namespace" in this article](http://api.jquery.com/ready/). You would more normally see this as `jQuery(document).ready(function($) {});`. This construct is primarily used to prevent collisions with other libraries using the `$`.
Comment: Thank you @BrandonBoone and marteljn
I tried this one too, but the errors stayed the same.
It was the jq lib loaded multiple times issue. But surprisingly it was only showing error in IE7, not even in IE8.
Anyways, thank you everybody for your time and help :)


How to conceptually add polymorphism?

Question: I've got a group project that involves taking a Java program used to emulate an ice-cream shop and converting it into a GUI application.
The shop pre-loads 16 different ice-creams. There are workers in the shop as well as cashiers & stockers (which both extend from worker, where cashiers have an int patience, and stockers have an int stamina).
Workers (and thus cashiers/stockers) are able to serve ice-cream. Only cashiers can process orders, and only stockers can restock ice-cream (each ice cream starts with 80 scoops).
There is only one active cashier/stocker at a given time, and possibly a cashier/stocker on break. The workers are loaded from a file (where each line explicitly states if it is a Worker, Stocker, or Cashier) into their respective array lists (whereby there's an ArrayList for Workers, an ArrayList for Stockers, and an ArrayList for Cashiers).
I'm now finding it very complicated to convert this into a GUI having to mess around with 3 ArrayLists. I want to change the project to save all workers into one ArrayList of type Worker. However, a lot of the actions within the shop are already defined/executed assuming three different ArrayLists.
Changing the code to load the whole Worker file into one ArrayList of type Worker is simple. However, how can I conceptually change the rest of the functionality of the shop to work with one ArrayList?
For example - if I want to set the shop's active cashier to be Bill, how could I navigate the ArrayList to find only cashiers, then find Bill, then set him to be active?
I suppose what I'm confused about is how can I interact with an ArrayList of subclasses and know which type of subclass I'm interacting with at a given time? I'm aware of how to use instanceOf() but I feel like it extends (no pun intended) further than that?
Comment: Generally if you have to check for specific types then the polymorphism in the design is likely broken.  It's a violation of the Liskov Substitution Principle.  The model itself should know what it needs to do when you invoke an operation that's common to all models.  For example, if "Bill" needs to begin his shift, then you would find the element in the collection with `Name` equal to `"Bill"` and would invoke an operation on that object, something like `beginWorking()`.  The object itself should contain the logic of what it needs to do.
Comment: Having *zero* knowledge of your code, I can't really say how you'd show anything.  If I had a collection of Employee objects, I imagine I'd also have an object which coordinates their current work schedules.  Perhaps called a TimeClock object or something of that semantic nature.  It would maintain the state of current shifts and would know which Employees are currently working where.  The ArrayList is really just a repository of Employee objects, nothing more.  You fetch an Employee from it.  It shouldn't be used to coordinate shifts and other business logic.
Comment: So - let's say my Workers ArrayList looked like (where the letter denotes the type of class, Worker/Stocker/Cashier): [W, S, S, W, C, C]. If I started the shop and wanted to set the active cashier/stocker to their first instances in the ArrayList (so at index 1 for Stocker and 4 for Cashier) - and later on I pressed on a button to "Change Active Cashier/Stocker" - how could I go about showing all cashiers/stockers except the active one?
Answer: Normally you would iterate over an array of Workers when you want to call generic Worker actions (like getPaid() or startShift()). The implementations of these might vary according to the specific class (this is Polymorphism in essence), but they would be common to all Workers.
Without looking at your code, it seems unlikely you would get benefit from trying to call Cashier or Stocker specific methods from a Collection of Workers.
Answer: I think that putting them all into a single collection is going to prove more problematic than keeping the separate lists.
As you mentioned, finding one of a particular type would be "messy".
If you have a lot of other cases where you need to iterate over all of the workers, consider either keeping them all in an additional collection just for that purpose, or creating a method that iterates over all three lists, that you can reuse.
Answer: It sounds it would be easier to manage them as different arrays/objects for the worker types, and yet another object to manage them as employees.  Employees would not be an array, but an object containing pointers to all the different arrays, but could also process high level tasks, as well as display them on the GUI in a generic fashion.  Displaying them would be grouped by type, unless you need to display them by some other criteria (ordering from file), in which case you could return a (temporary?) array.  If you have the flexibility on the GUI, make worker type views/subviews that could handle anything specific to that object type.
Answer: You could do something like that
private void processCashiers(){
    List<Cashier> cashiers = new ArrayList<>();
        for(Worker w : workers){
            if(w instanceof Cashier){
                cashiers.add(w);
            }
        }
    // do something with cashierers here
}

Basically creating a specified list locally and process it.

How to conceptually add polymorphism?


Highcharts area direction

Question: Is it possible to show gradient area on Highchart over the line?
I need the chart to have the area over the line and not under it. I would be happy for help because i did not find a solution using the Highcharts API.
Comment: You can see the example of area under the line here: https://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/demo/line-time-series/
Answer: You can achieve this with the threshold (API) option. For example:
plotOptions: {
    area: {
        // ... for brevity
        threshold: Infinity
    }
}

Or see this JSFiddle example of it in action. This utilized the following:

If Infinity or -Infinity, the area between the graph and the corresponing Y axis extreme is filled (since v6.1.0).

Highcharts area direction


What kind of passage I may use this Key and What's the name of this Key?

Question: I'm a flute player and I bought this flute sometime ago and I'd like to know:
Flute Yamaha 371 Allegro version

What kind of passage I may use this Key and What's the name of this
  Key?

Please, I'd like the references or a comment of a recognized flute player or some article with the example.
Edited:
I found the name of the key the the manufacturer's website. They call it the Ice lever (A#).
Reference from Yamaha

Can you give me an example of how the Ice lever is used in practice?
I'm accustomed to using alternative keys depending the passages on the music sheet, but this key doesn't make sense because B flat is very near to this key.
The key:

The hole that key close:
Answer: That's an alternative B-flat key.  It's particularly useful in chromatic combinations e.g. B B♭ A B♭, in chromatic scales, or for trills e.g. A♭ to B♭. Or for this kind of chromatic phrase

There are two advantages of using this key rather than than the F key ("long B♭"):

There are two springs less to overcome pressing the key down, so it's faster and less noisy
The key can be left down in passages that go down to A, A♭ or G and back

The Woodwind Fingering Guide calls this the
"Bb trill key". Others call it the "B-flat lever". Yamaha calls it the "Ice lever" (possibly from the German word "Ais" for A#, pronounced "ice").
Blogger Jennifer Cluff has a series of articles on using the three different B-flat alternatives: part 1, part 2, more.
Comment: @Elizeu: "Ice lever" sounds very strange. However the word "ice" sounds just the same as "ais", the German name for A sharp... Maybe it comes from that?
Comment: @ScottWallace I thought that was obvious, but I've now mentioned it explicitly.
Comment: @Elizeu "Ice lever" is a term I've never heard before
Comment: Me neither, for this purpose I was asking.
Comment: your anwser is right. I did some tests and it make sense.
Comment: @Ramillies Yes, I think one of the instrument makers at Yamaha must have studied in Germany.
Comment: It should be perhaps pointed out that the advantage of the "ice" (or "Ais") lever over just using the first finger key of the right hand is that there's one less spring to overcome pressing it down.  It's thus faster and less noisy.


Questions about CTS/VTS and CDD for android 10

Question: We are developing Head Unit for Automotive and using Android 10.
We won't integrate Google Play Services on this. I concern that we have to run and pass CTS/VTS or not? And, Do you have compliant all items in Android CDD?
Please help us to make clear.
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Answer: Let's assume, you are not Integrating the GMS Package, which would be the case like OEMs - Zebra, who launches their product without GMS suite, in this case, you can avoid testing and certification for GTS but if you claim, your phone is android then you have to pass CTS, CTS on GSI, STS, VTS, CTS Verifier compulsory.