Walking bass line/chord help

Question: I've been playing bass for about a year, so pardon my question, what is the relation between chords, arpeggios and scales? I always learnt and played scales, but in order to learn this new jazz bassline my teacher has me do, it only shows the chord (G7, C7, etc, etc) and no notes. How am I suppose to play it? Im trying to learn more arpeggios but I can't seem to put two and two together and see what arpeggios have to do with chords.  I also am wondering what the chord tone (if that is the right word) means in the difference of playing it, like the different of a diminshed chord and any other chord.
I hope I'm not getting ahead of myself, is there anyway I can learn to play chords?
Comment: Teacher *should* be explaining all this - or should have already! The how and the why. But welcome to the site where several will come up with everything you need - and more!
Answer: Not that you can't ask here, but given that you have a teacher and your teacher gave you the material, your teacher would be the perfect person to ask.
Anyway, let's start with a few very basic definitions:

Scale: An ordered collection of notes. For our purposes we'll use a C Major scale which you are probably familiar with.
Chord: Several notes played at the same time
Arpeggio: The notes of a chord played one at a time in succession.

Now how do they relate to each other? There's a lot to this question so, again, we'll have to keep it very basic.
To start with the chords we use are usually built from a scale. If we take a C Major scale and harmonize it in 3rds, we'll get a chord for each degree in the scale. In other words we'll create a chord from each scale degree by stacking 3rds which is like taking every other note from the scale.

CMaj7: C, E, G, B
Dm7: D, F, A, C
Em7: E, G, B, D
FMaj7: F, A, C, E
G7: G, B, D, F
Am7: A, C, E, G
Bm7(b5): B, D, F, A

So we used a scale to build some chords. And now we can use the chords to build a chord progression:
Dm7   |  G7  |  CMaj7
Now let's say the pianist is playing those as full chords (playing all the notes simultaneously). As a bass player your job is to outline that same harmony but usually using single notes. The easiest way to do that is by using arpeggios. So during the bar of Dm7, you'd play the notes D, F, A, or C. And during the bar of G7 you'd play the notes G, B, D, or F. These are all notes of C Major scale so you could just play that. But you'll outline the harmony better—and it will sound better—if you target the chord tones, or the notes that make up that specific chord, by playing an arpeggio.
Walking Bass
All that said, there's a bit more to walking bass lines than just playing arpeggios. You usually want to play certain notes on certain beats and throw in some passing notes as well. Here are few tips to get started:

