Percentage breakdown of categories of doubles in NBA

Question: A double consists of a player accumulating double digit number in one of the following categories per game: points, assists, rebounds, steals, and blocked shots. Achieving 2, 3, 4, or 5 doubles in a game is called double double, triple double, quadruple double, and quintuple double, respectively.
What is the percentage breakdown of each category for each of the 5 double types in the NBA? In other words, the percentage of a category for a given double type is the ratio of number of double that include that category to the number of all doubles.
Here is a hypothetical example only for double double type of what I'm looking for:

74% points
63% assists
45% rebounds
17% blocks
9% steals.

Percentage of each of the above categories is how often that category was part of double doubles. Of course a complete answer would have the same kind of percentage breakdown for all double types.
Answer: Since the 1983-1984 NBA Season (presumably the earliest data Basketball Reference has for double- and triple-doubles) to the creation of this post, there have been:

[number of type of double, double-doubles and beyond] (percentage among doubles, double-doubles and beyond)
71088 double-doubles (98.07%)

70970 points (99.8% of all double-doubles)
15861 assists (22.3%)
56631 rebounds (79.7%)
16 steals (0.02%)
99 blocks (0.14%)

1398 triple-doubles (1.93%)

1397 points (99.9% of all triple-doubles)
1334 assists (95.4%)
1394 rebounds (99.7%)
8 steals (0.057%)
64 blocks (4.58%).

4 quadruple-doubles (0.06%) (1)

4 points (100% of all quadruple-doubles)
4 assists (100%)
4 rebounds (100%)
1 steal (25%)
3 blocks (75%)

0 quintuple-doubles (0%)

I see a requirement for "single-doubles" and "single" category breakdown...I'll update this post if I collect that information.
Comment: I added the comment example to the question. I tried my best to convey that I wanted the breakdown by introducing the categories - otherwise they are not related to the question. But it clearly wasn't enough
Comment: With all the double talk (no pun intended), I became lost. It's almost a tongue twister haha.
Comment: If you think you can edit it to make the point more clear feel free to do so
Comment: It's much clearer now with your example and "Percentage of a category is how often that category was part of a double double." I don't think I can make it clearer than that. In any case, I added double-double category breakdowns.


Feature Scaling in Reinforcement Learning

Question: I am working with RL algorithms like DQN and ActorCritic and I'm curious whether there is a way to correctly scale features which represent state or state/action pair while learning parameters of value function approximator and policy approximator.
In supervised learning we generally scale features on whole training set, in order to make objective function more convex and decrease learning time, storing mean and variance (i.e. zscore normalization) and applying them on test/cv set during validation.
In RL we dynamically obtain data via agent-environment interaction, so DQN's memory buffer updates at every timestep.
It is also necessary to normalize features if they have different scales in RL as well as in Supervised Learning.
Is there any standard process to scale features correctly for DQN and ActorCritic methods specifically, considering the dynamic nature of RL?
Answer: I've seen a number of different tactics used in different projects.

Some people just ignore scaling altogether.
Some people define the environment such that all of the data is implicitly scaled. For example, the information about the state is already scaled as a standard normal distribution.
Relying on strategies like layer normalization to do scaling for you.

If it's possible, (2) seems like the preferred option: if you have the ability to control how the environment relays its data, then you can just solve the problem directly.
If that doesn't work, then using layer normalization seems sufficient, since it will dynamically update to reflect the mean and variance of the incoming data.
Ignoring scaling seems risky  to me, since it's well-known that scaling can dramatically improve the learning process in supervised settings.
Comment: @mdornfe1 You can ask a new question by clicking the Ask Question button.


How to recursively fill a tree with 4 children below each node in Java

Question: I've built my own tree data class in Java which is to be used in a minimax algorithm. Each node in the tree will hold a Board object (something else I created) representing a unique game state, and edges (Integer's representing move directions —— the game is Tron) in the tree will represent the move made by a user to reach the state the edge leads to. I want to make a function which takes in a Tree and recursively fills it up to a depth 'DEPTH' (held as a constant elsewhere, not a parameter) with modified game states given each of the four possible Integer moves made by each player at each level. I'm just not quite sure how best to do it...
Also, since it's being used for minimax, the tree structure has to be as follows:

A root representing the current, unchanged game state
1st level children representing the altered game states given the user's 4 possible moves
2nd level children representing the altered game states given the opponent's 4 possible moves
3rd level game states for the user's 4 moves given the opponent's moves, and so on... extending on to DEPTH number of levels

Here are the basic methods that I have to work with:

a constructor for Tree taking a Board and an Integer direction leading to the board
a method called produceChildren() that takes a Tree and boolean 'userMove' and adds 4 new Board's to the Tree's internal list of children which represent the altered game states given each of the user or opponent's 4 possible moves. The 'userMove' parameter designates whether the Board's produced as children should be results of a user's 4 moves or an opponent's 4 moves.
a method of Tree called getDepth() that return the node's depth within a larger tree consisting of its parent and children (if it has any) --> returns 0 if it is the root

