Write to file not work in unit test

Question: I have a function that writes some data to file when. I run it in python interpreter and it works just as expected but when I run it in unittest it just creates the file and writes nothing in it.
Here is my code:
def write(text):
    with open('test.db', 'a') as db:
        db.write(text)

When I execueted it in python interpreter test.db updated, but when I run it from unittest not it not works and nothing added to test.db. I need to have changes that come from unittest how could I fix it?
Here is full code:
# dbwrapper/file.py

class Status:
    UP = 'up'
    DOWN = 'down'

class FileWrapper:
    def __init__(self, path):
        self.path = path

    def get_service_status(self, service_id):
        for line in self._reverse_readline():
            service_id, time_string, status = line.split('#')
            service_id = service_id.strip().replace('\\n', '\n').replace('\@', '#')
            time_string = time_string.strip()
            status = status.strip()
            if service_id == self.service_id:
                return status
        return Status.UP

    def set_service_status(self, service_id, status):
        if status not in self.status_list:
            raise InvalidStatus
        with open(self.path, 'a') as db:
            db.write(
                '#service_id: %(service_id)s #time: %(time)s #status: %(status)s'%{
                    'service_id': str(service_id).replace('\n', '\\n').replace('#', '\@'),
                    'time': datetime.utcnow(),
                    'status': status
                }
            )
            print '#service_id: %(service_id)s #time: %(time)s #status: %(status)s'%{
                    'service_id': str(service_id).replace('\n', '\\n').replace('#', '\@'),
                    'time': datetime.utcnow(),
                    'status': status
                }
    def _reverse_readline(self, buf_size=8192):
        """a generator that returns the lines of a file in reverse order"""
        with open(self.path, 'w+') as fh:
            segment = None
            offset = 0
            fh.seek(0, os.SEEK_END)
            file_size = remaining_size = fh.tell()
            while remaining_size > 0:
                offset = min(file_size, offset + buf_size)
                fh.seek(file_size - offset)
                buffer = fh.read(min(remaining_size, buf_size))
                remaining_size -= buf_size
                lines = buffer.split('\n')
                # the first line of the buffer is probably not a complete line so
                # we'll save it and append it to the last line of the next buffer
                # we read
                if segment is not None:
                    # if the previous chunk starts right from the beginning of line
                    # do not concact the segment to the last line of new chunk
                    # instead, yield the segment first
                    if buffer[-1] is not '\n':
                        lines[-1] += segment
                    else:
                        yield segment
                segment = lines[0]
                for index in range(len(lines) - 1, 0, -1):
                    if len(lines[index]):
                        yield lines[index]
            # Don't yield None if the file was empty
            if segment is not None:
                yield segment

# test/test_dbwrapper.py
class TestFileWrapper(unittest.TestCase):
    PATH = 'test.db'
    SERVICE_ID = '#test_service\n'

    def setUp(self):
        self.filewrapper = FileWrapper(self.PATH)

    def tearDown(self):
        self.filewrapper = None
        # os.remove(self.PATH)

    def test_status(self):
        self.assertEqual(
            self.filewrapper.get_service_status(self.SERVICE_ID),
            Status.UP
        )
        self.filewrapper.set_service_status(self.SERVICE_ID, Status.DOWN)
        self.assertEqual(
            self.filewrapper.get_service_status(self.SERVICE_ID),
            Status.DOWN
        )

I have run it with this command:
python -m test.test_dbwrapper
Comment: btw, technically this is not a unit test if you are writing to a file.
Comment: In the call to your write function, check the current work directory. `print os.getcwd()`
Comment: You'll need to show your unit testing code, it's not clear if/how you call the function
Comment: @Chris_Rands all code (including test) added
Answer: unit tests should work flawlessly regardless of the environment; A straightforward and bad idea would be to write a couple of Unit Tests that make use of a real file and simply test the reading and writing. But the way, here you can see an example of a test function that writes something on the file:
import unittest

class TestExample(unittest.TestCase):

    def test_something(self):
        f = open('filename.txt', 'w')
        f.write('The owls are not what they seem')
        f.close()

        f = open('filename.txt', 'r')
        txt = f.read()
        f.close()
        self.assertEqual(txt, 'The owls are not what they seem')

if __name__ == '__main__':
    unittest.main()

when you run it using python 2:
$ python2 test.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

And content of filename:
$ cat filename.txt
The owls are not what they seem

Comment: Check my project structure, I have some module. plase check it with that structure

Write to file not work in unit test


Correct octave technique

Question: I am an amateur pianist (of about 17 years) and I'm not sure if I ever learned correct octave technique.
I just "finished" Chopin's first ballad and there are several sections which require some quick (at least quick for me) octaves. I tend to tense up and use a lot of my arm when I play octaves and I think it limits the speed at which I play.
My question is what is the correct way to play octaves? Should I be using more wrist? Are there any good exercises I can do to help improve?
Answer: The key (as is almost always the case when you feel aches and pains from piano) is relaxation.
Each of your fingers only needs to be "active" (i.e. not relaxed) at the instant it actually strike a key, because you can move from key to key and hold keys down while relaxing that finger. In fact, if you are not relaxed, you are inhibiting your movement (though this is more relevant to your arm than your individual fingers).
When playing repetitive chord shapes, especially octaves, most students tend to try to "freeze"  their hand into the proper shape, then push it down onto the keys in each location on the keyboard where the chord occurs. Thus you are tensing your fingers, palm, and wrist into an awkward, contorted shape while trying to quickly move your forearm laterally. But it's much harder to accomplish this movement quickly, fluidly, and easily when so much of your arm is stuck in a tense state! So you must relax, at every possible instant, rather than trying to maintain the shape.
This means that you need to be able to spread your hand into an octave-shape very quickly, because you must re-form the shape for every octave you play. This sounds difficult, and indeed it's hard to master, but it's mechanically much easier and much better for your arms than "freezing" is.
So you should start by practicing making the octave-shape very quickly. As an exercise, starting with your hand floating above the keyboard and completely relaxed, drop it down onto the keyboard while (at the last possible moment) stretching into the octave.
As you do this exercise, start thinking about what happens when you release the keys. Remember, the octave-shape is tense and uncomfortable, so release it as soon as possible to get your hand back into a relaxed shape. So, first, you can practice relaxing as you release the keys.
...But above, I said that you don't need your fingers to be "active" even when you're holding the keys. So practice dropping your hand into an octave and immediately relaxing as much as you can--and holding this relaxed shape. (This is tricky, but necessary when playing octaves that are too quick for relaxing "between" them.)
Now, the last element of a run of octaves is the movement from octave to octave. This movement must begin the instant you release the keys--or just before, if possible. There are several ways to make this movement. You can try to make a smooth and symmetric arc, but you risk landing on each octave at a slight angle, which can be problematic. Alternatively, you can rise off the first octave in a a shallow slope, moving more laterally than upward, until you are directly above the next octave, at which point you can drop directly down onto it. The optimal motion, in my opinion, is somewhere between the "arc" and the "slope-drop"; you need the smoothness of the arc, the laterals movement efficiency of the slope, and the precision of the drop. So practice both ways, and as you speed up your practice, you should naturally find something that works efficiently and comfortably.
Answer: John W. Schaum wrote a progressive series of "Octave Studies for Piano" Book One and Book Two.
I can hardly wait until I get both completed!
Book One allows you to begin with studies in smaller intervals through Hand expansion, How to read octaves, including a worksheet in quickly recognizing octaves; Applied octave technic teaching the weight of octave playing, broken staccato octaves, three octaves on one arm impulse, octave in skip; Octave Melody and polyphonic octaves; practice tips in multiple ways by experts such as Duvernoy, Ascher along with Jensen teaching overlapping octaves. Also Legato octaves through such greats as Wolf, Czibulka; Bertini; Kohler;Schmitt; Lemoine; Czerny; Beyer; Biehl; Gurlitt;Streabbog;Le Couppey; Concone; Neupert; Kunz; and all of Schaum's exercises of which my favorite is his Hand Expansion Waltz and Hiller teaches an octave study in 5/4 time.
This was given to me by Boise State University's Music Department, Dr. Madeline Hsu, Instructor, Professional Classical Concert Pianist in Paris and an amazing pianist,  a wonderfully knowledgeable as well as an expert instructor , incredibly beautiful and exhuberant performer a very kind and generous person.  I trust her advice 100%.
If this book is too difficult for you at first as it was for me, I highly recommend these sources to bring you up to speed, the first I will mention was also given to me by Madeleine: "Piano Literature of the 17th, 18th, and 19th Centuries Book5 Part A Frances Clark Library for Piano Students Edited by Louise Goss"
"John Thompson's Third Grade Velocity Studies Edited and Annotated Versions of Standard Dexterity Etudes" The Willis Music Company.
There are fingering and hand rotation technics that are important to perfect  toward achieving virtuosity.  Happy practicing!
Answer: If you're going up or down the piano playing octaves you'll need to move your arm, but you should minimize the movement as much as possible. A lot of times beginners will move their arm up much more than they need to in general when moving up or down the piano. Minimizing the movement minimizes the distance you need to move from one octave to another.
As for your wrist, it should not tense up more than any other chord you play. Compare how tense a typical triad is for your hand compared to a typical triad. If it's tense compared to it, you may need to do exercises to loosen up the tension like starting on an interval you don't tense up with and stretch up or down one note at a time to get use to the interval of an octave.
A very simple exercise you can do to improve this is practice going up and down every scale with octaves.
I'll post examples of this in a little bit.
Comment: I see, so it really should be no different than playing a typical triad. It might be a bit of "oh no, here comes the quick octaves" that's getting to me. I'll try the exercises to get comfortable with it.
Answer: I decided to post my own answer to this question, partially because in the past two years I had the opportunity to learn from a professional pianist, secondly because this question seemed to generate a lot of answers and I think it would be good to highlight what helped me in the end.
In the end, the issue was not really about playing octaves as much as it was about general hand position, relaxation of the arms, strengthening my pinky finger and most importantly practicing slowly and with great attention to the melody and meaning of the piece. After modifying these aspects of my playing, playing octaves quickly and clearly was quite easy. I'll expand a bit on each point.

General hand position:

Previously, I has been shifting my wrist to reach certain notes. I also would occasionally move my wrist up and my knuckles down, striking the keys quickly and superficially instead of feeling deeply into the keys. I now understand that the correct position for you wrist is generally down, with your knuckles up and fingers pointed downward so that you can strike into the keys.

Relaxation of the arms:

Before working with a professional, I never realized how much I relied on arm strength in playing. Often times I would find my forearm getting soar toward the end of a piece. Now I understand that your arm should be completely relaxed and that the strength comes from your actual fingers.
A helpful exercise was to make a tight fist, keeping my arm relaxed at all times, holding my fist above the piano and then letting it fall down into a chord position. This does two things. First, if you miss the notes of the chord then it means that your fingers don't know the shape of the chord well enough. Second, it trains you to use finger and hand strength rather than arm strength in playing the chord.

