How to get Interval Date in Android?

Question: I want to get the date interval for each month in a given month.I have three Edit Text .I have enter date in 1st EditText and i have enter 30 days in 2nd Edit Text and I want to display that date after 30 days in 3rd Edit Text. After that 30 days it should be display in 3rd Edit Text date in 1st EditText.Can someone help me please. Thanks to appreciate.
 Like 1 Oct ->  1 Nov, 2 Nov -> 1 dec, 2 dec -> 1 jan, 2 Jan -> 1 feb
Here is my Activity Code
public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.form_details);

        // Get current date by calender
            final Calendar c = Calendar.getInstance();
            year  = c.get(Calendar.YEAR);
            month = c.get(Calendar.MONTH);
            day   = c.get(Calendar.DAY_OF_MONTH);

         etReplacementDate.setText(new StringBuilder()
            // Month is 0 based, just add 1
            .append(month + 1).append("-").append(day).append("-")
            .append(year).append(" "));

         etInterval_Date.setText(new StringBuilder()
            // Month is 0 based, just add 1
            .append(month + 1).append("-").append(day).append("-")
            .append(year).append(" "));

         etReplacementDate.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                showDialog(DATE_OF_REPLACEMENT);
            }
        });

         etInterval_Date.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                showDialog(DATE_OF_INTERVAL);
            }
        });

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DATE_OF_REPLACEMENT:

            return new DatePickerDialog(this, pickerListenerReplacement, year, month, day);

        case DATE_OF_INTERVAL:

            return new DatePickerDialog(this, pickerListenerInterval, year, month, day);

        }
        return null;
    }

     private DatePickerDialog.OnDateSetListener pickerListenerReplacement = new DatePickerDialog.OnDateSetListener() {

            // when dialog box is closed, below method will be called.
            @Override
            public void onDateSet(DatePicker view, int selectedYear,
                    int selectedMonth, int selectedDay) {

                year  = selectedYear;
                month = selectedMonth;
                day   = selectedDay;

                // Show selected date
                etReplacementDate.setText(new StringBuilder().append(month + 1)
                        .append("-").append(day).append("-").append(year)
                        .append(" "));

               }
            };

            private DatePickerDialog.OnDateSetListener pickerListenerInterval = new DatePickerDialog.OnDateSetListener() {

                // when dialog box is closed, below method will be called.
                @Override
                public void onDateSet(DatePicker view, int selectedYear,
                        int selectedMonth, int selectedDay) {

                    year  = selectedYear;
                    month = selectedMonth;
                    day   = selectedDay;

                    // Show selected date
                    etInterval_Date.setText(new StringBuilder().append(month + 1)
                            .append("-").append(day).append("-").append(year)
                            .append(" "));

                   }
                };

}

