Left hand finger exercise giving massive tension

Question: This is a piano question.
I've identified a left hand exercise that is very hard for me and I wanted to ask:

Whether it's healthy to try doing it
Whether it's useful to spend time on

The exercise is simple: I put all my fingers of left hand on the D major scale, pinky on the D, thumb on A, and the rest on all notes in between (this leaves middle finger on F sharp), and depress all of them.
And then keeping those fingers depressed, I play eighths with pinky, then eighths with ring finger..
This exercise is well known on the white keys (C major), and I can do it ok there. On this D major it's a disaster! My whole hand tenses up. I've tried this for two mornings now, hence I wanted to ask whether trying to focus on removing this tension is a good thing.
My goal is to be better at left hand - also musically and rhythmically.
Comment: I'm not a pianist, but I had a similar problem when playing some weird chords on the guitar, where I could simply not physically put my fingers in the requested configuration without it straining badly. Note: it was highly uncomfortable, but didn't hurt or anything. The solution was to keep gently trying it. I tried the chord each day at the start of my practice session and didn't strain my hand too much, just a couple of tries. After a few weeks, I can now hit the chord, and can even reach beyond the chord because of the flexibility I attained. Hth, maybe you just need some more time :-)
Comment: The ring finger in particular is not built for this.  I can perform this exercise with all the other fingers on both hands relatively easily (not that I ever do so - I was just testing after reading this), but lifting the ring finger while the others are held down is very difficult - fortunately there's almost never a reason to do it in real piano playing...
Answer: Is it healthy? No. Even the C major version I would never do and would never suggest a student to it. The exercise reinforces isolating the fingers, which is not how one plays the piano, and it focuses on lifting the fingers, which is also not how one should release keys.
Is it useful? No. A better, similar exercise would be to let your fingers gently rest on the surface of the keys while using your entire arm, hand, and one finger to gently play one note in rhythm. My belief, however, is that rhythm is best practiced away from the piano: clapping, dancing, ..., movement in general is the best way to develop a feel for meter and rhythm.
Answer: Just tried it, and it was no problem! However, I'm not sure what it achieves. Exercises (and studies) should be designed to pinpoint technicalities in playing that may cause difficulties when encountered in real pieces.
There's never going to be a situation when you're going to play four fingers held down, on consecutive notes, and use just one to play eight notes. Might hold two from a chord and play the third.
Yes, it will mean you develop use of each finger separately - an excellent thing to be able to do on just about every instrument, let alone piano. There really should be no tension while playing this exercise, if you use the weight of your hand/arm to keep the keys down, but a better one would be to rest those fingers on the keys rather than keep them depressed. That would more reflect 'proper' piano playing.
If there's still tension then, you need to address what's causing it. Could be height you're playing at,(raise/lower the seat), or your position left/right, (move l/r). Could be your hand/fingers just can't cope (nothing to do about that). In which case, don't do it!
Like any new exercise that works muscles in a new way, there will be some pain/discomfort, but if that's too much, there's thousands of other exercises that are waiting to be tried instead. But always ask yourself (or your teacher)- will this ever be useful in future playing?
Comment: Yes, "separation" is good, in general, but... I seem to recall that Robert Schumann had a gadget supposed to increase separation, and injured his hand sufficiently that his virtuoso piano days ended. Doing more natural exercises is better: trills, trills in thirds, are plenty.
Answer: Is it healthy to try? That depends on how you define "try". How hard are you going to try? Are you going to spend hours pushing through the pain?
Is it useful? Ernő Dohnányi has exercises that will provoke a similar type of anxiety, and lots of good pianists swear by his book: Essential Finger Exercises (Dohnányi, Ernő)
Answer: First, never isolate a finger.  They are interconnected and isolation causes strain.  I know, most of us are taught to isolate fingers and many silly exercise books condone it.  Well, it is wrong. Believe me or don't.  In forty years you'll think back and think "Malcolm was right." but by then it will be too late if it is not already.
Technique comes from moving properly, not moving more or from some exercise. If you can't do something it is either because you have improper movements or not the correct ones.  It is possible to have both.  More practice can't fix that, only proper practice can.
If you walk knock kneed for a few hours and your knees begin to hurt, walking knock kneed more isn't going to make things better, stop walking knock kneed and walking properly will.  Likewise, practice doesn't make perfect, perfect practice does.  What you should really do is find a better teacher who knows physics, anatomy and ergonomics.  Piano playing is 99% in the arm, not the fingers. The fingers are a conduit of the arm.  Like casting a fishing pole, you cast from the feet, knees, hips, abs, shoulders, elbow, wrist then fingers with copious amounts of contrary motions.  Every motion must have an equal and opposite motion.  It is the law.  The fingers are important but power and control comes from all the other fulcrums and contrary motions combined with the laws of physics and your anatomy.  If you poke someone's eye out of course your finger does the poking but it is initiated from the shoulder and elbow.  Piano playing is the same but we also use gravity and arm weight combined with rotations, in, out, up, down,  shifts and tilts.  The arm places the fingers.  Like playing hopscotch, the feet don't jump from square to square, the calves, quads, knees, hips and shoulders contribute to unweighing your body and they all place the feet where they need to be. The feet don't drag the body. Then fingers don't drag the arm.  The arm places the fingers.
As far as it being a waste of time, if you never play anything like that in real repertoire, is there a need to be able to do it?  For example, if you live in the city where the speed limit is 30 mph, why own a sports car that can go 130?  All the technique you need you can get from your repertoire. I am an organist and rarely play stride or octaves so I don't have a need to practice them.  However, once you learn to move properly, most everything comes easily and one just needs to figure out the proper movement.
Tension is bad.  It means you are doing something wrong.  It must be corrected because further improper practice augments and amplifies the strain and also hard wires the improper movement into the brain or "muscle memory" where it will haunt you forever.  Tension is caused by muscular co-contractions or dual muscular pulls.  Each muscle pulls one bone in one direction and we have multiple muscles which can pull on one bone each in their own directions.  When you activate two muscles at the same time you pull the bone in two directions simultaneously and that strains one of the tendons connected to the bone and muscle.  It is a tug of war and one of them will lose.  This is the major cause of median nerve entrapment (carpal tunnel syndrome) because we strain our long flexor tendons which run through the carpal tunnel and the strain results in inflamed tendons which then press on the median nerve.  The cure isn't drugs, splints, rest, more practice, injections or surgery, it is learning to move properly so the inflammation can go down.  It can never go down if one continues doing what is wrong, no matter how much rest, drugs or surgery you have.
Here is a simple example.  With all 5 fingers together, slowly wave bye bye.  It should be effortless because all 5 fingers are moving in the same direction at the same time.  Some call this "tapping."  Now abduct your fingers (spread them out) and wave bye bye.  Feel the strain?  It is because you are using both your flexors/extensors and abductors at the same time. Hold all 5 fingers extended and wave bye bye with just one finger:  Strain?   Those pulls not only damage our tendons but they also hinder technique because  you are trying to play in one direction and another muscle is pulling you into an opposite direction resulting in mistakes, uneven playing, tension or bad tone.
Find a better teacher. Your current one might be wonderful but what they don't know can hurt you or, sentence you to a career of mediocrity.
Comment: This is so inaccurate on so many counts. -1.
Comment: Regarding "if you live in the city where the speed limit is 30 mph, why own a sports car that can go 130?": I'd rather own the sports car just in case I ever need to go on the highway (say my family wants to go to the neighbouring city).


How do I find the selenium element's invisibility, if its already assigned to a variable

Question: First I have a code that finds the element :
    @property
    def tools_button(self):
        driver: WebDriver = current().context.driver
        return driver.find_element(
            SelectBy.XPATH, f"//button[contains(text(),'Tools')]"
        )
--------------------------------------------------------------------
       tools_button = locators.tools_button

this tools button is in a modal that disappears after I click the Close Button.
My question is, how do i find element's invisibility similar to what this code does:
wait.until(
            ui.EC.invisibility_of_element_located(
                (SelectBy.XPATH, "//button[contains(text(),'Tools')]")
            )
        )

I need to check if the modal was closed or not, by checking the invisibility of the Tools Button in that modal.
But I need to find the Tools Button without having to pass the xpath and "by" again. is there a way to extract those two attributes from the already found element? or is there some special way to provide the invisibility_of_element_located function whole element.
Answer: You can use the invisibility_of expected condition along with the WebElement directly, without passing the locator again. Here's how you can achieve it
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

# Assuming `tools_button` is the WebElement you've already found
tools_button = locators.tools_button

# Wait for the element to become invisible
wait = WebDriverWait(driver, timeout)
wait.until(EC.invisibility_of(tools_button))

Comment: there is no such function in the selenium


AWS SQS / Lambda -> Process Data 1 Record At a Time with Delay Between Message Sent or Synchronously

Question: I am looking for a solution that does the following using SQS (or any other AWS service really):
Use Case Two: If I have X (1-10 messages per second) amount of messages being sent to an SQS queue from a lambda function. I would like to send messages 1-by-1 to another lambda function from the SQS Queue synchronously. For example, my lambda function sends messages to the SQS queue; it sends 1 message every 0.1 seconds. So 10 messages every second. I would like my SQS queue to send data 1 message at a time to my destination function for processing, and only send the next message when the previous message has finished processing. So in this case, message one is processed straight away, the second message sits in the queue till the first message is complete, once complete the second message get sent, so so and so on.
Use Case Two: If I have X (1-10 messages per second) amount of messages being sent to an SQS queue from a lambda function. I would like to send messages 1-by-1 to another lambda function from the SQS Queue with a delay between each message sent. For example, message one is sent to my destination, 3 seconds later message two gets sent, three seconds later message three gets sent, etc.  I choose 3 seconds here as that is the maximum time it takes for my destination process to run.
TL;DR I need a way to only send data from a queue one record at a time; with either a delay of 3 seconds between each message or until the previous message has finished processing.
What I have done so far?
I thought creating a FIFO queue with a 3-second delay would do the trick here?
<code>  GSSAREventQueue:
    Type: AWS::SQS::Queue
    Properties:
      ContentBasedDeduplication: false
      DeduplicationScope: messageGroup
      FifoThroughputLimit: perMessageGroupId
      DelaySeconds: 3
      FifoQueue: true
      ReceiveMessageWaitTimeSeconds: 3
      RedrivePolicy:
        deadLetterTargetArn: !GetAtt MyDeadLetterQueue.Arn
        maxReceiveCount: 10

  MyDeadLetterQueue:
    Type: AWS::SQS::Queue
    Properties:
      FifoQueue: true

