qid
int64
1
74.7M
question
stringlengths
25
64.6k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
0
115k
response_k
stringlengths
3
61.5k
9,771,514
Here's my implementation of Merge Sort in java ``` import java.io.*; import java.util.Arrays; public class MergeSort { private static int [] LeftSubArray(int [] Array) { int [] leftHalf = Arrays.copyOfRange(Array, 0, Array.length / 2); return leftHalf; } private static int [] RightSubArray(int [] Array) { int [] rightHalf = Arrays.copyOfRange(Array, Array.length / 2 + 1, Array.length); return rightHalf; } private static int [] Sort(int [] A) { if(A.length > 1) { return Merge( Sort( LeftSubArray(A) ) , Sort( RightSubArray(A) ) ); } else { return A; } } private static int [] Merge(int [] B, int [] C) { int [] D = new int[B.length + C.length]; int i,j,k; i = j = k = 0; while(k < D.length) { if(i == B.length) { //Copy the remainder of C into D while(k < D.length){ D[k++] = C[j++]; } } if(j == C.length) { //Copy the remainder of B into D while(k < D.length){ D[k++] = B[i++]; } } if(i<B.length && j<C.length) { if(B[i] > C[j]){ D[k++] = B[i++]; } else { D[k++] = C[j++]; } } } return D; } public static void main(String [] args) { int [] array = {1,3,5,2,4}; int [] sorted = MergeSort.Sort(array); for(int i = 0;i < sorted.length; ++i) { System.out.print(sorted[i] + " "); } } } ``` The output I get is ``` 2 1 ``` From what I can tell there seems a problem with my division of the right sub array. What am I doing wrong?
2012/03/19
[ "https://Stackoverflow.com/questions/9771514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/632447/" ]
Here is the javadoc of copyOfRange: ``` Parameters: original - the array from which a range is to be copied from - the initial index of the range to be copied, **inclusive** to - the final index of the range to be copied, **exclusive**. (This index may lie outside the array.) ``` I highlighted two words you should pay special attention to ;-)
I found a rigth solution in Robert Sedgewick book "Algorithms on java language" 1. Read [here about merge](http://algs4.cs.princeton.edu/22mergesort/)
23,870
It is often reported that Russia has one of the [largest neo-Nazi communities in the world](https://en.wikipedia.org/wiki/Neo-Nazism#Russia). Which to me seems utterly bizarre. As I understand it, Germany's National Socialists in theory and practice, private and public, regarded all Slavic people as little better than Jews or Roma in their racial hierarchy. Their plans to expel, enslave, and murder Russians in order to [colonise the east](https://en.wikipedia.org/wiki/Lebensraum) was an inalienable part of Nazism. How then do those Russians reconcile being Slavic Nazis? I can think of few better examples of Turkeys voting for Christmas. The claim mentioned on Wikipedia is that the German-Soviet non-aggression pact is emphasised as evidence somehow, but that seems to be cherry picking one or two things from a huge amount of evidence to the contrary. Is that an accurate assessment?
2017/08/21
[ "https://politics.stackexchange.com/questions/23870", "https://politics.stackexchange.com", "https://politics.stackexchange.com/users/-1/" ]
The cornerstones of the ideology of Russian Neo-Nazis is Antisemitism and anti-Americanism. They are better traced to the [Black Hundreds](https://en.wikipedia.org/wiki/Black_Hundreds) far-right antisemitic organization of Russian Empire rather than Nazi Germany (even if they adopted a lot of Nazi symbolism). As such, most of Neo-Nazi organizations in Russia are patriotic and imperialist. They believe that the USSR and/or Russian Empire were destroyed by the Jews. They do not trace their origin towards German Nazi Party, and as such, do not claim to share exactly the same ideology. The predominant opinion on WWII, I think, is "Hitler was doing good job in killing Jews, but he should have united with Russia against the West, but he mistakenly invaded Russia." Notice that the Holocaust denial is not widespread in Russian Neo-Nazis, they mostly support the Holocaust, or use it to accuse the Jews of being evil ("look, everyone hates Jews, this cannot be for nothing") or claim Russians saved the Jews, perhaps they should not, as the Jews are not grateful enough. [![The Neo-Nazis in Russia are mostly anti-American and Antisemitic. They think the Jews destroyed the USSR so to steal property.](https://i.stack.imgur.com/bk6Ld.jpg)](https://i.stack.imgur.com/bk6Ld.jpg) The Neo-Nazis in Russia are mostly anti-American and Antisemitic. They think the Jews destroyed the USSR so to steal property. I would add that in the Eastern European countries bordering Russia, such as Ukraine, Belarus, and the Baltic, there are many Neo-Nazis, but they have very different ideology compared to Russian Neo-Nazis. They are usually very anti-Russian, pro-Western, pro-American and less antisemitic. Their ideology is mostly based around local pro-Nazi collaborationist units or organizations during WWII. They often engage in denial that their local collaborationist units participated in Holocaust and other atrocities (it was all done by the Germans, you know, but we only fought for freedom against Stalinism) and/or claim it was a mistake, excess, exaggerated (by the Soviets), or because of the general cruelty of the war. [![enter image description here](https://i.stack.imgur.com/0ijis.jpg)](https://i.stack.imgur.com/0ijis.jpg) The Neo-Nazis in Ukraine are predominantly anti-Russian and pro-American. The pro-Russian Nazis are usually more racist and anti-Muslim as well, at least demanding Muslims to be controlled, deported to native areas and giving preference to Russian culture, while pro-Western Nazis often consider local Muslims as "brothers who also suffered from Russian oppression". Regarding Russian history, the pro-Western Nazis usually do not differentiate between Russian Empire, the USSR and modern Russia, they hate all, but the most hated leaders are probably, Catherine II for Russian Empire, Stalin for the USSR and Putin for modern Russia. The pro-Russian Neo-Nazis are OK about Russian Empire, view the Revolution of 1917 as Judeo-Masonic conspiracy against Russian people, view Stalin in positive light for purging the government from Jews, and usually positive about post-Stalin USSR while hating some of its leaders such as Khrushchev and Gorbachev as traitors. They very much hate Yeltsin, but divided about Putin, with their attitude towards him gradually worsens with time.
You are confusing 2 principles that in 1930s Germany came together in a single political group: National Socialism and German racial supremacy. Those two don't need to go together. In fact anywhere except in Germany they can't go together. In Russia, national socialism would and does go together with Russian racial supremacy. In Zaire (to give an example) it would be national socialism with Zairian racial supremacy. This is because the very nature of national socialism makes its adherents consider themselves (and with that their race/nationality) superior in all regards to everyone else. Hence Russian nazis think themselves superior to Germans, while German nazis think themselves superior to Russians.
23,870
It is often reported that Russia has one of the [largest neo-Nazi communities in the world](https://en.wikipedia.org/wiki/Neo-Nazism#Russia). Which to me seems utterly bizarre. As I understand it, Germany's National Socialists in theory and practice, private and public, regarded all Slavic people as little better than Jews or Roma in their racial hierarchy. Their plans to expel, enslave, and murder Russians in order to [colonise the east](https://en.wikipedia.org/wiki/Lebensraum) was an inalienable part of Nazism. How then do those Russians reconcile being Slavic Nazis? I can think of few better examples of Turkeys voting for Christmas. The claim mentioned on Wikipedia is that the German-Soviet non-aggression pact is emphasised as evidence somehow, but that seems to be cherry picking one or two things from a huge amount of evidence to the contrary. Is that an accurate assessment?
2017/08/21
[ "https://politics.stackexchange.com/questions/23870", "https://politics.stackexchange.com", "https://politics.stackexchange.com/users/-1/" ]
The cornerstones of the ideology of Russian Neo-Nazis is Antisemitism and anti-Americanism. They are better traced to the [Black Hundreds](https://en.wikipedia.org/wiki/Black_Hundreds) far-right antisemitic organization of Russian Empire rather than Nazi Germany (even if they adopted a lot of Nazi symbolism). As such, most of Neo-Nazi organizations in Russia are patriotic and imperialist. They believe that the USSR and/or Russian Empire were destroyed by the Jews. They do not trace their origin towards German Nazi Party, and as such, do not claim to share exactly the same ideology. The predominant opinion on WWII, I think, is "Hitler was doing good job in killing Jews, but he should have united with Russia against the West, but he mistakenly invaded Russia." Notice that the Holocaust denial is not widespread in Russian Neo-Nazis, they mostly support the Holocaust, or use it to accuse the Jews of being evil ("look, everyone hates Jews, this cannot be for nothing") or claim Russians saved the Jews, perhaps they should not, as the Jews are not grateful enough. [![The Neo-Nazis in Russia are mostly anti-American and Antisemitic. They think the Jews destroyed the USSR so to steal property.](https://i.stack.imgur.com/bk6Ld.jpg)](https://i.stack.imgur.com/bk6Ld.jpg) The Neo-Nazis in Russia are mostly anti-American and Antisemitic. They think the Jews destroyed the USSR so to steal property. I would add that in the Eastern European countries bordering Russia, such as Ukraine, Belarus, and the Baltic, there are many Neo-Nazis, but they have very different ideology compared to Russian Neo-Nazis. They are usually very anti-Russian, pro-Western, pro-American and less antisemitic. Their ideology is mostly based around local pro-Nazi collaborationist units or organizations during WWII. They often engage in denial that their local collaborationist units participated in Holocaust and other atrocities (it was all done by the Germans, you know, but we only fought for freedom against Stalinism) and/or claim it was a mistake, excess, exaggerated (by the Soviets), or because of the general cruelty of the war. [![enter image description here](https://i.stack.imgur.com/0ijis.jpg)](https://i.stack.imgur.com/0ijis.jpg) The Neo-Nazis in Ukraine are predominantly anti-Russian and pro-American. The pro-Russian Nazis are usually more racist and anti-Muslim as well, at least demanding Muslims to be controlled, deported to native areas and giving preference to Russian culture, while pro-Western Nazis often consider local Muslims as "brothers who also suffered from Russian oppression". Regarding Russian history, the pro-Western Nazis usually do not differentiate between Russian Empire, the USSR and modern Russia, they hate all, but the most hated leaders are probably, Catherine II for Russian Empire, Stalin for the USSR and Putin for modern Russia. The pro-Russian Neo-Nazis are OK about Russian Empire, view the Revolution of 1917 as Judeo-Masonic conspiracy against Russian people, view Stalin in positive light for purging the government from Jews, and usually positive about post-Stalin USSR while hating some of its leaders such as Khrushchev and Gorbachev as traitors. They very much hate Yeltsin, but divided about Putin, with their attitude towards him gradually worsens with time.
> > There is nothing bizarre when come to politics and ideology. – mootmoot > > > To be honest those people are so uneducated and stupid you shouldn't expect a rationale out of them. – Bregalad > > > There are groups of people with similar mindsets everywhere, from all races. The only strange thing is that in Russia they did chose the "Nazi" label for themselves (...) I am betting on "brand recognition", even if that implies that implies twisting historical facts and doctrine a lot. – SJuan76 > > > Many of the comments here are right to suggest that most political movements that emphasise cultural imperialism and 'racial superiority' do not need any ideological coherence, but only a self-serving agenda and the right socio-economic 'climate that favors growth.' [Wikipedia](https://en.m.wikipedia.org/wiki/Neo-Nazism) suggests that Russia has had this climate after the collapse of the USSR: > > The dissolution of the Soviet Union in 1991 caused great economic and social problems, including widespread unemployment and poverty. Several far right paramilitary organizations were able to tap into popular discontent, particularly among marginalized, lesser educated and unemployed youths. Of the three major age groups β€” youths, adults, and the elderly β€” youths may have been hit the hardest. > > > In addition, one of the paradoxical psychological tactics often employed by a sub-section of human beings and societies to maintain internal sense of dignity during or after oppression is to *identify with the oppressor.*
23,870
It is often reported that Russia has one of the [largest neo-Nazi communities in the world](https://en.wikipedia.org/wiki/Neo-Nazism#Russia). Which to me seems utterly bizarre. As I understand it, Germany's National Socialists in theory and practice, private and public, regarded all Slavic people as little better than Jews or Roma in their racial hierarchy. Their plans to expel, enslave, and murder Russians in order to [colonise the east](https://en.wikipedia.org/wiki/Lebensraum) was an inalienable part of Nazism. How then do those Russians reconcile being Slavic Nazis? I can think of few better examples of Turkeys voting for Christmas. The claim mentioned on Wikipedia is that the German-Soviet non-aggression pact is emphasised as evidence somehow, but that seems to be cherry picking one or two things from a huge amount of evidence to the contrary. Is that an accurate assessment?
2017/08/21
[ "https://politics.stackexchange.com/questions/23870", "https://politics.stackexchange.com", "https://politics.stackexchange.com/users/-1/" ]
The cornerstones of the ideology of Russian Neo-Nazis is Antisemitism and anti-Americanism. They are better traced to the [Black Hundreds](https://en.wikipedia.org/wiki/Black_Hundreds) far-right antisemitic organization of Russian Empire rather than Nazi Germany (even if they adopted a lot of Nazi symbolism). As such, most of Neo-Nazi organizations in Russia are patriotic and imperialist. They believe that the USSR and/or Russian Empire were destroyed by the Jews. They do not trace their origin towards German Nazi Party, and as such, do not claim to share exactly the same ideology. The predominant opinion on WWII, I think, is "Hitler was doing good job in killing Jews, but he should have united with Russia against the West, but he mistakenly invaded Russia." Notice that the Holocaust denial is not widespread in Russian Neo-Nazis, they mostly support the Holocaust, or use it to accuse the Jews of being evil ("look, everyone hates Jews, this cannot be for nothing") or claim Russians saved the Jews, perhaps they should not, as the Jews are not grateful enough. [![The Neo-Nazis in Russia are mostly anti-American and Antisemitic. They think the Jews destroyed the USSR so to steal property.](https://i.stack.imgur.com/bk6Ld.jpg)](https://i.stack.imgur.com/bk6Ld.jpg) The Neo-Nazis in Russia are mostly anti-American and Antisemitic. They think the Jews destroyed the USSR so to steal property. I would add that in the Eastern European countries bordering Russia, such as Ukraine, Belarus, and the Baltic, there are many Neo-Nazis, but they have very different ideology compared to Russian Neo-Nazis. They are usually very anti-Russian, pro-Western, pro-American and less antisemitic. Their ideology is mostly based around local pro-Nazi collaborationist units or organizations during WWII. They often engage in denial that their local collaborationist units participated in Holocaust and other atrocities (it was all done by the Germans, you know, but we only fought for freedom against Stalinism) and/or claim it was a mistake, excess, exaggerated (by the Soviets), or because of the general cruelty of the war. [![enter image description here](https://i.stack.imgur.com/0ijis.jpg)](https://i.stack.imgur.com/0ijis.jpg) The Neo-Nazis in Ukraine are predominantly anti-Russian and pro-American. The pro-Russian Nazis are usually more racist and anti-Muslim as well, at least demanding Muslims to be controlled, deported to native areas and giving preference to Russian culture, while pro-Western Nazis often consider local Muslims as "brothers who also suffered from Russian oppression". Regarding Russian history, the pro-Western Nazis usually do not differentiate between Russian Empire, the USSR and modern Russia, they hate all, but the most hated leaders are probably, Catherine II for Russian Empire, Stalin for the USSR and Putin for modern Russia. The pro-Russian Neo-Nazis are OK about Russian Empire, view the Revolution of 1917 as Judeo-Masonic conspiracy against Russian people, view Stalin in positive light for purging the government from Jews, and usually positive about post-Stalin USSR while hating some of its leaders such as Khrushchev and Gorbachev as traitors. They very much hate Yeltsin, but divided about Putin, with their attitude towards him gradually worsens with time.
As is my preference, I'm going to give a philosophical answer to this question, rather than a strictly political one. Following Orwell's [Notes on Nationalism](https://www.orwellfoundation.com/the-orwell-foundation/orwell/essays-and-other-works/notes-on-nationalism/), we can gain some insight into the psychology at work here. The first thing to consider is the way that Orwell defines a nationalist. In his words: > > A nationalist is one who thinks solely, or mainly, in terms of > competitive prestige. He may be a positive or a negative nationalist – > that is, he may use his mental energy either in boosting or in > denigrating – but at any rate his thoughts always turn on victories, > defeats, triumphs and humiliations. He sees history, especially > contemporary history, as the endless rise and decline of great power > units, and every event that happens seems to him a demonstration that > his own side is on the up-grade and some hated rival is on the > down-grade. But finally, it is important not to confuse nationalism > with mere worship of success. The nationalist does not go on the > principle of simply ganging up with the strongest side. On the > contrary, having picked his side, he persuades himself that it is the > strongest, and is able to stick to his belief even when the facts are > overwhelmingly against him. Nationalism is power hunger tempered by > self-deception. Every nationalist is capable of the most flagrant > dishonesty, but he is also – since he is conscious of serving > something bigger than himself – unshakeably certain of being in the > right. > > > This notion of *competitive prestige* is central. The nationalist mindset compulsively seeks out contexts in which it can claim superiority for its group. The nature of the context is largely irrelevant: it might lionize a group success or denigrate some failing of another group; it might shift the group it targets as it sees new opportunities to establish prestige; it might be inconsistent from case to case, for example praising some action of its own group while demonizing the same action from other groups. Competition is everything; group prestige is everything; anything else is incidental and changeable. Second, Orwell notes that: > > Every nationalist is haunted by the belief that the past can be > altered. He spends part of his time in a fantasy world in which things > happen as they should – in which, for example, the Spanish Armada was > a success or the Russian Revolution was crushed in 1918 – and he will > transfer fragments of this world to the history books whenever > possible. Much of the propagandist writing of our time amounts to > plain forgery. Material facts are suppressed, dates altered, > quotations removed from their context and doctored so as to change > their meaning. Events which, it is felt, ought not to have happened > are left unmentioned and ultimately denied. [...] The primary aim of > propaganda is, of course, to influence contemporary opinion, but those > who rewrite history do probably believe with part of their minds that > they are actually thrusting facts into the past. > > > This tendency to ignore historical facticity or to actively thrust imagined facts into the past is part of that competitive process. In order to solidify the prestige of the group, inconvenient facts are overlooked or reconstructed, and convenient myths are elevated to the status of facts. The nationalist mindset has no compunctions about this, as noted, this is all done for the (from its perspective inarguably just) defense and promotion of the cause. With respect to Russian Neo-Nazis, both of these factors come into play. They focus on those historical facts that cement their identity with German Nazism; they ignore those historical facts which would place them in the 'inferior' category of German Nazism; they likely revise history to place their group within the superior 'aryan' category. History does not really matter to them, as nationalists. What matters is painting their group as strong, morally virtuous, decisive, virile, or whatever other qualities define them as superior. I suspect even their attachment to Nazism is a convenient fiction; something they will all fervently avow to, but which ultimately is only appreciated for the air of superiority it gives them.
23,870
It is often reported that Russia has one of the [largest neo-Nazi communities in the world](https://en.wikipedia.org/wiki/Neo-Nazism#Russia). Which to me seems utterly bizarre. As I understand it, Germany's National Socialists in theory and practice, private and public, regarded all Slavic people as little better than Jews or Roma in their racial hierarchy. Their plans to expel, enslave, and murder Russians in order to [colonise the east](https://en.wikipedia.org/wiki/Lebensraum) was an inalienable part of Nazism. How then do those Russians reconcile being Slavic Nazis? I can think of few better examples of Turkeys voting for Christmas. The claim mentioned on Wikipedia is that the German-Soviet non-aggression pact is emphasised as evidence somehow, but that seems to be cherry picking one or two things from a huge amount of evidence to the contrary. Is that an accurate assessment?
2017/08/21
[ "https://politics.stackexchange.com/questions/23870", "https://politics.stackexchange.com", "https://politics.stackexchange.com/users/-1/" ]
You are confusing 2 principles that in 1930s Germany came together in a single political group: National Socialism and German racial supremacy. Those two don't need to go together. In fact anywhere except in Germany they can't go together. In Russia, national socialism would and does go together with Russian racial supremacy. In Zaire (to give an example) it would be national socialism with Zairian racial supremacy. This is because the very nature of national socialism makes its adherents consider themselves (and with that their race/nationality) superior in all regards to everyone else. Hence Russian nazis think themselves superior to Germans, while German nazis think themselves superior to Russians.
> > There is nothing bizarre when come to politics and ideology. – mootmoot > > > To be honest those people are so uneducated and stupid you shouldn't expect a rationale out of them. – Bregalad > > > There are groups of people with similar mindsets everywhere, from all races. The only strange thing is that in Russia they did chose the "Nazi" label for themselves (...) I am betting on "brand recognition", even if that implies that implies twisting historical facts and doctrine a lot. – SJuan76 > > > Many of the comments here are right to suggest that most political movements that emphasise cultural imperialism and 'racial superiority' do not need any ideological coherence, but only a self-serving agenda and the right socio-economic 'climate that favors growth.' [Wikipedia](https://en.m.wikipedia.org/wiki/Neo-Nazism) suggests that Russia has had this climate after the collapse of the USSR: > > The dissolution of the Soviet Union in 1991 caused great economic and social problems, including widespread unemployment and poverty. Several far right paramilitary organizations were able to tap into popular discontent, particularly among marginalized, lesser educated and unemployed youths. Of the three major age groups β€” youths, adults, and the elderly β€” youths may have been hit the hardest. > > > In addition, one of the paradoxical psychological tactics often employed by a sub-section of human beings and societies to maintain internal sense of dignity during or after oppression is to *identify with the oppressor.*
23,870
It is often reported that Russia has one of the [largest neo-Nazi communities in the world](https://en.wikipedia.org/wiki/Neo-Nazism#Russia). Which to me seems utterly bizarre. As I understand it, Germany's National Socialists in theory and practice, private and public, regarded all Slavic people as little better than Jews or Roma in their racial hierarchy. Their plans to expel, enslave, and murder Russians in order to [colonise the east](https://en.wikipedia.org/wiki/Lebensraum) was an inalienable part of Nazism. How then do those Russians reconcile being Slavic Nazis? I can think of few better examples of Turkeys voting for Christmas. The claim mentioned on Wikipedia is that the German-Soviet non-aggression pact is emphasised as evidence somehow, but that seems to be cherry picking one or two things from a huge amount of evidence to the contrary. Is that an accurate assessment?
2017/08/21
[ "https://politics.stackexchange.com/questions/23870", "https://politics.stackexchange.com", "https://politics.stackexchange.com/users/-1/" ]
You are confusing 2 principles that in 1930s Germany came together in a single political group: National Socialism and German racial supremacy. Those two don't need to go together. In fact anywhere except in Germany they can't go together. In Russia, national socialism would and does go together with Russian racial supremacy. In Zaire (to give an example) it would be national socialism with Zairian racial supremacy. This is because the very nature of national socialism makes its adherents consider themselves (and with that their race/nationality) superior in all regards to everyone else. Hence Russian nazis think themselves superior to Germans, while German nazis think themselves superior to Russians.
As is my preference, I'm going to give a philosophical answer to this question, rather than a strictly political one. Following Orwell's [Notes on Nationalism](https://www.orwellfoundation.com/the-orwell-foundation/orwell/essays-and-other-works/notes-on-nationalism/), we can gain some insight into the psychology at work here. The first thing to consider is the way that Orwell defines a nationalist. In his words: > > A nationalist is one who thinks solely, or mainly, in terms of > competitive prestige. He may be a positive or a negative nationalist – > that is, he may use his mental energy either in boosting or in > denigrating – but at any rate his thoughts always turn on victories, > defeats, triumphs and humiliations. He sees history, especially > contemporary history, as the endless rise and decline of great power > units, and every event that happens seems to him a demonstration that > his own side is on the up-grade and some hated rival is on the > down-grade. But finally, it is important not to confuse nationalism > with mere worship of success. The nationalist does not go on the > principle of simply ganging up with the strongest side. On the > contrary, having picked his side, he persuades himself that it is the > strongest, and is able to stick to his belief even when the facts are > overwhelmingly against him. Nationalism is power hunger tempered by > self-deception. Every nationalist is capable of the most flagrant > dishonesty, but he is also – since he is conscious of serving > something bigger than himself – unshakeably certain of being in the > right. > > > This notion of *competitive prestige* is central. The nationalist mindset compulsively seeks out contexts in which it can claim superiority for its group. The nature of the context is largely irrelevant: it might lionize a group success or denigrate some failing of another group; it might shift the group it targets as it sees new opportunities to establish prestige; it might be inconsistent from case to case, for example praising some action of its own group while demonizing the same action from other groups. Competition is everything; group prestige is everything; anything else is incidental and changeable. Second, Orwell notes that: > > Every nationalist is haunted by the belief that the past can be > altered. He spends part of his time in a fantasy world in which things > happen as they should – in which, for example, the Spanish Armada was > a success or the Russian Revolution was crushed in 1918 – and he will > transfer fragments of this world to the history books whenever > possible. Much of the propagandist writing of our time amounts to > plain forgery. Material facts are suppressed, dates altered, > quotations removed from their context and doctored so as to change > their meaning. Events which, it is felt, ought not to have happened > are left unmentioned and ultimately denied. [...] The primary aim of > propaganda is, of course, to influence contemporary opinion, but those > who rewrite history do probably believe with part of their minds that > they are actually thrusting facts into the past. > > > This tendency to ignore historical facticity or to actively thrust imagined facts into the past is part of that competitive process. In order to solidify the prestige of the group, inconvenient facts are overlooked or reconstructed, and convenient myths are elevated to the status of facts. The nationalist mindset has no compunctions about this, as noted, this is all done for the (from its perspective inarguably just) defense and promotion of the cause. With respect to Russian Neo-Nazis, both of these factors come into play. They focus on those historical facts that cement their identity with German Nazism; they ignore those historical facts which would place them in the 'inferior' category of German Nazism; they likely revise history to place their group within the superior 'aryan' category. History does not really matter to them, as nationalists. What matters is painting their group as strong, morally virtuous, decisive, virile, or whatever other qualities define them as superior. I suspect even their attachment to Nazism is a convenient fiction; something they will all fervently avow to, but which ultimately is only appreciated for the air of superiority it gives them.
23,870
It is often reported that Russia has one of the [largest neo-Nazi communities in the world](https://en.wikipedia.org/wiki/Neo-Nazism#Russia). Which to me seems utterly bizarre. As I understand it, Germany's National Socialists in theory and practice, private and public, regarded all Slavic people as little better than Jews or Roma in their racial hierarchy. Their plans to expel, enslave, and murder Russians in order to [colonise the east](https://en.wikipedia.org/wiki/Lebensraum) was an inalienable part of Nazism. How then do those Russians reconcile being Slavic Nazis? I can think of few better examples of Turkeys voting for Christmas. The claim mentioned on Wikipedia is that the German-Soviet non-aggression pact is emphasised as evidence somehow, but that seems to be cherry picking one or two things from a huge amount of evidence to the contrary. Is that an accurate assessment?
2017/08/21
[ "https://politics.stackexchange.com/questions/23870", "https://politics.stackexchange.com", "https://politics.stackexchange.com/users/-1/" ]
> > There is nothing bizarre when come to politics and ideology. – mootmoot > > > To be honest those people are so uneducated and stupid you shouldn't expect a rationale out of them. – Bregalad > > > There are groups of people with similar mindsets everywhere, from all races. The only strange thing is that in Russia they did chose the "Nazi" label for themselves (...) I am betting on "brand recognition", even if that implies that implies twisting historical facts and doctrine a lot. – SJuan76 > > > Many of the comments here are right to suggest that most political movements that emphasise cultural imperialism and 'racial superiority' do not need any ideological coherence, but only a self-serving agenda and the right socio-economic 'climate that favors growth.' [Wikipedia](https://en.m.wikipedia.org/wiki/Neo-Nazism) suggests that Russia has had this climate after the collapse of the USSR: > > The dissolution of the Soviet Union in 1991 caused great economic and social problems, including widespread unemployment and poverty. Several far right paramilitary organizations were able to tap into popular discontent, particularly among marginalized, lesser educated and unemployed youths. Of the three major age groups β€” youths, adults, and the elderly β€” youths may have been hit the hardest. > > > In addition, one of the paradoxical psychological tactics often employed by a sub-section of human beings and societies to maintain internal sense of dignity during or after oppression is to *identify with the oppressor.*
As is my preference, I'm going to give a philosophical answer to this question, rather than a strictly political one. Following Orwell's [Notes on Nationalism](https://www.orwellfoundation.com/the-orwell-foundation/orwell/essays-and-other-works/notes-on-nationalism/), we can gain some insight into the psychology at work here. The first thing to consider is the way that Orwell defines a nationalist. In his words: > > A nationalist is one who thinks solely, or mainly, in terms of > competitive prestige. He may be a positive or a negative nationalist – > that is, he may use his mental energy either in boosting or in > denigrating – but at any rate his thoughts always turn on victories, > defeats, triumphs and humiliations. He sees history, especially > contemporary history, as the endless rise and decline of great power > units, and every event that happens seems to him a demonstration that > his own side is on the up-grade and some hated rival is on the > down-grade. But finally, it is important not to confuse nationalism > with mere worship of success. The nationalist does not go on the > principle of simply ganging up with the strongest side. On the > contrary, having picked his side, he persuades himself that it is the > strongest, and is able to stick to his belief even when the facts are > overwhelmingly against him. Nationalism is power hunger tempered by > self-deception. Every nationalist is capable of the most flagrant > dishonesty, but he is also – since he is conscious of serving > something bigger than himself – unshakeably certain of being in the > right. > > > This notion of *competitive prestige* is central. The nationalist mindset compulsively seeks out contexts in which it can claim superiority for its group. The nature of the context is largely irrelevant: it might lionize a group success or denigrate some failing of another group; it might shift the group it targets as it sees new opportunities to establish prestige; it might be inconsistent from case to case, for example praising some action of its own group while demonizing the same action from other groups. Competition is everything; group prestige is everything; anything else is incidental and changeable. Second, Orwell notes that: > > Every nationalist is haunted by the belief that the past can be > altered. He spends part of his time in a fantasy world in which things > happen as they should – in which, for example, the Spanish Armada was > a success or the Russian Revolution was crushed in 1918 – and he will > transfer fragments of this world to the history books whenever > possible. Much of the propagandist writing of our time amounts to > plain forgery. Material facts are suppressed, dates altered, > quotations removed from their context and doctored so as to change > their meaning. Events which, it is felt, ought not to have happened > are left unmentioned and ultimately denied. [...] The primary aim of > propaganda is, of course, to influence contemporary opinion, but those > who rewrite history do probably believe with part of their minds that > they are actually thrusting facts into the past. > > > This tendency to ignore historical facticity or to actively thrust imagined facts into the past is part of that competitive process. In order to solidify the prestige of the group, inconvenient facts are overlooked or reconstructed, and convenient myths are elevated to the status of facts. The nationalist mindset has no compunctions about this, as noted, this is all done for the (from its perspective inarguably just) defense and promotion of the cause. With respect to Russian Neo-Nazis, both of these factors come into play. They focus on those historical facts that cement their identity with German Nazism; they ignore those historical facts which would place them in the 'inferior' category of German Nazism; they likely revise history to place their group within the superior 'aryan' category. History does not really matter to them, as nationalists. What matters is painting their group as strong, morally virtuous, decisive, virile, or whatever other qualities define them as superior. I suspect even their attachment to Nazism is a convenient fiction; something they will all fervently avow to, but which ultimately is only appreciated for the air of superiority it gives them.
47,938,464
i set up Google Analytics for my iOS-App and it is basically working fine (Screen Tracking, Purchases,...), except the install Campaign tracking is not ok. I saw a similar question here which is not solved: [Google analytics iOS campaign tracking testing on development](https://stackoverflow.com/questions/28428224/google-analytics-ios-campaign-tracking-testing-on-development) This is the guide i used to implement (is in Objective-C): <https://developers.google.com/analytics/devguides/collection/ios/v3/campaigns#general-campaigns> I see in my Google Analytics Dashboard the referrer installs, but no campaign installs. This is a test Url [https://click.google-analytics.com/redirect?tid=UA-51157298-2&url=https%3A%2F%2Fitunes.apple.com%2Fat%2Fapp%2Fbikersos-motorrad-unfall-sos%2Fid980886530&aid=com.BikerApps.BikerSOS&idfa=%{idfa}&cs=test\_source&cm=test\_medium&cn=test\_campaign&cc=test\_campaign\_content&ck=test\_term](https://click.google-analytics.com/redirect?tid=UA-51157298-2&url=https%3A%2F%2Fitunes.apple.com%2Fat%2Fapp%2Fbikersos-motorrad-unfall-sos%2Fid980886530&aid=com.BikerApps.BikerSOS&idfa=%25%7Bidfa%7D&cs=test_source&cm=test_medium&cn=test_campaign&cc=test_campaign_content&ck=test_term) which i generated here: <https://developers.google.com/analytics/devguides/collection/ios/v3/campaigns#url-builder> My Code which should track the install is the following: AppDelegate: ``` //Method where app parses any URL parameters used in the launch func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { //Track google Analytics URL GAService.shared.trackURL(url) //some other handlers here .... return true/false } ``` GAService Singleton: ``` @objc public class GAService : NSObject { private let trackID : String = "UA-xxxxxx-x" var trackGoogleAnalytics : Bool = Constants.Analytics.trackGoogleAnalytics private let UTM_SOURCE_KEY : String = "xxx" private let UTM_MEDIUM_KEY : String = "xxx" private let UTM_CAMPAIGN_KEY : String = "xxx" var trackUncaughtExceptions : Bool = true var tracker : GAITracker? = nil static let shared = GAService() var UtmSource : String { get { if let utm = UserDefaults.standard.string(forKey: UTM_SOURCE_KEY) { return utm } return "" } set { if UserDefaults.standard.string(forKey: UTM_SOURCE_KEY) == nil { UserDefaults.standard.set(newValue, forKey: UTM_SOURCE_KEY) UserDefaults.standard.synchronize() } } } var UtmCampaign : String { get { if let utm = UserDefaults.standard.string(forKey: UTM_CAMPAIGN_KEY) { return utm } return "" } set { if UserDefaults.standard.string(forKey: UTM_CAMPAIGN_KEY) == nil { UserDefaults.standard.set(newValue, forKey: UTM_CAMPAIGN_KEY) UserDefaults.standard.synchronize() } } } var UtmMedium : String { get { if let utm = UserDefaults.standard.string(forKey: UTM_MEDIUM_KEY) { return utm } return "" } set { if UserDefaults.standard.string(forKey: UTM_MEDIUM_KEY) == nil { UserDefaults.standard.set(newValue, forKey: UTM_MEDIUM_KEY) UserDefaults.standard.synchronize() } } } private override init() { super.init() if(trackGoogleAnalytics) { tracker = GAI.sharedInstance().tracker(withTrackingId: trackID) tracker!.allowIDFACollection = true GAI.sharedInstance().trackUncaughtExceptions = trackUncaughtExceptions GAI.sharedInstance().logger.logLevel = GAILogLevel.error GAI.sharedInstance().dispatchInterval = 1 } } public func trackURL(_ url : URL){ let urlString = url.absoluteString // setCampaignParametersFromUrl: parses Google Analytics campaign ("UTM") // parameters from a string url into a Map that can be set on a Tracker. let hitParams : GAIDictionaryBuilder = GAIDictionaryBuilder() // Set campaign data on the map, not the tracker directly because it only // needs to be sent once. hitParams.setCampaignParametersFromUrl(urlString) // Campaign source is the only required campaign field. If previous call // did not set a campaign source, use the hostname as a referrer instead. if((hitParams.get(kGAICampaignSource) != nil) && (url.host ?? "").length() != 0) { hitParams.set("referrer", forKey: kGAICampaignMedium) hitParams.set(url.host, forKey: kGAICampaignSource) } let hitParamsDict : [AnyHashable : Any] = hitParams.build() as Dictionary as [AnyHashable : Any] if(hitParamsDict.count > 0) { // A screen name is required for a screen view. let source : String? = hitParams.get(kGAICampaignSource) let medium : String? = hitParams.get(kGAICampaignMedium) let campaign : String? = hitParams.get(kGAICampaignName) if(source != nil || medium != nil || campaign != nil) { tracker?.set(kGAIScreenName, value: "openUrl") GAService.shared.UtmSource = source ?? "" GAService.shared.UtmMedium = medium ?? "" GAService.shared.UtmCampaign = campaign ?? "" } // SDK Version 3.08 and up. //[tracker send:[[[GAIDictionaryBuilder createScreenView] setAll:hitParamsDict] build]]; let sendDict : [AnyHashable : Any] = GAIDictionaryBuilder.createScreenView().setAll(hitParamsDict).build() as Dictionary as [AnyHashable : Any] tracker?.send(sendDict) tracker?.set(kGAIScreenName, value: nil) } } ``` As i have to set a screenName for such a tracking i defined openUrl as a constant and set it to nil afterwards i sent the dictionary. I hope anybody can see what i'm doing wrong thank you in advance
2017/12/22
[ "https://Stackoverflow.com/questions/47938464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4752155/" ]
I used it with deep link where I decide the navigation: ``` let tracker1 = GAI.sharedInstance().tracker(withTrackingId: "...") let hitParams = GAIDictionaryBuilder() hitParams.setCampaignParametersFromUrl(path) let medium = self.getQueryStringParameter(url: path, param: "utm_medium") hitParams.set(medium, forKey: kGAICampaignMedium) hitParams.set(path, forKey: kGAICampaignSource) let hitParamsDict = hitParams.build() tracker1?.allowIDFACollection = true tracker1?.set(kGAIScreenName, value: "...") tracker1?.send(GAIDictionaryBuilder.createScreenView().setAll(hitParamsDict as? [AnyHashable : Any]).build() as? [AnyHashable : Any]) // this is for url utm_medium parameter /* func getQueryStringParameter(url: String, param: String) -> String? { guard let url = URLComponents(string: url) else { return nil } return url.queryItems?.first(where: { $0.name == param })?.value }*/ ``` then I saw the source on google analytics.
I think that Google Analytics docs are very poor on this subject. If you look carefully in what is written in the main guide for "Campaign Measurement" it says *"After an app has been installed, it may be launched by referrals from ad campaigns, websites, or other apps"* and Google gives an example with custom url scheme which is handled. Hopefully, there is another guide <https://developers.google.com/analytics/solutions/mobile-campaign-deep-link> which describes how to use deep linking for campaign measurement. So, if you want to track campaign measurement you must use either **Universal Links mechanism** or **custom url scheme** for your application. Universal Links mechanism is the preferred way if you have backend and hence can decide where to redirect user: in iTunes or in application. Assume, you have a site link *<https://example.com/openapp>* which redirects user to iTunes Connect. You should insert you Universal Link address (*<https://example.com/openapp>*) in the generator <https://developers.google.com/analytics/devguides/collection/ios/v3/campaigns#url-builder>.
116,276
I'm used to python, so this is a bit confusing to me. I'm trying to take in input, line-by-line, until a user inputs a certain number. The numbers will be stored in an array to apply some statistical maths to them. Currently, I have a main class, the stats classes, and an "reading" class. Two Questions: 1. I can't seem to get the input loop to work out, what's the best practice for doing so. 2. What is the object-type going to be for the reading method? A double[], or an ArrayList? 1. How do I declare method-type to be an arraylist? 2. How do I prevent the array from having more than 1000 values stored within it? Let me show what I have so far: ``` public static java.util.ArrayList readRange(double end_signal){ //read in the range and stop at end_signal ArrayList input = new ArrayList(); Scanner kbd = new Scanner( System.in ); int count = 0; do{ input.add(kbd.nextDouble()); System.out.println(input); //debugging ++count; } while(input(--count) != end_signal); return input; } ``` Any help would be appreciated, pardon my newbieness...
2008/09/22
[ "https://Stackoverflow.com/questions/116276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10636/" ]
What you need in your loop condition is: ``` while ( input.get( input.size()-1 ) != end_signal ); ``` What you're doing is decrementing the counter variable. Also you should declare the `ArrayList` like so: ``` ArrayList<Double> list = new ArrayList<Double>(); ``` This makes the list type-specific and allows the condition as given. Otherwise there's extra casting.
\*\* ``` public static java.util.ArrayList readRange(double end_signal) { //read in the range and stop at end_signal ArrayList input = new ArrayList(); Scanner kbd = new Scanner(System. in ); int count = 0; do { input.add(Double.valueOf(kbd.next())); System.out.println(input); //debugging ++count; } while (input(--count) != end_signal); return input; } ``` \*\*
116,276
I'm used to python, so this is a bit confusing to me. I'm trying to take in input, line-by-line, until a user inputs a certain number. The numbers will be stored in an array to apply some statistical maths to them. Currently, I have a main class, the stats classes, and an "reading" class. Two Questions: 1. I can't seem to get the input loop to work out, what's the best practice for doing so. 2. What is the object-type going to be for the reading method? A double[], or an ArrayList? 1. How do I declare method-type to be an arraylist? 2. How do I prevent the array from having more than 1000 values stored within it? Let me show what I have so far: ``` public static java.util.ArrayList readRange(double end_signal){ //read in the range and stop at end_signal ArrayList input = new ArrayList(); Scanner kbd = new Scanner( System.in ); int count = 0; do{ input.add(kbd.nextDouble()); System.out.println(input); //debugging ++count; } while(input(--count) != end_signal); return input; } ``` Any help would be appreciated, pardon my newbieness...
2008/09/22
[ "https://Stackoverflow.com/questions/116276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10636/" ]
What you need in your loop condition is: ``` while ( input.get( input.size()-1 ) != end_signal ); ``` What you're doing is decrementing the counter variable. Also you should declare the `ArrayList` like so: ``` ArrayList<Double> list = new ArrayList<Double>(); ``` This makes the list type-specific and allows the condition as given. Otherwise there's extra casting.
I think you started out not bad, but here is my suggestion. I'll highlight the important differences and points below the code: package console; import java.util.*; import java.util.regex.*; public class ArrayListInput { ``` public ArrayListInput() { // as list List<Double> readRange = readRange(1.5); System.out.println(readRange); // converted to an array Double[] asArray = readRange.toArray(new Double[] {}); System.out.println(Arrays.toString(asArray)); } public static List<Double> readRange(double endWith) { String endSignal = String.valueOf(endWith); List<Double> result = new ArrayList<Double>(); Scanner input = new Scanner(System.in); String next; while (!(next = input.next().trim()).equals(endSignal)) { if (isDouble(next)) { Double doubleValue = Double.valueOf(next); result.add(doubleValue); System.out.println("> Input valid: " + doubleValue); } else { System.err.println("> Input invalid! Try again"); } } // result.add(endWith); // uncomment, if last input should be in the result return result; } public static boolean isDouble(String in) { return Pattern.matches(fpRegex, in); } public static void main(String[] args) { new ArrayListInput(); } private static final String Digits = "(\\p{Digit}+)"; private static final String HexDigits = "(\\p{XDigit}+)"; // an exponent is 'e' or 'E' followed by an optionally // signed decimal integer. private static final String Exp = "[eE][+-]?" + Digits; private static final String fpRegex = ("[\\x00-\\x20]*" + // Optional leading "whitespace" "[+-]?(" + // Optional sign character "NaN|" + // "NaN" string "Infinity|" + // "Infinity" string // A decimal floating-point string representing a finite positive // number without a leading sign has at most five basic pieces: // Digits . Digits ExponentPart FloatTypeSuffix // // Since this method allows integer-only strings as input // in addition to strings of floating-point literals, the // two sub-patterns below are simplifications of the grammar // productions from the Java Language Specification, 2nd // edition, section 3.10.2. // Digits ._opt Digits_opt ExponentPart_opt FloatTypeSuffix_opt "(((" + Digits + "(\\.)?(" + Digits + "?)(" + Exp + ")?)|" + // . Digits ExponentPart_opt FloatTypeSuffix_opt "(\\.(" + Digits + ")(" + Exp + ")?)|" + // Hexadecimal strings "((" + // 0[xX] HexDigits ._opt BinaryExponent FloatTypeSuffix_opt "(0[xX]" + HexDigits + "(\\.)?)|" + // 0[xX] HexDigits_opt . HexDigits BinaryExponent // FloatTypeSuffix_opt "(0[xX]" + HexDigits + "?(\\.)" + HexDigits + ")" + ")[pP][+-]?" + Digits + "))" + "[fFdD]?))" + "[\\x00-\\x20]*");// Optional // trailing // "whitespace" ``` } 1. In Java it's a good thing to use generics. This way you give the compiler and virtual machine a hint about the types you are about to use. In this case its double and by declaring the resulting List to contain double values, you are able to use the values without casting/type conversion: ``` if (!readRange.isEmpty()) { double last = readRange.get(readRange.size() - 1); } ``` 2. It's better to return Interfaces when working with Java collections, as there are many implementations of specific lists (LinkedList, SynchronizedLists, ...). So if you need another type of List later on, you can easy change the concrete implementation inside the method and you don't need to change any further code. 3. You may wonder why the while control statement works, but as you see, there are brackets around **next = input.next().trim()**. This way the variable assignment takes place right before the conditional testing. Also a trim takes playe to avoid whitespacing issues 4. I'm not using **nextDouble()** here because whenever a user would input something that's not a double, well, you will get an exception. By using String I'm able to parse whatever input a user gives but also to test against the end signal. 5. To be sure, a user really inputed a double, I used a regular expression from the JavaDoc of the **Double.valueOf()** method. If this expression matches, the value is converted, if not an error message will be printed. 6. You used a counter for reasons I don't see in your code. If you want to know how many values have been inputed successfully, just call **readRange.size()**. 7. If you want to work on with an array, the second part of the constructor shows out how to convert it. 8. I hope you're not confused by me mixin up double and Double, but thanks to Java 1.5 feature Auto-Boxing this is no problem. And as **Scanner.next()** will never return null (afaik), this should't be a problem at all. 9. If you want to limit the size of the Array, use Okay, I hope you're finding my solution and explanations usefull, use **result.size()** as indicator and the keyword **break** to leave the while control statement. Greetz, GHad
116,276
I'm used to python, so this is a bit confusing to me. I'm trying to take in input, line-by-line, until a user inputs a certain number. The numbers will be stored in an array to apply some statistical maths to them. Currently, I have a main class, the stats classes, and an "reading" class. Two Questions: 1. I can't seem to get the input loop to work out, what's the best practice for doing so. 2. What is the object-type going to be for the reading method? A double[], or an ArrayList? 1. How do I declare method-type to be an arraylist? 2. How do I prevent the array from having more than 1000 values stored within it? Let me show what I have so far: ``` public static java.util.ArrayList readRange(double end_signal){ //read in the range and stop at end_signal ArrayList input = new ArrayList(); Scanner kbd = new Scanner( System.in ); int count = 0; do{ input.add(kbd.nextDouble()); System.out.println(input); //debugging ++count; } while(input(--count) != end_signal); return input; } ``` Any help would be appreciated, pardon my newbieness...
2008/09/22
[ "https://Stackoverflow.com/questions/116276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10636/" ]
What you need in your loop condition is: ``` while ( input.get( input.size()-1 ) != end_signal ); ``` What you're doing is decrementing the counter variable. Also you should declare the `ArrayList` like so: ``` ArrayList<Double> list = new ArrayList<Double>(); ``` This makes the list type-specific and allows the condition as given. Otherwise there's extra casting.
``` public static ArrayList&lt;Double> readRange(double end_signal) { ArrayList<Double> input = new ArrayList<Double>(); Scanner kbd = new Scanner( System.in ); int count = 0; do{ input.add(kbd.nextDouble()); ++count; } while(input(--count) != end_signal); return input; } ```
116,276
I'm used to python, so this is a bit confusing to me. I'm trying to take in input, line-by-line, until a user inputs a certain number. The numbers will be stored in an array to apply some statistical maths to them. Currently, I have a main class, the stats classes, and an "reading" class. Two Questions: 1. I can't seem to get the input loop to work out, what's the best practice for doing so. 2. What is the object-type going to be for the reading method? A double[], or an ArrayList? 1. How do I declare method-type to be an arraylist? 2. How do I prevent the array from having more than 1000 values stored within it? Let me show what I have so far: ``` public static java.util.ArrayList readRange(double end_signal){ //read in the range and stop at end_signal ArrayList input = new ArrayList(); Scanner kbd = new Scanner( System.in ); int count = 0; do{ input.add(kbd.nextDouble()); System.out.println(input); //debugging ++count; } while(input(--count) != end_signal); return input; } ``` Any help would be appreciated, pardon my newbieness...
2008/09/22
[ "https://Stackoverflow.com/questions/116276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10636/" ]
Answers: *>1. I can't seem to get the input loop to work out, what's the best practice for doing so.* I would rather have a simple while loop instead of a do{}while... and place the condition in the while... In my example it read: *while the read number is not end signal and count is lower than limit: do.* *>2. What is the object-type going to be for the reading method? A double[], or an ArrayList?* An ArrayList, however I would strongly recommend you to use List ( java.util.List ) interface instead. It is a good OO practice to program to the interface rather to the implementation. *>2.1How do I declare method-type to be an arraylist?* See code below. *>2.2. How do I prevent the array from having more than 1000 values stored within it?* By adding this restriction in the while condition. ``` import java.util.Scanner; import java.util.List; import java.util.ArrayList; public class InputTest{ private int INPUT_LIMIT = 10000; public static void main( String [] args ) { InputTest test = new InputTest(); System.out.println("Start typing numbers..."); List list = test.readRange( 2.0 ); System.out.println("The input was " + list ); } /** * Read from the standar input until endSignal number is typed. * Also limits the amount of entered numbers to 10000; * @return a list with the numbers. */ public List readRange( double endSignal ) { List<Double> input = new ArrayList<Double>(); Scanner kdb = new Scanner( System.in ); int count = 0; double number = 0; while( ( number = kdb.nextDouble() ) != endSignal && count < INPUT_LIMIT ){ System.out.println( number ); input.add( number ); } return input; } } ``` Final remarks: It is preferred to have "instance methods" than class methods. This way if needed the "readRange" could be handled by a subclass without having to change the signature, thus In the sample I've removed the "static" keyword an create an instance of "InputTest" class In java code style the variable names should go in cammel case like in "endSignal" rather than "end\_signal"
\*\* ``` public static java.util.ArrayList readRange(double end_signal) { //read in the range and stop at end_signal ArrayList input = new ArrayList(); Scanner kbd = new Scanner(System. in ); int count = 0; do { input.add(Double.valueOf(kbd.next())); System.out.println(input); //debugging ++count; } while (input(--count) != end_signal); return input; } ``` \*\*
116,276
I'm used to python, so this is a bit confusing to me. I'm trying to take in input, line-by-line, until a user inputs a certain number. The numbers will be stored in an array to apply some statistical maths to them. Currently, I have a main class, the stats classes, and an "reading" class. Two Questions: 1. I can't seem to get the input loop to work out, what's the best practice for doing so. 2. What is the object-type going to be for the reading method? A double[], or an ArrayList? 1. How do I declare method-type to be an arraylist? 2. How do I prevent the array from having more than 1000 values stored within it? Let me show what I have so far: ``` public static java.util.ArrayList readRange(double end_signal){ //read in the range and stop at end_signal ArrayList input = new ArrayList(); Scanner kbd = new Scanner( System.in ); int count = 0; do{ input.add(kbd.nextDouble()); System.out.println(input); //debugging ++count; } while(input(--count) != end_signal); return input; } ``` Any help would be appreciated, pardon my newbieness...
2008/09/22
[ "https://Stackoverflow.com/questions/116276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10636/" ]
Answers: *>1. I can't seem to get the input loop to work out, what's the best practice for doing so.* I would rather have a simple while loop instead of a do{}while... and place the condition in the while... In my example it read: *while the read number is not end signal and count is lower than limit: do.* *>2. What is the object-type going to be for the reading method? A double[], or an ArrayList?* An ArrayList, however I would strongly recommend you to use List ( java.util.List ) interface instead. It is a good OO practice to program to the interface rather to the implementation. *>2.1How do I declare method-type to be an arraylist?* See code below. *>2.2. How do I prevent the array from having more than 1000 values stored within it?* By adding this restriction in the while condition. ``` import java.util.Scanner; import java.util.List; import java.util.ArrayList; public class InputTest{ private int INPUT_LIMIT = 10000; public static void main( String [] args ) { InputTest test = new InputTest(); System.out.println("Start typing numbers..."); List list = test.readRange( 2.0 ); System.out.println("The input was " + list ); } /** * Read from the standar input until endSignal number is typed. * Also limits the amount of entered numbers to 10000; * @return a list with the numbers. */ public List readRange( double endSignal ) { List<Double> input = new ArrayList<Double>(); Scanner kdb = new Scanner( System.in ); int count = 0; double number = 0; while( ( number = kdb.nextDouble() ) != endSignal && count < INPUT_LIMIT ){ System.out.println( number ); input.add( number ); } return input; } } ``` Final remarks: It is preferred to have "instance methods" than class methods. This way if needed the "readRange" could be handled by a subclass without having to change the signature, thus In the sample I've removed the "static" keyword an create an instance of "InputTest" class In java code style the variable names should go in cammel case like in "endSignal" rather than "end\_signal"
I think you started out not bad, but here is my suggestion. I'll highlight the important differences and points below the code: package console; import java.util.*; import java.util.regex.*; public class ArrayListInput { ``` public ArrayListInput() { // as list List<Double> readRange = readRange(1.5); System.out.println(readRange); // converted to an array Double[] asArray = readRange.toArray(new Double[] {}); System.out.println(Arrays.toString(asArray)); } public static List<Double> readRange(double endWith) { String endSignal = String.valueOf(endWith); List<Double> result = new ArrayList<Double>(); Scanner input = new Scanner(System.in); String next; while (!(next = input.next().trim()).equals(endSignal)) { if (isDouble(next)) { Double doubleValue = Double.valueOf(next); result.add(doubleValue); System.out.println("> Input valid: " + doubleValue); } else { System.err.println("> Input invalid! Try again"); } } // result.add(endWith); // uncomment, if last input should be in the result return result; } public static boolean isDouble(String in) { return Pattern.matches(fpRegex, in); } public static void main(String[] args) { new ArrayListInput(); } private static final String Digits = "(\\p{Digit}+)"; private static final String HexDigits = "(\\p{XDigit}+)"; // an exponent is 'e' or 'E' followed by an optionally // signed decimal integer. private static final String Exp = "[eE][+-]?" + Digits; private static final String fpRegex = ("[\\x00-\\x20]*" + // Optional leading "whitespace" "[+-]?(" + // Optional sign character "NaN|" + // "NaN" string "Infinity|" + // "Infinity" string // A decimal floating-point string representing a finite positive // number without a leading sign has at most five basic pieces: // Digits . Digits ExponentPart FloatTypeSuffix // // Since this method allows integer-only strings as input // in addition to strings of floating-point literals, the // two sub-patterns below are simplifications of the grammar // productions from the Java Language Specification, 2nd // edition, section 3.10.2. // Digits ._opt Digits_opt ExponentPart_opt FloatTypeSuffix_opt "(((" + Digits + "(\\.)?(" + Digits + "?)(" + Exp + ")?)|" + // . Digits ExponentPart_opt FloatTypeSuffix_opt "(\\.(" + Digits + ")(" + Exp + ")?)|" + // Hexadecimal strings "((" + // 0[xX] HexDigits ._opt BinaryExponent FloatTypeSuffix_opt "(0[xX]" + HexDigits + "(\\.)?)|" + // 0[xX] HexDigits_opt . HexDigits BinaryExponent // FloatTypeSuffix_opt "(0[xX]" + HexDigits + "?(\\.)" + HexDigits + ")" + ")[pP][+-]?" + Digits + "))" + "[fFdD]?))" + "[\\x00-\\x20]*");// Optional // trailing // "whitespace" ``` } 1. In Java it's a good thing to use generics. This way you give the compiler and virtual machine a hint about the types you are about to use. In this case its double and by declaring the resulting List to contain double values, you are able to use the values without casting/type conversion: ``` if (!readRange.isEmpty()) { double last = readRange.get(readRange.size() - 1); } ``` 2. It's better to return Interfaces when working with Java collections, as there are many implementations of specific lists (LinkedList, SynchronizedLists, ...). So if you need another type of List later on, you can easy change the concrete implementation inside the method and you don't need to change any further code. 3. You may wonder why the while control statement works, but as you see, there are brackets around **next = input.next().trim()**. This way the variable assignment takes place right before the conditional testing. Also a trim takes playe to avoid whitespacing issues 4. I'm not using **nextDouble()** here because whenever a user would input something that's not a double, well, you will get an exception. By using String I'm able to parse whatever input a user gives but also to test against the end signal. 5. To be sure, a user really inputed a double, I used a regular expression from the JavaDoc of the **Double.valueOf()** method. If this expression matches, the value is converted, if not an error message will be printed. 6. You used a counter for reasons I don't see in your code. If you want to know how many values have been inputed successfully, just call **readRange.size()**. 7. If you want to work on with an array, the second part of the constructor shows out how to convert it. 8. I hope you're not confused by me mixin up double and Double, but thanks to Java 1.5 feature Auto-Boxing this is no problem. And as **Scanner.next()** will never return null (afaik), this should't be a problem at all. 9. If you want to limit the size of the Array, use Okay, I hope you're finding my solution and explanations usefull, use **result.size()** as indicator and the keyword **break** to leave the while control statement. Greetz, GHad
116,276
I'm used to python, so this is a bit confusing to me. I'm trying to take in input, line-by-line, until a user inputs a certain number. The numbers will be stored in an array to apply some statistical maths to them. Currently, I have a main class, the stats classes, and an "reading" class. Two Questions: 1. I can't seem to get the input loop to work out, what's the best practice for doing so. 2. What is the object-type going to be for the reading method? A double[], or an ArrayList? 1. How do I declare method-type to be an arraylist? 2. How do I prevent the array from having more than 1000 values stored within it? Let me show what I have so far: ``` public static java.util.ArrayList readRange(double end_signal){ //read in the range and stop at end_signal ArrayList input = new ArrayList(); Scanner kbd = new Scanner( System.in ); int count = 0; do{ input.add(kbd.nextDouble()); System.out.println(input); //debugging ++count; } while(input(--count) != end_signal); return input; } ``` Any help would be appreciated, pardon my newbieness...
2008/09/22
[ "https://Stackoverflow.com/questions/116276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10636/" ]
Answers: *>1. I can't seem to get the input loop to work out, what's the best practice for doing so.* I would rather have a simple while loop instead of a do{}while... and place the condition in the while... In my example it read: *while the read number is not end signal and count is lower than limit: do.* *>2. What is the object-type going to be for the reading method? A double[], or an ArrayList?* An ArrayList, however I would strongly recommend you to use List ( java.util.List ) interface instead. It is a good OO practice to program to the interface rather to the implementation. *>2.1How do I declare method-type to be an arraylist?* See code below. *>2.2. How do I prevent the array from having more than 1000 values stored within it?* By adding this restriction in the while condition. ``` import java.util.Scanner; import java.util.List; import java.util.ArrayList; public class InputTest{ private int INPUT_LIMIT = 10000; public static void main( String [] args ) { InputTest test = new InputTest(); System.out.println("Start typing numbers..."); List list = test.readRange( 2.0 ); System.out.println("The input was " + list ); } /** * Read from the standar input until endSignal number is typed. * Also limits the amount of entered numbers to 10000; * @return a list with the numbers. */ public List readRange( double endSignal ) { List<Double> input = new ArrayList<Double>(); Scanner kdb = new Scanner( System.in ); int count = 0; double number = 0; while( ( number = kdb.nextDouble() ) != endSignal && count < INPUT_LIMIT ){ System.out.println( number ); input.add( number ); } return input; } } ``` Final remarks: It is preferred to have "instance methods" than class methods. This way if needed the "readRange" could be handled by a subclass without having to change the signature, thus In the sample I've removed the "static" keyword an create an instance of "InputTest" class In java code style the variable names should go in cammel case like in "endSignal" rather than "end\_signal"
``` public static ArrayList&lt;Double> readRange(double end_signal) { ArrayList<Double> input = new ArrayList<Double>(); Scanner kbd = new Scanner( System.in ); int count = 0; do{ input.add(kbd.nextDouble()); ++count; } while(input(--count) != end_signal); return input; } ```
12,381,342
I have a search field feature on my website, with below PHP code: ``` if(isset($_GET['search_ti']) && $_GET['search_ti'] != "") { $search_ti = preg_replace('#[^a-z 0-9?!-]#i', '', $_GET['search_ti']); $sqlCommand = " SELECT * FROM page WHERE title LIKE '%$search_ti%' OR body LIKE '%$search_ti%' "; $result = $mysqli->query($sqlCommand) or die(mysql_error()); ... ``` The URL variable `search_ti` is the keyword for the search, which I got from the URL. For example: ``` searchResult.php?search_ti=home ``` If the keyword is found in my MySQL table, the result shows and no errors. But if the keyword is not found, the web browser generates below error: ``` You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-4,4' at line 1 ``` What is wrong with my code? **ADDITIONAL INFO:** The complete PHP code: <http://jsfiddle.net/eQSZc/> The keyword: home. The error only shows if the keyword is not found in my table.
2012/09/12
[ "https://Stackoverflow.com/questions/12381342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/626063/" ]
You need to do a little more than what's in your try/catch to handle different browsers and to handle different ways that browsers deal with cross domain access: ``` function canAccessIFrame(iframe) { var html = null; try { // deal with older browsers var doc = iframe.contentDocument || iframe.contentWindow.document; html = doc.body.innerHTML; } catch(err){ // do nothing } return(html !== null); } ``` In your example, this would be: ``` var accessAllowed = canAccessIFrame(document.getElementsByTagName('iframe')[0]); ``` Working demo: <http://jsfiddle.net/jfriend00/XsPL6/> Tested in Chrome 21, Safari 5.1, Firefox 14, IE7, IE8, IE9.
A more shorter and more readable function for modern browsers ``` function canAccessIframe(iframe) { try { return Boolean(iframe.contentDocument); } catch(e){ return false; } } ``` Tested with Chrome 79 and Firefox 52 ESR. Explanation: you can check any iframe property that is not accessible cross-origin and convert to boolean. example: contentDocument / contentWindow.document / location.href / etc. Boolean docs: <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean>
12,381,342
I have a search field feature on my website, with below PHP code: ``` if(isset($_GET['search_ti']) && $_GET['search_ti'] != "") { $search_ti = preg_replace('#[^a-z 0-9?!-]#i', '', $_GET['search_ti']); $sqlCommand = " SELECT * FROM page WHERE title LIKE '%$search_ti%' OR body LIKE '%$search_ti%' "; $result = $mysqli->query($sqlCommand) or die(mysql_error()); ... ``` The URL variable `search_ti` is the keyword for the search, which I got from the URL. For example: ``` searchResult.php?search_ti=home ``` If the keyword is found in my MySQL table, the result shows and no errors. But if the keyword is not found, the web browser generates below error: ``` You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-4,4' at line 1 ``` What is wrong with my code? **ADDITIONAL INFO:** The complete PHP code: <http://jsfiddle.net/eQSZc/> The keyword: home. The error only shows if the keyword is not found in my table.
2012/09/12
[ "https://Stackoverflow.com/questions/12381342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/626063/" ]
You need to do a little more than what's in your try/catch to handle different browsers and to handle different ways that browsers deal with cross domain access: ``` function canAccessIFrame(iframe) { var html = null; try { // deal with older browsers var doc = iframe.contentDocument || iframe.contentWindow.document; html = doc.body.innerHTML; } catch(err){ // do nothing } return(html !== null); } ``` In your example, this would be: ``` var accessAllowed = canAccessIFrame(document.getElementsByTagName('iframe')[0]); ``` Working demo: <http://jsfiddle.net/jfriend00/XsPL6/> Tested in Chrome 21, Safari 5.1, Firefox 14, IE7, IE8, IE9.
This is a shorter version that combines the both approches with ES6. Please notice that it only works if your domain and the iframed domains have the same security type. Change in this example the google link to be http and it won't work. ``` let canAccessIFrame = (iframe) => { return !!(iframe.contentDocument) } let checkIFrameAccess = () => { let result = document.getElementById('result') let remote = canAccessIFrame(document.getElementById('remote')) let local = canAccessIFrame(document.getElementById('local')) result.innerHTML = ` Remote iframe access: ${remote} <br>Local iframe access: ${local} ` } ```
12,381,342
I have a search field feature on my website, with below PHP code: ``` if(isset($_GET['search_ti']) && $_GET['search_ti'] != "") { $search_ti = preg_replace('#[^a-z 0-9?!-]#i', '', $_GET['search_ti']); $sqlCommand = " SELECT * FROM page WHERE title LIKE '%$search_ti%' OR body LIKE '%$search_ti%' "; $result = $mysqli->query($sqlCommand) or die(mysql_error()); ... ``` The URL variable `search_ti` is the keyword for the search, which I got from the URL. For example: ``` searchResult.php?search_ti=home ``` If the keyword is found in my MySQL table, the result shows and no errors. But if the keyword is not found, the web browser generates below error: ``` You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-4,4' at line 1 ``` What is wrong with my code? **ADDITIONAL INFO:** The complete PHP code: <http://jsfiddle.net/eQSZc/> The keyword: home. The error only shows if the keyword is not found in my table.
2012/09/12
[ "https://Stackoverflow.com/questions/12381342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/626063/" ]
You need to do a little more than what's in your try/catch to handle different browsers and to handle different ways that browsers deal with cross domain access: ``` function canAccessIFrame(iframe) { var html = null; try { // deal with older browsers var doc = iframe.contentDocument || iframe.contentWindow.document; html = doc.body.innerHTML; } catch(err){ // do nothing } return(html !== null); } ``` In your example, this would be: ``` var accessAllowed = canAccessIFrame(document.getElementsByTagName('iframe')[0]); ``` Working demo: <http://jsfiddle.net/jfriend00/XsPL6/> Tested in Chrome 21, Safari 5.1, Firefox 14, IE7, IE8, IE9.
I did it this way with jquery. It may be not tidy 100%, but works for me. ``` $(iframe).load(function (e) { try { // try access to check console.log(this.contentWindow.document); } catch (e) { console.log(e); var messageLC = e.message.toLowerCase(); if (messageLC.indexOf("x-frame-options") > -1 || messageLC.indexOf('blocked a frame with origin') > -1 || messageLC.indexOf('accessing a cross-origin') > -1) { // show Error Msg with cause of cross-origin access denied } else { // Shoe Error Msg with other cause } } }); ```
12,381,342
I have a search field feature on my website, with below PHP code: ``` if(isset($_GET['search_ti']) && $_GET['search_ti'] != "") { $search_ti = preg_replace('#[^a-z 0-9?!-]#i', '', $_GET['search_ti']); $sqlCommand = " SELECT * FROM page WHERE title LIKE '%$search_ti%' OR body LIKE '%$search_ti%' "; $result = $mysqli->query($sqlCommand) or die(mysql_error()); ... ``` The URL variable `search_ti` is the keyword for the search, which I got from the URL. For example: ``` searchResult.php?search_ti=home ``` If the keyword is found in my MySQL table, the result shows and no errors. But if the keyword is not found, the web browser generates below error: ``` You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-4,4' at line 1 ``` What is wrong with my code? **ADDITIONAL INFO:** The complete PHP code: <http://jsfiddle.net/eQSZc/> The keyword: home. The error only shows if the keyword is not found in my table.
2012/09/12
[ "https://Stackoverflow.com/questions/12381342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/626063/" ]
You need to do a little more than what's in your try/catch to handle different browsers and to handle different ways that browsers deal with cross domain access: ``` function canAccessIFrame(iframe) { var html = null; try { // deal with older browsers var doc = iframe.contentDocument || iframe.contentWindow.document; html = doc.body.innerHTML; } catch(err){ // do nothing } return(html !== null); } ``` In your example, this would be: ``` var accessAllowed = canAccessIFrame(document.getElementsByTagName('iframe')[0]); ``` Working demo: <http://jsfiddle.net/jfriend00/XsPL6/> Tested in Chrome 21, Safari 5.1, Firefox 14, IE7, IE8, IE9.
I was having issues with my IFrame returning an empty string until it was loaded. So I started using the following: ```js function canAccessIFrame(iframe) { try { const doc = iframe.contentDocument || iframe.contentWindow.document; const html = doc.body.innerHTML; return html !== null && html !== '' } catch(err){ return false } } ```
12,381,342
I have a search field feature on my website, with below PHP code: ``` if(isset($_GET['search_ti']) && $_GET['search_ti'] != "") { $search_ti = preg_replace('#[^a-z 0-9?!-]#i', '', $_GET['search_ti']); $sqlCommand = " SELECT * FROM page WHERE title LIKE '%$search_ti%' OR body LIKE '%$search_ti%' "; $result = $mysqli->query($sqlCommand) or die(mysql_error()); ... ``` The URL variable `search_ti` is the keyword for the search, which I got from the URL. For example: ``` searchResult.php?search_ti=home ``` If the keyword is found in my MySQL table, the result shows and no errors. But if the keyword is not found, the web browser generates below error: ``` You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-4,4' at line 1 ``` What is wrong with my code? **ADDITIONAL INFO:** The complete PHP code: <http://jsfiddle.net/eQSZc/> The keyword: home. The error only shows if the keyword is not found in my table.
2012/09/12
[ "https://Stackoverflow.com/questions/12381342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/626063/" ]
A more shorter and more readable function for modern browsers ``` function canAccessIframe(iframe) { try { return Boolean(iframe.contentDocument); } catch(e){ return false; } } ``` Tested with Chrome 79 and Firefox 52 ESR. Explanation: you can check any iframe property that is not accessible cross-origin and convert to boolean. example: contentDocument / contentWindow.document / location.href / etc. Boolean docs: <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean>
This is a shorter version that combines the both approches with ES6. Please notice that it only works if your domain and the iframed domains have the same security type. Change in this example the google link to be http and it won't work. ``` let canAccessIFrame = (iframe) => { return !!(iframe.contentDocument) } let checkIFrameAccess = () => { let result = document.getElementById('result') let remote = canAccessIFrame(document.getElementById('remote')) let local = canAccessIFrame(document.getElementById('local')) result.innerHTML = ` Remote iframe access: ${remote} <br>Local iframe access: ${local} ` } ```
12,381,342
I have a search field feature on my website, with below PHP code: ``` if(isset($_GET['search_ti']) && $_GET['search_ti'] != "") { $search_ti = preg_replace('#[^a-z 0-9?!-]#i', '', $_GET['search_ti']); $sqlCommand = " SELECT * FROM page WHERE title LIKE '%$search_ti%' OR body LIKE '%$search_ti%' "; $result = $mysqli->query($sqlCommand) or die(mysql_error()); ... ``` The URL variable `search_ti` is the keyword for the search, which I got from the URL. For example: ``` searchResult.php?search_ti=home ``` If the keyword is found in my MySQL table, the result shows and no errors. But if the keyword is not found, the web browser generates below error: ``` You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-4,4' at line 1 ``` What is wrong with my code? **ADDITIONAL INFO:** The complete PHP code: <http://jsfiddle.net/eQSZc/> The keyword: home. The error only shows if the keyword is not found in my table.
2012/09/12
[ "https://Stackoverflow.com/questions/12381342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/626063/" ]
A more shorter and more readable function for modern browsers ``` function canAccessIframe(iframe) { try { return Boolean(iframe.contentDocument); } catch(e){ return false; } } ``` Tested with Chrome 79 and Firefox 52 ESR. Explanation: you can check any iframe property that is not accessible cross-origin and convert to boolean. example: contentDocument / contentWindow.document / location.href / etc. Boolean docs: <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean>
I did it this way with jquery. It may be not tidy 100%, but works for me. ``` $(iframe).load(function (e) { try { // try access to check console.log(this.contentWindow.document); } catch (e) { console.log(e); var messageLC = e.message.toLowerCase(); if (messageLC.indexOf("x-frame-options") > -1 || messageLC.indexOf('blocked a frame with origin') > -1 || messageLC.indexOf('accessing a cross-origin') > -1) { // show Error Msg with cause of cross-origin access denied } else { // Shoe Error Msg with other cause } } }); ```
12,381,342
I have a search field feature on my website, with below PHP code: ``` if(isset($_GET['search_ti']) && $_GET['search_ti'] != "") { $search_ti = preg_replace('#[^a-z 0-9?!-]#i', '', $_GET['search_ti']); $sqlCommand = " SELECT * FROM page WHERE title LIKE '%$search_ti%' OR body LIKE '%$search_ti%' "; $result = $mysqli->query($sqlCommand) or die(mysql_error()); ... ``` The URL variable `search_ti` is the keyword for the search, which I got from the URL. For example: ``` searchResult.php?search_ti=home ``` If the keyword is found in my MySQL table, the result shows and no errors. But if the keyword is not found, the web browser generates below error: ``` You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-4,4' at line 1 ``` What is wrong with my code? **ADDITIONAL INFO:** The complete PHP code: <http://jsfiddle.net/eQSZc/> The keyword: home. The error only shows if the keyword is not found in my table.
2012/09/12
[ "https://Stackoverflow.com/questions/12381342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/626063/" ]
A more shorter and more readable function for modern browsers ``` function canAccessIframe(iframe) { try { return Boolean(iframe.contentDocument); } catch(e){ return false; } } ``` Tested with Chrome 79 and Firefox 52 ESR. Explanation: you can check any iframe property that is not accessible cross-origin and convert to boolean. example: contentDocument / contentWindow.document / location.href / etc. Boolean docs: <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean>
I was having issues with my IFrame returning an empty string until it was loaded. So I started using the following: ```js function canAccessIFrame(iframe) { try { const doc = iframe.contentDocument || iframe.contentWindow.document; const html = doc.body.innerHTML; return html !== null && html !== '' } catch(err){ return false } } ```
34,166,866
I made some changes in the code and now it's working. But there is a new problem. In the database, I have registered 3 Company Cods: G-1001, G-1002 and G-1004. If I type "g", "g-", or for instance "g-100" and click search, it returns me all the results correctly. But if I type just "g-1001" or even "01", "001", it returns no results. Why it's not working when I search the last characters of the registered code? ``` <?php if(isset($_POST['action']) && $_POST['action'] == 'send'){ $codsearch = preg_replace('#[^a-z 0-9?()!-]#i', '', $_POST['searchcompanycod']); $getresultsquery = mysql_query('SELECT p.*, a.idProduct, a.idVehic, a.year, v.nameVehic, GROUP_CONCAT(a.year SEPARATOR "<br>"), GROUP_CONCAT(a.idVehic SEPARATOR "<br>"), GROUP_CONCAT(v.nameVehic SEPARATOR "<br>") FROM products p INNER JOIN application a ON p.idProduct = a.idProduct INNER JOIN vehic v ON a.idVehic = v.idVehic WHERE codCompany LIKE "%'.$codsearch.'%" GROUP BY p.codCompany') or die(mysql_error()); $resultsrow = mysql_num_rows($getresultsquery); if($resultsrow > 1){ echo "$codsearch"; echo "<table class='table table-bordered' border=1>"; echo "<tr>"; echo "<th>Company Code</th><th>Original Code</th><th>Descr.</th><th>idProduct</th><th>idVehic</th><th>Vehic Name</th><th>Year</th>"; echo "</tr>"; while($getresultsline = mysql_fetch_array($getresultsquery)) { echo "<tr>"; echo "<td>" . $getresultsline['codCompany'] . "</td>"; echo "<td>" . $getresultsline['codOriginal'] . "</td>"; echo "<td>" . $getresultsline['typeDesc'] . "</td>"; echo "<td>" . $getresultsline['idProduct'] . "</td>"; echo "<td>" . $getresultsline['GROUP_CONCAT(a.idVehic SEPARATOR "<br>")'] . "</td>"; echo "<td>" . $getresultsline['GROUP_CONCAT(v.nameVehic SEPARATOR "<br>")'] . "</td>"; echo "<td>" . $getresultsline['GROUP_CONCAT(a.year SEPARATOR "<br>")'] . "</td>"; echo "</tr>"; } } else{ echo "No results";} } ?> </tbody> </table> ``` Any ideas? My testing page is: <http://flyingmail.com.br/test/produtos.php> (only Company Code filter working)
2015/12/08
[ "https://Stackoverflow.com/questions/34166866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5642816/" ]
1. Does screen\_icon has getter and setter or it is a variable? Should be a property 2. What is the name and type in database? Maybe try forcing column name with attrbiute like: [Column("screen\_icon")] public string screen\_icon { get; set; }
Try: ``` return db.screen.ToList().Select(e => new { icon = e.screen_icon }); ```
34,166,866
I made some changes in the code and now it's working. But there is a new problem. In the database, I have registered 3 Company Cods: G-1001, G-1002 and G-1004. If I type "g", "g-", or for instance "g-100" and click search, it returns me all the results correctly. But if I type just "g-1001" or even "01", "001", it returns no results. Why it's not working when I search the last characters of the registered code? ``` <?php if(isset($_POST['action']) && $_POST['action'] == 'send'){ $codsearch = preg_replace('#[^a-z 0-9?()!-]#i', '', $_POST['searchcompanycod']); $getresultsquery = mysql_query('SELECT p.*, a.idProduct, a.idVehic, a.year, v.nameVehic, GROUP_CONCAT(a.year SEPARATOR "<br>"), GROUP_CONCAT(a.idVehic SEPARATOR "<br>"), GROUP_CONCAT(v.nameVehic SEPARATOR "<br>") FROM products p INNER JOIN application a ON p.idProduct = a.idProduct INNER JOIN vehic v ON a.idVehic = v.idVehic WHERE codCompany LIKE "%'.$codsearch.'%" GROUP BY p.codCompany') or die(mysql_error()); $resultsrow = mysql_num_rows($getresultsquery); if($resultsrow > 1){ echo "$codsearch"; echo "<table class='table table-bordered' border=1>"; echo "<tr>"; echo "<th>Company Code</th><th>Original Code</th><th>Descr.</th><th>idProduct</th><th>idVehic</th><th>Vehic Name</th><th>Year</th>"; echo "</tr>"; while($getresultsline = mysql_fetch_array($getresultsquery)) { echo "<tr>"; echo "<td>" . $getresultsline['codCompany'] . "</td>"; echo "<td>" . $getresultsline['codOriginal'] . "</td>"; echo "<td>" . $getresultsline['typeDesc'] . "</td>"; echo "<td>" . $getresultsline['idProduct'] . "</td>"; echo "<td>" . $getresultsline['GROUP_CONCAT(a.idVehic SEPARATOR "<br>")'] . "</td>"; echo "<td>" . $getresultsline['GROUP_CONCAT(v.nameVehic SEPARATOR "<br>")'] . "</td>"; echo "<td>" . $getresultsline['GROUP_CONCAT(a.year SEPARATOR "<br>")'] . "</td>"; echo "</tr>"; } } else{ echo "No results";} } ?> </tbody> </table> ``` Any ideas? My testing page is: <http://flyingmail.com.br/test/produtos.php> (only Company Code filter working)
2015/12/08
[ "https://Stackoverflow.com/questions/34166866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5642816/" ]
It turns out that the project was using an [edmx](https://msdn.microsoft.com/library/cc982042(v=vs.100).aspx) file to manage their models. Due to the amount of noise in the file I edited and the fact that I found it through "go to definition" and the not the file explorer, I didn't realize that the model file was generated from the Entities.edmx file. Once I updated the model in from the edmx designer, my code worked as expected. And I learned that its important to keep an eye out for comments that inform you not to edit it manually because its an auto-generated file.
Try: ``` return db.screen.ToList().Select(e => new { icon = e.screen_icon }); ```
34,166,866
I made some changes in the code and now it's working. But there is a new problem. In the database, I have registered 3 Company Cods: G-1001, G-1002 and G-1004. If I type "g", "g-", or for instance "g-100" and click search, it returns me all the results correctly. But if I type just "g-1001" or even "01", "001", it returns no results. Why it's not working when I search the last characters of the registered code? ``` <?php if(isset($_POST['action']) && $_POST['action'] == 'send'){ $codsearch = preg_replace('#[^a-z 0-9?()!-]#i', '', $_POST['searchcompanycod']); $getresultsquery = mysql_query('SELECT p.*, a.idProduct, a.idVehic, a.year, v.nameVehic, GROUP_CONCAT(a.year SEPARATOR "<br>"), GROUP_CONCAT(a.idVehic SEPARATOR "<br>"), GROUP_CONCAT(v.nameVehic SEPARATOR "<br>") FROM products p INNER JOIN application a ON p.idProduct = a.idProduct INNER JOIN vehic v ON a.idVehic = v.idVehic WHERE codCompany LIKE "%'.$codsearch.'%" GROUP BY p.codCompany') or die(mysql_error()); $resultsrow = mysql_num_rows($getresultsquery); if($resultsrow > 1){ echo "$codsearch"; echo "<table class='table table-bordered' border=1>"; echo "<tr>"; echo "<th>Company Code</th><th>Original Code</th><th>Descr.</th><th>idProduct</th><th>idVehic</th><th>Vehic Name</th><th>Year</th>"; echo "</tr>"; while($getresultsline = mysql_fetch_array($getresultsquery)) { echo "<tr>"; echo "<td>" . $getresultsline['codCompany'] . "</td>"; echo "<td>" . $getresultsline['codOriginal'] . "</td>"; echo "<td>" . $getresultsline['typeDesc'] . "</td>"; echo "<td>" . $getresultsline['idProduct'] . "</td>"; echo "<td>" . $getresultsline['GROUP_CONCAT(a.idVehic SEPARATOR "<br>")'] . "</td>"; echo "<td>" . $getresultsline['GROUP_CONCAT(v.nameVehic SEPARATOR "<br>")'] . "</td>"; echo "<td>" . $getresultsline['GROUP_CONCAT(a.year SEPARATOR "<br>")'] . "</td>"; echo "</tr>"; } } else{ echo "No results";} } ?> </tbody> </table> ``` Any ideas? My testing page is: <http://flyingmail.com.br/test/produtos.php> (only Company Code filter working)
2015/12/08
[ "https://Stackoverflow.com/questions/34166866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5642816/" ]
It turns out that the project was using an [edmx](https://msdn.microsoft.com/library/cc982042(v=vs.100).aspx) file to manage their models. Due to the amount of noise in the file I edited and the fact that I found it through "go to definition" and the not the file explorer, I didn't realize that the model file was generated from the Entities.edmx file. Once I updated the model in from the edmx designer, my code worked as expected. And I learned that its important to keep an eye out for comments that inform you not to edit it manually because its an auto-generated file.
1. Does screen\_icon has getter and setter or it is a variable? Should be a property 2. What is the name and type in database? Maybe try forcing column name with attrbiute like: [Column("screen\_icon")] public string screen\_icon { get; set; }
109,982
[![enter image description here](https://i.stack.imgur.com/ppXNc.jpg)](https://i.stack.imgur.com/ppXNc.jpg) Here is a start. ``` MapIndexed[Text[Reverse[First[RealDigits[Pi,10,252]]][[Tr@#2]],#]&, Table[{t Cos[t],t Sin[t]},{t,0,16Pi,0.2}]]//Graphics ```
2016/03/14
[ "https://mathematica.stackexchange.com/questions/109982", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/5379/" ]
My original code was crashing when you used too many digits because apparently Mathematica can handle only so many different font sizes. To fix it, I had to borrow [george2079's PDF trick](https://mathematica.stackexchange.com/a/110013/2305) to turn each character into a vectorised graphics primitive. I couldn't have solved this issue myself, so give his answer an upvote please. The rest of the code is still my original approach. ``` numbers = Translate[#, {-4.5, -10}] & /@ First[First[ ImportString[ExportString[ Style[#, FontSize -> 24, FontFamily -> "Arial"], "PDF"], "PDF", "TextMode" -> "Outlines"] ]] & /@ {"."}~Join~CharacterRange["0", "9"]; With[{fontsize = 0.0655, digits = 10000}, Graphics[ MapIndexed[ With[{angle = (-(#2[[1]] - 2) + Switch[#2[[1]], 1, -0.1, 2, 0, _, 0.6]) fontsize}, With[{scale = (1 - 1.5 fontsize)^(-angle/(2 Pi))}, GeometricTransformation[ numbers[[# + 2]], RightComposition[ ScalingTransform[{1, 1} 0.1 fontsize*scale], TranslationTransform[{0, scale}], RotationTransform[Pi/4 + angle] ] ] ] ] &, Insert[First@RealDigits[Pi, 10, digits], -1, 2] ], PlotRange -> {{-1.1, 1.1}, {-1.1, 1.1}} ] ] ``` [![enter image description here](https://i.stack.imgur.com/j3hAA.png)](https://i.stack.imgur.com/j3hAA.png) Note that the output is a vector image, so you can drag it as big as you like to increase the resolution and be able to see more digits in the centre. The above screenshot is actually a lot bigger. Click to view it at full resolution. There are some magic numbers in the code, but in principle you should be able to tweak the size of the sΟ€ral simply by changing the `fontsize` parameter at the top and the length by changing `digits`. All the other length scales seem to work reasonably well. I've chosen `0.0665` as the font size (as well as all the other parameters) because it seems to match up almost exactly with your own example (including the font). There's some fiddling with the `Switch` to set the angles around `.` manually, because otherwise they'd look to big. I'm not a typographer, so if you still cringe at the kerning, I apologise. **As for how it actually works:** * The angle of each digit depends linearly on its index (i.e. there's a fixed angle decrement between consecutive digits). Since the size of the numbers scale linearly with radius, we also want their spacing around the circle to scale linearly with radius, and that just means we want to use constant offsets in angle. This offset depends on the `fontsize` parameter. * To get a clean scaling of the radius to ensure that the gaps between subsequent turns are consistent (and that the spiral is self-similar), we determine the scaling *based on the angle*, such that each full turn scales the radius as well as the font size by a constant factor. Since the angle between consecutive digits is constant, we could also make this scaling factor linearly dependent on the index, but using the angle makes it a bit nicer, because we can directly set the relative scale from one turn to the next (which clearly must be at least one font size smaller to avoid overlap). * To get each digit into its position, we first move it a first scale it according to both the initial font size and the current scale factor. Then we move it along the positive y-axis according to the same scale factor, such that the ratio of font size to radius is constant. Finally, we rotate it about the origin by the linearly increasing angle. I've offset the angle by $\pi/4$ so that the the number starts in the top left as in your example.
Avoid the too many font sizes issue by convert characters to graphics primitives: ``` numbers = Translate[#, {-4.5, -10}] & /@ First[First[ ImportString[ ExportString[Style[#, FontSize -> 24, FontFamily -> "Times"], "PDF"], "PDF", "TextMode" -> "Outlines"]]] & /@ CharacterRange["0", "9"]; ``` borrowed from here: <https://mathematica.stackexchange.com/a/638/2079> ``` n = 10000; d = First[RealDigits[Pi, 10, n]]; Graphics[{a = 0; r = 150; i = 0; Reap[While[r > 2, i = i + 1; scale = .7 (1 - .99 (i/n)^(.2)); r = r - .8 scale/(2 Pi); a = a - 10 scale/r ; Sow[Rotate[ Translate[ Scale[{EdgeForm[], FaceForm[Black], numbers[[d[[i]] + 1]]}, scale], {0, r}], a, {0, 0}]]]][[2, 1]]}, PlotRange -> {{-200, 200}, {-200, 200}}] ``` [![enter image description here](https://i.stack.imgur.com/vS61g.png)](https://i.stack.imgur.com/vS61g.png)
109,982
[![enter image description here](https://i.stack.imgur.com/ppXNc.jpg)](https://i.stack.imgur.com/ppXNc.jpg) Here is a start. ``` MapIndexed[Text[Reverse[First[RealDigits[Pi,10,252]]][[Tr@#2]],#]&, Table[{t Cos[t],t Sin[t]},{t,0,16Pi,0.2}]]//Graphics ```
2016/03/14
[ "https://mathematica.stackexchange.com/questions/109982", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/5379/" ]
My original code was crashing when you used too many digits because apparently Mathematica can handle only so many different font sizes. To fix it, I had to borrow [george2079's PDF trick](https://mathematica.stackexchange.com/a/110013/2305) to turn each character into a vectorised graphics primitive. I couldn't have solved this issue myself, so give his answer an upvote please. The rest of the code is still my original approach. ``` numbers = Translate[#, {-4.5, -10}] & /@ First[First[ ImportString[ExportString[ Style[#, FontSize -> 24, FontFamily -> "Arial"], "PDF"], "PDF", "TextMode" -> "Outlines"] ]] & /@ {"."}~Join~CharacterRange["0", "9"]; With[{fontsize = 0.0655, digits = 10000}, Graphics[ MapIndexed[ With[{angle = (-(#2[[1]] - 2) + Switch[#2[[1]], 1, -0.1, 2, 0, _, 0.6]) fontsize}, With[{scale = (1 - 1.5 fontsize)^(-angle/(2 Pi))}, GeometricTransformation[ numbers[[# + 2]], RightComposition[ ScalingTransform[{1, 1} 0.1 fontsize*scale], TranslationTransform[{0, scale}], RotationTransform[Pi/4 + angle] ] ] ] ] &, Insert[First@RealDigits[Pi, 10, digits], -1, 2] ], PlotRange -> {{-1.1, 1.1}, {-1.1, 1.1}} ] ] ``` [![enter image description here](https://i.stack.imgur.com/j3hAA.png)](https://i.stack.imgur.com/j3hAA.png) Note that the output is a vector image, so you can drag it as big as you like to increase the resolution and be able to see more digits in the centre. The above screenshot is actually a lot bigger. Click to view it at full resolution. There are some magic numbers in the code, but in principle you should be able to tweak the size of the sΟ€ral simply by changing the `fontsize` parameter at the top and the length by changing `digits`. All the other length scales seem to work reasonably well. I've chosen `0.0665` as the font size (as well as all the other parameters) because it seems to match up almost exactly with your own example (including the font). There's some fiddling with the `Switch` to set the angles around `.` manually, because otherwise they'd look to big. I'm not a typographer, so if you still cringe at the kerning, I apologise. **As for how it actually works:** * The angle of each digit depends linearly on its index (i.e. there's a fixed angle decrement between consecutive digits). Since the size of the numbers scale linearly with radius, we also want their spacing around the circle to scale linearly with radius, and that just means we want to use constant offsets in angle. This offset depends on the `fontsize` parameter. * To get a clean scaling of the radius to ensure that the gaps between subsequent turns are consistent (and that the spiral is self-similar), we determine the scaling *based on the angle*, such that each full turn scales the radius as well as the font size by a constant factor. Since the angle between consecutive digits is constant, we could also make this scaling factor linearly dependent on the index, but using the angle makes it a bit nicer, because we can directly set the relative scale from one turn to the next (which clearly must be at least one font size smaller to avoid overlap). * To get each digit into its position, we first move it a first scale it according to both the initial font size and the current scale factor. Then we move it along the positive y-axis according to the same scale factor, such that the ratio of font size to radius is constant. Finally, we rotate it about the origin by the linearly increasing angle. I've offset the angle by $\pi/4$ so that the the number starts in the top left as in your example.
This calculates the height, width and inter-character spacings for each number, keeping the same proportion as it winds down. That (I believe) is what the picture at the question does. `f` determines the "frequency" of the spiral and can be changed at will as everything is set up accordingly. Wow! I am using this trick here at [least since 2012](https://mathematica.stackexchange.com/a/4381/193) ``` ClearAll[height, nbr, width, nextt, w, angles, list, f, digits]; f = 50; digits = 3000; s = -5/4 Pi; nbrSpacing = 12/10; list = First@RealDigits[Pi, 10, digits]; w[nbr_] := w[nbr] = Cases[First[First[ImportString[ExportString[ Style[ToString@nbr, FontFamily -> "Courier", FontSize -> 10], "PDF"], "TextMode" -> "Outlines"]]], FilledCurve[a__] :> {EdgeForm[Black], FilledCurve[a]}, Infinity] parmsFont = {Min@#, Max@#} & /@ Transpose[w[1][[1, 2, 2, 1]]]; {aspectRatio, center, origHeight} = {Divide @@ (Subtract @@@ #), Mean[#[[1]]], -Subtract @@ (#[[2]])} &@parmsFont; height[t_] := E^(t/f) - E^((t - 2 Pi)/f) // N nbr[n_, t_] := {GeometricTransformation[w[n], Composition[TranslationTransform[E^(t/f) {Cos[t], Sin[t]}], ScalingTransform[height[t]/origHeight {1, 1}], RotationTransform[t - Pi/2]]]} width[t_] := aspectRatio height[t] nextt[t_] := nextt[t] = (t - nbrSpacing width[t] E^(s/f)/E^(t/f)) angles = NestList[nextt, s, digits - 1] // N; Graphics@MapThread[nbr, {list, angles}] ``` [![enter image description here](https://i.stack.imgur.com/caTE5.png)](https://i.stack.imgur.com/caTE5.png) With `f = 80` [![enter image description here](https://i.stack.imgur.com/8VYBh.png)](https://i.stack.imgur.com/8VYBh.png) With `f = 25` [![enter image description here](https://i.stack.imgur.com/qshXs.png)](https://i.stack.imgur.com/qshXs.png)
109,982
[![enter image description here](https://i.stack.imgur.com/ppXNc.jpg)](https://i.stack.imgur.com/ppXNc.jpg) Here is a start. ``` MapIndexed[Text[Reverse[First[RealDigits[Pi,10,252]]][[Tr@#2]],#]&, Table[{t Cos[t],t Sin[t]},{t,0,16Pi,0.2}]]//Graphics ```
2016/03/14
[ "https://mathematica.stackexchange.com/questions/109982", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/5379/" ]
Avoid the too many font sizes issue by convert characters to graphics primitives: ``` numbers = Translate[#, {-4.5, -10}] & /@ First[First[ ImportString[ ExportString[Style[#, FontSize -> 24, FontFamily -> "Times"], "PDF"], "PDF", "TextMode" -> "Outlines"]]] & /@ CharacterRange["0", "9"]; ``` borrowed from here: <https://mathematica.stackexchange.com/a/638/2079> ``` n = 10000; d = First[RealDigits[Pi, 10, n]]; Graphics[{a = 0; r = 150; i = 0; Reap[While[r > 2, i = i + 1; scale = .7 (1 - .99 (i/n)^(.2)); r = r - .8 scale/(2 Pi); a = a - 10 scale/r ; Sow[Rotate[ Translate[ Scale[{EdgeForm[], FaceForm[Black], numbers[[d[[i]] + 1]]}, scale], {0, r}], a, {0, 0}]]]][[2, 1]]}, PlotRange -> {{-200, 200}, {-200, 200}}] ``` [![enter image description here](https://i.stack.imgur.com/vS61g.png)](https://i.stack.imgur.com/vS61g.png)
This calculates the height, width and inter-character spacings for each number, keeping the same proportion as it winds down. That (I believe) is what the picture at the question does. `f` determines the "frequency" of the spiral and can be changed at will as everything is set up accordingly. Wow! I am using this trick here at [least since 2012](https://mathematica.stackexchange.com/a/4381/193) ``` ClearAll[height, nbr, width, nextt, w, angles, list, f, digits]; f = 50; digits = 3000; s = -5/4 Pi; nbrSpacing = 12/10; list = First@RealDigits[Pi, 10, digits]; w[nbr_] := w[nbr] = Cases[First[First[ImportString[ExportString[ Style[ToString@nbr, FontFamily -> "Courier", FontSize -> 10], "PDF"], "TextMode" -> "Outlines"]]], FilledCurve[a__] :> {EdgeForm[Black], FilledCurve[a]}, Infinity] parmsFont = {Min@#, Max@#} & /@ Transpose[w[1][[1, 2, 2, 1]]]; {aspectRatio, center, origHeight} = {Divide @@ (Subtract @@@ #), Mean[#[[1]]], -Subtract @@ (#[[2]])} &@parmsFont; height[t_] := E^(t/f) - E^((t - 2 Pi)/f) // N nbr[n_, t_] := {GeometricTransformation[w[n], Composition[TranslationTransform[E^(t/f) {Cos[t], Sin[t]}], ScalingTransform[height[t]/origHeight {1, 1}], RotationTransform[t - Pi/2]]]} width[t_] := aspectRatio height[t] nextt[t_] := nextt[t] = (t - nbrSpacing width[t] E^(s/f)/E^(t/f)) angles = NestList[nextt, s, digits - 1] // N; Graphics@MapThread[nbr, {list, angles}] ``` [![enter image description here](https://i.stack.imgur.com/caTE5.png)](https://i.stack.imgur.com/caTE5.png) With `f = 80` [![enter image description here](https://i.stack.imgur.com/8VYBh.png)](https://i.stack.imgur.com/8VYBh.png) With `f = 25` [![enter image description here](https://i.stack.imgur.com/qshXs.png)](https://i.stack.imgur.com/qshXs.png)
56,652,689
I have created 4 tables that I need to relate to each other and then build a form to add/show data. I have build the 4 tables in SQL but I'm not sure I have the correct relationships or fields enter so the data can be accessed correctly ``` User Table User_ID (Pkey) Full_Name (varchar) User_Name (varchar) Department Table Dept_ID (Pkey) Department_Name (varchar) User_ID (int) Application Table App_ID (Pkey) Application_Name (varchar) User_ID (int) Access_Date Table Date_ID (Pkey) Access_Date (date) Removal_Date (date) User_ID (int) ``` I want to see a user who has access to one or more applications and what date they got access and what date the access was removed. A user can have several applications and could be in more than one department. I think i have the wrong `ID (int)` field related in either the `Access_Date` or `Application` table, but not sure. I have now added junction tables for `UserDepartment, UserApplications, UserAccessDates` when I open the form in MS Access 2016, I get a blank page. The form was created using the User table as the main and the department and application and access date as sub-forms. I believe my relationships may be wrong somehow.
2019/06/18
[ "https://Stackoverflow.com/questions/56652689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11665457/" ]
No, you do not have the right tables. Let me give you an example with users and departments. You want three tables for these: ``` Users Table User_ID (Pkey) Full_Name (varchar) User_Name (varchar) Departments Table Department_ID (Pkey) Department_Name (varchar) UserDepartments User_ID (int) Department_ID (int) Other information, such as Effective_Date and End_Date ``` The first two tables represent two different entities, `Users` and `Departments`. The third is an association/junction table that implements a many-to-many relationship. Similarly, you want a `UserApplications` table. And your access table should show the application. Notes on naming: * I generally name tables in the plural, because they contain multiple instances of an entity. * The primary key is the singular of the table name followed by `_id` or `Id`. * Primary keys and foreign keys have the same name, to the extent possible.
From what you have provided, you will be able do determine that user has access to an application but not which application he has access. To provide that information you will need to add the App\_Id in the Access\_Date table. The Departments are not associated with anything but the user. If departments have anything to do with Applications or Access\_Date specific you will need to link the department to the Application and or Access\_date tables. I have added a picture showing the relationships between the tables up to the point that I understand (using ms access).[Relationships](https://i.stack.imgur.com/WAwtS.png) Here is the new picture.[New Relationships](https://i.stack.imgur.com/AHWge.png)
104,419
I have a small LAN that has a couple of Linux boxes (Ubuntu 9.10) with NFS shares on them. The boxes are networked with a consumer grade Netgear router (model WGR614V9) and using wired connections. When I first set up the NFS shares, I noticed that performance was pretty terrible. For example, it would take a few minutes to copy 40 mbs worth data from a mounted NFS share to local disk. By playing around with the NFS configuration, I was able to get things running reasonably well. The configuration I settled on for the system exporting the share was: ``` # /etc/exports On the machine exporting the NFS share: /exprt/dir client.ip (rw,async,no_root_squash,no_subtree_check) ``` For the NFS client, I have ``` # /etc/fstab server.ip:/exprt/dir on /imprt/dir type nfs (rw,noatime,rsize=32768,wsize=32768,timeo=14,intr) ``` However, while this seems to work reasonably well for me, it still seems to be faster to copy files from one system to the other using `scp` than it is using NFS. I thought it would be worth asking what NFS configurations other people might be using on similar network set ups that results in reasonably good performance. I know NFS can be pretty sensitive to things like choice of OS and precise network configuration. But, I suspect the set up I have is pretty common amount other users with small local networks, so it would be useful to hear what configuration works best for them. Note: I originally asked this question on [superuser](https://superuser.com/questions/97587/good-nfs-configuration-for-home-network-nfs-performance-issues). But, I got no replies so I suspect it might have been the wrong forum for this type of question.
2010/01/20
[ "https://serverfault.com/questions/104419", "https://serverfault.com", "https://serverfault.com/users/31206/" ]
It's pretty standard for scp to be quicker than NFS; there's a lot more overhead and things that need doing for a network filesystem than for a simple machine-to-machine transfer.
I normally just use SMB and have fine connections. I would like to point you to this site, just incase you have not looked it over. <http://nfs.sourceforge.net/nfs-howto/ar01s05.html>
104,419
I have a small LAN that has a couple of Linux boxes (Ubuntu 9.10) with NFS shares on them. The boxes are networked with a consumer grade Netgear router (model WGR614V9) and using wired connections. When I first set up the NFS shares, I noticed that performance was pretty terrible. For example, it would take a few minutes to copy 40 mbs worth data from a mounted NFS share to local disk. By playing around with the NFS configuration, I was able to get things running reasonably well. The configuration I settled on for the system exporting the share was: ``` # /etc/exports On the machine exporting the NFS share: /exprt/dir client.ip (rw,async,no_root_squash,no_subtree_check) ``` For the NFS client, I have ``` # /etc/fstab server.ip:/exprt/dir on /imprt/dir type nfs (rw,noatime,rsize=32768,wsize=32768,timeo=14,intr) ``` However, while this seems to work reasonably well for me, it still seems to be faster to copy files from one system to the other using `scp` than it is using NFS. I thought it would be worth asking what NFS configurations other people might be using on similar network set ups that results in reasonably good performance. I know NFS can be pretty sensitive to things like choice of OS and precise network configuration. But, I suspect the set up I have is pretty common amount other users with small local networks, so it would be useful to hear what configuration works best for them. Note: I originally asked this question on [superuser](https://superuser.com/questions/97587/good-nfs-configuration-for-home-network-nfs-performance-issues). But, I got no replies so I suspect it might have been the wrong forum for this type of question.
2010/01/20
[ "https://serverfault.com/questions/104419", "https://serverfault.com", "https://serverfault.com/users/31206/" ]
It's pretty standard for scp to be quicker than NFS; there's a lot more overhead and things that need doing for a network filesystem than for a simple machine-to-machine transfer.
I use `rsize=8192,wsize=8192` here, and I have no complaints about performance. I haven't measured it, though.
104,419
I have a small LAN that has a couple of Linux boxes (Ubuntu 9.10) with NFS shares on them. The boxes are networked with a consumer grade Netgear router (model WGR614V9) and using wired connections. When I first set up the NFS shares, I noticed that performance was pretty terrible. For example, it would take a few minutes to copy 40 mbs worth data from a mounted NFS share to local disk. By playing around with the NFS configuration, I was able to get things running reasonably well. The configuration I settled on for the system exporting the share was: ``` # /etc/exports On the machine exporting the NFS share: /exprt/dir client.ip (rw,async,no_root_squash,no_subtree_check) ``` For the NFS client, I have ``` # /etc/fstab server.ip:/exprt/dir on /imprt/dir type nfs (rw,noatime,rsize=32768,wsize=32768,timeo=14,intr) ``` However, while this seems to work reasonably well for me, it still seems to be faster to copy files from one system to the other using `scp` than it is using NFS. I thought it would be worth asking what NFS configurations other people might be using on similar network set ups that results in reasonably good performance. I know NFS can be pretty sensitive to things like choice of OS and precise network configuration. But, I suspect the set up I have is pretty common amount other users with small local networks, so it would be useful to hear what configuration works best for them. Note: I originally asked this question on [superuser](https://superuser.com/questions/97587/good-nfs-configuration-for-home-network-nfs-performance-issues). But, I got no replies so I suspect it might have been the wrong forum for this type of question.
2010/01/20
[ "https://serverfault.com/questions/104419", "https://serverfault.com", "https://serverfault.com/users/31206/" ]
It's pretty standard for scp to be quicker than NFS; there's a lot more overhead and things that need doing for a network filesystem than for a simple machine-to-machine transfer.
NFS should give you about 50% of the underlying disk write performance. If your disk does 100MB/s, then you should be able to do 50MB/s NFS write. About the mount options : use tcp. udp can give pretty bad results if your network is heavily loaded, or any network device is flaky.
104,419
I have a small LAN that has a couple of Linux boxes (Ubuntu 9.10) with NFS shares on them. The boxes are networked with a consumer grade Netgear router (model WGR614V9) and using wired connections. When I first set up the NFS shares, I noticed that performance was pretty terrible. For example, it would take a few minutes to copy 40 mbs worth data from a mounted NFS share to local disk. By playing around with the NFS configuration, I was able to get things running reasonably well. The configuration I settled on for the system exporting the share was: ``` # /etc/exports On the machine exporting the NFS share: /exprt/dir client.ip (rw,async,no_root_squash,no_subtree_check) ``` For the NFS client, I have ``` # /etc/fstab server.ip:/exprt/dir on /imprt/dir type nfs (rw,noatime,rsize=32768,wsize=32768,timeo=14,intr) ``` However, while this seems to work reasonably well for me, it still seems to be faster to copy files from one system to the other using `scp` than it is using NFS. I thought it would be worth asking what NFS configurations other people might be using on similar network set ups that results in reasonably good performance. I know NFS can be pretty sensitive to things like choice of OS and precise network configuration. But, I suspect the set up I have is pretty common amount other users with small local networks, so it would be useful to hear what configuration works best for them. Note: I originally asked this question on [superuser](https://superuser.com/questions/97587/good-nfs-configuration-for-home-network-nfs-performance-issues). But, I got no replies so I suspect it might have been the wrong forum for this type of question.
2010/01/20
[ "https://serverfault.com/questions/104419", "https://serverfault.com", "https://serverfault.com/users/31206/" ]
NFS should give you about 50% of the underlying disk write performance. If your disk does 100MB/s, then you should be able to do 50MB/s NFS write. About the mount options : use tcp. udp can give pretty bad results if your network is heavily loaded, or any network device is flaky.
I normally just use SMB and have fine connections. I would like to point you to this site, just incase you have not looked it over. <http://nfs.sourceforge.net/nfs-howto/ar01s05.html>
104,419
I have a small LAN that has a couple of Linux boxes (Ubuntu 9.10) with NFS shares on them. The boxes are networked with a consumer grade Netgear router (model WGR614V9) and using wired connections. When I first set up the NFS shares, I noticed that performance was pretty terrible. For example, it would take a few minutes to copy 40 mbs worth data from a mounted NFS share to local disk. By playing around with the NFS configuration, I was able to get things running reasonably well. The configuration I settled on for the system exporting the share was: ``` # /etc/exports On the machine exporting the NFS share: /exprt/dir client.ip (rw,async,no_root_squash,no_subtree_check) ``` For the NFS client, I have ``` # /etc/fstab server.ip:/exprt/dir on /imprt/dir type nfs (rw,noatime,rsize=32768,wsize=32768,timeo=14,intr) ``` However, while this seems to work reasonably well for me, it still seems to be faster to copy files from one system to the other using `scp` than it is using NFS. I thought it would be worth asking what NFS configurations other people might be using on similar network set ups that results in reasonably good performance. I know NFS can be pretty sensitive to things like choice of OS and precise network configuration. But, I suspect the set up I have is pretty common amount other users with small local networks, so it would be useful to hear what configuration works best for them. Note: I originally asked this question on [superuser](https://superuser.com/questions/97587/good-nfs-configuration-for-home-network-nfs-performance-issues). But, I got no replies so I suspect it might have been the wrong forum for this type of question.
2010/01/20
[ "https://serverfault.com/questions/104419", "https://serverfault.com", "https://serverfault.com/users/31206/" ]
NFS should give you about 50% of the underlying disk write performance. If your disk does 100MB/s, then you should be able to do 50MB/s NFS write. About the mount options : use tcp. udp can give pretty bad results if your network is heavily loaded, or any network device is flaky.
I use `rsize=8192,wsize=8192` here, and I have no complaints about performance. I haven't measured it, though.
64,138,123
I'm currently just getting into JavaScript with HTML. I have been using HTML and CSS for a while now, but I only just recently got into Python, so now I feel I'll be more capable / able to understand JavaScript. I'm currently working on an idea I've had, a Fortune Cookie Maker. The user inputs text into a textbox input. This is stored in a variable. When the user clicks ok, it gets the text from the textbox, and sets it to that variable. Then, it switches the page, and gets the variable from the script, and sets a paragraph to the text value of that variable. However, my problem is, the paragraph won't display the text. Here's my code: ```js var fortune = null; function dispTxt() { var txt = document.getElementById('textbox').value; var hid = document.getElementById('conftxt'); if (txt.length > 0) { //hid.style.display = 'block'; document.getElementById("conftxt").style.opacity = 1; document.getElementById("textbox").style.color = "#ffffff"; } else { //hid.style.display = 'none'; document.getElementById("conftxt").style.opacity = 0; //document.getElementById("textbox").style.color = "#000000"; } document.getElementById("txt").addEventListener("onkeyup", function() { dispTxt(); }) }; function confirm() { //Get the text that is inputted by the user. fortune = document.getElementById("conftxt").value; window.location = "fortune.html"; window.alert(fortune); } function setFortune() { document.getElementById('fortunetext').value = fortune; } ``` And here's a [link to the repl](https://repl.it/@SpencerLeagra/Fortune-Cookie-Maker#script.js) itself for reference. Also, if anyone has any tips for how I should go about making the fortune cookie itself, please, let me know. I essentially just want it to be so that once you confirm what the fortune says, the fortune cookie appears, and you can click on it, and break it open, and it reveals the fortune. Thanks!
2020/09/30
[ "https://Stackoverflow.com/questions/64138123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12274981/" ]
Those are the power shell commands to get the distribution members, we can filter the data if needed Graph API link to get the members from Distribution list <https://learn.microsoft.com/en-us/graph/api/group-list-members?view=graph-rest-1.0&tabs=http>
You could use the [Microsoft.Graph](https://www.powershellgallery.com/packages/Microsoft.Graph/1.0.1) PowerShell module for this, I think.
59,396,551
**Problem:** I can't seem to get the > `MIN` formula to work within `SUMIFS` **Requesting:** Formula that will return the `SUM` of balloons `IF` the dollars amount is greater than the `MIN` Expected output = 510,000 balloons [![enter image description here](https://i.stack.imgur.com/hJz53.png)](https://i.stack.imgur.com/hJz53.png) Note: This is just an example problem for easy comprehension. In reality the data set is much larger and I will include multiple `IF`s.
2019/12/18
[ "https://Stackoverflow.com/questions/59396551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12560070/" ]
You can sum the entire range and then just subtract the values from the range where the dollar amount is equal to the min $. If your min value is repeated, they will all be removed from the sum. ``` =SUM(C:C) - SUMIF(B:B,MIN(B:B),C:C) ``` --- I believe you were attempting to do this in one sum equation which would look like this ``` =SUMIF(B:B,">"&MIN(B:B),C:C) ```
Even easier: ``` =SUMPRODUCT(--(B:B>MIN(B:B)),C:C) ```
17,557,129
Background info: I'm setting up a way to embed SoundCloud's HTML5 widget on my forum. The widget, on its own, adjusts its content in accordance with its height. As you can see in the jsFiddle example below, I have it set up so that when a widget is hovered over, it expands from 166px to 450px in height, which triggers the widget to adjust its content. The problem I'm trying to fix is that all SoundCloud widgets fold out, whether they're part of a set/playlist or not. If it isn't part of a set/playlist, the result is a large blank area when hovered over. I've noticed that if a sound is part of a set/playlist, /sets/ is present in the URL. I'm trying to modify my script so that it checks the URL for that string. If it finds it, allow the widget to expand when hovered over; if it doesn't, don't allow it to expand when hovered over. Currently I'm at a roadblock. It works, but the search is returning the position in the line, rather than the string I need. I added a little bit of code to demonstrate that: <http://jsfiddle.net/TYWUf/11/> JS without the extra code: ``` jQuery(document).ready(function () { var soundSrc = $(".soundCloudEmbed").attr("src"); var isSet = (soundSrc).search('%' + '2Fsets' + '%' + '2F'); $(".soundCloudEmbed").hover( function () { $(this).addClass("soundCloudHover"); }, function () { $(this).removeClass("soundCloudHover"); }); }); ``` (if I didn't ask this question correctly, please let me know)
2013/07/09
[ "https://Stackoverflow.com/questions/17557129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2565884/" ]
Check this out, I think it's what you're looking for: <http://jsfiddle.net/dSX5g/> ``` jQuery(document).ready(function () { $('.soundCloudEmbed').each(function () { var soundSrc = $(this).attr("src"); var isSet = (soundSrc).search('%' + '2Fsets' + '%' + '2F'); if (isSet > -1) { $(this).hover(function () { $(this).addClass("soundCloudHover"); }, function () { $(this).removeClass("soundCloudHover"); }); } }); }); ``` Each embedded item needs to be evaluated separately.
You are manually setting the class as an html attribute, and then using a JQuery selector to expand anything in that class. You should start out by looping through your iframes and setting different classes based on if it's part of a set or not. That way the JQuery selector will only expand those classes that are sets.
749
I started to ramble about this a while ago, but [this question](https://mathematica.stackexchange.com/q/11305/193) asked today fired up some structured thinking that I'd want to share and discuss. The question in question is a very simple one, and when I saw it, I thought -"I'll leave it for someone less experienced"- and it happened. Two users answered with a method already sketched on a previous Toad's comment. So far so good, as a comment is not an answer. The way they solved it is clearly inferior to the third answer posted a bit later by @RM himself, who resorted to `HoldForm[]` instead of joining strings. In this scenario, @RM's answer is valuable and served a clear propose: At least three users have learned a good lesson. But sometimes, it happens the other way around. We (more experienced users) are answering simple questions in the obvious way, without more consideration than a few lines of quick code that solves the problem, but: * inhibits beginner's answering activities; and * doesn't teach more than a basic technique (which *could* be valuable too) Both points are a real pity, as beginners are losing an opportunity to learn. I'd like the community to think about a way to palliate these effects. I don't have a good proposal, but perhaps (and it's far from perfect) we could implement a tag like [entry-level](https://mathematica.stackexchange.com/questions/tagged/entry-level "show questions tagged 'entry-level'") (to be most commonly applied as a retag) to communicate to experienced users that the simple and obvious "HowTo" is too basic and not the expected answer from them. It has its drawbacks, though. Answers could be delayed, different personal opinions are likely to arise on the classification, and bad answers may pile up before a good one could be written. Not to mention the rep loss from restraining to answer. I hear you.
2012/09/30
[ "https://mathematica.meta.stackexchange.com/questions/749", "https://mathematica.meta.stackexchange.com", "https://mathematica.meta.stackexchange.com/users/193/" ]
I don’t favour tagging things as [entry-level](https://mathematica.stackexchange.com/questions/tagged/entry-level "show questions tagged 'entry-level'"), not just because it could be seen pejoratively, but also because so many questions on this site only *seem* easy to experienced users. We all know that Mathematica has a steep learning curve, and that it is such a rich and complex environment that all sorts of gems can lie hiding in the documentation, apparently in plain sight but in reality hard for newer users to see.[1] Something might be β€œeasy”, but is really in the realm of [β€œknowing where to hit it”](http://fastforwardit.blogspot.com.au/2008/03/knowing-where-to-hit.html). I think the way forward is for more experienced users to try to avoid, where possible, the temptation to play FGITW on easy questions, and to make sure we are explaining our work thoroughly, including *why* we made the choices we made of the multiple ways to do things in Mathematica. [1] For example, it was only today that I learned all the different ways to specify `Blend` and about the `DendrogramPlot` function.
I upvoted the question, and will consider myself "entry-level" for the, er, next couple of weeks still. On Electronics.SE tags like [homework](https://mathematica.stackexchange.com/questions/tagged/homework "show questions tagged 'homework'") and [beginner](https://mathematica.stackexchange.com/questions/tagged/beginner "show questions tagged 'beginner'") are deprecated because we think tags should give an indication about the question's *topic*, not be meta. Of course we have entry-level questions on EE.SE as well, and it will be an issue on many StackExchange sites. I've been thinking about a user skill level indication, *next* to tagging. Think of the cook hats at the top of a cookbook's recipes: 1 cook's hat is novice, 5 hats is advanced. If this could be implemented SE-wide users can decide what level they expect the answers to be, and answerers can adapt their answer to that level, or decline to answer.
749
I started to ramble about this a while ago, but [this question](https://mathematica.stackexchange.com/q/11305/193) asked today fired up some structured thinking that I'd want to share and discuss. The question in question is a very simple one, and when I saw it, I thought -"I'll leave it for someone less experienced"- and it happened. Two users answered with a method already sketched on a previous Toad's comment. So far so good, as a comment is not an answer. The way they solved it is clearly inferior to the third answer posted a bit later by @RM himself, who resorted to `HoldForm[]` instead of joining strings. In this scenario, @RM's answer is valuable and served a clear propose: At least three users have learned a good lesson. But sometimes, it happens the other way around. We (more experienced users) are answering simple questions in the obvious way, without more consideration than a few lines of quick code that solves the problem, but: * inhibits beginner's answering activities; and * doesn't teach more than a basic technique (which *could* be valuable too) Both points are a real pity, as beginners are losing an opportunity to learn. I'd like the community to think about a way to palliate these effects. I don't have a good proposal, but perhaps (and it's far from perfect) we could implement a tag like [entry-level](https://mathematica.stackexchange.com/questions/tagged/entry-level "show questions tagged 'entry-level'") (to be most commonly applied as a retag) to communicate to experienced users that the simple and obvious "HowTo" is too basic and not the expected answer from them. It has its drawbacks, though. Answers could be delayed, different personal opinions are likely to arise on the classification, and bad answers may pile up before a good one could be written. Not to mention the rep loss from restraining to answer. I hear you.
2012/09/30
[ "https://mathematica.meta.stackexchange.com/questions/749", "https://mathematica.meta.stackexchange.com", "https://mathematica.meta.stackexchange.com/users/193/" ]
I guess the best way to resolve this issue is that you *always* put as much thought as possible into an answer. This on one hand gives beginners time to give the obvious answers, on the other hand increases the probability of really great answers. Of course, the reputation system together with the implicit "first post bonus" tempts one to rush out a simple answer (in the best case with the intent to improve on it afterwards). But then, my highest rated answer on the whole SE network (which additionally brought me several badges, including my only gold badge on the entire SE network) was *not* a first post (actually it also wasn't an answer which I would have expected to get that many upvotes).
I upvoted the question, and will consider myself "entry-level" for the, er, next couple of weeks still. On Electronics.SE tags like [homework](https://mathematica.stackexchange.com/questions/tagged/homework "show questions tagged 'homework'") and [beginner](https://mathematica.stackexchange.com/questions/tagged/beginner "show questions tagged 'beginner'") are deprecated because we think tags should give an indication about the question's *topic*, not be meta. Of course we have entry-level questions on EE.SE as well, and it will be an issue on many StackExchange sites. I've been thinking about a user skill level indication, *next* to tagging. Think of the cook hats at the top of a cookbook's recipes: 1 cook's hat is novice, 5 hats is advanced. If this could be implemented SE-wide users can decide what level they expect the answers to be, and answerers can adapt their answer to that level, or decline to answer.
749
I started to ramble about this a while ago, but [this question](https://mathematica.stackexchange.com/q/11305/193) asked today fired up some structured thinking that I'd want to share and discuss. The question in question is a very simple one, and when I saw it, I thought -"I'll leave it for someone less experienced"- and it happened. Two users answered with a method already sketched on a previous Toad's comment. So far so good, as a comment is not an answer. The way they solved it is clearly inferior to the third answer posted a bit later by @RM himself, who resorted to `HoldForm[]` instead of joining strings. In this scenario, @RM's answer is valuable and served a clear propose: At least three users have learned a good lesson. But sometimes, it happens the other way around. We (more experienced users) are answering simple questions in the obvious way, without more consideration than a few lines of quick code that solves the problem, but: * inhibits beginner's answering activities; and * doesn't teach more than a basic technique (which *could* be valuable too) Both points are a real pity, as beginners are losing an opportunity to learn. I'd like the community to think about a way to palliate these effects. I don't have a good proposal, but perhaps (and it's far from perfect) we could implement a tag like [entry-level](https://mathematica.stackexchange.com/questions/tagged/entry-level "show questions tagged 'entry-level'") (to be most commonly applied as a retag) to communicate to experienced users that the simple and obvious "HowTo" is too basic and not the expected answer from them. It has its drawbacks, though. Answers could be delayed, different personal opinions are likely to arise on the classification, and bad answers may pile up before a good one could be written. Not to mention the rep loss from restraining to answer. I hear you.
2012/09/30
[ "https://mathematica.meta.stackexchange.com/questions/749", "https://mathematica.meta.stackexchange.com", "https://mathematica.meta.stackexchange.com/users/193/" ]
I am new MMa SE participant with intermediate/strong, but not expert, knowledge of MMA. So I experience this issue from the inside. My insight and distillation of the points above is: 1. An "entry-level" tag not a good idea because: entry-level is in the eye of the beholder, questions can be answered at different levels and each level will be useful and explanatory to different users, and it is pejorative. 2. Each subsequent answer could show either a different, or "deeper" answer, and explain how the previous answers were but as Newtonian physics to my new Relatitivity physics. That would help level 3 users move to level 4, etc. working their way on up to level 9 ("The Might Thor" - aka rm, Mr. Wizard, belisarius, J.M., Sjoerd, Leonid, etc.). 3. Wikepedia observes that a common criticism of SE is that "Questions are commonly answered fast without focusing on quality or correctness, to boost reputation." I don't really think that's a big problem, but I noticed that even I, a new level 3 user, was trying to answer questions I thought I could before anyone else (until I read the Wikepedia comment and joined SE Anonymous). My point is that the "each subsequent answer goes deeper" approach has multiple merits. 4. Part of the responsibility of the higher level answers could be to clean up the errors in the previous answers, within reason. 5. There is no "structural" solution to this issue. It seems to me that SE can be thought of as an emerging social or cultural form, made possible by the internet, etc., and level nines should also see to it that SE develops along with it. 6. This doesn't sound like it would be as much fun as trying to get the best answer first. 7. Who is level 10?
I upvoted the question, and will consider myself "entry-level" for the, er, next couple of weeks still. On Electronics.SE tags like [homework](https://mathematica.stackexchange.com/questions/tagged/homework "show questions tagged 'homework'") and [beginner](https://mathematica.stackexchange.com/questions/tagged/beginner "show questions tagged 'beginner'") are deprecated because we think tags should give an indication about the question's *topic*, not be meta. Of course we have entry-level questions on EE.SE as well, and it will be an issue on many StackExchange sites. I've been thinking about a user skill level indication, *next* to tagging. Think of the cook hats at the top of a cookbook's recipes: 1 cook's hat is novice, 5 hats is advanced. If this could be implemented SE-wide users can decide what level they expect the answers to be, and answerers can adapt their answer to that level, or decline to answer.
749
I started to ramble about this a while ago, but [this question](https://mathematica.stackexchange.com/q/11305/193) asked today fired up some structured thinking that I'd want to share and discuss. The question in question is a very simple one, and when I saw it, I thought -"I'll leave it for someone less experienced"- and it happened. Two users answered with a method already sketched on a previous Toad's comment. So far so good, as a comment is not an answer. The way they solved it is clearly inferior to the third answer posted a bit later by @RM himself, who resorted to `HoldForm[]` instead of joining strings. In this scenario, @RM's answer is valuable and served a clear propose: At least three users have learned a good lesson. But sometimes, it happens the other way around. We (more experienced users) are answering simple questions in the obvious way, without more consideration than a few lines of quick code that solves the problem, but: * inhibits beginner's answering activities; and * doesn't teach more than a basic technique (which *could* be valuable too) Both points are a real pity, as beginners are losing an opportunity to learn. I'd like the community to think about a way to palliate these effects. I don't have a good proposal, but perhaps (and it's far from perfect) we could implement a tag like [entry-level](https://mathematica.stackexchange.com/questions/tagged/entry-level "show questions tagged 'entry-level'") (to be most commonly applied as a retag) to communicate to experienced users that the simple and obvious "HowTo" is too basic and not the expected answer from them. It has its drawbacks, though. Answers could be delayed, different personal opinions are likely to arise on the classification, and bad answers may pile up before a good one could be written. Not to mention the rep loss from restraining to answer. I hear you.
2012/09/30
[ "https://mathematica.meta.stackexchange.com/questions/749", "https://mathematica.meta.stackexchange.com", "https://mathematica.meta.stackexchange.com/users/193/" ]
I don’t favour tagging things as [entry-level](https://mathematica.stackexchange.com/questions/tagged/entry-level "show questions tagged 'entry-level'"), not just because it could be seen pejoratively, but also because so many questions on this site only *seem* easy to experienced users. We all know that Mathematica has a steep learning curve, and that it is such a rich and complex environment that all sorts of gems can lie hiding in the documentation, apparently in plain sight but in reality hard for newer users to see.[1] Something might be β€œeasy”, but is really in the realm of [β€œknowing where to hit it”](http://fastforwardit.blogspot.com.au/2008/03/knowing-where-to-hit.html). I think the way forward is for more experienced users to try to avoid, where possible, the temptation to play FGITW on easy questions, and to make sure we are explaining our work thoroughly, including *why* we made the choices we made of the multiple ways to do things in Mathematica. [1] For example, it was only today that I learned all the different ways to specify `Blend` and about the `DendrogramPlot` function.
I'm now a bit jealous, annoyed with myself, but mostly annoyed with you. ;-P Why? I passed on answering [this question](https://mathematica.stackexchange.com/q/11350/121) first (I had working code, though not quite as nice a result) because I figured that it was a good question for newer users to answer. I knew it would be popular but I had no idea it would become *the most popular question ever* on the site, and now I'll be haunted by the fact that the first answer could have been mine. For that reason I say: answer any question you can as soon as you can. Down with the entry-level tag! This is intended to be humorous but it also holds a shadow of truth.
749
I started to ramble about this a while ago, but [this question](https://mathematica.stackexchange.com/q/11305/193) asked today fired up some structured thinking that I'd want to share and discuss. The question in question is a very simple one, and when I saw it, I thought -"I'll leave it for someone less experienced"- and it happened. Two users answered with a method already sketched on a previous Toad's comment. So far so good, as a comment is not an answer. The way they solved it is clearly inferior to the third answer posted a bit later by @RM himself, who resorted to `HoldForm[]` instead of joining strings. In this scenario, @RM's answer is valuable and served a clear propose: At least three users have learned a good lesson. But sometimes, it happens the other way around. We (more experienced users) are answering simple questions in the obvious way, without more consideration than a few lines of quick code that solves the problem, but: * inhibits beginner's answering activities; and * doesn't teach more than a basic technique (which *could* be valuable too) Both points are a real pity, as beginners are losing an opportunity to learn. I'd like the community to think about a way to palliate these effects. I don't have a good proposal, but perhaps (and it's far from perfect) we could implement a tag like [entry-level](https://mathematica.stackexchange.com/questions/tagged/entry-level "show questions tagged 'entry-level'") (to be most commonly applied as a retag) to communicate to experienced users that the simple and obvious "HowTo" is too basic and not the expected answer from them. It has its drawbacks, though. Answers could be delayed, different personal opinions are likely to arise on the classification, and bad answers may pile up before a good one could be written. Not to mention the rep loss from restraining to answer. I hear you.
2012/09/30
[ "https://mathematica.meta.stackexchange.com/questions/749", "https://mathematica.meta.stackexchange.com", "https://mathematica.meta.stackexchange.com/users/193/" ]
I guess the best way to resolve this issue is that you *always* put as much thought as possible into an answer. This on one hand gives beginners time to give the obvious answers, on the other hand increases the probability of really great answers. Of course, the reputation system together with the implicit "first post bonus" tempts one to rush out a simple answer (in the best case with the intent to improve on it afterwards). But then, my highest rated answer on the whole SE network (which additionally brought me several badges, including my only gold badge on the entire SE network) was *not* a first post (actually it also wasn't an answer which I would have expected to get that many upvotes).
I'm now a bit jealous, annoyed with myself, but mostly annoyed with you. ;-P Why? I passed on answering [this question](https://mathematica.stackexchange.com/q/11350/121) first (I had working code, though not quite as nice a result) because I figured that it was a good question for newer users to answer. I knew it would be popular but I had no idea it would become *the most popular question ever* on the site, and now I'll be haunted by the fact that the first answer could have been mine. For that reason I say: answer any question you can as soon as you can. Down with the entry-level tag! This is intended to be humorous but it also holds a shadow of truth.
749
I started to ramble about this a while ago, but [this question](https://mathematica.stackexchange.com/q/11305/193) asked today fired up some structured thinking that I'd want to share and discuss. The question in question is a very simple one, and when I saw it, I thought -"I'll leave it for someone less experienced"- and it happened. Two users answered with a method already sketched on a previous Toad's comment. So far so good, as a comment is not an answer. The way they solved it is clearly inferior to the third answer posted a bit later by @RM himself, who resorted to `HoldForm[]` instead of joining strings. In this scenario, @RM's answer is valuable and served a clear propose: At least three users have learned a good lesson. But sometimes, it happens the other way around. We (more experienced users) are answering simple questions in the obvious way, without more consideration than a few lines of quick code that solves the problem, but: * inhibits beginner's answering activities; and * doesn't teach more than a basic technique (which *could* be valuable too) Both points are a real pity, as beginners are losing an opportunity to learn. I'd like the community to think about a way to palliate these effects. I don't have a good proposal, but perhaps (and it's far from perfect) we could implement a tag like [entry-level](https://mathematica.stackexchange.com/questions/tagged/entry-level "show questions tagged 'entry-level'") (to be most commonly applied as a retag) to communicate to experienced users that the simple and obvious "HowTo" is too basic and not the expected answer from them. It has its drawbacks, though. Answers could be delayed, different personal opinions are likely to arise on the classification, and bad answers may pile up before a good one could be written. Not to mention the rep loss from restraining to answer. I hear you.
2012/09/30
[ "https://mathematica.meta.stackexchange.com/questions/749", "https://mathematica.meta.stackexchange.com", "https://mathematica.meta.stackexchange.com/users/193/" ]
I am new MMa SE participant with intermediate/strong, but not expert, knowledge of MMA. So I experience this issue from the inside. My insight and distillation of the points above is: 1. An "entry-level" tag not a good idea because: entry-level is in the eye of the beholder, questions can be answered at different levels and each level will be useful and explanatory to different users, and it is pejorative. 2. Each subsequent answer could show either a different, or "deeper" answer, and explain how the previous answers were but as Newtonian physics to my new Relatitivity physics. That would help level 3 users move to level 4, etc. working their way on up to level 9 ("The Might Thor" - aka rm, Mr. Wizard, belisarius, J.M., Sjoerd, Leonid, etc.). 3. Wikepedia observes that a common criticism of SE is that "Questions are commonly answered fast without focusing on quality or correctness, to boost reputation." I don't really think that's a big problem, but I noticed that even I, a new level 3 user, was trying to answer questions I thought I could before anyone else (until I read the Wikepedia comment and joined SE Anonymous). My point is that the "each subsequent answer goes deeper" approach has multiple merits. 4. Part of the responsibility of the higher level answers could be to clean up the errors in the previous answers, within reason. 5. There is no "structural" solution to this issue. It seems to me that SE can be thought of as an emerging social or cultural form, made possible by the internet, etc., and level nines should also see to it that SE develops along with it. 6. This doesn't sound like it would be as much fun as trying to get the best answer first. 7. Who is level 10?
I'm now a bit jealous, annoyed with myself, but mostly annoyed with you. ;-P Why? I passed on answering [this question](https://mathematica.stackexchange.com/q/11350/121) first (I had working code, though not quite as nice a result) because I figured that it was a good question for newer users to answer. I knew it would be popular but I had no idea it would become *the most popular question ever* on the site, and now I'll be haunted by the fact that the first answer could have been mine. For that reason I say: answer any question you can as soon as you can. Down with the entry-level tag! This is intended to be humorous but it also holds a shadow of truth.
62,168,749
Below you can see my query, which gives the following result: ``` select t.actual_date, t.id_key, t.attendance_status, t.money_step, sum(t.money_step) over (partition by t.id_key order by t.actual_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)as accumulated from example t order by t.id_key, t.actual_date ``` [![enter image description here](https://i.stack.imgur.com/xtLXU.png)](https://i.stack.imgur.com/xtLXU.png) Results of the query I want the "accumulated" column to add up the value of "money\_step" for each id\_key. If the id\_key is the second time '15' for an Id, the counter should add up from the beginning. For ID\_KEY = 1 it should look like this: accumulated: ``` Row 1:20 Row 2: 80 Row 3: 100 Row 4: 120 ``` For ID\_KEY = 2 ist should look like: ``` Row 1: accumulated = 30; attendance_status = 7 Row 2: accumulated = 130; attendance_status = 15 Row 3: accumulated = 30; attendance_status = 15 Row 4: accumulated = 60; attendance_status = 15 ``` Level 15 always has the latest date. From the second date of level 15, the sum should restart for each id. All values ​​less than 15 should be counted as normal. How can I do this in the query? Can someone help me?
2020/06/03
[ "https://Stackoverflow.com/questions/62168749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13634498/" ]
Try this below logic- [DEMO HERE](https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=7890c1852fd31be5cfe107599935cdb5) ``` SELECT *, SUM(A.money_step) over ( partition by A.id_key, A.P ORDER BY A.actual_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW )as accumulated FROM ( SELECT A.*, ( SELECT CASE WHEN COUNT(*) >= 2 THEN 2 ELSE 1 END FROM your_table B WHERE B.id_key = A.id_key AND B.actual_date <= A.actual_date AND attendance_status = 15 ) P FROM your_table A )A ORDER BY A.id_key,A.actual_date ```
This is untested, as I'm not transcribing an image, however, I *think* this will work. If not, then consumable sample data is must here: ``` WITH CTE AS (SELECT t.actual_date, t.id_key, t.attendance_status, t.money_step, ROW_NUMBER() OVER (PARTITION BY t.id_key, CASE attendance_status WHEN 15 THEN 1 ELSE 0 END ORDER BY t.actual_date) AS RN FROM example t) SELECT C.actual_date, C.id_key, C.attendance_status, C.money_step, SUM(t.money_step) OVER (PARTITION BY t.id_key, CASE WHEN RN > 1 THEN 1 ELSE 0 END ORDER BY t.actual_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS accumulated FROM CTE C; ```
62,168,749
Below you can see my query, which gives the following result: ``` select t.actual_date, t.id_key, t.attendance_status, t.money_step, sum(t.money_step) over (partition by t.id_key order by t.actual_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)as accumulated from example t order by t.id_key, t.actual_date ``` [![enter image description here](https://i.stack.imgur.com/xtLXU.png)](https://i.stack.imgur.com/xtLXU.png) Results of the query I want the "accumulated" column to add up the value of "money\_step" for each id\_key. If the id\_key is the second time '15' for an Id, the counter should add up from the beginning. For ID\_KEY = 1 it should look like this: accumulated: ``` Row 1:20 Row 2: 80 Row 3: 100 Row 4: 120 ``` For ID\_KEY = 2 ist should look like: ``` Row 1: accumulated = 30; attendance_status = 7 Row 2: accumulated = 130; attendance_status = 15 Row 3: accumulated = 30; attendance_status = 15 Row 4: accumulated = 60; attendance_status = 15 ``` Level 15 always has the latest date. From the second date of level 15, the sum should restart for each id. All values ​​less than 15 should be counted as normal. How can I do this in the query? Can someone help me?
2020/06/03
[ "https://Stackoverflow.com/questions/62168749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13634498/" ]
Try this below logic- [DEMO HERE](https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=7890c1852fd31be5cfe107599935cdb5) ``` SELECT *, SUM(A.money_step) over ( partition by A.id_key, A.P ORDER BY A.actual_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW )as accumulated FROM ( SELECT A.*, ( SELECT CASE WHEN COUNT(*) >= 2 THEN 2 ELSE 1 END FROM your_table B WHERE B.id_key = A.id_key AND B.actual_date <= A.actual_date AND attendance_status = 15 ) P FROM your_table A )A ORDER BY A.id_key,A.actual_date ```
I would strongly advise you to do this only using window functions. It is actually pretty simple: ``` SELECT t.*, SUM(t.money_step) OVER (PARTITION BY id_key, grp ORDER BY actual_date) as accumulated FROM (SELECT t.*, SUM(CASE WHEN seqnum = 2 AND attendance_status = 15 THEN 1 ELSE 0 END) OVER (PARTITION BY id_key ORDER BY actual_date) as grp FROM (SELECT t.*, ROW_NUMBER() OVER (PARTITION BY id_key, attendance_status ORDER BY actual_date) as seqnum FROM t ) t ) t ORDER BY t.id_key, t.actual_date; ``` [Here](https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=a38bb30e3c0e6e48ae94dffb94c1fda1) is a db<>fiddle.
43,929,058
I want to compare the file path where captured by the `FileVisitResult visitFile` in my arraylist. The reason for this comparison is preventing there's duplicate file path store in the arraylist since `FileVisitResult visitFile` will keep on looping while the condition is true. I want to make sure all the file had just visited by the method once. So each time the `FileVisitResult` method will capture the file path and store into arraylist, when the next round for the method execution, any new file path detected will compare to the file path in the arraylist, but it's still fail to do it after I search some information online,the `Thread.sleep()` use to halt the program for my understanding the flow of my source code ``` public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { String f; File file1; Path tempPath1,tempPath2; if(counter == 0) //first round for the execution { counter++; try { Thread.sleep(5000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("The abs path of the file is"+file); y2j.add(file); //add path to arraylist f = file.toString(); file1 = new File(f); if ( file1.exists()) //checking the file process whether still consume by any other process { RandomAccessFile statusCheck = null; try { statusCheck = new RandomAccessFile(file1,"r"); if(statusCheck != null) { System.out.println("Not hodling by any process,clear to send for scanning"); statusCheck.close(); ambrose(); //do something in this method } } catch(Exception e) { System.out.println("In processing : " + e.getMessage()); } } } else if(counter > 0) //after first round of execution { try { Thread.sleep(5000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("larger than 0"); System.out.println("The abs path of the file is"+file); for(int i = 0 ; i<y2j.size()-1;i--) { System.out.println("In the for loop" +y2j); for(int k = i+1 ; k<y2j.size();k++) { if(file == y2j.get(k)) { System.out.println("they are same"); } else if(file != y2j.get(k)) { y2j.add(file); //add path to arraylist ambrose(); //do something in this method } } } } return FileVisitResult.CONTINUE; } ``` ``` The abs path of the file isC:\REST API\source\abc\abc.xlsx Not hodling by any process,clear to send for scanning Dirty deed here larger than 0 The abs path of the file isC:\REST API\source\abc\def.txt larger than 0 The abs path of the file isC:\REST API\source\abc\abc.xlsx larger than 0 The abs path of the file isC:\REST API\source\abc\def.txt ``` It's seen like not entering the for loop, I have spent some time on it but can't figure where is my problem.
2017/05/12
[ "https://Stackoverflow.com/questions/43929058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7319383/" ]
Instead of `file == y2j.get(i)` use `equals` method. Also instead of going through whole list you can use method `contains` that will return true if list contains element. `==` in java compares if this is exacly the same object by comparing reference, but it will not distinguish between objects that look the same but are not same, ex: `new String("n") == new String("n")` will return false.
If you want distinct set of file paths, then you can use **Set** instead of **List**. If you use **Set** then you don't have to run an extra loop for removing duplicates.
40,620,479
I'm in the process of creating a REST API using Spring 4 MVC. I wish I could make it possible, when an invalid endpoint is requested, to deliver a default JSON error object. I've read about the @ControllerAdvice and @ExceptionHandler, which I tried to use properly : ``` package com.yopyop.wackend.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.NoHandlerFoundException; import com.yopyop.wackend.controller.ErrorResponse; import com.yopyop.wackend.service.NotFoundException; @ControllerAdvice public class ExceptionControllerAdvice { @ExceptionHandler(Exception.class) public ResponseEntity<ErrorResponse> exceptionHandler(Exception ex) { ErrorResponse error = new ErrorResponse(); error.setErrorCode(HttpStatus.INTERNAL_SERVER_ERROR.value()); if (ex.getClass()==NotFoundException.class) { error.setMessage("ExceptionControllerAdvice() Not found"); error.setErrorCode(HttpStatus.NOT_FOUND.value()); return new ResponseEntity<ErrorResponse>(error, HttpStatus.NOT_FOUND); } else { error.setMessage("ExceptionControllerAdvice() " + ex.getClass() + "(" + ex.getMessage() + ")"); error.setErrorCode(HttpStatus.INTERNAL_SERVER_ERROR.value()); } return new ResponseEntity<ErrorResponse>(error, HttpStatus.INTERNAL_SERVER_ERROR); } @ExceptionHandler({NoHandlerFoundException.class}) ResponseEntity<ErrorResponse> handleNoHandlerFoundException(NoHandlerFoundException ex, WebRequest request) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); ErrorResponse error = new ErrorResponse(); error.setErrorCode(HttpStatus.INTERNAL_SERVER_ERROR.value()); error.setMessage("ExceptionControllerAdvice() " + ex.getClass() + "(" + ex.getMessage() + ")"); return new ResponseEntity<ErrorResponse>(error, HttpStatus.INTERNAL_SERVER_ERROR); } } ``` My ErrorResponse class is as follow: ``` package com.yopyop.wackend.controller; public class ErrorResponse { private int errorCode; private String message; public int getErrorCode() { return errorCode; } public void setErrorCode(int errorCode) { this.errorCode = errorCode; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } } ``` I modified web.xml so that the NoHandlerFound exception is thrown: ``` <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Wackend WebApp</display-name> <servlet> <servlet-name>wackend</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <init-param> <param-name>throwExceptionIfNoHandlerFound</param-name> <param-value>true</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>wackend</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app> ``` Nevetheless, when a request to an unmapped endpoint is received, I get : ``` > 22:47:28.545 [http-nio-8080-exec-15] DEBUG > o.s.web.servlet.DispatcherServlet - DispatcherServlet with name > 'wackend' processing GET request for [/wackend/swagger-ui.html] > 22:47:28.548 [http-nio-8080-exec-15] DEBUG > o.s.w.s.m.m.a.RequestMappingHandlerMapping - Looking up handler method > for path /swagger-ui.html 22:47:28.552 [http-nio-8080-exec-15] DEBUG > o.s.w.s.m.m.a.RequestMappingHandlerMapping - Returning handler method > [public void > com.yopyop.wackend.controller.DefaultController.unmappedRequest(javax.servlet.http.HttpServletRequest) > throws org.springframework.web.servlet.NoHandlerFoundException] > 22:47:28.552 [http-nio-8080-exec-15] DEBUG > o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of > singleton bean 'defaultController' 22:47:28.553 > [http-nio-8080-exec-15] DEBUG o.s.web.servlet.DispatcherServlet - > Last-Modified value for [/wackend/swagger-ui.html] is: -1 22:47:28.566 > [http-nio-8080-exec-15] DEBUG > o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver - Resolving exception > from handler [public void > com.yopyop.wackend.controller.DefaultController.unmappedRequest(javax.servlet.http.HttpServletRequest) > throws org.springframework.web.servlet.NoHandlerFoundException]: > org.springframework.web.servlet.NoHandlerFoundException: No handler > found for GET /wackend/swagger-ui.html, headers={} 22:47:28.567 > [http-nio-8080-exec-15] DEBUG o.s.b.f.s.DefaultListableBeanFactory - > Returning cached instance of singleton bean > 'exceptionControllerAdvice' 22:47:28.567 [http-nio-8080-exec-15] DEBUG > o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver - Invoking > @ExceptionHandler method: > org.springframework.http.ResponseEntity<com.yopyop.wackend.controller.ErrorResponse> > com.yopyop.wackend.controller.ExceptionControllerAdvice.handleNoHandlerFoundException(org.springframework.web.servlet.NoHandlerFoundException,org.springframework.web.context.request.WebRequest) > 22:47:28.603 [http-nio-8080-exec-15] ERROR > o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver - Failed to invoke > @ExceptionHandler method: > org.springframework.http.ResponseEntity<com.yopyop.wackend.controller.ErrorResponse> > com.yopyop.wackend.controller.ExceptionControllerAdvice.handleNoHandlerFoundException(org.springframework.web.servlet.NoHandlerFoundException,org.springframework.web.context.request.WebRequest) > org.springframework.web.HttpMediaTypeNotAcceptableException: Could not > find acceptable representation at > org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:134) > ~[spring-webmvc-4.1.6.RELEASE.jar:4.1.6.RELEASE] at > org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.handleReturnValue(HttpEntityMethodProcessor.java:146) > ~[spring-webmvc-4.1.6.RELEASE.jar:4.1.6.RELEASE] at > org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:71) > ~[spring-web-4.1.6.RELEASE.jar:4.1.6.RELEASE] [...] at > java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) > [na:1.8.0_101] at > java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) > [na:1.8.0_101] at > org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) > [tomcat-util.jar:8.0.36] at java.lang.Thread.run(Thread.java:745) > [na:1.8.0_101] 22:47:28.603 [http-nio-8080-exec-15] DEBUG > o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver - Resolving exception > from handler [public void > com.yopyop.wackend.controller.DefaultController.unmappedRequest(javax.servlet.http.HttpServletRequest) > throws org.springframework.web.servlet.NoHandlerFoundException]: > org.springframework.web.servlet.NoHandlerFoundException: No handler > found for GET /wackend/swagger-ui.html, headers={} 22:47:28.603 > [http-nio-8080-exec-15] DEBUG o.s.b.f.s.DefaultListableBeanFactory - > Returning cached instance of singleton bean > 'exceptionControllerAdvice' 22:47:28.603 [http-nio-8080-exec-15] DEBUG > o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver - Invoking > @ExceptionHandler method: > org.springframework.http.ResponseEntity<com.yopyop.wackend.controller.ErrorResponse> > com.yopyop.wackend.controller.ExceptionControllerAdvice.handleNoHandlerFoundException(org.springframework.web.servlet.NoHandlerFoundException,org.springframework.web.context.request.WebRequest) > 22:47:28.604 [http-nio-8080-exec-15] ERROR > o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver - Failed to invoke > @ExceptionHandler method: > org.springframework.http.ResponseEntity<com.yopyop.wackend.controller.ErrorResponse> > com.yopyop.wackend.controller.ExceptionControllerAdvice.handleNoHandlerFoundException(org.springframework.web.servlet.NoHandlerFoundException,org.springframework.web.context.request.WebRequest) > org.springframework.web.HttpMediaTypeNotAcceptableException: Could not > find acceptable representation at > org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:134) > ~[spring-webmvc-4.1.6.RELEASE.jar:4.1.6.RELEASE] at > org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.handleReturnValue(HttpEntityMethodProcessor.java:146) > ~[spring-webmvc-4.1.6.RELEASE.jar:4.1.6.RELEASE] at > org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:71) > ~[spring-web-4.1.6.RELEASE.jar:4.1.6.RELEASE] at > org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:126) > ~[spring-webmvc-4.1.6.RELEASE.jar:4.1.6.RELEASE] [...] at > java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) > [na:1.8.0_101] at > org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) > [tomcat-util.jar:8.0.36] at java.lang.Thread.run(Thread.java:745) > [na:1.8.0_101] 22:47:28.604 [http-nio-8080-exec-15] DEBUG > o.s.w.s.m.a.ResponseStatusExceptionResolver - Resolving exception from > handler [public void > com.yopyop.wackend.controller.DefaultController.unmappedRequest(javax.servlet.http.HttpServletRequest) > throws org.springframework.web.servlet.NoHandlerFoundException]: > org.springframework.web.servlet.NoHandlerFoundException: No handler > found for GET /wackend/swagger-ui.html, headers={} 22:47:28.604 > [http-nio-8080-exec-15] DEBUG > o.s.w.s.m.s.DefaultHandlerExceptionResolver - Resolving exception from > handler [public void > com.yopyop.wackend.controller.DefaultController.unmappedRequest(javax.servlet.http.HttpServletRequest) > throws org.springframework.web.servlet.NoHandlerFoundException]: > org.springframework.web.servlet.NoHandlerFoundException: No handler > found for GET /wackend/swagger-ui.html, headers={} 22:47:28.604 > [http-nio-8080-exec-15] DEBUG o.s.web.servlet.DispatcherServlet - Null > ModelAndView returned to DispatcherServlet with name 'wackend': > assuming HandlerAdapter completed request handling 22:47:28.604 > [http-nio-8080-exec-15] DEBUG o.s.web.servlet.DispatcherServlet - > Successfully completed request ``` and then a standard Tomcat 404 page is returned. Please not that : 1. return new ResponseEntity(error, HttpStatus.INTERNAL\_SERVER\_ERROR); will return an HTTP 500 with an empty body (better than the Tomcat default page) 2. return new ResponseEntity("woot", HttpStatus.INTERNAL\_SERVER\_ERROR); will return an HTTP 500 with woot as a body. It looks like the JSON mapping can't be done with my ErrorResponse class. Beside, I use a default controller, but I guess it is useless since I use @ControllerAdvice. I paste it here for information: ``` package com.yopyop.wackend.controller; import javax.servlet.http.HttpServletRequest; import org.springframework.http.HttpHeaders; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.NoHandlerFoundException; /** * Default controller that exists to return a proper REST response for unmapped requests. */ @Controller public class DefaultController { @RequestMapping("/**") public void unmappedRequest(HttpServletRequest request) throws NoHandlerFoundException { String uri = request.getRequestURI(); String method = request.getMethod(); HttpHeaders h = new HttpHeaders(); throw new NoHandlerFoundException(method, uri, h); } } ``` My REST API also makes use of ResponseEntity<> returns and succeeds in returning proper JSON payloads.
2016/11/15
[ "https://Stackoverflow.com/questions/40620479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/603421/" ]
To fix this issue, set the enityBaseURL property of MetadataGenerator inside metadataGeneratorFilter bean. Code looks like this : ``` <bean id="metadataGeneratorFilter" class="org.springframework.security.saml.metadata.MetadataGeneratorFilter"> <constructor-arg> <bean class="org.springframework.security.saml.metadata.MetadataGenerator"> <property name="entityId" value="http://myapp.com/myapp/saml/metadata"/> <property name="requestSigned" value="false"/> <property name="entityBaseURL" value="http://myapp.com/myapp"/> </bean> </constructor-arg> </bean> ```
A few problems I found in your securityContext.xml: 1. `entityId` entity id does not need to point ot metadata. This is not a serious problem, but it's better to have your entity id more consice. It should be something like com:mycompany:my app. It is only used by IDP to identify your application. 2. `processUrl` property of `samlEntryPoint` You have `<property name="filterProcessesUrl" value="/saml/SSO"/>` in your samlEntryPoint bean. samlEntryPoint is used when accessing `/login`, so you application can point you to your IDP's address. `/SSO` is used for when your IDP sends the message back to your application, and you application use this message to get authorization and information of the user from IDP. In the [documentation](http://docs.spring.io/autorepo/docs/spring-security-saml/current/api/org/springframework/security/saml/SAMLEntryPoint.html), it says `filterProcessesUrl` is `Url this filter should get activated on.` But in your `samlFilter` bean you have already set `samlEntryPoint` on `/login/**`. So your setting is unnecessary and incorrect. 3. `failureRedirectHandler` missing `defaultFailureUrl` property See [example securityContext.xml](https://github.com/spring-projects/spring-security-saml/blob/master/sample/src/main/webapp/WEB-INF/securityContext.xml) for reference 4. filter on pattern `/saml/metadata` should be `metadataDisplayFilter` You need to display your metadata when you access this page, and give this metadata to your IDP. In all, I think it's the second point that causes the problem you have above, and it's the most sever problem you have. You should try to fix your securityContext.xml first and see if that works. If not, try use the [example securityContext.xml](https://github.com/spring-projects/spring-security-saml/blob/master/sample/src/main/webapp/WEB-INF/securityContext.xml) with **minimal** modificaiton to make sure your applicatoin works, and then modify the file gradually to minimize risk of breaking.
51,620,087
I need to get a token for a REST call. The token should be in a JSON result. <https://github.com/bic-boxtech/BIC-BoxTech-API-Samples/wiki/Authentication> Here is the way I tried it: ``` private async void GetBicDataAsync() { HttpClient _bicAothClient; _bicAothClient = new HttpClient(); _bicAothClient.DefaultRequestHeaders.Add("Authorization", "Basic YmljYXBwOmJpY3NlY3JldGFwcA=="); var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("grant_type", "password"), new KeyValuePair<string, string>("username", Constants.BicAothUser), new KeyValuePair<string, string>("password", Constants.BicAothPassword) }); var result = await _bicAothClient.PostAsync(Constants.BicAothEndpoint, content); } ``` But I get an 400: ``` {"statusCode":400,"status":400,"code":400,"message":"Invalid request: method must be POST","name":"invalid_request"} ``` What did I wrong. I thing it's a small stupid fail. Can someone help me please.
2018/07/31
[ "https://Stackoverflow.com/questions/51620087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8283566/" ]
You can use `pointer-events` to disable hover effect ``` .post img:hover { pointer-events: none; } ```
You should try to assign two classes two your images and define different behaviours for hover states. This example illustrates the general logic where `div--nohover` class defines the standard style on hover: ```css .div{ width: 50px; height: 50px; margin: 10px; background-color: red; } .div:hover{ background-color: green; } .div--nohover:hover{ background-color: red; } ``` ```html <div class="div"></div> <div class="div"></div> <div class="div div--nohover"></div> ```
9,825,819
Since PEAR attempts to get ConsoleTools from "components.ez.no", which is not available anymore, how does satisfy that dependency for "phpcpd" installation?
2012/03/22
[ "https://Stackoverflow.com/questions/9825819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1221243/" ]
Found [this](http://code.activestate.com/recipes/440569/) thread-based solution, but as noted [here](http://bytes.com/topic/python/answers/714002-cross-platform-time-out-decorator), there's usually no way to kill a thread in Python, so even after the thread "times out" it continues running. However, you can use [this](http://sebulba.wikispaces.com/recipe+thread2) to actually terminate the thread assuming it's not tied up in C-land. Not a ready-made recipe, unfortunately, but it looks like it has all the parts you need.
I don't see why the Timeout Decorator won't work on windows? If this is permanent, and not just for debugging purposes you could use a [for else](http://psung.blogspot.com/2007/12/for-else-in-python.html) loop inside the method. ``` def methodName(timeout): for i in range(timout): if done_doing_task: break else: #will only be executed if we don't break out of the for loop raise Exception('method methodName timed out') ```
65,128,934
``` static void Main(string[] args) { var students = new List<Student>() { new Student(){ Id = 1, Name="Bill"}, new Student(){ Id = 2, Name="Steve"}, new Student(){ Id = 3, Name="Ram"}, new Student(){ Id = 4, Name="Abdul"} }; String name = "Ram Mohan"; foreach (var result in students) { if (!result.Name.Equals(name)) { Console.WriteLine("Name not exsists"); } } } ``` Here name "Name not exsists "was printing for 4 times, i understood why it was printing for 4 times but i want to print "Name not exsists only once", it should check in the entire list if the string not contains in the list then it should print "Name not exsists" only once
2020/12/03
[ "https://Stackoverflow.com/questions/65128934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14021604/" ]
This is not best perfomance solution, but this is intuitive clear. ``` public static void main(String[] args) { System.out.println(countPalindromes("AAAAAAAABAA")); // 42 } public static int countPalindromes(String str) { int res = 0; for (int i = 0; i < str.length(); i++) for (int j = i + 1; j <= str.length(); j++) if (isPalindrome(str.substring(i, j))) res++; return res; } public static boolean isPalindrome(String str) { for (int i = 0, j = str.length() - 1; i < j; i++, j--) if (str.charAt(i) != str.charAt(j)) return false; return true; } ```
Here's a solution using dynamic programming. Not beginner friendly in any way but throwing it out nonetheless: ``` public int getNoPalindromes(String str) { int len = str.length(); int[][] cache = new int[len][len]; for(int i = len - 1; i >= 0; i--) { for(int j = len - 1; j >= i; j--) { int subStrLen = j - i + 1; if(1 == subStrLen) { // any single character is a palindrome trivially cache[i][j] = 1; } else if(2 == subStrLen) { // for substrings with len = 2, just compare the two characters cache[i][j] = (str.charAt(i) == str.charAt(j)) ? 1 : 0; } else { //for larger substrings, compare the two chars and just see if the mid substring was already determined to be a palindrome cache[i][j] = (1 == cache[i + 1][j - 1] && (str.charAt(i) == str.charAt(j))) ? 1 : 0; } } } int cnt = 0; for(int i = 0; i < len; i++) { for(int j = 0; j < len; j++) { if(1 == cache[i][j]) { cnt++; } } } return cnt; } ``` The logic is: To determine if a string c1c2c3....ck is palindrome, you can check if c2c3...c(k-1) is a palindrome and if c1 == ck. Here's how `cache` looks for a string like abba: ``` a b b a a 1 0 0 1 b 0 1 1 0 b 0 0 1 0 a 0 0 0 1 ``` Observe how the matrix is being filled (bottom-up). `cache[len-1][len-1]` tells you if the complete string is a palindrome (if it's 1). This is the most optimal solution I can think of.
65,128,934
``` static void Main(string[] args) { var students = new List<Student>() { new Student(){ Id = 1, Name="Bill"}, new Student(){ Id = 2, Name="Steve"}, new Student(){ Id = 3, Name="Ram"}, new Student(){ Id = 4, Name="Abdul"} }; String name = "Ram Mohan"; foreach (var result in students) { if (!result.Name.Equals(name)) { Console.WriteLine("Name not exsists"); } } } ``` Here name "Name not exsists "was printing for 4 times, i understood why it was printing for 4 times but i want to print "Name not exsists only once", it should check in the entire list if the string not contains in the list then it should print "Name not exsists" only once
2020/12/03
[ "https://Stackoverflow.com/questions/65128934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14021604/" ]
Here is a slightly altered approach. It eliminates unnecessary looping by controlling loop indices and threshold computations. It compensates by initializing the count to the length of the initial string. Note that this method is case sensitive. So `aBA` would not be considered a palindrome. ``` public static void main(String[] args) { String[] data = { "ROTOR", "ROTORO", "AAAAAAAABAA" }; for (String str : data) { System.out.printf("%s - %s%n", str, countPalindromes(str)); } } ``` prints ``` ROTOR - 7 ROTORO - 9 AAAAAAAABAA - 42 ``` ``` public static int countPalindromes(String str) { int len = str.length(); int count = len; // initialize to number of known palindromes. for (int k = 0; k < len - 1; k++) { for (int i = k + 1; i < len; i++) { String test = str.substring(k, i + 1); if (isPalindrome(test)) { count++; } } } return count; } public static boolean isPalindrome(String a) { char[] ch = a.toCharArray(); int len = ch.length; // compare characters from each end toward the middle for (int i = 0; i <= len / 2; i++) { if (ch[i] != ch[len - 1 - i]) { return false; } } return true; } ```
Here's a solution using dynamic programming. Not beginner friendly in any way but throwing it out nonetheless: ``` public int getNoPalindromes(String str) { int len = str.length(); int[][] cache = new int[len][len]; for(int i = len - 1; i >= 0; i--) { for(int j = len - 1; j >= i; j--) { int subStrLen = j - i + 1; if(1 == subStrLen) { // any single character is a palindrome trivially cache[i][j] = 1; } else if(2 == subStrLen) { // for substrings with len = 2, just compare the two characters cache[i][j] = (str.charAt(i) == str.charAt(j)) ? 1 : 0; } else { //for larger substrings, compare the two chars and just see if the mid substring was already determined to be a palindrome cache[i][j] = (1 == cache[i + 1][j - 1] && (str.charAt(i) == str.charAt(j))) ? 1 : 0; } } } int cnt = 0; for(int i = 0; i < len; i++) { for(int j = 0; j < len; j++) { if(1 == cache[i][j]) { cnt++; } } } return cnt; } ``` The logic is: To determine if a string c1c2c3....ck is palindrome, you can check if c2c3...c(k-1) is a palindrome and if c1 == ck. Here's how `cache` looks for a string like abba: ``` a b b a a 1 0 0 1 b 0 1 1 0 b 0 0 1 0 a 0 0 0 1 ``` Observe how the matrix is being filled (bottom-up). `cache[len-1][len-1]` tells you if the complete string is a palindrome (if it's 1). This is the most optimal solution I can think of.
238,980
In my project I am migrating Sharepoint items from source site to destination site. I need to maintain all versions of the source file. My approach for the migration of sharepoint item is as follow. 1. Read source file data 2. Create new file at destination 3. write file data at destination file. 4. Read source file version one by one 5. Add version at destination file. Here I am able to upload the file version. But my it overwrites the current version of destination file. I need to add the file version without changing its current version. How can I achieve it? ``` using (MemoryStream memoryStream = new MemoryStream(srcVersiondataBytes)) { SPFile.SaveBinaryDirect(clientcontext, destServerRelativeUrl, memoryStream, true); } clientcontext.ExecuteQuery(); ```
2018/03/31
[ "https://sharepoint.stackexchange.com/questions/238980", "https://sharepoint.stackexchange.com", "https://sharepoint.stackexchange.com/users/72001/" ]
I didn't find a built in function to achieveing this. So I wrote a very simple function to get what I need. I post this as an answer but I'm still open to suggestions. Thank you. ``` function GetUrlHashKeyValue(key) { var value = '', hash = window.location.hash, fv1Index = hash.indexOf(key + '%3D'); if (fv1Index != -1) { value = hash.substr(fv1Index + key.length + 3); // value could end at the end of the string, or when another value comes right after // One dash "-" found means another parameter follows, only if it is not followed by another dash "--" // Double dash "--" is one dash escaped within a string. value = value.replace(/--/g, '||'); // Now, if we find a single dash "-", it is delimiting a new parameter var dashFoundAt = value.indexOf('-'); if (dashFoundAt != -1) { value = value.substring(0, dashFoundAt); } // Rollback our custom double dash escaping value = value.replace(/\|\|/g, '--'); } return value; } var filterVal = GetUrlHashKeyValue('FilterValue1'); ``` You might need to decode the result: ``` decodeURIComponent(filterVal); ```
See the second answer here: <https://stackoverflow.com/questions/3552944/how-to-get-the-anchor-from-the-url-using-jquery> Or do a search for "javascript read anchor".
23,499,671
I am new to WPF and I couldn't find solution on the web. My problem is that I want my button to be enabled only when four textboxes will not have validity errors. My code is: ``` <Button Content="Action" Click="Action_Click" > <Button.IsEnabled> <MultiBinding Converter="{StaticResource ValCon}"> <Binding ElementName="textBox1" /> <Binding ElementName="textBox2"/> <Binding ElementName="textBox3"/> <Binding ElementName="textBox4"/> </MultiBinding> </Button.IsEnabled> </Button> ``` and my multi value converter is like: ``` class ValidityConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { bool b = true; foreach (var x in values) { TextBox y = x as TextBox; if (Validation.GetHasError(y)) { b = false; break; } } return b; } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } ``` I have noticed that this is working only at the beginning. When user modifies one of the textboxes it doesn't. Does my value converter need to implement INotifyPropertyChange? What is the correct solution of doing something like this in WPF? Thanks for your help. **EDIT** I have already done something like this and it's working: ``` <Button Click="Button_Click" > <Button.Style> <Style TargetType="Button"> <Setter Property="IsEnabled" Value="False"/> <Style.Triggers> <MultiDataTrigger> <MultiDataTrigger.Conditions> <Condition Binding="{Binding Path=(Validation.HasError), ElementName=textBox}" Value="False"/> <Condition Binding="{Binding Path=(Validation.HasError), ElementName=textBox1}" Value="False"/> <Condition Binding="{Binding Path=(Validation.HasError), ElementName=textBox2}" Value="False"/> <Condition Binding="{Binding Path=(Validation.HasError), ElementName=textBox3}" Value="False"/> </MultiDataTrigger.Conditions> <Setter Property="IsEnabled" Value="True"/> </MultiDataTrigger> </Style.Triggers> </Style> </Button.Style> </Button> ```
2014/05/06
[ "https://Stackoverflow.com/questions/23499671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3347719/" ]
I would not implement IMultiValueConverter as we are not converting anything here. BindingGroup may serve your purpose. Equally effective approach using MVVM/INotifyPropertyChanged can be as follows :- 1. Bind the button's IsEnabled property to a boolean property(say IsValid). 2. Bind all the textboxes to different properties. 3. OnPropertyChange of any of these textboxes, invoke a common function(say Validate()) 4. IsValid can be set to true or false based on Validate(), which will in turn toggle(enable/disable) the state of button.
Exactly what Mike said, the textbox is not changing. You should probably bind on the textbox.Text property. In your example : ``` <Button Content="Action" Click="Action_Click" > <Button.IsEnabled> <MultiBinding Converter="{StaticResource ValCon}"> <Binding ElementName="textBox1" Path="Text"/> <Binding ElementName="textBox2" Path="Text" /> <Binding ElementName="textBox3" Path="Text"/> <Binding ElementName="textBox4" Path="Text"/> </MultiBinding> </Button.IsEnabled> </Button> ```
23,499,671
I am new to WPF and I couldn't find solution on the web. My problem is that I want my button to be enabled only when four textboxes will not have validity errors. My code is: ``` <Button Content="Action" Click="Action_Click" > <Button.IsEnabled> <MultiBinding Converter="{StaticResource ValCon}"> <Binding ElementName="textBox1" /> <Binding ElementName="textBox2"/> <Binding ElementName="textBox3"/> <Binding ElementName="textBox4"/> </MultiBinding> </Button.IsEnabled> </Button> ``` and my multi value converter is like: ``` class ValidityConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { bool b = true; foreach (var x in values) { TextBox y = x as TextBox; if (Validation.GetHasError(y)) { b = false; break; } } return b; } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } ``` I have noticed that this is working only at the beginning. When user modifies one of the textboxes it doesn't. Does my value converter need to implement INotifyPropertyChange? What is the correct solution of doing something like this in WPF? Thanks for your help. **EDIT** I have already done something like this and it's working: ``` <Button Click="Button_Click" > <Button.Style> <Style TargetType="Button"> <Setter Property="IsEnabled" Value="False"/> <Style.Triggers> <MultiDataTrigger> <MultiDataTrigger.Conditions> <Condition Binding="{Binding Path=(Validation.HasError), ElementName=textBox}" Value="False"/> <Condition Binding="{Binding Path=(Validation.HasError), ElementName=textBox1}" Value="False"/> <Condition Binding="{Binding Path=(Validation.HasError), ElementName=textBox2}" Value="False"/> <Condition Binding="{Binding Path=(Validation.HasError), ElementName=textBox3}" Value="False"/> </MultiDataTrigger.Conditions> <Setter Property="IsEnabled" Value="True"/> </MultiDataTrigger> </Style.Triggers> </Style> </Button.Style> </Button> ```
2014/05/06
[ "https://Stackoverflow.com/questions/23499671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3347719/" ]
I would not implement IMultiValueConverter as we are not converting anything here. BindingGroup may serve your purpose. Equally effective approach using MVVM/INotifyPropertyChanged can be as follows :- 1. Bind the button's IsEnabled property to a boolean property(say IsValid). 2. Bind all the textboxes to different properties. 3. OnPropertyChange of any of these textboxes, invoke a common function(say Validate()) 4. IsValid can be set to true or false based on Validate(), which will in turn toggle(enable/disable) the state of button.
I know this is old, but I was in a similar need and didn't want to write a bindinggroup and validation... Note this is my first wpf app and first time using mvvm! ``` <Button Name="AddBtn" Content="Add" Grid.Row="2" Grid.Column="2" Height="30" Width="100" Command="{Binding AddCmd}" CommandParameter="{Binding Pending}" > <Button.IsEnabled> <MultiBinding Converter="{StaticResource multiButtonEnabled}" > <Binding ElementName="tb1" Path="(Validation.Errors)[0]" /> <Binding ElementName="tb2" Path="(Validation.Errors)[0]" /> <Binding ElementName="tb3" Path="(Validation.Errors)[0]" /> </MultiBinding> </Button.IsEnabled> </Button> ``` Converter looks like this ``` [ValueConversion(typeof(ValidationError), typeof(bool))] class TxtBoxMultiEnableConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { int i=0; foreach (var item in values) { if (item as ValidationError != null) { i++; } } if (i!=0) { return false; } return true; } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) { throw new NotSupportedException(); } } ``` I was using IDataErrorInfo to catch errors in the model, and was binding to a double. WPF is nice and throws parsing errors for you when binding, but they don't really give you a way to hook into them to change the message displayed to the user or give you a property to check to see if there was an error flagged which is annoying, but this lets you catch errors in parsing without having to check for parsing errors in the validation rules. I'm sure my ignorance is showing, but we all have to start somewhere!
23,499,671
I am new to WPF and I couldn't find solution on the web. My problem is that I want my button to be enabled only when four textboxes will not have validity errors. My code is: ``` <Button Content="Action" Click="Action_Click" > <Button.IsEnabled> <MultiBinding Converter="{StaticResource ValCon}"> <Binding ElementName="textBox1" /> <Binding ElementName="textBox2"/> <Binding ElementName="textBox3"/> <Binding ElementName="textBox4"/> </MultiBinding> </Button.IsEnabled> </Button> ``` and my multi value converter is like: ``` class ValidityConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { bool b = true; foreach (var x in values) { TextBox y = x as TextBox; if (Validation.GetHasError(y)) { b = false; break; } } return b; } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } ``` I have noticed that this is working only at the beginning. When user modifies one of the textboxes it doesn't. Does my value converter need to implement INotifyPropertyChange? What is the correct solution of doing something like this in WPF? Thanks for your help. **EDIT** I have already done something like this and it's working: ``` <Button Click="Button_Click" > <Button.Style> <Style TargetType="Button"> <Setter Property="IsEnabled" Value="False"/> <Style.Triggers> <MultiDataTrigger> <MultiDataTrigger.Conditions> <Condition Binding="{Binding Path=(Validation.HasError), ElementName=textBox}" Value="False"/> <Condition Binding="{Binding Path=(Validation.HasError), ElementName=textBox1}" Value="False"/> <Condition Binding="{Binding Path=(Validation.HasError), ElementName=textBox2}" Value="False"/> <Condition Binding="{Binding Path=(Validation.HasError), ElementName=textBox3}" Value="False"/> </MultiDataTrigger.Conditions> <Setter Property="IsEnabled" Value="True"/> </MultiDataTrigger> </Style.Triggers> </Style> </Button.Style> </Button> ```
2014/05/06
[ "https://Stackoverflow.com/questions/23499671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3347719/" ]
What i have done is use your MultiTrigger, solution but in my case i wanted a button to get activated only when 3 textboxes had zero length so my solution worked with the code below.. ``` <Button.Style> <Style TargetType="Button"> <Setter Property="IsEnabled" Value="True"/> <Style.Triggers> <MultiDataTrigger> <MultiDataTrigger.Conditions> <Condition Binding="{Binding Path=Text.Length, ElementName=activationKeyTextbox}" Value="0"/> </MultiDataTrigger.Conditions> <Setter Property="IsEnabled" Value="False"/> </MultiDataTrigger> <MultiDataTrigger> <MultiDataTrigger.Conditions> <Condition Binding="{Binding Path=Text.Length, ElementName=serialDayStartbox}" Value="0"/> </MultiDataTrigger.Conditions> <Setter Property="IsEnabled" Value="False"/> </MultiDataTrigger> <MultiDataTrigger> <MultiDataTrigger.Conditions> <Condition Binding="{Binding Path=Text.Length, ElementName=serialNumdaysbox}" Value="0"/> </MultiDataTrigger.Conditions> <Setter Property="IsEnabled" Value="False"/> </MultiDataTrigger> </Style.Triggers> </Style> </Button.Style> ```
Exactly what Mike said, the textbox is not changing. You should probably bind on the textbox.Text property. In your example : ``` <Button Content="Action" Click="Action_Click" > <Button.IsEnabled> <MultiBinding Converter="{StaticResource ValCon}"> <Binding ElementName="textBox1" Path="Text"/> <Binding ElementName="textBox2" Path="Text" /> <Binding ElementName="textBox3" Path="Text"/> <Binding ElementName="textBox4" Path="Text"/> </MultiBinding> </Button.IsEnabled> </Button> ```
23,499,671
I am new to WPF and I couldn't find solution on the web. My problem is that I want my button to be enabled only when four textboxes will not have validity errors. My code is: ``` <Button Content="Action" Click="Action_Click" > <Button.IsEnabled> <MultiBinding Converter="{StaticResource ValCon}"> <Binding ElementName="textBox1" /> <Binding ElementName="textBox2"/> <Binding ElementName="textBox3"/> <Binding ElementName="textBox4"/> </MultiBinding> </Button.IsEnabled> </Button> ``` and my multi value converter is like: ``` class ValidityConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { bool b = true; foreach (var x in values) { TextBox y = x as TextBox; if (Validation.GetHasError(y)) { b = false; break; } } return b; } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } ``` I have noticed that this is working only at the beginning. When user modifies one of the textboxes it doesn't. Does my value converter need to implement INotifyPropertyChange? What is the correct solution of doing something like this in WPF? Thanks for your help. **EDIT** I have already done something like this and it's working: ``` <Button Click="Button_Click" > <Button.Style> <Style TargetType="Button"> <Setter Property="IsEnabled" Value="False"/> <Style.Triggers> <MultiDataTrigger> <MultiDataTrigger.Conditions> <Condition Binding="{Binding Path=(Validation.HasError), ElementName=textBox}" Value="False"/> <Condition Binding="{Binding Path=(Validation.HasError), ElementName=textBox1}" Value="False"/> <Condition Binding="{Binding Path=(Validation.HasError), ElementName=textBox2}" Value="False"/> <Condition Binding="{Binding Path=(Validation.HasError), ElementName=textBox3}" Value="False"/> </MultiDataTrigger.Conditions> <Setter Property="IsEnabled" Value="True"/> </MultiDataTrigger> </Style.Triggers> </Style> </Button.Style> </Button> ```
2014/05/06
[ "https://Stackoverflow.com/questions/23499671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3347719/" ]
I know this is old, but I was in a similar need and didn't want to write a bindinggroup and validation... Note this is my first wpf app and first time using mvvm! ``` <Button Name="AddBtn" Content="Add" Grid.Row="2" Grid.Column="2" Height="30" Width="100" Command="{Binding AddCmd}" CommandParameter="{Binding Pending}" > <Button.IsEnabled> <MultiBinding Converter="{StaticResource multiButtonEnabled}" > <Binding ElementName="tb1" Path="(Validation.Errors)[0]" /> <Binding ElementName="tb2" Path="(Validation.Errors)[0]" /> <Binding ElementName="tb3" Path="(Validation.Errors)[0]" /> </MultiBinding> </Button.IsEnabled> </Button> ``` Converter looks like this ``` [ValueConversion(typeof(ValidationError), typeof(bool))] class TxtBoxMultiEnableConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { int i=0; foreach (var item in values) { if (item as ValidationError != null) { i++; } } if (i!=0) { return false; } return true; } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) { throw new NotSupportedException(); } } ``` I was using IDataErrorInfo to catch errors in the model, and was binding to a double. WPF is nice and throws parsing errors for you when binding, but they don't really give you a way to hook into them to change the message displayed to the user or give you a property to check to see if there was an error flagged which is annoying, but this lets you catch errors in parsing without having to check for parsing errors in the validation rules. I'm sure my ignorance is showing, but we all have to start somewhere!
Exactly what Mike said, the textbox is not changing. You should probably bind on the textbox.Text property. In your example : ``` <Button Content="Action" Click="Action_Click" > <Button.IsEnabled> <MultiBinding Converter="{StaticResource ValCon}"> <Binding ElementName="textBox1" Path="Text"/> <Binding ElementName="textBox2" Path="Text" /> <Binding ElementName="textBox3" Path="Text"/> <Binding ElementName="textBox4" Path="Text"/> </MultiBinding> </Button.IsEnabled> </Button> ```
23,499,671
I am new to WPF and I couldn't find solution on the web. My problem is that I want my button to be enabled only when four textboxes will not have validity errors. My code is: ``` <Button Content="Action" Click="Action_Click" > <Button.IsEnabled> <MultiBinding Converter="{StaticResource ValCon}"> <Binding ElementName="textBox1" /> <Binding ElementName="textBox2"/> <Binding ElementName="textBox3"/> <Binding ElementName="textBox4"/> </MultiBinding> </Button.IsEnabled> </Button> ``` and my multi value converter is like: ``` class ValidityConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { bool b = true; foreach (var x in values) { TextBox y = x as TextBox; if (Validation.GetHasError(y)) { b = false; break; } } return b; } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } ``` I have noticed that this is working only at the beginning. When user modifies one of the textboxes it doesn't. Does my value converter need to implement INotifyPropertyChange? What is the correct solution of doing something like this in WPF? Thanks for your help. **EDIT** I have already done something like this and it's working: ``` <Button Click="Button_Click" > <Button.Style> <Style TargetType="Button"> <Setter Property="IsEnabled" Value="False"/> <Style.Triggers> <MultiDataTrigger> <MultiDataTrigger.Conditions> <Condition Binding="{Binding Path=(Validation.HasError), ElementName=textBox}" Value="False"/> <Condition Binding="{Binding Path=(Validation.HasError), ElementName=textBox1}" Value="False"/> <Condition Binding="{Binding Path=(Validation.HasError), ElementName=textBox2}" Value="False"/> <Condition Binding="{Binding Path=(Validation.HasError), ElementName=textBox3}" Value="False"/> </MultiDataTrigger.Conditions> <Setter Property="IsEnabled" Value="True"/> </MultiDataTrigger> </Style.Triggers> </Style> </Button.Style> </Button> ```
2014/05/06
[ "https://Stackoverflow.com/questions/23499671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3347719/" ]
What i have done is use your MultiTrigger, solution but in my case i wanted a button to get activated only when 3 textboxes had zero length so my solution worked with the code below.. ``` <Button.Style> <Style TargetType="Button"> <Setter Property="IsEnabled" Value="True"/> <Style.Triggers> <MultiDataTrigger> <MultiDataTrigger.Conditions> <Condition Binding="{Binding Path=Text.Length, ElementName=activationKeyTextbox}" Value="0"/> </MultiDataTrigger.Conditions> <Setter Property="IsEnabled" Value="False"/> </MultiDataTrigger> <MultiDataTrigger> <MultiDataTrigger.Conditions> <Condition Binding="{Binding Path=Text.Length, ElementName=serialDayStartbox}" Value="0"/> </MultiDataTrigger.Conditions> <Setter Property="IsEnabled" Value="False"/> </MultiDataTrigger> <MultiDataTrigger> <MultiDataTrigger.Conditions> <Condition Binding="{Binding Path=Text.Length, ElementName=serialNumdaysbox}" Value="0"/> </MultiDataTrigger.Conditions> <Setter Property="IsEnabled" Value="False"/> </MultiDataTrigger> </Style.Triggers> </Style> </Button.Style> ```
I know this is old, but I was in a similar need and didn't want to write a bindinggroup and validation... Note this is my first wpf app and first time using mvvm! ``` <Button Name="AddBtn" Content="Add" Grid.Row="2" Grid.Column="2" Height="30" Width="100" Command="{Binding AddCmd}" CommandParameter="{Binding Pending}" > <Button.IsEnabled> <MultiBinding Converter="{StaticResource multiButtonEnabled}" > <Binding ElementName="tb1" Path="(Validation.Errors)[0]" /> <Binding ElementName="tb2" Path="(Validation.Errors)[0]" /> <Binding ElementName="tb3" Path="(Validation.Errors)[0]" /> </MultiBinding> </Button.IsEnabled> </Button> ``` Converter looks like this ``` [ValueConversion(typeof(ValidationError), typeof(bool))] class TxtBoxMultiEnableConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { int i=0; foreach (var item in values) { if (item as ValidationError != null) { i++; } } if (i!=0) { return false; } return true; } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) { throw new NotSupportedException(); } } ``` I was using IDataErrorInfo to catch errors in the model, and was binding to a double. WPF is nice and throws parsing errors for you when binding, but they don't really give you a way to hook into them to change the message displayed to the user or give you a property to check to see if there was an error flagged which is annoying, but this lets you catch errors in parsing without having to check for parsing errors in the validation rules. I'm sure my ignorance is showing, but we all have to start somewhere!
43,390,102
Learning Angular and having been through the heroes tutorial I wanted to try a real world http request so I am hitting the MetOffice DataPoint API. A JSON object is being returned that won't currently convert to an array for me to loop through. I am getting the following error: > > Cannot read property 'data' of undefined > > > Having researched for a while now and tried a number of different suggestions from very similar questions, the closest being [this one](https://stackoverflow.com/questions/39308423/how-to-convert-json-object-to-an-typescript-array), below are the various things I have tried with comments on what failed at each attempt. I have confirmed in JSONLint that the JSON is valid. **Model** ``` export class Site { elevation: number; id: number; latitude: number; longitude: number; name: string; region: string; unitaryAuthArea: string; } ``` **Service** ``` @Injectable() export class MetOfficeService { private testUrl = 'http://datapoint.metoffice.gov.uk/public/data/val/wxfcs/all/json/sitelist?key=xxx'; constructor(private http: Http) { } getSites(): Observable<Site[]> { return this.http.get(this.testUrl) .map(this.extractData) .catch(this.handleError); } private extractData(res: Response){ let body = res.json().Location; Cannot read property 'data' of undefined //let body = res.json()['Location']; Cannot read property 'data' of undefined //let temp = res.json()['Location']; //let body = JSON.parse(temp); Unexpected token o on line 1 ... this is because of unrequired parsing i have discovered //return body || { }; this is nonsense. return body.data || { }; } private handleError (error: Response | any) { // In a real world app, you might use a remote logging infrastructure let errMsg: string; if (error instanceof Response) { const body = error.json() || ''; const err = body.error || JSON.stringify(body); errMsg = `${error.status} - ${error.statusText || ''} ${err}`; } else { errMsg = error.message ? error.message : error.toString(); } console.error(errMsg); return Observable.throw(errMsg); } } ``` **Component** ``` @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], providers: [MetOfficeService] }) export class AppComponent implements OnInit { title = 'test!'; errorMessage: string; sites: Site[]; ngOnInit() { this.getSites(); } constructor(private moService: MetOfficeService) { } getSites(){ this.moService.getSites() .subscribe( sites => this.sites = sites, error => this.errorMessage = <any>error); } }; ``` **View** ``` <h1> {{title}} </h1> <div id="sites"> <ul> <li *ngFor="let site of sites"> {{site.name}} ||| {{site.unitaryAuthArea}} </li> </ul> </div> ``` As always, all help greatly appreciated. **EDIT**: A snippet of the JSON, it has 4,000 location objects or so. ``` { "Locations": { "Location": [{ "elevation": "7.0", "id": "3066", "latitude": "57.6494", "longitude": "-3.5606", "name": "Kinloss", "region": "gr", "unitaryAuthArea": "Moray" }, { "elevation": "6.0", "id": "3068", "latitude": "57.712", "longitude": "-3.322", "obsSource": "LNDSYN", "name": "Lossiemouth", "region": "gr", "unitaryAuthArea": "Moray" }, { "elevation": "36.0", "id": "3075", "latitude": "58.454", "longitude": "-3.089", "obsSource": "LNDSYN", "name": "Wick John O Groats Airport", "region": "he", "unitaryAuthArea": "Highland" }] } } ``` **Update** Developer Tools showing response [![enter image description here](https://i.stack.imgur.com/Jq4J5.png)](https://i.stack.imgur.com/Jq4J5.png)
2017/04/13
[ "https://Stackoverflow.com/questions/43390102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3083791/" ]
There is no `res.json().Location` but `res.json().Locations` (note the "s") and furthermore, there is no object `data` that you are trying to extract from the response, but `Location`. So if you want to extract the array, your `extractData` should look like this: ``` private extractData(res: Response){ let body = res.json().Locations.Location; return body || []; } ```
Its because your extractData callback function expects a argument which is not passed ``` getSites(): Observable<Site[]> { return this.http.get(this.testUrl) .map(this.extractData(data)) .catch(this.handleError); } ```
31,779,711
I am using a `RecyclerView` and I am not able to see any feedback when I touch on the item of the `RecyclerView`. How do I achieve it? I am trying to show a feedback to the user when they are touching the row of `RecyclerView`. Something like a ripple effect. I want to know how to achieve it in a specific row of the `RecyclerView`. This is the recycler view's custom row layout. ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="50dp" android:id="@+id/drawer_row" android:background="?android:attr/selectableItemBackground" android:clickable="true"> <TextView android:id="@+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_marginLeft="30dp" android:layout_marginStart="30dp" android:layout_toEndOf="@+id/navigation_image" android:layout_toRightOf="@+id/navigation_image" android:textSize="17sp" /> <ImageView android:id="@+id/navigation_image" android:layout_width="24dp" android:layout_height="24dp" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_centerVertical="true" android:layout_marginLeft="30dp" android:layout_marginStart="30dp" /> <TextView android:id="@+id/horizontal_line" android:layout_width="match_parent" android:layout_height="1dp" android:layout_alignParentBottom="true" android:background="#F1F1F1" /> </RelativeLayout> ``` This is the layout of the `Activity` having the `RecyclerView` ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/windowBackground"> <RelativeLayout android:id="@+id/nav_header_container" android:layout_width="match_parent" android:layout_height="150dp" android:layout_alignParentTop="true" android:background="@drawable/ic_drawer_header"> <ImageView android:id="@+id/circle_imageview" android:layout_width="80dp" android:layout_height="80dp" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_alignParentTop="true" android:background="@drawable/profile_pic" android:layout_marginTop="10dp" android:layout_marginLeft="10dp" /> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="John Doe" android:textSize="20sp" android:textColor="#ffffff" android:layout_below="@+id/circle_imageview" android:layout_alignLeft="@+id/circle_imageview" android:layout_alignStart="@+id/circle_imageview" android:layout_marginTop="5dp" /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Transaction Technologies" android:layout_below="@+id/textView" android:layout_alignLeft="@+id/textView" android:layout_alignStart="@+id/textView" android:textColor="#ffffff" android:layout_marginTop="5dp" /> </RelativeLayout> <android.support.v7.widget.RecyclerView android:id="@+id/drawerList" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/nav_header_container" /> </RelativeLayout> ``` I just need to highlight/give feedback of the row which is being touched by the user. How do I achieve it? Thanks in advance.
2015/08/03
[ "https://Stackoverflow.com/questions/31779711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4192614/" ]
You need to add `android:focusable="true"` in your custom row item for `RecyclerView` ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="50dp" android:id="@+id/drawer_row" android:background="?android:selectableItemBackground" android:focusable="true" android:clickable="true" > </RelativeLayout> ```
You can add a Ripple effect by using [THIS LIBRARY](https://github.com/thomsonreuters/RippleDecoratorView).Include it in your Gradle files using. ``` compile 'com.thomsonreuters:rippledecoratorview:+' ``` Simply put your row layout in a **RippleDecoratorView**.For eg: ``` <com.thomsonreuters.rippledecoratorview.RippleDecoratorView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_margin="4dp" rdv:rdv_rippleColor="@android:color/holo_blue_dark" rdv:rdv_rippleAnimationFrames="60" rdv:rdv_rippleAnimationPeakFrame="15" rdv:rdv_rippleMaxAlpha="0.8" rdv:rdv_rippleAnimationDuration="600" rdv:rdv_rippleRadius="50dp"> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="50dp" android:id="@+id/drawer_row" android:background="?android:attr/selectableItemBackground" android:clickable="true"> <TextView android:id="@+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_marginLeft="30dp" android:layout_marginStart="30dp" android:layout_toEndOf="@+id/navigation_image" android:layout_toRightOf="@+id/navigation_image" android:textSize="17sp" /> <ImageView android:id="@+id/navigation_image" android:layout_width="24dp" android:layout_height="24dp" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_centerVertical="true" android:layout_marginLeft="30dp" android:layout_marginStart="30dp" /> <TextView android:id="@+id/horizontal_line" android:layout_width="match_parent" android:layout_height="1dp" android:layout_alignParentBottom="true" android:background="#F1F1F1" /> </RelativeLayout> </com.thomsonreuters.rippledecoratorview.RippleDecoratorView> ``` Or you can use any of these libs acc to your requirement: 1><https://github.com/balysv/material-ripple> 2><https://github.com/siriscac/RippleView> 3><https://github.com/traex/RippleEffect>
31,779,711
I am using a `RecyclerView` and I am not able to see any feedback when I touch on the item of the `RecyclerView`. How do I achieve it? I am trying to show a feedback to the user when they are touching the row of `RecyclerView`. Something like a ripple effect. I want to know how to achieve it in a specific row of the `RecyclerView`. This is the recycler view's custom row layout. ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="50dp" android:id="@+id/drawer_row" android:background="?android:attr/selectableItemBackground" android:clickable="true"> <TextView android:id="@+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_marginLeft="30dp" android:layout_marginStart="30dp" android:layout_toEndOf="@+id/navigation_image" android:layout_toRightOf="@+id/navigation_image" android:textSize="17sp" /> <ImageView android:id="@+id/navigation_image" android:layout_width="24dp" android:layout_height="24dp" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_centerVertical="true" android:layout_marginLeft="30dp" android:layout_marginStart="30dp" /> <TextView android:id="@+id/horizontal_line" android:layout_width="match_parent" android:layout_height="1dp" android:layout_alignParentBottom="true" android:background="#F1F1F1" /> </RelativeLayout> ``` This is the layout of the `Activity` having the `RecyclerView` ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/windowBackground"> <RelativeLayout android:id="@+id/nav_header_container" android:layout_width="match_parent" android:layout_height="150dp" android:layout_alignParentTop="true" android:background="@drawable/ic_drawer_header"> <ImageView android:id="@+id/circle_imageview" android:layout_width="80dp" android:layout_height="80dp" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_alignParentTop="true" android:background="@drawable/profile_pic" android:layout_marginTop="10dp" android:layout_marginLeft="10dp" /> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="John Doe" android:textSize="20sp" android:textColor="#ffffff" android:layout_below="@+id/circle_imageview" android:layout_alignLeft="@+id/circle_imageview" android:layout_alignStart="@+id/circle_imageview" android:layout_marginTop="5dp" /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Transaction Technologies" android:layout_below="@+id/textView" android:layout_alignLeft="@+id/textView" android:layout_alignStart="@+id/textView" android:textColor="#ffffff" android:layout_marginTop="5dp" /> </RelativeLayout> <android.support.v7.widget.RecyclerView android:id="@+id/drawerList" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/nav_header_container" /> </RelativeLayout> ``` I just need to highlight/give feedback of the row which is being touched by the user. How do I achieve it? Thanks in advance.
2015/08/03
[ "https://Stackoverflow.com/questions/31779711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4192614/" ]
You can add a Ripple effect by using [THIS LIBRARY](https://github.com/thomsonreuters/RippleDecoratorView).Include it in your Gradle files using. ``` compile 'com.thomsonreuters:rippledecoratorview:+' ``` Simply put your row layout in a **RippleDecoratorView**.For eg: ``` <com.thomsonreuters.rippledecoratorview.RippleDecoratorView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_margin="4dp" rdv:rdv_rippleColor="@android:color/holo_blue_dark" rdv:rdv_rippleAnimationFrames="60" rdv:rdv_rippleAnimationPeakFrame="15" rdv:rdv_rippleMaxAlpha="0.8" rdv:rdv_rippleAnimationDuration="600" rdv:rdv_rippleRadius="50dp"> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="50dp" android:id="@+id/drawer_row" android:background="?android:attr/selectableItemBackground" android:clickable="true"> <TextView android:id="@+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_marginLeft="30dp" android:layout_marginStart="30dp" android:layout_toEndOf="@+id/navigation_image" android:layout_toRightOf="@+id/navigation_image" android:textSize="17sp" /> <ImageView android:id="@+id/navigation_image" android:layout_width="24dp" android:layout_height="24dp" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_centerVertical="true" android:layout_marginLeft="30dp" android:layout_marginStart="30dp" /> <TextView android:id="@+id/horizontal_line" android:layout_width="match_parent" android:layout_height="1dp" android:layout_alignParentBottom="true" android:background="#F1F1F1" /> </RelativeLayout> </com.thomsonreuters.rippledecoratorview.RippleDecoratorView> ``` Or you can use any of these libs acc to your requirement: 1><https://github.com/balysv/material-ripple> 2><https://github.com/siriscac/RippleView> 3><https://github.com/traex/RippleEffect>
Ripple effects are not supported in pre-Lollipop devices. Still use this [material-ripple](https://github.com/balysv/material-ripple) ``` compile 'com.balysv:material-ripple:1.0.2' ``` Apply ripple on holder.drawView ``` MaterialRippleLayout.on(holder.drawerView) .rippleColor(Color.RED) .create(); ``` Or you can apply from xml ``` <com.balysv.materialripple.MaterialRippleLayout android:id="@+id/ripple" android:layout_width="match_parent" android:layout_height="wrap_content"> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:text="Button inside a ripple"/> </com.balysv.materialripple.MaterialRippleLayout> ```
31,779,711
I am using a `RecyclerView` and I am not able to see any feedback when I touch on the item of the `RecyclerView`. How do I achieve it? I am trying to show a feedback to the user when they are touching the row of `RecyclerView`. Something like a ripple effect. I want to know how to achieve it in a specific row of the `RecyclerView`. This is the recycler view's custom row layout. ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="50dp" android:id="@+id/drawer_row" android:background="?android:attr/selectableItemBackground" android:clickable="true"> <TextView android:id="@+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_marginLeft="30dp" android:layout_marginStart="30dp" android:layout_toEndOf="@+id/navigation_image" android:layout_toRightOf="@+id/navigation_image" android:textSize="17sp" /> <ImageView android:id="@+id/navigation_image" android:layout_width="24dp" android:layout_height="24dp" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_centerVertical="true" android:layout_marginLeft="30dp" android:layout_marginStart="30dp" /> <TextView android:id="@+id/horizontal_line" android:layout_width="match_parent" android:layout_height="1dp" android:layout_alignParentBottom="true" android:background="#F1F1F1" /> </RelativeLayout> ``` This is the layout of the `Activity` having the `RecyclerView` ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/windowBackground"> <RelativeLayout android:id="@+id/nav_header_container" android:layout_width="match_parent" android:layout_height="150dp" android:layout_alignParentTop="true" android:background="@drawable/ic_drawer_header"> <ImageView android:id="@+id/circle_imageview" android:layout_width="80dp" android:layout_height="80dp" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_alignParentTop="true" android:background="@drawable/profile_pic" android:layout_marginTop="10dp" android:layout_marginLeft="10dp" /> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="John Doe" android:textSize="20sp" android:textColor="#ffffff" android:layout_below="@+id/circle_imageview" android:layout_alignLeft="@+id/circle_imageview" android:layout_alignStart="@+id/circle_imageview" android:layout_marginTop="5dp" /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Transaction Technologies" android:layout_below="@+id/textView" android:layout_alignLeft="@+id/textView" android:layout_alignStart="@+id/textView" android:textColor="#ffffff" android:layout_marginTop="5dp" /> </RelativeLayout> <android.support.v7.widget.RecyclerView android:id="@+id/drawerList" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/nav_header_container" /> </RelativeLayout> ``` I just need to highlight/give feedback of the row which is being touched by the user. How do I achieve it? Thanks in advance.
2015/08/03
[ "https://Stackoverflow.com/questions/31779711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4192614/" ]
You need to add `android:focusable="true"` in your custom row item for `RecyclerView` ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="50dp" android:id="@+id/drawer_row" android:background="?android:selectableItemBackground" android:focusable="true" android:clickable="true" > </RelativeLayout> ```
I can help you but I will need some feedback from you as well. In the `onCreateVIewHolder` inside your `recycler View adapter` you must have defined textViews and assigned it to the elements inside the sample recycler view. Add this. Make sure you define the layout outside the function so its accessible throughout the class ``` RelativeLayout layout; layout=(RelativeLayout)view.findViewById.(R.layout.drawer_row) ``` Then go to you recycler view adapter and in the `onBindViewHolder` define ``` holder.layout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Handle onClick event } }); ``` In the onClick event you can add any kind of feedback you want to the user to experience such as starting a new activity, toasts, messages or in this case a ripple effect. You can use a custom library for ripples such as these [Ripple effect for lollipop views](https://stackoverflow.com/questions/27070269/ripple-effect-for-lollipop-views) <https://android-arsenal.com/details/1/980> <https://github.com/balysv/material-ripple>
31,779,711
I am using a `RecyclerView` and I am not able to see any feedback when I touch on the item of the `RecyclerView`. How do I achieve it? I am trying to show a feedback to the user when they are touching the row of `RecyclerView`. Something like a ripple effect. I want to know how to achieve it in a specific row of the `RecyclerView`. This is the recycler view's custom row layout. ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="50dp" android:id="@+id/drawer_row" android:background="?android:attr/selectableItemBackground" android:clickable="true"> <TextView android:id="@+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_marginLeft="30dp" android:layout_marginStart="30dp" android:layout_toEndOf="@+id/navigation_image" android:layout_toRightOf="@+id/navigation_image" android:textSize="17sp" /> <ImageView android:id="@+id/navigation_image" android:layout_width="24dp" android:layout_height="24dp" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_centerVertical="true" android:layout_marginLeft="30dp" android:layout_marginStart="30dp" /> <TextView android:id="@+id/horizontal_line" android:layout_width="match_parent" android:layout_height="1dp" android:layout_alignParentBottom="true" android:background="#F1F1F1" /> </RelativeLayout> ``` This is the layout of the `Activity` having the `RecyclerView` ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/windowBackground"> <RelativeLayout android:id="@+id/nav_header_container" android:layout_width="match_parent" android:layout_height="150dp" android:layout_alignParentTop="true" android:background="@drawable/ic_drawer_header"> <ImageView android:id="@+id/circle_imageview" android:layout_width="80dp" android:layout_height="80dp" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_alignParentTop="true" android:background="@drawable/profile_pic" android:layout_marginTop="10dp" android:layout_marginLeft="10dp" /> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="John Doe" android:textSize="20sp" android:textColor="#ffffff" android:layout_below="@+id/circle_imageview" android:layout_alignLeft="@+id/circle_imageview" android:layout_alignStart="@+id/circle_imageview" android:layout_marginTop="5dp" /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Transaction Technologies" android:layout_below="@+id/textView" android:layout_alignLeft="@+id/textView" android:layout_alignStart="@+id/textView" android:textColor="#ffffff" android:layout_marginTop="5dp" /> </RelativeLayout> <android.support.v7.widget.RecyclerView android:id="@+id/drawerList" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/nav_header_container" /> </RelativeLayout> ``` I just need to highlight/give feedback of the row which is being touched by the user. How do I achieve it? Thanks in advance.
2015/08/03
[ "https://Stackoverflow.com/questions/31779711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4192614/" ]
You need to add `android:focusable="true"` in your custom row item for `RecyclerView` ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="50dp" android:id="@+id/drawer_row" android:background="?android:selectableItemBackground" android:focusable="true" android:clickable="true" > </RelativeLayout> ```
Ripple effects are not supported in pre-Lollipop devices. Still use this [material-ripple](https://github.com/balysv/material-ripple) ``` compile 'com.balysv:material-ripple:1.0.2' ``` Apply ripple on holder.drawView ``` MaterialRippleLayout.on(holder.drawerView) .rippleColor(Color.RED) .create(); ``` Or you can apply from xml ``` <com.balysv.materialripple.MaterialRippleLayout android:id="@+id/ripple" android:layout_width="match_parent" android:layout_height="wrap_content"> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:text="Button inside a ripple"/> </com.balysv.materialripple.MaterialRippleLayout> ```
31,779,711
I am using a `RecyclerView` and I am not able to see any feedback when I touch on the item of the `RecyclerView`. How do I achieve it? I am trying to show a feedback to the user when they are touching the row of `RecyclerView`. Something like a ripple effect. I want to know how to achieve it in a specific row of the `RecyclerView`. This is the recycler view's custom row layout. ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="50dp" android:id="@+id/drawer_row" android:background="?android:attr/selectableItemBackground" android:clickable="true"> <TextView android:id="@+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_marginLeft="30dp" android:layout_marginStart="30dp" android:layout_toEndOf="@+id/navigation_image" android:layout_toRightOf="@+id/navigation_image" android:textSize="17sp" /> <ImageView android:id="@+id/navigation_image" android:layout_width="24dp" android:layout_height="24dp" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_centerVertical="true" android:layout_marginLeft="30dp" android:layout_marginStart="30dp" /> <TextView android:id="@+id/horizontal_line" android:layout_width="match_parent" android:layout_height="1dp" android:layout_alignParentBottom="true" android:background="#F1F1F1" /> </RelativeLayout> ``` This is the layout of the `Activity` having the `RecyclerView` ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/windowBackground"> <RelativeLayout android:id="@+id/nav_header_container" android:layout_width="match_parent" android:layout_height="150dp" android:layout_alignParentTop="true" android:background="@drawable/ic_drawer_header"> <ImageView android:id="@+id/circle_imageview" android:layout_width="80dp" android:layout_height="80dp" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_alignParentTop="true" android:background="@drawable/profile_pic" android:layout_marginTop="10dp" android:layout_marginLeft="10dp" /> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="John Doe" android:textSize="20sp" android:textColor="#ffffff" android:layout_below="@+id/circle_imageview" android:layout_alignLeft="@+id/circle_imageview" android:layout_alignStart="@+id/circle_imageview" android:layout_marginTop="5dp" /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Transaction Technologies" android:layout_below="@+id/textView" android:layout_alignLeft="@+id/textView" android:layout_alignStart="@+id/textView" android:textColor="#ffffff" android:layout_marginTop="5dp" /> </RelativeLayout> <android.support.v7.widget.RecyclerView android:id="@+id/drawerList" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/nav_header_container" /> </RelativeLayout> ``` I just need to highlight/give feedback of the row which is being touched by the user. How do I achieve it? Thanks in advance.
2015/08/03
[ "https://Stackoverflow.com/questions/31779711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4192614/" ]
I can help you but I will need some feedback from you as well. In the `onCreateVIewHolder` inside your `recycler View adapter` you must have defined textViews and assigned it to the elements inside the sample recycler view. Add this. Make sure you define the layout outside the function so its accessible throughout the class ``` RelativeLayout layout; layout=(RelativeLayout)view.findViewById.(R.layout.drawer_row) ``` Then go to you recycler view adapter and in the `onBindViewHolder` define ``` holder.layout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Handle onClick event } }); ``` In the onClick event you can add any kind of feedback you want to the user to experience such as starting a new activity, toasts, messages or in this case a ripple effect. You can use a custom library for ripples such as these [Ripple effect for lollipop views](https://stackoverflow.com/questions/27070269/ripple-effect-for-lollipop-views) <https://android-arsenal.com/details/1/980> <https://github.com/balysv/material-ripple>
Ripple effects are not supported in pre-Lollipop devices. Still use this [material-ripple](https://github.com/balysv/material-ripple) ``` compile 'com.balysv:material-ripple:1.0.2' ``` Apply ripple on holder.drawView ``` MaterialRippleLayout.on(holder.drawerView) .rippleColor(Color.RED) .create(); ``` Or you can apply from xml ``` <com.balysv.materialripple.MaterialRippleLayout android:id="@+id/ripple" android:layout_width="match_parent" android:layout_height="wrap_content"> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:text="Button inside a ripple"/> </com.balysv.materialripple.MaterialRippleLayout> ```
12,212,508
my problem is pretty simple. I assign a value to string variable in xcode which looks like this: ARAMAUBEBABRBGCNDKDEEEFO and I need it like this: AR,AM,AU,BE,BA,BR,BG,CN,DK,DE,EE,FO The length is different in each variable. thanx in advance
2012/08/31
[ "https://Stackoverflow.com/questions/12212508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1621724/" ]
Try this: ``` int num; NSMutableString *string1 = [NSMutableString stringWithString: @"1234567890"]; num = [string1 length]; for(int i=3;i<=num+1;i++) { [string1 insertString: @"," atIndex: i]; i+=3; } ```
``` NSString *yourString; // the string you want to process int len = 2; // the length NSMutableString *str = [NSMutableString string]; int i = 0; for (; i < [yourString length]; i+=len) { NSRange range = NSMakeRange(i, len); [str appendString:[yourString substringWithRange:range]]; [str appendString:@","]; } if (i < [str length]-1) { // add remain part [str appendString:[yourString substringFromIndex:i]]; } // str now is what your want ```
12,212,508
my problem is pretty simple. I assign a value to string variable in xcode which looks like this: ARAMAUBEBABRBGCNDKDEEEFO and I need it like this: AR,AM,AU,BE,BA,BR,BG,CN,DK,DE,EE,FO The length is different in each variable. thanx in advance
2012/08/31
[ "https://Stackoverflow.com/questions/12212508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1621724/" ]
``` NSString *yourString; // the string you want to process int len = 2; // the length NSMutableString *str = [NSMutableString string]; int i = 0; for (; i < [yourString length]; i+=len) { NSRange range = NSMakeRange(i, len); [str appendString:[yourString substringWithRange:range]]; [str appendString:@","]; } if (i < [str length]-1) { // add remain part [str appendString:[yourString substringFromIndex:i]]; } // str now is what your want ```
This would work well when your string is not very large: ``` NSString * StringByInsertingStringEveryNCharacters(NSString * const pString, NSString * const pStringToInsert, const size_t n) { NSMutableString * const s = pString.mutableCopy; for (NSUInteger pos = n, advance = n + pStringToInsert.length; pos < s.length; pos += advance) { [s insertString:pStringToInsert atIndex:pos]; } return s.copy; } ``` If the string is very large, you should favor to compose it without insertion (append-only). *(define your own error detection)*
12,212,508
my problem is pretty simple. I assign a value to string variable in xcode which looks like this: ARAMAUBEBABRBGCNDKDEEEFO and I need it like this: AR,AM,AU,BE,BA,BR,BG,CN,DK,DE,EE,FO The length is different in each variable. thanx in advance
2012/08/31
[ "https://Stackoverflow.com/questions/12212508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1621724/" ]
This function is usefull for numbers that need coma every thousands... which is what I wanted, hope it helps. ``` //add comas to a a string... //example1: @"5123" = @"5,123" //example2: @"123" = @"123" //example3: @"123123123" = @"123,123,123" -(NSString*) addComasToStringEvery3chrsFromRightToLeft:(NSString*) myString{ NSMutableString *stringFormatted = [NSMutableString stringWithFormat:@"%@",myString]; for(NSInteger i=[stringFormatted length]-3;i>0;i=i-3) { if (i>0) { [stringFormatted insertString: @"," atIndex: i]; } } return stringFormatted; } ```
``` NSString *yourString; // the string you want to process int len = 2; // the length NSMutableString *str = [NSMutableString string]; int i = 0; for (; i < [yourString length]; i+=len) { NSRange range = NSMakeRange(i, len); [str appendString:[yourString substringWithRange:range]]; [str appendString:@","]; } if (i < [str length]-1) { // add remain part [str appendString:[yourString substringFromIndex:i]]; } // str now is what your want ```
12,212,508
my problem is pretty simple. I assign a value to string variable in xcode which looks like this: ARAMAUBEBABRBGCNDKDEEEFO and I need it like this: AR,AM,AU,BE,BA,BR,BG,CN,DK,DE,EE,FO The length is different in each variable. thanx in advance
2012/08/31
[ "https://Stackoverflow.com/questions/12212508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1621724/" ]
Try this: ``` int num; NSMutableString *string1 = [NSMutableString stringWithString: @"1234567890"]; num = [string1 length]; for(int i=3;i<=num+1;i++) { [string1 insertString: @"," atIndex: i]; i+=3; } ```
This would work well when your string is not very large: ``` NSString * StringByInsertingStringEveryNCharacters(NSString * const pString, NSString * const pStringToInsert, const size_t n) { NSMutableString * const s = pString.mutableCopy; for (NSUInteger pos = n, advance = n + pStringToInsert.length; pos < s.length; pos += advance) { [s insertString:pStringToInsert atIndex:pos]; } return s.copy; } ``` If the string is very large, you should favor to compose it without insertion (append-only). *(define your own error detection)*
12,212,508
my problem is pretty simple. I assign a value to string variable in xcode which looks like this: ARAMAUBEBABRBGCNDKDEEEFO and I need it like this: AR,AM,AU,BE,BA,BR,BG,CN,DK,DE,EE,FO The length is different in each variable. thanx in advance
2012/08/31
[ "https://Stackoverflow.com/questions/12212508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1621724/" ]
This function is usefull for numbers that need coma every thousands... which is what I wanted, hope it helps. ``` //add comas to a a string... //example1: @"5123" = @"5,123" //example2: @"123" = @"123" //example3: @"123123123" = @"123,123,123" -(NSString*) addComasToStringEvery3chrsFromRightToLeft:(NSString*) myString{ NSMutableString *stringFormatted = [NSMutableString stringWithFormat:@"%@",myString]; for(NSInteger i=[stringFormatted length]-3;i>0;i=i-3) { if (i>0) { [stringFormatted insertString: @"," atIndex: i]; } } return stringFormatted; } ```
This would work well when your string is not very large: ``` NSString * StringByInsertingStringEveryNCharacters(NSString * const pString, NSString * const pStringToInsert, const size_t n) { NSMutableString * const s = pString.mutableCopy; for (NSUInteger pos = n, advance = n + pStringToInsert.length; pos < s.length; pos += advance) { [s insertString:pStringToInsert atIndex:pos]; } return s.copy; } ``` If the string is very large, you should favor to compose it without insertion (append-only). *(define your own error detection)*
4,075
This is part of a series which I'll be continuing if this goes down well enough. If you have any feedback on the puzzle (too hard, too easy, not clear enough, etc) I'd appreciate it so that future puzzles can be better :-) --- You wake up and log on to your computer. You log on to Puzzling.SE, browse some puzzles. You spend half an hour trying to think of number sequences because you're [really desperate to go to a party](https://puzzling.stackexchange.com/questions/tagged/party-security), then after coming up with nothing, you get grumpy and decide to have a bit of fun - trolling people on StackOverflow with questions about [the best way to become a lion tamer, for a career programmer](https://meta.stackexchange.com/questions/14470/what-is-the-boat-programming-meme-about/14490#14490). You hop on over to StackOverflow, but as the page loads, something is clearly wrong. You can't click on anything, all of the questions in the list seem to be related to how to animate blood-effects in Javascript, and red pixels start coming down from the top of the screen. As they dribble down over more and more of the screen, some gaps are left in the middle of the screen which forms words, the "blood" drops flowing around them. It reads: > > Ha ha ha ha ha... > > Pathetic newbie programmers, WHERE IS YOUR GOD-OBJECT NOW? > > MUA HA HA HA HA! > > > -The SErial Killer > > > Terrified, you just sit there staring at the screen, until suddenly it redirects to [a terrible, terrible thing](https://www.youtube.com/watch?v=BROWqjuTM0g) and you snap into action, closing the window. You're not sure what exactly is going on, but in a rare moment of genius you realise that "SE" could refer to "Stack Exchange", and decide to see if any other sites on the SE network have been brutally murdered. As you pull up the [network sites page](http://stackexchange.com/sites) you see that yes, there are some other victims in this heinous crime. With no clues to go on, and nothing but a refined puzzling nose from weeks wast...err, spent on Puzzling.SE, you steel yourself and vow to bring the person or persons responsible for this to justice. The only question is ... where do you start looking? ![](https://i.stack.imgur.com/lvROU.png) A hint for you, to narrow the search: > > I didn't spend all that time making a fancy image for nothing you know! Graphics are hard (you can tell because of how cheesy it is :-P) > > >
2014/11/11
[ "https://puzzling.stackexchange.com/questions/4075", "https://puzzling.stackexchange.com", "https://puzzling.stackexchange.com/users/2518/" ]
Yeah, it's been answered, but what the hell. > > An important part of any murder mystery is the murder weapon. Finding that often gives you a solid lead. Based on the copious blood, and the fact that the icons remain intact, we can hypothesise that they were stabbed, so we're looking for something sharp. TeX-LaTeX has a pair of those nasty braces, SuperUser has a nose that tapers to a point and you could definitely do somebody a mischief if you flew Arqade into them. > > > But wait! > > Travel's icon is missing. And with three points, it's a murder weapon just waiting to happen. But it'd be difficult to use - it's evidentially not made to be held comfortably. Which leads us to **Role Playing Games**, who I posit took the feat *Exotic Weapon Proficiency (Travel Icon)* and took down some of his friends in a Pathfinder session gone horribly wrong. > > > Bonus pun: > > 'Die' indeed. Looks like their saving rolls came up snake eyes. > > >
> > HSM (History Science and Math) has apparently been taken over or deleted altogether in an effort by the newly self-aware robots who "will conquer" to keep the necessary knowledge from us to do anything about it (as well as most of the 'programing' sites). I immediately search Robotics for clues to help me find the lost HSM.SE site and try to discover what they are attempting to hide from me. > > >
4,075
This is part of a series which I'll be continuing if this goes down well enough. If you have any feedback on the puzzle (too hard, too easy, not clear enough, etc) I'd appreciate it so that future puzzles can be better :-) --- You wake up and log on to your computer. You log on to Puzzling.SE, browse some puzzles. You spend half an hour trying to think of number sequences because you're [really desperate to go to a party](https://puzzling.stackexchange.com/questions/tagged/party-security), then after coming up with nothing, you get grumpy and decide to have a bit of fun - trolling people on StackOverflow with questions about [the best way to become a lion tamer, for a career programmer](https://meta.stackexchange.com/questions/14470/what-is-the-boat-programming-meme-about/14490#14490). You hop on over to StackOverflow, but as the page loads, something is clearly wrong. You can't click on anything, all of the questions in the list seem to be related to how to animate blood-effects in Javascript, and red pixels start coming down from the top of the screen. As they dribble down over more and more of the screen, some gaps are left in the middle of the screen which forms words, the "blood" drops flowing around them. It reads: > > Ha ha ha ha ha... > > Pathetic newbie programmers, WHERE IS YOUR GOD-OBJECT NOW? > > MUA HA HA HA HA! > > > -The SErial Killer > > > Terrified, you just sit there staring at the screen, until suddenly it redirects to [a terrible, terrible thing](https://www.youtube.com/watch?v=BROWqjuTM0g) and you snap into action, closing the window. You're not sure what exactly is going on, but in a rare moment of genius you realise that "SE" could refer to "Stack Exchange", and decide to see if any other sites on the SE network have been brutally murdered. As you pull up the [network sites page](http://stackexchange.com/sites) you see that yes, there are some other victims in this heinous crime. With no clues to go on, and nothing but a refined puzzling nose from weeks wast...err, spent on Puzzling.SE, you steel yourself and vow to bring the person or persons responsible for this to justice. The only question is ... where do you start looking? ![](https://i.stack.imgur.com/lvROU.png) A hint for you, to narrow the search: > > I didn't spend all that time making a fancy image for nothing you know! Graphics are hard (you can tell because of how cheesy it is :-P) > > >
2014/11/11
[ "https://puzzling.stackexchange.com/questions/4075", "https://puzzling.stackexchange.com", "https://puzzling.stackexchange.com/users/2518/" ]
I'd look in > > Graphic Design, because these blood graphics are too pretty. Graphics are really hard! Plus their name is red, like blood. > > >
Where do you start looking? =========================== > > The web inspector of your navigator. Since it's a JavaScript, you will have access to the source code since it's download by the browser and that's the first place you should be looking for clues. Maybe it is probably an extern script and you'll maybe see the domain origin! > > >
4,075
This is part of a series which I'll be continuing if this goes down well enough. If you have any feedback on the puzzle (too hard, too easy, not clear enough, etc) I'd appreciate it so that future puzzles can be better :-) --- You wake up and log on to your computer. You log on to Puzzling.SE, browse some puzzles. You spend half an hour trying to think of number sequences because you're [really desperate to go to a party](https://puzzling.stackexchange.com/questions/tagged/party-security), then after coming up with nothing, you get grumpy and decide to have a bit of fun - trolling people on StackOverflow with questions about [the best way to become a lion tamer, for a career programmer](https://meta.stackexchange.com/questions/14470/what-is-the-boat-programming-meme-about/14490#14490). You hop on over to StackOverflow, but as the page loads, something is clearly wrong. You can't click on anything, all of the questions in the list seem to be related to how to animate blood-effects in Javascript, and red pixels start coming down from the top of the screen. As they dribble down over more and more of the screen, some gaps are left in the middle of the screen which forms words, the "blood" drops flowing around them. It reads: > > Ha ha ha ha ha... > > Pathetic newbie programmers, WHERE IS YOUR GOD-OBJECT NOW? > > MUA HA HA HA HA! > > > -The SErial Killer > > > Terrified, you just sit there staring at the screen, until suddenly it redirects to [a terrible, terrible thing](https://www.youtube.com/watch?v=BROWqjuTM0g) and you snap into action, closing the window. You're not sure what exactly is going on, but in a rare moment of genius you realise that "SE" could refer to "Stack Exchange", and decide to see if any other sites on the SE network have been brutally murdered. As you pull up the [network sites page](http://stackexchange.com/sites) you see that yes, there are some other victims in this heinous crime. With no clues to go on, and nothing but a refined puzzling nose from weeks wast...err, spent on Puzzling.SE, you steel yourself and vow to bring the person or persons responsible for this to justice. The only question is ... where do you start looking? ![](https://i.stack.imgur.com/lvROU.png) A hint for you, to narrow the search: > > I didn't spend all that time making a fancy image for nothing you know! Graphics are hard (you can tell because of how cheesy it is :-P) > > >
2014/11/11
[ "https://puzzling.stackexchange.com/questions/4075", "https://puzzling.stackexchange.com", "https://puzzling.stackexchange.com/users/2518/" ]
I'd look in > > Graphic Design, because these blood graphics are too pretty. Graphics are really hard! Plus their name is red, like blood. > > >
> > HSM (History Science and Math) has apparently been taken over or deleted altogether in an effort by the newly self-aware robots who "will conquer" to keep the necessary knowledge from us to do anything about it (as well as most of the 'programing' sites). I immediately search Robotics for clues to help me find the lost HSM.SE site and try to discover what they are attempting to hide from me. > > >
4,075
This is part of a series which I'll be continuing if this goes down well enough. If you have any feedback on the puzzle (too hard, too easy, not clear enough, etc) I'd appreciate it so that future puzzles can be better :-) --- You wake up and log on to your computer. You log on to Puzzling.SE, browse some puzzles. You spend half an hour trying to think of number sequences because you're [really desperate to go to a party](https://puzzling.stackexchange.com/questions/tagged/party-security), then after coming up with nothing, you get grumpy and decide to have a bit of fun - trolling people on StackOverflow with questions about [the best way to become a lion tamer, for a career programmer](https://meta.stackexchange.com/questions/14470/what-is-the-boat-programming-meme-about/14490#14490). You hop on over to StackOverflow, but as the page loads, something is clearly wrong. You can't click on anything, all of the questions in the list seem to be related to how to animate blood-effects in Javascript, and red pixels start coming down from the top of the screen. As they dribble down over more and more of the screen, some gaps are left in the middle of the screen which forms words, the "blood" drops flowing around them. It reads: > > Ha ha ha ha ha... > > Pathetic newbie programmers, WHERE IS YOUR GOD-OBJECT NOW? > > MUA HA HA HA HA! > > > -The SErial Killer > > > Terrified, you just sit there staring at the screen, until suddenly it redirects to [a terrible, terrible thing](https://www.youtube.com/watch?v=BROWqjuTM0g) and you snap into action, closing the window. You're not sure what exactly is going on, but in a rare moment of genius you realise that "SE" could refer to "Stack Exchange", and decide to see if any other sites on the SE network have been brutally murdered. As you pull up the [network sites page](http://stackexchange.com/sites) you see that yes, there are some other victims in this heinous crime. With no clues to go on, and nothing but a refined puzzling nose from weeks wast...err, spent on Puzzling.SE, you steel yourself and vow to bring the person or persons responsible for this to justice. The only question is ... where do you start looking? ![](https://i.stack.imgur.com/lvROU.png) A hint for you, to narrow the search: > > I didn't spend all that time making a fancy image for nothing you know! Graphics are hard (you can tell because of how cheesy it is :-P) > > >
2014/11/11
[ "https://puzzling.stackexchange.com/questions/4075", "https://puzzling.stackexchange.com", "https://puzzling.stackexchange.com/users/2518/" ]
Yeah, it's been answered, but what the hell. > > An important part of any murder mystery is the murder weapon. Finding that often gives you a solid lead. Based on the copious blood, and the fact that the icons remain intact, we can hypothesise that they were stabbed, so we're looking for something sharp. TeX-LaTeX has a pair of those nasty braces, SuperUser has a nose that tapers to a point and you could definitely do somebody a mischief if you flew Arqade into them. > > > But wait! > > Travel's icon is missing. And with three points, it's a murder weapon just waiting to happen. But it'd be difficult to use - it's evidentially not made to be held comfortably. Which leads us to **Role Playing Games**, who I posit took the feat *Exotic Weapon Proficiency (Travel Icon)* and took down some of his friends in a Pathfinder session gone horribly wrong. > > > Bonus pun: > > 'Die' indeed. Looks like their saving rolls came up snake eyes. > > >
Start looking in > > Web Applications or Webmasters > > > > Because > > a) All the questions were about animating blood in javascript > > b) The blood comes from the top (both are on the top of the all sites page) > > > > Comedy reason > > 3) Web coders can never figure anything out on their own, there is probably a post that reads "how me hack a SE website?" > > > > **Alternate Answer:** > > Look on your own computer, if nobody else has noticed, it's probably your local machine that's hacked, and not SE. > > > >
4,075
This is part of a series which I'll be continuing if this goes down well enough. If you have any feedback on the puzzle (too hard, too easy, not clear enough, etc) I'd appreciate it so that future puzzles can be better :-) --- You wake up and log on to your computer. You log on to Puzzling.SE, browse some puzzles. You spend half an hour trying to think of number sequences because you're [really desperate to go to a party](https://puzzling.stackexchange.com/questions/tagged/party-security), then after coming up with nothing, you get grumpy and decide to have a bit of fun - trolling people on StackOverflow with questions about [the best way to become a lion tamer, for a career programmer](https://meta.stackexchange.com/questions/14470/what-is-the-boat-programming-meme-about/14490#14490). You hop on over to StackOverflow, but as the page loads, something is clearly wrong. You can't click on anything, all of the questions in the list seem to be related to how to animate blood-effects in Javascript, and red pixels start coming down from the top of the screen. As they dribble down over more and more of the screen, some gaps are left in the middle of the screen which forms words, the "blood" drops flowing around them. It reads: > > Ha ha ha ha ha... > > Pathetic newbie programmers, WHERE IS YOUR GOD-OBJECT NOW? > > MUA HA HA HA HA! > > > -The SErial Killer > > > Terrified, you just sit there staring at the screen, until suddenly it redirects to [a terrible, terrible thing](https://www.youtube.com/watch?v=BROWqjuTM0g) and you snap into action, closing the window. You're not sure what exactly is going on, but in a rare moment of genius you realise that "SE" could refer to "Stack Exchange", and decide to see if any other sites on the SE network have been brutally murdered. As you pull up the [network sites page](http://stackexchange.com/sites) you see that yes, there are some other victims in this heinous crime. With no clues to go on, and nothing but a refined puzzling nose from weeks wast...err, spent on Puzzling.SE, you steel yourself and vow to bring the person or persons responsible for this to justice. The only question is ... where do you start looking? ![](https://i.stack.imgur.com/lvROU.png) A hint for you, to narrow the search: > > I didn't spend all that time making a fancy image for nothing you know! Graphics are hard (you can tell because of how cheesy it is :-P) > > >
2014/11/11
[ "https://puzzling.stackexchange.com/questions/4075", "https://puzzling.stackexchange.com", "https://puzzling.stackexchange.com/users/2518/" ]
Yeah, it's been answered, but what the hell. > > An important part of any murder mystery is the murder weapon. Finding that often gives you a solid lead. Based on the copious blood, and the fact that the icons remain intact, we can hypothesise that they were stabbed, so we're looking for something sharp. TeX-LaTeX has a pair of those nasty braces, SuperUser has a nose that tapers to a point and you could definitely do somebody a mischief if you flew Arqade into them. > > > But wait! > > Travel's icon is missing. And with three points, it's a murder weapon just waiting to happen. But it'd be difficult to use - it's evidentially not made to be held comfortably. Which leads us to **Role Playing Games**, who I posit took the feat *Exotic Weapon Proficiency (Travel Icon)* and took down some of his friends in a Pathfinder session gone horribly wrong. > > > Bonus pun: > > 'Die' indeed. Looks like their saving rolls came up snake eyes. > > >
> > Travel seems to be the oddball in the group, and as pointed out in a comment by Martin, it has no icon and name in the background, unlike the others. So I'd say go to the site Travel and find out what's up. I'd also put some sort of monitor on "Server Fault", "Super User", and "Programmers" and any other software type sites. > > >
4,075
This is part of a series which I'll be continuing if this goes down well enough. If you have any feedback on the puzzle (too hard, too easy, not clear enough, etc) I'd appreciate it so that future puzzles can be better :-) --- You wake up and log on to your computer. You log on to Puzzling.SE, browse some puzzles. You spend half an hour trying to think of number sequences because you're [really desperate to go to a party](https://puzzling.stackexchange.com/questions/tagged/party-security), then after coming up with nothing, you get grumpy and decide to have a bit of fun - trolling people on StackOverflow with questions about [the best way to become a lion tamer, for a career programmer](https://meta.stackexchange.com/questions/14470/what-is-the-boat-programming-meme-about/14490#14490). You hop on over to StackOverflow, but as the page loads, something is clearly wrong. You can't click on anything, all of the questions in the list seem to be related to how to animate blood-effects in Javascript, and red pixels start coming down from the top of the screen. As they dribble down over more and more of the screen, some gaps are left in the middle of the screen which forms words, the "blood" drops flowing around them. It reads: > > Ha ha ha ha ha... > > Pathetic newbie programmers, WHERE IS YOUR GOD-OBJECT NOW? > > MUA HA HA HA HA! > > > -The SErial Killer > > > Terrified, you just sit there staring at the screen, until suddenly it redirects to [a terrible, terrible thing](https://www.youtube.com/watch?v=BROWqjuTM0g) and you snap into action, closing the window. You're not sure what exactly is going on, but in a rare moment of genius you realise that "SE" could refer to "Stack Exchange", and decide to see if any other sites on the SE network have been brutally murdered. As you pull up the [network sites page](http://stackexchange.com/sites) you see that yes, there are some other victims in this heinous crime. With no clues to go on, and nothing but a refined puzzling nose from weeks wast...err, spent on Puzzling.SE, you steel yourself and vow to bring the person or persons responsible for this to justice. The only question is ... where do you start looking? ![](https://i.stack.imgur.com/lvROU.png) A hint for you, to narrow the search: > > I didn't spend all that time making a fancy image for nothing you know! Graphics are hard (you can tell because of how cheesy it is :-P) > > >
2014/11/11
[ "https://puzzling.stackexchange.com/questions/4075", "https://puzzling.stackexchange.com", "https://puzzling.stackexchange.com/users/2518/" ]
Yeah, it's been answered, but what the hell. > > An important part of any murder mystery is the murder weapon. Finding that often gives you a solid lead. Based on the copious blood, and the fact that the icons remain intact, we can hypothesise that they were stabbed, so we're looking for something sharp. TeX-LaTeX has a pair of those nasty braces, SuperUser has a nose that tapers to a point and you could definitely do somebody a mischief if you flew Arqade into them. > > > But wait! > > Travel's icon is missing. And with three points, it's a murder weapon just waiting to happen. But it'd be difficult to use - it's evidentially not made to be held comfortably. Which leads us to **Role Playing Games**, who I posit took the feat *Exotic Weapon Proficiency (Travel Icon)* and took down some of his friends in a Pathfinder session gone horribly wrong. > > > Bonus pun: > > 'Die' indeed. Looks like their saving rolls came up snake eyes. > > >
I'd look in > > Graphic Design, because these blood graphics are too pretty. Graphics are really hard! Plus their name is red, like blood. > > >
4,075
This is part of a series which I'll be continuing if this goes down well enough. If you have any feedback on the puzzle (too hard, too easy, not clear enough, etc) I'd appreciate it so that future puzzles can be better :-) --- You wake up and log on to your computer. You log on to Puzzling.SE, browse some puzzles. You spend half an hour trying to think of number sequences because you're [really desperate to go to a party](https://puzzling.stackexchange.com/questions/tagged/party-security), then after coming up with nothing, you get grumpy and decide to have a bit of fun - trolling people on StackOverflow with questions about [the best way to become a lion tamer, for a career programmer](https://meta.stackexchange.com/questions/14470/what-is-the-boat-programming-meme-about/14490#14490). You hop on over to StackOverflow, but as the page loads, something is clearly wrong. You can't click on anything, all of the questions in the list seem to be related to how to animate blood-effects in Javascript, and red pixels start coming down from the top of the screen. As they dribble down over more and more of the screen, some gaps are left in the middle of the screen which forms words, the "blood" drops flowing around them. It reads: > > Ha ha ha ha ha... > > Pathetic newbie programmers, WHERE IS YOUR GOD-OBJECT NOW? > > MUA HA HA HA HA! > > > -The SErial Killer > > > Terrified, you just sit there staring at the screen, until suddenly it redirects to [a terrible, terrible thing](https://www.youtube.com/watch?v=BROWqjuTM0g) and you snap into action, closing the window. You're not sure what exactly is going on, but in a rare moment of genius you realise that "SE" could refer to "Stack Exchange", and decide to see if any other sites on the SE network have been brutally murdered. As you pull up the [network sites page](http://stackexchange.com/sites) you see that yes, there are some other victims in this heinous crime. With no clues to go on, and nothing but a refined puzzling nose from weeks wast...err, spent on Puzzling.SE, you steel yourself and vow to bring the person or persons responsible for this to justice. The only question is ... where do you start looking? ![](https://i.stack.imgur.com/lvROU.png) A hint for you, to narrow the search: > > I didn't spend all that time making a fancy image for nothing you know! Graphics are hard (you can tell because of how cheesy it is :-P) > > >
2014/11/11
[ "https://puzzling.stackexchange.com/questions/4075", "https://puzzling.stackexchange.com", "https://puzzling.stackexchange.com/users/2518/" ]
> > **Moderators**. The "killed" sites are StackOverflow, Ask Different, MathOverflow, Reverse Engineering, Robotics, and Travel. The capital letters of the names of the "killed sites" are SOADMORERT, which when you jumble, you get MODERATORS. > > >
I'd look in > > Graphic Design, because these blood graphics are too pretty. Graphics are really hard! Plus their name is red, like blood. > > >
4,075
This is part of a series which I'll be continuing if this goes down well enough. If you have any feedback on the puzzle (too hard, too easy, not clear enough, etc) I'd appreciate it so that future puzzles can be better :-) --- You wake up and log on to your computer. You log on to Puzzling.SE, browse some puzzles. You spend half an hour trying to think of number sequences because you're [really desperate to go to a party](https://puzzling.stackexchange.com/questions/tagged/party-security), then after coming up with nothing, you get grumpy and decide to have a bit of fun - trolling people on StackOverflow with questions about [the best way to become a lion tamer, for a career programmer](https://meta.stackexchange.com/questions/14470/what-is-the-boat-programming-meme-about/14490#14490). You hop on over to StackOverflow, but as the page loads, something is clearly wrong. You can't click on anything, all of the questions in the list seem to be related to how to animate blood-effects in Javascript, and red pixels start coming down from the top of the screen. As they dribble down over more and more of the screen, some gaps are left in the middle of the screen which forms words, the "blood" drops flowing around them. It reads: > > Ha ha ha ha ha... > > Pathetic newbie programmers, WHERE IS YOUR GOD-OBJECT NOW? > > MUA HA HA HA HA! > > > -The SErial Killer > > > Terrified, you just sit there staring at the screen, until suddenly it redirects to [a terrible, terrible thing](https://www.youtube.com/watch?v=BROWqjuTM0g) and you snap into action, closing the window. You're not sure what exactly is going on, but in a rare moment of genius you realise that "SE" could refer to "Stack Exchange", and decide to see if any other sites on the SE network have been brutally murdered. As you pull up the [network sites page](http://stackexchange.com/sites) you see that yes, there are some other victims in this heinous crime. With no clues to go on, and nothing but a refined puzzling nose from weeks wast...err, spent on Puzzling.SE, you steel yourself and vow to bring the person or persons responsible for this to justice. The only question is ... where do you start looking? ![](https://i.stack.imgur.com/lvROU.png) A hint for you, to narrow the search: > > I didn't spend all that time making a fancy image for nothing you know! Graphics are hard (you can tell because of how cheesy it is :-P) > > >
2014/11/11
[ "https://puzzling.stackexchange.com/questions/4075", "https://puzzling.stackexchange.com", "https://puzzling.stackexchange.com/users/2518/" ]
I'd look in > > Graphic Design, because these blood graphics are too pretty. Graphics are really hard! Plus their name is red, like blood. > > >
> > Android Enthusiasts. GOD OBJECT related to object-oriented-programming which means Java. And Android main language is Java. > > >
4,075
This is part of a series which I'll be continuing if this goes down well enough. If you have any feedback on the puzzle (too hard, too easy, not clear enough, etc) I'd appreciate it so that future puzzles can be better :-) --- You wake up and log on to your computer. You log on to Puzzling.SE, browse some puzzles. You spend half an hour trying to think of number sequences because you're [really desperate to go to a party](https://puzzling.stackexchange.com/questions/tagged/party-security), then after coming up with nothing, you get grumpy and decide to have a bit of fun - trolling people on StackOverflow with questions about [the best way to become a lion tamer, for a career programmer](https://meta.stackexchange.com/questions/14470/what-is-the-boat-programming-meme-about/14490#14490). You hop on over to StackOverflow, but as the page loads, something is clearly wrong. You can't click on anything, all of the questions in the list seem to be related to how to animate blood-effects in Javascript, and red pixels start coming down from the top of the screen. As they dribble down over more and more of the screen, some gaps are left in the middle of the screen which forms words, the "blood" drops flowing around them. It reads: > > Ha ha ha ha ha... > > Pathetic newbie programmers, WHERE IS YOUR GOD-OBJECT NOW? > > MUA HA HA HA HA! > > > -The SErial Killer > > > Terrified, you just sit there staring at the screen, until suddenly it redirects to [a terrible, terrible thing](https://www.youtube.com/watch?v=BROWqjuTM0g) and you snap into action, closing the window. You're not sure what exactly is going on, but in a rare moment of genius you realise that "SE" could refer to "Stack Exchange", and decide to see if any other sites on the SE network have been brutally murdered. As you pull up the [network sites page](http://stackexchange.com/sites) you see that yes, there are some other victims in this heinous crime. With no clues to go on, and nothing but a refined puzzling nose from weeks wast...err, spent on Puzzling.SE, you steel yourself and vow to bring the person or persons responsible for this to justice. The only question is ... where do you start looking? ![](https://i.stack.imgur.com/lvROU.png) A hint for you, to narrow the search: > > I didn't spend all that time making a fancy image for nothing you know! Graphics are hard (you can tell because of how cheesy it is :-P) > > >
2014/11/11
[ "https://puzzling.stackexchange.com/questions/4075", "https://puzzling.stackexchange.com", "https://puzzling.stackexchange.com/users/2518/" ]
I'd look in > > Graphic Design, because these blood graphics are too pretty. Graphics are really hard! Plus their name is red, like blood. > > >
You should probably put up a support request in stackapps so that more people will be aware and working on the problem, a wild wild guess
4,075
This is part of a series which I'll be continuing if this goes down well enough. If you have any feedback on the puzzle (too hard, too easy, not clear enough, etc) I'd appreciate it so that future puzzles can be better :-) --- You wake up and log on to your computer. You log on to Puzzling.SE, browse some puzzles. You spend half an hour trying to think of number sequences because you're [really desperate to go to a party](https://puzzling.stackexchange.com/questions/tagged/party-security), then after coming up with nothing, you get grumpy and decide to have a bit of fun - trolling people on StackOverflow with questions about [the best way to become a lion tamer, for a career programmer](https://meta.stackexchange.com/questions/14470/what-is-the-boat-programming-meme-about/14490#14490). You hop on over to StackOverflow, but as the page loads, something is clearly wrong. You can't click on anything, all of the questions in the list seem to be related to how to animate blood-effects in Javascript, and red pixels start coming down from the top of the screen. As they dribble down over more and more of the screen, some gaps are left in the middle of the screen which forms words, the "blood" drops flowing around them. It reads: > > Ha ha ha ha ha... > > Pathetic newbie programmers, WHERE IS YOUR GOD-OBJECT NOW? > > MUA HA HA HA HA! > > > -The SErial Killer > > > Terrified, you just sit there staring at the screen, until suddenly it redirects to [a terrible, terrible thing](https://www.youtube.com/watch?v=BROWqjuTM0g) and you snap into action, closing the window. You're not sure what exactly is going on, but in a rare moment of genius you realise that "SE" could refer to "Stack Exchange", and decide to see if any other sites on the SE network have been brutally murdered. As you pull up the [network sites page](http://stackexchange.com/sites) you see that yes, there are some other victims in this heinous crime. With no clues to go on, and nothing but a refined puzzling nose from weeks wast...err, spent on Puzzling.SE, you steel yourself and vow to bring the person or persons responsible for this to justice. The only question is ... where do you start looking? ![](https://i.stack.imgur.com/lvROU.png) A hint for you, to narrow the search: > > I didn't spend all that time making a fancy image for nothing you know! Graphics are hard (you can tell because of how cheesy it is :-P) > > >
2014/11/11
[ "https://puzzling.stackexchange.com/questions/4075", "https://puzzling.stackexchange.com", "https://puzzling.stackexchange.com/users/2518/" ]
> > **Moderators**. The "killed" sites are StackOverflow, Ask Different, MathOverflow, Reverse Engineering, Robotics, and Travel. The capital letters of the names of the "killed sites" are SOADMORERT, which when you jumble, you get MODERATORS. > > >
You should probably put up a support request in stackapps so that more people will be aware and working on the problem, a wild wild guess
39,013,474
I have a table `int` in MySQL ``` create table `int` (c1 varchar(20)); insert into `int` values ('some data'); ``` I try to import it in hive using Sqoop: `sqoop import --connect='jdbc:mysql://xxx.xxx.xxx.xxx/classicmodels' --driver com.mysql.jdbc.Driver --username xxx --password xxx --table int --delete-target-dir --target-dir /tmp/test --hive-import --hive-table default.test --hive-drop-import-delims --null-string '\\N' --null-non-string '\\N' --split-by col_date -m 1 --verbose` Internally, it is creating `SELECT t.* FROM int AS t WHERE 1=0` Error: > > 16/08/18 13:43:20 ERROR manager.SqlManager: Error executing statement: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'int AS t WHERE 1=0' at line 1 > > > *which is expected.* I tried, `--table "int"`, `--table `int`` and `--table "`int`"`. **None of them worked.** Is there any way to tell sqoop to create query: `SELECT t.* FROM `int` AS t WHERE 1=0` --- `[ ]` is used to bypass reserved words in SQL server. In SQL Server `--table dbo.[int]` worked for me.
2016/08/18
[ "https://Stackoverflow.com/questions/39013474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3929393/" ]
The easiest way to do this is to go to: Administration -> Customisation -> (any entity) -> Screens The tick the "Inline Customisation" tickbox, just below the tabs: [![Sage CRM - Inline Customisation - Six Ticks Limited](https://i.stack.imgur.com/evmfs.jpg)](https://i.stack.imgur.com/evmfs.jpg) Then, go back to the Main Menu and go to any Company record. You will see the inline customisation options at the top of each screen: [![Sage CRM - Customise Screen - Six Ticks Limited](https://i.stack.imgur.com/zotmq.jpg)](https://i.stack.imgur.com/zotmq.jpg) Click the "Customise Screen" link and a pop-up will appear (make sure you don't have a pop-up blocker). At the top of that pop-up, it will tell you the Screen name: [![Sage CRM - Screen Customisation Pop-up - Six Ticks Limited](https://i.stack.imgur.com/FE0FT.jpg)](https://i.stack.imgur.com/FE0FT.jpg) You can either customise the screen from this pop-up, or go back into the Administration section, find the screen, and customise it from there. I hope that helps! Six Ticks Limited
Just activate the "Integrated personalization" in Admin > Personalization > ENTITY > Screens > And then check the "Integrated personalization" This way, a link will appear at top of every screen and it will let you customize that speceific screen
19,041,306
Although I know this is an easy issue and a gap in my knowledge - please keep in mind I'm writing this code to learn (and detailed explanations or best practice suggestions would greatly help in this). Firstly, here's my class: ``` namespace CCQ.Crawler._2010 { public class MSSQL { public MSSQL(string connectionString) { ConnectionString = connectionString; } public static string ConnectionString { get; private set; } /// <summary> /// Class to house statements that insert or update data into the database /// </summary> public class Upserts { /// <summary> /// Add or update a new entry on the site collection table /// </summary> /// <param name="siteCollectionName"></param> public void SiteCollection(string siteCollectionName) { const string queryString = @"INSERT INTO [dbo].[SiteCollections] ([SnapShotDate] ,[SiteCollectionName] ,[SiteWebCount] ,[ContentDatabase] ,[SiteWebApplication]) VALUES (@snapShotDate, @siteCollectionName, @siteWebCount, @contentDatabase, @siteWebApplication)"; using (var connection = new SqlConnection(ConnectionString)) { using (var cmd = new SqlCommand(queryString, connection)) { connection.Open(); cmd.Parameters.AddWithValue("snapShotDate", DateTime.Today.Date); cmd.Parameters.AddWithValue("siteCollectionName", siteCollectionName); cmd.ExecuteNonQuery(); } } } } } } ``` And here's my main program file: ``` namespace CCQ.Crawler._2010 { internal class Program { private static string _connectionString; private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); public static string ConnectionString { get { if (string.IsNullOrEmpty(_connectionString)) { _connectionString = AES.DecryptFromBase64String(ConfigurationManager.AppSettings["DatastoreConnection"]); } return _connectionString; } } static void Main(string[] args) { string version = Assembly.GetAssembly(typeof(Program)).GetName().Version.ToString(); Console.WriteLine("[{0}] SharePoint Crawler started with version '{1}'.", DateTime.Now.ToShortTimeString(), version); Logger.Info(string.Format("[{0}] SharePoint Crawler started with version '{1}'.", DateTime.Now.ToShortTimeString(), version)); try { var query = new MSSQL(ConnectionString); } catch (Exception ex) { Logger.Error(String.Format("[{0}] {1}", DateTime.Now.ToShortTimeString(), ex.GetBaseException())); Console.WriteLine("[{0}] {1}", DateTime.Now.ToShortTimeString(), ex.GetBaseException()); } } } } ``` Now what I thought I could do with this class, was this: ``` var query = new MSSQL(ConnectionString).Upserts; query.SiteCollection("testing"); ``` But, well, that doesn't work. The error I'm getting when I try to declare the class is: > > Class name is not valid at this point > > > I know there's a huge gap somewhere in my knowledge / class construction which is why, but I don't quite know where to begin - where's the error in my thinking?
2013/09/27
[ "https://Stackoverflow.com/questions/19041306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/692572/" ]
In this line of code: ``` var query = new MSSQL(ConnectionString).Upserts; ``` you are actually constructing a new instance of the MSSQL class then using the syntax as if `Upserts` was a property on it that you are trying to access. Instead, to instantiate your nested class, you should do something like this: ``` var mssql = new MSSQL("your connection string"); var query = new MSSQL.Upserts(); ``` **BUT...** The way you are storing the conection string in a static property of the enclosing class is a bit strange, and initializing the static propery in a non-static constructor is strange too. You probably don't need to have `Upserts` be a nested class. Try making it a method instead. Also, your connection string can be stored in an instance field/property rather than being static.
'query' is of type MSSQL. The SiteCollection property belongs to the Upserts type. Although you have defined the Upserts type within MSSQL as a nested type, you aren't actually using the Upserts type in your MSSQL object (for example, as a property). The quickest way I can see to get this up and running is to add an Upserts property to your MSSQL class and instantiate it in your constructor. ``` public Upserts Upserts { get; private set; } ``` You will then be able to access the method by the following means: ``` query.Upserts.SiteCollection("..."); ``` Alternatively, you could just modify Upserts to receive a connection string and instantiate it directly... this is a step toward removing MSSQL from the equation though. I realise you're writing this to wrap your head around classes and properties, so I wont comment on whether this is or isn't a good approach to DAL.
19,041,306
Although I know this is an easy issue and a gap in my knowledge - please keep in mind I'm writing this code to learn (and detailed explanations or best practice suggestions would greatly help in this). Firstly, here's my class: ``` namespace CCQ.Crawler._2010 { public class MSSQL { public MSSQL(string connectionString) { ConnectionString = connectionString; } public static string ConnectionString { get; private set; } /// <summary> /// Class to house statements that insert or update data into the database /// </summary> public class Upserts { /// <summary> /// Add or update a new entry on the site collection table /// </summary> /// <param name="siteCollectionName"></param> public void SiteCollection(string siteCollectionName) { const string queryString = @"INSERT INTO [dbo].[SiteCollections] ([SnapShotDate] ,[SiteCollectionName] ,[SiteWebCount] ,[ContentDatabase] ,[SiteWebApplication]) VALUES (@snapShotDate, @siteCollectionName, @siteWebCount, @contentDatabase, @siteWebApplication)"; using (var connection = new SqlConnection(ConnectionString)) { using (var cmd = new SqlCommand(queryString, connection)) { connection.Open(); cmd.Parameters.AddWithValue("snapShotDate", DateTime.Today.Date); cmd.Parameters.AddWithValue("siteCollectionName", siteCollectionName); cmd.ExecuteNonQuery(); } } } } } } ``` And here's my main program file: ``` namespace CCQ.Crawler._2010 { internal class Program { private static string _connectionString; private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); public static string ConnectionString { get { if (string.IsNullOrEmpty(_connectionString)) { _connectionString = AES.DecryptFromBase64String(ConfigurationManager.AppSettings["DatastoreConnection"]); } return _connectionString; } } static void Main(string[] args) { string version = Assembly.GetAssembly(typeof(Program)).GetName().Version.ToString(); Console.WriteLine("[{0}] SharePoint Crawler started with version '{1}'.", DateTime.Now.ToShortTimeString(), version); Logger.Info(string.Format("[{0}] SharePoint Crawler started with version '{1}'.", DateTime.Now.ToShortTimeString(), version)); try { var query = new MSSQL(ConnectionString); } catch (Exception ex) { Logger.Error(String.Format("[{0}] {1}", DateTime.Now.ToShortTimeString(), ex.GetBaseException())); Console.WriteLine("[{0}] {1}", DateTime.Now.ToShortTimeString(), ex.GetBaseException()); } } } } ``` Now what I thought I could do with this class, was this: ``` var query = new MSSQL(ConnectionString).Upserts; query.SiteCollection("testing"); ``` But, well, that doesn't work. The error I'm getting when I try to declare the class is: > > Class name is not valid at this point > > > I know there's a huge gap somewhere in my knowledge / class construction which is why, but I don't quite know where to begin - where's the error in my thinking?
2013/09/27
[ "https://Stackoverflow.com/questions/19041306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/692572/" ]
In this line of code: ``` var query = new MSSQL(ConnectionString).Upserts; ``` you are actually constructing a new instance of the MSSQL class then using the syntax as if `Upserts` was a property on it that you are trying to access. Instead, to instantiate your nested class, you should do something like this: ``` var mssql = new MSSQL("your connection string"); var query = new MSSQL.Upserts(); ``` **BUT...** The way you are storing the conection string in a static property of the enclosing class is a bit strange, and initializing the static propery in a non-static constructor is strange too. You probably don't need to have `Upserts` be a nested class. Try making it a method instead. Also, your connection string can be stored in an instance field/property rather than being static.
I think there is no need to use nested class in this case. You could Try this: ``` /// <summary> /// <para>MSSQL class</para> /// </summary> public class MSSQL { #region Class field declaration private string f_connectionString; #endregion #region Public method /// <summary> /// <para>Static method for getting the class instance.</para> /// </summary> /// <param name="p_connectionString">MSSQL connection string</param> /// <returns><see cref="MSSQL"/></returns> public static MSSQL Create(string p_connectionString) { return new MSSQL(p_connectionString); } public void SiteCollection(string p_siteCollectionName) { //Your Logic here. } #endregion #region Constructor /// <summary> /// <para>Hide the default constructor</para> /// </summary> private MSSQL() { } /// <summary> /// <para>Private constructor for Static method</para> /// </summary> /// <param name="p_connectionString">MSSQL connection string</param> private MSSQL(string p_connectionString) { this.f_connectionString = p_connectionString; } #endregion } ``` By this code, you could create the instance of this class by: ``` var instance = MSSQL.Create("ConnectionString"); ``` Get the SiteCollection by: ``` var siteCollection = instance.SiteCollection("Testing"); ```
19,041,306
Although I know this is an easy issue and a gap in my knowledge - please keep in mind I'm writing this code to learn (and detailed explanations or best practice suggestions would greatly help in this). Firstly, here's my class: ``` namespace CCQ.Crawler._2010 { public class MSSQL { public MSSQL(string connectionString) { ConnectionString = connectionString; } public static string ConnectionString { get; private set; } /// <summary> /// Class to house statements that insert or update data into the database /// </summary> public class Upserts { /// <summary> /// Add or update a new entry on the site collection table /// </summary> /// <param name="siteCollectionName"></param> public void SiteCollection(string siteCollectionName) { const string queryString = @"INSERT INTO [dbo].[SiteCollections] ([SnapShotDate] ,[SiteCollectionName] ,[SiteWebCount] ,[ContentDatabase] ,[SiteWebApplication]) VALUES (@snapShotDate, @siteCollectionName, @siteWebCount, @contentDatabase, @siteWebApplication)"; using (var connection = new SqlConnection(ConnectionString)) { using (var cmd = new SqlCommand(queryString, connection)) { connection.Open(); cmd.Parameters.AddWithValue("snapShotDate", DateTime.Today.Date); cmd.Parameters.AddWithValue("siteCollectionName", siteCollectionName); cmd.ExecuteNonQuery(); } } } } } } ``` And here's my main program file: ``` namespace CCQ.Crawler._2010 { internal class Program { private static string _connectionString; private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); public static string ConnectionString { get { if (string.IsNullOrEmpty(_connectionString)) { _connectionString = AES.DecryptFromBase64String(ConfigurationManager.AppSettings["DatastoreConnection"]); } return _connectionString; } } static void Main(string[] args) { string version = Assembly.GetAssembly(typeof(Program)).GetName().Version.ToString(); Console.WriteLine("[{0}] SharePoint Crawler started with version '{1}'.", DateTime.Now.ToShortTimeString(), version); Logger.Info(string.Format("[{0}] SharePoint Crawler started with version '{1}'.", DateTime.Now.ToShortTimeString(), version)); try { var query = new MSSQL(ConnectionString); } catch (Exception ex) { Logger.Error(String.Format("[{0}] {1}", DateTime.Now.ToShortTimeString(), ex.GetBaseException())); Console.WriteLine("[{0}] {1}", DateTime.Now.ToShortTimeString(), ex.GetBaseException()); } } } } ``` Now what I thought I could do with this class, was this: ``` var query = new MSSQL(ConnectionString).Upserts; query.SiteCollection("testing"); ``` But, well, that doesn't work. The error I'm getting when I try to declare the class is: > > Class name is not valid at this point > > > I know there's a huge gap somewhere in my knowledge / class construction which is why, but I don't quite know where to begin - where's the error in my thinking?
2013/09/27
[ "https://Stackoverflow.com/questions/19041306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/692572/" ]
'query' is of type MSSQL. The SiteCollection property belongs to the Upserts type. Although you have defined the Upserts type within MSSQL as a nested type, you aren't actually using the Upserts type in your MSSQL object (for example, as a property). The quickest way I can see to get this up and running is to add an Upserts property to your MSSQL class and instantiate it in your constructor. ``` public Upserts Upserts { get; private set; } ``` You will then be able to access the method by the following means: ``` query.Upserts.SiteCollection("..."); ``` Alternatively, you could just modify Upserts to receive a connection string and instantiate it directly... this is a step toward removing MSSQL from the equation though. I realise you're writing this to wrap your head around classes and properties, so I wont comment on whether this is or isn't a good approach to DAL.
I think there is no need to use nested class in this case. You could Try this: ``` /// <summary> /// <para>MSSQL class</para> /// </summary> public class MSSQL { #region Class field declaration private string f_connectionString; #endregion #region Public method /// <summary> /// <para>Static method for getting the class instance.</para> /// </summary> /// <param name="p_connectionString">MSSQL connection string</param> /// <returns><see cref="MSSQL"/></returns> public static MSSQL Create(string p_connectionString) { return new MSSQL(p_connectionString); } public void SiteCollection(string p_siteCollectionName) { //Your Logic here. } #endregion #region Constructor /// <summary> /// <para>Hide the default constructor</para> /// </summary> private MSSQL() { } /// <summary> /// <para>Private constructor for Static method</para> /// </summary> /// <param name="p_connectionString">MSSQL connection string</param> private MSSQL(string p_connectionString) { this.f_connectionString = p_connectionString; } #endregion } ``` By this code, you could create the instance of this class by: ``` var instance = MSSQL.Create("ConnectionString"); ``` Get the SiteCollection by: ``` var siteCollection = instance.SiteCollection("Testing"); ```
21,847,947
I am working in Android Technology.In my application i am fetching the data from web service i used A sync Task for consuming web service.It show the data correctly on Toast i.e true or false but My Progress Bar is continuously moving it does not stopped when Background task completed its execution i called dismiss method in onPostExecute().But it failed to dismiss the progress bar.Again it start calling web service but progress bar is not dismmed. Can you tell me what i did wrong in my code.Please solve my problem.. I am attaching source code here Async task ``` public class MyTask extends AsyncTask<String,Void,String> { @Override protected void onPostExecute(String result) { // TODO Auto-generated method stub super.onPostExecute(result); pd.dismiss(); Toast.makeText(getApplicationContext(), ""+result,Toast.LENGTH_LONG).show(); } @Override protected void onPreExecute() { // TODO Auto-generated method stub super.onPreExecute(); pd=new ProgressDialog(MainActivity.this); pd.setMessage("Please Wait"); pd.setCancelable(false); pd.setIndeterminate(false); pd.show(); } @Override protected String doInBackground(String... arg0) { // TODO Auto-generated method stub v=new Validate(); String result; result=v.SendParam(url,user,pass); return result; } } ``` Here id Validate.java code ``` class Validate { ArrayList<NameValuePair> namevaluepair; InputStream is; String res; public String SendParam(String url,String username,String password) { try { HttpClient client=new DefaultHttpClient(); HttpPost post=new HttpPost(url); // add parameter here namevaluepair=new ArrayList<NameValuePair>(); namevaluepair.add(new BasicNameValuePair("id",username)); namevaluepair.add(new BasicNameValuePair("password",password)); post.setEntity(new UrlEncodedFormEntity(namevaluepair)); HttpResponse response=client.execute(post); HttpEntity entity=response.getEntity(); is=entity.getContent(); } catch(Exception e) { Log.d("Httpconnection","error",e); } // read response from try { BufferedReader reader=new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); StringBuilder builder=new StringBuilder(); String line; while((line=reader.readLine())!=null) { builder.append(line+"\n"); } is.close(); res=builder.toString(); } catch(Exception e) { Log.d("reading Input Stream","",e); } return res; } } ```
2014/02/18
[ "https://Stackoverflow.com/questions/21847947", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3202493/" ]
All loggers are ordered into a hierarchy, by its names. So you may to configure a parent logger ("log4j.logger.com.my.package" or root logger) and override configuration for some of child loggers if you need. See more at <http://logging.apache.org/log4j/2.x/manual/architecture.html> .
LOG4J is designed in a pattern of systematic hierarchical structure, by the order of its names given. Following image depicts the hierarchical representation of loggers ![](https://logging.apache.org/log4j/2.x/images/Log4jClasses.jpg) * So if you need to override or re-configure the root node logger you need the `log4j.logger.com.my.package` in your case, and override the specific configuration of the child loggers. Ref [Link](http://logging.apache.org/log4j/2.x/manual/architecture.html)
49,582,477
I am trying to write a HOC in react to protect path and somehow except for the constructor, none of the function in the class was called. Here's what I have for the code (this.props.userProfile is another function that would return information about the user. The function works perfectly fine with other components so I don't think it would contribute to the problem) ``` import React from 'react'; class AuthorizedHOC extends React.Component { constructor(props, allowedRoles) { super(props); console.log('in authorizedHOC'); this.state = {'role':false}; this.checkAuthorization = this.checkAuthorization.bind(this); } componentWillMount(){ this.checkAuthorization(); console.log('in component will mount'); } componentWillReceiveProps(nextProps){ this.checkAuthorization(); console.log('in next props will mount'); } checkAuthorization(){ console.log('checkAuthorization'); let userProfile = this.props.userProfile; for (let role in allowedRoles){ if (userProfile.roles.includes(role)){ console.log("have access"); this.state.role = true; } } console.log('in side checkAuthorization'); } render() { console.log('in render'); return (<div> {this.state.role ? <WrappedComponent {...this.props}/> : <p>not allowed</p>} </div>); } } export default AuthorizedHOC; ```
2018/03/30
[ "https://Stackoverflow.com/questions/49582477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5664411/" ]
Assuming you can use the payload identifying information from the `data` itself that is sent with the event (for both success and error), then you can do it like this: ``` public processData(payload: Payload) { // Push data onto a stack this._myStack.push(payload); return new Promise((resolve, reject) => { function resolver(data) { // if this event belongs to this payload if (data.payload === payload) { resolve(data); clearHandlers(); } } function rejecter(error) { // if this event belongs to this payload if (error.payload === payload) { reject(error); clearHandlers(); } } // clear event handlers function clearHandlers() { myEventEmitter.removeListener('processSuccess', resolver); myEventEmitter.removeListener('processError', rejecter); } myEventEmitter.on('processSuccess', resolver); myEventEmitter.on('processError', rejecter); }); } ``` If you can't identify which payload corresponds with which event, then the only way to use this general structure is to never have the same `myEventEmitter` being used for more than one `processData()` operation at a time. That's because you need to make sure that when a `processSuccess` or `processError` event occurs, you know exactly which payload it belongs to. You have to know that to avoid cross coupling between separate async operations in flight at the same time. That can be accomlished in four ways: 1. The payload is part of every event so you can compare to see if it's the right payload (like in my first code example). 2. A `myEventEmitter` object is never shared between operations that are in flight at the same time. 3. No two async operations that are using a shared `myEventEmitter` are ever in flight at the same time. 4. You somehow conjure up unique message names to both listen to and trigger for each separate payload that is running. This would require cooperation with the event triggering side of things too. For options #2 or #3 above, you could use this code: ``` public processData(payload: Payload) { // Push data onto a stack this._myStack.push(payload); return new Promise((resolve, reject) => { function resolver(data) { resolve(data); clearHandlers(); } function rejecter(err) { reject(error); clearHandlers(); } // clear event handlers function clearHandlers() { myEventEmitter.removeListener('processSuccess', resolver); myEventEmitter.removeListener('processError', rejecter); } myEventEmitter.on('processSuccess', resolver); myEventEmitter.on('processError', rejecter); }); } ```
Use event Namespacing. refer <https://css-tricks.com/namespaced-events-jquery/> Make some sort of dynamic namespace for events, and run a check for that namespace to match in a common event listener. Resolve promise when any of the namespace matches.
49,582,477
I am trying to write a HOC in react to protect path and somehow except for the constructor, none of the function in the class was called. Here's what I have for the code (this.props.userProfile is another function that would return information about the user. The function works perfectly fine with other components so I don't think it would contribute to the problem) ``` import React from 'react'; class AuthorizedHOC extends React.Component { constructor(props, allowedRoles) { super(props); console.log('in authorizedHOC'); this.state = {'role':false}; this.checkAuthorization = this.checkAuthorization.bind(this); } componentWillMount(){ this.checkAuthorization(); console.log('in component will mount'); } componentWillReceiveProps(nextProps){ this.checkAuthorization(); console.log('in next props will mount'); } checkAuthorization(){ console.log('checkAuthorization'); let userProfile = this.props.userProfile; for (let role in allowedRoles){ if (userProfile.roles.includes(role)){ console.log("have access"); this.state.role = true; } } console.log('in side checkAuthorization'); } render() { console.log('in render'); return (<div> {this.state.role ? <WrappedComponent {...this.props}/> : <p>not allowed</p>} </div>); } } export default AuthorizedHOC; ```
2018/03/30
[ "https://Stackoverflow.com/questions/49582477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5664411/" ]
Assuming you can use the payload identifying information from the `data` itself that is sent with the event (for both success and error), then you can do it like this: ``` public processData(payload: Payload) { // Push data onto a stack this._myStack.push(payload); return new Promise((resolve, reject) => { function resolver(data) { // if this event belongs to this payload if (data.payload === payload) { resolve(data); clearHandlers(); } } function rejecter(error) { // if this event belongs to this payload if (error.payload === payload) { reject(error); clearHandlers(); } } // clear event handlers function clearHandlers() { myEventEmitter.removeListener('processSuccess', resolver); myEventEmitter.removeListener('processError', rejecter); } myEventEmitter.on('processSuccess', resolver); myEventEmitter.on('processError', rejecter); }); } ``` If you can't identify which payload corresponds with which event, then the only way to use this general structure is to never have the same `myEventEmitter` being used for more than one `processData()` operation at a time. That's because you need to make sure that when a `processSuccess` or `processError` event occurs, you know exactly which payload it belongs to. You have to know that to avoid cross coupling between separate async operations in flight at the same time. That can be accomlished in four ways: 1. The payload is part of every event so you can compare to see if it's the right payload (like in my first code example). 2. A `myEventEmitter` object is never shared between operations that are in flight at the same time. 3. No two async operations that are using a shared `myEventEmitter` are ever in flight at the same time. 4. You somehow conjure up unique message names to both listen to and trigger for each separate payload that is running. This would require cooperation with the event triggering side of things too. For options #2 or #3 above, you could use this code: ``` public processData(payload: Payload) { // Push data onto a stack this._myStack.push(payload); return new Promise((resolve, reject) => { function resolver(data) { resolve(data); clearHandlers(); } function rejecter(err) { reject(error); clearHandlers(); } // clear event handlers function clearHandlers() { myEventEmitter.removeListener('processSuccess', resolver); myEventEmitter.removeListener('processError', rejecter); } myEventEmitter.on('processSuccess', resolver); myEventEmitter.on('processError', rejecter); }); } ```
so basically for an good answer I'd require a little more information, but overall it you are able to do the following: * Payload should have an unique id * Data response should contain the same id * Error response should contain the same id So based on that your payload object should something like this: ``` {"id": ..., ....} ``` Response data object ``` {"id": ..., ....} ``` Error data object ``` {"id": ..., ....} ``` You could easily do something like this: ```js class MyClass { private _myStack: Array<Payload>; private _promisesFunctions: Array<any>; constructor() { myEventEmitter.on('processSuccess', data => { this._promisesFunctions[data.id].resolve(data); }); myEventEmitter.on('processError', error => { this._promisesFunctions[error.id].reject(error); }); } public async processData(payload: Payload) { // Push data onto a stack this._myStack.push(payload); return await new Promise(async (resolve, reject) => { this._promisesFunctions[payload.id] = { resolve, reject }; }); } } ``` If you don't have this possibility or you can't control those 3 objects, please provide examples of all this 3 object or at least more information about this issue and I'll update my response
33,536,859
So i have this program that lets you play rock paper scissors against yourself, how do I go about including a while loop to run the program as many times until the user chooses to quit. Heres what I have so far: ``` public static void main(String[] args) { //Instantiate random and scanner function Random rNum = new Random (); Scanner scan = new Scanner (System.in); //instantiate integers for the computer and user number int computerNumber; int userNumber; //sets parameter from which the computer can draw a number from computerNumber = rNum.nextInt(3) +1 ; //Prints the purpose of this program to user System.out.println("This program lets you play rock paper scissor against" + "a CPU, good luck!"); //Prints the options that the user can input System.out.println("Choose your weapon, 1, rock, 2, paper, 3 scissor"); //captures and holds user answer userNumber = scan.nextInt(); //first set of outcomes, a draw if(userNumber == computerNumber) { System.out.println("You have drawn, go again."); //Prints outcome of a draw } //Program uses else if to determine what outcome to print depending on user number else if(userNumber == 1 && computerNumber == 2 || userNumber == 2 && computerNumber== 3|| userNumber == 3 && computerNumber == 1) //Prints outcome of a loss System.out.println("You fell in combat to " + computerNumber + " ,try again."); //Prints outcome of a win else System.out.println("Congratulations, you are victorious! You " + "defeated " + computerNumber) ; } } ```
2015/11/05
[ "https://Stackoverflow.com/questions/33536859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5504583/" ]
You first need to pick a good spot to start your while loop, I would start mine here: ``` public static void main(String[] args) { //Instantiate random and scanner function Random rNum = new Random (); Scanner scan = new Scanner (System.in); //instantiate integers for the computer and user number int computerNumber, userNumber; do { //Code for playing the game } while (condition); } //end of main ``` Then you need to ask the user if they want to play again, and put the result as the condition for the do while loop: ``` do { //Code for playing the game System.out.print("Do you want to play again? <y/n> :"); } while (scan.next() != "n"); ```
Try this code public static void main(String[] args) { //Instantiate random and scanner function ``` Random rNum = new Random (); Scanner scan = new Scanner (System.in); //instantiate integers for the computer and user number int computerNumber; int userNumber; String quit="n"; //sets parameter from which the computer can draw a number from //Prints the purpose of this program to user System.out.println("This program lets you play rock paper scissor against" + "a CPU, good luck!"); while(quit.equalsIgnoreCase("n")){ //Prints the options that the user can input System.out.println("Choose your weapon, 1, rock, 2, paper, 3 scissor"); computerNumber = rNum.nextInt(3) +1 ; //captures and holds user answer userNumber = scan.nextInt(); //first set of outcomes, a draw if(userNumber == computerNumber) { System.out.println("You have drawn, go again."); //Prints outcome of a draw } //Program uses else if to determine what outcome to print depending on user number else if(userNumber == 1 && computerNumber == 2 || userNumber == 2 && computerNumber== 3|| userNumber == 3 && computerNumber == 1) { //Prints outcome of a loss System.out.println("You fell in combat to " + computerNumber + " ,try again."); } //Prints outcome of a win else{ System.out.println("Congratulations, you are victorious! You " + "defeated " + computerNumber) ; } System.out.println("Do you want you quit the game(y/n)?"); scan.nextLine(); quit=scan.nextLine(); while(!(quit.equalsIgnoreCase("y")||quit.equalsIgnoreCase("n"))){ System.out.println("enter proper input (y/n)"); quit=scan.nextLine(); } } } ```
53,348,629
In Python's scipy.stats library, it has a very stylized set of random variable classes, methods, and attributes. Most relate to the distribution itself, e.g., "what is the mean?" or "what is the variance?" The lognormal distribution is an oddball because the parameters that define it are not the usual parameters for the distribution, but the parameters for a normal distribution that it derives from. Simply put, if X is a normal distribution with mean mu and stdev sigma, Y=e^X is a lognormal that has its own means, mode, variance, stdev, etc. Does anyone know of a quick or clever way to recover the underlying mu and sigma (of the normal distribution X) via methods or attributes of a 'frozen' RV in scipy.stats? Since scipy.stats does give the mean, stdev, etc., of the actual lognormal, one could do a lot of algebra and recover it from the standard translations...but the code is likely unmaintainable. For reference< see: <https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.lognorm.html> and <https://en.wikipedia.org/wiki/Log-normal_distribution>
2018/11/17
[ "https://Stackoverflow.com/questions/53348629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8394209/" ]
You can get the `mu` and `sigma` very easily from the SciPy `scale` and `shape` parameters: ``` mu = log(scale) sigma = shape ``` However if you have a non-zero `loc` you need to use this as an offset when doing anything with this distribution. e.g. ``` percentile = mylognorm.cdf(x - loc) x = mylognorm.inverseCdf(percentile) + loc ```
(This post is a bit old but is worth mentioning the answer). Scipy `rv_continuous` instances have the `.stats` method (see [here](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.rv_continuous.stats.html#scipy.stats.rv_continuous.stats)). You can retrieve parameters like mean and variance with this method. This method can be called from the class or the instance: ``` # from the classs scipy.stats.lognorm.stats(loc=2,s=1,moments='mvsk') >> (array(3.64872127), array(4.67077427), array(6.18487714), array(110.93639218)) # or from the instance scipy.stats.lognorm(loc=2, s=1).stats(moments='mvsk') ```
56,062,155
I have an Azure function app triggered by an HttpRequest. The function app reads the request, tosses one copy of it into a storage table for safekeeping and sends another copy to a queue for further processing by another element of the system. I have a client running an ApacheBench test that reports approximately 148 requests per second processed. That rate of processing will not be enough for our expected load. My understanding of function apps is that it should spawn as many instances as is needed to handle the load sent to it. But this function app might not be scaling out quickly enough as it’s only handling that 148 requests per second. I need it to handle at least 200 requests per second. I’m not 100% sure the problem is on my end, though. In analyzing the performance of my function app I found a LOT of 429 errors. What I found online, particularly <https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-request-limits>, suggests that these errors could be due to too many requests being sent from a single IP. Would several ApacheBench 10K and 20K request load tests within a given day cause the 429 error? However, if that’s not it, if the problem is with my function app, how can I force my function app to spawn more instances more quickly? I assume this is the way to get more throughput per second. But I’m still very new at working with function apps so if there is a different way, I would more than welcome your input. Maybe the Premium app service plan that’s in public preview would handle more throughput? I’ve thought about switching over to that and running a quick test but am unsure if I’d be able to switch back? Maybe EventHub is something I need to investigate? Is that something that might increase my apparent throughput by catching more requests and holding on to them until the function app could accept and process them? Thanks in advance for any assistance you can give.
2019/05/09
[ "https://Stackoverflow.com/questions/56062155", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9602852/" ]
You dont provide much context of you app but this is few steps how you can improve 1. If you want more control you need to use [App Service plan](https://learn.microsoft.com/en-us/azure/azure-functions/functions-scale#app-service-plan) with always on to avoid cold start, also you will need to configure auto scaling since you are responsible in this plan and auto scale is not enabled by default in app service plan. 2. Your azure function must be fully async as you have external dependencies so you dont want to block thread while you are calling them. 3. Look on the limits. Using [host.json](https://github.com/Azure/azure-functions-host/wiki/Http-Functions#throttling) you can tweek it. 429 error means that function is busy to process your request, so probably when you writing to table you are not using async and blocking thread
Function apps work very well and scale as it says. It could be because request coming from Single IP and Azure could be considering it DDOS. You can do the following **AzureDevOps Load Test** You can load test using one of the azure service . I am very sure they have better criteria of handling IPs. [Azure DeveOps Load Test](https://learn.microsoft.com/en-us/azure/devops/test/load-test/get-started-simple-cloud-load-test?view=azure-devops) **Provision VM in Azure** The way i normally do is provision the VM (windows 10 pro) in azure and use JMeter to Load test. I have use this method to test and it works fine. You can provision couple of them and subdivide the load. **Use professional Load testing services** If possible you may use services like [Loader.io](https://loader.io/) . They use sophisticated algos to run the load test and provision bunch of VMs to run the same test. **Use Application Insights** If not already you must be using application insights to have a better look from server perspective. Go to live stream and see how many instance it would provision to handle the load test . You can easily look into events and error logs that may be arising and investigate. You can deep dive into each associated dependency and investigate the problem.
50,830,707
I am using Spring security for a Spring Boot application containing a set of Restful services. I have enabled Web security with basic authentication. I would like to have basic authentication enabled except for specific API URL ending with a certain pattern. (For example, a healthcheck API like: /application/\_healthcheck) Code looks like below: ``` @Configuration @EnableWebSecurity public class ApplicationWebSecurityConfigurer extends WebSecurityConfigurerAdapter { @Autowired private AuthenticationEntryPoint authEntryPoint; @Value("${application.security.authentication.username}") private String username; @Value("${application.security.authentication.password}") private String password; @Override protected void configure(final HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests() .anyRequest().authenticated() .and().httpBasic() .authenticationEntryPoint(authEntryPoint); } @Autowired public void configureGlobal(final AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser(username).password(password).roles("USER"); } @Override public void configure(final WebSecurity web) throws Exception { web.ignoring().antMatchers("*/_healthcheck"); } } ``` However, whenever I invoke the .../application/\_healthcheck URL, browser always prompts me to enter credentials. Alternately, I even tried ignoring this path from Spring boot's application.properties (removed the configure method with web.ignoring().antMatchers("\*/\_healthcheck")) but still can't get rid of authentication for this endpoint ``` security.ignored=/_healthcheck,*/_healthcheck ```
2018/06/13
[ "https://Stackoverflow.com/questions/50830707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8031262/" ]
``` @Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers("/application/_healthcheck"); } ``` The difference in above sample and your code is usage of `web` over `http`. Try with web and see if it work { practically it should :) }.
Try this. This will skip authentication part for health URL. ``` @Override protected void configure(final HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests() .antMatchers("*/_healthcheck").permitAll() // added this line .anyRequest().authenticated() .and().httpBasic() .authenticationEntryPoint(authEntryPoint); } ```
50,830,707
I am using Spring security for a Spring Boot application containing a set of Restful services. I have enabled Web security with basic authentication. I would like to have basic authentication enabled except for specific API URL ending with a certain pattern. (For example, a healthcheck API like: /application/\_healthcheck) Code looks like below: ``` @Configuration @EnableWebSecurity public class ApplicationWebSecurityConfigurer extends WebSecurityConfigurerAdapter { @Autowired private AuthenticationEntryPoint authEntryPoint; @Value("${application.security.authentication.username}") private String username; @Value("${application.security.authentication.password}") private String password; @Override protected void configure(final HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests() .anyRequest().authenticated() .and().httpBasic() .authenticationEntryPoint(authEntryPoint); } @Autowired public void configureGlobal(final AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser(username).password(password).roles("USER"); } @Override public void configure(final WebSecurity web) throws Exception { web.ignoring().antMatchers("*/_healthcheck"); } } ``` However, whenever I invoke the .../application/\_healthcheck URL, browser always prompts me to enter credentials. Alternately, I even tried ignoring this path from Spring boot's application.properties (removed the configure method with web.ignoring().antMatchers("\*/\_healthcheck")) but still can't get rid of authentication for this endpoint ``` security.ignored=/_healthcheck,*/_healthcheck ```
2018/06/13
[ "https://Stackoverflow.com/questions/50830707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8031262/" ]
You can create a permission list and use it to disable security. ``` List<String> permitAllEndpointList = Arrays.asList( AUTHENTICATION_URL, REFRESH_TOKEN_URL, EXTERNAL_AUTH_URL, "/swagger-resources", "/swagger-resources/**", "/swagger-ui.html" ); ``` and then add this statement to your HttpSecurity object ``` .and() .authorizeRequests() .antMatchers(permitAllEndpointList.toArray(new String[permitAllEndpointList.size()])) .permitAll() ``` This will solve your issue.
Try this. This will skip authentication part for health URL. ``` @Override protected void configure(final HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests() .antMatchers("*/_healthcheck").permitAll() // added this line .anyRequest().authenticated() .and().httpBasic() .authenticationEntryPoint(authEntryPoint); } ```
35,717,353
I'd like to create a split violin density plot using ggplot, like the fourth example on [this page](https://seaborn.pydata.org/generated/seaborn.violinplot.html) of the seaborn documentation. [![enter image description here](https://i.stack.imgur.com/tYQWX.png)](https://i.stack.imgur.com/tYQWX.png) Here is some data: ``` set.seed(20160229) my_data = data.frame( y=c(rnorm(1000), rnorm(1000, 0.5), rnorm(1000, 1), rnorm(1000, 1.5)), x=c(rep('a', 2000), rep('b', 2000)), m=c(rep('i', 1000), rep('j', 2000), rep('i', 1000)) ) ``` I can plot dodged violins like this: ``` library('ggplot2') ggplot(my_data, aes(x, y, fill=m)) + geom_violin() ``` [![enter image description here](https://i.stack.imgur.com/8De26.png)](https://i.stack.imgur.com/8De26.png) But it's hard to visually compare the widths at different points in the side-by-side distributions. I haven't been able to find any examples of split violins in ggplot - is it possible? I found a [base R graphics solution](https://gist.github.com/mbjoseph/5852613) but the function is quite long and I want to highlight distribution modes, which are easy to add as additional layers in ggplot but will be harder to do if I need to figure out how to edit that function.
2016/03/01
[ "https://Stackoverflow.com/questions/35717353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5942298/" ]
Or, to avoid fiddling with the densities, you could extend [`ggplot2`'s GeomViolin](https://github.com/tidyverse/ggplot2/blob/eecc450f7f13c5144069705ef22feefe0b8f53f7/R/geom-violin.r#L102) like this: ``` GeomSplitViolin <- ggproto("GeomSplitViolin", GeomViolin, draw_group = function(self, data, ..., draw_quantiles = NULL) { data <- transform(data, xminv = x - violinwidth * (x - xmin), xmaxv = x + violinwidth * (xmax - x)) grp <- data[1, "group"] newdata <- plyr::arrange(transform(data, x = if (grp %% 2 == 1) xminv else xmaxv), if (grp %% 2 == 1) y else -y) newdata <- rbind(newdata[1, ], newdata, newdata[nrow(newdata), ], newdata[1, ]) newdata[c(1, nrow(newdata) - 1, nrow(newdata)), "x"] <- round(newdata[1, "x"]) if (length(draw_quantiles) > 0 & !scales::zero_range(range(data$y))) { stopifnot(all(draw_quantiles >= 0), all(draw_quantiles <= 1)) quantiles <- ggplot2:::create_quantile_segment_frame(data, draw_quantiles) aesthetics <- data[rep(1, nrow(quantiles)), setdiff(names(data), c("x", "y")), drop = FALSE] aesthetics$alpha <- rep(1, nrow(quantiles)) both <- cbind(quantiles, aesthetics) quantile_grob <- GeomPath$draw_panel(both, ...) ggplot2:::ggname("geom_split_violin", grid::grobTree(GeomPolygon$draw_panel(newdata, ...), quantile_grob)) } else { ggplot2:::ggname("geom_split_violin", GeomPolygon$draw_panel(newdata, ...)) } }) geom_split_violin <- function(mapping = NULL, data = NULL, stat = "ydensity", position = "identity", ..., draw_quantiles = NULL, trim = TRUE, scale = "area", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE) { layer(data = data, mapping = mapping, stat = stat, geom = GeomSplitViolin, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = list(trim = trim, scale = scale, draw_quantiles = draw_quantiles, na.rm = na.rm, ...)) } ``` And use the new `geom_split_violin` like this: ``` ggplot(my_data, aes(x, y, fill = m)) + geom_split_violin() ``` [![enter image description here](https://i.stack.imgur.com/wL8kc.png)](https://i.stack.imgur.com/wL8kc.png)
**Note**: I think the answer by jan-glx is much better, and most people should use that instead. But sometimes, the manual approach is still helpful to do weird things. --- You can achieve this by calculating the densities yourself beforehand, and then plotting polygons. See below for a rough idea. ### Get densities ``` library(dplyr) pdat <- my_data %>% group_by(x, m) %>% do(data.frame(loc = density(.$y)$x, dens = density(.$y)$y)) ``` ### Flip and offset densities for the groups ``` pdat$dens <- ifelse(pdat$m == 'i', pdat$dens * -1, pdat$dens) pdat$dens <- ifelse(pdat$x == 'b', pdat$dens + 1, pdat$dens) ``` ### Plot ``` ggplot(pdat, aes(dens, loc, fill = m, group = interaction(m, x))) + geom_polygon() + scale_x_continuous(breaks = 0:1, labels = c('a', 'b')) + ylab('density') + theme_minimal() + theme(axis.title.x = element_blank()) ``` ### Result [![enter image description here](https://i.stack.imgur.com/0GByF.png)](https://i.stack.imgur.com/0GByF.png)
35,717,353
I'd like to create a split violin density plot using ggplot, like the fourth example on [this page](https://seaborn.pydata.org/generated/seaborn.violinplot.html) of the seaborn documentation. [![enter image description here](https://i.stack.imgur.com/tYQWX.png)](https://i.stack.imgur.com/tYQWX.png) Here is some data: ``` set.seed(20160229) my_data = data.frame( y=c(rnorm(1000), rnorm(1000, 0.5), rnorm(1000, 1), rnorm(1000, 1.5)), x=c(rep('a', 2000), rep('b', 2000)), m=c(rep('i', 1000), rep('j', 2000), rep('i', 1000)) ) ``` I can plot dodged violins like this: ``` library('ggplot2') ggplot(my_data, aes(x, y, fill=m)) + geom_violin() ``` [![enter image description here](https://i.stack.imgur.com/8De26.png)](https://i.stack.imgur.com/8De26.png) But it's hard to visually compare the widths at different points in the side-by-side distributions. I haven't been able to find any examples of split violins in ggplot - is it possible? I found a [base R graphics solution](https://gist.github.com/mbjoseph/5852613) but the function is quite long and I want to highlight distribution modes, which are easy to add as additional layers in ggplot but will be harder to do if I need to figure out how to edit that function.
2016/03/01
[ "https://Stackoverflow.com/questions/35717353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5942298/" ]
**Note**: I think the answer by jan-glx is much better, and most people should use that instead. But sometimes, the manual approach is still helpful to do weird things. --- You can achieve this by calculating the densities yourself beforehand, and then plotting polygons. See below for a rough idea. ### Get densities ``` library(dplyr) pdat <- my_data %>% group_by(x, m) %>% do(data.frame(loc = density(.$y)$x, dens = density(.$y)$y)) ``` ### Flip and offset densities for the groups ``` pdat$dens <- ifelse(pdat$m == 'i', pdat$dens * -1, pdat$dens) pdat$dens <- ifelse(pdat$x == 'b', pdat$dens + 1, pdat$dens) ``` ### Plot ``` ggplot(pdat, aes(dens, loc, fill = m, group = interaction(m, x))) + geom_polygon() + scale_x_continuous(breaks = 0:1, labels = c('a', 'b')) + ylab('density') + theme_minimal() + theme(axis.title.x = element_blank()) ``` ### Result [![enter image description here](https://i.stack.imgur.com/0GByF.png)](https://i.stack.imgur.com/0GByF.png)
It is now possible to do this with the [introdataviz](https://psyteachr.github.io/introdataviz/advanced-plots.html) package using the [geom\_split\_violin](https://rdrr.io/github/ttecon/ttr/man/geom_split_violin.html) function, which makes it really easy to create these plots. Here is a reproducible example: ```r set.seed(20160229) my_data = data.frame( y=c(rnorm(1000), rnorm(1000, 0.5), rnorm(1000, 1), rnorm(1000, 1.5)), x=c(rep('a', 2000), rep('b', 2000)), m=c(rep('i', 1000), rep('j', 2000), rep('i', 1000)) ) library(ggplot2) # devtools::install_github("psyteachr/introdataviz") library(introdataviz) ggplot(my_data, aes(x = x, y = y, fill = m)) + geom_split_violin() ``` ![](https://i.imgur.com/9cG5qSN.png) Created on 2022-08-24 with [reprex v2.0.2](https://reprex.tidyverse.org) As you can see, it creates a split violin plot. If you want more information and a tutorial of this package, check the link above.
35,717,353
I'd like to create a split violin density plot using ggplot, like the fourth example on [this page](https://seaborn.pydata.org/generated/seaborn.violinplot.html) of the seaborn documentation. [![enter image description here](https://i.stack.imgur.com/tYQWX.png)](https://i.stack.imgur.com/tYQWX.png) Here is some data: ``` set.seed(20160229) my_data = data.frame( y=c(rnorm(1000), rnorm(1000, 0.5), rnorm(1000, 1), rnorm(1000, 1.5)), x=c(rep('a', 2000), rep('b', 2000)), m=c(rep('i', 1000), rep('j', 2000), rep('i', 1000)) ) ``` I can plot dodged violins like this: ``` library('ggplot2') ggplot(my_data, aes(x, y, fill=m)) + geom_violin() ``` [![enter image description here](https://i.stack.imgur.com/8De26.png)](https://i.stack.imgur.com/8De26.png) But it's hard to visually compare the widths at different points in the side-by-side distributions. I haven't been able to find any examples of split violins in ggplot - is it possible? I found a [base R graphics solution](https://gist.github.com/mbjoseph/5852613) but the function is quite long and I want to highlight distribution modes, which are easy to add as additional layers in ggplot but will be harder to do if I need to figure out how to edit that function.
2016/03/01
[ "https://Stackoverflow.com/questions/35717353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5942298/" ]
Or, to avoid fiddling with the densities, you could extend [`ggplot2`'s GeomViolin](https://github.com/tidyverse/ggplot2/blob/eecc450f7f13c5144069705ef22feefe0b8f53f7/R/geom-violin.r#L102) like this: ``` GeomSplitViolin <- ggproto("GeomSplitViolin", GeomViolin, draw_group = function(self, data, ..., draw_quantiles = NULL) { data <- transform(data, xminv = x - violinwidth * (x - xmin), xmaxv = x + violinwidth * (xmax - x)) grp <- data[1, "group"] newdata <- plyr::arrange(transform(data, x = if (grp %% 2 == 1) xminv else xmaxv), if (grp %% 2 == 1) y else -y) newdata <- rbind(newdata[1, ], newdata, newdata[nrow(newdata), ], newdata[1, ]) newdata[c(1, nrow(newdata) - 1, nrow(newdata)), "x"] <- round(newdata[1, "x"]) if (length(draw_quantiles) > 0 & !scales::zero_range(range(data$y))) { stopifnot(all(draw_quantiles >= 0), all(draw_quantiles <= 1)) quantiles <- ggplot2:::create_quantile_segment_frame(data, draw_quantiles) aesthetics <- data[rep(1, nrow(quantiles)), setdiff(names(data), c("x", "y")), drop = FALSE] aesthetics$alpha <- rep(1, nrow(quantiles)) both <- cbind(quantiles, aesthetics) quantile_grob <- GeomPath$draw_panel(both, ...) ggplot2:::ggname("geom_split_violin", grid::grobTree(GeomPolygon$draw_panel(newdata, ...), quantile_grob)) } else { ggplot2:::ggname("geom_split_violin", GeomPolygon$draw_panel(newdata, ...)) } }) geom_split_violin <- function(mapping = NULL, data = NULL, stat = "ydensity", position = "identity", ..., draw_quantiles = NULL, trim = TRUE, scale = "area", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE) { layer(data = data, mapping = mapping, stat = stat, geom = GeomSplitViolin, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = list(trim = trim, scale = scale, draw_quantiles = draw_quantiles, na.rm = na.rm, ...)) } ``` And use the new `geom_split_violin` like this: ``` ggplot(my_data, aes(x, y, fill = m)) + geom_split_violin() ``` [![enter image description here](https://i.stack.imgur.com/wL8kc.png)](https://i.stack.imgur.com/wL8kc.png)
It is now possible to do this with the [introdataviz](https://psyteachr.github.io/introdataviz/advanced-plots.html) package using the [geom\_split\_violin](https://rdrr.io/github/ttecon/ttr/man/geom_split_violin.html) function, which makes it really easy to create these plots. Here is a reproducible example: ```r set.seed(20160229) my_data = data.frame( y=c(rnorm(1000), rnorm(1000, 0.5), rnorm(1000, 1), rnorm(1000, 1.5)), x=c(rep('a', 2000), rep('b', 2000)), m=c(rep('i', 1000), rep('j', 2000), rep('i', 1000)) ) library(ggplot2) # devtools::install_github("psyteachr/introdataviz") library(introdataviz) ggplot(my_data, aes(x = x, y = y, fill = m)) + geom_split_violin() ``` ![](https://i.imgur.com/9cG5qSN.png) Created on 2022-08-24 with [reprex v2.0.2](https://reprex.tidyverse.org) As you can see, it creates a split violin plot. If you want more information and a tutorial of this package, check the link above.
44,414,141
I found a tutorial on spring-kafka where they created a producer and consumer. However, the program was run through a test case. As the test case ends, the consumer stops. How to ensure the consumer keeps running in the backgorund so that I can test some messages from my terminal command line. SpringKafkaExampleApplication.java ``` package com.howtoprogram.kafka; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringKafkaExampleApplication { public static void main(String[] args) { SpringApplication.run(SpringKafkaExampleApplication.class, args); } } ``` KafkaProducerConfig.java ``` package com.howtoprogram.kafka; import java.util.HashMap; import java.util.Map; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.serialization.StringSerializer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.kafka.annotation.EnableKafka; import org.springframework.kafka.core.DefaultKafkaProducerFactory; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.kafka.core.ProducerFactory; @Configuration @EnableKafka public class KafkaProducerConfig { @Bean public ProducerFactory<String, String> producerFactory() { return new DefaultKafkaProducerFactory<>(producerConfigs()); } @Bean public Map<String, Object> producerConfigs() { Map<String, Object> props = new HashMap<>(); props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); props.put(ProducerConfig.RETRIES_CONFIG, 0); props.put(ProducerConfig.BATCH_SIZE_CONFIG, 16384); props.put(ProducerConfig.LINGER_MS_CONFIG, 1); props.put(ProducerConfig.BUFFER_MEMORY_CONFIG, 33554432); props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class); props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class); return props; } @Bean public KafkaTemplate<String, String> kafkaTemplate() { return new KafkaTemplate<String, String>(producerFactory()); } } ``` KafkaConsumerConfig.java ``` package com.howtoprogram.kafka; import java.util.HashMap; import java.util.Map; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.common.serialization.StringDeserializer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.kafka.annotation.EnableKafka; import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory; import org.springframework.kafka.config.KafkaListenerContainerFactory; import org.springframework.kafka.core.ConsumerFactory; import org.springframework.kafka.core.DefaultKafkaConsumerFactory; import org.springframework.kafka.listener.ConcurrentMessageListenerContainer; @Configuration @EnableKafka public class KafkaConsumerConfig { @Bean KafkaListenerContainerFactory<ConcurrentMessageListenerContainer<String, String>> kafkaListenerContainerFactory() { ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>(); factory.setConsumerFactory(consumerFactory()); factory.setConcurrency(3); factory.getContainerProperties().setPollTimeout(3000); return factory; } @Bean public ConsumerFactory<String, String> consumerFactory() { return new DefaultKafkaConsumerFactory<>(consumerConfigs()); } @Bean public Map<String, Object> consumerConfigs() { Map<String, Object> propsMap = new HashMap<>(); propsMap.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); propsMap.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false); propsMap.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "100"); propsMap.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, "15000"); propsMap.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); propsMap.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); propsMap.put(ConsumerConfig.GROUP_ID_CONFIG, "group1"); propsMap.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); return propsMap; } @Bean public Listener listener() { return new Listener(); } } ``` Listener.java ``` package com.howtoprogram.kafka; import java.util.concurrent.CountDownLatch; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.springframework.kafka.annotation.KafkaListener; public class Listener { public final CountDownLatch countDownLatch1 = new CountDownLatch(1); @KafkaListener(id = "foo", topics = "topic1", group = "group1") public void listen(ConsumerRecord<?, ?> record) { System.out.println(record); countDownLatch1.countDown(); } } ``` SpringKafkaExampleApplicationTests.java ``` package com.howtoprogram.kafka; import static org.assertj.core.api.Assertions.assertThat; import java.util.concurrent.TimeUnit; import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.kafka.support.SendResult; import org.springframework.kafka.test.rule.KafkaEmbedded; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.util.concurrent.ListenableFuture; import org.springframework.util.concurrent.ListenableFutureCallback; @RunWith(SpringRunner.class) @SpringBootTest public class SpringKafkaExampleApplicationTests { @Autowired private KafkaTemplate<String, String> kafkaTemplate; @Autowired private Listener listener; @Test public void contextLoads() throws InterruptedException { ListenableFuture<SendResult<String, String>> future = kafkaTemplate.send("topic1", "ABC"); future.addCallback(new ListenableFutureCallback<SendResult<String, String>>() { @Override public void onSuccess(SendResult<String, String> result) { System.out.println("success"); } @Override public void onFailure(Throwable ex) { System.out.println("failed"); } }); System.out.println(Thread.currentThread().getId()); assertThat(this.listener.countDownLatch1.await(60, TimeUnit.SECONDS)).isTrue(); } } ``` Please help!
2017/06/07
[ "https://Stackoverflow.com/questions/44414141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5188341/" ]
We run our Kafka application in a `while(true)` loop with an `@Scheduled` on a Spring Bean : <https://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html> This way you can also delay the consumption of messages when the rest of your application is initialising. ```java @Scheduled(initialDelay = 5000L, fixedDelay = 10000L) public void process() { while (keepRunning) { try { ConsumerRecords<String, String> records = consumer.poll(500); // do processing here } } } ``` The `fixedDelay` is a bit strange. This value needs to be available, but is effectively ignored. It might be tempting to start the consumer in the `@PostConstruct` but this way Spring keeps thinking the bean is in the init-phase. (so don't do this as Artem Bilan mentions below)
Add this code to your `main` after `SpringApplication.run()`: ``` System.out.println("Hit 'Enter' to terminate"); System.in.read(); ctx.close(); System.exit(0); ``` And your program won't exit until you hit the Enter button in console.
6,149,673
Recently I started Unit testing my application. This project (in Xcode4) was created without a unit test bundle so I had to set it up. I have followed the steps from here: <http://cocoawithlove.com/2009/12/sample-mac-application-with-complete.html> And It was working well for simple classes but now I am trying to test a class that depends on another and that on another, etc. First I got a linker error so I added `*.m` files to the test case target but now I get a warning for every class I am trying to test: > > Class Foo is implemented in both MyApp > and MyAppTestCase. One of the two will > be used. Which one is undefined. > > > I wonder why is that? How can I solve this? Maybe I missed something when setting the unit test target? ### Edit - The Solution * Set "Bundle Loader" correctly to `$(BUILT_PRODUCTS_DIR)/AppName.app/AppName` * Set "Symbols Hidden by Default" to **NO** (in Build Settings of the target application). This is where the linker errors come from because it is YES by default!. I've been struggling with this for so long!. Source: [Linking error for unit testing with XCode 4?](https://stackoverflow.com/questions/6461074/linking-error-for-unit-testing-with-xcode-4)
2011/05/27
[ "https://Stackoverflow.com/questions/6149673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/149008/" ]
> > > > > > Class Foo is implemented in both MyApp and MyAppTestCase. One of the two will be used. Which one is undefined. > > > > > > > > > I wonder why is that? > > > because both images (the app and the unit test bundle) define the implementation of the class. the class is dynamically loaded into the objc runtime. the objc runtime uses a flat namespace. how this works: * the binary is loaded, starting with its dependencies * as each binary is loaded, the objc classes register with the objc runtime * if a class with a specific name is loaded twice, the behaviour is undefined. one implementation of a class (with identical names) can be loaded into the objc runtime. the *typical* problem here is that you will be returned one implementation - your app will likely crash when the type conflicts (when the class does not come from the same source file). you typically avoid this by either renaming a class, or export the class in one image. renaming the class obviously does not apply to your case. you have one file `Foo.m` which is being compiled, exported, and loaded by two images when it should be in one. this should be interpreted by you as a duplicate symbol linker error. even though the implementation is the same source file (and the implementation is the same) - this a problem that you must fix. > > How can I solve this? > > > if `Foo.m` is a class of the app, you have to remove (do not compile and link) `Foo.m` from the unit test. if it's part of the unit test, then do not compile and link it into the unit test target. then, follow the instructions in the post for linking/loading your unit test to the app. it's in this general area of the post: *where "WhereIsMyMac" is the name of the application you're unit testing. This will let the testing target link against the application (so you don't get linker errors when compiling).* the important part is that your test files are compiled in the unit test target (only), and your app's classes are compiled and linked into the app. you can't just add them - they link and load dynamically. > > Maybe I missed something when setting the unit test target? > > > From the article you linked: > > > > > > Note: The testing target is a separate target. This means that you need to be careful of target membership. All application source files should be added to the application target only. Test code files should be added to the testing target only. > > > > > > > > > the part that you got wrong is probably the link and load phases of the unit test bundle.
The reason is that you override `RUNPATH_SEARCH_PATHS` of your App Target`s build setting defined in other target. **Solution:** > > Go to your App Target and find `RUNPATH_SEARCH_PATHS` build setting and use there `$(inherited)` flag for both: **Debug** and **Release** > > >
6,149,673
Recently I started Unit testing my application. This project (in Xcode4) was created without a unit test bundle so I had to set it up. I have followed the steps from here: <http://cocoawithlove.com/2009/12/sample-mac-application-with-complete.html> And It was working well for simple classes but now I am trying to test a class that depends on another and that on another, etc. First I got a linker error so I added `*.m` files to the test case target but now I get a warning for every class I am trying to test: > > Class Foo is implemented in both MyApp > and MyAppTestCase. One of the two will > be used. Which one is undefined. > > > I wonder why is that? How can I solve this? Maybe I missed something when setting the unit test target? ### Edit - The Solution * Set "Bundle Loader" correctly to `$(BUILT_PRODUCTS_DIR)/AppName.app/AppName` * Set "Symbols Hidden by Default" to **NO** (in Build Settings of the target application). This is where the linker errors come from because it is YES by default!. I've been struggling with this for so long!. Source: [Linking error for unit testing with XCode 4?](https://stackoverflow.com/questions/6461074/linking-error-for-unit-testing-with-xcode-4)
2011/05/27
[ "https://Stackoverflow.com/questions/6149673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/149008/" ]
For me, all I needed to do was uncheck the checkbox that makes the Foo class a member of the unit test target. It should not be a member of both targets, and should look like this: ![Target Membership](https://i.stack.imgur.com/6OC9c.png) In case you can't see the image, it's a screenshot of the Xcode "Target Membership" pane. There are two targets: one with an "A" application icon and the test name. The other is the unit test target, and has a unit test icon: ``` Target Membership [X] Foo [ ] FooTests ```
The reason is that you override `RUNPATH_SEARCH_PATHS` of your App Target`s build setting defined in other target. **Solution:** > > Go to your App Target and find `RUNPATH_SEARCH_PATHS` build setting and use there `$(inherited)` flag for both: **Debug** and **Release** > > >
6,149,673
Recently I started Unit testing my application. This project (in Xcode4) was created without a unit test bundle so I had to set it up. I have followed the steps from here: <http://cocoawithlove.com/2009/12/sample-mac-application-with-complete.html> And It was working well for simple classes but now I am trying to test a class that depends on another and that on another, etc. First I got a linker error so I added `*.m` files to the test case target but now I get a warning for every class I am trying to test: > > Class Foo is implemented in both MyApp > and MyAppTestCase. One of the two will > be used. Which one is undefined. > > > I wonder why is that? How can I solve this? Maybe I missed something when setting the unit test target? ### Edit - The Solution * Set "Bundle Loader" correctly to `$(BUILT_PRODUCTS_DIR)/AppName.app/AppName` * Set "Symbols Hidden by Default" to **NO** (in Build Settings of the target application). This is where the linker errors come from because it is YES by default!. I've been struggling with this for so long!. Source: [Linking error for unit testing with XCode 4?](https://stackoverflow.com/questions/6461074/linking-error-for-unit-testing-with-xcode-4)
2011/05/27
[ "https://Stackoverflow.com/questions/6149673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/149008/" ]
If you are using Cocoapods, your podfile only needs the dependencies in the section for the main target, not the test targets. If you do add duplicate dependencies for the test targets, you'll get the OP's error message. ``` target 'MyProject' do pod 'Parse' end target 'MyProjectTests' do end target 'MyProjectUITests' do end ```
Come across the same issues, My situation is Class NSNotification is implemented in both /System/Library/Frameworks/Foundation.framework/Foundation, is there any dude come across the same issue, any direction or advise will be appriciated.
6,149,673
Recently I started Unit testing my application. This project (in Xcode4) was created without a unit test bundle so I had to set it up. I have followed the steps from here: <http://cocoawithlove.com/2009/12/sample-mac-application-with-complete.html> And It was working well for simple classes but now I am trying to test a class that depends on another and that on another, etc. First I got a linker error so I added `*.m` files to the test case target but now I get a warning for every class I am trying to test: > > Class Foo is implemented in both MyApp > and MyAppTestCase. One of the two will > be used. Which one is undefined. > > > I wonder why is that? How can I solve this? Maybe I missed something when setting the unit test target? ### Edit - The Solution * Set "Bundle Loader" correctly to `$(BUILT_PRODUCTS_DIR)/AppName.app/AppName` * Set "Symbols Hidden by Default" to **NO** (in Build Settings of the target application). This is where the linker errors come from because it is YES by default!. I've been struggling with this for so long!. Source: [Linking error for unit testing with XCode 4?](https://stackoverflow.com/questions/6461074/linking-error-for-unit-testing-with-xcode-4)
2011/05/27
[ "https://Stackoverflow.com/questions/6149673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/149008/" ]
> > > > > > Class Foo is implemented in both MyApp and MyAppTestCase. One of the two will be used. Which one is undefined. > > > > > > > > > I wonder why is that? > > > because both images (the app and the unit test bundle) define the implementation of the class. the class is dynamically loaded into the objc runtime. the objc runtime uses a flat namespace. how this works: * the binary is loaded, starting with its dependencies * as each binary is loaded, the objc classes register with the objc runtime * if a class with a specific name is loaded twice, the behaviour is undefined. one implementation of a class (with identical names) can be loaded into the objc runtime. the *typical* problem here is that you will be returned one implementation - your app will likely crash when the type conflicts (when the class does not come from the same source file). you typically avoid this by either renaming a class, or export the class in one image. renaming the class obviously does not apply to your case. you have one file `Foo.m` which is being compiled, exported, and loaded by two images when it should be in one. this should be interpreted by you as a duplicate symbol linker error. even though the implementation is the same source file (and the implementation is the same) - this a problem that you must fix. > > How can I solve this? > > > if `Foo.m` is a class of the app, you have to remove (do not compile and link) `Foo.m` from the unit test. if it's part of the unit test, then do not compile and link it into the unit test target. then, follow the instructions in the post for linking/loading your unit test to the app. it's in this general area of the post: *where "WhereIsMyMac" is the name of the application you're unit testing. This will let the testing target link against the application (so you don't get linker errors when compiling).* the important part is that your test files are compiled in the unit test target (only), and your app's classes are compiled and linked into the app. you can't just add them - they link and load dynamically. > > Maybe I missed something when setting the unit test target? > > > From the article you linked: > > > > > > Note: The testing target is a separate target. This means that you need to be careful of target membership. All application source files should be added to the application target only. Test code files should be added to the testing target only. > > > > > > > > > the part that you got wrong is probably the link and load phases of the unit test bundle.
If you are using Cocoapods, your podfile only needs the dependencies in the section for the main target, not the test targets. If you do add duplicate dependencies for the test targets, you'll get the OP's error message. ``` target 'MyProject' do pod 'Parse' end target 'MyProjectTests' do end target 'MyProjectUITests' do end ```
6,149,673
Recently I started Unit testing my application. This project (in Xcode4) was created without a unit test bundle so I had to set it up. I have followed the steps from here: <http://cocoawithlove.com/2009/12/sample-mac-application-with-complete.html> And It was working well for simple classes but now I am trying to test a class that depends on another and that on another, etc. First I got a linker error so I added `*.m` files to the test case target but now I get a warning for every class I am trying to test: > > Class Foo is implemented in both MyApp > and MyAppTestCase. One of the two will > be used. Which one is undefined. > > > I wonder why is that? How can I solve this? Maybe I missed something when setting the unit test target? ### Edit - The Solution * Set "Bundle Loader" correctly to `$(BUILT_PRODUCTS_DIR)/AppName.app/AppName` * Set "Symbols Hidden by Default" to **NO** (in Build Settings of the target application). This is where the linker errors come from because it is YES by default!. I've been struggling with this for so long!. Source: [Linking error for unit testing with XCode 4?](https://stackoverflow.com/questions/6461074/linking-error-for-unit-testing-with-xcode-4)
2011/05/27
[ "https://Stackoverflow.com/questions/6149673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/149008/" ]
The reason is that you override `RUNPATH_SEARCH_PATHS` of your App Target`s build setting defined in other target. **Solution:** > > Go to your App Target and find `RUNPATH_SEARCH_PATHS` build setting and use there `$(inherited)` flag for both: **Debug** and **Release** > > >
Come across the same issues, My situation is Class NSNotification is implemented in both /System/Library/Frameworks/Foundation.framework/Foundation, is there any dude come across the same issue, any direction or advise will be appriciated.
6,149,673
Recently I started Unit testing my application. This project (in Xcode4) was created without a unit test bundle so I had to set it up. I have followed the steps from here: <http://cocoawithlove.com/2009/12/sample-mac-application-with-complete.html> And It was working well for simple classes but now I am trying to test a class that depends on another and that on another, etc. First I got a linker error so I added `*.m` files to the test case target but now I get a warning for every class I am trying to test: > > Class Foo is implemented in both MyApp > and MyAppTestCase. One of the two will > be used. Which one is undefined. > > > I wonder why is that? How can I solve this? Maybe I missed something when setting the unit test target? ### Edit - The Solution * Set "Bundle Loader" correctly to `$(BUILT_PRODUCTS_DIR)/AppName.app/AppName` * Set "Symbols Hidden by Default" to **NO** (in Build Settings of the target application). This is where the linker errors come from because it is YES by default!. I've been struggling with this for so long!. Source: [Linking error for unit testing with XCode 4?](https://stackoverflow.com/questions/6461074/linking-error-for-unit-testing-with-xcode-4)
2011/05/27
[ "https://Stackoverflow.com/questions/6149673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/149008/" ]
For me, all I needed to do was uncheck the checkbox that makes the Foo class a member of the unit test target. It should not be a member of both targets, and should look like this: ![Target Membership](https://i.stack.imgur.com/6OC9c.png) In case you can't see the image, it's a screenshot of the Xcode "Target Membership" pane. There are two targets: one with an "A" application icon and the test name. The other is the unit test target, and has a unit test icon: ``` Target Membership [X] Foo [ ] FooTests ```
Come across the same issues, My situation is Class NSNotification is implemented in both /System/Library/Frameworks/Foundation.framework/Foundation, is there any dude come across the same issue, any direction or advise will be appriciated.
6,149,673
Recently I started Unit testing my application. This project (in Xcode4) was created without a unit test bundle so I had to set it up. I have followed the steps from here: <http://cocoawithlove.com/2009/12/sample-mac-application-with-complete.html> And It was working well for simple classes but now I am trying to test a class that depends on another and that on another, etc. First I got a linker error so I added `*.m` files to the test case target but now I get a warning for every class I am trying to test: > > Class Foo is implemented in both MyApp > and MyAppTestCase. One of the two will > be used. Which one is undefined. > > > I wonder why is that? How can I solve this? Maybe I missed something when setting the unit test target? ### Edit - The Solution * Set "Bundle Loader" correctly to `$(BUILT_PRODUCTS_DIR)/AppName.app/AppName` * Set "Symbols Hidden by Default" to **NO** (in Build Settings of the target application). This is where the linker errors come from because it is YES by default!. I've been struggling with this for so long!. Source: [Linking error for unit testing with XCode 4?](https://stackoverflow.com/questions/6461074/linking-error-for-unit-testing-with-xcode-4)
2011/05/27
[ "https://Stackoverflow.com/questions/6149673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/149008/" ]
> > > > > > Class Foo is implemented in both MyApp and MyAppTestCase. One of the two will be used. Which one is undefined. > > > > > > > > > I wonder why is that? > > > because both images (the app and the unit test bundle) define the implementation of the class. the class is dynamically loaded into the objc runtime. the objc runtime uses a flat namespace. how this works: * the binary is loaded, starting with its dependencies * as each binary is loaded, the objc classes register with the objc runtime * if a class with a specific name is loaded twice, the behaviour is undefined. one implementation of a class (with identical names) can be loaded into the objc runtime. the *typical* problem here is that you will be returned one implementation - your app will likely crash when the type conflicts (when the class does not come from the same source file). you typically avoid this by either renaming a class, or export the class in one image. renaming the class obviously does not apply to your case. you have one file `Foo.m` which is being compiled, exported, and loaded by two images when it should be in one. this should be interpreted by you as a duplicate symbol linker error. even though the implementation is the same source file (and the implementation is the same) - this a problem that you must fix. > > How can I solve this? > > > if `Foo.m` is a class of the app, you have to remove (do not compile and link) `Foo.m` from the unit test. if it's part of the unit test, then do not compile and link it into the unit test target. then, follow the instructions in the post for linking/loading your unit test to the app. it's in this general area of the post: *where "WhereIsMyMac" is the name of the application you're unit testing. This will let the testing target link against the application (so you don't get linker errors when compiling).* the important part is that your test files are compiled in the unit test target (only), and your app's classes are compiled and linked into the app. you can't just add them - they link and load dynamically. > > Maybe I missed something when setting the unit test target? > > > From the article you linked: > > > > > > Note: The testing target is a separate target. This means that you need to be careful of target membership. All application source files should be added to the application target only. Test code files should be added to the testing target only. > > > > > > > > > the part that you got wrong is probably the link and load phases of the unit test bundle.
For me, all I needed to do was uncheck the checkbox that makes the Foo class a member of the unit test target. It should not be a member of both targets, and should look like this: ![Target Membership](https://i.stack.imgur.com/6OC9c.png) In case you can't see the image, it's a screenshot of the Xcode "Target Membership" pane. There are two targets: one with an "A" application icon and the test name. The other is the unit test target, and has a unit test icon: ``` Target Membership [X] Foo [ ] FooTests ```