Strengthening the pinky:

Previously when I played octaves I would rely heavily on my thumb believing this note to be the source of the tone I wanted to create, but this is not correct. Both pinky and thumb are equally important. Your pinky should rest comfortably on the key and both fingers should be pressing into the keys with equal strength.

Playing slowly and undestanding the piece:

This was by far the most helpful. Previously I tried to force my way through parts that I found difficult to play, sometimes playing faster, moving my arm more, etc. I found that when one playes very carefully and slowly, paying great attention to every sound, thinking carefully about what sound the composer wants to express and what sound I want to convey, then these "difficult parts" become effortless. Instead of thinking about the difficulty of a section, you become obsorbed with the melody. I find this to be a remarkable experience that I did not previously have in performance and especially not in practice.
Answer: I'm going to disagree with some of the advice in other answers. There is a very basic mistake which is easy for beginners to fall into without really thinking about it, and that is to assume that "you play the piano with your fingers". To get beyond simple playing technique, you have to realize that you really play with piano with your arms, and even with your whole upper body. Even when playing pianissimo, the main job of your fingers is to pick off the right notes, not to "do the work" of pressing the keys and moving around the keyboard.
Try practising leaps in octaves, one hand at a time, over the whole keyboard. For example start at the lowest C octave with the left hand and play in octaves C E (up a third) C G (up a fifth) C C (up an octave) C E (up a tenth) etc till you are jumping the from the bottom C octave to the top C. Play the octaves staccato, and make sure your hand and wrist relaxes between each octave. Start very slow, till both the accuracy and the relaxation become automatic. Then try increasing the speed.
Once you have got hold of the idea of moving your whole arm freely around the keyboard, reduce the size of the arm movements by practising conventional arpeggios in octaves. Finally, play diatonic and chromatic scales in octaves. If you start to "tense up", go back to the big arm movements and slower speeds.
(And once you have mastered that, the C# minor section near the end of Ballade #3 or Liszt's "La Campanella" study shouldn't terrify you, let alone Ballade #1.)
Answer: I'll add my two cents to this. Here are Rubinstein and Horowitz performing the octave passage in Chopin's Ab Polonaise:

This is instructive because it has a stream of octaves in the left hand, going gradually from pianissimo to fortissimo. As you can see, neither of them use the fingers to play them, just getting the finger and thumb in the right place and using lateral movements of the arm to position the fingers over the right notes. However, they have a rather different approach to how they move their hands up and down to hit the notes.
Horowitz uses his entire body in a consistent fashion. He starts with very little force and goes on to use a great deal, with little variation in how he strikes the keys. (I'm reminded of Bruce Lee and his "one inch punch"; I have the feeling that Horowitz understood how to put his whole body into a very small movement as well as Lee did.)
Rubinstein, on the other hand, uses a good deal of up-and-down movement of the wrist. As the octaves get louder, he supplements that with up-and-down movement of the arm.
So, in the end, the proper technique is what works. You will see variations like these in all the great pianists.
However, there are common problems that everyone has to correct, because they don't work. One of these, as you have found, is the "sore arm" problem. Most of the muscles that move the fingers up and down are in the forearms -- if you waggle your fingers, you can see them rippling in your forearm. If the muscles in your hand, which you use to support your finger position, are weak, then you will often lock the forearm muscles to compensate. That's what causes the problem. The other main problem is lack of accuracy in the way you use your arms to position your hands.
You have to find the balance between tension and relaxation, as well as the details of positioning and movement, that allow you to maximize the force while minimizing the effort. While you are looking, pay attention to technique, but keep the music foremost in mind at all times. The music will teach you the technique, but the technique will not teach you the music.
Answer: Playing 8ths (AKA Octaves)
Creds: I've been a piano teacher of all levels for more than 10 years.
First thing:
If you're just beginning, start off learning 6ths first. 6ths use the exact same arm motion as 8ths, except 8ths are wider, and cause more arm strain. Thus, it's best to learn 6ths before 8ths to get the hang of it. (depending on how big or small your reach is.)
What you need to be able to play good 6ths or 8ths:

Be able to hold the position of a 6th or 8th.  You need to know the distance required and call on it automatically. To do this just play a 6th or 8th, close your eyes and memorize how it feels to play that interval. How does your hand feel? How far apart is it? Then take your hand away from the piano, shake it out, and then set your hand on your lap and stretch your 1 and 5 out to where you think they need to be to hit the 6th or 8th. Now, put it back on the piano and see if it fits. If your hand lands on the 6th or 8th cleanly, great, if not try again until successful. Keep doing this until you've successfully got the 6th and 8th at least 10 times in a row without any mistakes.
Arm motion of arm/hand/finger unit: move from one key to the next accurately. This skill is called by both 6ths and 8ths, so learning 6ths arm motion will also transfer to your 8ths.  Basically the idea is to pick up your hand and move it to the next desired key. You'll want to keep your hand relaxed while you move and play. (Learning to relax takes at least a month or two of dedicated practice time) Keep your motions as small as possible. The smaller you move, the shorter your distances, the better. You'll want to direct your motion sideways and not up and down. When you play C to D, think of skipping a rock across water, stay to the surface and move sideways. A good exercise to understand the arm motions is: Take an invisible salt shaker in your hand, and do small shakes as gentle and fast as you can while you glide your hand left-right across a table, while keeping the distance above the table at about 2-3 inches.   The salt shake motion is like hitting the 6ths or 8ths, and the glide is moving from one key to the next while your arm moves.
Final exercise

Starting on D's (8ths) play each key listed 3-8 times: D D D, D# D# D#, D D D, Db Db Db, D D D, (loop)
Same thing but starting on F's play pattern: F, F#, F, E, F (loop)
Same thing but starting on B's play pattern: B, Bb, B, C, B (loop)
Same thing but starting on F's play pattern: E, F#, E, Eb, E (loop)
Same thing but starting on F's play pattern: C, C#, C, Bb, C (loop)
Once you've done all these patterns, you've done all possible diatonic scale combinations you could encounter.
I also made this video on arpeggios and octaves a long time ago, but there should be a few good tips!
If this answers your question, please mark as answered to keep up with maintenance. I wish you the best. :)
Comment: While this was a good answer when you posted it on the other question, it doesn't quite fit here as well. I'd recommend writing a new answer for a new question, in order to directly answer it - or if the questions are duplicates, please just Let us know so we can close as duplicate.
Answer: Maybe it is to do with the positioning of your hands. Whenever I tensed up while playing, my piano teacher always told me to reach up to the top of the keys instead of playing the edge of the key. What I mean is this:
It helps for me, but it also depends on how large your hands are.
It may also be to do with your practising. If you are having trouble with octaves, try and relax your wrists and fingers and practise. I think it would be best to start slow and gradually move faster. I used to tense up whenever playing octaves too, but using these techniques, I gradually improved.
Answer: Positioning

The correct way to play octaves is to keep the wrist completely still and relaxed while your fingers do all the "leg work." Moving your wrist up and down will cause your fingers to have uneven lengths when reaching the keyboard. Keeping your wrist still and slightly below the keyboard will even out the length of your fingers so that they have the same amount of access to the keyboard.

Practicing

In order to practice said wrist technique, start by playing the same octave over and over again slowly. Once you lift your hand between each octave, relax it immediately. These little "relaxation" techniques in between octaves should help your hand familiarize itself with the motions. Slowly build yourself up to a quicker tempo, always keeping your wrist below the keyboard when you're pressing down on the keys.
Comment: Can't agree with 'keep the wrist completely still'. Your hand will move as a hand better than moving your fingers. If the wrist is low, it'll work for white keys maybe, but not the black keys.

Correct octave technique


android:windowSoftInputMode="adjustResize" is not working as it should be

Question: Even though this problem has many solutions in stackoverflow, I could not solve my problem.
I have two edit texts in the screen, one  on top, another is attached to bottom of the screen.
Whenever I click on bottom edit text, softkey board comes over it. I already played with windowSoftInputMode.
I dont want other content of the screen to scroll up when I click on my bottom edittext.
This is my xml layout.
 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:background="@color/background"
android:orientation="vertical"
>
<RelativeLayout
  android:layout_width="match_parent"
  android:layout_height="wrap_content" >
<EditText
   android:id="@+id/phone_number_edit_text_compose"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_alignParentLeft="true"
   android:layout_alignParentTop="true"
   android:layout_marginLeft="@dimen/activity_horizontal_margin"
   android:layout_marginTop="@dimen/activity_horizontal_margin"
   android:layout_toLeftOf="@id/select_contact"
   android:background="@drawable/phone_edittext_background_selector"
   android:ems="10"
   android:hint="@string/phone_edittext_hint"
   android:inputType="phone"
   android:paddingBottom="12dp"
   android:paddingLeft="8dp"
   android:paddingTop="12dp"
   android:textAppearance="?android:attr/textAppearanceMedium"
   android:textColor="@color/white" />

<ImageButton
 android:id="@+id/selectcontact_compose"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_alignParentTop="true"
 android:layout_alignBottom="@+id/phone_number_edit_text_compose"
 android:layout_marginTop="@dimen/activity_horizontal_margin"
 android:layout_toRightOf="@id/phone_number_edit_text_compose"
 android:background="@drawable/select_contact_background_selector"
 android:contentDescription="@string/select_contact_content_description"
 android:src="@drawable/select_contact_selector"
 android:layout_marginLeft="2dp"
 android:paddingLeft="8dp"
 android:paddingRight="8dp"/>

<View
     android:id="@+id/view1"
     android:layout_width="wrap_content"
     android:layout_height="2px"
     android:layout_below="@id/phone_number_edit_text_compose"
     android:layout_marginTop="@dimen/redial_screen_distance_between_views"
     android:background="@drawable/separator" />

<LinearLayout
   android:id="@+id/repetition_layout"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:layout_below="@+id/view1"
   android:clickable="true"
   android:onClick="RepetitionLayoutClickListener"
   android:orientation="horizontal"
   android:paddingBottom="@dimen/redial_screen_distance_between_views"
   android:paddingTop="@dimen/redial_screen_distance_between_views"
   android:background="@drawable/repetition_layout_background_selector"
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin">

<TextView
  android:id="@+id/repetition_textview"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="@string/repetition"
  android:textColor="@color/green"
  android:textAppearance="?android:attr/textAppearanceLarge" />

<Spinner
  android:id="@+id/repetition_spinner"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:background="@null"
  android:clickable="false"
  android:popupBackground="@color/dark_background" />

</LinearLayout>

<View
     android:id="@+id/view2"
     android:layout_width="wrap_content"
     android:layout_height="2px"
     android:layout_below="@id/repetition_layout"
     android:background="@drawable/separator" />

<LinearLayout
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:layout_below="@+id/view2"
   android:orientation="horizontal"
   android:paddingBottom="@dimen/redial_screen_distance_between_views"
   android:paddingTop="@dimen/redial_screen_distance_between_views"
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:id="@+id/date_layout">

<TextView
   android:id="@+id/textView1"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="@string/d"
   android:textColor="@color/green"
   android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
   android:id="@+id/date_textview"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="@string/a"
   android:paddingLeft="5dp"
   android:textColor="@color/white"
   android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
<View
     android:id="@+id/view3"
     android:layout_width="wrap_content"
     android:layout_height="2px"
     android:layout_below="@id/date_layout"
     android:background="@drawable/separator" />

<LinearLayout
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:layout_below="@+id/view3"
   android:orientation="horizontal"
   android:paddingBottom="@dimen/redial_screen_distance_between_views"
   android:paddingTop="@dimen/redial_screen_distance_between_views"
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:id="@+id/time_layout">

<TextView
   android:id="@+id/textView2"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="@string/t"
   android:textColor="@color/green"
   android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
   android:id="@+id/time_textview"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="@string/b"
   android:paddingLeft="5dp"
   android:textColor="@color/white"
   android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
</RelativeLayout>

<RelativeLayout
   android:id="@+id/compose_layout"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:layout_weight="1">

<EditText
   android:id="@+id/editText1"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:background="@drawable/compose_message_background"
   android:hint="@string/compose_message_hint"
   android:paddingLeft="5dp"
   android:paddingRight="5dp"
   android:paddingTop="12dp"
   android:paddingBottom="12dp"
   android:layout_alignParentLeft="true"
   android:layout_alignParentBottom="true"
   android:textAppearance="?android:attr/textAppearanceMedium"
   android:layout_toLeftOf="@+id/imageButton1" >

</EditText>

<ImageButton
   android:id="@+id/imageButton1"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:background="@drawable/send_button_background"
   android:src="@drawable/ic_action_send_now"
   android:paddingRight="8dp"
   android:paddingLeft="8dp"
   android:layout_alignBottom="@+id/editText1"
   android:layout_alignTop="@+id/editText1"
   android:layout_alignParentRight="true"/>
</RelativeLayout>

</LinearLayout>

And this my manifest xml.
    <activity
        android:name="com.task.SmsScreen"
        android:label="@string/app_name"
        android:windowSoftInputMode="adjustResize"
      >
    </activity>

Comment: Use this android:windowSoftInputMode="adjustPan|stateVisible"
Comment: try  `android:windowSoftInputMode="stateAlwaysHidden|adjustPan"`
Comment: @PiyushGupta I played with all combination Piyush... This scrolls all other content of the screen up.
Comment: @RethinavelPillai This scrolls all other content of the screen up
Answer: You did not say which version of android are you compiling for and which version are you running on.
But check if you perhaps use fullscreen option set by about android:windowFullscreen attribute or by setting FLAG_FULSCREEN. This prevents adjusrResize option to wrok properly on newer APIs. It works for API 10 (2.3.5).
Comment: Thanks. I was using SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN for SystemUiVisibility which was causing adjustResize to not work correctly
Answer: Remove your outer Linear Layout and place everything inside a Relative Layout. And align your bottom edit text to bottom of the layout by making alignParentBottom true.
And main thing "Dont do anything to the android:windowSoftInputMode." Delete that line from manifest file.
Let android take default.
Comment: This worked for me, although I really don't know why it would work with a Relative but not with a Linear
Comment: why should place it inside relative layout?
Comment: @zihadrizkyef When the keyboard opens your root container becomes small but edit text is aligned to the bottom it will also move up with the parent
Comment: @Praveena why I can't use LinearLayout? why should RelativeLayout?
Answer: You should use
<activity
        android:name="com.task.SmsScreen"
        android:label="@string/app_name"
        android:windowSoftInputMode="adjustPan"
      >
    </activity>

Comment: Thank you but I dont want other content of the screen to scroll up when I click on my bottom edittext.
Answer: After two days of hassle and reading all the stackoverflow solutions I came up with my own. It worked for me.
I had to use scrollview only then it adjusts itself in the tiny space by shrinking the view. Without scrollview I had to use the Outermost LinearLayout with layout_gravity:bottom. But with this settings all the elements drops at the bottom of the Screen. if used layout_margintop or layout_marginbottom then when keyboard pops up some of the textview or edittextview thrown away out of the screen .. Grrrrrrrrrrr....
So, finally I found this solution hope it may solve some of your problem.
in Manifest.xml
<activity
    android:windowSoftInputMode="adjustResize"
    android:screenOrientation="portrait"
    android:configChanges="orientation">
In Layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/love_bg_red_10"
android:gravity="center"
android:orientation="vertical"
tools:context="${packageName}.${activityClass}" >

<ScrollView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/txtvwYourName"
            android:layout_width="fill_parent"
            android:layout_height="40dp"
            android:layout_gravity="center"
            android:layout_marginLeft="15dp"
            android:layout_marginRight="15dp"
            android:background="@layout/border_header"
            android:gravity="center"
            android:text="Your Name"
            android:textColor="#FFF"
            android:textSize="20sp"
            android:textStyle="bold" />

        <EditText
            android:id="@+id/edttxtFistName"
            android:layout_width="fill_parent"
            android:layout_height="45dp"
            android:layout_marginLeft="15dp"
            android:layout_marginRight="15dp"
            android:background="@layout/border_edittextview"
            android:gravity="center"
            android:hint="Type your name here"
            android:includeFontPadding="false"
            android:inputType="textPersonName"
            android:lines="1"
            android:maxLength="30"
            android:tag="edttxtFistName"
            android:textAllCaps="false"
            android:textColor="#FFF"
            android:textSize="20sp" />

        <TextView
            android:id="@+id/txtvwFavPersonName"
            android:layout_width="fill_parent"
            android:layout_height="35dp"
            android:layout_marginLeft="15dp"
            android:layout_marginRight="15dp"
            android:background="@layout/border_header"
            android:gravity="center"
            android:text="Name of your favorite person"
            android:textColor="#FFF"
            android:textSize="20sp"
            android:textStyle="bold" />

        <EditText
            android:id="@+id/edttxtLastName"
            android:layout_width="fill_parent"
            android:layout_height="45dp"
            android:layout_marginBottom="35dp"
            android:layout_marginLeft="15dp"
            android:layout_marginRight="15dp"
            android:background="@layout/border_edittextview"
            android:gravity="center"
            android:hint="Type your favorite person's name"
            android:inputType="textPersonName"
            android:lines="1"
            android:maxLength="30"
            android:tag="edttxtLastName"
            android:textColor="#fff"
            android:textSize="20sp" />

        <Button
            android:id="@+id/btnCalculate"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:background="@layout/button_background"
            android:text="Calculate"
            android:textSize="20sp"
            android:textStyle="bold" >
        </Button>
    </LinearLayout>
</ScrollView>

put a Linearlayout enclosing tag after scrollview.
Android really really awful .
Device info
Devcie: Xperia Z
OS: JellyBean
[ Dont know how it will behave in older versions.]


Change a page for other users by what a admin selects in a form in PHP

Question: I am stuck with a bit of a problem.
I have to build an application that shows everyone that visits the webserver a message which says if there is maintenance or a failure on the server.
Which of the 2 messages gets shown to the user depends on what the admin sets it to. This is done by clicking one of two buttons on the admin page.
I got it working to the point where if I click one of the two buttons on the admin page it redirects me to the index page and shows the right text.
My problem is that the choice I made is a one time thing and will not be saved.
Meaning that if anyone else visits the site he/she gets to see an empty index page.
I am not allowed to use a database to store the choice i made, so I will have to store the variable somewhere else.
But I have no idea how to save a variable without a database.
My code goes something like this:
Index.php:
if(!session_id()) session_start();

$filename = $_SESSION['filename'];

 $page = $_POST['sb'];
 // // echo $page;
 //
 if($page == 'Maintenance')
 {
      require './pages/index.html';
 }
 elseif($page == 'Failure')
 {
      require './pages/fail.html';
 }

Admin.php:
 if(!session_id()) session_start();
 //include("global.php");
 $_SESSION['filename'] = $page;

 require './functions.php';

 $page = $_POST['sb'];
 change();

Functions.php:
   if(!session_id()) session_start();
    $filename = "test";
    if(!isset($_SESSION['filename'])) {
        $_SESSION['filename'] = $filename;
    }
         echo '
' .
                   '<form method="POST" action="../index.php">' .
                   '<input class="button" type="submit" name="sb" value="Maintenance">' .

          '<input class="button" type="submit" name="sb" value="Failure">' .
           '</form>' .
           '
';
}

