Edit tensorflow inceptionV3 retraining-example.py for multiple classificiations

Question: TLDR: Cannot figure out how to use retrained inceptionV3 for multiple image predictions.
Hello kind people :) I've spent a few days searching many stackoverflow posts and the documentation, but I could not find an answer to this question. Would greatly appreciate any help on this!
I have retrained a tensorflow inceptionV3 model on new pictures, and it is able to work on new images by following the instructions at https://www.tensorflow.org/versions/r0.9/how_tos/image_retraining/index.html and using the following commands:
bazel build tensorflow/examples/label_image:label_image && \
bazel-bin/tensorflow/examples/label_image/label_image \
--graph=/tmp/output_graph.pb --labels=/tmp/output_labels.txt \
--output_layer=final_result \
--image= IMAGE_DIRECTORY_TO_CLASSIFY

However, I need to classify multiple images (like a dataset), and am seriously stuck on how to do so. I've found the following example at
https://github.com/eldor4do/Tensorflow-Examples/blob/master/retraining-example.py
on how to use the retrained model, but again, it is greatly sparse on details on how to modify it for multiple classifications.
From what I've gathered from the MNIST tutorial, I need to input feed_dict in the sess.run() object, but was stuck there as I couldn't understand how to implement it in this context.
Any assistance will be extremely appreciated! :)
EDIT:
Running Styrke's script with some modifications, i got this
    waffle@waffleServer:~/git$ python tensorflowMassPred.py  I
       tensorflow/stream_executor/dso_loader.cc:108] successfully opened
       CUDA library libcublas.so locally I
       tensorflow/stream_executor/dso_loader.cc:108] successfully opened
       CUDA library libcudnn.so locally I
       tensorflow/stream_executor/dso_loader.cc:108] successfully opened
       CUDA library libcufft.so locally I
       tensorflow/stream_executor/dso_loader.cc:108] successfully opened
       CUDA library libcuda.so locally I
       tensorflow/stream_executor/dso_loader.cc:108] successfully opened
       CUDA library libcurand.so locally
       /home/waffle/anaconda3/lib/python3.5/site-packages/tensorflow/python/ops/array_ops.py:1197:
       VisibleDeprecationWarning: converting an array with ndim > 0 to an
       index will result in an error in the future
       result_shape.insert(dim, 1) I
       tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:924] successful
       NUMA node read from SysFS had negative value (-1), but there must be
       at least one NUMA node, so returning NUMA node zero I
       tensorflow/core/common_runtime/gpu/gpu_init.cc:102] Found device 0
       with properties:  name: GeForce GTX 660 major: 3 minor: 0
       memoryClockRate (GHz) 1.0975 pciBusID 0000:01:00.0 Total memory:
       2.00GiB Free memory: 1.78GiB I tensorflow/core/common_runtime/gpu/gpu_init.cc:126] DMA: 0  I
       tensorflow/core/common_runtime/gpu/gpu_init.cc:136] 0:   Y  I
       tensorflow/core/common_runtime/gpu/gpu_device.cc:806] Creating
       TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GTX 660, pci
       bus id: 0000:01:00.0) W tensorflow/core/framework/op_def_util.cc:332]
       Op BatchNormWithGlobalNormalization is deprecated. It will cease to
       work in GraphDef version 9. Use tf.nn.batch_normalization(). E
       tensorflow/core/common_runtime/executor.cc:334] Executor failed to
       create kernel. Invalid argument: NodeDef mentions attr 'T' not in
       Op<name=MaxPool; signature=input:float -> output:float;
       attr=ksize:list(int),min=4; attr=strides:list(int),min=4;
       attr=padding:string,allowed=["SAME", "VALID"];
       attr=data_format:string,default="NHWC",allowed=["NHWC", "NCHW"]>;
       NodeDef: pool = MaxPool[T=DT_FLOAT, data_format="NHWC", ksize=[1, 3,
       3, 1], padding="VALID", strides=[1, 2, 2, 1],
       _device="/job:localhost/replica:0/task:0/gpu:0"](pool/control_dependency)
         [[Node: pool = MaxPool[T=DT_FLOAT, data_format="NHWC", ksize=[1, 3,
       3, 1], padding="VALID", strides=[1, 2, 2, 1],
       _device="/job:localhost/replica:0/task:0/gpu:0"](pool/control_dependency)]]
       Traceback (most recent call last):   File
       "/home/waffle/anaconda3/lib/python3.5/site-packages/tensorflow/python/client/session.py",
       line 715, in _do_call
           return fn(*args)   File "/home/waffle/anaconda3/lib/python3.5/site-packages/tensorflow/python/client/session.py",
       line 697, in _run_fn
           status, run_metadata)   File "/home/waffle/anaconda3/lib/python3.5/contextlib.py", line 66, in
       __exit__
           next(self.gen)   File "/home/waffle/anaconda3/lib/python3.5/site-packages/tensorflow/python/framework/errors.py",
       line 450, in raise_exception_on_not_ok_status
           pywrap_tensorflow.TF_GetCode(status)) tensorflow.python.framework.errors.InvalidArgumentError: NodeDef
       mentions attr 'T' not in Op<name=MaxPool; signature=input:float ->
       output:float; attr=ksize:list(int),min=4;
       attr=strides:list(int),min=4; attr=padding:string,allowed=["SAME",
       "VALID"]; attr=data_format:string,default="NHWC",allowed=["NHWC",
       "NCHW"]>; NodeDef: pool = MaxPool[T=DT_FLOAT, data_format="NHWC",
       ksize=[1, 3, 3, 1], padding="VALID", strides=[1, 2, 2, 1],
       _device="/job:localhost/replica:0/task:0/gpu:0"](pool/control_dependency)
         [[Node: pool = MaxPool[T=DT_FLOAT, data_format="NHWC", ksize=[1, 3,
       3, 1], padding="VALID", strides=[1, 2, 2, 1],
       _device="/job:localhost/replica:0/task:0/gpu:0"](pool/control_dependency)]]

       During handling of the above exception, another exception occurred:

       Traceback (most recent call last):   File "tensorflowMassPred.py",
       line 116, in <module>
           run_inference_on_image()   File "tensorflowMassPred.py", line 98, in run_inference_on_image
           {'DecodeJpeg/contents:0': image_data})   File "/home/waffle/anaconda3/lib/python3.5/site-packages/tensorflow/python/client/session.py",
       line 372, in run
           run_metadata_ptr)   File "/home/waffle/anaconda3/lib/python3.5/site-packages/tensorflow/python/client/session.py",
       line 636, in _run
           feed_dict_string, options, run_metadata)   File "/home/waffle/anaconda3/lib/python3.5/site-packages/tensorflow/python/client/session.py",
       line 708, in _do_run
           target_list, options, run_metadata)   File "/home/waffle/anaconda3/lib/python3.5/site-packages/tensorflow/python/client/session.py",
       line 728, in _do_call
           raise type(e)(node_def, op, message) tensorflow.python.framework.errors.InvalidArgumentError: NodeDef
       mentions attr 'T' not in Op<name=MaxPool; signature=input:float ->
       output:float; attr=ksize:list(int),min=4;
       attr=strides:list(int),min=4; attr=padding:string,allowed=["SAME",
       "VALID"]; attr=data_format:string,default="NHWC",allowed=["NHWC",
       "NCHW"]>; NodeDef: pool = MaxPool[T=DT_FLOAT, data_format="NHWC",
       ksize=[1, 3, 3, 1], padding="VALID", strides=[1, 2, 2, 1],
       _device="/job:localhost/replica:0/task:0/gpu:0"](pool/control_dependency)
         [[Node: pool = MaxPool[T=DT_FLOAT, data_format="NHWC", ksize=[1, 3,
       3, 1], padding="VALID", strides=[1, 2, 2, 1],
       _device="/job:localhost/replica:0/task:0/gpu:0"](pool/control_dependency)]]
       Caused by op 'pool', defined at:   File "tensorflowMassPred.py", line
       116, in <module>
           run_inference_on_image()   File "tensorflowMassPred.py", line 87, in run_inference_on_image
           create_graph()   File "tensorflowMassPred.py", line 68, in create_graph
           _ = tf.import_graph_def(graph_def, name='')   File "/home/waffle/anaconda3/lib/python3.5/site-packages/tensorflow/python/framework/importer.py",
       line 274, in import_graph_def
           op_def=op_def)   File "/home/waffle/anaconda3/lib/python3.5/site-packages/tensorflow/python/framework/ops.py",
       line 2260, in create_op
           original_op=self._default_original_op, op_def=op_def)   File "/home/waffle/anaconda3/lib/python3.5/site-packages/tensorflow/python/framework/ops.py",
       line 1230, in __init__
           self._traceback = _extract_stack()

This is the script: some functions are removed.
import os
import numpy as np
import tensorflow as tf
os.chdir('tensorflow/') #if need to run in the tensorflow directory
import csv,os
import pandas as pd
import glob

imagePath = '../_images_processed/test'
modelFullPath = '/tmp/output_graph.pb'
labelsFullPath = '/tmp/output_labels.txt'

# FILE NAME TO SAVE TO.
SAVE_TO_CSV = 'tensorflowPred.csv'

def makeCSV():
    global SAVE_TO_CSV
    with open(SAVE_TO_CSV,'w') as f:
        writer = csv.writer(f)
        writer.writerow(['id','label'])

def makeUniqueDic():
    global SAVE_TO_CSV
    df = pd.read_csv(SAVE_TO_CSV)
    doneID = df['id']
    unique = doneID.unique()
    uniqueDic = {str(key):'' for key in unique} #for faster lookup
    return uniqueDic

def create_graph():
    """Creates a graph from saved GraphDef file and returns a saver."""
    # Creates graph from saved graph_def.pb.
    with tf.gfile.FastGFile(modelFullPath, 'rb') as f:
        graph_def = tf.GraphDef()
        graph_def.ParseFromString(f.read())
        _ = tf.import_graph_def(graph_def, name='')

def run_inference_on_image():
    answer = []
    global imagePath
    if not tf.gfile.IsDirectory(imagePath):
        tf.logging.fatal('imagePath directory does not exist %s', imagePath)
        return answer

    if not os.path.exists(SAVE_TO_CSV):
        makeCSV()

    files = glob.glob(imagePath+'/*.jpg')
    uniqueDic = makeUniqueDic()
    # Get a list of all files in imagePath directory
    #image_list = tf.gfile.ListDirectory(imagePath)

    # Creates graph from saved GraphDef.
    create_graph()

    with tf.Session() as sess:

        softmax_tensor = sess.graph.get_tensor_by_name('final_result:0')

        for pic in files:
            name = getNamePicture(pic)
            if name not in uniqueDic:
                image_data = tf.gfile.FastGFile(pic, 'rb').read()
                predictions = sess.run(softmax_tensor,
                                   {'DecodeJpeg/contents:0': image_data})
                predictions = np.squeeze(predictions)

                top_k = predictions.argsort()[-5:][::-1]  # Getting top 5 predictions
                f = open(labelsFullPath, 'rb')
                lines = f.readlines()
                labels = [str(w).replace("\n", "") for w in lines]
#            for node_id in top_k:
#                human_string = labels[node_id]
#                score = predictions[node_id]
#                print('%s (score = %.5f)' % (human_string, score))
                pred = labels[top_k[0]]
                with open(SAVE_TO_CSV,'a') as f:
                    writer = csv.writer(f)
                    writer.writerow([name,pred])
    return answer