Could anyone perhaps provide me with a bit of pseudocode (using the methods I've provided, unless other methods are needed) for how I would fill a Tree in this alternating, minimax-catered way?
Answer: I have a couple of comments on your data structure before you move on to implementation of the logic.
It's not necessary to store a complete copy of the board in each node of the tree. Given it's being used for minimax the only thing you need to know at each point is the moves to get there and the value of that position. You will need to know the state of the board in the leaves to calculate the value but even then there's no need to keep a copy of it once the calculation is complete.
To go even further, minimax doesn't even require you to keep a permanent copy of the tree. If done using recursion the max or min value at each node can be kept in local variables and returned - there's no need to keep a permanent copy in a tree.
The wikipedia article on minimax has some pseudocode that can get you started.


Calendário Android por semanas e meses

Question: Estou a trabalhar com calendários em Android. O objetivo é mostrar o calendário por semanas e por meses. Mas o calendário que estou a utilizar só me permite a visualização por mes.
Código xml
    <android.support.constraint.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <com.prolificinteractive.materialcalendarview.MaterialCalendarView
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/calendarView"
            android:layout_centerInParent = "true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:mcv_showOtherDates="all"
            app:mcv_selectionColor="#00F"
            />
    </android.support.constraint.ConstraintLayout>

Activity onde este é invocado
    MaterialCalendarView materialCalendarView = (MaterialCalendarView) findViewById(R.id.calendarView);
    materialCalendarView.state().edit()
            .setFirstDayOfWeek(Calendar.MONDAY)
            .setFirstDayOfWeek(Calendar.DAY_OF_WEEK)
            .setMinimumDate(CalendarDay.from(1900, 1, 1))
            .setMaximumDate(CalendarDay.from(2100, 12, 31))
            .setCalendarDisplayMode(CalendarMode.MONTHS)
            .commit();

    //quando um dos dias é selecionado
    materialCalendarView.setOnDateChangedListener(new OnDateSelectedListener() {
        @Override
        public void onDateSelected(@NonNull MaterialCalendarView widget, @NonNull CalendarDay date, boolean selected) {
            Intent intent = new Intent(getBaseContext(), ActivitySelecionado.class);
            enviarDados(intent, date);
            startActivity(intent);
        }
    });

A partir do que tenho aqui é possível configurar o calendário para ter a vista por semanas?
Answer: Para "ter a vista por semanas" você precisa modificar o valor do parâmetro do método setCalendarDisplayMode para CalendarMode.WEEKS.
Basicamente alterar de:
setCalendarDisplayMode(CalendarMode.MONTHS)

para:
setCalendarDisplayMode(CalendarMode.WEEKS)

Calendário Android por semanas e meses


Disable a check box after the the checkvalue enter into the database

Question: book.php
<input type="hidden" name="bus_fare" id="bus_fare" value="<?php echo $row['price'];?>"> 1

 <input type="checkbox" name="seat[]" id="seat_1"  value="1" onclick="seat_display(this.value);" />

<input type="hidden" name="bus_fare" id="bus_fare" value=""> 3

<input type="checkbox" name="seat[]" id="seat_3"  value="3" onclick="seat_display(this.value);" />

 <input type="hidden" name="bus_fare" id="bus_fare" value=""> 5

<input type="checkbox" name="seat[]" id="seat_5"  value="5" onclick="seat_display(this.value);" />

<input type="text" id="total_seats" name="total_seats" value="" readonly />

javascript

I want to disable those check boxes which are already checked and the values (checkbox) has already been sent to the database. Each checkbox has it's own unique value, so once an user check 1 or multiple checkbox in the book.php and the checkbox values are sent to the database, when next time another user comes he/she should see the already checked checkboxes are disabled, he/she cant select them. I want to use javascript for this. Any help?
Comment: I dont understand why you are using the name bus_fare repeatedly. It will be having only the last value. All the previous values will be overridden. I think you can get values from database before building the form . If there is value already present disable it.
Comment: i ve to call the ids with the same name thats why i m using the same name bus_fare.. how can i disable a checkbox after its value got inserted into database ??
Comment: can you please give what value are you adding to database or atleast the column names
Comment: the checkboxes which are checked are being displayed here "   " , these values got inserted to the database according to the checkbox value
Answer: Try this method
HTML
<input id="inlineCheckbox1" type="checkbox" value="1" name="spam[]">
<input id="inlineCheckbox1" type="checkbox" value="2" name="spam[]">
<input id="inlineCheckbox1" type="checkbox" value="3" name="spam[]">

Script
//Data from server already booked seats no
var data={
    "bookedseats": [
        "1",
        "2"
    ]
};
var ass=data.bookedseats
$("input[name='spam[]']").each( function(i,j) {
    if(jQuery.inArray($(j).val(), ass) != -1){
    $(j).prop('disabled', true);//this disables already booked seats no from server data
    }

});

DEMO
Comment: you update the database once user booked seats.then accessing that specific bus table to get the booked seats to update when the new user is logged
Comment: i want to disable the te textbox once the value got inserted to the DB
Comment: ok thats not a problem in using checkbox onchange function you update the db and get updated response and do the function
Comment: i just want to first fetch the seat numbers (checkbox value) inserted into the database according to the bus_name in javascript, i can update my databse aftre that can you write me that code please ??
Comment: fetch details using php ajax


Mailing content to a list/group of email addresses

Question: What kind of module should I use to send content to a list of emails?

I need to create a groups with list of emails.
I need to send it to one or a few of these groups.
I need for admins to be able to look at the email addresses which will receive the emails.

I am thinking about using mailchimp, but it does not fulfill all of my needs. Also simplenews_roles can be a good decision, but whre is no version on drupal-7. Is there another option available?
Answer: You can use the Newsletter module, which has a release for Drupal 7.

Newsletter module aims to be a full blown newsletter solution for Drupal 7. It is especially recommended for people that need more than one newsletter list for their site.
Features

Multiple newsletters lists configurable on existing terms
Plain text or HTML out of the box.
Multiple schedules Each newsletter can have more than one schedule, e.g. Daily, Monthly, Weekly, manually or even custom, eg after 10 new posts for this term.
Centralized administration and configuration on a single page.
Users can customize the terms in the list they subscribe to.
Custom template per list.
Statistics (CTR and Open-Rate).
Drupal 7 only.
Comment: Its not the best solution for me, because i need send content manualy to list of people.
Comment: This can handle manual newsletters as well.


Calculate big O complexity of partitioning problem

Question: My pseudo-code looks like:
solve(n)
    for i:= 1 to n do
       process(i);
       solve(n-i);

where process(n) is a function with some complexity f(n). In my case f(n)=O(n^2), but I am also interested in general case (for example if f(n)=O(n)).
So, I have T(n) = f(n) + ... + f(1) + T(n-1) + ... + T(1). I cannot apply Master theorem as the sub-problems are not the same size.
How to calculate complexity of this recursion?
Answer: Small trick – consider solve(n-1):
solve(n)  :  T(n)   =  f(n) + f(n-1) + f(n-2) + ... + f(1) + T(n-1) + T(n-2) + ... + T(0)
solve(n-1):  T(n-1) =         f(n-1) + f(n-2) + ... + f(1) +          T(n-2) + ... + T(0)

Subtract the latter from the former:

Expand repeatedly:

Solve the last summation for f(n) to obtain the complexity.
e.g. for f(n) = O(n):

Alternative method – variable substitution:

S(m) is in the correct form for the Master Theorem.
e.g. for f(n) = O(n) = O(log m), use Case 2 with k = 0:

Same result, q.e.d.
Comment: Excellent explanation. I think that there is one mistake, the sum of `i*2^i` is equal `n2^n` not `n2^n+2(2^n-1)`. Right? Anyway, this doesn't change overall complexity.
Comment: @Dejan I did make a typo there (should be - not + – will edit to correct), but the sum is [definitely not just equal to `n2^n`](https://www.wolframalpha.com/input/?i=sum+of+x*2%5Ex+from+x+%3D+0+to+x+%3D+n+-+1).


Why using gradient decent if we can just minimize function in closed form?

Question: I don't really understand why gradient descent is so important in neural networks? Wouldn't it be much easier to define an objective function in a way to do 0=parameters of objective function ? This way you would get the most perfect parameters out imidiately.
Answer: Most of the problems do not have exact analytical solutions. Let aside neural networks, even logistic regression (with MSE or cross-entropy) cannot be solved analytically. Logistic regression is a simple neural network, so solving exactly for neural nets in general is impossible when you're not even be able to solve the simplest of them. Even in the presence of an exact analytical solution (commenting for models other than neural nets), sometimes the way it is calculated exactly is not numerically stable or it is computationally more expensive and we may resort to iterative methods.


AutoFilter - Find out if second row of Visible Cells is blank

Question: I have some code that autofilters a worksheet based on either the first criteria, and then the second if no criteria is returned. The conditional statement is where I need help, it keeps on erroring even if there is data in the first cell of the second row (I obviously don't want to include the headers):
With ActiveSheet
    .AutoFilterMode = False
    With .Range("A1:F1")
        .AutoFilter Field:=1, Criteria1:="FirstTest"

        'See if first cell in second row is blank
        If (.Offset(2,1).SpecialCells(xlCellTypeVisible).Value = "") Then

            'if blank, change criteria
            .AutoFilter Field:=1, Criteria1:="SecondTest"
        End If

   End With
End With

I know you can use VBA.Array's for multiple criteria, but this gets more complex, I merely need to now how to reference the visible data in the second row.
Thankyou in advance for any assistance.
Answer: Try this:
With ActiveSheet
    .AutoFilterMode = False
    With .Range("A1:F1")
        .AutoFilter Field:=1, Criteria1:="FirstTest"

        'See if first cell in second row is blank
        If (.Parent.AutoFilter.Range.SpecialCells(xlCellTypeVisible).Count < 2) Then

            'if blank, change criteria
            .AutoFilter Field:=1, Criteria1:="SecondTest"
        End If

   End With
End With

Comment: Try: `.Parent.AutoFilter.Range.Rows.SpecialCells(xlCellTypeVisible).Count < 2`
Comment: Sorry I jumped the gun, this is working without errors but not accurately.
I have 10 rows on the screen (1 being the headings) and it's returning 126. If I filter down to 3 visible, it returns 18. Any ideas how this is even possible?
Comment: Oh! It's counting the cells, not the rows.Yahtzee. Thanks mate, your solution was definitely correct, I'll just update it slightly to count the rows.
Comment: The .Rows.Count was sometimes returning some odd results, but to fix this I just divided the cell count by the amount of columns I had:
rowCount = .Parent.AutoFilter.Range.SpecialCells(xlCellTypeVisible).Count / 6


find caller of python builtins

Question: This is similar to Profiling in Python: Who called the function? but with a twist.  I have a python function that I am profiling with cProfile.  On my first run, stats showed it spending most of its time in get_loc() from datetimes.py;
Fine, I found the datetimes.py file on my system and temporarily added import pdb and pdb.set_trace() at the top of get_loc() and then randomly used debugger command where several times with a more-or-less random number of continue's between wheres.  This showed me that, per my random sample, pretty much all of the couple thousand calls to get_loc() where coming ultimately from the same place in my own code.  I modified that code to significantly reduce the number of calls.  Great!
Next up, I now see a large amount of time being spent in over 66,000 calls to builtins.isinstance();  The problem is I can't find the source code to implement a stack trace to find out what's calling isinstance().  (I am guessing, based on my limited knowledge of Python, that isinstance is actually C code that is either directly, or via shared object, linked into the Python interpreter).  At any rate, I can't find what is calling is isinstance.  I tried the Gprof2dot method also found among the answers of Profiling in Python: Who called the function? but that only shows me that isinstance() is being called by is_dtype() and the call graph stops there (at is_dtype).
Any ideas?
Answer: I've done some digging, and will attempt, at least partially, to answer my question (in the hopes that others will see and contribute additional ideas on how to make this easier).
So here's how I profile my function
pr = cProfile.Profile()                # create a cProfiler object
pr.enable()                            # turn profiling on
pr.runcall( myfunc, arg1, arg2, ... )  # profile my function
pr.disable()                           # turn profiling off

Then, here is the key to finding callers:
import pstats
p = pstats.Stats(pr)           # create pstats obj based on profiler above.
p.print_callers('isinstance')  # find all the callers of isinstance.

The print_callers function prints out 130 callers of isinstance, along with how many times each caller calls isinstance.  That's a lot to digest, but for profiling purposes it makes sense to focus on the handful that call the most, and find their callers.  Here is part of the list (which print_callers presents in more-or-less random order, but I have sorted them here based on the number of calls) ...
Function {built-in method builtins.isinstance} was called by...
                                           ncalls  tottime  cumtime
                                             2808    0.002    0.002  /anaconda3/lib/python3.7/site-packages/pandas/core/indexes/datetimes.py:974(get_loc)
                                             2158    0.006    0.018 /anaconda3/lib/python3.7/site-packages/pandas/core/dtypes/base.py:75(is_dtype)
                                             2030    0.001    0.001  /anaconda3/lib/python3.7/site-packages/pandas/core/dtypes/common.py:1845(_is_dtype_type)
                                             1930    0.001    0.001  /anaconda3/lib/python3.7/site-packages/pandas/core/dtypes/common.py:1981(pandas_dtype)
                                             1440    0.001    0.001  /anaconda3/lib/python3.7/site-packages/pandas/core/dtypes/dtypes.py:68(find)
                                             1058    0.001    0.001  /anaconda3/lib/python3.7/site-packages/pandas/core/indexes/datetimes.py:924(get_value)
                                              841    0.000    0.000  /anaconda3/lib/python3.7/site-packages/pandas/core/dtypes/common.py:1809(_get_dtype)
                                              726    0.000    0.000  /anaconda3/lib/python3.7/site-packages/pandas/core/dtypes/common.py:1702(is_extension_arr
...
                                                6    0.000    0.000  /anaconda3/lib/python3.7/site-packages/pandas/core/indexing.py:153(_get_setitem_indexer)
                                                5    0.000    0.000  /anaconda3/lib/python3.7/site-packages/pandas/core/ops.py:1660(wrapper)
                                                5    0.000    0.000  /anaconda3/lib/python3.7/site-packages/pandas/core/ops.py:1447(_align_method_SERIES)
                                                5    0.000    0.000 /anaconda3/lib/python3.7/site-packages/pandas/core/computation/expressions.py:163(_has_bool_dtype)
                                                4    0.000    0.000 /anaconda3/lib/python3.7/site-packages/pandas/core/internals/blocks.py:3100(_extend_blocks)
                                                4    0.000    0.000  /anaconda3/lib/python3.7/site-packages/pandas/core/indexing.py:2501(check_setitem_lengths)
                                                3    0.000    0.000  /anaconda3/lib/python3.7/site-packages/pandas/core/indexes/base.py:566(_shallow_copy)
                                                3    0.000    0.000  /anaconda3/lib/python3.7/site-packages/pandas/core/dtypes/common.py:702(is_datetimelike)
                                                3    0.000    0.000  /anaconda3/lib/python3.7/posixpath.py:41(_get_sep)
                                                2    0.000    0.000  /anaconda3/lib/python3.7/distutils/version.py:331(_cmp)

At this point, I suppose I could tediously go through the biggest callers (find their biggest callers, and so on) or write a script to do it.  Will continue digging and post later additional progress.

find caller of python builtins


Call to undefined function variable_get()

Question: I have an ansible script that transfers a production database to my devel server, then runs a few Drush commands to prepare it (e.g. updating the filesystem settings, clearing the cache).
A more complex task is updating a nested configuration value like the following one.
mail_system:
  default-system: SmtpMailSystem
  maillog: MaillogMailSystem

Supposedly I ought to be able to do this with drush ev (aka php-eval) and variable_get() and variable_set() as with drush7 ev '$v = variable_get("file_public_path")', but I get this error message.

Error: Call to undefined function variable_get() in /usr/local/bin/drush7.4.0/commands/core/core.drush.inc(1122): eval()'d code, line 1

It does work correctly when I use the interactive shell.
drush7 core-cli
self> variable_get('mail_system');
array:2 [
  "default-system" => "SmtpMailSystem"
  "maillog" => "MaillogMailSystem"
]

I can work-around it by reading the content of $conf easily enough.
drush7 ev 'global $conf; echo $conf["mail_system"]["default-system"];'

Writing involves a database query and clearly variable_set() is in core.
Why cannot I use variable_get() and variable_set()?
I am using Drush 7.4.0 and Drupal 7.59.
(I also have Drush 8.1.16 available, but that's much use for this, Drush 8's cget and cset require Drupal 8, and Drush 8 doesn't have Drush 7's vget and vset.)
Comment: FWIW I just wrote a custom Drush command to do exactly what I wanted, this answer: https://drupal.stackexchange.com/questions/181848/custom-drush-command-not-working was useful for getting that working.
Answer: It seems you are confusing Drush 8 and 9 - Drush 8 has vget and vset.
Using Drush 8, the following two commands worked:
drush vget "mail_system"

drush ev 'print_r(variable_get("mail_system"));'

PS! Drush 7 isn't supported and you should use Drush 8 (currently 8.1.17) for Drupal 7.


KnockoutJs : ko.mapping.fromJS and binding => how to do it properly?

Question: I really am struggling with something that I thought was simple...
I am making a simple search-result table based on $.getJSON call, and want to keep my code as "generic" as possible.
In my (simplified) HTML :
<form id="searchForm">
(...)
    <button type="button" onclick="search()">Search</button>
</form>

(...)

(...)

Then in my javascript (in script tags lower in the page):
var search = function(){
    var form = $('#searchForm');
    $.getJSON("php/query/jsonQuery.php?jsonQuery=search", form.serialize(), function(jsonAnswer, textStatus) {
        console.log(jsonAnswer);
        if(typeof viewModel === 'undefined'){
            var viewModel = ko.mapping.fromJS(jsonAnswer);
            ko.applyBindings(viewModel);
        }
        else{
            ko.mapping.fromJS(jsonAnswer, viewModel);
        }
        $('#divResults').show();
//         console.log(viewModel)
    });
}

This works fine on the first "search" click... but not the following : Error You cannot apply bindings multiple times to the same element.
As you can guess, this very ugly "if" testing viewModel is a desperate attempt to get rid of that error.
I've tried many things but I just can't figure out how to do it properly...
I've read this Knockout JS update view from json model and this KnockoutJs v2.3.0 : Error You cannot apply bindings multiple times to the same element but it didn't help me much... maybe because the search() function isn't called on load (and indeed shouldn't be).
Any KO master to give me a clue? Thanks in advance for your help!
Answer: This is how I would be approaching what you are trying to accomplish.

var searchService = {
  search: function(form, vmData) {
    //$.getJSON("php/query/jsonQuery.php?jsonQuery=search", form.serialize(), function(jsonAnswer, textStatus) {
      var jsonAnswer = [{
        FOO: "Item 1 Foo",
        BAR: "Item 1 Bar"
      }, {
        FOO: "Item 2 Foo",
        BAR: "Item 2 Bar"
      }]
      ko.mapping.fromJS(jsonAnswer, [], vmData);
      //})
    }
};

var PageViewModel = function() {
  var self = this;
  self.data = ko.observableArray();
  self.hasResults = ko.pureComputed(function() {
    return self.data().length > 0;
  });

  self.search = function() {
    var form = $('#searchForm');
    searchService.search(form, self.data);
  };
};

ko.applyBindings(new PageViewModel());
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.0/css/bootstrap.min.css" rel="stylesheet"/>

<form id="searchForm">
  <button type="button" data-bind="click:search">Search</button>
</form>

No Results

        FOO
        BAR

Comment: THAT was incredibly helpfull and clear!
I had to adapt some tweaks, but I couldn't imagine a better answer. Thanks a LOT!


I fail to see how plotting these points help to conclude the lines are parallel

Question: Final question
I guessed "there is no line" and the test told me the answer is "the lines are parallel to the x-axis."
Comment: I think it's a poorly made question, whose intentions are not clear. I can't argue that it is "wrong," though.
Comment: I'm not sure what the ordered pairs are for, but I see a bunch of lines in the plot, that are parallel with the x-axis.
Comment: The problem would make more sense to me if "lines" were not plural in the proposed answer. Seems pretty poorly written.
Comment: Sure, But, maybe this is "ticky tack," but strictly speaking those are line segments and not lines.  And yeah, what do the ordered pairs have to do with anything?  The question implies plotting the ordered pairs leads to the answer.
Comment: Thanks for the comments.  Another thing about the "lines."  There is no way to tell for sure that they are parallel.  Yes they do look parallel.  But they don't have to be.
Answer: Since it is assumed that the points are plotted on a graph, it is implicit that the graph is a line and it is parallel to the x-axis, which in this case it is the x-axis.
Comment: Lines are obviously parallel to the x-axis but I do not see the relevance to the ordered pairs. May be the ordered pairs are there to show us which line is the x-axis.
Comment: Not sure I agree with that "implicit" part.  But the answer says lines, plural.  Apparently referring to the other, apparently parallel, lines shown.
Comment: @MohammadRiazi-Kermani: Aha! I think you've figured out what the question meant. The plotted points let you identify which axis is the $x$-axis.


How to prove there exists a function $h : A → B$ such that $g ◦ h = f$.

Question: Let $A = \{1, 2, 3\}, B = \{4, 5, 6\}, C = \{7, 8, 9, 10\}$.
Define the functions $f : A → C$ and   $g : B → C$ by $f(1) = 7$, $f(2) = 9$, $f(3) = 7$, $g(4) = 10$, $g(5) = 7$, $g(6) = 9$.
I'm approaching this by proving the domains and codomains equal for the functions $g o k$ and f but I'm never sure whether my proof is actually sound.
$f(1) = 7 = g(h(1))$. There exists a $b \in B$ such that $g(b) = 7$, which is 5, so $h(1) = 5$.
I repeated this for the rest of the elements in set $A$. In my eyes, I think that I showed each element in set $A$ maps to the same output for both functions but I'm not sure if this is right or if this alone is even sufficient to prove the function $h$ such that $g ◦ h = f$ exists.
I appreciate any criticism and help. Thanks
Comment: Yes, this is exactly the process you are supposed to go through.  You can think of it as a game of "connect the dots."  If it seems too easy or too trivial, that's because it is and it is just being asked of you here to make sure you are paying attention and understand the words being used.
Comment: Since the sets in question are finite, it may help to draw a diagram and draw arrows. The goal is to find for each $a \in A$ a $b \in B$ such that $f(a) = g(b)$, in which case you can define $h(a) = b$.
Answer: First of all, look where $f$ sends 1, 2 and 3. Since $f(1)=7=f(3)$, we need to have $h(1)$ and $h(3)$ be such $b\in B$ that $g(b)=7$. Such a $b$ exists, namely $b=5$. Then we have $f(2)=9$, so $h(2)$ must be such that $g$ sends it to $9$. This gives us $h(2)=6$. Combining these, we have a function $h\colon\{1, 2, 3\}\to\{4, 5, 6\}$ given by $h(1)=7, h(2)=9, h(3)=7$.
Comment: You're welcome! :) The image is just {5, 6}, so the codomain of h could be any set containing those two. Specifying it to be {4, 5, 6} lets us compose it with g whereas {5, 6} or {5, 6, 11} etc. wouldn't! But the essential part is just to find an element for each of the 1, 2 and 3 to get a function h mapping into {4, 5, 6}.
Comment: Yes makes sense, do you think saying h:{1,2,3}→{4,5,6} is necessary to show it's a function? Or is proving the domains and codomains are defined and equal each other enough? Thanks for the answer anyways!


$x_n - x_{n-2} \to 0$, how to prove that the limit of $(x_n - x_{n-1})/n$ is zero?

Question: A sequence of real number $\langle x_n \rangle_{n \in \mathbb N_+}$ satisfies that $\lim_{n \to \infty} (x_n - x_{n-2}) = 0$.
Please prove that
$$
    \lim_{n \to \infty} \frac{x_n - x_{n-1}}{n} = 0.
$$
I tried to use O. Stolz's theorem so that
$$
    \lim_{n \to \infty} \frac{x_n - x_{n-1}}{n} = \lim_{n \to \infty} (x_{n+1} - 2x_n + x_{n-1}),
$$
but I failed to find the way to utilize the condition that $x_n - x_{n-2} \to 0$.
Comment: @Alan I don't think that's going to be true in general, for example if $x_n = (-1)^n \log n$.
Comment: I think if you apply the Cesaro-Stolz theorem to the Cesaro sum of $x_{2n} - x_{2n-2}$ you should get $\frac{x_{2n}}{n} \to 0$ and similarly $\frac{x_{2n-1}}{n} \to 0$.
Comment: @abiessu did you forget about the division by $n?$ Hard to tell, since you chose $x$ as your variable.
Comment: Hint:  Show that the sequence $x_{2n}$ converges to a number and the sequence $x_{2n+1}$ also converges to a (posssibly different) number.
Comment: Woops, forgot they could both grow slower and slower.  Would need to be modified.  And @ThomasAndrews why wouldn't that converge when divided by $n$?
Comment: Oh, yeah, forgot the division by $n.$ Deleting.
Comment: @thomasandrews yep, that's a solid reason for my example to not work as intended.
Answer: Let $M_N=\sup\{|x_{n}-x_{n-2}|:n>2N\}$.
Then
$$ |x_{2k}-x_{2N}|\le M_N(k-N)<M_Nk$$
and
$$ |x_{2k-1}-x_{2N-1}|\le M_N(k-N)<M_Nk$$
for $k>N$, thus for $n=2k$ making for
$$\left|\frac{x_{n}-x_{n-1}}{n}\right|\le\frac{M_Nk+M_Nk+|x_{2N}-x_{2N-1}|}{n} $$
and similarly for odd $n$. As the right hand side $\to M_N$ and we can make $M_N$ small by making $N$ big, the claim follows.
Answer: If $a_i\to L$ then: $$b_n=\frac{1}{n}\sum_{i=1}^n a_i$$ converges to $L,$ too. (This is a common result. It is the first application of the Stolz-Cesàro theorem at Wikipedia, but it is also a common exercise in analysis.)
Let $a_n=x_{2n+2}-x_{2n}.$ Then $a_n\to 0.$ Here, $$b_n=\frac{x_{2n+2}-x_{2}}{n}\to 0$$ But since $\frac{x_{2}}n\to 0,$ this means $\frac{x_{2n+2}}{n}\to0.$
Similarly, from $a_n'=x_{2n+1}-x_{2n-1},$ you get $\frac{x_{2n+1}}n\to 0.$
Comment: Thank you for your answer! I would like to add a note: if $z_{2k}$ and $z_{2k+1}$ has a same limit $a$, then $z_n$ must converge to the same limit too. $\forall \varepsilon \in \mathbb R_+$, we can find $N_1$ for $z_{2k}$ and $N_2$ for $2k+1$ such that $\forall k > \max\{N_1, N_2\}$ ($n > \max\{2N_1, 2N_2+1\}$), $|z_n - a| < \varepsilon$.


Migrating only articles with a specific taxonomy term

Question: In the source D7, i have a content type 'article' containing a reference to a 'category' taxonomy vocabulary term.
In the target D8, I have a content type 'article' as well, but i only want to import those nodes whose 'category' reference does not equal 'interview' ('interview' is one of its terms).
Also, in the target D8, i have a content type 'interview' to which i want to import all D7's 'article' nodes whose 'category' reference equals 'interview'.
Any ideas how to condition this?
Comment: You can implement a process plugin and set it on that field. Process plugins can throw a https://api.drupal.org/api/drupal/core%21modules%21migrate%21src%21Plugin%21migrate%21process%21StaticMap.php/class/StaticMap, in which case the record is skipped and not imported. either implement one that is configurable or two different ones that skip all the records that you don't want. You might also be able to use a map plugin and map the ids that you do want to migrate, skipping those that you don't. See
Answer: Besides setting up a process plugin for the migrate import mapping (via code) as suggested by Berdir in the comments, another option is to setup a views data export on the legacy site to output only the select articles or "interviews".
This approach also allows non-database admins or developers to easily audit the content being migrated (because you can setup an alternative view display as a webpage, or excel spreadsheet, for use as a checklist).
To setup a view in JSON format:

install the Views Data Export module
install one of the add-on modules for JSON, such as Services Views or Views Data Source.

Refer to this StackOverflow answer/post about setting up a JSON view display mode.


did not receive a response from an authoritative server

Question: I'm using docx4j-3.3.1 library and running this project  Here's a link  but it show me error like this
<code>
Looks like your endpoint URL 'http://converter-eval.plutext.com:80/v1/00000000-0000-0000-0000-000000000000/convert' is wrong
Something went wrong...
main.java.com.plutext.converter.ConversionException: This is usually a temporary error during hostname resolution and means that the local server did not receive a response from an authoritative server
    at main.java.com.plutext.converter.ConverterHttp.execute(ConverterHttp.java:194)
    at main.java.com.plutext.converter.ConverterHttp.convert(ConverterHttp.java:76)
    at sample.java.Sample.main(Sample.java:66)
Caused by: java.net.UnknownHostException: This is usually a temporary error during hostname resolution and means that the local server did not receive a response from an authoritative server
    at java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method)
    at java.net.InetAddress$2.lookupAllHostAddr(InetAddress.java:928)
    at java.net.InetAddress.getAddressesFromNameService(InetAddress.java:1323)
    at java.net.InetAddress.getAllByName0(InetAddress.java:1276)
    at java.net.InetAddress.getAllByName(InetAddress.java:1192)
    at java.net.InetAddress.getAllByName(InetAddress.java:1126)
    at org.apache.http.impl.conn.SystemDefaultDnsResolver.resolve(SystemDefaultDnsResolver.java:45)
    at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:111)
    at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:353)
    at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:380)
    at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:236)
    at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:184)
    at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:88)
    at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:107)
    at main.java.com.plutext.converter.ConverterHttp.execute(ConverterHttp.java:184)