Comment: You can just persist the state with a simple toggle in the `$_SESSION` variable
Answer: I would recommend using a txt file as a place to store your data and retrieve it in the index file to display the correct page.
Posting "sb" to txt file on server:
<?php
if($_POST['sb'] != ""){
$file = fopen('sbstore.txt', 'w');
fwrite($file, $_POST['sb']);
fclose($file);
}
?>

Retrieving data from txt file on server:
<?php
if (filesize('sbstore.txt') != 0){
$txt_file = file_get_contents('sbstore.txt');
$sb = $txt_file;
} else {
$sb = "Default";
}
?>

Comment: Thanks for your help, but this is not working at the moment. I have placed the top code in the page where the button is clicked, but when I click a button it does not create a file. I also tried making the file myself but it does not write in this either. Do you have any idea what could be wrong?
Comment: I just tried it on my localhost on my laptop and it does work there, so I guess I will have to figure out why it does not work in the actual project. But thanks  anyways.


how should I play this notes?

Question: In what order should I play this on piano? Where exactly metronome tick should appear?
4&1 - 3 - 2  begin with metronome tick
4 - 3 - 2&1 end with metronome tick
4 - 3 - 2 - 1 start or stop with metronome tick
Answer: In this case, I think the rhythmic integrity of the RH melody should prevail, the arpeggio should lead into it.
If we can not be completely ruled by the 'tick' and play a little more freely, it wouldn't be unreasonable to start the arpeggio on the beat, giving emphasis to the melody note by delaying it a little.
Not 5 times in 8 bars though!  Arpeggio before the beat, melody on it.  Final answer.
Answer: The initial 8th notes in the left hand are like a written-out, slow, arpeggio.
The arpeggios marked with wavy lines need to be faster than those 8th-notes, otherwise they will distort the rhythm so much that it "falls apart" and listeners can't follow the beat at all, but the 8th-notes are a strong clue about how to play the arpeggios IMO.
If you interpret the notation literally, it would mean the second note of the two-note arpeggios goes on the beat, at the same time as the right hand note. However I would be inclined to play both notes of the arpeggio before the beat, following the pattern of the written-out 8th note "arpeggio". Otherwise, the two-note arpeggios sound a bit "lame and weedy" to my ears. For the three-note chords with arpeggios, maybe it makes more sense for the third (top) note to coincide with the right-hand note, on the beat, following the overall pattern.
For scores like this, you have to make up your own mind how "professional" the notation really is - does it literally mean what it says, or did the person who made it not have much in-depth knowledge, but just took whatever their notation software did by default as "good enough"? Sometimes, identifying which notation package they used (from give-aways like the music and text fonts being used, and more subtle clues from the default layout of the complete page or the note spacing) can be a forensic clue as to what the writer really meant. Even if the writer "knew" the difference in meaning between the arpeggio lines as written, and lines that spanned both staves, some notation software is more "friendly" about creating lines across both staves than others! It doesn't make sense to take what is on the page completely at its face value, unless you feel sure that the person who created it (whether the composer, or someone else) fully understood exactly what it meant.
For me (as a "nit-picker" about music notation!) the fact that the quarter-note rest in the pickup bar in the right hand is in the wrong position rhythmically (it should be vertically aligned with the first of the two 8th-notes in the left hand) is a clue that "this music isn't engraved to a professional standard, and/or it's not engraved with professional-standard software, so don't take everything else you see on the page literally" - but you might choose to take a different position from me over how much you read into "details" like that.