if __name__ == '__main__':
    run_inference_on_image()

Answer: The raw jpeg data seems to be fed directly to a decode_jpeg operation, which only takes a single image as input at a time. In order to process more than one image at a time you would probably need to define more decode_jpeg ops. If it is possible to do that then I don't currently know how.
The next best thing, which is easy, is probably to classify all the images one by one inside with a loop the TensorFlow session. This way you will at least avoid reloading the graph and starting a new TF session for every image that you want to classify, both of which can take quite a bit of time if you have to do it a lot.
Here I have changed the definition of the run_inference_on_image() function so it should classify all images in the directory that is specified by the imagePath variable. I have not tested this code, so there may be minor problems that need to be fixed.
def run_inference_on_image():
    answer = []

    if not tf.gfile.IsDirectory(imagePath):
        tf.logging.fatal('imagePath directory does not exist %s', imagePath)
        return answer

    # Get a list of all files in imagePath directory
    image_list = tf.gfile.ListDirectory(imagePath)

    # Creates graph from saved GraphDef.
    create_graph()

    with tf.Session() as sess:

        softmax_tensor = sess.graph.get_tensor_by_name('final_result:0')

        for i in image_list:
            image_data = tf.gfile.FastGFile(i, 'rb').read()
            predictions = sess.run(softmax_tensor,
                                   {'DecodeJpeg/contents:0': image_data})
            predictions = np.squeeze(predictions)

            top_k = predictions.argsort()[-5:][::-1]  # Getting top 5 predictions
            f = open(labelsFullPath, 'rb')
            lines = f.readlines()
            labels = [str(w).replace("\n", "") for w in lines]
            for node_id in top_k:
                human_string = labels[node_id]
                score = predictions[node_id]
                print('%s (score = %.5f)' % (human_string, score))

            answer.append(labels[top_k[0]])
    return answer

Comment: Hi, Thanks so much for your reply - I got several problems running this script, i've updated my answer. It would be great if you could help again! :)
Comment: @Wboy There's a [TensorFlow issue](https://github.com/tensorflow/tensorflow/issues/1528) that seems related to your new problem.
Comment: Haven't solved it yet, but I'll award you the bounty before it ends :)
Answer: So looking at your linked script:
with tf.Session() as sess:

    softmax_tensor = sess.graph.get_tensor_by_name('final_result:0')
    predictions = sess.run(softmax_tensor,
                           {'DecodeJpeg/contents:0': image_data})
    predictions = np.squeeze(predictions)

    top_k = predictions.argsort()[-5:][::-1] # Getting top 5 predictions

Within this snippet, image_data is the new image that you want to feed to the model, that's loaded a few lines previously:
image_data = tf.gfile.FastGFile(imagePath, 'rb').read()

So my instinct would be to change the run_inference_on_image to accept imagePath as a parameter, and use os.listdir and os.path.join to do that on each image in your dataset.
Comment: Hi, thanks for your reply! I'm sorry, I dont understand what you mean. Are you saying to load all the pics, then loop sess.run()?
Comment: Unfortunately, that is not what I'm looking for. Its akin to fitting rows one by one in a normal classifier (like xgboost) and is incredibly slow (takes 31 hours for 8k images). I'm looking for a solution that feeds the entire X images into feed_dict and into the classifier, and outputs predictions for all the images at one shot.
Comment: [OK, reading the code which actually constructs the inference portion of the graph](https://github.com/tensorflow/models/blob/master/inception/inception/slim/inception_model.py), you've got a tensor `_inputs`, which should be of size `[batch_size, height, width, channels]`. The next thing I'd try is [reading the JPEG](http://stackoverflow.com/questions/34484148/feeding-image-data-in-tensorflow-for-transfer-learning), into such a 4D array, and then substituting `_inputs:0` for `DecodeJpeg/contents:0` in the `sess.run` invocation.
Comment: `ResizeBilinear:0` may also be useful.
Answer: I had the same issues. I followed all the possible solutions and finally found one that worked for me. This error occurs when the version of Tensorflow used to re-train the model is different  from the one where it is being used.
The solution is to update Tensorflow to the latest version. Since I had used  pip to install Tensorflow, I only had to run the following command :
sudo pip install tensorflow --upgrade

And it worked perfectly.


Como realizar comparação segura de 2 Hashes em Node.js?

Question: Estou estudando sobre timing attack e encontrei essa pergunta relacionada ao tema, e identifiquei o problema que comparação de string hash pode provocar nesse tipo de ataque.
O problema é que temos microsserviços que são APIs fechadas para uso por outras APIs internas, como se fosse um Back-end for Back-end e para que essas APIs internas sejam consumidas, algumas restrições são feitas. Uma delas é a verificação de uma chave de API que fica em um header x-api-key, onde a verificação é feita por um middleware com um código semelhante a esse:
function checkApiKey(req, res, next) {
  const { 'x-api-key': apiKey } = req.headers

  if(apiKey !== process.env.API_KEY) {
    throw new InvalidApiKey();
  }
  ...

  return next()
}

O código acima não é muito seguro com essa comparação !==. Eu esperava o uso de alguma biblioteca para realizar essa comparação, mas pelo visto o desenvolvedor que fez o código não conhece sobre o problema de TA. Na verdade, os sistemas usam algumas soluções duvidosas e bem questionáveis.
As chaves de APIs podem ser no formato semelhante à essa:

89JhP8rekXxwJMEr9khQuVKAVrdKaOfp2jCc5hV54BAbAHoeujAGvjGxTZkdBSnMXpHzijl8SC8WNLgoeWKATM3STe5Se9IM22NmerIPlcp71zwfX7O112OkY0K2T3dz

Dito isto, sabendo que eu preciso de uma solução que resulte em tempo constante de operação, como eu resolveria essa comparação de forma segura em Node.js?
Uma das respostas menciona a função hash_compare para comparação de hashes. Qual seria a equivalente em Node.js?
Answer: A biblioteca nativa crypto
Com crypto, podemos realizar comparações seguras de hashes. Ela possui uma função chamada timingSafeEqual (acho que o nome já explica tudo).
Vamos com um exemplo:
const crypto = require('crypto');

// criamos 2 hashes aleatorios
const hash1 = crypto.createHash('sha256').update('hash1').digest();
const hash2 = crypto.createHash('sha256').update('hash2').digest();

// aqui é feita a comparacao segura
const result = crypto.timingSafeEqual(hash1, hash2);

if (result) {
  console.log('As hashes são iguais');
} else {
  console.log('As hashes são diferentes');
}

Porém, por mais que essa solução resolva o problema, ela tem alguns detalhes importantes. timingSafeEqual recebe apenas Buffers de mesmo tamanho como parâmetros, ou seja, para o código mencionado na pergunta funcionar, apiKey e process.env.API_KEY precisam ser convertidos em Buffers.
Veja o código atualizado:
const crypto = require('crypto');

function checkApiKey(req, res, next) {
  const { 'x-api-key': apiKey } = req.headers;

  const apiKeyBuffer = Buffer.from(apiKey, 'utf8');
  const envApiKeyBuffer = Buffer.from(process.env.API_KEY, 'utf8');

  if (!crypto.timingSafeEqual(apiKeyBuffer, envApiKeyBuffer)) {
    throw new InvalidApiKey();
  }
  ...
  return next();
}

Nesta solução acima, considero que já foi feita uma validação prévia do tamanho das strings e que ambas sejam de tamanho igual, antes de converter para Buffers. Caso contrário, timingSafeEqual irá lançar um erro. Isso pode ser facilmente adicionando um if anterior que compara o tamanho das strings.
Bibliotecas do NPM
Caso você uma solução mais simples, existem alguns pacotes do NPM para alcançar o mesmos objetivo. Elas já resolvem problemas como ter que garantir strings com possíveis tamanhos diferentes e conversões para Buffer.
tsse
Isso difere de crypto.timingSafeEqual porque ele:

suporta tanto strings quanto Buffers;
suporta entradas de tamanhos diferentes.

const tsse = require('tsse');

const hash      = '0a4d55a8d778e5022fab701977c5d840bbc486d0';
const givenHash = '1265a5eb08997ced279d3854629cba68a378b528';

if (tsse(hash, givenHash)) {
  console.log('good hash');
} else {
  console.log('bad hash');
}
// => bad hash

safe-compare
Idem, mas sem updates já tem 4 anos.
var safeCompare = require('safe-compare');

safeCompare('hello world', 'hello world'); // -> true

safeCompare('hello', 'not hello'); // -> false
safeCompare('hello foo', 'hello bar'); // -> false


part of the image

Question: using the canvas tag in HTML5, you can load a small area of a large image? and have very low load times?
Why would I want to make a play, with a few tiles but rather large, so you have a few loops (for).
I'd like to redraw only a specific area when you animate a character for example, minimizing the time.
Answer: context.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)
s = source, d = destination.

source https://developer.mozilla.org/en/Canvas_tutorial/Using_images#drawImage_example_3
But you cannot improve load time you will have to load it before you can crop it !
Good luck

part of the image


Why does maximum likelihood estimation have issues with over fitting?

Question: I came across this in lecture but failed to understand why:

Why does maximum likelihood estimation have issues with over fitting? Given data X and you want to estimate parameter theta.