</code>
But when I look in the logs of my lambda which the data is being sent to:
<code>2021-09-30T14:49:28.816+01:00   END RequestId: 5f9e784c-bba1-56f5-84e7-2183793ac607

2021-09-30T14:49:28.816+01:00   REPORT RequestId: 5f9e784c-bba1-56f5-84e7-2183793ac607 Duration: 217.39 ms Billed Duration: 218 ms Memory Size: 128 MB Max Memory Used: 101 MB XRAY TraceId: 1-6155c068-6565d6de237fd0170fb290d0 SegmentId: 11f9660438a56763 Sampled: true
</code>
2021-09-30T14:49:30.808+01:00   START RequestId: 7d98c954-47c6-5b7f-8665-909b855be17b Version: $LATEST
there is literally no delay. I made sure to send the data in batches of 1 on my Lambda
<code>      Events:
        UserEvent:
          Type: SQS
          Properties:
            BatchSize: 1
            Queue: !GetAtt GSSAREventQueue.Arn
</code>
I am likely doing something wrong here; is my use case possible?
What I thought could be happening:
SQS is sending data with a 3-second delay between each batch of messages? Maybe it's sending 10 messages at a time, and because I have set the  BatchSize: 1  on the lambda, it is sending data through 1 at a time?
--
The main reason for needing this is I am reading/writing data from the same record in the DynamoDB Table; and if the lambda gets 10 messages at the same time and 10 lambdas are processing separately, the numbers are going to be wrong.
Comment: So, Have a look at these documentation links. If you keep messages in the same MessageGroupID with Batch size,it should work. You could also do a reserved concurrency of 1 for the lambda. A simple test setup should be able to validate the results. https://docs.aws.amazon.com/lambda/latest/dg/with-sqs.html https://aws.amazon.com/blogs/compute/new-for-aws-lambda-sqs-fifo-as-an-event-source/ https://docs.aws.amazon.com/lambda/latest/operatorguide/reserved-concurrency.html
Comment: The age of the message may be impacting your delay setting. If the messages are older than 3 seconds, they are candidates to be sent to a consumer. It looks like this will be 1 lambda processing one at a time though. If you need the wait, I would add it to the lambda consumer. It will only get a new msg once execution completes successfully
Comment: Yeah, there may be like 20 messages in the queue in the last 3 seconds. I don't want to send all 20 at the same time though. I worry that now it's sending all 20 of them; and because my batch is 1, is it spinning up 10 instances of the lambda; 1 message at a time? Which defeats the point of what I am trying to do. If that makes sense?
Answer: You may use the reserved concurrency feature of lambda.
https://docs.aws.amazon.com/lambda/latest/dg/configuration-concurrency.html
You may set the value of reserved concurrency to 1 and batch size to 1 for the destination lambda. This will ensure that only one instance of destination lambda will run at a time and will pick up one message at a time from SQS.
Comment: Yup this is what I ended up doing :) Thanks @manish :)


Remove the smallest element(s) from a dictionary

Question: I have a function such that there is a dictionary as parameters, with the value associated to be an integer. I'm trying to remove the minimum element(s) and return a set of the remaining keys.
I am programming in python. I cant seem to remove key value pairs with the same key or values. My code does not work for the 2nd and 3rd example
This is how it would work:
remaining({A: 1, B: 2, C: 2})
{B, C}

remaining({B: 2, C : 2})
{}
remaining({A: 1, B: 1, C: 1, D: 4})
{D}

This is what I have:
def remaining(d : {str:int}) -> {str}:
    Remaining = set(d)
    Remaining.remove(min(d, key=d.get))
    return Remaining

Comment: You forgot the relevant tag for programming language. Also you forgot to mention what is your  problem, do you get an error ? where are you stuck ?
Comment: Python! I am stuck on removing key value pairs where the values are the same. Examples 2 and 3 in the description are where I am having trouble
Answer: One approach is to take the minimum value, then build a list of keys that are equal to it and utilise dict.viewkeys() which has set-like behaviour and remove the keys matching the minimum value from it.
d = {'A': 1, 'B': 1, 'C': 1, 'D': 4}

# Use .values() and .keys() and .items() for Python 3.x
min_val = min(d.itervalues())
remaining = d.viewkeys() - (k for k, v in d.iteritems() if v == min_val)
# set(['D'])

