Issue with showing lists of running apps on List view

Question: I'm trying to show the list of background running apps in ListView. what I have tried is creating AppAdapter extending ArrayAdapter and used Async task to call the method which returns the list of running services' package names. I posted the code below.
AppAdapter:
public class AppAdapter extends ArrayAdapter<String> {

private List<ActivityManager.RunningServiceInfo> applist =null;
private Context context;
private PackageManager packageManager;
private List<String> applist1 = null;

public AppAdapter(@NonNull Context context, int resource, @NonNull List<String> objects) {
    super(context, resource, objects);

    this.context = context;
    this.applist1 = objects;
    packageManager = context.getPackageManager();
}

@Override
public int getCount() {
    return ((applist1 != null) ? applist1.size() : 0);
}

@Override
public String getItem(int position) {
    return ((applist1 != null) ? applist1.get(position) : null);
}

@Override
public long getItemId(int position) {
    return position;

}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View view = convertView;
    if (view == null) {
        LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = layoutInflater.inflate(R.layout.list_item, null);
    }

    ActivityManager.RunningServiceInfo data = applist.get(position);
    Log.d("Test", "data is  : " + data);

    if (data != null){
        Log.d("Test", "data is not null : " + data);
        TextView appName = view.findViewById(R.id.applabel);
        TextView packageName = view.findViewById(R.id.pname);
        ImageView iconView = view.findViewById(R.id.appicon);

        ComponentName mComponentName = data.service;
        appName.setText(mComponentName.getClassName());
        packageName.setText(mComponentName.getPackageName());

    } else {
        Log.d("Test", "data is null : " + data);

    }
    return view;
}
}

Code in Main Activity:
private class LoadApplications extends AsyncTask<Void, Void, Void>{

    private ProgressDialog progressDialog = null;

    @Override
    protected Void doInBackground(Void... voids) {

         applist1 = runningServices();
        listadapter = new AppAdapter(Taskmanager.this, R.layout.list_item, applist1);
        Log.d("Test", "applist1 is : " + applist1);
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {

        listView.setAdapter(listadapter);
        progressDialog.dismiss();
        super.onPostExecute(aVoid);
    }

    @Override
    protected void onPreExecute() {
        progressDialog = ProgressDialog.show(Taskmanager.this, null, "Loading..");
        super.onPreExecute();
    }
}

and the runningServices() method correctly returns the list of package names (if you want to see that let me know).
The problem is the after app launch it shows nothing (no list). I didn't forget to call the async task in the onCreate method of the activity.
Can someone please figure out what might be going wrong. I posted only limited code if you want more then ask me in the comments, please.
Answer: Do the necessary work after getting a list from the background task. Return the List value from the doInBackgroind method and then assign it to adapter in the onPostExecute method which runs on the UI thread.
public class LoadApplications extends AsyncTask<Void, Void, List<ActivityManager.RunningServiceInfo>> {

        @Override
        protected List<ActivityManager.RunningServiceInfo> doInBackground(Void... arg0) {
              return runningServices();
        }