An example would be helpful.
Comment: http://stats.stackexchange.com/questions/82664/bayesian-vs-mle-overfitting-problem
Comment: While it is true that this question is somewhat underspecified &/or overly broad, the existence of a good & upvoted answer establishes that it is not too unclear to be answerable. I'm voting to leave open.
Comment: A common failure case of MLE is when the model is "too flexible" relative to the amount of data given, e.g., fitting a 3-component Gaussian mixture to two data points, or fitting a Bernoulli to a single coin toss. Collecting more data *may* fix this issue, but won't help when there is severe model misspecification (so MLE isn't even defined), e.g., when the data lies on a low-dimensional subset of $\mathbb{R}^d$ yet we insist on fitting a density model that has support  over all of $\mathbb{R}^d$. Here are more [details](https://yiboyang.com/files/ill_defined_mle.pdf) if you're interested.
Answer: Maximum likelihood does not tell us much, besides that our estimate is the best one we can give based on the data. It does not tell us anything about the quality of the estimate, nor about how well we can actually predict anything from the estimates.
Overfitting means, we are estimating some parameters, which only help us very little for actual prediction. There is nothing in maximum likelihood that helps us estimate how well we predict. Actually, it is possible to increase the likelihood beyond any bound, without increasing predictive accuracy at all.
To illustrate the last point about increasing likelihood without increasing predictive quality, let me give an example. Let's assume we want to predict the number of car crashes in the USA on a given day. As a predictor we only have the number of rocks analyzed by the curiosity rover on mars. Now, it seems highly unlikely that the predictor has any relation to the number of car crashes, but we can still generate a maximum likelihood model using that predictor. Maximum likelihood only tells us, it is the best we can do given the current dataset, even though this "best we can do" may still be total garbage. Since there is no relationship between the predictor and the number to be predicted, we cannot do anything except to overfit.
Now let's take this a bit further, and assume we want to further increase our maximum likelihood. We add the average distance of the planet Jupiter on that day as another predictor. Again this carries no predictive value. But our maximum likelihood for the model will increase. It cannot decrease, since we are still including the original predictor, so the model that just ignores the distance of Jupiter is a possible model, and this has the exact same likelihood as the previous model. So we are increasing likelihood without adding predictive value, i.e., we are overfitting.
Let's further assume somebody provides a model that is estimating the number of car crashes based on some reasonable predictors (number of cars driven on that day, whether the day is a holiday / weekend / weekday, etc.) and that model gives us a likelihood of $L$. Now we can carry our "astrological" model by just adding arbitrary figures derived from constellations of stars and planet. If we just add enough constellations, we can get our "astrological" model to have a maximum likelihood $L' > L$. Does that mean we should discard the well reasoned model and use the astrological one instead? Of course not.
This should show that overfitting is always present, unless we introduce some method to guard against overfitting.
Comment: I really like your answer, but I miss how overfitting influences the **external** validity of prediction models. What I mean to say is, is that overfitting (due to finding maximum likelihood, as you explained), provides parameter estimates which are based on your data alone. As you never know whether you might have an 'unlucky' sample of associations between (true or false) predictors and outcome, you probably overestimated/overfit the coefficients in your model. This is why shrinkage methods (which combat extreme parameters) are often used to guard models against overfitting.
Comment: @IWS Yes, you are correct, I tried to include that in there at first, but then felt that it would complicate the simple explanation. As there are multiple causes for overfitting (e.g. your predictors may be meaningless/noisy, your sample may bad, or your model may tend to generalize badly) that all contribute to low predictive value, I find it hard to include all possible causes in a single explanation. Therefore, I decided to give an explanation based only on one of these causes. If you have some idea on how to integrate the others without overly complicating the issue just go ahead and edit.
Comment: Don't you mean $L' > L$ ?
Answer: Some models are just too flexible: In these cases, maximum likelihood estimators can effectively "memorize" the data---signal and noise. Such considerations motivate reducing the flexibility of some models, through, for instance, some kind of regularization.
Answer: In my opinion, the reason of overfitting caused by the use of maximum likelihood method is that the values of parameters are estimated in the light of current data. You should derive the values of parameters in the light of future data instead of current data. If you are interested in this idea, please refer to the paper below.
Takezawa, K. (2012): "A Revision of AIC for Normal Error Models," Open Journal of Statistics, Vol. 2 No. 3, 2012, pp. 309-312. doi: 10.4236/ojs.2012.23038. http://www.scirp.org/journal/PaperInformation.aspx?paperID=20651
Comment: Unfortunately you failed to mention that the paper you are linking to is your own...


How to use Rules to send an E-mail after saving a new comment, to users who checked a boolean in their profile?

Question: What I try to achieve with Rules:
After saving a new comment, this comment has to be sent only to those users who've checked a corresponding boolean box on their profile page.
Any suggestions?
Answer: Assuming your question is about D7, there are basically 2 ways (options) to answer your question, as further detailed below.
Option 1: Use Rules and Views Bulk Operations
You could create a view (using the Views module) of those users that you want to send an eMail to.
After you succeeded in creating such view, you can process the results of a VBO enabled view via Rules, using a rule that looks like so:

Rules Event: After saving a new comment.
Rules Actions:

Load the VBO list of the users in your View.
Add a loop to perform a Rules Action "Send an eMail", for each user contained in your Views results.

For more details, have a look at the tutorial "How to process the results of a VBO enabled view via Rules?".
Option 2: Use Rules and Views Rules
a) About this module
The Views Rules module makes Views data available in Rules, enabling intuitive rule configuration for dynamic data. Some details from its project page:

... provides two types of elements in Rules, configured with a "Rules" view display:

Views loop: A views loop is similar to a regular Rules loop, but allows looping over rows of view results.

Collect view result rows (action): This action collects each variable in all view result rows into list variables for use in Rules.

Tip: When selecting the data type for variables in the view, if the field is an entity identifier (e.g. Node ID), you can set the data type to the entity type (i.e. Node) to directly use the variable in Rules as an entity!

b) Create a view of display type 'Rules'
After you enable the Views Rules module, you can use Views to create a view of those users that you want to send an eMail to. Add of view of display type Rules (important, that's the key to make it work!). Here is how you can add such display:

Next configure the row variables, by using the link that says "edit field info", as shown here:

You probably want to use one or more of the variables similar to those that are shown in this screenprint:

c) Create a rule using the view of display type 'Rules'
Create a rule that looks like so:

Rules Event: After saving a new comment.
Rules Actions:

Use the link that says Add view loop to add a Views loop, and select the "Rules" display created in the previous step.
Configure the parameters and variable names.
For each user contained in your Views loop, perform a Rules Action "Send an eMail", using the variables you configured at the end of the previous step (you may have to revisit the previous step to add more similar variables there if needed). If you created the Rules row variables as suggested in the previous step, your actual eMail can use tokens such as [usermail:value], [username:value], etc.


ASP.NET ProfileBase.Create behavior when supplied with an existing username

Question: When supplied with a username that already exists, does ProfileBase.Create return the ProfileBase associated with the existing user (and if the username does not exisit, creates a new user and returns the new user)?
Apologies for the trivial question, but MSDN documentation really is of little help.
Answer: Here's the code for ProfileBase.Create():
public static ProfileBase Create(string username, bool isAuthenticated)
{
    if (!ProfileManager.Enabled)
    {
        throw new ProviderException(SR.GetString("Profile_not_enabled"));
    }
    InitializeStatic();
    if (s_SingletonInstance != null)
    {
        return s_SingletonInstance;
    }
    if (s_Properties.Count == 0)
    {
        lock (s_InitializeLock)
        {
            if (s_SingletonInstance == null)
            {
                s_SingletonInstance = new DefaultProfile();
            }
            return s_SingletonInstance;
        }
    }
    HttpRuntime.CheckAspNetHostingPermission(AspNetHostingPermissionLevel.Low, "Feature_not_supported_at_this_level");
    return CreateMyInstance(username, isAuthenticated);
}

private static ProfileBase CreateMyInstance(string username, bool isAuthenticated)
{
    Type profileType;
    if (HostingEnvironment.IsHosted)
    {
        profileType = BuildManager.GetProfileType();
    }
    else
    {
        profileType = InheritsFromType;
    }
    ProfileBase base2 = (ProfileBase) Activator.CreateInstance(profileType);
    base2.Initialize(username, isAuthenticated);
    return base2;
}

Looks like it always returns a new instance of ProfileBase.
Comment: Thanks - this is very useful. What were the steps you went through to get this code?
Answer: As I thought, the Create method actually retrieves the profile. Who designs these APIs?!
See also here.
Comment: I completely agree that while the Membership & Roles providers are great, the Profile part has been poorly designed.


How to get current route in the midst of a Views AJAX request

Question: I need to conditionally pass contextual filter values to a view based on the current route and am attempting to do so in hook_views_pre_view. This is the result of using AJAX via views_infinite_scroll and losing the contextual filters that I initially pass in programmatically.
On the initial request, the following works great for getting the current route in hook_views_pre_view:
<code>$current_route_match = \Drupal::getContainer()->get('current_route_match');
$current_route_match->getRouteName();
</code>
However, when I hit the 'Load more' button supplied by views_infinite_scroll, the route name of the current route match is 'views.ajax'. While I understand that this is technically the request's route, I need to know the original route, or from where the request was made.
After digging around, I noticed that $_SERVER['HTTP_REFERER'] had the right path, but the documentation says:

Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.
Comment: False alarm. While accessing the "original route" in the midst of an AJAX request would be helpful, I discovered that my problem was actually a misunderstanding of Views. I have two contextual filters for a view and was passing in `false` as the first in an effort to not filter by any value. For some reason this worked on the initial page request but ended up evaluating to `null` on the subsequent AJAX requests, being ignored completely. This bug caused me to think that contextual filters  - applied programmatically - did not persist through multiple requests. Luckily I was wrong :)
Answer: <code>use Symfony\Component\HttpFoundation\Request;

if (\Drupal::routeMatch()->getRouteName() == 'views.ajax') {
    $previousUrl = \Drupal::request()->server->get('HTTP_REFERER');
    $fake_request = Request::create($previousUrl);
    $url_object = \Drupal::service('path.validator')->getUrlIfValid($fake_request->getRequestUri());
    if ($url_object) {
      $route_name = $url_object->getRouteName();
      // Do something with $route_name;
    }
  }
</code>
Comment: `$previousUrl` can be null, e.g. when is the first page visited by the user. With PHP 8.1+ it causes the warming `Deprecated function: parse_url(): Passing null to parameter #1 ($url) of type string is deprecated`. It may be better to add a check on the existence of `$previousUrl`


Is this 3/4 at 270 BPM or 6/8 at 90 BPM?

Question: So im composing a song called "Consonant Dissonance II" (You can listen to the first one), and I hear it as 270 BPM 3/4 but I dont know if it is correct to notate it as that. (Sorry if the question is too short but I dont really know how to extend it)
Here is a link to the current progress (unlisted): https://musescore.com/user/36283528/scores/6829608/s/z4nUs4?share=copy_link
EDIT: I finished the song! (https://musescore.com/anything/consonant-dissonance-2)
Answer: Even though you already accepted an answer I'd like to add there is no right or wrong way to notate this as long as you get the desired result when the music is being read. It is your piece so you decide how you feel it and what the meter should be. I believe you made the right call in writing it in 3/4 time, it seems like a frantic waltz to me and 3/4 time fits that, the bass notes feel like downbeats to me.
Comment: I agree, it depends on which beats you'd like to be strong vs weak; but, is it practical to count eighth notes at 270 BPM? (This is an honest question)
Comment: @Giovanni Regardless of whether the piece is written in 3/4 or 12/8 the notes have to be executed at that velocity. The fact that the bars and tempo are slower in 12/8 doesn't make it easier. There is no need to count eighth notes, on the contrary, when a piece in 3/4 is this fast it can be felt, counted and conducted (if necessary) in "1", one pulse per measure. I have done this many times when playing in ensembles for musical theater for example, a genre that often has very fast waltzes.


A simple distribution problem

Question: Suppose that $x \sim U(0, 255)$ and and $y \sim U(0, 255)$, and that $x$ and $y$ are independent.
What is the distribution of $x - y$?
If I were to draw 1,000 samples from this distribution, how many times should I expect to see each possible value?
NB. These are all discrete random variables, in case that wasn't clear...

Update:
I've written a computer program to work out the expected count for each difference value. However, when I ask the computer to sum them all, it doesn't add up to 1,000. Clearly I've done something wrong somewhere, but I'm not sure precisely what. I'm probably just being dumb; if somebody could walk me through this slowly, it would be helpful.
The reason I'm doing this is that I want to do a chi-squared test to see if the data I'm getting actually does follow the expected distribution. Clearly this doesn't work if you calculate your expectations wrong. (!)
In addition, I think I may have over-simplified the program description. What my program actually does is obtain $x_1 \ldots x_{1000}$, and then compute $d_n = x_{n+1} - x_n$. Would that mean that the $d$ values are not statistically independent? If so, presumably a chi-squared test won't work at all. (I suppose I could throw away all the even-numbered $d_n$ so I'm left with non-overlapping pairs...)
Comment: Assuming that $X$ and $Y$ are independent discrete random variable equally likely to take on any of the $256$ numerical values $\{0, 1, 2, \ldots, 255\}$ (which is **not** the same as your $\sim U(0,255)$ but matches your comment), then $$P\{X-Y = 17\} = \sum_{i=17}^{255}P\{X=i,Y=i-17\}=\sum_{i=17}^{255}P\{X=i\}\{Y=i-17\}\\=\sum_{i=17}^{255}\left(\frac{1}{256}\right)\times \left(\frac{1}{256}\right)$$
Comment: One way to think of it is as $x+(-y).$ Then you can view it as the sum of two uniform random variables, which is triangular.
Comment: @soakley So, a triangular distribution with a peak at $0$, minimum of $-255$ and maximum of $+255$. (?) How would I compute the actual probability for, say, $x-y = 17$?
Comment: How many ways can $x=y+17$ ? What is the probability of each outcome?
Answer: For a uniform, distribution, the distribution of the difference is a triangle centered on zero and falling to zero at +/- 2*255, the height given by requiring normalizing to 1.
You're problem is using integers so this isn't exact. The exact value is given by the convolution of the two distributions. The distribution is just the number of possible values from both distribution whose difference is that value (and normalized to 1).
Answer: Following the comments from Dilip Sarwate, I was able to get the expected outcomes to sum to 1,000.
My mistake was in assuming that I only need to count how many ways you can make (for example) 17, not the probability of each of those ways.
What I eventually came up with is
\begin{equation}
  \Pr(d = v) = \frac{256 - v}{256\times256}
