Show multiple values for a day in Highcharts time series

Question: I have an array of information. Each value is from either the beginning or the end of each day.
To illustrate this, take this array: <code>[5, 18, 7, 2]</code>. 5 and 18 were recorded on June 7th, with 5 recorded in the morning, and 18 in the evening. 7 and 2 were recorded June 8th.
How would I represent this information in a Highcharts time series chart?
Comment: I guess the more important question is, how do you *want* to represent this on a chart? How to do it depends on what you want from it.
Comment: Do you have a timestamp for those values?
Comment: The values were imported all at once, so unfortunately the timestamps have an inaccurate time. The date itself is accurate, but the time is not.
Comment: You can use [pointInterval](http://api.highcharts.com/highcharts#plotOptions.series.pointInterval) or pairs [x,y] for each point.
Answer: my naive implementation would be to just space the points equal distance across the day.
For instance, if you have 2 points on June 7th:
<code> var seriesData = [];
 var milliInDay = 86400000; // milliseconds in a day
 var startOfDay = 1402099200000; // javascript timestamp for start of June 7th
 var numberOfPointsInDay = 2;
 var daySpacing = milliInDay / numberOfPointsInDay;
 seriesData.push([startOfDay + daySpacing, 5]);
 seriesData.push([startOfDay + (daySpacing * 2), 18]);
</code>


Why is the expectation of a trace equal to the trace of the expectation?

Question: Some textbooks use the property $$\mathbb{E}\left[\operatorname{tr}\left(X\right)\right]=\operatorname{tr}\left(\mathbb{E}\left[X\right]\right)$$
But why? I would really appreciate it if someone could prove this.
Comment: Taking the trace is a linear operation (it's essentially a sum). So you can use linearity of expectations.
Answer: I am assuming that $X$ is a random matrix, with finite dimensions. Then
$$
\textrm{tr}\ X=\sum_i X_{ii}.
$$
Hence, the claim follows by linearity of expectation, since
$$
\mathbb E(\textrm{tr}\ X)=\mathbb E\sum_i X_{ii}=\sum_i \mathbb E X_{ii}=\sum_i (\mathbb E X)_{ii}=\textrm{tr}\ (\mathbb EX).
$$


How to write a slur to nothing in LilyPond?

Question: Just like this:

This is a Piano Staff, the example was created on MuseScore.
The \laissezVibrer slur only creates a small slur.
I don't mind whether the slur crosses the measure or not, I just don't want it to be that short.
This is LilyPond's Engraving:

Also, as they're two voices, in LilyPond the last two rests appear above the default position in both staves. But they're written on a single line as << { } \\ { } >> and I don't know how to make the second voice disappear after that bar so the rest goes back to the default position.
Comment: The technical solution aside: what should this kind of notation indicate for the player?
Comment: @guidot  I see it as emphasizing the composer's desire for the note to hang right thru the downbeat rather than stopping any time sooner.
Answer: The easiest way to achieve this is to insert empty chords with <> that catch the open slur or tie. The following code ...
<<
\new Staff {
    << { f'1( <>) } \\ { \voiceThree e'4_( dis'8 cis') dis'2_( <>) } >> R1 R1
}

\new Staff {
    << { g'8 d'' g''2.( <>) } \\ { g'1( <>) } >> R1 R1
}
>>

results in the following output:

The nice thing here is that, like in the original score, all the open slurs end at about the same position. Moreover, you can put the rests outside the double-voice part so that they will be typeset at their regular vertical position.
Empty chords have no rhythmic length and can be used to catch spanners such as crescendi etc. With \voiceThree, you tell LilyPond that the notes should be shifted a bit to the right in case where note heads overlap with other voices, but the stems should be upwards. You then need to explicitly set the direction of the slurs and ties with _(.
Answer: A simple way to achieve this is to write a normal note that looks as if it's a rest, like this:
b8 fis' b2.~ | b1\rest |

(It's also possible to tweak almost every individual property of every object using \override, but I have to look those up again every time I need them.)
Comment: Can you show how that renders?   Does the choice of 'note' (b1 vs bX) affect where the rest is placed?
Comment: Yes, the rest appears exactly where the B would appear, so it would be too high up in the staff. Jasper's "empty chord" solution is much better because it doesn't have that problem. You learn something new every day!


Sums are independent of index

Question: This may sound like a very stupid question but hear me out.
I was reading analysis from Amann and stumbled upon this remark on page 42:
"Sums and products are independent of the choice of index. That is"
$$\sum_{k=0}^{n} x_k = \sum_{j=0}^{n} x_j$$ and $$\prod_{k=0}^{n} x_k = \prod_{j=0}^{n} x_j$$
To be clear, this is how they defined sums and products rigorously in Amann on page 41.
If we have an associative operation $$\cdot$$, they define a function $$V_n: X^n \rightarrow X$$ by $$(y_0, \cdots, y_{n-1}) \mapsto y_{n-1} \cdot x_n$$ and then, form the unique function $$\mathbb{N} \rightarrow X$$ such that $$f(n) = V_n(f(0), \cdots, f(n-1)) = f(n-1) \cdot x_n$$
Then, they set $$f(n) = \cdot_{k=0}^{n} x_k = f(n)$$
To get the sums and products, just replace $\cdot$ with $\sum$ and $\prod$ respectively.
Of course, this makes sense intuitively but to prove this rigorously is different. Are sums and products independent of the choice of the index because there is no mention of $k$ or $j$ in this recursive definition? I just want to make sure I make no blanket assumptions before continuing and want to make sure that my understanding of this is completely sound and rigorous.
Answer: Yes, whatever variable you choose as the index should be a "new" variable. We say that the index variable is not a free variable but is bound.
Outside of the scope of the sum or product, the variable should have no meaning. Otherwise you start getting conflicting values and all meaning is lost.
Comment: Thank you for your answer!

Sums are independent of index


Problemas com UTF8 no postgres

Question: Tenho um projeto JSF com JPA, banco Postgres 9
A informação com acendo esta sendo gravada com problemas no acento.

Ex:
ã grava como ã
Tubarão grava como Tubarão

O Banco esta com:

Ecoding = UTF8
  Collation = Portuguese_Brasil, 1252
  Character Type = Portuguese_Brasil, 1252

Todas as paginas xhttp com:
<h:head>
   <f:facet name="first">
       <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
       <meta name="viewport" content="width=device-width, initial-scale=1"/>
   </f:facet>
   ...

Obs:
Se gravo direto no banco, grava correto e vem correto para pagina, mas quando regravo volta o problema.
O inverso também acontece, digito corretamente na pagina mas quando grava grava com problema.
Comment: Marcelo note que UTF8 é diferente de UTF8 sem BOM, mas ok, vamos prosseguir... muitas coisas parecem ser na gravação, mas o problema geralmente é na exibição mesmo (raramente é na gravação a não ser que você tenha feito algo mirabolante rsrs). Tem um exemplo com mysql que pareceu ser a mesma situação, o usuário acreditava ser no momento de gravar, mas conseguimos detectar que a falha era totalmente na leitura ou codificação dos arquivos. Se puder dar mais detalhes poderemos determinar a origem real do problema.
Comment: Os arquivos foram salvos em UTF8 sem BOM? É um carregamento ajax?
Comment: Desculpe não compreendi o BOM. Acredito que foram salvos sim em UTF8. Quanto ao carregamento ajax hora sim hora não.
Comment: Tem sublimeText ou notepad++ instalado? Abra seus arquivos "java" nele e no rodapé deve aparecer a codificação que foram salvos.... Outra duvida, o problema somente ocorre no momento ajax ou em outro momento ou ambos?
Comment: O problema ocorre no momento da gravação. Persistência.
Os .java foram salvos em UTF8 (visto pelo notepad++)
Comment: Posso sim o que você necessita?
Comment: Marcelo é um pouco complicado de explicar o que é necessário para entender o problema, todavia uma leitura neste link talvez ajude a entender o que pode ajudar a tornar o teu problema mais claro: http://pt.stackoverflow.com/help/mcve Criar um bom exemplo do problema pode ser uma boa maneira de explicar como o processo ocorre até falhar.
Comment: Blz vou dar uma olhada. Só complementando o UTF-8 é sem BOM [agora entendi o tal do BOM :)  ]
Answer: Assumindo que a codificação da sua DATABASE e do seu servidor estão utilizando o UTF8 como ENCODING, sugiro verificar o seu cliente.
O PostgreSQL possui uma variável de ambiente chamada CLIENT_ENCODING que é responsável por controlar a codificação utilizada pelo cliente que está conectado ao servidor de banco de dados.
Com essa variavél configurada adequadamente, o servidor é capaz de converter as codificações do cliente/servidor e servidor/cliente de forma adequada, caso contrário, o caso reportado vir a acontecer.
Com o comando SHOW, podemos examinar como essa variável está configurada:
SHOW CLIENT_ENCODING;

Com o comando SET, podemos alterar seu valor, por exemplo:
SET CLIENT_ENCODING = 'UTF8';

Atenção: Uma vez que os dados foram gravados com esse tipo de erro, fica praticamente impossível corrigi-los de forma ortodoxa.
Referências:
Portugueŝ (v8.0):
http://pgdocptbr.sourceforge.net/pg80/multibyte.html
Inglês (v9.2):
https://www.postgresql.org/docs/9.2/static/multibyte.html
Espero ter ajudado!
Comment: Não era isso.
Tem pagina que grava certo, pagina que grava com o problema.
Comment: Estou verificando mas ainda não encontrei o problema e nem como melhor descreve-lo.
Answer: No arquivo glassfish-web.xml que fica na pasta WEB-INF acrescente:
<glassfish-web-app error-url="">
    <parameter-encoding default-charset="UTF-8"/>
    ...
</glassfish-web-app>

Comment: Não tenho esse aquivo.

Problemas com UTF8 no postgres


Facebook /{object-id}/likes - Error#803 "Some of the aliases you requested do not exist"

Question: https://developers.facebook.com/tools/explorer/145634995501895/?method=GET&path=%7B751199848395776%7D%2Flikes&version=v2.9
<code>    {
      "error": {
        "message": "(#803) Some of the aliases you requested do not exist: {751199848395776}",
        "type": "OAuthException",
        "code": 803,
        "fbtrace_id": "BvhO4SGizLJ"
      }
    }
</code>
751199848395776/likes
<code>{
  "error": {
    "message": "(#12) singular statuses API is deprecated for versions v2.4 and higher",
    "type": "OAuthException",
    "code": 12,
    "fbtrace_id": "BBG7Nujj+PC"
  }
}
</code>
Comment: `{object-id}` Is only a number. It does not include the brackets...
Comment: 751199848395776/likes
Comment: {
  "error": {
    "message": "(#12) singular statuses API is deprecated for versions v2.4 and higher",
    "type": "OAuthException",
    "code": 12,
    "fbtrace_id": "BBG7Nujj+PC"
  }
}
Comment: And what do you not understand about that error? Look up the word *deprecated*, and look at your API version
Comment: Please Help How to works in versions v2.4 and higher
Comment: Read the API documentation. I was only here for the Android tag, which your question isn't about
Answer: Change Api Level 2.3
<code>{
  "id": "751199848395776",
  "from": {
    "name": "Keshav Gera",
    "id": "303261006522998"
  },
  "updated_time": "2017-06-09T05:59:33+0000",
  "likes": {
    "data": [
      {
        "id": "124778301449917",
        "name": "Manisha Gera"
      },
      {
        "id": "1680577265523548",
        "name": "Rubi Sharma"
      }
    ],
    "paging": {
      "cursors": {
        "before": "MTI0Nzc4MzAxNDQ5OTE3",
        "after": "MTY4MDU3NzI2NTUyMzU0OAZDZD"
      }
    }
  },
  "comments": {
    "data": [
      {
        "created_time": "2017-06-26T04:54:27+0000",
        "from": {
          "name": "Manisha Gera",
          "id": "124778301449917"
        },
        "message": "Working",
        "can_remove": false,
        "like_count": 1,
        "user_likes": true,
        "id": "751199848395776_760186854163742"
      },
      {
        "created_time": "2017-06-26T05:00:17+0000",
        "from": {
          "name": "Keshav Gera",
          "id": "303261006522998"
        },
        "message": "hi",
        "can_remove": false,
        "like_count": 0,
        "user_likes": false,
        "id": "751199848395776_760188187496942"
      }
    ],
    "paging": {
      "cursors": {
        "before": "WTI5dGJXVnVkRjlqZAFhKemIzSTZAOell3TVRnMk9EVTBNVFl6TnpReU9qRTBPVGcwTlRJNE5qYz0ZD",
        "after": "WTI5dGJXVnVkRjlqZAFhKemIzSTZAOell3TVRnNE1UZAzNORGsyT1RReU9qRTBPVGcwTlRNeU1UYz0ZD"
      }
    }
  }
}
</code>
Comment: using through likes array size


Classical Guitar. How to study from fret 5 to 12

Question: I started learning to read music with a classical guitar. What I'm doing is to study the C scale from fret 0 to 4, and next I try to play a study based in that scale. So far, I have noted that most of the studies I have found, are composed to play notes between the frets 0 to 4. I wonder, when I finally master that section of the fretboard, how can I study the notes starting from fret 5 to 12? are there studies that concentrates the notes in that section of the fretboard (I haven't found a lot)?
The big question is: how do you study the note learning process from the fret 5 to 12?
Comment: Google Caged system
Answer: One way is to use the scales you already know, but shift the fretted notes down one string and up to the 5th fret but use the same open strings as always.
C Major Scale (C:V)
<code>$6.8 $4.0 $5.7 8 $3.0 $4.7 $2.0 $3.5
</code>

You can see from this example that the fifth fret itself is only needed for one note, the upper C. So, the same technique can be applied to shifts up to the 7th fret. In this scale, of course, since the index finger is anchored at the seventh fret, all the fingerings shift by one and the first C is fretted with the second (middle) finger.
C Major Scale (C:VII)
<code>$6.8 $4.0 $5.7 8 $3.0 $4.7 $2.0 $4.10
</code>

Another way is to practice scales on one string, shifting up five frets instead of shifting strings. To fret high up on the neck on a classical guitar without a cutaway, stick the tip of your thumb in the crack right where the neck and fretboard join the body, then you can reach all the upper register notes.
Answer: I'd be inclined to use the same studies, but use position 1 of the C scale, which spans between 7th and 10th frets.The root C is on bottom string, 8th fret. On the lower strings, you'll play exactly the same notes as starting on 5th st, 3rd fret. As much as possible, try to keep your playing within a four finger/ four fret span. Using open strings in some tunes, interspersed with fretted notes often gives an unwelcome change of tone that won't happen once you play every note fretted.
Answer: By doing scales in the lower positions.
What I also find useful is to not stymie your creativity by only knowing a scale two octaves in one position. Learn an octave of a scale on one two and three strings. For instance two string scale and you go the the next string after the fourth note of the scale and learn to go after the fifth as well.
When you have these three main patterns down try combining them. The aim is to have total creative control over where your fingers can go so that the music and the effects you are trying to achieve with your music dictate the positions you play in and not just a mere lack of knowledge.


How do you do a JQuery slideDown when the 2 divs are overlapping?

Question: Let's say there's a big div.
<code>onmouseover, a small div, which is on absolute, slidesDown(), in front of the big div.

onmouseout, the small div hides().
</code>
Let's say I move my mouse to the small div after it dropped down.  The problem is...when it gets there, there is a "twitch". That's because the browser sensed mouseout from the big div and a sudden mouseover.  When I stop the mouse, the browser senses that I'm still on my big div (with the small div on top), and finally slidesDown the small div.
As I move my mouse around the small div, it twitches.
Answer: You can use jQuery .hover() method to attach event handlers. This problem occurs because of mouse event bubbling, IE has two special events called "mouseenter" and "mouseleave" which does not fire if you move your mouse in child elements, for more info on this you can checkout this link:
MouseEvents - QuirksMode
Hope it helps.


Make a list of code paths mutually exclusive

Question: This is more a general question, not specific to a language.
Basically: how can I convert a list of 1-deep code paths, i.e. a list of if conditions, to a list of mutually exclusive if conditions? I.e. is there a family of algorithms to do that? I have the feeling this is a common problem in compilers.
Let's constrain the problem. We have a very simple language.

integer variables
an if/else condition with two binary operators == and !=
execution happens from top to bottom
there are no side effects: below if b = 1 and then b = 2, we can remove the first assignment

Example:
if a == 1 { b = 1 }
if a == 2 { b = 2 }
if a != 3 { b = 2 }
if a == 4 { b = 3 }

would be converted to e.g.:
if a == 4 { b = 3 }
else if a != 3 { b = 2 }

If that is solved, it would get more challenging with supporting <, >, &, |.
Comment: Are those two really equivalent? Wouldn't `b` retain its previous value if `a` is 3 (whereas it'd become 3 in the converted version)?
Comment: In my experience any technical problem can be solved by throwing three-letter acronyms at it until it goes away. In this case SSA and SMT sound like the right candidates. Note though that it's not that common for SMT solvers to be used in compilers' optimization stages due to their run time cost. Neither gcc nor clang will optimize your example, but they will optimize if you replace `a != 3` with `a != 2` (presumably because they detect that as the negation of the previous if and then realize on their own that it's an if-else, superseding the previous if's assignments one way or another).
Comment: @sepp2k right! fixed it.
Comment: I don't understand your reasoning. If (a != 3) b→2. If (a==4), well, then it is "!=3", so b→2. But you write if (a==4) b→3. So the rules are contradicting each other. Now, if (a == 4) beats (a != 3), then later rules beat former rules?
Comment: It's like a program: executed from top to bottom. I'll update the question.
Comment: @sepp2k cool, thank you, that were the terms I was looking for! That family can help solving the subproblem of determining mutual exclusiveness of (sub-)conditions.
Comment: @sepp2k: I feel that your comment is just enough of being an answer.  Please post it as such and let bobbel accept it, so SO can properly archive the question.
Answer: I did a bit more research. So there are two steps:

detecting mutual exclusiveness
make two non-mutually exclusive conditions mutually exclusive

ad 1. Detecting mutual exclusiveness can be done using SAT solvers as sepp2k already said. Not sure how they work internally, but a colleague gave the hint of using the idea of abstraction interpretation with lattices as values.
ad 2. In a naive approach, for two non-mutually exclusive code paths A and B, we simply replace the two with conditions A & B, A & ~B and ~A & B.


Detect digit on a live video camera using OpenCV and TensorFlow

Question: I tried the code provided below to detect digit in the video camera and put a contour around it then classify it using the H5 model but it's giving me bad results, just the camera is open and I can see neither detection nor classification. I'm not sure what I need to change or work on.
I use python2.7
OpenCV 4.2.0 and TensorFlow 1.5.0
The code I'm working with:
from statistics import mode
import cv2, time
from keras.models import load_model
from keras.datasets import mnist
import tensorflow as tf
import numpy as np
import vision_definitions
from PIL import Image
import numpy as np
import sys, os

from utils.inference import detect_digits
from utils.inference import draw_text
from utils.inference import draw_bounding_box
from utils.inference import apply_offsets
from utils.inference import load_detection_model
from utils.preprocessor import preprocess_input

# parameters for loading data and images
detection_model_path = '../trained_models/detection_models/model.sav'
class_model_path = '../trained_models/class_models/Num.h5'

# hyper-parameters for bounding boxes shape
frame_window = 10
class_offsets = (20, 40)

# loading models
digit_detection = load_detection_model(detection_model_path)
class_classifier = load_model(class_model_path)

# getting input model shapes for inference
class_target_size = class_classifier.input_shape[1:3]

class_window = []
class_window1 = []

# starting video streaming
cameraIndex = 0
resolution = vision_definitions.kVGA
colorSpace = vision_definitions.kRGBColorSpace
resolution = 2
colorSpace = 3
cv2.namedWindow('window_frame')
video_capture = cv2.VideoCapture(0)
if video_capture.isOpened():
 frame = video_capture.read()
else:
 rval = False
while True:
    rval, frame = video_capture.read()
    gray_image = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    rgb_image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    digits = detect_digits(digit_detection, gray_image)
    frame = cv2.resize(frame, (640, 480))
    key = cv2.waitKey(1)
    b,g,r = cv2.split(frame) # get b,g,r
    rgb_img = cv2.merge([r,g,b]) # switch it to rgb

    for digit_coordinates in digits:
        x1, x2, y1, y2 = apply_offsets(digit_coordinates, class_offsets)
        gray_digit = gray_image[y1:y2, x1:x2]
        try:
            gray_digit = cv2.resize(gray_digit, (class_target_size))
        except:
            continue

        gray_digit = preprocess_input(gray_digit, True)
        gray_digit = np.expand_dims(gray_digit, 0)
        gray_digit = np.expand_dims(gray_digit, -1)
        class_prediction = class_classifier.predict(gray_digit)
        class_probability = np.max(class_prediction)
        class_label_arg = np.argmax(class_prediction)

        color = color.astype(int)
        color = color.tolist()

        draw_bounding_box(digit_coordinates, rgb_image, color)
        draw_text(digit_coordinates, rgb_image, class_mode,
                  color, 0, -45, 1, 1)

    frame = cv2.cvtColor(rgb_image, cv2.COLOR_RGB2BGR)
    cv2.imshow('window_frame', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

Answer: I spend sometimes since there is no CV2.imshow() on Windows except C++ but there it is ...
[ Sample ]:
import cv2
import matplotlib.pyplot as plt
import matplotlib.animation as animation

import numpy as np

import tensorflow as tf

import os
from os.path import exists

import time

def f1( picture ):
    return np.asarray( picture )

fig = plt.figure()
image = plt.imread( "C:\\Users\\Jirayu Kaewprateep\\Pictures\\Cats\\samples\\03.png" )
im = plt.imshow( image )

global video_capture_0
video_capture_0 = cv2.VideoCapture(0)
video_capture_1 = cv2.VideoCapture(1)

def animate(i ):
    ret0, frame0 = video_capture_0.read()
    if (ret0):
        picture = np.concatenate( ( np.reshape(frame0[:,:,2:3], ( 480, 640, 1 )),
                                    np.reshape(frame0[:,:,1:2], ( 480, 640, 1 )),
                                    np.reshape(frame0[:,:,0:1], ( 480, 640, 1 ))),
                                    axis=2 )

        im.set_array( f1( picture ) )
    return im,

while True:
    # Capture frame-by-frame
    ret0, frame0 = video_capture_0.read()
    ani = animation.FuncAnimation(fig, animate, interval=50, blit=True)
    plt.show()

# When everything is done, release the capture
video_capture_0.release()
cv2.destroyAllWindows()

[ Model ]:
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
: Model Initialize
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
model = tf.keras.models.Sequential([
    tf.keras.layers.InputLayer(input_shape=( 29, 39, 3 )),
    # tf.keras.layers.Reshape(( 29, 39 * 3 )),
    # tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(128, return_sequences=True, return_state=False)),

    tf.keras.layers.RandomFlip("horizontal_and_vertical"),
    tf.keras.layers.RandomRotation(0.2),
    tf.keras.layers.RandomZoom(.5, .2),

    tf.keras.layers.Conv2D(32, (3, 3), activation='relu'),
    tf.keras.layers.MaxPooling2D((2, 2)),
    tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
    tf.keras.layers.MaxPooling2D((2, 2)),
    tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
    tf.keras.layers.Dense(64),
    tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
    tf.keras.layers.Dense(64),
])

model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(64))
model.add(tf.keras.layers.Dense(2))
model.summary()

[ Output ]:
Sample
Sample 2
Comment: The problem is not how to use OpenCV on windows, but how I can make predictions correctly from models and can detect the digits and classify them?
Comment: that is because the code need camera interfaces implementation and that is first example, do detect digits you can use CV provided algorithms or own model build you can find from example of the website.
Comment: How should I proceed, I have no idea Sir. I thought of modifying the xml file that is responsible for making the detection I replaced it with a model h5 but I get this error   File "cnn.py", line 68, in
    digits = digit_detection.detectMultiScale(gray_image, 1.3, 10)
AttributeError: 'Sequential' object has no attribute 'detectMultiScale'


Average result of game

Question: I'm trying to find the average result for a game where you have 12 items (containing a score), you can pick up to five of them, one of them is a multiplier, that when selected multiplies your result by it ( for example a x2).
How do I have to approach this problem? Do I have to analyze case by case, first by setting all the 11 numbers and the multiplier, and then making the calculus, or can I find a generic formula where I insert this values and find my expected result.
The expected result of the game, is calculated with the sum of the 5 itemes selected, with the exception where the multiplier is selected, where the sum of the other 4 is multiplied by it.
Answer: You can do it generically. Treat the case of the multiplier separately. So there's 11C5 (eleven choose 5) ways with no multiplier. You want the average. It's just 5 times the average of those eleven numbers. Then there's 11C4 ways with the multiplier. Let the multiplier be k. The average for the other 4 will be 4 times the average of the eleven. So, if A's the average, you have 4Ak.
So, ((11C5)*5A + (11C4)*4Ak)/(12C5) is your answer :)
Then simplify.
I get (35+20k)A/12. Hope that's right.
Comment: I will try this out, and then let you know about it.
Comment: Works great! Thank you.
Comment: Awesome, it was a fun problem :)
Comment: The extended formula version should be:((11C5)*5A + (11C4)*4Ak)/(12C5)
The first term was missing the 5 multipling the average of the eleven numbers!
Comment: Doh! Fixed now :)

