Is there a name for a chord which combines the major and minor thirds of the root?

Question: I noticed while noodling on my acoustic guitar that playing Cm using the Am shape barred on 3rd fret, that opening the high E string gives a pleasingly discordant sound. I realised the E comes from the major C chord.
So for C we have the notes C, E, G from C-major and C, Eb, G from C-minor, giving us C, Eb, E, G in my chord.
Does this chord have a particular name - is it in any way special - or depending on the key would you just call it Cm(add E)or something?
Comment: The C minor triad is C,Eb and G. Not E,D# and G. I know that Eb and D# are the same note, but Eb is a minor third and D# is a augmented second.
Comment: You could simply be playing a bluesy Eb melody note over a C triad. This is probably by far the most common reason that you'd hear this sonority, and it's not something that you'd be able to analyze successfully within the framework of traditional western harmony.
Answer: I'd  call it a Cadd#9 and there's  a few reasons why.
First of all if you think about the chord in terms of extensions a #9 is rather common and if you added a Bb to the chord you described people would hands down call that a C7#9 which is a common altered dominant chord.
Second in general when naming chords we typically like to compare the notes to the naturally occurring in the major scale (with the exception of the 7th which we typically preferred lowered). Combine this with the fact that we build and name chords in stacks of thirds makes the major third much more preferable to include in a chord then a minor third.
For example including all extensions, a C13 would include the notes:

C  E  G  Bb  D  F  A

As you can see this includes all naturally named notes of a scale excluding B which has been modified to Bb. Let's take the notes you've given and see how they line up.

C  Eb  G  E

We quickly see the root is there, but we are left with two thirds. Since the natural major 3rd is typically preferred, we will convert the minor third into it's enharmonic equivalent D# and since there is no seventh it becomes an added tone. This is why you see #9 sometimes, but you'll never see a b11 as the major 3rd is the default in chord construction.

There is an alternative way to view the chord that I talk about in this question, but it's a lot less neat. Pretty much If you view the E as the root, you could view the Eb as a D# which is a major 7th and the C as a B# which is an augmented 5h so you could call it a E#mM7#5/C.
Comment: Yeah, I think this is the best name as well. Some people also call it in the "Hendrix chord" because it was a major part of his harmonic vocabulary. In post-tonal and neo-tonal discussions it is sometimes called a "split third".
Comment: Would it make a difference what key the song was in? e/g/ if you were in C minor wouldn't it make sense to call it a Cm-something chord?
Comment: @Mr.Boy Most likely not. There can be only one third in a chord and ever heard of anyone using a b11 in a chord? There's a reason why which is another reason I'm about to edit in.
Answer: While most pop and jazz musicians would call this chord a ♯9 chord of some sort, classical people may say that the chord has split thirds, and a theory professor would say that the chord is the pitch class set [0,3,4,7]. There are a lot of ways to rationalize this chord, and any of these would be acceptable depending on who you speak to. If you're just talking about a C major triad with an E♭ on top, then I would write C(add♯9). If you are talking about a C minor triad with E natural on top, then I would write (and I know I will get flak for this) Cm(maj10). Other people have stated that you might not want to have a Cm triad with a major 10 above it; this is because an interval of a minor ninth is created by the E♭/E combination, which is particularity jarring (though, again, not musically illegal) and obscures the sense of major versus minor. (The minor 7th created by E/E♭ is less jarring and creates more of a bluesy/funky kind of sound).
[However, if they are right next to each other without the octave distance between them, I would probably still write C(add♯9).]
Comment: One small note: the Eb–E interval would usually be considered an *augmented octave* — it would be a minor ninth if the bottom note were considered as D# instead of Eb.
Comment: Your ear can't tell the difference.
Comment: While the minor 9th (or augmented unison) may clash more by itself than a major 7th (or diminished unison), we often voice chords in such a way that a minor ninth is created, and it clashes no more than the major 7th. In this particular example, I say CEbGe clashes no more than CEGeb. Even if you add the octave C to reduce the clashing, they both seem to clash about the same. And even all that is isolation without dealing with horizontal harmony (the chords around it). Those matter even more.
Comment: If I were writing a chord sheet, I'd call it a Cadd#2, not Cadd#9. I think the default is to give the split thirds some room, so I would want to specify to not do this.
Answer: Putting in the b7 as well makes it what is affectionately known as the Hendrix chord - 7#9. He didn't invent it - just loved using it. It sounds like the major and minor third are played within the same chord, but technically it's written as a #9. Usually 9ths will incorporate a 7th as well.In this case, a flat 7th. Without the 7th, it'll be, as already stated, add#9, as it's just a triad plus a sharpened 9 note.
Answer: When you swap the G for the E, you get rid of a perfect 5th and get a major 3rd. That 5th is being played anyway on fret 5, D string. You end up with:

Root
Minor 3rd
Major 3rd
Perfect 5th

If you want to see it strictly as a minor C chord, the E is a major 10th tension. This tension is not diatonic to any minor mode from the major scale, so it is an "outside" tension.
It all depends on the harmonic context, but you can also see this chord as a Dominant #9 chord with the 7th ommited. The minor 3rd can be seen as an augmented 9th (#9). That would be a C7#9. Since your chord doesn't have the minor 7th, maybe Cadd#9 would be more appropriate. You could also play the Bb in fret 3 of string G, although a more common fingering would be X3234X, the "hendrix" chord, which ommits the 5th. You should try this one out. Pretty common in jazz as well.
Dominant chords are built on the 5th degree of the major scale. They are formed by a major triad plus a minor 7th chord tone. A C7 belongs to the key of F major, with the notes C, E, G and Bb. That #9 is a D#, an altered tension that doesn't belong to the F major scale, but it's widely used to add dissonance to the dominant chord, even though it's not diatonic to the major scale.
C7#9:

1 - Root, C
3 - Major 3rd, E
5 - Perfect 5th, G
7 - Minor 7th, Bb (you left this one out)
#9 - Augmented 9th, D# (not diatonic to F major, look into altered harmony)

If this didn't help at all, I suggest that you take a look into basic harmony, especially  the diatonic 7th chord sequence of the major scale. Once you understand it, study altered harmony.
Answer: The Eb more typically comes at the top. I hear it much more as a flattened third than a sharpened 9th, so I prefer to label it C7(b10).  People who want every chord to be built out of a pile of thirds may strongly disagree :-)
Comment: You may hear it as a minor third because you're more used to tha min3 sound. However, it isn't and can't be., It's #9 all day long. My cheap keyboard sounds like a cathedral organ, but there are no pipes!
Comment: No, no, no!  Theory describes, it doesn't command.  If you hear it as a flattened third, it IS a flattened third, even if that doesn't fit in with a preconceived system of harmony. When you play the blues, is it full of sharpened supertonics?  No, of course not!


Entry level guitar amp, as a gig amp for hobbyist

Question: Is it a very bad idea to use an entry-level 15W rms guitar amp (mini-cubes i.e. amp+cabinet combo, which otherwise is quiteloud), for as a small gig-amp into which one uses a passive 4-channel mono mixer, that is connected to an acoustic guitar with clip-on pickup, and 3 microphones (shure s-58 clones). One of the microphones would be used for vocals + harmonica, other pair for the drums.
I have all of the equipment, minus the 4-channel mono mixer, which I am planning on buying, and thus this question. Microphones when directly connected to the guitar amp, sound fine, when all the settings (treble, bass are at mid-point, and overdrive is turned off). In these settings, the guitar sounds neutral, and close to the natural side of the acoustic (not that I have a fine musical ear to make out the difference).
As mentioned in question, the gig is something that I intend to start doing in small outdoor gathering settings, and it is all hobbyist level.
Comment: The drums alone,without miking, will be louder than the output of a 15amp amp
Answer: I think it's awesome that you are making music with your friends and playing with a band.  I can understand what you are trying to accomplish.  But I don't believe you will be happy with the results from a 15 watt amp speaker combo.  Trying to provide sound reinforcement for vocals, harmonica, drums and guitar with a 15 watt amp is simply asking way too much out of the amplifier for good results.
You should be able to get all your mics and guitar to emit sound through the amp's speakers, but the quality and volume of the overall sound is not going to be stellar by any stretch of the imagination.
This setup might work fine in your garage or living room, but in that scenario, you won't really even need amplification.  And as Tim mentioned, miking drums to play through a 15 watt amp makes no sense.  I don't even mic the acoustic drums in my band playing through a 1200 watt PA system unless we are playing an outdoor gig where the demands are greater due to no walls to reflect the sound back and greater ambient noise (traffic, airplanes, wind blowing, etc.).  In most places we play (restaurants, sports bars) the drummer has to hold back or use hot rods or brushes to keep from being too loud in the mix.
Most 15 watt amps are optimized to do one thing well - amplify a single guitar which in the absence of an amplifier, would not be heard.  The speakers are not intended to be "full range" as it is anticipated by the manufacturer that the only frequency that needs to be reproduced, is that of an electric guitar.
There are some two channel acoustic amps which are designed to amplify both vocals and a guitar, but the smaller less powerful versions of those yield the most satisfactory results with just one mic and one guitar.
You will get more useful results from a small powered PA speaker with at least 100 watts.  In general, the more powerful PA speakers will sound better.  You could probably find a used Mackie Thump 1000 watt 12 inch full range powered PA speaker for about $175 - $200 US or a Behringer Eurolive B110D 200 Watt Powered Speaker with a 10 inch speaker used for around $150. US.  All of these Powered Speakers have inputs for both a guitar and microphone and you can feed a mix into them through a small unpowered mixer as you are contemplating.
This speaker by Harbinger would also work and it is often on sale new for $150. (I have one)  Harbinger Powered PA Speaker at Guitar Center
And if you shop around - you might find a deal like this for the Harbinger Powered PA Speaker
Good luck!
Comment: My first band, in '60/'61 all went through one little amp - bass played on a 6-string guitar! True, it didn't work well, but it was early days, and at 14 it was all we could afford...
Answer: A 15watt boutique type amp with a decent sized speaker (!0" minimum) may do, but a cheapo won't. Drums wouldn't really need micing up, and that size amp wouldn't do justice. Playing outdoors soaks up an awful lot of sound, so 40watt would be preferable. Vocals through a small speaker won't work too well, either. A mixer is a good idea, though.


django how to add a MinLengthValidator validator in a form

Question: I have a search form and I want to validate that the input 'seach_word' has at least 4 letters. I'm getting this error when I'm trying to validate my forms
The response content must be rendered before it can be iterated over.
#views.py
class SearchFormView(FormView):
    form_class = PostSearchForm
    template_name = 'lineup/post_search.html'

    def form_valid(self, form):
        schWord = form.cleaned_data['search_word']
        search_type = form.cleaned_data['search_type']
        context = {}

        if search_type == 'store':
            post_list = Store.objects.filter(
                  Q(cie_name__icontains=schWord)).distinct()
            context['object_type'] = 'store'
            context['object_list'] = post_list

        if search_type == 'city':
            post_list = Address.objects.filter(
                  Q(city__icontains=schWord)).distinct()
            context['object_type'] = 'city'
            context['object_list'] = post_list

        context['form'] = form
        context['search_term'] = schWord
        return render(self.request, self.template_name, context)

    def form_invalid(self, form):
        schWord = form.cleaned_data['search_word']
        messages.add_message(
         self.request, messages.WARNING, _('Please correct this...'))
        context =  super(SearchFormView, self).form_invalid(form)
        return render(self.request, self.template_name, context)

content of forms.py
#forms.py
class PostSearchForm(forms.Form):
    SEARCH_TYPE_CHOICES = (
        ('city', 'city'),
        ('store', 'store'),
        ('product', 'product'),
        )
    search_type = forms.ChoiceField(choices=SEARCH_TYPE_CHOICES,  required=True)
    search_word = forms.CharField(label='Search Word',
                  validators=[MinLengthValidator(4)], required=True)
    '''
    def clean_search_word(self):
        cd = self.cleaned_data
        if len(cd['search_word']) < 4:
            raise forms.ValidationError('too short.')
        return cd['search_word']
    '''
    def __init__(self, *args, **kwargs):
        self.helper = FormHelper()
        self.helper.form_tag = False
        self.helper.layout = Layout(
            Fieldset(
                '',
                Field('search_type', css_class='span6'),
                Field('search_word', css_class='span6'),
            ),
            FormActions(
                Submit('submit', 'Go', css_class='btn btn-primary')
            )
        )
        super(PostSearchForm, self).__init__(*args, **kwargs)

tracenack
Environment:

Request Method: POST
Request URL: http://localhost:8000/search/

Django Version: 1.10.3
Python Version: 3.5.2
Installed Applications:
['grappelli',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.sites',
 'debug_toolbar',
 'stripe',
 'vote',
 'django_messages',
 'pinax.notifications',
 'admin_honeypot',
 'easy_thumbnails',
 'django_extensions',
 'crispy_forms',
 'datetimewidget',
 'lineup',
 'allauth',
 'allauth.account',
 'allauth.socialaccount']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'debug_toolbar.middleware.DebugToolbarMiddleware',
 'django.middleware.locale.LocaleMiddleware']