\end{equation}
and therefore the expected count for $d=v$ is the above probability multiplied by the number of items in the sample.
This just leaves open the question of whether it's appropriate to use a chi-squared test on the differences of overlapping pairs in the first place...
Comment: You need to rethink this. What about, for example, $v=-255$?
Comment: What's the probl... oh, wait, it's $256 - |v|$. Sorry, my bad. I missed that out when I converted source code into mathematics.

A simple distribution problem


Abrir como administrador apenas na primeira vez em Delphi.

Question: Coloquei um método em meu sistema para alterar o registro fazendo com que ele inicie junto com o windows, para isso é necessário que o executável seja executado em modo de administrador. O problema é que toda vez que o sistema inicia, a aplicação abre e mostra a mensagem perguntando se o usuário deseja iniciar como administrador, o que me parece algo chato.
A pergunta que faço é: Existe como abrir a aplicação em modo de administrador apenas na primeira vez? ou talvez verificar se existe o registro no windows e se sim executar em modo normal?
Comment: Esse tipo de alteração não costuma ser bem vista. Sugiro que você verifique no seu sistema se a aplicação foi aberta como administrador, e caso não tenha sido, exibir uma mensagem alertando o usuário de que determinada função não será executada por causa dos privilégios, e solicitar que da próxima vez execute a aplicação como administrador.
Comment: Isso mesmo que fiz Victor. Acho que não tem como fazer de outra forma.
Comment: http://chapmanworld.com/2015/06/08/elevated-privileges-for-delphi-applications/
Comment: Você pode fazer com que a aplicação tente se re-executar com o perfil do administrador, e caso o usuário aceite, encerre a versão "não administrativa'. Uma vez que a aplicação esteja configurada como deseja, basta não chamar esta função de elevação. É uma solução elegante, pois só vai "incomodar" o usuário com o UAC até que ele aceite (e no caso de uma recusa, pode oferecer uma opção de não insistir, ou de lembrar de novo em N dias)
Comment: E nesse caso, você não ponha a opção no manifest. Tem que executar em runtime.
Answer: Em project options/Application na seção Manifest File, marque a opção:
Enable Administrator Privileges que deve resolver.
Comment: Ele quer abrir elevado apenas na primeira execução. Isso não vai resolver.
Answer: Não é possível abrir a aplicação com privilégios apenas na primeira vez se ela já carrega o manifest para abrir elevada. Também não interessante você iniciar a aplicação elevada e depois executar ela sem privilégios.
Talvez fosse melhor fazer o seguinte:

Fazer a configuração na instalação de sua aplicação.
Durante a execução validar se a aplicação está na inicialização e, caso negativo, avise ao usuário. Daí execute um outro processo/aplicativo para fazer essa configuração.
Comment: Melhor resposta! Apenas para complementar, você também pode usar a chave HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run ao invés da HKEY_LOCAL_MACHINE, assim não precisa de privilégios elevados. O único detalhe é que será válido apenas para a conta de usuário onde o programa estiver rodando. Boa sorte!
Answer: Como o uso vai ser ocasional, você pode implementar uma função em C para chamar pelo Delphi só quando necessitar da elevação:
#include "windows.h"

SHELLEXECUTEINFO lpExecInfo;
memset(&lpExecInfo, 0, sizeof(SHELLEXECUTEINFO));

lpExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
lpExecInfo.lpFile = // aqui vai o nome do executável (no caso, o próprio aplicativo);
lpExecInfo.lpDirectory = // aqui vai o caminho no qual ele deve ser executado;
lpExecInfo.lpVerb = "runas";
lpExecInfo.lpParameters = "runasadmin";
lpExecInfo.nShow = SW_NORMAL;
lpExecInfo.fMask = 0;
lpExecInfo.hwnd = NULL;

ShellExecuteEx(&lpExecInfo); // retorna verdadeiro se o usuário aceitou

Neste caso, você não especifica no manifest que precisa de privilégios administrativos, e só chama a função acima no caso de precisar fazer algo como admin.
Se o resultado do ShellExecuteEx for verdadeiro, pode encerrar a instância atual, pois o usuário aceitou o UAC e já está rodando uma versão admin em paralelo.


Is it possible to add an Ajax action on a button define in a twig view template?

Question: I have a view for which I customized the views-view-field...html.twig template. On each row, I added a first button A which opens a modal with two buttons: Button B to confirm the action and Button C to cancel the action.
When the users click on Button B, I would like to programmatically create new content and close the modal. I imagine I should use AJAX.
How can I implement this?
Answer: So i found the solution using webform module


How do I resolve the config error which states a machine to application error

Question: I imported a website made in visual studio express 2008 to visual studio express 2010.  When I run the home page I get the following error:
"It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level.  This error can be caused by a virtual directory not being configured as an application in IIS."
When I looked up the meaning of this on Google I read their needed to be a change to the configuration of the virtual directory.  Another suggestion was to change the web config files .  T
Were these suggestions correct? If so how do I emplement them so that I can view these website pages on my local machine.
Answer: To try the first suggestion:
Right-Click MY_COMPUTER, choose MANAGE.
Expand the SERVICES (then IIS) section(s) in the left-hand pane until you can see the directory containing the "home page"
Right-Click that folder and Choose PROPERTIES.
Click the "Create Application" button.
================================  EDIT ADDED after I realized I could edit an answer
No, you can't create an app using the WINDOWS EXPLORER...
So... here's a more descriptive instruction:
Once you've expanded "Services and Apps" the left hand pane should contain (at least) "Services", Indexing Service, and "Internet Information Services."
Click the "+" to the left of "Internet Information Services" and that action should expose (at least) "Web Sites", Again click the "+" to expose (at least) "Default Web Site."
Once more click the "+" to the left of Default, to expose the Virtual Directories.
Hopefully you will find the FOLDER in question (containing your 'Home Page'). Right-click it, choose PROPERTIES, and see the "Create Application" on the "Directory" tab of the window that pops up.
////////////////////////////////\
If You Do Not See your folder in that final list, it is because there is no virtual directory pointing to the My Documents folder that contains your web site (and home page.)
To create a virtual directory, right-click on that DEFAULT WEB SITE (now visible in the left hand pane) Click "New.." and choose "Virtual Directory." Follow the directions offered in the popup window ... i.e. Browse to your folder, etc.
Too bad StackOverflow does not offer the ability for me to add pictures.
If you still have trouble, I can create a set of screen shots for you and put a link to it in another response.
Comment: Tobrien, thanks for replying to my question.
When I click Services and Applications the Internet Information Server is there and on the right-hand content pane there is a list of different things about IIS, however I see nothing about directories or file paths to select the home page. Since I did not see this folder structure I went back to my documents where the folder is located,right clicked and selected properties but there was no option to select "Create Application".
Answer: Did the directory tree get jacked up on import?  I've gotten this when for whatever reason, I end up with two web.configs in the directories of the project.


how can i use value right way in javascript

Question: hello i am a beginner and i want to make a small game by html, c s s and java script the game is that i have a input and button and a div(box) and i want to write in the input a color(red,blue,green and yellow) then click on the button so the background-color div(box) will change

var myInput = document.getElementById('input-test'),
  myButton = document.getElementById('button-test'),
  myColor = document.getElementById('color-test');

if (myInput === "blue") {
  myButton.onclick = function() {
    'use strict';
    myColor.classList.add('blue');
  };
} else if (myInput == "red") {
  myButton.onclick = function() {
    'use strict';
    myColor.classList.add('red');
  };
}
.in {
  margin-top: 50px;
  height: 40px;
  width: 100px;
  border-radius: 10px;
  border: 2px solid;
}

.vo {
  height: 50px;
  width: 100px;
  border-radius: 20px;
}

.go {
  height: 100px;
  width: 100px;
  background-color: black;
  margin-top: 5px;
  border-radius: 20px;
}

.red {
  background-color: red;
}

.blue {
  background-color: blue;
}

.green {
  background-color: green;
}

.yellow {
  background-color: yellow;
}
<input id="input-test" class="in" type="text" placeholder="Write the color" value="blue">
<button id="button-test" class="vo">click</button>