The first beat should usually be the root of the chord (D for Dm7). It's pretty important that the bass player is covering the root of the chord because the pianist or guitarist playing the chords might not.
The third beat (assuming the chord lasts a full bar) should be a chord tone
The second and fourth beats may be passing tones (leading you from one chord tone to the next) from the chord scale. (Remember how we built the chord from a scale? We can use notes of that scale as passing notes—technically we'd probably say the "chord scale" is D Dorian for Dm7 and G Mixolydian for G7 but those are still the same notes as C Major)
Don't leap into or away from any passing tone or non-chord tone. Try to use stepwise motion instead.
Chromatic half-steps from above or below leading into the next chord can work well and are very idiomatic in jazz bass lines. Just don't abuse them too much or it starts to sound cliché.

That's definitely a simplification of it and those rules are not set in stone. But that should get you started.
Comment: Thanks for helping me understand. So if I'm playing the chord of c major for 4 beats and I play a chord tone on beats one and three, how would I do that? C, E, and G are the chord tones right, so what would I use as the passing notes? Would I use open D if I'm going C to E?
Comment: If you are playing C on beat 1 and E on beat 3, then yes, D would be a good option for beat 2 as a passing note. As for beat 4, that depends on what the next chord is.
Comment: The term 'walking' might be a clue to what would be good between C and E!
Comment: @Jeremiahh Patrick Pfeiffer explains this really well in Bass For Dummies, he goes through each note of the scale with a given chord and guides you to play that note frequently/on a strong beat, or very sparingly. In your example, you can use D (2nd) to get to somewhere else like the E third or G fifth but use it only as a passing note and keep it short    You can play anything you like that sounds good, its making it sound good to others that is the tricky part.
Answer: Chords are just several notes played at the same time. So that G7 in your exercise: the G7 chord has the notes G, B, D and F (if you're asking why, that's because if you changed any of the notes, it wouldn't be a G7 anymore, it would be a different chord; the G7 sound is actually defined by the notes G, B, D and F put together). And if I play them all at the same time, like on a piano, I get that very specific G7 sound. Now, you can think of arpeggios as really just chords played one note at a time. So on your bass, if you play G, then B, then D, then F, (i.e., NOT all at the same time, but instead one by one) what you did is arpeggiate the notes of the G7 chord - but we now call it a G7 arpeggio because you played it one note at a time, "bottom to top" starting from G and ending at the F. There really isn't any trick here, so if it feels like you're missing something, you really aren't (from a practical perspective). Arpeggios are chords just broken up into pieces, and chords are arpeggios played all at once. Make sense?
Now as far as scales go, that gets a little more complicated because names of what are called modes get involved. The scale that is typically taught to accompany a G7 sound is called G mixolydian. If that name sounds scary, that's totally fine; I normally don't teach students modes until they're well acquainted with chords and arpeggios first, and then the major and minor scales (I'm aware most teachers tend to teach them earlier than that). As far as playing bass goes, it's far more important for you to become acquainted with your chords and arpeggios first (and be able to know all of the chord tones of any given chord, or figure them out) because a good jazz musician "knows all of his/her changes," i.e., knows their chords and arpeggios inside and out.
As far as basslines go: They are, out of necessity, mainly constructed out of chord tones because the bass has the task of both describing the harmony as well as keeping time. If you're new to playing jazz bass and you use that G mixolydian scale on that G7, you could make it sound like a whole bunch of other unrelated chords and could cause confusion to the other players on the bandstand. However if you play that G7 arpeggio by itself, absolutely nobody will be confused as to what chord you're playing (even if a plain G7 isn't super interesting to the ear, it's still 100% right). That's in part why arpeggios are so important for building basslines. After you learn your arpeggios (and chords) you can start creating more interesting basslines by adding other stuff to them, like approach notes, passing tones, scale tones, and so on. I hope that clears it up a little.
Comment: To become a *really* splendid answer, walking bass needs explaining. Can't get away with just arpeggios as a walking bass.

Walking bass line/chord help


Introspect referenced type of an annotated class

Question: I'm developing an annotation processor aiming to generate code by introspecting annotated class return types methods.
I have 2 modules:

app: containing my annotated classes
processor: containing my annotation and the relative processor

These are my gradle files:
app/build.gradle
plugins {
    id 'java'
}

dependencies {

    testImplementation 'org.junit.jupiter:junit-jupiter:5.7.2'

    implementation project(':processor')
    annotationProcessor project(':processor')
}

compileJava {
    options.annotationProcessorPath = configurations.annotationProcessor
}

processor/build.gradle
plugins {
    id 'java-library'
}

repositories {
    mavenCentral()
}

dependencies {

    testImplementation 'org.junit.jupiter:junit-jupiter:5.7.2'
}

settings.gradle
rootProject.name = 'MyProject'
include('app')
include('processor')

I have this annotation (processor module)
@Target(ElementType.TYPE)
public @interface MyAnnotation {

}

This is an annotated class
@MyAnnotation
public class DogGenerator {

    public Dog getDog() {
        return new Dog("Brutus");
    }
}

This is my processor
@SupportedSourceVersion(SourceVersion.RELEASE_11)
@SupportedAnnotationTypes("com.myann.MyAnnotation")
public class MyAnnotationProcessor extends AbstractProcessor {

    private Filer filer;
    private Messager messager;
    private Elements elementUtils;

    @Override
    public synchronized void init(ProcessingEnvironment processingEnv) {
        super.init(processingEnv);
        filer = processingEnv.getFiler();
        messager = processingEnv.getMessager();
        elementUtils = processingEnv.getElementUtils();
    }

    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {

        final Set<? extends Element> elementsAnnotatedWith = roundEnv.getElementsAnnotatedWith(
                MyAnnotation.class);

        for (Element annotatedElement : elementsAnnotatedWith) {
            if (annotatedElement.getKind() != ElementKind.CLASS) {

                messager.printMessage(Kind.ERROR, "Only classes and method can be annotated with " + MyAnnotation.class.getSimpleName(), annotatedElement);
                return false;
            }

            TypeElement typeEl = elementUtils.getTypeElement(annotatedElement.asType().toString());
            final Element method = typeEl.getEnclosedElements()
                    .stream()
                    .filter(o -> o.getKind() == ElementKind.METHOD)
                    .findFirst()
                    .get();

            TypeMirror returnType = ((ExecutableElement)method).getReturnType();
            messager.printMessage(Kind.WARNING,"return type " + returnType.toString());

        }

        return false;
    }
}

With this code I'm able to print the return type com.myann.Dog, but how can I introspect it in order to get its fields or methods?
If I try to load the class with Class.forName, I receive a ClassNotFoundException.
If I add app module as a dependency of the processor module I hit a circular dependency error.
Comment: How about using the same method you already used in the code, `elementUtils.getTypeElement(…)`?
Comment: @Holger you are right, I don't know why I didn't try that way XD thanks
Answer: This is what I ended up with, ymmv:
for (TypeElement tEl : annotations) {
  for (Element el : roundEnv.getElementsAnnotatedWith(tEl)) {
    // .. put yer code 'ere arrrr
  }
}


Comma Separated Numbers For an Axis in Flot

Question: Is there a way to have Flot make axis numbers be comma-separated?
So for example, instead of 1000000 have 1,000,000
Answer: You can do that by using the tickFormatter property of the axis.
<code>xaxis: {
  tickFormatter: function(val, axis) {
    // insert comma logic here and return the string
  }
}
</code>
Source: http://people.iola.dk/olau/flot/API.txt (under "Customizing the axes")
This page has a function to format numbers with commas: http://www.mredkj.com/javascript/nfbasic.html
For Example on the yaxis:
<code>    $(function () {
            var plotarea = $("#plotarea");
            $.plot( plotarea , [data], {
                            xaxis: {mode: "time", timeformat: "%m/%d %H:%M:%S"},
                            yaxis: {tickFormatter: function numberWithCommas(x) {
                                      return x.toString().replace(/\B(?=(?:\d{3})+(?!\d))/g, ",");
                                }
                            },
                            points: { show: true },
                            lines: { show: true, fill: true }

                    } );
    });
</code>
Comment: I saw this, but wasn't quite clear on how a function operates on it though
Comment: Whenever Flot wants to print the value of a tick for an axis, it will pass the value ('val' up above) and the axis into the function you supply, and it'll use the return value of that function as the label of the tick. Say up above if you replaced the comment with **return "foo"** then all of your tick labels would be "foo"
Comment: And axis should be 'x' or 'y'?
Comment: Depends on which axis you want to format. If it's both, then you'll want to set this property on both axes.
Comment: Oh, I'm being dense. I didn't realize that this went within the `xaxis:` or `yaxis:`. Updated your post with a working complete example for the yaxis.


Preciso clonar o conteudo de uma div e colocar no form de meu modal

Question: Boa tarde pessoal.
Mais uma vez recorro a vocês sobre um problema que tenho.
Estou precisando usar a sintaxe abaixo em um modal.
$("#divConsulta").clone().appendTo($("#formFruta"));

Na linha abaixo ao clicar, eu abro meu modal com o formulário de dados a atualizar:
<a href="<c:url value="edita?cod=${fruta.cod}"/>" class="btn btn-success btn-xs" data-toggle="modal" data-target="#update-modal" title="Editar">

O prolema é que não sei como fazer esse:

clone().appendTo

para o meu modal.
Resumindo, não sei se estou correta, preciso passar o conteudo de uma div que está em uma página, que ao ser clicado o botão de abrir modal, o conteudo de #divConsulta vá para o #formFruta que esta em um modal do Bootstrap.
Espero ter sido clara, pois estou a horas tentando isso.
Grata
Comment: @Ricardo lendo a documentação (http://api.jquery.com/appendto/) o método `appendTo` aceita como parâmetro: selector, element, HTML string, array de elementos ou objeto jQuery, portanto o `$('#formFruta')` é um valor válido. O problema deve ser outro.
Comment: Eu acredito que não precisa usar o $('#formFruta') para identificar o elemento, usa apenas ('#formFruta'). Ficaria assim: $("#divConsulta").clone().appendTo("#formFruta");
Comment: O elemento com o ID `formFruta` existe no momento que o append é executado? Ocorre algum erro? Dê uma olhada na console do browser para ver se alguma exception é disparada.
Answer: O problema pode ser que quando você tenta inserir o conteúdo clonado do elemento #divConsulta, o conteúdo do modal ainda não foi inserido no DOM e, portanto, o elemento #formFruta ainda não está disponível para manipulação com Javascript.
Tente os eventos shown.bs.modal ou show.bs.modal do Boostrap:
$("#update-modal").on('show.bs.modal', function () {
    $("#divConsulta").clone().appendTo($("#formFruta"));
});

Espero ter ajudado.
Comment: Funcionou perfeitamente. Muito obrigada
Answer: Tenta assim: $("#divConsulta").clone().appendTo("#formFruta");
Dá uma olhada nesse teste que eu fiz, vê se te ajuda: plunker
Comment: Lendo a documentação (api.jquery.com/appendto) o método appendTo aceita como parâmetro: selector, element, HTML string, array de elementos ou objeto jQuery, portanto o $('#formFruta') é um valor válido.
Answer: Acho que a melhor formar de se fazer isso é com o append e não o appendTo.
Você pode usar assim:
var div = $("#divConsulta").clone();
$("#formFruta").append(div);

Dessa forma você está adicionando um conteúdo clonado ao formulário.


Series proof validity and questions

Question: I want to prove that: For all $t \in \mathbb{N}$, show that
$$
\sum_{k=2^{t-1}+1}^{2^{t}} \frac{1}{k} \geq \frac{1}{2}
$$
My attempt:
$$
\sum_{k=2^{t-1}+1}^{2^{t}} \frac{1}{k}=\frac{1}{2^{t-1}+1}+\frac{1}{2^{t-1}+2}+\frac{1}{2^{t-1}+3}+\cdots+\frac{1}{2^{t}}
$$
for any $k \in\left\{1,2,3, \ldots, 2^{t-1}\right]$ we have
$$
2^{t-1}+k \leq 2^{t} \Rightarrow \frac{1}{2^{t-1}+k} \geq \frac{1}{2^{t}}
$$
Using the above inequality we get
$$
\sum_{k=2^{t-1}+1}^{2^{t}}=\frac{1}{2^{t-1}+1}+\frac{1}{2^{t-1}+2}+\frac{1}{2^{t-1}+3}+\cdots+\frac{1}{2^{t}} \geq \frac{1}{2^{t}}+\frac{1}{2^{t}}+\frac{1}{2^{t}}+\cdots+\frac{1}{2^{t}}=\frac{2^{t-1}}{2^{t}}=\frac{1}{2}
$$
I want to show this inequality is true so that I can show that the limit of the sequence of partial sums $ \sum_{k=1}^{2^t} {\frac{1}{k}}$ diverges to infinity, If I can conclude this, can I also argue that since this is a subsequence of $ \sum_{k=1}^{n} {\frac{1}{k}}$ so that $ \sum_{k=1}^{n} {\frac{1}{k}}$ must diverges as $n$ goes to infinity or the subsequence is not a valid argument here?
Comment: This proof is fine.
Comment: This is, indeed, precisely the standard argument.
Answer: Your proof is valid. Regarding your questions, you should consider, as a consequence of your result, that:
$$\sum_{t=1}^n \sum_{k={2^{t-1}+1}}^{2^t} {\frac 1k}\geq \frac n2$$ Then, if you let ${n\to \infty}$, your proof will be completed.

Series proof validity and questions


Flutter flavor for iOS gives SharedPreference error on run

Question: Issue faced while trying to run flavors for iOS using Build Schemas
 /Labs/Workspace/Flutter/camp-flutter/ios/Runner/GeneratedPluginRegistrant.m:6:9: fatal error:
    'shared_preferences/SharedPreferencesPlugin.h' file not found
    #import <shared_preferences/SharedPreferencesPlugin.h>
            ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    1 error generated.

Flutter Doctor output
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, v1.7.8+hotfix.4, on Mac OS X 10.14.5 18F132, locale en-IN)

[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
[✓] Xcode - develop for iOS and macOS (Xcode 10.3)
[✓] iOS tools - develop for iOS devices
[✓] Android Studio (version 3.4)
[✓] VS Code (version 1.36.1)
[✓] Connected device (1 available)

• No issues found!

Additional Information
We are using flavors and schemes for iOS build and using below command to run applications
flutter run --flavor abcd --target lib/main/abcd_main.dart

Comment: Can you run flutter run with verbose to see if it gives any additional error information. `flutter run --flavor abcd --target lib/main/abcd_main.dart --verbose`
Answer: Uh, given that we can run build flavors via the changes from flutter 1.2 to 1.5 would not that be easier?
You use a build delegate your build config will use a new target flag that points to your new build flavor via dart file..see my medium post and several others talking about ti on medium...
BuildExtensions
The only hiccup is once in a while you have to wipe the emulator or device due to it having the old build flavor but generally it works
Comment: Fred, this isn't an issue, we can create dart level configs easily but the problem statement is with iOS Schemas that helps to develop different products by bundle id
Answer: I just tried the debug and release build and there is some rules for this workaround:
folder to add .h file
debugging on simulator => ios/Debug-iphonesimulator
debugging on iOS => 'ios/Debug-iphoneos'
release on iOS => 'ios/Release-iphoneos'
BTW, I can build my project in all modes with many 3rd lib using this workaround.
Answer: In my opinion, this problem can be resolved in two ways. They are below.
I checked in one of my project and found SharedPreferencesPlugin.h has following code.
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#import <Flutter/Flutter.h>

@interface FLTSharedPreferencesPlugin : NSObject <FlutterPlugin>
@end

This file is present at location :

(mysiyaram is the project name)
Now you might have two ways to solve this issue.
Plan A : You create the file manually with the code above. It doesn't contain any version specific info any way.
Plan B : Create another dummy project, add shared preferences in there. And copy the file (or folder structure) from the dummy project to your project.
Note : Please take this options as a workaround since I don't know the structural solution.
Comment: Didn't actually worked out this way. What I am seeking is a solution for managing Build Schema in iOS


Is there any way to run linux non locally for a big group of people?

Question: we want to use a custom linux distro over the internet with Gui for some simple tasks (mainly writing running simple python programs) and not something very computationally intensive.
At its peak the system could be used from 150 people max.
Is there any way to make something like that work? E.g. something like amazon's cloudfront but in a local server implementation.
Comment: When you say "over the internet", what kinds of speeds are available? If it's on a local network (i.e. 10/100/1000MBit LAN) then something simple like VNC may work; if it's over the general internet, you'll probably want to use something like X forwarding (mentioned below) which is much more efficient.
Answer: Running that many sessions simultaneously is going to take some pretty serious hardware, and tradeoffs need to be made. Don't forget that amazon has pretty much an entire cluster of servers set up to run together.
One tradeoff is efficiency of your network usage (where nx is better) over processor use (where simple x forwarding is better).LTSP is one option but you'll need sufficient ram for all these graphical sessions - LTSP/ubuntu  recommends a quad processor system with a gig of ram for THREE clients, though what you'd need, practically would likely be significantly less, depending on the setup and usage patterns.
Comment: It is the base system of LTSP that uses that gigabyte. 2GB would run those 200 clients easily.
Answer: X11 provides such access. Maybe NX would use less bandwidth.
Comment: You mean X forwarding? It's horrible. ;)
Comment: Why is it horrible? I have no experience with it. Probably it will be over the internet. I guess I have to go with something scalable like cloudfront?
Comment: What forwarding? I mean direct XDMCP access....
Answer: If your Users already have ssh access, simply using ssh with x forwarding should suffice in many cases.
If not, you may want to check out x2go: http://www.x2go.org/


How can I verify Windows DNS forwarders are working?

Question: I thought I knew how to do this, but I guess not.
Even the d2 debugging in nslookup doesn't show the actual forwarder being queried.
So...let's say I set up DNS forwarders in a Windows DNS server and then query using nslookup (or something else?) that server for an external FQDN like "www.purpleflowers.com".
Can I actually see where the Windows DNS server is querying its forwarder, which forwarder it ended up using, and the response from that forwarder?
Comment: Why would you expect debugging in `nslookup` to show this? The forwarding is being done by the server, not the client.
Comment: Can you turn on query logging on the servers you're forwarding to?
Comment: @Barmar - the forwarders are at OpenDNS...not something I can administer.
Comment: Try this using ETW: https://stackoverflow.com/a/34518185/843000  haters gonna hate.
Answer:
Can I actually see where the Windows DNS server is querying its forwarder, which forwarder it ended up using, and the response from that forwarder?

I am not aware of any logs that would give you that detail.  But you could always start a packet capture filtering for DNS traffic.  You should see the requests come in from your clients, and requests going out to your configured forwarders for requests that couldn't be answered from the cache.
Comment: Thanks Zoredache...that's what I figured but had a little hope that my Google-Fu was failing me.  I'll grab a packet capture and edit your answer with that info sometime this week.  (BTW, in my particular case, we were switching to OpenDNS and Umbrella.  They have a "verify" page that basically verifies they are receiving DNS queries from your WAN IP.  That's good enough for me, but the question is still relevant for others that don't use them)
Answer: DNS packages doesn't contain information about its source and destination they are doing automatically using the DNS query cascade.
What you can do to know if it's working the forwarders or not is to set up a client with the Windows Server DNS IP as only DNS.
Make sure to clean up the cache by executing (ipconfig /flushdns) on client.
Then try without any forwarder configured it, you should have issues to hit external sites. (remember that there's cache information involved in client and in server too that needs to be cleaned up).
Then try using one forwarder like 184.108.40.206 and you should be able to reach the sites, but the specific ip of what DNS server is being queried you won't be able to get that information since in the networking level there's no such information.
Here's an interesting question related to what you want: https://www.experts-exchange.com/questions/24079211/How-can-I-trace-the-DNS-forwarder-query-from-my-Server.html
Comment: Jose, I appreciate the answer but this part `Then try without any forwarder configured it, you should have issues to hit external sites.` isn't true.  Most of our DNS servers aren't configured with forwarders but simply use the Root Hints servers as their non-authoritative lookup.  You should edit that part out (or I can) to not confuse others.


User picture on multi site / multi database setup

Question: I have an unusual problem that doesn't appear to have a workable solution....
We have a multi-site setup that has a shared database for taxonomy and the users tables and it's related tables.
Each site then has it's own core database with content, permissions and file_managed.
We would like to keep the file managed table unique to each site, as the amount of images and video's expected will be significant over time.
This leaves us with one small issue in that the "picture" field in the user table is referring to a FID from the file_managed table. If I set my profile picture when on site 1, it works great. If I visit site 2, the same user table will return a FID from that site, which could and usually would be a completely different picture.
Has anyone had any experience in getting around this situation? We don't want to go down separate users for each site, and we don't want to have one file table for all sites.
Ideally I'd like to be able to hard code a url for the "picture" field in the user table, but I'm not sure if this is possible?
Any help is very much appreciated.
Answer: What I would do is:

Use hook_form_alter to add non-managed file upload to profile edit page.
Configure Drupal or webserver so that directory for these files was common, or so that all pictures would get uploaded to the "main" site's folder.
To a profile, I would add a link field. Configure it to be shared between sites, too.
In a submit handler (again, added using hook_form_alter) I would populate this field with the URL to uploaded image.
Comment: So does the link field you refer to in step 3, link the picture dynamically to whatever is in the new non managed field we've created
Comment: @BeardedGeek I'm not sure I understand your comment, but if I do then yes, that's the idea.


MySQL impossible suspicious connections

Question: I have a MySQL Community service binded locally to "bind-address=127.0.0.1", bind that suppose no expose it to the internet.
I can't connect externally. However i'm receiving constantly on the log this kind of errors:
<code>[Server] IP address '194.**.16.73' could not be resolved: This is usually a temporary error during hostname resolution and means that the local server did not receive a response from an authoritative server.

[Server] Host name 'hos*<probabily a malicious site>*nnet.biz' could not be resolved: No such host is known.
</code>
With a lot of addreses supicious (including TOR exit points).
I see this thread Suspicious Connections to My Database x.x.x.x Could Not Be Resolved
But didn't respond the main question:

How is possible that kind of requests without internet access?

What does fire this? Ok i understand, server want to nslookup it, but, what are trying from that hosts? It's dangerous?

If someone can bring ligth to my life I will be very grateful.
Thanks.
Comment: What is the log file that contains these errors? Can you provide a bigger snippet of the log file?
Comment: Hello. Is Error log of MySQL Community Server  8 and all entries are the same. With repeated and another hosts.
Comment: Please tell what is the path for this log file.
Comment: I found the problem. Reply on  my own question.
Answer: I found it.
Solution for help someone in the future:
The problem is MySQL since idk what version opens antoher tcp listener for Plugin X. Has to bind it locally too.

MySQL impossible suspicious connections


Why does variable only increment once in Java code?

Question: I am making a game where a player ('P') starts on a 2d array of dashes at [0][0]. The player is prompted to enter the size of the array, and then enter an action (left, right, up, down, or exit). When that action is entered, 'P' is supposed to move by 1 index.
I am working on my moveDown method and nothing else yet. When I type "down", it will increment to theWorld[1][0], but will not increment again (theWorld[2][0]) if I type "down". It just stays at [1][0].
There are two classes to this program, but the only thing my other class has right now is the main method and the world.userInput method, so I won't include that. This is a work in progress, so excuse any sloppy code, extra space, etc. Here is what I have so far:
<code>    import java.util.Scanner;

class World {

private int characterRow;
private int characterColumn;
private char[][] theWorld;
char player = 'P';
int playerX = 0;
int playerY = 0;
String userAction;
boolean keepPlaying = true;
boolean outOfBounds;

public World() {

    characterRow = 0;
    characterColumn = 0;

}
public World(int height, int width) {

    this.characterRow = height;
    this.characterColumn = width;

}

public void setHeight(int height) {

    characterRow = height;

}
public void setWidth(int width) {

    characterColumn = width;

}
public void userInput(int height, int width, int x, int y) {
    Scanner input = new Scanner(System.in);

    System.out.print("Enter World width: ");
    width = input.nextInt();
    System.out.print("Enter World height: ");
    height = input.nextInt();

    displayWorld(height, width, x, y);

    input.nextLine();

    while(keepPlaying)
    {
    System.out.print("ACTION > ");
    String action = input.nextLine();

    while(!action.equalsIgnoreCase("exit"))
    {
        keepPlaying = true;
        if(action.equalsIgnoreCase("down") && x > theWorld.length)
        {
          outOfBounds = true;
          System.out.println("You cannot go out of bounds. Try again.");
        }
        else
        break;
    }

    if(action.equalsIgnoreCase("down"))
    {
        moveDown(height, width, x, y, action);

    }
}

public void moveDown(int height, int width, int x, int y, String action) {

      if(x < theWorld.length-1)
      {
      x += 1;
    }
      displayWorld(height, width, x, y);

}

    public void displayWorld(int height, int width, int x, int y) {
    theWorld = new char[height][width];
    for(height = 0; height < theWorld.length; height++)
    {
        for(width = 0; width < theWorld[height].length; width++)
        {

            theWorld[height][width] = '-';
            theWorld[x][y] = player;

            System.out.print(theWorld[height][width] + " ");
        }
        System.out.println();
    }

}//end displayWorld
}//end class
</code>
Comment: Are you sure `theWorld.length` > 2 ?
Comment: Yes. I'm using 5 for height and width right now. Just a small number to work through the program. It increments once, then I type "down" again, and it reprints the array with the 'P' still at [1][0], no matter how many times I do it.
Comment: Have you tried to print it in `moveDown`, just to double check ?
Comment: That's why I have the displayWorld(height, width, x, y) method after the increment. Perhaps my logic is incorrect. It reprints the first time just fine, just not after any subsequent actions.
Comment: Why in the world was this question given a down vote? I see where beginners stand when they are struggling. I figured it out anyway, so I'll post my answer.
Answer: I added a setPlayerX method, and changed the assignment in moveDown to what you see here. It works now, so I figured it out.
<code>   public void setPlayerX(int x) {
    x = 1;
    playerX = x;
}
    public void moveDown(int height, int width, int x, int y) {
    x++;
    playerX = playerX + x;
    displayWorld(height, width, x, y);

}
</code>


Magento completely crashed after flushing cache

Question: I'm new to Magento, but I managed to install Magento and also installed a new theme. While I was modifying and customizing Magento I needed to flush the cache (Magento itself suggested it). I had done this already twice, but the third time Magento completely crashed.
I have no idea what is gone wrong, but I cannot access the site anymore.
When I want to visit the frontend, the site finally resolves to an IP address that is completely unknow to me. Chrome also tells This page is not available. The IP / URL where the browser finally is pointing to is:
http://192.168.9.43/2013/11_12_552_5xx/mu_resp_1800_21670_571/

When visiting the backend, a login form is shown, but the markup is completely lost.
One of the errors in the browser console:
Failed to load resource: net::ERR_CONNECTION_TIMED_OUT http://192.168.9.43/2013/11_12_552_5xx/mu_resp_1800_21670_571/skin/adminhtml/default/default/reset.css

So somehow it's continuously pointing to the mentioned IP address. What has gone wrong..?
When I remove the index.php file and replace it with some simple HTML, the site is just resolving under the domainname and all seems to be fine.
The IP address mentioned is not the IP addres fo the domainname.. looks like an internal IP.
Answer: Oke, I found the problem!
I've bought an template and also imported the sample data. But after re-indexing, flushing and all other stuff Magento does, the base url (web/unsecure/base_url) was modified due to the sample date into the url http://192.168.9.43/2013/11_12_552_5xx/mu_resp_1800_21670_571/.
After I had the site working again, I also could not login into the admin, because the sample data also deleted all user accounts and put in their own user account! So now I also must try to fix this issue, but that's well written down on the internet!


Chosen module/jquery plugin not accessible on mobile devices?

Question: I have installed the Chosen Module and was surprised to find out when viewing the page on an actual mobile device or on a desktop mobile device simulator that the Chosen menu is totally missing from the html markup and the menu items are not being displayed on the device.
Anyone know by any chance what I may be missing here? Is it possible the module only works for desktop or tablet devices?
Answer: I just found on the Chosen jQuery documentation in the FAQ section towards the bottom they say that they have disabled the Chosen module for mobile devices by default as there are bugs with the Menu working properly on those devices. Here is a GitHub discussion about the issue.


What is a good approach to proving $f$ is continuous in $\bar 0$

Question: I'm reading up on metric spaces, and the following question appeared in the continuous functions section:
$$\text{Let} f:\mathbb R^2 \to \mathbb R  \text{ be defined such that }  f(\bar0)=0  \text{ and} \\ f(x,y) = \frac{xy^2}{x^2+y^2} \text{, for } (x,y) \not = \bar 0. \ \text{Show that } f \text{ is continuous in the origin.}$$
I haven't studied vector calculus, so the continuity of two-dimensional functions is unclear to me. If I've understood correctly, the definition in this case is $|f(x,y)| < \epsilon$ for $|\sqrt{x^2 + y^2}| < \delta$. However, I can't see the desired simplifications and a choice for $\delta$. Also, since I'm studying topology, is there a "more topologically" relevant way to answer this question (i.e an argument based on open sets)?
Answer: We have
$$
\left|\frac{xy^2}{x^2 + y^2}\right|=|x|\cdot\left|\frac{y^2}{x^2 + y^2}\right|\leq |x|\cdot \left|\frac{y^2}{y^2}\right| = |x|
$$
Ok, this is nicely simplified. We can now start our actual proof.

Let $\varepsilon>0$, and pick* $\delta = \varepsilon$. Assuming $\sqrt{x^2 + y^2}<\delta$, we get
  $$
\left|\frac{xy^2}{x^2 + y^2}\right|\leq |x|=\sqrt{x^2}\leq \sqrt{x^2 + y^2}<\delta = \varepsilon
$$
  showing that our function is continuous at the origin

* I fill in $\delta = \varepsilon$ after actully doing the calculations further down, so that I know what I need. But I write it before the calculations in the finished proof, so it looks like I pulled it out of thin air, somehow knowing that it would work out.
Comment: I got the $|x|$ part but missed the estimation from above. Gave me a chuckle with "pulled it out of thin air" :^). Cheers for the solution!
Answer: With polar coordinates $x= r \cos t, y=r \sin t$ we see that
$|f(x,y)-f(0,0)| \le r = \sqrt{x^2 + y^2}.$
Hence, if $ \epsilon >0$ is given, let $ \delta= \epsilon.$
Comment: Somehow I doubt that this person will be comfortable with polar coordinates...


SQL query to access a field collection's data? At them moment, I'm only getting field_collection_item returned

Question: In the below example, I am trying to return the value of a field from all the field collections in the database but only get field_collection_item. This example is just the most basic field collection sql possible.
SELECT field_collection_item.item_id AS item_id, 'field_collection_item' AS field_data_field_grade_decimal_field_collection_item_entity_
FROM
field_collection_item field_collection_item

What do I need to change in this example? My SQL is terrible unfortunately. I just can't return any values from field collections using sql. I need to be able to do this for Forena Reports.
I'm getting the above code from views which returns the field collection values.
Comment: What I'm trying to do is return field values from a field collection using sql. The above code doesn't return the ID of the field collection; it returns a decimal field in the field collection when used in views.
Comment: Notice that you don't need `'field_collection_item' AS field_data_field_grade_decimal_field_collection_item_entity_` and `FROM
field_collection_item field_collection_item` can simply be `FROM
field_collection_item`.
Comment: But I need to return the value of *the field_data_field_grade_decimal_* fields. Views does it with the above output but it doesn't work if I query the database.
Answer: You can use the field_collection_field_get_entity() function to obtain the desired result without writing SQL, like this:

$node = node_load(12);
$items = field_get_items('node', $node, 'field_fc_field');
foreach ($items as $item) {
$fc = field_collection_field_get_entity($item);
// Do something with $fc
dpm($fc);
}

Comment: It's for Forena reports so I need it as SQL unfortunately.
Comment: You simply need the field collection item id associated with the node and then you have to make inner join with the tables containing the values. I will post a sample code here later tonight.
Comment: Thanks, but could you wait until tomorrow. I want to put my final code query in the question as I feel that I won't be able to do it myself. I'm going to put a bounty on it as well.


Calculating karma from upvotes/downvotes on a user's posts

Question: I have a User and Post model and am using the acts_as_votable gem (which gives me a 'votes' table) to upvote/downvote a post. I want to assign karma to each user, where karma is the number of upvotes a user has gained from all his/her posts minus the total number of downvotes.
Currently I have this instance method on the User's model to calculate karma:
<code>  def karma
    count = 0
    self.posts.each do |post|
      count += post.upvotes.size - post.downvotes.size
    end
    return count
  end
</code>
I don't think the above is very efficient with a run time of O(2n), because for every post two additional database queries are required, one for the upvotes, and one for the downvotes.
Any ideas on how to combined the above into a single query, or otherwise make it more efficient?
Answer: Not only about efficiency, such design is not good in terms of OOP. The User model considers too much beyond its scope. Karma is something belongs to user and should not be tied in anything else.
A better approach is to separate "Karma" from Post.
<code># Add a "karma" column
$ rails g migration AddKarmaToUser

# Or use a dedicated table
class User < ActiveRecord::Base
  has_one :karma
</code>
Then, use Controller or service object to change karma. I'll cover Controller here for simplicity. Do not use Model callbacks as that is cross models.
<code>class PostsController < ApplicationController
  def upvote
    post = Post.find(params[:id])
    post.upvote # pseudo API of acts_as_votable
    current_user.increase_karma
  end

  def downvote
    # ...
    current_user.decrease_karma
  end
end

# Model
class User < ActiveRecord::Base
  attr_accessible :karma

  def increase_karma(count=1)
    update_attribute(:karma, karma + count)
  end

  def descrease_karma(count=1)
    # ...
  end
end

# View
user.karma
</code>
Comment: What do you mean, "...such design is not good in terms of OOP. The User model considers too much beyond its scope." Is it bad design because I am trying to access votes which do not belong to the User model but rather the Post model, or is it because I am accessing posts which is defined by a relationship and is not an actual attribute on the Users table? Is user.posts okay but user.posts.first.votes bad? or are they both not good?

Also, currently I have a separate votes_controller. Is it more restful to have the votes action in the posts_controller like you demonstrate above?
Comment: Steve, for your first statement, yes, `user.posts` is okay, but `user.posts.first.votes` is not good. This user's hands are too long :) He touched something not belonging to him. For votes, I think putting them in PostsController is more natural. Even if you have more votes for others say Comment, you can put votes for comments in CommentsController.


Webview Javascript chamando método java - android

Question: Tenho um app webview que chama uma index.html :
WebView webView = (WebView)findViewById(R.id.webView);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.setWebViewClient(new webViewClient());
    webView.loadUrl("file:///android_asset/index.html");
    webView.addJavascriptInterface(this, "android");

nessa index tenho um javascript que acessa uma função java para verificar se existe conexão, se o retorno for true ele envia para meu site:
function connection(){
   return android.CheckConnection();
}
if(!connection()){
   alert('sem conexão');
}else{
   window.location.href = 'http://meusite.com';
}

função java acessada pelo javascript
@JavascriptInterface
public boolean CheckConnection(){
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnectedOrConnecting();
}

Quando meu site é carregado, ele tenta acessar as funções do java assim como fiz com a index.html porém é retornado um erro "Uncaught Error: Java exception was raised during method invocation"
Answer: Fala Gustavo,
Tenta trocar essa linha:
webView.addJavascriptInterface(this, "android");

Por essa:
webView.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");

E fora do seu onCreate, coloca esse método:
/* An instance of this class will be registered as a JavaScript interface */
    class MyJavaScriptInterface
    {
        @JavascriptInterface
        @SuppressWarnings("unused")
        public void processHTML(String html)
        {
            // process the html as needed by the app
        }
    }

Abraços.
Comment: Leonardo, a minha função CheckConnection deve ficar dentro da classe MyJavaScriptInterface? fiz desta maneira e o erro persiste, mas o problema piorou porque agora o jquery do site também parou de funcionar
Comment: Qual erro que apresenta no seu LogCat? O mesmo de antes?
Comment: Descobri que rodando o app normalmente tudo está funcionando, porém este erro acontece quando o app está fechado (clear data) e ele recebe uma notificação, ao clicar na notificação ele inicia o app que após carregar a webview com jquery, o jquery executa um metodo do java e nesse momento o erro acontece, lembrando que o erro acontece somente quando inicio o app via notificação...o logcat é o mesmo sim Leonardo


ios/iphone sdk form management best practices

Question: I'm working on an iPhone app that will have involve a lot of forms. Currently I have a ViewController class for each settings page which has an UITableView loaded with possible settings. When someone clicks on a setting they are taken taken to a new view to enter the form value, or allowed to enter things in place.
What's the best way to keep things DRY? What pieces of this implementation could be implemented once and re-used?
When someone clicks on a settings option which goes to a new view how can I create this view and add a text field according to the data type (uitextfield or picker or something else) in code?
Answer: You can programmatically:
create view hierarchy
UIButton
UILabel
You get the idea.
However, I would recommend getting your logic working for a few of the cases, and then it should become obvious what parts are redundant as you find yourself typing in the same thing over and over.  At that point, refactor to get the redundant code into a re-usable form.
HTH.
Comment: +1 for code first, refactor after. Code two forms, refactor to capture commonalities if it's not a contortionist trick, then add a third form, etc.
Answer: If you have a tableView, the flow is to create the viewController of the selected settings in the didSelectCell method of your tableView delegate and to push it through the current viewController's navigation controller.
here's a sample:
<code>- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.navigationController pushViewController:[self settingsViewControllerAtIndexPath:indexPath] animated:YES];
}
</code>
so you'll have to implement the method:
<code> - (UIViewController*)settingsViewControllerAtIndexPath:(NSIndexPath *)indexPath;
</code>
wich will return the viewController managing the settings associated with the selected row of your root tableView.
If your forms are pretty statics, you should consider using a xib in order to minimize the amount of code needed. it isn't a perfect answer to your "how to keep DRY" but it's neat enough ;)
Good luck.


how does a surjective function not contradict the definition of a function.

Question: I was reading up on functions and different types of functions.
From wikipedia :

A function is a process or a relation that associates each element x
  of a set X, the domain of the function, to a single element y of
  another set Y

Surjective function:

a function f from a set X to a set Y is surjective (or onto), or a
  surjection, if for every element y in the codomain Y of f there is at
  least one element x in the domain X of f such that f(x) = y. It is not
required that x be unique; the function f may map one or more elements
of X to the same element of Y.

Can someone explain how these two definitions does not contradict eachother?
Comment: For each $x\in X$ there is a unique $y\in Y$ such that $f(x)=y$. It doesn't mean that for each $y\in Y$ there is a unique $x\in X$ such that $f(x)=y$. These are completely different things.
Answer: You are understanding one of the definitions wrong.
Surjectivity means that if you have a function $f:X\to Y$ then every $y\in Y$ gets mapped onto.

A function is a process or a relation that associates each element x of a set X, the domain of the function, to a single element y of another set Y

This says that something like this:
$f:\{1,2\}\to \{1,2,3\}$, $f(1)=1$, $f(1)=2$ and $f(2)=3$ is not a function, because $f(1)$ is not unique.
Other example:

It is not required that x be unique; the function f may map one or more elements of X to the same element of Y.

Meant is something like this:
Consider the function $f:\{1,2,3\}\to\{1,2\}$
Then we can have $f(1)=1$ and $f(2)=1$ and $f(3)=2$. Then $f$ is surjective and there are values (1 and 2) that are mapped onto the same element (here 1).
This is completly fine.
Keep in mind that if you have a function $f:X\to Y$. Every $x\in X$ needs to be mapped onto something. But not every $y\in Y$ needs to be mapped onto.
Example:
$g:\{1,2,3\}\to\{1,2\}$
$g(1)=g(2)=g(3)=1$ is a function. But not surjective.
Answer: If you read those definitions carefully you will see that the "uniqueness" is in $Y$, not in $X$. For example consider the function from people in the US to states, which assigns to each person the state they live in. Each person lives in just one state (for mathematical and census purposes), but there are many people who live in the same state.
So that is a function.
If you try to define a function by assigning to each person the state in which they have ever lived you see the problem right away. People can move from state to state so there is no "the state" so there is no such function.
Answer: A function is a relation that maps every element in the domain to a SINGLE element in the codomain... and it may be the case that
$1$. elements in the codomain that are mapped to are mapped to only once, or
$2$. one or more elements in the codomain are mapped to multiple times from DIFFERENT elements in the domain.
In either case, you would not have a contradiction because each element in the domain still only maps to ONE element in the codomain. In the case of #$2$, you would simply have multiple elements in the domain mapping to THE SAME element in the codomain.
When #$1$ occurs, we say the function is injective.  When #$2$ occurs, we say the function is not injective. It is injective if and only if every element in the domain maps to a different element in the codomain.
In short, you think there is a contradiction because you are confusing the definition of a function with that of an injective function. And indeed, if that were true then there would be a contradiction! But this is not the case. A function can be injective or not, and in either case it can be surjective or not.


Why SQLite crash in UWP with cannot find the file specified?

Question: I install the SQLite from Nuget as below:

And after I ran the program it throws this error:

I feel strange that it showed the Version is 126.96.36.199 but not the version I installed which 220.127.116.11

What's more, I tried the way what Could not load file or assembly 'System.Data.SQLite, Version=188.8.131.52 - Why does it search for version 22.214.171.124 when I have referenced 188.8.131.52
said
But all the way no works.
In addition, I opened the .csproj and here is the SQLite package reference:

The version in .csproj is right.

What's wrong with it.Would you please tell me how to solve it? Thank you.
Comment: Install the `sqlite` package instead of the `System.Data.SQLite.Core` package and make sure that the `SQLite` assembly gets copied to your output directory.
Comment: @mm8 Thanks for reminding me that the SQLite assembly gets copied to my output directory. I embed the SQLite in a dll and runs it in a UWP program. The UWP program does not embed SQLite yet. After I embed it, it works!
Answer: Make sure that the SQLite assembly gets copied to your output directory so it can be found at runtime. It should if you install the SQLite package in your UWP app project.


Drag and Drop entre colunas com Sort, mover os cards entre eles

Question: Estou desenvolvendo uma aplicação em que tenho 3 colunas de cards, preciso que os cards possam ser movidos de uma coluna para a outra e entre si.
Eu consegui fazer com que o card possa ser movido para outra coluna, mas eu só consigo move-lo uma unica vez, depois que é movido ele não pode ser realocado para outra posição.
Segue o código:

                                    eos-youtube-gjs #29

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris at urna rhoncus, elementum eros eu, mattis risus suspendisse

                                    username 13 pts

Como eu faço para que os cards possam ser movidos quantas vezes necessário?
Answer: Você não consegue mover de novo porque ele fica por baixo das outras divs. Ao soltá-lo, você não consegue mais arrastá-lo.
Inclua um z-index: 1 na div id="card" para que fique por cima ficando sempre ao alcance do cursor do mouse:
#card{
   z-index: 1;
}

Exemplo:

$(function() {
   $( ".draggable" ).draggable();
   $( ".droppable" ).droppable({
       drop: function (event, ui){
           $(this)
               .find (".card-body #card-label #card-spacing #card-text img #user #user-spacing");
       }
   });
});

$(function(){
   $("#do-now").sortable({
       handle: '.card .card-body #card-label #card-spacing #card-text img #user #user-spacing',
       connectWith: '#do-later #on-hold'
   }).disableSelection();
   $("#do-later").sortable({
       handle: '.card .card-body #card-label #card-spacing #card-text img #user #user-spacing',
       connectWith: '#do-now #on-hold'
   }).disableSelection();
   $("#on-hold").sortable({
       handle: '.card .card-body #card-label #card-spacing #card-text img #user #user-spacing',
       connectWith: '#do-now #do-later'
   }).disableSelection();
});
#card{
   z-index: 1;
}

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">

               eos-youtube-gjs #29

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris at urna rhoncus, elementum eros eu, mattis risus suspendisse

               username 13 pts


Calves muscles pain when running

Question: Recently when I run I always get my calves muscles rigid like stones. If I run 10 minutes, I don't stop because I go out of breath, rather because I feel pain. I tried to rest some days, but it doesn't help. I also tried to take magnesium and potassium.
Nothing to do: my muscles are rigid. Maybe also because of the cold. I also have stretching, it helps a bit but I still have the problem. What can I do?
Comment: "**General health** and medical advice is off-topic here." Sure, you may not be sick, but without professional direction, how would we know if it is not an underlying condition? Nonetheless, your question has been answered and welcome to Sports SE.
Comment: Is this a medical advice request? Am I sick? Ridicolous.
Answer: My experience with this has to do with getting the blood flowing, and my calve muscles hurt alot as I begin running, until I warm up.
What I try is before I head out, not to sit, rather to move around, and bounce up on my toes as I move around (Activate calf muscles).
Then I run for 6 minutes, and walk for 8 before continuing my run.  This usually gets my calf muscles warmed up and blood flowing, so they do not go anaerobic and get lactic acid buildup.
Sadly, this does not work every time, and I sometimes find I need a longer warm up.  Your mileage may vary.

Calves muscles pain when running


Can entities as users exist without being tied to nodes

Question: Can entities as users exist without being tied to nodes, I'm starting a site that I don't want a lot of overhead and it will have a lot of users and they will be contacting each other often.
Comment: You did not specify your Drupal version. Users were never "tied" to nodes in Drupal core, however there was a Usernode module for Drupal 6 that made users into nodes.
Answer: In D7 Users are an Entity type, they are their own Entity type. A Node is another entity type with various bundles such as Page, Article, etc.
Taxonomy is another example of an Entity.
An Entity does not necessarily mean a "Node" in drupal 7.
See this introduction to Drupal 7 Entities on drupal.org


How many combinations are possible in this question?

Question: I was curious how many combinations are possible in this scenario:

The characters allowed to make up the combination are so:

Letters a-z (lowercase only)
Numbers 0-9
Underscores _
Periods .

The combination is 4 digits
The combination cannot end with a period (.)

Just a side note, this can have repeating characters.I also appreciate it a lot if someone were to answer this.
Comment: What have you tried so far?
Comment: I had tried `38*37*4`, but I didn't know how to do it.
Answer: We have $26+10+1+1=38$ possible characters. We want $4$ characters and the combination cannot end with a period so we have $38^3 \times 37$ possible combinations.


Need help understanding for loops

Question: Currently I am learning Java and I am stuck at some for loops which I have no idea how they work.
The code looks like this:
int sum = 0, maximum = number[0], minimum = number[0];
for (int i = 0; i < number.length; i++) {
    sum += number[i];
    if (maximum < number[i]) {
        maximum = number[i];
    }
    if (minimum > number[i]) {
        minimum = number[i];
    }
}

So my questions are:

What does
int sum = 0, maximum = number[0], minimum = number[0] do? Does it make the loop start
from 0?
in the for loop, what does number.length; do?
What does sum+=number[i] do and why is the [i] needed?
Same in the if loops which check the maximum/minimum values, why is there [i] behind number?
Comment: There's no such thing as an "if loop".
Comment: @ArunkumarSharma Loops are also a type of statement.
Comment: You should go through a basic tutorial.
Comment: http://www.learnjavaonline.org/ would be a good place to start
Comment: You should refer CS 101
Comment: 'If' is a statement, not a loop.
Answer: This line:
int sum = 0, maximum = number[0], minimum = number[0];

Declares three variables (sum, maximum and minimum) of type int and initializes them with some values (0, number[0] and number[0] respectively.
number seems to be an array (probably an int[]), which means it holds multiple int values.
number.length simply returns the number of elements in number.
number[i] returns the element at position i in the array (just as number[0] returns the element at position 0, a.k.a the first element).
So most of your confusion seems to be caused by the lack of knowledge of what arrays are.
See this tutorial for a starter.
Comment: It could be interesting to point out that declaring several variables on a single line is not recommended, see the [Java Code Conventions](http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-141270.html#2992)
Answer:
What does int sum = 0, maximum = number[0], minimum = number[0] do?
  Does it make the loop start from 0?

It declares 3 int variables (sum, maximum and minimum) + initializes them

in the for loop, what does number.length; do?

It gets the length of the number array

What does sum+=number[i] do and why is the [i] needed?

sum += number[i] can also be written as: sum = sum + number[i]
+= is called a preincrement. the [i] is needed because it refers to a certain index in the number array

Same in the if loops which check the maximum/minimum values, why is
  there [i] behind number?

Because you are getting the number at index i in the numbers array.
Answer: the loop is a for-loop. If is a condition statement.
int sum = 0, maximum = number[0], minimum = number[0];

this creates and initializes 3 int variables: sum, maximum and minimum.
number.length is part of the end-condition for this loop. As long as i < number.length is true, this looop will be executed
number[] is an array
sum+=number[i]

this adds the value of the number[i] to sum
[i] is the cell of an array - i gets a new number every loop:
int i = 0; i < number.length; i++

so it starts with 0, is incremented by 1 and this is done, as long as i is lower than number.length.
so number[i] will be number[0] in the first iteration of the loop, then number[1] then number[2] and so on
Answer:
1 . What does int sum = 0, maximum = number[0], minimum = number[0] do? Does it make the loop start from 0?

(Note that this line has no effect on the for loop that comes next.)
This line initializes sum, maximum and minimum to 0, number[0] and number[0] respectively.
Note that this line is a shorthand for:
int sum = 0;
int maximum = number[0];
int minimum = number[0];

2 . in the for loop, what does number.length; do?

number.length is the length of the array number, it is to say the number of int values stored in the array number.

3 . What does sum+=number[i] do and why is the [i] needed?

It increments sum of number[i].
number[i] is the i-th int value stored in the int-array number. Here, i is called an index.

4 . Same in the if ... which check the maximum/minimum values, why is there [i] behind number?

Here also, i is an index to say that you want the i-th value in the array number.
(By the way, also consider
maximum = Math.max(maximum, number[i]);
minimum = Math.min(minimum, number[i]);

instead of the two if conditions.)
Comment: Thank you for the explanation, and yes, I meant for-loop. Was confused while posting it.
Answer: I guess you mean "for loop". Let's start with the syntax of a for loop.
 for (int i = 0; i < number.length; i++) {
   your code here....
 }

The "int i=0" part declares a "phantom" integer variable, which means that it only exists in that if loop; when the loops ends the compiler "tosses away" that variable. The initial value of i is 0.
Then you have the part ;i < number.length;. This part expresses that "run the loop until i reaches the length of array number.
Finally, "i++" defines the step length; how bigger(or smaller) i will be after each run. In this case i++ means i = i + 1.
So in summary. Your for loop starts with the initialization of a counter, then decides for how big a counter you want to run iterations and finally how much you'll increment this counter.
I have to note that these are one of the basic stuff and a book or a guide would be great for you to start. Otherwise you will have to as

Need help understanding for loops


model(features) does not return EagerTensor

Question: I have built a model which I can only train with a custom loss which I am trying to debug.
For this I have this simple loop here:
for (mel_specs, pred_inp), labels in train_dataset:
    enc_predictions = model((mel_specs, pred_inp))  # <--- Returns a Tensor, not an EagerTensor
    input_lengths = get_padded_length(mel_specs[:, :, 0])
    label_lengths = get_padded_length(labels)
    print(enc_predictions)
    loss_value = rnnt_loss(enc_predictions, labels, input_lengths, label_lengths)
    print(loss_value)

The model is just:
model = tf.keras.Model(
    inputs=[mel_specs, pred_inp],
    outputs=[outputs]
)

The problem is that model((mel_specs, pred_inp)) just gives me a regular Tensor but not a EagerTensor and I don't understand why. mel_specs and pred_inpu are EagerTensors coming from train_dataset which is a tf.data.Dataset.
What am I missing here?
Environment
$ pip freeze | grep tensorflow
tensorflow==2.2.0
tensorflow-addons==0.10.0
tensorflow-datasets==3.1.0
tensorflow-estimator==2.2.0
tensorflow-metadata==0.22.2
warprnnt-tensorflow==0.1

Update: MVCE
I was able to boil it down to the encoder part of the model. If I run this it will fail and print:
Calling model(x) didn't return EagerTensor
Traceback (most recent call last):
    ...
    return loss_value, tape.gradient(loss_value, model.trainable_variables)
  File "/home/sfalk/miniconda3/envs/asr2/lib/python3.8/site-packages/tensorflow/python/eager/backprop.py", line 1042, in gradient
    flat_grad = imperative_grad.imperative_grad(
  File "/home/sfalk/miniconda3/envs/asr2/lib/python3.8/site-packages/tensorflow/python/eager/imperative_grad.py", line 71, in imperative_grad
    return pywrap_tfe.TFE_Py_TapeGradient(
  File "/home/sfalk/miniconda3/envs/asr2/lib/python3.8/site-packages/tensorflow/python/eager/backprop.py", line 157, in _gradient_function
    return grad_fn(mock_op, *out_grads)
  File "/home/sfalk/miniconda3/envs/asr2/lib/python3.8/site-packages/tensorflow/python/ops/math_grad.py", line 252, in _MeanGrad
    sum_grad = _SumGrad(op, grad)[0]
  File "/home/sfalk/miniconda3/envs/asr2/lib/python3.8/site-packages/tensorflow/python/ops/math_grad.py", line 211, in _SumGrad
    output_shape_kept_dims = math_ops.reduced_shape(input_shape,
  File "/home/sfalk/miniconda3/envs/asr2/lib/python3.8/site-packages/tensorflow/python/ops/math_ops.py", line 3735, in reduced_shape
    input_shape = input_shape.numpy()
AttributeError: 'Tensor' object has no attribute 'numpy'

The code:
import numpy as np
import tensorflow as tf
from tensorflow.python.framework.ops import EagerTensor

class TimeReduction(tf.keras.layers.Layer):

    def __init__(self,
                 reduction_factor,
                 batch_size=None,
                 **kwargs):
        super(TimeReduction, self).__init__(**kwargs)
        self.reduction_factor = reduction_factor
        self.batch_size = batch_size

    def call(self, inputs):
        input_shape = tf.shape(inputs)
        batch_size = self.batch_size
        if batch_size is None:
            batch_size = input_shape[0]
        max_time = input_shape[1]
        num_units = inputs.get_shape().as_list()[-1]
        outputs = inputs
        paddings = [[0, 0], [0, tf.math.floormod(max_time, self.reduction_factor)], [0, 0]]
        outputs = tf.pad(outputs, paddings)
        return tf.reshape(outputs, (batch_size, -1, num_units * self.reduction_factor))

def make_encoder_model(
    input_shape: tuple,
    out_dim: int,
    num_layers: int,
    d_model: int,
    proj_size,
    initializer=None,
    dtype=tf.float32,
    stateful: bool = False,
    dropout=0.5,
    reduction_index=1,
    reduction_factor=2,
):
    def lstm_cell():
        return tf.compat.v1.nn.rnn_cell.LSTMCell(
            d_model,
            num_proj=proj_size,
            initializer=initializer,
            dtype=dtype
        )

    batch_size = None if not stateful else 1

    inputs = tf.keras.Input(
        shape=input_shape,
        batch_size=batch_size,
        dtype=tf.float32
    )

    x = tf.keras.layers.BatchNormalization()(inputs)

    for i in range(num_layers):
        rnn_layer = tf.keras.layers.RNN(lstm_cell(), return_sequences=True, stateful=stateful)
        x = rnn_layer(x)
        x = tf.keras.layers.Dropout(dropout)(x)
        x = tf.keras.layers.LayerNormalization(dtype=dtype)(x)
        if i == reduction_index:
            x = TimeReduction(reduction_factor, batch_size=batch_size)(x)

    outputs = tf.keras.layers.Dense(out_dim)(x)

    return tf.keras.Model(
        inputs=[inputs],
        outputs=[outputs],
        name='encoder'
    )

def gradient(model, loss, inputs, y_true):
    y_true = tf.transpose(y_true, perm=(0, 2, 1))
    with tf.GradientTape() as tape:
        y_pred = model(inputs, training=True)
        loss_value = loss(y_true=y_true, y_pred=y_pred)
        return loss_value, tape.gradient(loss_value, model.trainable_variables)

def main():
    X, Y = [
        np.random.rand(100, 512),
        np.random.rand(100, 512)
    ], [[[0]*50], [[1]*50]]
    # assert len(X) == len(Y)

    encoder_model = make_encoder_model(
        input_shape=(None, 512),
        out_dim=1,
        num_layers=2,
        d_model=10,
        proj_size=23,
        dropout=0.5,
        reduction_index=1,
        reduction_factor=2
    )

    enc_dataset = tf.data.Dataset.from_generator(
        lambda: zip(X, Y),
        output_types=(tf.float32, tf.int32),
        output_shapes=([None, 512], [None, None]),
    ).batch(2)

    loss = tf.keras.losses.MeanSquaredError()

    for x, y in enc_dataset:
        from_predict = encoder_model.predict(x)
        from_call = encoder_model(x)
        if not isinstance(from_predict, np.ndarray):
            print("Calling model.predict(x) didn't return np.ndarray")
        if not isinstance(from_call, EagerTensor):
            print("Calling model(x) didn't return EagerTensor")
        loss_value, gradients = gradient(encoder_model, loss, x, y)
        print(loss_value)
        print(gradients)

    print('All done.')

if __name__ == '__main__':
    main()

Comment: Please provide a MVCE and the full error traceback.
Comment: @xdurch0 I have condensed the code down to some 100 lines which seem to reproduce the issue.
Answer: Why do you use the LSTM cell from compat.v1? I would imagine this leads to compatibility issues.
Most importantly, those "pure Tensorflow" RNN cells are not made to be used with the keras RNN anyway -- they were used with tf.nn.dymanic_rnn for example, which is now deprecated and also found only in the compat.v1 module.
I would recommend that you simply use tf.keras.layers.LSTM directly as it's much faster anyway -- it allows for the use of highly optimized GPU kernels. Alternatively, you can replace the compat.v1.LSTMCell with a tf.keras.layers.LSTMCell and put this into the RNN.
Comment: Yeah, the interfaces in TF1 were confusing because there were so many ways of doing things... I would say that in TF2 you can pretty much stick with Keras layers for most things.
Comment: Yes, indeed. This caused the issue. I used `compat.v1` because I took the code from somewhere else and I wasn't aware that this may cause an issue. Thank you for your help!


Try to use an array to create a new object from a class

Question: I am trying to use an array to create a new object in StringInstrument class. Instead of StringInstrument ukulele = new StringInstrument(); I put StringInstrument instrumentList[i] = new StringInstrument();; however, it keeps giving me the error "The array is only read from, never written to" and "variable instrumentList is already defined in method main(String[])". I cannot figure out what I am doing wrong. My code is displayed below.
<code>    class StringInstrument {//begin class
    //declare variables
    boolean isTuned;
    boolean isPlaying;
    boolean band;
    public String nameOfInstrument;
    int numberOfStrings;
    String nameofStringsInInstrument[] = {"E", "A", "D", "G", "B"}; //an array of string names

    public StringInstrument() {//begin contructor
        numberOfStrings = 5;
        isTuned = false;
        isPlaying = false;
        band = false;
     }//end constructor

    public int NumberOfStrings(int stringNumber){//begin method
        System.out.println("The number of strings for the " + nameOfInstrument + " is " + stringNumber );
        return this.numberOfStrings = stringNumber;
    }//end method

    public String InstrumentNameGet() {//begin method
        return nameOfInstrument;
    }//end method

    public void SetInstrumentName (String instrumentName) {//begin getter method
            nameOfInstrument = instrumentName;
        }//end method

    public String InstrumentNameDisplay() {//begin method
        System.out.println("Your instrument is the " + nameOfInstrument);
        return nameOfInstrument;
    }//end method

    public boolean PlayInstrument(){//begin method
        System.out.println("You are playing your " + nameOfInstrument);
        return isPlaying = true;
    }//end method

    public boolean TuneInstrument(){//begin method
        System.out.println("Tune " + nameOfInstrument);
        return isTuned = true;
    }//end method

    public boolean stopTuneInstrument() {//begin method
        System.out.println("The" + nameOfInstrument + " is out of tune.");
        return isTuned = false;
    }//end method

    public boolean StopPlayInstrument() {//begin method
        System.out.println("The " + nameOfInstrument + " has stopped playing");
        return isTuned = false;
    }//end method

    public boolean PlayInstrumentBand() {//begin method
        System.out.println("The " + nameOfInstrument + " is playing in a band");
        return band = true;
    }//end method

    public boolean StopPlayInstrumentBand() {//begin method
        System.out.println("The " + nameOfInstrument + " has stoped playing with the band");
        System.out.println("\n");
        return band = false;
    }//end method
}//end class

public class RandyGilmanP3 {//begin class

     public static void main(String[] args) throws Exception{//begin main

            java.io.File file = new java.io.File("RandyGilmanP3.txt");

            //create a file
            java.io.PrintWriter output = new java.io.PrintWriter(file);

    //Declaring, creating, and intialize arrays
            String[] instrumentList = new String [10];
            String[] instrumentContent = new String [10];
            int[] stringNumber = new int [10];

            //input string names into array
            instrumentList[0] = "Guitar";
            instrumentList[1] = "Violin";
            instrumentList[2] = "Bass Guitar";
            instrumentList[3] = "Cello";
            instrumentList[4] = "Banjo";
            instrumentList[5] = "Sitar";
            instrumentList[6] = "Rabab";
            instrumentList[7] = "Viola";
            instrumentList[8] = "Harp";
            instrumentList[9] = "Ukulele";
            //input string amounts into array
            stringNumber[0] = 5;
            stringNumber[1] = 4;
            stringNumber[2] = 5;
            stringNumber[3] = 4;
            stringNumber[4] = 5;
            stringNumber[5] = 18;
            stringNumber[6] = 3;
            stringNumber[7] = 4;
            stringNumber[8] = 47;
            stringNumber[9] = 4;

            for (int i = 0; i < instrumentContent.length; i++){//begin for loop
                StringInstrument instrumentList[i] = new StringInstrument();
                output.println(instrumentList[i].InstrumentNameDisplay());
                output.println(instrumentList[i].NumberOfStrings(stringNumber[i]));
                output.println(instrumentList[i].TuneInstrument());
                output.println(instrumentList[i].PlayInstrument());
                output.println(instrumentList[i].PlayInstrumentBand());
                output.println(instrumentList[i].StopPlayInstrument());
           }//end for loop

        }//end main
    }//end class

I thought I would add the correct version, it took about 9 hours but I think I finally achieved the desired result.

class StringInstrument {//begin class
    //declare variables
    boolean isTuned;
    boolean isPlaying;
    boolean band;
    public String nameOfInstrument;
    int numberOfStrings;
    String nameofStringsInInstrument[] = {"E", "A", "D", "G", "B"}; //an array of string names

    public StringInstrument() {//begin contructor

        numberOfStrings = 5;
        isTuned = false;
        isPlaying = false;
        band = false;
     }//end constructor

    public int NumberOfStrings(int stringNumber){//begin method
        System.out.println("The number of strings for the " + nameOfInstrument + " is " + stringNumber );
        return numberOfStrings = stringNumber;
    }//end method

    public String InstrumentNameGet() {//begin method
        return nameOfInstrument;
    }//end method

    public void SetInstrumentName (String instrumentName) {//begin getter method
            nameOfInstrument = instrumentName;
        }//end method

    public String InstrumentNameDisplay() {//begin method
        System.out.println("Your instrument is the " + nameOfInstrument);
        return nameOfInstrument;
    }//end method

    public boolean PlayInstrument(){//begin method
        System.out.println("You are playing your " + nameOfInstrument);
        return isPlaying = true;
    }//end method

    public boolean TuneInstrument(){//begin method
        System.out.println("Tune " + nameOfInstrument);
        return isTuned = true;
    }//end method

    public boolean stopTuneInstrument() {//begin method
        System.out.println("The" + nameOfInstrument + " is out of tune.");
        return isTuned = false;
    }//end method

    public boolean StopPlayInstrument() {//begin method
        System.out.println("The " + nameOfInstrument + " has stopped playing");
        return isPlaying = false;
    }//end method

    public boolean PlayInstrumentBand() {//begin method
        System.out.println("The " + nameOfInstrument + " is playing in a band");
        return band = true;
    }//end method

    public boolean StopPlayInstrumentBand() {//begin method
        System.out.println("The " + nameOfInstrument + " has stoped playing with the band");
        System.out.println("\n");
        return band = false;
    }//end method

    //Create an array of instrument objects
    public static StringInstrument[] createInstrumentArray(){//begin method
            StringInstrument[] instruments = new StringInstrument [10];

            //Loop that inputs random integers into the array
                for (int i = 0; i < instruments.length; i++){//begin loop
                    instruments[i] = new StringInstrument();

                }//end loop
            return instruments;
     }//End method

     public static void printInstrumentArray(StringInstrument[] instruments)throws Exception{

            //request input from user
            java.io.File file = new java.io.File("RandyGilmanP3.txt");
            if(file.exists()){
                System.out.println("FILE ALREADY EXIST");
                System.exit(1);
            }
            //create a file
            java.io.PrintWriter output = new java.io.PrintWriter(file);
            String[] instrumentList = new String [10];
            int[] stringNumber = new int [10];
            //input string names into array
            instrumentList[0] = "Guitar";
            instrumentList[1] = "Violin";
            instrumentList[2] = "Bass Guitar";
            instrumentList[3] = "Cello";
            instrumentList[4] = "Banjo";
            instrumentList[5] = "Sitar";
            instrumentList[6] = "Rabab";
            instrumentList[7] = "Viola";
            instrumentList[8] = "Harp";
            instrumentList[9] = "Ukulele";

            stringNumber[0] = 5;
            stringNumber[1] = 4;
            stringNumber[2] = 5;
            stringNumber[3] = 4;
            stringNumber[4] = 5;
            stringNumber[5] = 18;
            stringNumber[6] = 3;
            stringNumber[7] = 4;
            stringNumber[8] = 47;
            stringNumber[9] = 4;
                //Print an array of instruments and their actions
                for (int i = 0; i < instruments.length; i++){//begin for loop
                    instruments[i].SetInstrumentName(instrumentList[i]);
                    output.println(instruments[i].InstrumentNameDisplay());
                    output.println(instruments[i].NumberOfStrings(stringNumber[i]));
                    output.println(instruments[i].TuneInstrument());
                    output.println(instruments[i].PlayInstrument());
                    output.println(instruments[i].PlayInstrumentBand());
                    output.println(" ");

                }//end for loop
                output.close();
            }//end method
}//end class

public class RandyGilmanP3 {//begin class

     public static void main(String[] args) throws Exception{//begin main
         //declare instruments
         StringInstrument[] instruments;

         //create instrument array
         instruments = StringInstrument.createInstrumentArray();

         //Print instrument array
         StringInstrument.printInstrumentArray(instruments);
     }//end main

}//end class
</code>
Comment: Change StringInstrument instrumentList[i] = new StringInstrument(); to instrumentList[i] = new StringInstrument();
Comment: Is `instrumentList` supposed to be an array of `String`s or of `StringInstrument`s? You cannot use it for both.
Comment: Is instrumentList a String[], or a StringInstrument[]?  If the  first, you can't assign a StringInstrument variable to it on the for loop.  If the second, you can't assign the String names to it at the top.
Comment: the array instrumentList is supposed to develop a list of different instruments, instead of making a new object by say    StringInstrument Guitar = new StringInstrument(); I want to use it in a loop so all I have to do is enter, StringInstrument instrumentList[i] = new StringInstrument();. Basically, so I can display the name for each instrument that I process.
Answer: Your first array:
String[] instrumentList = new String [10];
and the array in the loop:
StringInstrument instrumentList[i] = new StringInstrument();
must have different variable names.
You will also want to declare and initialize your StringInstrument array outside of the loop and give it values before looping through it and running a variety of methods on it.
Comment: StringInstrument is the class I didn't add that part of the code because it is kind of long.
Answer: Replace your for loop with something like this:
<code>StringInstrument[] stringInstruments = new StringInstrument [10];
for (int i = 0; i < stringInstruments.length; i++){//begin for loop
        stringInstruments[i] = new StringInstrument();
        stringInstruments[i].SetInstrumentName(instrumentList[i]); //You want to initialize the name of the instrument here.
        output.println(stringInstruments[i].InstrumentNameDisplay());
        output.println(stringInstruments[i].NumberOfStrings(stringNumber[i]));
        output.println(stringInstruments[i].TuneInstrument());
        output.println(stringInstruments[i].PlayInstrument());
        output.println(stringInstruments[i].PlayInstrumentBand());
        output.println(stringInstruments[i].StopPlayInstrument());
   }//end for loop
</code>
You cannot use the same array to store both a String and a StringInstrument.
Comment: Ok that definetly worked so thank you for that; however, now the out put reads:                                                   Your instrument is the null
The number of strings for the null is 5
Tune null
You are playing your null
The null is playing in a band
The null has stopped playing                                      For one iteration, how do I get it to have guitar, violin, or whatever to be in the null instead?
Comment: @RandyGilman, are you sure that `SetInstrumentName` is working correctly?
Comment: Im starting to get really confused I might have to take a step back for a while, it seemed to be working before.


Limit of power of Markov matrix

Question: Recently, a friend gave me the following problem:

Let $$M = \begin{pmatrix} p & q & r \\ q & r & p \\ r & p & q \end{pmatrix}$$ where $p, q, r > 0$ and $p + q + r = 1$. Prove that $$\lim_{n \rightarrow \infty} M^n = \begin{pmatrix} 1/3 & 1/3 & 1/3 \\ 1/3 & 1/3 & 1/3 \\ 1/3 & 1/3 & 1/3 \end{pmatrix}$$

Some of my observations include that $M^{2^n}$ remains cyclic, so I tried to bound (with no luck) the maximum and minimum to see if they both converged to $1/3$.
It would be nice if someone could post an elementary solution to this problem.
Comment: Do you know of Markov chains? This seems to resemble one.
Comment: I do not know of Markov Chains :( I will read on them now
Comment: The concept of stationary distribution in Markov chains.
Answer: This a problem which is probably intended to be solved using Markov chains. I will assume you have a basic knowledge of the subject.

Suppose $(X_n)_{n\in\mathbb{N}}$ is a homogenous markov chain with transition matrix given by
$$P=\begin{pmatrix}
p & q & r\\
q & r & p\\
r & p & q
\end{pmatrix}$$
where $p+q+r=1$ and $p,q,r>0$. Then, clearly, the chain is irreducible and ergodic.

Ergodic theorem: If $(X_n)_{n\in\mathbb{N}}$ is an irreducible and ergodic Markov chain, then, it admits a unique stationnary distribution which satisfies
  $$\pi_j=\lim_{n\to \infty} p_{i,j}^{(n)}\qquad \forall i,j.$$

Solving the equation $\pi P=\pi$ for your chain gives
$$\pi=(1/3,1/3,1/3)$$
and thus, by the cited theorem,
$$\lim_{n\to \infty} P^{(n)}=\begin{pmatrix}
\pi_1 & \pi_2 & \pi_3\\
\pi_1 & \pi_2 & \pi_3\\
\pi_1 & \pi_2 & \pi_3
\end{pmatrix}=\begin{pmatrix}
1/3 & 1/3 & 1/3\\
1/3 & 1/3 & 1/3\\
1/3 & 1/3 & 1/3
\end{pmatrix}$$
which is the result we were looking for.
Answer: Let
$$ \sigma = p^2 + q^2 + r^2 - qr - rp - pq = \frac{1}{2} \left( (q-r)^2 + (r-p)^2 + (p-q)^2 \right) \geq 0.  $$
Note $ \sigma = (p+q+r) \sigma = p^3 + q^3 + r^3 - 3 pqr.$
Which is why the characteristic polynomial of your matrix is
$$ \lambda^3 - \lambda^2 - \sigma \lambda + \sigma = (\lambda - 1)(\lambda^2 - \sigma) $$
On the other hand
$$ 1 = p^2 + q^2 + r^2 +2 qr +2 rp +2 pq, $$ so
$$ \sigma = 1 - 3 (qr + rp + pq) < 1. $$
The eigenvalues are $1, \sqrt \sigma, -\sqrt \sigma.$ The diagonalized matrix $ D = P^T MP$ (where $P$ is orthogonal) raised to an arbitrarily large power, converges to the diagonal matrix with entries $1,0,0.$ Reverse the diagonalization, we get a symmetric rank one matrix.. give me a minute
Where was I?
$$
P =
\left(
\begin{array}{rr}
\frac{1}{\sqrt 3} & a & b \\
\frac{1}{\sqrt 3} & c & d \\
\frac{1}{\sqrt 3} & e & f
\end{array}
\right)
$$
$$
D_\infty =
\left(
\begin{array}{rr}
1 & 0 & 0 \\
0 & 0 & 0 \\
0 & 0 & 0
\end{array}
\right)
$$
We then just multiply out
$$
M_\infty = P D_\infty P^T =
\left(
\begin{array}{rr}
\frac{1}{ 3} & \frac{1}{ 3} & \frac{1}{ 3} \\
\frac{1}{ 3} & \frac{1}{ 3} & \frac{1}{ 3} \\
\frac{1}{ 3} & \frac{1}{ 3} & \frac{1}{ 3}
\end{array}
\right)
$$
Comment: Take all the time you need, @Will Jagy!
Comment: @RobertLewis done.
Answer: firstly we note that all even powers of $M$ lie within a two-dimensional subalgebra whose members we denote $A(x,y)$ with $x,y \in \mathbb{R}$, since
$$
M^2 = \begin{pmatrix} x_2 & y_2 & y_2 \\ y_2 & x_2 & y_2 \\ y_2 & y_2 & x_2 \end{pmatrix} = A(x_2,y_2)
$$
where
$$
x_2=p^2+q^2+r^2
$$
and
$$
y_2 = pq+qr+rp
$$
with
$$
x_2+2y_2 = (p+q+r)^2 =1
$$
for subsequent squarings (of $M$) we will have:
$$
x_{2^{n+1}} = x_{2^n}^2+2y_{2^n}^2 \\
y_{2^{n+1}} = 2x_{2^n}y_n+y_{2^n}^2
$$
from which we have:
$$
x_{2^{n+1}}+ 2y_{2^{n+1}} = (x_{2^n}+ 2y_{2^n})^2 = 1\tag{1}
$$
and
$$
x_{2^{n+1}}-y_{2^{n+1}} = (x_{2^n}-y_{2^n})^2  = \lambda^{2^n} \tag{2}
$$
where $0 \le \lambda = x_2-y_2 \lt 1$
it is easily verified that if
$$
A(X,Y) = A(x,y)A(x',y')
$$
then
$$
X-Y = (x-y)(x'-y')
$$
any even number $2N$ may be written
$$
2N = \sum_{k=1} a_k2^k
$$
with $a_k \in \{0,1\}$ so
$$
M^{2N} = \prod_{a_k=1} M^{2k}
$$
so, using (2)
$$
x_{2N}-y_{2N} = \lambda^N
$$
this shows that the subsequence $M^2,M^4,M^6,\dots$ converges to $A(\frac13,\frac13)$#
to deal with the odd powers we note that
$$
M^{2N+1} = M(M^{2N}) = M\bigg(A(\frac13,\frac13) + \frac13\lambda^N A(2,-1)\bigg) = A(\frac13,\frac13) +O(\lambda^N)
$$
Comment: +1 This shows that the subsequence $M^{2^n}$ converges, but how to finish the rest?
Comment: good point. i'll add to the post.
Answer: Here is a slightly streamlined approach. Let $E$ the matrix with all entries equal to $1$ and let $A=M^2$. To prove that $M^n$ converges to $\frac13E$, it suffices to show that $A^n$ converges to $\frac13E$, because such convergence implies also that $M^{2n+1}=A^nM$ converges to $\frac13EM=\frac13E$.
As another answer has pointed out, $A=M^2$ is in the form of
$$
A=M^2=\pmatrix{x&y&y\\ y&x&y\\ y&y&x},
$$
where $y=pq+qr+rp$. Since all row sums of $M$ are equal to $1$, row sums of $A$ must be equal to $1$ too, i.e. $x+2y=1$. Furthermore, as $p+q+r=1$, if we substitute the equality $p^2+q^2+r^2=1-2(pq+qr+rp)$ into the inequality $(p-q)^2+(q-r)^2+(r-p)^2\ge0$, we get $y=pq+qr+pr\le\frac13$. Thus
$$
A=(1-3y)I+yE,
$$
where $0\le 1-3y<1$.
Let $U$ be any real orthogonal matrix whose first column is the unit vector $\frac1{\sqrt{3}}(1,1,1)^T$. Then $E=3U\operatorname{diag}(1,0,0)U^T$. Consequently,
$$
\begin{align}
\lim_{n\to\infty}A^n
&=\lim_{n\to\infty}U\,[\,(1-3y)I+3y\operatorname{diag}(1,0,0)\,]^n\,U^T\\
&=\lim_{n\to\infty}U\operatorname{diag}(1,\,1-3y,\,1-3y)^nU^T\\
&=U\operatorname{diag}(1,0,0)U^T=\frac13E.
\end{align}
$$
Answer: Except for the last line, this is a purely algebraic answer, as there is a lot of special structure in this problem.  (Note Gerschgorin discs are an elementary and powerful but underutilized tool to bound eigenvalues.  They also have a nice picture associated with them.)
you have a real valued symmetric transition matrix.  Hence it is diagonalizable with real eigenvalues, and mutually orthonormal eigenvectors.
$M = U \Lambda U^T$
It's rows and columns both sum to one i.e. it is double stochastic.  Hence we know $\lambda_1 = 1$ and $\mathbf u_1 \propto \mathbf 1$. (In fact $\mathbf u_1 = \frac{1}{\sqrt{3}}\mathbf 1$)
$trace(M) = p + q + r = 1 = \lambda_1 + \lambda_2 + \lambda_3 = 1 +\lambda_2 + \lambda_3$
Hence we know $\lambda_2 + \lambda_3 = 0$. Put differently: $\lambda_2 = - \lambda_3$.
Use Gerschgorin discs to find that the minimum eigenvalue $\gt -1$.
I.e. each disc has a center point $\gt 0$ and a radius $\lt 1$.  (It's really more of a line segment than a disc since we know the eigenvalues are real, but we can still draw the disc as an upper bound.)
Hence $\vert\lambda_2\vert \lt 1$ and $\vert\lambda_3\vert \lt 1$
$M^n = U \Lambda^n U^T = \big(\lambda_1^n \mathbf u_1 \mathbf u_1^T + \lambda_2^n \mathbf u_2 \mathbf u_2^T + \lambda_3^n \mathbf u_3 \mathbf u_3^T \big) = \big(1^n \mathbf u_1 \mathbf u_1^T + \lambda_2^n \mathbf u_2 \mathbf u_2^T + \lambda_3^n \mathbf u_3 \mathbf u_3^T \big)$
now at the end, take a limit:
$\lim_{n \to \infty} M^n = \lim_{n \to \infty}\big(1^n \mathbf u_1 \mathbf u_1^T + \lambda_2^n \mathbf u_2 \mathbf u_2^T + \lambda_3^n \mathbf u_3 \mathbf u_3^T\big) = 1 \mathbf u_1 \mathbf u_1^T + 0 \mathbf u_2 \mathbf u_2^T + 0 \mathbf u_3 \mathbf u_3^T = \mathbf u_1 \mathbf u_1^T $
Comment: Consider adding a link to some material on Gerschgorin discs, so future readers can easily verify the results you have stated.
Comment: The proof of Gerschgorin discs is intimately tied in with Levy-Desplanques and diagonally dominant matrices -- if people are familiar with such things.  There's a nice walk-through here: https://golem.ph.utexas.edu/category/2016/08/in_praise_of_the_gershgorin_di.html .  Though, they curriously did not make the connection with markov chains and how having non-zero entries in each diagonal of a transition matrix makes it necessarily become aperiodic-- a direct consequence of Gerschgorin discs.

Limit of power of Markov matrix


can you create / write / append a string to a file in a single line in Ruby

Question: Is it possible to do this?
v='some text'
w='my' + Time.new.strftime("%m-%d-%Y").to_s + '.txt'
File.write(w,v) # will create file if it doesn't exist and recreates everytime

without having to do File.open on an instance? Ie just a class method that will either append or create and write? Ideally a ruby 1.9.3 soln.
thx
Edit 1
here's what I tried based upon docs. I hadn't seen the rdoc but had seen some other examples. Again I'm just asking if possible to open a file in append mode via File.write? thx
irb(main):014:0> File.write('some-file.txt','here is some text',"a")
TypeError: can't convert String into Integer
    from (irb):14:in `write'
    from (irb):14
    from /usr/local/rvm/rubies/ruby-1.9.3-p392/bin/irb:13:in `'
irb(main):015:0>

irb(main):015:0> File.write('some-file.txt','here is some text',O_APPEND)
NameError: uninitialized constant O_APPEND
    from (irb):15
    from /usr/local/rvm/rubies/ruby-1.9.3-p392/bin/irb:13:in `'
irb(main):016:0>

Comment: soln. thx. What a polite expression.
Comment: You can always do something in one line if you want.
Comment: @sawa not sure what soln bothers you, oh well
Comment: What is your question? File.write works and did you try?
Comment: I'm aware on new file, I'm trying to append. I've updated question; just looking for syntax
Answer: Ruby has had IO::write since 1.9.3.  Your edit shows you're passing the wrong args.  The first arg is a filename, the second the string to write, the third is an optional offset, and the fourth is a hash that can contain options to pass to the open.  Since you want to append, you'll need to pass the offset as the current size of the file to use this method:
File.write('some-file.txt', 'here is some text', File.size('some-file.txt'), mode: 'a')

Hoisting from the discussion thread:
This method has concurrency issues for append because the calculation of the offset is inherently racy.  This code will first find the size is X, open the file, seek to X and write.  If another process or thread writes to the end between the File.size and the seek/write inside File::write, we will no longer be appending and will be overwriting data.
If one opens the file using the 'a' mode and does not seek, one is guaranteed to write to the end from the POSIX semantics defined for fopen(3) with O_APPEND; so I recommend this instead:
File.open('some-file.txt', 'a') { |f| f.write('here is some text') }

Comment: Hi folks - new to ruby, but why is the File.size() needed if opening with 'a'?  Isn't `File.write('f.txt','message', mode: 'a')` sufficient?
Comment: thx, this seems to do it. Not a big fan of that ruby api piece - just really ugly. Originally was looking at this for handling threading issues with block syntax that we have with code written like @ennuikiller . I doubt this is going to fix that though. thx again for answer, when I read that api docs first time I couldn't believe that was syntax.
Comment: @timpone Yeah, the use case for `IO.write` is nice for create or overwrite semantics, but awkward for append.  Might consider extendeding IO with `class IO; def self.append(fn,str,opts={}); IO.write(fn,str,File.size(fn),{mode: 'a'}.merge(opts)); end; end`
Comment: As I think on it again, this interface blows for append in a concurrent context because there's always a race between finding the file size and issuing the write. I think you're best off just opening the file in sync-append mode and writing.
Comment: isn't there a race condition on the block example like in @ennuikiller's example. One of the reasons we want to go with the single line example is better thread safety. Any info on what you think woudl be appreciated or more fleshing out of your most recent comment.
Comment: @timpone If you open the file in O_APPEND mode (ruby `'a'` mode) all writes will be at end of file ["Opening a file in append mode (a as the first character of mode) causes all subsequent write operations to this stream to occur at end-of-file, as if preceded by an fseek(stream,0,SEEK_END);"](http://linux.die.net/man/3/fopen). This relies on OS semantics and that ruby issues system writes on the open file and doesn't buffer internally.
Comment: @Beel because that isn't the argument signature of [`IO::write`](http://www.ruby-doc.org/core-2.0/IO.html#method-c-write) -- which is why my earlier comment says this interface blows for append. A better way to this with correct append semantics, not subject to races is `File.open('f.txt','a') { |f| f.print 'message' }`
Comment: @dbenhur -- isn't the offset optional for File.write?  It seems to work without the offset in irb.
Comment: Two things:1) The original question was "create or writeP
Answer: To make it clear as some comments are suggesting I tested this working:

IO.write("/tmp/testfile", "gagaga\n", mode: 'a')

That one appends to the file without need to calculate offset. Rubydoc is little misleading. Here's a bug about that:
https://bugs.ruby-lang.org/issues/11638
Answer: File.open('my' + Time.new.strftime("%m-%d-%Y").to_s + '.txt', 'w') { |file| file.write("some text") }

Comment: This is will write, but not append, to file. I believe OP was trying to append to a file. Create the file handle with 'a' when you want to append.
Answer: MRI has that method already (I literally copied and pasted your code and it worked), but last time I checked, JRuby and Rubinius didn't. They might now, I don't feel like installing the latest versions to see.
http://rdoc.info/stdlib/core/IO.write
Comment: thx for posting, I had seen this and updated question with edit 1. I tried file write with "a" but says it's looking for an int (which doens't appear to be consistent with rdoc) and then tried standard UNIX constant but doesn't like that either. Really, just looking to see if this syntax is possible. Not sure why all the downvotes
Comment: If you copy and pasted and it worked, your ruby is broken.  The problem with his call is that the third argument is supposed to be an integer offset, not a file mode.