File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
  39.             response = get_response(request)

File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/views/generic/base.py" in view
  68.             return self.dispatch(request, *args, **kwargs)

File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/views/generic/base.py" in dispatch
  88.         return handler(request, *args, **kwargs)

File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/views/generic/edit.py" in post
  185.             return self.form_invalid(form)

File "/home/laptopguy/Documents/lineupNovember/lineup/views.py" in form_invalid
  58.         return render(self.request, self.template_name, context)

File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/shortcuts.py" in render
  30.     content = loader.render_to_string(template_name, context, request, using=using)

File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/template/loader.py" in render_to_string
  68.     return template.render(context, request)

File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/template/backends/django.py" in render
  64.         context = make_context(context, request, autoescape=self.backend.engine.autoescape)

File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/template/context.py" in make_context
  267.             context.push(original_context)

File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/template/context.py" in push
  59.         return ContextDict(self, *dicts, **kwargs)

File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/template/context.py" in __init__
  18.         super(ContextDict, self).__init__(*args, **kwargs)

File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/template/response.py" in __iter__
  123.                 'The response content must be rendered before it can be iterated over.'

Exception Type: ContentNotRenderedError at /search/
Exception Value: The response content must be rendered before it can be iterated over.

Comment: Please show the full traceback.
Comment: I added the traceback
Answer: The traceback shows that your problem is in your form_invalid method. You are capturing the result from the superclass call as context, and passing it into the render function. But the superclass method returns a response, not a context - it has already rendered the template for you, you just need to return it.
def form_invalid(self, form):
    schWord = form.cleaned_data['search_word']
    messages.add_message(
         self.request, messages.WARNING, _('Please correct this...'))
    return super(SearchFormView, self).form_invalid(form)

Comment: I had to remove 'schWord = form.cleaned_data['search_word']' too it gave me an error KeyError at /search/   in this function ..../lineup/views.py" in form_invalid


Does there exist prime number of the form $n^n+s(n)^{s(n)}$ after the trivial one $1^1+1^1$?

Question: Let n be a positive integer and let s(n) be the digit's sum of n. Is there a prime number of the form $n^n+s(n)^{s(n)}$ ? after the trivial one $1^1+1^1$ ?, I've checked n up to $2500$ without finding a prime anymore (!). I found that numbers of such form often divisible by small primes below $100$, and occasionally they have large least prime factor, but after that they become divisible by small primes again (very often!). Is there a prime number of such form after the trivial one 2 ?
Comment: I found no prime for $1<n\le 5700$
Comment: Interesting question, but I'm sure you meant to put this on *MATH.stackexchange.com*...
Comment: If s(n)=n+1, dp you mean $n^n+(n+1)^{n+1}$?
Comment: @martycohen For what positive integer $n$ can the digit sum of $n$ exceed $n$?
Comment: This problem is very weird. I cannot find by computation a single prime in any odd-numbered base. Base 10 I cannot find and 16 is quite stubborn, too.
Comment: I don't see why there should be no other solutions. Are there infinitely many primes of the form $n^n+m^m$? It wouldn't be surprising. They're probably just way too large to find.
Comment: Looking at $n^{s(n)}+s(n)^n$ might be fun.  You get at least one more prime.  (@barto, primes of the form $n^m+m^n$ seem to be plentiful, early on at least.)
Comment: @BarryCipra In this case, the numbers $n$ leading to a prime upto $n=1000$ are $0,1,10,100$
Answer: I'm just stating a few trivial facts:
If $n$ is divisible by $3$ then clearly the number is not prime as it's divisible by 3 and greater than $3$.
If $n$ and $s_n$ are both even then also it's not prime.
For a general proof, I believe a mathematical proof is way very difficult and wouldn't be elementary.
Comment: In place of your second point, you might say that if $n$ and $s_n$ have the same parity, then it's not prime (except for $n=1$).


Performance linq group by with count

Question: I have a method using linq and a group by expression :
public List<SerieVu> ListSeriesLesPlusVuesSemaine()
{
    DateTime dateIlYaSeptJours = DateTime.Now.AddDays(-7);

    var resultat =
    from uev in Query(uev => uev.userepivu_date > dateIlYaSeptJours)
    group uev by uev.Episode.Saison.Serie into pgroup
    let count = pgroup.Count()
    orderby count descending
    select new SerieVu() { nombreDeVus = count, Serie = pgroup.Key };

    return resultat.Take(7).ToList();
}

This linq query generate this SQL Query :
SELECT TOP (7) [Project1].[C2]                        AS [C1],
               [Project1].[C1]                        AS [C2],
               [Project1].[serie_id]                  AS [serie_id],
               [Project1].[serie_image]               AS [serie_image],
               [Project1].[serie_image_thumb]         AS [serie_image_thumb],
               [Project1].[serie_format]              AS [serie_format],
               [Project1].[serie_motsclefs]           AS [serie_motsclefs],
               [Project1].[serie_statusproduction_id] AS [serie_statusproduction_id],
               [Project1].[serie_nom]                 AS [serie_nom],
               [Project1].[serie_nomvf]               AS [serie_nomvf],
               [Project1].[serie_synopsis]            AS [serie_synopsis],
               [Project1].[serie_syncthetvdb]         AS [serie_syncthetvdb],
               [Project1].[serie_dateajout]           AS [serie_dateajout],
               [Project1].[serie_datemiseajour]       AS [serie_datemiseajour],
               [Project1].[serie_actif]               AS [serie_actif],
               [Project1].[utilisateur_id]            AS [utilisateur_id],
               [Project1].[serie_francais]            AS [serie_francais]
FROM   (SELECT [GroupBy1].[A1]  AS [C1],
               [GroupBy1].[K1]  AS [serie_id],
               [GroupBy1].[K2]  AS [serie_image],
               [GroupBy1].[K3]  AS [serie_image_thumb],
               [GroupBy1].[K4]  AS [serie_format],
               [GroupBy1].[K5]  AS [serie_motsclefs],
               [GroupBy1].[K6]  AS [serie_statusproduction_id],
               [GroupBy1].[K7]  AS [serie_nom],
               [GroupBy1].[K8]  AS [serie_nomvf],
               [GroupBy1].[K9]  AS [serie_synopsis],
               [GroupBy1].[K10] AS [serie_syncthetvdb],
               [GroupBy1].[K11] AS [serie_dateajout],
               [GroupBy1].[K12] AS [serie_datemiseajour],
               [GroupBy1].[K13] AS [serie_actif],
               [GroupBy1].[K14] AS [utilisateur_id],
               [GroupBy1].[K15] AS [serie_francais],
               1                AS [C2]
        FROM   (SELECT [Extent4].[serie_id]                  AS [K1],
                       [Extent4].[serie_image]               AS [K2],
                       [Extent4].[serie_image_thumb]         AS [K3],
                       [Extent4].[serie_format]              AS [K4],
                       [Extent4].[serie_motsclefs]           AS [K5],
                       [Extent4].[serie_statusproduction_id] AS [K6],
                       [Extent4].[serie_nom]                 AS [K7],
                       [Extent4].[serie_nomvf]               AS [K8],
                       [Extent4].[serie_synopsis]            AS [K9],
                       [Extent4].[serie_syncthetvdb]         AS [K10],
                       [Extent4].[serie_dateajout]           AS [K11],
                       [Extent4].[serie_datemiseajour]       AS [K12],
                       [Extent4].[serie_actif]               AS [K13],
                       [Extent4].[utilisateur_id]            AS [K14],
                       [Extent4].[serie_francais]            AS [K15],
                       COUNT(1)                              AS [A1]
                FROM   [dbo].[UtilisateurEpisodeVu] AS [Extent1]
                       INNER JOIN [dbo].[Episode] AS [Extent2]
                         ON [Extent1].[episode_id] = [Extent2].[episode_id]
                       INNER JOIN [dbo].[Saison] AS [Extent3]
                         ON [Extent2].[saison_id] = [Extent3].[saison_id]
                       LEFT OUTER JOIN [dbo].[Serie] AS [Extent4]
                         ON [Extent3].[serie_id] = [Extent4].[serie_id]
                WHERE  [Extent1].[userepivu_date] > '2013-01-11T09:53:26' /* @p__linq__0 */
                GROUP  BY [Extent4].[serie_id],
                          [Extent4].[serie_image],
                          [Extent4].[serie_image_thumb],
                          [Extent4].[serie_format],
                          [Extent4].[serie_motsclefs],
                          [Extent4].[serie_statusproduction_id],
                          [Extent4].[serie_nom],
                          [Extent4].[serie_nomvf],
                          [Extent4].[serie_synopsis],
                          [Extent4].[serie_syncthetvdb],
                          [Extent4].[serie_dateajout],
                          [Extent4].[serie_datemiseajour],
                          [Extent4].[serie_actif],
                          [Extent4].[utilisateur_id],
                          [Extent4].[serie_francais]) AS [GroupBy1]) AS [Project1]