</code>
Thanks in advance
Answer: As it says:
<code>    java.net.UnknownHostException: This is usually a temporary error during
    hostname resolution and means that the local server did not receive a
    response from an authoritative server
    at java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method)
</code>
Comment: but we are getting this error frequently, is there any option to increase the time out to avoid such error always?


"Call to undefined function fivestar_widget_form()" error

Question: I am getting the following error - it's related to the fivestar module. As far as I can tell, it is using an obsolete function call (used in Drupal 6)
Fatal error: Call to undefined function fivestar_widget_form() in /home/SITENAME/public_html/sites/all/modules/contrib/views_php/plugins/views/views_php_handler_field.inc(202) : runtime-created function on line 5

The problem is that I've looked at all references to the widget in the template files, tried to change them.
I've tried the following, as said here, but I keep getting the error.
print render(fivestar_widget_form($node));
print render($content['field_vote']);
print drupal_render($content['field_vote']);
print drupal_render(fivestar_widget_form($node));

What could be causing the error?
Answer: There's no function called fivestar_widget_form() in the Drupal 7 version of Fivestar (I've just grepped the module folder).
It's likely that function is a CCK hook remnant, CCK having been incorporated into the core Field module in Drupal 7, and all of it's functions renamed.
As far as I know there's no easy way in Drupal 7 to use a field widget form as a stand-alone form so you might have to look for another way around this problem.
Answer: This might help if you still need it - I was just running into the same issue, banging my head against the wall until I finally found the solution (for me). For some reason, the Fivestar field had gotten set to hidden under full content in "Manage Display" for my content type. I'm pretty sure it defaulted to this, even though the "Default" display did not have it hidden. When I changed it to display "As Stars", I could use
print render($content['field_vote']);