how should I play this notes?


Is indefinite integration suspect?

Question: In this post, Qiaochu Yuan remarks that 'it is convenient but misleading to write
$$
\int f(x) \, dx=g(x)
$$
[where the derivative of $g$ is $f$]'. This sentiment seems to be shared by many contributors here, and I don't understand why. To me, both definite and indefinite integration are both valid operations you can perform on a function, and there is nothing suspect about indefinite integration.
I know about the fundamental theorem of calculus, which (as far as I understand) explains the link between indefinite and definite integration. If by integration we mean computing the area under the graph, the fundamental theorem of calculus shows us that integration is the opposite of differentiation, since
$$
\frac{d}{dx} \int_{a}^{x} f(t) \, dt = f(x)
$$
This shows that every continuous function has an antiderivative. Since a clear link between integration and antidifferentiation has been established, we give the antiderivative the convenient label 'indefinite integral'. (This also explains why the definite and indefinite integration notations are so similar.) This label is fine, so long as we remember that integration is defined as finding the area under the graph, while antidifferentiation is defined as finding the inverse of the derivative.
Another result of the fundamental theorem of calculus is that
$$
\int_{a}^{x}f(t) \, dt=\int f(x) \, dx
$$
So obviously every indefinite integral can be rewritten in terms of definite integrals, but I don't understand the motivation behind this. If $F$ is an antiderivative of $f$, then why is it more correct to write
$$
\int_{a}^{x} f(t) \, dt = F(x) \, ,
$$
compared to
$$
\int f(x) \, dx = F(x) \, ?
$$
Comment: I don't imagine that anyone is questioning the validity of integration.  But writing the indefinite integral that way $A$. obscures the nature of $x$ as a dummy variable for integration and $B.$ incorrectly suggests that there is only one function $f$ that might be used there.  Would you, say, write both $\int x\,dx = \frac {x^2}2$ and $\int x\,dx = \frac {x^2}2+1$ ?  I assume you see the problem with that.  Much better to write, e.g., $\int_a^x g(x)\,dx = f(x)$ or, better, $\int_a^x g(t)\,dt = f(x)$
Comment: Saying $\int f(x)dx = g(x)$ is equivalent
to saying that $\int f(t)dt = g(x).$  Then, you are left wondering: how can
this be, since there is no relationship between $x$ and the dummy variable
$t$.  Then, you avoid the formality of $\int_a^x f(t)dt = g(x)$ by the
very narrow interpretation of $\int f(t)dt = g(x)$ as only signifying that
$g'(x) = f(x).$
Comment: I like to think that you can use that notation, but then you have to be careful to realize that "$=$" means something different. You might find [this answer to a previous similar question](https://math.stackexchange.com/questions/3767159/how-should-one-understand-the-indefinite-integral-notation-int-fx-dx-in/3767192#3767192) useful.
Comment: Suppose $f(x)=\sin(x) \cos(x)$.  One person might find an anti-derivative of $\frac12 \sin^2(x)$.  Another might find $-\frac12 \cos^2(x)$. A third might get $-\frac14 \cos(2x)$. These are obviously different (the first is  non-negative and the second non-positive) but they are equally correct (or incorrect) and they differ by constants
Answer: Basically, there's a type error: "$\int f(x)\,dx$" is a perfectly meaningful thing, but that thing is not a single function - rather, it's a set of functions.
The point is that a function doesn't have a unique antiderivative. For example, ${x^2\over 2}$ is an antiderivative of $x$ (with respect to $x$ of course), but so is ${x^2\over 2}-4217$. It's not the indefinite integral which is suspect, but rather the notation we use around it - specifically, the way we use "$=$." Properly speaking, $\int f(x)dx$ refers to a set of functions.
This is generally addressed by including a constant of integration, so that we write $$\int x\,dx={x^2\over 2}+C$$ to mean "The set of antiderivatives of $x$ is the set of functions of the form ${x^2\over 2} + C$ for $C\in\mathbb{R}$."

That said, blindly adding a constant of integration still doesn't always fix the problem: let $f(x)=-{1\over x^2}+1$ if $x>0$ and $-{1\over x^2}-1$ if $x<0$; what's the derivative of $f$, and does $f$ have the form $-{1\over x^2}+C$ for some fixed real number $C$?
Comment: I like this example calculation:
$$
\int \frac1x \, dx
= \int 1 \cdot \frac1x \, dx
= x \cdot \frac1x - \int x \cdot \left( -\frac1{x^2}\right) \, dx
= 1 + \int \frac1x \, dx
$$
It looks like this gives $0=1$ after subtraction of $\int \frac1x \, dx,$ but this calculation rather exemplifies that the equal signs should rather be equivalence signs; $u \equiv v$ if $u'=v'$.
Comment: @Joe Yes. And even then a single constant of integration might not be enough; see the end of my answer, or see Randall's answer.
Comment: Hi Noah. Thank you for posting this answer. Could you please clarify that I understand it correctly? I'll do my best to summarise your points. If we interpret the statement $$\int f(x) \, dx = F(x)$$ literally, then it is false: the LHS represents a set of functions, whereas the RHS refers to one particular function. Even if we write $$\int f(x) \, dx = F(x)+C$$ we still have to interpret the RHS as referring to all possible values of $C$, rather than just one value.
Comment: Oh yes. I forgot about that. Also, it occurred to me that I might be abusing notation in another way. Technically, $f$ is the function, whereas $f(x)$ refers to $f$ evaluated at a particular point $x$. So, if we were being *really* pedantic, $$\int x^2 dx = \frac{x^3}{3}+C$$ means that the set of functions, where each function is defined on connected interval(s) by $\frac{x^3}{3}$ plus some constant, have a slope of $x^2$ at the point $x$ for all $x$. Is that right?
Comment: @Joe No - in my experience when we write "$\int f$" with no further decoration, we're looking at antiderivatives which are defined on as large a domain as possible. The set you're describing is the union of the sets of the form $\int_If(x)dx$ for $I$ a connected interval.
Comment: So "$\int x^2dx={x^3\over 3}+C$" means that $(i)$ every function of the form ${x^3\over 3}+C$ for $C\in\mathbb{R}$ is an antiderivative of $x^2$ w/r/t $x$ and is not the proper restriction of any antiderivative of $x^2$ (that last bit is vacuous here since each such function happens to be defined on all of $\mathbb{R}$), and $(ii)$ every such "maximally defined antiderivative" is of the form ${x^3\over 3}+C$ for some $C\in\mathbb{R}$.
Comment: Thanks, that clears up my confusion. So the function we are looking for has to be defined on the same domain as $f$ (or on a larger domain). Is *that* correct?
Comment: Isn't this the same kind of "suspect" as $\sin(x) = x + O(x^3)$?
Comment: @FedericoPoloni Yup. I hate hate *hate* **hate** **HATE** that notation. (hem)
Comment: Out of curiosity, why the downvote?
Comment: I realise that this is quite an old post now, but I'm still not exactly sure about the status of the variable $x$ in the integral $\int f(x) \, dx$. I'm sorry if what I'm asking doesn't make much sense. After Qiaochu posted his answer, he said that one of the main problems with writing $\int f(x) \, dx = F(x) + C$ is that $x$ is being used in two different ways—as a dummy variable, and as a free variable representing the input of a set of functions. So writing $\int x^2 \, dx = \frac{x^3}{3} + C$ is misleading because...
Comment: ...the $x$ on the LHS is doing two jobs: it is a dummy variable that serves to tell us that we are trying to find the antiderivatives of the function $f: x \mapsto x^2$; but it is also the point at which we are evaluating the antiderivatives. Hence, it might be more logical to write something such as $\left(\int t^2 \, dt\right)(x)=\frac{x^3}{3}$, meaning that $x$ is not being used in two different ways. I tried asking Qiaochu about this but he didn't reply. Do I understand things correctly?
Comment: @NoahSchweber: And if we wanted to define the indefinite integral formally, we could define it as the set $\{F\mid F' = f\}$. Then, it can be shown as a theorem that if $S$ is one antiderivative of $f$, then every antiderivative of $f$ must be of the form $F:x \mapsto S(x)+C$, where $C$ is a function that is constant over a connected interval.
Answer: The other answers have made good points about constants of integration but this is not actually what I meant, although it is related. What I meant is what lulu says in the comments: writing antiderivatives this way misleads you about the relationship between the $x$ on the LHS (which is a dummy variable) and the $x$ on the RHS (which is not). The "real" $x$ on the LHS is one of the bounds of integration, which is being suppressed in the notation.
The sense in which this is misleading becomes clearer once you start considering double integrals, which is the context of the question you link to. If it makes sense to write $\int f(x) \, dx = g(x)$, then surely it also makes sense to write $\int g(x) \, dx = h(x)$, right? Then does it make sense to write
$$\iint f(x) \, dx \, dx = h(x)$$
or not? What do you think?
Comment: @Joe: A helpful way of seeing whether a variable is a "dummy" is asking whether it would make sense to plug in a value for it.  Does it make any sense to say "take $\int x\,dx$, then plug in $x=3$, to get $\int 3\, d3$"?  No!  If you're thinking of $\int x\, dx$ as a function (or, better, a set of functions), and you want to see what the function does at 3, you don't plug 3 in for $x$, you put 3 in as the upper limit of integration.  So $x$ is *not* the variable representing the input of the function.
Comment: @Joe: please pay attention to the words I'm using; you've claimed I said indefinite integration is "suspect" or "inaccurate" and that's not what I said, I said "misleading" and I meant "misleading." It's misleading precisely because the LHS does not *appear* to contain a dummy variable, but in fact it does. The LHS is shorthand for an integral of the form $\int_a^x t \, dt$ where $a$ is a constant and $t$ can be replaced by any other dummy variable. People implicitly understand this and it's mostly fine for single integrals but gets confusing for double integrals.
Comment: @Joe: the $x$ in $\int f(x) \, dx$ is a dummy variable because it's been integrated over; the "real" $x$ is the upper bound of integration, which is why it's more accurate to write this integral as $\int_a^x f(t) \, dt$ (and $t$ can be replaced with any other dummy variable). This issue already arises when you consider definite and indefinite sums; the partial sum $\sum_{k=0}^n f(k)$ is a function of $n$ because $n$ is the upper bound of the sum, and $k$ is a dummy variable; after it's been summed over it no longer appears.
Comment: Another way of looking at this might be: when we write $f(x)=g(x)$ there's an implicit quantifier that this is true for all $x$. So we have $f(1)=g(1)$, $f(7)=g(7)$, $f(\pi)=g(\pi)$, and so on. But when we write $\int x\,dx = x^2/2+C$ we wouldn't then conclude that $\int 3\,d3=9/2+C$...
Comment: @Joe: it's exactly the same as the summation example. Maybe it's clearer if we change the "real" variable: $\int_0^y f(x) \, dx$ is a function of $y$, not $x$, because $y$ is what appears in the bounds of the integral. The $x$ has completely disappeared. Yes?
Comment: @Joe: it's not a matter of definitions, it's a matter of notation. The advantages are as I described: the $x$ is in the correct place, and the dummy variable is correctly treated as a dummy variable, which is less confusing for various reasons. It's the same reason we write $f(n) = \sum_{k=1}^n g(k)$ and not $f(n) = \sum_{n=1}^n g(n)$; here $k$ is the dummy variable.
Comment: Agree – the problem with the antiderivative-notion of indefinite integral wouldn't be so bad if it only were for integration on the real line, but it just doesn't scale to higher dimensions. In more advanced context, one very often considers something of the form $\int_\Omega\!\mathrm{d}x\:f(x)$, where $\Omega$ may be some subset of $\mathbb{R}^n$ or some manifold / Lie group or whatever – no problem for integration, but antiderivatives? No way.
Comment: And double integrals were the context for the question you linked to; you haven't addressed that part of my response at all.
Comment: The last point you make in the post is one of the key objections to this notation IMO. I see new student quite often do this mistake: they substitute $f(x) = \int g(x)dx$ into  $\int f(x) dx$ and end up with something that makes absolutely no sense and don't see where things went wrong. So even if the expression is fine to use when communicating with people that really understands the meaning of it, it is a source of error and leads to confusion for people new to integration so "misleading" is a very appropriate characterization.
Comment: @QiaochuYuan OK, I think I understand now. So we want $\int f(x) \, dx$ to represent a function (or, to be more precise, a function evaluated at $x$—I think). But there is no way to plug in $x=3$, for instance, into $\int f(x) \, dx$. By contrast, we can write $\int_{a}^{3} f(t) \, dt$ if we use the notation you suggested. Unfortunately, as someone who has never studied multivariable calculus before, I don't see much of a problem with $\iint f(x) \, dx \, dx = h(x)$, other than the problems in the single integral case. Are you saying that things get much more confusing with double integrals?
Comment: @QiaochuYuan And thank you, this has really helped me get a better grip on the notation surrounding integrals.
Comment: @Joe: yes, that's a good example, you can't plug a number into a dummy variable because it's already been "used up." It isn't *much* of a problem in the single-variable case; as I have already said, the original context of the quote you asked this question about was about a multivariable integral. If that isn't relevant to you then don't worry about it.
Comment: Hi Qiaochu. Thank you for clarifying your comments. I have one question, though: why is the $x$ in $\int f(x) \, dx$ considered a dummy variable? To me, the statement $$\int x \, dx=\frac{x^2}{2}+C$$ means that the function $f$ defined by $f(x)=\frac{x^2}{2}+C$ has a slope of $x$ at the point $x$ (for all $x$). When you say 'dummy variable', do you mean that I could just as well write that the function $f$ defined by $f(y)=\frac{y^2}{2}+C$ has a slope of $y$ at the point $y$?
Comment: @QiaochuYuan I understand what you mean in the summation example, but I'm still a little unsure about integrals. I'm sorry to bother you, but could you go into a bit more detail about how the $x$ in $\int f(x) \, dx$ is a dummy variable? I don't see how that immediately follows from the fact that the $x$ is being integrated over.
Comment: @QiaochuYuan Yes, that makes sense. But I don't understand how this makes the other notation inaccurate. If we write $$\int x \, dx = \frac{x^2}{2}+C \, \text{,}$$ then the LHS does not appear to contain a dummy variable, and I don't understand why it *should* contain one. Doesn't this notation correctly suggest that the slope of $f$, defined by $f(x)=\frac{x^2}{2}+C$ has a slope of $x$ at the point $x$? Here, $x$ seems to mean a genuine point on the graph of $y=\frac{x^2}{2}+C$—it's just that it's arbitrary which point we choose. And so to me it doesn't seem like $x$ is a dummy variable.
Comment: @QiaochuYuan I'm sorry, I didn't mean to misrepresent what you were saying. The reason I haven't mentioned double integrals is because I haven't studied multivariable calculus at all. So are you suggesting that we define $\int f(x) \, dx$ as $\int_{a}^{x} f(t) \, dt$? If so, what are the advantages of this, and is it possible to define the indefinite integral as a set of antiderivatives instead?
Comment: @QiaochuYuan: Sorry to bother you again, but are the following hypothetical notations *also* less misleading? If $f$ is an integrable function, then we could denote its set of antiderivatives as $\left(\int f\right)(x)$ (where $\int f$ is not a function but a multifunction). Or, perhaps, $\left(\int f(t) dt \right)(x)$, where $t$ is a dummy variable, meaning that the variable $x$ is not being used in two different ways. For instance, we could write $\left(\int t^2 \right)(x) = \frac{x^3}{3}+C$ (where the $C$ notation implicitly denotes a set of antiderivatives).
Comment: If you find the time to respond to my question, then I'd be very grateful. But don't worry if not.
Answer: For one example, the familiar old "formula"
$$
\int \frac{1}{x} \ dx = \ln|x| + C
$$
is false (unless you define the indefinite integral VERY carefully).  This purports to say that any antiderivative of $f(x) = \frac{1}{x}$ must take the form $F(x) = \ln|x|+C$ for some fixed constant $C$.  But this is only true over a connected interval.  For example, the function
$$
G(x) = \begin{cases} \ln|x| +1, & x < 0\\ \ln|x|-1, & x > 0\end{cases}
$$
satisfies $G'=f$, even though it is not expressible in the form $\ln|x|+C$.  Done right, we should only define indefinite integrals over intervals (this is due to the Mean Value Theorem).
Comment: It can be repaired by allowing $C$ to be a locally constant function and not just a constant. This is a very simple instance of de Rham cohomology, in this case the zeroth de Rham cohomology $H^0_{dR}(\mathbb{R} \setminus \{ 0 \}, \mathbb{R}) \cong \mathbb{R}^2$.
Comment: @QiaochuYuan Discussed in detail [here](https://math.stackexchange.com/a/2218109).
Comment: And, of course, things get even worse if you try to extend this antiderivative to the complex plane.
Answer: I think one clear way to see this is that the most pedantic notation would be something like this:
$$
f(x) \in \int f'(x)\,dx
$$
You just have to think of $f$ as some element in a vector space, e.g. $f \in C^1(a,b)$, the set of continuous functions with continuous first derivative. So the integral operator is a linear transformation, a map of the kind $\int_a^x: C(a, b) \rightarrow C^1(a, b)$. This makes evident that the writing $$F(x) = \int f(x)\,dx,$$ where $F'(x) = f(x)$, could easily be notation abuse, though most of the time it's not the case, as the others have pointed out. The writer knows what they're writing: they assumed $F$ as a stand-in for a whole set of functions, but this is not always clear to the reader. Another problem this brings to surface is that the integral operator $\int_a^x$ as it has been written above is ill-defined, as it should point one element $f \in C(a,b)$ to one element $g \in C^1(a,b)$, not to a whole set of them. How to define this integral operator soundly is a question above my paygrade.
Answer: If we define a function $F(x)$ as the antiderivate of the function $f(x)$ then by FTC we see that:
$$\int_a^xf(t)\,dt=F(x)-F(a)\neq F(x)\forall f(x)$$
The problem lies in that for a given known derivative, $F'(x)=f(x)$, there are many different equations which satisfy $F(x)$ which differ by a constant, often notated by${}+C$. This can be seen in many cases where people neglect this "constant of integration":
$$\int\frac{1}{ax}\,dx=\frac{1}{a}\int\frac 1x\,dx=\frac1a\ln|x|+C_1$$
$$\int\frac1{ax}\,dx=\frac1a\ln|ax|+C_2$$
which at first seem completely different but when the correct values of $C_1,C_2$ are chosen these are the same, see?

I think the point that the post is trying to make is that while in many scenarios it is easy to define a new function as the antiderivative of another, some may find this as misleading by thinking there is only one function $g(x)$ which satisfies these conditions, when in reality it is what we call a "family" of similar functions
Answer: Setting the math of it aside, there is a real pedagogical/linguistic problem.
New students (reasonably) think the "Definite" and "Indefinite" integral are two variations on the same phenemonenon, whereas in fact the former is the phenemonon and the latter is notation that makes the former easier to compute.
In particular, the Fundamental Theorem of Calculus looks tautological the first time students see it, since they already "know" that integrals are anti-derivatives.
Comment: Do you mean that the only reason antiderivatives are useful in the first place is that they help us compute areas? If so, that would make sense: both derivatives and integrals tells us about slopes and areas, but the antiderivative, in of itself, doesn't seem to be very useful.
Answer: Mark.
Basically, the information provided by that book has been summarized in former answers to the original question of this conversation. If you can consult Chapter 5 of that book, you may find the main ideas:

there is a distinction between "antiderivatives" and "primitives":
an antiderivative is ONE solution to the equation $\int f(x) dx = g(x)$  where g(x) is the unknown solution, while the primitive is the set of all solutions to the same equation.
Moreover, it is convenient to regard the equation $\int f(x) dx =g(x)$ as a differential equation f(x) = g'(x), which, formally, has nothing to do with (definite) integration, although definite integration is a very important tool in developping theoretic antidifferentiation results (such as the existence of a solution to f(x) =g'(x) when f(x) is continuous on an interval).

the set of all solutions to f(x) = g'(x) is connected with the constant of integrations, and constant of integrations are realted to the shape of the domain of f(x). A basic example has been already provided:  if f(x) = 1/x, then all solutions are
g(x)= log|x| +C(x), where C(x) is a function  constant on (-\infty,0) and constant on (0,\infty)   (this type of functions are called locally constant in that book); for instance, g(x) = log|x| if x<0 and g(x) = log|x| - 5 if x>0 is one of the solutions.

chapters 9, 10, 11 and 12 deal with standard functions (trigonometric, binomial differentials, etc) and there, dealing with integrations constants is the main issue.
Summarizing a lot, is something else than a mechanical implementation of formulas as most of books do.

Is indefinite integration suspect?


Translation of 0-dimensional objects

Question: As far as I can understand we can think of any line on a plane as a product of translation of some other arbitrary line by some arbitrary vector (and vice versa). But while it makes sense when we talk about lines, I cannot imagine the same procedure for dots. Is it even "possible" to translate a dot such that its origin and a translated "copy" would define a line?
Comment: When you talk about "points", "vectors" and "translating point by some arbitrary vector", it means you are dealing with some [affine space](https://en.wikipedia.org/wiki/Affine_space); I would suggest you take a look at this wikipedia page.
Answer: Any point is a translate of any other point:
$$y = x + (y - x).$$
Taking any two points $x_0\ne y_0$ of a line, the line can be written as the set
$$\{x_0 + t(y_0 - x_0)\,\vert\,t\in\Bbb R\}.$$

Translation of 0-dimensional objects


Retorno do conteúdo por cURL

Question: Estou desenvolvendo um gerador de boletos automático, utilizando uma ferramenta disponibilizada pelo banco Banrisul.
Para gerar esse boleto automático preciso enviar uma requisição através da seguinte URL:
    https://ww8.banrisul.com.br/brb/link/Brbw2Lhw_Bloqueto_Titulos_Internet.aspx
Os dados que informei nesse link são fictícios, gostaria de saber qual a melhor forma de obter o retorno desse boleto gerado automaticamente por cURL? Como posso fazer para que o boleto seja aberto de forma que facilite a impressão?
Obrigado.
Comment: Dificil dizer o que é melhor neste caso, depende da aplicação. Na dúvida, só disponibilize um link/botão e ponha um aviso embaixo dizendo que o usuário será direcionado ao sistema do banco. Tem coisa que não compensa complicar.
Comment: Explique pra ele que o site usa um frame gerado por javascript, etc... (quem sabe ele não entenda e desista de complicar :) )
Comment: Bom, você vai ter um pequeno complicador neste caso, pois o conteúdo do boleto em si é gerado num frame e chamado por JS. Se você simplesmente pegar o resultado do cURL, não vai ter o boleto.
Comment: @Bacco o certo seria criar uma pop-up então?
Comment: @Bacco Entendo, tentei de várias formas obter uma resposta para esse problema, pois o Gerente solicitou algo diferente do que terá que ser feito. Por isso a minha pergunta aqui no StackOverflow.
Comment: @Bacco vai ter que ser assim mesmo. Obrigado pela ajuda
Comment: Para ler a página que roda JavaScript para ser gerada eu usei uma vez essa lib https://github.com/mikehaertl/phpwkhtmltopdf.
Comment: Por que é muito ampla a minha pergunta?
Comment: Pegue o action do form, e os campos que o form possui. Monte um CURL com o conteúdo exatamente igual. Inspecionar o elemento e verificar a aba network pode ajudar a ver o que o form atual envia e para onde envia

Após montar um CURL que simule exatamente o form, voce terá o resultado direto, onde poderá recuperar a URL que o banco disponibiliza para o boleto

Tente usar a aba network do navegador, e veja todas as ações que a pagina faz, e vá fazendo exatamente igual com CURL
Answer: Tome cuidado com o CURLOPT_SSL_VERIFYPEER ele de ser setado para true para verificar a conexão segura (já sofri muito com isso).
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);

Segundo, para exibir isso ai com o cURL basta recuperar a resposta do curl_exec e imprimir ela para seus usuários. Acho que não deveria alterar a opção de imprimir que o banco já disponibiliza, ele é boa e funciona bem em qualquer navegador.
Comment: A minha resposta está vindo vazia, o que poderia causar isso?

Teria algum exemplo para me dar que eu consiga imprimir na tela em uma modal?
Answer: Se entendi corretamente você está perguntando como faz para pegar o retorno do cURL.
Neste caso lhe recomendo utilizar a função curl_setopt, passando por parametro:

A conexão cURL
A opção CURLOPT_RETURNTRANSFER
1 ou true

Passando estas opções você informa ao cURL que o retorno da url deverá voltar para você quando invocar a função curl_exec ao invés de ser exibido diretamente no browser.
Comment: Está me retornando um array vazio, o que pode ser?
Comment: Provavelmente está ocorrendo algum erro.
Para testar por erros tente o seguinte:
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, ...OPCOES QUE EU QUERO CONFIGURAR....);
    $retorno = curl_exec($ch);
    $erro = curl_errno($ch);
    $erroMsg = curl_error($ch);