ORDER  BY [Project1].[C1] DESC

My question is how to improve performance of this query ? It take about 6 secondes on a very important page of my website.
Thank you for your help
Answer: You can start by making some indexes in your database
you should put the field form where, order by and group by in the indexes
you will probably get the most performance improvement by creating an index on the userepivu_date because  this WHERE  [Extent1].[userepivu_date] > '2013-01-11T09:53:26'
will scan your whole table
Creating an index on SQL Server:
CREATE INDEX [indexname] ON Extent1 (userepivu_date)

Comment: Thank you for your answer. Unfortunatly, I already have index on concerned tables
Answer: First advice I should give is to take a look at the execution plan and search for bottlenecks
then, why a LEFT OUTER JOIN there ?
LEFT OUTER JOIN [dbo].[Serie] AS [Extent4]
Shouldn't it be an inner join (if so, might be some issue with your mapping) ?
I guess it might screw up query optimization by preventing the where clause to be performed early in the join process.
Maybe you can try running the query replacing the left outer join with an inner join and see if it makes a difference.
Also, agree with @user1802430 , if there is no index on userepivu_date, you sure need to place one.
Comment: Thank you very much for your answer. I have try to user INNER JOIN instead of LEFT OUTER JOIN and the performance is really great : 300 ms. Now my question is : How to do this with linq ? Because this SQL Query is generated by Linq
Comment: @toregua You'll have to code the joins manually. Apparently `Saison.Serie` is not a required field so EF creates an outer join.
Comment: @toregua Not familiar with EF : you might have to change your model or code mapping, to have a foreign key between Saison and Serie making it a 1,* relationship instead of 0,*. or adding a Required attribute, as suggested by GertArnold
Bon courage
Comment: I already have a 1, * relationship between Saison and Serie.The foreign key between Saison and Serie exists too :(
Comment: Seems to be a Entity framework bug ? http://stackoverflow.com/questions/7484249/entity-framework-generating-left-outer-joins-when-it-should-be-doing-inner-joins or again http://stackoverflow.com/questions/2916830/too-many-left-outer-joins-in-entity-framework-4
Comment: @toregua you might give a try to this comment : http://stackoverflow.com/questions/2916830/too-many-left-outer-joins-in-entity-framework-4#comment2976865_2916830
eager loading your entities (with .Include(...)?) might be of some help. Which Ef Version do you use ?
Comment: @jbl I've just move from EF4 to EF5 but the generated query is always the same with "LEFT OUTER JOIN" ... I am going to try eager loading thanks
Comment: @jbl Nothing change with eager loading : _query.Include("Episode.Saison.Serie") ... The generated query is the same with "LEFT OUTER JOIN"... :(  I've migrated to EF 5 because some topics said that recent version correct this "bug" but without success (query generated is always and always the same)
Answer: I've found a solution. I have forced inner join using explicit join :
public List<SerieVu> ListSeriesLesPlusVuesSemaine()
{
    DateTime dateIlYaSeptJours = DateTime.Now.AddDays(-7);

    ObjectSet<UtilisateurEpisodeVu> UtilisateurEpisodeVuSet = _context.CreateObjectSet<UtilisateurEpisodeVu>();
    ObjectSet<Episode> EpisodeSet = _context.CreateObjectSet<Episode>();
    ObjectSet<Saison> SaisonSet = _context.CreateObjectSet<Saison>();
    ObjectSet<Serie> SerieSet = _context.CreateObjectSet<Serie>();

    var resultat =
    from uev in UtilisateurEpisodeVuSet.Include("Episode.Saison.Serie").Where(uev => uev.userepivu_date > dateIlYaSeptJours)
    join e in EpisodeSet on uev.episode_id equals e.episode_id
    join sai in SaisonSet on e.saison_id equals sai.saison_id
    join s in SerieSet on sai.serie_id equals s.serie_id
    group uev by s into pgroup
    let count = pgroup.Count()
    orderby count descending
    select new SerieVu() { nombreDeVus = count, Serie = pgroup.Key };

    return resultat.Take(7).ToList();
}

Using this method the linq query generate only inner join ;) Thank everyone who tried to help me
Comment: thx for the follow-up. If you can, you should accept your own answer. Also was wondering if, provided you have the reverse relationships, you could start the other way round : from se in Series from sa in se.saisons  ... where uev.userepivu_date > dateIlYaSeptJours group by uev by se into pgroup ...

Performance linq group by with count


Find the original function by using convolution theorem

Question: Seems like I don't know how to apply convolution theorem on this problem properly, I would appreciate some help and a brief explanation how did you solve it if you do it.
\begin{equation}\frac{1}{((s+\frac{1}{2})^2+\frac{1}{4})*s}\end{equation}
This 1/s is confusing me, my solution is:
\begin{equation}-2cos(\frac{t}{2})+2e^{\frac{-t}{2}}+2sin(\frac{t}{2})\end{equation}
And it should be:
Answer: Convolution in time domain corresponds to multiplication in the s-domain. You can decompose the laplace transform as
$$
\frac{1}{((s+1/2)^2+1/4)s} = \frac{1}{((s+1/2)^2+1/4)}\cdot\frac{1}{s}
$$
The second term corresponds to the laplace transform of the step function $u(t)$. The first term is
$$
\frac{1}{((s+1/2)^2+1/4)}
$$
The inverse laplace transform of this function should not be difficult. Let's call it $f(t)$.
Then you will have the convolution of $f(t)$ and $u(t)$ in the time domain. This would correspond to a function $h(t)$ such that $h(t)=0$ for $t\leq 0$, and then for $t>0$
$$
h(t) = \int_0^tf(x)d(x).
$$


Como chamar um role "Admin" em um IF no C#?

Question: Galera eu criei varias roles para que eu faça um controle de acesso. Portanto quero saber como chamar a role do admin para eu passar em um if, tipo exemplo que colocarei abaixo no meu _layout:
  @if ("Aqui que eu preciso saber como chamar a role admin")
                {

@Html.ActionLink("Início", "Index", "Home")

@Html.ActionLink("Sobre", "About", "Home")

@Html.ActionLink("Contato", "Contact", "Home")

                }
                else
                {

@Html.ActionLink("Sobre", "About", "Home")

                }

Aqui é como eu criei a role em meu arquivo startup:
public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        ConfigureAuth(app);
        createRolesandUsers();
    }

    // In this method we will create default User roles and Admin user for login
    private void createRolesandUsers()
    {
        ApplicationDbContext context = new ApplicationDbContext();

        var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
        var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));

        // In Startup iam creating first Admin Role and creating a default Admin User
        if (!roleManager.RoleExists("Admin"))
        {

            // criando a role do usuario Admin
            var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
            role.Name = "Admin";
            roleManager.Create(role);

            //Aqui estou criando o usuario que terá o acesso completo

            var user = new ApplicationUser();
            user.UserName = "ebase";
            user.Email = "firstname.lastname@example.com";

            string userPWD = "123456";

            var chkUser = UserManager.Create(user, userPWD);

            //Add default User to Role Admin
            if (chkUser.Succeeded)
            {
                var result1 = UserManager.AddToRole(user.Id, "Admin");

            }
        }

Answer: @if (User.IsInRole("Admin"))
{

}

Comment: Passando o nome Admin não esta funcionando, qual seria a forma correta? O menu continua não sendo exibido depois de logado
Comment: O usuário possui a permissão de admin na tabela de AspNetUserRoles ?
A role de admin está cadastrada com o mesmo nome em AspNetUsers ?
Comment: eu não entendi, eu preciso fazer alguma coisa na base de dados???
Comment: Sim, você deve ter salvo na tabela AspNetRoles, o id da role e o nome, exemplo:
**1  -  Admin**
E na tabela de AspNetUsersRoles o id do usuário e o id da role, exemplo:
**UserId | RoleId **
**   2       |    1  **
Comment: Verifique também se o usuário está logado
Comment: O ID de ambas as tabelas devem ser iguais então???
Comment: Sim, porque a coluna RoleId é chave estrangeira. E o id da mesma deve existir em AspNetRoles
Comment: Eu criei aqui um novo usuário portanto quando fui na tabela AspNetUserRoles tava tudo null, apenas estão salvo os dados na tabela AspNetUsers e AspNetRoles, como faço para salvar isso na outra tabela? Desculpe mais é que to começando agora com C#, antes eu programava em PHP
Comment: Cara consegui, fiz o que vc falou, fui no AspNetUserRoles e coloquei o ID e o roleid iguais dos demais, dai deu certo


Does the Morse homology depend on the orientation?

Question: Before asking my question I need to define some objects. I will follow the book "M. Audin, M.Damian - Morse theory and Floer homology", but the terminology is quite standard:
Let $M$ be a smooth compact manifold and consider a Morse-Smale pair $(X,f)$ on $M$ ($X$ is a gradient-like vector field and $f$ is an adapted Morse function). If $a,b$ are two critical points of $f$, we indicate with $\mathcal L(a,b)$ the manifold such that every point is a trajectory of $X$ ''starting'' from $a$ and ''ending'' in $b$. One can show that if $\text{ind}(a)=\text{ind}(b)+1$ then $\mathcal{L}(a,b)$ is a finite set. Moreover if we orient the stable manifold  $W^s(a)$, remember that it is a disk, we induce an orientation on $\mathcal L(a,b)$, namely at each point we associate $\pm 1$ if $\text{ind}(a)=\text{ind}(b)+1$.
At this point one can define the Morse-Smale complex:
$$C_k:=\sum_{a\in\text{Crit}_k(f)}\mathbb Za$$
where clearly $\text{Crit}_k(f)$ is the set of critical points of index $k$. The map $d_k:C_k\longrightarrow C_{k-1}$ acts on the generators of $C_k$ in the following way:
$$d_k(a)=\sum_{a\in\text{Crit}_{k-1}(f)}N(a,b)b$$
where $N(a,b)\in\mathbb Z$ is the sum of the $\pm 1$ (the orientations) attached to the points of $\mathcal L(a,b)$.

Question: From the above construction it is evident that the Morse-Smale complex (in particular the number $N(a,b)$) depends on the
  orientation that we fix on the stable manifolds $W^s(a)$. This sounds
  very strange to me, indeed I'd expect a complex independent from the
  orientation. Maybe by passing to the homology group one can recover
  the independence but I can't see it.