On a side note, I find it odd that {B: 2, C : 2} should be {} as there's not actually anything greater for those to be the minimum as it were.
Comment: [Pretty sure it's 3 from the annotation syntax.]
Comment: @DSM I kind of glossed over that bit... not sure `{str:int}` looks quite right... but never really had a reason to both with annotations as of yet (If I need it, the docs are there...)
Answer: That's because you're trying to map values to keys and map allows different keys to have the same values but not the other way! you should implement a map "reversal" as described here, remove the minimum key, and then reverse the map back to its original form.
from collections import defaultdict

# your example
l = {'A': 1, 'B': 1, 'C': 1, 'D': 4}

# reverse the dict
d1 = {}
for k, v in l.iteritems():
    d1[v] = d1.get(v, []) + [k]

# remove the min element
del d1[min(d1, key=d1.get)]

#recover the rest to the original dict minus the min
res = {}
for k, v in d1.iteritems():
    for e in v:
        res[e] = k

print res

Comment:
@Jon Clements's solution is more elegant and should be accepted as the answer
Answer: This removes all the items with the minimum value.
import copy

def remaining(dic):
    minimum = min([i for i in dic.values()])
    for k, v in copy.copy(dic.items()):
        if v == minimum: dic.pop(k)

    return set(dic.keys())

Comment: It works in Python 2 because `dict.items()` is a list, but it raises an exception in Python 3 because `dict.items()` is a iterator (is like `dict.iteritems()` in Python 2).
Comment: OP wants a set() with all the keys but the ones whose value is the minimum.
Comment: You can't change the size of dict while you iterate it. `dict.pop()` inside that `for` raises `RuntimeError: dictionary changed size during iteration`
Comment: Yes you can, it's just not suggested. I'll make a copy anyway.
Answer: Take the minimum value and construct a set with all the keys which are not associated to that value:
def remaining(d):
    m = min(d.values())
    return {k for k,v in d.items() if v != m}

If you don't like set comprehensions that's the same as:
def remaining(d):
    m = min(d.values())
    s = set()
    for k,v in d.items():
        if v != m:
            s.add(k)
    return s

Answer: An easier way would be to use pd.Series.idxmin() or pd.Series.min(). These functions allow you to find the index of the minimum value or the minimum value in a series, plus pandas allows you to create a named index.
import pandas as pd
import numpy as np
A = pd.Series(np.full(shape=5,fill_value=0))#create series of 0
A = A.reindex(['a','b','c','d','e'])#set index, similar to dictionary names
A['a'] = 2
print(A.max())
#output 2.0
print(A.idxmax())#you can also pop by index without changing other indices
#output a


How to concatenate constant string with jsonpath

Question: I have AWS step machine and one of the step is used to notify failure using SNS service. I want to select some metadata from input json into outgoing message. So i am trying to concatenate constant string with jsonpath like below
"Notify Failure": {
      "Type": "Task",
      "Resource": "arn:aws:states:::sns:publish",
      "Parameters": {
        "Message.$": "A job submitted through Step Functions failed for document id $.document_id",
        "Subject":"Job failed",
        "TopicArn": "arn:aws:sns:us-west-2:xxxxxxx:xxxxxxxx"
      },
      "End": true
    }

where document_id is one of the property in input json
However when i try save state machine defination i get error

There is a problem with your ASL definition, please review it and try
  again The value for the field 'Message.$' must be a valid JSONPath
Answer: I was able to solve a similar issue using:
"Message.$": "States.Format('A job submitted through Step Functions failed for document id {}', $.document_id)",

Described in a AWS News Blog post.
Comment: Amazing, been looking for this for days, thank you! Docs here https://docs.aws.amazon.com/step-functions/latest/dg/amazon-states-language-intrinsic-functions.html
Answer: I know that this thread is quite old, but I think it might be useful for some people.
It IS actually possible to concatenate strings or JSONPaths in AWS Step Functions thanks to the function States.Format.
The principle is the same as the string format method in Python.
Example with strings
"States.Format('{}<separator_1>{}<separator_2>{}', 'foo', 'bar', 'baz')"

will give you
'foo<separator_1>bar<separator_2>baz'

Example with JSONPaths
"States.Format('{}<separator>{}', $.param_1, $.param_2)"

will give you
'<value of param_1><separator><value of param_2>'

NB: You can also combine strings with JSONPaths.
Hope it helps!
Comment: Adding clarification. The occurrences of {} indicate where parameters should be placed. "separator" is not really a separator -- it can be any desired text, or nothing at all if parameters should appear with no separation. So as example, where $.inputparam = "inpath": "States.Format('I want {} to go here, and {} goes there. I also want input parameter to be {}{}', 'param 1', 'param 2', 'right here: ', $.inputparam" will result in the output "I want param 1 to go here, and param 2 goes there. I also want input parameter to be right here: inpath".
Answer: The JSONPath implementation referenced from the AWS Step Functions documentation supports String concatenation via $.concat($..prop) but sadly this does not work when deployed to AWS, suggesting that AWS uses a different implementation.
Therefore there is no way to do string concatenation with JSONPath in AWS.
Answer: As the message suggest you need to provide a valid JSONPath.
"Message.$": "$.document_id"
You cannot use any string interpolation as it invalidates the JSONPath format. You will need to construct the message in the preceding state.
Comment: Even in the preceding state how would you do that if I cannot cancatinate. And creating lambda just for concatenation is too much
Comment: the state that set $.document_id needs to set full string.
Comment: also when there is an exception in preceding state, it passes the error to `Notify Failure` state, The error would not have `$document_id`
Comment: Perhaps do a try/catch in your preceding state and then construct some sort of json output like `{ "error_message": "Failed for document id {document_id}" }`. This becomes part of your `ResultPath` that you can pass through to the next state.
Answer: We can do this with the AWS CDK like this:
import {
  aws_stepfunctions as sfn,
  aws_stepfunctions_tasks as tasks,
} from "aws-cdk-lib";

sfn.JsonPath.format(
            "s3://{}/{}",
            sfn.JsonPath.stringAt("$.detail.bucket.name"),
            sfn.JsonPath.stringAt("$.detail.object.key"),
          )


Package Managers and Custom Installs?

Question: Is it possible to use custom installs in conjunction with the package manager?
For example, I would like to use apt-get to install EngineX because it will also install all the applicable dependencies.
However, I prefer to use version 0.8.34 which I then configure to include modules that EngineX does not come with by default.
Is there some way for me to get the best of both worlds?
edit: the main goal for me is to find a way to keep all the dependencies updated
Answer: You can have a look at checkinstall, which allows to automate the package creation from a fresh compiled application, it can create both .deb and .rpm packages, to use it, just install it and replace the traditional "make install" by "checkinstall". In your case, since you still have installed your app from the repositories, just uninstall the package first (but keep the installed dependencies).
If it doesn't work with your application (this can happen sometimes), you'll have to make your package by yourself, there are many tutorials about this over the web. You can look here for .deb creation, and here for .rpm creation.
I hope this will help.
Comment: to properly handle dependencies (i.e. being able to redistribute packages) you have to build your packages yourself, the tutorials i gave should explain how to configure dependencies while creating packages. checkinstall makes life easy when installing from sources, but it doesn't allow dependecies tracking (or i missed that)
Comment: Right now I do all of my installs from source, none from packages. If I created packages from my own installs, how would I be able to keep the dependencies updated?
Answer: What you're doing is not a good practice.  Eventually it will cause you headaches it will definitely cause migraines for anyone who takes over managing these machines if you're no longer there.
You're much better off finding a repository that has the version of the package you're looking for.  As that will track dependencies, allow for easier uninstallation, and allow visibility of what's installed to the package manager.  Google should help you find a repository.  The other option is to learn to build your own packages.
Answer: As others have said, you should start by looking for packages of the version you need, and, failing that building your own packages.
However, there's no reason you can't install the dependencies from apt (or yum), just look for the dependencies (apt-cache show nginx or apt-cache showsrc nginx) and install them.

Package Managers and Custom Installs?


How to colour a CUBE ?!

Question: As I remember, this question was asked by my Mathematics teacher to the whole class and we discussed this question "only" in a whole lecture.
A cube, $6$ non distinguishable faces, is given. All we need to tell is the number of ways in which its faces can be coloured with $6$ different colours.
$1$. faces are to be coloured... and not edges !!
$2$. A face must be coloured with exactly one colour.
$3$. All six colours are to be used, say Blue, Green, Red, Yellow, Orange and White. as in the Rubik's cube.
Comment: @AbcDexter The Fibonacci numbers have application to pineapples. A question about Fibonacci numbers will not be tagged pineapples. The tags indicate essential subject matter, not the incidental. It lets answerers know the required expertise.
Comment: This doesn't seem to have anything to do with probability.
Comment: Does rotating the cube in space count as a "different" coloring?
Comment: Yes, just tell the number of different colourings...
Comment: If one configuration can be rotated to obtain another, are they distinct or no (I assume no, but want to make sure)? Must all six colors be used?
Comment: Please read the question again...
Comment: @AbcDexter: WHAT does it have to do with probability? Try "nothing" instead of "everything".
Comment: @AbcDexter Your edited post says the faces are not distinguishable. What do you mean by that?
Comment: @AbcDexter, if you wanted people to help you and answer your question, it would help if you would answer their clarifications. (Also, if you would accept their criticism of your tag choice, because this is combinatorics, not probability)
Comment: Ok, "nothing" instead of "everything"...
Comment: @Henning thanks for the answer...
Comment: This question has nothing to do with probability and has a simple solution with combinatorics...see my answer for that
Comment: @hawk , Henning already gave the correct solution. Thanks.
Comment: @AbcDexter I know he gave a solution and a damn good one at that...but it doesn't hurt to provide another solution...afterall that is what this community is about
Comment: Ok, what's your approach ?!
Answer: One approach: First imagine that the cube is fixed in space and cannot rotate. Then there are clearly $6!$ ways to distribute colors on the faces. But once we allow the cube to rotate, we find that we have counted each combination many times, namely one for each way the cube can be oriented in space. Each color combination has $6\cdot 4$ possible orientations, namely 6 directions the black face can point in, times 4 ways to then rotate the cube around the axis that passes through the center of that face. So the number of combinations is
$$ \frac{6!}{4\cdot 6} = 5\times 3\times 2 = 30 $$

As another approach, we can divide into two cases: Either the black and the white face are neighbors, or they are opposite each other. If they are neighbors, we can choose to orient the cube with the black face up and the white face towards us, which completely specifies its orientation. Then the remaining 4 colors can be distributed in $4!$ ways.
If the black and white face are opposite, then orient the cube with the black face up, white face down and red face towards us. Then there remaining 3 colors can be distributed in $3!$ ways. So the number of combinations is
$$ 4! + 3! = 24 + 6 = 30 $$
Comment: And the answer is correct ^_^
Comment: I still don't know, how my teacher convinced me that the solution is exactly 1.
Answer: Call the six colors $1, 2, 3, 4, 5, 6.$ Put the cube on the table so that face $1$ is at the
bottom. Consider face $2.$ If it is at the top then we can rotate the cube about a vertical
axis so that face 3 is in front. Now the cube is fixed. There are $3!=6$ ways to
complete the coloring. Now, suppose that face $2$ is a neighbor of $1.$ The we rotate the
cube so that $2$ is in front. Now the cube is fixed, and the coloring can be completed
in $4!=24$ ways. Altogether, there are $6+24=30$ distinct colorings of the cube by
six colors.
Answer: There are $6!$ ways to color a cube, but we get many overcountings, and we want distinct colourings, so there are $24$ ways in which we can orient a cube. So, $\dfrac{6!}{24}=30$ ways of coloring the cube distinctly.
Comment: I understand the spatial arrangement. correct ...

How to colour a CUBE ?!


Android Listview : Center items in layout when fewer items

Question: I have a listview that can have items from 1 to 100, dynamically varying.
However, when I have fewer items, I want the items to appear vertically centered in
the listview layout.  By default, Android draws the items form the top. I have attached a picture to illustrate what I need.
Is there any way I can achieve this, either by code or in XML layout ?
Thanks.

Edit: Based on the answers I have received now, I am adding more clarity to my question as the answers are off mark.
The positioning of the Listview in the main layout or positioning of individual item layouts is not an ISSUE here.  The listview is positioned properly as shown in the shaded background.  The question to which I need answer is:

Assume there are 10 items, the entire shared area of Listview will be used by items,
possibly Items 1 to 5 are shown.
Assume there are 3 items only.  The listview is still shown but Items 1,2 and 3 are rendered at the top of the listview (shaded area).  However, in this case, I want the items to be drawn at centre of the listview's layout (as shown in the picture).

Anyway this can be done ?
Comment: Did you try "android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"....I think you might have already tried but still checking. And try with wrap_content for both width and height. This might work, please check.
Comment: share your `layout file`.
Comment: Try wrap your items inside linear layout that is set to wrap content and is centered inside single view of list view if thats what you want, otherwise im missing the point :P
Comment: @user3455363 if you keep up with your habit of not marking answers as answers, soon people will stop help you.
Comment: @Sufian : None of the answers worked for me.  Hence, have not marked them, not because I dont care.
Comment: It doesn't hurt to comment/respond to a proposed answer. Look around and you'll see many SO threads where questioner got his desired solution only after communicating with the answerer.
Answer: Use this property
<code>    mLoginUserNameValueView.setGravity(Gravity.CENTER_HORIZONTAL);
</code>
which one you want to center in the List view adapter and which position exactly where you need
e-x  you need your 55th position you want center the item means
     in getview you will use this line like below.
<code>@Override
    public View getView(int position, View convertView, ViewGroup parent) {
        convertView = null;
        if (convertView == null) {
            convertView = mLayoutInflater.inflate(R.layout.navigationlayout,
                    null);
            mHolder.mLayout = (LinearLayout) convertView
                    .findViewById(R.id.navigationLayout);
            mHolder.mNavigationtext = (TextView) convertView
                    .findViewById(R.id.navigationText);
            convertView.setTag(mHolder);
        }
        if (\\Your desired position checking )
            \\ and set the above line here
        }
        return convertView;
    }
</code>


Background Image wont display with HTML/CSS

Question: I'm trying to add an image to my "welcome" ID but the image wont display.
Here is my CSS and HTML:

body {
  margin: 0;
  width: 100%;
  height: 100%;
  font-family: Helvetica;
}
.header {
  width: 100%;
  height: 35px;
  background-color: rgba(0, 0, 0, 0.3);
}
#welcome {
  background-image: url(../images/Welcome.jpg);
  width: 100%;
  height: 100%;
}
<!DOCTYPE html>

  <title>Template</title>
  <link rel="stylesheet" href="design.css">
  <link rel="stylesheet" type="text/css" href="simplegrid.css">
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Logo

        About
        What we do
        Who we are
        Our Work
         Contact Us

I've tried both single and double quotes inside the url box. I have also added the image to the body using  tags and it displayed that way, but for some reason it wont display through the style sheet. I have also tried embedded and inline css, neither has worked.
Any help would be appreciated.
Comment: try adding some content on the section mate
Comment: Have you made sure the url is correct? The tag has nothing in it also...
Comment: You need to add some content. Also make sure the path to the image is correct.
Answer: The section will just take a 0px width and height since it doesnt have any content. Either add come content, which will then force it to expand to its height, or gives fixed heights, like below. That should ideally work.