Comment: No idea why you tagged this C#.
Comment: i dont understand the tag !!!
Comment: You should add tags that are relevant to your question. See [tagging help](https://stackoverflow.com/help/tagging) for more info.
Comment: `use strict` should be at the beginning, not in the middle of the code.
Comment: Although it would be better for the `use strict` to be at the top in this small proof-of-concept, it is not actually wrong for it to be at the function scope. It only applies within that function and is useful for gradual transitions in large codebases.
Comment: OP, what is the question then? If something is not working as expected in your code you should mention in your question what did you expect and what is actually happening.
Answer: You need to get the value of the input, and do it when the user clicks.
You also need to remove the other color's class.

var myInput = document.getElementById('input-test'),
  myButton = document.getElementById('button-test'),
  myColor = document.getElementById('color-test');

myButton.onclick = function() {
  if (myInput.value == "blue") {
    myColor.classList.add('blue');
    myColor.classList.remove('red');
  } else if (myInput.value == "red") {
    myColor.classList.add('red');
    myColor.classList.remove('blue');
  };
}
.in {
  margin-top: 50px;
  height: 40px;
  width: 100px;
  border-radius: 10px;
  border: 2px solid;
}

.vo {
  height: 50px;
  width: 100px;
  border-radius: 20px;
}

.go {
  height: 100px;
  width: 100px;
  background-color: black;
  margin-top: 5px;
  border-radius: 20px;
}

.red {
  background-color: red;
}

.blue {
  background-color: blue;
}

.green {
  background-color: green;
}

.yellow {
  background-color: yellow;
}
<input id="input-test" class="in" type="text" placeholder="Write the color" value="blue">
<button id="button-test" class="vo">click</button>

Comment: thank you very much but wen i run the code i found blue is already written in the input , i want the place holder appear in the input
Comment: Then don't write `value="blue"` in the input. That's the initial value.
Answer:

  const colors = ['red', 'blue', 'green', 'green', 'yellow', 'maroon', 'black']; //etc
  var myInput = document.getElementById('input-test'),
    myButton = document.getElementById('button-test'),
    myColor = document.getElementById('color-test');

    myButton.onclick = function() {
      if(colors.includes(myInput.value)){
        myColor.setAttribute("style", "background-color:" + myInput.value);
      }
    }
.in {
  margin-top: 50px;
  height: 40px;
  width: 100px;
  border-radius: 10px;
  border: 2px solid;
}

.vo {
  height: 50px;
  width: 100px;
  border-radius: 20px;
}

.go {
  height: 100px;
  width: 100px;
  background-color: black;
  margin-top: 5px;
  border-radius: 20px;
}
<input id="input-test" class="in" type="text" placeholder="Write the color" value="blue">
<button id="button-test" class="vo">click</button>


Bandwidth out of control, where to go next

Question: I was wondering if someone could give me a bit of advice.
I have just released a site live and it has maxed my bandwidth / space more than what i predicted.
Im from Australia so space and bandwidth is quite expensive, the first 5 days of the site being live the bandwidth has hit 5Gb, and the max for my account is 20Gb.
I've been told space is so cheap now that instead of opting for an account in the US i should go straight to cloud.
Im not really sure my next move, but i need to figure it out quite fast.
Is it possible to host sites in the cloud?
Any help would be greatly appreciated.
Answer: Yes, it's possible to host sites "in the cloud", but it's no different than hosting sites anywhere else when it comes to the basic economics of hosting in general.
What you really need to decide is "do I host in Australia, or overseas?".  Hosting in Australia is expensive, because the bandwidth market is just stupidly expensive (the .au side pays most of the costs of hauling all that data across the Pacific, so in effect we're all subsidising the transit costs of the .us providers -- also, we're a much smaller and geographically dispersed market, which also drives up the costs).  On the upside, if your customers are in Australia you can give them a wonderful low-latency browsing experience.  Hosting in the US is cheap (bandwidth is orders of magnitude cheaper, for a start), with the latency downside for .au-based users of your site.  Note that you don't necessarily have to go with a US-based provider to get US hosting -- there are several Australian companies that have local support teams, but can provide you with a US presence (so you get the upside of local support in your preferred timezone, but with the cost benefits of being in the US).  (Full Disclosure: my employer is one of the companies that provides this option).
Is it worth it to host in Australia?  It depends on your site and what your needs are.  Only you can decide that.
Comment: S3 works fine as a CDN with CloudFront in front of it.
Comment: @ceejayoz: If you're using CloudFront, then you're using *CloudFront*, not S3, as a CDN.
Comment: Good to see you back around these parts.
Comment: @womble - Thank you for your response ... Im thinking of hosting the main parts of the site with US and just using amazon S3 for images as the site is basically users uploading collections of pictures ... Does that sound like a good way of doing it?
Comment: Whether you use S3 is orthogonal to the question of Australian vs US hosting; S3 as a CDN is a pretty bad idea, though, if that's what you're pondering.
Comment: Ok thanks for that .... So you would recommend just moving straight to a US based VPS?
Comment: As I said in my answer... *maybe*.  It depends on whether the lower latency to Australian users of an Australian-hosted server would be sufficiently beneficial to you.
Answer: I suppose it depends on what you mean by hosting in the cloud and what your requirements are. There are plenty of sites in which you can rent space, such as Amazon's EC2/VPC services. You set up a server and serve your content from there.
Without knowing what you're hosting or what your needs are there's not much more to say.
So...it is possible to host sites in the cloud? Yes.
Answer: Hosting your application "in the cloud" may require some alteration of your code, depending on the service that you choose. This is a moot point of course if your site is completely static server-side.
You've not stated how much dynamic and static output there is in your traffic pattern - you may get the gain you are looking for without moving the application code by hosting your images and other static content elsewhere, perhaps a shared host or VPS in another country or a "content delivery network" service like Amazon's "Cloud Front" (there are several decent CDNs around, some catering for small users and some optimised for larger concerns which may therefore be too expensive for your scale, so shop around).
20Gb does not sound like a lot of bandwidth (caveat: I know little of the Australian market) so. Am I right in guessing that you are using a "shared hosting" provider? If so then consider a VPS - most (even the cheaper options) come with at least a couple of hundred Mb of bandwidth allowance, some with a full Tb or more (though be careful: many hosts look "to good to be true" value wise and the usually turn out to be!).
If bandwidth is as expensive in your home country than you may have to look further afield even for the VPS option. If your audience is international than this may be a bonus: more of your visitors will get a better response than will get a slower one, but if your core audience in more local to you then you'll have to consider that the site will be less responsive for them if hosted on the other side of the trans-pacific links. This will be an issue for you no matter what hosting options you use (shared, VPS, "cloud", ...).
Comment: Hey @David - Thanks for the post, Australian bandwidth is very expensive ... Currently the site is on a quite big VPS account, im considering US hosting but worried about the latency
Comment: 20GB of traffic per month isn't a "big" VPS, even in Australia.
Answer: "Look at CloudFlare -- they have a free Content Delivery Network that is really impressive that will take care of the problem. The best part if you don't have to change your site -- just some DNS records."
Just a quick note that we should be able to help with the bandwidth. Since we don't have a datacenter directly in or around AU just yet (perhaps later in 2012), we might actually add a little latency for some visitors in AU (some would hit the USA, some would hit Singapore right now). If the bulk of the traffic is not in AU, then we should be a pretty good option.
Answer: Just in case, I want to mention the other option: optimize bandwith usage.
Review your site and see if you can optimize it a bit:
1) Ensure HTTP caching headers are set correctly so clients can reuse images and static parts
2) You can perhaps configure your web server to compress html output
3) Compress Javascript code using code-minifiers
4) The web application or site may be optimized in terms of bandwith usage
If you haven't considered all this so far and, for exmaple, clients are not caching your images, you could obtain huge bandwith reductions.
Answer: Look at CloudFlare -- they have a free Content Delivery Network that is really impressive that will take care of the problem.  The best part if you don't have to change your site -- just some DNS records.


Removing hover features and auto loading from site

Question: So I'm trying to remove all hover features and auto loading from my site so I commented out all the code that is related to the :hover feature in my site but there is still hovering available.
I'm also trying to remove all the available auto load features like the loader transform and animations. I did but I still see both hovering and some animations.
Is there something that I could be missing?
Like this hover and transform features below I removed them
.cateogory ul li a:hover:before {
transform: scale3d(1, 1, 1);
transform-origin: 0 50%;
}

.category-2 {
  transition: all 0.4s ease;
}

Comment: From where did you remove all the :hover features? I am not able to understand your question
Comment: from my css pages
Comment: Can you add a snippet of your css file by editing your question?
Comment: @AtheeshThirumalairajan could you ptal at the css snippets
Answer: In your code it looks like there is a typo
cateogory

.category ul li a:hover:before {
transform: scale3d(1, 1, 1);
transform-origin: 0 50%;
}

.category-2 {
  transition: all 0.4s ease;
}

If that does not solve You may create another class and copy all inside and change its classname with javascript

.category ul li a:hover:before {
transform: scale3d(1, 1, 1);
transform-origin: 0 50%;
}

.category-nohover ul li a:hover:before {

}

.category-2 {
  transition: all 0.4s ease;
}

Comment: so I can remove the hover by creating a new class with an identical name and adding -nohover to it?


Why is $T^4+6T^2-8T-3\in\mathbb Q[T]$ is irreducible?

Question:
Why is $T^4+6T^2-8T-3\in\mathbb Q[T]$ is irreducible ?

Obviously Eisenstein doesn't work, but can we do a substitution and obtain a form such that the criterion is applicable ?
We didn't cover it in the lecture, but I've seen now there's a so called rational root theorem, If I didn't understand it wrong, does it state:
For any polynomials with integer coefficients and having a rational solution, say $x=p/q$ must $p$ be a factor of $a_0$(here $-3$) and $q$ a factor of leading coefficient, (here $1$), so in this case there is no rational root $\implies$ we cannot factor it as $(T^3+...)(T+...)$, it must be of the form $(T^2+aT+b)(T^2+cT+d)$ am I wrong ?

EDIT: After the hint of ajotatxe. I got the following relations;

$\begin{cases}bd=-3\\ad+bc=-8\\ac+b+d=6\\a+c=0\end{cases}$
Substituting $c=-a$ and $d=\frac{-3}b$ in the second equation and multiplying it by $b$, I have:
$ab^2-8b+3b=0$, I assume that $a$ is rational and consider $b$ as an indeterminate, thus;
$\displaystyle b_{1,2}=\frac{4\pm\sqrt{16-3a^2}}{a}$
In both cases $b$ is irrational, contradiction.
Can somebody confirm it ?
Comment: You are on the right way . You might want to look here - http://math.stackexchange.com/questions/308984/show-x6-1-5x5-3x-4-5-is-irreducible-in-mathbb-qx?rq=1 for similar question.
Comment: What's going on if $a=2$? Then I can't see anything irrational.
Comment: @user26857 If it's the only possibility then I continue; $b$ is either $0$ (impossible, $bd=-3$) or $b=4$ (impossible 3rd relation is wrong then)
Comment: This was only a poor example. But $a\in\mathbb Q$, and then write it as $m/n$ and see when $16n^2-3m^2$ is a perfect square. I'd say that there is some work left to do. (Anyway, I'd never follow this way.)
Answer: You are in the right path. Expand the product $(T^2+aT+b)(T^2+cT+d)$ and equal coefficients.
Answer: For this kind of problems you can suppose $a,b,c,d\in\mathbb Z$; see Gauss' Lemma. Then the system of equations becomes more tractable since from $bd=-3$ you get only few cases for $b$ and $c$.


If F followed by Fm resolves to C, What do F# and F#m resolve to?

Question: Firstly, apologies if I am using the wrong terminology here. I am a beginner guitarist and only know a little music theory.
Considering the example of 'I will Follow you into the Dark' by Death Cab For Cutie, the introduction features the progression:

Am, C, E, Am, G, F, Fm, C/G