Many thanks.
Comment: Yes, it turns out to be independent, because it turns out to be the same as singular homology!
Comment: I don't think this is very strange - the ambiguity of the orientation on the differential is a $\pm 1$ on each term. When you work mod 2 there is no such ambiguity - in fact, this is the entire reason it is sometimes desirable to work mod 2.
Comment: Ok, this is true but there is another strange thing: we can pass to the $\mathbb Z/2\mathbb Z$-complex by the canonical homomorphism $\mathbb Z\rightarrow\mathbb Z/2\mathbb Z$ (it is unique). Now, if we have many $\mathbb Z$-complexes, depending on the orientations,  then we have many $\mathbb Z/2\mathbb Z$-complexes. On the other hand if we construct directly the  $\mathbb Z/2\mathbb Z$-complex, as in the book cited in my question, you can see that it is unique.
Comment: Oh yes! changing a single $\pm 1$ doesn't modify the number mod $2$.
Answer: Yes, it's independent of these choices - if only because it turns out to be isomorphic to singular homology. The need for orientations is a necessity of working with $\Bbb Z$ coefficients instead of $\Bbb Z/2$ - when writing down the differential, we need to know when a flow line is "positively oriented" or "negatively oriented" to properly count them with signs. This leads us to the unseemly need for this choice.
One reason many books first work mod 2 (and sometimes Floer homology books will do the same, at least at first) is precisely so that one doesn't have to worry about these orientation issues. The ambiguity from the orientations is a bunch of $\pm 1$s induced in the differential - but in $\Bbb Z/2$, there is no ambiguity at all, since $1=-1$. Indeed, when working mod 2, we don't need to assign signs to each flow line - we just need to count them.
Answer: If you change the orientation on $W^s(a)$ then an isomorphism from the old complex to the new is given by sending the generator $a$ of $C_k$ to $-a$ (and acting as the identity on all other critical points).


What are good, freely available journals for keeping track of the latest developments in machine learning?