Comment: possible duplicate of [Add 30 days to Date in java](http://stackoverflow.com/questions/11727933/add-30-days-to-date-in-java)
Answer: Add days to the calendar. Use the following code, For more information refer this link
      Calendar cal = Calendar.getInstance()

      // print current date
      System.out.println("The current date is : " + cal.getTime());

      // add 30 days to the calendar
      cal.add(Calendar.DATE, 30);
      System.out.println("30 days later: " + cal.getTime());

      // add 60 days to the calendar
      cal.add(Calendar.DATE, 30); // already 30 days added
      System.out.println("60 days later: " + cal.getTime());

Answer: Use GregorianCalendar For Adding Specified Dates In Calender..
Calendar cal=new GregorianCalendar();

    //added 30 days from currunt date
    cal.add(Calendar.DATE, 30);
    Date dte =cal.getTime(); //getting new date

How to get Interval Date in Android?


Stuck on a bubble sort (only using while loops) in python

Question: def bubble_sort(alist):
    i = 0
    j = 0
    while i<len(alist):
        while j<(len(alist)-1-i):
            if alist[j]>alist[j+1]:
                temp = alist[j]
                alist[j] = alist[j+1]
                alist[j+1] = temp
            j = j+1

        i = i + 1
    return alist

abc = [54,26,93,17,77,31,44,55,20]
alist1 = bubble_sort(abc)
print(alist1)

I have no idea why this only undergoes one pass. Can someone pls help??
Comment: Shouldn't you be resetting `j` at some point?
Comment: Use `for i in range(n)` loop instead of `while` with `i+1`. Also python is smart enough to swap vars by `a[j], a[j+1] = a[j+1], a[j]`.
Answer: You just have to move the initialization j=0 inside the first while loop, as follows. Note that you can also swap two values in a shorter way in Python, as I did:
def bubble_sort(a):
    i = 0
    while i<len(a):
        j = 0
        while j<(len(a)-1-i):
            if a[j]>a[j+1]:
                a[j], a[j+1] = a[j+1], a[j]
            j = j+1
        i = i + 1
    return a

abc = [54,26,93,17,77,31,44,55,20]
alist1 = bubble_sort(abc)
print(alist1)   # [17, 20, 26, 31, 44, 54, 55, 77, 93]

Comment: Thnx tons mate!


C++ Template type inside a structure

Question: Here is my MESSAGE structure:
struct tEventMessage
{
    // Type of the event
    int Type;

    // (void*) Allows those to be casted into per-Type objects
    void *pArgument1;
    void *pArgument2;

};

Can i add some kind of 'template' member to this structure, so that later on when building message i can pass those pointers + and any other data i wish ? ( see example below )
struct tEventMessage
{
    // Type of the event
    int Type;

    // (void*) Allows those to be casted into per-Type objects
    void *pArgument1;
    void *pArgument2;

    // Template
    T tSomeTemplateMember;
};

 void HandleClick(....)
 {
 CVector3 vNewPosition = ....

 tEventMessage _msg;
 _msg.Type = xxxx;
 _msg.pArgument1 = pA->GetObjectPointer();

 //
 // Wrong!
 // Because this CVector3 will not be alive in next tick
 // - my pointer will point to nothing.
 //
 _msg.pArgument2 = static_cast<CVector3*>(&vNewPosition)

 //
 // Something like that would be great
 // And would allow me to use CVector2,CVector3,CVector4 with one template member
 //
 _msg.tSomeTemplateMember = vNewPosition;

 }

Comment: Just use polymorphism properly.
Comment: Why don't you create inherited classes for your messages, and not have a struct with a type identifier? It would be much more resilient, and you wouldn't have to deal with this mess.
Comment: @Xymostech never thought about that this way.. that's a damn good advice.
Answer: I think you're over complicating the problem. Instead of one problem, how to pass arbitrary data in a message, you now have two, how to cope with templates as well.
The usual method to implement this sort of thing is to use inheritance:-
class Message
{
public:
  int Type () { return type; }
protected:
  int type;
};

class ClickMessage : public Message
{
public:
  ClickMessage () { type = ClickMessageID; }
private:
  // the message data
};

void HandleMessage (Message *message)
{
  switch (message->Type ())
  {
  case ClickMessageID:
    HandleClick (reinterpret_cast <ClickMessage *> (message));
    break;
  default:
    // unhandled message error
    break;
  }
}

void HandleClick (ClickMessage *message)
{
  // do stuff
}

The problem is you end up repeating a lot of code, i.e the cast in the switch statement. There's also a maintenance issue too - added new messages requires a bit of careful updating. You could hack the code a bit and use function pointers and a map to convert message types to functions and replace the switch statement.
There might be a clever template solution, but I can't think what it might be.
Using RTTI might help (at a cost).
This is one problem that reflection is really good at solving!
Answer: Perhaps I am missing something however I am wondering why you do not start with an abstract class from which you then derive your various kinds of event messages.  By taking advantage of abstract classes and deriving classes from them, you let the compiler figure out the logic that you are using a switch statement for.  See this C++ Polymorphism and Abstract Base Class tutorial.
Also see this from MSDN on Abstract classes.
For instance you might have an abstract class that looks like the following.  However you may not want as much of this and in fact may just want the single processEvent() method only.  Any derived classes will need to provide their own versions of each of the functions specified in the abstract class.
class EventMessage abstract {
public:
    virtual void *getArgument1 (void) = 0;
    virtual void *getArgument2 (void) = 0;
    virtual int   processEvent (void) = 0;
protected:
    void *pArgument1;
    void *pArgument2;
};

What this abstract class defines is a class that basically contains the data that is used by  all of the various event messages along with a method that is called to process the the actual message.  The class itself is not instantiated however it is used as the parent or super class for other derived class that are actually instantiated as objects.
What you would then do is to derive new classes that would implement the EventMessage interface.  For instance here are two different classes that would do that:
class JoJoEvent : public EventMessage {
public:
    JoJoEvent(void *arg1, void *arg2);
    void *getArgument1 (void);
    void *getArgument2 (void);
    int   processEvent (void);
};
JoJoEvent::JoJoEvent(void *arg1, void *arg2)
{
    pArgument1 = arg1;
    pArgument2 = arg2;
}

void * JoJoEvent::getArgument1 (void) {
    return pArgument1;
}
void * JoJoEvent::getArgument2 (void) {
    return pArgument2;
}

int JoJoEvent::processEvent (void) {
    // do stuff with the arguments
    return 1;
}

class KoKoEvent : public EventMessage {
public:
    KoKoEvent(void *arg1, void *arg2);
    void *getArgument1 (void);
    void *getArgument2 (void);
    int   processEvent (void);
};
KoKoEvent::KoKoEvent(void *arg1, void *arg2)
{
    pArgument1 = arg1;
    pArgument2 = arg2;
}

void * KoKoEvent::getArgument1 (void) {
    return pArgument1;
}
void * KoKoEvent::getArgument2 (void) {
    return pArgument2;
}

int KoKoEvent::processEvent (void) {
    // do stuff with the arguments
    return 1;
}

Then when using these you would do something like the following code:
EventMessage *myMessage = new JoJoEvent(0, 0);

EventMessage *myMessage2 = new KoKoEvent(0, 0);

myMessage2->processEvent();
myMessage->processEvent();

If you need to add additional data into the derived classes you can do so just provide a mechanism to put the data into the derived class.

C++ Template type inside a structure


Play Framework, Hibernate and too slow insertation

Question: I have two models: User and Base.
User model:
http://pastebin.com/WdLzBkHJ
Base model:
http://pastebin.com/tQrEUaSu
At first I want to put your mind on this notation in Base model:
@org.hibernate.annotations.Entity(dynamicInsert=true,dynamicUpdate=true)

It doesn't work (in SQL Debug shown that Hibernate generated queries with using unnecessary columns which in MySQL are configured as nullable). Tell me please why? What am I doing wrong?
And the main problem is there (method in which user uploads base and string in this base inserts in the MySQL table after parsing):
http://pastebin.com/yG3Mapze
Insertation is VERY SLOW. I have file with 70000 string per line and I can't wait until Hibernate insert this string into DB. Maximum I was waiting for 30 minutes and that wasn't the end.
If I'll use raw queries like that:
DB.execute("INSERT INTO bases (user_id,email,password) VALUES (1,'" + email.replaceAll("'", "\'") + "','" + password.replaceAll("'", "\'") + "')");

instead of
b.save();

After that insertation of 70000 strings to DB completes after ~10-20 seconds.
So I can't understand where is the problem and how to fix it?
Also you can see this code above method declaration:
@NoTransaction

If I uncomment it then I'll recieve this exception:
@689mbad1k
Internal Server Error (500) for request POST /checker/uploadnewbase
JPA error
A JPA error occurred (The JPA context is not initialized. JPA Entity Manager automatically start when one or more classes annotated with the @javax.persistence.Entity annotation are found in the application.):
play.exceptions.JPAException: The JPA context is not initialized. JPA Entity Manager automatically start when one or more classes annotated with the @javax.persistence.Entity annotation are found in the application.
    at play.db.jpa.JPA.get(JPA.java:22)
    at play.db.jpa.JPA.em(JPA.java:51)
    at play.db.jpa.JPQL.em(JPQL.java:16)
    at play.db.jpa.JPQL.find(JPQL.java:44)
    at models.User.find(User.java)
    at controllers.Security.getUser(Security.java:30)
    at controllers.GlobalController.userStat(GlobalController.java:21)
    at play.mvc.ActionInvoker.invoke(ActionInvoker.java:502)
    at play.mvc.ActionInvoker.invokeControllerMethod(ActionInvoker.java:476)
    at play.mvc.ActionInvoker.invokeControllerMethod(ActionInvoker.java:471)
    at play.mvc.ActionInvoker.handleBefores(ActionInvoker.java:320)
    at play.mvc.ActionInvoker.invoke(ActionInvoker.java:140)
    at Invocation.HTTP Request(Play!)
But in Play manual we can see that:
"If you want to prevent Play from starting any transaction at all, you can annotate the method with @play.db.jpa.NoTransaction.
To prevent transactions for all methods, you can annotate the Controller-class with @play.db.jpa.NoTransaction."
So I have three problems which I described:

About exception in NoTransaction.
About using dynamicInsert = true.
About improving perfomance for Hibernate like if I'll use raw queries.
Answer: The problem is the hibernate session, which must be cleared. Otherwise you get problems with memory and performance. You can found some information in http://docs.jboss.org/hibernate/core/3.3/reference/en/html/batch.html. Unfortunately I don't know how to get the HibernateSession. Perhaps you can get the EntityManager and work with it. But my experiences with Hibernate and Batch are really frustrating, so I would recommend to use your raw-solution.
Comment: You can get the Play hibernate session with `Session session = (Session) JPA.em().getDelegate();` and then use `session.flush`` and `session.clear()` as described in the documentation in the answer. You may also make a new session exclusively for you're import.
Comment: @purple: I'm not a hibernate-expert, but as far as I know, there are many meta-information which must be handled in the background, which are increased exponential. About your question: I have no idea.
Comment: Yes thanks I already read about batch on jboss.org and results are frustrated me. Insertations are too slow. So I am using now raw-solution for this loop. But I can't understand _what_ Hibernate do except setting model properties and why is insertation so slow.
Comment: By the way don't you know solution for dynamicInsert and exception after NoTransaction?


Using async to sleep in a thread without freezing

Question: So I a label here (""). When the button (button1) is clicked, the label text turns into "Test". After 2 seconds, the text is set back into "". I made this work with a timer (which has an interval of 2000):
private void button1_Click(object sender, EventArgs e)
{
    label1.Text = "Test";
    timer.Enabled = true;
}

private void timer_Tick(object sender, EventArgs e)
{
    label1.Text = "";
}

This works; however though, I am curious about making it work in an async method.
My code looks like this currently:
private void button1_Click(object sender, EventArgs e)
{
    label1.Text = "Test";
    MyAsyncMethod();
}

public async Task MyAsyncMethod()
{
    await Task.Delay(2000);
    label1.Text = "";
}

This doesn't work though.
Comment: Could you expound on "This doesn't work"? What were you expecting and what did you observe? Compiler errors? Exception stack traces?
Comment: I just tried your method and it works fine, on click it changes to "Test" 2 seconds later it changes to ""
Answer: As I mentioned your code worked fine for me, But perhaps try setting your handler to async and running the Task.Delay in there.
private async void Button_Click_1(object sender, RoutedEventArgs e)
{
    label1.Text = "Test";
    await Task.Delay(2000);
    label1.Text = "";
}

Comment: @JoshMc You are right, but that would cause the GUI thread to be blocked for 2 seconds. That's not a good solution.
Comment: For those who do not wish to create an async function: `Task.Delay(2000).Wait();`
Comment: Yeah, I think it was really difficult to tell what my problem was. However though, this seems to work without any problems :) Thank you and I'll try to word future questions more careful.
Comment: True - only recently realized this, good point .Wait() is not preferable, for the vast majority of circumstances.


Can I access SessionState from within an NUnit test?

Question: One of my methods in an NUnit test checks a Session-State variable :
if (Sesssion[variableName] == null) ...
and the NUnit test is failing with err:

System.Web.HttpException: Session
  state can only be used when
  enableSessionState is set to true,
  either in a configuration file or in
  the Page directive. Please also make
  sure that
  System.Web.SessionStateModule or a
  custom session state module is
  included in the
  \\
  section in the application
  configuration.

I tried taking the test method out of a class library and putting it into the codebehind cs of an aspx page that set EnableSessionState="True" in the aspx page directive.  Added a web config with  sessionState mode = "InProc" in the web config, then tried < pages enableSessionState ="true"/> in the web.config.
Nunit tests still failed on the session state action.
Do I have to mock these out?
Answer: I don't believe you can access Session from your unit tests without mocking it.
Have a look at Phil Haack's HttpSimulator
http://haacked.com/archive/2007/06/19/unit-tests-web-code-without-a-web-server-using-httpsimulator.aspx


Best practice for loading javascript code for multiple pages and code specific for just one page

Question: I know that there are many similar questions about how to load javascript files but this one is more about what to do with page specific files.
So, here is the question:
I have a couple of javascript files with different functionalities. Some of them are used on many pages and some just on one specific page.
From your practice, is it better to:

Load scripts for many pages on all pages and page specific scripts only on the specific pages.
(PROBLEM: many requests for js and css files)
Load just one big javascript file (that contains all those scripts including scripts for many and specific pages) on all pages.
(PROBLEM: code needed only for one page will be present on all pages)
Comment: 2. Is less of a problem than you might think - after downloading it the first time, the browser will keep the file cached and not make the request on subsequent pages.
Comment: Having one single big file is not a good practice. It's not only about loading the page faster but also about doing it in a clean way.
Answer: You should use minification and bundling. That way you make just one request and you get all the .JS files you need. You can create a different bundle for each page if you want.
You can read more about bundling here: http://vswebessentials.com/features/bundling


Guitar Computer Setup

Question: I have been playing acoustic guitar for awhile and I also have an electric guitar with a small cheap combo amp. Lately, I've been wanting to play more electric guitar, but find my small combo amp rather unsatisfactory tone-wise. I don't really have tons of money to get a good stack and pedals/effects etc... so I was thinking (as I mostly play just for myself in an apartment) that it would be better to simply use my computer (a higher-end gaming PC). Unfortunately, I know close to 0 about how this is possible. If anyone could help to tell me what I would need, (possibly recommend some products), it would be immensely appreciated.
In a nutshell, I am looking for a way to:

Plug my electric guitar into my PC (using regular guitar cable)
Have some sort of program where I can adjust the sound/effects etc... on my computer.
Be able to hear the guitar through headphones or computer speakers plugged into my PC.
Maybe even record some guitar for fun.

So, since I really only play for myself, I was wondering if this route is possible for me to get solid tones without paying heaps of money for a stack and pedals.
I've heard something about pods or soundcards or something, but am really new to this method and could use quite a bit of direction, as the amount of information online has me all over the place.
Thanks!
Comment: It might be easier and more effective to spend money on a dedicated device than to double up on your gaming PC. I say that from experience. You can get all-in-one devices like a Line 6 Pocket Pod, a Line 6 Micro Spider, or a Roland MicroCube or Cube - really there are many options. The nice thing there is you can be noodling on the guitar while you're waiting for a respawn in a game or watching Netflix. Again - speaking  from experience. :-)
Answer: Well you could easily plug-in and play your guitar through your computer. Things you need to get this done are :

A USB guitar link : A USB interface for your guitar . This helps connecting your guitar with the computer . There are many good quality and cheap USB guitar links available online so getting one is easy,
DAW Software (Digital Audio Workstation Software) : You need to have DAW installed on your computer . Again there are many DAW softwares available online. This will helps you to record and play your music . You can do many things in that like editing , adding effects and more .
VST Plugin : To add effects into your guitar tones , you need to install some VST Effects into your DAW and again getting one is easy online .
Playback Device : Speakers i mean or you can also use your headphones as monitors to hear what you are playing . This playback device gets its input from the USB Guitar link .

And that's it , you can start with these things and as you go more deep into that you'll see some advance equipment and tech used in pro studios .
Hope this helps !
Comment: You definitely need a proper audio interface, yes - this is what Pankaj describes as USB guitar link. I have tried all the main DAWs and to be honest, they are all good. Just find one that you enjoy using and that has the features you want to use.
Comment: DAW with VSTs is overkill for the OP. Just use one of the guitar effects applications.
Comment: @DrMayhem Any recommendations for DAWs and VSTs? Also is there any benefit to using audio interfaces/boxes like the line 6 POD studio?
Comment: @DrMayhem Then again, with Reaper being only $60 and having a host application giving you more options for MIDI stuff and all kinds of other plug-ins, maybe a DAW isn't such a bad idea. On OS X, Garage Band actually can be your virtual guitar rig and I'm pretty sure it comes free.
Answer: Rocksmith 2014 is very good. It's kind of like guitar hero but using a real guitar to play along with original recordings of songs. The focus is on learning and playing along with songs, but it does have an amp/pedal simulation mode and dynamic jamming mode. You need to buy the  software and the usb to guitar cable.

Guitar Computer Setup


Error reading JSON from URL

Question: I am trying to read json into my C# application from a url. When I run the application I keep getting a error:
"Additional Text encountered after finished reading JSON content: {. Path ",line 2, position 667".
This is from this URL
I checked the page and the view source and can't seem to find the problem. How do I fix this?
The JSON is derived from a php array that is json encoded and echoed:
    $args = array( 'post_type' => 'product', 'posts_per_page' => 200, 'product_cat' => 'Alcopops' );

    $loop = new WP_Query( $args );

    while ( $loop->have_posts() ) : $loop->the_post();
    global $product;
echo json_encode($product);

    endwhile;

    wp_reset_query();

Comment: Surround Json with square brackets.
Comment: did you use `WebClient`?
Comment: @SirwanAfifi I used `HttpClient client = new HttpClient();
               // HttpResponseMessage response = await client.GetAsync(App.DataServiceUrl + "/products?category=" + (String)navigationParameter);`
Comment: @BappiDatta. I did that and now I get another error message: "After parsing a value an unexpected character was encountered: {. Path '[0]',line 2, position 668."
Answer: That page doesn't contain valid json. Take a look at this:

"product_type":"simple"}{"id":246,"post":

there's no comma between } and {
Edit:
The problem is with your php, rather than the c#.
Try this:
$args = array( 'post_type' => 'product', 'posts_per_page' => 200, 'product_cat' => 'Alcopops' );
$loop = new WP_Query( $args );
echo json_encode($loop->get_posts());
wp_reset_query();

Comment: Are you looping over each element in the array and calling json_encode for each element by any chance?
Comment: Ok, well I am using json_encode to get a php array in this format.
Comment: Really! Can you show the code where you're building the array and calling json_encode? Something funny there.
Answer: use WebClient :
var json = new WebClient().DownloadString("http://cbbnideas.com/brydens-website/products/?category=Alcopops");

Comment: [Client profile](http://msdn.microsoft.com/en-us/library/cc656912%28v=vs.110%29.aspx) does not have System.Web.dll so you can't really use WebClient in an app that targets client profile.
Comment: This is for a windows 8 desktop app. I doesn't seem to recognize WebClient
Comment: @add `using System.Net;`

Error reading JSON from URL


How to play "Moonlight" sonata with pedal

Question: Here is tact #20 of "Moonlight" Sonata:

My right hand position (B + B - C# - G#):

The hand is definitely overstressed. Plus I am inadvertently pressing the G key in order to press G#. I watched this video about playing the sonata with pedal.
But I can't reproduce what he says. When I press the sustain pedal at the beginning of the tact all C#-s and G#-s get sustained and overlap.
What is the correct way to play it with pedal?
Comment: Quickly lift the pedal up and then press it down again every time the left hand octave changes in that piece.
Answer: It's only an octave stretch, which is OK for most people - but in the photograph your hand is in a bad position with the palm very low and close to the keys, and the fingers arched upwards in an attempt to clear them.
Your third (ring) finger in particular is pressing a white key in trying to reach the black.
Most sources suggest the seat should be set so the elbows are a little above the key tops, so the palms are above the keys and the fingers curve down smoothly to the keys. Having the hands low and arching the fingers up as shown in the picture looks very restricting to me.
I'd suggest searching around for the vary basics of playing position before you try to play this piece further.
Pedal is irrelevant at the moment, don't worry about it. (But note my score says the pedal can be held continuously for the entire movement...)
Comment: I concur except one should be careful about lifting one's elbows lest one create tension in one's shoulders. And I should just use "you" instead of "one" lest I create a snobby attitude in my comments - except I'm too lazy to go back and fix it now.
Comment: @ToddWilcox thanks for the comment, I've clarified that bit. (It read like I was suggesting holding the elbows up, when I meant they should hang naturally a little above the height of the keyboard).  I think the original questioner may have the seat set too low.  I personally sit on a few cushions to get my perfect height.
Answer: 'Anytime' a chord changes you have to release the pedal...
So you press the keys and in the moment the hammer touch the strings you release the pedal and press it again as soon as possible. You never press the pedal 'on' the beat - you release it 'on' the beat
Now the Octave B-B 'floats' and your right hand can have its relaxed position for the triad of the accompaniment.
In the very bar you mentioned you have to do the same on beat 3, too - that's the trick - no stress for the right hand at all...
Comment: So, to play just these 2 triplets with right hand: 1) press B - B 2) press the pedal 3) release B - B 4) C# - G#. Then holding the pedal: B - C# - G#?
Answer:
But I can't reproduce what he says. When I press the sustain pedal at
  the beginning of the tact all C#-s and G#-s get sustained and overlap.