in my node--*.tpl.php file.
Comment: The OP is asking why he gets an error about a not existing function.
Comment: Right, so my answer may not be the correct answer to his stated question. But, I found this original post when I was searching for that error, and it appeared I had tried similar things as the OP, so thought I would share how my situation was resolved in case it's helpful for others out there.


Need help performing the taylor series expansion for below-mentioned expression in square brackets

Question: The Taylor series expansion result, limited to the first order term, for the expression
$$\left[1-\left(1+\frac{1}{y}\right)^\frac{1}{2}\right] = \left(\frac{1}{2y}\right)$$
Then right hand side is the result. Can someone show me the step/s, I do not know how to do this.
Thank you.
Comment: Can you please describe in more detail the trouble you are having? What did you try to do? Click "Edit" above rather than elaborating in the comments, thanks.
Comment: The first step is to find the Taylor series for $(1+(1/y))^{1/2}$. Do you know how to do that?
Comment: Hint: the expression  $\sqrt{1 + \frac{1}{y}}$ can be simplified to  $\sqrt{\frac{y + 1}{y}}$ then express it as the reciprocal of the reciprocal which should be $\sqrt{\frac{1}{\frac{1}{\frac{y + 1}{y}}}}$. Now consider the taylor series of $\frac{1}{y + 1}.$
Comment: No, I do not know exactly how to do that. I obtained the first derivative, I believe, I only need that. After that I am not clear how to proceed.
Comment: OK, you found the first derivative. Then do you know how to use it to find the beginning of the Taylor series?
Answer: Everyone seems to have overlooked that in a Taylor series, the variable appears in the numerator, not the denominator. What you have is not the Taylor series of the function with respect to $y$, but instead with respect to $\frac 1y$.
That is, if you let $x = \frac 1y$, the function becomes $$f(x) = 1-\sqrt{1+x}$$ The Taylor series for this function begins with
$$f(x) = 0 - \frac12 x + \frac 18x^2 + \dots$$
Dropping the higher order terms and substituting $\frac 1y$ for $x$, we get
$$f\left(\frac 1y\right) \approx -\frac 1{2y}$$
Which is the result you should be after. The negation is correct, your version is not. For positive $y$, the function has a negative value.
Comment: Thank you very much for showing the steps to the answer. This is what I was looking for.


Como posicionar elementos html com css

Question: Tenho dificuldade em posicionar controles, do tipo: Tenho um TextArea e gostaria de colocar um label ao lado dele, ao lado da parte inferior direita e abaixo do label, um controle SELECT.
Bem eu tenho conseguido, mas tipo assim, dando top e left com valores numéricos, o que eu não gosto muito, devido as inconsistências dos browsers. Há uma forma mais prática, mais confiável de se posicionar sem ter que estar fixando numericamente o controle?
Coloquei uma imagem e essa imagem está ligeiramente abaixo do label, isso faz com que eu tenha um espaço a mais entre um e outro. Veja o código completo abaixo.
<form class="form-horizontal" role="form">

        CNPJ:

          <input type="text" class="form-control" id="txtCnpj" placeholder="Digite o Cnpj">

          Status:

        Razão Social:

          <input type="text" class="form-control" id="txtRazaoSocial" placeholder="Digite a razão social">

        ID Evento:

          <input type="text" class="form-control" id="txtIdEvento" placeholder="Digite um evento">

   </form>

Answer: Use um sistema de grids, como o Twitter Bootstrap. Segue exemplo de formulário com uso do sistema de grids do mesmo:
<form class="form-horizontal" role="form">

    Email

      <input type="email" class="form-control" id="inputEmail3" placeholder="Email">

    Password

      <input type="password" class="form-control" id="inputPassword3" placeholder="Password">

          <input type="checkbox"> Remember me

      <button type="submit" class="btn btn-default">Sign in</button>

</form>

Comment: Então, mas como eu faço com o CSS nesse caso?
Comment: Preciso instalar o bootstrap? Fui rodar esse exemplo, e até aí ok, agora o difícil será como posicionar um TextArea e ao lado dele na parte inferior direita, posicionar mais controles.
Comment: Você precisa estudar o esquema de grids do Bootstrap para saber como usar corretamente. Perca uns 3 dias de trabalho e se dedique a isso, o ganho posterior de produtividade será compensador.
Comment: O Bootstrap é uma biblioteca CSS, basta usá-la! Eles têm links de CDN no site
Comment: Estou começando a usar. Só estou com dificuldade é de colocar um controle ao lado do outro e não consegui colocar o label em cima e o textbox logo abaixo. Mas preciso ler mais, três dias em 4 horas, é meu tempo.
Answer: Sem o uso de framework e sem fixar numericamente o conteúdo, seria interessante limitar o seu conteúdo do formulário dentro de uma div, e posicioná-los com um determinado padding, usando o posicionamento flutuante:
float: left; //left/center/right

Como posicionar elementos html com css


Capturing only Incoming call in Android

Question: I am creating an app and need to capture the Incoming calls only. I am using BroadCast class and Phone Listener class for this and in the PhoneListnere class capturing whether there is incoming call or not. My problem is that i do not want my app to get trigerred if there is any outgoing call. My broadcast class gets trigger even if there is any outgoing call (though i am neatly exiting the app for the outgoing calls) but not liking the idea that the app is actually getting trigerred. Is there any specific Intent just to handle the Incoming calls?
Answer: You can use the ACTION_PHONE_STATE_CHANGED intent, and store the last state. If the current state is TelephonyManager.EXTRA_STATE_OFFHOOK, a call exists that is dialing, active or on hold. If the previous state was RINGING then this is an incoming call. If the previous state was IDLE, then this is an outgoing call.
The following receiver distinguishes different scenarios:
public void onReceive(Context context, Intent intent) {
    String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
    if(state.equals(TelephonyManager.EXTRA_STATE_RINGING)){
        // Device call state: Ringing. A new call arrived and is ringing or waiting. In the latter case, another call is already active.
        String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
    }else if(state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK){
        // Device call state: Off-hook. At least one call exists that is dialing, active, or on hold, and no calls are ringing or waiting.
        if(lastState.equals(TelephonyManager.EXTRA_STATE_IDLE){
            // outgoing call
        } else if(lastState.equals(TelephonyManager.EXTRA_STATE_RINGING){
            // incoming call
        }
    }else if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)){
        // Device call state: No activity.
    }
    lastState = state;
}