Question: Feel free to substitute 'journals' for any other useful portal of knowledge.
I am interested in keeping an eye on new developments in machine learning, with a view to practical applications. I am not an academic seeking to publish my own work (at least not in this field), but I do want to be aware of potential new algorithms or tricks that would be useful on a practical level.
The only caveat is that the journal/conference proceeding or whatever must be freely available without requiring a subscription.
Comment: The arxiv [entry](http://arxiv.org/list/stat.ML/recent) for recent machine learning submissions is also a good option; at least for checking some abstracts during your morning coffee.
Comment: @Procrastinator, I did check arXiv before posting the question, but it didn't seem right that there are 'only' a handful of pre-prints a day. I'm used to seeing 100+ papers every day in the arXiv categories in my field. I though that maybe the ML community wasn't really into arXiv. Can you confirm that the majority of ML papers get posted to arXiv? If so that would be wonderfully convenient, as I already peruse other parts of arXiv daily anyway.
Comment: I am sure only few ML papers are posted on arXiv, some of them are either posted on universities websites, personal websites or even never posted as preprints. Also, there are many useless papers which makes difficult to get the useful ones. On the other hand, when you are lucky enough and find a good one, you can read it before it is published. Publishing may take even two years. So, my opinion about arXiv is that it is worth to take a quick look at the abstracts and see if you find something useful, but I agree it is not the best option (this is why I posted this as a comment).
Answer: New developments in ML are almost always presented in conferences first, and sometimes later refined into journal papers.
If you only follow two conferences, they should be:

NIPS (Neural Information Processing Systems); December. Conference site, proceedings. (Despite the name, most papers are unrelated to neuroscience or neural networks.)
ICML (International Conference on Machine Learning); July. Site (including proceedings links).

These conferences also include workshops that publish less-polished work, which can often be a good way to find about ongoing and not-yet-published research.
The following ML conferences also contain many excellent papers, though they are not as "first-tier" as NIPS and ICML and may be more focused in scope:

AISTATS (Artificial Intelligence and Statistics); May. Conference site; proceedings published in JMLR and available here. Sometimes more theoretical, especially from a statistics viewpoint.
COLT (Conference on Learning Theory); July. 2015 site, proceedings also published in JMLR. Very theoretical.
UAI (Uncertainty in Artificial Intelligence); July. Conference site, proceedings. Typically more focused on graphical models and/or Bayesian techniques.
ICLR (International Conference on Learning Representations); May. Conference site. (Focused on deep learning, relatively new; all submissions appear on arXiv.)
ECML PKDD (European Conference on Machine Learning and Principles and Practice of Knowledge Discovery in Databases); September. Conference site.
ACML (Asian Conference on Machine Learning); November. Conference site.

Some AI conferences also include good machine learning papers or specific tracks on machine learning, especially:

IJCAI (International Joint Conference on Artificial Intelligence); July. Conference site, somewhat out-of-date proceedings.
AAAI (Association for the Advancement of Artificial Intelligence); February. Conference site, proceedings.

Conferences in related fields are also often relevant, especially:

KDD (Knowledge Discovery and Data Mining); August. Conference site, links to individual conferences here.
CVPR (Computer Vision and Pattern Recognition); June. 2016 site, overview.
Answer: The Journal of Machine Learning is freely-available online and on the cutting edge, but it is pretty heavy.
Answer: I think that the best way to keep track of the latest developments in Machine Learning is to follow the Reddit feed:
https://www.reddit.com/r/MachineLearning/
Many researchers post some comments about the papers they recently submitted to different venues.

You might also follow what is submitted to Arxiv here:
http://arxiv.org/list/stat.ML/recent
Most researchers submit pre-print versions of their papers to Arxiv before publication.

Also, you might want to have a Twitter account and follow particular researchers/professors who work in machine learning. However, the people you might want to follow really depend on your area of interest. A good starting point might be following the hashtag #machinelearning

Also remember that the terms machine learning, data mining, knowledge discovery in data bases, data science are sometimes used interchangeably. In order to find some interesting developments in machine learning you might look at news in those other areas as well.


How to deal with an unavoidable correlation between two independent variables?

Question: In a simple linear regression model with two independent variables, if there is a strong correlation found between the variables, it is suggested that we should include only one of them in the model.
I am building a model where the dependent variable is Lunch Cost and the independent variables are Number of Class 1 Students Buying Lunch and Number of Class 2 Students Buying Lunch. However, I found there was a strong correlation between the two independent variables; when Number of Class 1 Students Buying Lunch increases, Number of Class 2 Students Buying Lunch increases as well.
In this case, removing one of them from the model seems not ideal since my goal is to know how  the two independent variables would describe Lunch Cost. What should I do here? Thanks!
Answer: The first question to ask is: do you actually need to care? If you're just trying to predict the cost of future lunches, then this isn't really an issue. On the other hand, if you're trying to assess the relative contributions of Class #1 and Class #2 students to the cost, then collinearity is a bigger problem.
In a well-behaved, non-colinear model, we might take a model like $y = \beta_0 + \beta_1 \cdot x_1 + \beta_2 \cdot x_2$ and fit it with our data to find the $\beta$ values. We might find that $\beta_1 = 2$ and $\beta_2 = -0.5$, which would indicate that a one unit increase in $x_1$ results in a 2 unit increase in $y$, while a similar change in $x_2$ causes a half-unit decrease in $y$. However, if $x_1$ and $x_2$ are highly correlated, this interpretation goes right out the window.
Suppose we fit a model $Y = \beta_0 + \beta_1 \cdot x_1$ and found that $\beta_0 = 0$ and $\beta_1 = 4.$ Everything's great! Now we do something dumb and fit this model instead $Y = \beta_0 + \beta_1 \cdot x_1 + \beta_2 \cdot x_2$, where $x_1 = x_2$ (in other words, $x_1$ and $x_2$ are completely correlated).
In this case, we can pick literally any set of $\{\beta_1, \beta_2\}$ values that add up to four: (2,2), (1,3), (1003, -999), and so on: these are all the points on the line $x+y=4$ (hence the name!). These all give you the same prediction, but depending on your choice you would be claiming that a 1 unit increase in $x_1$ is associated with a 2, 1, or 1003 unit increase in $y$, respectively, which can't all be correct! This is obviously an extreme example, but you could imagine similar things happening when the $x_s$ are somewhat less strongly correlated.
I'm also tempted to ask why you're separating out students by class--is there some reason to think that Class #1 and Class #2 students contribute differently to the price of lunch? Perhaps a model where you regress lunch cost ~ total number of students would be more appropriate?
Comment: @GuessGucci: "The main reason to think that the two classes would contribute differently to the price of lunch is that Class 2 is older than Class 1 on average" then wouldn't separating this into total number of students (= class 1 + class 2) and difference between class 1 and class 2 be a sensible transformation? Which of course gets you on the way to re-invent principal component regression...
Comment: The main reason to think that the two classes would contribute differently to the price of lunch is that Class 2 is older than Class 1 on average. I just want to predict the future lunch cost; however, should I mention the correlation that I found between the two classes in my report?
Comment: That seems pretty reasonable: "The model predicts [this and that], but due to multi-collinearity, we are unable to assess the relative contributions of Class 1 and 2." All that said, there are some ways of getting around it: http://online.stat.psu.edu/online/development/stat501/12multicollinearity/01multico_intro.html
Comment: By the way, what do you mean by relative contribution? For instance, I have Y = 2*X_1 + 4*X_2 and am able to conclude that 1 unit increase in X_1 would lead to a 2 unit increase in Y. Is this the relative contribution you are talking about? Thanks again.
Comment: GuessGucci, exactly. I've edited in an example, which I hope clears things up.

One way to solve colinearity problems is to transform your data in a way that reduces the correlations between variables while keeping the variables interpretable. @cbeleites's solution is a great idea--you should give it a shot!
Answer: Based on the fact that it's the average age of Class 2 vs. Class 1 that (you hypothesize) may matter, you could try a model where the response is Lunch Cost, and the predictors are

a factor for whether a student is in class 1 or class 2
the student's age

This way, you can ask whether age matters, and whether belonging to class 2 (rather than class 1, which would be a baseline) also matters.


Ajax callback change "checked" radio button

Question: I have a radio button group like this:
$options = array('2' => t('Active (2)'), '1' => t('Upcoming (1)'), '0' => t('Finished (0)'));
$form['active'] = array(
'#type' => 'radios',
'#title' => t('Update state:'),
'#default_value' => $default_entry->active,
'#options' => $options,
);

which works fine. However, based on a drop-down list of entries, it calls an ajax function which should update the selection:
foreach (array('name', 'test') as $item) {
$form[$item]['#value'] = $entry->$item;
}
foreach (array('active') as $item) {
???
}

Now, the "name" and "test" work as expected as they are text fields.... but the active radio button stays the same as it was (i.e. based on the '#default_value').
I have tried
$form[$item]['#value'] = $entry->$item;
$form[$item]['#default_value'] = $entry->$item;

but neither change which radio button is selected. Is there something I'm missing based on updating the "checked" attribute for that radio group?
Any help and/or points in the right direction much appreciated.
Comment: I'm guessing it can't be done. I've seen a couple of other similar issues, but nothing with a viable solution, most notably here:
http://drupal.org/node/1446510

It may be a solution, but I can't get my head around it if anyone could explain a little more, it'd help greatly!
Comment: https://drupal.stackexchange.com/questions/276978/how-to-set-default-value-for-radio-button-on-ajax-callback/290917#290917
Answer: You would need to show more code (the form definition), I would recommend you to try:
unset($form['input'][$item]);
Right prior to calling:
$form[$item]['#default_value'] = $entry->$item;
Relative links: https://www.drupal.org/node/1082818#comment-5335080


Area between paraboloid cut out by cylinder

Question:
Find area between surface $z^2=x^2+y^2$ and $x^2+y^2=2x$.

So, after using polar coordinates $x=r\cos \phi,y=r\sin \phi$ i get $0\le r \le 2\cos\phi$ and $0\le \phi \le \frac{\pi}{2}$. Than i plugged that into formula $\iint \sqrt{1+p^2+q^2}\,dx\,dy$ where $p=\frac{\partial z}{\partial x}=\frac{x}{\sqrt{x^2+y^2}}$ and $q=\frac{\partial z}{\partial y}=\frac{y}{\sqrt{x^2+y^2}}$ and got $\frac{\sqrt{2}\pi}{2}$ but correct answer is $2\sqrt{2}\pi$. I probably need to multiply area with $4$ but honestly I'm not sure when to do that, on what it depends etc. I sketched this in plane(paraboloid and cylinder) and I can only see two symmetric areas (instead of four). If someone could clear this for me i would be very thankful.
Comment: First of all, $z^2 = x^2 + y^2$ is a cone and not a paraboloid. Second, your working is correct but only considers first octant. You need to multiply by $4$ and not $2$. It is $- \pi/2 \leq \phi \leq \pi/2$ but your working has $0 \leq \phi \leq \pi/2$. So you need to multiply your answer by $2$. That takes care of the cone $z = \sqrt{x^2 + y^2}$. But you have another cone below $XY$ plane (negative $z$), $z = - \sqrt{x^2 + y^2}$. So you need to multiply by  $2$ again for that.
Comment: You can see the Example 1 of the following link (https://home.iitk.ac.in/~psraj/mth101/lecture_notes/lecture35.pdf). This are more or less same.
Answer: It's a basic algebra exercise to see that the horizontal cross-section of your cyclinder is a circle centered at $(1,0,0)$ on the $xy$-plane.
$$\Huge{\lvert \hspace{-15px} \bigodot}$$

object
code
$\text{equation}$

$\lvert$
$\lvert$
$x = 0$

$\bigodot$
$\bigodot$
$(x-1)^2 + y^2 = 1$

It's clear that in your cylindrical coordinates $\begin{cases}x = r\cos \phi& \\ y = r\sin \phi,& \end{cases}$, $\phi$ represents the angle between the segment from $(0,0)$ to $(x,y)$ and the $x$-axis.  By setting $0\le \phi \le \dfrac{\pi}{2}$, you've only swept the first quadrant.  However, by observing the symmetry along the $xz$-plane (i.e. $y = 0$), it suffices you have to multiply your calculated value by $2$ to get the correct answer area for one slice.
As @MathLover has pointed out, there's another slide due to the symmetry along the $xy$-plane, so you have $$\frac{\sqrt2 \pi}{2} \cdot 4 = 2\sqrt2 \pi,$$ which is your desired answer.
Comment: There is also a symmetry along $XY$ plane. $z^2 = x^2 + y^2$ depicts two cones, one above $XY$ plane and one below $XY$ plane. So the calculated value has to be multiplied by $4$ and not $2$.
Comment: @MathLover Sorry for error. Thanks for pointing it out.  I've corrected it.
Comment: You are welcome!


Socket program to send and receive user defined objects not working

Question: I have a user defined class Message, whose object I would like to pass between the client and the server.
The Message class is as follows:
import java.io.Serializable;

public class Message implements Serializable
{
    String CorS;
    int data_id;
    int status_id;
    Integer value;
    boolean withdraw;

    public Message()
    {
        CorS = null;
        data_id = 0;
        status_id = 0;
        value = 0;
        withdraw = false;
    }

    public Message(String CorS, int data_id, int status_id, Integer value)
    {
        this.CorS = CorS;
        this.data_id = data_id;
        this.status_id = status_id;
        this.value = value;
    }

    public Message(boolean withdraw)
    {
        this.withdraw = withdraw;
    }
}

The code in the client side which sends the object to the server is as follows:
Socket s = null;
    ObjectInputStream in = null;
    ObjectOutputStream out = null;

    String hostname = null;
    int port_no = 0;

    HashMap<String, Integer> map = null;

    Message m = null;

    map = servers.get("Server" + server);

    for(String key : map.keySet())
    {
        hostname = key;
        port_no = map.get(key);
    }
    //System.out.println(hostname + " " + port_no);

    s = new Socket(hostname, port_no);
    in = new ObjectInputStream(new BufferedInputStream(s.getInputStream()));
    out = new ObjectOutputStream(new BufferedOutputStream(s.getOutputStream()));

    s_now = s;

    m = new Message(client, data, 0, 0);
    out.writeObject(m);
    out.flush();
    System.out.println("Sent obj");

Similarly, the code on the Server side is as follows:
while (true)
    {
        try
        {
            System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
            Socket server = serverSocket.accept();
            System.out.println("Just connected to " + server.getRemoteSocketAddress());

            ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(server.getInputStream()));
            //ObjectOutputStream out = new ObjectOutputStream(server.getOutputStream());

            Message m = (Message) in.readObject();

            System.out.println(m.value);
        }

        catch (IOException e)
        {
            e.printStackTrace();
            break;
        }
        catch (ClassNotFoundException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

The problem is that the object is not getting printed. The output I get is as follows:
Waiting for client on port 1051...
Just connected to /127.0.0.1:59216

Any help in this regard will be greatly appreciated. Thanks :)
Answer: You need to create the ObjectOutputStream before the ObjectInputStream at both ends.
The reason is that, as described in the Javadoc, the respective constructors write and read a stream header. So the input stream constructor can't return until the output stream constructor at the peer has executed. So if you construct both input streams first there is a deadlock.
Comment: Thanks. That worked. But could you tell me why this is the case? Any reasonable explanation?


How do i deal with responsive menu?

Question: I'm trying to make a responsive menu but texts are coming down when im resizing my website.
When i'm resizing to a lower dimension like 637 x 400  "a empresa" "projetos" and "contato" they drop and come down.
nav {
    height: 60px;
    width: 100%;
    background-color: #a23286;
    color: #eee;
    position: fixed;
    text-align: center;
}
/* menu + logo dimensoes */
nav ul {
    display: inline-block;
    padding: 0;
    margin: 0;
    text-align: center;
}

nav li {
    float: none;
    display: inline-block;
    text-align: center;
}

nav a {
    display: inline-block;
    width: 100px;
    text-align: center;
    padding: 17px 0;
    color: #eee;
    text-decoration: none;
}

nav ul li:hover {
  border-bottom: 5px solid #a23286;
}

nav a#openup {
    display: none;
}

Should i just create a query in css for this state and change the font of the text?
https://codepen.io/rfop2/pen/JjjBBRe
Comment: Please include enough HTML, CSS, and JavaScript to reproduce the issue **in the question here on Stack Overflow**, not just on an external site. You can use [Stack Snippets](https://meta.stackoverflow.com/q/358992/215552) to do a lot of the things you can do on CodePen right here (the icon in the post editor toolbar looks like a page with `<>` in it).
Answer: You can use a media query and set the interval between 400px and 637px and set the width of nav a to 85px.
@media only screen and (max-width: 637px) and (min-width: 400px)  {
  nav a {
    width: 85px;
  }
}

Your codepen: Codepen
Answer: You can just use css flex for this. See ul style below.
nav ul {
    display: flex;
    flex-wrap: no-wrap;
    justify-content: center;
    padding: 0;
    margin: 0;
}

$(function() {
    menu = $("nav ul");

    $("#openup").on("click", function(e) {
      e.preventDefault();
      menu.slideToggle();
    });

    $(window).resize(function() {
      var w = $(this).width();
      if (w > 480 && menu.is(":hidden")) {
        menu.removeAttr("style");
      }
    });

    $("nav li").on("click", function(e) {
      var w = $(window).width();
      if (w < 480) {
        menu.slideToggle();
      }
    });
    $(".open-menu").height($(window).height());
  });

  $('.cf a').on('click', function(event){
    if(this.hash !== ''){
      event.preventDefault();

      const hash = this.hash;

      $('html, body').animate(
        {
          scrollTop: $(hash).offset().top
        },
        800,
        function(){
          window.location.hash = hash;
        }
      );
    }
  });

@import url('https://fonts.googleapis.com/css?family=Titillium+Web&display=swap');

/* corpo geral */

body {
    font-family: 'Titillium Web', sans-serif;
    margin: 0;
    line-height: 1.6;
}

/* menu */

nav {
    height: 60px;
    width: 100%;
    background-color: #a23286;
    color: #eee;
    position: fixed;
    text-align: center;
}
/* menu + logo dimensoes */
nav ul {
    display: flex;
    flex-wrap: no-wrap;
    justify-content: center;
    padding: 0;
    margin: 0;
}

nav li {
    float: none;
    display: inline-block;
    text-align: center;
}

nav a {
    display: inline-block;
    width: 100px;
    text-align: center;
    padding: 17px 0;
    color: #eee;
    text-decoration: none;
}

nav ul li:hover {
  border-bottom: 5px solid #a23286;
}

nav a#openup {
    display: none;
}

/* logo no menu */

.logo{
    float: left;
    height: 50px;
}

.textoIn{
  background-color: #a23286;
  height: 400px;
}

h1{
  margin: 0;
  padding: 0;
  padding-top: 100px;
  text-align: center;
  font-size: 30px;
  color: black;
}

/* texto abaixo do menu */

@media screen and (max-width: 580px) {

    nav {
      height: auto;
      border-bottom: 0;
    }
    nav ul {
      display: none;
      height: auto;
    }
    nav li {
      width: 100%;
      float: left;
      position: relative;
    }
    nav a {
      text-align: left;
      width: 100%;
      text-indent: 25px;
      background: #a23286;
      border-bottom: 1px solid #555;
    }
    nav a:hover {
      background-color: #a23286;
    }
    nav a#openup:after {
      content: "|||";
      transform: rotate(-90deg);
      -ms-transform: rotate(-90deg);
      /* IE 9 */
      -webkit-transform: rotate(-90deg);
      /* Safari and Chrome */
      width: 30px;
      height: 30px;
      display: inline-block;
      position: absolute;
      right: 5px;
      top: 20px;
    }
    nav a#openup {
      display: block;
      background-color: #a23286;
      width: 100%;
      position: relative;
    }
  }
  .cf:before, .cf:after {
    content: "";
    display: table;
  }

  .cf:after {
    clear: both;
  }

  .cf {
    zoom: 1;
  }
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

    <link href="https://fonts.googleapis.com/css?family=Titillium+Web&display=swap" rel="stylesheet">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <link rel="stylesheet" href="css/style.css">
    <title>JRConecte</title>
  </style>

                INICIO

                ATUAÇÃO

                EQUPE

                A EMPRESA

                PROJETOS

                  CONTATO

            JRConecte

            asdasdasddsadaasdasdsadadadsa

How do i deal with responsive menu?