That is what is supposed to happen. In the first edition, Beethoven's instructions at the start of the movement were "Adagio sostenuto", "Si deve suonare tutto questo pezzo delicatissimamente et senza Sordino", and "Semper pianissimo e senza Sordino" - i.e. he says "keep the sustain pedal down continuously for the whole movement" twice, but that doesn't work on modern pianos which sustain notes for much longer than pianos in Beethoven's time.
I suspect your hand position is wrong (as the other answers describe) because you are trying to hold down all the notes but your hands are too small. But the pedal holds the notes for you, so your fingers can let go.
The "4-5" fingering on the A in your score implies that the editor wants you to hold down the top notes, which is a good idea psychologically (even though it doesn't make any difference physically when the pedal is down) because it makes you focus on the melody part rather than all the notes in the triplet accompaniment. If your hands are too small to stretch the 7th C# to B with 2-5, play the C# with your thumb. The pedal will cover the "gap" when you move your thumb from B to C#. "Jumping" between notes with your thumb is much less important than not accidentally playing extra wrong notes like the G natural.
Answer: Don't hold the RH bottom B! Release it as soon as you're done, let the pedal carry it through, and relax your hand to play the other two beamed notes in that group.


How to draw a animation upon a background image in Java Swing

Question: Here is my code, I used two image, one for background image and one for the pinball animation, but with this code, the ball will wipe off the background image within it's flying trace so I need some help that can allow me draw on a transparent bufferedimage then put it as a mask over the background image. Thanks in advance.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.util.Random;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

public class MainTest {

    private final int TABLE_WIDTH = 300;
    private final int TABLE_HEIGHT = 400;
    private final int BALL_SIZE = 16;
    private JFrame f = new JFrame("Pinball game");
    Random rand = new Random();
    private int ySpeed = 5;
    private double xyRate = rand.nextDouble() - 0.5;
    private int xSpeed = (int) (ySpeed * xyRate * 2);
    private int ballX = rand.nextInt(200) + 20;
    private int ballY = rand.nextInt(10) + 20;

    private BackgroundPanel background = new BackgroundPanel();
    private Foreground foreground = new Foreground();
    private int preX = -1;
    private int preY = -1;

    BufferedImage image = new BufferedImage(TABLE_WIDTH, TABLE_HEIGHT, BufferedImage.TYPE_INT_ARGB);
    Image back = new ImageIcon("res/cat1.jpg").getImage();
    Graphics g = image.getGraphics();

    Timer timer;

    public void init() {
//      Graphics2D g = image.createGraphics();
//      image = g.getDeviceConfiguration().createCompatibleImage(30, 30, Transparency.TRANSLUCENT);
        background.setBackground(new ImageIcon("res/cat1.jpg"));
        background.setPreferredSize(new Dimension(TABLE_WIDTH, TABLE_HEIGHT));
        foreground.setPreferredSize(new Dimension(TABLE_WIDTH, TABLE_HEIGHT));
        background.add(foreground);
        f.add(background);

        ActionListener taskPerformer = evt -> {
            if (ballX <= 0 || ballX >= TABLE_WIDTH - BALL_SIZE) {
                xSpeed = -xSpeed;
            }
            else if (ballY <= 0 || (ballY >= TABLE_HEIGHT - BALL_SIZE)) {
                ySpeed = -ySpeed;
            }
            ballY += ySpeed;
            ballX += xSpeed;
            g.setColor(Color.BLUE);
            g.fillOval(ballX, ballY, BALL_SIZE, BALL_SIZE);
            if (preX == -1) {
                preX = ballX;
                preY = ballY;
            }
            g.clearRect(preX, preY, BALL_SIZE, BALL_SIZE);
            preX = ballX;
            preY = ballY;
            foreground.repaint();
        };
        timer = new Timer(10, taskPerformer);
        timer.start();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.pack();
        f.setVisible(true);
    }

    public static void main(String[] args) {
        new MainTest().init();
    }

    public class Foreground extends JPanel {
        private static final long serialVersionUID = 1L;

        public Foreground() {
        }

        @Override
        public void update(Graphics g) {
            paint(g);
        }

        @Override
        public void paint(Graphics g) {
            super.paint(g);
            g.drawImage(back, 0, 0, this);
            g.drawImage(image, 0, 0, this);
        }
    }
}

public class BackgroundPanel extends JPanel {

    private static final long serialVersionUID = 6702278957072713279L;
    private Icon wallpaper;

    public BackgroundPanel() {
    }

    protected void paintComponent(Graphics g) {
        if (null != wallpaper) {
            processBackground(g);
        }
    }

    public void setBackground(Icon wallpaper) {
        this.wallpaper = wallpaper;
        this.repaint();
    }

    private void processBackground(Graphics g) {
        ImageIcon icon = (ImageIcon) wallpaper;
        Image image = icon.getImage();
        int cw = getWidth();
        int ch = getHeight();
        int iw = image.getWidth(this);
        int ih = image.getHeight(this);
        int x = 0;
        int y = 0;
        while (y <= ch) {
            g.drawImage(image, x, y, this);
            x += iw;
            if (x >= cw) {
                x = 0;
                y += ih;
            }
        }
    }
}

Comment: I would recommend taking a look at [Painting in AWT and Swing](https://www.oracle.com/technetwork/java/painting-140037.html) to for a better understanding of how the painting process and how you're suppose to work with it. Before you get worried about optimisation, focus on just making it work as simply as you can
Comment: Neither, because it's not really how you should be going it, as I said, understand how the api works first, the change your design to work with it
Comment: That doesn't help alot on my question, could you advise when I add 2 Jpanels to one JFrame, which one is the best practice, JFrame.add(JPanel1) then JFrame.add(JPanel2)? or JPanes1.add(JPanel2) then JFrame.add(JPanel1)? I tried both and set the foreground JPanel.setOpaque(false), but my problem didn't be solved.
Answer: Draw ball after draw background image.
in your case, draw ball after method "processBackground".
Comment: Thanks the problem fixed, So I don't need use two JPanels for this scenario right? Just use one JPanel and draw a background image then draw other shapes after that. Thanks alot.
Comment: Yes! right. and please accept my answer. i want get privilege.
Answer: I got this problem solved, and post the code here, thanks @MadProgrammer and @SuperShark's help.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.util.Random;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

public class MainTest {

    private final int TABLE_WIDTH = 300;
    private final int TABLE_HEIGHT = 400;
    private final int BALL_SIZE = 16;
    private JFrame f = new JFrame("Pinball game");
    Random rand = new Random();
    private int ySpeed = 5;
    private double xyRate = rand.nextDouble() - 0.5;
    private int xSpeed = (int) (ySpeed * xyRate * 2);
    private int ballX = rand.nextInt(200) + 20;
    private int ballY = rand.nextInt(10) + 20;

    private BackgroundPanel background = new BackgroundPanel();
    Timer timer;

    public void init() {

        background.setBackground(new ImageIcon("res/cat1.jpg"));
        background.setPreferredSize(new Dimension(TABLE_WIDTH, TABLE_HEIGHT));

        f.add(background);

        ActionListener taskPerformer = evt -> {
            if (ballX <= 0 || ballX >= TABLE_WIDTH - BALL_SIZE) {
                xSpeed = -xSpeed;
            } else if (ballY <= 0 || (ballY >= TABLE_HEIGHT - BALL_SIZE)) {
                ySpeed = -ySpeed;
            }
            ballY += ySpeed;
            ballX += xSpeed;
            background.repaint();
        };
        timer = new Timer(10, taskPerformer);
        timer.start();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.pack();
        f.setVisible(true);
    }

    public static void main(String[] args) {
        new MainTest().init();
    }

    public class BackgroundPanel extends JPanel {

        private static final long serialVersionUID = 6702278957072713279L;
        private Icon wallpaper;

        public BackgroundPanel() {
        }

        protected void paintComponent(Graphics g) {
            if (null != wallpaper) {
                processBackground(g);
                drawball(g);
            }
            System.out.println("f:paintComponent(Graphics g)");
        }

        public void setBackground(Icon wallpaper) {
            this.wallpaper = wallpaper;
            this.repaint();
        }

        private void processBackground(Graphics g) {
            ImageIcon icon = (ImageIcon) wallpaper;
            Image image = icon.getImage();
            int cw = getWidth();
            int ch = getHeight();
            int iw = image.getWidth(this);
            int ih = image.getHeight(this);
            int x = 0;
            int y = 0;
            while (y <= ch) {
                g.drawImage(image, x, y, this);
                x += iw;
                if (x >= cw) {
                    x = 0;
                    y += ih;
                }
            }
        }
        private void drawball(Graphics g){
             g.setColor(Color.BLUE);
             g.fillOval(ballX, ballY, BALL_SIZE, BALL_SIZE);
        }
    }
}


Como criar uma function e chamar seus métodos sem usar new, semelhante ao $ do jQuery?

Question: O $ (cifrão) do jQuery é uma function, contudo é possível acessar seus métodos como se fosse um objeto através do operador "." . Alguém poderia explicar, de que forma eu poderia fazer isso em uma function func, por exemplo?

De forma mais esclarecedora, pretendo usar func() como também func.each() por exemplo.
Answer: Você pode armazenar uma função em uma variável e utiliza-la para executar funções internas através de um objeto, este algoritmo implementa Javascript Module Pattern.
var $fn = function() {
  return {
    alertar: alertar
  }

  function alertar(message){
    alert(message);
  }
}();

$fn.alertar("teste")

Você também pode implementar uma function através de prototype:
var $fn = function () {
    if (this instanceof $fn)
        return this

    return new $fn;
};

$fn.prototype = {
    alertar: function (message) {
        alert(message);
    }
};

window.$ = $fn();

Comment: Dessa forma não responde minha questão, pois $fn não é uma function e sim um objeto. Ou seja  typeof $fn retorna "object" e não "function" como typeof $
Answer: Em JavaScript as funções são tipos especiais de objetos, e podem ter propriedades (incluindo outras funções) como qualquer objeto:

function funcao(x) {
    console.log('função chamada');
}

funcao.propriedade = 10;
funcao.metodo = function() { console.log('método chamado') }

// Testes:
funcao();
console.log(funcao.propriedade);
funcao.metodo();

No jQuery a coisa é um pouco mais complexa porque todos os métodos vão no protótipo, a função $ é um construtor, e ainda a biblioteca implementa encadeamento de métodos das instâncias desse construtor. Mas no seu caso talvez baste o feijão-com-arroz acima (avise caso não baste).


Limit of a shifted sequence is the same limit of the non shifted sequence

Question: I've searched for this but I didn't found anything here, hope it is not a duplicate.
I would like to prove that if $a_n \to l$ for $n \to \infty$ then $a_{n+k} \to l$ for fixed $k\in\mathbb{Z}\setminus \{0\}$.
Let $\varepsilon>0$. By hypothesis $a_n \to l$ for $n \to \infty$, so for all $\varepsilon>0$ exists $N_{\varepsilon} \in \mathbb{N}$ such that if $n>N_{\varepsilon}$ then $|a_n-l|<\varepsilon$.
Let $k \in \mathbb{Z}\setminus \{0\}$. Since $n+|k|>n$, when $n>N_{\varepsilon}$ we have that $n+|k|>n>N_{\varepsilon} \Rightarrow n+|k|>N_{\varepsilon}$; so $|a_{n+|k|}-l|<\varepsilon$.
This shows that $a_{n+k} \to l$ for $n \to \infty$ for all fixed $k\in\mathbb{Z}\setminus \{0\}$.
Is this correct? I've used $|k|$ because it unifies both the cases for $k>$ and $k<0$, but I'm not sure if it is correct.
Thanks.
Answer: The use of $|k|$ is not correct because although it allows you to correctly conclude that $a_{n+|k|}$ converges to $l$, this tells you nothing about $a_{n+k}$, except when $k$ is positive. Conceptually, this argument fails at its core, in that if $n$ is big enough for $a_n$ to be close to $l$, it is not necessarily the case that $a_{n-k}$ is close to $l$, if $k$ is big enough.
If $a_n$ gets close to $l$ starting at $N$, then we need to go to at least $N-k$ in order to make sure $a_{n+k}$ will be close to $l$. For example if $a_n$ gets close to $l$ starting at $N$, then we can only be sure $a_{n-10}$ is that close to $l$ starting at $N+10$. In general, the argument is that $n+k>N$ if and only if $n>N-k$, by simple algebra.


sending data with history.goBack()

Question: So i am working on a MERN stack app. When the user registers i want to redirect him to the log in page and show him an alert on the log page. To redirect i am using the react {useHistory} however when i send data from signup using the history.goBack({data}), nothing happens...
this is the code in the signup
this is the login where i console.log the history
Comment: `history.goBack()` does not accept any params. Set the data in cookies and read the cookies after going back to the previous page.
Comment: are you sure `history.goBack` take arguments?
Comment: nope, i am not sure
Comment: Please show all relevant code, data, and errors as text, not as a picture of text.
Answer: You can't pass data into the goBack() method.
Instead, set a query param and then on the other page look if it's present and use it.
history.push({
  pathname: '/test',
  search: '?foo=bar',
})

And to get it (native way):
const params = new URLSearchParams(props.location.search);
const foo = params.get('foo'); // bar

sending data with history.goBack()


Correlation: If $Z^2$s are correlated, it doesnt imply that $Z$s are correlated?

Question: I read in my lecture slide that if $Z^2$s are correlated, it doesn't imply that $Z$s are correlated, but I don't understand it. Any example will be  welcome.
Answer: Let

$X$ be a standard normal random variable with distribution $\mathcal N(0,1)$,
$Y$ be independently another standard normal random variable and
$Z=\text{sign}(Y) \, |X|$, also a standard normal random variable

Then $X^2=Z^2$, so with correlation of $1$ between them, but $X$ and $Z$ are uncorrelated with correlation of $0$ between them (though they are not independent since $|X|=|Z|$)
while $Y^2$ and $Z^2$ are independent, so uncorrelated with correlation of $0$ between them, but $Y$ and $Z$ are correlated with correlation of $\frac{2}{\pi} \approx 0.6366$ between them
Comment: thanks! is the opposite also true? If X and Z are correlated, then $X^2$ and $Z^2$ may not be correlated
Comment: @ELI - Yes - I have added an example in the opposite direction


Less code lines for scaling and stacking columns in numpy

Question: I just started using iPython and numpy. I am sure that it is possible to do the same thing as below with less code.. I would like to scale all columns (=dimensions of a datapoint, which is the row) to values between 0 and 1 and recombine the columns to one array with the same "shape".
import numpy as np
from StringIO import StringIO

data = np.genfromtxt("wine_names.csv", dtype=float, delimiter=',', skip_header=1)

Data.shape => (178, 14). A csv file with 178 rows and 14 columns (178 datapoints in 14 dimensions).
data0 = (data[:,0] - np.amin((data[:,0]))) / (np.amax((data[:,0]))-np.amin((data[:,0])))
data1 = (data[:,1] - np.amin((data[:,1]))) / (np.amax((data[:,1]))-np.amin((data[:,1])))
data2 = (data[:,2] - np.amin((data[:,2]))) / (np.amax((data[:,2]))-np.amin((data[:,2])))

until n. In this case it is 14. This can be written with less code I am sure, but I don't know how..
data_all = np.column_stack([data0, data1, data2])

here as well np.column_stack([data0, data1, data2, ....., n])
Comment: Should this be in Code Golfing/Programming Puzzles?
Comment: You can get all the min values of the columns by doing `np.min(data, axis=0)` and the same for max.
Answer: By taking the minimum values, and maximum values along an axis, you can do it in one line.
data_all = (data - np.min(data, axis=0))/(np.max(data, axis=0) - np.min(data, axis=0))

Comment: I would not do it in one line, because you're calculating the same `min` twice.  Do it in two: `mn, mx = data.min(0), data.max(0); data_all = (data - mn)/(mx-mn)`  Or, if you don't mind modifying the `data` array in place, you could also do `data -= data.min(0); data /= data.max(0)` which might be even faster.
Comment: @M4rtini thanks for the help! It is still difficult for me to understand the concept of axis..


Deleting a directory including a file that is currently being downloaded by a client

Question: Imagine the following scenario:

Client (browser) calls a PHP script
Script generates a ZIP file in web_root/downloads/tmp/test.zip
Script returns headers accordingly and therefore initiates a download of that ZIP file
Script terminates the directory web_root/downloads/tmp/

What could happen?

Server queues deletion and deletes folder as soon as possible
Directory (and file) are deleted and the client therefore loses the connection
Server declines deletion because directory is somehow locked
Apache actually clones/caches files before streaming them, so that deleting the original will have no effect

Which one is correct?
Now, i could test this behaviour on my own server, but what i want to know is whether there exists any sort of convention that defines UNIX/LINUX based standard behaviour in such a case?
How are such cases handled in general?
Answer: 5. Apache has the filesystem inode open, so when you delete the file, it's not deleted, it's unlinked. That is, link web_root/downloads/tmp/test.zip is removed, but the inode still exists as long as apache has the inode open. When apache closes the inode, its link count reaches zero and is removed by the system
Comment: Exactly what i needed to know! I assume this is consistent behaviour amongst all platforms and (perhaps even) different HTTP server solutions?
Comment: Not all platforms, only unix. On Windows a file is THE file, not a link, that's why it's necessary to restart after updates. But on unix it's consistent for all applications (and so http servers too).


Why do uploaded files gets saved with an all-caps file extension?

Question: On my product site any uploaded images get saved with the .JPG saved in all-caps. I don't see the same issue on my local development machine so I would think it has to be a server issue? The live site uses NGINX.
Comment: @MotoTribe As the question seems interesting please post your answer if you find. +1
Comment: Perhaps this is a dumb question, but do the original files have an uppercase extension? Also, do you have any modules installed performing file renaming such as Transliteration?
Comment: no to both questions
Comment: it appears as if they are uploaded in all caps filenames. Maybe most cameras store filenames all caps. My Sony and my gopro camera for example do. I wonder if there is a way to force the filenames to lowercase?
Answer: Definitely not a server (nginx) issue, as the server does not do anything with the files (well, it transfers them bit by bit). Like Charlie already asked, do you use any modules?
Edit: To answer your second question, of course you can "force" lowercase extensions. But personally I wouldn't bug your users with that, they should simply upload whatever they have. Instead simply alter the files extension before saving the file to disk/database.
hook_file_presave() seems like the correct way to do this. You would have to create a little module and have a look at the file variable that's passed to your hook, then simply strtolower() the file extension.
Comment: good to know that it can't be the server. I use a bunch of modules of course, none that would have any effect on an uploaded file name.
Answer: Files on the camera are stored using a very simple file system using 8.3 file names, which by default are upper-case (originally these file systems didn't distinguish between upper and lower case in filenames)


Simple Slopes: significance testing

Question: Can somebody explain me how to test whether simple slopes are significant?
...and is it necessary to test the significance of the simple slopes or would it be sufficient to plot the slopes and describe the effects?
I performed a moderation analysis with a regression, i.e. a regression with an interaction. The interaction is significant. I calculated the simple slopes for different Levels of the moderator, mean + / - 1 SD. But I do not know how I can test whether These slopes are significant.
Comment: Does "simple slope" mean something different than "slope"?
Comment: I do not think so. In the context of Moderation Analysis this term is used when you calculate slopes for different levels of the moderator.
Answer: You said that the interaction is significant. In a model with different slopes in different groups the meaning of interaction is that the slopes are different! So I think you have already answered your own question, unless you mean something different with significance of slopes.

Simple Slopes: significance testing


k-means for many same points in R

Question: Suppose I have a one dimension data set, which contains many same numbers, for example data set S = c(rep(4, times(1000)), rep(5, times(808)), rep(9, times(990))). Is there any efficient ways to do k-means in R? Actually in my data I have just a around 20 different points, but each of them appears around 100000 times, it runs very slow. So I wonder if there is a more efficient way.
Answer: K-means can be implemented with weights. It's straightforward to do so.
But IIRC the version included with R is not implemented this way. The version on flexcluster maybe is, but it's pure R and much much much slower.
Either way, you will want to implement this in Fortran or C, like the regular kmeans version. Maybe you can find some package that has a good implementation already.
Comment: Thank you. I find a function kmeansW {FactoClass}, which works well.

k-means for many same points in R


Multilingual Jade templates?

Question: I'm using the Jade template engine with gulp, gulp-jade and gulp-data to build a very basic one-page website in two languages. The result should be static HTML documents with no further server-side or client-side processing. Is it possible to load website content from a JSON file depending on a language I define in my index.jade, and what would be the best way to go about doing this?
My current attempt causes an error:
gulpfile.js:
gulp.task('views', function () {
  return gulp.src('app/**/*.jade')
    .pipe($.data(function(file) {
      return require('./app/data/text.json'); // load language file
    }))
    .pipe($.jade({pretty: true, basedir: 'app/'}))
    .pipe(gulp.dest('.tmp'));
});

text.json:
{
  "de": {
    "foo": "deutsch"
  },

  "en": {
    "foo": "english"
  }
}

index_en.jade:
extends /_layouts/default.jade

var lang = "en"

block content

    h1 #{lang.foo} // load text from json

This results in the following error when I run gulp:
Cannot read property 'foo' of undefined

I don't mind splitting up the JSON into different files per language if that makes things easier, but I have no idea how I would include the appropriate file from within index_en.jade.
Some context:
I should note that I'm extending a default layout file (default.jade), which itself includes a bunch of things like header.jade and footer.jade to keep the template system as DRY as possible. Those files would need to be multilingual as well, which is why I would like to define lang="en" in my index_en.jade, lang="de" in index_de.jade, and just have that propagate to all of the other partials without having to duplicate those as well (e.g. no header_de.jade or such).
I'm also merging these features back into my yeoman generator, so I would like to find a system where I can avoid having to adjust gulpfile.js if I were to add another language later on.
Answer: The error lies in #{lang.foo}. You've set lang to a string and that doesn't have a foo on it… If you set lang to the actual object that you're loading (en or de in this case), it works fine:
extends /_layouts/default.jade

block content

    - var lang = en

    h1 #{lang.foo} // load text from json

Note the missing quotation marks.
Edit: Variable declaration needs to be inside block (sometimes).
Comment: Perfect, thank you. Both the string and block scope were a problem.

Multilingual Jade templates?


Private tempstore storage contains data for previous anonymous user

Question: I have an issue with private tempstore storage that I wasn't able to solve. I've implemented a webform handler, which populates data in this storage and then I'm creating tokens out of the saved values. This works fine, however, when anonymous user comes to page where token value is used, he/she sees last value saved in to the storage, before his/her session has been created.
This is strange, because setting a value for anonymous user should create a session for user, if it doesn't exist, yet: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21TempStore%21PrivateTempStore.php/function/PrivateTempStore%3A%3Aset/8.6.x Do you have any idea why this happens, please? Should I use module https://www.drupal.org/project/session_based_temp_store? Should I consider using Sessions directly (https://drupal.stackexchange.com/a/246268/7580)?
Comment: More likely the page where you're using that data has been cached for anonymous users which all share the same cached page content. You'll need to disable anonymous page caching on that page your outputting the data
Answer: Yes, this looks very much like a caching problem. You don't need to disable the anonymous page cache, though, this happens automatically for requests with a session cookie. What you need is a cache context session in render arrays containing session data, no matter whether you serve anonymous or authenticated users:
public function build() {
  $session = \Drupal::request()->getSession();
  $build = [
   '#markup' => $session->get('value'),
  ];
  $build['#cache']['contexts'][] = 'session';
  return $build;
}

The private tempstore is for large amounts of data. See What is the difference between \Drupal::request()->getSession() and \Drupal::service('user.private_tempstore')?
Comment: Thanks. So this basically means that I need to override this part of a block definition of the module?  ```/**
   * {@inheritdoc}
   */
  public function getCacheContexts() {
    return Cache::mergeContexts(parent::getCacheContexts(), ['url.path']);
  }```
Comment: No, add the cache context directly to the build array the block plugin returns. `session` is a default auto placeholder condition and then the block cache methods no longer work. See https://drupal.stackexchange.com/questions/288881/problem-setting-user-specific-cache-tags-on-custom-block-with-user-context
Comment: Thanks. I added following hook implementation to my module:

`function mymodule_block_build_social_sharing_block_alter(array &$build, \Drupal\Core\Block\BlockPluginInterface $block) {
  $build['#cache']['contexts'][] = 'session';
}`

But it didn't help. Am I doing something wrong?
Comment: My answer is more about that you need to add a cache context, not where. So I've assumed you have a render element in the build array which displays a session value. If you add the session value in a different place I would suggest to add the cache data at the same place. Tokens can also bubble up cache metadata. But there are a lot of things that can go wrong if you have for example a custom token placed in a contrib/custom block rendered via a custom theme.


Show Block only if it's a front page and GET variable is set

Question: I am setting up a block in Drupal 7 to "show block on specific pages" through PHP.
What I want is that if it's a Front page and there is a GET (listed) variable, only then it shows the block otherwise not.
Hence, the block would only be shown, if the url is www.site.com/?listed=true
I tried this, but it doesn't work:-
<?php
if ( (drupal_is_front_page()) && ( !empty($_GET['listed'])  ) {
  return true;
}
?>

any idea?
Answer: You missed a closing bracket. Try this:
<?php
if (drupal_is_front_page() && !empty($_GET['listed'])) {
  return TRUE;
}
?>

or
<?php
if (drupal_is_front_page() && isset($_GET['listed'])) {
  return TRUE;
}
?>

Answer: I would suggest to look at Context module. It gives you lot of options to configure.
In your case you can add a new context and put two conditions

Path = <front>
Query String : listed=true

then add a reaction to display the block you want. Its simple.


Adding a light to javascript w/ ping test

Question: I want to display this light if a certain condition is true in javascript using an if statement. How can I add an external CSS class to a javascript if statement?
Here is my css code:
.beacon{
  position:absolute;

  background-color:#32CD32;
  height:1.5em;
  width:1.5em;
  border-radius:50%;
  -webkit-transform:translateX(-50%) translateY(-50%);
}
.beacon:before{
  position:absolute;
  content:"";
  height:1.5em;
  width:1.5em;
  left:0;
  top:0;
  background-color:transparent;
  border-radius:50%;
  box-shadow:0px 0px 2px 2px #32CD32;
  -webkit-animation:active 2s infinite linear;
  animation:active 2s infinite linear;
}

@-webkit-keyframes active{
  0%{
    -webkit-transform:scale(.1);
    opacity:1;
  }
  70%{
    -webkit-transform:scale(2.5);
    opacity:0;
  }
  100%{
    opacity:0;
  }
}

@keyframes active{
  0%{
    transform:scale(.1);
    opacity:1;
  }
  70%{
    transform:scale(2.5);
    opacity:0;
  }
  100%{
    opacity:0;
  }
}

this is the javascript code:

Comment: Possible duplicate of [How do you add CSS with Javascript?](https://stackoverflow.com/questions/707565/how-do-you-add-css-with-javascript)
Comment: If my submission answered your question then please accept it. If not, what aspect was not answered?
Answer: It depends on any framework you're using. For example, if you're using jQuery then change a DOM element's CSS using .css(property, value). Angular has it's own methods. For raw DOM manipulation take a look at the w3c page on JavaScript HTML DOM - Changing CSS, which shows the following.
document.getElementById(id).style.property = new style


Settimeout Within The Same Function

Question: I need your help.
When I run the iframe and the click code in the code below separately without setting settimeout, it works, but when I add settimeout to both, I get a "findo is not defined" error.
setTimeout(function () {
var findo = $('')
.attr('src',"url link")
.attr('id', 'sevecen')
.attr('class', 'class_in_iframe')
.appendTo('.class');},5000);
setTimeout(function () {var selo = findo.contents().find(".class
id").trigger("click");},8000);

Comment: Move the second timeout inside the first one, with a delay of 3000. That way, it will have access to the `findo` variable you created locally in the first one
Answer: You have to run this only when document is loaded. Try:

In myFunction, run your logic without timeout and check.
Answer: I agree with @blex, you should put the second timeout inside the first one and adjust wait time.
setTimeout(function () {
  var findo = $("")
    .attr("src", "url link")
    .attr("id", "sevecen")
    .attr("class", "class_in_iframe")
    .appendTo(".class");

    setTimeout(function () {
        var selo = findo.contents().find(".class id").trigger("click");
      }, 3000);

}, 5000);

Settimeout Within The Same Function


Without Replacement; Hypergeometric / With replacement: Binomial

Question: I have read this statement :
Trials are independent (i.e. use binomial) if sampling is done with replacement.
Trials are dependent (i.e. use hypergeometric) if sampling is done without replacement from a known population size.
Can someone explain it /proove it ?
Thanks
Answer: Consider an urn with $5$ red balls and $5$ black balls, where drawing a red ball is considered a "success".
If we replace the ball after each selection, then we always have a probability of $0.5$ of selecting a red ball next. Thus, our probability $p$ of a success stays constant.
If we do not replace the ball each time, then that affects the probability for future selections. If we initially selected a red, then we now have a probability of $\frac{4}{9}$ of selecting a red. If we selected red again, then we now have a probability of $\frac{3}{8}$ of selecting a red, and so forth.
Similarly, if we initially selected a black, then we now have a probability of $\frac{5}{9}$ of selected a red. If we selected black again, then we now have a probability of $\frac{5}{8}$ of selecting a red, and so forth.
Comment: Thanks you ! I get it now :)
Answer: As in @Remy's example (+1), suppose you have an urn with 5 red balls and 5 black balls.
(1) You draw 4 balls with replacement and let $X$ be the number of red balls drawn.
Then $X$ has a binomial distribution with $n = 4$ and $p = P(\text{Red}) = 1/2$ at each draw.
Also, $\mu =E(X) = np = 4(1/2) = 2; Var(X) = np(1-p) = 1.$ (This same distribution applies to tossing a fair coin four times and counting the number of Heads that occur.)
(2) You draw 4 balls without replacement and let $Y$ be the number of red balls drawn. Then $Y$ has a hypergeometric distribution, for which the
original contents of the urn are parameters.
Again here, $\mu = E(Y) = 2,$ but as
the number of balls left in the urn decreases, so do the possible choices, and the variability of
the count of red balls decreases accordingly. (In particular, as the number of red balls in the urn decreases, drawing a red ball gets less likely, and chances of getting all red balls become small.) So $Var(Y) < Var(X).$ can you find the exact formula for
$Var(X)?.$

The table below, made using R statistical software, shows how probabilities
differ between the two distributions. (Ignore the brackets [ ].)
<code>k = 0:4;  bin.pdf = dbinom(k, 4, .5);  hyp.pdf = dhyper(k, 5, 5, 4)
round(cbind(k, bin.pdf, hyp.pdf), 4)

     k bin.pdf hyp.pdf
[1,] 0  0.0625  0.0238
[2,] 1  0.2500  0.2381
[3,] 2  0.3750  0.4762
[4,] 3  0.2500  0.2381
[5,] 4  0.0625  0.0238
</code>
In the figure below, heights of vertical bars show the binomial probabilities and
the centers of the circles show the hypergeometric probabilities.

Can you see that hypergeometric probabilities are a little more
tightly clustered around $\mu = 2?$
Answer: To explain the statements, consider with replacement first. If you have "with replacement", it means no matter what you do in that trial, the next trial is going to have the same starting condition as your previous trial. Hence, the probability of your outcomes is the same. This means they are independent of each other: your previous outcome has no affect on the conditions of the next trial.
If you have "without replacemnt", this means the outcome you have in one trial affects the next as the ending condition of a trial is the same as the starting condition of the next trial. Hence, the trials are dependent.
As an example, if you have one red ball and one blue ball and you are trying to take a random ball out of it. Probability is obviously $0.5$ for the first trial. Now, if you have replacement, you are guaranteed to go back to the condition that you have two balls in each trial, so probability is the same for each trial=$0.5$. However, if I don't replace the first ball that I take, then my next pick will be $100$% for the ball that is still left and $0$% for the ball already taken. Hence trials are dependent.


Taylor's Theorem Expansions to equate centered difference formula with O(h^2)

Question: As I am really struggling with my Numerical Method's class, I am trying to prepare for an upcoming exam with some example problems. This being one of them, I am not exactly sure how to even approach this fully. I have looked at this post Using Taylor Polynomial To Derive Centered Difference and think it is fairly similar with what I am trying to do, but there was no finishing responses to this post.
The question is:
Use Taylor's Theorem expansions about both $$f(x + h) $$$$ f(x - h)$$ to show that the centered difference formula $$f^`(x) = \frac{f(x+h)-f(x-h)}{2h}$$ is $$O(h^2)$$

Like the post, I started off with
$$f(x+h) = f(x) + f^`(x)h + O(h^2)$$
$$f(x-h) = f(x) - f^`(x)h + O(h^2)$$
and subtracted them and end up getting the centered difference
$$\frac{f(x+h)-f(x-h)}{2h}$$
Does this just mean that because I was able to get this from Taylor's Theorem expansions, I can just set this value equal to the remaining $$O(h^2)$$ and be done?
I am very confused on how this problem can be finished and hoping to get an idea around it.
Comment: Why don't you take an extra term in your Taylor expansions?
Answer: Starting from Taylor's series definition for a real value a (arbitrarily selected):
$$f(x)=\frac{f^{(0)}(a)}{0!}(x-a)^0+\frac{f^{(1)}(a)}{1!}(x-a)^1+\frac{f^{(2)}(a)}{2!}(x-a)^2+...$$
which can be written simpler as
$$f(x)={f(a)}+\frac{f^{(1)}(a)}{1!}(x-a)+\frac{f^{(2)}(a)}{2!}(x-a)^2+...$$
In our case it's important to remember that h is a very small number, so the bigger exponent is over h, the smaller resulting value.
Now let's add some substitutions:

Our function will be f(x+h)
Expansion at point zero

$$f(x+h)={f(0)}+\frac{f^{(1)}(0)}{1!}(x+h)+\frac{f^{(2)}(0)}{2!}(x+h)^2+...$$
Same thing for f(x-h):
$$f(x-h)={f(0)}+\frac{f^{(1)}(0)}{1!}(x-h)+\frac{f^{(2)}(0)}{2!}(x-h)^2+...$$
Let's make a substitution:
$$\phi_i=\frac{f^{(i)}(0)}{i!}$$
Then
$$f(x+h)=\phi_0+\phi_1(x+h)+\phi_2(x+h)^2+\phi_3(x+h)^3+...$$
And
$$f(x-h)=\phi_0+\phi_1(x-h)+\phi_2(x-h)^2+\phi_3(x-h)^3+...$$
Let's subtract:
$$f(x+h)-f(x-h)=\phi_1(2h)+\phi_2(4hx)+\phi_3(6hx^2+2h^3)+...$$
Let's replace dots with big O:
$$f(x+h)-f(x-h)=\phi_1(2h)+\phi_2(4hx)+\phi_3(6hx^2+2h^3)+O(h^4)$$
It's useful to extract factor 2h since that's the denominator in final equation:
$$f(x+h)-f(x-h)={2h}{(\phi_1+\phi_2(2x)+\phi_3(3x^2+h^2)+O(h^3))}$$
So:
$$\frac{f(x+h)-f(x-h)}{2h}={\phi_1+\phi_2(2x)+\phi_3(3x^2+h^2)+O(h^3)}$$
Since on the right side we still have squared h:
$$\frac{f(x+h)-f(x-h)}{2h}={\phi_1+\phi_2(2x)+O(h^2)}$$
Since h is a very small value, big O for smaller exponent dominates over one with larger exponent.
I guess that's a verbose answer to the question.
Question's importance may come from the fact that standard form of numerical derivative has error of O(h) order. Discussed under this wiki page.


php how to keep track (in database) of image tag filenames included in html ouput from ckeditor wysiwyg editor

Question: I have changed the title to this post as I think I have not been clear with my question...
This is my first post, so please be gentle with me!
I am building a content management system for a small static site which I built for a client some years ago.
The client is eager within some content areas of the site to be able to enter formatted text and images freely - in blog-esque fashion. I've chosen ckeditor and ckfinder for these tasks.
For all other parts of the site I've no problem envisaging how this data would be uploaded/entered and stored in a database and served to each instance of template etc. My difficulty is in conceiving how I would - in PHP - extract the image filenames from the wysiwyg field content when posting data.
Would I use regex() on the $_POST['wysiwygText'] and search the html outputed by the wysiwyg editor for any .jpg/.png/.gif etc - if so what function/search argument would I use?
I'm only trying to do this as the rest of the site's image names would be stored in a db where the domain rules are more ridig eg, every menu will have either 1,2 or 2 set sized images in it's header - and text is always formated the same way...- theoretically is is good practice to store a record of images used on each page for a site? I just thought it would easier in time as client adds and takes out images to have images automatically removed when not used etc.
However I can forsee that if image names used within the wysiwyg area it might be really difficult to track many to many relationships of images used on different pages as it would be an unreasonalbe task to add this logic to ckeditor's output. Or should I just be firmer with my client and not have wysiwyg editor but simple form fields to input images within a text field - an example of some code to do that would be excellent if the wysiwyg option is deemed to unmageable.
Many thanks for any contributions/help/suggestions
Answer: You can access all of the information needed with the $_FILES Global array that is automatically created for you when an image is uploaded.
http://php.net/manual/en/reserved.variables.files.php
Example usage. Note: this has no error checking such as max file size, file type etc etc, It's only an exmaple to get you on the correct path.
<code>if ($_FILES)
{
$uploadDir = 'images/';

$filename = $uploadDir . $_FILES['filename']['name'];
move_uploaded_file($_FILES['filename']['tmp_name'], $filename);
}

else echo "No image uploaded"
</code>
Comment: I don't understand where the above logic fits my needs, unless you are directly refering to using ckfinder and ckeditor - if so I don't know how to access the $_files array from their scripts - can't find any documentation on this. Assuming you know ckfinder is a file manager plug in for wysiwyg editor ckeditor are you saying that ckfinder uses the  $_files array too and that I can access this - do you know which php file?
Comment: Sorry, from your OP I thought you were hard-coding your PHP scripts and my answer was relating to that assumption. I'm not personally aware of ckfinder, but why not have a go at coding it yourself from scratch? You will learn more this way.


Django {% csrf_token %} or @csrf_protect

Question: I am curious: I know there are 2 ways of csrf protection in Django: {% csrf_token %} in templates and @csrf_protect in views.
So, question is: are they interchangeable? I mean I can use for example only @csrf_protect i my views without {% csrf_token %} tag in my templates and effect will be the same?
I'm asking that because I use mako in recent Django project and there is no such tag as {% csrf_token %}...
Comment: 1. `{% csrf_token %}` must be there in templates 2. view should either be protected by `@csrf_protect` or by `CSRF middleware`.

If you are using other template engine or AJAX, you need to provide csrf token in the template context. Read how : https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#other-template-engines
Answer: You need both. {% csrf_token %} adds hidden fields that is included in POST requests. While @csrf_protect adds a context variable that is used by {% csrf_token %}.
Comment: But documentation says:    1) Alternatively, you can use the decorator csrf_protect() on particular views you want to protect (see below).            2) Rather than adding CsrfViewMiddleware as a blanket protection, you can use the csrf_protect decorator, which has exactly the same functionality, on particular views that need the protection. It must be used both on views that insert the CSRF token in the output, and on those that accept the POST form data.
Comment: @VitaliPonomar You always need the `{% csrf_token %}` inside your form, and the view has to add the context variable needed. If the context variable is added through the decorator, middleware, or manually added doesn't matter, just that it comes as a pair.


how to generate random time series for a given one, including all trends?

Question: I have a 250-time points series of actual data and I want to generate a similar time series including all its curves
first, I was interested to know its probability distribution and see if it fits other distributions, after fitting, it was Normal and Lognormal seem better. So I generated 250 points of Lognormal but they came absolutely random resembling no properties of the original time series (Lognormal are illustrated in the second chart)
The original time series it looks like this

My generated Lognormal according to the data parameters looks like this

the data is as follows
1800
1650
1850
2050
2150
1950
1700
1850
2200
2270
1950
1730
1850
2200
2350
1950
1780
1930
2200
2400
2270
1920
2080
2340
2470
2300
1890
2180
2340
2490
2300
1900
2130
2370
2440
2430
2050
2220
2400
2550
2060
1960
1890
2240
2490
2070
1920
1870
2330
2490
2170
1840
1970
2240
2570
2140
1810
1930
2270
2530
2080
1720
1970
2340
2510
2070
1680
1990
2310
2410
1990
1710
1970
2260
2470
2010
1620
1910
2270
2430
1840
1720
1960
2090
2240
1820
1680
2030
2070
2190
1820
1710
1970
2010
2160
1770
1670
1980
2050
2080
1620
1440
1710
1870
2120
1610
1470
1720
1820
2070
1690
1340
1770
1920
2080
1610
1540
1740
1960
2140
1730
1620
1710
1910
2230
1690
1580
1770
1870
2170
1740
1690
1730
1910
2210
1750
1590
1760
1930
2170
1840
1880
2030
2110
2240
1940
1740
2030
2090
2390
1910
1840
2190
2120
2270
1940
1840
2090
2160
2370
1930
1720
1870
1980
2210
1990
1670
1830
1920
2110
1910
1740
1890
1920
2170
1840
1760
1820
1990
2190
2080
1990
2230
2340
2470
2080
1910
2150
2310
2460
2120
1950
2200
2280
2520
2140
1970
2220
2320
2550
2610
2240
2387
2520
2560
2470
2210
2490
2450
2630
2510
2170
2420
2440
2580
2490
2270
2380
2520
2620
2610
2460
2520
2540
2760
2690
2530
2590
2630
2750
2680
2480
2630
2690
2770
2630
2420
2570
2580
2740
2170
2420
2440
2580
2490
2270
2380
2520
2620
2580
Comment: How did you find the parameters for the first series? From a rough visual look at the series, it seems like it has some persistence that your second simulated series does not have (plus some short-term ciclicality that is close to seasonality because it seems fairly regular, but this is not the main point here and should be confirmed by something else than visual inspection). What seems clear is that is either a very persistent stationary process that keeps coming back to 2000 or even a I(1). In any case it is far more persistent than yours, that seems a stationary process with not much memory
Comment: This is a question where I gotta ask: why? What is the goal that you are trying to achieve? There is a lot of different ways to interpret the stated goal to "generate a similar time series". The most "similar" time series is the original series itself. If you want a similar time series, what should be different? I would also echo the sentiment of @Fr1 which is that your data is clearly not a stationary random process, so modelling it as a stationary lognormal process will clearly not capture the high- and low-frequency trends that are obvious in your oringinal data.
Comment: *"the required was to plug the 250 days data into an optimization model. that is a decision has been made."* could you explain more about this optimization model and the 'decision' that has to be made. It seems to me like you sort of want to generate ['made up data'](https://stats.stackexchange.com/questions/420525/best-term-for-made-up-data) in order to test those optimization models. This seems like a valid approach. But details are lacking. In addition it is complex as this question mixes two concepts: 1 how to correctly fit the data 2 how to simulate 'made up data' for a specific purpose.
Comment: So I suspect that the problem may be that you have not estimated the parameters very well. Was the first series a simulated series as well? or was it a real-world example with real data? consider that you are focusing on the shape of the pdf in your question, but here the estimated parameters are very important. Once you get an accurate estimate of the parameters, then, you can use them with a random innovation (possibly from the same marginal pdf as the original series 1) to simulate.
Comment: At that point, depending on the properties of the series (firstly depending on stationarity and secondly depending on the presence of trends etc.) you may or may not have a similar graph. Consider the case of a random walk without drift, which is by definition fully dependent on innovations. In that case, since the the future level of the process is just a function of current level and innovations, you may have a completely different graph in the simulation as the simulated innovations change compared to the historical innovations of series 1. If a trend exist, it may reduce the discrepancy.
Comment: Maybe try fitting an AR process?
Comment: @Fr1: I did a distribution fitting procedure; histogram and selecting another distribution based on KS and Chi-Squared tests. Lognormal scored better on KS D critical value basis. But I have not incorporated any trend proprties
Comment: @timchap: the data is collected from experts. the required was to plug the 250 days data into an optimization model. that is a decision has been made. my role is to simulate 20 scenarios that are equivalent to the data in order to plug them into the optimization model, not a future forecast
Comment: So I suppose that you are using real data, my suggestion is to forget about the shape of the pdf for a while and focus on the parameter estimation for at least your conditional mean.. the idea is that it is likely that there will exists a better specification of the model compared to yours.. but this is not about the pdf, this is about the structure of your conditional mean.. are you using an Arma/Ma/Ar/Arima? Etc. I suppose you are in a univariate setting here.. Since the QMLE is still consistent if you mispecify the pdf function, then the pdf FOR THE MOMENT is not the most relevant thing.
Comment: Well have you done your research ?. You probably are concerned with how do you accomplish this with the tools you have on hand.  I  have laid out a working approach here in great detail. I was able to simulate a number of look-alikes ...personally reinforcing my suggested approach .  which has never been published (that I am aware of !)  but is dead-on in terms of fulfilling your reasonable expectations. @Martin is dead on suggesting the need to "make-up data"
Comment: In order to proceed .. please restate your question ...e.g. How do I simulate a new series  with the same characteristics (equation) as the series that I have observed ?
Answer: "I was interested to know its probability distribution and see if it fits other distributions"  ... there is no reason to model the observed series which can be reduced to simpler structure.  Failing modelling attempts one simple uses monte-carlo procedures using the cdf of the observed series to generate values for the composite BUT not time series traces.
There is no need to transform your data see the following for clues on power transforms When (and why) should you take the log of a distribution (of numbers)?
What I propose here is a 2 step procedure 1) characterize the series ..separating observed to signal and noise AND then 2) simulating white noise and using it to render a data realization of the model .
It is important to characterize the series i.e identify the nature of the "curves" . In this way you can separate the data into signal and noise and focus on simulating trial/candidate noise processes leading to "similar time series" i.e. time series with nearly identical acf.
In this way after a useful model has been identified one can then use simulated error processes and then "reverse" the model by injecting/inputting the simulated error processes to generate a trial realization of the data. This is essentially how one generates a forecast and the probability distribution to assess prediction limits for a given interval of time BUT we will not be forecasting here.
Please post your actual 250 data points and I and others might be able to help you further.
EDITED AFTER RECEIPT OF YOUR 250 OBSERVATIONS :
One of the reasons I asked you to post your data is that I have long been a fan of simulation (dating back to the mid-sixties) as an objective  way of evaluating strategies and suggested procedures. As I developed and improved model identification strategies , I conducted simulation of data in order to evaluate signal detection. I always have maintained a currency in simulation as a possible lithmus test.
I  took your 250 values and used AUTOBOX , a piece of software that not only has model identification BUT data simulation capabilities. I used it to take your data and identify the following model in order to separate signal and noise and then to use the model as the basis for simulations.
Here is the ACF of the original series . AUTOBOX rendered a model here  with residuals here  and acf here
The Actual & Fitted values are plotted here
Now the Histogram of the original 250 values is here and is shown for completeness sake  while the histogram of the error series from our model is here  and much more important in our exercise.
We now proceed to use the simulation option in AUTOBOX which requires a model , presented here in a structured manner
We ask the software to generate 0,1 random numbers and use them as the basis (input) into the model form to create a 250 period realization . This can then be repeated for as many replications of the 250 simulated values.
I show here the acf of the original 250 values  and the acf of the first replication of the 250 simulated values  . The simulated series "resembles" the original series which is what I think you want to do.
Your question could have/should have been worded more correctly. I guess you now how to modify your question given my answer. I suggest you do so.
I suggest that you get hold of a good simulation piece of software ( and there are a few !) to allow you to specify the required equation for the generated simulation OR write your own code to do this .
 presents the relationship between an error process (perhaps the result of simulation) and the realization in terms of Y
Comment: I posted the data, can you guide me?
Comment: Wow! Now this will need some serious understanding from my side as this is my first time to do time series. But at least, where in this is the method to simulate different scenarios of the same time series without forecasting
Comment: if you can characterize thus separating signal & noise via  a FILTER AND then vary the noise BUT not it's nature & then use it you can get a "new series" .Simulation is the CONVERSE  of modelling . With modelling you convert or filter the original series to render a "simpler series" . With simulation you do tjhe converse you take a set of a set of values and inject it via the INVERSE FILTER read model in order to generate a new series with similar characteristics as the original series.  I have often characterized myself as a wannabe "noise maker"  via efficient characterizarion/modelling.
Comment: there was no forecasting done at all .. The underlying model was detected and then useful in separating signal to fit and a white noise set of errors. time series modelling is a bi-directional approach i.e.  y via a filter leads to a stochastic process white noise ... white noise (possibly simulated !)  via an inverse filter leads to y.


Drools KnowledgeBase size

Question: What is the best way to calculate (without serialisation) the amount of heap memory in bytes that a Drools KnolwedgeBase will occupy?
Answer: I'm interested to know why do you need to know that?
The knowledge base size is related with the number of Knowledge Packages that you are planning to add to it, so it really depends on the things that you are planning to do in your rules or processes.
Cheers
Comment: I have no processes, i have 1 package per knowledgebase. This package has a variable number of rules, anything ranging from several to several hundred rules.

The reason i need to know is because i am storing lots of  knowledgebases inside a cache. I have an eviction process that starts to destroy entries when the cache reaches a certain size in memory.

Drools KnowledgeBase size


How can I dynamically create userdefined folder for file upload using multer in nodejs?

Question: i want to upload the file into a folder which should be get from form data submit by user. which is req.body.coursename
/*conditions for directory check*/
var isvalidate = function (data) {
    var data = data;
    var dir = '../uploads'+'/'+data;
    if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir);
        return dir;
    } else {
        return dir;
    }
};

/*multer*/

var date = moment().format('YYYY-MM-DD');
var storage = multer.diskStorage ({
    destination: function (req, file, callback) {
        console.log("filename upload",file.originalname);
        callback(null, isvalidate(req.body.coursename));
    },
    filename: function (req, file, callback) {
        //console.log("filename upload",file.originalname);
        callback(null, date+ '-' +file.originalname );
    }
});
var data = multer({ storage : storage }).any();

/*file upload*/

router.post('/create',function(req, res) {
    console.log(req.body);
    data(req, res, function(err) {
        console.log(req.body);
        //isvalidate (req.body.coursename);
        if (err) {
            res.json({error_code:1,err_desc:err});
            return;
        }
    });
});

How can I create a folder with the name req.body.coursename for file upload?
Answer: You can't but you can move the file to other locations after the file is uploaded. You could make your storage object a module and change the directory dynamically via init
var multer = require('multer'); //  middleware for handling multipart/form-data,
// Constructor
module.exports = function (name) {
    try {
        // Configuring appropriate storage
        var storage = multer.diskStorage({
            // Absolute path
            destination: function (req, file, callback) {
                callback(null, './uploads/'+name);
            },
            // Match the field name in the request body
            filename: function (req, file, callback) {
                callback(null, file.fieldname + '-' + Date.now());
            }
        });
        return storage;
    } catch (ex) {
        console.log("Error :\n"+ex);
    }
}

OR Use busboy
var Busboy = require('busboy');
var fs = require('fs');
app.post('.....',fucntion(req, res, next){
var busboy = new Busboy({ headers: req.headers });
busboy.on('field', function(fieldname, val) {

  req.body[fieldname] = val;
});
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
fstream = fs.createWriteStream("path/desiredImageName");
    file.pipe(fstream);
    fstream.on('close', function() {

       file.resume();

 });
})
 return req.pipe(busboy);
})

