Stuck on "Updating setup files..." when installing Diablo 3?

Question: After a reasonable hiatus from Blizzard games, I have decided to reinstall Diablo 3. I used to have it installed and working on this machine and removed my previous install using Add/Remove Programs. However, now when I try to reinstall the game, the Diablo 3 Setup starts 'Updating setup files...' and then hangs;

I have had a quick google for ideas on how to fix it which seems to bring up a bunch of posts when the server loads were really high last year, nevertheless I have been through the list of suggestions, making sure that secondary login is enabled, running the installer as administrator, etc.
After leaving the installer for ~30 minutes, it finally brings up an error stating it could not run the Blizzard agent;

This gives me an error code - BLZPTS00007 - which gives me a few more google hits including a seemingly official guide on how to troubleshoot agent issues on Battle.net, however performing the steps listed under 'Advanced Troubleshooting' still hasn't resolved my problem.
How can I get past "Updating setup files..." when reinstalling Diablo 3, and what is error BLZPTS0007?
Comment: Related: http://gaming.stackexchange.com/questions/65601/my-blizzard-downloader-is-stuck
Comment: Killing any of the agent processes that spawn (it spawns many) results in the launcher loading with an immediate error stating "There has been a communication error, please restart the launcher", restarting the launcher results in the process repeating again
Comment: Did you try to remove D3 again, then manually delete all the files associated with it(don't know which ones exactly, but most probably in `My Documents` there will be a folder for D3)? Run `CCleaner` twice, then try it again. If it didn't help maybe there is a problem with the game disk? Try downloading an installer from `Blizzard` website. These were just some wild guesses, so I kept it as a comment
Comment: since it didn't "install" yet - there is no entry in add/remove programs. I have nothing in My Documents, I have the launcher files in C:\ProgramData and I have removed all of those, I have cleared all of my various temporary file locations as per the recommendations, rebooted, ensured that none of the files had returned, etc etc - still doesn't get past that screenshot
Comment: What OS are you running? Windows 7 64bit I presume?
Comment: Windows 8 64 bit - I have previously run Diablo 3 on this machine with this operating system but I had uninstalled it and now I can't reinstall it
Answer: For whatever reason, Internet Explorer (which I never use) was set to "work offline". For whatever reason, with Internet Explorer set to work offline, the Diablo 3 installer was failing to do anything other than time out.
I disabled "work offline" by unchecking "Work Offline" in the file menu (available by pressing the ALT key in newer versions of Windows/Internet Explorer);

Once this option was disabled, everything worked first time.


When in AC: Syndicate does the song "Underground" play?

Question: Ubisoft recently posted the entire soundtrack of Assassin's Creed: Syndicate on their Youtube channel, UBILOUD. I've listened to the tracks and would like to know the context in which the track Underground which I like quite a lot, is being played.
I am perfectly okay with answers containing spoilers.
Answer: I've checked some youtube videos, and it appears to play during the credits.

 calls it the Ending Song.
Note: I'm not 100% sure about this, but the evidence points to it. Youtube commenters are referring to an emotional scene that played around the time of this song, and searching for the keywords of that scene returns the ending of the game.

Update: I finished the game. This song does not exactly play during the credits, but it does play at the very end of the main storyline,  during the emotional moment I mentioned above. I will not spoil it any further because this moment has significance to people who played earlier installments.
Answer: Modern day scene at the very end when Rebecca and Shane are ambushed in the crypt
Comment: First off: it is Shaun,  not Shane. Secondly,  it is not a crypt, it is a vault. Thirdly, Shaun and Rebecca are the ones doing the ambushing.


Maximum distance between points in a triangle

Question: An equilateral triangle has sides of unit length.
a)Show that if five points lie in/on the triangle, then at least two of the     points lie no farther than 0.5 units apart.
b)Show that 0.5 cannot be replaced by a smaller number even if there are six points.
c)If there are eight points, can 0.5 be replaced by a smaller number?
a) was simple, just divided the triangle into four equilateral triangles and used PHP. b) followed with a counterexample by placing the points on the vertices and midpoints, but c) has me stumped. I tried an approach similar to the one and think that the answer should be Yes, but can't prove it.
PS. How can we rigorously prove that two points in one of the sub-triangles differ by at most 0.5 unit. The distance "should" be maximal when the points are on the vertices, but can't prove it.
Comment: What do you mean by PHP?
Comment: [Pigeonhole Principle] (https://en.wikipedia.org/wiki/Pigeonhole_principle)
Answer: Re your PS: Pick two points $P,Q$ in an equilateral triangle $A,B,C$. project $A,B,C$ to the line $PQ$, giving $A',B',C'$. Say $A'$ is the "leftmost" and $B'$ the "rightmost" of the projections. Then $|PQ|\le |A'B'|\le |AB|$. (We see that by the same argument, two points in a polygon are at most as far apart as two vertices, i.e., as the maximal edge-or.diagonal.
Now to c:
Let $ABC$ be our triangle. Pick suitable $r=\frac{\sqrt3-1}{2}\approx 0.366<\frac12$. Draw the circles with radius $r$ around $A,B,C$. In the "middle" there is room for a small equilateral triangle with vertices on these circles and side length $1-r\sqrt 3=r$. Verify that all seven parts in the figure have diameter $r$. Therefore, the pigeons strike back if we have eight points.
To visualize, in the following illustration all blue circles have radius $r$ and centre one of the nodes:
Answer: To answer your 'PS': Consider two distinct points in an equilateral triangle. Draw the line joining them and let this line intersect the triangle in $P$ and $Q$. It will do so in two distinct points because the original points are themselves distinct. Obviously, the distance between $P$ and $Q$ is not less than that between the two original points. Now, move $P$ along the circumference of the triangle until it is as far as possible from $Q$.
$P$ will end up at a vertex of the triangle. To prove this, suppose it ended up at a point $P^{\prime}$ on the edge. Now, drop a perpendicular from $Q$ on to the edge containing $P^{\prime}$, at $D$. ${QP^{\prime}}^2 = QD^2 + {DP^{\prime}}^2$, by Pythagoras' Theorem, but the distance to the further vertex $V$ on the edge, $DV$, is not less than $DP^{\prime}$; thus ${QP^{\prime}}^2 = QD^2 + {DP^{\prime}}^2 \leq QD^2 + DV^2 = QV^2$.
Repeating the above argument for $Q$ as well, we see that both $P$ and $Q$ end up at vertices of the triangle and you cannot move them further apart. Note that the symmetry of an equilateral triangle is implicitly used in the proof, when we talk about dropping the perpendicular and pushing the points away.
To answer 'c': if we draw the four sub-triangles again, we can place six points at the vertices and thus achieve the maximum space between them, but now, a seventh point will definitely be at a distance less than $0.5$ from one of the six points. In fact, the maximum distance will be achieved when the seventh point is at the centroid of a sub-triangle, at a distance of $\frac{1}{\sqrt{3}}$ from a vertex.


Setup Identity Server 4 Reverse proxy

Question: Edit: more detailed explanation
We have the following setup:

NGINX reverse proxy set to do SSL offload. All internal
communication goes through HTTP. The setup of the redirect is like
this:
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Original-For $proxy_add_x_forwarded_for;
proxy_set_header X-Original-Proto $scheme;
proxy_cache_bypass $http_upgrade;
IS4 has the following setup before app.UseIdentityServer
var fordwardedHeaderOptions = new ForwardedHeadersOptions
    {
        ForwardedHeaders = ForwardedHeaders.XForwardedFor |
        ForwardedHeaders.XForwardedProto
    };
fordwardedHeaderOptions.KnownNetworks.Clear();
fordwardedHeaderOptions.KnownProxies.Clear();
app.UseForwardedHeaders(fordwardedHeaderOptions);
On the client side RequireHttpsMetadata is being set to FALSE
On the IS4 side all the Clients are configured to have HTTPS addresses for "RedirectUris" and "PostLogoutRedirectUris".
On the Client side IdentityServerAuthenticationOptions are configured like this:
new IdentityServerAuthenticationOptions
         {
            Authority = "https://[OAUTH_ADDRESS]",
            ApiName = "[API_NAME]",
            ApiSecret = "[API_SECRET]",
            RequireHttpsMetadata = false
    }

What actually happens is that when we try to visit one of our registered in IS4 Clients and the request is being redirected to IS4 for authentication we have "Unauthorized client" message screen. Furthermore after inspecting the query string of the redirected request we can see that the return URL is HTTP instead of HTTPS.
Please advise.
Comment: You don't need HTTPs for IS4 when its behaind HTTPS frontend such as NGINX, let NGINX do SSL/TLS offloading 'termination'. Its well-known practice to do ssl-offloading for backend to avoid unnecessary complexity and performance reduction without security impact. MS Azure apply similar architect concept. more here: https://learn.microsoft.com/en-us/aspnet/core/publishing/linuxproduction?tabs=aspnetcore2x#why-use-a-reverse-proxy-server
Answer: The default behaviour of Identity Server's discovery endpoint is to use the scheme
 (Http vs Https) from the request that was made to the endpoint.
Since your identity server is being hit using HTTP (since it's behind the reverse proxy) the endpoint information it's giving out will also use HTTP.
You can see this for yourself by navigating to http://[OAUTH_ADDRESS]/.well-known/openid-configuration
The latest version of Identity Server includes an origin option that allows you to force the base url to HTTPS. Use as follows:
services.AddIdentityServer(options =>
    {
        options.PublicOrigin = "https://[OAUTH_ADDRESS]";
    })

Comment: We're using version 1.5.2 and there is no "PublicOrigin" property. Maybe you're referring to versions >= 2, which as far as I can see require .NET Core 2.0.

What we currently do is:

    services.AddIdentityServer(options =>
    {
        options.IssuerUri = "https://[OAUTH_ADDRESS]";
    })

But apparently it doesn't work.
Comment: Yeah it was only added in v2. I'm currently updating everything to .net core 2 myself, I'll let you know if there's any huge problems. Anything stopping you so far?
Comment: That works for me on Identityserver4 behind treafik proxy, Thanks.
Answer: Your setup may vary but in case you are still on identityserver version < 2, i remember setting up RequireHeaderSymmetry = false as well worked for us
var forwardOptions = new ForwardedHeadersOptions
{
    ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto,
    RequireHeaderSymmetry = false
};

forwardOptions.KnownNetworks.Clear();
forwardOptions.KnownProxies.Clear();
app.UseForwardedHeaders(forwardOptions);

The issue has been discussed in here as well

Setup Identity Server 4 Reverse proxy


Forked Java VM exited abnormally. JUnit Test?

Question: I have a simple Java program that seems to work well until uploaded to my school's grading system, "WebCat", which I'm assuming is just running JUnit.  The error it kicks back is:

Forked Java VM exited abnormally. Please note the time in the report does not reflect the >time until the VM exit.

I've researched this issue and and the main first troubleshooting step seems to be to look at the dump log.  Unfortunately I cannot do that in this case. I am really at a loss on how to begin to troubleshoot this considering the lack of feedback from the grading system and the lack of compile or run-time errors.
Here is the code if anyone is familiar with this error or can at least give me some direction of where to begin troubleshooting.  Much appreciated!
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.io.IOException;

class PlayerApp {
    public static void showMenu()
    {
        System.out.println("Player App Menu");
        System.out.println("P - Print Report");
        System.out.println("A - Add Score");
        System.out.println("D - Delete Score");
        System.out.println("L - Find Lowest Score");
        System.out.println("H - Find Highest Score");
        System.out.println("Q - Quit");
    }
    public static void main(String[] args) throws IOException
    {
        if (args.length == 0)
        {
            System.out.println("File name was expected as a run argument.");
            System.out.println("Program ending.");
            System.exit(0);
        }
        String fileName = args[0];
        Scanner sc = new Scanner(System.in);
        String stnew = "";
        boolean exit = false;
        Player p = null;
        double[] scoreList;

        File dbFile = new File(fileName);
        FileInputStream fis = new FileInputStream(fileName);
        InputStreamReader inStream = new InputStreamReader(fis);
        BufferedReader stdin = new BufferedReader(inStream);
       String name = stdin.readLine();
       stnew = stdin.readLine();
       int numScore = Integer.parseInt(stnew);
       scoreList = new double[numScore];
       for (int i = 0; i < numScore; i++)
       {
          stnew = stdin.readLine();
          scoreList[i] = Double.parseDouble(stnew);
       }

       p = new Player(name, numScore, scoreList);

       stdin.close();

        System.out.println("File read in and Player object created.");
       showMenu();
       while (exit == false)
       {

        System.out.print("\nEnter Code [P, A, D, L, H, or Q]:");
        String choice = sc.nextLine().toLowerCase();
        if (choice.equals("p"))
        {
            System.out.println(p.toString());
        }
        else if (choice.equals("a"))
        {
            System.out.print("   Score to add: ");
            stnew = sc.nextLine();
            double scoreIn = Double.parseDouble(stnew);
            p.addScore(scoreIn);
        }
        else if (choice.equals("d"))
        {
            System.out.print("   Score to delete: ");
            stnew = sc.nextLine();
            double scoreIn = Double.parseDouble(stnew);
            p.deleteScore(scoreIn);
            System.out.println("   Score removed.");
        }
        else if (choice.equals("l"))
        {
            System.out.println("   Lowest score: " + p.findLowestScore());
        }
        else if (choice.equals("h"))
        {
            System.out.println("   Highest score: " + p.findHighestScore());
        }
        else if (choice.equals("q"))
        {
            exit = true;
        }
        }

   }
}

break
import java.text.DecimalFormat;

public class Player {

    //Variables
    private String name;
    private int numOfScores;
    private double[] scores = new double[numOfScores];

    //Constructor
    public Player(String nameIn, int numOfScoresIn, double[] scoresIn) {
       name = nameIn;
       numOfScores = numOfScoresIn;
       scores = scoresIn;
   }

    //Methods
    public String getName() {
       return name;
    }
    public double[] getScores() {
       return scores;
    }
    public int getNumScores() {
       return numOfScores;
    }
    public String toString() {

        String res = "";
        DecimalFormat twoDForm = new DecimalFormat("#,###.0#");
      DecimalFormat twoEForm = new DecimalFormat("0.0");
        res += "   Player Name: " + name + "\n   Scores: ";
        for (int i = 0; i < numOfScores; i++)
        {
            res += twoDForm.format(scores[i]) + " ";
        }
        res += "\n   Average Score: ";
        res += twoEForm.format(this.computeAvgScore());
        return res;
    }
    public void addScore(double scoreIn) {
       double newScores[] = new double[numOfScores +1 ];
       for (int i = 0; i < numOfScores; i++)
       {
           newScores[i] = scores[i];
       }
       scores = new double[numOfScores + 1];
       for(int i = 0; i < numOfScores; i++)
       {
           scores[i] = newScores[i];
       }
       scores[numOfScores] = scoreIn;
       numOfScores++;
    }
    public boolean deleteScore(double scoreIn) {
        boolean found = false;
        int index = 0;
        for (int i = 0; i < numOfScores; i++)
        {
           if (scores[i] == scoreIn)
            {
                found = true;
                index = i;
            }
        }
        if (found == true)
        {
            double newScores[] = new double[numOfScores -1 ];
            for (int i = 0; i < index; i++)
            {
               newScores[i] = scores[i];
            }
            for (int i = index + 1; i < numOfScores; i++)
            {
                newScores[i - 1] = scores[i];
            }
            scores = new double[numOfScores - 1];
            numOfScores--;
            for (int i = 0; i < numOfScores; i++)
            {
                scores[i] = newScores[i];
            }
            return true;
        }
        else
        {
            return false;
        }

    }
    public void increaseScoresCapacity()
    {
        scores = new double[numOfScores + 1];
        numOfScores++;
    }
    public double findLowestScore() {
        double res = 100.0;
        for (int i = 0; i < numOfScores; i++)
        {
            if (scores[i] < res)
            {
                res = scores[i];
            }
        }
        return res;
    }
    public double findHighestScore() {
        double res = 0.0;
        for (int i = 0; i < numOfScores; i++)
        {
            if (scores[i] > res)
            {
                res = scores[i];
            }
        }
        return res;
    }
    public double computeAvgScore() {
        double res = 0.0;
      if (numOfScores > 0) {
           for (int i = 0; i < numOfScores; i++)
        {
               res += scores[i];
           }
           return res / (double)(numOfScores);
      }
      else {
         //res = 0.0;
         return res;
      }
    }

}

Answer: Your program is calling System.exit(0) for certain inputs. Don't do that! That's exactly what the message is telling you: that the JVM exited in the middle of the text, before the scoring code could finish up. Instead of calling exit(), just use return to return from main() early.
Comment: Good grief! It's embarrassing to admit the time I wasted on this one small issue. Your time is much appreciated!
Comment: Is this a problem that I can have in real life, or is this just an automated grading issue?  Seems that "exiting" the program is what I wanted to do at that juncture in the program?
Comment: You do actually have to be careful when you call `exit()` in real life. If you're writing `main()` yourself, then go for it, because you're in control. If, on the other hand, you're writing a library that talks to a scanner (just an example), then that library better never, ever call `exit()`, because you don't know what kind of program might be calling you. If I use your library and my program mysteriously quits, I will not be happy!
Comment: System.exit() causes the JVM to shut down right there and now.  You don't normally want to do this in an app except for places like well defined shutdown actions.
Answer: The library System Rules has a JUnit rule called ExpectedSystemExit. With this rule you are able to test code, that calls System.exit(...).


Android Hilt dagger inject interface in viewModel @ViewModelInject got UninitializedPropertyAccessException

Question: I trying on Hilt codelab
https://codelabs.developers.google.com/codelabs/android-hilt#10
It's working fine with Activity and Fragment
logger is a RoomDB
Then I try to inject logger into viewModel with this article
By add
implementation "androidx.hilt:hilt-lifecycle-viewmodel
    :1.0.0-alpha02"
kapt 'androidx.hilt:hilt-compiler:1.0.0-alpha02'

ViewModelCode
class RecordFragmentViewModel @ViewModelInject constructor(@Assisted private val savedStateHandle: SavedStateHandle) :
    ViewModel() {
    @DatabaseLogger
    @Inject
    lateinit var logger: LoggerDataSource

Class logger to inject
 class LoggerLocalDataSource
@Inject constructor(private val logDao: LogDao) : LoggerDataSource {

LoggingModule
@Qualifier
annotation class InMemoryLogger

@Qualifier
annotation class DatabaseLogger

@InstallIn(ApplicationComponent::class)
@Module
abstract class LoggingDatabaseModule {

    @DatabaseLogger
    @Singleton
    @Binds
    abstract fun bindDatabaseLogger(impl: LoggerLocalDataSource): LoggerDataSource
}

@InstallIn(ActivityComponent::class)
@Module
abstract class LoggingInMemoryModule {

    @InMemoryLogger
    @ActivityScoped
    @Binds
    abstract fun bindInMemoryLogger(impl: LoggerInMemoryDataSource): LoggerDataSource
}

DatabaseModule
@InstallIn(ApplicationComponent::class)
@Module
object DatabaseModule {

    @Provides
    @Singleton
    fun provideDatabase(@ApplicationContext appContext: Context): AppDatabase {
        return Room.databaseBuilder(
            appContext,
            AppDatabase::class.java,
            "logging.db"
        ).build()
    }

    @Provides
    fun provideLogDao(database: AppDatabase): LogDao {
        return database.logDao()
    }
}

It's compile and run without error.
However, I use debug to watch logger and its got.
Method threw 'kotlin.UninitializedPropertyAccessException' exception.

I call logger.something() at run time its throw
Fatal Exception: kotlin.UninitializedPropertyAccessException
lateinit property logger has not been initialized

More info
https://dagger.dev/hilt/migration-guide.html
https://codelabs.developers.google.com/codelabs/android-hilt#10
https://medium.com/mobile-app-development-publication/injecting-viewmodel-with-dagger-hilt-54ca2e433865
Comment: What happens when you change the injection of your database logger from field injection to constructor injection? You could also write `class RecordViewModel (@DataBaseLogger private val logger: LoggerDataSource ...)`. Also try adding @Singleton to your DAO
Comment: @Andrew not work its Unresolved reference
Answer: Since LoggerDataSource is a interface we need to specify which implementation we need to inject. Thanks to @Andrew for the idea of inject to constructor
class RecordFragmentViewModel
@ViewModelInject
constructor(@Assisted private val savedStateHandle: SavedStateHandle,
            @DatabaseLogger private val logger: LoggerDataSource) :
    ViewModel(), LifecycleObserver {

To specify
@Qualifier
annotation class InMemoryLogger

@Qualifier
annotation class DatabaseLogger

@InstallIn(ApplicationComponent::class)
@Module
abstract class LoggingDatabaseModule {

    @DatabaseLogger
    @Singleton
    @Binds
    abstract fun bindDatabaseLogger(impl: LoggerLocalDataSource): LoggerDataSource
}

@InstallIn(ActivityComponent::class)
@Module
abstract class LoggingInMemoryModule {

    @InMemoryLogger
    @ActivityScoped
    @Binds
    abstract fun bindInMemoryLogger(impl: LoggerInMemoryDataSource): LoggerDataSource
}

Comment: Now `@ViewModelInject` and `ApplicationComponent::class` are both deprecated so If we use `@HiltViewmodel`  and replace `ApplicationComponent' with `Singltoncomponent`  then how to use this?


sound-juicer is failing for me in 16.04 (see the cascade in the question)

Question: I'm pretty sure I don't have enough information yet to solve this question, but sound-juicer has failed for me in a very specific way, which I'd like suggestions for how to debug, with the understanding that it may be a hardware problem (the disc in question, for example).
After hitting extract:

But I am able to write other files from this disk. And from other disks, so why this file?
Hitting "Close":

So, possibly data corruption? I've checked the disk, and it appears pristine.
Close again:

?
None of the results at a Google search for this string and sound-juicer are relevant.  are useful.
How would I go about making it possible to debug this usefully?
Answer: To further debug what is going on here, first step:
Run sound-juicer from the command line
Try to get the bug to reproduce after you run it from the command line, and hopefully you will see more output show up in the terminal where you ran it.
# First open up 'gnome-terminal', then
$ sound-juicer

If that doesn't get you any more info...
Check common log files

General errors: /var/log/syslog
Kernel/Hardware errors: run the command dmesg
Kernel/Hardware errors: /var/log/kern.log

Next...
Run sound-juicer from the command line with debug options
$ sound-juicer --help-all |grep -i debug
  --gdk-debug=FLAGS                 GDK debugging flags to set
  --gdk-no-debug=FLAGS              GDK debugging flags to unset
  --gtk-debug=FLAGS                 GTK+ debugging flags to set
  --gtk-no-debug=FLAGS              GTK+ debugging flags to unset
  --brasero-media-debug             Display debug statements on stdout for Brasero media library
  --gst-debug-help                  Print available debug categories and exit
  --gst-debug-level=LEVEL           Default debug level from 1 (only error) to 9 (anything) or 0 for no output
  --gst-debug=LIST                  Comma-separated list of category_name:level pairs to set specific levels for the individual categories. Example: GST_AUTOPLUG:5,GST_ELEMENT_*:3
  --gst-debug-no-color              Disable colored debugging output
  --gst-debug-color-mode            Changes coloring mode of the debug log. Possible modes: off, on, disable, auto, unix
  --gst-debug-disable               Disable debugging

Looking at that list and the text of the error pop up, I'd start with
$ sound-juicer --gst-debug=all

And proceed from there.  Once I reproduced it, perhaps with all the debug flags turned, on, and it was clear this was not a setup problem, or problem with something you did configuration-wise.  I would...
File a bug on sound-juicer upstream
Look in their bug tracker, and file away!   You can also file a bug in launchpad, but make sure to reference the upstream bug when you file.  You can also go the other way around and use ubuntu-bug sound-juicer which would make a nice first start in launchpad, but don't be shy and leave the issue there, inform the upstream devs of the issue too.
More info
See here for some general tips on running gtk apps with debug flags.


How to pick a random string from an array on mouse press in Processing

Question: I want to do the following in Processing:

Display text on the screen
When mouse is not pressed, always display the first string in the array
When mouse is pressed, choose a random string from the array and have this string persist until the mouse is pressed again

I tried moving "int index = int(random(0, 3));" two draw() but this picks a random string many times a second, and I want it to pick it once until I press the mouse again.
In draw(), the value of index is always zero. It only changes in mousePressed().
Here's my code:
String[] sentences = { // defines an array of three strings
  "Sentence one",
  "Sentence two",
  "Sentence three",
};

int index = 0; // initializes variable "index" to zero

void setup() {
  size(600, 600);
}

void draw() {
  background(255);
  fill(0);
  text(sentences[index], 10, 100); // picks a random sentence from the array
}

void mousePressed() {
  if (mousePressed == true) { // when mouse pressed
    int index = int(random(0, 3)); // picks a random value for index: either 0,1,2
  }
}

Answer: You're experiencing variable shadowing.
This line:
int index = int(random(0, 3)); // picks a random value for index: either 0,1,2

declares index as a local variable, so within that scope only it shadows the global variable.
you probably meant
index = int(random(0, 3)); // picks a random value for index: either 0,1,2

(you're defining and assigning index at the top of your code, but in mousePressed() you just want to assign a different variable to the previously defined variable)
Off topic:

if (mousePressed == true) is the same as if (mousePressed), but in this context (within the mousePressed() function is redundant since it will always be true there
you're not handling the "when the mouse is not pressed" case: mouseReleased() can help with that.

Here's a modified version of your code reflecting the above:
String[] sentences = { // defines an array of three strings
  "Sentence one",
  "Sentence two",
  "Sentence three",
};

int index = 0; // initializes variable "index" to zero

void setup() {
  size(600, 600);
}

void draw() {
  background(255);
  fill(0);
  text(sentences[index], 10, 100); // displays sentence at index from the array
}

// when mouse pressed
void mousePressed() {
  index = int(random(3)); // picks a random value for index: either 0,1,2
}
// when mouse released
void mouseReleased() {
  index = 0; // always displays the 1st sentence when mouse is not pressed
}


What does gobject.type_register() do?

Question: In PyGTK, what does gobject.type_register() do? The documentation merely says

registers the specified Python class as a PyGTK type

Well, duh. What does registering a class as a PyGtk type do?
Answer: A PyGTK type can be used as the type of a PyGTK property. To be known to the GObject type system, a type has to be registered. I don't think you actually have to call this function in PyGTK, it is probably done automatically when you call <code>__gobject_init__</code>.
Sometimes the PyGTK docs are too succinct. In that case you might want to read the C docs.
Comment: You do have to in some cases (e.g. http://stackoverflow.com/questions/2022594), though I don't know *when* you need to and whether that's a bug.

What does gobject.type_register() do?


How to format entire HDD to it's factory condition?

Question: I tried to install an image onto a secondary HDD but wasn't able to make it work. Now I want to wipe out everything on the HDD to it's original factory condition so I can try again. I tried using Gparted but it still shows 4 different empty partitions. Any help on how I can bring it back to original factory condition is greatly appreciated :)
Comment: This isn't really an answer. (I would have commented but do not have enough rep) This link is related and might help:
http://askubuntu.com/questions/162602/how-do-i-remove-ubuntu-wipe-hard-drive-and-install-windows-xp
Mainly the steps 3 to 7 seem relevant.
Answer: Just create a new partition table, and this will get rid of all the partitions. You can do this in Gparted by going to "Device" and then "Create Partition Table".


Swapping list elements with jQuery

Question: I have a list:

item one<img src="/assets/img/site/down_arrow.png" class="downArrow"/

item two<img src="/assets/img/site/down_arrow.png" class="downArrow"/

item three<img src="/assets/img/site/down_arrow.png" class="downArrow"/

item four<img src="/assets/img/site/down_arrow.png" class="downArrow"/

item five<img src="/assets/img/site/down_arrow.png" class="downArrow"/

Each one has an up and down arrow on. In my jquery I have:
$(".upArrow").click(function() {

});

$(".downArrow").click(function() {

});

How can I get it so that when a user clicks up arrow it swaps the li with the one above, and when they click down it swaps with the li below (if one exists).
Answer: jsFiddle( http://jsfiddle.net/A9j3E/6/ )
$(".upArrow").click(function() {
    $(this).parent().insertBefore( $(this).parent().prev() );
});

$(".downArrow").click(function() {
    $(this).parent().insertAfter( $(this).parent().next() );
});

Comment: This is only for adjacent children, right? I mean if you want to swap first with 4th child, it won't work, I guess.
Answer: You could get a reference to the list item, and insert it before/after its sibling.
$(".upArrow").on("click", function(){
  var li = $(this).closest("li");
  li.insertBefore( li.prev() );
});

Also, be sure to properly close your images. Your down arrow images were all malformed.
Answer: try something like this
$(".upArrow").click(function() {
  var thisItem = $(this).closest('li');
  var prevItem = thisItem.prev();

  if(prevItem.length != 0) {
    thisItem.before(prevItem);
  }
});

$(".downArrow").click(function() {
  var thisItem = $(this).closest('li');
  var nextItem = thisItem.next();

  if(nextItem.length != 0) {
    thisItem.after(nextItem);
  }
});

Swapping list elements with jQuery


When creating a custom Toolkit, why does createFrame fail on OSX?

Question: We are trying to extend the UISpec4j testing framework to display the user interface when running tests. So we have a custom toolkit that wraps around the native toolkit for the relevant platform. We managed to get everything working well on windows XP, however when testing our changes on OSX, our extension of createFrame appears to behave oddly:
 public FramePeer createFrame(Frame target) {
   FramePeer resultc = new UISpecFramePeer(target);
   //super.createFrame(target);

   return resultc;
 }

Essentially with the above, we want to create a UISpecFramePeer as an interception class... So that UISpec4j can interrogate what is happening within the UI. But in our changes, we also want to display the UI. So we attempt this by creating a frame using the native toolkit and wrapping it in the UISpecFramePeer (not shown in the code above).
When we run the above code, the tests run (as we expect) but obviously nothing is displayed. However, when we include super.createFrame(target). We get the following exception:
SEVERE: Application class org.openshapa.OpenSHAPA failed to launch
java.lang.ClassCastException: org.uispec4j.interception.toolkit.UISpecFramePeer
    at apple.awt.CWindow$8.convertJComponentToTarget(CWindow.java:236)
    at apple.awt.CWindow$8.convertJComponentToTarget(CWindow.java:233)
    at apple.awt.ClientPropertyApplicator.attachAndApplyClientProperties(ClientPropertyApplicator.java:24)
    at apple.awt.CWindow$1.propertyChange(CWindow.java:190)
    at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSupport.java:333)
    at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSupport.java:341)
    at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSupport.java:270)
    at java.awt.Component.firePropertyChange(Component.java:7277)
    at javax.swing.JComponent.addNotify(JComponent.java:4479)
    at javax.swing.JRootPane.addNotify(JRootPane.java:680)
    at java.awt.Container.addNotify(Container.java:2544)
    at java.awt.Window.addNotify(Window.java:467)
    at java.awt.Frame.addNotify(Frame.java:501)
    at java.awt.Window.pack(Window.java:485)
    at org.jdesktop.application.SingleFrameApplication.initRootPaneContainer(SingleFrameApplication.java:216)
    at org.jdesktop.application.SingleFrameApplication.show(SingleFrameApplication.java:463)
    at org.openshapa.OpenSHAPA.startup(OpenSHAPA.java:444)
    at org.jdesktop.application.Application$1.run(Application.java:171)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:461)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:269)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:190)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:184)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:176)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
Exception in thread "AWT-EventQueue-2" java.lang.Error: Application class org.openshapa.OpenSHAPA failed to launch
    at org.jdesktop.application.Application$1.run(Application.java:177)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:461)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:269)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:190)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:184)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:176)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
Caused by: java.lang.ClassCastException: org.uispec4j.interception.toolkit.UISpecFramePeer
    at apple.awt.CWindow$8.convertJComponentToTarget(CWindow.java:236)
    at apple.awt.CWindow$8.convertJComponentToTarget(CWindow.java:233)
    at apple.awt.ClientPropertyApplicator.attachAndApplyClientProperties(ClientPropertyApplicator.java:24)
    at apple.awt.CWindow$1.propertyChange(CWindow.java:190)
    at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSupport.java:333)
    at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSupport.java:341)
    at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSupport.java:270)
    at java.awt.Component.firePropertyChange(Component.java:7277)
    at javax.swing.JComponent.addNotify(JComponent.java:4479)
    at javax.swing.JRootPane.addNotify(JRootPane.java:680)
    at java.awt.Container.addNotify(Container.java:2544)
    at java.awt.Window.addNotify(Window.java:467)
    at java.awt.Frame.addNotify(Frame.java:501)
    at java.awt.Window.pack(Window.java:485)
    at org.jdesktop.application.SingleFrameApplication.initRootPaneContainer(SingleFrameApplication.java:216)
    at org.jdesktop.application.SingleFrameApplication.show(SingleFrameApplication.java:463)
    at org.openshapa.OpenSHAPA.startup(OpenSHAPA.java:444)
    at org.jdesktop.application.Application$1.run(Application.java:171)
    ... 7 more

Why would simply using the native toolkit to create a frame (but not return it) create an exception, when it would otherwise behaves as normal when the super.createFrame is commented?
Answer: I havent worked on OSX, but the same problem would occur on Windows too and the reason would be this:
When you do super.createFrame(), you are essentially creating the native peer which ends up trying to show and hence addNotify methods are called. Now inside there are lot of methods that directly cast the peer to WFramePeer(this is incase of Windows, OSX it may be CWindowPeer or whatever), hence the ClassCastException. In your case, my guess is, the class CWindow is trying to cast your UISpecFramePeer to WFramePeer(or CFramePeer or whatever). Just check the CWindow code by decompiling and check. Please don't forget to post your findings.
Comment: Thanks Suraj, I feared it may have been something like this... It seems to work alright for windows, but the OSX toolkit must be setting some sort of internal flag telling it what to expect. Will try to have a crack at decompiling and checking next week sometime.


Can't access private String in Parent class for Java

Question: When I run my program I get this:

error: name has private access in Animal

The following are my classes:
Animal class
public class Animal
{
    private String name;

    public Animal(String name)
    {
         this.name = name ;
         System.out.println("The Animal " + name + " has been created.") ;

    }
    public String getAnimalName()
    {
        return name ;
    }
    public String setAnimalName(String newName)
    {
        return name = newName ;
    }
    public void sleep()
    {
        System.out.println("The Animal" + name + " is asleep.");
    }
    public void noise()
    {
        System.out.println("The Animal " + name + " is making a noise.");
    }

    public String toString()
    {
        return "The Animal " + name ;
    }
    public boolean equals(Animal otherAnimal)
    {
        return (name.equals(otherAnimal.name)) ;
    }

}

Bird class
public class Bird extends Animal
{
    public Bird (String name)
    {
        super(name);
        System.out.println("A Bird " + name + " has been created.");

    }
    public void makesNoise()
    {
        System.out.println("The Bird " + name + " is chirping.");
    }
    public String toString()
    {
        System.out.println("The Bird " + name);
    }
    public boolean equals(Bird otherBird)
    {
        return (name.equals(otherBird.name));
    }

}

Dog class
public class Dog extends Animal
{
    private String breed ;

    public Dog (String name, String breed)
    {
        super(name);
        this.breed = breed ;
        System.out.println("A Dog " + name + "of breed " + breed
                           + " has been created.") ;
    }
    public String getDogBreed()
    {
        return breed ;
    }
    public String setDogBreed(String newBreed)
    {
        return breed = newBreed ;
    }
    public void makeNoise()
    {
        System.out.println("The  " + name + " is barking.");
    }
    public String toString()
    {
        System.out.println("The Dog " + name + " of breed " + breed);
    }
    public boolean equals(Dog otherDog)
    {
        return (name.equals(otherDog.name) &&
                breed.equals(otherDog.breed));
    }

}

Main class
public class AnimalMain
{
    public static void main(String[] args)
    {

    Animal animal = new Animal("Oscar");
    Bird bird = new Bird("Tweety");
    Dog dog = new Dog("Inka", "Mutt");

    animal.toString();
    bird.toString();
    dog.toString();

    }

}

The first class compiles but the other three don't because it can't access private String from the parent class. Now I know this was to occur but is there a way of making it work where the parent class has one private String named name and only one constructor?
Comment: Use the getter!
Comment: Why do you think it is called `private` ?
Comment: *A subclass **does not** inherit the private members of its parent class* - https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
Comment: Maybe you should answer this - why do you **want** to access the field rather than use the existing getter method?
Comment: That's the problem I had, where do I implement the getter?
Answer: Can be fixed by adding a public getter in the Animal class (parent)
public String getName() {
   return name;
}

Comment: But how do I access it in the child classes?
Comment: use the `extend` keyword, public class ChildClass `extends` Animal. It will inherit all the public / default fields and methods from it's parent.
Comment: Or you could just use the getter that has already been defined (`getAnimalName()` returns `name`).
Answer: The baseclass Animal has a getter for the private variable "name". Use that function, getAnimalName(), in the subclasses that extend the Animal class wherever you would like to get the name. Like this:
public class Animal
{
    private String name;

    public Animal(String name)
    {
        this.name = name ;
        System.out.println("The Animal " + name + " has been created.") ;
    }

    ...

    public String getAnimalName()
    {
        return name ;
    }
}

public class Bird extends Animal
{
    public Bird (String name)
    {
        super(name);
        System.out.println("A Bird " + name + " has been created.");

    }

    ...

    public String toString()
    {
        System.out.println("The Bird " + getAnimalName());
    }

}


Expanding $x^x$ to series with $o(x)$ polynomials

Question: I have some doubts in finding $x^x$ series.  I know that from Taylor theorem I have
$$ f(x) = f(a) + f'(a)(x-a) + \frac{f''(a)}{2!}(x-a)^2 + \cdots + \frac{f^{(k)}(a)}{k!}(x-a)^k + o(x^k) $$
I want to have $o(x)$ polynomials so:
Let $$ f(x) = x^x $$
$$ f'(x) = (e^{x\cdot \ln x}) = (\ln x + 1)x^x$$
In use of taylor I should
$$ f(x) = f(0) + \frac{f'(0)(x)}{1!} + o(x) $$
but $f(0)$ is not defined $0^0$. Also $f'(0)$ is not defined...
But I found informations that it should be
$$  1+ \ln x \cdot x + o(x)$$
I don't know why :-(
Comment: notice that $0^0 =1$
Comment: $x^x$ is not defined for $x<0$ so you can't possibly expand it in a Taylor series about the origin.  However, since $x^x=e^{x\log{x}}$ you can substitute $x\log{x}$ into the Taylor series for $e^x$
Comment: Not every function has a Taylor series (it has to be differntiable arbitrarily many times). $x^x$ is one of those that do not have Taylor expansion around 0 (because it's not differentiable at that point). It has a Taylor expansion around any point $a>0$ though.
Answer: As you have written
$$x^x=e^{x\ln{x}}$$
and as the series expansion of $e^x$ converges for all values of $x\in\mathbb{C}$ one can write
$$e^x=\frac{x^0}{0!}+\frac{x^1}{1!}+\frac{x^2}{2!}+...$$
$$e^{x\ln{x}}=\frac{(x\ln{x})^0}{0!}+\frac{(x\ln{x})^1}{1!}+\frac{(x\ln{x})^2}{2!}+...$$
$$\therefore x^x=1+x\ln{x}+\frac{x^2\ln^2{x}}{2}+\frac{x^3\ln^3{x}}{6}+...$$
Comment: Yes, that trick really helps me, thanks!
Answer: Although $f(0)$ and $f'(0)$ are not defined, one can write$$\lim_{x\to 0^+} f(x)=\lim_{x\to 0^+} x^x=e^{\lim_{x\to 0^+} x\ln x}=e^0=1$$In that case $${f(x)=x^x\sim 1\\f'(x)=x^x(\ln x+1)\sim \ln x+1}$$both when $x\to0^+.$ Here is a plot of the function:


Limit of answers per day

Question: Is there any limit to the answers that a single user may give in one day?
As far as I know and I am aware of the reputation limit per day, there is no restriction to the number of answers that a user may post in a day. I am not mentioning the questions -someone may really have a lot of questions.
I am asking this because I have seen many bad, off topic, even misleading (not on purpose) answers in many different tags. Most of them are not up-voted (even if they wanted to) but they still add noise to the system.
We are all seeking of reputation but there is no meaning in posting low quality answers everywhere just in case.
Comment: "off topic answers" are not answers, please point that in comment and flag as "not an answer". Bad answers should be simply downvoted, and misleading ones - commented and downvoted. i hope you are doing that already, just making sure.
Comment: @mchar : Not sure where I ever read it, but I'm pretty sure that there is some rule like "***you can only ask 30 questions over a period of 50 days***". Maybe you want to include something like that to the end of your 2nd parg in your question?
Answer: As far as I know, new users (those <10 reputation) have some restrictions.
What are the new user restrictions?
New users cannot:

post more than two hyperlinks at a time, either in a post or their
user profile
contribute answers to protected questions
ask or answer questions too rapidly

You can find more info on https://drupal.stackexchange.com/help/privileges/new-user
Here is the privileges page
Answer: AFAIK you can post all the answers that you want. But if you find a bad answer you can flag it as very low quality
Answer: Significant percentage of downvoted or deleted answers will get user an answer ban. So the most important limit is not by reputation. It comes from your actions.
"Off topic answers" are not answers, please point that in comment and flag as "not an answer". Bad answers should be simply downvoted, and misleading ones - commented and downvoted. More people doing this means faster cutting out noise.
Comment: So it's up to the community members to keep the "ground" clean, makes sense, but... I have the feeling that, most of the times you are reporting a bad - misleading answer  you have to be ready to argue, to give explanations, to waste time -we have seen this many times- and this is a pain. On the other hand by doing so, shows that someone really cares for the community's quality. Concluding, to myself, a limit to the number of answers a user may post within a day would be good, so to consider twice before he answers.
Thanks all for your answers and clarifications!
Comment: @mchar downvoting and flagging "not an answer" does not require you to argue or explain. Sure, it's nice to do if you have time and patience, and if you can, you *should* do it, but in no way it is *required*.
Comment: @mchar Also, if you would (will?) post it as a feature request, my answer would be different. Probably positive, if your proposal will be reasonable.
Comment: I didn't know that I can propose requests (officially) and I guess that my statement/proposal is quite reasonable (!) given the amount of bad answers.
Comment: @mchar just tag with [meta-tag:feature-request]

Limit of answers per day


What is this material on my interior foundation walls?

Question: I have a poured concrete foundation. A portion of my basement is unfinished.
It looks like a white plaster has been sprayed onto the foundation wall inside my house:

I suspect spraying as there are pieces of wood and other things that are close to the wall are covered in what looks like splash back of the same material:

Due to some previous water damage (the source of the problem has been fixed), this material has flaked off from the wall. I have cleaned up the loose bits with a masonry chisle and now wish to restore the wall in these areas to look like the rest.

I have no idea what this material is or how to apply it. I have searched the internet for things like "spackle" or "popcorn" (since it looks like ceiling popcorn) as they relate to basement or foundation walls but everything I turn up is about troweling on parging mix, portland cement, or other masonry products (i.e. the end result is a smooth wall).
My backup plan should I not be able to replace the material is to figure out what it is and determine if I could parge over it.
Any ideas?
Answer: Two common types of things are sprayed on basement walls.
What I suspect you have there is a white "waterblocking" coating - something like UGL Drylock (not an endorsement, just an example. I prefer waterbase version)
(source: drylok.com)
 It can be brushed or rolled, and a vigorous rolling may well provide the spatter you see. It's also becoming common to see sprayed-on polyurethane foam in basements (it's better put on the outside, but if retrofitting, putting it on the inside doesn't involve excavating all around the building) but that's usually a bit thicker and somewhat yellow (plus it's obviously plastic when you touch it.)
Comment: I don't think it's polyurethane either. It's hard and seems sort of like an enamel. I think you're right about a waterblocking coat or masonry waterproofer. I searched for Drylok and the website for this product says it can be applied using a sprayer and has a PDF detailing the process.
Answer: It is not UGL.
It is a thin parging sprayed on to help damp-proof the foundation.  It actually does very little except give an even appearance to the walls.


What is springProfile in logback?

Question: I wanted to put my log in to aws CloudWatch.
So I googled it and copied one of them.
But I understand what other thing's do but I can't under stand what springProfile does.
What is springProfile and when does it get trigger?
I'll show my code below.
<configuration packagingData="true">
    <timestamp key="timestamp" datePattern="yyyy-MM-dd-HH-mm-ssSSS"/>

    <springProperty name="AWS_ACCESS_KEY" source="cloud.aws.credentials.accessKey"/>
    <springProperty name="AWS_SECRET_KEY" source="cloud.aws.credentials.secretKey"/>

    <appender name="aws_cloud_watch_log" class="ca.pjer.logback.AwsLogsAppender">
        <layout>
            <pattern>[%thread] [%date] [%level] [%file:%line] - %msg%n</pattern>
        </layout>
        <logGroupName>Kculter-log</logGroupName>
        <logStreamUuidPrefix>Kculter-log-</logStreamUuidPrefix>
        <logRegion>ap-northeast-2</logRegion>
        <maxBatchLogEvents>50</maxBatchLogEvents>
        <maxFlushTimeMillis>30000</maxFlushTimeMillis>
        <maxBlockTimeMillis>5000</maxBlockTimeMillis>
        <retentionTimeDays>2</retentionTimeDays>
        <accessKeyId>${AWS_ACCESS_KEY}</accessKeyId>
        <secretAccessKey>${AWS_SECRET_KEY}</secretAccessKey>
    </appender>

    <appender name="application_log" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>[%thread] [%date] [%level] [%file:%line] - %msg%n</pattern>
        </encoder>
    </appender>

    <springProfile name="(local | development)">
        <root level="INFO">
            <appender-ref ref="application_log"/>
            <appender-ref ref="aws_cloud_watch_log"/>
        </root>
    </springProfile>
    <springProfile name="(stage | production)">
        <root level="INFO">
            <appender-ref ref="application_log"/>
            <appender-ref ref="aws_cloud_watch_log"/>
        </root>
        <logger name="com.example" level="DEBUG">
            <appender-ref ref="aws_cloud_watch_log"/>
        </logger>
    </springProfile>
</configuration>

Answer: your application will be using that particular appender while logging in a particular spring profile.
example :
<springProfile name="(local | development)"> // only application_log appender will be use if your spring.profile=local
        <root level="INFO">
            <appender-ref ref="application_log"/>
        </root>
    </springProfile>
    <springProfile name="(stage | production)">// only aws_cloud_watch_log appender will be use if your spring.profile=stage/production & so on.
        <root level="INFO">
            <appender-ref ref="aws_cloud_watch_log"/>
        </root>
        <logger name="com.example" level="DEBUG">
            <appender-ref ref="aws_cloud_watch_log"/>
        </logger>
    </springProfile>

hope you get the idea.

What is springProfile in logback?


Should a State Machine need to expose its current state?

Question: We use a State Machine 'framework' (based on the State Pattern) which doesn't expose its current state, which sometimes means I have to do things in a roundabout way.
When I questioned this design decision, one of the justifications was that "if you need to know the current state, you're using it wrong".
Is this correct? I'm not much of an expert on state machines.
(I'm asking here because I know I have an inherent bias against the State Pattern, which I find too verbose.)
EXAMPLE
Imagine a system which in one of it states reads two sensors. One sensor gives a numeric value, the other gives a boolean which tells you if the first is 'reliable' or not. The system outputs a value which is either the current 'good' value, or an interpolation (or some other fancy calculation) based on the last n good values.
My idea would be to have two substates - one 'good', the other 'not'. And when a new value arrives, I'd like to ask the state machine which state it's in so that I know how to handle the interpolation.
(I think I've answered my own question: the solution would be to have a NewDataValue(val) event in the state machine, which would only forward the value from the 'good' state?)
Answer: I have to agree with the person who made the "using it wrong" comment.
The whole point of a state machine is to be a black box into which events are pumped and which cause certain things to happen based on those events (including state transitions). The events themselves should not depend at all on the current state of the machine.
I cannot envisage a single situation in which the event should change depending on the current state (but feel free to enlighten me if you have one).
An event will always be what it is. If it needs to be treated differently based on the current state, that is an issue for the state machine itself, not the event pump.
In fact, the whole idea of changing an event based on the current state flies in the face of encapsulation.
The best state machines have a very simple form:
                         +------+
                         |      | state
                         V      |  transitions
            +---------------+   |
 events --> |               | --+
            | state machine |
effects <-- |               |
            +---------------+

In other words, events are pumped into it somehow (independent of the state) and it has certain effects based on its state and the events. And it maintains its own state.

In terms of the update to your question where you would like to handle the output differently based on whether the last reading was good or a formula based on previous ones, I would just put that in the effects section. Have the state machine output the current value plus an indication as to whether it was from the sensor or calculated.
Then your code which handles the effects can do what it likes with that information. That effectively gives you the information you need and doesn't break the black-box nature.
Comment: I had an example (see my updated question), but I think I've answered it myself :)
Answer: Well, that's the real question. Why do you need to know the current state of the state machine? What do you plan on doing with it?
If you're second guessing it, that is trying to predict where the state machine will be in the future based on the current state and new inputs, then you're running something in parallel to the state machine. Dunno whether that's good or bad, kind of depends on what and why you're doing it.
Ostensibly, the state machine is a black box (or in some cases, it seems like a slot machine!) that you feed data in to and pull data out of.
Like anything in programming, there's no need for things to be opaque black boxes. Things can always be clear cased boxes that have input slots and output slots, but you can at least see the gears running inside of them. But it is counter to the abstraction if you're trying to work around it, since the state machine is designed to encapsulate a block of logic.
So, the opacity of the structure isn't really the issue, it's what you're trying to do with the information if or when you get it.
Comment: I'm afraid i have to disagree with "there's no need for things to be opaque black boxes". This will invariably lead to information leakage and people relying upon that information. That's the same people who will track you down and beat you to death when you try to make your code more efficient, breaking that leakage that they have come to depend upon. You don't _ever_ make information available outside a data structure unless you want to be locked into supporting it forever.
Comment: Just because the process is open to inspection doesn't mean that it has to be corrupted. Your contract is explicit, the implementation may well provide light upon that contract, but it doesn't make the contract inviolate. If others try to violate that contract, that's their problem. You may like to conduct your business in a dark, locked, smoke filled rooms. I prefer more sunlight on mine. I prefer an open grill so I can see the food being made. I prefer trusting my users than locking them out because of what they MIGHT do. I guess you choose not to trust yours.
Answer: "if you need to know the current state, you're using it wrong". - That's correct.
Current state can not be exposed. All the things that require you to act differently, because of being in specified state, should be placed inside (and only there) of that state - as private methods called from public ones, or as public, doing nothing (or something else) in other states. Your "state machine" has to work... and you, looking from outside, shouldn't know why.
Answer: In hierarchical systems design usually the higher level object knows only the abstraction of the state of the lower level object e.g. state_good abstracting (perfect, acceptable, ...) and state_bad abstracting (failed1, failed2, failed3..).
In non hierarchical systems it is OK for one object to know precisely the state of another object, especially if objects are assigned dissimilar tasks.
-Janusz


Creating a ggplot() from scratch in R to illustrate results

Question: I'm a bit new to R and this is the first time I'd like to use ggplot(). My aim is to create a few plots that will look like the template below, which is an output from the package effects for those who know it:
:
Given this data:
     Average     Error     Area
1: 0.4407528 0.1853854 Loliondo
2: 0.2895050 0.1945540 Seronera

How can I replicate the plot seen in the image with labels, error bars as in Error and the line connecting both Average points?
I hope somebody can put me on the right track and then I will go from there for other data I have.
Any help is appreciated!
Answer: Using ggplot2::geom_errorbar you can add error bars by first deriving your ymin and ymax.
df <- tibble::tribble(~Average, ~Error, ~Area,
0.4407528, 0.1853854, "Loliondo",
0.2895050, 0.1945540, "Seronera")

dfnew <- df %>%
  mutate(ymin = Average - Error,
         ymax = Average + Error)

p <-   ggplot(data = dfnew, aes(x = Area, y = Average)) +
  geom_point(colour = "blue") + geom_line(aes(group = 1), colour = "blue") +
  geom_errorbar(aes(x = Area, ymin = ymin, ymax = ymax), colour = "purple")

Comment: Thank you for your answer. I'm wondering how can I edit the colours so that they similarly match the plot I posted?
Comment: I have edited the post to add the colours. there are a number of ways to go about this.
Answer: Here's a quick and dirty one that is similar to what was just posted:
df <-
  tibble(
    average = c(0.44, 0.29),
    error = c(0.185, 0.195),
    area = c("Loliondo", "Seronera")
  )

df %>%
  ggplot(aes(x = area)) +
  geom_line(
    aes(y = average, group = 1),
    color = "blue"
  ) +
  geom_errorbar(
    aes(ymin = average - 0.5 * error, ymax = average + 0.5 * error),
    color = "purple",
    width = 0.1
  )

The trickiest part here is the group = 1 segment, which you need for the line to be drawn with factors on the x axis.
The aes(x = area) goes up top because it's used in both geoms, while the y, group, ymin, and ymax are used only locally. The color and width arguments appear outside of the aes() call since they are used for appearance modifications.
Comment: Thank you for your answer. However, I'm getting the following error when using your script:```Don't know how to automatically pick scale for object of type function. Defaulting to continuous.
Error: All columns in a tibble must be 1d or 2d objects:
* Column `x` is function
Call `rlang::last_error()` to see a backtrace```
Comment: I'm not sure - after loading `library(tidyverse)`, the above code works for me in a fresh R session.


How to improve image uploading and downloading time on google cloud bucket

Question: I am uploading & downloading files in bucket created on Google Cloud through Project created in Android-Studio.
I am feeling that images upload and download is taking long time.
I have also checked it by enabling automatic scaling, my appengine-web.xml file looks like:
<?xml version="1.0" encoding="utf-8"?>
<appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
    <application>APP_ID</application>
    <version>1</version>
    <threadsafe>true</threadsafe>
    <instance-class>F4_1G</instance-class>

    <automatic-scaling>
        <min-idle-instances>1</min-idle-instances>

        <max-idle-instances>automatic</max-idle-instances>

        <min-pending-latency>30ms</min-pending-latency>
        <max-pending-latency>automatic</max-pending-latency>
        <max-concurrent-requests>50</max-concurrent-requests>
    </automatic-scaling>

    <system-properties>
        <property name="java.util.logging.config.file" value="WEB-INF/logging.properties" />
        <property name="gcm.api.key" value="gcm_key" />
    </system-properties>
</appengine-web-app>

And Servlet to Upload image looks like this:
public class UploadImageServlet extends HttpServlet {

    private static final Logger logger = Logger.getLogger(UploadImageServlet.class.getName());

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            ServletFileUpload upload = new ServletFileUpload();
            resp.setContentType("text/plain");

            FileItemIterator iterator = upload.getItemIterator(req);
            ImageJson data = new ImageJson();
            byte[] image = null;
            byte[] imageThumbnail = null;

            while (iterator.hasNext()) {
                FileItemStream item = iterator.next();
                InputStream stream = item.openStream();

                if (item.isFormField()) {
                    String field = item.getFieldName();
                    String value = IOUtils.toString(stream);
                    try {
                        if (field.equalsIgnoreCase(SESSION_PARAM_IN_FORM)) {
                            data.session = value;
                        } else if (field.equalsIgnoreCase(USER_PARAM_IN_FORM)) {
                            data.user = Long.parseLong(value);
                        }
                    } catch (NumberFormatException e) {
                        logger.warning("Invalid " + field);
                    }
                    // user, session

                } else {
                    logger.info("Got an uploaded file: " + item.getFieldName() + ", name = " + item.getName());

                    data.imageName = item.getName();

                    // You now have the filename (item.getName() and the
                    // contents (which you can read from stream). Here we just
                    // print them back out to the servlet output stream, but you
                    // will probably want to do something more interesting (for
                    // example, wrap them in a Blob and commit them to the
                    // datastore).

                    image = IOUtils.toByteArray(stream);

                    System.out.println("Creating Thumbnail...");
                    ImagesService imagesService = ImagesServiceFactory.getImagesService();
                    Image oldImage = ImagesServiceFactory.makeImage(image);

                    Transform resize = ImagesServiceFactory.makeResize(120, 120);

                    //Resize The Image using the transform created above
                    Image resizedImage = imagesService.applyTransform(resize, oldImage);
                    imageThumbnail = resizedImage.getImageData();

                    System.out.println("Thumbnail created!!");
                }
            }

            resp.getWriter().write(new Gson().toJson(saveImage(data, image, imageThumbnail)));

        } catch (Exception ex) {
            throw new ServletException(ex);
        }

    }
}

Answer: You must upload and download images using Json format.
If you want to know any more, please contact me
Hope will be helpfull
Comment: https://cloud.google.com/storage/docs/json_api/v1/how-tos/upload
Please check this URL.


Adamantite Armor vs Palladium Armor

Question: I have heard that Palladium Armor is really good for healing. I have Adamantite Armor. Should I change to Palladium? I am currently a melee character.
Answer: Yes, the paladium armor gives you a 'Rapid Healing buff for 5 seconds when you hit an enemy'.
http://terraria.gamepedia.com/Palladium_armor
I would switch if you have the ore for it. Otherwise, I would just continue to collect items for the next armor tier.

Adamantite Armor vs Palladium Armor


What is the last column on the scoreboard before players' items?

Question: There are 5 columns on the scoreboard in Paragon. From playing other MOBA games, I've figured out what 4 of them represent, but the last eludes me. The first four are kills, deaths, assists, and number of minions killed.
The last one starts at 0 for each player, and seems to only be able to be a multiple of 10. I've seen people end the match still at 0, and I've seen people go over 1000 in that column. I've personally had games where my score has been both low and high, but I can't figure out what was different between them.
What does this column represent?
Answer: That is the accumulative total of Card XP (CXP) that that player has earned for your team.
According to this forum post, killing towers/inhibitors, and using harvesters will contribute to global CXP, increasing the total in the 5th column.
It doesn't include your individual CXP, earned from minions and enemy heroes, however. So that total is strictly the global CXP.


If I move my capital in CK2 will I take my technology with me?

Question: I'm currently playing as the king of Eire in Charlemagne and I am around 150 years in. I've started to expand into England and will soon hold all the southern counties. With the bonus of the additional holdings I was considering changing my capital from Dublin to Middlesex and my duchies to Essex and Kent.
The only downside I can see is my technology in Dublin (e.g., legalism etc.) is currently higher than in Middlesex. Will the technology transfer or will I lose it and adopt the technology levels that Middlesex currently has?
Are there any other disadvantages to moving my capital that I've not considered?
Answer: If your capital moves to Middlesex, you will use Middlesex's technology levels.
However, you will keep any technology points you haven't spent, and can spend them in Middlesex after the move. If you spend some time saving them, you'll be able to give Middlesex a technology boost when you arrive.


Python runs functions that are elements of a declared dictionary

Question: As soon as i define this dictionary:
case_dict={
    "run" : runn(),
    "name" : namee(),
    "help" : helpp(),
    "quit": quitt(),
}

python runs all these functions successively. How do i avoid these functions from running in the console when i just want to define the dict  ?
PS: all these functions are defined earlier in the code.
Comment: When do you plan to execute them ? What exactly do you expact to happen?
Comment: `runn` is the name of a function object and `runn()` is a call to it.
Comment: I plan to execute them when i call them from the dict later on in the program
Answer: You assigned the value of each key to the return value of the function, not the function itself.
Through the brackets at the end the functions get executed the moment you create the dict.
to avoid this, write runn instead of runn()
so you would end up with
case_dict={
    "run" : runn,
    "name" : namee,
    "help" : helpp,
    "quit": quitt,
}

Now, if you would like to call one of these functions you would do it like so:
case_dict["run"](parameter_1, parameter_2 ... )

Comment: yes, but when i call an element of the dict like: case_dict["run"] it doesn't run the function, it returns the runn function object.
I want each function defined as an element of the dict to run when i call it from the dict.
Comment: yes, in order to call the function you always have to use brackets. so you would have to write `case_dict["run"]()`
Comment: Ohh ok, now i get it. Thanks a lot !
Comment: @bendo97 that isn't what "calling" means


Download the latest relase file with token from private repo

Question: I want to download files from my private repository using python.
What should I do?
I tried something like this, but it doesn't work.
I also allowed everything in the token for testing, I get error again.
import requests

headers = {'Authorization': 'token ' + 'ghp_xxxxxxxxxxxxxxx'}

def download_and_apply_update(self, loading_window):
        download_url = "https://github.com/HamzaYslmn/example/releases/latest/download/example.exe"
        new_executable_path = "DetaBaseFatura_New.exe"

        response = requests.get(download_url, stream=True , headers=headers)
        total_size = int(response.headers.get("content-length", 0))
        chunk_size = 8192  # You can adjust this value as needed

        with open(new_executable_path, "wb") as new_executable_file:
            downloaded_size = 0
            for data in response.iter_content(chunk_size=chunk_size):
                new_executable_file.write(data)
                downloaded_size += len(data)
                progress_percentage = (downloaded_size / total_size) * 100
                loading_window[1]["text"] = f"Progress: {progress_percentage:.2f}%"
                loading_window[2]["value"] = progress_percentage
                loading_window[0].update()

this way I can access the tag, for example. But downloading is a completely different matter.
def get_latest_version_from_github(self):
        latest_tag_url = "https://api.github.com/repos/HamzaYslmn/example/releases/latest"
        response = requests.get(latest_tag_url, headers=headers)
        response_data = response.json()
        print(response_data)
        latest_tag = response_data['tag_name']

        return latest_tag

Answer: latest_tag_url = "https://api.github.com/repos/HamzaYslmn/{REPO}/releases/latest"
        headers = {
            "Accept": "application/vnd.github+json",
            "Authorization": "Bearer ghp_xxxxxxxxxxxxxxxxxxxxxxxxxxxx",
            "X-GitHub-Api-Version": "2022-11-28"
        }
        response = requests.get(latest_tag_url, headers=headers)

I solved


How to run one jQuery animation function on multiple elements simultaneously?

Question: The idea is to make a certain number of elements sway, and to use only one function to do it (I assume that's the best option). I made a function that would make a single element sway, which worked really well, but then I tried to make this apply to multiple elements and I ran into real problems.
What's complicating this is that the sway function is designed to generate a slightly different diameter and speed each time its called, so the swaying looks natural. It's also made to loop the motion indefinitely.
Thus the function is broken into three parts, the first setting up the array of elements it will apply to, the second (called main) generating the variables necessary for that elements swaying, and the third (called act) to run and loop the sway animation.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Balloon Proof of Concept Page</title>

    <link rel="stylesheet" type="text/css" href="main.css">

        Proj 1

        Proj 2

        Proj 3

I expected the function might get stuck on the first array element at the loop, and now that the basic code has been fixed I'm in exactly that situation. Does anyone have any ideas how to solve this, or alternative methods.
The CSS is very simple, just some basic styling
.box {
width:100px;
height:100px;
position: absolute;
background-color:red;}

.html .body {position: absolute;}

Comment: `$(hello)` is actually calling `$(0)` `$(1)` `$(2)` which obviously does nothing. Logic error or typo. Should be `main(balloons[now])` instead of `main(now)`
Comment: Thank you for that, updating immediately
Comment: @KevinB good spot, but it's the least of his problems ;-)
Comment: @Alnitak That's why it is a comment and not an answer, ;)
Answer: when you call .animate() it queues the animation, and then returns immediately.
Since you're then calling act again recursively the code just goes into an infinite loop.
Try this, instead:
function act() {
    $(hello)
       .animate({ left :  change }, speed)
       .animate({ left : -change }, speed, act);
}

i.e. register act as the completion callback of the second phase of the animation.
Comment: That's amazing, I have no idea why that works though. Why isn't this generating a queue of 'act's like before?
Comment: @OlivierButler because callbacks are ultimately triggered by the JS event loop - this might _look_ recursive, but it actually isn't, since the new version always terminates immediately and then _some time later_ it's called again.
Comment: So the function is adding the first two to the queue, moving on to the other array elements before coming back and acting again? This is really helpful thank you very much.
Comment: @OlivierButler yes, except that it doesn't come back to each element until each has finished a whole left to right (and back again) swing.
Comment: Oh I see, so by putting act at the end of the animate effect is that using the 'complete' function of the jQuery API or is it a general rule of javascript that such syntax waits for the function to complete before coming round?

P.S. If you get bored of my pestering I can understand, I could ask questions like these for a while I'm sure
Comment: @OlivierButler that's a jQuery `.animate` feature.
Answer: You can use a timer, this will repeat the movement after a period of time.


Get the name of his own variable? PHP ${$var}

Question: I want the variable name from example: ${'tell'.$var.'How}. I've tried a couple of the examples varName(); from How to get a variable name as a string in PHP?, but I didn't get it working. Any idea how to get this working?
<?php
    $var = 'Me';
    ${'tell'.$var.'How'} = 'Thanks!';
    $name = varName(${'tell'.$var.'How'});

    // Varialbe name: $tellMeHow = Thanks!
    echo 'Variable name: $'.$name.' = '.${'tell'.$var.'How'};
?>

Function:
<?php
    function varName($v) {
        $trace = debug_backtrace();
        $vLine = file( __FILE__ );
        $fLine = $vLine[ $trace[0]['line'] - 1 ];
        preg_match( "#\\$(\w+)#", $fLine, $match );
        return $match[1];
    }
?>

Is it possible that a variable is its own name?
<?php
    $var = 'is my name '.varName().'?';
    echo $var; // is my name var?

    $why = 'Why '.$var;
    echo $why; // Why is my name var?
?>

Cool if someone knows this... and what's to tell me. ;)
Comment: Can you explain more clearly? What is the result now and what is your expected result
Comment: You passing $v into `varName()` which doesn't do anything.  But in your last example you don't pass anything, which causes an error.
Answer: These are known as "variable variables" and are described in the PHP documentation.
Comment: @NgoTuan, my answer already provides that link if you click on "variable variables".
Comment: Perhaps the person who downvoted my answer could explain why they did so?


Problem with setting up xrdp on Lubuntu 13.04

Question: After fresh install of Lubuntu 13.04 I did
sudo apt-get install tightvncserver
sudo apt-get install xrdp

Now when I log in with remote desktop client from Windows or Ubuntu, I get black and white mesh screen. I followed various help forums like this one, but nothing worked!
Comment: VNC server is better than that. Because sometimes compiz crashes because of xrdp
Answer: Ubuntu 13.04 is no longer supported for that I'm giving you solution for Ubuntu 12.04 and then I'll add the 14.04 solution later.
For Ubuntu 12.04
Use a tricky hack(obligate the xrdp to use the ubuntu-2d session always without searching for other sessions)
Install xrdp:
sudo apt-get install xrdp

Now Edit the file startwm.sh:
sudo gedit /etc/xrdp/startwm.sh

In the end of the script you can find these three lines calling functions above:
pre_start
wm_start
post_start

All you have is to comment the wm_start function by inserting leading # then add the line for needed session.
pre_start
#wm_start

gnome-session --session=ubuntu-2d

post_start

The wm_start function which is responsible for starting the window manager.
Now save and exit, then restart xdrp:
sudo service xrdp restart

This should works smoothly. I'm using it since three years ago.
For Ubuntu 14.04 and later
Install xrdp same as above
Install XFCE4 or any other supported
sudo apt-get install xfce4

Edit our .xsession file in your home:
echo xfce4-session >~/.xsession

Edit  startwm.sh file:
sudo gedit /etc/xrdp/startwm.sh

In the wm_start() Add the line startxfce4 just directly under:
 if [ -r /etc/default/locale ]; then
    . /etc/default/locale
    export LANG LANGUAGE
  fi

so the function looks like:
wm_start()
{
  if [ -r /etc/default/locale ]; then
    . /etc/default/locale
    export LANG LANGUAGE
  fi

startxfce4

  # debian
  if [ -r /etc/X11/Xsession ]; then
    . /etc/X11/Xsession
    exit 0
  fi
.....

}

Now save and exit then restart xrdp.
sudo service xrdp restart


How to upload Gameplay to Instagram PS4?

Question: I've been looking round and want to creates gaming account on Instagram. But I can't seem to find a way to upload the gameplay to Instagram. I know it can be done on the Xbox one. But what about ps4? Is there something I'm missing? Help?
Answer: On the PlayStation 4 the last 15 minutes is automatically recorded.
In order to upload this:

Press the Share button and select Upload Video Clip
Select the video clip you wish to upload
Select an online service to upload it to.
(optional) Edit the video clip
Select Share

You can upload the clip to Youtube for instance and then use that for Instagram. I don't think you can upload directly to Instagram.
More info...
Comment: Okay awesome! How would I go about getting it off my YouTube and on Instagram? I don't know if that's your area or not.
Comment: I thought you could embed youtube videos into Instagram? Well if you can't you may wanna download the video using a youtube downloader like [this](http://deturl.com/) or [this](http://en.savefrom.net/). Once you download it, you can do anything you like with it.


Solve a congruence with polynomial modulus

Question: I am trying to find a solution for $f(x)$ to the congruence:
$ (x^2-1)f(x) \equiv (x^3+10x) \pmod{x^6+x^5+x+1}$ in $Z_{11}[x]$.
I've tried thinking about this problem in $Z_{11}[x]_{x^6+x^5+x+1}$, where I would just have to find some polynomial $f(x)$ s.t $(x^2-1)f(x) \equiv (x^3+10x)$ in the system. My approach was to just take $x^3+10x$ and mod out by $x^6+x^5+x+1$. But $x^3+10x$ is already simplified in the system so perhaps I need to first multiply it by some polynomial and then mod out. I tried this but I struggled to see how I could obtain a multiple of $x^2-1$.
Any help would be appreciated.
Answer: Consider a congruence like
\begin{eqnarray*}
2y \equiv 3 \pmod{6}.
\end{eqnarray*}
It is reasonably easy to see that this that $2$ is a zero divisor, Indeed multiply both sides by $3$.
In your case ... multiply by $x^5+1$ & see what happens ?
Comment: I didn't really find any results...I multiplied by $x^5 +1$ on both sides, then divided the right side by the modulus and got a remainder that was not divisible by $x^2-1$...
Comment: \begin{eqnarray*}
(x^5+1)(x^2-1)=(x^5+1)(x+1)(x-1)=\color{red}{(x^6+x^5+x+1)}(x-1).
\end{eqnarray*}
Comment: I understand that this is true. But, if you say $f(x) = x^5+1$, this property holds but I don't think the congruence statement works. What am I missing here?
Comment: That is right and the conclusion is ...  there is no solution.


Center This Android Layout?

Question: I can't for the life of me figure out how to get my box centered on BOTH the horizontal and vertical.

Heres my xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/dragon"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:background="@drawable/playerinfosquare"
        android:orientation="vertical">

        <TextView
            android:id="@+id/spellinfotitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_margin="10px"
            android:text="Spellventory"
            android:textAppearance="?android:attr/textAppearanceLarge" />

        <TextView
            android:id="@+id/spell1info"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_margin="10px"
            android:text="No Spell Equipped"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <TextView
            android:id="@+id/spell2info"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_margin="10px"
            android:text="No Spell Equipped"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <TextView
            android:id="@+id/spell3info"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_margin="10px"
            android:text="No Spell Equipped"
            android:textAppearance="?android:attr/textAppearanceMedium" />

    </LinearLayout>

</LinearLayout>

Help?
Are you kidding me? Stack overflow thinks it knows better than me and says that I don't have enough content to explain my code sections. Well, here you go! This is what you get for having arbitrary rules that don't always make sense.
Comment: This rule is kind of important as there where a lot of code only questions asked. Be nice! :D
Answer: Put your second LinearLayout into a RelativeLayout. You can then center it much easier by setting
android:layout_centerInParent="true"

on the second LinearLayout
Answer: You need to set android:gravity="center" on your first LinearLayout.

Center This Android Layout?


C# Call form from another form

Question: login form with "connect" button in it.
main form with a "disconnect" button.
Every time i click "connect" in the login form i want to go to the main form.
Every time i click "disconnect" i want to go back to the login form.
Here are the codes for the buttons:
 private void buttonConnect_Click(object sender, EventArgs e)
    {
        this.Hide();
        ShowMessage("Successfully connected.");
        Form MainForm = new MainForm();
        MainForm.Show();

    }

    private void buttonDisconnect_Click(object sender, EventArgs e)
    {
        this.AddOwnedForm(LoginForm);
        LoginForm.Show();
        LoginForm.BringToFront();
        this.Close();
    }

Notice the first line in my code:
this.Hide();

If I delete this line, the forms work as i want. However the login form does not hide.
If I dont delete this line,
I click connect          --->  the login form hides and the main form shows up.
Then, I click disconnect ---> the login form remains hidden. Meaning i end up with no forms on my screen to control my application, despite my attempt to make it visible.
Login.Show();
Login.BringToFront();

Any help appreciated... wasted almost a full day trying to figure it out.
Comment: Have you eve worked with MDI forms?
Comment: I have not, im trying to figure it out.
Answer: Try like this
private void buttonDisconnect_Click(object sender, EventArgs e)
{
    LoginForm frmLogin= (LoginForm)Application.OpenForms["LoginForm"];
    if (frmLogin != null)
    {
        //frmLogin.Visible = true; Uncomment this line if form still not get visible.
        frmLogin.Show();
    }
    else
    {
         frmLogin = new LoginForm();
         frmLogin.Show();
    }
    this.Close();
}

and your connect code should be like this
private void buttonConnect_Click(object sender, EventArgs e)
{
    this.Hide();
    ShowMessage("Successfully connected.");
    MainForm frmMain = new MainForm();
    frmMain.Show();
}

Comment: Can i ask what does LoginForm frm = (LoginForm)Application.OpenForms["LoginForm"];   this mean ?
Comment: Error 2 A local variable named 'frmLogin' cannot be declared in this scope because it would give a different meaning to 'login', which is already used in a 'parent or current' scope to denote something else
Comment: First time i run it it works well, second time i run it it does NOT hide, every time i run it it creates a new login form... :/, i want to be able to spam connect/disconnect withough creating new windows (forms)
Comment: What is the name of your LoginForm? Can you show your full code of MainForm on http://www.pastie.org?
Comment: this code was edited because i tried a solution in the comments and didnt work, i m so tired right now i cant even think...
Comment: http://pastie.org/9547610#21  this is your code ,  problem with this one is that everytime i click disconect it creates a new login form, when this.Hide() is uncommented , it "seems" like it works , but it just makes new forms every single time i click disconect and they stay hidden , http://pastie.org/9547634#21  this is my code, if i remove the line this.Hide() , it works EXACTLY as i want , BUT i doesnt hide the login form ! , if i comment it and i click login , then disconect, ALL forms become HIDDEN and i cant do anything :/ this is driving me crazy
Comment: welp... u sir are a god :) it fking works....... thank you so much mate... u are awesome
Comment: im gonna ask a general question that i have been trying to find the answer lately and i couldnt.. in my code u saw i had 2 classes , 'Login' and 'FormMySqlQueries' , if i want to add the same funcion 'Function1' to those classes , do i have to copy and paste the code to both of them? isnt there any other , more professional way of doing it ?
Comment: If the function is doing same process and it doesnt use any ui control of the form then you can create another class and make your method as static. Now, you can call that method from both form like `NewClass.MyFunction(param);`
Comment: i understand what you said , thats very useful, is there anyway to do this with UI control, if for example the form1 has a button1 and the form1 also has a button1 ?
Comment: unfortunatly it says "You must have 20 reputation on Stack Overflow to talk here" , oh i saw your answer in the chat room, i understand what you mean , thanks so much :) i guess making separate functions is good yeah.
Comment: Accessing the UI from outiside the form is not a good idea. it is better to make function separate. BTW, it is not possible to make common function that can access the UI of more than one form.
Answer: In the login form, subscribe to the MainForm.FormClosed event:
this.Hide();
ShowMessage("Successfully connected.");
Form MainForm = new MainForm();
MainForm.FormClosed += (s, args) => this.Show();
MainForm.Show();

Comment: i will try it , thank you. even though i dont know what that does.
Comment: @user3716252 It causes `MainForm` to invoke the specified delegate when it closes. If the syntax is confusing, the delegate is called a lambda expression. You can read about them here: http://msdn.microsoft.com/en-us/library/bb397687.aspx
Comment: thank you a lot, when i have a clear head i will check it with details.
Comment: @user3716252 Have you tried adding that one line to your original code?
Comment: for the last 30mins im trying to reply to 2 comments per minute, i didnt try your solution yet, i absolutly will though
Answer: Try this.
Class MainForm
{
    LoginForm login_form;
    public MainForm()
    {

    }
    public MainForm(LoginForm log)
    {
        login_form = log;
    }
    private void MainForm_Load(object sender, EventArgs e)
    {

    }

    private void buttonConnect_Click(object sender, EventArgs e)
    {
        this.Hide();
        ShowMessage("Successfully connected.");

        if(login_form == NULL)
        {
            login_form = new LoginForm(this);
        }
        login_form.Show();
    }
}

Class LoginForm
{
    MainForm main_form;
    public LoginForm()
    {

    }
    public LoginForm(MainForm man)
    {
        main_form = man;
    }
    private void LoginForm_Load(object sender, EventArgs e)
    {

    }

    private void buttonDisConnect_Click(object sender, EventArgs e)
    {
        this.Hide();
        ShowMessage("Successfully Disconnected.");

        if(main_form == NULL)
        {
            main_form = new MainForm(this);
        }
        main_form.Show();;
    }
}

Comment: should the login form give me " successfully connected" message ?
Comment: Successfully Connected message is displayed when you click Connect button on Main form and it results a login form is appears.
Comment: i got a "main form" where i can disconect and a "login" form where i only connect
Comment: ok. just swap the form names in these two classes, the logic remains the same.
Comment: trying it as we speak
Comment: (main_form == NULL): Error 1 The name 'NULL' does not exist in the current context, i think i got it mixed up with the codes, i have no idea how your code works
Comment: i have just given you the logic. NULL is not the keyword, its null.
Comment: alright im gonna study this, this is too much for me to think , because my app is pretty huge right now , thanks for this i think its correct
Comment: 2nd row from bottom,   main_form = new MainForm(this);   you are saying "this" which means its a LoginForm but you have public LoginForm(MainForm man)  constructor ? how does this work ?
Comment: so what? public is accessible from anywhere.
Comment: i mean it expects mainForm  and you put in this which is  LoginForm, different types ? or am i retarded ?
Comment: see this is the constructor signature, public MainForm(LoginForm log)... it accepts LoginForm.
Comment: Please post a solution or choose best answer, when found your solution.

C# Call form from another form


Hood of defiance for Huskar

Question: Since BKB prevents Huskar from getting damaged by his ulti when activated as Life Break deals magical damage to both Huskar and its enemy. Does Hood of defiance reduce damage dealt to Huskar as well?
Comment: @downvoter, why the downvote? It's a good clear question with a well-defined answer...
Answer: Yes it works, you can use Hood  of defiance to reduce the damage inflicted to yourself with life break. However I recommand to not use this item on Huskar as his magic resistance grows as his life decrease so putting Hood on him is quite useless. Since the last big update, he no longer gains damage when his life is low so damage item to compensate seems the way to go (Armlet, Cristalys) or massive tank items (Hearth of Tarrasque, Assault Cuirrass, BKB)

Hood of defiance for Huskar


PHP post variable is not being rendered

Question: I have a PHP program that takes in a image name and loads the image and displays the name and the image on the page.
The variable in javascrip is written as
var latest_image_name = '<?=$post_img_name?>';

The PHP code is
<?php
        foreach($files_assoc_array_keys as $file_name){
            if($file_name==$post_img_name){
            ?>
            <?=$file_name?>
            <?php
            }else{
            ?>
            <?=$file_name?>
            <?php
            }
        }
        ?>

the html output, is being rendered as

                    <?=$file_name?>

And as you can see it seems that PHP has not replaced the tag with the posted image name.
The code works on the original server that it was developed on, it does not work when i migrated it to another server, i have tried two other servers both Centos 6.4 with apache and PHP installed. I am not sure what the setup was for the original server that it as does work on.
the full code is seen below
<?php
header('Refresh: 5; URL=display.php');
print_r($_POST['post_img_name']);
$target_directory = "uploaded_images";

if(!file_exists($target_directory)){
    mkdir($target_directory);
}

if(isset($_POST['del_image'])) {
    $del_image_name = $_POST['del_img_name'];
    if(file_exists($target_directory."/".$del_image_name.".jpg")){
        unlink($target_directory."/".$del_image_name.".jpg");
    }
if(is_dir_empty($target_directory)){
        die("Last image delete. No images exist now.");
}
    $post_img_name = basename(get_latest_file_name($target_directory), '.jpg');

}else if(isset($_POST['post_img_name'])){
    $post_img_name=$_POST['post_img_name'];
    $post_img_temp_name = $_FILES['post_img_file']['tmp_name'];
}else{
    $post_img_name = basename(get_latest_file_name($target_directory), '.jpg');
}

$files_array = new DirectoryIterator($target_directory);
$total_number_of_files = iterator_count($files_array) - 2;
$files_assoc_array = array();

$already_exists = "false";
if($total_number_of_files != 0){
    foreach ($files_array as $file_info){
        $info = pathinfo( $file_info->getFilename() );
        $filename = $info['filename'];
        if ($filename==$post_img_name) {
            $already_exists = "true";
        }
    }
}

if(!isset($_POST['del_image']) && isset($_POST['post_img_name'])){
    $target_file = "$target_directory"."/".$post_img_name.".jpg";
    $source_file = $post_img_temp_name;

    if($already_exists == "true"){
        unlink($target_file);
    }
    move_uploaded_file($source_file, $target_file);
}

foreach ($files_array as $file_info){
    $info = pathinfo( $file_info->getFilename() );
    $filename = $info['filename'];
    if(!$file_info->isDot()){
        $files_assoc_array[$filename] =  $target_directory."/".$file_info->getFilename();
    }
}

$files_assoc_array_keys = array_keys($files_assoc_array);

function get_latest_file_name($target_directory){
    $files_array = new DirectoryIterator($target_directory);
    $total_number_of_files = iterator_count($files_array) - 2;
    $timestamps_array = array();

    if($total_number_of_files!=0){
        foreach($files_array as $file){
            if(!$file->isDot()){
                $timestamps_array[filemtime($target_directory."/".$file)] = $file->getFilename();
            }
        }
    }
    $max_timestamp = max(array_keys($timestamps_array));
    return $timestamps_array[$max_timestamp];

}
function is_dir_empty($dir) {
    if (!is_readable($dir))
        return NULL;
    $handle = opendir($dir);
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
            return FALSE;
        }
    }
    return TRUE;
}

?><!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title></title>
    <link rel="stylesheet" href="css/style.css"/>

            <?php
            foreach($files_assoc_array_keys as $file_name){
                if($file_name==$post_img_name){
                    ?>
                    <?=$file_name?>
                    <?php
                }else{
                    ?>
                    <?=$file_name?>
                    <?php
                }
            }
            ?>

    Go Back

Comment: are you sure the use of `` works on your server? try using ``
Answer: As arbitter has pointed out my server did not support <?= ... ?> it worked after i changed to <?php print $variable_name ?>

PHP post variable is not being rendered