Do Positive Eigenvalues (or Spectrum) of an Operator on Hilbert Space Imply Positivity

Question: Of an Hilbert Space $H$ and an (self-adjoint) operator $A$ on it,
(1) When $A$ has only real and positive / non-negative eigenvalues, does it imply positivity of $A$?
(2) When $A$ has only real and positive / non-negative spectrum, does it imply positivity of $A$?
I can only find cases where $H$ is finite, I want to know whether these statements are true on a general Hilbert space.
Answer: What is the base field of $H$ ? $\mathbb R$ or $\mathbb C$ ? I'll suppose the latter because it is the usual assumption and makes things easier. Is $A$ continuous (or equivalently, bounded) ? I'll suppose yes, because this case is simpler, far more frequent in math. discussion and I know little about the unbounded case. Then:
(2) has answer yes. Under some definitions (in C$^*$-agebras, which include the algebra of continuous endomorphisms of $H$ as a special case), it's by definition ($A$ self-adj. with positive real spectrum <=> $A$ positive) ... so I imagine you have got the definition specific to operators in Hilbert spaces: ($x|A(x)) \ge 0$ for all $x \in H$, and there is a theorem saying that this is equivalent. Now you probably are looking for a proof of the equivalence. The implication in one direction is relatively simple although not trivial, but what you need goes in the other direction, and that is quite a difficult story, unless one knows (and may use) a theorem from which one concludes easily ... I find no place where the theorem is named (may-be Wikipedia doesn't have it at all); it says that $A$ is positive iff it is a product $B^*B$ where B is some bounded linear operator on $H$ ... this is just a general theorem for C$^*$-algebras applied to our special case; the proof I know is in the general case, may-be there exists a simpler proof in the special case, but I don't know about that.
(1) is obviously true when $H$ is finite-dim. because it is then equivalent to (2). I guess it is wrong in the infinite-dim. case; in principle your hyp. in (1) is satisfied in case $A$ has no eigenvalue at all; it is probably easy to find an example where self-adj. $A$ has a spectral value < 0 but no eigenvalue, this will not be positive due to the converse of (2). If you want a case having an eigenvalue, you will probably have it by taking $H = \mathbb C . x \oplus H_1$ where $x \in H$ is $\neq 0$ and $H_1$ is the hyperplane orthogonal to $x$, then you transfer the example without eigenvalue to $H_1$ and define your operator on $\mathbb C . x$ as identity ...


Steps to connect IBM MQ Queue from .net core 3.1

Question: I have installed IBM MQ classes from NuGet repository (amqmdnetstd.dll version 9.1.4) using below code to create a connection but getting error "CWSMQ0006E: An exception was received during the call to the method ConnectionFactory.CreateConnection: System.ArgumentNullException: Value cannot be null. (Parameter 'destinationArray')"
<code>var xff = XMSFactoryFactory.GetInstance(XMSC.CT_WMQ);
            var cf = xff.CreateConnectionFactory();
            cf.SetStringProperty(XMSC.WMQ_HOST_NAME, WebsphereMqHost);
            cf.SetIntProperty(XMSC.WMQ_PORT, WebsphereMqPort);
            cf.SetStringProperty(XMSC.WMQ_CHANNEL, WebsphereMqChannel);
            cf.SetStringProperty(XMSC.WMQ_QUEUE_MANAGER, WebsphereMqQueueManager);
            cf.SetIntProperty(XMSC.WMQ_CONNECTION_MODE, XMSC.WMQ_CM_CLIENT);

            var conn = cf.CreateConnection();
            var sess = conn.CreateSession(false, AcknowledgeMode.AutoAcknowledge);
            var queue = sess.CreateQueue(QueueName);
            var consumer = sess.CreateConsumer(queue);
</code>
Comment: This [thread on MQSeries.net](http://www.mqseries.net/phpBB2/viewtopic.php?t=77072&sid=b3392b0a0d00476e300b968bcb2a72dc) seems to describe the same situation.  The poster fixed it by backing off to 9.1.3.  I would suggest trying the new 220.127.116.11 LTS version (this rolled up all features/updates that were present in 9.1.5).  If it doesn't work in 184.108.40.206, then try 9.1.5, if it does not work there, then go with 9.1.3 and open a case with IBM about the issue.
Answer: The above error seems to be a bug in the code and is fixed in APAR IT31572
and is part of MQ v9.1.5 CD or MQ v9.2 LTS. So using 9.1.5/9.2 should solve the problem.
Comment: This APAR lists fixed in 9.1.5, but it is not present on the 9.1 CDS fix list page or on 9.2 CDS fix list, can you update those?


python how to convert  to

Question: I have a below dictionary defined with IP address of the application for the respective region. Region is user input variable, based on the input i need to procees the IP in rest of my script.
app_list=["puppet","dns","ntp"]

dns={'apac':["188.8.131.52","220.127.116.11"],'euro':["184.108.40.206","220.127.116.11","188.8.131.52"],'cana':["18.104.22.168","188.8.131.52"]}
ntp={'asia':["126.96.36.199","184.108.40.206"],'euro':["126.96.36.199","22.214.171.124","126.96.36.199"],'cana':["22.214.171.124","126.96.36.199"]}
puppet={'asia':["184.108.40.2061","1932.1625.254.2493"],'euro':["184.108.40.206","1932.1625.254.2493"],'cana':["18.104.22.168","193.1625.254.249"]}

Code Tried
   region=raw_input("entee the region:")
    for appl in app_list:
            for ip in appl[region]:
                   <<<rest of operations with IP in script>>

When I tried the above code got the error mentioned below. I tried to convert the str object to dict using json and ast module but still did not succeedd.
Error received
TypeError: string indices must be integers, not str

As new to python unsure how to get the ip list based on the region
Comment: you can get a dictionary have format {Key: value},  string has indices by index.
Answer: The problem is that in each loop for appl in app_list appl will be a string and you are trying to index appl[region], so you are trying to index the string with another string. But actually you just want to loop over the dictionaries dns, ntp and puppet, so you could do this instead:
dns={'apac':["188.8.131.52","126.96.36.199"],'euro':["188.8.131.52","22.214.171.124","126.96.36.199"],'cana':["126.96.36.199","18.104.22.168"]}
ntp={'asia':["18.104.22.168","184.108.40.206"],'euro':["126.96.36.199","220.127.116.11","220.127.116.11"],'cana':["188.8.131.52","18.104.22.168"]}
puppet={'asia':["126.96.36.1991","1932.1625.254.2493"],'euro':["18.104.22.168","1932.1625.254.2493"],'cana':["184.108.40.206","193.1625.254.249"]}

app_list = [puppet, dns, ntp]

region = input("entee the region:")

for appl in app_list:
  for ip in appl.get(region, []):
    print(ip)

Notice that 1) app_list is now a list of the predefined dictionaries and 2) that you should indx the region using the get() method for dictionaries, because the region might not be present in a given dictionary, so you can return an empty list as default. Otherwise you could run into a KeyError.
I hope that's what you were looking for.
Answer: problem 1: your loop implies that app_list is a nested dict, which it isn't
problem 2: appl is a key to a dict, not the value of the dict.
this works:
app_list={
"puppet": {'asia':["126.96.36.1991","1932.1625.254.2493"],'euro':["18.104.22.168","1932.1625.254.2493"],'cana':["22.214.171.124","193.1625.254.249"]},
"dns": {'apac':["22.214.171.124","18.104.22.168"],'euro':["18.104.22.168","18.104.22.168","188.8.131.52"],'cana':["188.8.131.52","220.127.116.11"]},
"ntp": {'asia':["188.8.131.52","22.214.171.124"],'euro':["184.108.40.206","188.8.131.52","220.127.116.11"],'cana':["220.127.116.11","220.127.116.11"]}
}

region=input("entee the region:")
print("")
for key in app_list:
  appl = app_list[key]
  if region in appl:
    for ip in appl[region]:
      print(ip)
  else:
    print("region not found in appl " + str(appl))

output
echo "asia" | python3 blubb.py
entee the region:
126.96.36.1991
1932.1625.254.2493
region not found in appl {'apac': ['126.96.36.199', '220.127.116.11'], 'euro': ['18.104.22.168', '18.104.22.168', '220.127.116.11'], 'cana': ['188.8.131.52', '220.127.116.11']}
188.8.131.52
188.8.131.52

python how to convert  to


Convert android app to smart TVs

Question: We have developed an app as part of digital signage platform, to control multiple screens remotely using a web based dashboard. Currently we are installing the app in mini-pcs and selling it as a product.
Once deployed, this Android player app works as a standalone player with no user interaction what-so-ever, but only on mini-pcs.
What major changes are necessary for converting this app to work for smart TVs with Android TV OS ?
Answer: you can try Smaf.tv, the free cross-platform JS SDK and command line tool, with which you can build and package TV apps with one code base for LG WebOS, Samsung Smart TV (Orsay) & Tizen, Android TV and Amazon Fire TV.
Disclaimer: I am part of the Smaf.tv team, but honestly I believe it fits your objective
Answer: If you already have an Android app, then it technically should already work with Android TV. There are a few TV-specific things you can do:

Declare a Leanback Launcher intent. Add this to your main activity in the manifest:
<intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LEANBACK_LAUNCHER" />
</intent-filter>

Add a banner to your app's application tag:
<application
    android:banner="@drawable/banner" >

Test it out to make sure any user interaction you have works with a DPAD / remote control.

You can build and run on a device or in an emulator if you want to double-check. There's plenty more in the docs linked above if you want to learn more.

Convert android app to smart TVs


Reordering of matrix multiplication

Question: I want to compute the matrix multiplication $ABA$, where $A$ and $B$ are real and orthogonal matrices. In fact, they are specifically $3\times3$ rotation matrices.  However, it is much easier if I can reverse the order of $BA$ somehow, because I can then perform the multiplication much easier.
I know that matrix multiplication is not commutative, however, I am asking because both $A$ and $B$ are orthogonal matrices, and hopefully, may be there is some trick to utilize their orthogonality to reorder the product.
I tried to solve this, but got stuck here:
$$
ABA = A((BA)^{-1})^{-1}=A(A^{-1}B^{-1})^{-1}
$$
Is there a way to proceed from here?
Edit:
I also know that matrix multiplication is associative; however, I am not after associativity here. I want to multiply the $A$ matrix by $A$ (or by its inverse/transpose), then multiply the result by $B$.
Edit:
To put this into context, consider the following product of rotation matrices
$$
R_x(\theta)R_z(\pi)R_x(\theta)
$$
where, $R_x(\theta)$ is the rotation matrix about the $x$-axis by $\theta$, and $R_z(\pi)$ is the rotation matrix about the $z$-axis by $\pi$.
This product simplifies to $R_z(\pi)$. Is it possible to come to this conclusion without carrying out the matrix multiplication of the three rotation matrices? It looks that the $R_x(\theta)$ got cancelled somehow.
Comment: How can the product $AB$ be easier then $BA$ ??? In any case, whatever the computation procedure, the result is $ABA$ in all cases !
Comment: I did not say this, @Yves Daoust. Sorry for the misunderstanding. I said if I can reorder the $BA$, then the final product of the three matrices will be easier to compute.
Comment: How can it be if the result is the same ? There is no free lunch.
Comment: @Yves Daoust please read the context example I put at the end. It may give you some insight of what I am looking for. Also, read David K 's answer to have more insight about the example.
Comment: The product of three axial rotations is easy, as those matrices have a majority of zeroes/one. And it perfectly illustrates my comment: the final result is the same, whatever the computation procedure. http://mathworld.wolfram.com/EulerAngles.html
Answer: Sadly, no. As @TobyMak points out, the associativity
$$
A(BA) = (AB)A
$$
means you can choose to evaluate either $AB$ or $BA$ but there's no trick that will allow you to work with $A^2$.
You can probably show that with an example in which $A^2 = I$.
Answer: I take it that what you're trying to get at is that you have some matrix $A$ that you will use several times with several different other matrices in the place of $B.$
You would like some way to precompute a matrix $M_A$ by doing some operations on $A$
so that for any matrix $B$ you have $ABA = M_A B.$
First of all, if this is true in general it is true when $B=I,$ and therefore
$AIA = M_AI$ implies $M_A = A^2.$
But then for the formula to work in general you need $ABA = A^2 B$,
which implies $BA = AB,$ that is, the matrices have to commute.

