With MVC how can I bind a list of selected radio buttons?

Question: I have some nested view models used to display a questionnaire driven from a database. Displaying the questions is straightforward but I don't know how to bind to the model or parse the selected answers on submit.
My objects look like (pseudo):
public class QuestionSheetViewModel(){
    public list<QuestionViewModel> Questions;
    public string UserName;
}

public class QuestionViewModel(){
    public int QuestionId;
    public string QuestionText;
    public dictionary<int, string> answers;
}

In my view I iterate over the questions, displaying each question text and then rendering each answer as a radio button:
    @Html.RadioButton(question.QuestionID, answer.Key());

By using question.questionId as the radio button name they are grouped together, limiting the user to one answer per question.
When I submit, the model's list of questions is empty. Is it possible to automatically bind this to my view model? If not, what would I need to do to write something to parse the submitted form to find the selected answer for each question?
Thank you
Answer: You could adapt your models a little bit to match your requirements:
public class QuestionSheetViewModel
{
    public List<QuestionViewModel> Questions { get; set; }
    public int QuestionId { get; set; }
}

public class QuestionViewModel
{
    public string QuestionText { get; set; }
    public int SelectedAnswerId { get; set; }
    public List<AnswerViewModel> Answers { get; set; }
}

public class AnswerViewModel
{
    public int AnswerId { get; set; }
    public string Text { get; set; }
}

and then have a controller:
public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new QuestionSheetViewModel
        {
            QuestionId = 1,
            Questions = new[]
            {
                new QuestionViewModel
                {
                    QuestionText = "question 1",
                    SelectedAnswerId = 2,
                    Answers = new[]
                    {
                        new AnswerViewModel { AnswerId = 1, Text = "answer 1" },
                        new AnswerViewModel { AnswerId = 2, Text = "answer 2" },
                    }.ToList()
                },
                new QuestionViewModel
                {
                    QuestionText = "question 2",
                    SelectedAnswerId = 3,
                    Answers = new[]
                    {
                        new AnswerViewModel { AnswerId = 3, Text = "answer 3" },
                        new AnswerViewModel { AnswerId = 4, Text = "answer 4" },
                    }.ToList()
                },
            }.ToList()
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(QuestionSheetViewModel model)
    {
        // When the form is submitted the model will be properly bound
        return View(model);
    }
}

with a corresponding view (~/Views/Home/Index.cshtml):
@model QuestionSheetViewModel

@using (Html.BeginForm())
{
    @Html.HiddenFor(x => x.QuestionId)

        @Html.EditorFor(x => x.Questions)

    <button type="submit">OK</button>
}

and a corresponding editor template which will automatically be rendered by convention for each question (~/Views/Shared/EditorTemplates/QuestionViewModel.cshtml):
@model QuestionViewModel

    @Html.DisplayFor(x => x.QuestionText)
    @Html.HiddenFor(x => x.QuestionText)

        @for (int i = 0; i < Model.Answers.Count; i++)
        {

                @Html.HiddenFor(x => x.Answers[i].AnswerId)
                @Html.HiddenFor(x => x.Answers[i].Text)
                @Html.RadioButtonFor(x => x.SelectedAnswerId, Model.Answers[i].AnswerId)
                @Html.DisplayFor(x => x.Answers[i].Text)

        }

Comment: Thank you for the thorough answer, it makes a lot of sense! I have implemented things this way, and the rendering of the questions works great, but on Submit the model is completely empty. It's empty not only of questions/answers but also the other fields on the "QuestionSheet" object (i just added the "UserName" field as an example). Do you have any ideas why that would be? Thanks a million.


How do I get the cache string?

Question: In Drupal 8, CSS files, images and many other files, are cached by appending a token at the end, as in /sites/default/files/styles/lrg_thumbnail/public/p2i-product_1_zoomout.png?itok=DroPCbms.
Notice the itok=DroPCbms part.
What Drupal function returns this code?
Answer: Contrary to CSS/JS the itok is not for caching, but for DoS protection, see this question
Why are tokens added to image URLs?
The token is generated in
https://api.drupal.org/api/drupal/core%21modules%21image%21src%21Entity%21ImageStyle.php/function/ImageStyle%3A%3AgetPathToken/8.2.x

How do I get the cache string?


Hiding Polygons Drawn Using Google Maps Drawing Library

Question: I can't seem to hide the polygons drawn using the Google Maps Drawing Library. The following is what I am using as my hide function:
function hideRectangles() {
  if (rectangles.length > 0) {
    for (var i = 0; i < rectangles.length; i++) {
      rectangles[i].setMap(null);
    }
  }
}

See full example here: http://jsbin.com/wobapopu/2/edit
Answer: You never update the rectangles array (that is, add rectangles to it), so the hideRectangles() does nothing. Add these lines outside your functions draw/hideRectangles()
google.maps.event.addListener(drawingManager, 'rectanglecomplete', function(rectangle) {
  rectangles.push(rectangle);
});

Click here for Updated example
Answer: You're not pushing actual overlay objects to rectangles array, so it can't remove them from the map.
Instead you should do:
rectangles.push(e.overlay);

Then it will work. Working example here
Comment: Silly mistake. Thank you to both of you for your help.


Setting to limit allowed time for an IIS 7 request to complete?

Question: In IIS 7, you can view the worker processes and see which requests are currently executing. I am encountering some requests that remain in the "ExecuteRequestHandler" stage for hours - basically until the application pool is recycled. I am unsure why this is happening but it appears to correlate with "connection_dropped" errors in the httperr.log file.
I want to ensure these requests aren't tying up resources (we're seeing memory spikes as well, though I can't necessarily tie the two together; CPU for the requests is 0%), so is there a way to limit the amount of time a request can have? I found one for classic ASP but nothing for .NET.
Answer: You should be able to modify the executionTimeout attribute of the httpRuntime in either your application web.config or in machine.config to an appropriate value. Documentation here.
Comment: Thanks, I'll give it a try. It says the default is 110, so I wonder if something is interfering. Debug should already be off.
Comment: This does seem to be the proper way of setting things, but it unfortunately did not resolve my issue.
Comment: How did it not resolve the issue?
Comment: The requests continue to persist in IIS for many hours.


How to add a list to a dictionary as a key value in python

Question: I'm a new python learner and i have come here with a doubt
i have a dictionary my_dict with a 2 lists inside it with keys dic_keys and dic_values now i want to insert the popped elements from dic_values into dic_keys and also to create a new popped_ele key with all the popped elements as a list
<code>    my_dict = {'dic_keys':[],'dic_values':[1,2,3]}
    popped_ele = my_dict['dic_values'].pop()
    my_dict['dic_keys'].append(popped_ele)
    my_dict['dic_popped'] = [].append(popped_ele)
</code>
this is what i expected
my_dict
{'dic_keys': [3], 'dic_values': [1, 2], 'dic_popped': [3]}
but this is what i got
my_dict
{'dic_keys': [3], 'dic_values': [1, 2], 'dic_popped': None}
Comment: `list.append` returns `None`, so that's the value you are inserting to the dictionary
Answer: you can use
<code>my_dict = {'dic_keys': [], 'dic_values': [1, 2, 3]}
my_dict['dic_popped']=[]
popped_ele = my_dict['dic_values'].pop()
my_dict['dic_keys'].append(popped_ele)

my_dict['dic_popped'].append(popped_ele)
print(my_dict)
</code>


IPSec VPN access to VPS

Question: I would like to be able to be able to tunnel a local IP address (i.e 192.168.1.211) through my router that supports IPSec to a remote VPS (i.e. 188.8.131.52). Network map is here: http://cl.ly/3E233z3J2X063z202A0E Is this possible?
I believe that an IPSec VPN is the only way to go about this. Is this true? If I was going to do it from a single machine I would just create an SSH tunnel but obviously that isn't going to work in this situation.
Router is a TP-Link TD-W8960N and the VPS is running ubuntu 11.10. I have absolutly no experience with VPN's but I believe something like openswan would be the thing to use. Am I right? Is this the right path to take? Has anybody got and suggestions?
Answer: It is certainly possible to configure a site-to-site vpn between the network behind your TP-Link router and a network behind your unbuntu VPS.
For this you need to configure some kind of "dummy" network, for example 192.168.2.0/24 on your vps box, and an IPSec stack such as freeswan / openswan / racoon .. on the other.
Then, this is quite a lot of work to set it up, especially if you do not have a real subnetwork on your vps ( it would be the case if your unbuntu was an hypervisor for example, with a subnet of virtual machines ).
Why wouldn't you use ssh ? You can connect as many clients as you want from 192.168.1.100-200 to your vps.

IPSec VPN access to VPS


How can I add a background thread in form load function for notification in ASP.NET?

Question: I want to receive notification from database when table is updated but I need a background thread which call after 1 mint and check database table and show me notification. How can I implement a background thread? I have implemented a thread but when I use while(true) in it, my form is not loaded keep on processing.
Code:
protected void Page_Load(object sender, EventArgs e)
{
    t1 = new Thread(new ThreadStart(Function1));
    t1.IsBackground = true;
    t1.Start();
}

private void Function1()
{
    while (true)
    {
        Thread.Sleep(2000);
        count++;
        Label1.Text = "Function" + count;
    }
}

Answer: You can not use background thread on asp.net page. It works on http stateless protocol and the page object is not available after the response it sent. You can only send one response against one request. You can use jQuery ajax , asp.net ajax library timer control or web sockets to fetch data from server periodically.
This post explains how you can fetch data from server using jQuery ajax. This is also very good tutorial to get the data from server using web methods. The example from this tutorial is given below.
Code behind
public partial class _Default : Page
{
  [WebMethod]
  public static string GetDate()
  {
    return DateTime.Now.ToString();
  }
}

Javascript
$(document).ready(function() {
  // Add the page method call as an onclick handler for the div.
  $("#Result").click(function() {
    $.ajax({
      type: "POST",
      url: "Default.aspx/GetDate",
      data: "{}",
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: function(msg) {
        // Replace the div's content with the page method's return.
        $("#Result").text(msg.d);
      }
    });
  });
});

Comment: I have link to the post that can help you, http://stackoverflow.com/questions/5052543/how-to-fire-ajax-request-periodically
Comment: This code refresh my whole page i just wana refresh my label through timer_tick is it possible.....?
Answer: You have a fundamental misunderstanding of the difference between server-side and client-side code.
For example, your request would require a framework such as SignalR to push a real-time notification to a client.
The easier method is to use Javascript to poll a page of your choice.. for example (jQuery, obviously):
// I'm not a huge jQuery person so theres probably a jQuery way to do this
setInterval(function() {
    $.get('/yourPage.aspx', function(response) {
        if (response.success) {
            alert(response.message);
        }
    });
}, 5000); // poll a page every 5 seconds.

Then your C# page at /yourPage.aspx can check the database and return a Json object with the properties I've mentioned above.
You need to read up on the difference between Client Side and Server Side.. and how they interact in a stateless protocol such as HTTP.
Answer: You can do async tasks in ASP.NET if you are using the 4.5 framework:
http://www.hanselman.com/blog/TheMagicOfUsingAsynchronousMethodsInASPNET45PlusAnImportantGotcha.aspx


How to update c# value in Blazor using javascript?

Question: I am wondering is it possible to update C# value in Blazor using Javascript
For example
<input type="text" @bind="TestValue" >
<input type="button" value="Change value" onclick="ChangeValueFromJs()" >

@code
{
public string TestValue {get;set;} = "init value";
}

js
function ChangeValueFromJs()
{

}

Is there a way to update TestValue and successfully bind it to text input using js ChangeValueFromJs?
I tried doing this, but it didn't seem to work
function ChangeValueFromJs()
{
     DotNet.invokeMethodAsync("BlazorApp", "invokeFromJS", "ChangeValue");
}

@code
{
    [JSInvokable("invokeFromJS")]
    public static Task ChangeValue()
    {
          TestValue = "New value";
          return null;
    }
}