Average result of game


Establishing the inequality $\cos \alpha \sin \alpha < \alpha < \frac{\sin \alpha}{\cos \alpha}$ via a geometric argument

Question:
Hi guys. Could you please hint me toward how I could start a proof on this type of question? I have information on the area of $\triangle{OQP}$ and $\triangle{QPR}$.
I have that $Area_{\triangle{OQP}} = \frac{1}{2} (OP)^2 cos(\alpha) sin(\alpha)$ and $Area_{\triangle{QPR}} = \frac{1}{2} sin(\alpha) (OP) (QR)$.
Any hints on how I could take it from here would be sincerely appreciated.
Kindest regards
Answer: The "two triangles" in the statement refers to the triangles $\triangle OQP$ and $\triangle OPR$.
Geometrically, the following inequalities are clear: the area of $\triangle OQP$ is smaller than the area of the circular sector, which is again smaller than the area of $\triangle OPR$.
Knowing that $OP = 1$, the area of the circular sector is just the angle $\alpha$, more or less by the definition of radian.
What inequalities do you get from that?
Comment: Thank you very much for this.
Answer: remember that $OP = r = 1$ so you have already established
$$Area_{\triangle{OQP}} = \frac{1}{2}\cos \alpha \sin \alpha $$ $$Area_{\triangle{QPR}} = \frac{1}{2} QR \cdot sin \alpha $$
Now, you can notice that the two triangles are similar because $PR$ is tangent to the circle,  so $QR = \frac{PQ^2}{OQ} = \frac{\sin^2{\alpha}}{\cos{\alpha}}$, and that the area of the sector is $\frac12\alpha $ (why?).
Lastly, you can easily see that the triangle inside the sector is less than the sector itself which is less than the sum of the  triangles, therefore
$$\cos \alpha  \sin \alpha < \alpha < \cos \alpha \sin \alpha +\frac{ \sin^3(\alpha)}{\cos \alpha}=\frac{\sin \alpha \cdot (\sin^2 \alpha + \cos^2 \alpha)}{\cos \alpha} = \frac{\sin \alpha }{\cos\alpha }$$


