Some basic questions about creating a webform handler from the module webform_example_handler

Question: I'm "cutting my teeth" in Drupal 8 on the Webform module so these are going to be rather naive questions.
I need to programmatically fill a URL field in the form with an XML file that
I generate from the other data in the form and do it just before the submit
so that the form is complete. To do so I figured using a webform handler is
the way to go and I have been using webform_example_handler as my
template.
Now for my ridiculous naivety, just a few basic questions:
In webform_example_handler.schema.yml the first line is:
"webform.handler.example". Is this a standard Drupal construct of <webform>.<handler>.<my_module>, or
something specific that must be followed set by the webform module
or am I completely off base on how this is derived?
I would guess that for my
module the line would be: webform.handler.dis_doc_gen?
The "webform.webform.webform_example_handler.yml" file: could someone explain the parts? In my module would it be: webform.webform.dis_doc_gen.yml ?
Last: I have built my webform through the interface so I assume that I don't
need the file "webform.webform.webform_example_handler.yml" as that would
only be for creating a webform from a yml file upon installing the module as
far as I can tell. However, is there something in my webform that I need to
set so that it knows about my
".../dis_doc_gen/src/Plugin/WebformHandler/DISDocGenWebformHandler.php"
handler?
Could someone please tell me what key thing(s) I need to do to make that connection or is that all automatic as long as you clear the Plugin cache? (I just discovered that cache through the "Admin Toolbar" module).
I realize this could be done through one of the webform hooks but I would rather use a handler as part of getting familiar with Drupal 8 in general.
Answer:
Could someone please tell me what key thing(s) I need to do to make
  that connection

There are 4 ways that you can tell Drupal that your plugin exists.
You can read about the other 3 at D8 Plugin discovery
In this case Webform uses:

AnnotatedClassDiscovery
The AnnotatedClassDiscovery class uses name of the annotations that
  contains the plugin definition, e.g., @Plugin, @EntityType, in plugin
  docblocks to discover plugins, minimizing memory usage during the
  discovery phase. The AnnotatedClassDiscovery class takes an argument
  in its constructor, $subdir, which specifies the
  sub-directory/sub-namespace for this plugin type. The
  AnnotatedClassDiscovery class scans PSR-4 classes inside those
  sub-directories of Plugin folders to find plugins (see a
  "Annotations-based plugins").

Side Note: Entities and blocks also use this "annotation" method.
This "annotation" is seen in webform_example_handler/src/Plugin/WebformHandler/ExampleWebformHandler.php

Yes, this info is inside a comment block, weird, but that's just how it works.

In webform_example_handler.schema.yml the first line is:
  webform.handler.example. Is this a standard Drupal construct of
  <webform>.<handler>.<my_module>, or something specific that must be
  followed set by the webform module or am I completely off base on how
  this is derived?

Wrong, otherwise it would've been named webform.handler.webform_example_handler.
It's actually webform.handler.<WebformHandler_id> (The ID you use in the annotation).
This is because your module can have multiple plugins, so it makes no sense to use the module's name here.

The webform.webform.webform_example_handler.yml file: could someone explain the parts? In my module would it be: webform.webform.dis_doc_gen.yml ?
Assuming your module is named dis_doc_gen, correct.

Last: I have built my webform through the interface so I assume that I
  don't need the file webform.webform.webform_example_handler.yml as
  that would only be for creating a webform from a yml file upon
  installing the module as far as I can tell

Correct, anything inside the /install folder, runs on install and that file is creating a form. Since you created one via the UI, you don't need this in your use case.
Comment: I've created the class `DisDocGenWebformHandler` but since it's already under the namespace `Drupal\dis_doc_gen\Plugin\WebformHandler` probably `DisDocGen` or `DisDocumentGenerator` would be clearer and avoid redundancy. Is there a convention for this or is this a matter of preference?
Comment: @user5429087 yes there is a convention. `10. Classes and interfaces should have names that stand alone to tell what they do without having to refer to the namespace, read well, and are as short as possible without losing functionality information or leading to ambiguity.` For more info read [Declaring Classes: Naming Conventions](https://www.drupal.org/node/608152#naming)
Comment: Thanks! For anyone else who sees this there is one more step to make it all work, although if you are familiar with D8 you will probably already know this, which is, once you set all this up you must also connect your handler to your form and you do so (in my case since I created the form through the UI) by using  `Webforms:Email/Handlers:Add Handler` where your newly created handler should now show up. You may need to clear the Plugin cache as well.


Trying to assign a 1 dimensional array from an arraylist to another variable

Question: So I have an arraylist whose elements are 1 dimensional arrays, and I am trying to access that arraylist, and save it's first element on another variable, using the following piece of code, but the compiler gives me an "incopatible types, Object cannot be converted to int" error
int[] k=new int[3];
k[0]=0;
k[1]=0;
k[2]=0;
ArrayList qu=new ArrayList();
qu.add(0,k);
int[] j=new int[3];
j= qu.get(0);

Comment: You might want to specify the generic type of the `ArrayList`, e.g. `ArrayList`
Answer: If you are not using generics, do an explicit cast
j= (int[]) qu.get(0);

or you can use generics. Notice that arrays are objects in java and hence can be used as type parameters.
ArrayList<int[]> qu=new ArrayList<int[]>();
qu.add(0,k);
int[] j=new int[3];
j= qu.get(0);


drush --quiet cron generates watchdog notices

Question: We have started using drush cron to manage our basic Drupal sites' scheduled tasks. I set this up using the guide at http://docs.drush.org/en/master/cron/ and it seems to be working well, except that these messages are generated on every run:
 [notice] WD Periodic: No periodic processes to run.
 [notice] WD cron: Cron run completed.

despite passing the --quiet option.
Is there a way to silence this output while still being made aware of any issues that come up with the cron task in future? We can redirect these two lines to standard out and filter on them but I wanted to find out if there is something about our Drupal setup that is causing the lines to be generated.
Our cron line is almost identical to the one in the article, but for the sake of completeness I've included it below:
0 * * * * apache /usr/bin/env PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin COLUMNS=72 /bin/drush --root=/path/to/our/drupal/site --uri=our.drupal.url --quiet cron

The drush version is 9.0-dev. Drupal version is 7.50.
Thanks for any suggestions you can provide.
Answer: drush cron simply calls the Drupal cron function. Drupal is initiating the watchdog messages; Drush implements system_watchdog() to convert these messages to drush log entries (Drupal 6 and 7).  If you set the option --watchdog=0, then these messages will not be printed by Drush.
If there is a problem with cron, then $? should still be set to a nonzero value when drush cron exits, and the watchdog messages will still be available in the Drupal Watchdog log (visible via drush watchdog).
If you need a finer level of control over the error behavior of Drush cron, please submit a feature request in the issue queue.
Comment: Great, --watchdog=0 did the trick. Thank you very much.


Error: "Input is not proper UTF-8, indicate encoding !" using PHP's simplexml_load_string

Question: I'm getting the error:
parser error : Input is not proper UTF-8, indicate encoding ! Bytes: 0xED 0x6E 0x2C 0x20
When trying to process an XML response using simplexml_load_string from a 3rd party source. The raw XML response does declare the content type:
<?xml version="1.0" encoding="UTF-8"?>
Yet it seems that the XML is not really UTF-8. The langauge of the XML content is Spanish and contain words like Dublín in the XML.
I'm unable to get the 3rd party to sort out their XML.
How can I pre-process the XML and fix the encoding incompatibilities?
Is there a way to detect the correct encoding for a XML file?
Answer: Your 0xED 0x6E 0x2C 0x20 bytes correspond to "ín, " in ISO-8859-1, so it looks like your content is in ISO-8859-1, not UTF-8. Tell your data provider about it and ask them to fix it, because if it doesn't work for you it probably doesn't work for other people either.
Now there are a few ways to work it around, which you should only use if you cannot load the XML normally. One of them would be to use utf8_encode(). The downside is that if that XML contains both valid UTF-8 and some ISO-8859-1 then the result will contain mojibake. Or you can try to convert the string from UTF-8 to UTF-8 using iconv() or mbstring, and hope they'll fix it for you. (they won't, but you can at least ignore the invalid characters so you can load your XML)
Or you can take the long, long road and validate/fix the sequences by yourself. That will take you a while depending on how familiar you are with UTF-8. Perhaps there are libraries out there that would do that, although I don't know any.
Either way, notify your data provider that they're sending invalid data so that they can fix it.

Here's a partial fix. It will definitely not fix everything, but will fix some of it. Hopefully enough for you to get by until your provider fix their stuff.
function fix_latin1_mangled_with_utf8_maybe_hopefully_most_of_the_time($str)
{
    return preg_replace_callback('#[\\xA1-\\xFF](?![\\x80-\\xBF]{2,})#', 'utf8_encode_callback', $str);
}

function utf8_encode_callback($m)
{
    return utf8_encode($m[0]);
}

Comment: ISO-8859-1 is widely used in the Western world. If it's not UTF-8, it's usually ISO-8859-1. (or cp1252) As for the value of each byte, I just looked up at the char table.
Comment: This is very helpful. I was able to fix the XML by using utf8_encode(). Can you tell me how you deciphered the encoding from the string `0xED 0x6E 0x2C 0x20`?
Comment: To decrypt ASCII, go to https://www.dcode.fr/ascii-code Under "ASCII Converter", put those characters (e.g. ed 6e 2c 20), then the result is shown on left hand side "Results" HEX /2 column
Answer: I solved this using
$content = utf8_encode(file_get_contents('http://example.com/rss.xml'));
$xml = simplexml_load_string($content);

Comment: Worked for me too, in my case the XML didn't declare an encoding and came from one of those "Enterprise" systems so had weird encoding anyway
Comment: I had the same issue when using DOMDocument->load(), this solution works fine, just have to use ->loadXML on the result of file_get_contents
Comment: Works for me too! I was receiving files with ANSI characters in an XML file with a UTF-8 encoding.
Comment: why using $ before content please, i have an error cause of it ?
Answer: If you are sure that your xml is encoded in UTF-8 but contains bad characters, you can use this function to correct them :
$content = iconv('UTF-8', 'UTF-8//IGNORE', $content);

Answer: We recently ran into a similar issue and was unable to find anything obvious as the cause. There turned out to be a control character in our string but when we outputted that string to the browser that character was not visible unless we copied the text into an IDE.
We managed to solve our problem thanks to this post and this:

preg_replace('/[\x00-\x1F\x7F]/', '', $input);
Answer: Instead of using javascript, you can simply put this line of code after your mysql_connect sentence:
mysql_set_charset('utf8',$connection);