Comment: yes got your point but seems there is no solution (atleast i couldn't figure out) for handling incoming calls. If there is any outgoing call the app gets triggered (i understand and thanks) that you (Jeff) has provided a solution for it.
Comment:

.....This is my manifest and i am using intent which you mentioned but this gets triggered even if you make an outgoing call. The android site also says that it detects the change in the phone state. My intention is that my app shouldn't be trigerred if there is any outgoing call.
Comment: Hm, this seems to be triggered for outgoing calls as well indeed. What you can do is also register a receiver for the `android.intent.action.NEW_OUTGOING_CALL` intent. When that happens, store some kind of variable. In the onReceive() of the `ACTION_PHONE_STATE_CHANGED` intent you can then check if the outgoing happened shortly before or not.
Comment: Update: another solution that seems to work is to set the last state in onReceive(); I updated my answer with that code.

Capturing only Incoming call in Android


Get specific chars from a string in python

Question: I want to make a new string from an internal part of an old string, and when I know the length of the string I know I can do this:
newString = oldString[6:145]

This exludes the first and last chars from the old string when writing the newString. But is there a way to do this if i dont know the length of the string, like:
newString = oldString[6:len(oldString)-6]

Thanks.
Answer: Is this what you are looking for?
newString = oldString[6:-6]


Unconventional way to solve trig question

Question: I was working on a trig question and got stuck, but then I noticed a possible way to solve the problem. However, this way seemed to be slightly unconventional and possibly not what the book was looking for.
The question was: "Find $k$ and $b$ when $\sqrt3 \sin x + \cos x=k\sin(x+b)$"
The first thing I did was to expand $k\sin(x+b)$ to $k\sin x\cos b+k\cos x\sin b$.
Here is where I got stuck. I tried several different things, but I hit dead ends. Then I tried to equate coefficients and got $k\cos b=\sqrt3$ and $k\sin b=1$ which simplified to:
$\cos b=\displaystyle{\sqrt3 \over k}$ and $\sin b=\displaystyle{1\over k}$. The answer from there is fairly simple to get which is $k=2$ and $b=\displaystyle{\pi\over6}$.
However this method seems rather dubious and so I was wondering if someone new a better way of solving the problem using more rigorous mathematical methods.
Comment: Equating coefficients works here, but can be avoided by looking at the cases $x=0$ and $x=\pi/2$ and checking the final result.
Comment: What makes it seem like a guessing game?  Also, I believe you missed a solution.
Comment: $k^2=4$ has two solutions.
Comment: Good point. I just thought that using that method might not work all the, but I guess it might.
Answer: It's not at all dubious. The functions sin and cos are linearly independent and so $a_1 \sin x + b_1 \cos x = a_2 \sin x + b_2 \cos x$ for all $x$ iff $a_1=a_2$ and $b_1=b_2$.
To see that sin and cos are linearly independent, take $a \sin x + b \cos x = 0$ and set $x=0$ to get $b=0$ and $x=\pi/2$ to get $a=0$.
Comment: This appears to be the only answer that explains why the OP's method is valid.  +1
Comment: @Graphth, Henry's comment was also about this I think.
Comment: what about the case where $x=\pi /3$
Answer: I'm not sure how it's perceived as dubious. If you have $k \cos b = \sqrt{3}$ and $k \sin b = 1$, then you must $\frac{k \sin b}{k \cos b} = \tan b = \frac{1}{\sqrt{3}}$, which gets you $b = \frac{\pi}{6}$ or $\frac{7\pi}{6}$. From there it immediately follows that $k = 2$ or $-2$, respectively.
Answer: If you have $k\cos b=\sqrt{3}$ and $k\sin b=1$, you should also remember that $k^2\cos^2 b+ k^2\sin^2 b= k^2$.  That means $\sqrt{3}^2 + 1^2 = k^2$, so $k=\pm 2$.  If you take $k=2$, you can find a suitable value of $b$, and with $k=-2$, you can find another.
Answer: Suppose that $a\sin(x)+b\cos(x)=c\sin(x)+d\cos(x)$ holds for all $x$ in some neighborhood of $x_0$. Then we have the following equation and its derivative:
$$
\begin{align}
0&=(a-c)\sin(x_0)+(b-d)\cos(x_0)\tag{1}\\
0&=(a-c)\cos(x_0)-(b-d)\sin(x_0)\tag{2}
\end{align}
$$
Adding the squares of $(1)$ and $(2)$ gives
$$
0=(a-c)^2+(b-d)^2\tag{3}
$$
Thus, $a=c$ and $b=d$.
So if we have
$$
\begin{align}
\sqrt{3}\sin(x)+\cos(x)
&=k\sin(x+b)\\
&=k\cos(b)\sin(x)+k\sin(b)\cos(x)\tag{4}
\end{align}
$$
for all $x$ in some neighborhood of $x_0$, then we must have
$$
k\cos(b)=\sqrt{3}\quad\text{ and }\quad k\sin(b)=1\tag{5}
$$
and $(5)$ was solved above.
Answer: Here is what I come up in my mind, maybe this is an unconventional way too: Divide both sides by $2$, we get
$$\frac{\sqrt3}{2} \sin x +\frac{1}{2}\cos x=\frac{k}{2}\sin(x+b).$$
Note that $\displaystyle\sin(\frac{\pi}{6})=\frac{1}{2}$ and $\displaystyle\cos(\frac{\pi}{6})=\frac{\sqrt{3}}{2}$, the left hand side is given by
$$\cos(\frac{\pi}{6})\sin x +\sin(\frac{\pi}{6})\cos x=\sin(x+\frac{\pi}{6}),$$
where the last equality follows from compound angle forumula. Combining these, we have
$$\sin(x+\frac{\pi}{6})=\frac{k}{2}\sin(x+b).$$
Answer: Here is a standard trick to deal with expressions of the type $A \sin(x) + \cos(x)$:
Let $u$ be so that $\cot(u) =A$.
Then, after bringing everything to the same denominator, your expression becomes
$$A \sin(x) + \cos(x)= A\frac{\cos(u) \sin(x)+\sin(u)\cos(x)}{ \sin(u)} =\frac{ \sin(x+u)}{\sin(u) }$$
If you look over the other answers, this is exactly what they did, in a non-explicit way.
Remark If instead you use $\tan(v)=A$, you end up with
$$A \sin(x) + \cos(x) = \frac{\cos(x-v)}{\cos(v)} \,.$$
Same substitutions also solve the expressions of the type $\sin(x) + B\cos(x)$.
Answer: In general,
$$\begin{align*}
\alpha \sin(x) + \beta \cos(x)
&= \sqrt{\alpha^2+\beta^2}\left(\frac{\alpha}{\sqrt{\alpha^2+\beta^2}}\sin(x)
+ \frac{\beta}{\sqrt{\alpha^2+\beta^2}}\cos(x)\right)\\
&= \sqrt{\alpha^2+\beta^2}\left(\cos(y)\sin(x) + \sin(y)\cos(x)\right)\\
&= \sqrt{\alpha^2+\beta^2}\sin(x+y)
\end{align*}$$
where $y$ is the angle whose cosine is $\dfrac{\alpha}{\sqrt{\alpha^2+\beta^2}}$
and whose sine is $\dfrac{\beta}{\sqrt{\alpha^2+\beta^2}}$.  In your problem,
$\alpha = \sqrt{3}, \beta = 1$, which readily gives $k = 2$,  $b = \frac{\pi}{6}$.
As others have pointed out, this misses one of the two solutions.
If $\sqrt{\alpha^2+\beta^2}$ (which conventionally means the positive square root) is replaced throughout  by $({\alpha^2+\beta^2})^{1/2}$, we get the other
solution $k = -2, b = \frac{7\pi}{6}$ upon choosing
$({\alpha^2+\beta^2})^{1/2} = -2$.


Find the differential equation concerned with the problem?

Question: A body of mass $m$ falls under gravity and is retarded by a force proportional
to its velocity. Write down the differential equation satisfied by the
velocity $v(t)$ at time $t$.
Answer- $\frac{dv}{dt} = g-cv^2$ for some constant $c$
We have $$F = ma = m \frac{dv(t)}{dt} = mg- c v(t)$$ Where i am wrong?
Comment: Divide both sides by $m$ and absorb it into the constant $c$.
Answer: Your derivation is correct, indeed for a resistive force proportional to $v$, dividing by m your expression, we have
$$\frac{dv(t)}{dt} = g- \bar c v(t)$$
What is true is that the drag force for an object falling in the air is usually assumed proportional to $v^2$ but in general it depends upon the parameters for the motion (i.e. dimension of the object, viscosity of the fluid, speed, etc.) and in some context the assumption of proportionality to $v$ is true.
Answer: You just consider a quadratic drag, which follows from Bernoulli theorem, $$F(v)=-\frac{AC_{d}\varrho}{2}v^{2}$$
So the equation is
$$mv'=mg-\frac{AC_{d}\varrho}{2}v^{2}$$
By setting $c=\frac{AC_{d}\varrho}{2m}$ we obtain
$$v'=g-cv^{2}$$
Which is separable and the solution is
$$v(t)=\sqrt{\frac{g}{c}}\tanh(\sqrt{cg}(t-t_{0})+c_{1})$$
Where $c_{1}=\tanh^{-1}\sqrt{\frac{c}{g}}v(0)$


Showing $ \frac{2^j(2k-j)!}{(k-j)!}=\sum_{l=j}^k\frac{2^ll(2k-l-1)!}{(k-l)!} $

Question: For any given $j,k\in\mathbb{N}$, with $j\leq k$, how is it possible to prove the following equivalence?
$$
\frac{2^j(2k-j)!}{(k-j)!}=\sum_{l=j}^k\frac{2^ll(2k-l-1)!}{(k-l)!}
$$
My attempt is:
$$
\frac{2^j(2k-j)!}{(k-j)!}=\sum_{l=j}^k\frac{2^ll(2k-l-1)!}{(k-l)!}\\
2^j\binom{2k-j}{k-j}k!=\sum_{l=j}^k\binom{2k-l-1}{k-l}l2^l(k-1)!\\\binom{2k-j}{k-j}k=\sum_{l=j}^kl2^{l-j} \binom{2k-l-1}{k-l}
$$
and then I don't know how to continue. Maybe there is some binomial formula for this sum, but I don't know.
Comment: [This](https://math.stackexchange.com/questions/3508257) is very close.
Comment: Yes, I see thank you! But I can't apply it to my situation.
Comment: You can !! Just use ${n}\choose{r}$ = ${n}\choose{n-r}$ to reach the linked question
Comment: But that sum start at k=1 and mine at l=j
Comment: And $\displaystyle\sum_{l = 1}^k = \sum_{l = 1}^{j-1} + \sum_{l = j}^k$; the $\displaystyle \sum_{l = 1}^{j-1}$ is the linked question with a different $k$. To relate the two sums will probably take some work, but seems doable.
Comment: @JakobStreipel You mean the sum from 1 to k is related to the linked question right? Because for the sum ending at j-1 how could apply the linked question?
Comment: Is there a way to prove it by induction? Even if I have two parameters j and k.
Comment: @Brino this is direct by induction on $j$. Base case $j=k$, for the induction step, go from $j$ to $j-1$. I can post a full answer later if you haven't figured it out
Comment: Yes, please. It would be very helpful
Comment: @Brino in fact the linked question is a special case of this one, I believe there may be a generating functions approach too.
Answer: Here is a generating function approach that generalises @MarkoRiedel's answer to this problem. We use the coefficient of operator $[z^n]$ to denote the coefficient of $z^n$ of a series. This way we can write for instance
\begin{align*}
[z^k](1+z)^n = \binom{n}{k}\tag{1}
\end{align*}
We show the following identity is valid
\begin{align*}
\color{blue}{\sum_{l=j}^k\binom{2k-l-1}{k-l}l\,2^{l-j}=k\binom{2k-j}{k-j}}\tag{2}
\end{align*}

We obtain
\begin{align*}
\color{blue}{\sum_{l=j}^k}&\color{blue}{\binom{2k-l-1}{k-l}l\,2^{l-j}}\\
&=\sum_{l=j}^k[z^{k-l}](1+z)^{2k-l-1}l\,2^{l-j}\tag{3}\\
&=[z^k](1+z)^{2k-1}\sum_{l=j}^\infty\left(\frac{z}{1+z}\right)^ll\,2^{l-j}\tag{4}\\
&=[z^k](1+z)^{2k-1}\sum_{l=0}^\infty\left(\frac{z}{1+z}\right)^{l+j}(l+j)2^l\tag{5}\\
&=[z^{k-j}](1+z)^{2k-j-1}\sum_{l=0}^{\infty}\left(\frac{2z}{1+z}\right)^l(l+j)\\
&=[z^{k-j}](1+z)^{2k-j-1}\left(\frac{2z(1+z)}{(1-z)^2}+j\frac{1+z}{1-z}\right)\tag{6}\\
&=2[z^{k-j}](1+z)^{2k-j}\frac{z}{(1-z)^2}+j[z^{k-j}](1+z)^{2k-j}\frac{1}{1-z}\\
&=2\sum_{m=0}^{k-j}\binom{2k-j}{m}(k-j-m)+j\sum_{m=0}^{k-j}\binom{2k-j}{m}\tag{7}\\
&=\sum_{m=0}^{k-j}\binom{2k-j}{2k-j-m}(2k-j-m)-\sum_{m=1}^{k-j}\binom{2k-j}{m}m\tag{8}\\
&=(2k-j)\sum_{m=0}^{k-j}\binom{2k-j-1}{2k-j-m-1}-(2k-j)\sum_{m=1}^{k-j}\binom{2k-j-1}{m-1}\tag{9}\\
&=(2k-j)\sum_{m=0}^{k-j}\binom{2k-j-1}{m}-(2k-j)\sum_{m=0}^{k-j-1}\binom{2k-j-1}{m}\\
&=(2k-j)\binom{2k-j-1}{k-j}=(2k-j)\binom{2k-j-1}{k-1}\\
&\,\,\color{blue}{=k\binom{2k-j}{k}}
\end{align*}
and the claim (2) follows.
Comment:

In (3) we apply the coefficient of operator according to (1).

In (4) we apply $[z^{p-q}]A(z)=[z^p]z^qA(z)$ and some rearrangements. We also set the upper limit to $\infty$ without changing anything thanks to $[z^k]$.

in (5) we shift the index to start with $j=0$.

In (6) we recall the binomial series expansions
\begin{align*}
\frac{z}{(1-z)^2}=\sum_{q=1}^{\infty}qz^q\qquad\qquad\frac{1}{1-z}=\sum_{q=0}^{\infty}z^q
\end{align*}

In (7) we select the coefficient of $z^{k-j}$ recalling the Cauchy product of series.

In (8) we apply $\binom{p}{q}=\binom{p}{p-q}$ and rearrange the sums.

In (9) we apply $\binom{p}{q}=\frac{p}{q}\binom{p-1}{q-1}$.
Answer: Separate the last term of your sum as
$$
\sum\limits_{\ell  = j}^{k - 1} {\frac{{2^\ell  \ell (2k - \ell  - 1)!}}{{(k - \ell )!}}}  + \frac{{2^k k(2k - k - 1)!}}{{(k - k)!}} = \sum\limits_{\ell  = j}^{k - 1} {\frac{{2^\ell  \ell (2k - \ell  - 1)!}}{{(k - \ell )!}}}  + 2^k k!,
$$
and note the telescoping property
$$
\frac{{2^\ell  \ell (2k - \ell  - 1)!}}{{(k - \ell )!}} = \frac{{2^\ell  (2k - \ell )!}}{{(k - \ell )!}} - \frac{{2^{\ell  + 1} (2k - (\ell  + 1))!}}{{(k - (\ell  + 1))!}},
$$ for $j\le \ell \le k-1$.
Comment: Ah, I was so into finding an answer by induction that I forgot to notice my induction step could be used to telescope the sum directly! (+1)
Comment: @Gary: Very nice observation and elegant approach. (+1) In fact the generating function approach is done until the telescoping in the line after (9) becomes obvious. :-)
Answer: Using induction:
Let the RHS be $f(j)$, with $0\le j\le k$. We prove by induction that:
$$P(j): f(j) = \color{red}{\frac{2^j(2k-j)!}{(k-j)!}}$$is true for $j \le k$.
For the base case $j=k$, note that the sum has only one summand, i.e,
$$f(\color{blue}{k}) = \frac{2^{\color{blue}{k}}\color{blue}{k} (2k-\color{blue}{k}-1)!}{(k-\color{blue}{k})!} = \color{red}{\frac{2^k(2k-k)!}{(k-k)!}}$$
So, $P(k)$ is true.
Suppose $P(a+1)$ holds for $k-1\ge a$. We need to prove $P(a)$ is true. Note that:
$$\begin{align}f(a) &= f(a+1) + \frac{2^aa(2k-a-1)!}{(k-a)!} \\
&= \color{red}{\frac{2^{a+1}(2k-a-1)!}{(k-a-1)!}} + \frac{2^aa(2k-a-1)!}{(k-a)!} \\
&= \frac{2^a(2k-a-1)!}{(k-a-1)!}\left(2+\frac{a}{k-a}\right) \\
&= \frac{2^a(2k-a-1)!}{(k-a-1)!}\cdot \frac{2k-a}{k-a} \\
&= \color{red}{\frac{2^a(2k-a)!}{(k-a)!}} \tag*{$\blacksquare$}\\
\end{align}$$
Comment: $P(1)$ is equivalent to the linked question.
Comment: Thank you very much!


From log-normal parameters, to normal parameters

Question: from the following log-normal fitting function (https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.lognorm.html), I get the parameters [s, loc and scale]. How can I use them to get the μ and σ of the corresponding normal distribution? The location parameter troubles me a bit.
Answer: What you have there is a three parameter lognormal (shifted lognormal). As a result, just taking the log of this is not normal unless "loc" is set to zero.
This three parameter lognormal has the following density:
$$f_{X}(x)={\frac {1}{x}}\cdot {\frac {1}{\sigma {\sqrt {2\pi \,}}}}\exp \left(-{\frac {[\ln (x-\gamma)-\mu ]^{2}}{2\sigma ^{2}}}\right),\:x>\gamma,\,\sigma>0,\,-\infty<\mu,\gamma<\infty$$
The shift parameter $\gamma$ is what that help refers to as the parameter loc.
The variable $Y=\ln (X-\gamma)$ is $\sim N(\mu,\sigma^2)$.
That is, the log of scale is the mean of the log of the back-shifted variate ($X-\gamma$) (i.e. $\mu$ in the above formula, where $\mu=\ln(\text{scale}$)), and s is the standard deviation of the log of the back-shifted variate (i.e. $\sigma$ in the above formula).


scodec - Method too large

Question: Have a sealed trait DataTag and its subtypes (86 case classes). After upgrade project to scala 2.12, scodec-core 1.11.8 and scodec-bits 1.1.27, compilation fail with
[error] Method too large: protocol/Payload/BasePacket$.tagCodec ()Lscodec/Codec;
The error is called by this method:
implicit def tagCodec: Codec[DataTag] = Codec.coproduct[DataTag].auto
Is there an alternative way to generate codec with a large number of subtypes?
I tried to use the "key based discriminators" example (https://github.com/scodec/scodec/blob/series/1.11.x/unitTests/src/test/scala/scodec/examples/CoproductsExample.scala), but the result is the same.
P.S.: I made an issue on github(https://github.com/scodec/scodec/issues/324), but no one has answered it yet.
Answer: Problem solved. Codec wrote, specifying all codecs from subtypes сompanion objects through .typecase(discriminator, codec). This is ugly, but works.

scodec - Method too large


How can I render a view on user-profile.tpl.php that includes the user name as an argument in Drupal 7?

Question: In Drupal 7, on a custom user profile page (using user-profile.tpl.php) I would like to place a view that references all nodes of a specific content type that has that user as a reference. (The user may, or may not be an author of the node.)
Answer: use views_embed_view to embed a view:
<code>$views = views_embed_view('VIEW_NAME', 'DISPLAY_ID');
print render($views);
</code>
The DISPLAY_ID is typically 'page' or 'block' depending on the displays you have setup in views.
You can build the view with a contextual filter to get all nodes with a user reference.
If you don't need to embed the view in the middle of your user profile you can just use a block output and show that block before or after your user profile.
Comment: Thanks! For those looking for more info, I found it here this morning: http://drupalcontrib.org/api/drupal/contributions--views--views.module/function/views_embed_view/7


Real analysis text books

Question: I'm sure his has been asked before but can someone recommend a real analysis text book with lots of worked examples practice questions and solutions?
The sort of textbooks I've used and really benefited from before are Ken Stroud and Kuldeep Singh who use lots of questions which gradually increase in difficulty as the text progresses through the material.
Any suggestions would be gratefully appreciated
Comment: Your request is probably more broad than you think.  However, I'd like to recommend the lectures series in analysis by Elias Stein and Rami Shakarchi.  It's a pretty large collection of future-practitioner friendly books, covering a pretty wide range of subjects and applications.
Comment: Does this answer your question? [Good book for self study of a First Course in Real Analysis](https://math.stackexchange.com/questions/62212/good-book-for-self-study-of-a-first-course-in-real-analysis)
Comment: Does this answer your question? [What books introduce the concepts of proof, using real analysis?](https://math.stackexchange.com/questions/3940872/what-books-introduce-the-concepts-of-proof-using-real-analysis)
Answer: If you need a lot of worked problems in analysis, consider the three volumes of Problems in Mathematical Analysis by W. J. Kaczor and M. T. Nowak. About 100 pages of every volume are devoted to problems, and 300 pages to solutions.
What about regular textbooks: Charles C. Pugh's Real Mathematical Analysis is highly praised for its problems (contains about 600 problems). If you already have had one year of analysis, you might consider Folland's Real Analysis, it is quite challenging but readable.
Answer: Try these monographs aimed at undergraduate first-timers (to real analysis).

Title
Author
Publication Year

How to Think about Analysis
Lara Alcock
2014

Writing Proofs in Analysis
Jonathan M. Kane
2016

An Introduction to Proof through Real Analysis
Daniel J. Madden, Jason A. Aubrey
2017

The Real Analysis Lifesaver: All the Tools You Need to Understand Proofs
Raffi Grinberg
2017

Real Analysis With Proof Strategies
Daniel W. Cunningham
2021

Analysis with an Introduction to Proof, 6th ed.
Steven R. Lay, Richard G. Ligo
2023

Dave L. Renfro recommends other monographs at

Real analysis for a non-mathematician.
Proof analysis in Zorn's "Understanding real analysis"?
https://math.stackexchange.com/q/2316640

Real analysis text books


Properly fingering jazz chords?

Question: I've seen these come up in a few places (Crazy Train and a couple of Jimi Hendrix songs come to mind offhand), however I've never figured how to work them in fluidly;the fingerings always seem awkward, especial when the shape changes from one chord to the next.  Is there a guide to how to finger them properly?
Comment: Don't think of them as "jazz" chords because jazz is just one style using them. They are extended chords, using more than the root, third and fifth of the key, which are the common intervals used for rock and the simpler blues. Other styles of music, like country, throw in fourths, sixths. Some blues use the flatted-seventh and ninth a lot to add some dissonance. Jazz and modern classical use them all, and more. The overall reason is harmonic richness. The more notes added, the more directions the melody can go, and the more tension that can be added to the sound.
Comment: Jazz chords has become a blanket term for any chord that is rarely heard in more conventionally structured, not that its a bad term; i use it myself, but G#minb5 is a G#minb5; i have an answer for this but it will be long and i'm off :)
Comment: I'm interested in the answer too, though I'm not sure "jazz chord" is the proper term... maybe "dissonant chords" or "'colored' chords"?
Answer: One of the best ways is to play scales using chords. Set up a metronome, and change a chord on every forth beat. Choose a slower tempo if you can't do it on time. When you get comfortable, try more complex rhythm or a finger picking pattern. Here is an example of the F scale with jazz chords:
Fmaj7
Gm7
Am7
Bbmaj7
C7
Dm7
Ehalfdim
Fmaj7
Here are the fingerings, I've scanned my papers for you, so please do not mind the quality of an image :)

When chords are down, try improvising with them - just mix the chords from a scale in a way you feel is right. It's lots of fun and that's what jazz is all about :)
Good luck in your playing!
Comment: +1 Excellent answer; the only thing I would add to this it to look for and play inversions of each chord, play in different keys, and apply progressions when improvising starting with the basic ii v i
Comment: There are also a ton of voicings for different chords. For instance, in the m7 and 7 chords you have listed, you're not using the lower 5th. Adding that in doesn't change the composition of the chord, but it sure does change the fingering and sound. I'd suggest starting with a more comprehensive chord chart and exploring from there, as I think there are some more intuitive fingerings for someone already familiar with barre chords (although I do prefer the sound of some of the fingerings listed here).
Comment: I also think these kinds of chords are easier to learn based off your barre positions rooted on the E and A string than in the open position. For one, it's much easier to move them to different keys!
Answer: To take Silver Light's answer a step further (I can't seem to add this to the original, my apologies): Sal Salvador's book of chord scales systematizes most inversions of the major, melodic minor, and harmonic scale chords:
http://www.amazon.com/Sal-Salvador-Harmony-Comping-Guitar/dp/0871666480/ref=sr_1_7?s=books&ie=UTF8&qid=1295974240&sr=1-7

Properly fingering jazz chords?


Can I use strings for bridge pins on a non-bridge pin guitar?

Question: Very new to the guitar.  I borrowed an Oscar Schmidt OC11 nylon-string classical guitar, without an E-6th string and I bought a heap load of different weighted strings so I could try different types. However, the strings I bought are for guitars with bridge pins.
I just broke a string trying to make it work and I am even more worried about breaking the guitar.
Should I return the strings or can I make them work?
Comment: (This question came first, but the other one is asked more clearly and serves as a better signpost for the problem.)
Answer: Just to be clear, what you have are ball-end nylon strings, right? Because if you're planning on putting steel strings on a classical guitar, I'll have to advise you against moving forward. The instrument is not built for steel string tension.
If they are nylon strings, on a standard classical guitar, Frets.com has a tutorial on the right way to restring your classical guitar, if you have the right strings. But, if you're just putting in a ball-end nylon string, you should be able to run it through the hole in the bridge just fine and get your classical guitar on without doing tying.
That's if it's ball-end nylon strings. If not, stop and get other strings.
Comment: Big fat +1. **DO NOT** attempt to put steel strings on a classical guitar (as the Oscar Schmidt OC11 is) unless you're performing an experiment testing the playability of a guitar that has folded like a cheap card table.
Comment: I promise you, those strings are steel at the core, with phosphor bronze wraps to add mass without much affecting flexibility. It is neat stuff, but you have to build the instrument to account for it. Heavier bracing in the body and a truss rod in the neck. The tension between the bridge and neck on an electric guitar is about as many pounds as you are, so they need it.

It'd probably sound amazing for the few moments before it falls apart on you.
Comment: Those are not the strings for this instrument.
Comment: An acceptable acoustic guitar starts at $100. Strings start at $4. Match the strings to the guitar, not the other way around.
Comment: Well, they are definitely not nylon. The package says phosphor bronze. Here are they are: http://www.amazon.com/DAddario-EJ16-3D-Phosphor-Acoustic-Strings/dp/B000OR2RNM From the Amazon page, it looks like two of the six are steel.
Comment: A tool comes with a purpose. A screwdriver is not a chisel, no matter how much they seem similar. A classical guitar seems similar to a steel string guitar, but the neck is built for playing melodies while the steel string guitar is built for strumming. Unless you listen to Willie Nelson, Segovia or Earl Klugh and say "I want to play like that", the classical guitar is likely not what you want.
Answer: Remove the steel strings immediately. They will permanently damage your guitar.
Do not use light-gauge steel strings either. You should only use nylon strings on this guitar.
Steel strings put much more tension on the neck of a guitar compared to nylon strings.
Guitars designed for steel strings have very stiff, strong necks with a metal truss rod inside the neck designed to counteract the additional tension from the steel strings.
Classical guitars designed for nylon strings generally do not have a truss rod in the neck, and the neck is built only to withstand the lower tension of the nylon strings.
Furthermore, the top of the classical guitar and the bridge are braced underneath only to withstand the much lower tension of the nylon strings.
If you keep those steel strings on your guitar, the neck will permanently bend and warp, the top of the guitar will "belly up" and warp, and the bridge will eventually rip loose from where it is glued to the top of the guitar, taking a good deal of the wood of the top of the guitar with it. When these things happen, then your guitar will be ruined. It will not be feasible to repair the damage.
Never, never put steel strings on a classical guitar built for nylon strings.
Update:
I did the maths based on data from string sets at the D'Addario string company web site.
A typical set of regular-gauge steel acoustic guitar strings puts 179 lbs (81.3kg) of tension on a guitar.
A typical set of nylon strings puts 83.6 lbs (37.9kg) of tension on a guitar.
Therefore if you put steel strings on a classical guitar, you are more than doubling the amount of tension and strain that the classical guitar has been built to handle.
Comment: This is a repeat post of an answer I made on another question on this site, but I thought it important enough that I duplicated it. What the questioner was trying to do, not knowing any better, is very dangerous.
Comment: What information did you find about nylon strings and tensions?  As noted on another question, I'd like to find some nylon strings that would work well for a 2+4 bass/treble split [with the fourth string being an unwound "D"].  Also, out of curiosity, what sort of string gauge were you assuming for the steel strings?  I would expect that a set of 8/38 strings would probably only require about half the tension of a set of 12/56; there may not be any overlap between the lightest steel strings and the heaviest nylon strings, but I wouldn't be surprised if they were close.
Comment: I have referred to this string tension reference PDF from D'Addario many times on this site. It covers steel-string and nylon, and more. Check it out. http://daddario.com/upload/tension_chart_13934.pdf


module to test if e-mail is working

Question: In D7 I'm trying to determine the best way to periodically check if e-mail is working. I'm looking for a way to create a workflow that, say, on cron would check the day of the month, if it's the day that has been configured in the module as the test day, send an e-mail. Check the return value on the e-mail function. If the e-mail failed, write the error to the logs and/or send it to another service, like Slack, to alert the team.
Is there a module that comes close to doing this, or can something be cobbled together with actions and rules, etc? Thanks!
Comment: https://drupal.stackexchange.com/questions/84268/use-hook-cron-to-send-daily-mail-but-i-get-45-the-same-mail-every-day/275911#275911, and use Mail Logger module
Answer: What I did instead: Since all I really want to know is when e-mail fails, I went the watchdog rules route instead. Combining watchdog rules with the Slack API allowed me to create a rule that sends a slack message whenever one of our sites has an smtp error.

module to test if e-mail is working


Justification for and optimality of $R^2_{adj.}$ as a model selection criterion

Question: In a recent thread, use of adjusted $R^2$ ($R^2_{adj.}$) is mentioned in the context of model selection, e.g.

The adjustment was invented as a solution to problems caused by variable selection

Question: Is there any justification for using $R^2_{adj.}$ for model selection? That is, does $R^2_{adj.}$ have any optimality properties in the context of model selection?
For example, AIC is an efficient criterion and BIC is a consistent one, but $R^2$ does not coincide with any of them and so makes me wonder if it can be optimal in any other sense.
Comment: @ChristophHanck, my problem is exactly what $R^2_{adj.}$ is optimal for. It is neither efficient (like AIC) nor consistent (like BIC). So is it good for anything? Maybe there is some criterion in addition to efficiency and consistency that makes $R^2_{adj.}$ the measure of choice? If so, is the criterion ever desirable?
Comment: Also discussed here:  https://stats.stackexchange.com/questions/222461/how-to-show-that-a-model-is-not-over-fitted
Comment: model selection can quite easily be "optimally sub-optimal" and shrinkage/regularisation can be a better method. proceed carefully, particularly if your goal is prediction of new cases....
Comment: @Richard Hardy, isn't that pretty much this thread? https://stats.stackexchange.com/questions/197112/why-information-criterion-not-adjusted-r2-are-used-to-select-appropriate-la/197237#197237
Comment: @probabilityislogic, good point. Hansen ["A Winner's Curse for Econometric Models: On the Joint Distribution of In-Sample Fit and Out-of-Sample Fit and its Implications for Model Selection"](http://www.tse-fr.eu/sites/default/files/medias/stories/SEMIN_10_11/ECONOMETRIE/hansen.pdf) (2010) offers some concrete examples of that. So I wonder if there is *any* justification for $R^2_{adj.}$ as a model selection criterion.
Comment: +1, I see. To give a moderately useful example, as my answer in the link demonstrates, adjusted $R^2$ amounts to choosing the model with the smallest $\log(\widehat{\sigma}^2)+\frac{K}{n}$. Hence, one might say that it is optimal for someone who has this loss function trading off fit and parsimony.
Answer: I don't know if $R^2_{\text{adj.}}$ have any optimal properties for model selection, but it is surely taught (or at least mentioned) in that context. One reason might be because most students have met $R^2$ early on, so there is then something to build on.
One example is the following exam paper from University of Oslo (see problem 1.)  The text used in that course, Regression Methods
in Biostatistics
Linear, Logistic, Survival, and Repeated
Measures Models
Second edition by Eric Vittinghoff, David V. Glidden, Stephen C. Shiboski and Charles E. McCulloch mentions $R^2_{\text{adj.}}$ early on in their chapter 10 on variable selection (as penalizing less than AIC, for example) but neither it nor AIC is mentioned in their summary/recommendations 10.5.
So it is maybe mostly used didactically, as an introduction to the problems of model selection, and not because of any optimality properties.
Comment: Thank you. The relevant part for me is the first part of your first sentence.
Answer: I would propose six optimality properties.

Overfit Mitigation
Simplicity and Parsimony
General Shared Understanding
Semi-Efficient Factor Identification
Robustness to Sample Size Change
Explanatory Utility

Overfit Mitigation
What kind of model is overfit? In part, this depends on the model's use case. Suppose we are using a model to test whether a hypothesized factor-level relationship exists. In that case a model which tends to allow spurious relations is overfit.
"The use of an adjusted R2...is an attempt to account for the phenomenon of the R2 automatically and spuriously increasing when extra explanatory variables are added to the model." Wikipedia.
Simplicity and Parsimony
Parsimony is valued on normative and economic rationale. Occam's Razor is an example of a norm, and depending on what we mean by "justification," it might pass or fail.
The economic rationale for simplicity and parsimony are harder to dismiss:

Complex models with many factors are expensive to gather data for.
Complex models can be more expensive to execute.
Complex models are hard to communicate and think through. Business and legal risks can result from this, as well as plain time spent communicating from one person to another.

Given two models with equal explanatory power (R2), then, AR2 selects for the simpler and more parsimonious model.
General Shared Understanding
Justification involves shared understanding. Consider a peer-review situation. If the reviewer and the reviewed lack a shared understanding of model selection, questions or rejections may occur.
R2 is an elementary statistical concept and those only familiar with elementary statistics still generally understand that R2 is gameable and AR2 is preferred to R2 for the above reasons.
Sure, there may be better choices compared to AR2 such as AIC and BIC, but if the reviewer is unfamiliar with these then their use may not succeed as a justification. What's worse, the reviewer may have a misunderstanding themselves and required AIC or BIC when they aren't required - that itself is unjustified.
My limited understanding indicates that AIC is now considered rather arbitrary by many - specifically the 2s in the formula. WAIC, DIC, and LOO-CV have been suggested as preferred, see here.
I hope by "justified" we don't mean "no better parameter exists" because it seems to me that some better parameter might always exist unbeknownst to us, therefore this style of justification always fails. Instead "justified" ought to mean "satisfies the requirement at hand" in my view.
Semi-Efficient Factor Identification
Caveat: I made up this term and I could be using it wrong :)
Basically, if we are interested in identifying true factor relations, we should expect p < 0.5, ie P(B) > P'(B). AR2 maximization satisfies this as adding a factor with p >= 0.5 will reduce AR2. Now this isn't an exact match because I think AR2 generally penalizes p > 0.35-ish.
It's true AIC penalizes more in general but I'm not sure that's a good thing if the goal is to identify all observed features that have an identifiable relation, say at least directionally, in a given data set.
Robustness to Sample Size Change
In the comments of this post, Scortchi - Reinstate Monica notes that it "makes no sense to compare likelihoods (or therefore AICs) of models fitted on different nos observations." In contrast, r-squared and adjusted r-squared are absolute measures that can be compared with a change in the number of samples.
This might be useful in the case of a questionnaire that includes some optional questions and partial responses. It's of course important to be mindful of issues like response bias in such cases.
Explanatory Utility
Here, we are told that "R2 and AIC are answering two different questions...R2 is saying something to the effect of how well your model explains the observed data...AIC, on the other hand, is trying to explain how well the model will predict on new data."
So if the use case is non-predictive, such as in the case of theory-driven, factor-level hypothesis testing, AIC may be considered inappropriate.
Comment: Note that under some assumptions, LOOCV is asymptotically equivalent to AIC.
Comment: When you say "factor relations", what exactly do you mean?
Comment: Here I am trying to generally express coefficient hypothesis testing. Usually I care about direction of effect, significance, and importance. This general term leaves room to explore an independent factor, lags, interactions, marginal effects, and other computed, derived, or engineered features. Possibly including causal testing. I am mainly thinking about OLS at the moment.
Comment: Sometimes I'm also interested in how dependent variables relate to each other as a secondary concern. Eg does X2 "partial out" X1
Comment: I cannot find the relevant thread anymore to post this comment to but I will do it here. Just wanted to let you know I watched Ben Lambert's YouTube video about AIC, DIC, WAIC and LOOCV and did not find it convincing enough to drop AIC in favor of DIC or WAIC. Statements in the video (e.g. about popularity or approximation quality of AIC) are too general to be correct even if they may hold in special cases (though I understand this is intentional due to the format of the lecture series). DIC and WAIC may function OK for Bayesian modeling but I do not see if they are applicable outside of that.
Comment: Link for the audience [here](https://www.youtube.com/watch?v=xS4jDHQfP2o). The key statement in the video as I understand it wasn't to do with popularity; that's a result not a cause of utility. He says "The big step forward which DIC makes over AIC is applying a more general and useful measure of penalty." DIC penalty is related to data variance in contrast to the arbitrary 2k AIC penalty. It's hard for me to see how AIC can be preferred to either since it is a special case of either DIC or WAIC - a special case with little retrospective or comparative optimality justification.
Comment: Now, if we abandon "I must use the ideal optimality justification" for "I must use a satisfactory optimality justification," then sure AIC seems fine - the gains from others will often be unimportant and AIC is relatively widely used, understood, and supported in code libraries. However, on exactly parallel grounds, we can appreciate adjusted r-squared.
Comment: I do not remember Ben Lambert saying the 2k penalty is arbitrary. I hope he did not say that as that would simply be wrong. There is a clear theoretical justification for it in Akaiske's original paper and in later elaborations. I cannot comment on the relationship between AIC and DIC or WAIC as I do not know the latter two well enough. I am still looking for any optimality justification for $R^2_{adj.}$. The arguments you have provided are not quite what I am looking for. Nor are they on the level of concreteness that would lend itself for constructive criticism given my understanding. Sorry.
Comment: @RichardHardy I just added items 5 and 6 - I don't expect these are what you are looking for either, but just in case!
Answer: Answer for part1:

If you add more variables, even totally insignificant variable, R2 can only go up. this is not the case with adjusted R2.
You can try running multiple regression and then add random variable and see what happened to R2 and what happened to the adjusted R2.
Comment: Thanks! I do not think this constitutes a justification for the use of $R^2_{adj.}$ for model selection. It only justifies the preference of $R^2_{adj.}$ to $R^2$ when estimating the population $R^2$ under a very restrictive assumption, as I explain in the comment in the linked thread. I have edited my post to make my question clearer.
Comment: The adjusted R squared increases only if the under investigation variable improves the model more than just a random variable.
Comment: Thanks once more. Could you be more precise? In which sense exactly does it improve the model? Does the model become better at prediction under a given loss function? Or does a higher $R^2_{adj.}$ suggests the model is more likely to be the true model among a set of candidates? Or does it have any other properties that could justify it as a criterion for model selection?
Comment: R squared is the ratio of the explained variance and the adjusted R squared is less bias estimator for the population R squared. So you want higher explained variance in your model
Comment: The explained variance is the variance that the model knows to calculate. The not explain variance is the noise that the model can't predict,
Comment: OK, I think I get that. But in which way is $R^2_{adj.}$ relevant for model selection? (I do not dispute its relevance for measuring the ratio of explained variance to total variance, even though the simpler $R^2$ may be preferable in some cases, as I explain in the linked thread.) In prediction, it appears to be inferior to AIC (which is an efficient model selector) as it penalizes too little (less than AIC) and thus would select too rich a model. In search for the true model, this deficiency is even greater, as an even larger penalty is needed for selection consistency (compare BIC to AIC).
Comment: The are several algorithms like stepwise that start with all the variables (or with no variable)  and remove variable one by one so the final goal is to maximize the adjusted R squared (this good only as a screening method )
Comment: My question is not whether such methods exist (they do), but whether they have a justification. There are a number of historically popular methods in statistics that have been proven over and over again to have poor properties; stepwise model selection is one of them, regardless of which criterion (AIC, BIC, $R^2_{adj.}$) is employed inside. These methods do not get extinct; once they are created, they exist. My question is, do they have a justification to be used. More specifically, does $R^2_{adj.}$ have a justification as a model selection criterion.
Comment: As I wrote this is good only as a "screening method". It doesn't replace the expert that build the model base on logic, knowledge and other researches but help as supporting tool
Comment: @RichardHardy I see you say "it appears to be inferior to AIC (which is an efficient model selector) as it penalizes too little (less than AIC) and thus would select too rich a model" however AIC weighting is considered suboptimal and arbitrary itself (the 2s in the formula) and sometimes too severe; compare WAIC or DIC. If we are interested in collecting true factor effects, one logical approach is p<0.5 (more likely true than not). AR2 generally optimizes around .3 which can be considered more optimal in the sense of closer to 0.5 compared to AIC - optimal shouldn't mean restrictive.
Comment: @JohnVandivier, interesting. Consider contributing these points as an answer in the linked thread. The justification and optimality of AIC is clear -- under appropriate assumptions. The 2s have no effect on model selection as they apply equally to every model.
Comment: @RichardHardy Will do! Thanks. I was hoping to have my error cleared up prior to downvote, but we shall take the plunge :)
Comment: @JohnVandivier, not sure what downvote you are talking about.
Comment: I just mean that if I am mistaken I would prefer to be corrected in a comment rather than receiving a hypothetical downvote - hopefully no such vote obtains


How to clear the WKBackForwardList of a WKWebView?

Question: It appears that the backForwardList of a WKWebView is readonly, but I've seen people so some pretty magical things to get around this. I need to figure out some way of clearing the history of a WKWebView. Any ideas how I might so this? So far I've tries a few tricks that have failed:

using keyValue:forKey didn't work.
using a C pointer -> didnt work.

I've seen people talk about synthesizing the property and extending the class but I don't really know how that works and couldn't figure it out. Any other ideas?
Comment: You could try implementing your own storage... `WKBackForwardList` IS immutable
Comment: What about using: `allowsBackForwardNavigationGestures`, `canGoBack` or `canGoForward`? Or do you specifically need to clear `backForwardList`?
Comment: @nyg I need to clear the history, not just prevent swipe.
Answer: Worded on iOS8 ~ iOS11.
Objective-C
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
[wek.backForwardList performSelector:NSSelectorFromString(@"_removeAllItems")];
#pragma clang diagnostic pop

Swift 4
webView.backForwardList.perform(Selector(("_removeAllItems")))

!!!!NOTE!!!! THIS METHOD IS DECLARED IN WebKit Open Resource, not a public method。
Comment: Definetely gonna be rejected for using this method. It's very simple, it's not listed in the WKBackForwardList api doc, so it's private api. A very bad way to solve the problem and to generate crashes when Apple decides to change that signature in the future version of iOS.
Comment: What does "declear" mean, and secondly, where did you find out how to do this?
Comment: @Chet It's "declared".Spell error. Find in WebKit Open Resource
Comment: xu tong's solution will accept by apple ?
Is there any rejection due to this ?
Comment: It means it is working now but it's not a documented method, so you're not supposed to use it because it could go away without warning.
Answer: Because Apple keeps the interface for WKBackForwardList pretty tightly locked down and is notoriously strict with developers who go outside of the published public interfaces, you have two options:

The easiest way (and surely what Apple intends) is to create a new WKWebView and replace your current one with it. This isn't that hard of a solution to implement since there are a pretty finite number of configurations you could have to copy over from your old instance to your new one. You could even create a wrapper view that did this for you, so that you only ever had to call clearHistory() and the wrapper view would do the underlying swap for you.

If, for some reason, you can't replace the instance of WKWebView, you can take advantage of the 1D nature of history to clear the history down to two items. You cannot clear it farther than that, I'm afraid. To clear the URL down to two URLs, let's say they're stored in the values urlA and urlB, you would do:

// At initialization, ensure that urlA is the first item in the history
let webview = WKWebView()
// ... whatever other init you need
webview.load(URLRequest(url: urlA))

and then to "clear" the history:
func clearHistory() {
    // First we make sure the webview is on the earliest item in the history
    if webview.canGoBack {
        webview.go(to: webview.backForwardList.backList.first)
    }
    // Then we navigate to our urlB so that we destroy the old "forward" stack
    webview.load(URLRequest(url: urlB))
}

Answer: This code compiles, but I have not tested it...
First I subclass WKWebView to override backForwardList with my own subclass of WKBackForwardList.
Then, in my WKBackForwardList subclass, I can either override backItem & forwardItem to make them return nil, instead of having them look into their respective list (which is most probably the default implementation).
Or I can override backList & forwardList in the same way I did in WKWebView with backForwardList. I do this to add a setter, which will allow me remove items from the lists.
import Foundation
import WebKit

class WebViewHistory: WKBackForwardList {

    /* Solution 1: return nil, discarding what is in backList & forwardList */

    override var backItem: WKBackForwardListItem? {
        return nil
    }

    override var forwardItem: WKBackForwardListItem? {
        return nil
    }

    /* Solution 2: override backList and forwardList to add a setter */

    var myBackList = [WKBackForwardListItem]()

    override var backList: [WKBackForwardListItem] {
        get {
            return myBackList
        }
        set(list) {
            myBackList = list
        }
    }

    func clearBackList() {
        backList.removeAll()
    }
}

class WebView: WKWebView {

    var history: WebViewHistory

    override var backForwardList: WebViewHistory {
        return history
    }

    init(frame: CGRect, configuration: WKWebViewConfiguration, history: WebViewHistory) {
        self.history = history
        super.init(frame: frame, configuration: configuration)
    }

    /* Not sure about the best way to handle this part, it was just required for the code to compile... */

    required init?(coder: NSCoder) {

        if let history = coder.decodeObject(forKey: "history") as? WebViewHistory {
            self.history = history
        }
        else {
            history = WebViewHistory()
        }

        super.init(coder: coder)
    }

    override func encode(with aCoder: NSCoder) {
        super.encode(with: aCoder)
        aCoder.encode(history, forKey: "history")
    }
}

Comment: backForwardList never changes during navigation. it remains empty in my app. what's wrong?
Comment: Unfortunately, this brilliant idea doesn't work. It seems that `backList` is simply a derived property, and it's therefore not used internally by WebKit to store the actual visited items.
Comment: indeed, doesn't work. A workaround is to create a new WKWebView and pass the old configuration.
Comment: Thanks for the help! Trying to figure out how to convert this into Objective C and integrate into this plugin: https://github.com/apache/cordova-plugin-wkwebview-engine/blob/master/src/ios/CDVWKWebViewEngine.m#L62
Comment: Here's my attempt -- doesn't seem to work though. https://github.com/ccorcos/cordova-plugin-wkwebview-engine/commit/ae78c110a283eda9658f44f51125670fe54b1aa9  Again, I'm not an Objective C expert my any means...
Comment: I feel like I'm pretty close though. Currently getting this error: `-[WKWebView clearHistory]: unrecognized selector sent to instance`
Comment: @Chet I saw your latest commit which fixed a typo in the name of the method. Did that solved the error?
Comment: No, I get a runtime error saying that its not a CVDWKWebView... :/ Never figured it out
Comment: @Chet Check in `CDVWKWebViewEngine.m`, line 138, you're still using `[WKWebView alloc]`. I think it should be `[CVDWKWebView alloc]` no?
Comment: Ah you're right!! I was only looking at line 108. Thanks for the help -- I'll let you know if this works!
Answer: Reading in the documentation you can get WKBackForwardList for the WKWebView.
After that you can find the first item in the backList of WKBackForwardList and after that to use:
func go(to: WKBackForwardListItem) -> WKNavigation?
And with this you can clean the history up to the first url.