Why is my form not validating onsubmit?

Question: I am new at javascript, and am trying to get it so that when a user doesn't fill out all fields on my form, that they get an alert error.
Here is the first line of my form telling it to validate my function on submit...
<form accept-charset="UTF-8" action="xxxx" class="infusion-form" method="POST" name="myform" onsubmit="return validateForm();">

and here is my javascript function...

I am not sure what I am doing wrong? thank you so much for any help. Also the page is at http://business.uglyopportunities.com/affiliate-signup/ if you want to inspect element (form is located at bottom of page)
thanks
Comment: can you post your full html form code part
Comment: Not the problem, but you should be able to remove those `x == null` tests because the `.value` property shouldn't ever return `null`. Double-check the field names - if there's a typo in one then it (obviously) won't be found and then trying to access its `.value` property will cause an error.
Comment: nitpick: Single letter variable names are bad! Store the reference of `document.forms["myform"]` into a variable and use that as a look up. e.g. `var frm = document.forms["myform"]; var fName = frm["inf_field_FirstName"].value;` Also value is not going to be null on an input.
Answer: You declare validateForm in javascript AFTER the form. Try moving it up to before the form. Or even better, in the head of your page.
Learn how to use a javascript debugger. You would have caught this right away (validateForm throws an error when called).  http://www.youtube.com/watch?v=54IgWgoFToc
Comment: I would probably declare the function in the ``, but it shouldn't matter where the function is declared given that it likely won't be called until the whole page is loaded anyway (given the submit event is - presumably - in response to the user clicking something). That is, at the time that that `onclick` is triggered the function will exist.
Comment: Hi thank you very much mrtsherman I tried putting the script before the form, but that did not work.  However when I put it within the head tags it now works like a charm thank you very much for your time.

Why is my form not validating onsubmit?


Chart.js automatic chosen scale value

Question: I am using automatic scale starting value. It will generate and chose  min and max number in y axis automatically. Now i am facing problem, The scale start exactly from the min number and will be finish exactly from the max number. Can i set the scale to start before the min number like 2% of the value? This is my chart:
I just want to notice that i have random values, so i can not adjust the scale to start and end certain values!
Thanks
Answer: You can use min and max property of y-axis ticks, to set a minimum (start) and maximum (end) scale value respectively.
scales: {
   yAxes: [{
      ticks: {
         min: Math.min.apply(this, data_array) - 5,
         max: Math.max.apply(this, data_array) + 5
      }
   }]
}

ᴅᴇᴍᴏ

var data_array = [20, 22, 24, 28, 30];

var chart = new Chart(ctx, {
   type: 'bar',
   data: {
      labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
      datasets: [{
         label: 'BAR',
         data: data_array,
         backgroundColor: 'rgba(0, 119, 290, 0.5)',
         borderColor: 'rgba(0, 119, 290, 0.6)'
      }]
   },
   options: {
      scales: {
         yAxes: [{
            ticks: {
               min: Math.min.apply(this, data_array) - 5,
               max: Math.max.apply(this, data_array) + 5,
               stepSize: 5
            }
         }]
      }
   }
});

<canvas id="ctx"></canvas>
Comment: I have to  pick different value's number in my chart. So i can not limit the max and min number. for example the should take the min number automatically then start before 5 degrees ..Thanks for your help
Comment: You can easily calculate that, NO big deal. Do you have separate array for data values?
Comment: Yes, I  do. But could you please tell me how to calculate that?
Comment: Great  it's working now. and i have small issue left. if i could make with percent of the value `min: Math.min.apply(this, arrData[i]) - 2%,`? thank you so much for your help..
Comment: Yes you can, using - `Math.min.apply(this, data_array) - (Math.min.apply(this, data_array) * 2 / 100)`, but that'll look ugly tho, as you might sometimes get floating point numbers.
Comment: There is a grace function in chart.js. In your axis take just add grace:"2%".
Answer: Adding to the GRUNT answer.
function round(x) {
    return Math.ceil(x / 5) * 5;
}

min: round(Math.min.apply(this, data_array) - 5),
max: round(Math.max.apply(this, data_array) + 5),

This will make the chart more beautiful if your stepSize is 5.

Chart.js automatic chosen scale value


What are some ways I can secure my piano stand so it isn't moving as much?

Question: I just got the L85 stand for Yamaha P95 (with 3-pedal LP5), assembled the whole thing, and when I started playing, I noticed that it is moving quite a bit when I play something faster, or just hit the keys harder.
From looking at youtube videos, it seems that it is quite normal for the piano to move around a bit (around 1-2cm backward/forward).
Is this a result of a bad technique, or is it just how low-end stands are built? Are there some ways that I can secure my stand so that isn't moving as much?
Answer: Yes this is due to low quality stands and often the weight of the keyboard but also the resonance effect. When you hit the keys at the left or right end in a certain rhythm you increase the wobbling.
What you can do is attach the mount to a wall with some cheap brackets or just build your own frame from wood which is based on triangles. You won't have any wobbling then but here your frame has to weight enough to have enough mass or the whole construction will still wobble due to your keyboard being heavier. Even nicer is to mount the frame to a wall and it will be rock solid.
Answer: Your stand is probably of lower quality. Vibration caused by lower notes and forceful playing contribute to moving the stand, and it also gets worse with time by loosening the joints, screws and bolts (natural effect).
Another thing that can contribute to such problem is the levelling of the floor over which your stand lies. Joints between tiles, poorly settled wood floors or subtle inclination can lead to unpleasant unstability of the stand.
One possible solution is to put some form of wedge beneath one or two of the corners of the stand. Press down either side of the stand and check if the corners move up, leaving a gap to the floor. Put the wedge there, adjusting its thickness until the stand settles firmly.
Another good measure is to periodically re-screw every joint and connection of your base, checking for unreversible damage to the screw holes. In such cases, you can exchange current screws for longer or thicker ones, always taking care to avoid cracking/breaking the stand material due to overpressure.
Answer: From looking into the L85 stand image on the web (two parallel vertical boards), the most probable reason is that your floor may not be perfectly flat. Check if one of the corners of the stand is not hanging in the air rather than standing on the floor. If you observe a gap there, put something under that corner to close it.
Answer: We want our keyboards and stands to be lightweight enough to be portable, but heavy enough to stand firm. Not always a possible combination.   You could consider using a stand-alone music stand - something more substantial than the flimsy metal fold-up type - behind the keyboard.   On gigs I often have to use my knee to steady a bouncing keyboard!
Answer: I made my own stand! £20 for an 8x4 18mm mdf sheet and some paint
Comment: I don't immediately see how this answers the question.
Comment: Hi Dekkadeci, yes your right! To be more specific when I made my own stand, I added two brackets on the side legs of the stand that screw into the keyboard base (M5x20 for Yamaha P45 and P115) and what stopped the whole stand moving was adding the two ski type support rails on the base of each side panel. I then purchased some non slip rubber flat feet which I glued to the bottom of the ski's.


Two concatenated links throwing an error upon attempted logout