OR you can use changedest
app.post('/api/:type', multer({
dest: './uploads/',
changeDest: function(dest, req, res) {
var newDestination = dest + req.params.type;
var stat = null;
try {
    stat = fs.statSync(newDestination);
} catch (err) {
    fs.mkdirSync(newDestination);
}
if (stat && !stat.isDirectory()) {
    throw new Error('Directory cannot be created because an inode of a different type exists at "' + dest + '"');
}
return newDestination
}
}), function(req, res) {
 //set your response
});

Comment: is it posible other than multer
Comment: i am new in nodejs. what you mean by init ? .please explain


How pop is working in stack using linked list?

Question: Here in the pop function, after top is assigned to temp, its written top=top->link, but how is top=top->link making it point to its back node?
top=top->link is meant to move forward and point to the node to its front and here it should be NULL.
EDIT: cout added in pop. Now to make question more specific, how cout<<top->data will print 32 ? it should be pointing to NULL.
#include<iostream>
using namespace std;

class stack_ll{
    private:
        struct node{
            int data;
            node *link;
        }*top;

    public:
        stack_ll()
        {
            top=NULL;
        }
        void push(int);
        void pop();
        void display();

        ~stack_ll()
        {
            if(top==NULL)
            return;

            node *temp;
            while(top!=NULL)
            {
                temp=top;
                top=top->link;
                delete temp;
            }
        }
};