Comment: If you are not getting any errors, then most likely is that the value is being updated, but you need a call to `InvokeAsync(StateHasChanged)` inside `ChangeValue()` to let Blazor know something has changed and it needs to re-render.
Comment: I cannot call InvokeAsync(StateHasChanged) inside a static method
Comment: of course you are right, my mistake not reading it correctly. you would need to change your interop to call an instance method which means you would have to pass a dotnet instance to JS initially, which is messy. I prefer to keep things simple - in your javascript, set the value on the input and then use dispatchEvent to raise the change event on the input and Blazor will update the TestValue through binding
Comment: Could you provide me an example on how to use dispatchEvent in this case
Comment: In its simplest form without any error handling, `var el=document.getElementById('xyz123'); el.value = 'test value'; el.dispatchEvent(new Event('change'));` where `xyz123` is the id of your `input`
Answer:
I tried doing this, but it didn't seem to work

You're almost there. In order to invoke an instance method, you need to pass the instance reference to Javascript.
How-to
Wrap the onclick="ChangeValueFromJs()" with a C# delegate that will pass this component as a reference to js:

<input type="button" value="Change value"
    onclick="ChangeValueFromJs()"
    @onclick='async (e) => await jsRuntime.InvokeAsync("ChangeValueFromJs", DotNetObjectReference.Create(this))'
/gt;

And then change the js to invoke the instance method in following way:
function ChangeValueFromJs(wrapper)
{
    return wrapper.invokeMethodAsync("invokeFromJS")
        .then(_=>{
            console.log('state has changed');
        });
}

Finally, don't forget to add a StateHasChanged(); to notify the component

[JSInvokable("invokeFromJS")]
public Task ChangeValue()
{
    TestValue = "New value";
    StateHasChanged();
    return Task.CompletedTask;
}

Demo
Answer: You can call Blazor Component method from JS following these steps:
Here is what I did to load new values in my component listPages by using my component method loadListPagesAsync from JS onScroll event.
1- create a reference to your component in JS, I use initdotNetListPageHelperObj function to make a reference to my dotNetListPageHelper
JS:
var dotNetListPageHelperObj;
function initdotNetListPageHelperObj(dotNetListPageHelper){
    dotNetListPageHelperObj = dotNetListPageHelper;
};

2- I call this method when I initialise the component in Blazor:
Blazor code of my component ListPages:
private DotNetObjectReference<ListPages>? dotNetListPageHelper;

protected override async Task OnInitializedAsync()
 {
   dotNetListPageHelper = DotNetObjectReference.Create(this);
JS.InvokeVoidAsync("initdotNetListPageHelperObj", dotNetListPageHelper);
}
public void Dispose()
{
  dotNetListPageHelper?.Dispose();
}

3- make my function Invokable
Blazor code of my component ListPages:
[JSInvokable]
public void loadListPagesAsync(string pageNumIndex)
{
  loadListPages(Int32.Parse( pageNumIndex));
}

4- JS: I call my method by using dotNetListPageHelperObj and I pass a parameter lastPageVisible:
dotNetListPageHelperObj.invokeMethodAsync('loadListPagesAsync', lastPageVisible);

Using this method I can update my Blazor component ListPages and invoke loadListPagesAsync to load new pages related to lastPageVisible
I hope that this will help someone.


jQuery/JavaScript form validation is not working

Question: I am using this code for form validation,
$("#btnaddregistration").live("click", function(e) {
    e.preventDefault();
    var errorCount = 0;
    $("#formaddregistration").find("input").each(function(i) {
        if ($(this).val().length == 0) {
            errorfield = $(this);
            errorCount++;
            $("#modaldialogtext").text("'" + $(this).parent().parent().find("label").text() + "' cannot be left blank.");
            $("#modal_confirmation").dialog("open");
            return false;
        }
    });
    if (errorCount > 0) {
        return false;
    } else {
        document.forms["formaddregistration"].submit();
    }
});

But form is not submitting. I have used all possible submit methods but I failed. Any idea where I am getting wrong?
Comment: Have you tried `$("#formaddregistration").submit()` yet?  You have jQuery available after all.
Comment: Do you get any errors in the console section
Comment: Ya man, i have tried $("#formaddregistration").submit(); . It showing that f[a] is not a function. For this code i am getting document.form.formaddregistration.submit is not a function. Even i have return true; But still is not working for me.
Comment: Have you used a debugger? If so, what did you find?
Comment: Please show your HTML.  Also a jsFiddle demo might help.
Comment:

         Name

 Save
Comment: Please amend your answer with the "edit" link.
Comment: http://jsfiddle.net/fy9sz/1/  according to OP's javascript function and html provided in comments
Answer: First, you can improve your code quite a lot, that will help you in troubleshooting.
If the form is not submitting, make sure that the selector is actually working, ie, try something like $form.hide() and see if it hides, to ensure that it's not PEBCAK
var $form = $("#formaddregistration");
$("#btnaddregistration").on("click", function(e) {
    var errorCount = 0;

    $form.find("input").each(function(i) {
        var $this = $(this);
        if ($this.val().length < 1) {
            errorCount++;

            // this line also needs improving..
            $("#modaldialogtext").text("'" + $this.parent().parent().find("label").text() + "' cannot be left blank.");
            $("#modal_confirmation").dialog("open");
            return false;
        }
    });

    if (errorCount < 1) {
        $form.submit();
    }

    return false;
});

Comment: I agree, however, the answers section is just for answers... that's why you're the only one who's posted so far.  Otherwise, we'd have ten answers, each with a different suggestion, guess, or troubleshooting tip.
Comment: See latest comment by OP.  If `$("#formaddregistration").submit();` is not working for him, neither will your solution.
Comment: No, but cleaning up his code should help him to debug more easily. As it is, he fetches the form dom element multiple times, which is a pretty big problem in and of itself
Comment: I just posted a troubleshooting suggestion. If he wants to post a jsfiddle I could take a look. As it is, if you think you can do better, then post an answer yourself, I don't need your pedantry.
Comment: I am not posting a wild guess as an answer.  As just explained, that's not what the answers section is for.


Calculate the position of the end of a rope wrapped around a pulley

Question: I am struggling with a geometry problem, I hope someone more capable than I may be able to point me in the right direction.
I am considering a rope of a known fixed length, wrapped around a pulley of known diameter, with a variable but known position. One end of the rope is connected to a fixed anchor point, and the other end of the rope is constrained to a track that is horizontal, and its position is determined by the fixed length of the rope (under tension) and the pulley position.
i.e. I am trying to calculate the red dimension in the top image. See the below two images, the first a simple representation of the problem, and the second an annotated diagram to provide some labels for discussion.

I can calculate the position of $(x_5, y_5)$ as follows:
$$b = \sqrt{(x_2-x_1)^2+(y_2-y_1)^2} $$
$$c = r, \quad\text{where } 2r \text{ is the diameter of the pulley}$$
$$\hat{C} = \sin^{-1}(\frac{c}{b})$$
$$x_5 = b*\sin\left(\tan^{-1}\left(\frac{y_2-y_1}{x_2-x_1}\right)-\hat{C}\right) $$
$$y_5 = b*\cos\left(\tan^{-1}\left(\frac{y_2-y_1}{x_2-x_1}\right)-\hat{C}\right) $$
However, I am then stuck as to what to do next as both the length of the arc of rope wrapped around the pulley and the remaining straight length of pulley (between $\left(x_3,y_3\right)$ and $\left(x_4,y_4\right)$) are unknown.
Is it possible to set up a series of simultaneous equations that can arrive at an arc length or something similar from which the solution can be derived? (not my forte!). The dimensions in the diagrams are completely arbitrary, but can be used to test any solution - the diameter of the circle is 74.13, and the length of the rope is 821.14.
Edit
So I have attempted to do as suggested by @intelligenti pauca below:
$$ e = sqrt((x_3 - x_2)^2 + (y_3 - y_2)^2) $$
$$ \hat{F} = asin(f/e) $$
$$ x_4 = b*sin((tan^{-1}((y_3 - y_2)/(x_3 - x_2)) - \hat{F})) $$
$$ y_4 = b*cos((tan^{-1}((y_3 - y_2)/(x_3 - x_2)) - \hat{F})) $$
$$ d = sqrt((x_4 - x_3)^2 + (y_4 - y_3)^2) $$
$$ s = \frac{r*\pi}{180}*(tan^{-1}((y_3 - y_4)/(x_3 - x_4))-tan^{-1}((y_3 - y_2)/(x_3 - x_2))) $$
The above can be substituted into each other and the below equation.
$$ L = a + d + s $$
Then is it just a case of trying numerical guesses using something like Newton–Raphson?
Comment: Compute $d$ and $(x_4, y_4)$ in the same way, as a function of $x_3$. You can then also compute the length $s$ of the arc between $(x_4, y_4)$ and $(x_5, y_5)$. Equating $a+d+s$ to the known length of the rope will give you an equation to solve (numerically, I'm afraid) for $x_3$.
Comment: In order to make a test case out of the dimensions mentioned in your problem statement, we need to know the rope length. Can you please let us know the rope length for the scenario depicted in your diagram.
Comment: Ah yes, sorry I ommited those details orignally because I had hoped there would be an algebraic solution. I have edited the main post with the additional measurements.
Comment: Here is the answer to the question posed at the end of the edited section of your problem statement. Yes, that is exactly what @Intelligentipauca wanted you to do. I have already derived the Newton–Raphson formula and wanted to test it. That is why I asked for the length of the rope in my previous comment. Since you have also done the same, you can test your formula using the guess $x_3 = \cfrac{x_1+x_5}{2}$.
Answer:
Since the provided diagram is amply annotated, we decided to describe very concisely the calculation steps necessary to determine the horizontal distance $x_3$, which is the only unknown length. For brevity, let $z = x_2 – x_3$ and $y=y_3 - y_2$. Furthermore, to keep thing short and simple, we also assume $\left(x_1, y_1\right) =  \left(0, 0\right)$.
$$l_\mathrm{r} = AH+HG+GB=a+h+d \qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\quad\space\space$$
$$b^2 =x_2^2 + y_2^2 \qquad\qquad\qquad\qquad\qquad\qquad\qquad\space\text{Pythagoras theorem applied to }\triangle OPA \space$$
$$a^2 = b^2 – r^2 = x_2^2 + y_2^2 – r^2 \qquad\qquad\qquad\qquad\quad\text{Pythagoras theorem applied to } \triangle AHO$$
$$c^2 = z^2 + y^2 \qquad\qquad\qquad\qquad\qquad\qquad\qquad\space\space \text{Pythagoras theorem applied to } \triangle BQO  $$
$$d^2 = c^2 – r^2= z^2 + y^2 – r^2 \qquad\qquad\qquad\qquad\quad\text{Pythagoras theorem applied to } \triangle OGB $$
$$\theta = \tan^{-1}\left(\frac{a}{r}\right) = \tan^{-1}\left(\frac{\sqrt{x_2^2 + y_2^2 – r^2}}{r}\right) \qquad\text{right angled } \triangle AHO\qquad\qquad\qquad\qquad $$
$$\omega = \tan^{-1}\left(\frac{y_2}{x_2}\right) \quad\qquad\qquad\qquad\qquad\qquad\qquad\text{right angled } \triangle OPA \qquad\qquad\qquad\qquad\space$$
$$\varphi= \tan^{-1}\left(\frac{y}{z}\right)  \qquad\qquad\qquad\qquad\qquad\qquad\quad\quad\text{right angled } \triangle BQO \qquad\qquad\qquad\qquad\space $$
$$\beta = \tan^{-1}\left(\frac{d}{r}\right) = \tan^{-1}\left(\frac{\sqrt{z^2 + y^2 – r^2 }}{r}\right) \qquad\space\text{right angled }\triangle OCB \qquad\qquad\qquad\qquad\space$$
$\small{\measuredangle GOH =}$ $2\pi - \theta - \omega - \phi - \beta$
$$\qquad\space {\small{=}\space} 2\pi - \tan^{-1}\left(\frac{\sqrt{x_2^2 + y_2^2 – r^2}}{r}\right) -\tan^{-1}\left(\frac{y_2}{x_2}\right) -\tan^{-1}\left(\frac{y}{z}\right) - \tan^{-1}\left(\frac{\sqrt{z^2 + y^2 – r^2 }}{r}\right)$$
$$h = r\left\{ 2\pi - \tan^{-1}\left(\frac{\sqrt{x_2^2 + y_2^2 – r^2}}{r}\right) -\tan^{-1}\left(\frac{y_2}{x_2}\right) ) -\tan^{-1}\left(\frac{y}{z}\right) - \tan^{-1}\left(\frac{\sqrt{z^2 + y^2 – r^2 }}{r}\right)\right\}$$
$\space l_\mathrm{r} = \sqrt{x_2^2 + y_2^2 – r^2} + \sqrt{z^2 + y^2 – r^2 }+$
$$r\left\{2\pi - \tan^{-1}\left(\frac{\sqrt{x_2^2 + y_2^2 – r^2}}{r}\right) -\tan^{-1}\left(\frac{y_2}{x_2}\right) ) -\tan^{-1}\left(\frac{y}{z}\right) - \tan^{-1}\left(\frac{\sqrt{z^2 + y^2 – r^2 }}{r}\right) \right\}\tag{1}$$
You need to solve this behemothian nonlinear equation to determine the value of $x_3$. One needs to resort to numerical methods, such as Newton-Raphson method, to do that. So let's begin.
Using (1), we define the function $f\left(z\right)$ as shown below.
$f\left(z\right)=\sqrt{x_2^2 + y_2^2 – r^2} + \sqrt{z^2 + y^2 – r^2 }-l_\mathrm{r} +$
$$\quad\quad r\left\{2\pi - \tan^{-1}\left(\frac{\sqrt{x_2^2 + y_2^2 – r^2}}{r}\right) -\tan^{-1}\left(\frac{y_2}{x_2}\right) ) -\tan^{-1}\left(\frac{y}{z}\right) - \tan^{-1}\left(\frac{\sqrt{z^2 + y^2 – r^2 }}{r}\right) \right\}$$
The corresponding Newton-Raphson formula is given by
$$z_{i+1} =z_i - \frac{f\left(z_i\right)}{ f'\left(z_i\right)}\quad\text{with}\quad z_0 = \frac{x_2}{2},$$
$$\text{where}\qquad f'\left(z\right)=\frac{z\sqrt{z^2 + y^2 – r^2 }+ry}{z^2 + y^2}.\qquad\qquad\qquad\qquad$$
For the purpose of testing a case proposed by OP, we implemented an iteration procedure using the aforementioned Newton-Raphson formula in an MS-Excel worksheet. This sheet is available for downloading at DropBox. However, we provide this sheet without implying in any way that data and formulae given in it are free of errors. Therefore, if anybody decides to use the results obtained from those data and formulae, that person should do it at his or her own risk.
As you can see, the procedure converges very quickly (i.e. in four iteration steps) to the answer partly thanks to the educated guess we used to start the process. Interested parties can enter data depicting other cases in respective cells with yellow background to verify themselves whether this set of equations and the method are useful or not.


Show continuous functions need not be open maps and open maps need not be continuous.

Question: A function from one metric space to another is said to be an open map
if it maps open sets to open sets. Similarly one can define a closed
map.

1-Provide a continuous function which does not map an open set to another open set?
2- Provide a function which maps every open set to another one but it is not a continuous function?
Answer: For 1) take a constant function and let it be that singletons in the codomain are not open.
For 2) take the identity $\mathbb R\to\mathbb R$ where codomain is discrete (so $d(x,y)=0$ if $x=y$ and $d(x,y)=1$ otherwise) and domain is not discrete.
Comment: For 1) You mean the range of the constant function be singletons? Then how it can be constant? Could you explain it or represent is using $f: X \rightarrow Y$?
Comment: Every constant function is continuous. If $U$ is an open subset of $Y$ and $f$ is prescribed by $x\mapsto c$ where $c$ is an element of $Y$ then $f^{-1}(U)=\varnothing$ (this if $c\notin U$) or $f^{-1}(U)=X$ (this if $c\in U$). The sets $\varnothing$ and $X$ are always open. Further open set $U$ is sent to the not open set $\{c\}$ (provided that singletons in $Y$ are not open).
Answer: A) To violate openness you can give any map which is not bijective.
B) Open maps which are not continuous