Question: I've looked everywhere, and can't seem to find an answer to my problem. I've written some code to toggle between a log in block and, once the user has logged in, a line of text that includes both a link to the logged-in user's profile (I have the Profile 2 module installed) and a log out link.
Both the log in block and the line of text display nicely on my site when users log in and out. The problem comes when I click on the user profile link, which takes me to the user's profile page (which is correct). But then, when I click the "log out" link while on the profile page, it throws an error, rolling the two URLs into one.
Here is the code I included on the page.tpl.php:
  <?php
    global $user;
    $var1 = $user->name;
    $var2 = 'Welcome back' . " " . '' . ucwords($user->name) . '' . " " . '|' . " " . 'Log Out';
    if ($user->uid == false) {
      print render($page['code']);
    }
    else {
  ?>

  <?php print $var2; ?>

(Not that it matters, I'm sure, but a few lines of this code are wrapped in div wrappers that this post wouldn't allow me to include.) When a user logs out from the profile page, this is the URL that results:
www.site.com/users/user/logout
Which obviously doesn't do the job of logging the user out. I want to emphasize that on every other page I've tested, the user can hit the log out link and be logged out with no problem; the issue only exists when trying to log out from the profile page. I suspect that I've coded something wrong with respect to the link HTML, but can't seem to figure out what the issue is. Any help would be much appreciated, thank you.
Comment: Beside the answer below there seem to be a missing the closing  of
Comment: Yeah, for some reason the text editor wouldn't let me include those div tags, so I had to delete them for the purposes of this post. Thanks, redhatlab!
Answer: The issue is you have href="users/logout" not href="/users/logout", eg, it's a relative url, and thus building upon where you are in your site.
Comment: Yep, that did it! Thanks, Jimajamma. Except now, I'm getting an "Undefined property: stdClass::$name" error where I have included "$user->name". I'm not finding an explanation to why this is happening online. Anyone have any ideas?
Comment: if you are getting $name as the undefined property, check if you are doing $user->$name somewhere instead of $user->name :)
Comment: That's not the problem, unfortunately, Jimajamma - my code is displayed in my original post, and I use $user->name twice - I didn't use $name at all.
Comment: If it was working before and the only thing you added was a / to the href, something else has been "fat fingered" for no better word :(


Reading the second (or subsequent) line in Korn Shell

Question: My OS is AIX (7200-05-03-2136) and my Korn Shell version is ksh88 (Version M-11/16/88f), but I think my question doesn't depend on versions.
Consider a single-line output of a command. I can easily put this into a variable via "read":
command | read variable
Now, suppose the command would have a two-line output. Is there a way to capture only the second line into a variable? It would be easy to use some external program like, i.e.:
command | sed '1d' | read variable
But I would like to avoid that and find a pure shell-solution. I have tried the following variations:
    command | { read -r junk ; read -r variable }
    command | { IFS=\n read junk ; read variable }
    command | IFS='\n' read junk variable

But all these won't work.
Comment: Define "won't work". What does happen, and how does that differ from your expectation?
Comment: command | tail -1 amounts to the same as command | sed '1d'. The point of my question is actually if this can be done within shell, not with external commands.
Comment: It is `command | { read -r variable; read -r variable; }`
Comment: assuming the requirement could change (eg, 2nd line this time, 1st line next time, etc), use a `while read -r x; do ...; done < <(command)` loop and a counter; when the counter hits the desired line number you store the value in `variable` and `break` out of the loop
Comment: "won't work" obviously means that the variable won't get filled with the content i would like it to be filled, in this case the second line of the output of "command". I thought that would be obvious from the context of the question.
Answer: Assign everything to a variable first. Next you can print or assign the second line.
variable=$(echo "line 1
line 2")
echo "${variable#*$'\n'}"
# or
variable="${variable#*$'\n'}"


Change a header's position from fixed to relative on opening (active) mobile drop down menu?

Question: I have a responsive design that when viewed on a device less than 600px wide, uses drop down multi-level navigation. It is nested inside a header that is set to position: fixed. The problem is, that when you drop down the menu the menu overflows downward and does not scroll (because the header is fixed), so the tabs are not visible. Is there a way (using Javascript, jQuery or PHP) to dynamically set it so that when the drop down menu (by way of clicking on the hamburger menu icon in the top right or left), it changes the header's position from fixed to relative?
A good example would be www.dribbble.com. When it's less than 800px wide, the header is sticky (fixed), then when you click on the menu in the top left, it's obvious that the header's position automatically changes to relative.
HTML

    Menu

    Link

Link

Link

Link

CSS
header[role="banner"] {
    width: 100%;
    background: #fff;
    display: block;
    margin: 0 auto;
    padding: 0;
    box-shadow: 0 2px 4px rgba(0,0,0,0.25);
    z-index: 10000;
}

@media all and (min-width: 500px) {
    header[role="banner"] {
        position: fixed;
        top: 0;
        left: 0;
        clear: both;
        height: auto;
        display: block;
    }
}

@media all and (max-width: 499px) {
    header[role="banner"] {
        position: fixed;
    }
}

JavaScript
    $(document).ready(function() {

$('body').addClass('js');
      var $menu = $('#nav'),
          $menulink = $('.menu-toggle'),
          $menuTrigger = $('.subnav > a');

$menulink.click(function(e) {
        e.preventDefault();
        $menulink.toggleClass('active');
        $menu.toggleClass('active');
});

var add_toggle_links = function() {
    if ($('.menu-toggle').is(":visible")){
        if ($(".toggle-link").length > 0){
        }
        else{
            $('.subnav > a').before('Open');
            $('.toggle-link').click(function(e) {
                var $this = $(this);
                $this.toggleClass('active').siblings('ul').toggleClass('active');
            });
        }
    }
    else{
        $('.toggle-link').empty();
    }
 }
add_toggle_links();
$(window).bind("resize", add_toggle_links);

    });

Comment: show your code .. We cant help without it.
Answer: Well, if you have a custom id or some other kind of attribute for a selector than you can change the position CSS property in multiple ways.
CSS3
@media all and (max-width: 800px) {
   header[role="banner"] {
      position: relative;
   }
}

jQuery
$(document).ready(function() {
    $('.menu-toggle').click(function() {
       if ($( document ).width() < 499)
          $('header[role="banner"]').css('position', 'relative');
       else
          $('header[role="banner"]').css('position', 'fixed');
    });
});

Note: You edited your post. Did you realized that you used position: fixed; in both of your CSS @media rules? Change the second to position: relative;.
Comment: Thank you. I tried that, but it did not work. I need the header[role="banner"] position: fixed to change to position: relative when the #hamburger-icon menu is clicked only. So the header will be fixed, but when the menu is clicked, everything scrolls.
Comment: Okay, I did that, changed the max-width: 499px to position: relative, but it still does not work.
Comment: The jQuery code you provided does not work. The header needs to change from position: fixed to position: relative ONLY when viewed on a device less than 499 px, AND the .menu-toggle link is clocked, so essentially when the menu is activated.
Comment: @user2485157 According to your code I updated the jQuery solution and the CSS as well. Both of them work for me. Use only one of them.
Comment: Okay, thank you very much, that worked. However, when you click on the menu again, the header remains at position: relative. Is there a way to include the rule in the jQuery so if the menu-toggle link is clicked again (closing the menu), the header returns to the position: fixed? I also  notice a flicker, so let's say you scroll half way down the page with the header fixed, then click on the menu to open it, the page sort of jumps. And the header disappears off the page, but it really is at the top, but relative. Does this make sense?
Comment: @user2485157 You can get the actual value of the `position` property by omitting the second parameter: `$('header[role="banner"]').css('position');` just check the actual value in an `if()`.
Comment: Not sure how you would do that.
Comment: I still need the header to be position: relative. I just don't want the page to jump if a user is let's say in the middle of a page and then decides to click on the menu, and it "jumps".
Comment: And also, when you click on the menu again, the header remains at position: relative. Is there a way to include the rule in the jQuery so if the menu-toggle link is clicked again (closing the menu), the header returns to the position: fixed?
Comment: @user2485157 Use the CSS solution only. It will do all of this in the background, so you don't have to mess with jQuery. If you have problems with it, please ask it in a new question. Thats the way we do it here.


How to bulk delete Orders in Drupal Commerce module

Question: I need to delete 200 Drupal commerce orders. Is there any way to do this in a bulk action?
Orders are at:   /admin/commerce/orders
Same with Customer profiles. I need to delete them with a bulk action. Can I accomplish with this?
Customer profiles are at:   /admin/commerce/customer-profiles/list
Answer: If you've got 65,000 orders that you need to wipe, VBO isn't an option. You can try this:
<code>TRUNCATE commerce_customer_profile;
TRUNCATE commerce_customer_profile_revision;
TRUNCATE commerce_funds_transactions;
TRUNCATE commerce_funds_user_funds;
TRUNCATE commerce_line_item;
TRUNCATE commerce_order;
TRUNCATE commerce_order_revision;
TRUNCATE commerce_payment_transaction;
TRUNCATE commerce_payment_transaction_revision;
TRUNCATE commerce_paypal_ipn;

TRUNCATE field_data_commerce_customer_address;
TRUNCATE field_data_commerce_customer_billing;
TRUNCATE field_data_commerce_customer_shipping;
TRUNCATE field_data_commerce_line_items;
TRUNCATE field_data_commerce_order_total;
TRUNCATE field_data_commerce_price;
TRUNCATE field_data_commerce_product;
TRUNCATE field_data_commerce_shipping_service;
TRUNCATE field_data_commerce_total;
TRUNCATE field_data_commerce_unit_price;

TRUNCATE field_data_commerce_coupon_order_reference;
TRUNCATE field_data_commerce_display_path;
TRUNCATE field_data_field_order_deliveryinstructions;
TRUNCATE field_data_field_order_flags;
TRUNCATE field_data_field_order_id;
TRUNCATE field_data_field_order_notes;
TRUNCATE field_data_field_supplier;

TRUNCATE field_revision_commerce_customer_address;
TRUNCATE field_revision_commerce_customer_billing;
TRUNCATE field_revision_commerce_customer_shipping;
TRUNCATE field_revision_commerce_line_items;
TRUNCATE field_revision_commerce_order_total;
TRUNCATE field_revision_commerce_price;
TRUNCATE field_revision_commerce_product;
TRUNCATE field_revision_commerce_shipping_service;
TRUNCATE field_revision_commerce_total;
TRUNCATE field_revision_commerce_unit_price;

TRUNCATE field_revision_commerce_coupon_order_reference;
TRUNCATE field_revision_commerce_display_path;
TRUNCATE field_revision_field_order_deliveryinstructions;
TRUNCATE field_revision_field_order_flags;
TRUNCATE field_revision_field_order_id;
TRUNCATE field_revision_field_order_notes;
TRUNCATE field_revision_field_supplier;
</code>
Comment: Manually truncating tables can cause issues in drupal if the order entities are referenced anywhere else. I'd use this on a development site but never on production.

vijaycs85's answer would probably address the performance concern.
Answer: There is a module for that™
With Commerce VBO views you can create a view where you can mass delete orders and products. I don't know about customer profiles, but that could be a feature request if it's not added yet.
Comment: You trademarked it! A definite +1!
Comment: Thanks, I'll check that module. Just wondering... what if I just use the VBO module to add a vbo fiel to the main orders view. Is this bad practice?
Comment: @chefnelone What do you mean by a VBO field?
Comment: please, look a the image capture http://screencast.com/t/WgyeeSQyG
Comment: @chefnelone What you are talking about is not a "field" but the core functionality behind VBO which won't work without Views and is not something that is possible to add to entities like orders are.
Answer: Commerce Order Cleanup is another attempt on this front:

Allows to cleanup the orders by various order properties like last changed, status.


Give an example of two different metrics on $\mathbb{R}^2$ whose restrictions to the $x$-axis are equal.

Question: Give an example of two different metrics on $\mathbb{R}^2$ whose restrictions to the $x$-axis are equal.
Consider the two metrics $d_2$ and $d_1$ on $\mathbb{R}^2$ where $d_2$ denotes the usual Euclidean distance and $d_1$ denotes the "taxicab" metric on $\mathbb{R}^2$. Namely, $d_1(x,y)=|x_2-x_1|+|y_2-y_1|$.
Restricting $d_2$ to the $x$-axis gives us,
$$d_2((x_1,0),(x_2,0))=\sqrt{(x_2-x_1)^2+(y_2-y_1)^2}=\sqrt{(x_2-x_1)^2+(0-0)^2}=\sqrt{(x_2-x_1)^2}=|x_2-x_1|$$
Similarly, restricting $d_1$ to the $x$-axis yields,
$$d_1((x_1,0),(x_2,0))=|x_2-x_1|+|y_2-y_1|=|x_2-x_1|+0=|x_2-x_1|$$
Hence, $d_2$ and $d_1$ are equivalent when restricted to the $x$-axis.
Is this correct?
Comment: Yes, it is correct.
Answer: Your proof is correct. Additionally, note that the same proof shows that all metrics induced by $L^p$ norms are equal when restricted to $x$-axis for all finite $p$.
Answer: Your proof must be edited somewhere else, but they're just a typo. No logical flaw in your proof.
These three things only need to be fixed like this(when $x=(x_1,x_2), y=(y_1,y_2)$).
$$
d_1(x,y)=|x_2-x_1|+|y_2-y_1|\Rightarrow d_1(x,y)=|y_1-x_1|+|y_2-x_2|\\
d_2(x,0)\Rightarrow d_2((x_1,0),(x_2,0))\\
d_1(x,0)\Rightarrow d_1((x_1,0),(x_2,0))
$$
Comment: Makes sense. Obviously the number 0 is not an element of $\mathbb{R}^2$!
Comment: @pyridoxal_trigeminus Yeah. Your miss are only several typo.


Using spacy visualizer with custom data

Question: I want to visualize a sentence using Spacy's named entity visualizer. I have a sentence with some user defined labels over the tokens, and I want to visualize them using the NER rendering API.
I don't want to train and produce a predictive model, I have all needed labels from an external source, just need the visualization without messing too much with front-end libraries.
Any ideas how?
Thank you
Comment: You could create your own custom matcher and add it as a step into the pipeline of ``nlp()``
Answer: You can manually modify the list of entities (doc.ents) and add new spans using token offsets. Be aware that entities can't overlap at all.
import spacy
from spacy.tokens import Span
nlp = spacy.load('en', disable=['ner'])
doc = nlp("I see an XYZ.")
doc.ents = list(doc.ents) + [Span(doc, 3, 4, "NEWENTITYTYPE")]
print(doc.ents[0], doc.ents[0].label_)

Output:
XYZ NEWENTITYTYPE

Using spacy visualizer with custom data


Problema ao adicionar imagens C#

Question: Estou tentando criar um objeto do tipo Image a partir de uma imagem já existente, que será inserido em um Frame e que por sua vez será inserido em um StackPanel. No entanto, apenas imagens/ícones que estão inseridas dentro do projeto são exibidas no componente (#2). fiz testes para verificar se é o arquivo que não existe, porém não entra (#1).
Alguém sabe o que é? Todos os arquivos estão com permissão de acesso para todos os usuários...
if (!File.Exists("C:/Users/32-add.png")) MessageBox.Show("");
//teste para verificar a existência (#1)

//Uri imageUri = new Uri(photoPath + "32-star.png", UriKind.Relative);

//testando com um ícone do meu projeto, aqui vai (#2)

Uri imageUri = new Uri("C:/Users/32-add.png", UriKind.Relative);
//aqui não vai

BitmapImage imageBitmap = new BitmapImage(imageUri);
Image img = new Image {Source=imageBitmap, Width = 130, Height = 130, MinWidth = 130, MinHeight = 130};
//conversão

Frame frame = new Frame{Content = img};

stackPanel.Children.Add(frame);

Comment: Consegui resolver o meu problema com o vídeo, em inglês: https://www.youtube.com/watch?v=Nb89r13Z1q4 Grato :)
Answer: Você pode utilizar apenas uma \, mas para isso, coloque um @ na frente da string:
File.Exists(@"C:\Users\32-add.png")

E também pode utilizar duas \, porém sem o @:
File.Exists("C:\\Users\\32-add.png")

Answer: O problema está em como você passa o caminho da imagem. Para caminhos absolutos, deve-se usar a barra invertida, ficando:
if (!File.Exists("C:\\Users\\32-add.png")) MessageBox.Show("");

Comment: Não deveria escapar a barra invertida? Para evitar que `\n` seja interpretado como quebra de linha?
Comment: Se eu deixo apenas um \ para definição do path, ele me retorna erros de representação de texto para UTF 16 (?), eu uso a barra invertida por ser como eu uso para a localização do path com os meus ícones adicionados ao projeto, e que são reconhecidos com sucesso... Não sei se isso tem algo a ver, mas, é WPF
Comment: @JeffersonQuesado Isso mesmo. Corrigi a resposta baseada em sua observação.

Problema ao adicionar imagens C#


Covariates and moderator variables

Question: I have a 4 * 3 (both the IVs are categorical) factorial design with two covariates (both are continuous) to run ANCOVA. Can I do a moderation analysis?
Answer: You should take a look at your sample size and see if it is appropriate if you should do a moderation analysis. You are already estimating a large number of terms (your IVs, the interactions between the IVs, and your two covariates). If you are going to include interactions between your IVs and your covariates, you need to:

have an appropriate reason grounded in the literature to do so. Including an interaction term because you can is very different from if the literature suggests you should. I can assure you that a good reviewer will want to know the reason that you included a term in your manuscript. And saying "it was there so i did it" is rarely a reason that will convince an editor/reviewer.
Do you have the necessary sample size to estimate your model? Even if your model is able to converge, there is a real possibility that you will face an issue of sparsity if you do not have a large enough sample. You must ask yourself, do you really want to make inference on a three-way interaction with a small associated sample size.
Finally, be wary of inserting too many spurious interaction terms. It would not be beyond a reviewer to suggest that you are significance hunting. The number of estimated terms in your model is over 20. There is a good chance that one will be spuriously significant just based on pure chance.
Answer: There is nothing inherent in your problem that prohibits you from doing a moderation analysis.
That doesn't say that it is a good idea to do one. Whether it is a good idea depends on the nature of your data, your sample size, the theory (whether from the literature or from some new theory) and so on.

Covariates and moderator variables


FLVPlayBack component, how to built-in skin in project?

Question: FLVPlayBack asks a link for it's skin. How can I bult-in skin in project, so I will have only one swf in result?
Answer: if you are using flex or CS4 and above you could try using the Embed directive and point the skin at that.


Is inheritance a viable solution to pass a set of model parameters to different classes?

Question: I present my problem in the form of two questions.
First, I have a set of parameters which are obtained from a parameter file and need to be used in different classes of the model. I did this by creating a parsing class (let's call it parse_class) that reads the file and stores the parameters (with tag and value) using a hash table. Then, I use this class as a parent class for other classes that I need to use the parameters. Is this a good practice?
Second, using the above-mentioned method, I inherited "parse_class" in two classes, one of which is derived from another. In other words:
class parse_class {
    static T parameters;
};
class A: public parse_class{}
class B: public A, public parse_class{}

The reason I inherited again from parse_class in class B is that without it, the parameters member of parse_class is not recognized in class B (which is probably the subject of another question). This leads to warning: direct base "parse_clase" inaccessible in "class B" due to ambiguity. Any idea how to improve this?
Comment: The phrase "parameters are not recognized"  does not convey any useful information whatsoever. Please follow the instructions for creating a [mre].
Answer: At the first question, the answer is no.
You should use containment instead of inheritance.
Inheritance is a relationship of type "is a". By using it as the base of your hierarchy you are stating that every class is a parameter file parser.
Comment: More efficient in terms of what? Certainly not speed. And from the coding point of view, it is simply bad design.
Comment: I understand your point from the coding point of view but this approach makes my model way more efficient. Containment is not something I would rather go for this case.
Comment: the reason is I use the values of these parameters to do some math calculations in the bodies of other classes and if I use confinement, I have to modify all those equations. From the design perspective, you are completely right
Answer: I think inheritance is a bad idea as @Matei Florescu mentioned. And you also seem to not have really understood what static does.
Some hints:

You don't need to inherits a class to access its public static members.
You don't need an instance of the class to access its public static members
A static member of a class is unique (in other words, shared by everyone)

Knowing that, based on your code, you could write:
.h:
class ParamsParser
{
    public:
        static T parameters; // I assumed T is defined
        static void loadParameters(); // A method to load the parameters and store them into the above member "parameters"
};

.cpp:
T ParamsParser::parameters = {/*some default intialization*/};

void ParamsParser::loadParameters()
{
    //parse your file and store data in ParamsParser::parameters
}

Note that you have to call ParamsParser::loadParameters() at the beginning of your program in order to get the desired parameters file loaded once and for all.
Then every time you need these data for your calculations (in A or B or whatever), you just have to access the parameters like this ParamsParser::parameters.
Comment: I actually understand what is a static member and how to deal with it. I tried to simplify my problem with the given description but as it appears, I have failed to convey the problem properly. But I upvoted you for your admirable effort in helping
Comment: @JalilNourisa Ah, it seems that I didn't understand what is your problem then, I'm sorry.


Changing Commerce Credit Card option to read something else

Question: I have two radio options in my form for payment: the first says 'credit card' and the second says 'cheque' (I'm using the PayPal wpp and Cheque modules). The Cheque option is easy enough to change to say something else ('send me an invoice') and I changed that in the store > config > cheque settings.
But, does anyone know how or where to change the text for the 'Credit Card' option. I want to add more information about how we process it to the label itself.
Answer: Alter the form that has the form_id of commerce_checkout_form_review:
/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_commerce_checkout_form_review_alter(&$form, &$form_state) {
 $form['commerce_payment']['payment_method']['#options']['commerce_payment_example|commerce_payment_commerce_payment_example'] = t('AWESOME PAYMENT');
}

The #options array will hold a list of payment methods that are keyed by the payment_method followed by a pipe (|) and then an instance_id. Just update the title accordingly.


React add label to nested array object in Object.keys map

Question: I have a React component which is pulling JSON data via an axios.get call and then I am mapping an embedded object using the following function:
axios.get('MasterData.json').then(response => {
       const fullTree = response.data.graph.tree;
       const resultTree = Object.keys(fullTree).map(key => ({
          ...fullTree[key],
         id: key
    }));

This produces the following:
{5bd356cc-5ee6-49a0-ab68-65cbf0209105: Array(6), id: "5bd356cc-5ee6-49a0- ab68-65cbf0209105"}

which is great, but I need to add a label of "ports: to the entire nested array (Array(6)) that is being output above so that I can map it. Any help is appreciated.
Comment: You can use `({
          ports : ...fullTree[key],
         id: key
    })` instead of `({
          ...fullTree[key],
         id: key
    })`
Comment: What do you mean by 'add a label'? Can you add details on how the structure is now and what your expected output is?
Comment: Hassan I get a parsing error with your method (my first thought was to try that). Dinesh, what I am trying to do is exactly what I thought Hassan's code would do, which is give the entire array a key of "ports."
Answer: axios.get('MasterData.json').then(response => {
   const fullTree = response.data.graph.tree;
   console.log(fullTree) // you must check this fist
   const resultTree = Object.keys(fullTree).map(key =>
     new Port({  // create some function to generate get port as you want
        port : fullTree[key],
        id: key
     )
});

for create function maybe on bellow me can explain more :)


Consider throwing two six-sided dice. Let X be the sum of the two values and let Y be the product of the two values.

Question: What is the value of $P(X = i, Y = j)$ for $i = 1,2,\cdots,12$ and $j = 1,2,\cdots,36$.
Trying to figure out if there is a easier way to figure this out rather than writing out all the values.
Comment: Maybe the answers in that question could help - you could generalize the answers.
Comment: Possible duplicate of http://math.stackexchange.com/questions/707402/consider-throwing-two-six-sided-dice.
Comment: This is a different part of the question. Lets say the dice roll is (1,1), the sum would be 2 and product would be 1. So i = 2, and j = 1. P = 1/36.
Answer: Consider the system of two equations $i+j=m$, $ij=n$.
By substitution, one gets a quadratic equation. If $i+j=m$, $ij=n$ has a solution with $i$, $j$ integers in the right range, then it either has exactly $2$ solutions or $1$ solution. Thus all probabilities will be $0$, $2k$, or $k$ for some constant $k$. The pairs $(x,y)$ with probability $k$ are $(2,1),(4,4),\dots,(12,36)$.
This speeds up the work considerably, but does not eliminate drudgery entirely.
Answer: Hint: For $X=2$, there's the one possibility of $(1,1)$. For $X=3$, there's two options $(2,1), (1,2)$. This pattern continues increasing until after $7$, and then the possibilities decrease until $X=12$ with only $(6,6)$.
As for the product $Y$ it's just finding $2$ factors between $1$ and $6$. Note that primes above $6$ logically won't work, and also multiples of those numbers $(11, 22, 33)$.


Remove order from Field Collection set in form

Question: I am using the Field Collection and Field Collection Fieldset modules to group a set of elements in my form. But what i see in the form is an Order column for the fieldset items, which i would like to hide, as shown in the below screenshot.

I have tried a lot to figure out if i can hide the Order from the backend, but i could not find a setting for it anywhere. So i am now looking forward to use a hook, to hide it. I also checked the field level structure using Devel module and dpm($form); but i have no idea on how to accomplish this. Can anyone help me?
Comment: Just use CSS to hide that.
Answer: Well, as Rupesh suggested in his comment, i was able to use CSS for hiding the Order column in my form:
First, i specified an ID for the fieldset field in my module's node_form_alter() function:
$form['field_user_details']['#attributes'] = array('id' => 'user_details');

Then in my CSS, i used these lines to hide the Order column:
#user_details table th:nth-child(2) { display: none; } /* Hide the Order column Label */
#user_details table td.delta-order { display: none; } /* Hide the Order column */


Visual Studio C# grammar/sentence structure-checking method

Question: I'm working with C# in Visual Studio. I need an object to which I can send a String containing an English sentence. I need the object to have a method that will tell me if my English sentence has any grammar/structure errors.
Think of the spell/grammar checker in MS Word. Any grammar/structure errors will be underlined by a green line. I need to determine if any arbitrary sentence would have a green underline if it were written in MS Word.
If such a thing exists it may look like this:
checkGrammar("Arbitrary sentence");   //returns true/false based on being      correct or not.

I have looked for something like this but all my search efforts are dominated by results for a Visual Studio Spell Checker which checks your actual code....not what I need.
Does anyone know if such a thing exists in C#?
Thanks in advance for any help.
Comment: The linked "duplicate" is NOT a duplicate of this question. it only deals with spellcheck and is specific to winforms.
Comment: Visual Studio isn't a programming language, try "C# Spell Checker" https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=c%23%20spell%20checker
Comment: @BradleyUffner The OP states `would have a green underline`, which sounds like they're using WinForms or WPF, and one of the answers to the duplicate target detail how to use these functions elsewhere (e.g, WPF).
Comment: @AStopher, it's still NOT a duplicate, as it only mentions spelling and this is specific to spelling AND grammar.
Comment: @BrainSlugs83 Really not sure why you're pinging me about a comment I wrote almost five years ago, but one of the answers on the duplicate target _did_ detail (or still does, I haven't checked) how to use those functions elsewhere. I never implied the question was a duplicate, simply that one of the answers in the duplicate target might be helpful.
Comment: @AStopher Ahh, apologies, I wasn't looking at the dates.
Answer: You may be able to use Word's Grammar checker grammatically if you can be sure it will be installed on the computer running the program.
Documentation
Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();

return word.CheckGrammar("String to check");


Loss probability and VaR

Question: I would like to estimate Value-at-Risk analytically and through delta-gamma aproximation. I don't know if my idea is ok, but i would like to build a portfolio of European option. Suppose that in this moment ($t=0$) investor buying a option with strike price $K=55$, current price of derivative is $S_0=50\$$, $T=1$ (year), $r=5\%$ and $\sigma=30%$. I use Black-Scholes formulas so I can compute
$$S_T=S_0 \exp \left( \left(r-\frac{1}{2}\sigma^2 \right)t+ \sigma\sqrt{T}Z \right),$$
where $Z \sim \mathcal{N}(0,1)$. Any ideas what next? In my opinion, I should use Black-Scholes formula to calculate the price of European call option, so the loss is
$$L=-\Delta V=-(e^{-rT}C_T -C_0 ).$$
But there is $d_1$ and $d_2$ and I don't know which price and time I should use.
Maybe someone explain it to me?
Comment: Perhaps better asked at quant.stackexchange
Answer: Here is a link that you can refer to caculate VAR under different methods.  While I tried to answer this question, I clarified my doubts. I decided I shall direct you to this site than answer the question directly. Seems like a reasonable start for Delta Normal, Delta Gamma.  Nothing complicated. They have given the excel sheet and plough through it to get nitty gritty details on the implementation on a portfolio of stocks and options.
http://quantitative-finance-by-examples.com/Value-at-Risk-Model-II.html
Goodluck

Loss probability and VaR


How to create a QueueWorker and run it without cron

Question: Can someone please help me with an example on how to create a QueueWorker class, add items, and run it inside hook_ENTITY_TYPE_presave() or anywhere in a module file?
Basically, what I want is adding an item to the queue and run it soon after a node save, without waiting until the next cron runs.
Comment: Let's ask: Why you need to queue it when you want it to run immediately?
Comment: You should be able to extract what you need from [`Cron::processQueues()`](https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Cron.php/function/Cron%3A%3AprocessQueues/9)
Comment: The hook you want is probably `hook_ENTITY_TYPE_insert()`, which runs after successful node save.  `hook_ENTITY_TYPE_presave()` is run before save and will be run even if the save fails.
Comment: @PatrickKenny Main thing I'm after is a good example on how to run the queueworker from the hook. I created the QueueWorker and added an item, but, I'm not sure how to programmatically run it from  `hook_ENTITY_TYPE_insert()`
Comment: Thanks @Clive it was helpful. Fair question @leymannx. I have some business logic inside `hook_ENTITY_TYPE_presave()` which require me to save a node from one content type when updating another content type node. When I try to save the other node inside the `hook_ENTITY_TYPE_presave()` with `$other_entity->save()` it simply doesn't save it. That's when I thought maybe queueing it and claiming the queue would be the best thing to do.
Answer: What you probably want is a different kind of queue worker. See https://mglaman.dev/blog/flush-and-run-using-kernelterminate-improve-page-speed-performance
A simple example:
/src/EventSubscriber/TaskOnTerminateSubscriber.php
<?php

namespace Drupal\mymodule\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\TerminateEvent;
use Symfony\Component\HttpKernel\KernelEvents;

/**
 * A subscriber running a task by request
 */
class TaskOnTerminateSubscriber implements EventSubscriberInterface {

  /**
   * TRUE if a task run is requested.
   *
   * @var bool
   */
  protected $runTask = FALSE;

  /**
   * Request a task run
   */
  public function runTask() {
    $this->runTask = TRUE;
  }

  /**
   * Run task if requested.
   *
   * @param \Symfony\Component\HttpKernel\Event\TerminateEvent $event
   *   The Event to process.
   */
  public function onTerminate(TerminateEvent $event) {
    if ($this->runTask) {
      // replace this with your long-running task
      sleep(10);
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    return [KernelEvents::TERMINATE => [['onTerminate', 150]]];
  }

}

mymodule.services.yml
services:
  mymodule.task_on_terminate_subscriber:
    class: Drupal\mymodule\EventSubscriber\TaskOnTerminateSubscriber
    tags:
      - { name: event_subscriber }

Trigger the task in hook_ENTITY_TYPE_presave/insert/update:
\Drupal::service('mymodule.task_on_terminate_subscriber')->runTask();

runTask() could contain arguments, like the entity ID. You can also make the service store multiple tasks in an array class property, which would then be a queue stored in memory processed right after the response is flushed to the client.


How to stop speaking in multithreading?

Question: I have a form that is displaying a message box and at the same time started a new thread that speaks the same message.
What I want to achieve is to stop the thread speaking the message as soon as I click OK button on the message box.
I have tried killing the thread using the abort command as soon as I click OK on the message box but the SPEAK process still keeps speaking the whole message even the message box goes away.
I assume that the new thread is being killed by the abort command but the speak process might be using some player to speak the message and that player is not being stopped. Any help will be greatly appreciated.
Here is the code:
Imports SpeechLib

Public Class Form1

    Public voice As SpVoice = New SpVoice()
    Public speak As Boolean = True

    Private Sub btnOK_Click(sender As Object, e As EventArgs) Handles btnOK.Click

        Dim t1 As New Threading.Thread(AddressOf THREAD)
        t1.IsBackground = True
        t1.Start()
        MessageBox.Show("Data has not been saved yet. Are you sure you want to quit with out saving the chandes?")
        t1.Abort()

    End Sub

    Public Sub THREAD()

        If (speak = True) Then

            voice.Speak("Data has not been saved yet. Are you sure you want to quit with out saving the chandes?")

        End If

    End Sub

End Class

Answer: First you should start an asynchronous speech by specifying:
SpeechVoiceSpeakFlags.SVSFlagsAsync

Then you could stop the speech using Skip:
voice.Skip("Sentence", Int32.MaxValue)

This gives:
Imports SpeechLib

Public Class Form1

    Public voice As SpVoice = New SpVoice()
    Public speak As Boolean = True

    Private Sub btnOK_Click(sender As Object, e As EventArgs) Handles btnOK.Click

        Dim t1 As New Threading.Thread(AddressOf THREAD)
        t1.IsBackground = True
        t1.Start()
        MessageBox.Show("Data has not been saved yet. Are you sure you want to quit with out saving the chandes?")
                    voice.Skip("Sentence", Int32.MaxValue)

    End Sub

    Public Sub THREAD()

        If (speak = True) Then

            voice.Speak("Data has not been saved yet. Are you sure you want to quit with out saving the chandes?", SpeechVoiceSpeakFlags.SVSFlagsAsync)

        End If

    End Sub

End Class

Hope this helps.
Comment: Your solution work is fine. Your help is greatly appreciated.
Comment: I have another question. I want to achieve a form explode effect.
Comment: The form should display at the minimum size possible to 800 by 600 pixels. I m using the following code its not showing the way i want to do to show
Answer: you can abort thread by calling
t1.Abort()

Comment: It is already present in my code. Abort command does not stop the voice speaking the whole message. I need a command to stop the voice as soon as i click on the OK button on the message box.

How to stop speaking in multithreading?


How to configure JVM memory settings in Bluemix?

Question: I am using Cloud Foundry on Bluemix, and my app is constantly running out of metaspace. I am using OpenJDK 1.8 buildpack (https://github.com/cloudfoundry/java-buildpack.git), which has a default metaspace setting of 64M.
How do I configure and tune the JVM's memory settings to give it more metaspace?
Thanks
Patrick
Answer: I was digging into the java buildpack and ran into an issue on github that described the fix.  You need to set it with the following for 128m.
<code>cf set-env appname JBP_CONFIG_OPEN_JDK_JRE '[memory_calculator: {memory_heuristics: {heap: 70, metaspace: 15, native: 10, permgen: 15, stack: 5}, memory_sizes: {metaspace: 128m}}]'
</code>


Partial Fraction Decomposition with an irreducible denominator

Question: How can you use PFD (Partial Fraction Decomposition) to solve this integration problem? I can normally do these fine with denominators that factor, but this one doesn't seem to be able to do that.
$$
\int_0^2\frac{2x^2+x+8}{x^4+8x+16} \mathrm{d}x
$$
Could I set it up as $\displaystyle\frac{Ax^3+Bx^2+Cx+D}{x^4+8x+16}$ and then find the values of $A$,$B$,$C$, and $D$ to complete the integration?
Comment: Perhaps it's a typo and should be $x^4 + 8x^2 + 16 = (x^2+4)^2$.
Comment: Yes, you could; and the answer you'll get is $A=0$, $B=2$, $C=1$, and $D=8$; that is, you will just rewrite what you did. **However:** over the real numbers, **any** polynomial of degree greater than 2 must factor. Your polynomial *does* factor. It factors as a product of two irreducible quadratics.
Comment: You could set it up as described but the only thing you will find is A=0,B=2,C=1,D=8 so you're back to square one.I belive @BillDubuque is right and it's a typo.
Answer: Hint: assuming the denominator should be $(x^2+4)^2,\:$ rewrite the numerator as $\rm\:2\:(x^2+4) + x$. Then each summand/denom integrates easily, viz. an arctan + rational function.
Almost surely this was what was intended since the numerator has form that enables said easy partial fraction decomposition when the denominator is as speculated.


Can't use default inequality operator inside structure member function

Question: Consider slightly modified example from cppreferenece.com using default comparisons:
struct Point
{
    int x;
    int y;

    auto operator<=>(const Point&) const = default;
    //bool operator!=(const Point&) const = default;

    bool isDifferent(const Point& another) const
    {
        // Fails without explicit operator !=
        return operator != (another);
    }

    bool isSame(const Point& another) const
    {
        // Always OK
        return operator == (another);
    }
};

int main()
{
    Point pt1{1, 1}, pt2{1, 2};

    std::cout << std::boolalpha
        << (pt1 == pt2) << ' '  // Always OK
        << (pt1 != pt2) << ' '  // Always OK
        << (pt1 <  pt2) << ' '
        << (pt1 <= pt2) << ' '
        << (pt1 >  pt2) << ' '
        << (pt1 >= pt2) << ' ';
}

https://godbolt.org/z/dq56T3ssG
Here function that uses equality operator compiles fine. Other function that uses  inequality operator fails with "operator not defined" error. However if inequality operator used outside of member function everything works fine.
Question: Why this is happening and is there way to not define inequality operator and use it inside member function?
Answer: C++20 does not define operator != for you. What it does is that, when you use the != operator, if no matching operator != function exists (it's more complex than that, but nevermind that now), it can rewrite your code to call operator == and negate the result. And operator == is a real function generated by defaulting operator <=>.
However, you are not using the != operator. You are asking to call the function named operator !=. There is no such function, hence the error.
If you want to get the rewriting behavior, you need to use the actual != operator.
Comment: @uni: No, it's not a function. The compiler "invisibly" turns `*this != another` into `!(*this == another)`.
Comment: @uni just FYI, you don't need the parenthesis around `another`: `return *this != another;`
Comment: I see! It really is a function. So when I change it to `return *this != (another);` it compiles fine


Como modificar o último item de uma sequência em Java?

Question: Gente, nem sei se essa é a pergunta para dúvida que tenho, mas vamos lá...
Quero obter a seguinte saída: "V V V V V!".
Primeiro criei um algoritmo simples apenas para simular a saída, sem ponto de exclamação no final da saída:
public static void main(String[] args){

    int N, i;
    Scanner ler = new Scanner(System.in);

    N = ler.nextInt();
    for(i = 0; i < N; i++){
        System.out.print("V ");
    }
}

Alguém pode me ajudar e me dar uma sugestão de como fazer esse ponto de exclamação no final da saída?
Desde já, muito obrigada!
Answer: Uma forma bem simples de resolver é com uma condição dentro do for, que escreve o elemento seguido de:

Espaço caso não seja o ultimo
! caso seja o ultimo

Exemplo:
for(i = 0; i < N; i++){
    System.out.print("V" + (i < N - 1 ? " " : "!"));
}

Saída para N de 5:
V V V V V!

A condição i < N - 1 indica se o elemento não é o ultimo, e por isso escreve o " ".
Também consegue resolver sem utilizar uma condição dentro do for. Para isso pode alterar o limite dele para que vá até penúltimo elemento, e escreve o último manualmente:
for(i = 0; i < N - 1; i++){
    System.out.print("V ");
}
System.out.println("V!");

O for agora vai até ao penultimo devido ao i < N - 1, imprimindo os elementos seguidos de espaço, sendo que o ultimo é impresso fora do for.
No entanto, desta forma o N não pode ser 0, pois irá imprimir V!. Caso queira permitir que o N possa ser 0 tem que escrever o V! dentro de um if (n > 0).
Veja esses dois exemplos no Ideone
Comment: Obrigada! As duas soluções deram muito certo! Utilizei a segunda. Até mais!
Answer: Você pode criar uma String a adicionar os "V" nela e depois adicionar o ponto.
Assim:
N = ler.nextInt();
String str = "";

    for(i = 0; i < N; i++){
        srt = str.append("V ");
        System.out.print("V ");
    }

str = str.append("!");
System.out.println(str);


Compact vs. Linearly Compact

Question: Definition 1: A topological $R$-module $M$ is linearly compact in case every collection of closed linear varieties in $M$ with the finite intersection property has a nonvoid intersection (Daniel Zelinsky, Linearly Compact Modules and Rings). The phrase linear variety in $M$ to mean a coset of a submodule of $M$.
In topological group, we have every open subgroup is a closed subgroup.
Question 1: Can we restate Definition 1 as:
Definition 1': A topological $R$-module $M$ is linearly compact in case every collection of open linear varieties in $M$ with the finite intersection property has a nonvoid intersection?
Question 2: Why does it use closed linear varieties in a module like an open cover of $M$ in the definition of compact space? How do closed linear varieties in $M$ with the finite intersection property cover $M$?
Question 3: What is the motivation for a linearly compact module? Why, in topological algebra, are many authors interested in linearly compact space rather than compact space for topological modules?
Thank you in advance for considering my questions.
Comment: I have no background in the subject of your post, however it seems that the definition of linear compacity is based on this characterisation of compact spaces with the [finite intersection property](https://en.wikipedia.org/wiki/Finite_intersection_property#Compactness) rather than the definition of compact spaces with open covers.
Answer: I am not an expert in the area, but let me try to give you some answers.

Your definition is not equivalent to the original definition. First of all, even though open subgroups are closed, the converse is very rarely true. Take for example the trivial subgroup $\lbrace 0\rbrace$, which is only open in discrete subgroups.
Further, linear varieties are very rarely subgroups anyway - a non-trivial coset of the subgroup $H<G$ would have the form $a+H$ for $a\in G\setminus H$, so in particular $0\notin a+H$. I haven't been able to cook up a concrete counter-example off the top of my head, but I imagine it is doable.

The intersection property is related, but not completely analogous, to the open cover property. In particular, the linear varieties shouldn't constitute an open cover of the module. See 3) for how they are related.

Firstly, being linearly compact is a weaker property than being compact, and thus more flexible. If you follow Bruno B's link, you will see that being compact is equivalent to having the finite intersection property for any collection of closed subspaces, so in particular also for linear varieties. The true reason for introducing this notion and the needed flexibility, rather than working with compact modules, is rather deep. See Tom Leinster's blog post https://golem.ph.utexas.edu/category/2012/09/where_do_linearly_compact_vect.html, as well as his question on stack-overflow https://mathoverflow.net/questions/104777/what-are-the-algebras-for-the-double-dualization-monad/104845#104845. In essence, it is about finding the types of object that parallels compact spaces in the module setting - and here translating it directly to compact modules becomes too restrictive.

Compact vs. Linearly Compact


Dead notes mixed in with other notes or Chords

Question: I'm having trouble understanding a tab I'm trying to learn.
<code>E |---------------------------------------------------------|
B |---------------------------------------------------------|
G |--11----11----11---11----11------------------------------|
D |--9-----9-----9-----9----9-------------------------------|
A |--x-----x-----x-----x----x-------------------------------|
E |--7-----7-----7-----7----7-------------------------------|
</code>
What I don't understand are the dead notes mixed in with the notes. I see this pretty often and when I try to play it, it feels wrong, like i'm going against what i've learned by having one dead note with the other clearer notes.
Am I doing something wrong or is this just normal?
Answer: Chords with dead note are a common part of plectrum based guitar playing (but not so much with fingerstyle.
Hendrix himself, instead of playing barre chords, would wrap his thumb over top of the neck and play the following shape
<code>-x--
-5--
-6--
-7--
-x--
-5--
</code>

Now, I'm not saying that you should use that chord shape, it really depends on the shape of your hand, for a lot of people it isn't comfortable.
My point is though, when have you ever listened to a hendrix record and though "man, those muted notes really sound bad"?  By including muted strings in your chords, it actually opens you up to playing a set of chord voicings that would otherwise be impossible.  And you really don't notice the muted note in the sound if muted correctly.
A chord like:
<code>-x--
-6--
-5--
-4--
-x--
-4--
</code>
would be impossible without playing muted notes, and that would be a real shame.
And if you think "but won't that have a really harsh, aggressive sound?", listen to wes montgomery playing in octaves (as many muted notes as played ones!):
Answer: The problem with guitar is that when several adjacent strings are strummed together, it's difficult not to hit all of them. There are, in some cases, a string for which no note can be fretted to sound good with the rest. Therefore, it needs to be muted, by a finger already on an adjacent string that is being played. Thus, the x means do not let this particular string sound.
Although in this case, the 5th string could be fretted at 9, to produce an octave lower than the 3rd string note. Probably the tab writer just didn't want that note in the chord, a B5.


Slow finishing when cat a large file of null content

Question: The shell command:

truncate -s 1000000000 largefile
echo 'eof' >> largefile
cat largefile

Why the last command blocks for several seconds after `eof' being printed?
Comment: I tested it in Centos 6.4 with its terminal application(resides in System Tools).
Answer: cat doesn't just block - it is very busy reading and writing one billion zero bytes.


UITextField does not receive text changes

Question: we have a simple UITextField which lies on a second UIWindow. Touching it will correctly make it the first responder and a keyboard will be shown. However, no touched key, but the backspace, fires the textField:shouldChangeCharactersInRange:replacementString:. Every other UITextFieldDelegate method is being correctly fired.
The textfield is created in an Interface Builder and it is not subclassed. Nothing seem to be stealing a first responder.
The bug occurs only on an iPhone 3GS, iOS 6.1.6.
Answer: Apparently, only the key window does get the changes from a first responder. It is as simple as to call makeKeyWindow on the appropriate window.
From the documentation:
Makes the receiver the main window.

Comment: Still not sure why this was an issue for iOS 6 only. 3GS seems to not be as relevant here, since we don't have any other phone with iOS 6. Perhaps an unfortunate bug on Apple side?


intellij idea generate persistence mapping have no foreign key

Question: I use Intellij idea 15 generate persistence mapping to auto generate Entity code but there is no foreign key like @ManyToOne() or @OneToMany, so I think there must something wrong. thanks
Answer: In Intellij IDEA 16 If we are just checking the tables of which entity we have to make in the persistence tool window it doesn't include the foreign key relationships. So go in the drop down of all the tables and manually check all the relationship you wants to include and then try to generate the entities. It works for me.
Comment: Just what I was looking for! Is there a way to select all automatically?


Prove that if $A \subseteq [0,\infty)$ and $B \subseteq (-\infty,0]$, then $\sup(AB) = \sup{B} \inf{A}$

Question:
Prove that if $A \subseteq [0,\infty)$ and $B \subseteq (-\infty,0]$, then $\sup(AB) = \sup{B} \inf{A}$. Note: Assume $A,B$ are nonempty subsets of $\mathbb{R}$ and $\alpha \in \mathbb{R}$ and define $\alpha A = \{\alpha A | a \in A\}$.

I don't believe this result is true. Firstly, let $B \subseteq [0,\infty)$ and $A$ as defined in question. Then $\sup(A \cdot -B) = \inf{A}\inf{-B} = -\inf{A}\sup{B}$, while on the other hand, $\sup{-B}\inf{A} = -\inf{B}\inf{A}$ which means that if both sides are equal then $\sup{B} = \inf{B}$, contradiction.
Comment: You have a _very_ low acceptance rate on your posts. I suggest that you go through your old posts and accept as many answers as you feel have accurately answered your questions. Leaving questions unanswered is very poor form as a user of this site as it causes questions which have acceptable answers to be bumped by Community unnecessarily.
Comment: @Puzzled417 Agreed. Please see what Cameron wrote.
Comment: Leaving questions without acceptances* Not sure where my head was on that one.
Comment: @Puzzled417 Can you justify your claim that $\sup(A\cdot -B) = \inf A \inf -B$?  $A$ is non-negative but $-B$ is non-positive.
Comment: @ErickWong Sorry, that's wrong what I have. What I meant was $\sup{A \cdot -B} = -\inf{A} \cdot \inf{B}$.
Comment: @Puzzled417 I believe you now have enough to answer your own question.  You can even accept it :)
Answer: Let $A,B \in [0,\infty)$. Then $\sup(A\cdot -B) = -\inf{A} \cdot \inf{B}$ while $\sup{-B} \inf{A} = -\inf{B} \inf{A}$, as desired.


Fourier Sine Transform

Question: There is a question from my book which I find hard. Here it goes:

Consider
  $$\frac{\partial u}{\partial t}=k\frac{\partial^2 u}{\partial x^2}-v_0\frac{\partial u}{\partial x} \quad\quad(x>0)$$
  $$u(0,t)=0$$
  $$u(x,0)=f(x)$$
  Show that the Fourier sine transform does not yield an immidiate solution

Am I correct saying the Sine transform is as follows?:

$$\frac{\partial \bar{U}}{\partial t}=k\left.(\frac{2}{\pi}\omega f(0)-\omega^2\bar{U}\right.)+v_0\omega C[f]$$

Thnx in advance
Comment: What is the meaning of "does not yield an immidiate solution" in this question claimed?
Comment: I think an immidiate solution means a solution which can be made with little steps and such that you only need to plug the values of the constants in order to get a physical answer
Answer: When applying Fourier sine transform on $t$ , the term of $\dfrac{\partial u}{\partial t}$ will relate to Fourier cosine transform rather than that of Fourier sine transform; when applying Fourier sine transform on $x$ , the term of $\dfrac{\partial^2u}{\partial x^2}$ will relate to Fourier sine transform but the term of $\dfrac{\partial u}{\partial x}$ will relate to Fourier cosine transform rather than that of Fourier sine transform. So we cannot solve this PDE by Fourier sine transform unless $v_0=0$ . The statement of this question stated is partially correct.
Separation of variables has no such problem, as the concept of separation of variables is to choose the most suitable kernel transform type according to the solution forms of the ODEs separated rather than applying fixed kernel transform type.
Case $1$: $\text{Re}(kt)\geq0$
Let $u(x,t)=X(x)T(t)$ ,
Then $X(x)T'(t)=kX''(x)T(t)-v_0X'(x)T(t)$
$X(x)T'(t)=(kX''(x)-v_0X'(x))T(t)$
$\dfrac{T'(t)}{T(t)}=\dfrac{kX''(x)-v_0X'(x)}{X(x)}=-\dfrac{4k^2s^2+v_0^2}{4k}$
$\begin{cases}\dfrac{T'(t)}{T(t)}=-\dfrac{4k^2s^2+v_0^2}{4k}\\kX''(x)-v_0X'(x)+\dfrac{4k^2s^2+v_0^2}{4k}X(x)=0\end{cases}$
$\begin{cases}T(t)=c_3(s)e^{-\frac{t(4k^2s^2+v_0^2)}{4k}}\\X(x)=\begin{cases}c_1(s)e^{\frac{v_0x}{2k}}\sin xs+c_2(s)e^{\frac{v_0x}{2k}}\cos xs&\text{when}~s\neq0\\c_1xe^{\frac{v_0x}{2k}}+c_2e^{\frac{v_0x}{2k}}&\text{when}~s=0\end{cases}\end{cases}$
$\therefore u(x,t)=\int_0^\infty C_1(s)e^{\frac{2v_0x-t(4k^2s^2+v_0^2)}{4k}}\sin xs~ds+\int_0^\infty C_2(s)e^{\frac{2v_0x-t(4k^2s^2+v_0^2)}{4k}}\cos xs~ds$
$u(0,t)=0$ :
$\int_0^\infty C_2(s)e^{-\frac{t(4k^2s^2+v_0^2)}{4k}}ds=0$
$C_2(s)=0$
$\therefore u(x,t)=\int_0^\infty C_1(s)e^{\frac{2v_0x-t(4k^2s^2+v_0^2)}{4k}}\sin xs~ds$
$u(x,0)=f(x)$ :
$\int_0^\infty C_1(s)e^{\frac{v_0x}{2k}}\sin xs~ds=f(x)$
$\int_0^\infty C_1(s)\sin xs~ds=f(x)e^{-\frac{v_0x}{2k}}$
$\mathcal{F}_{s,s\to x}\{C_1(s)\}=f(x)e^{-\frac{v_0x}{2k}}$
$C_1(s)=\mathcal{F}^{-1}_{s,x\to s}\left\{f(x)e^{-\frac{v_0x}{2k}}\right\}$
$\therefore u(x,t)=\int_0^\infty\mathcal{F}^{-1}_{s,x\to s}\left\{f(x)e^{-\frac{v_0x}{2k}}\right\}e^{\frac{2v_0x-t(4k^2s^2+v_0^2)}{4k}}\sin xs~ds$
Case $2$: $\text{Re}(kt)\leq0$
Let $u(x,t)=X(x)T(t)$ ,
Then $X(x)T'(t)=kX''(x)T(t)-v_0X'(x)T(t)$
$X(x)T'(t)=(kX''(x)-v_0X'(x))T(t)$
$\dfrac{T'(t)}{T(t)}=\dfrac{kX''(x)-v_0X'(x)}{X(x)}=\dfrac{4k^2s^2-v_0^2}{4k}$
$\begin{cases}\dfrac{T'(t)}{T(t)}=\dfrac{4k^2s^2-v_0^2}{4k}\\kX''(x)-v_0X'(x)-\dfrac{4k^2s^2-v_0^2}{4k}X(x)=0\end{cases}$
$\begin{cases}T(t)=c_3(s)e^{\frac{t(4k^2s^2-v_0^2)}{4k}}\\X(x)=\begin{cases}c_1(s)e^{\frac{v_0x}{2k}}\sinh xs+c_2(s)e^{\frac{v_0x}{2k}}\cosh xs&\text{when}~s\neq0\\c_1xe^{\frac{v_0x}{2k}}+c_2e^{\frac{v_0x}{2k}}&\text{when}~s=0\end{cases}\end{cases}$
$\therefore u(x,t)=\int_0^\infty C_1(s)e^{\frac{2v_0x+t(4k^2s^2-v_0^2)}{4k}}\sinh xs~ds+\int_0^\infty C_2(s)e^{\frac{2v_0x+t(4k^2s^2-v_0^2)}{4k}}\cosh xs~ds$
$u(0,t)=0$ :
$\int_0^\infty C_2(s)e^{\frac{t(4k^2s^2-v_0^2)}{4k}}ds=0$
$C_2(s)=0$
$\therefore u(x,t)=\int_0^\infty C_1(s)e^{\frac{2v_0x+t(4k^2s^2-v_0^2)}{4k}}\sinh xs~ds$
$u(x,0)=f(x)$ :
$\int_0^\infty C_1(s)e^{\frac{v_0x}{2k}}\sinh xs~ds=f(x)$
$-i\int_0^\infty C_1(s)\sin ixs~ds=f(x)e^{-\frac{v_0x}{2k}}$
$\int_0^\infty C_1(s)\sin xs~ds=if(-ix)e^{\frac{iv_0x}{2k}}$
$\mathcal{F}_{s,s\to x}\{C_1(s)\}=if(-ix)e^{\frac{iv_0x}{2k}}$
$C_1(s)=\mathcal{F}^{-1}_{s,x\to s}\left\{if(-ix)e^{\frac{iv_0x}{2k}}\right\}$
$\therefore u(x,t)=\int_0^\infty\mathcal{F}^{-1}_{s,x\to s}\left\{if(-ix)e^{\frac{iv_0x}{2k}}\right\}e^{\frac{2v_0x+t(4k^2s^2-v_0^2)}{4k}}\sinh xs~ds$
Comment: I do not understand the justification for using separation of variables here.
Comment: Doraemonpaul can you explain why the sine-transform of this function gives a problem? You just solved it, but that was not the question.

Fourier Sine Transform


Como deletar um nodo em uma lista encadeada em Java?

Question: Tenho o seguinte código em java mas não está funcionando corretamente. Necessito deletar um nodo de uma lista encadeada. Alguém me ajuda?
     /*
      Delete Node at a given position in a linked list
       head pointer input could be NULL as well for empty list
         Node is defined as
        class Node {
         int data;
         Node next;
     }
     */

   // This is a "method-only" submission.

   // You only need to complete this method.

    Node Delete(Node head, int position) {
    // Complete this method
    int cont=1;
    Node tmp=head;
    if(head==null)
    {
    return null;
    }
   if(position==0)
    {
    Node prox= head.next;
    head=prox;
    return head;
  }
  Node tmp=head;
  Node tmp2=head.next;
  while(cont<position)
  {
   tmp=tmp2;
    tmp2=tmp2.next;
    cont++;

 }
 tmp.next=tmp2.next;

 return head;
 }

Answer: Acho que assim deve funcionar:
public static Node delete(Node head, int position) {
    if (head == null) return null;
    if (position == 0) {
        Node prox = head.next;
        head.next = null;
        return prox;
    }

    int cont = 1;
    Node tmp = head;
    Node tmp2 = head.next;

    while (cont < position) {
        tmp = tmp2;
        tmp2 = tmp2.next;
        cont++;
    }
    tmp.next = tmp2.next;
    tmp2.next = null;
    return head;
 }

Havia um erro de compilação porque você declarava tmp duas vezes. Havia duas linhas Node tmp=head;.
Outra diferenças é que eu faço o nó retirado deixar de apontar para algum ponto no meio da lista ao fazer noRetirado.next = null;. Isso ajuda o coletor de lixo e faz com que se houver uma referência ao nó retirado, que ela não possa ser usada para bagunçar com o restante da lista de onde ele foi tirado.
Também mudei o local onde algumas variáveis são declaradas para declará-las somente quando forem se fazer inevitavelmente necessárias.
Comment: @YODA Deletaria a posição 0, ou seja, o primeiro nó da lista. Na verdade, ele separa a cabeça do resto e retorna o resto.
Comment: @YODA Ocorre que `head.next = null` faz com que o primeiro nó deixa de conhecer o segundo. Entretanto, o segundo não é perdido porque a referência a ele havia sido armazenada em `prox`, que é o que é retornado.
Comment: Obrigado Victor ! Mas tive uma duvida no primeiro if, você colocou head.next= null ... isso não deletaria a posição 1?