void stack_ll::push(int num)
{
    node *temp;
    temp=new node;

    if(temp==NULL) {
    cout<<"stack is full"<<endl;
    return;
    }

    temp->data=num;
    temp->link=top;
    top=temp;

}

void stack_ll::pop(){
    if(top==NULL)
    {
        cout<<"stack is empty"<<endl;
        return;
    }

    node * temp;
    int item;

    temp=top;
    item=temp->data;
    top=top->link;
    cout<<top->data<<endl;
    delete temp;

}

int main()
{
    stack_ll l1;
    l1.push(5);
    l1.push(56);
    l1.push(32);
    l1.push(34);
    l1.pop();
    l1.push(23);
    l1.pop();
}

Comment: @FirstStep: what are you talking about? The links point down. `top->link` points to the next element down, i.e. the new top one after a pop.
Answer: You are right. Pop here will remove the first object and will now have top as NULL even though there are some objects in the stack. What you should do to fix that, is change the link direction - meaning each object will point to the lower object. In that case, when removing the top, you will be able to retrieve the next object, that is lower in the stack
change:
temp->data=num;
temp->link=top;
top=temp;

to:
temp->data=num;
top->link=temp;
top=temp;

and add a special case for an empty stack where top->link=temp; will not be legal like:
if(top==NULL){
    temp->data=num;
    top=temp;
    top->link=NULL;
}