Proving surjectivity of $\cos(z)$ and $\sin(z)$ and find all $z : \cos(z) \in \mathbb R$ and all $z: \sin(z) \in \mathbb R$

Question: I am trying to solve the following two problems:
1) Prove that the functions $\cos(z)$, $\sin(z)$ are surjective over the complex numbers.
2) Find all $z \in \mathbb C$: $cos(z) \in \mathbb R$ and find all $z \in \mathbb C$: $\sin(z) \in \mathbb R$.
For 1),I've tried to prove it for the function $\cos(z)$ (I suppose the other one is analogue)  so I've used the fact that $\cos(z)=\dfrac{e^{iz}+e^{-iz}}{2}$.
Let $w \in \mathbb C$, I want to show there exists $z \in \mathbb C : f(z)=w$, i.e., $\dfrac{e^{iz}+e^{-iz}}{2}=w$, multiplying by $2$ and then by $e^{iz}$ yields $e^{2iz}+1=2we^{iz}$ iff $e^{2iz}-2we^{iz}+1=0$.
I don't know if this approach is the correct one but here I've replaced $e^{iz}$ by $x$, so the solutions of the equation would be the roots of the polynomial $p(x)=x^2-2wx+1$, by the quadratic formula, I get that $x \in \{\dfrac{2w+w_0}{2},\dfrac{2w-w_0}{2}\}$, where $w_0^2=4w^2-4$.
Then, $e^{iz} \in \{\dfrac{2w+w_0}{2},\dfrac{2w-w_0}{2}\}$. At this point I got lost, I would like to explicitly show that $z$ exists and I can't see existence directly from the fact that $e^{iz}=\dfrac{2w+w_0}{2}$ or $e^{iz}=\dfrac{2w-w_0}{2}$.
First I thought of taking logarithm of both sides of the equation ir order to solve for $z$, but this is not a legitimate operation unless $e^{iz} \in \mathbb R$.
I couldn't go any farther.
For point 2) I have no idea what to do, should I use the identity $\cos(z)=\dfrac{e^{iz}+e^{-iz}}{2}$?
I would appreciate some help with the two points (specially with point 2), at least in 1) I could do something).
Btw, Happy new year!
Comment: Do you know that $e^z$ is surjective except at $0$?
Answer: 1) Note that one of $\frac{2w+w_0}{2}, \frac{2w-w_0}{2}$ must be nonzero, and that $e^{iz}$ achieves all values except $0$, since for any $re^{i\theta}\in \Bbb C$ we have
$re^{i\theta}=e^{i(\theta-i\ln r)}$
thus we have some $z$ such that $e^{iz}=\frac{2w+w_0}{2}$ or $e^{iz}=\frac{2w-w_0}{2}$.
2) If we write $z=x+iy$ then
$$\cos(z)=\frac{e^{ix-y}+e^{-ix+y}}{2}=\frac{e^{-y}e^{ix}+e^y\overline{e^{ix}}}{2}$$
which has conjugate
$$\frac{e^{-y}\overline{e^{ix}}+e^ye^{ix}}{2}$$
so $\cos(z)$ is real iff
$$e^{-y}e^{ix}+e^y\overline{e^{ix}}=e^{-y}\overline{e^{ix}}+e^ye^{ix}.$$
If $e^{ix}$ is real then $x=n\pi$ for some $n\in\Bbb N$. Otherwise $e^{ix}$ and $\overline{e^{ix}}$ are linearly independent over $\mathbb R$, so $e^{-y}=e^y$ thus $y=0$.
The case of $\sin$ is similar for both problems.
Comment: Note that both solutions to the quadratic equation are non-zero, whether they coincide or not. So we get "double" the number of solutions when $w \not\in \{1,-1\}$.
Comment: Hi just wondering how you got the last part of the proof. I get that $cos(z) $ must be equal to the conjugate but cannot see how from that you got $x=np$ i tried to simplify and did however get $y=0$ thanks in advance.
Answer: The complex logarithm is indeed what you can do when you have $e^z$ and you want to get $z$. As you did, the quadratic equation always has at least one solution (repeated if $w \in \{1,-1\}$). Choosing any of them, we only have to "take logs" of $e^{iz} = a$ for some $a \ne 0$ which you have to check. Now $e^{x+yi} = e^x \cdot e^{iy}$ (length times angle) and so we can represent any non-zero complex number as $e^{x+yi}$ for some $(x,y)$ (possible values of $y$ repeating every $2\pi$). This also shows how to get the exact solution set.
Finally, $\sin$ can as you guessed be solved analagously but you can also use the identity involving $\sin$ and $\cos$ being "translations" of one another.
Answer: \begin{align}
\sin z & = w \\[10pt]
e^{iz} - e^{-iz} & = 2iw \\[10pt]
u - \frac 1 u & = 2iw \\[10pt]
u^2 - 1 & = 2uiw \\[10pt]
u^2 - 2iw u - 1 & = 0
\end{align}
This is the quadratic equation $au^2 + bu + c=0$ with $a=1,$ $b=-2iw,$ $c= - 1.$ It solutions are
$$
u = \frac{-b \pm \sqrt{b^2-4ac}}{2a} = \frac{2iw \pm \sqrt{-4w^2 + 4}} 2 = iw \pm \sqrt{1-w^2}.
$$
Once you have $u,$ you have $e^{iz} =u.$ There are infinitely many values of $z$ making this true.


Unique AngularFire calls in Angular template functions

Question: I'm using AngularFire and have an ng-repeat list with items that contain data specific to the "author" of that item (multiple users can add to the list), such as name, location, etc. I'm not writing that data into the array being iterated over by ng-repeat since it could change in the future. Instead, that author-specific data is store in a different location so the goal is that if the author changes their information, all of it is reflected in the list.
For a contrived example, imagine I'm iterating over a list of books from different authors. That list will contain the book-specific data (such as title, publish date, etc.) but I will also want to display the author's information in the list. Instead of including the author's information directly within the book data, I want to simply reference that author ID, and pull in whatever data is in their profile so if they change their name, it'll reflect the changes in all of their book listings.
That means I'm left to make async calls to Firebase to retrieve that information for each list item via a template function, such as {{getAuthorName(authorId)}}. The only problem is that they're async calls and the template function evaluates before the data is available.
I've looked into how to accomplish but have yet to find a solution that accommodates what I need. The answers here seem close, but they appear to no longer work in Angular >= 1.2.0 and they don't account for having to return different data for each template function call.
Update
Here is a JSFiddle with what I have now. I've made some progress, but all that's being returned now is the promise object as expected. I'm not sure how to implement .then in this scenario to get the actual value.
Any help would be great.
Comment: Can you please paste what you've tried? Or create a jsFiddle/plunkr demonstrating the problem?
Answer: You can make use of $firebaseObject and then store that in an object to make sure it doesn't get hit again. like so:
var authors = {};

$scope.getAuthorName = function(authorId){
    if(!authors[authorId]){
        var authorRef = new Firebase(fburl + "/authors/" + authorId);
         authors[authorId] = $firebaseObject(authorRef);
    }
    return authors[authorId];
};