        @Override
        protected void onPostExecute(List<ActivityManager.RunningServiceInfo> applist) {
                  // call super
                   listadapter = new AppAdapter(Taskmanager.this,
                   R.layout.list_item, applist);

                  listView.setAdapter(listadapter);
                  progressDialog.dismiss();

                  //other works
        }
    }


loop through two lists to find if an element from 1st list exists in the 2nd list

Question: I've got two lists. One is a list of languages, and the second is a list of strings. I would like to search if any language exists in the list of text and append it (the found language) to a new list, otherwise, append "english" to that new list instead.
languages = ['afrikaans', 'russian', 'amharic', 'japanese', 'armenian', 'polish', ...]

texts = ['apple', 'orange in polish', 'grape in russian']

The desired output:
['english', 'polish', 'russian']

I first tried these lines but it returns ['polish', 'russian']!
list_of_valid_langs = []
for lang in langs:
    for text in texts:
        if lang in text:
            list_of_valid_langs.append(lang)

For my second attempt, I added a second condition but this is not what I need
list_of_valid_langs = []
for lang in langs:
    for text in texts:
        if lang in text:
            list_of_valid_langs.append(lang)
        elif lang not in text:
            list_of_valid_langs.append('english')

Comment: What is wrong with your second attempt?
Comment: I would have something like this:

['english', 'english', 'english', 'english', 'english', 'english', 'english', 'english', 'english', 'english', 'english', 'english', 'english', 'english', 'english', 'english', 'english', 'english', 'english', 'english', 'english', 'english', 'english', 'english', 'english',
Answer: I think your mistake is first iterating over the langueges, and then iterating over the texts. Let's try flipping it around:
for text in texts:
    for lang in langs:
        if lang in text:
            list_of_valid_langs.append(lang)
            break  # lang is found, no need to keep searching
    else:  # if no lang was found, append 'english'
        list_of_valid_langs.append('english')

After seeing @fsimonjetz's answer, I found a better sulotion using sets:
# first of all, turn langs into a set
langs = set(langs)

# iterate over the texts
for text in texts:
    # check if one of the words in the text is a language
    for word in text.split():
        if word in langs:
            # if a language is found, append it and break
            list_of_valid_langs.append(word)
            break
    else:
        # if no language is found, append 'english'
        list_of_valid_langs.append('english')

A note about for else: The code in the for loop runs as usual, but the code in the else block only runs if the for loop exited normally. Another way to look at this is that the else block only runs if the break statement wasn't reached.
If you want, you can replace the for else with a normal for loop followed by an if block by using a bool variable.
Answer: I think Roy Cohen's answer is the perfect solution to your problem, but I'd like to suggest an alternative using set intersection that would be more efficient:
languages = set(['afrikaans', 'russian', 'amharic', 'japanese', 'armenian', 'polish'])
texts = ['apple', 'orange in polish', 'grape in russian']

list_of_valid_langs = []

for t in texts:
    # this will return the set of the language(s) occurring in the
    # string if there are any, otherwise it returns {'english'}
    lang = set(t.split()).intersection(languages) or {'english'}

    # pop the element from the set and append to the list
    list_of_valid_langs.append(lang.pop())

Comment: After seeing your answer I came up with another answer based on my old answer and yours combined. Check out the edit I made.
Comment: @Roy Cohen, nice! I think the way you did it will be more readable, especially for beginners.
Comment: @fsimonjets thanks! Your idea of using sets is awsome. I don't know if my solution is begginer-friendly, specifically the `for else` part, but I'll add a little explanation about it.
Answer: This should work:
for text in texts:
    lang_found = False

    for lang in langs:
        if lang in text:
            list_of_valid_langs.append(lang)
            lang_found = True

    if not lang_found:
        list_of_valid_langs.append('english')

Comment: This is fantastic, it works for me and it is clear to follow as well. Thank you.


how to add a class to the widget pager of views slideshow

Question: I want to add a class to the widget pager of views slideshow. I found the function in the file /theme/views_slideshow.theme.inc wich theme the wrapper of the widget
function theme_views_slideshow_pager_widget_render($vars) {
  // Add javascript settings for the pager type.
  $js_vars = array(
    'viewsSlideshowPager' => array(
      $vars['vss_id'] => array(
        $vars['location'] => array(
          'type' => preg_replace('/_(.?)/e', "strtoupper('$1')", $vars['settings']['type']),
        ),
      ),
    ),
  );

  drupal_add_js($js_vars, 'setting');

  // Create some attributes
  $attributes['class'] = 'widget_pager widget_pager_' . $vars['location'];
  $attributes['id'] = 'widget_pager_' . $vars['location'] . '_' . $vars['vss_id'];
  return theme($vars['settings']['type'], array('vss_id' => $vars['vss_id'], 'view' => $vars['view'], 'settings' => $vars['settings'], 'location' => $vars['location'], 'attributes' => $attributes));
}

I just want to modify the line to add my own class (as grid-6 for example)
$attributes['class'] = 'widget_pager widget_pager_' . $vars['location'];

I try to use this function in my file template.php without success.
the classes of the wigdet pager in my html code are :
views-slideshow-pager-fields widget_pager widget_pager_bottom views_slideshow_pager_field views-slideshow-pager-field-processed

So i imagine that an other function add the classes. But wich ?
How can i do this ? May i write a module or simply use a preprocess function in my template.php
Thanks
Comment: I think simple than a module will be to use the template.php file. Also check the views_slideshow module as it ships with some tpl.php files that you might be able use as well by making a copy of the same in your theme folder.
Comment: Yes i look the .tpl use : views-slideshow.tpl.php. i can override it but the class that i can add are on the wrapper of ALL the widgets (pager, controls, slide-counter). I would like add a class only on the wrapper of the pager widget, and why not, add a different class to the widget controls or slide-counter
Answer: In fact, after looking at the HTML code generated by views slideshow, pager widget is contained in a div on the same level that the content of the slideshow. So even if I could add a class, it would not be useful because I already positioned text to the right of my image. So the div content of the slideshow is already 100% of the width (and the sub-content have already custom classes to position them in line) .
So I have to use position: absolute to position the pager widget, so I can just add my classes on the container of all global gadgets (positioned at the bottom) by overriding the template views-slideshow.tpl.php as below, and then use the default classes of the widget in my css.
views-slideshow--MY-BANNER.tpl.php

<div class="skin-<?php print $skin; ?>">
  <?php if (!empty($top_widget_rendered)): ?>

      <?php print $top_widget_rendered; ?>

  <?php endif; ?>

  <?php print $slideshow; ?>

  <?php if (!empty($bottom_widget_rendered)): ?>

      <?php print $bottom_widget_rendered; ?>

  <?php endif; ?>

But I'd like to know if this is possible and with wich function.
Answer: Here is a hook_preprocess_HOOK() solution.
I couldn't find a way to add a class to theme_pager(), so I decided to take a closer look at the source and found that views pagers are also run through theme_item_list() which does allow you to add classes.
function MYTHEME_preprocess_item_list(&$vars) {
  $vars['attributes']['class'][] = 'my-class';
}

You can/should add an if condition check to see that the list really is going to be a pager, e.g. use if ($vars['attributes']['class'][0] == 'pager') or some other identifier to confirm that you're adding the class to a pager ul.


Marshalling information from JSON into MVC model classes

Question:
Possible Duplicate:
PHP MVC - Convert JSON to Model data

Is there an easy way using vanilla PHP, a PHP library, or Kohana to easily marshall information from a json encoded object into a Kohana MVC model object? The json_encoded object has the same fields as the model object, but none of the functionality. Is there a generally accepted way of avoiding this silly dance?
It just feels like I am constantly writing code to move data around with code like:
$array = json_decode(returnsObject());
$model = Model::factory("model");
$model->field1 = $array['field1'];
$model->field2 = $array['field2'];
.....

Now obviously I have this in a method, but it seems outlandish that there is not a better method of doing this.
Answer: This is the easy way.
Controller in MVC design pattern is responsible only for extracting data from users request and passing it to model layer and current view. Your code example is actually a almost acceptable implementation of controller's action ... that's of course, if you ignore the factory method anti-pattern and referring to domain objects as "models".
You could extent the Request class and add the method that extracts data from JSON string before returning it, but it would violate single responsibility principle.
Comment: Could you explain that last sentence a bit more? I am a little confused reading your answer.
Comment: @thatidiotguy do you mean the part about domain object or the factory method?
Comment: The domain object, sorry you edited right after I submitted comment.
Comment: The problem is partially related to fact that CodeIgniter was basically a Rails clone and the core ideas in Ko3 haven't really changed. It implemented the same perversion of original MVC pattern. In a proper implementation of MVC pattern you have two layers: presentation layer (which might contain controllers, views and templates) and model layer. The model is not a class or any single object. It is a layer which contains storage abstractions and structures, that encompass domain business logic (usually domain objects and services).
Comment: To be clear, the model does have functionality other than just a variable mule. If all it was doing was holding information, then the result of the `json_decode` function would return just what I need.
Comment: did you READ the link, that explained what domain objects are ?
Comment: Yes, are you saying that calling my "model" object a model in MVC lingo, is the problem you are pointing out with the framework?
Comment: Kinda both. It is a misnomer. But the historical lack of isolation between domain business logic and presentation layer is a flaw in framework. When you have interaction between two+ "models", you put it in the controller. But this is actually a part of business logic, that should stay in model layer (encapsulated in services). It is possible to implement a proper separation, but it is not a common practice and most of people are not aware of this being a problem. Thus turning this lack of separation in the main cause for fat controllers and skinny "models".


Character of induced representation: explicit formula

Question: I'm trying to work through Exercise 7.1 in Serre's "Linear Representations of Finite Groups" but I'm having trouble finishing my proof. The problem reduces to the following.
Let $N\subset H$ be a normal subgroup of a finite group $H$, and $V$ a $\mathbb{C}[H]$-module such that no nonzero vector is fixed by the whole of $N$. Let $\chi$ denote the corresponding character and $\pi: H\twoheadrightarrow H/N$ the projection. Prove that for any $t\in H/N$,
$$ \sum_{\pi(s)=t} \chi(s) = 0. $$
When $t=1$ I can prove this, since we can decompose $V$ into irreducible $N$-representations and none of these can be the trivial one; thus we can use orthogonality of characters to finish, by inner-producting $\chi$ with the trivial character. However if $t\neq 1$ I can't see how to finish. I would try to inner-product $\chi$ with the function $f:H\to \mathbb{C}$ that sends $\{s \mid \pi(s)=t\}$ to 1 and the rest to 0, but this isn't (necessarily) a class function!
EDIT: I should clarify that the title refers to using $\pi: H\twoheadrightarrow (H/N)=: G$ to induce a $G$-representation $Ind_H^G(V)$. (We don't need to assume no nonzero vector of $V$ is fixed by the whole of $N$). Then Serre asks to prove its character shall be, for $t\in G$,
$$ t \mapsto \frac{1}{|N|}\sum_{\pi(s)=t} \chi(s). $$
Answer: Let
$$\rho: H \rightarrow \mathrm{GL}(V)$$
denote the corresponding representation. Let
$$e_N:= \frac{1}{|N|} \sum_{n \in N} \rho(n) \in \mathrm{End}(V)$$
The endormorphism $e_N$ is just the projection of $V$ onto the $N$-invariant subspace, so, by assumption, $e_N = 0$ since $V^N = 0$.
We have $\chi(s) := \mathrm{Tr}(\rho(s))$. The elements of $H$ such that $\pi(s) = t$ are just the cosets (left or right since $N$ is normal) of some element in $H$, which by abuse of notation we can also call $t$. Thus
$$\begin{aligned} \sum_{\pi(s) = t} \chi(s) = & \
\sum_{n \in N} \chi(tn) \\
= & \ \sum_{n \in N} \mathrm{Tr}(\rho(t) \rho(n)) \\
= & \ \mathrm{Tr} \left( \rho(t) \sum_{n \in N} \rho(n) \right) \\
= & \ \mathrm{Tr} \left( \rho(t) |N| e_N \right)= \mathrm{Tr}(0) = 0.
\end{aligned}$$
ps. One usually reserves the notation $\mathrm{Ind}^{G}_{H}(V)$ to be the induction of a representation $V$ from a subgroup $H$ to $G$. Does Serre really use that notation? (Looks up bootleg copy of Serre -  he does not.) You should probably avoid it as it will cause confusion. The character turning up here is the character of $H/N$ acting on $V^N$. That's also easy enough to see from the same calculation above, since in general we get
$$\frac{1}{|N|} \sum_{\pi(s) = t} = \mathrm{Tr} \left( \rho(t) e_N \right)$$
which is just the trace of $t \in G/H$ acting on $V^N$.
Comment: Oh, nice finish! Thank you :). Btw, Serre uses $Ind_\alpha(V)$ where $\alpha:H\to G$ is any morphism (in this case an epimorphism). I guess it is confusing to use the notation I used in my statement, since that notation doesn't specify the morphism, and most people will assume I'm talking about an injection.


Add an appender for a portion of code

Question: For a certain portion of my code, I need to log all messages to a second file, specific to each instance of the action completed in two classes.
These classes (Parser and Importer) both have the following logger definition:
private static ILog _logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

Both also have this method:
public void AddAppender(IAppender appender)
{
    ((Logger)_logger.Logger).AddAppender(appender);
}

The whole project (ASP.NET WebForms) logging is initialized in the AssemblyInfo.cs:
[assembly: XmlConfigurator]

Now, when the user triggers a certain action, this happens:
var logFile = new FileInfo(ConfigurationManager.AppSettings["uploadDir"] + "/" + importId + "_log.txt");
var appender = new FileAppender() {
    Threshold = Level.Info,
    Layout = new PatternLayout("%message%newline"),
    File = logFile.FullName
};

var parser = new Parser(...);
parser.AddAppender(appender);
var candidates = parser.Parse(File.ReadAllLines(uploadFile.FullName));

var importer = new Importer(...);
importer.AddAppender(appender);
importer.Import(candidates, false, ignoreWarnings.Checked);

My expectation would be, that a file will be created at the logFile location, that would contain all INFO and above message from either of the two classes.
This, however, is not the case - no file is created at all.
What am I doing wrong and how can I make this work?
Comment: Does calling `appender.ActivateOptions()` right after construction help? Also, is this the only part where you're using log4net or can you see it working from other places? If not, initialization may simply not be happening at all. Try using `XmlConfiguration.ConfigureAndWatch` explicitly rather than relying on assembly attributes (which are unreliable).
Comment: Because of [this](https://logging.apache.org/log4net/release/sdk/html/T_log4net_Config_XmlConfiguratorAttribute.htm): "log4net will only look for assembly level configuration attributes once. When using the log4net assembly level attributes to control the configuration of log4net you must ensure that the first call to any of the `LoggerManager` methods is made from the assembly with the configuration attributes." This is fairly easy to get wrong in practice, especially in an ASP.NET project. Also, troubleshooting explicit initialization is way easier since you know when it's happening.
Comment: @JeroenMostert `ActivateOptions` did the trick! It works as expected now. PS: Why are assembly attributes unreliable? I was under the impression it was the preferred way to initialize log4net?
Comment: @JeroenMostert Okay, I see. Thanks for the info (and the answer).
Answer: Per the documentation of FileAppender:

This appender will first try to open the file for writing when
  ActivateOptions is called. This will typically be during
  configuration. If the file cannot be opened for writing the appender
  will attempt to open the file again each time a message is logged to
  the appender. If the file cannot be opened for writing when a message
  is logged then the message will be discarded by this appender.

This documentation is slightly ambiguous, since it seems to imply the file will be opened when you attempt to log a message in all cases, but this isn't true -- unless you call ActivateOptions, the appender is never considered ready for appending.

Add an appender for a portion of code


Why do I need to register $moment with the $injector before each Jasmine test?

Question: So, I'm writing some Jasmine unit tests for a controller which utilizes Moment.js. Moment.js is included in app.js like so:
.config(function ($momentProvider) {
  $momentProvider
    .asyncLoading(false)
    .scriptUrl('bower_components/moment/min/moment.min.js');
})

Then, I can just inject $moment into wherever. $moment isn't directly called from the controller, but some of the directives on the controlled page use it.
Originally, the controller unit tests failed with errors like these:
Error: [$injector:unpr] Unknown provider: cProvider <- c <- $moment <- myService <- $moment
Error: [$injector:unpr] Unknown provider: cProvider <- c <- $moment <- $moment

Later, I added some code to register $moment with the $injector inside of beforeEach, as follows:
beforeEach(function(){
  module('myApp');
  module('socketMock');

  module(function ($provide) {
    $provide.value('$moment', moment);
  });
});

I don't understand why this is necessary. I use other services in the controller (i.e. $cookieStore, $stateParams, and a whole bunch of custom services) that don't require this. Could it because those services are injected directly into the controller, but $moment is not ($moment is injected into some directives on the page, but not the controller)?
Comment: Does the module that your controller belongs to depend on the moment module?
Comment: @dskh I do not include the moment module as a dependency via angular.module('myApp', ['$moment']), if that's what you mean.
Answer: The module that your directive/controller under test is in needs to depend on the moment module.  It probably won't be called $moment - the $moment service is part of the moment module.
Let's take the example of one of your working services: $stateParams.  You are not needing to stub $stateParams because your module will depend on ui.router i.e.
angular.module('yourApp', ['ui.router'])

The $stateParams service is part of the ui.router module, so by depending on the ui.router module we can inject $stateParams.
I can't tell you the exact name of the module that $moment is in from the code provided, but hopefully the example above can help


How can I display unique names in Excel?

Question: Given the following table on sheet one:
Name
-------
Alan
Barb
Corey
Barb
Alan
Daniel
Alan

How can I generate the following table on sheet two?
Name
-------
Alan
Barb
Corey
Daniel

I cannot leave empty rows like this:
Name
-------
Alan
Barb
Corey

Daniel

Answer: I'm assuming you have Excel 2007 or later.
Copy the entire list, duplicates and all, to Sheet 2.
Then go to the Data tab. In the Data tools section there is a large button called "Remove Duplicates." It will do just that.
Answer: There is a formulaic approach that is not version-dependent. See Oscar's Site.
Answer: As far as I know, there is no way to do it formulaically.
If you just need a one-time copy, though, this article explains how to do it.


Filter by/Aggregate multiple columns in Power BI

Question: I would like to group by item and count for each store how many rows are there for my sales data.
table:
Id   Item   Store   Qty
1    A      store1  5
2    B      store1  2
3    A      store2  3
4    B      store2  10
  ....

To group by item I tried:
groupby_item = SUMMARIZE(table, table[Item], "Count", COUNT(table[Item]))

which gives the table:
Item   Count
A      2
B      2

but I want to introduce a Store slicer in a visual and I couldn't because Store column is absent in the aggregated table. Can I group by Store then by item and count?
Like in Python you could maybe do:
table.groupby('Item').agg({'Store': 'first', 'Id': 'count'})

to keep the Store information by keeping the first value of Store in each item group.
Would you be able to do that in Power BI? Or is there a better way to do this?
Answer: Why create an aggregate table in the first place?  You can use the base table in the visual and it would reflect any filters on Store.
The default behavior of PBI visuals is to group categorical columns and aggregate numerical ones.


How to structure database

Question: I'm using firestore and have a profile collection where each document consists of this model:
User
  - First name
  - Last Name
  - Bio
  - CreatedAt
  - Profile Pic
    - Location
    - Type

Now a user can record a video of a stream between two people. This video is stored and needs to be accessible by the two streaming people when they view their profile.
My plan is to have a separate collection called "Videos" where each video is as such:
Video
  - PersonAId
  - PersonBId
  - url
  - thumbnail

My first question is, should I be storing these in a separate collection, or should I just add the video to a "video" subcollection under each person's User model?
Secondly, I need to get the First name + Last name of PersonAId and PersonBId. Obviously one of those IDs is gonna be the user who's retrieving the video, so I will have their name, but will I then need to make a database call for the other ID in each video? Or is there an easier way to do that like being able to join collections?
Answer: You should create a separate collection for video, as it needed to be accessed by both. So why to create two entries, also separate collection would be easy to maintain and making query would at the easy approach.
I haven't seen any joins in their documentation, it's in dev pipeline.

How to structure database


Cross hands while playing?

Question: In the score below
(from 1905 incidental score to Peter Pan by John Crook (1852–1922),
see http://hdl.handle.net/1802/24425),
the first few bars in both bass & treble staves have notations "L.H." & "R.H.".
What's going on here?
Is this an indication that the performer ought to cross his hands while playing this piece?
Answer: That's exactly it. Most players are better playing block chords with l.h. and the fiddly bits with r.h., so the composer has designated cross hand playing.A good player could play it either way, though. It looks sort of good as well!I reckon that the l.h. is actually playing the 1st and 3rd bass notes with l.h. too. Otherwise the stretch would be a 10th, or even bigger in bar 4.  Bonus points for also crossing the eyes...
Comment: For an extreme and hilarious example, see https://www.youtube.com/watch?v=Aajtw30-YG0
Comment: "!I reckon that the l.h. is actually playing the 1st and 3rd bass notes with l.h. too." The notation on the bottom staff follows the convention that you play the notes with stems up with the RH and those with stems down with the LH. You could split up the notes of "the tune" between the hands and play it without any hand crossing, but it's probably just as irritating to play it either way.
Comment: It's too early yet to say this is the accepted answer. Please wait until others have put in their tuppenceworth.
Comment: I agree completely with @Tim.  This is a technique that is used quite a lot.  An extreme example would be Liszt's Third Concert Etude normally called  _"Un Sospiro"_
Comment: Haha, "bonus points" ...

A scenario like this typically does call for a tad bit of memorization unless you're REALLY a monster sight-reader.

Cross hands while playing?


js/jquery: scheduling events

Question: I want to schedule events, that will fire and call my predefined callback
How can schedule in js / jquery:

one time event?
recurring event (to call my function every minute, or five minutes)?
Answer: You want  setTimeout for a one time event and  setInterval for a repeating event.
Both take two arguments: a function and an interval of time specified in milliseconds.
var delay_millis = 1500;

//will alert once, at least half a second after the call to setTimeout
var onceHandle = window.setTimeout(function() {
  alert("Time has passed!");
}, delay_millis);

//will alert again and again
var repeatHandle = window.setInterval(function() {
  alert("Am I annoying you yet?");
}, delay_millis);

Bonus: if you keep around the values returned by calling these functions, you can cancel the callback if you need to.
var shutUpShutUp = function() {
  window.clearInterval(repeatHandle);
};

shutUpShutUp(); //now I can hear myself think.

Answer: jQuery has nothing to do with it. You need JavaScript timers: setTimeout() and setInterval()
Answer: A one-time event is just scheduled with a setTimeout call.  An easy way for a recurring event is to simply call setTimeout in the function that you are setting the timeout on.
Answer: The easiest way to schedule events (at predefined intervals) is window.setTimeout.
For a one time event, you set the timeout once and let the timeout fire.
For recurring events, you set the timeout once and then reset the timeout in the method that gets called.
Answer: You can bind a function to an event that will be run only once by using .one() in jQuery...
http://api.jquery.com/one/
For the problem of a timing threshold for an event, declare your event like this:
var clickAvailable = true;
$('#element').click(function(e) {
    if(!clickAvailable) {
       clickAvailable = false;
       //your code
       setTimeout(function() {
           clickAvailable = true;
       }, 5*60*1000); // 5 minutes...
    }
});

js/jquery: scheduling events


How to get the node id before saving the node in drupal 6?

Question: I have created a content type called 'inquiry.'  I am using the rules module to send an email after submitting an inquiry.  My requirement is to get the node id before it is saved.  I need to generate a link from that node id so the inquiry handler can view the inquiry by clicking on that link.
Comment: You can't get the node id of a new node *before* the node is saved. The node is generated in MySQL when the node is saved. As you use rules, just switch the event from presave to insert/update.
Answer: You can use hook_nodeapi presave option to get node content before saving the node.
Example :
<code>function MODULENAME_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  switch ($op) {
    case 'presave':
      print $node->nid;
      exit;
    break;
  }
}
</code>
Comment: This will not work ofr newly created nodes. On node creation $node->nid will not be set until the node is actually saved in the database. This will only works when an existing node is updated.
Comment: i have not created custom module , so what should i write in place of MODULENAME ..???
Comment: Karthi would reply "any name you want". But make sure that it's any string that can be used as a function name. But usually we use a lowercase short name for the module. it should be used in other hooks, in .info file name and event better in the module's folder name.


Transitioning from E minor to an "Asian" G major

Question: For a mutual friend's wedding, a cellist friend and I (violin) are trying to adapt Ludovico Einaudi's "Divenire" for the groomsmen walking in (as it's the groom's favorite song as of late), transitioning to the unofficial Korean national anthem, Arirang, because the bride is Korean and has specifically requested this.
Divenire is in A minor. The arrangement of Arirang we're playing is in... G major? (It goes D E D E G A G A B A B G E D.) The thing is, I don't know if this should be considered a different, "Asian" kind of scale. Because something about the missing Fourth and Major 7th makes it not "truly" sound like a major key to me.
Where I'm running into trouble is writing a transition from Divenire to Arirang. We don't want to change the key of Arirang, so I transposed my arrangement of Divenire from A minor to E minor, thinking E minor and G major should be doable. Like, we'd loop a bunch of whole notes at the end of our Divenire that transition the mood, until the first bridesmaid walks in, and then we begin Arirang from a violin solo.
But no matter what I try, E minor doesn't seem to go into this particular "brand" of G major. And I have a strong feeling it is connected to the missing Fourth and Major 7th because when I add those into a more "westernized" version of Arirang, the transition is easy.
Does anyone know what concepts I'm missing, and if there is a known way to do these kinds of transitions?
Thank you.
Comment: I don't know the song but the melody you've written here is very much G major pentatonic.  This can sound "Asian" but doesn't necessarily have to, the pentatonic is one of the most common sets of notes to use in all kinds of music, European folk music included. Take a look at this nice demonstration of how intuitive it is by bobby mcferrin https://www.youtube.com/watch?v=ne6tB2KiZuk Also this video shows is just how readily and easily major pentatonic modulates to and from the relative minor (when he sings dyaaa da da da above, that's exactly what's happening). , in fact, it's one of (cont.)
Comment: (cont.) the few "functional harmony" things you *can* do with the pentatonic, so that's not going to be the problem.  I'll have a listen to the einaudi song now.  Pretty much all of his music is diatonic chords thoughtlessly thrown together and repeated ad nauseum, so it shouldn't be too hard to get it to transition effectively by just throwing another couple of chords in.
Comment: Also just as a side note, it's seems a little strange to want to play a Korean folk song in the "original" key, since it will have existed long long before concert pitch was standardised, and for most of its history will have been played at a myriad of pitches.  I mean, how long has the Korean musical practice even included the western "notes"?  I don't know anything at all about Korean music, but I imagine the answer is a couple of hundred years at most?  Or do you just like the way that key for that melody works specifically on the violin, in which case, fair play.
Comment: Thank you for all of your comments, @Some_Guy! Very helpful. The actual reason we don't wanna change the key is indeed unrelated to history: we already have the folk song down, bowings and all, and the wedding is coming up very soon. Just trying to economize on effort :-) Totally agree with your points though.
Comment: please do give an update as to how it's going :) Also, sorry about my ...er... presentational style, the other night, although hopefully at least my content was helpful!
Answer: OK, so I didn't listen to the whole Einaudi song, but the last minute or so is a straight up Dorian vamp in A minor.
That is to say, it's a repetition of the following chords:
Am, C , G, D MAJOR
That is to say, this is a modal piece of music, not "minor" in the Bach-y sense.  Harmonically it's like "Scarborough fair" for example.  The harmonic progression is like that of Dorian folk music not like that of minor classical music: an E dominant seventh chord would sound ugly in this context for example, whereas an E minor chord would sound natural: a very different beast.
Transitioning from Dorian to major by going up a minor third works sometimes, but other times it sound odd, and the reason for that (like you've perceived here) is that the sharp 6 note is the augmented fourth of the major.
So in this example, you're coming straight from a big D major chord and trying to make that sound natural in C major.  (Or transposed as you have, you're trying to make an huge A major chord blend nicely into G major.)  It's awkward.
A better transition is to transition to the major key a whole tone below.  Good news for you, that's G major!  So you don't need to transpose either piece.  A minor, C major, G major, and D major are the bread and butter of G major anyway, so the transition is easy.  You can use an E minor to smooth things over if you like too.  It works quite well because it doesn't have much of a dominant pull back to A minor, and you can just smoothly walk it up to G through D major first inversion, and bingo, you're home!
Another option is to resolve the Einaudi piece on a minor, then flick back between A minor and E minor for a bit, then pay E minor, A7, D major, and land on Arirang in G major.
In short, keep it in a minor. The transition will be more natural.
http://vocaroo.com/i/s12Ao5Bkaxaf
Comment: @AreelXochaI will admit that my terminological choices may have been affected by my level of inebriation.
Comment: Am7-D7-G6 makes the ii-V for the modulation to G major. Am I jazzy yet, mom?
Answer: As others have pointed out, Arirang is based on a G major pentatonic scale which, while not strictly Asian, is used often in traditional asian music (traditional Chinese music for example, as opposed to traditional Japanese music which is usually based on a minor pentatonic scale). In fact, folk traditions of music are pretty universally based on the pentatonic scale, even for instance Mary Had a Little Lamb, or Auld Lang Syne.
As for your question, I agree E minor (the relative minor of G major) would be a good transposition for Divenire, and for the actual transition you have many options. You could vamp on an E minor chord, or continue to play the Em-G-D-Am progression of Divenire until it comes time to switch and then slow down and on the A minor, instead of switching back to E minor, hit a D major real quick before jumping into G major for the next song. Or even take the actual dramatic ending of Divenire (after vamping for enough time) and then just slide smoothly and slowly into Arirang. Just some suggestions.
Whatever you choose, I suggest avoiding the notes C and F# in whatever melody you play during the vamp, as those won't be present in Arirang in just a few seconds.
Comment: The problem isn't with Arirang, it's that the einaudi piece is dorian.  It'd be better to leave it in A minor and transition from there (or moving through E Aeolian)


Solution to ODE $ x'= x^3+ \sin( t)$ and showing it has a periodic solution

Question: I am used to finding periodic solution after finding the general solution.
I am kinda stuck at its general solution. Don't understand how to go about.
Any hint would do.
Also is there a way to prove that this equation has a periodic solution without finding the general solution?
Comment: I am afraid you won't find an analytical solution, Alpha couldn't.
Comment: Then is there a way to prove existence of periodic solution ?
Comment: If $x(t)$ is periodic with period $2\pi$, then so is $x'(t)$. So if there exists a solution such that $x(2\pi)=x(0)$, it will be periodic.

Notice that if $x(0)\ge0$, $x(t)$ is increasing and diverges to infinity. That's all I can say for now.
Answer: The cubic term provides positive feedback which causes exploding solutions in positive time direction with poles of the form $x(t)\approx\pm(2(t_*-t))^{-1/2}$.
Thus look at the reversed time direction. To have the more "intuitive" forward time direction consider $y(t)=x(-t)$. Then
$$
y'(t)=-y(t)^3+\sin(t).
$$
The same cubic term now provides negative feedback, moving large $y$ in the direction of the interval $[-1,1]$.
On the line $y=2$ we find that the slope $y'=-8+\sin(t)\le -7$ points down towards $0$, the same on the line $y=-2$ where $y'=8+\sin(t)\ge 7$ points upwards towards $0$. In conclusion, solutions starting in $[-2,2]$ stay inside that interval.
Let $f(a)$ denote the value $y(2\pi)$ of a solution for the initial value $y(0)=a$. If $\phi(t;t_0,y_0)$ is the flow, then $f(a)=ϕ(2\pi;0,a)$. $f$ is a continuous map from the interval $[-2,2]$ into itself. Thus there is at least one fixed point. The solution(s) to the fixed point(s) are $2\pi$-periodic.

black - periodic solution, red - nullcline $y=\sqrt[3]{\sin(t)}$
<code>import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint

def eqn(y,t): return -y**3+np.sin(t)
# flow
def f(a): return odeint(eqn, [a], [0, 2*np.pi], atol=1e-10, rtol=1e-9)[-1,0]
# apply simple fixed-point iteration
a=0.0
for k in range(15): print k, a; a = f(a)
tsol = np.linspace(0, 2*np.pi, 701)
ysol = odeint(eqn, [a], tsol, atol=1e-10, rtol=1e-9)

# generate streamplot
T, Y = np.meshgrid(np.arange(0, 6.35, 0.1), np.arange(-2, 2.05, 0.1))
dotT = 0*T+1
dotY = eqn(Y,T)

plt.streamplot(T, Y, dotT, dotY, density=2.5)
plt.plot(tsol, np.cbrt(np.sin(tsol)),'r',tsol, ysol,'k')
plt.grid(); plt.show()
</code>
Comment: Got it. Thanks. :)


Confused with the reference level in logistic regression in R

Question: I am confused with the answer from
https://stackoverflow.com/questions/23282048/logistic-regression-defining-reference-level-in-r
It said if you want to predict the probability of "Yes", you set as  relevel(auth$class, ref = "YES"). However, in my experiment, if we have a binary response variable with "0" and "1". We only get the estimation for probability of "1" when we set relevel(factor(y),ref="0").
n <- 200
x <- rnorm(n)
sumx <- 5 + 3*x
exp1 <- exp(sumx)/(1+exp(sumx))
y <- rbinom(n,1,exp1) #probability here is for 1
model1 <- glm(y~x,family = "binomial")
summary(model1)$coefficients
            Estimate Std. Error  z value     Pr(>|z|)
(Intercept) 5.324099  1.0610921 5.017565 5.233039e-07
x           2.767035  0.7206103 3.839849 1.231100e-04
model2 <- glm(relevel(factor(y),ref="0")~x,family = "binomial")

summary(model2)$coefficients
            Estimate Std. Error  z value     Pr(>|z|)
(Intercept) 5.324099  1.0610921 5.017565 5.233039e-07
x           2.767035  0.7206103 3.839849 1.231100e-04

I think if we want to get probability of "Yes", we should set relevel(auth$class, ref = "No"), am I correct? And what is reference level here means? Actually, what is glm() to predict in default if we use response other than "0" and "1"?
Answer: The reference level is the base-line. If you wanted to predict probability of 'Yes', you'd set the base-line (i.e. reference level) "No". So you are correct, I think the answer in the other thread is incorrect.
I prefer to set up the levels of variables explicitly using the factor function.
i.e.
    y = factor(y, levels=c(0,1), labels=c("No","Yes")
    # Reference level is listed first
    # I prefer to have character labels rather than 0,1.

Sorry, but I am unsure about what you're asking about for default behavior for the glm function when you've specified family="binomial" -- the function will expect a two-level factor as the response variable.


Shape of the hidden state of LSTM in Keras

Question: I have a question on Keras.
from keras.layers import Input, LSTM

inputs1 = Input(shape=(3, 1))
lstm1 = LSTM(1)(inputs1)

print lstm1

>> Tensor("lstm_1/TensorArrayReadV3:0", shape=(?, 1), dtype=float32)

In the above code, why is the shape of lstm1 (?, 1) instead of (1)? Doesn't LSTM(1) indicate that the shape of the last LSTM unit should be (1)? Where ? does come from?
Answer: You didn't specify the batch size. So Keras with assume that you have a dynamic input size that's why it is marked as '?'
inputs1 = Input(shape=(3, 1)) # batch shape = none
lstm1 = LSTM(1)(inputs1)
print(lstm1.shape)

>> TensorShape([Dimension(None), Dimension(1)]))

You can notice that once the batch size is not specified, you get 'None'.
Let's try to specify a batch size:
inputs1 = Input(shape=(3, 1), batch_shape=(2, 1, 1))
lstm1 = LSTM(1)(inputs1)
print(lstm1.shape)
print(lstm1)
>> TensorShape([Dimension(2), Dimension(1)])
>> <tf.Tensor 'lstm_6/TensorArrayReadV3:0' shape=(2, 1) dtype=float32>

You can notice that dimension has changed to (2,1) where 2 is the batch size.
Comment: Thanks for the answer. Let me ask one more question. If I change LSTM(1) to LSTM(1, return_sequences=True), then the output shape of lstm1 is (?, ?, 1). Shouldn't it be (?, 3, 1), since the sequence length is known (i.e., 3)?
Comment: There is a confusion:
In fact, printing `lstm1.shape` outputs the shape of the lstm layer before applying it to input, means the lstm layer shape would be a 3D tensor (None, None, 1). (it is not already compiled)
If you want  the output of your model:
`inputs1 = Input(shape=(3, 1))
lstm1 = LSTM(1, return_sequences=True)(inputs1)
model = Model(inputs=inputs1, outputs=lstm1)
print (model.summary())`

And result will be:
`Layer (type)               |Output Shape
input_6 (InputLayer)  | (None, 3, 1)
lstm_6 (LSTM)           | (None, 3, 1)`
An this is what you expect.
Answer: You didn't specify the batch size. TensorFlow (and Keras by extension) allows one or more axes to have their size determined at runtime. This unspecified axis is usually the batch size, but in the case of a sequential model, it can be useful to make that axis the sequence length.


Evaluate the closed form $\int_{0}^{\pi/2}\sin^k(x)\ln\left[\sin(x)\sin^2\left({x\over 2}\right)\right]\mathrm dx=F(k)$

Question: Proposed:

$$\int_{0}^{\pi/2}\sin^k(x)\ln\left[\sin(x)\sin^2\left({x\over 2}\right)\right]\mathrm dx=F(k)\tag1$$

Where $k=1,3,5,...$
Where $F(1)=-2$, $F(3)=-{17\over 18}$, $F(5)=-{587\over 900}$, $... $
It looks that $F(k)$ only yield rational numbers.
My try:
Split out the integral
$$\int_{0}^{\pi/2}\sin^k(x)\ln\sin(x)+2\int_{0}^{\pi/2}\sin^k(x)\ln\left[\sin\left({x\over 2}\right)\right]\mathrm dx\tag2$$
How may one find the closed form for $F(k)?$
Comment: It is enough to consider the Fourier series of $\log\sin$ and perform a bunch of tedious computations.
Comment: The integral isn't an integer for even $k$ - instead, we have the following
$$
\begin{array}{c|l}
k & \text{Integral Value}\\
\hline
0 & -2 C-\frac{3}{2} \pi  \log (2)\\
2 & \frac{1}{4} (-4 C+2+\pi -\pi  \log (8))\\
4 & \frac{1}{96} (-72 C+44+\pi  (21-54 \log (2)))\\
6 & -\frac{5 C}{8}+\frac{299}{720}+\frac{1}{192} \pi  (37-90 \log (2))\\
8 & -\frac{35 C}{64}+\frac{15371}{40320}+\frac{\pi  (533-1260 \log (2))}{3072}\\
10 & -\frac{63 C}{128}+\frac{142819}{403200}+\frac{\pi  (1627-3780 \log (2))}{10240}
\end{array}
$$ There is a clear pattern here and easy-to-conjecture general form
Comment: @JackD'Aurizio indeed, this is superboring to do
Comment: According to Mathematica, we have $$\int_0^{\pi/2} \sin^k(x) \log(\sin x ) \mathrm dx = \frac{\sqrt{\pi } \left(H_{\frac{k-1}{2}}-H_{\frac{k}{2}}\right) \Gamma
   \left(\frac{k+1}{2}\right)}{4 \Gamma \left(\frac{k}{2}+1\right)}$$ We clearly have a beta function with one constant parameter here, and I would guess we can write this in terms of double factorials and/or binomial coefficients
Comment: the result Looks terrible
Comment: The latter of your split integrals has simple forms in terms of Catalan's Constant, the natural logarithm, and Pi for integer $k$, but Mathematics doesn't give an answer for any non-integer $k$. @OP - what are the restrictions on $k$? $\mathbb{N}$? $\mathbb{Z}$? $\mathbb{R}$? $\mathbb{C}$?
Comment: Final edition. Proved and checked.
Answer: Let us try to achieve the required result, if possible using elementary approaches.
At first,
$$F(k) = \int\limits_{0}^{\pi/2}\sin^kx\ln\left({1\over2}\sin x(1-\cos x)\right)\,\mathrm dx = \int\limits_{0}^{\pi/2}\sin^kx\ln\left({\sin x\over2} - {\sin 2x\over 4}\right)\,\mathrm dx.$$
$\mathbf{k=1}$
$$F(1) = \int\limits_{0}^{\pi/2}\sin x\ln\left({1\over2}\sin x(1-\cos x)\right)\,\mathrm dx = \int\limits_{0}^{\pi/2}\ln\left({\sin x\over2} - {\sin 2x\over 4}\right)\,\mathrm d(1-\cos x).$$
By parts:
$$ F(1) = (1-\cos x)\left.\ln\left({1\over2}\sin x(1-\cos x)\right)\right|_{0}^{\pi/2} - \int\limits_{0}^{\pi/2}(1-\cos x)\,{{1\over2}(\cos x - \cos2x)\over{{1\over2}\sin x(1-\cos x)}}\,\mathrm d x$$
$$ = -\ln2 - \int\limits_{0}^{\pi/2}{\cos x - 1 + 2\sin^2 x\over{\sin x}}\mathrm dx = -\ln2 - 2\int\limits_{0}^{\pi/2}\sin x\mathrm dx + \int\limits_{0}^{\pi/2}{1-\cos x\over1-\cos^2x}\sin x\,\mathrm dx$$
$$ = -\ln2 + 2\cos x\biggr|_0^{\pi/2} - \int\limits_{0}^{\pi/2}{d(1+\cos x) \over1+\cos x}\,\mathrm dx = -\ln2 - 2 - \ln(1+\cos x)\biggr|_0^{\pi/2} = -2,$$
$$\boxed{F(1) = -2}.$$
$\mathbf{k=3}$
$$\int\limits_0^x\sin^3y\,\mathrm dy = \int\limits_0^x(1-\cos^2y)\sin y\,\mathrm dy$$
$$ = \int\limits_0^x\left(2(1-\cos y)-(1-\cos y)^2\right)\,\mathrm d(1-\cos y)  = \int\limits_0^{1-\cos x}(2t-t^2)\,\mathrm dy = J_3(1-\cos x),$$
where
$$J_3(t) = t^2-{1\over3}t^3.$$
Then
$$F(3) = \int\limits_{0}^{\pi/2}\sin^3x\ln\left({1\over2}\sin x(1-\cos x)\right)\,\mathrm dx = \int\limits_{0}^{\pi/2}\ln\left({\sin x\over2} - {\sin 2x\over 4}\right)\,\mathrm dJ_3(1-\cos x).$$
By parts:
$$ F(3) = J_3(1-\cos x)\left.\ln\left({1\over2}\sin x(1-\cos x)\right)\right|_{0}^{\pi/2} - \int\limits_{0}^{\pi/2}J_3(1-\cos x)\,{{1\over2}(\cos x - \cos2x)\over{{1\over2}\sin x(1-\cos x)}}\,\mathrm dx$$
$$ = -J_3(1)\ln2 - \int\limits_{0}^{\pi/2}J_3(1-\cos x){\cos x - 1 + 2\sin^2 x\over{\sin x(1-\cos x)}}\mathrm dx$$
$$ = -J_3(1)\ln2 + \int\limits_{0}^{\pi/2}{J_3(1-\cos x)\over\sin x}\mathrm dx - 2\int\limits_{0}^{\pi/2}{J_3(1-\cos x)\over1-\cos x}\sin x\,\mathrm dx$$
$$ = -J_3(1)\ln2 + \int\limits_{0}^{\pi/2}{J_3(1-\cos x)\over(1-\cos x)(1+\cos x)}\mathrm d(1-\cos x) - 2\int\limits_{0}^{\pi/2}{J_3(1-\cos x)\over1-\cos x}\,\mathrm d(1-\cos x)$$
$$ = -J_3(1)\ln2 + \int\limits_{0}^{1}{J_3(t)\over t(2-t)}\mathrm dt - 2\int\limits_{t}^{\pi/2}{J_3(t)\over t}\,\mathrm dt$$
$$ = -J_3(1)\ln2 + {1\over2}\int\limits_{0}^{1}{J_3(t)\over t}\mathrm dt + {1\over2}\int\limits_{0}^{1}{J_3(t)\over2-t}\mathrm dt - 2\int\limits_{t}^{\pi/2}{J_3(t)\over t}\,\mathrm dt$$
$$ = -J_3(1)\ln2 + {1\over2}J_3(2)\int\limits_{0}^{1}{\mathrm dt\over2-t} - {1\over2}\int\limits_{0}^{1}{J_3(t)-J_3(2)\over t-2}\mathrm dt - {3\over2}\int\limits_{t}^{\pi/2}{J_3(t)\over t}\,\mathrm dt$$
$$ = -J_3(1)\ln2 + {1\over2}J_3(2)\ln(2-t)\biggr|_{0}^{1} - {1\over2}\int\limits_{0}^{1}{J_3(t)-J_3(2)\over t-2}\mathrm dt - {3\over2}\int\limits_{t}^{\pi/2}{J_3(t)\over t}\,\mathrm dt$$
$$ = \left(-J_3(1)+{1\over2}J_3(2)\right)\ln2 - {1\over2}\int\limits_{0}^{1}{J_3(t)-J_3(2)\over t-2}\mathrm dt - {3\over2}\int\limits_{t}^{\pi/2}{J_3(t)\over t}\,\mathrm dt$$
$$ = \left(-{2\over3}+{1\over2}\cdot{4\over3}\right)\ln2 - {17\over18} = -{17\over18}$$
(see also Wolfram Alfa),
$$\boxed{F(3) = -{17\over18}}.$$
$\mathbf{k=2n+1}$
Similarly,
$$\int\limits_0^x\sin^{2n+1}y\,\mathrm dy = \int\limits_0^x(1-\cos^2y)^n\sin y\,\mathrm dy = \int\limits_0^{1-\cos x}(2z-z^2)^n\,\mathrm dz = J_{2n+1}(1-\cos x),$$
where
$$J_{2n+1}(t) = \int\limits_0^{t}(2z-z^2)^n\,\mathrm dz.$$
Then
$$F(2n+1) = \left(-J_{2n+1}(1)+{1\over2}J_{2n+1}(2)\right)\ln2 $$
$$- {1\over2}\int\limits_0^1{J_{2n+1}(t)-J_{2n+1}(2)\over t-2}\,\mathrm dt- {3\over2}\int\limits_0^1{J_{2n+1}(t)\over t}\,\mathrm dt.$$
Note that
$$J_{2n+1}(1) = \int\limits_0^1(2t-t^2)^n\,\mathrm dt = \int\limits_0^1(1-(1-t)^2)^n\,\mathrm dt = \int\limits_0^1(1-t^2)^n\,\mathrm dt = {\sqrt{\pi}\,\Gamma(n + 1)\over2\Gamma(n + 3/2)}$$
(see also Wolfram Alfa),
$$J_{2n+1}(2) = \int\limits_0^2(2t-t^2)^n\,\mathrm dt = {\sqrt{\pi}\,\Gamma(n + 1)\over\Gamma(n + 3/2)} = {n!\cdot2^{n+1}\over(2n+1)!!}$$
(see also Wolfram Alfa), therefore
$$F(2n+1) = - {1\over2}\int\limits_0^1{J_{2n+1}(t)-J_{2n+1}(2)\over t-2}\,\mathrm dt- {3\over2}\int\limits_0^1{J_{2n+1}(t)\over t}\,\mathrm dt,$$
and the integrands are polynomials with rational coefficients.
Besides,
$$J_{2n+1}(t) - J_{2n+1}(2) = \int\limits_2^t(2y-y^2)^n\,\mathrm dy = -\int\limits_2^t((2-y)(2-(2-y))^n\,\mathrm d(2-y) = -\int\limits_0^{2-t}(z(2-z))^n\,\mathrm dz = -J_{2n+1}(2-t).$$
That gives
$$\boxed{F(2n+1) = - {1\over2}\int\limits_0^1\left(R_n(2-t)+3R_n(t)\right)\,\mathrm dt},$$
where
$$\boxed{R_n(t) = {1\over t}\int\limits_0^t(2z-z^2)^n\,\mathrm dz}.$$
This allows one to obtain closed form for the required integrals (as shown below) and explains the rational form of the results.
The general formula
Let us use Newton binomial formula
$$(2z-z^2)^n = z^n(2-z)^n = z^n\sum\limits_{i=0}^n\genfrac{(}{)}{0}{0}{n}{i}(-1)^i\cdot2^{n-i}z^i,$$
then
$$R_n(t) = {1\over t}\int\limits_0^t(2z-z^2)^n\,\mathrm dz$$
$$ = {1\over t}\sum\limits_{i=0}^n\genfrac{(}{)}{0}{0}{n}{i}(-1)^i\cdot2^{n-i}\int\limits_0^t z^{n+i}\,\mathrm dz = \sum\limits_{i=0}^n{(-1)^i\over n+i+1}\genfrac{(}{)}{0}{0}{n}{i}\cdot2^{n-i}t^{n+i},$$
$$F(2n+1) = - {1\over2}\int\limits_0^1\left(R_n(2-t)+3R_n(t)\right)\,\mathrm dt$$
$$ = - {1\over2}\sum\limits_{i=0}^n{(-1)^i\over n+i+1}\genfrac{(}{)}{0}{0}{n}{i}\cdot2^{n-i}\int\limits_0^1\left((2-t)^{n+i}+3t^{n+i}\right)\,\mathrm dt $$
$$ = - {1\over2}\sum\limits_{i=0}^n{(-1)^i\over (n+i+1)^2}\genfrac{(}{)}{0}{0}{n}{i}\cdot2^{n-i}\left(-(2-t)^{n+i+1}+3t^{n+i+1}\right)\biggr|_0^1 $$
$$ = - {1\over2}\sum\limits_{i=0}^n{(-1)^i\over (n+i+1)^2}\genfrac{(}{)}{0}{0}{n}{i}\cdot2^{n-i}\left(2+2^{n+i+1}\right),$$
$$\boxed{\boxed{F(2n+1) = -4^n\sum\limits_{i=0}^n{(-1)^i\over (n+i+1)^2}\genfrac{(}{)}{0}{0}{n}{i}(1+2^{-n-i})}}.\tag1$$
Results
Calculation results by $(1)$ using the Wolfram Alpha program (сliсk to the right symbols "="):
$\mathbf{n=0}\quad F(1)\ $=$\ -2$
$\mathbf{n=1}\quad F(3)\ $=$\ -\dfrac{17}{18}$
$\mathbf{n=2}\quad F(5)\ $=$\ -\dfrac{587}{900}$
$\mathbf{n=3}\quad F(7)\ $=$\ -\dfrac{629}{1225}$
$\mathbf{n=4}\quad F(9)\ $=$\ -\dfrac{342319}{793800}$
$\mathbf{n=5}\quad F(11)\ $=$\ -\dfrac{3613679}{38419920}$
Done!
Comment: Please avoid absolutely using formulas such as $$\int_0^xf(x)dx$$
Comment: @Did Hi! Fixed, thank you.


How to reverse engineer a section of a Drupal Page

Question: Sorry if this is a beginner or inappropriate question, but I'm trying to work on modifying a complex Drupal site and I have no idea how to find out how it's built.
At the top of the home page there's a bunch of content (specifically an image that moves and zooms like a google map) but I can't find anything about how to edit or control this area.
Where should I look? Views, Blocks, or in the Theme files? I've tried looking through all of these as best as I know but I'm hitting dead ends.
Thanks!
Comment: can you provide screen shots as to what section you are trying to figure out? Is there a front-page.tpl?
Comment: You could also try to look at the source code (firebug e.g.) that most of the time reveals a bit more of what happens. And as DMAC mentioned already, the template files in your theme folder will give you more insight.
Comment: It's hard to be specific, but starting with the markup is usually the way to go. Look at the classes on the elements surrounding the area you're interested in - normally that'll tell you whether you're looking at a view, panel, rendered node, etc. Bear in mind Views can be inside blocks, and each can be themed independently, and a block could easily contain a node containing a view containing other nodes, and so on, so it may get murky. Something like the [Theme Developer](https://www.drupal.org/project/devel_themer) module can help to identify templates, but it's known to be a bit buggy
Comment: Some themes hide their magic under the appearance settings.
Answer: Your question could use more specifics, but I think I understand what you are experiencing.
I've been there. If you cannot find it anywhere, a good bet is that it is part of the theme tpl pages. If you want to confirm this, you should go to the sites/all/themes/whatever-theme-you-are-using and search for files ending in .tpl.php, which are the files that control the theme you are currently using.
Frequently, any special effect or non-drupal configurable behaviour is likely inserted directly into these files. If your intention is to re-use whatever you are seeing at the top of the page, look for js (javascript) files: it is likely that dynamic pages are using some library, and that by googling the js filenames you can find a reference that might be useful.
At least, it has worked for me.


Any solution to this question using sine law?

Question:
Suppose $ABCD$ is a cyclic quadrilateral and $x, y, z$ are the distances
  of $A$ from the lines $BD, BC, CD$ respectively. Prove that $\frac{BD}{x} = \frac{BC}{y} + \frac{CD}{x}$

If it can't be proved using law of sines, what are other easy methods?
Answer: By  Ptolemy's Theorem
$\, AC \cdot BD =  BC \cdot AD +AB \cdot CD .\, $ Divide both sides by the same value
$$ AB \cdot AC \cdot AD \quad \text{to get} \quad
\frac{BD}{AB \cdot AD} = \frac{BC}{AB \cdot AC} + \frac{CD}{AC \cdot AD} $$
where the denominators are proportional to $\, x,y,z \,$ respectively. This is because the distance from $\, A \,$ to line $\, BD,  \,$ for example, is the length of the perpendicular to that line, and using the law  of sines is equal to $\, AB \cdot AD \,$ divided by the diameter of the circle. That is the key result used here.
We prove the result for any triangle $\, ABC. \,$ Drop a perpendicular from $\, A \,$ to the opposite side $\, BC \,$ which splits the triangle into two right triangles which share the perpendicular. By definition of $\, \sin \,$ and the law of sines, the length of the perpendicular is equal to $\, b \sin(C) = c \sin(B) = b \, c / (2R) \,$ where $\, 2R \,$ is the diameter of the circumscribed circle of $\, ABC. \,$


how to retrieve field collection data associated with a node

Question: I have an event node which contains a reference to a gallery field collection. If I do a dump of the $variables variable, I can find this
<code>$variables -> field_gallery_image['und'][0]['value']
</code>
but I don't know where to use that value to do a table look up to actually find the data in the field collection. I was able to find that id number in the field_collection_item table, and then was able to find that id in the field_data_field_image table (I have an image field), but I'm not sure where to go from here.
Comment: Where do you want to use this value? In `node.tpl.php`?
Answer: I believe you are looking for field_collection_item_load or field_collection_item_load_multiple function both are in field_collection.module
Comment: can those functions be called from inside of the theme template, or do I need a custom module? I want to be able to use the data for display purposes.
Comment: That did it, thanks! I used that function in a custom block.


Calling CGI python script as root from a web form

Question: I'm having difficulty getting a web form to run a CGI script that needs to perform a command with root permission. The form is:
<form class="mainform" action="./py/print_msg.py" method="POST">
    <textarea name="post" cols=70 rows=20></textarea>

    <input type="submit" value="Print" class="button">
    <input type="reset" value="Clear" class="button">
</form>

The python script print_msg.py is executable (-rwxr-xr-x 1 root  root) and a version that just prints strings to the browser work ok, so apache's CGI settings seems ok.
#!/usr/bin/env python

from Adafruit_Thermal import *

print "Content-type: text/html\n\n"

printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5)
printer.wake()
time.sleep(1)
print "test"
printer.sleep()

This works when root runs it.  I've edited /etc/sudoers as follows:
www-data ALL=(ALL) NOPASSWD: /usr/bin/sudo -u root /home/pi/www/html/py/print_msg.py

Not sure if this means www-data can run that script as root or if it will do so without needing to invoke sudo?  Now when I call the page I get:
Traceback (most recent call last):
  File "/var/www/html/py/print_msg.py", line 7, in <module>
    printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5)
  File "/home/pi/www/html/py/Adafruit_Thermal.py", line 73, in __init__
    Serial.__init__(self, *args, **kwargs)
  File "/usr/lib/python2.7/dist-packages/serial/serialutil.py", line 261, in __init__
    self.open()
  File "/usr/lib/python2.7/dist-packages/serial/serialposix.py", line 278, in open
    raise SerialException("could not open port %s: %s" % (self._port, msg))
serial.serialutil.SerialException: could not open port /dev/ttyAMA0: [Errno 13] Permission denied: '/dev/ttyAMA0'
[Wed Jun 01 13:50:04.383712 2016] [cgid:error] [pid 30345:tid 2993681456] (104)Connection reset by peer: [client 192.168.1.158:51239] AH02550: Failed to flush CGI output to client, referer: http://192.168.1.174/

Do I not have the right sudoers line perhaps?  Grateful for assistance.
Comment: Changing `sudoers` won't help, because Apache doesn't use `sudo` to start the CGI process. Instead, you should give the `/dev/ttyAMA0` device file permissions that allow the `www-data` user to access it directly.
Comment: @geotheory It's **much** safer than having the CGI script run as root.
Comment: `su` to `www-data` and find out if it can run it with sudo? If `www-data` is not allowed a shell you might not be able to execute anything
Comment: @Recct I tried that, but I got prompted for a www-data password, and I'm not sure if it's safe to set one..?
Comment: @MosheKatz OK I added www-data to group tty, and chmod 660 ttyAMA0 (from 600).  Well it works, but is it a safe thing to do?
Answer: If you don't want to request root access each time you need to install this: https://github.com/quick2wire/quick2wire-gpio-admin
Answer: #!/usr/bin/env python

from Adafruit_Thermal import *

print "Content-type: text/html\n\n"

printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5)
printer.wake()
time.sleep(1)
print "test"
printer.sleep()

Cross domain ?
Can't pause CGI out ! (0.1 second delay will be corrupted your data)

Like this :
import cgi # Maybe need form value etc.
form = cgi.FieldStorage()

myVar = "Failed : "
def myHandler(myVar = myVar):
    try :
        #Do stuf here !
        myVar = myContent