EDIT:
your logic should be like this:
empty stack has only a null_ptr (top)
push: if stack is empty - top is now new element and it's link is null_ptr, else - top's link is now new element, top becomes new element and new element's link is null_ptr
pop: if stack is empty do nothing, else - print top's data, save top as temp, top becomes top's link (the lower element in stack), print temp's data and delete temp
Comment: You misunderstand: the OP's code is fine as it is. Nothing needs to be changed. The op is asking why it works, not about a problem.
Comment: No but i am asking that if you put a coutlink is supposed to move to NULL ?
Comment: you should print before assigning null to top. pop function should go like this: if top != null print top. assign top->link to top
Answer: This implementation is correct. You don't need to change anything.
Working of push
When we try to add an element is this stack, we create a new node and make it head of the link list. Hence the last element added will always be head of the link list.
Working of of Pop
When we try to pop an element we just do top- = top->link. This means we just changed the head node to the previous element which was added in the stack.


If $\mathbb{k}$ is a division ring then $\mathbb{k}^n$ is a simple $M_n(\mathbb{k})$ module

Question: Problem: If $\mathbb{k}$ is a division ring then $\mathbb{k}^n$ is a simple $M_n(\mathbb{k})$ module
I'm lost on this problem, the hint is to use linear algebra but i dont see how it helps.
Answer: Hint : First try to see that it's enough to show "for any nonzero vector $v$, there is $M\in M_n(\mathbb k)$ with $Mv = (1,0,...,0)$".
Then try to prove that, using a nonzero coordinate of $v$ and the fact that $\mathbb k $ is a division ring.
Comment: Yes, that's exactly the point. The nonzero coordinate of $v$ would be used to prove the first claim
Comment: I misinterpreted: I though that "that" referred to the original statement rather than the claim.
Comment: @Omnomnomnom : ah, sorry if it was unclear then !