You can see the working fiddle here: http://jsfiddle.net/0rcdpq47/
Comment: Yep. See also the userCache service is [this fiddle](http://jsfiddle.net/katowulf/vspo65qm/)
Comment: Thanks both of you! @Kato I see your normalizing script hasn't been updated for AngularFire 1.x so I've gone through and made the necessary changes to make it compatible (from what I can see), but the original post list is being returned instead of the postData + userData. Ideas? I'm afraid I'm still missing something that needs to changed for AngularFire 1.x.
Comment: The userCache service would require changing exactly one line of code $firebase(ref).$asObject() to $firebaseObject(ref).
Comment: @Kato I'm afraid that's not correct, unless I'm not understanding something. Making the change you mentioned on line 66 of the fiddle still results in a few errors: `FirebaseArray.$extendFactory` is not a function on line 13 (guessing it needs to be `$firebaseArray.$extend`?) and `$firebase(ref).$asArray()` needs to be changed to `$firebaseArray(ref)` on line 25. Still after those additional changes (what ends up being the fiddle I linked to), I don't get the merged data.


Deixar submenu na largura do container

Question: Como deixar o submenu (dropdown) dentro da largura do container?
Onde tem a div com a classe: class="navbar-collapse collapse" coloquei (position: relative), deu certo porém o link do logo não funciona não é clicável.
Veja o link: http://wsnippets.com/demo/bootstrap-mega-menu/
Assim é o padrão do script: pasteboard.co/12NtG7PEO.png Mas gostaria que ficasse assim: pasteboard.co/12QapxzIV.png que o submenu não ficasse com a largura completa na tela.
Answer: Não sei se entendi bem sua pergunta. Mas pelo que pude ver nesse seu exemplo, o que está deixando o submenu do tamanho do container é a classe .megamenu:
 div.navbar-collapse.collapse > ul > li.dropdown.menu-large.open > ul.megamenu

.megamenu {
    padding: 20px 0px;
    width: 100%;
}

Comment: Assim é o padrão do script: http://pasteboard.co/12NtG7PEO.png Mas gostaria que ficasse assim: http://pasteboard.co/12QapxzIV.png que o submenu não ficasse com a largura completa na tela.
Answer: Adiciona um conteiner após o

          ...

          ...

Comment: Assim é o padrão do script: http://pasteboard.co/12NtG7PEO.png Mas gostaria que ficasse assim: http://pasteboard.co/12QapxzIV.png que o submenu não ficasse com a largura completa na tela.

Deixar submenu na largura do container


Regular Expression to Remove Subdomain from Root Domain in List - Notepad++ or Gvim

Question: I have a list of URLs stored in a .txt file (I'm using Windows 7).
The format of the URLs is this:
somesite1.com
somesite2.com
somesite3.com
sub1.somesite3.com
sub2.somesite3.com
sub3.somesite3.com
sub1.somesite3.net
sub1.somesite1.org

In notepad++, there is an option to use "find-replace with regular expressions", and I'm fairly sure that gvim allows the user of regular expressions (although I'm not entirely sure how to use them in Gvim).
Anyway, I don't know what to put in the find & replace boxes so it can go through the contents of the file and leave me with only the root domains.  If done properly, it would turn the above example list into this:
somesite1.com
somesite2.com
somesite3.com
somesite3.com
somesite3.com
somesite3.com
somesite3.net
somesite1.org

Can somebody help me out?
Answer: A couple of ways of doing it for Vim (the trailing slashes are optional, too):
:%s/^.\+\.\ze[^.]\+\.[^.]\+$//
:%s/^.\+\.\([^.]\+\.[^.]\+\)$/\1/

See also :help /\ze etc. \ze and \zs are Vim-specific and very useful. There are also look-ahead and look-behind assertions which can be useful, in Vim and PCRE.
I believe Notepad++ uses PCRE; find ^.+\.([^.]+\.[^.]+)$ and replace it with \1 should work (but I don't use Notepad++).
Be aware this won't work well with country code top level domains which use third-level registration - example.com.au would be turned into com.au. And then there are some countries which use second- or third-level registration under certain rules... if you care about those cases, you'll need more rules and a full parser would be neater than a regular expression (though as always it would be possible with regular expressions).
Answer: Replace ^[^.]*\.(?=\w+\.\w+$) with <blank>
Deciphered, this means:

^ = start of line
[^.]* = any number of chars that are not a dot
\. = a dot
(?=[^.]+\.[^.]+$) = there must be exactly one word, one dot then one word from here to the end

EDITED - Added look ahead for another dot
EDITED AGAIN - Changed look ahead for exactly one dot between words
Comment: Eek!  `somesite1.com` -> `com`?  Time to rethink.
Comment: @Chris - nice pickup. thanks. I fixed it with the look-ahead (i think!)
Comment: There are a few quirks of look-ahead and look-behind assertions (especially with negative assertions—annoying things, those, considering how useful they should be) so I personally avoid them if at all possible through using real groups and/or `\zs`/`\ze` in Vim.
Comment: This will still turn `sub.sub.example.com` into `sub.example.com`, rather than `example.com` which is what's desired (though Robert gave no indication that he will run across fourth-level domains, it's a possibility and quite valid).
Comment: I want to use your code in mysql but I got this problem: "MySQL uses Henry Spencer's implementation of regular expressions, which is aimed at conformance with POSIX 1003.2" Any chance you can find solution without "?"
Comment: @Ilya_Gazman sure. I assume since MySQL doesn't support regex replace that your need is a little different and you want to *match*, but you haven't said exactly what. I'll take a guess it's "word.word.word", so try `\w+\.\w+.\w+`. If it's something else, let me know what.
Comment: May be I didn't understood the OP question, but in my case its: "a(1).a(2).a(3).a(4)...a(n-1).an" and I want to match "a(1).a(2).a(3).a(4)...a(n-2)." so I can replace it with empty string and get the true domain result: "a(n-1).a(n)". Tell me if you understand OP question differently, in such case I will ask a new one
Comment: @ilya are you able to use back references in your replacement?
Comment: I can't test in the moment, only on sunday. So far I only had problems with the question mark
Answer: Replace whole of line to Last word and previous word of one.
%s/^.*\.\(\w\+\.\w\+\)$/\1/g

Note that vim require \,(,) for + like \+
UPDATE:
%s/^.*\.\([0-9a-z\-]\+\.[0-9a-z\-]\+\)$/\1/g

is better maybe.
Comment: `\w` won't cut it: `-` is valid in domain names.
Comment: i just tried to use this. and realized that there is a special case with some tlds in some countries, e.g .co.uk


Fast Evaluation of a Double Sum

Question: Let

$q$ be a probability distribution on $\mathcal{X}$,
$w$ be a nonnegative function from $\mathcal{X}$ to $\mathbf{R}$ which is bounded away from $0$ and $\infty$, and
$s$ be a bounded function from $\mathcal{X}$ to $\mathbf{R}_+$ with mean $0$ under $q$

I am interested in unbiased estimation of the following quantity:
\begin{align}
\gamma = \int_{\mathcal{X}^N} \left( \prod_{i = 1}^N q (x_i)\right) \cdot \frac{w(x_1)}{\sum_{i = 1}^N w(x_i)} \cdot s(x_1) \, dx_{1:N}
\end{align}
given $(N + 1)$ iid samples from $q$, where $N$ is a positive integer.
Now, given that $s$ has mean $0$ under $q$, I can actually rewrite this expression in terms of a covariance, i.e. define
\begin{align}
W ( x_1 | x_{2:N} ) = \frac{w(x_1)}{\sum_{i = 1}^N w(x_i)},
\end{align}
then
\begin{align}
\gamma = \int_{\mathcal{X}^{N - 1}} \left( \prod_{i = 2}^N q (x_i)\right) \cdot \text{Cov}_{q(x_1)} \left( W ( x_1 | x_{2:N} ), s(x_1) \right) \, dx_{2:N}
\end{align}
Given samples $x_{0:N}$, one can then form an unbiased estimator of the inner covariance as
\begin{align}
\hat{c} (x_0, x_1 | x_{2:N} ) \triangleq \frac{1}{2}  \left\{ W ( x_0 | x_{2:N} ) - W ( x_1 | x_{2:N} ) \right\} \cdot \left\{ s(x_0) - s(x_1) \right\},
\end{align}
and so one can form an overall estimator by re-using this estimator for all splits of the data, i.e.
\begin{align}
\frac{1}{N(N+1)} \sum_{i = 0}^N \sum_{j = 0}^N \hat{c} (x_i, x_j | x_{0:N \setminus \{i, j\} } ).
\end{align}
Unfortunately, naive evaluation of the above sum costs $\mathcal{O} \left( N^2 \right)$, which is more expensive than I would like. My question is thus: can one simplify this sum such that it can be evaluated exactly in time $\mathcal{O} \left( N \right)$?
One reason why I suspect that this may be possible is that $\hat{c}$ can be re-written as
\begin{align}
\hat{c} (x_i, x_j | x_{0:N \setminus \{i, j\} } ) = \frac{1}{2}  \left\{ \frac{w (x_i)}{W - w (x_j)} - \frac{w (x_j)}{W - w (x_i)} \right\} \cdot \left\{ s(x_i) - s(x_j) \right\},
\end{align}
where $W = \sum_{i = 0}^N w (x_i)$, which may be able to simplify some things.
Comment: The term $W(x_1|x_{2:N})\times s(x_1)$ is an unbiased estimator of $\gamma$.
Comment: @Xi'an indeed! My aim is not just to construct an unbiased estimator, but to construct one which i) uses the knowledge that $s$ is mean-0 to reduce variance, ii) uses the full information of all of the samples which I have generated, and iii) can be evaluated quickly.

The single-term estimator satisfies only iii), as it has cost $\mathcal{O} \left( N \right)$.

A mid-way point would be to use

$$ \frac{1}{N+1} \sum_{i = 0}^N \hat{c} (x_i, x_{i+1} | x_{0:N \setminus \{i, i + 1 \} } )$$

(interpreting indices $\mod (N+1)$), which also costs $\mathcal{O} \left( N \right)$ to form.
Answer: I think that the following should work: re-write
\begin{align}
\hat{c} (x_i, x_j | x_{0:N \setminus \{i, j\} } ) &= \frac{1}{2}  \left\{ \frac{w (x_i)}{W - w (x_j)} - \frac{w (x_j)}{W - w (x_i)} \right\} \cdot \left\{ s(x_i) - s(x_j) \right\} \\
&= \frac{1}{2}  \left\{ \frac{1}{W - w (x_j)} \cdot \left[ w(x_i) \cdot s(x_i) \right] + \frac{1}{W - w (x_i)} \cdot \left[ w(x_j) \cdot s(x_j) \right] \right\} \\
&-  \frac{1}{2}  \left\{ \frac{s(x_j)}{W - w (x_j)} \cdot w(x_i) + \frac{s(x_i)}{W - w (x_i)} \cdot w(x_j) \right\}
\end{align}
which allows for the reformulation
\begin{align}
\hat{\gamma} &\triangleq \frac{1}{N(N+1)} \sum_{i = 0}^N \sum_{j = 0}^N \hat{c} (x_i, x_j | x_{0:N \setminus \{i, j\} } ) \\
&= \frac{1}{N(N+1)} \sum_{i = 0}^N \sum_{j = 0}^N \left\{ \frac{1}{W - w (x_j)} \cdot \left[ w(x_i) \cdot s(x_i) \right]  \right\} \\
&- \frac{1}{N(N+1)} \sum_{i = 0}^N \sum_{j = 0}^N \left\{ \frac{s(x_j)}{W - w (x_j)} \cdot w(x_i) \right\} \\
&= \frac{N+1}{N} \cdot \left\{ \overline{\frac{1}{W - w}} \cdot \overline{ws} - \overline{\frac{s}{W-w}} \cdot \overline{w} \right\}
\end{align}
where
\begin{align}
\overline{\frac{1}{W - w}} &\triangleq \frac{1}{N+1} \sum_{i = 0}^N \frac{1}{W - w (x_i) } \\
\overline{ws} &\triangleq \frac{1}{N+1} \sum_{i = 0}^N w(x_i) s(x_i) \\
\overline{\frac{s}{W-w}} &\triangleq \frac{1}{N+1} \sum_{i = 0}^N \frac{s(x_i)}{W - w(x_i)} \\
\overline{w} &\triangleq \frac{1}{N+1} \sum_{i = 0}^N w(x_i)
\end{align}
which suggests that the whole estimator can be computed in time $\approx 4N = \mathcal{O} \left( N \right)$, noting that $\overline{w} = \frac{W}{N + 1}$ does not need to be re-computed.
Some additional manipulations reveal that this estimator can be written as
\begin{align}
\hat{\gamma} &= \left\{ \frac{1}{N+1} \sum_{i = 0}^N \frac{1}{W - w(x_i)} \right\} \cdot \left\{ \frac{1}{N} \sum_{i = 0}^N \left( s(x_i) - \overline{s} \right) \cdot \left( w(x_i) - \overline{w} \right) \right\} \\
&- \left\{ \frac{1}{N} \sum_{i = 0}^N \left( \frac{1}{W - w(x_i)} - \overline{\frac{1}{W - w}} \right) \cdot \left( s(x_i) - \overline{s} \right) \right\} \cdot \left\{ \frac{1}{N+1} \sum_{i = 0}^N w(x_i)  \right\}
\end{align}
which may suggest implementations of this estimator which achieve improved numerical stability.