Messing around on the fretboard, I realised that I can play those same F barre chords on the second fret which presumably are F# and F#m.
So what what would naturally follow in that case and be the 'resolving chord' instead of C/G? And why?
Comment: I'm not doing that. I just played the same barre chords one fret up and wondered what the next chord would be if I did transpose everything...
Comment: It depends on the context and key.  If you're subbing those two chords straight into that song it isn't going to work regardless.  If you're transposing everything up ... transpose *everything* up.
Comment: Two more songs with this resolution are Till there was you, and In my life. I always thought the D-Dm-A was John's genius at work, till I realized Till there was you, a song the Beatles covered, had that same progression in a different key.
Comment: It can resolve to whatever you want, if you make it.
Comment: I repeat: +1. To the remover of my comments: I do not appreciate having my voice removed from the forum. I **will** let it be known that I **do** think this is a good question and that I most definitely *do* disagree with any downvoters, regardless of their opinion of the question's integrity. To wit: I am *not at all* a beginner musician (15+ years of dedicated improvement), though I don't know as much about theory as I would like to, and this question and it's answers has proved useful to me ...
Comment: but, *more importantly*, I have a distinct proclivity to think other beginner musicians might have the same question and, further, that they will learn something here. If it is a duplicate, please indicate so; or otherwise flag it as a poor question with either your downvote or a community-accepted mehod of doing so. **Please do not make the mistake that your sacrosanct opinion regarding the quality of a question coincides with that of the learners of the community, and, especially, that it is somehow more important.**
Answer: C#.   Because it's the same thing, shifted up a semi-tone.
Comment: Doesn't look any "harder" than F or Fm to me?
Comment: @AJFaraday Your opinion that it is harder to finger an A-shaped barre chord is just that - an opinion! Also, I play C-shaped barre chords across all 6 strings *more often than not* (although technically it's an inversion of the root chord, I suppose). Just sayin' ;)
Comment: Cool, thanks. Looks like C# is a harder chord for a beginner which is probably why I haven't been exposed to it yet. http://chord-c.com/guitar-chord/C/sharp-major/
Comment: @LaurencePayne It is harder to finger an A-shaped barre chord than an E-shaped one. And a C-shaped barre is rarely even fingered across 6 strings because it's more finger-bending.
Answer: The answer is in fact "C#/G#" (a C# with a G# as the bass note).  That chord can be played as an A shaped barre chord on the 4th fret (446664).
But playing the progression - Am, C, E, Am, G, F, Fm, C/G a semitone higher will mean having to play all barre chords instead of the open Am, E, and G and C/G.
Not sure why you would want to do that.  If your desire is to play the song in a key one half step higher, my solution would be to put a capo on the first fret and play the same (mostly open) chord shapes.  Unless you would rather play barre chords.  I personally try to only play barre chords when there is a good reason or a need.  Otherwise I avoid barre chords.
Just sayin .....
Answer: The progression F - Fm - C/G is a technique used in many songs.  The F is the IV of C. The walk down is in the third of the F chord (A) to F Minor (Ab) then to the C Major (G), there is a G bass note over the C chord.  So their is a chromatic movement of A-Ab-G in the harmony.
'Wake Me Up When September Ends' uses this over the hook in the song. It is used in all forms of music for a smooth transition to the I chord.
To answer the question you would resolve to the C# chord. What you are hearing is that popular movement at the end of the progression.


Como criar divs com Imagens especificas?

Question:
Qual a melhor maneira de criar divs com as imagens abaixo utilizando CSS? Gostaria que meu painel ficasse exatamente como a imagem que está de exemplo.
Criei duas classes par tentar inserir, mas a mesma deu problema e a imagem ficou cortada.

.squareGray{
    background-color:#808080;
    color:white;
    font-size:30px;
    background-image:url("../Images/caixa_cinza.png");
    background-size: cover;

}

.squareGreen{
    background-color:green;
    color:white;
    font-size:30px;
    background-image:url("../Images/caixa_green.png");
    background-size: no-repeat;

}
<c:if test="${realizadoSG < metaSG}">

        SAMSUNG

META:
        <fmt:formatNumber value="${SG.rows[0].META}" type="currency"/>

ACUMULADO

        <fmt:formatNumber value="${realizadoSG}" type="currency" />

          <c:out value="${SG.rows[0].ACUMULADO}" />%

  </c:if>
Answer: Se eu entendi corretamente, eu faria da seguinte forma:
Utilizaria 3 divs, uma é o container com o background do mapa do Brasil e usaria outras duas internamente para adicionar as 2 outras imagens.

E, usaria CSS grid para trabalhar as divs internamente das imagens. Pelo meu ver, as divs estão com uma margem a direita e a esquerda (e não estão centralizadas em nenhum eixo)
.bg {
  padding-top: nPx; //valor em px da margem para cima
  padding-right: nPx; //valor em px da margem para a direita

  display: grid;
  grid-template-rows: repeat(2, max-content);
  gap: nPx; //distância entre as duas imgs
  .img {
     background-image:url("...");
     background-size: cover;
  }
}

Se não é isso que você está querendo, peço que você reformule um pouco sua pergunta pois tive dificuldade de entender o que você quer fazer, onde você quer chegar e como está sua situação no momento (como está ficando na sua tela)


Proving that all sets of size n have $2^n$ subsets

Question: I've tried to construct a proof for this using recursion. My knowledge of recursion and set theory in general is quite limited so I'd appreciate some feedback!
The claim in symbolic logic: $\forall n \in \mathbb N, \exists u \in U, S(u) \wedge |u| = n \Rightarrow \mathcal |P(u)| = 2^n$ where:
$U:$ the set of everything
$S(x):$ x is a set
Initial Value
Assume $n = 0$
Then $\exists u \in U, |u| = 0$
Then $ u = \varnothing $
Then $ |\mathcal P(u)| = | \{ \varnothing \} | = 1 = 2^0 $
Prove: $\forall n \in \mathbb N, \exists u, x \in U, [S(u) \wedge (x \notin u) \wedge (|u| = n) \wedge \mathcal |P(u)| = 2^n] \Rightarrow  [(|u \cup \{x\}| = n + 1) \wedge (|\mathcal P(u \cup \{x\})| = 2^{n + 1})]$
Assume $|u| = n$
Then $ |\mathcal P(u)| = 2^n$
Then $ |u \cup \{x\} | = n + 1$ because  $ |\{x\}| = 1$
Then $ \mathcal |P(u \cup \{x\})| = |\mathcal P(u)| * |\mathcal P(\{x\})| = 2^n * 2 = 2^{n+1} $
Is this convincing enough or do I need to add more?
EDIT: Fixed notation
Comment: Yes, that is a correct equation.  Also: Hint: The set of subsets of $u\cup \{u\}$ is the same as that of a set having $|u|+1$ elements.
Comment: The "set of everything" is not considered a valid set.  I would build your set using unions rather than attempting to use intersections (the $\cap$ is for intersection).
Comment: The empty set is empty, so $|\varnothing|=0$ is legal notation, although different from the value you have.  The set containing the empty set denoted $\{\varnothing\}$ has one element.  Use escape characters to capture the curly braces.
Comment: so would it make sense if i wrote it like this? $|\{\varnothing\}| = 1$
Comment: thanks. how does the rest of the proof look though? minus the whole empty set issue?
Comment: yea i was kinda confused about that. what would be a better alternative? the set of all sets? as for the intersection, I think i meant union (~ typo). I'll fix it right now.
Comment: Actually, no, the "set of all sets" is another way of identifying the same not-considered-valid concept.  Allowing such a set to exist causes contradictions and invalid logic.  Better to start with only the empty set, and build a set using the union of [the previous set] and [the set containing the previous set].
Answer: Let $h_n$ be an $n$-bit string. i.e. A string consisting of 0's and 1's. Now let $S$ be your ground set with $n$ elements and $H \subseteq S$. If you label the elements of $S$ from 1 to $n$, given a fixed $H$, you can construct an $n$-bit string, say $h_n$ as follows, if $H$ has the 1st element, it has 1 in the first position and 0 otherwise. If $H$ has the second element, it has 1 in the 2nd position and 0 otherwise and so on...
For example if $S$ = {1,2,3,4,5,6} and $H$ = {2,4,6}, then $h_n$ is '010101'.
It is clear that given any subset, you can construct such an $n$-bit string. Conversely, given an $n$-bit string, you can construct a corresponding subset. In other words, there is a bijection from the set of $n$-bit strings to the set of all subsets of $S$. So the number of subsets of $S$ is equal to the number of $n$-bit strings which is $2^n$.
Alternate proof by induction:
Let the statement hold for all $n$ element sets. i.e. if $\vert S \vert = n$ then $S$ has $2^n$ subsets. Now suppose you add one more element $x_{n+1}$ to $S$ and call that set $S'$. Then all the subsets of $S'$ will be subsets of $S$ either with or without the new element $x_{n+1}$. In other words, for every $H \subseteq S$, there will be two subsets $H'$ and $H''$ of $S'$ given by $H' = H$ and $H'' = H \cup \{x_{n+1}\}$. So if $S$ has $2^n$ subsets, $S'$ will have $2 \times 2^n = 2^{n+1}$ subsets.
Answer: Recursion isn't neded here. If we have set of size $n$, then we can makes subsets of size $0,1,2,3...n$. Because the order of the elements in the set isn't important the number of ways we can choose subsets with size 0 is $\binom{n}{0}$. There are $\binom{n}{1}$ combinations for choosing subsets of size 1.
So the total number of subsets will be:
$$\sum_{k=0}^n \binom{n}{k} = 2^n$$
If you want a proof for this expression, here's one. Not that the sum is actually representing the sum of the numbers in $n^{th}$ row of the Pascal's triangle, where firs row is counted as 0. We know how to generate this triangle and we know that every number of the $n^{th}$ row is calculated twice in the sum of the next row. So the ratio between neighbour rows is $2$. This lead to geometric progresion: $ar^{n-1}$. We know that $a=1$ and $r=2$ so if we let our first row to be denoted as $n=0$, then the formula gets its final look:
$$\sum_{k=0}^n \binom{n}{k} = 2^n$$
Comment: And this is an excellent way to prove it without needing exact sets to work with.
Comment: Lovely answer. The only problem is I'm supposed to use induction to solve this question (sorry I should have clarified this initially)
Comment: You could try that this holds:

$$\sum_{k=0}^n \binom{n}{k} = 2^n$$

using induction, but I doubt it's what you want.
Answer: First, do not use the concept of a "set of all sets."  Such a set cannot exist.  Please read this article for more info.
Second, start by letting $u_0 = \varnothing$ and $u_{i+1}=u_i \cup \{u_i\}$.  Specifically, note that this means that $u_2=\{\varnothing,\{\varnothing\}\}$.  Then you have guaranteed unique elements in $u_i$ for all $i$, and you can build an induction on it.  The powerset of $u_i$ and $u_{i+1}$ will be very easy to build and confirm as having $2^i$ and $2^{i+1}$ elements (respectively).
Finally, I believe that $|\mathcal P(u \cup \{x\})| = |\mathcal P(u)| * |\mathcal P(\{x\})|$ would need to be proven separately.
Comment: Awesome! Thanks for the tip!
Answer: You can represent each subset of a set with $n$ elements by a sequence of $a_1...a_n$ where $a_i$ is either $0$ or $1$. $a_i=0$ means that the $i$th element of the set is not present in the subset. Now the number of all such sequences is $2\times 2\times ...\times 2=2^n$.
Answer: you have proved it for sets of size 0
now you have to prove:
if a set of  size n has $ 2^n $ different subsets
then a set of size n+1 has $ 2^{n+1} $ different subsets
and then you can use induction


Construction of a sequence of simple functions converging pointwise to a given function

Question: Q1: How to construct a sequence of $\{f_n\}$ of simple function for a function $f$  such that $f_n\to f$ converges pointwise?
Q2: If $f$ is measurable is $f_n$ also measurable for each $n$?
Q2 is by Q1
Comment: What does "p.c." mean?
Comment: pointwise coverge
Comment: See Theorem 2.10 in Folland's book "Real Analysis, Modern techniques and their applications".
Answer: You can do it in a very direct way. Namely, for each $n$ choose a number of values allowable for the function $f_n$ - for instance the values of the form $\frac{k}{2^n}$ where $k$ is and integer and $-n 2^n \leq k \leq n 2^n$ (so that the value is $(-n,n)$). Now, at each point, assign the "best" possible value, by declaring for instance that $f_n(x) = \frac{k}{2^n}$ if $x \in \left[\frac{k}{2^n}, \frac{k+1}{2^n}\right)$, and $f_n(x) = \pm n$ if $\lvert f(x)\rvert > n$.
To see pointwise convergence, just note that if you fix $x$ and take $n > \lvert f(x)\rvert$ at some point $x$, then $\lvert f(x) - f_n(x) \rvert \leq \frac{1}{2^n}$. And $f_n$ are simple, because they take a finite number of values by definition.
If $f$ is measurable, then $f_n$ are measurable, because you can express preimages of the possible values of $f_n$ using preimages of measurable sets (intervals, even) of $f$.


Inputs to k-means are often normalized per-feature. Why not fully whiten the data instead?

Question: We often normalize inputs to the k-means algorithm by 1) subtracting the mean on a per-feature basis and 2) dividing by the standard deviation on a per-feature basis. Some rational behind this is discussed here:
Are mean normalization and feature scaling needed for k-means clustering?
But it seems strange to assume that the features aren't correlated, so my question is, why don't we fully whiten the data instead? In other words, if the data has mean $\mu$ and covariance $\Sigma$, why not preprocess each sample using $ \tilde{x} = \Sigma^{-1/2} (x - \mu) $ ?
The only argument I see is that this will get computationally difficult when the dimensionality of $x$ gets very large, for example $\gg 100$, but are there other reasons?
Thank you.
Comment: It is possible. You may pre-process data in any way if it has sense relative to the future result obtained. But - I'd notice - K-means doesn't assume variables to be uncorrellated. What it assumes is that clusters within the data are, roughly, spherical, and it is another thing.
Comment: Yes, but the data will be "more spherical" after full whitening than after per-feature normalization.
Comment: The _whole_ data cloud - yes. But not necessarily clusters _in it_. Normalizations (any) are not _required_ by K-means, but they may have sense and often do have.
Comment: Agreed! Although now we're getting into a different topic :). You could say the same about per-feature normalization.
Answer: That is a good question, and it really makes a lot of sense to perform whitening of data. In particular there is a paper by Coates and Ng where they discuss the difference among these two steps (among other things) and their effect on k-means in order to learn some dictionary of patches of images.
As you already point out, whitening decorrelates data (up to a second order, since you are using the covariance matrix). Whitening presents some numerical problems (as well as normalization), and the standard trick is to add some constant term (regularization) when performing scalings.


