Extracting the matched string found System.Text.RegularExpressions.Regex.IsMatch

Question: I am new to C#. I am able to deternine if the string is found in a input record using the following code but I need to extract the found string (it should also contain some addtional characters) so that I can see what I have found, because I am doing a partial search.
For example I am looking "NY" in a string which will carry city names. I should be able to get for example"New york" (Don't mind few more letters but at least I will be able to see what I found). Here is the code I am using for searching a string.
 if (System.Text.RegularExpressions.Regex.IsMatch(CityNames, CheckName, System.Text.RegularExpressions.RegexOptions.IgnoreCase))
                {
                    MessageBox.Show("String Found");

                }
                else
                {
                    MessageBox.Show("String Not Found");

                }

Answer: Use the Match method to find the match, the Success property to see if it found anything, and the Value property to get the matched string:
Match m = Regex.Match(CityNames, CheckName, RegexOptions.IgnoreCase);

if (m.Success) {
  MessageBox.Show("String Found: " + m.Value);
} else {
  MessageBox.Show("String Not Found");
}

Comment: @user2026794: Add `using System.Text.RegularExpressions;` at the top of the file. Or right click on the word and select to include the namespace.
Comment: I am only getting NY for m.value I need to get lets say 15 characters from the found string position. Thanks
Comment: @user2026794: Use a pattern that includes more characters, like `"NY.{1,13}"`. If that's not possible, you can use the index of the match to get part of the string: `CityNames.Substring(m.Index, 15)`;
Answer: check this code :
string CityNames = "N York";
string CheckName = @"(NY|New York|[^N-Y])";

System.Text.RegularExpressions.Match match = System.Text.RegularExpressions.Regex.Match(CityNames, CheckName, System.Text.RegularExpressions.RegexOptions.IgnoreCase);

if (match.Success)
{
    MessageBox.Show("String Found");
}
else
{
    MessageBox.Show("String Not Found");
}


Transposing the human voice

Question: I've been playing around with the pitch changer in Audacity. I noticed that when I change the key on instrumental music, while it may sound off, the timbre is mostly the same. In fact, it only sounds weird for pieces I've heard before since it conflicts with the key I remember; for new pieces, I can transpose it by half an octave and it will sound pretty normal. On the other hand, transposing a song with vocals by even 1 or 2 semitones will make a huge difference. Why is the human voice more sensitive to changes in pitch?
Another thing I've noticed is that in some cases, female voices modulated down a few semitones sound reasonably close to male voices and vice versa, but for other singers no amount of pitch change can make them sound like the other gender. For example, Taylor Swift (song: "You Belong With Me") down 3 semitones sounds somewhat like a tenor. On the other hand, Adele (song: "Someone Like You") down 1 semitone sounds like herself, down 2 semitones sounds in between male and female, and anything 3 or more sounds hideous. Train (song: "Hey, Soul Sister") up 3 semitones could plausibly be female. Elton John (song: "Can You Feel the Love Tonight?") still sounds male up to 3 semitones up, and anything more starts to sound chipmunk-like. What qualities in a singer's voice determine whether they sound like the other gender when transposed or not?
Answer: Vowels are formed using formants: the basic characteristic particularly of chest voice is a "pulse train" which has lots of harmonics/overtones.  Those harmonics are then amplified or dampened depending on the shape of the mouth.  The strongest surviving harmonics are called "formants".  Basically, one hears the mouth shape under the "lighting" of the voice box, and it remains recognizable under different "lighting conditions".
A deep chest voice has lots of harmonics and provides a clear picture of the formants.  Doubling its frequency doubles all the harmonics as well, painting a picture of a mouth or vocal tract half the original size.
Head voice has less pronounced harmonics, falsetto (and the somewhat equivalent female "flute voice") even less.  Vowels become harder to distinguish, both because of the higher fundamental pitch (leading to a more spread out spectrum of harmonics) and because of less pronounced overtones to shape.
With practice and control of the resonances and mouth shapes, one can "gender shift" a lot without actually employing electronics.  I can produce a distinctly female sounding singing voice solidly into the baritone range.
If you take a look at male travesty stars, they tend to speak with a flute-like voice in a low range and drop "out of character" into chest voice, usually without much of an actual pitch change, for comedic effect.
On rereading, I was missing sort of a conclusion: "resounding" voices in chest voice are the worst for pitch-shifting and the best for vowel recognition: they have good and distinguishable formants and paint a good picture of the relation of mouth size to speaking pitch.  Mouth cavity size changes less between male/female than fundamental pitch.  With singing voices, falsetto/head voice is less committed than resonant voices: "chanson-style" female singing is probably the female voice type with strongest chest voice components and will likely pitch-bend rather badly.  If you know you are singing for pitch-shifting, you can artificially precompensate with small/big mouth shapes (speaking from a "small mouth" in the front of your mouth by shaping with tongue and vellum, or speaking in a "hot potato" style).  The more distinctive your vowels are, the worse for pitch-shifting (not that having your mouth go all over the place when singing is a good idea, anyway, since directional effects amplify the effects of mouth shaping for the non-close listener).

Transposing the human voice


Editing image using double-loop (weight and height)

Question: I want to edit pixels around the middle of the picture and for that i need double loop of x and y each represents the height or weight of the image bitmap. This is an example:
for(x = 0; x < bm.getWeight(); x++)
{
    for(y = 0; y < bm.getHeight(); y++)
    {
        //
    }
}

The problem is that the method getPixles works as an array whose length is the weight*height and then the loop looks like that:
int [] pixels = new int [bm.getWidth() * bm.getHeight()];
for(x = 0; y < pixels.length; x++)
{
    //
}

I hope you guys understand what i am trying to explaing.
So is there a way to seperate it to a double loop or get the middle pixels with another way?
Thanks a lot ! :)
Answer: Try this:
int width = bm.getWidth();
int height = bm.getHeight();

int[] pixels = new int[width * height];
int curPixel;

for (int columnNum = 0; columnNum < width; columnNum++) {
    for (int rowNum = 0; rowNum < height; rowNum++) {
        curPixel = pixels[rowNum * width + columnNum];
        // do stuff with curPixel
    }
}


How can I reference images in my HTML document when the page is being accessed on disk?

Question: I created and deployed a webpage locally on my hard disk and found that nothing is working as I expected. All code for my website is structured in the following format:
default.html
images/tpc/....  [all images here]
js/              [all js file is here]
And my HTML looks something like this:

This is creating a problem, when another person open the default.html page from their own disk, I suppose the image links are getting referred to as:
file:///C:/images/tpc/slide-butn.png

Is there something I can do to resolve this issue?
Answer: Have you tried a relative URL?

Answer: Try to use relative path:
src="images/tpc/slide-butn.png"

(first slash omitted)
Answer: Most websites need to be tested using a webserver, not just opening random files. There may not necessarily be a way to "fix" it so that you can directly open the files. If a URL starts with "/", then it is relative to the domain on which the file is served, which may have a different effect than a relative URL, depending on what file the domain-relative URL appears on. My suggestion would be to develop  a standard mechanism for testing your website, such as a command that can start up a demo webserver in a similar configuration to that of the real website, or some shared testing server.
Note that even if you change everything to relative URLs, you will run into similar trouble when it comes to headers set by the webserver, cookies, any sort of dynamic or interpreted pages, mime types, etc.  at some point if you just open files rather than use a test web server, so might as well bite the bullet now.
Answer: You need to drop the leading slash and make the urls relative to the file save location.
For example, if your images are in a directory named images in the directory where your html file is, the correct url would be

This says you look in the images directory in the same directory as the file. With the leading slash, the browser will look in the root. Great great for a website, not so much for a local directory.
This post on relative and absolute urls should give you a better explanation.


Varied bass line and varied tune: What is the term used for this style?

Question: I've been looking for the term in English for this kind of gestures or ornamentations:
Figuration is understood in the music playing a melody in small note values, in contrast to an ornament.  The melody is figured, that means varied designed.  Figurations are unstressed intermediate or passing notes in the melody.  Because they are unstressed, it does not matter that they can be alien.  Intermediate or continuity tones can be diatonic (ladder-like, usually whole-tone-stepping) or chromatic (semitone-stepping and mostly non-conducting).  Alternating notes also occur as figurations, upper or lower and again diatonic or chromatic.  Similar to the melody-related change notes, there are also change chords.
In German this called figurierter bass and
figurierter sopran or descant. If all voices are treated like this we call it: figurierter Choral:
"Figurierter Gesang, Cantus figuratus, Italian Canto figurato, is the name given to the song in which figures appears, and it is opposed to the planned chorale singing, who does not have these notations.  The figures always consist of the main note, or the note which is actually required for harmony  and from other reds belonging to harmony. These figures occur in the foreground in the main voice;  and the others who serve her to accompany her have only singular sounds belonging to harmony.  Often it is also true that, as the main voice lasts one tone longer, one of the accompanying voices makes a figure on it.  Sometimes the figure sometimes even falls into the bass, which is then called a figurative bass (???) Figurierter Kirchengesang is the song that is decorated with the ornamental advice.  Thus the choir is figurated, if the cantus firmus is kept in one of the four main parts, but is accompanied by figurative voices, which make many imitations, or have, indeed, been set in the manner of joints.  In this way, the chorales of the church are projected forward, so that they can hear the melody and sing more easily.  "
Now I have learnt, that figured bass is what we call in German Generalbass.
So I wonder if there are equivalent terms to describe this style for this kind of treatment. Maybe figurative bass and figurative Chorale? Or is it just variation?
Comment: Is "chorale prelude" the English term you are looking for? https://en.wikipedia.org/wiki/Chorale_prelude
Comment: The Chorale preludes also contain this style - but the I could also accept the term "ritornell". What I am asking and looking form is the term for this kind of voice setting, not the forms, where they have been applied.
Answer: The generic English term variation can be used. It would include variations where figuration is applied to both the melody and the bass.
Just to confirm what we are talking about with music examples, Mozart K 265:
http://imslp.eu/files/imglnks/euimg/9/96/IMSLP188992-PMLP55775-Mozart,_Wofgang_Amadeus-NMA_09_26_06_KV_265_scan.pdf
Theme in mostly simple quarter note rhythm

Most of the variations involve figuration in only one of the voices, like treble...

...or in the bass...

...but the final variation uses sixteenth note figuration in both parts after the double bar...