    except Exception,e :
        myVar += str(e)

myHandler()#we don't need any arguments !

print "Content-Type: text/html;charset=utf-8;" # What is your ContentType ?
print "Access-Control-Allow-Origin:*"
print
print myVar

This is the basic flowchart (do not use it in this way without securing it)


Selecting X amount of rows from one table depending on value of column from another joined table

Question: I am trying to join several tables. To simplify the situation, there is a table called Boxes which has a foreign key column for another table, Requests. This means that with a simple join I can get all the boxes that can be used to fulfill a request. But the Requests table also has a column called BoxCount which limits the number of boxes that is needed.
Is there a way to structure the query in such a way that when I join the two tables, I will only get the number of rows from Boxes that is specified in the BoxCount column of the given Request, rather than all of the rows from Boxes that have a matching foreign key?
Script to initialize sample data:
CREATE TABLE Requests (
  Id int NOT NULL PRIMARY KEY,
  BoxCount Int NOT NULL);

  CREATE TABLE Boxes (
  Id int NOT NULL PRIMARY KEY,
  Label varchar,
  RequestId INT FOREIGN KEY REFERENCES Requests(Id));

  INSERT INTO Requests (Id, BoxCount)
  VALUES
  (1, 2),
  (2, 3);

  INSERT INTO Boxes (Id, Label, RequestId)
  VALUES
  (1, 'A', 1),
  (2, 'B', 1),
  (3, 'C', 1),
  (4, 'D', 2),
  (5, 'E', 2),
  (6, 'F', 2),
  (7, 'G', 2);

So, for example, when the hypothetical query is ran, it should return boxes A and B (because the first Request only needs 2 boxes), but not C. Similarly it should also include boxes D, E and F, but not box G, because the second request only requires 3 boxes.
Comment: SQL questions work best when you provide `Create Table ...`and a few `Insert...` statements and describe the expected result based on those test data you provided
Answer: The INNER JOIN keyword selects records that have matching values in both tables
SELECT (cols) FROM Boxes
INNER JOIN Request on Boxes.(FK_column) = request.id
WHERE Request.BoxCount = (value)

Answer: select      r.id,
            r.boxcount,
            b.id,
            b.label
from        requests      r
cross apply (
               select   top (r.BoxCount)
                        id, label
               from     boxes
               where    requestid = r.id
               order by id
            ) b;

Answer: Here is another approach using ROWCOUNT - a common and useful technique that every sql writer should master. The idea here is that you create a sequential number for all boxes within a request and use that to compare to the box count for filtering.
with boxord as (select *,
                ROW_NUMBER() OVER (PARTITION BY RequestId ORDER BY Id) as rno
                from dbo.Boxes
                )
select req.*, boxord.Label, boxord.rno
from dbo.Requests as req inner join boxord on req.Id = boxord.RequestId
where req.BoxCount >= boxord.rno
order by req.Id, boxord.rno
;

fiddle to demonstrate


Is the square of the module of an entire function real differentiable?

Question: Let $\phi$ entire and such that $|\phi(0)|=1$. I am wondering if it is true that the function $\Phi$ given by $\Phi(t)=|\phi(t)|^2$ is real differentiable in some interval of the form $(p, q)$, where $p<q\in\Bbb R$ (maybe in $(0, +\infty)$ or $(1,+\infty)$?). Is that true of false?
If it is false, could you give me a counterexample please?
If it is false, could you tell me what is $\Phi'(t)$ please?
(I am looking for $\phi$ among those with "moderate growth" but I can't find a counterexample)
Comment: Is the small φ differentiable?
Comment: If $\phi$ is holomorphic on $\mathbb{C}$ (and hence, in particular, smooth on $\mathbb{R}^2$), then $\overline{\phi}$ is antiholomorphic on $\mathbb{C}$ (and hence, in particular, smooth on $\mathbb{R}^2$), so that $\Phi = \lvert \phi \rvert^2 = \phi \overline{\phi}$ is the product of two smooth functions on $\mathbb{R}^2$, and hence itself smooth on $\mathbb{R}^2$.
Comment: @dmtri yeap, it is entire
Comment: @BranimirĆaćić What it the derivative of $\Phi$?
Comment: @BranimirĆaćić It is $\Phi'(t)=2\phi_R(t)\phi'_R(t)+2\phi_I(t)\phi'_I(t)$, where $\phi_R$ and $\phi_I$ are the real and imaginary parts of $\phi$, right?
Comment: Indeed. An equivalent expression is in my answer below.
Answer: If $\phi$ is holomorphic on $\mathbb{C}$ (and hence, in particular, smooth on $\mathbb{R}^2$), then $\overline{\phi}$ is antiholomorphic on $\mathbb{C}$ (and hence, in particular, smooth on $\mathbb{R}^2$), so that $\Phi = \lvert \phi \rvert^2 = \phi \overline{\phi}$ is the product of two smooth functions on $\mathbb{R}^2$, and hence itself smooth on $\mathbb{R}^2$. In particular, since
$$
 \frac{\partial}{\partial x} = \frac{\partial}{\partial z} + \frac{\partial}{\partial \bar{z}}, \quad \frac{\partial}{\partial y} = i\left(\frac{\partial}{\partial z} - \frac{\partial}{\partial \bar{z}}\right),
$$
and since
$$
 \frac{\partial\phi}{\partial z} = \phi^\prime, \quad \frac{\partial\phi}{\partial\bar{z}} = 0, \quad \frac{\partial\bar{\phi}}{\partial z} = \overline{\frac{\partial\phi}{\partial\bar{z}}} = 0, \quad \frac{\partial \bar{\phi}}{\partial \bar{z}} = \overline{\frac{\partial\phi}{\partial z}} = \overline{\phi^\prime},
$$
it follows that
$$
 \frac{\partial \phi}{\partial x} = \phi^\prime, \quad \frac{\partial\phi}{\partial y} = i\phi^\prime, \quad \frac{\partial\bar{\phi}}{\partial x} = \overline{\phi^\prime}, \quad \frac{\partial\bar{\phi}}{\partial y} = -i\overline{\phi^\prime},
$$
and hence that
$$
 \frac{\partial\Phi}{\partial x} = \phi^\prime\bar{\phi}+\phi\overline{\phi^\prime}, \quad \frac{\partial\Phi}{\partial y} = i\left(\phi^\prime\bar{\phi}-\phi\overline{\phi^\prime} \right),
$$
where $\frac{\partial\Phi}{\partial x}$ is the derivative you want.


Swift 3 - Generated QR Code UIImage to be attached to email but I get error "found nil while unwrapping an Optional value"

Question: I have the QR Code generator working, it display image to my qrImageView UIImageView.
Now, what I want to do is attach that QR Code image to email. Tried the code specified below but I get an error "found nil while unwrapping an Optional value".
Please help!
Function for generating QR CODE
  func generateQRCode(from string:String) -> UIImage? {

    let data =  string.data(using: String.Encoding.isoLatin1)

    if let filter = CIFilter(name:"CIQRCodeGenerator") {
        filter.setValue(data, forKey: "inputMessage")
        let transform = CGAffineTransform(scaleX: 100, y: 100)

        if let output = filter.outputImage?.applying(transform) {
            return UIImage(ciImage: output)
        }
    }
    return nil
}

@IBAction func generateAction(_ sender: Any) {

    if let actualText = qrCodeTextField.text {
        let image = generateQRCode(from: actualText)
        qrImageView.image = image
    }

}

Code for attaching QR Code to Email
func configureMailController() -> MFMailComposeViewController {
    let mailComposerVC = MFMailComposeViewController()

    mailComposerVC.mailComposeDelegate = self

    mailComposerVC.setToRecipients(["email@example.com"])
    mailComposerVC.setSubject("\(subject) QR Code")
    mailComposerVC.setMessageBody("Please see attached QR Code", isHTML: false)

    //Add Image as Attachment

    if let image = qrImageView.image {
        let data: NSData = UIImagePNGRepresentation(image)! as NSData

        mailComposerVC.addAttachmentData(data as Data, mimeType: "image/png", fileName: "image")

    }

    return mailComposerVC

}

Answer: This works for me. I have to convert the CIImage first to UIImage so that the QRCode can be attached to email
func convert(cmage:CIImage) -> UIImage
{
    let context:CIContext = CIContext.init(options: nil)
    let cgImage:CGImage = context.createCGImage(cmage, from: cmage.extent)!
    let image:UIImage = UIImage.init(cgImage: cgImage)
    return image
}

Source: Unable to convert CIImage to UIImage in Swift 3.0
Answer: Try this,
if let image = qrImageView.image {
    let data = UIImagePNGRepresentation(image) as NSData?
}

Instead of
if let image = qrImageView.image {
    let data = UIImagePNGRepresentation(image)! as NSData
}

It seems that this is the only part of the code that force unwraps the value.
Comment: Hello. Thanks for your reply. I tried it and i still get the same error. It seems that it can't find any value inside the qrImageView.image even if it is currently displaying the QRCode image.
Comment: I believe this is the line of code that throws an error. It occurs whenever I click on the send email button. I actually tried this code ***   if let image = qrImageView.image {

            if let data = UIImagePNGRepresentation(image) {

                mailComposerVC.addAttachmentData(data, mimeType: "image/png", fileName: "image")

            }

        } *** and the email page shows up but it does not contain any attachment, only the subject, recipient and message body


why $\int \sqrt{(\sin x)^2}\, \mathrm{d}x = \int |\sin x| \,\mathrm{d}x$

Question: May be this is a stupid question but why $$\int \sqrt{(\sin x)^2}  \,\mathrm{d}x = \int |\sin x|  \,\mathrm{d}x$$ instead of $$\pm \int \sin x  \,\mathrm{d}x$$
I think may be because it violates the rule that a function can't have more than 1 output for a single input, which brings me to my next question does the intgrand need to be a function?
Comment: @user236182, if you are going to restrict to $x\geq 0$, then writing $\sqrt{x^2}=x$ suffices since $|x|=x~\forall~x\geq 0$. I think what you meant to write was $\sqrt{x^2}=|x|~\forall~x\in\Bbb R$.
Comment: when you use $\pm$ you do not know when things are positive and when negative. But leaving the absolute value as is, you do not face this complication.
Answer: In general: The symbol $\sqrt{a}$, for $a>0$ means the positive square root of the number $a$, so $\sqrt{a^2}$ is the positive number $x$ such that $x^2=a^2$, so it is $|a|$.
Answer: The definition of the square root, $\sqrt{\,\cdot\,}$, in real numbers is a function that given a non-negative number $y$, we take the non-negative number $x$ such that $x^2 = y$. That's why we write $$x^2 = k \Rightarrow x = \pm\sqrt{k}$$ instead of $$x^2 = k \Rightarrow x = \sqrt{k}.$$
We have to put the $\pm$ sign because the square root itself only considers the positive answer.
Observation: If the answer of square root was the two numbers, then it couldn't be a function.
Answer: Notice, in general $\sqrt {a^2}=|a|=a\ \ \ \forall\ \  a\ge 0$
$$\int \sqrt{(\sin^2x)}\ dx=\int |\sin x|\ dx=\int \sin x\ dx\ \ \ \forall \ \ x\in \left[2n\pi, 2n\pi+\pi\right]$$
$$=-\cos x+C$$

Edit: $$|\sin x|=\begin{cases}-\sin x\ \ \ \ \forall \ \ \ x\in[(2n-1)\pi, 2n\pi]\\
\sin x\ \ \ \ \ \ \ \ \forall \ \ \ x\in[2n\pi, (2n+1)\pi]
 \end{cases}$$
  where, $n$ is any integer


Using Lax Milgram to find a weak solution in an intersection of Sobolev spaces

Question: I am trying to prove the existence of a weak solution of the problem:
$$
-\Delta^2 u = f \in L^2(U)\\ \\
u|_{\partial U}=\Delta u|_{\partial U} = 0
$$
on the bounded open set $U\subset\mathbb{R}^n$ which has smooth boundary. The weak formulation follows from multiplying by the test function $v$ and integration by parts:
$$
\int_U fv\,dx= \int_U \, (\Delta^2 u) v\, dx= \int_U \Delta u \Delta v \, dx + \int_{\partial U} (v \frac{\partial \Delta u}{\partial n} - \frac{\partial v}{\partial n}\Delta u)dS.
$$
The second boundary vanishes for $\Delta u|_{\partial U} = 0$ and to make the first boundary term vanish we require $v$ to be in the Sobolev space $H^1_0(U)\cap H^2(U)$, so that $v=0$ on the boundary.
Therefore $u\in H^1_0(U)\cap H^2(U)$ is a weak solution if:
$$
\int_U \Delta u \Delta v \, dx = \int_U fv\,dx\,\,\,\, \forall v\in H^1_0(U)\cap H^2(U).
$$
Now I want to use the Lax-Milgram theorem on the bilinear form $B[u,v]=\int_U \Delta u \Delta v \, dx$. My problem is: what norm on $H^1_0(U)\cap H^2(U)$ should I use? At first I thought I could use either one of the norms of $H^1_0(U)$ or $H^2(U)$, since clearly $H^1_0(U)\cap H^2(U)$ is a closed subspace of both spaces. However I realized that this argument must be wrong, otherwise I might as well use the norm of the subspace $H^{8}(U)$ and conclude there exists a weak solution in that space.
Or should I use Lax Milgram for both $H^1_0(U)$ and $H^2(U)$ and conclude that the weak solution is in their intersection?
My second problem: when proving the coercivity of $B[u,v]$, I think I need an inequality like $\int_U |\Delta u|^2 dx \geq C\int_U u^2 dx$ for some constant $C$. I know this holds for $u\in H^2_0(U)$ but I don't see why this should hold in $H^1_0(U)\cap H^2(U)$?
Comment: These are called Navier boundary conditions, and the usual way of dealing with them is to treat them as a system of equations.
Comment: You mean using Lax-Milgram on $-\Delta u = w$ and $-\Delta w = f$, with $u =0$ and $w=0$ on the boundary? I then get two weak solutions $u$ and $w=-\Delta u$ in $H^1_0(U)$. Wouldn't that mean that $u$ is in $H^1_0(U)\cap H^3(U)$ rather than $H^1_0(U)\cap H^2(U)$?
Comment: Um. Yes, but $H^3(U) \subset H^2(U)$, so isn't that okay?
Comment: It is, but I'm not sure the weak solution is supposed to be in $H^3(U)$. Also, $w = -\Delta u$ implies that $w$ is a strong solution which I didn't prove, so I can really only conclude that $u \in H^1_0(U)$ if I use the method of the system of equations. The problem is the $u\in H^2 (U)$ part.
Comment: Just a quick comment (I might expand this into an answer if I find time): I am not sure what you mean by "using a norm". Where exactly do you need a norm in Lax-Milgram? As for the second problem, I am pretty sure your bilinear form is coercive in the sense that you have $B(u,u)+\gamma\|u\|_{L^2}^2>c\|u\|_{H^2}^2$ in $H^1_0\cap H^2$ for some (large) constant $\gamma$. It might even be true with $\gamma=0$. Spend some energy on this please.
Comment: @timur: I was able to prove coercivity just now. I need a norm for Lax-Milgram, because if I want to find a weak solution $u$ in a Hilbert space $H$, I must prove that $B[u,u] \geq \alpha ||u||_H^2$. Hence if I use the $H^2(U)$ norm, I can only conclude the existence of a weak solution in $H^2(U)\cap H^1_0(U)$ if that space is actually a Hilbert space with the $H^2(U)$ norm. Or am I missing something here?
Comment: I see. So what you need boils down to showing that $H^1_0\cap H^2$ is a closed subspace of $H^2$. Is that right? It is not clear to me why you would want to use $H^1$ norm, for instance, as in your question.
Comment: @timur: If it is indeed a closed subset of $H^2$ then that is indeed what I must prove.

A sequence $(u_n)$ in $H^2\cap H^1_0$ which converges to $u$ in the $H^2$ norm is naturally in $H^2$ and hence $H^1$. But why could we choose all $u_n$ to be in $C^{\infty}_c$, so that $u$ is in $H^1_0$?
Comment: If I understood correctly, you don't choose $u_n\in C^\infty_c$, but you choose $u_n\in H^2\cap H^1_0$.
Comment: Yes, but to prove that $H^2\cap H^1_0$ is closed, I need to prove that  $u\in H^2\cap H^1_0$, so I must prove $u\in H^1_0$ which requires that $u$ is the limit of some sequence in $C^{\infty}_c$. Perhaps this follows from the fact that all $u_n$ are in $H^1_0$, so all $u_n$ are limits of a sequence in $C^{\infty}_c$.
Comment: Just to make sure, note that the two limits you mention are different types of limits. The first one is in $H^2$, and the last one is in $H^1$.
Answer: Let $H=H_0^1\cap H^2$. A good norm to work with is $$\|u\|_H=\|\Delta u\|_2$$
As you can see here, this norm is equivalently to the usual one. Also, the inequality you are looking for is true, in fact, you have that $$\int |\Delta u|^2\geq\lambda_1^2\int|u|^2,\ \forall\ u\in H$$
where $\lambda_1$ is the firt eigenvalue associated with $(-\Delta, H_0^1)$. To prove this inequality, note that
\begin{eqnarray}
 \int |\nabla u|^2 &=& -\int u\Delta u       \nonumber \\
   &\leq& \|u\|_2\|\Delta u\|_2 \nonumber
\end{eqnarray}
From the last inequality, you can conclude by using Poincare inequality. Now you can easily apply Lax-Milgram.
Comment: Just a observation. You have to take off the sign of minus from your equation or change the weak formulation, because they are different.
Comment: Is it true that the second displayed formula is not exactly coercivity. One would want an $H^2$-norm in the right hand side.
Comment: @timur, I do not understood your comment. What formula is not coercive?
Comment: The second formula that is displayed. The left hand side is the $L^1$-norm of $\Delta u$, and the right hand side is the $L^1$-norm of $u$, multiplied by $\lambda_1^2$. My understanding is that in coercivity you need $H^2$-norm of $u$ in the right hand side.
Comment: You are right, there is an error there, as you can see in the proof a few lines down. I am gonna fixt it, thank you @timur.


Showing sequence is Cauchy in L^1 norm

Question: Let
$$f_n(x)=\begin{cases}
\left(x+\frac{1}{2}\right)^n,&\text{if }0\le x<\frac{1}{2}\\\\
1,&\text{if } \frac{1}{2}\le x\le 1\;.
\end{cases}$$
Then clearly $(f_n)$ is sequence in $C[0,1]$. I need to show this is cauchy sequence in $C[0,1]$ with $L^1$ norm.
My attempt  By definition of cauchy sequence, i think we need establish
$||f_n-f_m||<\epsilon$ for sufficiently large $m, n$
i.e. $\int^{1}_0 |f_n(x)-f_m(x)|dx<\epsilon$ for sufficiently large $m, n$
But,
$\int^{1}_0 |f_n(x)-f_m(x)|dx\\
=\int^{1/2}_0 |(x+1/2)^n-(x+1/2)^m|dx$
(Since on $[1/2,1]$ both $f_n$, $f_m$ are equal for all $m, n$ )
In next step i had used traingle inequality and spit the integral into two parts and obtained,
$\int^{1}_0 |f_n(x)-f_m(x)|dx\\
≤\int^{1/2}_0 |(x+1/2)^n| dx+\int^{1/2}_0 |(x+1/2)^m| dx$\
$=\frac{1}{n+1}[1-(1/2)^{n+1}]+\frac{1}{m+1}[1-(1/2)^{m+1}]$
But i am unable to obtain conclusion
Further, i like to know is there is any direct approach to conclude it is Cauchy sequence?
Comment: Use the triangle inequality, split up the integral using linearity, and evaluate those integrals. You should be able to calculate them explicitly.
Comment: @Oiler sir, i used traingle inequality,  but, unable to show it is less than $\epsilon$
Answer: Let $\varepsilon > 0$ be fixed. Note that
\begin{eqnarray*}
\int_{0}^{1/2} \left| (x + 1/2)^n - (x + 1/2)^m \right| \, dx & \leq & \int_{0}^{1/2}  \left| (x + 1/2)^n \right| \, dx + \int_{0}^{1/2}  \left| (x + 1/2)^n \right| \, dx \\
& = & \left[\frac{1}{n+1} - \frac{(1/2)^{n+1}}{n + 1} \right] + \left[ \frac{1}{n+1} - \frac{(1/2)^{m+1}}{m + 1} \right]\\
& < & \frac{1}{n} + \frac{1}{m}.
\end{eqnarray*}
From here, can you determine what constraints you must put on $n$ (resp. $m$) so tha $\dfrac{1}{n} < \dfrac{\varepsilon}{2}$?
Comment: @AkashPatalwanshi The terms in the numerator with powers of 1/2 are both negative and $\dfrac{1}{n+1} < \dfrac{1}{n}$
Comment: @AkashPatalwanshi Yes.
Comment: I'm not really sure I'm understanding your question correctly, but this is a direct proof. If you want to show a sequence is Cauchy, you have to show that it satisfies the definition.
Comment: Sir, How to obtain last inequality, $<\frac{1}{m}+\frac{1}{n}$?
Comment: Is that, mean $=\frac{1}{n+1}[1-(1/2)^{n+1}]+\frac{1}{m+1}[1-(1/2)^{m+1}]≤\frac{1}{n+1}+\frac{1}{m+1}<\frac{1}{n}+\frac{1}{m}$
Comment: Thank you so much sir for your help. I like to know, is there is any direct approach to conclude sequence is Cauchy in this space? Otherwise we need to check by definition, for each of Sequence in this space.

Showing sequence is Cauchy in L^1 norm


piling of two diffrent types of coins and permutation

Question: You have an unlimited supply of 2 types of coins(coin-1 and coin-2). You are asked to build a pile of 1000 coins such that the number of coins between any two coin-2 is not equal to five. So what is the maximum number of coin-2 that can be included in the pile?
i know permutation and combination bit well but this question seems different and unique to me, how to tackle such problem? please help, thank you.
Comment: So basically this is equal to building a string of length 1000 from A and B, so that the substring "BAAAAAB" is not present.
Comment: The approach of every even coin (only) is coin-2 is no good, since there are **presumably** 5 coins between positions 2 and 8.  The approach of every third coin, would work but is inferior to repeating the pattern of BBBBAAAAAA.  This pattern leads to 400 coins.  So the problem *semi-reduces* to showing that 400 is maximum, or showing an example for $k > 400$ and then proving that $k$ is maximum.
Comment: @MattiP. Although I could easily be wrong, I am interpreting the problem differently than you have commented.  As I see it, there must be no occurrence of BxxxxxB, where x can be A or B.
Comment: Correction to my 1st comment: bbaabbaabbaa... seems to work, so the maximum seems to be at least 500 (since 1000 is divisble by 4).
Comment: @user2661923 I got 502 as maximum
Comment: @RezhaAdrianTanuharja Did your pattern generally follow my last comment, with a minor variation, or did you come up with an entirely new pattern?
Comment: @user2661923 posted an answer :)
Answer: Evaluate the pile from bottom to top and list all the locations of coin-2: $\{x_{1},…,x_{m}\}$.
Say that there are no coin-2 pair with five coins between them. Then there are no $i<j$ that satisfy $x_{i}+6=x_{j}$ because otherwise there will be five coins between coin number $i$ and coin number $j$. Consequently, $\{x_{1},…,x_{m}\}$ and $\{x_{1}+6,…,x_{m}+6\}$ are $2m$ distinct integers between $1$ and $1006$. This give us an upper bound for $m$; $2m\leq1006\to m\leq 503$
However, $503$ is not the answer. Notice that $\{x_{1},…,x_{m}\}$ and $\{x_{1}+6,…,x_{m}+6\}$ are identical in modulo $6$ so if we write these in modulo $6$ we will get even number of each of $0,1,2,3,4,5$. Write $1$ to $1006$ in modulo $6$ and you'll see that $1,2,3,4$ appear $168$ times while $5,0$ appear $167$ times. Means at least one number with $0$ in modulo $6$ and one number with $5$ in modulo $6$ will not appear. Therefore the upper bound need to be revised: $2m\leq 1006-2\to m\leq 502$
Turn out, stacking $6$ coin-2 and $6$ coin-1 alternatingly gives us the desired pile and a total of $502$ coin-2.
Comment: yes, I got it, bbbbbbaaaaaabbbbbbaaaaaa... works.  Now, you have to prove that 502 is a maximum (if possible).  $2^{1000} \approx 10^{300}$ is clearly too big to pc-computer-sanity-check.  A reasonable alternative is to sanity-check the lesser case of 30 coins, since $2^{30} \approx 10^9$ should be small enough to pc-computer-sanity-check.
Comment: Check my second paragraph, I have proven that the maximum cannot be higher than $503$. If we want to have $503$, all numbers from $1$ to $1006$ must appear, try it and you'll realize why $502$ is the max
Comment: +1 to your answer.  However, I question the validity of your proof, which assumes that the optimal approach is to have blocks of consecutive coin-2's, followed by blocks of consecutive coin-1's.  While I strongly suspect that this is true, it is unclear to me that you have proven it.  However, it could be my shortcoming: it could be that you have actually proven it, and I am simply not grasping it.
Comment: @user2661923 I revised it, how about now?
Comment: Yes, it finally sank in, elegant proof.


How can I calculate a confidence interval for the percentage change between two means?

Question: The percentage change between two measurements is usually calculated as $100 \cdot \frac{x_2 - x_1}{x_1}$. If I have confidence intervals $(a_1, b_1)$ for $x_1$ and $(a_2, b_2)$ for $x_2$, is the confidence interval for the percentage change given as $100 \cdot \left ( \frac{a_2 - b_1}{b_1}, \frac{b_2 - a_1}{a_1} \right )$?
(The thought being that $a_2-b_1$ is the smallest difference, while $b_2-a_1$ is the greatest difference.)
Additional questions:

Is this valid for confidence intervals for variables other than the (sample) mean?
Is this valid for confidence intervals for sample means that were obtained for different sample sizes?
Is this valid regardless of the distribution of the (sample) mean?
Is this valid regardless of the procedure used to obtain the confidence interval (assuming that all the assumptions of the procedure were met)?

It would be nice to have references backing up every answer.
Comment: You can simplify a bit by asking for the distribution of the ratio of $x_2 / x_1$ and subtracting 1.
Answer: No, it is not valid:

It can produce nonsense: for example if $a_1=-1$, $b_1=2$, $a_2=-2$ and $b_2=3$ then your statement would produce a confidence interval for the percentage change starting at -200% and increasing to -400%.
The width of the confidence interval ought to depend on any dependence between the two random variables.
Even if the the random variables are independent and positive, the confidence interval will depend on their distribution.
Comment: What can be done that maybe you were thinking of is if you have say a 95% confidence interval [A, B] for a parameter m  and you want a 95% confidence interval for f(m) where f is monotone (either nondeceasing or nonincreasing) [F(A), F(B)] will be a 95% confidence interval for f(m) in the nondecreasing case and [F(B), F(A)] will be a 95% confidence interval in the nonincreasing case.
Comment: Thanks for disputing my proposed method. The reason I have not accepted this answer is that it does not answer the question proper, which is how to *actually* compute the confidence interval.
Comment: +1 Henry good point! To and to his points,a confidence interval is defined not only by its endpoints but also by it coverage (aka confidence level).  Say that you start with two 95% confidence intervals for your respective means and you construct a random interval based on the random endpoint from the confidence intervals (the endpoint are random variables when considering confidence levels and constants when evaluated on a particular sample) and you manipulate the endpoint to make them into your percentage change form.
Comment: (continued) Furthermore you take the two point estimates for the means and convert to a percent change for the estimates.  If that value falls within the interval you will have some sort of confidence interval for the percent change.  But what is its confidence level.  Not 95% and probably a lot less.
Comment: Can't you easily construct a $90\%$ confidence interval for $f(X,Y)$ as the range of values $f$ takes on a $95\%$ confidence interval for $X$ and a $95\%$ confidence interval for $Y$?
Answer:

If we have distributions of $x_1$ and $x_2$; just creates random $x_1$ and $x_2$ for $10000$ times, then generate $(x_2-x_1)/x_1$,  within $10000$ number to get CI.
2.
This question is similar in [Lancet paper DOI:https://doi.org/10.1016/S0140-6736(16)31678-6]
they use uncertainty intervals : Each of these 9·3 billion estimates was calculated 1000 times to determine uncertainty intervals.


Inserindo e atualizando dados em tabelas N-N (muitos para muitos)

Question: Estou com problema em salvar em um relacionamento de muitos para muitos, segue meu modelo:
public class Pessoa
{
    public int id { get; set; }
    public string descricao { get; set; }
    public ICollection<Conta> Conta { get; set; }
}

public class Conta
{
    public int id { get; set; }
    public string descricao { get; set; }
    public ICollection<Pessoa> Pessoa { get; set; }
}

Aqui está a configuração no meu contexto para n-n:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Pessoa>()
        .HasMany<Conta>(x => x.Conta)
        .WithMany(x => x.Pessa)
        .Map(x =>
        {
            x.ToTable("PessoaConta");
            x.MapLeftKey("pessoaId");
            x.MapRightKey("contaId");
        });
    base.OnModelCreating(modelBuilder);
}

Até aqui tudo bem: meu esquema de migrations funciona perfeitamente, mas gostaria de saber quando salvar os dados na tabela pessoa e tabela conta já inserir os valores respectivos na tabela pessoaConta. Desde já agradeço a todos.
Answer: As Collections precisam ser virtual. Procure também usar nomes no plural:
public virtual ICollection<Conta> Contas { get; set; }
public virtual ICollection<Pessoa> Pessoas { get; set; }

Faça alguns testes:
var fulano = new Pessoa { descricao = "Fulano" };
var beltrano = new Pessoa { descricao = "Beltrano" };
var sicrano = new Pessoa { descricao = "Sicrano" };

context.Pessoas.Add(fulano);
context.Pessoas.Add(beltrano);
context.Pessoas.Add(sicrano);

context.SaveChanges();

var conta = new Conta { descricao = "Conta Coletiva" };
conta.Pessoas = new List<Pessoa> { fulano, beltrano, sicrano };
context.Contas.Add(conta);

context.SaveChanges();

Comment: resolveu temporariamente, mas apareceu o seguinte problema. seria possível quando já tiver a conta e a pessoa registrada fazer a vinculação dos dados na tabela N-N
Comment: Aí você tem que mapear manual. [Veja mais aqui](http://pt.stackoverflow.com/search?q=user%3A2999+associativa).