Answer: Sobre a impressão, o Banrisul já disponibiliza um link na página gerada com essa funcionalidade.
No seu caso, eu abriria o link num pop-up e deixaria a pessoa clicar no imprimir.
Comment: A ideia é ter uma opção de confirmar inscrição e imprimir/enviar por e-mail o boleto, por isso comentei sobre pegar somente o boleto.

Retorno do conteúdo por cURL


Is f(z)=1/z truly an analytic function

Question: For an analytic function $f(z)$, we have $$\frac{\partial f}{\partial \bar{z}}=0.$$ Consider the function $f(z)=\frac{1}{z}$, which, at first sight, is a bona fide analytic function. However, we can write it as $$f(z) = \frac{\partial}{\partial z} (\ln z + \text{const}),$$ where const is any expression that doesn't depend on $z$. So, let's take $\text{const}=\ln \bar{z}$ so that $$f(z) = \frac{\partial \ln z\bar{z}}{\partial z}.$$ Now the condition that $f(z)$ is analytic takes the form $$\frac{\partial^2}{\partial z \partial \bar{z}} \ln z \bar{z} = 0.$$ However, by employing the cartesian coordinates, we see that this is exactly the 2D Green function for laplacian $$\frac{1}{4} (\partial_x^2 + \partial_y^2) \ln (x^2 + y^2) = \pi \delta(\vec{r}).$$
My question: how can a perfectly decent analytic function $f(z)=\frac{1}{z}$ secretly depend on $\bar{z}$? I presume that there is a deep connection with the residue theorem?
Comment: $\overline z$ doesn't depend on $z$? So what is the value of $\overline z$ to two significant figures?
Comment: Well, $$f(x)=\dfrac{1}{z}=\overline{\dfrac{1}{\overline{z}}}$$
Comment: "However, we can write it as..." No.
Comment: @bof I don't understand your question. And yes, $\bar{z}$ and $z$ are linearly independent.
Comment: @LittleBrownOne Then we're even, because I didn't understand your question. You set $\text{const}=\ln\bar z$ as if you think $\ln\bar z$ is a constant, but in fact $\bar z$ and $\ln\bar z$ are functions of $z$; you can't tell me their values unless you know the value of $z$.
Answer: A word of caution: $\dfrac{1}{z} \neq \dfrac{\partial}{\partial z}\log(z)$. These are inherently different functions due to domain of definition. $\log(z)$ is only well-defined if you make a branch cut, which means that you are eliminating an entire ray emanating from the origin from your domain but $\dfrac{1}{z}$ is well-defined for all $z\neq 0$. This can likely be remedied by an Identity Theorem type argument though so it's not a big issue.
Furthermore, $\frac{1}{z}$ is not holomorphic everywhere and so we can expect weird things to happen sometimes which is the crux of your post. When introducing $\log(\bar{z})$, you are implicitly assuming that $\bar{z}\neq 0$. In this setting, what you get is that the Laplacian of $\log(z\bar{z})$ is zero which you should expect. If $z=0$, none of what you did makes sense from the get-go (since $\log(\bar{z})$ is undefined!) so your oddities really only exist because you're not treating your functions as you should.
To add on to this post: the appearance of the Dirac delta is not surprising and does indeed get reflected in the Cauchy integral formula. You can view the Cauchy integral formula as the line integral portion of Green's (first? second?) theorem (from which the Green's function appears quite naturally). Saff does this treatment which really gives complex analysis a huge boost because it relates directly to vector analysis in some ways.
Really you should treat the Dirac delta not as a function but as what it does in integration. As a function, $\dfrac{\partial^2}{\partial z\partial\bar{z}}\log(z\bar{z}) = 0$ but when you do closed contour integrals of functions against $\log(z\bar{z})$ you end up not getting zero which is where the Dirac delta property comes into play and the Dirac delta property all in one fell swoop.
Answer: If f is function like $Re^{i \theta}$, that constant can vary depending on your choice for domains for the angle, and thus not be equal to $\bar z$. They can map similarly, but the functions are not equal.
Comment: Welcome to stackexchange. It's good that you want to contribute here - but not particularly useful in this case, when you are providing a short somewhat cryptic answer to a three year old question that has a long, detailed accepted answer. It's more helpful to pay attention to new unanswered questions.