Fast Evaluation of a Double Sum


send data to a new jsp when user click on a div

Question: <form action="" method="get" enctype="application/x-www-form-urlencoded">

Current Users

    <c:if test="${!empty pagedListHolder}">

Name

Email

Last Seen

                <c:forEach items="${pagedListHolder.pageList}" var="user">

${user.name}

${user.email}

Last Seen

                </c:forEach>

                <tg:paging pagedListHolder="${pagedListHolder}"
                    pagedLink="${pagedLink}" />

    </c:if>
</form>

Now what i want  is to send data into a new jsp when user click on a div.
How can i do this. please suggest. previously in place of
 i was using , than i was able to do it in this way
<c:forEach items="${pagedListHolder.pageList}"  var="user">

                    ${user.name}
                    ${user.email}
                    ${user.email}

            </c:forEach>

    </c:if>

Now i want same with div. please suggest.
Answer: Your
 needs a handler for clicks like your
 had:
Solution:


Understanding crash log "this may be a leak"

Question: My app sometimes throws strange log like:
: notify name "com.apple.iapd.notify.extendedMode" has been registered 40 times - this may be a leak
: notify name "com.apple.iapd.notify.extendedMode" has been registered 100 times - this may be a leak
: notify name "com.apple.iTunesStore.daemon.launched" has been registered 1700 times - this may be a leak
and repearts many times.
I could not find out googling that.
Please help.
Thanks!
Kostia.
Answer: I have the same message when launching multiple background downloads through newsstand. But it works.


PatternSyntaxException using apache poi

Question: I am using Apache POI in two different projects
The first project is a standalone Java application. Everything is fine here.
The second project is an Android project. I can access the Workbook of an xlsx just fine, but when it comes to evaluating formulas, it crashes with an Exception
java.util.regex.PatternSyntaxException: U_ILLEGAL_ARGUMENT_ERROR \P{IsL}
   at java.util.regex.Pattern.compileImpl(Native Method)
   at java.util.regex.Pattern.compile(Pattern.java:411)
   at java.util.regex.Pattern.<init>(Pattern.java:394)
   at java.util.regex.Pattern.compile(Pattern.java:381)
   at org.apache.poi.ss.formula.functions.TextFunction$5.<init>(TextFunction.java:124)
   at org.apache.poi.ss.formula.functions.TextFunction.<clinit>(TextFunction.java:123)

This is the code line in question:
    final Pattern nonAlphabeticPattern = Pattern.compile("\\P{IsL}");