Why is my HKWorkoutSession (usually) not ending?

Question: I have a very simple workout app I'm working on for Apple Watch.  It uses Health Kit to start and end workouts, my only problem is that when I try to end the workout it usually doesn't end the session and I get this error
2020-07-22 12:27:46.547720-0700 5k WatchKit Extension[25774:944527] [workouts] <HKWorkoutSession:0x80156310 A54AF52C-8B08-4BAD-A28C-03D8E54044B5 ended>: Failed to end: Error Domain=com.apple.healthkit Code=3 "Unable to transition to the desired state from the Ended(3) state (event 6). Allowed transitions from the current state are: {
    7 = "<error(7): Ended(3) -> Ended(3)>";
}" UserInfo={NSLocalizedDescription=Unable to transition to the desired state from the Ended(3) state (event 6). Allowed transitions from the current state are: {
    7 = "<error(7): Ended(3) -> Ended(3)>";
}}

I'm really not even sure where to start looking for the problem from this information, nor do I know what it means.  Also, usually on the 4th or 5th try, it will actually end the workout session.
Answer: The probable cause is the wrong sequence of ending workout session and workout builder data collection.
If your code looks something simmilar to this, you'll get the error:
session.end()

builder.endCollection(withEnd: Date()) { (success, error) in
 builder.finishWorkout { (workout, error) in
// do something
 }
}

The session hasn't finished yet, but the code immediately is trying to end the builder's session.
In Apple's example (https://developer.apple.com/documentation/healthkit/workouts_and_activity_rings/speedysloth_creating_a_workout) is the correct way of completing a workout through delegates:
session.delegate = self
.....
func endWorkout() {
        // End the workout session.
        session.end()
}
....
extension WorkoutManager: HKWorkoutSessionDelegate {
    func workoutSession(_ workoutSession: HKWorkoutSession, didChangeTo toState: HKWorkoutSessionState,
                        from fromState: HKWorkoutSessionState, date: Date) {
        // Wait for the session to transition states before ending the builder.
        /// - Tag: SaveWorkout
        if toState == .ended {
            print("The workout has now ended.")
            builder.endCollection(withEnd: Date()) { (success, error) in
                self.builder.finishWorkout { (workout, error) in
                    // Optionally display a workout summary to the user.
                    self.resetWorkout()
                }
            }
        }
    }

    func workoutSession(_ workoutSession: HKWorkoutSession, didFailWithError error: Error) {

    }
}

Answer: Building from @Nastya's answer, it was also necessary for me to set my session to nil:
session.delegate = self
.....
func endWorkout() {
        // End the workout session.
        session.end()
}
....
extension WorkoutManager: HKWorkoutSessionDelegate {
    func workoutSession(_ workoutSession: HKWorkoutSession, didChangeTo toState: HKWorkoutSessionState,
                        from fromState: HKWorkoutSessionState, date: Date) {
        // Wait for the session to transition states before ending the builder.
        /// - Tag: SaveWorkout
        if toState == .ended {
            print("The workout has now ended.")
            builder.endCollection(withEnd: Date()) { (success, error) in
                self.builder.finishWorkout { (workout, error) in
                    // Optionally display a workout summary to the user.
                    self.resetWorkout()

                    // I had to add this step
                    self.session = nil
                }
            }
        }
    }

    func workoutSession(_ workoutSession: HKWorkoutSession, didFailWithError error: Error) {

    }
}