Cheers.
Answer: Can you open the 3rd party XML source in Firefox and see what it auto-detects as encoding? Maybe they are using plain old ISO-8859-1, UTF-16 or something else.
If they declare it to be UTF-8, though, and serve something else, their feed is clearly broken. Working around such a broken feed feels horrible to me (even though sometimes unavoidable, I know).
If it's a simple case like "UTF-8 versus ISO-8859-1", you can also try your luck with mb_detect_encoding().
Comment: mb_detect_encoding() says the content is UTF-8 yet if it were valid UTF-8 would the XML parser complain about it?
Comment: @Camsoft strange. Can you try it with Firefox? Can you boil it down to the character that creates the problem? Are you at liberty to publish the URL to the XML feed?
Answer: If you download XML file and open it for example in Notepad++ you'll see that encoding is set to something else than UTF8 - I'v had the same problem with xml made myself, and it was just te encoding in the editor :)
String <?xml version="1.0" encoding="UTF-8"?> don't set up the encoding of the document, it's only info for validator or another resource.
Answer: I just had this problem. Turns out the XML file (not the contents) was not encoded in utf-8, but in ISO-8859-1. You can check this on a Mac with file -I xml_filename.
I used Sublime to change the file encoding to utf-8, and lxml imported it no issues.
Answer: After several tries i found htmlentities function works.
$value = htmlentities($value)

Answer: What I was facing was solved by what Erik proposed
https://stackoverflow.com/a/4575802/14934277
and it IS, actually, the only way to know if your data is okay to be printed.
And here is some peace of code that could be useful to anyone out there:
$product_desc = ..;
//Filter your $product_desc here. Remove tags, strip, do all you would do to print XML
try{(new SimpleXMLElement('<sth><![CDATA['.$product_desc.']]></sth>'))->asXML();}
catch(Exception $exc) {$product_desc = '';}; //Don't print trash

Note that part.
<![CDATA[]]>

When you try to create an XML out of it, be sure to pass it the final product a browser would see, meaning, having your field wrapped with CDATA
Answer: When generating mapping files using doctrine I ran into same issue.  I fixed it by removing all comments that some fields had in the database.


Should my authoritative nameserver's zone records use the registrar's nameservers?

Question: I'm migrating my nameserver machines from a datacenter into a cloud service (AWS) by replacing each of the physical machines with virtual machines. The nameservers I am migrating are authoritative for dozens of different domains.
During this process, I noticed something weird that has me confused:
The nameservers I want to migrate use the following authoritative nameservers:
ns1.example.com
ns2.example.com

example.com is an old, legacy name for the nameservers and I am also the owner the example.com domain. When I went to check the zone records at example.com, I discovered the exact same zone records:
ns1.example.com
ns2.example.com

This was unexpected. Basically, the example.com domain is authoritative for itself. I imagined I would have been using the registrar to manage the zone record and it would contain the ip addresses of each of the nameservers for example.com. Otherwise, what prevents the example.com name records from getting spoofed? Should I start using the registrar's nameservers to point to the authoritative name servers?
The current nameserver config was set up by someone else and I'm very rusty with setting up a DNS. Any guidance appreciated.
Answer: This is not unexpected, this is how they should look like.
The registrar includes NS records for your zone in the parent zone. So in case of example.com domain name it will place the following records:
example.com NS ns1.example.com
example.com NS ns2.example.com

in .com zone. In this particular case this is not sufficient as the nameservers are inside the delegated zone and we need to provide hints where these two nameservers can be found. Hence you can see so called glue records which provide IP addresses for the abovementioned nameservers:
ns1.example.com A <ipv4_of_ns1>
ns1.example.com AAAA <ipv6_of_ns1>
ns2.example.com A <ipv4_of_ns2>
ns2.example.com AAAA <ipv6_of_ns2>

They are also placed in .cm zone, along with NS records.
Now, it is YOUR zone which provides authoritative information so it will also contain both NS records for nameservers at zone apex and their IP addresses.
You, as the zone administrator, have the responsibility to make sure that delegation data (along with glue records) at parent zone and the authority data in your zone agree with each other. This usually means they should be identical.
This is described in Technical requirements for authoritative name servers, under "Consistency between delegation and zone" heading.
In your particular case, when you move ns1.example.com and ns2.example.com to new systems (which means new IP addresses) you have to update A/AAAA records both in you zone and at your registrar - which will trigger the update of the glue records in the parent zone.
Comment: OK, thanks. And I discovered the registrar (godaddy) has a way to register nameserver host names in a different part of the interface. I was confused as to how Godaddy would know what the actual IP addresses of the nameservers were. Now I know.


What kind of side work can math professors (researchers) do for extra income?

Question: I am considering a career as a math professor with interests in Abstract Algebra and Topology. I wonder if there's any side work that a math professor can do for extra income?
Thank you!
Comment: Maybe ask on the academia stackexchange.
Answer: Getting a job as a professor is non-trivial, and depending on the environment, you may not have the connections or time or ability to do extra work.
Some professors consult for companies depending on their needs, usually based on some application area of their expertise. But, you  need to know companies that you can provide value to.


Obtaining deterministic information from probability theory

Question: A simple but very useful fact that constitutes the basis of the probabilistic method is the following: if an event $A$ has positive probability, then it can't be empty: there should exist at least one realization $\omega \in A$, just by definition of probability measure. However, the converse is not true in general: non-empty events can have zero measure.
The question is: if $P(A) > k$, where $k \in [0,1)$, can we say anything else about the event $A$, depending on the value of $k$, besides the fact that $A \neq \emptyset$? In other words, can we reveal more deterministic information about $A$ by knowing not only that $P(A) > 0$, but also that $P(A) > k$? In particular, if we are told that $P(A) > 0$ and $P(B) = 1$, does $B$ have different properties than $A$? If so, how many?
For instance, higher probability means higher cardinality in certain probability spaces. Of course, the answer depends on the probability space. If we consider a countable probability space $\Omega = \{w_{i} : i \in \mathbb{N}\}$ with $p(w_{i}) > 0$ for every $i \in \mathbb{N}$, then $P(B) = 1$ implies that $B = \Omega$, since any event strictly contained in $\Omega$ has strictly less probability by construction.
I understand that my question may be a bit unclear, so feel free to answer what you think might be helpful. There is no correct answer, as indicated by the soft-question tag. I'm just looking for conclusions that can be determined, just as the examples in the previous paragraph. Please don't close the question.
Comment: This is pretty vague.  Personally, I'd say that events with probability $1$ aren't "interesting" because we "know" in advance that they occur.  Saying there's a tornado outside is a lot more interesting than saying that the sun rose this morning.
Comment: Remove the word interesting then. I just care about if the degree of likelihood reveals more deterministic information of the event, besides the fact that it's non-empty. For instance, in the example I describe above, events with probability 1 always happen, so that's more information than just being non-empty.
Comment: Not sure what sort of information you have in mind.  Obviously, higher probability means it is more likely to be observed.  What sort of information are you interested in?
Comment: I edited the question, it might be a little more clear now.
Answer: Here is a nice example I had just learned in a course.
$G$ is a group acting on some topological space $X$.  Take a probability distribution $\mu$ on $G$. We mark $A= supp (\mu) = \{g\in G:\mu(g) >0\}$.
Assume $A$ generates $G$ and that $G$ is countable (for the sake of simplicity).
We can think about the notion of a "random walk" of a group $G \acts X$  - start with a point $x\in X$. Pick at random some $g_1\in G$. Go from $x_1= x$ to $x_2 = g_1x$. Then pick again at random another $g_2$ and go from $x_2$ to $x_3=g_2x_2$ and so on.
The classical example is a random walk on $\mathbb{Z}^{2}$- take $X=\mathbb{Z}^2$ and the group $\Gamma =<g_1,g_2>$ with $g_1((x,y)) = (x+1,y)$ , $g_2((x,y)) = (x,y+1)$ and a probability distribution $\mu(g_1) = \mu(g_2) = \mu(g_1^{-1}) = \mu(g_2^{-1}) = \frac{1}{4} $.
A probability distribution $\nu$ on  $X$ is called $\mu$ - stationary if the measuere $\mu * \nu(f) = \int_{G} \int_{X} f(x)d \nu(g\cdot x) d\mu(g) $ is equal to $\nu$ ($ \mu*\nu$ is called the convolution measure). You can say that being $\mu$ - stationary is being "invariant" to a random walk by this group.*
The simplest example - if $\nu$ is invariant under the action of $G$ (i.e
$\nu(g\cdot A) = \nu(A)$) obviously it is $\mu$ stationary... However a measure doesn't have to be invariant in order to be stationary...
Assume $\nu$ is $\mu$ stationary.
Now - assume there is an atom $\nu(\{x\}) = p>0$. We take $\{x\}$ to be the atom with maximal measure.
Observe that $\nu (\{x\}) = \mu * \nu(\{x\}) = \sum_{g\in A} \nu(\{g\cdot x\}) \mu(g)$. From this simple equation we can deduce two things:

Since this is the atom with maximal probability, $\nu(\{g\cdot x\}) = \nu(\{x\})$ for all $g\in A$, and since $<A> = G$,  $\nu(\{x\}) = \nu(\{g\cdot x\})$ for all $g\in G$.
Since $\nu$ is a probability measure, $A= |supp(\mu)| < \infty $.

Furthermore - we can deduce that the orbit of $x$ has to be finite.
*This definition of $\mu$ - stationary measure is not precise, but I don't think its the main issue and this answer is long enough.
Answer: [Edited]
If the probability measure is nonatomic and $P(A) > 0$, then $A$ is uncountable.  Martin's axiom implies $A$ has cardinality $\ge c$.
Comment: Thanks! Did you mean $P(A) > c$ instead of $P(A) > 0$? If so, could you provide a reference or hint for the proof? Thanks a lot!
Comment: No, $c$ is not a real number, it is the cardinality of the continuum.


why Assertion failure in -[UISectionRowData refreshWithSection:tableView:tableViewRowData:]?

Question:  Assertion failure in -[UISectionRowData refreshWithSection:tableView:tableViewRowData:], /SourceCache/UIKit/UIKit-2380.17/UITableViewRowData.m:400

 *** Terminating app due to uncaught exception 'NSInternalInconsistencyException',     reason:'Failed to allocate data stores for 997008923 rows in section 0. Consider using fewer rows'

my code
 -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  {

   return 1;

  }

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

   return [appDelegate.purchaseArray count];

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:  (NSIndexPath *)indexPath
   {
    static NSString *CellIdentifier = @"cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault         reuseIdentifier:CellIdentifier];
    }
    return cell;
}

-(void)viewWillAppear:(BOOL)animated
{

    [cartTbl reloadData];

}