In your particular example, the rotation $R_z(\pi)$ maps the axis of $R_x(\theta)$ onto itself, but reversed. Hence the initial rotation by $\theta$ becomes a rotation by $-\theta$. You will not get such a nice result for any $B$ that is not a rotation by a multiple of $\pi$, and even when $B = R_z(\pi)$ you will not get such a nice result for any non-trivial rotation around an axis that is not either the $z$ axis or an axis in the $x,y$ plane.
Comment: I might add that rotations in $\mathbb R^3$ that have a common axis do commute.
Answer: $$ABA = (AB)A$$
since matrix multiplication is associative. One proof of this is on this other post on Math SE.
Comment: That's fine. Could you include more context about the orthogonal matrices? I still find it hard to understand which particular forms you would like.
Comment: Thanks for the answer, but this is actually not what I am after. By reordering I meant changing the order from $ABA$ to something like $AAB$ or $AA^{-1}B$ or something similar. Let me edit my question to reflect this fact.
Comment: Sure, I'm on it.

Reordering of matrix multiplication


Display multiple window in Python

Question:
Simple question but can't find the answer, am looking for a module that allows me to display in one window multiple windows with python.
Example Above:

[![Example][1]][1]
[1]: https://i.stack.imgur.com/i8zzD.png
Comment: Like this https://www.tutorialspoint.com/pyqt/pyqt_multiple_document_interface.htm ?
Comment: Yes, thanks you.
Answer: I think you can have a idea to do this From here. Kivy can be used for the purpose Check this too.

Display multiple window in Python


Registering users for instant messaging

Question: I am planning for an application where the users has to register using their mobile number and they can communicate with their friends who uses the same app. I need to know what to do to make the application find if the users in the phone contacts have the same app?
Comment: You will need a server that will inform each user whom of his friends are using the app.
Answer:
Get a server
When a user signs up, register them on the server with their phone number
When another user signs up, register them, and then check their contacts with the numbers you already have registered.
If a number in their contacts matches one you have registered, then you have two users using the same app.
After that, use the server as a middle man in communicating between the two users.
Comment: Thanks @raghav . Now I have got an idea. After finding my friends, how to send a message to them? I don't want to use the inbuilt SMS service. I want to send message to them online like an instant messanger. Any ideas on where to get started on that? Thanks in advance.
Comment: There are many ways to do that, the two most common being sending the message to the server from one device, and then pushing it from the server to the other, or using the server as a middle man to create the connection between two devices, and then directly sending the messages. The first one is more robust and less prone to losing messages
Comment: ok I got it. What kind of service should I use for that? I mean how to push the message to the server and push from the server to the users according to their phone number?
Comment: GCM would be your best bet.
Answer: Find if the users contacts have the app?
Well you'll have to have a server to message, and that server will have a database.
Now this database will contain the information about the users including their numbers (or basically whatever fields you want).
Cross check against your database and you'll find who else has the app already.

Registering users for instant messaging


Creating new blob from older one that is stored in local storage

Question: I have basic html page where I want to upload image file, and after closing or reloading page I want that image to be there.
HTML code is :
<input type='file' accept="image/*">

Javascript code:
let img = document.querySelector('img');

document.body.onload = () => {
    if(localStorage.image){
        let source = JSON.parse(localStorage.image)
        let file =  new File([source], 'download.jpg', {type: 'image/jpeg', lastModified: Date.now()})
        img.src = URL.createObjectURL(file)
    }
}

document.querySelector('input[type="file"]').addEventListener('change', function() {
    img.src = URL.createObjectURL(this.files[0])
    localStorage.image = JSON.stringify(img.src)
});

My questions are:

When I console.log(localStorage.image), after uploading and reloading page, I will get one blob, and because from security reasons I can't use same blob, I tried to make new File and then from that file to create blob that I can later use, but when I console.log new blob (conosle.log(img.src)) I received different blob, so my question is why that happened, is there a way to correct that, I see that these two  files has different file.size but when I want to change that it stays same
Also is there a second way to do that
Answer: As you can't persist blob objects between sessions (the blob URL will expire), you need to use a serializable format such as a data URL. Using a FileReader you can read the image file straight to a data url, and this can be stored in localStorage.
const fileReader = new FileReader();

fileReader.addEventListener('loadend', function() {
  img.src = fileReader.result;
  storage['image'] = fileReader.result;
})

document.querySelector('input[type="file"]').addEventListener('change', function() {
    if (this.files.length > 0) {
      fileReader.readAsDataURL(this.files[0]);
    }
});

Here is a pen where I modified your code to use FileReader and data URLs (had to use sessionStorage because of codepen but localStorage should work)
https://codepen.io/Douile/pen/gOwORea?editors=1011


In JavaScript, how to replace every $WORD with an href to website while keeping the original message unchanged?