Answer: Looks like you try to end session twice (when it's in ended state already).
Try to check the current state before ending.
if session.state == .running {
    session.stopActivity(with: Date())
}

if session.state == .stopped {
    session.end()
}

BTW from my experience it can take some time (some seconds) before green light turns off (You end session, and green light on your watch turns off some seconds later)
Comment: thanks, but this doesn't quite end the workout.  I'm curious how you read the error and can see that I'm trying to end the session twice? I'm terrible at reading error messages and debugging them.


Check if a jquery mobile listivew already contains a specific item?

Question: as the title says, is there a function that helps me find out if a listview contains a specific list item that has an id of say hello?
in my javascript i am currently pre loading items in a listview but there is a situation where the same code that adds the items in the listview, it will of coure add and duplicate the items.
i want to do something like this to find id of "hello"
if( (#listView).find("hello")  ){
//do nothing
}else{
$(#listView).append('
hello
')

}

Html:

New Claim

divider

Is this possible? is there some kind of .Find("id") method for a listview?
Answer: what is wrong with find?
if(!$('#listViewId').find("#hello").length){
  // append the element
}

Comment: doesnt work. i also am not trying to find the length but the valie "hello"


Can't get hook_field_attach_view_alter to set the value of the field

Question: I'm using some hook code I got from Drupal 7 show empty fields in order to show all of the empty fields on my node when viewing it. I would like to put a simple - as the displayed value when the field is empty.
function mymodule_field_attach_view_alter(&$output, $context) {
    // other stuff clipped...
    $output[$field_name] = array(
        '#theme' => 'field',
        '#title' => $instance['label'],
        '#label_display' => 'inline',
        '#field_type' => $field['type'],
        '#field_name' => $field_name,
        '#bundle' => $node->type,
        '#object' => $node,
        '#items' => array(),
        '#entity_type' => 'node',
        '#weight' => $display['weight'],
        0 => array('#markup' => '-'),
    );
}

I pulled the code from the linked page above and just changed the one line at the end that has #markup. As far as I can tell from the api docs, this code should work, but nothing that I put into that #markup value shows up.
All of the empty fields DO show up, it's just that the value shown is empty instead of - or blah or foo, because I've tried those as well. :)
How do I set the value to display when I use hook_field_attach_view_alter?
Comment: Did you find a way to get this working? It has been a while butI am facing exactly the same problem at the moment and hope that you might help me.
Answer: Ok, I found the answer: the key "#items" in the output array needs to have an array with an array as the value - not just the array:
$output[$field_name] = array(
    '#theme' => 'field',
    '#title' => $instance['label'],
    '#label_display' => 'above',
    '#field_type' => $field['type'],
    '#field_name' => $field_name,
    '#bundle' => $node->type,
    '#object' => $node,
    '#items' => array(),
    '#entity_type' => 'node',
    '#weight' => $display['weight'],
    0 => array('#markup' => ' '),
  );

becomes
$output[$field_name] = array(
    '#theme' => 'field',
    '#title' => $instance['label'],
    '#label_display' => 'above',
    '#field_type' => $field['type'],
    '#field_name' => $field_name,
    '#bundle' => $node->type,
    '#object' => $node,
    '#items' => array(array()),
    '#entity_type' => 'node',
    '#weight' => $display['weight'],
    0 => array('#markup' => ' '),
  );


What *can* Euclid prove?

Question: It is well-known that Euclid's axioms for geometry are not up to modern standards of rigor: in particular, there are a lot of times when he used "obvious" facts about the geometric objects which were neither stated in, nor derivable from, the axioms.
For example, in his very first proposition, Book I Proposition I, he sets out to construct an equilateral triangle. Seems easy enough, right? He gives a construction involving two circles drawn at the ends of a line segment which is to be one side of the triangle and uses this to produce the remaining two sides. Trouble is, he has no axioms which guarantee that the circles will intersect, as they must to produce the third vertex of the triangle! Another, even more subtle, problem is that when you draw the segments to the third vertex, how do you know what you form is in fact a triangle? You need another axiom for that -- specifically, the problem is you don't know the sides don't meet somewhere else than the new point before they get there. This trouble was actually known even back in old Greece: Zeno of Sidon pointed this one out.
So that makes me wonder: just what can you prove from Euclid's axioms, definitions, etc. without resorting to any hidden, "obvious" assumptions? If you can't so much as even get something as basic as whether the points you are attempting to construct by crossing lines and circles really exist, it seems the answer is "not a whole heck of a lot!" Or am I wrong?
Answer: You can see :

Ian Mueller, Philosophy of Mathematics and Deductive Structure in Euclid's Elements (1981 - Dover reprint).

It is a detailed analysis of Euclid's Elements logical structure. In particular, Ch.1.2 : Book I of the Elements , is devoted to the reconstruction of Book I, with graphical maps depicting the logical dependencies between Propositions.
You can use them, to check what Prop depends from the "flawed" ones : I mean those Prop of Book I which have some "hidden assumptions" asking for additional axioms not stated by Euclid.

What *can* Euclid prove?


Authenticate with Atmosphere + Dropwizard

Question: Hi I am looking for a way to authenticate users when they make WebSocket connection and simply if they are not authenticated close the connection. I am using Dropwizard framework and Atmosphere for the WebSocket connections. Here is the example that I use.
It would be great if I could use '@Auth' annotation provided by Dropwizard for authentication when the connection is establishing.
Answer: How are you exposing this? Is it through a javascript frontend?
You are using the servlet based approach as described in your link and here: https://cvwjensen.wordpress.com/2014/08/02/websockets-in-dropwizard/, and not the jersey atmosphere extension?
If you are using the servlet based approach would recommend using a token-based approach putting the token in the http header an then access this header in the @Ready handler method, like this:
<code>@Ready
public String onReady(final AtmosphereResource resource) {
    String AuthHeader = resource.getRequest().getHeader("Authorization");

    ...DO AUTH HERE

    logger.info("Resource {} connected ", resource.uuid());
    return "Connect " + resource.uuid();
}
</code>
Then, you could also easily close the connection if auth fails. However, depending on your client side implementation, you might want to think about this. If the client auto-reconnects on close, you have a scenario of constant closing and opening of sockets that may cause a resource drain. You could, if auth is not successful, store a private variable that states whether or not this instance is authenticated and just drop sending any messages to or process any messages from it. That would also be a "obscure" way of letting an attacker know that auth failed, it simply is in a limbo state; connected, but not failed or closed. Just not receiving any data. But again, this is specific to your implementation.
Jwt auth is an option, check this out: https://github.com/ToastShaman/dropwizard-auth-jwt. I have, although not made it public, ported this implementation to dropwizard 0.8rc3-SNAPSHOT. If you need this, please let me know and I can post it to github.
Comment: Thanks for your response, I ended up adding the access token to the header. Also like you said, before closing the connection I let the client know why the connection is being closed.


Is there way to use existing content type field to custom form in drupal?

Question: I want to use existing content type field in my own custom form.
Like In content type, we can use existing field.
Answer: In Drupal 7 you can use field_attach_form

function hook_form($form, &$form_state) {
  $form['fname'] = array(
    '#type' => 'textfield',
    '#title' => t('first name'),
  );
  $form['lname'] = array(
    '#type' => 'textfield',
    '#title' => t('last name'),
  );
  //attaching existing content type fields
  $node = new stdClass();
  $node->type = 'article'; //content type
  field_attach_form('node', $node, $form, $form_state); //it will attach all the fields
  unset($form['body']); //unset other fields like this.
  //..
  return $form;
}

Comment: How I can attach a user field to a custom form? I will display that field using views in an existing view. Here is the [statuses.form.inc file](https://www.dropbox.com/s/o1gf5j51n7jbo81/statuses.form.inc?dl=0).
Answer: You should consider using field_attach_form function.
An example use of this in user.module is as follows.
field_attach_form('user', $form['#user'], $form, $form_state, $langcode);


C# https connection issue

Question: I am using VSTS 2008 + C# + .Net 3.5 to develop a Silverlight 3 application and I need to access some https address on another web server (other than the server delivering the Silverlight application).
Here is my code which works with .Net 3.5 console application, But I cannot find class like ServicePointManager when using Silverlight. Any suggestions how to implement the same feature in Silverlight (accept all certificate from server).
<code>public static void SetBypassSslCertificateValidation()
{
    ServicePointManager.ServerCertificateValidationCallback
        += new RemoteCertificateValidationCallback(BypassSslCertificateValidation);
}

private static bool BypassSslCertificateValidation(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)
{
    return true;
}
</code>
Comment: There's really no point in using HTTPS if you're willing to accept arbitrary bad certificates, since any bad guy can MITM your connection.

Why is the target server using a bad certificate?
Answer: Silverlight leaves trust decisions for web services and other content to the web browser, since the BHWR (browser network stack) is used.
As a result, you cannot bypass certificate validation using any APIs in Silverlight.
You might be able to investigate special configuration options or security/zone settings for your web browser, if you're looking at using this for testing.

C# https connection issue


Efetuar ação ao pressionar tecla

Question: Necessito que quando o usuário pressiona a tecla DOWN (para baixo) do teclado, ele vá para uma div, da mesma forma como se fosse com scrollTop.
Alguém já fez algo parecido com isso usando Jquery?
Seria algo mais ou menos assim?
<code>$(window).trigger('keydown', function (e) {
    if (e.which != 40) return false;
    var posicao = $('.homeBaixoRodapeTexto1').position().top;
    $('html, body').stop().animate({
        scrollTop: posicao
    }, 1500);
});
</code>
Comment: https://api.jquery.com/keydown/ o Key code do DOWN é 40. Depois disso você só precisa definir o scrollTop ou ScrollDown.
Comment: Obrigado, editei a minha pergunta.
Answer: O que você precisa saber é a posição do elemento para onde quer fazer o scroll. Esse valor pode ser achado com o método .position() do jquery:
<code>var posicao = $('#destino').position().top;
</code>
Para correr o scroll somente quando a tecla down for pressionada pode usar assim:
<code>$(window).on('keydown', function (e) {
    if (e.which != 40) return false;
</code>
Para usar um scroll suave pode usar o jQuery animate() onde pode defenir a velocidade no segundo parametro da função (em milisegundos). Neste caso coloquei 1 segundo e meio.
<code>$('html, body').stop().animate({
    scrollTop: posicao
}, 1500);
</code>
Demo
O código que coloquei na demo:
<code>$(window).on('keydown', function (e) {
    if (e.which != 40) return false;
    var posicao = $('#destino').position().top;
    $('html, body').stop().animate({
        scrollTop: posicao
    }, 1500);
});
</code>

Dê uma olhada nesta pergunta/resposta que é relacionada com a sua se quiser ver mais exemplos de scrollTo.
Comment: Muito obrigado @Sergio. Fiz baseado na demo que você postou. Só que quando pressiono a tecla DOWN ele não faz nada. A div `homeBaixoRodapeTexto1` é onde quero que ele vá parar.
Comment: @FelipeStoker, coloque o seu código no jsFiddle que eu dou uma olhada e ajudo se ainda não funciona.
Comment: não sei como faria para colocar todo o HTML, pois o código está gigante, coloquei a parte do que realmente preciso. Quando pressiona DOWN (Tecla para baixo do teclado) ele vai para a div `.homeBaixoRodapeTexto1`
http://jsfiddle.net/felipestoker/3fHvf/

Efetuar ação ao pressionar tecla


Filtering iOS Push Notifications Documentation

Question: I have an iOS app which has the Notification Service Extension to intercept incoming remote notification to update/enhance the content.
The problem here is, the notification gets displayed to user. If the app is unable to update the notification within the given time limit or due to it's logic, app wants display selective notification (and not everything it receives from the server) - In both the cases, the Notification Service Extension cannot drop a remote notification.
But then, there's this independent wiki page which talks about how the Notification Service Extension can filter out notifications from iOS 13.3 onwards.
The first step is to 'Request Notification Service Entitlement', which is only for Account holder to view. Finally, when I viewed the wiki page, I see a webpage form Apple where they ask for info like 'App Store URL', 'When your extension runs, what system and network resources does it use?' etc. and many others.
I only have a sample test app to study user notifications. I can't provide App Store URL or answer other questions like 'When your extension runs, what system and network resources does it use?'- because I don't have a full fledged app. I'm merely logging when the extension runs, to work out the code flows and understand the expectations of the OS when invoking each method.
I don't know how to proceed from here.Please let me know if I have missed something.
Has anyone faced this? Were you'll able to successfully test filtering push notifications?
Comment: I am looking for a way to filter notifications in iOS. Did you get this working?
Comment: @AnsonKao No :(
Answer: To filter notification, you have to ask Apple for a special entitlement: https://developer.apple.com/documentation/bundleresources/entitlements/com_apple_developer_usernotifications_filtering
Apple is very touchy in allowing your application to filter notifications. You must have a good reason like encrypted VoIP.
And it takes a few weeks for Apple to answer your request.
Comment: I have seen that wiki page (already linked in the question). But Apple is asking questions like 'App store URL', 'network resource usage' etc. How can I bypass all this since I only have a test app? First, I have to see it working in my small PoC. Do they really expect to test this feature after app is in the store?
Comment: If your app is in TestFlight, it has an app ID.
The appStore URL is not mandatory.
But the review is finally 'manual' on Apple side, and long… (a few weeks)


Will someone explain this polynomial regression equation?

Question: I am in high school and I need to write a program that does polynomial regression to any degree on a set of data for a personal project. I think that this Wikipedia Article has the equation that I need to use. I need someone to explain this equation in particular. We have not covered anything like this is school. I have a basic understanding of matrixes but a lot of these symbols are new to me.
To clarify, I do not need help with the programming aspect but I need to understand the equation so that I can work with it.
Answer: Notation: $\langle x,y \rangle$ is the inner product between $x$ and $y$. It is sometimes called the dot product, denoted by $x \cdot y$. In any case we have $\langle x,y \rangle = \sum_{i=1}^n x_i y_i$.
You want an approximate solution to $Ax=b$. The trick is to choose it such that $Ax-b$ is orthogonal to the span of $A$. In other words you want $\langle Ay,Ax-b \rangle$ to be zero for every $y$. This is equivalent to $\langle y,A^T (Ax-b) \rangle$ being zero for every $y$, which is equivalent to $A^T(Ax-b)$ being zero. So $A^T Ax = A^T b$ which is your equation.
The geometry behind this idea is the following. Suppose $y$ is some other candidate for the least squares solution. Then by definition, $Ax-b$ is orthogonal to $A(x-y)=Ax-Ay$, so the Pythagorean theorem tells you that $\| Ay - b \|^2 = \| Ax - b \|^2 + \| Ax - Ay \|^2 \geq \| Ax-b \|^2$.
Answer: Can you clarify exactly what you do not understand?
$X^T$ is the transpose of $X$.
$X^{-1}$ is the inverse matrix of $X$.
Does this help?
Comment: Thank you now I know how to put this into code. It would help if I understood why it worked but I assume that is more complicated
Answer: for polynomial regression you are trying to create a model for your data with a simple form of a sum of linear terms
imagine you have $n$ data points indexed from ${1,..i,..n}$
$y_i = a_0 + a_1x_i + a_2x_i^2 + ...+ \epsilon_i$
it is easier to see these equations in matrix form
$\vec{y} = X\vec{a} + \vec{\epsilon}$
here $\vec{y},\vec{a},\vec{\epsilon}$ are vectors of length $n$
and $X$ is a matrix which has $n$ rows and as many columns as you have coefficients. So for a quadratic that would be 3 (intercept,$x$, and $x^2$), cubic would be 4 etc
right so now you have the problem, how do we determine the coefficients ($a_0,a_1..$) that produce a best fit model to the data $y$.
One easy solution in this case is least squares regression estimation.
in brief (as this has been described countless times on this forum):
we want to minimize the squared "distance" between the model and the data,so producing a model that best fits and represents the data. Therefore:
$E=\frac{1}{n}|| X\vec{a} - \vec{y}||^2$
which is done using the standard calculus technique of computing the derivative and setting it to zero
$\nabla E=\frac{2}{N} X^T(X\vec{a}-\vec{y})=0$
$X^T X \vec{a} = X^T \vec{y}$
so your best fit $a's$ are
$\vec{a}=(X^T X)^{-1}X^T \vec{y}$
Now this is just the start. I suggest you consult Yaser Abu-Mostafa's excellent lectures on the subject, found for free here https://work.caltech.edu/telecourse.html
this is easy to put into code also. You have the final equation, collect your terms to form the X's (also called the design matrix) and compute the transpose, matrix multiplication, and inverse using pre-built functions. Or just use the lm function in R...