i didn't get what's problem in this?
Comment: Unfortunately, Apple chooses not to carefully check parameters on many UI objects when you create/modify them, and similarly choose not to use an informative error message when an inconsistency is detected.  But basically the assertion means that you've mucked up something in your table controls.  First make sure that you've actually set both `delegate` and `dataSource`.
Comment: But on closer examination see "Failed to allocate data stores for 997008923 rows in section 0.  Consider using fewer rows".  I doubt that purchaseArray.count actually has that many rows, but somehow that value must be mucked up.  Add an NSLog in numberOfRowsInSection to log the return value.
Comment: it's run proper in simulator but not work in device.
Comment: Which suggests that the problem has something to do with an uninitialized variable.
Comment: Most of the issues I can solve out by resetting simulator and restart Xcode! This seems that you don't have any problem with the code but a something wrong understanding of Xcode compiler.
Comment: i think here is the problem  [appDelegate.purchaseArray count]; check that is the array consist of the data or not.
Answer: Check your tableView:heightForRowAtIndexPath:. Maybe you're returning something like NaN/+inf/-inf instead of height. That was my bug.
Remember this is not a crash for double and float types to divide by zero:
double d = 5.0;
double r = d/0.0;

So this can help you:
if (isnan(r) || isinf(r)) {
    // ...
}

Answer: I also had failure in -[UISectionRowData refreshWithSection:tableView:tableViewRowData:]. In my case it was caused by set too small estimatedRowHeight while using:
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

for autosizing tableView's cells.
Setting estimatedRowHeight to 2.0 instead 1.0 solved problem.
Comment: It worked for me after adding:
    `func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        return 44
    }`
Answer: I had an error like this for a different reason.
My app was working fine, when I decided to change something in my view model (The object that I was binding my table to). I deleted a property, and recompiled. Suddenly the app was throwing this error.
It turned out that there was still a reference to the deleted property in the code that the compiler didn't catch. I had cleaned and rebuilt several times, and the compiler never caught that error that I missed.
Restarting xcode made the build fail, with the offending line now highlighted as an error. Once I fixed that, everything was fine again.
If you encounter bad access errors like this, and see weird stuff in the debugger, like properties with values that should be assigned to other properties, then you might have an error that should have kept your build from compiling that xcode just didn't catch somehow. A restart might fix it - it's worth a try.
Answer: return [appDelegate.purchaseArray count]; looks like a garbage value. Make sure it's initialized.


Laravel How to pass data in all views included in main template file?