body {
  margin: 0;
  width: 100%;
  height: 100%;
  font-family: Helvetica;
}
.header {
  width: 100%;
  height: 35px;
  background-color: rgba(0, 0, 0, 0.3);
}
#welcome {
  background-image: url(data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxITEhUTExMWFhUXFxUVGBgYGBcYFxgYGBUXFxgWFhcYHSggGBolHRUYITEiJSkrLi4uGh8zODMtNygtLisBCgoKDg0OGhAQGi8lHx0tLS0tLS0tLS0tLS0tLS0tLSstLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLf/AABEIAHsBmgMBIgACEQEDEQH/xAAcAAACAwEBAQEAAAAAAAAAAAADBAECBQAGBwj/xAA5EAABAwIEAwYEBQMEAwAAAAABAAIRAyEEEjFBUWFxBSKBkaHwBhOx0TJCUsHhByPxFDNichUWkv/EABkBAAMBAQEAAAAAAAAAAAAAAAABAgMEBf/EACMRAAICAgMAAwADAQAAAAAAAAABAhEDIRIxQQQTUSIyYRT/2gAMAwEAAhEDEQA/APlbQrQqgqZldxkSrAqoRA1NCZLUXLZUa1FDh4qkQwc7I4pGAfNCY26eaw2VITYGm0TcFXIF4bHXoj5ANb9PopDZA+nVBFnYZ0eqaLTlaRpHjxVMMIMH3um6RmIgTt76JMlgaUzEbogce9fTgiBgAcTrcwlqZOvFHYhrDMLrg8k2ymePvmlcLWhw6iT0K0zoTbQ+Nys5IkVpVHabjX0081q4LEGSQeH0WOIzCPdp1Wlgom1pM+iUkqA1nYx5i8x5A9dvorYaj8wENs4GQZ1AmR9EtVp2Ph9UHs+u5r9NOPNY8FX8SlLez1NDE1AyQ/vWHGRHo4aLUw1a8kXgnLxIix58PFef7NqgjK7X8NpEjaR4a9OC0aVW7gbg6e+UlcmSH+HVjmbHadYEB0GABpoGGLx1+iHSxQkRABiBtmG3Q+9EmKmak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jvEA9LXB5lFLO8HMGUczPOSTYnwSz3lgJbYpht3GdhZAhsvD3Z6gLi60jK28AAi2kDhdWZWeWxmdBuReHETFt9Vn/6hw0PA7KBiH/qPHVaxikQ3Zu0szmPaRznYxeORgeiDTwVSD3Sedo0WQKzr94+ZUmu+IzGOpV0RxNXC4VzmTw5pij2bUgknLvf662KwGuKkEo4hxPQMwkjNnGwnMNTylP4DD0y2S6HcWP5fmE+4XkQVYFDiLiehrQHNIdTtzAFjeRrMdUejiaHzDmqmL3AJ3iBvePILzIVpT4i4m9isZhQRkzu2NsoPW+qD/5WkIilJHF3TgFjFcUcUPiekZ8UZW5WYekDxILvQpGp27WIIDsoOzQGj0CyVKFCK8FQ47H1TrUffXvFAlUUqgouXJnAYCrWdlpU3PPIWHU6DxTfwnhGVcVTp1G5mmZF7w0nbovs2GwzKbctNrWN4NAA9Flky8dEN0eD7G/p0TldiakDU02a6aF2xmNF7XsvsXDYcf2qTWmILolxEzdxuU5KrK5pTlLtk2MGoqmogEqCVFBYU1FU1EIlDcUUKwpqJfFY1lNpc9wa0akmFDivkPxxi3uxbw5xIbLWjYDkqURwjydGx8V/F3zyKVEvbTBcHmw+ZoBEScuvWV5KoDuYOsTPmlC4397oc2lbaSOpQS0g1Qi8nhwJ8/BDDrdTufJAB3TTxZCLqizhAgx4IIeNOd9ugVaIkwVRuqLCi739FTZQ/VVKCkiQVVyrN1zhBQM4lVUlc5ICFSFaFVIZ/9k=);
  width: 400px;
  height: 100px;
}
<!DOCTYPE html>

  <title>Template</title>
  <link rel="stylesheet" href="design.css">
  <link rel="stylesheet" type="text/css" href="simplegrid.css">
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Logo

        About
        What we do
        Who we are
        Our Work
         Contact Us

Answer: The reason it won't display is because you applied height: 100% to #welcome, however, the browser doesn't actually know what that size is because percentage values are relative to the immediate parent. In this case the immediate parent is the body tag which you've also set to height: 100%, but yet again the browser can't calculate that either. This time it's because you have not defined the height of the body tag's parent, which is the html tag. So because the html tag's height is undefined and it is the parent of the body tag, the browser has no reference value to calculate 100% height from. So both the body tag and #welcome's heights are 0.
You can set your CSS like so.
html {
  min-height: 100%; // this will reference the viewport but could become bigger than viewport depending on your content
}
body {
  height: 100%;
}
#welcome {
  height: 100%;
}

Another option would be to set #welcome to be 100% of the viewport like so:
#welcome {
  height: 100vh;
}

Hope this helps.


Mapping URLs with different port in Apache

Question: I have a URL:
http://ip:9200/_plugin/head/

I want to open that URL when I visit:
http://ip/es-head

How do I do that in Apache?
Answer: You need to use mod_proxy. Apache configuration would look like this:
ProxyPass /es-head/ http://ip:9200/_plugin/head/
ProxyPassReverse /es-head/ http://ip:9200/_plugin/head/

Apache manual has some examples.


Minishift MySQL service not showing actual database

Question: Using Springboot 2.2.4 and a local distribution of Openshift (Minishift, Kubernetes Master 1.11, Openshift Web Console 3.11).
The app itself is just a spring-boot-starter-data-rest CRUD for a simple Employee entity configured in a pod within Openshift. The data source is a MySQL service in another container.
On deployment some data is loaded in the employee table. Just 4 employees for testing purposes.
DROP TABLE IF EXISTS employee;