Question: I am a bit stumped. I am working with StockTwits data and one of the requirements of their API is that you need to link their 'cashtags' (a hashtag but instead of using # they use $).
My input data is

This is my amazing message with a stock $symbol that I need to click on

and what I need back (in string format) is

This is my amazing message with a stock  $symbol  that I need to click on

Obviously when it gets rendered I would just have $symbol clickable instead of the entire a href tag.
If it helps, for each message I have an array of all the symbols that will appear (without a $) infront of them.
Right now I am trying to do this and it is a bit messy but not sure how to get it to work right. I am doing this in react.
//Message incoming is: 'This is my amazing message with a stock $symbol that I need to click on'
const message_body = unescape(this.props.data.body)

//used for finding what words to replace. Output is ['symbol1', 'symbol2', 'symbol3']
let find = [];
for(let symbl of this.props.data.symbols){
  find.push(symbl.symbol)

}

//used for setting the values I want to replace in the incoming message
let replace = [];
for(let symbl of find){
  let url = `https://stocktwits.com/${symbl}`
  let link = `<a href=${url} target="_blank">${symbl}</a>`
  replace.push(link)

}

//using the replace-once library, it takes the message, words to find, what to replace them with, and global or not.
let formed_message = replaceOnce(message_body, find, replace, 'gi')

......

//using react-html-parser to convert the  tags into a clickable link
<Card.Text>{ReactHtmlParser(formed_message)}</Card.Text>

What all my code will output is

This is my amazing message with a stock $symbol that I need to click on

but the $ is not included in the link, as well as if symbol appears anywhere else, it will make it a link. Example below

$GOOG $SPY $AAPL off topic. Good job GOOGle!

in the above message, it still turns GOOGLe into a link, and I only want the ones leading with a $ to be considered.
Like I said, this is super messy and I am close but open to any and all suggestions.
Thanks
Comment: look into escaping special characters
Answer: Please try this:
let formed_message = this.props.data.symbols.map({symbol} = symbol).reduce(
      (p, s) => p.replace(`$${s}`, `<a href ='https://stocktwits.com/${s}' target='_blank> $${s}</a>`),
      message_body
)

const message_body = "This is my amazing message with a stock $symbol that I need to click on and also test $symbol2";

console.log(['symbol', 'symbol2', 'symbol3'].reduce(
      (p, s) => p.replace(`$${s}`, `<a href ='https://stocktwits.com/${s}' target='_blank> $${s}</a>`),
      message_body
))
Comment: so this works when I am doing the console log, but nothing comes back when I try to assign it to the variable like you have in your first code snippet

edit: for some reason ReactHtmlParser no longer likes it. But other then that, this looks to be exaclty what I was hoping for!
Comment: @Brian please try again, i've edited the first snipped
Comment: again it works, but now the issue i am Having is that ReactHtmlParser doesn't seem to like the tags anymore. The issue i found is that I need to wrap the entire thing in a tag in order to work. gives me the error  ``` cannot appear as a descendant of ```
Answer: You can use a regular expression to match all words preceded by a dollar symbol.

let text = 'This is my amazing message with a stock $symbol that I need to click on';
let res = text.replace(/\$(\w+)/g, (match,group)=>
   `<a href ='https://stocktwits.com/${group}' target='_blank> ${match} </a>`);
console.log(res);
Comment: but this won't work if there are words that have `$` that are not in the symbols list, no?
Comment: this also works, thank you! now i just need HTML parser to not yell at me and say
 ``` cannot appear as a descendant of ```


MySQL creates huge files every night, bringing down the server

Question: I have an Ubuntu 12.04 LEMP server with shop app ontop, running MySQL 5.5 as DB (currently since this problem started I've already switched to Percona with no success).
So, current facts: every night my monitoring tells me that the server is not responsive. Exact time varies. It can be down for several minutes, or even couple of hours. It can start at around 1 in the night or at any other time up through 5. Munin and atop shows that at this time iowait takes all resources, used disk space increases in steps by ~2Gb. Even up to taking all space available.
Mysql slow query log shows nothing. No slow queries at the time.
Web server log shows no special activity - just general web site use, static, shop, products, products listings. Nothing extra.
There are no entries in cron that might be executed at that time and that might do anything with DB.
Mysql SHOW EVENTS is empty on all databases. MySQL error log (with warnings logging enabled) has nothing at a time. Something appears there but only when disk is full, such as:
151028  4:03:54 [ERROR] Got an error from unknown thread, /mnt/workspace/percona-server-5.5-debian-binary/label_exp/ubuntu-precise-64bit/percona-server-5.5-5.5.45-rel37.4/storage/myisam/mi_write.c:226
151028  4:03:54 [ERROR] /usr/sbin/mysqld: Incorrect key file for table '/tmp/#sql_5e90_21.MYI'; try to repair it
151028  4:03:54 [ERROR] Got an error from unknown thread, /mnt/workspace/percona-server-5.5-debian-binary/label_exp/ubuntu-precise-64bit/percona-server-5.5-5.5.45-rel37.4/storage/myisam/mi_write.c:226
151028  4:03:54 [ERROR] /usr/sbin/mysqld: Incorrect key file for table '/tmp/#sql_5e90_20.MYI'; try to repair it
151028  4:03:54 [ERROR] Got an error from unknown thread, /mnt/workspace/percona-server-5.5-debian-binary/label_exp/ubuntu-precise-64bit/percona-server-5.5-5.5.45-rel37.4/storage/myisam/mi_write.c:226

Here are some munin graphs: CPU usage, Disk space usage (you can see some peaks on this graph - this is not normal for our server, there were no peaks prior to when this started).
This has started some time ago, before that server was okay, and server never demanded such amounts of disk space.
Comment: Have you looked to see if there are any cron jobs running at  the same time ? Is there a mysqldump running ?
Comment: It seems your /tmp get full, so it can't create the temporary table required.
Maybe it's because your data has increased ? So temporary tables have become much bigger, you should check the size of your biggest table.
http://dev.mysql.com/doc/refman/5.1/en/temporary-files.html
Comment: @Iain as I said there are no related jobs. There are backup jobs, but these run at another time.
Comment: @pat yes, root directory gets full and then unrelated errors occur. Data has not increased (it stays around the same size, ~200Mb). If you take a look at the disk space usage graph, you'll see that at Wed midnight free space is ~30% (6 GB), and then it drops down to zero in couple of chunks, each around 2 GB. The error in log occured at 4:03, but this space usage problem appeared at around 3:30. At 4:03 entire disk was full.
Answer: This error usually means disk full in my experience.
Try increasing the tmpfs partition size by remounting it:
mount -t tmpfs -o remount,size=1G tmpfs /tmp

Or, you can set the tmpdir=/some/drive in mysql config to move the tmp storage to some place with more available space.
Comment: As I said, that error is irrelevant, since drive has 6Gb free, and then suddenly MySQL takes up all that space. Sure, then it gets errors that occur when disk is full. The problem is: MySQL then releases that space and everything returns to normal. But it does not always take all space. It can take just 2g, and then release them back, but during this process server becomes unresponsive.


Create an event that is connected to the change of a variable value?

Question: I have issues with the following problem in AnyLogic:
I would like to create an event that is connected to a changing value of another variable. That variable can wheter be 1 or -1. At any moment it changes from -1 to 1, that event shall be triggered, but only once per occasion. Does anyone have a solution for this?
I already thought about implementing an boolean that checks that change, but I wouldn't know how.
Answer: You need to approach this the other way around.
You are trying to "monitor" the variable and wait for a change of it.
Instead, you should only allow 1 way to change that variable and add any additional model changes that come from it.
In OOP, you do it by:

setting your variable myVariable to access level private
adding a public function setMyVariable(int newValue) next to it
in the function, you have the code myVariable = newValue; AND any other code you want to be triggered whenever newValue==1 or newValue==-1
change your model such that myVariable is only ever changed via the function setMyVariable(...)
Comment: A *much* worse solution would be to have a cyclic event that constantly checks if `myVariable==1` and do something if it happens. *MUCH* worse :)


If $f$ is continuous in $[0,1]$, find $\lim\limits_{x \to 0^{+}}x\int\limits_x^1 \frac{f(t)}t dt$

Question: I'm solving this problem and I guess it shouldn't be too hard. Since $f$ is continuous it is bounded, so one has
$$\left| {x\int\limits_x^1 {\frac{{f\left( t \right)}}{t}dt} } \right| \leq x\int\limits_x^1 {\left| {\frac{{f\left( t \right)}}{t}} \right|dt}  \leqslant Mx\int\limits_x^1 {\frac{{dt}}{t}}  =  - Mx\log x \to 0$$
Where $M=\operatorname{sup}\{|f(x)|:x\in[0,1]\}$
I'm not 100% certain on this, so I want a better, clearer approach.
Then, there is a second problem, similar, which is:
If $f$ is integrable on $[0,1]$ and $\exists\lim\limits_{x\to0}f(x)=L$, find
$$\ell  = \mathop {\lim }\limits_{x \to {0^ + }} x\int\limits_x^1 {\frac{{f\left( t \right)}}{{{t^2}}}dt} $$
ADD: The second might follow from the first since
$$\mathop {\lim }\limits_{x \to {0^ + }} x\int\limits_x^1 {\frac{{f\left( t \right)}}{{{t^2}}}dt}  =\mathop {\lim }\limits_{x \to {0^ + }}  f\left( x \right) - xf\left( 1 \right) + x\int\limits_x^1 {\frac{{f'\left( t \right)}}
{t}dt} $$
$$ = L + \mathop {\lim }\limits_{x \to {0^ + }} x\int\limits_x^1 {\frac{{f'\left( t \right)}}{t}dt} $$
So, what can I sat about $f'(t)$ given $f(t)$ is integrable on $[0,1]$ that will allow me to apply the first case to the last limit?
Comment: The first argument is fine, except that the first $<$ should be $\le$, and you should say explicitly that $M=\sup\{|f(x)|:x\in[0,1]\}$ and that at the end you're taking the limit as $x\to 0^+$.
Comment: @Brian Ok. I thought the $M$ was implicitly defined, but I guess it is appropriate to clarify. Any hints on the second one?
Comment: Not offhand; there might be after I think about it a bit, but someone else is likely to get there first.
Comment: You can't speak about $f'$ in second problem, since $f$ is only integrable
Comment: @Norbert Is there any way to prove that $x\int\limits_x^1 {\frac{{f'\left( t \right)}}{t}dt} \to 0$?
Comment: The problem is that $f'(t)$ has no meaning for general integrable funtion. There a lots of integrable functions which are not differentiable. For examplу Reimann function.
Comment: You can check out my user page, it has a lot of similar questions that might be of interest to you.
Answer: If $f$ is continuous let's use L'Hopital rule
$$
\lim\limits_{x\to+0}x\int\limits_{x}^{1}\frac{f(t)}{t}dt=
\lim\limits_{x\to+0}\frac{\int\limits_{x}^{1}\frac{f(t)}{t}dt}{x^{-1}}=
\lim\limits_{x\to+0}\frac{-\int\limits_{1}^{x}\frac{f(t)}{t}dt}{x^{-1}}=
\lim\limits_{x\to+0}\frac{-\frac{f(x)}{x}}{-x^{-2}}=
\lim\limits_{x\to+0}xf(x)=0
$$
$$
\lim\limits_{x\to+0}x\int\limits_{x}^{1}\frac{f(t)}{t^2}dt=
\lim\limits_{x\to+0}\frac{\int\limits_{x}^{1}\frac{f(t)}{t^2}dt}{x^{-1}}=
\lim\limits_{x\to+0}\frac{-\int\limits_{1}^{x}\frac{f(t)}{t^2}dt}{x^{-1}}=
\lim\limits_{x\to+0}\frac{-\frac{f(x)}{x^2}}{-x^{-2}}=
\lim\limits_{x\to+0}f(x)
$$
P.S. Big thanks to David Mitra, he pointed out that requirement for integrals to be divergent is unnecessary!
Comment: Remember that you can only use l'Hopital's rule if the limit is in an indeterminate form (in this case, $\infty/\infty$). So your proof works only in the case that the integral in the numerator goes to infinity.
Comment: @GregMartin For the infinite limit case, you do not need the numerator to tend to infinity to use L'Hopital's rule, only the denominator.
Comment: @GregMartin For your example, the limit of the quotient of the derivatives does not exist. L'Hopital doesn't apply (Lopital states if the limit of the quotient of the derivatives *exists*, then...
Comment: Accordingly upvoted. However, I'm looking for an approach following what I proposed.
Comment: Ok, I will add this restrictions
Comment: @DavidMitra I don't understand Greg said that there must be infinity in the numerator
Comment: @DavidMitra: try using l'Hopital's rule on $\lim_{x\to\infty} \frac{\sin(x^3)}x$.
Comment: @Norbert It's not well-known, but the hypothesis that the numerator tends to infinity is not needed. The [wiki page](http://en.wikipedia.org/wiki/L%27H%C3%B4pital%27s_rule) on L'Hopital's rule mentions this. In some analysis texts, such as Bartle and Sherbert's *Introduction to Real Analysis*, the theorem is stated: "Let $f,g$ be differentiable on $(a,b)$ with $g'(x)\ne 0$ for all $x\in(a,b)$. Suppose that $\lim\limits_{x\rightarrow a^+}g(x)=\pm\infty$. Then if $\lim\limits_{x\rightarrow a^+}{f'(x)\over g'(x)}=L$, it follows that $\lim\limits_{x\rightarrow a^+}{f(x)\over g(x)}=L$.
Comment: Fair enough. Let me instead say that the version of l'Hopital that we often use in practice - that is, just take derivatives of numerator and denominator and see what happens - is not valid unless the original limit has an indeterminate form.
Answer: For the first problem, your approach is fine (but the first inequality maybe be an equality when $f$ is non-negative). For the second, denote $L:=\lim_{x\to 0}f(x)$. Fix $\varepsilon>0$. We can find $\delta>0$ such that if $0\leq x\leq \delta$ then $|f(x)-L|\leq \varepsilon$, so for $0\leq x\leq \delta$:
$$x\int_x^1\frac{f(t)}{t^2}dt=x\int_x^1\frac{f(t)-L}{t^2}dt+Lx\int_x^1\frac{dt}{t^2}=x\int_x^1\frac{f(t)-L}{t^2}dt+L\left(\frac 1x-1\right)x$$
hence
\begin{align*}\left|x\int_x^1\frac{f(t)}{t^2}dt-L\right|&\leq x\int_x^1\frac{|f(t)-L|}{t^2}dt+|Lx|\\
&=x\int_x^\delta\frac{|f(t)-L|}{t^2}dt+ x\int_\delta^1\frac{|f(t)-L|}{t^2}dt+|Lx|\\
&\leq x\int_x^\delta\frac{\varepsilon}{t^2}dt+ x\int_\delta^1\frac{|f(t)-L|}{t^2}dt+|Lx|\\
&=\varepsilon x\left(\frac 1x-\frac 1{\delta}\right)+x\int_\delta^1\frac{|f(t)-L|}{t^2}dt+|Lx|\\
&=\varepsilon-\frac{\varepsilon}{\delta}x+x\int_\delta^1\frac{|f(t)-L|}{t^2}dt+|Lx|
\end{align*}
so
$$\limsup_{x\to 0^+}\left|x\int_x^1\frac{f(t)}{t^2}dt-L\right|\leq \varepsilon$$
and since $\varepsilon$ was arbitrary, $L=\ell$.
Comment: I'm OK with this, but can't you devise an approach that avoids the prediction that the limit is indeed $L$? (See my last edit, where it suffices to show that the integral goes to zero).
Comment: @PeterT.off My approach gives prediction for integrabale $f$ :)
Comment: First we work in the case on which $\ell=0$, , using $g=f-\ell$, then we try to generalize.