In English "variation" would include rhythmic figuration in any of the voices.
I think I see the potential confusion between the German term figurierter bass and the English term figured bass.
You can capture the sense of figurierter bass in English with terms like ornamented bass, embellished bass, or just varied bass. The first two terms probably give a clearer sense the changes involve short note values (figuration or diminutions) than the generic term variation.
Also, I understand that diminution and division were used in English to mean variation by rhythmic subdivision, but that is an older usage. It is commonly used today.
https://en.wikipedia.org/wiki/Diminution#English_literature
Comment: I would agree with ornamented bass respectively descant and choral.  But I wouldn't post the Mozart Sonata as this kind of variations or something different than  I'm varied bass I'm thinking of.
Answer: I have found this differentiation:
Choralbuch Style (homophonic) and Choralgesang Style.

This shows that embellished or varied - like Michael Curtis  has proposed - would explain it fine. Actually I wonder why this Choralgesang style  is not called a figured bass instead of using (erroneously?) figured bass as synonym for  thorough bass.


Using Newtons Method for Asymptotic analysis Question

Question: I have the following question:
Suppose algorithm A is able to solve a computational problem with input size N=100 in 0.5ms (milliseconds).
If the algorithm has a running time $\in O(N \log_{2}N)$ then how large a problem can it solve in 1 minute?
My approach to the problem currently is as follows:
let $t = (0.0005s) = (0.5ms)$, then:
$\frac{t}{(100)log_{2}100} = \frac{(12*10^4)t}{(x)log_{2}x}$
where x is unknown input size that A can solve in 1 minute
this implies: $(x)log_{2}x = \frac{(100)log_{2}100(12*10^4)t}{t} = log_{2}100(12*10^6)$
now let $y = log_{2}x$ then the equation $(x)log_{2}x = log_{2}100(12*10^6)$ becomes:
$y2^y = log_{2}100(12*10^6) \Longrightarrow y2^y - log_{2}100(12*10^6) = 0$
Now at this point my plan is to use Newton's method for approximating roots (https://en.wikipedia.org/wiki/Newton%27s_method) to determine a solution for $y$ in the above equation.
Then once I have $y$ I just solve for $x$ (since $x = 2^y$)
My issue with this approach is the initial guessing I would have to make using Newton's method. I feel like there's no way to carry out this approach without using a calculator to calculate ridiculously large powers of 2 and that there must be a more elegant approach to this question. Is there a better approach I haven't explored yet?
Answer: Your approach makes sense. If you are applying Newton's Method programmatically, I would keep the original equation $x \lg x - M = 0$ where $\lg x = \log_2 x$. To guess the initial value, note that for large $M$ you also expect large $x$, and you certainly have $\lg x \le x$ so $x \le x \lg x \le x^2$ so $x_0 = \sqrt{M}$ is a good lower bound and $x_0 = M$ is a good upper bound. You can start with either one or their average.
In terms of the recurrence relation, we have $f(x) = x \frac{\ln x}{\ln 2} - M$ and $f'(x) = \frac{\ln x}{\ln 2} + \frac{1}{\ln 2} = \frac{1+ \ln x}{\ln 2}$ so
$$
\frac{f(x)}{f'(x)}
 = \frac{x \frac{\ln x}{\ln 2} - M}{\frac{1+ \ln x}{\ln 2}}
 = \frac{x \ln x - M\ln 2}{1+ \ln x}
$$
and the recurrence is
$$
x_{n+1} = x_n - \frac{f(x_n)}{f'(x_n)}
$$
which you can program in Python or MATLAB etc.


How to choose a threshold?

Question: One of the factors for my regression analysis is customer's familiarity with the store which equals 1 if the customer visited the store more than $N$ times and 0 otherwise. Is there a right way to choose $N$? For some $N$ this factor is statistically significant and for some not.
Comment: Must you choose a threshold $N$ at all?  Can you not study directly how the number of visits is related to the response?
Comment: You are encountering the substantive import of *aggregation bias* and the necessity of theoretical justification for aggregation. See for example, Gehlke, C. E. and Biehl, K. (1934). Certain Effects of Grouping Upon the Size of the Correlation Coefficient in Census Tract Material. *Journal of the American Statistical Association*, 29(185):169–170. Or possibly see, Openshaw, S. and Taylor, P. J. (1979). Statistical Applications in the Spatial Sciences, chapter A million or so correlation coefficients: Three experiments on the modifiable area unit problem, pages 127–144. *Pion*, London, UK.
Comment: @whuber A customer with 200 visits is not twice more familiar with the store than a customer with 100 visits.
Comment: Nobody is suggesting that.  The first order of business is to study how number of visits relates to the response, and then to incorporate the number of visits into the regression in a suitable fashion.  Forcing that number into a binary variable may be too Procrustean.
Comment: @whuber Thanks for your comments. Do you suggest to use the number of visits as it is as a factor?
Comment: Why not model the relationship using [nonparametric regression](https://en.wikipedia.org/wiki/Nonparametric_regression) on number of visits, thereby limiting *a priori* assertion of specific functional form relating *Y* and *X*? (within the limit of the number of smooths accommodated by the sample size and joint distribution, naturally). See, for example, Buja, A., Hastie, T., and Tibshirani, R. (1989). [Linear Smoothers and Additive Models](http://projecteuclid.org/download/pdf_1/euclid.aos/1176347115). *The Annals of Statistics*, 17(2):453–510.
Comment: @Alexis Thanks. I think it's too complicated for my needs.
Comment: It's no more complicated to use and interpret than linear regression. usually the syntax is along the lines of `npreg Y X`.
Answer: Don't discretize your predictor at all. This would amount to treating everyone with $0$ to $N$ visits exactly the same, and also treating everyone with $N+1, N+2, \dots, 2N, \dots, 1000N, \dots$ exactly the same - with a discontinuous step at $N$. This is almost certainly not a good reflection of reality. See this earlier thread for more information: What is the justification for unsupervised discretization of continuous variables?, in particular this page edited by Frank Harrell.
As you note, it makes little sense to include the number of visits "as is", as familiarity with the store will not scale linearly with the number of visits.
My recommendation would be to transform the number of visits using splines, e.g., restricted cubic splines or natural splines. A very good introduction can be found at the very beginning of Frank Harrell's Regression Modeling Strategies.
Comment: [A simpler model can perform better than a correct one](https://ideas.repec.org/a/for/ijafaa/y2016i40p20-26.html) because of the [bias-variance tradeoff](https://en.wikipedia.org/wiki/Bias%E2%80%93variance_tradeoff).
Comment: Thank your for your detailed explanation. How can I choose the spline knots? Isn't it the same problem as choosing $N$ in my original question?
Comment: I wouldn't say that it's the same as choosing $N$. Yes, it's a choice for a parameter. But the *consequences* are different: choosing a threshold makes your response discontinuous, but choosing spline knots only deforms a continuous response curve. ...
Comment: ... You would typically set the knots at specific quantiles of your observed number of store visits. Harrell has a rule of thumb table in his book. You can look at the default behavior of the `splines:ns()` function in R, [see this earlier thread](https://stats.stackexchange.com/q/7316/1352) or look [through earlier questions](https://stats.stackexchange.com/search?q=%5Bsplines%5D+knots+is%3Aq).
Comment: Thank you. By saying that choosing knots is the same that choosing the threshold I mean that it is also not related to the relation between familiarity and the number of visits. For example, the idea that this relation is not linear is not reflected there, right?
Comment: The nonlinearity will come in once you have transformed your original variable into a set of multiple spline regressors and fitted a model. The weighted sum of the spline regressors, weighted by the estimated coefficients, will be a nonlinear response function. Take a look at [the Wikipedia page](https://en.wikipedia.org/wiki/Spline_(mathematics)), or run the example in the help page for `splines::ns`.
Comment: Thanks. How the coefficients of `ns` can be interpreted?
Comment: Interpretation of spline coefficients is hard. Better to just calculate the matrix product between the spline regressors and the parameter estimates and plot this (the response function) against the number of visits.
Comment: Thanks again. Could you please be a bit more detailed? I just need to know if the corresponding factor has a statistically significant effect on the outcome.
Comment: Ah. In that case, I would recommend that you compare two models, e.g., using ANOVA or a likelihood ratio test. Model 1 would contain all your predictors *except* the number of visits (or any transform). Model 2 would contain all predictors *plus* the spline-transformed number of visits. Thus, Model 2 nests Model 1, and you can compare them using ANOVA or similar.
Comment: Thank you very much. Thus I can see the statistical significance and what about the direction of the effect? The signs of the spline coefficients? It's fine if they are equal but what if they aren't?
Comment: Even the signs are not overly helpful. The response function can curve up and down. Best to plot it and eyeball it.
Comment: Thank you. Then why on earth is linear regression still in use? No relation is purely linear...

How to choose a threshold?


Como importar projetos e módulos do Android Studio via Git

Question: Olá! Boa tarde. Sou estudante de bacharel em sistemas de informação e estou praticando o desenvolvimento para Android. Meu professor disponibilizou um link do Git contendo um "pack" de cada assunto abordado em suas aulas, separados por modulos/pastas. Como se o projeto presente no Git, fosse na verdade vários sub projetos(chamamos isso de Módulos, certo?).
Ele desenvolveu na IDE do Android Studio e o meu problema está sendo em importar este projeto pois parece que, durante a importação, a IDE não entende esses módulos como sendo aplicações separadas e acaba gerando bugs seja pelos arquivos manifests ou relacionados ao grande build.
A primeira questão é que não sei se devo importar a partir de um modelo existente ou a partir de um novo pois tanto uma opção, quanto outra, geram situações diferentes com erros diferentes.  De qualquer forma, estou bem enrolado com isso e gostaria de saber qual seria o passo a passo ideal para realizar esta importação
link do git: https://github.com/raphaelframos/devmov1
link das Screenshots tiradas: https://postimg.org/gallery/upws86ty/
Problema com migração para Grandle: https://s26.postimg.org/lw9yvc2t5/Sem_t_tulo.jpg
Comment: Você consegue nos enviar imagens dos passos que você está executando pra importar estes arquivos no Android Studio?
Comment: 1) https://s26.postimg.org/yzx5p21bt/Sem_t_tulo.jpg
2) https://s26.postimg.org/g3rh57zg9/image.jpg
3) https://s26.postimg.org/vqiqild89/image.jpg
4) https://s26.postimg.org/tzzph3vp5/image.jpg
Answer: Olá, primeiro você deve ter o GIT instalado em seu PC, você tem?
Se o projeto estiver em um link você pode fazer um "git clone" pela IDE (Android Studio) que possui um plugin nativo para controle de Versão, no caso GIT.
Se o projeto está subdividido em links diferentes você deve fazer o import, pra cada link diferente.
Caso o projeto seja subdividido em branches, você só precisa fazer um fork e submeter cada alteração em uma branch, atraves do "git pull"
Tenta se basear nesse link, que ele mostra passo a passo como proceder.
Link:
http://javapapers.com/android/android-studio-git-tutorial/
Comment: Opa! Eu tenho o Git instalado e já estou um pouco familiarizado com ele. Mas nesse caso específico, não estou sabendo importar pois está ocorrendo falhas. Temos diversos projetos ditos como módulos, dentro de um "todo". o link do meu git é esse: https://github.com/raphaelframos/devmov1 para você entender do que se trata.
Comment: Certo, você não consegue fazer "git clone https://github.com/raphaelframos/devmov1.git" ?
Comment: Depois de clonar o projeto TODO, você vai importar as partes (projetos) pela IDE
Comment: Consigo mas ele não gera o grandle build ou não sei explicar o que está acontecendo mas não está importando de maneira que a estrutura permaneça como deve ser no android studio. o link contendo as SS que tirei, pra entender melhor: https://postimg.org/gallery/upws86ty/
Comment: mas devo clona-lo a partir de um modelo existente ou um novo? e eu tentei ir adicionando modulo por modulo após a importação mas tive complicações de paths e tals. Realmente queria entender melhor para me expressar melhor aqui x.x
Comment: Ao clonar um projeto ele cria exatamente uma copia da estrutura definida no git. Recomendo você remover a existente e efetuar o clone novamente. Apos você clonar o projeto você deve abrir a IDE para importar dessa estrutura o projeto para você trabalhar. O Gradle é o gerenciador de dependências do Android, como o maven para projetos JAVA, então no Android Studio você deve ter uma opção para importar um Gradle Project. Apos importar a propria IDE vai organizar o projeto pra você.
Comment: Vou tentar aqui e te retorno
Comment: Não estou conseguindo resolver isso =\


checking whether the C compiler works... no when installing python 2.6 (mac os x lion)

Question: I'm trying to install python 2.6 using pyenv but when doing pyenv install 2.6.9I get the following:

checking MACHDEP... darwin
checking EXTRAPLATDIR... $(PLATMACDIRS)
checking machine type as reported by uname -m... x86_64
checking for --without-gcc... no
checking for gcc... gcc
checking whether the C compiler works... no
configure: error: in `/var/folders/r9/771hsm9931sd81ppz31384p80000gn/T/python-build.20150213191018.2121/Python-2.6.9':
configure: error: C compiler cannot create executables

I've installed Xcode 4.6.3 and installed Command Line Tools as info.
Cheers,
Ch
Comment: Show the contents of config.log.
Comment: Autoconf `configure` scripts output a log that provides details about the run, including any errors that occur.  Check that log to find out what command failed, with what error message.
Comment: This is part of my configure file:configure: `gcc -V >&5
gcc: error: unrecognized option '-V'
gcc: fatal error: no input files` and also `ld: library not found for -lgcc_ext.10.5`
Comment: to complete the above: `ld: library not found for -lgcc_ext.10.5
collect2: ld returned 1 exit status
configure:3436: $? = 1
configure:3474: result: no
configure: failed program was:
| /* confdefs.h */
| #define _GNU_SOURCE 1
| #define _NETBSD_SOURCE 1
| #define __BSD_VISIBLE 1
| #define _BSD_TYPES 1
| #define _DARWIN_C_SOURCE 1
| /* end confdefs.h.  */`
Answer: Actually I found the problem. The problem was with the ld: library not found for -lgcc_ext.10.5
The gcc version given by Xcode 4.6.3 on Mac OS X Lion is 4.6.

I installed the new gcc via homebrew, brew install gcc.
I symlink my gcc to gcc-4.9 by doing ln -s /usr/local/bin/gcc /usr/local/bin/gcc-4.9.
make sure the that in your PATH /usr/local/bin is before /usr/bin ).
To a ls -l 'which gcc' to check that gcc is associated to the 4.9 version. Once this is done, the library is found and python 2.6 can be installed using pyenv.


Activity Transition API Calling Intent

Question: ActivityTransitionUpdate returns null, always. But if I change it to requestactivityupdate it works fine. But I need the transition API. I do not understand why this is not working, especially since a couple of days ago it was working right.
I have tried rewriting the code, looked everywhere on the web, copied code from other projects that apparently work, but the requestActivityTransitionUpdates does not want to work anymore. I have also uninstalled and reinstalled android studio, but nothing is working.
Main Activity
''''
private List<ActivityTransition> transitions;

    private ActivityRecognitionClient activityRecognitionClient;

    private PendingIntent transitionPendingIntent;
    private Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

       System.out.println(getExternalCacheDir());
        Log.i(TAG, "ON");

        mContext = this;
        activityRecognitionClient = ActivityRecognition.getClient(mContext);

        Intent intent = new Intent(mContext, TransitionIntentService.class);

        transitionPendingIntent = PendingIntent.getService(this, 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    }

    public void registerHandler(View view) {

        transitions = new ArrayList<>();

        transitions.add(new ActivityTransition.Builder()
                .setActivityType(DetectedActivity.WALKING)
                .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_ENTER)
                .build());

        transitions.add(new ActivityTransition.Builder()
                .setActivityType(DetectedActivity.WALKING)
                .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_EXIT)
                .build());

        transitions.add(new ActivityTransition.Builder()
                .setActivityType(DetectedActivity.STILL)
                .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_ENTER)
                .build());

        transitions.add(new ActivityTransition.Builder()
                .setActivityType(DetectedActivity.STILL)
                .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_EXIT)
                .build());

        transitions.add(new ActivityTransition.Builder()
                .setActivityType(DetectedActivity.RUNNING)
                .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_ENTER)
                .build());

        transitions.add(new ActivityTransition.Builder()
                .setActivityType(DetectedActivity.RUNNING)
                .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_EXIT)
                .build());

        transitions.add(new ActivityTransition.Builder()
                .setActivityType(DetectedActivity.IN_VEHICLE)
                .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_ENTER)
                .build());

        transitions.add(new ActivityTransition.Builder()
                .setActivityType(DetectedActivity.IN_VEHICLE)
                .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_EXIT)
                .build());

        ActivityTransitionRequest activityTransitionRequest
                = new ActivityTransitionRequest(transitions);

        Task<Void> task;
        task = activityRecognitionClient.requestActivityTransitionUpdates(activityTransitionRequest, transitionPendingIntent);

        task.addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                Toast.makeText(mContext, "Transition update set up", Toast.LENGTH_LONG).show();
            }
        });

        task.addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(mContext, "Transition update Failed to set up", Toast.LENGTH_LONG).show();
                e.printStackTrace();
            }
        });
        //startService(intent);
    }

    public void deregisterHandler(View view) {
        Task<Void> task = activityRecognitionClient.removeActivityTransitionUpdates(transitionPendingIntent);
        task.addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                transitionPendingIntent.cancel();
                Toast.makeText(mContext, "Remove Activity Transition Successfully", Toast.LENGTH_LONG).show();
            }
        });

        task.addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(mContext, "Remove Activity Transition Failed", Toast.LENGTH_LONG).show();
                e.printStackTrace();
            }
        });
    }

''''
IntentService
''''
 public TransitionIntentService(String name) {
        super(name);
    }

    private int activityBang;
    private int transitionBang;

    @Override
    public void onHandleIntent(Intent intent) {

        Log.i(TAG, "onHandleIntent: GO");
        if (intent != null) {
            if (ActivityTransitionResult.hasResult(intent)) {
                ActivityTransitionResult result = ActivityTransitionResult.extractResult(intent);
                for (ActivityTransitionEvent event : result.getTransitionEvents()) {

                    Toast.makeText(this, event.getTransitionType() + "-" + event.getActivityType(), Toast.LENGTH_LONG).show();
                    //7 for walking and 8 for running
                    Log.i(TAG, "Activity Type " + event.getActivityType());
                    activityBang = event.getActivityType();

                    // 0 for enter, 1 for exit
                    Log.i(TAG, "Transition Type " + event.getTransitionType());
                    transitionBang = event.getTransitionType();

                    try {
                        ActivityWriter();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        else {
            Log.d(TAG, "onHandleIntent: Banana");
        }
    }

    private void ActivityWriter() throws IOException {

        String baseDir = getExternalCacheDir().toString();
        String fileName = "SentinelData.csv";
        String filePath = baseDir + File.separator + fileName;
        File f = new File(filePath);
        CSVWriter writer;

       SimpleDateFormat date1 = new SimpleDateFormat("yyyy.MM.dd G");
       SimpleDateFormat time1 = new SimpleDateFormat("HH:mm:ss z");

        String date = date1.format(new Date());
        String time = time1.format(new Date());

        if(f.exists()&&!f.isDirectory())
        {
            FileWriter mFileWriter = new FileWriter(filePath, true);
            writer = new CSVWriter(mFileWriter);
        }
        else
        {
            writer = new CSVWriter(new FileWriter(filePath));
        }

        String[] data = {date, time, String.valueOf(activityBang), String.valueOf(transitionBang)};

        writer.writeNext(data);

        writer.close();
    }

''''
My Manifest
''''
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.a200000"
    tools:ignore="GoogleAppIndexingWarning">

    <uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:fullBackupContent="@xml/backup_descriptor"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service
            android:name=".TransitionIntentService"
            android:exported="false" />
    </application>

</manifest>

''''
My Gradle
    apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.example.a200000"
        minSdkVersion 22
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation 'com.google.android.gms:play-services-location:17.0.0'
    implementation 'com.google.code.gson:gson:2.8.5'
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation 'com.opencsv:opencsv:4.0'
}

I expect to and was receiving transition updates when the app was open that were being stored in a csv file in the apps cache. Now my OnHandleIntent is not even being run from the task as it should be.
Answer: Not sure about it, but maybe helpful:
transitionPendingIntent = PendingIntent.getService(this, 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Task task = activityRecognitionClient.requestActivityUpdates(1000, transitionPendingIntent);

Comment: I am a bit worried about that eating up battery. This is going to be running all day as a service and I am trying to ensure it's not detrimental to have running. Plus it does not give me the transitions. I just don't get why the transitions would just stop working.
Answer: It happened to me the same thing before.It seems that last activity transition event kept in catch. Sometimes, you get an old event results from device's catch. So, to avoid all that problem, check the elapsed time of when the transition occurred, and ignore the callback if the transition happened over 30 seconds ago.
if (intent != null) {
        if (ActivityTransitionResult.hasResult(intent)) {
            ActivityTransitionResult result = ActivityTransitionResult.extractResult(intent);
            for (ActivityTransitionEvent event : result.getTransitionEvents()) {

                //if event occurred less than 30 seconds, get the event. Sometimes app gets old events from device's catch
                //that is why you have to make sure that the event is not that old.
                if(((SystemClock.elapsedRealtime()-(event.getElapsedRealTimeNanos()/1000000))/1000) <= 30) {
                   //Do your staff here......
                   ............................
                   ............................
                   ...............................
                }

            }
        }
    }
    else {
        Log.d(TAG, "onHandleIntent: Banana");
    }

Activity Transition API Calling Intent


Como deixar o background de uma  fixo no Safari do iOS (iPad)?

Question: Tenho um layout que funciona muito bem no desktop, mas ao visualizar no Safari do iOS (iPad especificamente) ele não aparece como esperado. Eu quero que o background da div permaneça fixo ao rolar a página. Alguém sabe como corrigir esse problema?
css
#caixa{
    background:url(imagem.jpg) no-repeat center center fixed;
    height:300px;
    width:300px;
}

html

Answer: Na verdade, o seu background está fixo. O problema é o "viewport"...

Primeiro, vamos recapitular por que o posicionamento fixo não funciona
  como esperado. O Safari Mobile usa um "viewport" para mostrar websites.
  Imagine um livro diante de você. Pegue um pedaço de papel, corte um
  quadrado 320×416 no mesmo, e coloque o papel com o quadrado aberto
  no meio sobre o livro. Para ler o livro, mova o papel e posicione o
  buraco sobre as palavras que você quer ver. Isso é exatamente o que o
  "viewport" do Safari Mobile está fazendo. Quando você toca e arrasta,
  você está movendo o "viewport" por sobre o site, que continua estático
  "abaixo" dele.
Isso faz com que o posicionamento fixo se torne nulo e inútil no
  iPhone. Um elemento que tem posicionamento fixo está afixado ao
  body, e não ao viewport. Ou seja: o fixed está atualmente
  funcionando como desejado, apesar de que gostaríamos que estivesse
  afixado ao "viewport".

fonte: http://old.doctyper.com/archives/200808/fixed-positioning-on-mobile-safari/
Comment: Foi o que eu imaginei, pois nenhum site que utiliza este recurso estava funcionando corretamente no iPad. Obrigado.
Comment: Após uma rápida pesquisa, me parece que a opção "snap" da biblioteca iScroll consegue contornar o problema: http://iscrolljs.com/#snap - boa sorte!
Answer: @PauloMaciel,
deixe seu id assim:
#caixa{
  background:url(imagem.jpg) no-repeat;
  height:300px;
  width:300px;
  background-position: center center;
  background-attachment:fixed;
}

Ou tente:
@media screen and (-webkit-min-device-pixel-ratio:0){
  #caixa{
    background:url(imagem.jpg) no-repeat;
    height:300px;
    width:300px;
    background-position: center center;
    background-attachment:fixed;
  }
}

Comment: Continua apresentando o mesmo problema no iPad.
Comment: Esta testando com simulador ou dispositivo mesmo?
Comment: Estou testando no próprio iPad, já tentei de várias formas solucionar mas o problema persiste, inclusive sites que utilizam este recurso também não funcionam no iPad.
Answer: Já testou em outro iPad? Tem certeza que não é um erro do teu iPad. Uma vez tive um problema de visualização de margem no firefox. Fiz de tudo e nada. Então em outro pc que tinha só o chrome (e a porcaria do IE) eu instalei o firefox e funcionou bem. Não sei o que causou o problema no meu firefox, eu tinha windows7. Por outros motivos eu tirei o windows e passei a usar linux (que o firefox é padrão) e agora o firefox não apresenta aquele erro. Talvez seja algo parecido com o teu iPad.
Comment: Não é um problema do meu iPad, iOS é diferente de Windows, esse comportamento é padrão nesse sistema.


Problemas na utilização de JSTL

Question: Estou implementando uma aplicação WEB com J2EE, mas não estou conseguindo listar os dados vindos do ServletListarCursos para a página ListaDeCursos.jsp que utiliza JSTL.
  public class ServletListarCursos extends HttpServlet {

    private static final long serialVersionUID=1L;
    private static final String CONTENT_TYPE="text/html";

    public void doPost(HttpServletRequest request, HttpServletResponse response)throws HTTPException, IOException{

        response.setContentType(CONTENT_TYPE);
        HttpSession session = request.getSession(true);
        FachadaControladorDAO fachada = FachadaControladorDAO.getInstancia();

        Curso curso = new Curso();
        try {
          List colecao =  fachada.getListarCursos(curso);
          session.setAttribute("colecao", colecao);

          RequestDispatcher rd = request.getRequestDispatcher("view/curso/ListaDeCursos.jsp");
          rd.forward(request, response);

        } catch (RepositorioException ex) {
            Logger.getLogger(ServletListarCursos.class.getName()).log(Level.SEVERE, null, ex);
        }catch(ServletException ex){
            ex.printStackTrace();
        }

    }

}

O ServletListarCursos enviar a lista de cursos("colecao") para ListaDeCursos.jsp.
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Lista de cursos</title>
         <select id="selecaoCursos" name="selecaoCursos"  >
            <option value="0" >Selecione o curso</option>
            <c:forEach items="${colecao}" var="cursos"  >
               <option  value="${cursos.codigoCurso}"
                        id="codigoCurso">
                        ${cursos.nomeCurso}
               </option>
            </c:forEach>
         </select>

Dúvida não estou conseguindo listar os valores do DB através do ServletListarCursos, utilizando JSTL.
Comment: Não vejo nada de errado.
tem certeza que sua list colecao está preenchendo algo?
Answer: Faça o acesso à lista no escopo correto, no seu caso o objeto foi enviado para a sessão:
session.setAttribute("colecao", colecao);

No jsp chame dessa forma:
 <c:forEach items="${sessionScope.colecao}" var="cursos"  >

Ou ainda você pode utilizar o escopo de request
request.setAttribute("colecao", colecao);

jsp
<c:forEach items="${colecao}" var="cursos"  >

Comment: Na verdade, quando não se explicita o escopo na expressão, a API pesquisa em diversos escopos numa ordem pré-definida. Claro que seria uma boa prática definir o escopo para evitar surpresas, além de sempre usar o escopo mais limitado possível, neste caso o `requestScope`. A ordem de procura pode ser vista aqui: http://stackoverflow.com/a/875423/1683070
Comment: Testei as formas apresentadas, mas ainda não funcionou. Importei  para a pasta lib: jstl-1.1.2.jar e standard-1.1.2.jar, mas continua não funcionando.

Problemas na utilização de JSTL


AJUDA NO IONIC!

Question: Galera, acabei de instalar o ionic no ubuntu e ele veio na última versão, no caso a 4 (4.12.0, pra ser mais exato), como que eu posso instalar a versão 3 ? tem como fazer ?
Answer: Então, você provavelmente deve ter dado um npm install -g ionic certo? Fazendo isto o npm irá buscar sempre a última versão atualizada oficialmente disponível, no caso aí 4.12.0 para você instalar uma versão anterior (fazer downgrade, contrário de upgrade) pode seguir os seguintes passos:

Passo 1 - Desinstalar a versão 4.12.0 instalada anteriormente com o comando
npm uninstall -g ionic

Passo 2 - Instalar exatamente a versão que preferir
npm install -g firstname.lastname@example.com

Isto "força" o npm a baixar e instalar exatamente esta versão.

AJUDA NO IONIC!


Método POST recebendo objeto vázio. C#

Question: Tenho uma controller com um método POST que sempre recebe o parâmetro nulo.
Estou mandando o JSON pelo postman.
Já tentei por a classe como parâmetro, já tentei por string como parâmetro e em ambos os casos está deixando ele nulo;
Segue a controller:
using API_Shop.AppComponents.Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace API_Shop.Controllers
{
    public class TesteController : ApiController
    {
        // GET: api/Teste
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET: api/Teste/5
        public string Get(int id)
        {
            return "value";
        }

        // POST: api/Teste
        public void Post([FromBody]string value)
        {
            Teste tt = new Teste();
            tt = JsonConvert.DeserializeObject<Teste>(value);
            throw new Exception(tt.Texto.ToString());
        }

        // PUT: api/Teste/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE: api/Teste/5
        public void Delete(int id)
        {
        }
    }
}

Esta exception está dando 'Valor não pode ser nulo'.
O outro teste informando o tipo do parâmetro 'Teste' também está recebendo nulo. No caso, a exception que é lançada é de referência nula de objeto.
Segue JSON enviado pelo POSTMAN:
{
  "Teste":{
  "texto":"teste de post para controller"
   }
}

Já teste o GET e funciona normalmente.
Alguém pode me dar uma mãozinha com isso? Como faço para ele pegar o objeto corretamente?
Comment: Onde está o código de onde você está fazendo o post?
Comment: Pelo o que eu entendi de sua pergunta você quer saber da onde está saindo o POST.
Estou enviando pelo POSTMAN. Vou no headers coloco o Content-type em application/json e descrevo o arquivo na aba Body e dou 'send'
Comment: isso é em asp.net core?
Answer: Bom, você está enviando um "objeto" JSON equanto sua Action espera uma string
Conteúdo do POST
{
  "Teste":{
  "texto":"teste de post para controller"
   }
}

Sua Action
// POST: api/Teste
public void Post([FromBody]string value)

Quando você faz isso, você está realizando o POST de JSON que representa um Objeto que possui outro Objeto, chamado Teste, que por sua vez possui o atributo "texto", onde está declarado o valor "teste de post para controller". Enquanto isso na sua Action você simplesmente espera uma string.
A representação correta para esse envio seria criar os objetos para refletirem sua estrutura e "tipar" o parâmetro de entrada da sua Action
public PostApresentado
{
   public Teste Teste {get;set;}
}

public Teste
{
   public string Texto {get; set;}
}

A sua Action deveria esperar o seguinte input:
public void Post([FromBody]PostApresentado value)
{
}

E trabalhando dessa forma, você não precisa da JsonConvert para serializar e deserializar, isso fica a cargo do framework e você pode trabalhar "diretamente" com os objetos/classes.
Comment: @ABCDEFGH, ficou claro para você??
Answer: Se não precisares que seja string podes receber o model ou DTO. Vejo que depois convertes a string para o teu objecto "model" Teste. Acho que tens o mesmo problema que eu tenho. Funciona na app, mas no Postman não. Conseguiste resolver? Preciso tb de enviar pelo Postman um string em vez de json e depois converter também como tu. O Post anterior não percebeu o teu problema, mas eu percebi.

Método POST recebendo objeto vázio. C#


Find a graph on eight vertices with a pair of pseudosimilar vertices

Question: Can somebody give me an example of a graph on eight vertices that has a pair of pseudosimilar vertices? Or, is it not possible? If it is not possible, please do not give me a proof, as I would like to figure out how to prove it myself.

Definition: vertices $u$ and $v$ in a graph $X$ are similar if there is an automorphism of $X$ that maps $u$ to $v$. If $u$ and $v$ are similar, then the vertex-deleted subgraphs $X-u$ and $X-v$ are isomorphic. If $X-u$ and $X-v$ are isomorphic but $u$ and $v$ are not similar, we say that they are pseudosimilar.
Comment: This is similar to the [reconstruction conjencture](http://en.wikipedia.org/wiki/Reconstruction_conjecture)
Comment: So far, I haven't found any counter-example
Answer: Here is a copy of the first figure in Kimble et al.'s "Pseudosimilar vertices in a graph", J. Graph Th. 5(2) (2006), which as of writing is the top Google hit for "pseudosimilar vertices". The graph has 8 vertices and is stated to be the smallest possible graph having pseudosimilar vertices.

The paper credits the discovery of this example to Harary and Palmer ("On similar points of a graph", J. Math. Mech. 15 (1966); "A note on similar points and similar lines of a graph", Rev. Roumaine Math. Pures Appl. 10 (1965)).
Comment: I assume reproducing one figure with attribution falls under fair use.
Comment: It seems like a proper citation to me ;-)
Comment: I was looking for some smaller counterexample. No wonder I didn't succeed.
Comment: Having posted this answer, I have effectively acted as someone's Google daemon. I feel quite ridiculous.
Comment: So you want me to unupvote? ;-)


Why does my adjacency list contain a blank space? (Java)

Question: My code creates and prints an adjacency list from a given text file, however when printing out it leave a blank space after the second node for whichever input file I use. Here's the main part of the code:
class Neighbor {
    public int vertexNum;
    public Neighbor next;
    public Neighbor(int vnum, Neighbor nbr) {
            this.vertexNum = vnum;
            next = nbr;
    }
}

class Vertex {
    String name;
    Neighbor adjList;
    Vertex(String name, Neighbor neighbors) {
            this.name = name;
            this.adjList = neighbors;
    }
}

public class Graph
{

    static Vertex[] adjLists;

    public Graph(String file) throws FileNotFoundException
    {
        Scanner fileScanner = new Scanner(new File(file));
        fileScanner.useDelimiter("[^A-Za-z0-9]");

        ArrayList<String> words = new ArrayList<String>();

        while (fileScanner.hasNext())
        {
            String nextWord = fileScanner.next();
            if (!words.contains(nextWord))
            {
                words.add(nextWord);
            }
        }

        adjLists = new Vertex[words.size()];

        // read vertices
        for (int v=0; v < adjLists.length; v++)
        {
            adjLists[v] = new Vertex(words.get(v), null);
        }

        // read edges
        Scanner sc = new Scanner(new File(file));

        while (sc.hasNext())
        {
             // read vertex names and translate to vertex numbers
            int v1 = indexForName(sc.next());
            int v2 = indexForName(sc.next());

            // add v2 to front of v1's adjacency list and
            // add v1 to front of v2's adjacency list
            adjLists[v1].adjList = new Neighbor(v2, adjLists[v1].adjList);
            // Doesn't add the node twice if it's connected to itself
            if(v1!=v2) {
         adjLists[v2].adjList = new Neighbor(v1, adjLists[v2].adjList);
            }
        }
    }

    int indexForName(String name)
    {
        for (int v=0; v < adjLists.length; v++) {
            if (adjLists[v].name.equals(name)) {
                return v;
            }
        }
        return -1;
    }

    public void print()
    {
        System.out.println();
        for (int v=0; v < adjLists.length; v++) {
            System.out.print(adjLists[v].name);
            for (Neighbor nbr=adjLists[v].adjList; nbr != null;nbr=nbr.next) {
                System.out.print(" --> " + adjLists[nbr.vertexNum].name);
            }
            System.out.println("\n");
        }

    }

Here is the example output:
Sara --> Ajay --> Sam

Sam --> Mira --> Sean --> Sara

Ajay --> Sara

Sean --> Sam
etc.

Why does this gap between Sam and Ajay exist? No matter how long the list is, or what file I use, there is always a gap between the 2nd and 3rd node, and when running analysis on the list it has an effect because it is essentially reading a blank line and counting it as a node. This doesn't happen anywhere else in the list, just after the second node.
My input data looks like this
Sara Sam
Sara Ajay
Sam Sean
Sam Mira
Mira Jane
etc.

Calling print:
Scanner br = new Scanner(System.in);
System.out.print("Enter graph input file name: ");
String file = br.nextLine();
Graph graph = new Graph(file);
graph.print();

Comment: show your input data
Comment: Also where are you calling `print()` ?
Comment: Print is called later on, I'll edit with that code too
Comment: debug if your `nbr==null` . If thats the case, your inner loop wont execute that iteration, will go to next step and print next line.
Answer: If you debug your code you will see that your third element of the words ArrayList is an empty string. This is due to how the file is read and how your input is handled.
Commenting the fileScanner.useDelimiter line provides a correct output. Otherwise you could just add the following condition:
        if (!nextWord.isEmpty() && !words.contains(nextWord)) {
            words.add(nextWord);
        }

and it should be fine.
Comment: Thanks you're totally right, removing the delimiter does fix it. Weird. Thanks again!


How can i apply tuple to my code so I can get an output "{('a', 'x'))"?

Question: Below is my code. Its written for when a user enters 2 text files, it pairs lines from the text files together.
#User enters text file names
user_input = input("Enter First Text file: ")
user_input2 = input("Enter Second Text file: ")

#Opens the inputted text files
File = open(user_input, "r")
Text1 = File.read().splitlines()

File2 = open(user_input, "r")
Text2 = File2.read().splitlines()

PairedFiles = set()
for r in Text1[0].split():
    for s in Text2[0].split():
        PairedFiles.add(r + s)
print(PairedFiles)

These are examples text files that would be used in relation to the above code:
Text File #1:
a

Text File #2:
x

The output of this is:
{'ax'}

The output I'm wanting is:
{('a', 'x'))

Its been said that the above output happens when using tuples. How would I apply tuple to get the above desired output of {('a', 'x'))?
Help would be much appreciated!
Comment: Ok, I missed that. Point taken. I will be voting to close soon given no feedback from the OP. (although all the clues are there in the question: creating a set in the code and mentioning tuples.)
Comment: Your desired output isn't even valid in Python. You've repeated it twice, so it's not a typo. Why would you even want that, if it was `{('a', 'x')}`? That looks like you want JSON
Comment: @gblomqvist then you should take more effort over writing posts. We're not here to guess at badly-written posts. If people want help, they need to review their posts properly; so it escaped their review of their own question twice. EDIT: they did it thrice
Comment: @roganjosh How can you be sure it's not a typo? He probably just copied the first string, I know I would have.
Comment: @roganjosh Isn't it pretty obvious what was meant? And even if it wasn't, you could always ask for clarification/suggest an edit.
Comment: @gblomqvist I could just edit it, I don't need to suggest it. But that would be the _wrong_ thing to do here (please don't suggest it). I highlighted the issue in my first post; the OP should be perfectly aware of the issue and can edit it out. It's not for _any_ of us to make changes like that. This might be a trivial example, but I've seen it cause all sorts of issues when people take it upon themselves to make such changes
Comment: @roganjosh it looks perfectly valid python to me.
Comment: @quamrana as a string, sure. How do you propose parsing it when reading it in?
Comment: Ok, now I'm confused. I thought that the set containing a tuple was the output.
Comment: @quamrana look again at `{('a', 'x'))`. That is not a set because there is no closing `}` but instead a `)`. It's repeated 3 times; in the question title and twice in the question (which was edited and I rolled it back, and the edit didn't even fix the title)
Comment: @quamrana I agree with you fully that the clues are there, but I've seen so many things derailed by people making assumptions like these. It's for the OP to fix. In a broader context, I can't think of a single reason why you'd want to store this in a text file, so I don't think the Q/A is of any use to anyone else
Comment: @quamrana and it's just been edited and none of them were "corrected" by the OP :/
Answer: >>> 'a' + 'x'   # adding two strings
'ax'
>>> ('a', 'x')  # forming a tuple of two strings
('a', 'x')

Change this:
PairedFiles.add(r + s)

to this:
PairedFiles.add((r, s))


Request for suggestions on doing IPC/event capture

Question: I have a simple python server script which forks off multiple instances (say N) of C++ program. The C++ program generates some events that need to be captured.
The events are currently being captured in a log file (1 logfile per forked process). In addition, i need to periodically (T minutes) get the rate at which the events are being produced across all child processes to either the python server or some other program listening for these events (still not sure). Based on rate of these events, some "re-action" may be taken by the server (say reduce the number of forked instances)
Some pointers i have briefly looked at:

grep log files - go through the running process log files (.running), filter those entries generated in the last T minutes, analyse the data and report
socket ipc - add code to c++ program to send the events to some server program which analyses the data after T minutes, reports and starts all over again
redis/memcache (not sure completely) - add code to c++ program to use some distributed store to capture all the generated data, analyses the data after T minutes, reports and starts all over again

Please let me know your suggestions.
Thanks
Comment: Voting to migrate to Programmers.SE -- by definition, anything asking for suggestions rather than concrete answers does not belong on SO.
Answer: As a alternative to your socket IPC suggestion, how about 0mq. It's a library (in C with python bindings available) that can do message transfer on an inter-thread, inter-process or inter-machine level. Pretty simple to get going, and pretty quick.
I'm not affiliated with it. I'm just evaluating it for other uses and thought it might be a fit for you as well.
Answer: if time is not of the essence (T minutes sounds like it is long compared to whatever events are happening in the C++ programs that are kicked off) then dont make things any more complicated than they need to be.  forget IPC (sockets, shared mem, etc),  just have each C++ program log what you need to know about time/performance and let the python script check logs every T minutes that you need the data.  dont waste time overcomplicating something that you can do in a simple manner


I feel my limits when I am learning drums techniques

Question: I love drums.  I am an amateur, but from my childhood I was fascinated by this great instrument.
I've never owned a drum kit but I was always doing noise (with my hands on my belly, with my mouth, fork and spoon while waiting to be served to eat, etc.). With time, as many teenagers do, I listened to hard rock, metal, and punk and I've played along with the bands. I used my ears to reproduce what the drummers were doing, and it was fine.
But I started to try jazz, and some drums techniques, such as paradiddle and etc., but for now I just can not do it.  I feel that my arms will NEVER succeed, and it makes me sad/angry and frustrated.
Is it normal to not be able to do something at all, but practice to do it?
Comment: The beauty of the drums is that you don't have just one instrument, you have DOZENS! And while most of them have the same basics, hit it at the right time, they are all unique and have different techniques. You just don't hit a tom the same way you hit a high hat, and neither are the same as a cymbal (and different cymbals are different at that! And some cymbals are almost different instruments on the outside as they are in the middle!) That's why drums can be so hard to learn. Keep practicing, you'll do great!
Comment: Thank you @corsiKa and I agree 110% with your logic and point of view !
Answer:
Is it "normal" to not be able at all and with practice to do it ?

Yes, this is exactly how it works. There is not a single musician on the planet that started out being able to play their instrument immediately. Everyone starts out terrible and then gets better with practice and time.
Through repetition your body will start to develop muscle memory and this will allow you to be able to play without having to consciously think about it. It literally becomes automatic.
From Wikipedia: https://en.wikipedia.org/wiki/Muscle_memory

Muscle memory has been used synonymously with motor learning, which is
  a form of procedural memory that involves consolidating a specific
  motor task into memory through repetition. When a movement is repeated
  over time, a long-term muscle memory is created for that task,
  eventually allowing it to be performed without conscious effort. This
  process decreases the need for attention and creates maximum
  efficiency within the motor and memory systems. Examples of muscle
  memory are found in many everyday activities that become automatic and
  improve with practice, such as riding a bicycle, typing on a keyboard,
  typing in a PIN, playing a musical instrument, poker, martial arts or
  even dancing.

This is why experienced musicians can play their instruments and make it look so easy and effortless. They have developed this muscle memory to the point that it IS easy and effortless. With enough time and practice you will get to this point also. This is simply how our bodies work. Think of all the things you can already do without having to focus on them like walking, writing, riding a bike, throwing a ball, etc. these are all things you have developed muscle memory for and you can easily do them with without thought. Your drumming will eventually get to this point as well.
Here is the most important thing, when first learning something new make sure to practice very slowly and with proper technique because while developing muscle memory you want your body to learn the motions correctly. Have patience and resist the urge to try to play fast right away. Trying to play too fast too soon will only teach your body how to do it wrong which will end up reducing your overall speed, making you sound sloppy, and could even cause physical injuries such as tendonitis. Practice slowly and give your body plenty of time to learn how to do the motions while staying very relaxed. Speed will come with time and then you will be able to play faster, have better control, play with better feel, and you will protect your body from injuries.
One final point, make sure you are practicing consistently every day. You are better off practicing a few minutes every day (if you have limited time to practice) than practicing a lot all in one day and then taking the rest of the week off. Muscle memory will develop much faster through consistent reinforcement. Having long extended breaks in between practicing will cause you to loose a lot of the muscle memory you had developed before and it'll almost be like starting over each time you sit down to practice.
Practice slow, practice consistently, have patience and you will absolutely succeed. :)
Comment: Thank you @Tekkerue for all your advices and references, I'll just practice consistently and continue to enjoy playing drums
Comment: One of the OP's problems may be that he has developed 'muscle memory', perhaps including bad techniques, and now he's trying out jazz - potentially more demanding - those techniques have come back to bite him?
Answer: I think it is very common for players to hit plateaus, especially self taught players. It may be beneficial to get a teacher to help you along with the parts you are struggling with. A good teacher will help you where you are struggling and enforce things you already know as well as correct any mistakes in your technique.
Comment: Some of the plateaus might even be psychological, because some people become much more receptive to new techniques because of the presence of a teacher, so all in all, consulting with an instructor is always a good idea as a learner
Answer: Is it normal? Yes, that's how it works. You begin by not knowing something then through study and practice, you gradually learn it. Is sounds to me like you're ready for some lessons. Jazz is one of the most challenging music forms and a good teacher can help you acquire the skills you're looking for. I would also recommend Jim Blackley's "Essence of Jazz Drumming".


mouse hover Javascript

Question: Consegui fazer com jquery, está ai o código para quem precisar.
<code> <script type="text/javascript" src="dist/jquery/jquery-1.12.3.min.js"></script>
 <canvas id="diamond" width="100" height="100"></canvas>
    <script type="text/javascript">

        var canvas = document.getElementById("diamond");
        var context = canvas.getContext("2d");

    var diamond = function (x,y){
        context.beginPath();
        context.moveTo(25,15);
        context.lineTo(40,25);
        context.lineTo(25,35);
        context.lineTo(10,25);

        context.lineWidth = 1;
        context.fillStyle = "#F2673D";

        context.closePath();

        context.fill();
    }

    diamond();

    $(document).ready(function() {

        $("#diamond").hover(function() {
            $(this).stop().animate({ marginTop: "-48px" }, 200);
        },function(){
            $(this).stop().animate({ marginTop: "-50px" }, 300);
        });

});
</script>
</code>
Answer: Este é um exemplo. Elabore mais detalhadamente a partir dele.
<code>var canvas = document.getElementById("diamond");
var context = canvas.getContext("2d");

var diamond = function (x,y){
    x = x || 0;
    y = y || 0;
    context.beginPath();
    context.moveTo(25 + x,15 + y);
    context.lineTo(40 + x,25 + y);
    context.lineTo(25 + x,35 + y);
    context.lineTo(10 + x,25 + y);
    context.lineWidth = 0;
    context.fillStyle = "#F2673D";
    context.closePath();
    context.fill();
}

function clearCanvas() {
    context.clearRect(0, 0, canvas.width, canvas.height);
}

function move(p){
  if (p < 200 ){
    setTimeout(function(){
      clearCanvas();
      diamond(p, p);
      p += 10;
     move(p);
    }, 1000);
  }
}

move(10);
</code>
tem um exemplo rodando aqui:
https://jsfiddle.net/zLg27m9p/4/

mouse hover Javascript


Formas Normais modelagem de dados

Question: Tenho um arquivo excell com informações do PRODUTO E PEDIDO. Ele esta fora das formas normais, pois as informações estão todas em uma tabela só.
Estou subindo através de bulk insert essas informações para um banco no SQLServer. A primeira tabela da imagem mostra como ela é atualmente. As outras duas como devem ficar apos a normalização. Como proceder para associar o novo campo criado na tabela produtos(CodigoProduto)com o pedido? Já que na primeira tabela desnormalizada não existem informações para esse campo?
Comment: Você esta criando a tabela Produtos ou irá utilizar uma existente para efetuar o relacionamento?
Comment: Estou criando a tabela Produto mas com base nas informações que eu ja tenho. Entao nessas informações eu nao tenho um codigo de produto.
Comment: Faça o `bulk insert` na tabela Produtos somente com a descrição e depois acrescente a `primary key`.
Comment: Ok, isso é facil. O problema é: na tabela do excel eu tenho uma linha só. Ex:
Comment: Você quer incluir os novos produtos em uma tabela já existente e com a `primary key` definida?
Comment: Isso é facil fazer, acontece que a partir do momento que eu separar as informações de produto como cor, nome, tamanho. Ela vai ficar perdida e eu nao vou saber mais a qual produto ela pertence. Na tabela excel que tenho esta assim: NomeFulano, CodigoFulano, EndereçoFulano, DataPedido, NumeroPedido, NomeProduto, CorProduto, tamanhoProduto. Note que Tenho o campo CodigoFulano, posso usar como pk na table Cliente, e tambem tenho NumeroPedido, mas nao tenho CodigoProduto.
Comment: Pode resolver isso manualmente cadastrando 1 a 1 os relacionamentos caso não tenha muitos dados. Por exemplo ,se tiver somente uns 100 registros, faça na mão mesmo pois o custo de tempo será igual ou menor do que criar um script para automatizar a migração dos dados. Se for mais de 400, 1000, etc, talvez seja mais viável criar uma automação. No caso de uma automação, uma lógica mais simples é setar o campo do código do produto de acordo com o nome do mesmo. Mas deve observar também o campo "corProduto".
Answer: Sugestão de como proceder:

Faça o bulk insert de todo o arquivo excel, inclusive com a
Descrição do Produto para um tabela do bd.
Crie a tabela de Produtos com as descrições do produto e depois
adicione a primary key.
Crie o campo Código do Produto na tabela com a descrição do produto
e os outros campos.
Atualize o campo Código do produto usando a Descrição do Produto das
duas tabelas para fazer a associação (join).
Exclua o campo descrição do produto da tabela e só deixe na tabela
produto.

Sei que não é uma boa prática fazer join com campos string, mas, como é só com paliativo, acho que não terá problemas.
Comment: @Felipe Gomes Coloque as imagens no post.
Comment: Coloquei as imagens no post agora. Desculpe ainda sou noob no forum.

Formas Normais modelagem de dados


cluster analysis after factor analysis: do I need to use all factors for cluster analysis?

Question: I have a 127-question survey with 6-level likert type answers. With EFA I have kept 56 items and got 8 factors. With CFA (on sample not used in EFA) I confirmed these factors. so far all good.
When I tried to do cluster analysis, with 8 all factors I did not get clear solution (I used SAS, and used the CCC and pseudo F and T statistics indicators to judge the number of clusters; ccc: Cubic Clustering Criterion).
When I used 7 factors, I got a clearly solution of 3 clusters. All three indicators (CCC, pseudo F and statistics) suggested cluster number of 3. And further analysis with 3 clusters looks very reasonable to us.
my question is: Do I must use all 8 factors from EFA/CFA to do cluster analysis?
If I must use all factors, what can I do if it does suggest a clear number of clusters? It seems there is no much to tune.
if I use 7 factors but not 8 factors from EFA, will this be a problem and reviewers may question on this?
Comment: There are a number of very unclear points in your question. To mention just two: 1) `have a 127-question survey... With EFA I have kept 56 items and got 8 factors` What does that mean? Did you do EFA on 127? You kept 56 based on EFA - i.e. meaning that you are developing a questionnaire and selecting items for it? If so then did re-doing EFA on those 56 items confirmed well that 8-factor structure? You have not explained all that - what you were doing.
Comment: Next thing, are you clustering cases (data points) or variables (the items) - also unclear (for me, I'm sorry for being stupid). `Do I must use all 8 factors from EFA/CFA to do cluster analysis?` What for? What is your purpose after all?
Comment: I used 127 items in EFA and removed many based on communalities, low factor loading, cross loading, etc) and finally 56 left. I split data into two parts, one for EFA and the rest for CFA. And then I want to use cluster analysis to group cases (people, data points); purpose is to see difference between groups of cases
Answer: The quick answer is "no," you do not need to use all of the factors. More specifically, there is no "rule" or law about what you eventually use in creating a cluster solution. Moreover, each of the factors is an expression of all of the input variables.
Having done many cluster solutions over the years that were based on SAS Proc Fastclus, I found that there were three important input options:

The "drift" option
The "delete=" option setting a minimum floor to the size of the seeds
Varying the number of input variables

If all the factors don't return a useful solution, then whack a few with the smallest eigenvalues and rerun it. Another useful idea is to put the first pass of Fastclus within a macro which loops from 3 to some appropriately large number of clusters, i.e., maxc=. Then, if a promising solution is found based on triangulating the CCC, the frequencies of the clusters and the inflection point for the pseudo-Rsquared, roll that out based on the original input variables.
Comment: Thank you. I use proc aceclus followed by proc cluster with method=ward to get ccc, F and T statistics. But I found method=ward does not work for proc fastclus (syntax error if I use it in proc fastclus)
Comment: I used to use Proc Cluster to curate the seeds for input into Fastclus until I figured out it was a waste of time. Not being a fan of hierarchical partitions, I never use Cluster, relying on Fastclus. Aceclus delivers elliptical solutions where Fastclus is spherical.
Comment: do you mind sharing a little bit more on using Proc fastclus to determine the best number of clusters? In proc cluster using method=ward, SAS output 3 curves for CCC F and T^2 against number of clusters, which helps determine number of clusters. In Proc Fastclus it only generates one value for each, and how to use these to determine the best number of clusters? Thank you.
Comment: Np. First, identify solutions with a spread in the frequencies across the clusters. Basically, this means avoiding solutions that put 40%-45% or more of the observations in one cluster. Next, within that set, identify the *first* solution that maximizes the CCC. If the CCC is always negative, either whack more input variables or take the least negative solution. Usually, maximizing the CCC will return something close to the inflection point for the pseudo-Rsquare.


ML Search Grammar

Question: I was wondering what I want is possible using search grammar.. For eg:let us assume 3 documents
 doc 1:
    <seq>
       <chain><name>PL-1</name></chain>
    </seq>
doc 2:
    <seq>
         <chain><name>PL-1</name></chain>
         <chain><name>PL-2</name></chain>
     </seq>
doc 3:
    <seq>
         <chain><name>PL-1</name></chain>
         <chain><name>PL-2</name></chain>
         <chain><name>PL-3</name></chain>
     </seq>

I want to search for documents containing chain names "PL-1". and nothing else.. so for this search criteria I need to get only doc 1, if I want to search for PL-1 and PL-2, I should get only doc2
Is this possible with Search Grammar ??
Answer: The default search grammar uses minus (-) as a starter token that translates into a negated query, so you could use that:
xquery version "1.0-ml";

import module namespace search = "http://marklogic.com/appservices/search"
at "/MarkLogic/appservices/search/search.xqy";

search:parse("PL-1 -PL-2 -PL-3")

That will return the query for your first example, matching doc 1:
<cts:and-query xmlns:cts="http://marklogic.com/cts">
  <cts:word-query>
    <cts:text xml:lang="en">PL-1</cts:text>
  </cts:word-query>
  <cts:not-query>
    <cts:word-query>
      <cts:text xml:lang="en">PL-2</cts:text>
    </cts:word-query>
  </cts:not-query>
  <cts:not-query>
    <cts:word-query>
      <cts:text xml:lang="en">PL-3</cts:text>
    </cts:word-query>
  </cts:not-query>
</cts:and-query>

Using the same method, you could create a string for the query that matches only doc 2:
PL-1 PL-2 -PL-3

Comment: Actually I do not how many chains are there in a document.. So this will not work as I am looking for documents containing only names specified in the search string
Comment: @Ravi That's actually a very different question from the one you asked. You need to state all your constraints; otherwise, why would anyone answer with a solution to a harder problem than the one you asked? What you want is possible, but more complicated, so please create a new question.

ML Search Grammar


Font Awesome with Half Style CSS

Question: I'm wondering if anyone can help me / If this is even possible.
I'm trying to half style (using halfstyle.js) the youtube font-awesome icon so that the icon is like the youtube logo (bottom half red, top half white)
I'd like to do this on hover, but I can't even seem to get this going for just as default.
JSFiddle

body {
    background: rgba(0,0,0,.4);
}
.fa {
    font-size: 10em;
    color: white;
}
.fa-youtube {}

.halfStyle {
    position:relative;
    display:inline-block;
    font-size:80px; /* or any font size will work */
    color: transparent; /* hide the base character */
    overflow:hidden;
    white-space: pre; /* to preserve the spaces from collapsing */
}
.halfStyle:before { /* creates the top part */
    display:block;
    z-index:2;
    position:absolute;
    top:0;
    height: 50%;
    content: attr(data-content); /* dynamic content for the pseudo element */
    overflow:hidden;
    pointer-events: none; /* so the base char is selectable by mouse */
    color: #f00; /* for demo purposes */
    text-shadow: 2px -2px 0px #af0; /* for demo purposes */
}
.halfStyle:after { /* creates the bottom part */
    display:block;
    position:absolute;
    z-index:1;
    top:0;
    height: 100%;
    content: attr(data-content); /* dynamic content for the pseudo element */
    overflow:hidden;
    pointer-events: none; /* so the base char is selectable by mouse */
    color: #000; /* for demo purposes */
    text-shadow: 2px 2px 0px #0af; /* for demo purposes */
}

Comment: Looking for something like [**this**](https://jsfiddle.net/vivekkupadhyay/ogxwpdmd/3) ?
Comment: @vivekkupadhyay No I'm just looking for the 'tube box' to go red and the rest stay the same
Answer: You cannot do that for FontAwesome i.fa icons because, already HalfStyle is based on the ::after and ::before pseudo elements. Also, FontAwesome uses :after for this. You need to create another element and give :hover option for achieving this.
Snippet

$(function () {
  $(".textToHalfStyle").each(function () {
    $(this).parent().append('

');
    $(".cloned").append($(this).clone());
  });
});
body {
  background: rgba(0,0,0,.4);
  font-size: 160px;
}
.fa {
  color: #fff;
}
.cloned {
  opacity: 0;
  position: absolute;
  display: block;
  z-index: 1;
  left: 8px;
  top: 76px;
  height: 0.65em;
  overflow: hidden;
}
.cloned .fa {
  position: relative;
  top: -68px;
  color: #f00;
}
.fa:hover ~ .cloned,
.cloned:hover {
  opacity: 1;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" />

Comment: I would like for the icon to be white, and then on hover it would display like you have it (no red on top)
Comment: @Tom Need some time to figure it out. `:P`
Comment: Thank you ever so much!!

Font Awesome with Half Style CSS


ASP.net Gridview Disable selection of certain rows

Question: I am using Visual Studio 2015 and Entity Framework 6.  I have a gridview and I need to disable selection of rows where the column Status value is "completed".
This is what I have:
<code> <asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False" CellPadding="4" DataKeyNames="OrderID" DataSourceID="SqlDataSource1" ForeColor="#333333" GridLines="None">
        <AlternatingRowStyle BackColor="White" />
        <Columns>

            <asp:TemplateField HeaderText="Delete">
    <ItemTemplate>
        <asp:Button ID="deleteButton" runat="server" CommandName="Delete" Text="Delete"
OnClientClick="return confirm('Are you sure you want to delete this order?');" />
    </ItemTemplate>
</asp:TemplateField>

            <asp:CommandField ShowEditButton="True" ShowSelectButton="True"  />

            <asp:BoundField DataField="OrderID" HeaderText="OrderID" InsertVisible="False" ReadOnly="True" SortExpression="OrderID" />
            <asp:BoundField DataField="CustomerID" HeaderText="CustomerID" SortExpression="CustomerID" />
            <asp:BoundField DataField="OrderDate" HeaderText="Order Date" DataFormatString="{0:MMMM d, yyyy}"  SortExpression="OrderDate" />
            <asp:BoundField DataField="FlowerName" HeaderText="Name" SortExpression="FlowerName" />
            <asp:BoundField DataField="FlowerPrice" HeaderText="Arrangement Price" SortExpression="FlowerPrice" />
            <asp:BoundField DataField="OrderMessage" HeaderText="Message" SortExpression="OrderMessage" />
            <asp:CheckBoxField DataField="Vase" HeaderText="Vase" SortExpression="Vase" />
            <asp:BoundField DataField="OrderCost" HeaderText="Total Cost" SortExpression="OrderCost" />
            <asp:BoundField DataField="DeliverDate" HeaderText="Delivery Date" DataFormatString="{0:MMMM d, yyyy}" SortExpression="DeliverDate" />
            <asp:BoundField DataField="OrderStatus" HeaderText="Order Status" SortExpression="OrderStatus"  Visible="false" />

            <asp:TemplateField>
                <HeaderStyle Width="10%" />
                <ItemTemplate>
                    <asp:Image ID="Image1" runat="server" Width="150px" Height="150px" ImageUrl='<%#GetImagePath(Eval("OrderStatus").ToString())%>' />
                </ItemTemplate>
            </asp:TemplateField>

        </Columns>
</code>
I've tried various methods already and I cannot seem to grasp how.
QUESTION 1:  How to disable selection of rows with status column value of "Completed"
Side Question:  How do I get the CustomerID field to show the table Customers First name/last name instead without messing up my gridview?
Answer: to disable selection of row with status completed
<code>        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
     {
         if (e.Row.RowType == DataControlRowType.DataRow)
         {

             if (e.Row.Cells[8].Text == "completed")//orderstatus index
             {

                 e.Row.Enabled = false;
             }

             else
             {

                e.Row.Enabled = true;

             }

         }
     }
</code>
Comment: Doesn't work, it still lets me edit the row and also removed the image I have showing that its complete.
Comment: what is the index of column orderstatus in your gridview ?
Comment: Working now, image fault was my own.  Thank you for the help!


Does the Context module check block visibility settings?

Question: I am using Drupal 7.14 and the Context module (7.x-3.0-beta4).
I set block visibility settings and the Context module doesn't seems to be checking them before rendering. Only context conditions are validated before rendering a block.
I would like to use PHP code as visibility conditions to render a block, but Context module is not respecting block visibility settings.
Is it a bug? Or context module is designed to respect only Context Visibility settings but not block visibility settings that are enabled in a particular context.
Any idea ?
Answer: Context module ignores Block visibility settings
The Context module does not check (take into account) the "Block visibility settings". If you want that to be the case, then you need to also use the Context Respect module. Some details about this module, from its project page:

Extends the Context module by making it respect default block settings.
This makes it so you can retain your block visibility when assigning them into various Contexts. You can also 'Override' from the block level to ignore Context Respect.

Alternative to Context module
Have a look at the Rules block visibility module as a valid alternative. Refer to my answer to "How to stop a Views block from displaying to admins, such as user/1?" for more details about it.
By using this module as an alternative, you'd only have to create a Rules Component with Rules Conditions that could be identical to the "PHP code" as in your question. However, if you can, you should try to avoid such PHP code if you have other Rules Conditions available that could be used as an alternative to such PHP code.
Answer: Context module does not care what you write on block visiblity settings. It will only check context conditions. Here is the link which will help you have context and drupal core block system work together. http://www.echoditto.com/blog/mixing-context-and-drupals-native-block-ordering-system
Answer: Try the Context Respect Module:

Extends the Context module by making it respect default block
  settings.
This makes it so you can retain your block visibility when assigning
  them into various Contexts. You can also 'Override' from the block
  level to ignore Context Respect.


Oracle sql count

Question: I have below information in table and want to retrive the count if difference between two dates is >= 1.
Id  testdate  exdate
1   20120502  20120501  --> This should included, because diff is 1
2   20120601  20120601  --> This should not included, because diff is 0
3   20120704  20120703  --> This should included, because diff is 1
4   20120803  20120802  --> This should included, because diff is 1

Based on the above data, my select count should return 3.
I am trying the following, but it's not giving any results:
select count(to_char(testdate,'YYYYMMDD')-to_char(exdate,'YYYYMMDD')) from test ;

Answer: select count(*)
  from my_table
 where testdate <> exdate

You really should convert those to a date data-type though... it saves a lot of problems in the long run.
Your query will give you results. It will return 4. It gives you results because as long as the result of testdate - exdate is not null it will return a value for that row.
However, as you're not using dates Oracle will most probably convert those to numbers, which won't help for date comparisons should you do that in the future.
20120901 - 20120831 = 70 -- not 1

Okay, from your comment:

Working with ,if i use down voteaccept select count(*) from test where
  to_char((testdate,'YYYYMMDD') - to_char(exdate,'YYYYMMDD')) >= 1; .But
  count is one of the column.how to retrive above select statement as
  one of the column

you're trying something completely different.
Your dates are actually dates; it's helpful to post this. You're looking for an analytic function, specifically count().
select a.*, count(*) over ( partition by 1 ) as ct
  from my_table a
 where trunc(exdate) <> trunc(testdate)

Note the trunc function, which, without additional parameters will remove the time portion of the date this enabling a direct comparison without resorting to converting the date to a character.
Comment: :I want the count only when difference between 2 dates is >=1.
Comment: If the dates aren't equal then by definition the difference is greater or equal to 1 as they don't have a time component.
Comment: :Getting error ,non numeric charcter was found where numeric expected
Comment: What is the _data type_ of your columns?
Comment: Working with ,if i use

down voteaccept

select count(*)
   from test
  where to_char((testdate,'YYYYMMDD') - to_char(exdate,'YYYYMMDD')) >= 1; .But count is one of the column.how to retrive above select statement as one of the column
Comment: i want above select statement in select clause,like select id,above count stement from test
Comment: Thanks Ben,i ma getting correct results if i am deducting process date from trade date
Answer: select count(*)
   from test
  where to_date(testdate,'YYYYMMDD') - to_date(exdate,'YYYYMMDD') >= 1;

or
select count(*)
   from test
  where to_date(testdate,'YYYYMMDD') <> to_date(exdate,'YYYYMMDD');

Looking at testdate and exdate it looks more like the columns are VARCHAR type so you would require apropriate date conversion.
Comment: Getting error ,non numeric charcter was found where numeric expected
Answer: In Oracle if the type is date you can calculate with them. 1 equal 1 day. 1/24 equals 1 hour.
Your case is rather easy because you could even compare the strings.
SELECT count(*)
  FROM test
 WHERE testdate <> exdate

But it sounds like you want to be able to be variable, so you rather convert them to a date and then you can do
SELECT count(*)
  FROM test
 WHERE to_date(testdate,'YYYYMMDD')-to_date(exdate,'YYYYMMDD') >= 1

I am not sure what you want if testdate minus exdate is -1 or more because the exdate is after testdate. Then you can work with ABS
SELECT count(*)
  FROM test
 WHERE ABS(to_date(testdate,'YYYYMMDD')-to_date(exdate,'YYYYMMDD')) >= 1

Comment: Getting error ,non numeric charcter was found where numeric expected.
Comment: This happens when the character string is not a date. In that case you cannot use to_date. You need to implement an is_date function which returns null instead of an error. This link shows how http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:890580198758

Oracle sql count


Is logistic regression valid if IV is categorical and one level has perfect success rate?

Question: I'm doing a logistic regression in R (using glmer and family='binomial').
I'm measuring how performance in a task differs between 2 factors (2 levels each). The IVs are categorical. (It might be helpful to know that the design is split-plot, with one IV repeated within subjects and subjects nested within the other IV).
I previously did the analysis as a regular GLM by converting the DV to percent correct (i.e. number of items correct / number of items total) for each condition.  However, this method does not allow for item to be used as a random effect.  It also assumes a continuous distribution for the DV and a distribution that goes above 1.0 and below 0.0, both of which are violated.
Therefore, I chose to use logistic regression and code each item (per participant) as a success or failure (DV is 1 or 0). (Subject and Item are random factors in the analysis).
Interestingly, the logistic regression completely eliminates the interaction effect of the 2 IVs, which was significant in the linear regression. (This is even the case if I make the analyses more comparable by not adding item as a random effect.)
One reason why I think this is happening: One of the 4 categories has a very high proportion of participants with perfect accuracy (i.e. 10 of 10 items correct). It seems that this is disproportionately increasing the Beta estimate for that category.
Looking at a graph of the logit function, the mapping between probability and log odds ratio blows up around p=1.0 or 0.0, with very small changes in p producing very large changes in the log odds ratio. (The R analysis uses a binomial distribution, but I would think this still to be related.)
In cases like these, with a categorical IV and perfect accuracy for one of the categories, is logistic regression still valid?  My intuition is that this might make the estimates less robust. If so, what are alternatives to logistic regression that I can perform which will still counter the problems associated with regular GLM?
Answer: All 1s or 0s for some categorical independent variable (or combination of them) in standard logistic regression would be a case of "complete separation". I.e. the maximum likelihood estimate of the log-odds ratio is not finite and any output from a software is suspect. The random effects in the model might make some difference to what should and does happen, but I don't think so.
Standard strategies when this happens are Firth's penalized LR, exact methods - but these do not allow random effects -, or Bayesian methods with (weakly-)informative priors. There may be other reasonable approaches that I am not aware off, but the last one one would be my personal choice. In terms of implementation this may require specifying the model in your Bayesian language of choice (Stan, JAGS, PROC MCMC, BUGS etc., which have interfaces to many platforms/programs such as R, SAS, Python etc.), unless the particular model is already implemented somewhere.
Answer: As @Björn has pointed out, this is called separation.
One other way of approaching this is to ask what it means in the context of your scientific question. Why do you get a perfect prediction here? Is this (a) just the result of your not having very much data in that part of data space or (b) does it reflect something interesting about the world, or (c) is it just an uninteresting feature of the way the variables relate which is an artefact? If it is (a) then @Björn's suggestions may help you but if (b) or (c) you may need to find some way of describing what happened and perhaps even take the extreme step of excluding that level of that factor from your model. This is an interesting situation and I do not think there is a single correct answer.


model bind error while using compiled template with ember.js

Question: I am trying to put ember's template under templates folder.The related codes is here:
define(["ember","holder","emberData","text!/templates/index.html"],function(Ember,Holder,DS,indexTpl){
window.App = Ember.Application.create();
/*Route definition*/
App.Router.map(function() {
    // put your routes here
});
App.IndexRoute = Ember.Route.extend({
  model: function() {
      return this.store.find("listItem");
  },
  setupController: function(controller, model) {
      this._super(controller, model);
      Ember.run.next(function (){Holder.run();});
  }
});
App.ApplicationView = Ember.View.extend({
    defaultTemplate:Ember.Handlebars.compile(indexTpl)
});
App.IndexController = Ember.ArrayController.extend({

});

/*Model definition*/
App.ListItem = DS.Model.extend({
    col1 : DS.attr("string"),
    col2 : DS.attr("string"),
    col3 : DS.attr("string"),
    col4 : DS.attr("string")
});
App.ApplicationAdapter = DS.FixtureAdapter.extend();
App.ListItem.reopenClass({
    FIXTURES:[...]
});
});

Related template:
    ...
    {{#each}}

    {{id}}
    {{col1}}
    {{col2}}
    {{col3}}
    {{col4}}

    {{/each}}
    ...

Test results in chrome browser:
    Uncaught Error: Assertion Failed: The value that #each loops over must be an Array. You passed '(null)' (wrapped in (generated application controller))

Can you help me with this? Thanks for your help in advance!
Answer: You're assigning your index template to your application view. Your template is now going to expect the application model to be an array when you haven't defined it. Assign your index template to your index view:
App.IndexView = Ember.View.extend({
    defulatTemplate: Ember.Handlebars.compile(indexTpl)
});

Comment: Aha,when i saw your post, i knew the mistake i made. It works. Thanks very much!