CREATE TABLE employee (
  id int(11) NOT NULL AUTO_INCREMENT,
  first_name varchar(45) DEFAULT NULL,
  last_name varchar(45) DEFAULT NULL,
  email varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id`)
);

--
-- Data for table `employee`
--

INSERT INTO employee VALUES
(1,'Leslie','Andrews','firstname.lastname@example.com'),
(2,'Emma','Baumgarten','firstname.lastname@example.com'),
(3,'Avani','Gupta','email@example.com'),
(4,'Yuri','Petrov','firstname.lastname@example.com');

Everything works perfect. All of the endpoints are well published and all works perfectly.
But just out for curiosity, I am trying to connect some mysql viewer to check the data that it is loaded on startup and changed later on API usage. But I can't find the table anywhere. I am trying two ways:

Entering the mysql container and going through command line (mysql command). I connect to the database, but it is empty (no tables).
Configuring a third pod with a phpMysqlAdmin instance, which apparently connects too to the database perfectly but, again, showing no tables or data (other than information_schema).

configmap.yml
apiVersion: v1
kind: ConfigMap
metadata:
  name: spring-boot-bootstrap
data:
  application.properties: |-
    spring.datasource.url=jdbc:mysql://mydatabase:3306/mydatabase

fabric8\deployment.yml
spec:
  template:
    spec:
      containers:
      - env:
        - name: SPRING_PROFILES_ACTIVE
          value: mysql
        - name: SPRING_DATASOURCE_USER
          valueFrom:
            secretKeyRef:
              name: mydatabase
              key: database-user
        - name: SPRING_DATASOURCE_PASSWORD
          valueFrom:
            secretKeyRef:
              name: mydatabase
              key: database-password
        livenessProbe:
          httpGet:
            path: /actuator/health
            port: 8080
            scheme: HTTP
          initialDelaySeconds: 180
        readinessProbe:
          httpGet:
            path: /actuator/health
            port: 8080
            scheme: HTTP
          initialDelaySeconds: 30

Any idea?
Comment: You can't easily run databases in a container. Imagine there are 3 instances of your DB in your cluster, A, B, and C (each on a different node). Now, imagine that your load-balancer chooses instance-A to run your SQL initialisation against, and by luck, your app is routed to the same container. Now, when you bring up your viewer (or 2nd consumer container) the load-balancer connects you to a different instance on a different node, say instance-B. You can search as hard as you like in instance B, but you'll not find tables that only exist in instance-A.
Answer: Postgres have the same behaver.
Entering the Postgres container and going through command line (Postgres command). I connect to the database, but it is empty (no tables).
I use minishift.
jdbc:postgresql://localhost:25432/pstgrs1 work in client. I used spring app, it works, but table is empty.
Example
DROP TABLE IF EXISTS cities;
CREATE TABLE cities(id serial PRIMARY KEY, name VARCHAR(255), population integer);


marginal conditional from joint of three r.v.'s

Question: I have two random variables, $X$ and $Y$. I know that $X \sim \text{Gamma}(a,b)$ and $Y \sim \text{Gamma}(c,d)$. Furthermore, I know that $Z \sim \text{Poisson}(XY)$.
I know the joint distribution factorises as $P(X,Y,Z) = P(Z|XY)P(X|a,b) P(Y|c,d)$.
I would like to find the mean of the marginal distribution of $X$ given that $Z$ is known. I am not sure whether or not this is possible because of the way $X$ and $Y$ are coupled together in the Poisson mean. Ideally I would just like a yes/no as to whether I am wasting my time!
The marginal $P(X)$ is itself not that hard to find after I rewrite all the Y terms into a new Gamma distribution. The problem is when I try to calculate $E[X] = \int x P(X=x)$, there is no easy way to write it into an exponential family form due to a term that appears from the marginalisation of $Y$. This makes me think the calculation is not possible....
Comment: When you write $X \sim \text{Gamma}(a,b)$, you have already told us what $P(X)$ is. Why do you need to find "the marginal $P(X)$" all over again? Isn't it just the $\text{Gamma}(a,b)$ distribution? or is $X \sim \text{Gamma}(a,b)$ a conditional distribution of $X$, including, as a special case if you are a frequentist, conditional on unknown parameters $a$ and $b$?
Answer: Since the joint distribution of $(X,Y,Z)$ writes like
$$p(x,y,z)\propto x^{a-1}\exp\{-bx\}\,y^{c-1}\exp\{-dy\}\,(xy)^z\exp\{-xy\}/z!$$
the conditional of $(X,Y)$ given $Z=z$ is
$$p(x,y|z)\propto x^{a-1}\exp\{-bx\}\,y^{c-1}\exp\{-dy\}\,(xy)^z\exp\{-xy\}$$
and the marginal conditional of $X$ given $Z=z$ is
\begin{align}p(x,y|z)&\propto \int_0^\infty x^{a-1}\exp\{-bx\}\,y^{c-1}\exp\{-dy\}\,(xy)^z\exp\{-xy\}\,\text{d}y\\
&\propto x^{z+a-1}\exp\{-bx\}\,\int_0^\infty y^{c-1}\exp\{-dy-xy\}\,y^z\,\text{d}y\\
&\propto x^{z+a-1}\exp\{-bx\}\,(d+x)^{-c-z}\end{align}
The conditional mean of $X$ given $Z=z$ is thus
$$\mathbb E[X|Z=z] = \dfrac{\int_0^\infty  x^{z+a}\exp\{-bx\}\,(d+x)^{-c-z}\,\text{d}x}{\int_0^\infty x^{z+a-1}\exp\{-bx\}\,(d+x)^{-c-z}\,\text{d}x}$$
I do not know if there exist nice representations of this ratio of integrals. My copy of Gradsteyn & Ryzhik is at the office but, checking it online, it sounds like 3.353 (p.341) is the closest and not particularly helpful identity.


Pat Martino chord concept - Augmented Forms - Guitar Fretboard shapes

Question: Imagine a A+ chord that Pat transfers to a Dm chord by raising the note c# to d. Pat seems to relate a A+ chord to a D-minor chord.
What´s the improvisational use of that approach as A+ is not "really" Dm at all? I know that PM is deep, but I don´t get this one.
Comment: Unclear what you're asking.  I'm voting to close.
Comment: I'd have to agree.  It is not at all clear what you are asking.  Pat has his own unique view of music theory, based on the diminished form.  You need to provide some more background, and specific example.
Comment: I think it's clear enough what is being asked. "_What´s the improvisational use of that approach as A+ is not "really" Dm at all?_" In what situation and how does Pat Martino look at something as either an A augmented and/or Dm, and how can this be used to perform something sensible in improvisation. It's a good question.
Comment: Ok, the original unedited question was a bit cryptic. But now it makes sense and is a valid question. It's about a misconception that the augmented triads are supposed to be played, when actually they're only a tool for looking at chord shapes on the fretboard.
Answer: According to this summary: https://andrewdiruzza.blogspot.com/2011/02/pat-martino.html
... the augmented triads are used as a "practical aid in visualizing twelve diatonic keys on the guitar in a horizontally smaller area on the instrument." You're not supposed to play the A augmented (if you don't happen to want an augmented chord). You're supposed to see the shape on the fretboard, and the minor triad as a modification to the augmented shape. This helps you locate and create chord voicings in different positions on the fretboard. You don't have to know all possible major and minor voicings as such - if you can see the augmented shapes, you can create major and minor chords from them.
Compare this with the black and white key arrangement on the piano - all keyboard players use the black and white keys as a visualization and location aid without even thinking about it, because it's built into the instrument and it cannot be removed. If the piano keys were all the same color and if they were only side by side chromatically without separation to a C major scale and "sharp/flat keys", ... and if it wasn't linear but the same pitch in many different places, then you would have to invent some kind of a system to find your way around the keys and to be able to operate. Like what you have to do if you're a guitar player. :) As far as I understand, with Pat Martino's method you build a (supposedly) more guitar-friendly visualization aid into your mind, by training yourself to see minor and major chords as modifications of augmented triads.
For example, here are two ways to obtain the Dm chord from an A augmented triad. The augmented triad is marked with black dots. I guess Pat Martino sees dot patterns like this on the guitar fretboard.

Will this system of looking at chords and the fretboard help you? Maybe, but it will take practice. According to a post on the Yahoo Jazz Guitar Group (YJGG) discussion thread archived by Google, it takes years to really master this skill
https://groups.google.com/forum/#!msg/jazz_guitar/pKUG2P_HPAs/OMfOaNUNsI4J
Comment: Thx!! I can understand the point of a vehicle with the symmetric properties of a aug triad for navigation conrol on the fretboard and doing small changes for several application opportunities, to memorize all chord forms would be much more effort without this ancor so to speak.  We can create certain forms better out of a overall symmetry. I guess it is the same idea behind the convert to minor concept that pat uses. Learn to play and automate a set of minor positions and substitute these mechanics to all possible chordal situations.
Comment: Thx for the nice links also!!!


setOnItemClickListener within Custom Adapter

Question: This is the error I receive:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setOnItemClickListener(android.widget.AdapterView$OnItemClickListener)' on a null object reference

Why can't I do something like this? I've pasted the View class that exists within my custom Adapter class:
@Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder;

        if (convertView == null) {
            convertView = LayoutInflater.from(mContext).inflate(R.layout.notifications_listview_item, null);
            holder = new ViewHolder();
            holder.username = (TextView)convertView.findViewById(R.id.username);
            holder.notificationText = (TextView)convertView.findViewById(R.id.notificationText);
            holder.time = (TextView)convertView.findViewById(R.id.time);
            holder.profilePicture = (ImageView) (convertView.findViewById(R.id.profilePicture));
            holder.notificationsIcon = (ImageView) (convertView.findViewById(R.id.notificationsIcon));

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder)convertView.getTag();
        }

        final ParseObject notifications = mNotifications.get(position);

        Date createdAt = notifications.getCreatedAt();
        long now = new Date().getTime();
        String convertedDate = DateUtils.getRelativeTimeSpanString(createdAt.getTime(), now, DateUtils.SECOND_IN_MILLIS).toString();

        holder.username.setText(notifications.getString(ParseConstants.KEY_SENDER_NAME));
        holder.notificationText.setText(notifications.getString(ParseConstants.KEY_NOTIFICATION_TEXT));
        holder.time.setText(convertedDate);
        holder.profilePicture = (ImageView)convertView.findViewById(R.id.profilePicture);

        if (notifications.getString(ParseConstants.KEY_NOTIFICATION_TYPE).equals(ParseConstants.TYPE_LIKE)) {
            holder.notificationsIcon.setImageResource(R.drawable.ic_action_like_feed_full);
        }

        if (notifications.getString(ParseConstants.KEY_NOTIFICATION_TYPE).equals(ParseConstants.TYPE_CYCLE)) {
            holder.notificationsIcon.setImageResource(R.drawable.ic_not_saved);
        }

        if (notifications.getString(ParseConstants.KEY_NOTIFICATION_TYPE).equals(ParseConstants.TYPE_EDIT)) {
            holder.notificationsIcon.setImageResource(R.drawable.ic_action_edit_feed);
        }

        holder.username.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startGalleryActivity(notifications.getString(ParseConstants.KEY_SENDER_ID));
            }
        });

        holder.profilePicture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startGalleryActivity(notifications.getString(ParseConstants.KEY_SENDER_ID));
            }
        });

        holder.notificationsIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, FeedActivitySingle.class);
                intent.putExtra(FeedActivitySingle.EXTRA_DESIGN, notifications.getString(ParseConstants.KEY_SENDER_FEED_OBJECT_ID));
                mContext.startActivity(intent);
            }
        });

        ListView listView = (ListView)convertView.findViewById(android.R.id.list);

            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Intent intent = new Intent(mContext, FeedActivitySingle.class);
                    intent.putExtra(FeedActivitySingle.EXTRA_DESIGN, notifications.getString(ParseConstants.KEY_SENDER_FEED_OBJECT_ID));
                    mContext.startActivity(intent);
                }
            });

        return convertView;
    }

I want to set an onItemClickListener on one of the listView items in the Adapter. Why can't I do this? The error is thrown here where I've defined the listView:
ListView listView = (ListView)convertView.findViewById(android.R.id.list);

What should I do? All the regular ClickListeners work but I want the user to be able to select the listView item in the Adapter itself.
Edit (Answer):
Problem resolved! Just had to put my onItemClickListener in the onCreate method of the main activity where the custom Adapter was initialized.
    ListView listView = (ListView)findViewById(android.R.id.list);

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Toast.makeText(getApplicationContext(), "Voila! It works.", Toast.LENGTH_SHORT).show();
            List<ParseObject> notifications = adapter.getNotifications();
        }
    });

Answer: The findViewById method looks for children:

Look for a child view with the given id. If this view has the given id, return this view.

The ListView is a parent of the convertView so the findViewById is returning null.
Why not set the AdapterView.OnItemClickListener in the Activity or Fragment that you are creating the layout in?
Comment: I would but then I can't get the string attached to the notifications variable. Conceptually, your method works, but for my specific problem I need to adjust some things. Thanks!
Comment: The `onItemClick(AdapterView parent, View view, int position, long id)` gives you the position of the item clicked. Which in turn you can use in the `getItem` method of your adapter to retrieve the `Object` clicked.
Answer: The convertView variable is a row in the listView, because this the method findViewById.
convertView.findViewById()

Always return null.
if you want to do that u can do this.
convertView.setOnClicListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent=newIntent(mContext,FeedActivitySingle.class);
                intent.putExtra(FeedActivitySingle.EXTRA_DESIGN, notifications.getString(ParseConstants.KEY_SENDER_FEED_OBJECT_ID));
                mContext.startActivity(intent);
            }
        });


Generate The Auto Incrementig Number With Prefix Laravel

Question: I have table named as product.The product table Consistis of the productcode field
and while adding the product I need to generte the code as PRO-1,PRO-2,PRO-3 in the sequence for the product code field and its must be loaded in the form
Answer: i have Created the function in my product model and succefully done this
public static function generateSeriesNumberWithPrefix($tableName = '', $autogenField = '', $autogenStart = '', $autogenPrefix = '')
    {
        $listFiledValues = DB::table($tableName)->select($autogenField)->get();
        if ($listFiledValues->isEmpty())
        {
            $generatedAutogen = $autogenPrefix.$autogenStart;
            return $generatedAutogen;
        }
        elseif ($listFiledValues->isNotEmpty())
        {
            foreach($listFiledValues as $listFiledValue)
            {
                $eachListarray = $listFiledValue->$autogenField;
                $totalListArrays[] = $eachListarray;
            }
            foreach($totalListArrays as $totalListArray)
            {
                $stringRemovedEachListArray = substr($totalListArray,strlen($autogenPrefix));
                $stringRemovedTotalListArray[] = $stringRemovedEachListArray;
            }
            $maximumValue = max($stringRemovedTotalListArray);
            $generatedAutogen = $autogenPrefix.++$maximumValue;
            return $generatedAutogen;
        }
    }

And Finally in the create function
public function create ()
    {
    $autogen = Product::generateSeriesNumberWithPrefix('product','autogen','1','PRO-');
    return view('product.formadd', compact('result','sequence'));
    }

I am using the Laravel Form builder So that
{!! Form::text('productcode', $autogen, null, ['class' => 'form-group']) !!}

here generateSeriesNumberWithPrefix is a function name and Product is a Model Name
Main Advantage of this function is it does not depend upon other fields such as created_ator the Max value in the primary keyit is standalone function


Identificador inválido SQL - Oracle

Question: <code>CREATE TABLE IndustrialUnit (
UnitId NUMBER (7,2) PRIMARY KEY,
Location_place VARCHAR(50),
Country VARCHAR (50),
FOREIGN KEY (ProdId) REFERENCES Production(ProdId)
);
</code>
Quando tento definir a FOREIGN KEY surge o seguinte erro: ORA-00904: "PRODID": identificador inválido.
Answer: vc não criou a coluna ProdId nessa tabela (IndustrialUnit).
além disso essa coluna deve ser do mesmo tipo e não nula na tabela Production.
verifique.

Identificador inválido SQL - Oracle


NFL: Why do kick coverage teams always run all the way down the field

Question: I've noticed this frequently in the NFL. When there's a kickoff that is downed in the end zone for a touchback (or is out of the back of the endzone), the coverage team still runs all the way down the field. Sometimes the receiving team is already walking off the field as the referees take the ball to the 20 yard line and still the coverage team is running full speed and they don't stop until they reach the end zone. (At which point they have to turn around and run back to their bench). Is this a macho thing? Intimidation? Young players trying to show their dedication and hustle to the coaches?
Comment: it's just a common practice; compare it to when a baseball hitter's air ball is caught by an infielder or the pitcher while the batter is still half way running to the first base, in most cases the runner will run till he gets to the base and then he'll turn around and go back to the dugout.
Answer: From personal experience (high school and not the NFL), we were required to run through the goal line every time.
There are a couple of reasons I could see for them doing so:

If the kick does not go out of the end zone, the player may return it. There are plenty of players that will return a kick from 8 or 9 yards in the end zone if they see an opening. If the players slow down and the returner takes it out of the end zone it could be a big return.
Players are on a full sprint for 40+ yards sometimes and instead of breaking down, they choose to contine through the goal line to slow down at a decreased rate (possibly limiting a muscle pull injury).
Players on special teams are often the last players on the 53 man roster and do not want to give off an impression that they are slacking or taking it easy. Especially if they are on the team for only kicks and punts. It may have started at some point and players decided they wouldn't be the guy that didn't sprint down to the goal line.
Special teams coaches may require it.

I cannot say for certain the reason other than I am sure they have a good reason for it. Whether it is keeping their job or for strategic purposes.
Answer: I always coached my guys to run through the end zone at full speed for the following reasons:

Why not?  It is a free sprint that keeps them in shape for the next kickoff.
Most importantly... Intimidation.  I want the returner to see how hard my guys are working and decide to kneel when the ball goes 2 yards deep in the endzone.

Why do they do it?  Because I told them too and they won't be on kickoff if they don't (and possibly the team).
Comment: And I disagree with the comment on your answer comparing this to baseball.  Baseball is a series of non-related events.  Given that you have two pretty closely matched football teams it is the little things that add up.  Every action on the football field builds on the previous plays both mentally and physically.  I am not a Pats fan at all (cheaters) but Belichek somehow gets all 11 players playing 100% through the whistle better than any other coach...  No coincidence they win so much.
Answer: My biggest reason is to make it a habit. Even if the ball goes into the endzone it is a live ball and the offensive players must down the ball. Don't leave any room for "I thought he downed it" or "I thought I heard the whistle" just run to the ball always.
Comment: Also, in the NFL many of the players on the kickoff team are second string players, so they have something to prove.


$z^6+iz^3+i-1=0$

Question: I am trying to solve $z^6+iz^3+i-1=0$. I tried to factor/reduce the equation, but nothing seems to be helpful.
I don't necessarily need the solution to this. But, I want to know what is the right approach to reducing such equations? Where can I practice such problems?
Comment: I think you make progress if you apply sum of cubes and difference of squares formulae.
Answer: Hint : Letting $x = z^3$, your problem it convert in a quadratic equation
$$x^2 + ix + (-1+i) = 0$$
and the left hand side it can be factored as
$$(x-(1-i))(x+1)$$
Comment: I think recognizing the equation as a quadratic is the best way to go here.
Answer: Different approaches:

Look for solutions.

You might be able to spot $z=-1$ as a solution right away. Now we can make progress by factoring out (z+1).

Apply the formulas you know.

I would think that
$a^3+b^3=(a+b)(a^2-ab+b^2)$ and $a^2-b^2=(a+b)(a-b)$ would be particularly useful.

Use a tool

You can find the answer here
Your next question asks for practice problems. I would think that AOPS books on algebra and precalculus would do the trick. But any good textbook on Algebra 2/ precalculus content should have practice like this in it.
Answer: $$z^6-1+i(z^3+1)= (z^3+1)(z^3-1)+i(z^3+1)$$ $$=(z^3+1)(z^3-1+i)$$
Comment: And then one should factor the sum of cubes. $z^3+1=(z+1)(z^2-z+1)$

$z^6+iz^3+i-1=0$


Flex - Download asset to local

Question: I've got an interactive presentation, and it's all working as it should.
Now I want to add a function to download the currently visible image/video.
Because this presentation has a lot of files (all stored under assets/...) and it's a pain to navigate through the assets, I want an easy way to just click a button and get a "Save as.." window.
I've managed to get the url of the media, so now I just need a way to show a "save as.." dialog to allow the users to save/download the file and save it locally.
This whole presentation should be put online, so all the files are located somewhere in the /assets/.. folder inside the project.
Any ideas of how to do this? =)
Thanks!
EDIT #1:
For now I'm using "navigateToURL" to open a new browser window with the media. This works, but is there a way to show a "Save as.." dialog instead of opening the image?
Or any other ways to do this? =)
Answer: You are looking for the FileReference class, in particular the FileReference.save( data:*,defaultFileName:String = null ) method. That will open up a "Save..." dialog to save the corresponding data object and allow you to set a default file name. I'm unsure if this class can also handle the download as I have never had a time when I needed to prompt to save something that was to be downloaded. If it cannot handle it, you'll need to look into the URLStream class. That can handle the download and either on ProgressEvent.PROGRESS or Event.COMPLETE, you simply do a URLStream.readBytes( byteArray ); to save the downloaded bytes to a ByteArray and then that is the data object you save. I would look into the FileReference class, though. Odds are it can handle downloads as well.

Flex - Download asset to local


Autofocus routine detecting very small differences in blur

Question: I'm developing an autofocus routine for positioning on the micrometer scale, so I need to find very small differences in focus/blur between images. Luckily, the image pattern will always be the same (these are 256x256 center crops of the original 2 MP images):

         Perfect focus         |           50 µm off

Finding the better focused image of the two above is not a problem, I guess most algorithms will do. But I really need to compare images with a lot less difference in focus, like the ones below:

           5 µm off            |           10 µm off

An alternative to stepping closer and closer to optimal focus is to find two images that have the same amount of blur on opposite sides of the focus plane. For example, one could save an image from -50 µm and then try to find an image around +50 µm where the blur is equal. Lets say that the image was found at +58 µm, then the focus plane should be positioned at +4 µm.
Any ideas for a suitable algorithm?
Comment: What happens when you try basic algorithms? Is there too little signal-to-noise?
Comment: Well, I just assumed that a basic algorithm wouldn't detect any valid difference between the 0, 5 and 10 µm images. But I tried a few just now and actually got quite promising results. I will acquire more images just 1 µm apart and see if the results are still satifying.
Answer: Surprisingly, many quite simple autofocus algorithms actually performed quite well on this problem. I implemented 11 of the 16 algorithms outlined in the paper Dynamic evaluation of autofocusing for automated microscopic analysis of blood smear and pap smear by Liu, Wang & Sun. Since I had trouble finding recommendations for setting the threshold values, I also added some variants without thresholds. I also added a simple but clever suggestion found here on SO: compare the file size of the JPEG compressed images (larger size = more detail = better focus).
My autofocus routine does the following:

Save 21 images at an interval of 2 µm focus distance, total range ±20 µm.
Calculate the focus value of each image.
Fit the result to a second degree polynomial.
Find the position that gives a maximum value of the polynomial.

All algorithms except Histogram Range gave good results. Some of the algorithms are slightly modified, for example they use the brightness difference in both X & Y directions. I also had to change the sign of the StdevBasedCorrelation, Entropy, ThresholdedContent, ImagePower and ThresholdedImagePower algorithms to get a maximum instead of a minimum at the focus position. The algorithms expect a 24 bit grayscale image where R = G = B. If used on a color image, only the blue channel will be calculated (easily corrected of course).
The optimal threshold values was found by running the algorithms with threshold values 0, 8, 16, 24 etc up to 255 and selecting the best value for:

Stable focus position
Large negative x² coefficient resulting in a narrow peak at the focus position
Low residual sum of squares from the polynomial fit

It's interesting to note that the ThresholdedSquaredGradient and ThresholdedBrennerGradient algorithms have an almost flat line of focus position, x² coefficient and residual sum of squares. They are very insensitive to changes in the threshold value.
Implementation of algorithms:
public unsafe List<Result> CalculateFocusValues(string filename)
{
  using(Bitmap bmp = new Bitmap(filename))
  {
    int width  = bmp.Width;
    int height = bmp.Height;
    int bpp = Bitmap.GetPixelFormatSize(bmp.PixelFormat) / 8;
    BitmapData data = bmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, bmp.PixelFormat);

    long sum = 0, squaredSum = 0;
    int[] histogram = new int[256];

    const int absoluteGradientThreshold = 148;
    long absoluteGradientSum = 0;
    long thresholdedAbsoluteGradientSum = 0;

    const int squaredGradientThreshold = 64;
    long squaredGradientSum = 0;
    long thresholdedSquaredGradientSum = 0;

    const int brennerGradientThreshold = 184;
    long brennerGradientSum = 0;
    long thresholdedBrennerGradientSum = 0;

    long autocorrelationSum1 = 0;
    long autocorrelationSum2 = 0;

    const int contentThreshold = 35;
    long thresholdedContentSum = 0;

    const int pixelCountThreshold = 76;
    long thresholdedPixelCountSum = 0;

    const int imagePowerThreshold = 40;
    long imagePowerSum = 0;
    long thresholdedImagePowerSum = 0;

    for(int row = 0; row < height - 1; row++)
    {
      for(int col = 0; col < width - 1; col++)
      {
        int current = *((byte *) (data.Scan0 + (row + 0) * data.Stride + (col + 0) * bpp));
        int col1    = *((byte *) (data.Scan0 + (row + 0) * data.Stride + (col + 1) * bpp));
        int row1    = *((byte *) (data.Scan0 + (row + 1) * data.Stride + (col + 0) * bpp));

        int squared = current * current;
        sum += current;
        squaredSum += squared;
        histogram[current]++;

        int colDiff1 = col1 - current;
        int rowDiff1 = row1 - current;

        int absoluteGradient = Math.Abs(colDiff1) + Math.Abs(rowDiff1);
        absoluteGradientSum += absoluteGradient;
        if(absoluteGradient >= absoluteGradientThreshold)
          thresholdedAbsoluteGradientSum += absoluteGradient;

        int squaredGradient = colDiff1 * colDiff1 + rowDiff1 * rowDiff1;
        squaredGradientSum += squaredGradient;
        if(squaredGradient >= squaredGradientThreshold)
          thresholdedSquaredGradientSum += squaredGradient;

        if(row < bmp.Height - 2 && col < bmp.Width - 2)
        {
          int col2    = *((byte *) (data.Scan0 + (row + 0) * data.Stride + (col + 2) * bpp));
          int row2    = *((byte *) (data.Scan0 + (row + 2) * data.Stride + (col + 0) * bpp));

          int colDiff2 = col2 - current;
          int rowDiff2 = row2 - current;
          int brennerGradient = colDiff2 * colDiff2 + rowDiff2 * rowDiff2;
          brennerGradientSum += brennerGradient;
          if(brennerGradient >= brennerGradientThreshold)
            thresholdedBrennerGradientSum += brennerGradient;

          autocorrelationSum1 += current * col1 + current * row1;
          autocorrelationSum2 += current * col2 + current * row2;
        }

        if(current >= contentThreshold)
          thresholdedContentSum += current;
        if(current <= pixelCountThreshold)
          thresholdedPixelCountSum++;

        imagePowerSum += squared;
        if(current >= imagePowerThreshold)
          thresholdedImagePowerSum += current * current;
      }
    }
    bmp.UnlockBits(data);

    int pixels = width * height;
    double mean = (double) sum / pixels;
    double meanDeviationSquared = (double) squaredSum / pixels;

    int rangeMin = 0;
    while(histogram[rangeMin] == 0)
      rangeMin++;
    int rangeMax = histogram.Length - 1;
    while(histogram[rangeMax] == 0)
      rangeMax--;

    double entropy = 0.0;
    double log2 = Math.Log(2);
    for(int i = rangeMin; i <= rangeMax; i++)
    {
      if(histogram[i] > 0)
      {
        double p = (double) histogram[i] / pixels;
        entropy -= p * Math.Log(p) / log2;
      }
    }

    return new List<Result>()
    {
      new Result("AbsoluteGradient",            absoluteGradientSum),
      new Result("ThresholdedAbsoluteGradient", thresholdedAbsoluteGradientSum),
      new Result("SquaredGradient",             squaredGradientSum),
      new Result("ThresholdedSquaredGradient",  thresholdedSquaredGradientSum),
      new Result("BrennerGradient",             brennerGradientSum),
      new Result("ThresholdedBrennerGradient",  thresholdedBrennerGradientSum),
      new Result("Variance",                    meanDeviationSquared - mean * mean),
      new Result("Autocorrelation",             autocorrelationSum1 - autocorrelationSum2),
      new Result("StdevBasedCorrelation",       -(autocorrelationSum1 - pixels * mean * mean)),
      new Result("Range",                       rangeMax - rangeMin),
      new Result("Entropy",                     -entropy),
      new Result("ThresholdedContent",          -thresholdedContentSum),
      new Result("ThresholdedPixelCount",       thresholdedPixelCountSum),
      new Result("ImagePower",                  -imagePowerSum),
      new Result("ThresholdedImagePower",       -thresholdedImagePowerSum),
      new Result("JpegSize",                    new FileInfo(filename).Length),
    };
  }
}

public class Result
{
  public string Algorithm { get; private set; }
  public double Value     { get; private set; }

  public Result(string algorithm, double value)
  {
    Algorithm = algorithm;
    Value     = value;
  }
}

To be able to plot and compare the focus values of the different algorithms they were scaled to a value between 0 and 1 (scaled = (value - min)/(max - min)).
Plot of all algorithms for a range of ±20 µm:

              0 µm             |             20 µm

Things look quite similar for a range of ±50 µm:

              0 µm             |             50 µm

When using a range of ±500 µm things get more interesting. Four algorithms exhibit more of a fourth degree polynomial shape, and the others start to look more like Gaussian functions. Also, the Histogram Range algorithm start to perform better than for smaller ranges.

              0 µm             |             500 µm

Overall I'm quite impressed by the performance and consistency of these simple algorithms. With the naked eye, it's quite hard to tell that even the 50 µm image is out of focus but the algorithms have no problem comparing images just a few microns apart.
Comment: Hi, I know this is an old question, but I am working on a VERY similar problem, so I was hoping you could elaborate on this point "Fit the result to a second degree polynomial."
Comment: Hi NindzAl, please see my extra answer (http://stackoverflow.com/a/17758994/306074)
Comment: @Anlo I know it is a very old question but maybe you can try also the very simple JPEG size based algorithm used in NASA Curiosity Mars Rover, see my answer http://stackoverflow.com/a/32951113/15485
Comment: Yes, Jpeg size was one of the algorithms I tested. It performed reasonably well.
Answer: An extra answer to NindzAl's comment on the original answer:
I use the Extreme Optimization library to fit the sharpness values to a second degree polynomial. The distance of maximum sharpness is then extracted using the first derivative of the polynomial.
The Extreme Optimization library costs USD 999 for a single dev license, but I'm sure there are open source math libraries that can perform the fitting just as well.
// Distances (in µm) where the images were saved
double[] distance = new double[]
{
  -50,
  -40,
  -30,
  -20,
  -10,
    0,
  +10,
  +20,
  +30,
  +40,
  +50,
};

// Sharpness value of each image, as returned by CalculateFocusValues()
double[] sharpness = new double[]
{
  3960.9,
  4065.5,
  4173.0,
  4256.1,
  4317.6,
  4345.4,
  4339.9,
  4301.4,
  4230.0,
  4131.1,
  4035.0,
};

// Fit data to y = ax² + bx + c (second degree polynomial) using the Extreme Optimization library
const int SecondDegreePolynomial = 2;
Extreme.Mathematics.Curves.LinearCurveFitter fitter = new Extreme.Mathematics.Curves.LinearCurveFitter();
fitter.Curve = new Extreme.Mathematics.Curves.Polynomial(SecondDegreePolynomial);
fitter.XValues = new Extreme.Mathematics.LinearAlgebra.GeneralVector(distance,  true);
fitter.YValues = new Extreme.Mathematics.LinearAlgebra.GeneralVector(sharpness, true);
fitter.Fit();

// Find distance of maximum sharpness using the first derivative of the polynomial
// Using the sample data above, the focus point is located at distance +2.979 µm
double focusPoint = fitter.Curve.GetDerivative().FindRoots().First();

Answer: As for the free library, Math.Net will work for that purpose


How to add gaussian noise (10%) to a set of datapoints

Question: i have a set of 100 point (2-dimensional, x-y). I have to add to each x-coordinate a 10% gaussian noise. The 10% is referred to each x-value. I've found around this line of code:
noisy_data = exact_data
relativeError = 0.1
noisy_data[:,0] = [ np.random.normal(loc=value, scale=abs(relativeError*value)) for value in noisy_data[:,1]]

I'm not sure this is the right way to do that. Do you know if it is correct? If not, is there a function that can do it properly?
Comment: what are mean and variance of the guassian noise?
Comment: The excercise doesn't specify that.
Comment: if first column is x and second column is y:
`noisy_data = [np.random.normal(value, abs(relativeError*value)) for value in exact_data[:,0]]; noisy_data = np.c_[noisy_data, exact_data[:, 1]]`
Answer: It sounds to me like the y values don't matter. Also, there's no need to iterate over each element.
noisy_data = exact_data.copy()
noisy_data[:, 0] += np.random.normal(loc=0, scale=abs(relativeError*noisy_data[:, 0]))


Does permutation-similarity of Kronecker products imply permutation-similarity of the factors?

Question: Suppose $A$ and $B$ are square Boolean matrices. If $\hat{P} (A \otimes A) = (B \otimes B) \hat{P}$ for some permutation matrix $\hat{P}$, does it follow that $\hat{P} = (P \otimes P)$ for some permutation matrix $P$? In other words, can the matrix witnessing permutation-similarity in the higher dimension be "factored" into a matrix witnessing permutation-similarity in the lower dimension?
Answer: The answer is no.  This fails drastically in the case that $A = B = I$, since the equality holds for any matrix $\hat P$ (so it isn't necessarily true that $\hat P = P \otimes P$ for some $P$).


Finding Perimeter and area of a Rectangle object? (C#)

Question: I know that the formula for finding the area of a rectangle is just length * width, and the peremiter formula is 2(length) + 2(width).  My question is, whats the most efficient way to find the area and perimeter of a rectangle object made up of other objects?
My Code Snippet:
class Rectangle
{

public Line left { get; set; }
public Line top { get; set; }
public Line right { get; set; }
public Line bottom { get; set; }

public Rectangle() : this(new Line(new Point(), new Point())) { }

public Rectangle(Line diaganol)
{
    Point beginningDiagonalPoint = diaganol.startPoint;
    Point endingDiagonalPoint = diaganol.endPoint;

    int begXC = beginningDiagonalPoint.xCoord;
    int begYC = beginningDiagonalPoint.yCoord;

    int endXC = endingDiagonalPoint.xCoord;
    int endYC = endingDiagonalPoint.yCoord;

    Point rightSideEnd = new Point(endXC, begYC);
    Point leftSideEnd = new Point(begXC, endYC);

    right = new Line(endingDiagonalPoint, rightSideEnd);
    left = new Line(beginningDiagonalPoint, leftSideEnd);
    top = new Line(leftSideEnd, endingDiagonalPoint);
    bottom = new Line(rightSideEnd, beginningDiagonalPoint);
}
}

I want to write two methods, one to calculate the area, and one to caclulate the perimeter, how should I approach this with objects?
I know I could take the xfinal coord - xinitial coord for width, and yfinal - yinitial for the length, but is there another and/or better way of doing this with objects?
Thanks!
Answer: The area of a rectangle will always be:
area = width * height

The perimeter will always be:
perimeter = width * 2 + height * 2

It doesn't matter how you arrive at width or height, it will always be the same.
Answer: Your class constructors define a rectangle, but since the Lines are unprotected, outside code could change them to be parallelograms, other quadrilaterals, or just disjointed lines.
You're on the right track, though--your Rectangle class should be implementing Area and Perimeter methods, that's the "right way" when doing OOP.
You don't need the lines to calculate Area or Perimeter, you only need the original diagonal Points. In fact, you don't need left/top/right/bottom at all, so it might be better to make them lazy-initialized, read-only properties.
Area = Math.Abs( (Point1.X - Point2.X) * (Point1.Y - Point2.Y) )

Perimeter = (Math.Abs(Point1.X - Point2.X) + Math.Abs(Point1.Y - Point2.Y)) * 2

Comment: defining the quad by its diagonal can only describe a rectangle
Answer: Your perimeter would be the sum of the lengths of the four lines.  Presumably the Line objects have or will be able to have a length method.
Similarly, the area is the product of length of the right or left and top or bottom lines.
Answer: Your perimeter is (endXC - begXC)*2 + (endYC - begYC) *2
Your area is (endXC - begXC) * (endYC - begYC)
...assuming the points are ordered in the poitive x and y directions (otherwise enclose each calc in abs e.g. abs(endXC - begXC)
if area and circumference are likely to be called, you might want to calculate & store them on init
Answer: If you look at your class, your wasting more time in the constructor of the class than you'll ever lose to calculate the area and perimeter. Why do you store lines? Points are way more convenient:
class Rectangle
{

public Point bottomLeft { get; set; }
public Point topRight { get; set; }
public int? area;
public int? perimeter;

public Rectangle() : this(new Line(new Point(), new Point())) { }

public Rectangle(Line diaganol)
{
    bottomLeft = diagonal.StartPoint;
    topRight = diagonal.EndPoint;
}

public int Area()
{
  if (area == null)
  {
     area = Math.Abs(diagonal.StartPoint.X - diagonal.EndPoint.X) *
            Math.Abs(diagonal.StartPoint.Y - diagonal.EndPoint.Y);
  }
  return (int)area;
}
public int Perimeter()
{
  if (perimeter == null)
  {
     perimeter = Math.Abs(diagonal.StartPoint.X - diagonal.EndPoint.X) * 2 +
            Math.Abs(diagonal.StartPoint.Y - diagonal.EndPoint.Y) * 2;
  }
  return (int)perimeter;
}
}


How to group elements inside  tag in joint.js?

Question: How to group svg elements like rect , text inside g tag in joint.js using custom elements?
I just need something like this.
 <g record-group="0" joint-selector="group_0" id="v-225" transform="matrix(1,0,0,1,10,30)">
<g joint-selector="bodiesGroup_0" id="v-222" fill="transparent" stroke="none">
<rect x="-10" y="0" height="20" item-id="value_1" joint-selector="itemBody_value_1" id="v-217" class="record-item-body" stroke="black" width="83"></rect>
</g>
</g>

Answer: you can create nested markup using the children property:
var Circle = joint.dia.Element.define('custom.Circle', {
    markup: [{
        tagName: 'g',
        selector: 'wrapper',
        children: [{
            tagName: 'text'
        }]
    }]
});


What does $\sup _n$ mean?

Question: I came across this notation when studying about the Kolmogorov Convergence Criterion, namely
Suppose that $\sup _n |X_n| \leq A$ for some $A>0$, ...
I understand what does $\sup$ mean, but what does $\sup_n$ mean?
I have tried to search for more information online but did not manage to find anything.
Comment: Is there supposed to be anything between the $\sup_n$ and the $\leq$?
Comment: @Arthur edited. Thanks!
Comment: @BrevanEllefsen how is that relevant?
Answer: It means the supremum of the possible values of $|X_n|$ as you vary $n$ (presumably in the domain of $X_n$).
Answer: If $(a_n)$ is a sequence of real numbers, which is bounded from above, then let $A:=\{a_1,a_2,a_3,...\}$.
By definition we have
$$\sup_n a_n= \sup A.$$

What does $\sup _n$ mean?


Random Walk solution shortcut

Question: I remember from stochastic processes that certain types of random walks can be simplified into the following:
Probability of eventually winding up at the left stop point = Probability of walking DIRECTLY to the left point without hesitation/(Probability of walking DIRECTLY to the left point without hesitation + Probability of walking DIRECTLY to the right point without hesitation)
What are the criteria that need to be met to use this simplification?
Comment: Are we to assume that your random walk is 1-Dimensional and with finite states?
Comment: In a way that is my question... what do we have to assume in order for this to be true?  I would think we would have to assume it is a walk where the probability of terminating goes to 1.
Comment: Even for simple random walk this doesn't appear to be true.
Comment: Random walks with non zero transition probabilities on a finite segment always *terminate* with probability 1.
Answer: It is true when the required number of steps to the left is equal to the required number of steps to the right.
For example, imagine if there are 6 steps between left and right, i.e. 7 points.  Then if the probability of a step left is $\frac{1}{2}$ and of a step right is also $\frac{1}{2}$, the probability of winning from each starting point is:
$$\frac{6}{6},  \frac{5}{6},  \frac{4}{6},  \frac{3}{6},  \frac{2}{6},  \frac{1}{6},  \frac{0}{6}$$
while your method might suggest
$$\frac{64}{65},  \frac{16}{17},  \frac{4}{5},  \frac{1}{2},  \frac{1}{5},  \frac{1}{17},  \frac{1}{65}.$$
and these are only the same in the middle.
But the probabilities can vary and your algorithm will still work for the cntral starting point.  For example, if the probability of a step left is $\frac{1}{3}$ and of a step right is also $\frac{2}{3}$, the probability of winning from each starting point is:
$$\frac{63}{63},  \frac{31}{63},  \frac{15}{63},  \frac{7}{63},  \frac{3}{63},  \frac{1}{63},  \frac{0}{63}$$
and the central $\frac{7}{63}$ is equal to the $\frac{1}{9}$ which your algorithm would give.
It is not hard to generalise this, though it is slightly messy. Measuring steps from right to left, if there are $n$ steps, and the probability of a step to the left is $p$ and to the right $1-p$, then starting at point $i$ (with $i=0$ at the right hand side and $i=n$ at the left) the probability of hitting the left first is
$$Pr_{i} =\frac{p^{n-i}\left( (1-p)^i-p^i\right)}{(1-p)^{n}-p^n}$$
since $Pr_{0}=0$, $Pr_{n}=1$ and $Pr_{i} = p Pr_{i+1} + (1-p) Pr_{i-1}$. [The expression doesn't work if $p=1/2$, but in that case the probability is $Pr_{i} = i/n$].
The only values for which this expression is equal to $\dfrac{p^{2n-i}}{p^{2n-i}+(1-p)^{i}}$ are when $n$ is even and $i=n/2$.

Random Walk solution shortcut


Is it possible to use a sort of constant or a custom token in the rewrite section of a views field?

Question: My use case.
I have a portion of a URL of another site (www.example1.com) under each of my nodes (let's say node type B).
Each of these nodes can be related with another node (let's say node type A).
I need a view which show informations of A nodes and get the URL portions from B nodes using the relationship section of the view.
That's ok, I get what I want but I would like to create a URL with this URL's portion adding a constant/token at the beginning (www.example1.com) so that it can changed in a simple way (let's say www.example2.com) instead of modify each field of the view.
My best bet should be probably to rewrite the template of the view and using a constant (variable_get/set should be fine) but I would like to have this field configurable with the UI.
Thanks
Comment: does the view show the correct fields (via the relationship) that hold the information you want to present in the link? If so, creating a customized link field should be simple.
Comment: yes, my problem is only focused on how to use a constant or a token or whatsoever variable which can later be changed without changing the view.
Think that: you put [my-custom-token]/path1 in the rewrite output of one field, [my-custom-token]/path2 in a second field, [my-custom-token]/pathN in the n-th field.
If [my-custom-token] is externally configurable, you can have:
[my-custom-token] = "http://www.myexternalurl1.com" and then you easily change it "http://www.myexternalurl2.com" if you want (that's exactly my case).
Answer: If I'm understanding the question properly, you can either use a hidden field on a node to create a node specific value which you can rewrite as a link if desired, or create a Global:Custom Text where you can include whatever static or variable data you desire, so long as the fields containing the information are present (visible or not).
Comment: Yes, you are right. If I create an hidden "Global: Custom Text" with value "www.example1.com" and then I use this value on the rewrite output of the fields that I need to rewrite, I can solve this problem. Then, if I need to change "www.example1.com" into "www.example2.com" instead of changing each field I can just change the value of the "Global: Custom Text" field. Thanks.


Changing the background color of html buttons forward and backward after clicks

Question: I'm new to JavaScipt and HTML and only need it as a side issue. I have some buttons and I want their backround color to change after clicked. That I could solve partly with:

<input class="choice" onclick="this.style.background='blue';" type="submit" value='V' id='0' />

However, when the button is clicked a second time it should change back. Preferably would be a one line statement like above. Would appreciate any help.
Comment: how is it supposed to be clicked again if it gets disabled?
Comment: Are you trying to get the button enabled on second click? It's a bit unclear.
Comment: @nicael Sry, forgot to take this out here. I should be without the `this.disabled=true`.
Comment: Edited to remove this.disabled=true; per the user's comment.
Answer: I broke your code out into seperate JS, it's cleaner that way and easier to maintain.
If you disable the button, then it stops recieving click events. I assume that's not what you want.
Here, I've made it so that when the button is clicked, it toggles the background color between red and blue.
http://jsbin.com/huqoyixuhe/edit?html,css,js,output
// select the button
var input = document.querySelector('input.choice');
// add a click event listener
input.addEventListener('click', function () {
  // if the button is red, make it blue
  if (this.style.background === 'red') {
    this.style.background = 'blue';
  }
  // otherwise, it is already blue, so make it red!
  else {
    this.style.background = 'red';
  }

});

EDIT
here, as a one-liner:
http://jsbin.com/bolowuceqa/edit?html,output
<input class="choice" onclick="this.style.background==='red' ? this.style.background = 'blue' : this.style.background = 'red'" style="background:red;" type="submit" value='V' id='0' />

Comment: Thx, but are u sure it's working? For me the button just stays red. Isn't there any "one line solution"? I would prefer that, because the html document that contains these buttons will be build up with some template engine (jinja2) and, so far, I have trouble inserting JavaScript functions in that. I also can't import a JavaScript file. It has to be written already within the html document.
Answer: You can use toggole between class Name through pure javascript.
HTML:
<button id="toggole" class="red" onclick="toggolecolor()">
Click Please
</button>

CSS:.red{
  background-color:red;
}
.blue{
  background-color:blue;
}

Javascript:
function toggolecolor(){
 var element = document.getElementById("toggole");
  element.classList.toggle("red");
    element.classList.toggle("blue");

}

Answer: <!doctype html>

    <meta charset="utf-8">

Comment: Hi. Welcome to StackOverflow. Please note that this is not valid html. You need to close the tags correctly. For example `` is missing. Also `bgcolor` is deprecated  https://developer.mozilla.org/en-US/docs/Web/API/Document/bgColor. Besides, please read: https://stackoverflow.com/help/how-to-answer