Question: I have a main template file and it's called by different controllers and different views. In footer the list of categories display so how can i pass data from all controller`s method without writing code in all functions and pass data?
Comment: Possible duplicate of [How to pass data to all views in Laravel 5?](https://stackoverflow.com/questions/28608527/how-to-pass-data-to-all-views-in-laravel-5)
Answer: get categories in app/Providers/AppServiceProvider.php boot method

namespace App\Providers;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;

use Illuminate\Support\Facades\Auth;
use DB;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
         View::share('key', 'value');
         Schema::defaultStringLength(191);

        $categories=DB::table('categories')->get();
        View::share('categories',$categories);

    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

now you can access categories in all views and controllers in $categories variable
in your footer :
@foreach($categories as $category)

{{$category->name}}

@endforeach

Comment: This is called view composers and further details can be found here: https://laravel.com/docs/5.6/views#view-composers


Combining AD permissions with FTP

Question: We're using Windows Server 2008 with Active Directory controlling access to a network share. We've setup FTP so that people can access that share from outside (we used to use the PPTP VPN but for various reasons we need to switch to FTP). So far here is what we've managed to implement on the FTP:
-The network share is used as the FTP root (defined as a UNC) and that is working fine.
-AD authentication is working fine (wrong password and you stay out, good password you're in, password management in AD correctly synched with the FTP).
-AD permissions are failing: the AD permissions on the content of the FTP root are ignored: it's either a user only has read or write access, but this applies to the whole FTP root, which obviously isn't suitable since that FTP root is initially our network share and files/folders have different AD permissions depending on people's groups...
Whether we set the permissions through the share OR the FTP management interface, AD permissions are never enforced.
Q1: Is that normal?
Q2: If so what solutions exist to combine AD permissions with FTP on MS server 2008?
Q3: If not, where should I look to fix the configuration?
1st update:
Following MarkM's answer I did the following:
-Set the NTFS permissions on the share (which is also the FTP root) to List folder contents for Domain users
-Set the FTP Authorization Rules to Specified roles or user groups=Domain Users with Permissions=Read (before write was also enabled hence why NTFS permissions were probably overwritten).
I then created 3 folders with the following NTFS permissions:
-folderA: inheritable, nothing else
-folderB: not inheritable, Full control to Domain users
-folderC: not inheritable, no permissions for Domain users
Via FTP, the NTFS read permisisons are properly enforced, however the write permissions aren't:
-folderA: can see the folder, can open it and download it's content, can't upload to it
-folderB: can see the folder, can open it and download it's content, can't upload to it (NTFS write permission is NOT enforced)
-folderC: can't even see the folder (NTFS read permission is properly enforced)
Q4: What other settings should I be looking at?
Comment: Why on earth are you using FTP? It's almost 2012. It's clunky and completely insecure.
Comment: Because our employees travel a lot to developing countries (Rwanda, Burundi...) where the Internet connection is very very very bad. The VPN just sucks with high latency, we're thinking that FTP will help as all they need is a link to the file to download it. I welcome other suggestions. As for FTP being insecure we will enable SSL as part of IIS.
Answer: Q1
No, that's not normal, unless you have anonymous FTP access turned on in IIS. If you disable this, then access is evaluated based on NTFS ACLs and SMB Share ACLs. Best practices are to give Everyone Full Control on the Share ACLs and control access through the NTFS permissions. I think this might be what's tripping you up. Chances are, your NTFS permissions give Users (or some other widely populated group) R/W at the root of the share. Consider just giving them Traverse Directory and List Folder Contents instead. FTP (and anything else that isn't SMB) ignores Share ACLs. Triple check your NTFS ACLs and make sure that they are in order.
Q2
This is natively supported
Q3
See above answsers.
Comment: I've unchecked the `write` permission option in the `FTP Authorization Rules` which seems to have resolved the issue whereby FTP users had full control over the whole share. It looks like NTFS `read` permissions are properly enforced, but now I can't `write` to any directory. Please have a look at my update and advise further if you can.
Comment: @user64204 You are misunderstanding. You should allow FTP read and write and turn off anonymous FTP if it is on. This is pretty clearly an NTFS permission problem. Instead of posting what you added to the ACLs, can you please post the **entire** ACL for each folder that you're having problems with? Posting just what you changed isn't going to help, since you were experiencing the issue before you changed anything.
Comment: You were right, everything seems to be working fine with both `read` and `write` FTP permissions enabled. `Anonymous authentication` was always disabled. It looks like I may not have tested properly and started getting confused. Latest tests are conclusive.

Combining AD permissions with FTP


Given a solution of a second order non-homogeneous ODE, how to get all of its solutions?

Question: If $x_1(t)$ is one solution of the equation
$$x''+a_1(t)x'+a_2(t)x=f(t),$$
how to get all solutions of it?
Assume $x_2(t)$ is another solution of the equation above.
I know if $f(t)=0$, it is a homogeneous equation, according to Abel's identity:
$$W(x_1, x_2)(t) = \begin{vmatrix}x_1(t) & x_2(t) \\ x_1'(t) & x_2'(t)\end{vmatrix} = W(x_1, x_2)(t_0) e^{-\int_{t_0}^t p(\eta) d\eta}$$
then $x_2(t)$ can be solved. But if $f(t)\ne 0$, I don't know how to do. And can this be done?
Answer: Any solution is necessarily of the type $x(t)=x_1(t)+y(t)$ where $y(t)$ is a solution corresponding to $f=0$. This is because $x(t)-x_1(t)$ solves the equation with $f=0$.
Comment: I know, but $x_1(t)$ is the solution of the nonhomogeneous equation, the Abel's identity isn't correct.
Comment: You are told that $x_1$ is a solution and you are asked to write all solutions using it, right? @YanPeng
Comment: @YanPeng Use Wronskian only for the homogeneous equation. Don't use it with $f$ on the right side.
Comment: Yes, you are right. So I don't know how to do, I just know one solution of the nonhomogeneous equation, from this I don't know how to get a solution of the corresponding homogeneous equation.
Comment: @YanPeng I don't quite understand what you are saying. You clearly mentined that when $f=0$ you know how to get $x_2$. I am calling this this $x_2$  as $y$.
Comment: Yes, you are right. I mean, if $f\ne 0$, I don't know how to get $x_2$, because I cannot use Wronskian.


Series of functions $\log(1+x^{2n})$

Question: Does the series of functions $\sum_{n=0}^{+\infty} \log(1+x^{2n})$ converges for $|x|<1$?
Obviously I've observed that for $x=0$ the series is convergent and for $x\ge1$ is divergent.
How should I proceed? Thank you.
Comment: Why do you say that it diverges when $x>0$?
Comment: Sorry, I meant to say $x\ge 1$
Answer: Given the series of functions
$$
\sum_{n=0}^{+\infty} \log(1+x^{2n})
$$
you're interested in its convergence for $|x| < 1$. You've already observed the behavior at $x = 0$ and $x \geq 1$, which is a good start.
To study its convergence for $|x| < 1$, let's use the properties of the logarithm and the fact that the domain in question does not contain any non-positive integers.
Since $\log(1 + t) < t$ for $t > 0$ (you can see this from the series expansion of the logarithm or by considering the graph of $y = \log(1+t)$ and $y = t$), we can say:
$$
\log(1 + x^{2n}) < x^{2n}
$$
Now, consider the sum of the right-hand side:
$$
\sum_{n=0}^{+\infty} x^{2n}
$$
This is a geometric series with ratio $x^2$. Since $|x| < 1$, $|x^2| < 1$ as well, so this series converges (to $\frac{1}{1-x^2}$).
By the comparison test, if $\sum_{n=0}^{+\infty} x^{2n}$ converges and $0 \leq \log(1+x^{2n}) < x^{2n}$ for all $n$, then $\sum_{n=0}^{+\infty} \log(1+x^{2n})$ also converges for $|x| < 1$.
Hence, the given series converges for all $|x| < 1$.
I hope this helps!
Comment: Thanks a lot. Now the question is: the convergence you've proved is pointwise, right? It's also uniform on every subset $[a,b]\subset(-1,1)$, right?
Comment: Yes. The convergence I demonstrated was pointwise for \( |x| < 1 \). For uniform convergence on subsets \([a,b] \subset (-1,1)\), you'd typically employ the Weierstrass M-test. Given our earlier inequalities, for any \( x \) in \([a,b]\), the terms \( x^{2n} \) will have a maximum on this interval due to the compactness of \([a,b]\). By showing the series of these maxima converges, we can then establish uniform convergence on the subset. Thus, the series does indeed converge uniformly on every \([a,b] \subset (-1,1)\).

Series of functions $\log(1+x^{2n})$


Administer simplenews subscriptions with views

Question: In simplenews the default path to manage the subscriptions to newsletters is: admin/people/simplenews. The problem with that page is that it doesn't, for example, have any columns that would allow you to see when the subscription was added or even select all the subscriptions and perform actions on them (a feature that is available by default in vbo).
My question is the following:
Is there any way to make the specific page available for further configuration through Views so that I can add extra fields/features to it? What I'm looking for is basically something like Administration Views but for the simplenews interface.
Comment: I just tested the direct access to `admin/people/simplenews` for a non-admin. It works.
Answer: Answer for 2016 and Drupal 7.  Simplenews module does now include bulk operations.  Simplenews has Views integration built in.  It does not come with a pre-defined view, so you have to create one.
Here is an export of a view that shows when the subscriber was added and by what means.  However Simplenews does not current provide VBO integration to allow a bulk action.
<code>  $view = new view();
  $view->name = 'newsletter_subscriptions';
  $view->description = '';
  $view->tag = 'default';
  $view->base_table = 'simplenews_subscription';
  $view->human_name = 'Newsletter subscriptions';
  $view->core = 7;
  $view->api_version = '3.0';
  $view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

  /* Display: Master */
  $handler = $view->new_display('default', 'Master', 'default');
  $handler->display->display_options['use_more_always'] = FALSE;
  $handler->display->display_options['access']['type'] = 'none';
  $handler->display->display_options['cache']['type'] = 'none';
  $handler->display->display_options['query']['type'] = 'views_query';
  $handler->display->display_options['exposed_form']['type'] = 'basic';
  $handler->display->display_options['pager']['type'] = 'full';
  $handler->display->display_options['pager']['options']['items_per_page'] = '25';
  $handler->display->display_options['style_plugin'] = 'table';
  $handler->display->display_options['style_options']['columns'] = array(
    'mail' => 'mail',
    'name' => 'name',
    'timestamp' => 'timestamp',
    'activated' => 'activated',
    'source' => 'source',
    'status' => 'status',
    );
  $handler->display->display_options['style_options']['default'] = 'mail';
  $handler->display->display_options['style_options']['info'] = array(
    'mail' => array(
      'sortable' => 1,
      'default_sort_order' => 'asc',
      'align' => '',
      'separator' => '',
      'empty_column' => 0,
      ),
    'name' => array(
      'sortable' => 1,
      'default_sort_order' => 'asc',
      'align' => '',
      'separator' => '',
      'empty_column' => 0,
      ),
    'timestamp' => array(
      'sortable' => 1,
      'default_sort_order' => 'asc',
      'align' => '',
      'separator' => '',
      'empty_column' => 0,
      ),
    'activated' => array(
      'sortable' => 1,
      'default_sort_order' => 'asc',
      'align' => '',
      'separator' => '',
      'empty_column' => 0,
      ),
    'source' => array(
      'sortable' => 1,
      'default_sort_order' => 'asc',
      'align' => '',
      'separator' => '',
      'empty_column' => 0,
      ),
    'status' => array(
      'sortable' => 1,
      'default_sort_order' => 'asc',
      'align' => '',
      'separator' => '',
      'empty_column' => 0,
      ),
    );
  /* Relationship: Simplenews subscription: Subscriber ID */
  $handler->display->display_options['relationships']['snid']['id'] = 'snid';
  $handler->display->display_options['relationships']['snid']['table'] = 'simplenews_subscription';
  $handler->display->display_options['relationships']['snid']['field'] = 'snid';
  /* Relationship: Simplenews subscription: Term ID */
  $handler->display->display_options['relationships']['tid']['id'] = 'tid';
  $handler->display->display_options['relationships']['tid']['table'] = 'simplenews_subscription';
  $handler->display->display_options['relationships']['tid']['field'] = 'tid';
  $handler->display->display_options['relationships']['tid']['label'] = 'Newsletter';
  /* Field: Simplenews subscriber: Subscriber */
  $handler->display->display_options['fields']['mail']['id'] = 'mail';
  $handler->display->display_options['fields']['mail']['table'] = 'simplenews_subscriber';
  $handler->display->display_options['fields']['mail']['field'] = 'mail';
  $handler->display->display_options['fields']['mail']['relationship'] = 'snid';
  /* Field: Taxonomy term: Name */
  $handler->display->display_options['fields']['name']['id'] = 'name';
  $handler->display->display_options['fields']['name']['table'] = 'taxonomy_term_data';
  $handler->display->display_options['fields']['name']['field'] = 'name';
  $handler->display->display_options['fields']['name']['relationship'] = 'tid';
  $handler->display->display_options['fields']['name']['label'] = 'Newsletter';
  /* Field: Simplenews subscription: Timestamp */
  $handler->display->display_options['fields']['timestamp']['id'] = 'timestamp';
  $handler->display->display_options['fields']['timestamp']['table'] = 'simplenews_subscription';
  $handler->display->display_options['fields']['timestamp']['field'] = 'timestamp';
  $handler->display->display_options['fields']['timestamp']['date_format'] = 'short';
  $handler->display->display_options['fields']['timestamp']['second_date_format'] = 'long';
  /* Field: Simplenews subscription: Source */
  $handler->display->display_options['fields']['source']['id'] = 'source';
  $handler->display->display_options['fields']['source']['table'] = 'simplenews_subscription';
  $handler->display->display_options['fields']['source']['field'] = 'source';
  /* Field: Simplenews subscriber: Activated */
  $handler->display->display_options['fields']['activated']['id'] = 'activated';
  $handler->display->display_options['fields']['activated']['table'] = 'simplenews_subscriber';
  $handler->display->display_options['fields']['activated']['field'] = 'activated';
  $handler->display->display_options['fields']['activated']['relationship'] = 'snid';
  $handler->display->display_options['fields']['activated']['type'] = 'unicode-yes-no';
  $handler->display->display_options['fields']['activated']['not'] = 0;
  /* Field: Simplenews subscription: Status */
  $handler->display->display_options['fields']['status']['id'] = 'status';
  $handler->display->display_options['fields']['status']['table'] = 'simplenews_subscription';
  $handler->display->display_options['fields']['status']['field'] = 'status';
  $handler->display->display_options['fields']['status']['type'] = 'unicode-yes-no';
  $handler->display->display_options['fields']['status']['not'] = 0;
  /* Filter criterion: Simplenews subscriber: Subscriber */
  $handler->display->display_options['filters']['mail']['id'] = 'mail';
  $handler->display->display_options['filters']['mail']['table'] = 'simplenews_subscriber';
  $handler->display->display_options['filters']['mail']['field'] = 'mail';
  $handler->display->display_options['filters']['mail']['relationship'] = 'snid';
  $handler->display->display_options['filters']['mail']['operator'] = 'contains';
  $handler->display->display_options['filters']['mail']['group'] = 1;
  $handler->display->display_options['filters']['mail']['exposed'] = TRUE;
  $handler->display->display_options['filters']['mail']['expose']['operator_id'] = 'mail_op';
  $handler->display->display_options['filters']['mail']['expose']['label'] = 'Subscriber';
  $handler->display->display_options['filters']['mail']['expose']['operator'] = 'mail_op';
  $handler->display->display_options['filters']['mail']['expose']['identifier'] = 'mail';
  $handler->display->display_options['filters']['mail']['expose']['remember_roles'] = array(
    2 => '2',
    1 => 0,
    3 => 0,
    4 => 0,
    );
  /* Filter criterion: Taxonomy term: Term */
  $handler->display->display_options['filters']['tid']['id'] = 'tid';
  $handler->display->display_options['filters']['tid']['table'] = 'taxonomy_term_data';
  $handler->display->display_options['filters']['tid']['field'] = 'tid';
  $handler->display->display_options['filters']['tid']['relationship'] = 'tid';
  $handler->display->display_options['filters']['tid']['group'] = 1;
  $handler->display->display_options['filters']['tid']['exposed'] = TRUE;
  $handler->display->display_options['filters']['tid']['expose']['operator_id'] = 'tid_op';
  $handler->display->display_options['filters']['tid']['expose']['label'] = 'Newsletter';
  $handler->display->display_options['filters']['tid']['expose']['operator'] = 'tid_op';
  $handler->display->display_options['filters']['tid']['expose']['identifier'] = 'tid';
  $handler->display->display_options['filters']['tid']['expose']['remember_roles'] = array(
    2 => '2',
    1 => 0,
    3 => 0,
    4 => 0,
    );
  $handler->display->display_options['filters']['tid']['type'] = 'select';
  $handler->display->display_options['filters']['tid']['vocabulary'] = 'newsletter';
  /* Filter criterion: Simplenews subscriber: Activated */
  $handler->display->display_options['filters']['activated']['id'] = 'activated';
  $handler->display->display_options['filters']['activated']['table'] = 'simplenews_subscriber';
  $handler->display->display_options['filters']['activated']['field'] = 'activated';
  $handler->display->display_options['filters']['activated']['relationship'] = 'snid';
  $handler->display->display_options['filters']['activated']['group'] = 1;
  $handler->display->display_options['filters']['activated']['exposed'] = TRUE;
  $handler->display->display_options['filters']['activated']['expose']['operator_id'] = '';
  $handler->display->display_options['filters']['activated']['expose']['label'] = 'Activated';
  $handler->display->display_options['filters']['activated']['expose']['operator'] = 'activated_op';
  $handler->display->display_options['filters']['activated']['expose']['identifier'] = 'activated';
  $handler->display->display_options['filters']['activated']['expose']['remember_roles'] = array(
    2 => '2',
    1 => 0,
    3 => 0,
    4 => 0,
    );

  /* Display: Page */
  $handler = $view->new_display('page', 'Page', 'page');
  $handler->display->display_options['path'] = 'newsletter-subscriptions';
  $handler->display->display_options['menu']['type'] = 'normal';
  $handler->display->display_options['menu']['title'] = 'Newlsetter subscriptions';
  $handler->display->display_options['menu']['weight'] = '0';
  $handler->display->display_options['menu']['context'] = 0;
  $handler->display->display_options['menu']['context_only_inline'] = 0;
</code>


how to check two json and yaml files to compare

Question: This is the yaml file (the type field is both in Persian and English, and also Type TypeB is correct and is not a typo):
-
    dedicatedip: 22.214.171.124
    status: Active
    type: 'نوع اول'
-
    dedicatedip: 18.104.22.168
    status: Active
    type: 'Type TypeB'
-
    dedicatedip: 22.214.171.124
    status: Active
    type: 'نوع اول'
-
    dedicatedip: 22.214.171.124
    status: Suspended
    type: 'Type TypeC'
-
    dedicatedip: 126.96.36.199
    status: Active
    type: 'نوع اول'
-

This is the json file:
{
  "error": false,
  "data": {
    "licenses": [
      {
        "id": 167689,
        "cycle": "monthly",
        "type": "typeA",
        "ip": "188.8.131.52",
        "renewDate": "2023-12-22 09:10:00",
        "status": "Active",
        "hostname": "some.fqdn.co.com",
        "autoRenew": true
      },
      {
        "id": 167689,
        "cycle": "monthly",
        "type": "typeB",
        "ip": "220.127.116.11",
        "renewDate": "2023-12-22 09:10:00",
        "status": "Suspended",
        "hostname": "some.fqdn.co.com",
        "autoRenew": true
      },
      {
        "id": 167689,
        "cycle": "monthly",
        "type": "typeA",
        "ip": "126.96.36.199",
        "renewDate": "2023-12-22 09:10:00",
        "status": "Active",
        "hostname": "some.fqdn.co.com",
        "autoRenew": true
      },
      {
        "id": 167689,
        "cycle": "monthly",
        "type": "typeC",
        "ip": "18.104.22.168",
        "renewDate": "2023-12-22 09:10:00",
        "status": "Active",
        "hostname": "some.fqdn.co.com",
        "autoRenew": true
      },
      {
        "id": 167689,
        "cycle": "monthly",
        "type": "typeA",
        "ip": "22.214.171.124",
        "renewDate": "2023-12-22 09:10:00",
        "status": "Active",
        "hostname": "some.fqdn.co.com",
        "autoRenew": true
      }
    ]
  }
}

I'm going to to this over iterating both files:
check if the ip of json and yaml match, if it matches then check the type of both (case-insensitive), then if they both match, now if status don't match then print something.

Since one IP may have several license types, the `type` should be matched too.

The expected output:
ip 188.8.131.52, license typeB "active" in "yaml" but "suspended" in "json".
ip 18.104.22.168, license typeA "suspended" in "yaml" but "active" in json.

I tried to write a code, but this is my attempt so far:
import json
from ruamel.yaml import YAML

file_name = 'file.json'

with open(file_name) as file:
    data = json.load(file)

json_names = []
for r in data:
    for j in r['data']:
        if j is not None and 'licenses' in j and j['licenses'] is not None and 'ip' in j['licenses']:
            json_names.append({'licenses': j['licenses']['ip'] })

yaml = YAML()
with open('file.yaml') as file:
    code = yaml.load(file)

yaml_names = []
for d in code:
    yaml_names.append({'ip': d['dedicatedip']})

But I'm not sure what to do next for what I'm trying to reach.
Answer: IIUC, you can use :
import json, yaml

with (
    open("file.yaml", "r", encoding="utf-8") as yf,
    open("file.json", "r", encoding="utf-8") as jf
):
    ydata = list(yaml.safe_load_all(yf)); jdata = json.load(jf)

    delta = [
        (yd["dedicatedip"], jd["type"], yd["status"], jd["status"])
        for yd in ydata[0] for jd in jdata["data"]["licenses"]
        if yd and yd["dedicatedip"] == jd["ip"]
        and yd["type"].removeprefix("Type ").lower() == jd["type"].lower()
        and yd["status"] != jd["status"]
    ]

Output(s) :
print(delta)
# [('22.214.171.124', 'typeB', 'Active', 'Suspended'),
#  ('22.214.171.124', 'typeC', 'Suspended', 'Active')]

for vals in delta:
    print('IP {}, license {} "{}" in YAML but "{}" in JSON.'.format(*vals))

# IP 18.104.22.168, license typeB "Active" in YAML but "Suspended" in JSON.
# IP 220.127.116.11, license typeC "Suspended" in YAML but "Active" in JSON.

for vals in delta:
    print(*map("{:<10}".format, vals))
# 126.96.36.199    typeB      Active     Suspended
# 188.8.131.52    typeC      Suspended  Active

Comment: Works fine here, I can't reproduce (see [this](https://i.stack.imgur.com/cs7sZ.png)). Can you make a *screenshot* ?
Comment: I'm using `removeprefix` in my code and not `noremoveprefix`. Check yours please!
Comment: Sorry, I wrote it manually on the comments and it was a typo. `removeprefix` was the error.
Comment: [`removeprefix`](https://docs.python.org/3/library/stdtypes.html#str.removeprefix) was added in 3.9. So you can replace `yd["type"].removeprefix("Type ").lower()` with `yd["type"].replace("Type ", "").lower()`
Comment: Yes but I feel like whatever solution I'd propose, you'll always find something to ask for more, `∞`.
Comment: Thanks, but I get `SyntaxError` in line 4 `as yf`.
Comment: What's your Python version? I use 3.8.10 in Ubuntu. I edited the question.
Comment: I use 3.11. You can try using two `with` statements (like [this](https://i.stack.imgur.com/QL2X7.png)) instead of one.
Comment: I get `AttributeError: 'str' object has no attribute 'removeprefix'`
Comment: Thanks, this is fixed. But how do you check the word `نوع اول` with `TypeA`?
Comment: Sorry, I can't help you with that. Your question becomes now a moving target and I'm not sure people here can speak Persian. Is making a mapping of the types would solve your problem ?
Comment: Thanks, got it. Just a hint: is it proper to add variable for these?
Comment: No:) I won't do that:( Thanks a lot for the answer. I'll add variable.
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/255980/discussion-between-timeless-and-saeed).


Logistic regression with partially observed variables

Question: Let's say I have a binary variable to explain using "some" logistic regression approach. The set of variables I have at disposal are exhaustive for a given period of time and for a longer period a subset of those data are missing.
I think this is a very common issue and was looking for some references about the classic (or maybe more exotic) methodologies available to deal with this kind of situation.
Ideally, I would like to fit the model to all the available data without filling the missing value with best estimates. I was thinking that maybe nesting model or conditionning appriopriately would be possible.
Comment: Can you please tell use a bit more about the data? Is it a repeated measures design, in which the same subjects are measured several times?
Comment: If the observations are cross-sectional and not longitudinal/repeated measures and you have some of the variables *not* missing for later time periods, you can use multiple imputation.
Answer: I guess you'd have to move towards data augmentation techniques. Introductions are given in this rather old article by Van Dyk and Meng and more generally, but also from some time ago in Pigott's article on missing data. These could be good starting points for your literature research.
The machine learning field is quite extensively covered on Wikipedia and reading up on expectation–maximization (EM) algorithm could also be a good starting point for you.
This literature is quite varied, and some methods are well developed and incorporated in standard statistical software packages, while others are rather basic. Generally, the ideal method depends on the finer peculiarities of your data and the desired type of inference. So if you could provide more information on that part, people here will be more likely to provide specific help.
Comment: Only now I realized that the bounty started isn't the OP, and that the post is three years old. So I might be waiting in vain for "more information on that part"..


Looking for Clarification Regarding Hausdorff Dimension (Lay)

Question: I am reading an introductory book on Fractals where the following intuition is given for Hausdorff dimension of a smooth curve: if we define "length" as $L(r)=N(r)\cdot r$, with $N(r)$ straight line segments of length $r$ that step around the curve. As $r$ approaches $0$, $L(r)$ approaches the length of the curve.
For finite-length smooth curves, this approaches a finite length $L$. However, for fractals embedded in a one-dimensional space, this is not so, so we can define a "dimension" $D_H$ such that $N(r)\cdot r^{D_H}$ remains finite.
This means we can define
$$D_H:=\lim_{r\to0} \frac{\log(N_r)}{\log(1/r)}.$$
I understand how this intuition holds for fractals embedded in one dimensional space. However, my issue arises when the book attempts to extend the induction to higher dimensions. For example, the 3-D Sierpinski gasket: start with an equilateral tetrahedron and remove the open central upside down equilateral tetrahedron with half the side length. Repeating the process with $n$ iterations, there will be $3^n$ tetrahedron of side length $r=r_0({1/2^n})$. The book then goes on to say that the Hausdorff dimension can be thought of as
$$D_H=\lim_{n\to\infty}\frac{\log(4^n)}{\log(2^n)}=2.$$
However, wouldn't the "measure" of each individual tetrahedron be more appropriately expressed as the volume of said tetrahedron: changing proportionally to $1/2^{3n}$ with $n$ iterations? Wouldn't this make
$$D_H=\lim_{n\to\infty}\frac{\log(4^n)}{\log(2^{3n})}<1?$$
I know this is by no means the formal definition of Hausdorff dimension but I do not have enough background to understand the formal definition. Is there an issue simply with extending the intuition, or with my using the area of triangles instead of lengths of their sides?
Edit: Changed triangle to tetrahedron to make the limiting procedure easier.
Answer: Area is a two-dimensional concept.  The basic idea is that $d$-dimensional measure scales with the $d$'th power of length.  So if you have an object that scales so that magnifying lengths by a factor of $r$ gives you $r^d$ copies of the original, that object should have dimension $d$.
EDIT: For example, consider your 3-d Sierpinski gasket.  If you magnify the original by a factor of $2$, you get four (not $3$) objects the same size as the original.  Since $4 = 2^2$, the gasket has dimension $2$.
Comment: Not entirely sure I understand what you mean by this and how it applies. Could you elaborate more?


Flex div (do not stretch full width)

Question: I have 2 divs and using flex:
.parent {
  display: flex;
  flex-direction: column;
  align-items: center;
  background: red;
}

.item {
  height: 40px;
  margin-bottom: 10px;
}

something here

My issue is that the parent is 100% the width of the screen.
How can I make it so it stay's as large as the item content, so auto grows (when there's more text is grows or shrinks with less)?
Comment: See here: https://stackoverflow.com/questions/40141163/make-flex-items-take-content-width-not-width-of-parent-container/40141200
Answer: Use inline-flex instead of flex:
display: inline-flex;

Flex div (do not stretch full width)


How many Jordan blocks correspond to $\lambda$? What is the intuition?

Question:
Let $V$ be a finite-dimensional vector space over $\mathbb{F}$ and $T: V → V$ be linear. Assume that $m_T(t)$ the minimal polynomial splits over $\mathbb{F}$. Show that for any eigenvalue $λ$ of $T$, the number of Jordan blocks corresponding to $λ$ in the Jordan canonical form of $T$ is $\dim\ker(T-\lambda I)$

What is the intuition behind this? I fail to see why this must hold, it seems totally non-intuitive and out of the blue. Could someone help me come up with a proof, and possibly drive some much-needed intuition along the way?
I know that since the minimal polynomial splits over $\mathbb{F}$, $V$ can be written as a direct sum of the generalized eigenspaces $V(\lambda_i)$. Also, $(T-\lambda_iI)$ is nilpotent on $V(\lambda_i)$, so the restriction $(T-\lambda_iI)\vert_{V(\lambda_i)}:V(\lambda_i)\to V(\lambda_i)$ has a Jordan basis (its matrix can be brought to the Jordan normal form). The number of elements in this basis are equal to $\dim V(\lambda_i) = \dim\ker (T-\lambda_iI)^{\dim V}$ which is not necessarily equal to $\dim\ker (T-\lambda_iI)$.
What now? I'm stuck.
Comment: It's probably easier to see if you try it out yourself. Write down a matrix in Jordan canonical form with a bunch of blocks and subtract off $\lambda I$ for some eigenvalue $\lambda I$. Then count the number of zero rows/columns.
Comment: @EuYu Yes, I see it now! I really liked your argument.
Comment: How much do you know about Jordan bases? Do you know what I mean by a "chain of generalized eigenvectors"?
Comment: I know what generalized eigenvectors are. I don't know what their chain is?
Comment: Since you mentioned that you already know $V$ decomposes as generalized eigenspaces, write $T$ in its Jordan canonical form. The nullity of a Jordan block is either $0$ to $1$ depending on if its diagonal is zero or not. The nullity of $T-\lambda_i I$ is therefore equal to the number of Jordan blocks whose diagonal is equal to $\lambda_i$.
Comment: "The nullity of $T−λ_iI$ is therefore equal to the number of Jordan blocks whose diagonal is equal to $λ_i$." - Why is that true?
Answer: Consider a $3\times 3$ Jordan block
$$\begin{pmatrix}\lambda&0&0\\
1&\lambda&0\\
0&1&\lambda
\end{pmatrix}.$$
Now subtract the matrix $\lambda I$ to get the matrix
$$\begin{pmatrix}0&0&0\\
1&0&0\\
0&1&0\end{pmatrix}.$$
Can you see why the kernel of this matrix has dimension $1$?
And if we subtract $\mu I$, where $\mu\neq\lambda$, we get the matrix
$$\begin{pmatrix}\lambda-\mu&0&0\\
1&\lambda-\mu&0\\
0&1&\lambda-\mu\end{pmatrix}.$$
Can you see why the kernel of this matrix has dimension $0$?
This applies to all Jordan blocks. The kernel of $J_\lambda-\lambda I$ for any Jordan block $J_\lambda$ has dimension $1$, always. And the kernel of $J_\lambda-\mu I$ where $\mu\neq0$ has dimension $0$, always. So if we have a block diagonal matrix consisting of only Jordan blocks, each block with eigenvalue $\lambda$ contributes exactly one dimension to the kernel of $T-\lambda I$, and there are no other contributions from the rest of the blocks. So $\dim\ker(T-\lambda I)$ is the number of blocks corresponding to the eigenvalue $\lambda$.
Answer: Let $J$ be the Jordan form of $T$. In other words, $J$ is in Jordan form and there is an invertible map $S: \Bbb R^n \to V$ for which
$$
T = SJS^{-1}.
$$
With that, it follows that
$$
\begin{align}
\dim \ker(T - \lambda I_V) &=
\dim \ker(SJS^{-1} - \lambda SI_n S^{-1})
\\ &= \dim \ker(S[J - \lambda I_n]S^{-1})
= \dim \ker(J - \lambda I_n).
\end{align}
$$
Now, the question is how $\dim \ker(J - \lambda I_n)$ relates to the structure of the blocks of $J$. Without loss of generality, suppose that the blocks of $J$ are ordered so that
$$
J = \pmatrix{J_1 &0\\0 & J_2},
$$
where $J_1$ consists of all blocks associated with $\lambda$ (and the remaining blocks form $J_2$). We see that $J_2 - \lambda I$ is invertible, which means that $\dim \ker(J - \lambda I) = \dim \ker (J_1 - \lambda I)$.
However, note that $J_1 - \lambda I$ is already in reduced row-echelon form: at the start of each Jordan block, there is a zero-column, and all other columns are pivot-columns. Thus, $\dim \ker(J_1 - \lambda I)$ is simply the total number of Jordan blocks in $J_1$.
Comment: Note: I follow the convention in which Jordan matrices are upper-triangular, in agreement with [the wiki page](https://en.wikipedia.org/wiki/Jordan_normal_form)


Is using Natural Join or Implicit column names not a good practice when writing SQL in a programming language?

Question: When we use Natural Join, we are joining the tables when both table have the same column names.  But what if we write it in PHP and then the DBA add some more fields to both tables, then the Natural Join can break?
The same goes for Insert, if we do a
insert into gifts values (NULL, "chocolate", "choco.jpg", now());

then it will break the code as well as contaminating the table when the DBA adds some fields to the table (example as column 2 or 3).  So it is always best to spell out the column names when the SQL statements are written inside a programming language and stored in a file in a big project.
Answer: Natural joins are not a good idea wherever you write them. They hide the meaning that more explicit code would expose and may introduce subtle bugs if column names change.
Answer: yes it is always best practice to state your fields explicitly. Otherwise when you modify your schema, your code will break.
Answer: Yes it is always a good idea to explicitly name the columns you are concerned with. As you point out, this prevents the query breaking if someone adds a column to the table.
The same applies for prefering to list columns in a SELECT instead of writing SELECT *. See this related question.


Calcular de x em x segundos

Question: Tenho este código que calcula em 1 segundo em 1 segundo entre uma certa hora para depois inserir numa tabela. Em vez de calcular a cada 1 segundo, como posso calcular, por exemplo, de 5 em 5 segundos?
for y = horaInicial, horaFinal-1 do
    hora = tostring(math.floor(y / (3600)))
    minuto = tostring(math.floor((y - hora * (3600)) / (60)))
    segundo =  tostring(math.floor(y - hora * (3600) - minuto * (60)))

end

Comment: Explique melhor o que é esse "calcular em 5 segundos".
Comment: Esse codigo insere numa tabela de 1 em 1 segundo, entre a hora inicial e a hora final. Queria que calculasse com um determinado secundo, como por exemplo 5.
Comment: Topico com o codigo completo: http://pt.stackoverflow.com/questions/49812/inserir-num-array-entre-determinados-valores
Answer: Basta adicionar um terceiro parâmetro para o for indicado os pulos que devem ser dados. Assim:
function str2time(hora)
    return tonumber(string.sub(hora, 1, 2)) * 3600 + tonumber(string.sub(hora, 4, 5)) * 60 + tonumber(string.sub(hora, 7, 8))
end

hora_array = {"20:03:02", "20:03:35"}
horaInicial = str2time(hora_array[1])
horaFinal = str2time(hora_array[2])
hora_array = {}
for i = horaInicial, horaFinal - 1, 5 do --note o 5 aqui --------------------------
    hora = math.floor(i / 3600)
    minuto = math.floor((i - hora * 3600) / 60)
    segundo =  math.floor(i - hora * 3600 - minuto * 60)
    table.insert(hora_array, string.format("%02d:%02d:%02d", hora, minuto, segundo))
end

for i, v in ipairs(hora_array) do print(v) end

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.

Calcular de x em x segundos


how to properly reflect changes from branch to another with rebase

Question: I have three branches named master, foo and bar. foo and bar both branches are created with master branch. When I make changes in foo(a very minor on which is very important for bar too) I want the same changes to be applied to bar and vice versa.
I think, I can do merge and rebase but merging is long way to go. I don't want master to be affected, just foo and bar.
Comment: Cherry pick your foo commit in bar  edit : See Ivan answer
Answer: You can git cherry-pick your commit from foo to bar.
Just find out what the SHA of the commit is, navigate to bar and run git cherry-pick <SHA_ID>.
You can find more on cherry-pick here.
Answer: The most straightforward solution would be to rebase bar on top of foo, and to redo the rebase whenever foo changes.
This would be simpler than having to cherry pick your changes.  For one thing, it would be much easier to see whether you'd missed anything in foo; you'd know because foo would diverge.  With git cherry-pick you wouldn't get that kind of visual confirmation.


Real Analysis Estimate of a Lebesgue measurable function

Question: I am trying to prepare for a qualifying exam and I came across the following question. I'm not sure how to proceed.
Could you please give me a hint on where to start?
Let $\{f_n\}$ be a sequence of Lebesgue measurable functions on $\Bbb R^n$.
Suppose you have an estimate of the form $\int_\Bbb {R^n}|f_n|\le c_n$ where $c_n$ decrease to $0$.
Can you conclude that $f_n \to 0$ almost everywhere?
If not, what additional conditions on $\{c_n\}$ would guarantee this?
Thank you so much for your help.
Answer: Consider following function on $\Bbb R$ for simplicity:
$f_1=1_{[0,1]}$
$f_2=1_{[0,1/2]}, f_3=1_{[1/2,1]}$
$f_4=1_{[0,1/3]}, f_5=1_{[1/3,2/3]}, f_6=1_{[2/3,1]}$
.
.
.
Then, clearly it's integral goes to $0$ as $n\to \infty$ but $f_n$ does not.
Comment: To finish off, note that if in addition we require that $\sum c_n<\infty$, then the conclusion holds.
Comment: @AndresCaicedo I think that's right but can you give some hint for that condition?
Comment: Let $f$ be $|f_0|+\sum|f_{n+1}|-|f_n|$, so $\int f=\lim\int|f_n|$, and use the $M$-test to justify the manipulations of the series.
Comment: I understand what you are saying but i don't quite see why it is true that f_n does not go to 0 almost everywhere as n -> infinity
Comment: @Mike As you see, $\int f_n\to 0$. But if you take any point $x$ in $[0,1]$, it's contained in infinitely many interval of form $[k/n,(k+1)/n]$, so it does not go to $0$.
Comment: ahh i see! thanks!


How to get i18next.t() in plain JS file?

Question: Overview
React application in which internationalization is required, using i18next to achieve this.
Problem
In project structure there is constants.js (Plain JS) where I am trying to get i18next.t() for translation. Please find the relevant code.
index.js
import React,{Suspense} from "react";
import ReactDOM from "react-dom";
import "./style/index.scss";
import App from "./app";
import createSagaMiddleware from "redux-saga";
import { createStore, applyMiddleware } from "redux";
import { Provider } from "react-redux";
import rootReducer from "./reducers";
import rootSaga from "./sagas";
import './i18n';

const sagaMiddleware = createSagaMiddleware();
const store = createStore(rootReducer, applyMiddleware(sagaMiddleware));
sagaMiddleware.run(rootSaga);

ReactDOM.render(<Provider store={store}>

    <App store={store} />

</Provider>,
    document.getElementById("root")
);

App.js
import React from "react";
import "./App.scss";
import MyOrders from "../component/my-orders";
import { toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import i18n from 'i18next'

toast.configure({ autoClose: 5000 });

const changeLanguage = (lng) => {
    i18n.changeLanguage(lng);
};

const App = () => {

    return (

                <button className="btn btn-group-sm" onClick={() => changeLanguage('de')}>German</button>
                <button className="btn btn-group-sm" onClick={() => changeLanguage('en')}>English</button>

            <MyOrders />

    );
};

export default App;

i18n.js
import i18n from "i18next";
import detector from "i18next-browser-languagedetector";
import { reactI18nextModule } from "react-i18next";

import translationEN from '../public/locales/en/translation.json';
import translationDE from '../public/locales/de/translation.json';

// the translations
const resources = {
  en: {
    translation: translationEN
  },
  de: {
    translation: translationDE
  }
};

i18n
  .use(detector)
  .use(reactI18nextModule) // passes i18n down to react-i18next
  .init({
    resources,
    lng: "en",
    fallbackLng: "en", // use en if detected lng is not available

    interpolation: {
      escapeValue: false // react already safes from xss
    }
  });

export default i18n;

Question Updates with progress so far
constants.js (Plain JavaScript file, exporting multiple constant objects)
import i18n from "../../i18n";
import { withNamespaces } from "react-i18next";

function parentFunction(){
   let constantsMap = new Map();
   constantsMap.set("constant1", valueOfConstant1);
   ....
}
export default withNamespaces()(parentFunction)

translation.js (de)
{
"MODAL": {
    "CANCEL": "Stornieren",
    "UPDATE": "Aktualisieren",
    "SAVE": "Speichern",
    "CANCEL_BOD": "Ja, Abbrechen BOD",
    "KEEP_BOD": "Nein, behalte BOD",
    "NEXT": "Nächster"
}, .....

I tried the following solution with no luck:
Solution
Answer: You can import i18n instance from your i18n.js file, it contains t on it.
import i18n from '../i18n';

i18n.t // <- use it.

Comment: Ha, so invert the dependencies, constants will hold the keys, and each user will import it and pass to translation.
Comment: You probably need to define the `namespace` && `language`, which doesn't make sense to do directly in constants file. Consider to convert those constants to functions that gets `t` (from react) and returns a translated value.
Comment: @felixmosh, Thanks for the help buddy, it was a good discussion.
Comment: Thanks for the answer, still having an issue, I am able to get `i18n.t()` in the constants file but it's not translating content as per defined in translation.js file instead it does not seem to do anything at all.

I've updated the question with some of the content of the translation file.
Comment: I am trying it as per directives from you, hope it should work.
Comment: I've tried to convert constants to a function called `parentFunction` (updated question with progress so far) and then exported it to where I wanna use but exporting with name spaces doesn't seem to work. I get an error where I am getting value of Map:

> constantsMap.get("constant1") is not a function

When I am exporting it without namespaces it exported correctly with no error, but unable to translate because I am not exporting with namespaces.
Comment: I ment something much simpler, assume that constants export a constant variable X, instead of that export function getX, that accepts t from outside (react) and returns the translated value.
Comment: I tried this, I am importing i18n in one of my constants.js file. It's a simple plain JS file with contant strings and objects. In my case it properly load the default language and get the correct value from translation file. But when I change the language it doesn't reflect. Changing language works well everywhere else
Comment: Sure, it won't work on language change. Can u explain what are those constants strings that you have in it? And what do u want to translate?
Comment: So for example some basic array to populate some drop down. It's been used multiple times so kept them in a central location for reuseability.
Comment: I didn't get the part "invert the dependencies". However I ended up putting keys in constants.js and used t function inside components and it worked as expected
Comment: That what I've meant by "invert dependencies" :]
Comment: I use `i18next-scanner` and so I have also set up an `N_()` function that I use to mark the constants for translation. At the callers, we can use the `t()` function to actually get the translation. This is how I implemented the "invert dependencies" discussed above.
Answer: I used it this way on redux saga
import i18n from "i18next";
      toast.error(i18n.t('thereWasAnErrorUpdating'), {
            position: toast.POSITION.TOP_CENTER,
            autoClose: NOTIFICATION_TIME,
            toastId: 'settingInformationFailure'
        });


Area of the grey region in the following triangle

Question:
$ABC$ is a triangle having area of $240$.
Given that $BD:DF:FC=3:4:3$; $BE:EA=5:7$ ; $CG:GA=2:7$ then what is the area of the grey region?

I am not getting any way to start this question, any hint on the theorem will be helpful.
Comment: I dont know how to start this, i know the properties for lines parallel to a side of triangle dividing in some ratios but in this case they are not parallel.
Answer: $$\frac{S_\Delta{BED}}{S_\Delta ABC}=\frac{5\cdot3}{12\cdot10}=\frac{1}{8};$$
$$\frac{S_\Delta{GFC}}{S_\Delta ABC}=\frac{2\cdot3}{9\cdot10}=\frac{1}{15}$$
Thus, $$S_{AEDFG}=240\left(1-\frac{1}{8}-\frac{1}{15}\right)=194.$$
Comment: A little explanation around this might be quite nice
Comment: The idea is the same as mine below. Let h be the height of triangle ABC from C. $A_{ABC}=0.5*AB*h$ and  $A_{EBC}=0.5*EB*h$ hence  $A_{EBC}=EB/AB * A_{ABC}$. Similarly $A_{EBD}=DB/CB * A_{EBC}$, and then you get Michael's formulas...
Comment: can you please explain how you did this? did you establish bed and abc are similar triangles?
Comment: @swapedoc It was typo. See now.
Comment: @MichaelRozenberg Can you please give a little explanation on the property used to calculate ratio of areas
Comment: I dont find BED and ABC as similar ie ED not parallel AC similarly GF is not parallel AB
Comment: Nvm understood .You used 1/2 AB*BC sin B
Answer: Let H be the point of (BC) s.t. (AH) // (ED)
You can find the ratio of BD/BH, hence the area of BAH (which has the same height from A than ABC).
Then you can calculate the area of BED which is a triangle similar to BAH.
You can find the area of GFC in the same way.
The answer is Area ABC - Area BED - Area GFC.
Comment: i am sorry i am not getting you BED lets say = x ABH (as they are similar)
Lets say I take another point T on BC such that AT//GF and GFC = yATC. (as they will be similar) but T and G are not same !.Then how will the solution be possible


A specific improper integral

Question: I have been given the following improper integral to evaluate

$$ \int_{0}^{1} \frac{x^2-1}{\log{x}} dx $$

I tried substituting $ u = \log{x} $ which gives the following improper integral
$\displaystyle \int_{-\infty}^{0} \frac{e^{3u}-e^{u}}{u} du $
This integral can be evaluated by software like Wolfram but I am interested in the method. How does one solve the integral analytically? I have no real idea on this. Thanks to all helpers.
Answer: $$\int_{-\infty}^{0} \frac{e^{3u}-e^{u}}{u} du=\int_{-\infty}^{0} \int_1^3 e^{xu}\ dx\ du=\int_1^3 \int_{-\infty}^{0}  e^{xu}\ du\ dx=\int_1^3 \dfrac1x\ dx=\ln3$$
Comment: This is a classic Frullani integral - https://en.wikipedia.org/wiki/Frullani_integral

A specific improper integral


Is there a specific name for the type of bridge that signals that a song is going from one key to another

Question: The music starts in C and then there is a BRIDGE of some type that is played and the ear is prepared for the fact that the music is going to another key.
What is this "we are shifting to another key"bridge called?
Comment: When should that transition take place? WIthin the bridge, directly after it or even later?
Comment: Directly after it.
Answer: I don't study popular music all that often, but in other genres, we would just qualify this with an adjective that suggests it modulates. We have a few ways of saying this in our toolbox:

Modulating bridge
Modulatory bridge
Progressive bridge

I don't know if there's an official term for this, but if there isn't, I think any educated musician would know what you mean if you used one of the above terms.
Answer: The word "bridge" refers to a part of the song or piece of music and is often discussed in terms of the song's "structure" or musical form.  See https://tobyrush.com/theorypages/ Under the subheading "The Common Practice Period: Development & Form,"  there are a number of easy to comprehend pamphlets that should cover about this area of music theory albeit with reference to log-dead composers.
If the music changes key centre that would be called "modulation" Here Toby Rush covers modulation on a pamphlet called, "Diatonic Common Chord Modulation" Toby explains the jargon.
Comment: Thanks, Emma.  This was exactly what I needed.


OAuth authorization returns "Authorization has been denied for this request" in a Azure Mobile App project

Question: I implemented OAuth authorization in a .Net Web Api project following this tutorial. I need to do the same, but within an Azure Mobile App project. It is published and everything works fine like a Web Api until I try to authenticate my calls to the controllers. When I add the authorize attribute and I call the api, I am supposed to send a bearer token. Please note that I do this using PostMan with my Web Api project and everything works perfect. But, in the Azure Mobile Application, every time that I call a controller with the authorize attribute using the right bearer token, it comes back with the "authorization has been denied for this request" error. The code between the web api project and the azure mobile application project is exactly the same with the only exception been in the startup class.
Web Api startup.cs:
public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        ConfigureAuth(app);
    }
)

Azure Mobile Application startup.cs:
public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {

        ConfigureMobileApp(app);
        ConfigureAuth(app);
    }
}

I think that the problem has to do with the ConfigureMobileApp function, as it has some authentication code within itself, but I am not sure. I am not used to the start up class. Still kinda noob with it.
So, every call to the web api project using the bearer token, works fine. Every call to the azure mobile application project using the bearer token, comes back with the "authorization has been denied for this request" error.
What can I do to workaround this???
Thank you!!
Answer: According to your description, I followed the tutorial you mentioned to test this issue. According to your code, I assumed that you have created the Azure Mobile App application. You could try to change your Configuration method as follows:
public void Configuration(IAppBuilder app)
{
    ConfigureAuth(app);
    ConfigureMobileApp(app);
}

Note: The ConfigureMobileApp method within Startup.MobileApp.cs called this app.UseWebApi(config);, so you need to init your middleware before this code.
Here is my code snippet, you could refer to it.
Startup.OAuth.cs
public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }

static Startup()
{
    OAuthOptions = new OAuthAuthorizationServerOptions
    {
        TokenEndpointPath = new PathString("/token"),
        Provider = new OAuthAppProvider(),
        AccessTokenExpireTimeSpan = TimeSpan.FromDays(2),
        AllowInsecureHttp = true
    };
}

public void ConfigureAuth(IAppBuilder app)
{
    app.UseOAuthAuthorizationServer(OAuthOptions);
    app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}

Startup.MobileApp.cs
public static void ConfigureMobileApp(IAppBuilder app)
{
    HttpConfiguration config = new HttpConfiguration();

    new MobileAppConfiguration()
        .AddMobileAppHomeController()
        .MapApiControllers() //provides custom API capabilities for WebAPI controllers decorated with the [MobileAppController] attribute
        .ApplyTo(config);

    app.UseWebApi(config);
}

ValuesController.cs
// Use the MobileAppController attribute for each ApiController you want to use
// from your mobile clients
[MobileAppController]
[Authorize]
public class ValuesController : ApiController
{
    // GET api/values
    public string Get()
    {
        return "Hello World!";
    }
}

Result

Additionally, Azure Mobile Apps use App Service Authentication / Authorization to secure your mobile backend, for more details, you could refer to this official document. Also, you could refer to Adrian Hall's blog for a better understanding of Azure Mobile Apps.
Comment: Thank you Bruce for your fast answer. I edited my code following yours and now, when I test it locally in PostMan, it cames back with the following error: ""No API version was specified in the request, this request needs to specify a ZUMO-API-VERSION of '2.0.0'.  For more information and supported clients see: http://go.microsoft.com/fwlink/?LinkId=690568#2.0.0""

What this could be?
Comment: Well, it worked adding the header "ZUMO-API-VERSION" with the value "2.0". Thank you Bruce!!
Comment: Glad to hear that you have solved this issue. For `ZUMO-API-VERSION`, you could call `MobileAppSettingsDictionary settings = config.GetMobileAppSettingsProvider().GetMobileAppSettings();
settings.SkipVersionCheck = true;` before `app.UseWebApi(config);` to skip the version checking.  If my answer could help you, kindly mark it as acceptable answer, which could help other community members who could encounter the same issue.
Comment: Sorry for being late on this one. I marked your answer as the accepted one. Thank you very much.


Redirecting only root without changing the URL in Apache

Question: I'm redirecting only the requests coming to the root to a subfolder in the same server.
Now I would like to make the URL not change during the redirection.
My .htaccess looks like this
RewriteEngine on
RewriteBase /

RewriteCond %{HTTP_HOST} !^m\.
RewriteRule ^$ /myFolder [R,L]

I tried to add P as an option, but it did not help. How can it be done?
Answer: You can use :
AliasMatch ^/$ /path/to/myFolder/

Old reply:
If you want to keep the query string, you must add the QSA option to your rewrite rule.
Comment: It's not about the query string, I just want the URL to show mydomain.com instead of mydomain.com/myFolder
Comment: See my new answer.


Deploying web app: updating assets on cdn and references to assets on server

Question: I deploy my web application server code to the cloud platform.
While the procedure the deploy tool takes all files (from local file system or git repo), uploads it to the cloud and restarts the app.
Every time my front-app assets (images, css, js) change I need to redeploy the whole app (and restart it). There is not build in file API to upload only some files for the application.
My build process of front app prepares all the assets: images, css, js and index.html file that contains references to the assets. Every build assets have different md5 names (if changed) to insure caching.
After front build is completed it deploy the whole app. User request the certain address and server responds with new app's index.html.
What I want is to avoid deploy of server app, when only the front app is changed.
I can upload new files to CDN, but the client first will connect to the server and it needs to know which assets it should load (actually it needs correct index.html in response).
The problem is about updating web application front assets and references on server without touching other parts of running server app.
How this problem can be solved?
What I though of:

Server has index.html template
Build process of front app uploads new files to CDN
Build process updates some enties indatabase to reflect changes in assets
Every time client request
the server for the app, it builds correct index.html using template
and database data.
The alternative option without using database, every time client request the server, server first requests some CDN (or shared location) with correct index.html, and responds to the client.

Which way is more correct to go with, and what are best practices for that problem?
Comment: Is the problem that your index.html is linking to some "app.js" out on the cdn, but maybe the name of your js file changes after each asset build? E.g. "app_1.js" on first build, "app_2.js" on second, etc. (as probably an extremely simplified example)? I'd think you can get away with not renaming assets between builds, but using your CDN's tools to bust the cache as needed when updates land there.
Comment: What CDN's tools do you mean?
Answer: One way around this problem is proper separation of business logic and your views.
Restructuring your application along the lines stated below would benefit you in the long run.
1.Build an API  out of your current business logic.
2.Convert your views into a full  client side application with a client side technology like angular, react, backbone, etc.
Your client can be pushed to a CDN (or hosted separately) easily and only maintains reference to your server API.
This way your server app doesn't know anything about your views/client apart from handling API calls.


Extended chord types for all major scale degrees

Question: I am trying to chart the types of extended chords for all scale degree of the major scale. I have come up with the chart below.
A few questions on this:

Have I got the chord types correct?
In a chord progression, is it possible to substitute any chord degree for any of the extended
chords in the same degree? As in, a ii minor 11 can be played for any ii chord to make it more interesting. (Assume playing diatonically only.)
The vii degree is beyond me. What are the chord types for the extended chords?
I am working of the basis that the chords are defined as below. Is this correct:

   Maj -> 1 3 5 7 9 11 13 Min -> 1 b3 5 b7 9 11 13 Dom -> 1 3 5 b7 9 11 13
Comment: I'm a little confused. Let's take key C. iii is E. At this point, which set of notes is being used? If we take E Phrygian, or E natural minor, or E harmonic minor, or E melodic minor, we have four different sets of notes. All will use the same three for the basic triad, but problems arise with extensions, starting with the 7ths. They could be m7, m,maj7. The 9ths will be o.k., but then it goes awry - for me at least. using purely diatonic notes (from key C), Em7b9? The b9 is another root note.
Comment: The title and first line of the question states that this is in relation to the major scale. We only have one set of notes. There is no mention of modes anywhere. In your example, the iii7 chord would be built up of EGBD which is a minor 7. Futher, the three basic notes on the triad DO NOT remain the same between modes. The thrid in the root chord is major in a major key (Ionian), and is flat in a minor key (Aeolian).
Comment: O.k., so it's *only* using diatonic notes from the parent scale. That's now understood. 'All will use the same three for the basic triad' means Em, in whatever Em mode or scale, will always have EGB, only. It's a given that a major triad will not have the same 3rd as a minor triad ! So have I understood that the 9th built on iii is made up from E G B D F (which *could* be G13) is called m7b9 due to the 'normal' 9 being F#?
Answer: The vii row of your chart will be

o (diminished)   |   m7b5 (half-diminished)   |   m7b5b9   |   m11b5b9   |   m11b5b9b13

The remaining chords are correct.
Substitutions depend on context, but as a general statement, yes, you can add or remove chord extensions/alterations as you see fit. Notice also that extended chords "contain" other chords. For example, the CM9 chord "contains" an Em7 chord, opening up addition substitution possibilities.


Need to sort views block by current node first

Question: So what I'm doing is setting up a block with images that link to it's corresponding testimonial page.  Each testimonials has it's own node, and I want to sort the block so that the first image in the block is the one that links to the current testimonial page that the user is on. For example:
I have testimonials from:
Student A
Student B
Student C
Student D
If I'm on the page for Student C then the order of the block should be:
Student C
Student A
Student B
Student D
Anyone have a good way to do this?
Answer: A quick solution might be using the module Views PHP.
As far as I understand your problem, you want to sort a list but have the current student at the top.
I used a Content Type name 'Students' with a integer field 'Rank', representing the field to sort the students.
Create your view and a block and set up your view as follows:

Format: as you like, no grouping
Show: Fields, no special settings
Fields:

Content: Nid (exclude from display)
Content: Title
Content: Rank

Filter Critera

Content: Published (yes)
Content: Type (= Student)

Sort Criteria:

Content: Rank (asc)
Global: PHP (asc) -> this is from the Views PHP module

Configure the Views PHP filter similar to this:
Sort Code (no php tags!):
<code>$nidFirst = arg(1);
return $row1->nid != $nidFirst;
</code>
That's it. Embed the resulting block on your students page and navigate to one of those pages.
Sort criteria 1 gets the result into the default order, e.g. best rank is on top.
Sort criteria 2 fetches the current students node id (nid) from the url (assuminf it realy is the first argument), compares it to each row and returns true, if the rows nid is not equal to the current students nid.
As the sort direction is ascending, all rows with a comparison result of true will be moved below the row with the result false, so the current student ends up at the top of the list.
Comment: Thanks so much, that worked perfectly. I never thought of using Global: PHP in the sort field.


Tkinter PhotoImage: References in Memory?

Question: I have a program that displays many tkinter PhotoImages at once (relevant: I'm not using PIL). It currently has several screens, and when the play gets to the edge it loads a new tilemap, creating a bunch more photoimages in the currentTiles array after clearing the old contents. I'm fairly certain there are no other references to these photoimages in the rest of the program.
The weird thing is that when I print the contents of the last item in the array after the loadLevel function is called, it says things such as "pyimage3761", and it increments each time I load a new screen. Is this due to tkinter keeping track of how many have been created so far, or is it because the old tiles are still in memory? I can't for the life of me figure out where there could be another reference, so I'm just wondering if there are any other possibilities before I spend hours looking for errors.
Thanks!!
Answer: Every created image is assigned a unique name (unless you specify the name of the image when creating). This unique name is generated  by using a counter, which increases monotonically.
Comment: Even if the previous ones are no longer in memory?
Comment: what does that have to do with anything?
Comment: My concern is whether the previously created photoimages have been retained in memory through an obscure reference I am missing. I can't seem to find one, so I'm wondering if the numbers on pyimages increase regardless of whether the previous ones are still retained in memory. Sorry for being unclear.
Comment: The numbers increase regardless of the existence of previous ones. That's part of what "increases monotonically" means.


Primes of the form 1..1

Question: For $n \ge 1$ an integer, let's denote
$u_n = \sum_{k = 0}^{n-1} 10^k$
That is $u_1 = 1$, $u_2 = 11$, $u_3 = 111$, $u_4 = 1111$, ...
My question is the following : Which of them are prime numbers ?
What I know so far :

If $u_n$ is prime, then $n$ is prime (meaning there's an obvious factorization when $n$ is not prime).
When $p$ is prime, $u_p$ can either be prime (2, 19 and 23 being the only examples I found so far) or not prime (all primes up to 67 with the exception of 2, 19 and 23). But I haven't been able to see any pattern.

Any thought is welcome. Maybe a sub-question would be to know whether there's a finite or infinite number of such primes. Thanks for your help.
Comment: Note: these are called repunit primes http://en.wikipedia.org/wiki/Repunit
Comment: You mean k starts with 0? see this form: $(10^(n+1)-1)/9$ which is equivallent to yours, if it helps...
Comment: @tomerg : Yes that's what I meant. Thanks for pointing it out.
Comment: @ Douglas S. Stones : Thanks for the reference. Also I see I had forgotten $u_{19}$ somehow. So it seems it's an open problem. This question was asked to me on an exam, so I thought there might be an easy answer I had overlooked.
Answer: OEIS has a list of the number of 1's where these are prime.  It only has eight of them, the next is 317.  So you could have looked for a while.
Comment: @Joel Cohen: Primality tests are usually much faster than factoring.  A primality test on that number revealed that it is composite in less than a millisecond.
Comment: Thank you. Factoring $u_{71}$ already took a considerable amount of time. I surrendered at that point.
Comment: @ Charles : You're right. At first, I was also looking for a pattern in the factorization (any obvious factor). I should have had switched to just testing primality after a while.

Primes of the form 1..1