Tensor product of abelian group and a free abelian group

Question: I am trying to show that if $F,H$ are abelian groups with $F$ free abelian, and if $a \in F$ and $h \in H$ are non-zero, then $a \otimes h \ne 0$ in $F \otimes H$.
This is specifically in a section describing the derived functor Tor. Of course, that doesn't mean the solution has to involve that, but there is probably a way. I know that $F$ free abelian means that $F$ is torsion free and hence $\mbox{Tor}(F,A)=0$.
I was trying to use a formulation of $\mbox{Tor}$ in terms of exact sequences. If:
$$0 \to R \stackrel{i}{\hookrightarrow} F \to A \to 0$$ is an exact sequence then $\mbox{Tor}(A,B) =\mbox{ker}(i \otimes 1_b)$
Seemed to me if I picked the right sequence I could get that $\mbox{Tor}=0$ implies that the kernel is trivial, which would give the result, but I can't get this to work
Edit It appears that this is false from the answers below.
Here is a link to the question.
Comment: Can you describe more about what you know of tensor products? For example, I think most people would give the solution " $F$ is a direct sum of copies of $\mathbb{Z}$ and tensor product distributes over direct sums, so..."
Comment: No, not exactly; see the two answers below.
Comment: @Steve, yes retracted after seeing the comment
Answer: Suppose $F=\mathbb Z$ and $H=\mathbb Z/2\mathbb Z$. Let $a=2\in F$ and let $\xi\in H$ be the non-zero element. Then $$a\otimes\xi=(2\cdot1)\otimes\xi=1\otimes(2\cdot \xi)=1\otimes 0=0$$.
It follows that what you want to prove is false.
Answer: Here is an answer using Tor:
Consider the exact sequence
$$ 0\rightarrow\mathbb{Z}\rightarrow F\rightarrow K\rightarrow 0,$$
where the map from $\mathbb{Z}$ to $F$ sends the generator $1$ to $a$, and $K$ is the cokernel.  Tensoring with $H$ we get the long exact sequence
$$ \cdots Tor(F,H)\rightarrow Tor(K,H)\rightarrow H\rightarrow F\otimes H\rightarrow H\otimes K\rightarrow 0. $$
Now $Tor(F,H)=0$ since $F$ is torsion-free.  So the kernel of $H\rightarrow F\otimes H$, given by sending $h$ to $a\otimes h$, is $Tor(K,H)$.  This is not always non-zero, and the problem as stated is incorrect.  Consider $H=\mathbb{Z}/2\mathbb{Z}$, $F=\mathbb{Z}$, $a=2$.
Comment: thanks for that. I guess we need some additional hypothesis like $H$ is torsion free as well?
Comment: Well actually you can say exactly what you need.  If I can write $a=b^m$ for some $b\in F$, then we need $mh\neq 0$. Basically $a$ looks like $(n_1,n_2,\ldots,n_r)$ for some integer $r$ (ignoring the zero coordinates), and if $m=GCD(n_1,\ldots,n_r)$, we need $mh\neq 0$.