Why does Android not accept this? As I said: It's working fine on a standalone Java application ....
Comment: Android is using ICU regex library, Java has its own ICU-based regex. See [*this*](https://developer.android.com/reference/java/util/regex/Pattern.html#gnumber): *Unicode scripts, blocks, categories and binary properties are written with the `\p` and `\P` constructs as in Perl. `\p{prop}` matches if the input has the property prop, while `\P{prop}` does not match if the input has that property.*
Comment: Use `final Pattern nonAlphabeticPattern = Pattern.compile("\\P{L}");`
Comment: Isn't `\\P{IsL}` a perfectly legal pattern? According to Oracle, it is `Categories may be specified with the optional prefix Is: Both \p{L} and \p{IsL} denote the category of Unicode letters. Same as scripts and blocks, categories can also be specified by using the keyword general_category (or its short form gc) as in general_category=Lu or gc=Lu.`
Comment: Don't get me wrong ... I would change it if I could. It is part of apache poi code from their library
Comment: Do you mean you cannot change the pattern?
Comment: At least I don't know how ... I'd have to recompile the apache poi code, wouldn't I?
Comment: Sorry, can't help more.
Answer: Android is using ICU regex library that is a bit different from Java regex engine.
See this reference:

Unicode scripts, blocks, categories and binary properties are written with the \p and \P constructs as in Perl. \p{prop} matches if the input has the property prop, while \P{prop} does not match if the input has that property.

Thus, the pattern should be written as
Pattern nonAlphabeticPattern = Pattern.compile("\\P{L}");

Comment: In POI trunk we now have rewritten the PROPER function to not use regular expressions at all and also fixed a few cases where the method did behave incorrectly, e.g. on some accented characters, see https://github.com/apache/poi/commit/aec95a44918e5331f0d3a746202c713bc8ac6aad
Comment: Thank you. I managed to do it. I recompiled the apache poi sources and replaced the jar for my project. Et voilà

PatternSyntaxException using apache poi


How many solutions does this equation have xyz + yvv = xxzy?

Question: Given the following equation:
xyz + yvv = xxzy

where all numerical digit replaced by letters (x, y, z and v). How many solutions does this equation have, if all numbers matches different letters?
I have found only one solution:
194 + 955 = 1149

But, I think, that there is some trick in this task. And there is more than one solution
Answer: Hint: note if $xyz + yvv = xxzy$ for digits, then: $$100x + 10y + z +100y + 11v = 1100x + 10z + y$$ This reduces to $$11v = 1000x + 9z - 109y$$ Now, reducing this modulo 11 gives: $$ 0 = y-x-2z \pmod{11}$$ Can you continue from this - note that since we are summing two $3$ digit numbers (I assume $x$ isn't $0$) our number $xxzy$ will definitely be less than $2000$, this means $x$ must be.....? From this value of $x$, what value must $y$ take since if $y<8$ what do you know about the left hand side of your equation....?
Answer: For sure you can just brute force it with for example mathematica which would look like
Count[
      Flatten[
            Table[
                  TrueQ[
    x*100 + y*10 + z + y*100 + v*10 + v*1 == x*1100 + z*10 + y],
    {x,0, 9}, {y, 0, 9}, {z, 0, 9}, {v, 0, 9}]],
      True]
which gives 2 as an answer. But with some thinking you don't need to check every case, because we have something like $a+b=c$ where we know that $a$ and $b$ are strictly smaller than $1000$, so the only possible cases for $x$ are $0$ or $1$.
If $x=0$ for the very same reason it follows that $y=0$ so we got the equation
$z+v\cdot 11= z\cdot 10$. If we now check how often both sides to have $2$ as a factor we see, that $z$ must be odd and $v$ must be even.
Furthermore we check this equation modulo $5$ which yields
$z+v=0 \mod 5$.
Now there aren't that many cases left in special we only need to check the cases $z=1$ and $z=3$ because in the other cases $v$ will be to small for the equation to hold.
In the case that $x=1$ you get immediately that $y=9$ for the same reason as above. So the equation is
$190+ z +900+ v\times 11 = 1109 +z\times 10$  which is equivalent to
$$z + v\times 11 = 19 + z \times 10$$
Looking on the equation modulo $2$ yiels
$z+v=1\mod 2$ meaning one of $z,v$ is odd and the other is even. Similar arguments show that your solution is the only nontrivial.


Como pegar o início e fim da semana no Moment.js

Question: Eu uso o seguinte código para pegar o início e o fim da semana.
pegaData() {
    moment().locale();
    var agora;
    var datainicial;
    var datafinal;
    agora = moment().format('DD-MM-YYYY');
    console.log(agora);
    if(agora = 'Thusday'){
        datainicial = moment().subtract(4, 'days').calendar();
        datainicial = moment().format('DD-MM-YYYY');
        datafinal = moment().add(2, 'days').calendar();
        datafinal = moment().format('DD-MM-YYYY');

    }
    console.log(datainicial);
    console.log(datafinal);
}

E o código retorna certo a data inicial e final, só que não no formato que eu preciso, que seria 'DD-MM-YYYY'.
Mas no momento da conversão, como eu chamo o moment novamente, ele converte a data atual. Como eu posso formatar a data sem chamar o moment novamente?
Answer: Se quer mudar o dia da semana, basta usar o método day, passando um valor entre zero (domingo) e 6 (sábado):

let agora = moment();

let inicio = moment().day(0); // domingo desta semana
let fim = moment().day(6); // sábado desta semana

// imprimir as datas no formato desejado
let formato = 'DD/MM/YYYY';
console.log('agora=', agora.format(formato));
console.log('início=', inicio.format(formato));
console.log('fim=', fim.format(formato));

Assim você não precisa ficar fazendo vários testes, como estava fazendo ("se hoje é quinta, soma 2 dias, etc").
Depois você atribui o resultado de cada um em uma variável e usa format para mostrá-las no formato desejado.
No código acima, como hoje é 30/05/2019, então o valor inicial será 26/05/2019, e o valor final será 01/06/2019.
Comment: Muito obrigado man, onde vi sobre o moment.js não tinha o método day, muito obrigado por me mostrar ele, ajudou demais!!!!


Linear Algebra Matlab matrix loop?

Question: I'm new to both linear algebra and Matlab, so naturally I'm probably asking an obvious question. If someone could attempt to explain to me in layman's terms how to go about answering this question in Matlab it'd be great, thanks in advance.
Comment: This September was the first time I've used it, other than this my only other coding experience is some html webpage writing
Comment: how new are you to matlab?
Answer: Loops are for suckers.
function x_new = matrix_recursion(A, endp, x_start)
 if (endp == 0)
  x_new = x_start
 else
  x_new = matrix_recursion(A, endp-1, A*x_start);
 end
I don't have MatLab on this computer so I can't test it, but it should work fine.
Comment: it actually didn't, got an error about how function is not permitted
Comment: What exactly did it say?
Comment: function x_new = matrix_recursion(A, end, x_start)
 |
Error: Function definitions are not permitted in this
context.
Comment: Are you entering it in the interactive shell? This is supposed to be saved as a script matrix_recursion.m and then run
Comment: I just noticed a couple mistakes and edited my answer accordingly. Try it now.
Comment: I'm not sure what you meant by the interactive shell and saving it as a script matrix_recursion.m
Comment: The place where it has the >> on every line and does every command as soon as you press enter is called a shell. You need to save the code in a file called "matrix_recursion.m", then type (for instance) "matrix_recursion([1,0;0,1], 25, [0;1])" into the shell. The first parameter should be the matrix that you actually want to use for A, I put it [1,0;0,1] as an example. If that doesn't work try deleting the entire first line (with the %) and try saving and running it again.

Linear Algebra Matlab matrix loop?


$(x-y)^2+(y-z)^2+(z-x)^2=8$, $x^3+y^3+z^3=1$ what is the Minimum value of $x^4+y^4+z^4$

Question: Given that, for $x, y, z \in \mathbb R,\, $\begin{align}(x-y)^2+(y-z)^2+(z-x)^2&=8\\ x^3+y^3+z^3&=1, \end{align}
find the minimum value of $\;x^4+y^4+z^4$
Comment: How to know that the mentioned conditions are sufficient to find minimum value of $x^4+y^4+z^4$? I think we need to know that the value of $x+y+z$ to proof this question.
Comment: are $$x,y,z$$ real numbers?
Comment: x,y,z are defined in R
Comment: With Lagrange Multipliers method,Somebody has done it
Answer: $1^4+(-1)^4+1^4=3$.
We'll prove that it's a minimal value.
Indeed, let $x+y+z=3u$, $xy+xz+yz=3v^2$, where $v^2$ can by negative, and $xyz=w^3$.
Hence, $$\sum_{cyc}(x-y)^2=8$$ it's
$$\sum_{cyc}(x^2-xy)=4$$ or
$$9u^2-9v^2=4.$$
In another hand, $$1=x^3+y^3+z^3=27u^3-27uv^2+3w^3=12u+3w^3,$$
which gives $v^2=u^2-\frac{4}{9}$ and $w^3=\frac{1}{3}-4u$.
Now, $(x-y)^2(x-z)^2(y-z)^2\geq0$ gives
$$3u^2v^4-4v^6-4u^3w^3+6uv^2w^3-w^6\geq0$$ or
$$3u^2\left(u^2-\frac{4}{9}\right)^2-4\left(u^2-\frac{4}{9}\right)^3-4u^3\left(\frac{1}{3}-4u\right)+6u\left(u^2-\frac{4}{9}\right)\left(\frac{1}{3}-4u\right)-\left(\frac{1}{3}-4u\right)^2\geq0$$ or
$$(1-3u)(9u^2+3u+25)(27u^3+72u+7)\geq0$$ or
$$u_1\leq u\leq\frac{1}{3},$$
where $u_1$ is a real root of the equation $27u^3+72u+7=0$. $u_1=-0.096...$.
But $$x^4+y^4+z^4=81u^4-108u^2v^2+18v^4+12uw^3=$$
$$=3+\frac{1}{9}(1-3u)(27u^3+9u^2+51u+5)\geq3$$
for all $u_1\leq u\leq\frac{1}{3}$ and we are done!
Comment: But when it takes the equal sign,3v^2=xy+xz+yz=-1,that is unpossible
Comment: @lurk lurk $v^2$ can be negative. See third line of my proof.
Comment: you mean v is defined in C?@Michael Rozenberg
Comment: @lurk lurk I mean that $v^2$ can be negative real number. Say me please, why does this bother you?
Comment: Can I replace $v^2$ with v @Michael Rozenberg
Comment: @lurk lurk Yes, of course! But in this case $v$ can be negative and the expression like $\sum\limits_{cyc}(x^2-xy)$ will be equal to $9u^2-9v$ and $x^3+y^2+z^3=27u^3-27uv+3w^3$.
Comment: If $$(a^5-a^3+3)(b^5-b^3+3)(c^5-c^3+3)\ge 3(a+b+c)^2 \quad a,b,c\in\mathbb R. $$ Prove that $a^5-a^3\ge a^2-1$.@Michael Rozenberg
Comment: @Peter Sheldrick $v^2$ is a real number. We work with $v^2$ only.

$(x-y)^2+(y-z)^2+(z-x)^2=8$， $x^3+y^3+z^3=1$ what is the Minimum value of $x^4+y^4+z^4$


Pass value from autoit.exe to java program

Question: Hi i need to return a value(String) from the autoit.exe to java program(The program which is calling the autoit.exe). So please help me to return value. Below is the code for - Autoit script where i am trying to read a value from the combo box which i am reading correctly. Then i return the value.
Main()

Func Main()

Local Const $dialogTitle = $CmdLine[1]
Local Const $timeout = 5
Local $OTHERARGS= $CmdLine[1]
Local $windowFound = WinWait($dialogTitle, "", $timeout)

Local $windowHandle

If $windowFound Then
    $windowHandle = WinGetHandle("[LAST]")
    WinActivate($windowHandle)
     Local $sString = ControlGetText("","","[CLASS:Edit;INSTANCE:1]")
    ControlClick($windowHandle, "", "[CLASS:Button; TEXT:&Cancel]")
    Return $sString
  Else
    Exit(1)
EndIf
EndFunc

This code is working fine as it is returning 0 as a process exit value. However i am not able to get the return string value. Below is the code for java:
String exePath = "D:\\amit\\Documents\\CancelSave.exe";
exePath = exePath.replace("//", "\\");
Process process = new ProcessBuilder(exePath,""+windowName).start();

// get the input stream of the process and print it
InputStream in = process.getInputStream();

for (int i = 0; i < in.available(); i++) {
 System.out.println("" + in.read());//Here it print nothing

 }

Comment: As far as I know you cannot use a string as the exit code. Returning $sString there probably just causes the process to return 0 or 1 as the exit code. You may want to write the value to the standard output stream (not sure if its possible) and capture it via java.
Comment: Exit can only set Integer values. You can create a mapping in your Java program. 1 = ok 2 = Ok, but 3 = Found nothing, ... You could write the value to memory or file or ... and read it with java from there
Comment: Please add some example code to demonstrate and show what you've already tried and what part you are getting stuck on.
Answer: ConsoleWrite ( "data" ) writes a string to STDOUT. So instead returning a value from your AutoIt script you should write the value to STDOUT and exit the AutoIt script, then read the value with a stream reader.


Carregar aba somente ao clicar(com jquery)

Question: Estou usando o sistema de abas com jqueryUI e me deparei com um problema onde eu preciso que ao carregar a página, somente carregue a primeira aba, existe um modo de fazer isso?
Comment: Mas para que serveria então as outras abas?
Comment: Isso é facil, agora me diga, quando é que as outras abas poderão ser visíveis?
Comment: uma forma seria vc dizer no jquery q as outras abas iniciam ocultas e qnd um input da aba exibida for preenchido, a seguinte seria exibida. não entendi como seria o clique se as outras estariam ocultas.
Comment: Você pode utilizar o AJAX para fazer o carregamento das abas, assim que o usuário clicar na aba, uma função, por exemplo, carregar() é disparada para cada aba e carrega o conteúdo.
Comment: LeAndrade, as outras abas servem para o conteúdo dela, eu só quero fazer isso por que há conteúdos na aba, como o do google maps que carrega ao carregar a página, na primeira aba não tem nada que precise carregar assim, portanto uma pessoa que entra na página teria que esperar carregar todo conteúdo da página que não está vendo, isso meio que é um incoveniente, por isso que fazer
Answer: Cara basicamente é isto que está no exemplo. Na ABA 1 você carrega o conteúdo na página mesmo, nas outras abas, você carrega um html diferente para cada uma.

$(document).ready(function() {
    $("#tabs").tabs({
      beforeLoad: function(event, ui) {
        ui.jqXHR.fail(function() {      // função se houver algum erro
          ui.panel.html(
            "Mensagens de erro caso o conteúdo não seja carregado por algum motivo" );
        });
      }
    });
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">

Tab 1

Tab 2

Tab 3

Tab 4

TEXTO QUE JÁ VEM PRE CARREGADO QUANDO VOCÊ ACESSAR A PÁGINA.

Comment: não acho que vc não entendeu, eu não quero criar página html e sim deixar tudo na mesma página, mas só carregar o conteúdo da primeira aba+o restante em torno da página
Comment: Sem deixar html separados, com Ajax, não vai funcionar. Terá que buscar uma outra tecnologia que carregue elementos da própria página por eventos.
Comment: blz obrigado pela resposta


I get a different accuracy each time I run a classifier on my data

Question: I'm trying to perform binary classification on a data (80 sample data points, 39542 predictor dimensions). The data contain 2 classes, one in 18 samples and the other one in 62 samples.
I split my data into training, validation, and test samples, but each time I run the classifier it gets a different result, e.g., 0.87, 0.83, 0.70, or even sometimes 0.50. I tried SVM or DT - both give almost the same result.
What does this indicate? Does this mean my data is noisy? Is there any way that I can stabilize my result?
Answer: If you split your sample in different ways, then your classifier will get different training and validation data in each case and therefore classify the test data in different ways. (Plus, it will get different test data in each case.)
You have very little data and very many predictors. In such a case, your classification variance will necessarily be large, so re-running your classifier on different training and validation sets will yield classifications that differ a lot.
I'd recommend either getting (a lot) more data, or regularizing in some way.
Incidentally, re-running your classification to see how much it varies is an excellent idea. You are learning a lot about your data and your problem in this way!


Fair results from a biased coin: most efficient solution

Question: A well-known procedure for simulating a fair coin from a biased one (attributed to Von Neumann) is to toss it twice: if the results differ then use the last result, otherwise start over. If the biased coin had a heads probability of $p$, then the expected number of tosses for this is $\frac{1}{p(1-p)}$. If, unbeknownst to us, the coin was in fact unbiased ($p = 0.5$), this evaulates to 4.
We can in fact do better than this by not discarding all the previous toss results when we toss again. For example, just as "HT" and "TH" can respectively be mapped to "T" and "H", so can "HHTT" and "TTHH", or "HHHHTTTT" and "TTTTHHHH". Below is a function in Python that, given the sequence of toss results so far, returns either "H", "T" or None (to indicate that you need to continue tossing).
>>> def unbias(tosses):
  if len(tosses) % 2 == 1: return None
  elif set(tosses[-2:]) == {"H", "T"}: return tosses[-1]
  else: return unbias(tosses[::2])
>>> unbias("HT")
'T'
>>> unbias("HH")
>>> unbias("HHTH")
'H'
>>> unbias("HHTT")
'T'
>>> unbias("HHHH")
>>> unbias("HHHHTH")
'H'
>>> unbias("HHHHTT")
>>> unbias("HHHHTTTT")
'T'

My question is: is there a closed form expression for the expected number of coin tosses here? Specifically, I'm interested in the case when $p$ is 0.5. Simulation indicates that the expectation here is around 3.401.
Comment: What are  `unbias("HHHHTTHH")`  and `unbias("HHHHHHTT")` ?
Comment: "H" and "T" respectively. There was a typo in the function definition, which I've now fixed, sorry.
Answer: If you look at the probabilities of needing more than $2n$ tosses when $p=\frac12$, this suggests you get an expectation of $$\sum_{n=0}^\infty 2^{a(n)-n}$$ where $a(n)$ is the number of $1$s in the binary representation of $n$, OEIS A000120.
This is $$2^{0-0}+2^{1-1}+2^{1-2}+2^{2-3}+2^{1-4}+2^{2-5}+2^{2-6}+2^{3-7}+2^{1-8}+\cdots \\ \,\\ \approx 3.40147099057$$
which  is also $\sum\limits_{n=0}^\infty \frac{1}{b(n)}$ where $b(n)$ is the largest power of $2$ that divides $n!$, OEIS A060818
but I do not see an obvious closed form.

Investigating further, this improvement of about $0.5985$, compared with the expectation of $4$ tosses from the traditional procedure you describe, turns out to be the best improvement from the traditional expectation of $\frac{1}{p(1-p)}$.
As the coin becomes more biased, the improvement of your method reduces towards $0.5$.
Here is some R code calculating the expectation:
expectedrounds <- function(p){
  q <- 1 - p
  maxrounds <- 2 ^ ceiling(log(40 / -log(max(p,q), 2), 2))
  unresolvedH <- 0
  probresolved <- numeric(maxrounds)
  for (round in 1:maxrounds){
    potential <- c(unresolvedH, unresolvedH + 1)
    resolvedH <- potential[duplicated(potential)]
    probresolved[round] <- sum(2 * p^resolvedH * q^(round -  resolvedH))
    unresolvedH <- potential[! potential %in% resolvedH]
    }
  expectedrounds <- sum(probresolved * (1:maxrounds)) +
      sum(p^unresolvedH * q^(round -  unresolvedH)) * (maxrounds + 1/p/q)
  return(expectedrounds)
  }

giving for example
> expectedrounds(0.5)
[1] 3.401471

The number of expected rounds for some different probabilities of heads are:
probability Heads   expectedrounds  traditional  improvement
0.5                    3.4014710      4.0000000   0.5985290
0.49  or 0.51          3.4031325      4.0016006   0.5984681
0.4   or 0.6           3.5741042      4.1666667   0.5925625
0.25  or 0.75          4.7684595      5.3333333   0.5648738
0.1   or 0.9          10.5851114     11.1111111   0.5259997
0.01  or 0.99        100.5075887    101.0101010   0.5025123
0.001 or 0.999      1000.5007509   1001.0010010   0.5002501

Comment: It is also $\sum\limits_{n=0}^\infty \frac{1}{b(n)}$ where $b(n)$ is the largest power of $2$ that divides $n!$, [OEIS A060818](https://oeis.org/A060818)


How to assess the quality and goodness of fit of a lasso model?

Question: So far I evaluate the lasso model by its out-of-sample predictions and by the $R^2$ for the goodness of fit. What other measures should I look at? Particularly, do I need to examine the residuals for certain attributes?
Edit: The point of the evaluation is not model selection so in my understanding measures like AIC or BIC are not relevant
Comment: Lasso is an estimation technique, not a model. For a given model, you assess the model fit just as you normally would. What you do now seems fine to me.
Answer: In principle you can check residuals of regularised models (L1, L2) as you would for normal regression models.
Keep in mind though that regularisation creates a bias towards zero on the regression estimates. If you now plot residuals against predictions or predictors, you may see a bottom-left to top-right residual patterns. This is because the zero-bias from the regularisation tends to cause overestimation for small and underestimation for high values. Such a pattern is expected and not an indicator of model misspecification.
Btw: the same happens when you plot residuals against predictions made with a random effect, because random effect estimates are in some sense L2 regularised (because of the underlying normal distribution, which creates an adaptive shrinkage on the RE estimates, identical to L2). See example here https://github.com/florianhartig/DHARMa/issues/43


The "Add another item" button doesn't work with field groups

Question: I am working on a site that uses a lot of horizontal field groups. I am having a problem where any fields that sit in a field group and have "unlimited" set for the number of entries is unable to use the "Add another item" button. The AJAX call is returning some JS settings but no HTML.
The fields themselves range from simple text fields to node references. If a field is not residing in a field group then it works fine.
I will point out that I am using Drupal 7 and field_group version 7.x-1.1.
It seems that the Drupal core is unable to properly identify which button was clicked and so has not idea how to respond.
Comment: I have the exact same problem here, when I click on Add another item for a multiple values field inserted in a fieldgroup, it does not work. Could you tell me if you found any solution for that (jQuery update? AJAX problem? PHP version?). Thanks.
Comment: Even i have same problem. "Add Another item" is working if i login as administrator,but is not working with user's id.I have given node edit permission to all registered users.Please can anybody help me
Answer: another option is to use the field_collection as described here: http://openconcept.ca/blog/mducharme/creating-multiple-value-field-groups-drupal-7
i'd like to see this in field_group to though - as the detour of making collections under 'structure' isn't as intuitive as under 'manage fields'
Comment: Even i have same problem. "Add Another item" is working if i login as administrator,but is not working with user's id.I have given node edit permission to all registered users.Please can anybody help me.


mediaelement.js - Play random video?

Question: I have lots of videos in the directory "video" in my WordPress installation.
They all play nice using the MediaElement.js plugin, but is it also possible to play a random clip from this directory? For example using a shortcode that directs to the directory (and not to a specific video), something like
[video src="http://www.domain.com/wordpress/wp-content/video" random="true"]

That would be great!
Answer: This should be possible.
What you might want to do is use AJAX to generate the div containing your video player. If you do this, you can delete/recreate the player very easily.
After that what you'd need is a shortcode definition which feeds a directory string value and a boolean value into whichever function you attach to the shortcode handler.
For Instance

$defaultDirectory=site_url()+"/videos/";

add_shortcode( 'video', 'videoDiv' );

function videoDiv( $shortcodeAttributeList )
{
  extract( shortcode_atts( array(
             'src'    => $defaultDirectory,
             'random' => true,              /*set default values, use lowercase*/
         ), $shortcodeAttributeList ) );

  if($random)
  {
      $numFiles=fileCounter($src);
      $choice=rand(1, $numFiles);
  }

  $output='
';
  // Continue by making a string which spans from
 to

  return $output; //a div
}

Also from http://php.net/manual/en/function.readdir.php
<?php
/**
* get the number of files within a given dir
*/
function fileCounter($dir){
    $counter = 0;
    if ($handle = opendir($dir)) {
      //echo "Directory handle: $handle\n";
      //echo "Files:\n";
      /* This is the correct way to loop over the directory. */
      while (false !== ($file = readdir($handle))) {
          //echo "
".$counter." - $file";
          $counter++;
      }
      closedir($handle);
    }
    $counter -= 1; // in order to exclude '.' and '..', as well as start the counter on 1
    return $counter;
}
/**
* get the filename in a giver dir, starting the first file with the index 1
*/
function fileNameByIndex($dir, $fileIndex){
    $counter = 0;
    if ($handle = opendir($dir)) {
      while (false !== ($file = readdir($handle))) {
          $counter++;
          if($counter - 2 == $fileIndex)
              return $file;
      }
      closedir($handle);
    }
    return "";
}
}

mediaelement.js - Play random video?


Webkit Background Attachment Fixed bug

Question: I use parallax effect. In firefox works ok, but in Chrome, Safari, Opera bg dissapear (webkit). I use too animate.css, so when i remove this styles, all works ok. I read a lot on stackoverflow about this situation, I tried with Backface-visbility.
URL with project: http://margar.edl.pl/
Comment: You need to provide code in order for us to help you.
Comment: Which background are you talking about?
Comment: Chrome/Opera all backgrounds without in home. In webkit white place (there are content too, but white color). I've read that this bug. I would skip this problem, but on my another page [link](http://inesta-wordpress.studio-themes.com) works. And I made almost the same.
Comment: I'm betting it's because of the transforms on the parent elements, `body` and `html`, but I cannot test *anything* because your site isn't letting me change the CSS. You should provide relevant code *in the question itself* so we can help you more
Comment: http://jsfiddle.net/yFgy8/ maybe look this. This is not 100% of my situation, but you can see that there is a problem with the fixed. I tried with webkit Backface, ztrasnlate, the problem still was.
Comment: [It seems to work fine](http://jsfiddle.net/Zeaklous/yFgy8/1/) once jQuery is added. Also, you still provide too much code. You need to learn how to localize your problem to get good, quick responses from SO
Comment: Just the problem appeared suddenly and have it only on the page. I can not share the package with the site. However, look for another solution. Thanks.
Answer: I think I found a solution. I removed the relative position of the container with parallax effect. I do not know why it just worked.

Webkit Background Attachment Fixed bug


Can I use each for elements create on the fly?

Question: Hello can I use each for elements that they are created on the fly?
<code>$('#cart-info .shopp').each(function(){
    var cartitem = $(this);
    alert(cartitem);
    cartitem.find('img.remove').on('click',function(){
        alert(cartitem.attr('id'));
    });
});
</code>
I created elements under div cart-info. But unfortenately the click event does not work. If the elements are provided when the page loads it works. For example look at http://jsfiddle.net/epapathanasiou/jpdZt/1/
Comment: There are numerous examples of binding events for dynamic elements using event delegation in stack overflow. http://api.jquery.com/on/
Comment: You should use `console.log()` rather than `alert()` for debugging - it is _much_ nicer to work with. Check your browser's JavaScript console for the output. You'll find that console within the Developer Tools of modern browsers, which are generally opened by pressing F12.
Answer: use event delegation
<code>$('#cart-info').on('click', '.shopp img.remove', function(){
    alert(cartitem.attr('id'));
});
</code>
Comment: And now your `cartitem` is `undefined`. In the question it refers to the `.shopp` element.
Comment: I will use event delegation. Thank you very much. Your code I think it will not work because as i see it depends on iteration. But we cannot use each for elements are not created. I tried it and I did not get any events.
Answer: <code>$('#cart-info').on('click', '.shopp img.remove', function(){
    // this is the `img.remove` element
    alert($(this).closest('.shopp').attr('id'));
});
</code>
Here is the demo.
Comment: Thank you very much. I think you gave me a work around. In the beginning I tried to develop the solution as I did in the creation of the elements but unfortunately it did not work. Your code is very close to give a solution to my task.
Answer: You could also do this:
<code>$('#cart-info .shopp').each(function () {
    var cartitem = $(this);
    console.log(cartitem.text());
    cartitem.find('img').on('click',function () {
        console.log(cartitem.attr('id'));
    });
});
</code>
Comment: This is the same as the code in the question, except that you're no selecting all `img` elements inside each `.shopp`.
Comment: Unless in the actual code there are other images. And it doesn't solve the problem in the question
Comment: I will use event delegation. Thank you very much. Your code I think it will not work because as i see it depends on iteration. But we cannot use each for elements are not created. I tried it and I did not get any events
Comment: is up to you to decide what's answer fit with your problem, I don't know all possibilities.


How to set outputPath for inline file-loader imports?

Question: I load Ace editor dynamically with following code:
async function loadAceEditor() {
    return import(/* webpackChunkName: "ace", webpackMode: "lazy" */ 'ace-builds/src-noconflict/ace').then(() => {
      return import(/* webpackChunkName: "ace", webpackMode: "lazy" */ 'ace-builds/webpack-resolver').then(()=>{
          return import(/* webpackChunkName: "ace", webpackMode: "lazy" */ './additional-modes/webpack-resolver');
      })
    })
}

And if we will look in  'ace-builds/webpack-resolver' we will see many many lines like this:
ace.config.setModuleUrl('ace/ext/beautify', require('file-loader?esModule=false!./src-noconflict/ext-beautify.js'))

how can I make webpack (v4.6) (via webpack.config.js) to write generated *.js modules in some sub-directory in default output.path?
Answer: Have found solution with NormalModuleReplacementPlugin, this just adds outputPath to inline loaders.
plugins: [
       new webpack.NormalModuleReplacementPlugin(/^file-loader\?esModule=false!(.*)/, ( res ) =>{
         const out = res.request.replace(/^file-loader\?esModule=false!/, "file-loader?esModule=false&outputPath=js/ace-modes!");
        // console.log("replacing ", res.request, out);
         res.request = out;
       })
    ]


Grouping observations by ID while also creating characteristic variables

Question: I'm working with a survey for individuals in Ecuador and I want to analyse the characteristics of each household. Every individual has a houseID, so I guess I would need to group them using that variable while also creating some extra variables regarding their characteristics: for example, a dummy that is 1 if the household has two women or more. I will post an example below.
I would know how to do this in R (group_by), but I haven't found a similar command in Stata.
A simplified version of my data would be:
houseID         femaleDummy   maleDummy
10000000001     1             0
10000000001     1             0
10000000001     0             1
10000000002     0             1
10000000002     0             1

And I would like to get something like
houseID         twoFemalesormoreDummy
10000000001     1
10000000002     0

Comment: dude if the solution solves your question, please accept it. thanks
Comment: Sorry! I was sure I had done it. The solution was perfect. Thanks!
Answer: very easy my friend
gen d_female = femaleDummy == 1
bysort houseID: egen total_female = total(d_female)
bysort houseID: gen dummy = total_female >= 2

Comment: You don't need the first statement if the second is amended to `bysort houseID: egen total_female = total(femaleDummy == 1)`.  Note that OP wants 2 or more so the code should end `>= 2`.


What does "plagal" actually mean for modal music and melody generally

Question: Basic textbook descriptions of the church modes seem clear, but I find things confusing when looking at actual compositions. I especially don't understand what "plagal" modes really means.
I have a book, Helmore, Plain Song, with an authentic/plagal example like:

And because that is a bit unclear visually what tones are being labeled, here is another version...

Helmore then gives a harmonization...

...it isn't clear which part would represent the chant, I assume it's the scale in the soprano, because it goes G to G like the example of the mode with solfege labels. To me, that looks like the final, the C is in the bass, and the G in the soprano, the melody, is SOL, the fifth of the scale, and so a "plagal" chant - melody - would end on SOL, end on the fifth of the scale.
And then finally an actual piece of Renaissance music which an editor labeled hypoionian...

...this matches up with the two unharmonized examples of the mode. I assume the final is G, and it's plagal hypoionian, because it moves above and below the final (in this case it conveniently goes to the upper/lower SOL like the examples, although I understand that isn't always the case in actual compositions.) But, clearly it ends with both bass and melody on G, DO so there is no question whether ending on SOL is the reason it's labeled hypoionian.
The Helmore and Goudimel (or the Goudimel editor's) examples seem to contradict each other. One seems to say plagal means ending on the fifth of the mode SOL and the other shows ending on DO but moving above and below the ending tone.
Here are two other examples but in phrygian...
Helmore:

Goudimel:

...I truncated the Goudimel but there is enough to see the start and end.
The two are essentially the same musically but the are labeled differently: Helmore says hypophrygian for ending on ^5 but Goudimel says phrygian. They seem to be labeling things opposite.
Can someone clear up what's going on between these two sources?
I would really like a good reference source of actual Renaissance music with the modes properly labeled. If the Goudimel examples are good, then I'll use them. But then why does Helmore seem to be so different?

My original question was about possibly applying the term "plagal" to describe melodies that are not modal Renaissance.
An example from The Revivalist hymnal in a clearly major key where the melody starts and ends on SOL...

My understanding - which could be wrong - is melodies that start/end on the fifth of the (authentic) modes are called "plagal" and the mode name gets prefixed with "hypo". So, for example mixolydian, key signature of no sharps/flats, starts and ends on G, but its plagal form start and ends on D and the mode is then called hypomixolydian.
This Wikipedia page suggest it could be called hypoionian, but the discussion seems to say that was a theoretical idea of one person in the Renaissance and possibly not in line with even the modal conventions of that time.
Either way, this music clearly isn't modal music. So, is calling this melody, the soprano part, "plagal" inappropriate?

This was just a related add on question.
Similarly, some melodies start/end on the mediant, like The First Noel. Gjerdingen has a phrase schema called Pastorella that outlines MI RE FA MI. So, I thought such melodies could be called "pastoral", but I doubt anyone would understand the intended meaning. Is there some other common terms to use?
Comment: I'm not remotely knowledgeable, but this prompted me to look at the Wikipedia page for [Gregorian modes](https://en.wikipedia.org/wiki/Gregorian_mode#Plagal_mode), which essentially says the "plagal" vs. "authentic" distinction doesn't affect the final tone or the set of pitch classes, it only affects the range of pitches.
Comment: I'm not familiar with a use of "plagal" to define a *melody*, especially in a common-era context. Cadence, sure, but a little light googling looks like the only other use is to describe a church mode (or, I suppose, by extension a melody in such a mode).
Comment: I'm with @AndyBonner on this one. But just to clarify, you're looking for a term or terms that describe a melody that ends on a pitch other than the tonic?
Comment: @Aaron, in part that is my question, but probably more important is confusion specifically about Renaissance modal compositions. I re-wrote my question.
Comment: I think this video by Elam Rotem is probably what you are looking for: [Modes in the 16th and 17th centuries](https://www.youtube.com/watch?v=lyq48eybjZw)
Comment: @ElementsinSpace, I"ll check out that video, but I doubt it will answer specifically about my Helmore/Goudimel question.
Comment: related - https://scholarcommons.sc.edu/cgi/viewcontent.cgi?article=4442&context=etd
Answer: Plagal is a theoretical term originally used to classify liturgical chants in Western European and colonial traditions, through the mid 17th century. For monophonic chants, plagal means that the ambitus of the melody ranges from a fourth below the final to a fifth above it.
In polyphonic music of the 16th-17th century, if you follow Zarlino's theories, then the plagal vs. authentic quality of a mode is determined by the ambitus of the tenor (not the melody), while the final is determined by the  lowest voice. There was and is wide disagreement about what mode actually means in polyphonic music, as your examples demonstrate, but I would stress that there really is no universal theory that you can apply to all times and places.
About the examples:

Helmore is not theorizing mode, but teaching you how to harmonize plainchant according to 19th-century traditions. His practice has absolutely nothing to do with what mode meant back in the 15th-17th centuries. Better to ignore it unless you are studying mid-19th-century keyboard harmonization.

If the Old 100th melody had a final on C, then it would make sense to classify the melody (as monophonic music) as "hypoionian" or mode 12, using Glarean and Zarlino's system of 12 modes defined by their final and the melodic ambitus.

For a polyphonic piece, though, Zarlino would say that the mode of a polyphonic piece was defined by the final note in the lowest voice and the ambitus of the tenor voice, not the melody. So technically, if you treat this as a C mode transposed to G, then since the tenor does have a plagal ambitus, this would be mode 12.

The Genevan Psalm 26 melody is certainly Phrygian: it ranges between E and E, and ends on E (i.e., mode 3). The harmonization, however, has an A final and the tenor voice has a plagal ambitus, so that would be Zarlino's mode 10 (A plagal). This is a nice example of the difference between mode as a monophonic vs. polyphonic concept.

The Lowell Mason setting is in tonal C major, and concepts of mode are not relevant. But yes, a time-travelling 16th-century chapelmaster would probably look at this and call it mode 12 (ends on C, tenor is plagal). The melody does have a plagal range, and it is valuable to assert, in defiance of Schenker, that European melodies do not in fact always descend to the tonic.

I have to wonder how helpful it is to apply any of these labels, especially when we don't know if the creators of the music even thought this way. Had Goudimel read Zarlino? Did French/Swiss Reformed musicians care what Italian Catholic theorists thought?
Far more relevant to 16th and especially 17th century harmonic practice are the eight psalm tones, and the harmonic practices developed by keyboardists and chapelmasters to match chants in those tones with polyphonic music. From these practices come the concepts of tonos and "church keys", which over the 17th century increasingly started to resemble major and minor keys.
Just to summarize the rules of thumb for mode:

When speaking of Western European monophonic liturgical chants:

mode is defined by the final note (D = Mode I, II; E = Mode III, IV; F = Mode V, VI; G = Mode VII, VIII)
and the ambitus or total melodic range:

the odd-numbered modes have authentic ambitus (range from the final to an octave above)
the even-numbered ones are plagal (range from a fourth below the final to a fifth above it)

When speaking of polyphonic music of 15th through mid-17th century Europe and its colonies:

mode is determined by the final note in the lowest voice (same as above but by mid 16th century modes are added: IX/X on A, XI/XII on C)
and the ambitus of the Tenor voice (same rule as above)

See chapters 11-13 of The Cambridge History of Western Music Theory, ed. Thomas Christensen (2002).
Comment: This is very helpful, thank you. Zarlino and classifying polyphonic music is definitely what I have been missing. FWIW, I do agree with your sentiment about whether it makes sense to use these labels. I recently printed out a lot of Renaissance music from IMSLP. I'd like to know the theory that goes with it, but especially don't want to misapply the wrong theory.
Comment: @MichaelCurtis note that there is an error in this otherwise thorough answer, namely "the tenor voice, not the melody": in Zarlino's day, the tenor _was_ the melody, which is precisely why that is the voice used to determine the ambitus. Applying this rule blindly to a later style where the melody is in a voice other than the tenor is anachronistic. Instead, one should consider the ambitus of whichever voice has the melody. It's also worth noting that the dominant is different in the plagal modes compared to the authentic.
Comment: @Phoog, OK, that's a good point. The notes I have about Goudimel say his settings were unusual, because he put the melody in soprano not tenor. So, Psalm 134 is `G` hypionian, right? But what about Psalm 26? The soprano melody is clearly phrygian and authentic, right? But the final in the bass is `A`. So what should the music be called, `A` phrygian, `E` phrygian?
Comment: @MichaelCurtis yes, 134 is hypoionian (as it claims) transposed to G, and I would say that 26 is (untransposed) E phrygian.  There were various different solutions to the problem of harmonizing the lower second degree of the phrygian mode, one of the most common of which leaves modern ears thinking that the piece "ends on the dominant" (of a minor key).  In early use, the mode of a piece would be determined by the mode of the preexisting chant or other melody on which it was based.
Comment: @MichaelCurtis Last night, while looking for a 16th century example with the cantus firmus in the soprano, which I didn't find, I found a Palestrina Magnificat in hypophrygian. The ambitus of both tenor and soprano would suggest authentic phrygian, and the chant ranges from E to the B above, so on ambitus alone you can't really distinguish which mode it is, but the reciting tone, the dominant, is A, identifying the mode as plagal. The tenor ambitus rule seems to be secondary, describing the common case, but in fact you identify the mode (by whatever means) from the melody (in whichever voice).
Comment: I think your "D= Mode I" may need a little clarification; it's perfectly possible to have a Mode I chant on some other note, providing the semitone intervals are in the right place (eg B C# D E F# G# A B). Mode I is "Minor scale with sharp 6 and flat 7"; it just happens that it fits on the piano's white notes if D is the tonic.
Comment: @AndrewLeach, "your?" Who do you mean? Use the "at" sign. I think everyone here understands that mode I can be transposed to a final other than `D`.
Comment: @Michael Sorry: it was directed to musarithmia, as it's a comment on this answer and they would get the notification. I think there's a lot of ambiguity here, with fixed pitches being bandied about. *We* may know that chant doesn't have a fixed pitch, but that may not apply to everyone. Also, the tenor part in polyphony is only important because that's where the tune was customarily placed.
Comment: @Phoog, thanks for those follow ups. I understand what your wrote. And especially about the ambiguity and disagreement over polyphonic mode classification. I need to accept that it isn't a cut and dried thing like common practice style and key.
Comment: @AndrewLeach in Zarlino's day, however, you couldn't in fact have mode I with a final on B, because they hadn't started using sharps in key signatures.  But, on the other hand, there was a far wider range of frequencies that could be called "A", so not being able to write a mode I piece with a B final wasn't perhaps as limiting.
Answer: In my research, I came upon the following

In an authentic mode such as D Dorian, we have octave, here D-D, built
from a lower fifth (D-A) and an upper fourth (A-D), with D as the
"final" or usual note of repose or conclusion.
In a plagal mode such as D Hypodorian, in contrast, we have a mode
built from the fourth below the final (A-D) and the fifth above
(D-A).
Thus in authentic Dorian, we have an octave starting with the final D,
divided as it were D-A-D, with the fifth below and the fourth above.
This was regarded as the more "natural" or harmonious division of the
fifth; I could get into the mathematics of thus, but will for now only
say that medieval theory (especially as codified by some writers
around 1300) regarded it better to place the simpler 3:2 fifth below
the more complex 4:3 fourth. (These are the string-ratios for these
intervals, which add up to a 2:1 octave.)
In plagal Dorian or Hypodorian, in contrast, we an octave starting
with A (the fourth below the final D), divided A-D-A, with the fourth
A-D below the fifth D-A. This was taken as in theory less harmonious
or "natural" in its arrangement, although, of course, both forms are
respected parts of the system.

It would seem that a plagal mode is just basically one built on fourths, instead of the regular fifth or octave.
SOURCE


Applying Cayley's Theorem to $D_n$

Question: Cayley's Theorem states, every group G is isomorphic to a subgroup of the symmetric group acting on G. I also know the dihedral group $D_n$ is a subgroup of $S_n$. But I was wondering, is it because of Cayley's Theorem we know $D_n$ is a subgroup of $S_n$ (Does Cayley's Theorem guarantee that $D_n$ is a subgroup of $S_n$?)?
Comment: I see why Cayley's Theorem is not need, but could you still say Cayley's Theorem guarantees that $D_n$ is a subgroup of $S_n$?
Comment: You would be able to guarantee that $D_{2n}$ is isomorphic to a subgroup of $S_n$, it depends on how you initially define $D_{2n}$ as to whether it IS a subgroup.
Answer: If you think of $D_{2n}$ by its geometric action, it is the group corresponding to the reflections and rotations of an $n$-gon. Each of these reflections and rotations is a bijection on the vertices of our $n$-gon. So we get that $D_{2n}$ is (at least isomorphic to) a group of bijections on $n$ elements, i.e. a subgroup of $S_n$.
As you can see, we haven't used Cayley's Theorem anywhere in this explanation.
Notation: I use $D_{2n}$ to be the dihedral group with $2n$ elements. I'm just pointing it out because others (as I'm assuming you do) use $D_n$ because it acts on an $n$-gon. Both are valid I just have a preference for $D_{2n}$, that's the only reason I used it.
Answer: If you know the description of $D_n$ as symmetries of an $n$-sided polygon then you can see that it naturally permutes the vertices of that polygon giving a realization as a subgroup of $S_n$, no Cayley's thoerem is needed. (Actually that theorem would say $D_n$ is a subgroup of the symmetric group $S_{2n}$ of order $(2n)!$.
Dihedral group is generated by the fundamental rotation which is a cyclic permutation of length $n$ on $1,2,\dots, n$ and any reflection.
A convenient reflection would be the one passing through the mod-point the first and last vertex: $v_1$ and $v_n$ It would be swapping simultaneously the $k$th vertex from the first with the $k$th vertex from the last.
So $D_n\subset S_n$ is the subgroup generated by the cycle
$(123\quad  n)$ and $(1,n)(2,n-1)(3,n-2)\cdots$
Comment: Cayley says a group of order $r$ is a subgroup of $S_r$, so I think it is an exclamation mark, and not a factorial.
Comment: @Gerry Myerson: That stupid mistake has been corrected.

Applying Cayley's Theorem to $D_n$