Is f(z)=1/z truly an analytic function


Adding column in Views for completed submission plus several days

Question: A have a table column using Views from Webform submission. The variable of this column is submission date [completed].
I need to create another column showing another date [completed] + 7 days.
I tried Global: Math expression
[completed]+7
but it does show the correct date but another value.
How can I display [completed]+7 in another column.
Answer: I have solved my own problem. Using Views PhP module.
Add field Global:PHP,
in the output code box:
<code><?php
$correctdate = $row->completed;
$correctdate1 =strtotime("+7 days", $correctdate);
$cdate = date("j/n/Y - g:i a", $correctdate1);
echo ($cdate);
?>
</code>


Opening a new command prompt and writing to it in Java

Question: The idea behind this is that I have a main class that acts as an agent, constantly running and waiting for instructions. Then, the agent gets instructed to launch n instances of another class which plays a monitoring role.
Since each instance of the monitoring class is going to be doing heavy printing (plus the fact that the agent class also prints a little bit), I would like for each instance to have its own command window to do all its printing to.
Is this possible? If not, I welcome suggestions on how to get a similar effect.
Thank you.
EDIT: I feel like some clarification is in order. I want to start a new command/terminal window per monitoring instance and regularly write to that window.
I would obviously love to be able to run this on any machine,  but at least I'd like to it to be able to work on Windows.
I know that there are some GUI libraries available (AWT, Swing) but I want the application to be as lightweight as possible, so that I can maximize the number of monitors that I can have on each computer. I will use a GUI library only if I have no other option.
Comment: Just to see if I understood, what you want is your application to open a new console window for each monitor class, right?
Comment: Yes, open a new console window and having each instance regularly print stuff to its window.
Answer: First of all, if an instance is running for a long time and you may require multiple of those running at the same time, you will need to implement multi-threading. In particular, look into concurrency: http://docs.oracle.com/javase/tutorial/essential/concurrency/
Next, once you figure out how to run each instance in a separate thread, you simply access Runtime:
<code>Runtime RT = Runtime.getRuntime();
RT.exec("cmd.exe /c start command", null, new File(newDir)); // for example
</code>
Comment: Wouldn't that just execute once and leave me no way to write to that command window again?
Answer: There are plenty of GUI libraries that can do what you want. AWT is one see AWTConsoleWindow. Or this one.
Comment: To be honest, I was trying not to use a GUI library because I want my application to be as lightweight as possible in order to maximize the number of monitoring instances that I can run. I will consider it if I have no other option.
Comment: I am not aware of any way that would be platform independent without using a library like this.
Comment: What about Windows specific?
Comment: You can with JNI but I really don't recommend it.


Redirect 301 com web.config

Question: Estou atualizando um site, e as URLs vão mudar. Então, preciso fazer um redirecionamento 301 com web.config, mas não consegui. Abaixo o código que montei:
<configuration>
    <location path="site-antigo">
        <system.webServer>
            <httpRedirect enabled="true" destination="site-novo" httpResponseStatus="Permanent" />
        </system.webServer>
    </location>
</configuration>

O que eu esperava que ocorresse com esse código:
Ao acessar a página http://meusite.com.br/site-antigo o usuário seria redirecionado para http://meusite.com.br/site-novo, mas isso não está acontecendo. Estou fazendo algo errado?
Answer: Neste caso vc deve precisar usar o url rewrite module.
<rewrite>
  <rules>
    <rule name="Redirect from blog">
      <match url="^site-antigo" />
      <action type="Redirect" url="site-novo" redirectType="Found" />
    </rule>
  </rules>
</rewrite>

Comment: Mas tem o mesmo efeito de um redirect 301? O Google entende isso?
Comment: [Segundo consta na documentação, sim.](https://docs.microsoft.com/en-us/iis/extensions/url-rewrite-module/creating-rewrite-rules-for-the-url-rewrite-module/_static/image21.jpg) Mas sugiro confirmar no console do navegador, pois vai depender das configurações feitas. Usar o `IIS Manager` tb pode ser bem útil :)

Redirect 301 com web.config


Prove the inverse of the Hilbert matrix has integer entries

Question:
$1 \frac{1}{2} ... \frac{1}{n}$
$\frac{1}{2} \frac{1}{3} ... \frac{1}{n+1}$
$.$
$.$
$.$
$\frac{1}{n} \frac{1}{n+1} ... \frac{1}{2n-1}$
Does the inverse of this matrix have integer entries? Prove your
  statement.

I thought of  multiplying every line $i$ by $i!$, but it leads to a very complicated solution (if it leads to a solution at all).
Source: Linear Algebra, Kenneth Hoffman and Ray Kunze. Section 1.6, exercise 12.
Comment: Honestly, I don't know, however, you can try for a couple of n values and see what happens. I know, it is not a proof, but maybe at least a start
Comment: Yes, it does. $\textbf{}$
Comment: Have you tried to work through the example referenced in the problem statement in more generality? (For others reading this: this reference is omitted in the question as written here, but it appears in the book.)
Comment: The reference is not important, since it's just the case when n equals 3.
Comment: @user68659 It's important in the sense that understanding it is the key to doing the exercise.
Answer: The answer to your first question is yes.
Do not dismiss the example referenced in the problem statement (the case where $n = 3$). Examples like the one I'll reproduce below help to build insight:

Given $\quad A=\begin{pmatrix}1 & \frac{1}{2} & \frac{1}{3} \\ \frac{1}{2} & \frac{1}{3} & \frac{1}{4} \\ \frac{1}{3} & \frac{1}{4} & \frac{1}{5}\end{pmatrix},\qquad$
  $A^{-1}=\begin{pmatrix} 9 & -36 & 30 \\ -36 & 192 & -180 \\ 30 & -180 & 180 \end{pmatrix}$.

I'd suggest you explore the matrix and its inverse for $n = 4$.
What we want to show is that
$B=\begin{pmatrix} 1 & \frac{1}{2} & \ldots & \frac{1}{n} \\ \frac{1}{2} & \frac{1}{3} & \ldots & \frac{1}{n+1} \\ \ldots & \ldots & & \ldots \\ \frac{1}{n} & \frac{1}{n+1} & \ldots & \frac{1}{2n-1}\end{pmatrix}$
is invertible and $B^{-1}$ has integer entries.
Hints to get you started: The matrix $B$ is known as a Hilbert matrix and the entries of its inverse can be represented as the product of binomial coefficients.
Comment: It is about 24 years left I read this book at my MSc (+1).
Comment: I had to brush the dust off my copy, @Babak!
Comment: @amWhy: Needs another TU! +1
Comment: Could you add the actual proof? I think posting one using only the tools developed so far in the book would be instructive.


Multiple-enabled Select Causing Server-Side Error

Question: I have a form that I am passing to an apps script function. One of the form elements is a list box that allows the user to make multiple selections. Whenever one item is selected from the list box, the function (which uploads an image from another input element) runs fine, but whenever two or more items are selected, the function throws a failure. While the function never makes use of the list box, is there some reason why it being part of the form might cause issues with passing it into the function, and how can I fix it?
HTML snippets:
  <form id="classForm">

<input type="file" name="imageLoader" id="imageUpload" accept="image/*"      onchange="upload();">
<select multiple="true">
  <option>1</option>
  <option>2</option>
  <option>3</option>
  <option>4</option>
  <option>5</option>
</select>
</form>

Javascript:

The function (called from upload, which does some processing and then sends in the form):
function uploadFile(form) {
 // Name of folder where the files should be saved
var folderName = "AdImages";
var folder, folders = DriveApp.getFoldersByName(folderName);

//Find the folder, create if the folder does not exist
if (folders.hasNext()) {
  folder = folders.next();
} else {
  folder = DriveApp.createFolder(folderName);
}

// Get file from form as blob
var blob = form.imageLoader;
var file = folder.createFile(blob);

// Set the file description to something
file.setDescription("title");

//get picID

var picId = file.getId();

// Return the id of the picture, to be used to construct the previewable url
return picId;
}

Comment: What's the error message? A multi-select will give a comma-separated list of values, so you'd need to handle that - but what is the `upload()` function doing? Your snippets aren't enough to reproduce the problem, so it's hard to help you. [mcve]
Comment: Sorry about that -- I rebuilt a minimal version of the program to reproduce the problem and updated the details above. I went over the logs and no error message appears, but it still runs as though it's throwing the withFailureHandler.
Comment: I would recommend encasing your uploadFile() function in a try-catch statement and logging the message so that you can see exactly what is causing the error.
Comment: The exact error I receive is NetworkError: Form submission failed.
Answer: I solved the issue by wrapping the file input element in its own form. It's admittedly a hacky solution, but since I only need access to that one particular element for the function in question, it gets the job done.


can some one help me for set my amp for j-rock?

Question: I have started playing 1 week ago. I don't understand how to completely set my amp. Can some one help me for set my amp for j-rock?
I use blackstar id core 10. I use blackstar's amp software for amp settings:

(source: tonereport.com)
Comment: Please define j-rock?
Comment: @MrTheBard: Correct, but that's a pretty large genre. The OP might need to be more specific in terms of what exactly they are trying to achieve.
Comment: I believe that j-rock is Japanese rock.
Comment: @grumtaku, sounds like a good question for the Blackstar INSIDER community. Not sure, were the hid it, but you probably can find more insiders here: https://forum.blackstaramps.com/index.php .
Answer: I don't know what J-Rock is definitively as it could mean a number of things, however if you mean a 'metal' style rock guitar sound that I believe to be popular over there, then it can be quite simple:

Strip all of your pedals and effects, and turn all dials to zero;
Turn the volume up as far as it will go;
Keep the Bass and Treble dials high;
Turn down any 'Middle' dials until the sound becomes
scooped - bear in the mind that middle frequencies are important for
clarity, so find a decent compromise;
Bring up the gain until you get the sound you require;
Finally, bring the volume down to a more manageable level.

This will get you a lot of the way, but without any clearer description of what you want to sound like, then I can't offer any more help.


Pandas dataframe group by 10 min intervals with different actions on other columns

Question: I have a pandas dataframe which includes a timestamp and 71 other columns, something like this:
              timestamp           |close_price|highest_price|volume| ...
              2018-09-29 00:00:20 |1809       |1811         |  ... |
              2018-09-29 00:00:34 |1823       |1832         |
              2018-09-29 00:00:59 |1832       |1863         |
              2018-09-29 00:01:09 |1800       |1802         |
              2018-09-29 00:01:28 |1832       |1845         |
              .
              .
              .

I want to put the data into 10 min intervals and I want to do separate operations on each column, for example I want the 10 min intervals of close_price column to show the last value of the corresponding range in the real table, or for the highest_price column, I want the max value of the corresponding range, or for volume I want the mean of the values in that range. I already tried
dataTable = datefram.resample("10min").agg({'first_price':'first',
                                       'close_price':'last',
                                       'highest_price': 'max',
                                       'volume':'mean',
                                        #other attributes...
                                        })

but the result seems to be incorrect.
Is there any other ways to do what I want to do?
I will appreciate any comments or thoughts.
Note that there is no specific pattern in timestamp values. In 1 minute, we can have 0 to 60 rows.
Comment: How are the results incorrect? It looks like you're on the right track based on this similar question: https://stackoverflow.com/questions/68229747/resample-dataframe-calculate-min-max-and-first-and-last-of-different-columns-w
Comment: @ChrisSears thank you for your comment, Yeah it looks to be ok but the problem is that it I have 12808 rows in the input and 13207 rows in output.
Comment: Does your data span multiple days? If so, `resample()` could be creating output rows for overnight periods where you don't have any data points, leading to a lot of `NaN` values.
Comment: @ChrisSears OH, yes, you are right. I have so many ```nan``` values. could you please consider writing a simple answer so I can up-vote it?
Answer: If your data spans multiple days or periods where you don't have any data points, calling resample() can result in lots of additional rows with NaN values. I think your code is actually correct, you just got the wrong impression from seeing all the extra rows.
Comment: Thank you so much
Answer: Your approach is correct. The
 dataframe.resample("10min").agg() does the calculations for you.
You might get more outputs than what you expect and that is because of this: resample method continuously adds 10 minutes to the time and does the calculations that you asked. But if there was no data in any of the 10 min intervals, it creates a NULL row. Maybe your data is not continuous and causes this Null rows.
You can simply delete the NULL rows by using dataframe.dropna()


Find a basis for the subspace $M \in M_{2\times2} | MJ = JM^T for \space all \space J \in M_{2\times2}$

Question: $M \in M_{2\times2} | MJ = JM^T for \space all \space J \in M_{2\times2}$
Find a basis.
Let $A = \begin{bmatrix}a & b \\ c & d\end{bmatrix}$ and
$ J = \begin{bmatrix}e & f \\ g & h\end{bmatrix}$
Then from the condition of the subspace,
$ae + bg = ae +fb$
$af + bh = ec + fd$
$ce + dg = ga + hb$
$cf + dh = gc + hd$
Then from the first equation we get $ f = g$.
Replacing into the second (or third) equation just ends up with the same equation as the third (or second) one. And the fourth equation does not help either, since it gives $ f = g$ as well.
I am doing something wrong here but I can't figure it out, so some help is appreciated.
Answer: Hint
The best here is to consider specific $J$ and get some specifications for $M$. For example, take for $J$ the identity matrix. You get that $M$ has to be symmetric.
Then consider the $J$ matrix with coefficients equal to zero except one equal to $1$ and make some deductions.
Comment: I think I understand what you are saying. Since the condition states that the statement must be true for every J, a 2 by 2 matrix, then we can use specific J to determine the properties of M. Because if it did not work for one specific 2 by 2 matrix, then there would be a contradiction.

Following your hint, set $ J = \begin{bmatrix}0 & 1 \\ 0 & 0\end{bmatrix}$

and this leads to $ b = c = 0$

This coupled with the fact that M must be symmetric leads to
$ M = \begin{bmatrix}a & 0 \\ 0 & a\end{bmatrix}$.

and I am able to find the basis from there.
Comment: This is exactly what I meant.


Weak convergence of $f_n$ in $L^p$ implies that of $|f_n|$?

Question: I am wondering that if $f_n$ converge weakly to $f$ in $L^p(\mathbb R^d)$, for $1<p<\infty$ then also $|f_n|$ converge weakly to $|f|$ in $L^p(\mathbb R^d)$?
I think it is true but I do not know how to prove it.
Comment: Consider the unit vectors for $p = 2$. They converge to $0$
Comment: I do not understand. Can you explain more, please.
Answer: No, it's not true in general.
Consider $d=1$, $p=2$, $f_n(x)=\sin(nx)\chi_{(-\pi,\pi)}$, and $f(x)\equiv 0$. Riemann-Lebesgue Lemma implies $f_n \rightharpoonup f$. However, if we consider $g(x)=\chi_{(-\pi,\pi)}$, then one can compute that
\begin{equation}
\int^\infty_{-\infty} |f_n|g \,dx= \int^\pi_{-\pi} |\sin(nx)|\,dx=4\not\to 0 = \int^\infty_{-\infty} |f|g\, dx.
\end{equation}
Answer: Consider the Hibert space $l^2(\mathbb{R})$ of complex square summable real sequences. For each $n \in \mathbb{N}$ let $(e^{(n)}_i)_{i=0}^{\infty} \in \ell^2$ be defined by $e^{(n)}_i = 1$ when $i = n$ and $e^{(n)}_i = 0$ otherwise. Then $(e^{(n)})_{n \in \mathbb{N}}$ is a sequence in $\ell^2$ which converges weakly to $0$.
proof: Let $y:= (y_i)_{i=0}^{\infty} \in \ell^2$ be arbitrary, then $\langle y, e^{(n)} \rangle = y_n $ which converges to $0$ since $y$ is square summable.
However, for every $n \in \mathbb{N}$ we have $\Vert e^{(n)} \Vert = 1$.
Answer: Let $$f_n:=\sum_{k=1}^{2^n}(-1)^k\mathbf{1}_{\left[(k-1)2^{-n},k2^{-n}\right)}.$$
Using boundedness in $\mathbb L^p$ of $(f_n)_{n\geqslant 1}$ for $1\lt p\lt\infty$ and the fact that linear combinations of indicator functions of intervals of the form $((\ell-1) 2^{-N},\ell 2^{-N})$ are dense in $\mathbb L^{p'}$, with $1/p+1/p'=1$, we can see that $f_n\to 0$ weakly in $\mathbb L^p$, see here for more details.
However, since the interval $\left[(k-1)2^{-n},k2^{-n}\right)$, $1\leqslant k\leqslant 2^n$ are disjoint, $\lvert f_n\rvert=\mathbf 1_{[0,1)}$ which does not converge weakly to $0$.


tick checkbox programmatically

Question: <code>$('#comment-form-subscribe input:checkbox:not(:checked)').prop("checked", true);
</code>
If checkboxes are unchecked, manually check them, but this doesn't seem to be working.
Comment: Do you execute this on document ready? What is `#comment-form-subscribe`? If it is an ancestor of the checkboxes, your code should work fine.
Comment: what version of jquery are you using?
Answer: You might have a selector issue: I'd check that the length of the jQuery object returned isn't 0. This is what I typically use:
EDIT: as @nbrooks pointed out, <code>:input</code> is deprecated. This might work:
<code>$('#comment-form-subscribe').find('[type="checkbox"]').not(':checked').prop("checked", true);
</code>
Comment: The [`:input` selector](http://api.jquery.com/input-selector/) is deprecated, and the rest is functionally identical.
Answer: try
<code>$('#comment-form-subscribe input:checkbox:not(:checked)').attr('checked', true);
</code>

tick checkbox programmatically


Vim Send Alt-F10 Keys at Startup

Question: I need to send Alt-F10 key combination at vim startup. I am on Linux Mint. I tried: au GUIEnter * call feedkeys("\<M-F10>").
But that didn't work.
Thanks.
Comment: What are you trying to do? [(XY Problem)](http://meta.stackexchange.com/a/66378/188334)
Comment: In my Linux Mint, if I press Alt-F10, it will maximize the current application.
Comment: You are right. It's XY problem.
Answer: You are probably looking for the :simalt command.
VimFAQ 33.3. - 'How do I start GUI Vim in a maximized window always?' shows a example similar to what you have attempted:
autocmd GUIEnter * simalt ~x

Edit:
The simalt command is only available for ms-windows, so it will only display an error message on Linux.
You can make gVim become similar to a maximized window by using large values for 'lines' and 'columns' options, by adding the following to your vimrc:
set columns=1000
set lines=100

You could change to maximized state by using feedkeys, as you mentioned you have tried. On Linux Mint with LXDE the command call feedkeys("\<M-F10>") displays gVim 'File' menu: 'Open, Save, Print, Exit, etc'. Here the command to open the menu and hit 'Maximize' is Alt+space,x. But unfortunately it is not easy to send  from gVim, similar to what is discussed on this post. If your windows manager also relays on Alt+space you should try to change its configuration (for LXDE it is on ~/.config/openbox/lxde-rc.xml) to use some other key combination and then send it through feedkeys().
A third option is the shell plugin, which provides a :Maximize command.
Comment: I think simalt for Windows. In the documentation it says - "{not in Vi} {only for Win32 versions}". I am on Linux Mint. However, simalt ~x is for Win-key + Up (I think). What is for Alt-F10?
Comment: @Joydeep I have included more info on the answer.
Comment: I have already tried
`set columns=999`
`set lines=999`
But, it does not maximize the whole window.
But once again, forget maximize. My question is, how do I send Alt-F10 key combination at vim startup on Linux Mint?
Comment: @Joydeep "My question is, how do I send Alt-F10 key combination..." -- As I have already stated on the answer,I have tested `call feedkeys("\")` on Linux Mint with LXDE and it worked fine. It also work as expected with the autocmd GUIEnter. Without further information from your side is really hard to provide any help.

Vim Send Alt-F10 Keys at Startup


Java (Android) Decrypting msg with IV attached

Question: I generate a random IV, this IV is attached (in plain bytes) to front of the encrypted msg as shown below;
public String encrypt(String plainText, byte[] encryptionKey) throws Exception {
    SecretKeySpec key = new SecretKeySpec(encryptionKey, "AES");
    cipher.init(Cipher.ENCRYPT_MODE, key, iV);
    byte[] data = new byte[iV.getIV().length + plainText.getBytes("UTF-8").length];
    // Merge together plain IV and encrypted cipher text
    System.arraycopy(iV.getIV(), 0, data, 0, iV.getIV().length);
    System.arraycopy(cipher.doFinal(plainText.getBytes("UTF-8")), 0, data, iV.getIV().length, plainText.getBytes("UTF-8").length);

    return Base64.encodeToString(data, Base64.DEFAULT);

}

The message is sent between devices using WiFi Direct. This is handled in my MainActivity;
case MESSAGE_READ:
    byte[] readBuf = (byte[]) msg.obj;

    crypto.iV = new IvParameterSpec(Arrays.copyOf(readBuf, 16));
    // Construct a string from the valid bytes in the buffer
    String readMessage = new String(readBuf, 0, msg.arg1);
    Log.d(TAG, readMessage);

    try {
        String decryptMsg = crypto.decrypt(readMessage, SECRET_KEY);
        // Present the message
        (chatFragment).pushMessage("Buddy (decrypt): " + decryptMsg);

        Log.d(TAG, decryptMsg);
    } catch (Exception e) {
        e.printStackTrace();
    }

    // Present the message (comment out after testing!)
    //(chatFragment).pushMessage("Buddy (encrypt): " + readMessage);
    break;

During decryption it fails with the warning;

04-04 14:55:05.770: W/System.err(9847): javax.crypto.IllegalBlockSizeException: last block incomplete in decryption
04-04 14:55:05.789: W/System.err(9847):   at com.android.org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher.engineDoFinal(BaseBlockCipher.java:850)
04-04 14:55:05.790: W/System.err(9847):   at javax.crypto.Cipher.doFinal(Cipher.java:1340)
04-04 14:55:05.790: W/System.err(9847):   at com.example.cryptochat.Crypto.decrypt(Crypto.java:52)
04-04 14:55:05.790: W/System.err(9847):   at com.example.cryptochat.MainActivity.handleMessage(MainActivity.java:463)

The problem lies in the decrypt method, i am however unsure on what i am doing wrong. That method is below;
public String decrypt(String cipherText, byte[] encryptionKey) throws Exception {
    SecretKeySpec key = new SecretKeySpec(encryptionKey, "AES");
    cipher.init(Cipher.DECRYPT_MODE, key, iV);
    String decrypt = new String(cipher.doFinal( Base64.decode(cipherText, Base64.DEFAULT)));
    decrypt = new String(Arrays.copyOfRange(decrypt.getBytes(), 16, decrypt.getBytes().length));

    return decrypt;
}

Answer: When using a block cipher with padding the encrypted text is always larger that the decrypted text. But you only copy as many bytes as the decrypted text has into the message to be sent. Therefore your encrypted message is incomplete.
byte[] encryped = cipher.doFinal(plainText.getBytes("UTF-8"));
byte[] data = new byte[iV.getIV().length + encrypted.length];
System.arraycopy(iV.getIV(), 0, data, 0, iV.getIV().length);
System.arraycopy(encrypted, 0, data, iV.getIV().length, encrypted.length);

Comment: Thanks for the help robert! I can decrypt the text with the IV attached, it does not work in decrypting "cipherTextWithoutIv". What should to remove the Iv after decryption?
Comment: Don't to string operations on a base64 encoded string. Decode it and then perform the operation.
Comment: I still can-not successfully remove the IV from the decrypted msg. CopyOfRange() does not seem to work, any suggestion on what i should be doing? (*updated code)