Obtuse triangles

Question: How many values of the integer k will make the triangle with sides 6, 8 and k obtuse?
6,8,10 is a right triangle therefore if we enlarge the hyp, then the right angle will become obtuse?
Isn't it only 10 < k <14? How do I get the others using a systematic method?
Comment: What about the $3,6,8$ triangle?
Comment: Your error is that you assume that the new side will be longest, but that is not stated.  The triangle $5.29..,6,8$ is right so lowering the $5.29$ will produce an obtuse triangle.
Answer:
$k$ has to be in $(2,14)$ for the triangle to exist.
Let's note $\hat{A}$, $\hat{B}$ and $\hat{C}$ the angles between the sides of length respectively $6$ and $8$, $6$ and $k$ and $k$ and $8$.
The side opposing the obtuse angle in an obtuse triangle is the longest of the three and $6<8$, so $\hat{C}$ can never be obtuse.
As you noticed, $\hat{A}$ is obtuse iff $k^2>6^2+8^2$, i.e. $k>10$.
By the same reasonning, $\hat{B}$ is obtuse iff $8^2>6^2+k^2$, i.e. $k<\sqrt{28}=2\sqrt{7}$
Finally, the triangle is obtuse iff $k \in (2;2\sqrt{7})\cup(10;14)$

Obtuse triangles


How to create a node with mulitple field-collection items?

Question: I've a content type having filed collection item (3 fields of 5 sets). Created a custom module form, when user submits that form, it should create a node with all 5 set field collection items.
So far tried the following code. it's working for 1st set but not for all.
$values = array(
  'type' => 'ct_machine_name', // Content Type machine name
  'uid' => $uid,
  'status' => 1,
  'promote' => 0,
  'title' => 'xxxx',
);
$entity = entity_create('node', $values);
$ewrapper = entity_metadata_wrapper('node', $entity);
$ewrapper->save();
$node = node_load($entity->nid);

$fc_val= entity_create('field_collection_item', array('field_name' => 'field_fc_mcnename'));
// Attach to the node
$fc_val->setHostEntity('node', $node);
$fc_val->field_field1[LANGUAGE_NONE][0]['value'] = $val1;
$fc_val->field_field2[LANGUAGE_NONE][0]['value'] = $val2;
$fc_val->field_field3[LANGUAGE_NONE][0]['value'] = $val3;

// Save field-collection item.
$fc_val->save();

The above code working. But I need to loop through it and save all field collection items in an user submitted order.
I tired as follows, but doesn't work. (example)
for ($i=0; $i<=4; $i++) {
$fc_val->field_field1[LANGUAGE_NONE][$i]['value'] = $val1;
$fc_val->field_field2[LANGUAGE_NONE][$i]['value'] = $val2;
$fc_val->field_field3[LANGUAGE_NONE][$i]['value'] = $val3;
}
$fc_val->save();

Also tried
for ($i=0; $i<=4; $i++) {
$fc_val->field_field1[LANGUAGE_NONE][0]['value'] = $val1;
$fc_val->field_field2[LANGUAGE_NONE][0]['value'] = $val2;
$fc_val->field_field3[LANGUAGE_NONE][0]['value'] = $val3;
$fc_val->save();
}

Any inputs or suggestions would be much appreciated.
Comment: Check this out [Create node programatically with nested fieldcollection item Drupal 7](https://www.drupal.org/forum/support/module-development-and-code-questions/2015-01-08/create-node-programatically-with#comment-10066624) It may help you.
Comment: Hey @berramou sorry for not mentioned that URL in my question. Yes I've tried but no luck.
Comment: Hey Okay and this one with Entity meta data wrapper [Example using field collections](https://www.drupal.org/docs/7/api/entity-api/entity-metadata-wrappers)   Example using field collections Section?
Answer: Try This:
Example for field1 and repeat it with other fields.

$entity_fc_val = entity_metadata_wrapper('field_collection_item', $fc_val);
$entity_fc_val->field_field1->set(array('value' => $val1));


How can I mitigate influence of other factors on correlation

Question: Let's say we found strong correlation between meat consumption and life expectancy. We also know there's correlation between GNI and meet consumption and between GNI and life expectancy. Is there a way to mitigate influence of GNI in our first correlation so connection between meat consumption and life expectancy become more clear?
*GNI stands for Gross National Income
Comment: I think you are probably looking for either partial correlation or some form of multiple regression although without more detail I am not clear which you want.
Comment: Specifying the scientific question might help. Are you interested in modelling one of the variables as a function of the others or just looking at their relationship? It might also help to know what GNI is.
Comment: Multiple regression would be worth investigating then.
Comment: @mdewey what details should I provide, I'm just a beginner in stats, sorry
Comment: @mdewey ah, sorry, its Gross national income https://en.wikipedia.org/wiki/Gross_national_income I think I'm looking at their relationship, trying to understand how meat consumption itself related to health. But if meat consumption strongly correlates with people wealth, which probably correlates with healthcare and other variables which can be the real cause of extended life span. So I'm wondering if it's possible somehow mathematically "substract" their influence.
Comment: Just checked it out and it looks like what I was looking for. Thanks for your patience, @mdewey, I should just check the both options after your first comment.
Answer: Just so this does not join the pile of unanswered questions.
You can use multiple regression here. You would model life expectancy (LE) as a function of meat consumption (MC). So LE is on the left hand side, MC on the right hand side. You would then include GNI. The coefficient of MC now would give you the effect of MC on LE allowing for GNI sometimes expressed as holding GNI constant.
Some caveats.
This is an ecological analysis so what it is saying is that countries with high meat consumption have higher or lower life expectancy. It does not tell you what happens for individuals. Similarly it is the effect of living in a country with high or low wealth not having that personally. In a country with high inequality most people might be very poor even though the GNI is high.
The direction of causality, if any, is not clear here either. It seems reasonable that what you eat affects when you die but it could be that people who for other reasons live for a long time happen to really like eating meat.
Comment: > It does not tell you what happens for individuals.

@mdewey I don't quite get it, it's obvious about wealth as the gap can be huge. But in case of lifespan, don't you think deviation is pretty modest, no one lived even for 150 years as I know. So why do you think we can't transfer the relationsheep into individual level here? The only factor coming to my mind is child mortality, but we can easily exclude countries-outliners.


Apache cxf jax-rs implementation with xml databind

Question: I configured my rest service to implement content negotiation through Variant.
On jersey all works fine but on apache cxf something goes wrong.
No message body writer has been found for class ContentType: application/xml
It seems thath when I construct the response as xml type it cannnot find the correct body writer.
I configured jax-rs with jacksonJaxbJsonProvider and all works great with json databind.
<jaxrs:providers>
  <bean class="com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider" />
</jaxrs:providers>

cxf-rt-frontend-jaxrs version 3.0.3
jackson-databind: 2.4.2
Any idea?
Comment: Let us see your jaxb class
Comment: @XmlType(propOrder = { "orderId"})
public class OrderForConfirmationEmail implements Serializable {  @XmlElement
  public long getOrderId()
  {
    return orderId;
  }
Answer: Add a @XmlRootElement(name="order") generated xml cannot be <orderId>data<orderId>, it should have root element.  Thus updated code would look like
@XmlRootElement(name="order")
@XmlType(propOrder = { "orderId"})
public class OrderForConfirmationEmail implements Serializable {

    @XmlElement
    public long getOrderId() {
        long orderId = new Random().nextLong();
        return orderId;
    }

}

Generated xml is
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><order xmlns="http://com.kp.swasthik/so/schema">
   <orderId>369317779145370211</orderId>
</order>

and json is
{"orderId":6812414735706519327}


Javascript style overriding CSS hover

Question: To make this clearer, I'll use my code below:
I have a divider container, "c_container":

Menu

MenuContent

Then I have CSS that controls it's style:
#c_container {
    width: 550px;
    height: 265px;
    position: fixed;
    left: -550px;
    margin-left: 35px;
    top: 50%;
    margin-top: -100px;
}
#c_container:hover{
    margin-left: 0px;
    left: -40px;
}

Then after I update the style using Javascript from an onClick function:
function hideForm(){
    var msg = document.getElementById("c_container");
    msg.style.left = "-550px";
}

The CSS hover only effects the margin property and doesn't effect the left property as it did before. It's like javascript has locked it.
Comment: Does your actual code also contain improper quoting? You need to use `'` inside the `onclick="..."` string or use `onclick='...'` - basically you cannot use the same quote type inside which was used to quote the the attribute value.
Comment: Sorry, yes it does. I'll edit
Comment: Curious...why are you forcefully hiding `c_container` if it will hide when the user moves the mouse off of it?
Comment: I want the user to be able to click to hide it from within the c_main divider. It makes sense if you saw my web design :)
Comment: Maybe a link to a live server page? Will clear any questions (I think).
Comment: It's only hosted on localhost at the moment.
Comment: Use jQuery if you can (Hidde) provides an example below. Although your CSS is correct, Javascript sets the inline style properties which take precedence, as already mentioned. So you need to control both the *display* and *hiding* of this element with Javascript instead of trying to let CSS pick up the slack. Your CSS will come into play as a fallback for those with Javascript disabled. jQuery is the easiest way to create the exact effect if you don't mind using it.
Answer: jQuery:
//Normal:
$('elementNameOrID').hover (function () {
    $(this).css('left', 0);
}, function () {
    $(this).animate('left', -500);
});

//Nice:
$('elementNameOrID').hover (function () {
    $(this).animate({left: 0});
}, function () {
    $(this).animate({left: -500});
});

JS:
onclick = function () {
    document.getElementById("div").style.left = '-550px';
};

Sidenote: Using div as a name for an element is NOT a good idea and very confusing and misleading when reading your code.
Answer: Styles added with the JavaScript style are creating an inline style which has higher precedence than your style sheet. To fix this you can add !important to your style sheet:
#c_container:hover{
    margin-left: 0px;
    left: -40px !important;
}

Comment: The problem is that the left property gets overridden by javascript not margin-left. If i apply !important to the left property javascript does not effect its position
Comment: Whoops, I added that to the wrong item, meant to add it to `left` not `margin-left`.
Comment: I tried that and then javascript's style.left function doesn't change it's position.
Comment: Yes, I just saw from your other comment that you are clicking from within the div, so I assume you are still 'hovering' when you want to hide it? In that case I don't think there's a lot you can do, either the js style will override the hover or the other way round. I could maybe suggest more if I could see the actual page.
Comment: it was mainly for aesthetic pleasure, but it can be sacrificed. it's ok
Answer: Have problem with commas in onclick function ...
onclick="document.getElementById('div').style.left='-550px;'"

and 'div' is not good name for id.
Your CSS is confusing. For apply DIV tag
div {
   position: fixed;
   left: -550px;
}
div:hover{
   left: 0px;
}

OR
#DIV_ID { ... }

OR
.CLASSNAME { ...}

EDIT
I'm recriate your example ... http://jsfiddle.net/PAg9M/1/ and work for me. What you need?
Answer: You are facing this problem because inline css haves more priority than the one in"style" tag and javascript add inline css.
So should use only javascript to do this-
modify your html-

Menu

MenuContent

This will sort out your problem.

Javascript style overriding CSS hover


How works intruction mod in the vhdl program?

Question: I just have one doubt with the following program:
process(clk)
        variable cuenta : integer range 0 to 255 := 0;
    begin
        if clk = '1' and clk'event then
            cuenta := (cuenta +1) mod 256;
            if cuenta < D then
                S <= '1';
            else
                S <= '0';
            end if;
        end if;
    end process;

On statement cuenta:= (cuenta+1) mod 256, the value of cuenta reaches the value of 255 ? , I mean cuenta it is not just 0 all the time ? D is just a value between 0 a 255.
Thanks and I hope someone could help me with this maybe simple question.
Comment: That's not a program nor a VHDL design unit, it's a process statement without context. If you were to provide a [mcve] and also simulated it you would find that a) cuenta *reaches the value 255* and b) *is not just 0 all the time*.  Should your simulator not support displaying the value of variables, you could make cuenta a signal or [define a signal the value of cuenta is assigned to before `end process`](https://i.stack.imgur.com/xAEq3.jpg).
Comment: change `cuenta` from `variable` to `signal`. It's a clocked/registered signal, so define it as such. using variables this way is asking for problems.
Answer: I recreated your code with a testbench, if you run this you will be able to tell that cuenta just gets 1 added to it then module devised by 256. I stopped the increment, now it's just a signal driven in.
Getting more information may help actually solve your problem. Hopefully what I have added helps though.
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;
use ieee.std_logic_unsigned.all;

entity cuenta is
port(
    clk       : in std_logic;
    reset     : in std_logic;
    D         : in std_logic_vector(7 downto 0);
    cuenta    : in std_logic_vector(8 downto 0);
    modulo_in : in std_logic_vector(8 downto 0);
    S         : out std_logic
);

end cuenta;

architecture behav of cuenta is

    signal cuenta_q : std_logic_vector(8 downto 0);

begin
 process(clk)
    begin
        if rising_edge(clk) then
           if reset = '1' then
              cuenta_q <= (others => '0');
              S <= '0';
           elsif reset = '0' then
              cuenta_q <= std_logic_vector(unsigned(cuenta + 1) mod unsigned(modulo_in));
              if cuenta_q < D then
                 S <= '1';
              else
                 S <= '0';
              end if;
           end if;
       end if;
    end process;

end behav;

library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;
use ieee.std_logic_unsigned.all;

entity tb_cuenta is
end tb_cuenta;

architecture tb of tb_cuenta is

   signal clk       : std_logic := '1';
   signal reset     : std_logic := '1';
   signal D         : std_logic_vector(7 downto 0);
   signal cuenta    : std_logic_vector(8 downto 0);
   signal modulo_in : std_logic_vector(8 downto 0);
   signal S         : std_logic;

begin

    D         <=  x"F0";
    cuenta    <= "000100000";
    modulo_in <= "100000000";

    clk   <= not clk after 50 fs;
    reset <= '0' after 200 fs;

ceunta_inst : entity work.cuenta
   port map(
        clk => clk,
    reset => reset,
    D => D,
    cuenta => cuenta,
    modulo_in => modulo_in,
    S => S
   );

end tb;


How to access contents of Object If I don't know the structure in c#?

Question: I have an object and I don't know its structure until runtime. So is there any way to access data from the object ?
Thanks.
PS: I can't think of any other details to provide, please ask me if this isn't enough!
Comment: When you say an object, do you mean a class object or some binary data for which you don't know anything about its structure?
Comment: @Raj, Hi, I mean a Class Object, I will have the class in Var o, and I know that the o is object, i need to access its contents!
Answer: Well, you can do with with reflection. For example:
public static void ShowProperties(object o)
{
    if (o == null)
    {
        Console.WriteLine("Null: no properties");
        return;
    }
    Type type = o.GetType();
    var properties = type.GetProperties(BindingFlags.Public
                                        | BindingFlags.Instance);
    // Potentially put more filtering in here
    foreach (var property in properties.Where
                 (p => p.CanRead && p.GetIndexParameters().Length == 0))
    {
        Console.WriteLine("{0}: {1}", property.Name, property.GetValue(o, null));
    }
}

Look at the Type API for ways to get methods, events, fields, nested types etc.
Comment: Hi, i am able to access the properties of objects this way, but I wanted to know the actual values of its members. thanks
Comment: @iamserious: Properties *are* members, and that's displaying the values. If you want to get the fields, call `GetFields` instead - although then you'll presumably want to get *private* fields, which means you'll need a higher trust level. Just something to be aware of.
Answer: Have a look at Reflection
Answer: You can use reflection to determine what properties, methods, and fields an object has.  take a look at the methods on the Type type


Entity Framework Save changes on Collection

Question: I have this piece of code
public int Update(Item item)
{
    using (var ctx = new DataConext())
    {
        ctx.Entry(item).State = EntityState.Modified;
        return ctx.SaveChanges();
    }
}

Class Item
{
 public string Name {get;set;}
 public ICollection<Foobar> Foos {get;set;}
}

Class Foobar
{
 public string FirstName {get;set;}
 public string LastName {get;set;}
}

Lets say:
item.Foos.ElementAt(0).FirstName = "edited name"

SaveChanged() is executed but I have the 'old' values on the database and not 'edited name'...
I can see the correct changes in Local in debug.
Answer: Looks like your object came from a different context that the one you are using now. In that case you can't do that with a generic because you need to do a foreEach in your Foobar collection and change the state for each item individually.
What you have here is a disconnected entity graph so the entity is disconnected and change tracking is lost. You only set the state of the main entity and so EF assumes that everything else is unchanged.
Jullie Lerman's books is a good source to understand how this works
What I would do is I would keep this method for simple entities but make it virtual so you can inherit this repo to create specific entity repos and override the update method with a more specific implementation suitable to an entity like the one in your example.
An article that helped my to design such a repo was this: http://www.asp.net/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application.
Answer: You are loading the object in a context and saving in another. Remove using (var ctx = new DataConext()) block, and search for a way to reach the context that loaded the item, then call SaveChanges(); Another way is pass the context to the method, like this public int Update(Item item, DbContext context) and save the changes.
Answer: Class Item
{
    public string Name {get;set;}
    public ICollection<Foobar> Foos {get;set;}
}

You need Include to include the Foos to the object manager. Right now, it is eager loading. Wherever you are loading the item, you have to include it.
You should use include, or you can use virtual to have them lazy load.


open slider jquery twice don't work

Question: I've tried to programm a slider in jQuery. This slider are centered at main page but hidden. When I do click on a specific image, slider turn visible and slider runs perfect. This slider fade out when I do click on "body" tag.
The problem: When I do click for twice on the mentioned image, the slider appear 1 second and disappear immediately.
The "solution" is refreshing web page, but I don't want to do this.
This is my HTML code:

This is my jQuery functions:
function runCarrusel(){
    $("#accordion img").click(function(){
        $("#slides").show("bind",callback);
    });
    return false;
}
function callback(){
    $("body").click(function(){
        $("#slides").fadeOut();
    });
    return false;
}

function carrusel(){
    var t = setInterval(function(){
        $("#slides ul").animate({marginLeft:-300},1000,function(){
            $(this).find("li:last").after($(this).find("li:first"));
            $(this).css({marginLeft:0});
        })
    },5000);
    return false;
}

I've been searching the solution, but it's impossible for me to do that. Thanks.

The problem was the propagation of handler event to body. With retun false sentence break the event and we can do click more times.
Answer: When you click to show the slider, the click event propagates up to the body, which hides the slider. You should stop the click event from propagating:
$("#accordion img").click(function(){
    $("#slides").show("bind",callback);
    return false; // This prevents the event from propagating.
});

Also, because you attach the click-handler to the body element in the callback() function, you attach a handler every time that function is called. You should just attach the handler once.
Comment: Thanks for your solution. Was the propagation to body. Simple solution with a "return false;" sentence.
Answer: You don't need two separate click handlers.  Instead, inspect the target of the click event and do different things:
$('body').on('click', function(event) {
  var target = $(event.target);
  if (target.is('.accordion .slide')) {
    alert("show slide");
  } else {
    alert("hide slide");
  }
});

http://jsfiddle.net/MLBkA/
Comment: Thanks, great aportatation and complete.

open slider jquery twice don't work


How to solve matrix equation $AX+XB=C$ for $X$

Question: How does one solve the matrix equation $AX+XB=C$ for $X$?
It doesn't seem too difficult. I tried many times but failed.
I'm an adult student... I am now vexed about Gilbert Strang - An Introduction to Linear Algebra.
I don't even understand a single word in Wikipedia: Sylvester equation. If you have ever use some nice workable materials or lecture notes? You can generously upload and share the links of the lecture notes and assignments. Different subjects/ topics are welcome, as long as you deem they are nice and workable.
The problem origins from a system of diff equation, using undetermined coefficients (matrix) to find the particular solution. Try $y_p=X\begin{pmatrix}   e^{\alpha t} \\ e^{\beta t} \end{pmatrix}$
$\dot{y}+Ay=C\begin{pmatrix} e^{\alpha t} \\ e^{\beta t}\end{pmatrix}$
$\dot{y_p}=X\begin{pmatrix} \alpha & 0 \\ 0 & \beta \end{pmatrix} \begin{pmatrix}e^{\alpha t} \\ e^{\beta t}\end{pmatrix}$
substitute $\dot{y_p}$ and $y_p$ into the original differential equation..
$X\begin{pmatrix} \alpha & 0 \\ 0 & \beta \end{pmatrix}+AX=C$
Comment: What you have there is a [Sylvester equation](http://en.wikipedia.org/wiki/Sylvester_equation) for which many solution methods are known.
Comment: Are in interested in solving the matrix equation to solve the differential equation, or in its own right?
Comment: I think this question was asked here on math.SE before, but I can't find the link.
Comment: "I don't even understand a single word in Wikipedia" - fine... do you at least know what a Kronecker product is? Or, better yet, what part of the Wiki article do you not understand?
Comment: @JenniferDylan: I think the closest thing is this, but it's not exactly a duplicate, since it has no free term: http://math.stackexchange.com/questions/39906/solving-a-matrix-equation-ax-xb-in-a-cas
Comment: It seems I'm seriously incapable. It is better to suggest me some materials or books rather than just give a solution to my problem. I'd like to contact J.M. also...
Answer: The  matrix equation that prompted this post, $$X\begin{pmatrix} \alpha & 0 \\ 0 & \beta \end{pmatrix}+AX=C,$$ actually has a very easy solution.
Let $X$ and $C$ have columns $X_1,X_2$ and $C_1,C_2$, respectively. Then $$X_1=(A+\alpha I)^{-1}C_1,X_2=(A+\beta I)^{-1}C_2.$$
Footnote
A nice feature of this solution is that the condition for the existence and uniqueness of a solution to a Sylvester Equation is self evident in this simple case :-
$A$ and $-B$ must have no common eigenvalue.
Answer: It seems $AX+XB=[A,I_1]X[I_2,B]^T$, where $I_1$ and $I_2$ are identity matrices and subscript 'T' is transpose of a matrix. Thus, the problem becomes how to solve $[A,I_1]X[I_2,B]^T = C $. Obviously, $X=[A,I_1]^\dagger C {[I_2,B]^T}^\dagger$, where subscript '$\dagger$' means the Pseudo-inverse.
Comment: This is incorrect. $AX+XB$ is $[A,I]\begin{bmatrix}X\\ &X\end{bmatrix}\begin{bmatrix}I\\ B\end{bmatrix}$, not $[A,I]X[I,B]^T$. Note that $[A,I]X$ is not a legitimate matrix product, as $[A,I]$ has $2n$ columns but $X$ has $n$ rows.
Comment: Yeah, I made a mistake. Thank you for your pointing out.
Answer: Use the superoperator formalism:
$$
AXB=C \mapsto ( {B}^T\otimes A)\text{vec} X =  C
$$
(see here for a definition of $\text{vec}(X)\;$ and here for more information: Kronecker product)
Rewrite your equation (using $AXB\to (B^T\otimes A) \text{vec}\;X$) to
$$
AX+XB=C  \to  (1\otimes A)\text{vec}\;X + (B^T\otimes 1)\text{vec}\;X=\text{vec}\;C\\
\text{vec}\;X=\left((1\otimes A) + (B^T\otimes 1)\right)^{-1}\text{vec}\;C,
$$
assuming that the last inverse exists...


What is the best way to learn Alzapua?

Question: Sometimes, when I do Alzapua, I can not produce clean sound, there're still I heard my thumb's nail picking. Usually, I use it while I'm playing (or learning with) some regular chord, like E major. Well, I do have long thumb nail because I want to learn that flamenco technique, because I think it'll be easier doing it while you have long nail.
Am I doing wrong step? If so, is there any method that I can try with?
Comment: I don't have enough experience with this technique to give a solid answer, but I can say it sounds like you would need to REALLY develop the right hand thumb for that technique, for instance by slowly alternate-picking with the thumb over single-string patterns. It can be easy to underestimate how much time you really have to spend to master a new technique. Good luck!
Answer: It is a difficult technique to acquire.
For clarity's sake, let us break it down as following:
(1) The base note
(2) The downward stroke
(3) The upward stroke
If your issue is failing to get a "clean sound", I'd recommend the following:

Always bear in my mind that (1) is the melody, the rest is just rythmic filling. The melody should always stand out and not be drowned out by the rythm added by (2) and (3). Focus on making the (1) stand out and that should go a long ways in cleaning up the sound.
Learn to control (2) and (3). Say you're practicing alzapua on a basic E chord. Instead of simply doing (2) and (3) across all strings or an indeterminate amount of strings, try limiting it to specific strings. For instance, start out with (1) on the sixth string, then do (2) and (3) only on the fifth string. Focus on not touching any of the other strings! Practice this, then move on to (1) on the sixth string and (2) and (3) across the fifth and fourth string. Then (1) on the sixth string and (2) and (3) across the fifth, fourth and third string, etc. etc. This will help substantially increase the precision of your alzapua.
Play with your wrist, not with your thumb. At high speeds, the thumb may in fact move a little bit but for the purposes of practicing, it shouldn't. The strength of the alzapua comes from a lateral movement of the wrist, not from moving the thumb. Extend your thumb so that it is slightly arched backwards. Then maintain that position all throughout the alzapua. The rest is done by turning your wrist. If you  bend your thumb forwards, you're doing it wrong. Some also advise to slightly extend your pinky finger, the idea being that it strengthens the balance of your hand (the pinky serving as a counterweight to your thumb).
Mix up the rythms. Because the alzapua consists of three movements, many people practice it as triplets. This is good practice, but you can also learn a lot by using other rythmic patterns. For instance, play an alzapua on a sixteenth note pattern, either by doubling (1) (to the effect of (1)-(1)-(2)-(3) and repeat) or by leaving a pause on the second sixteenth note (to the effect of (1)-pause-(2)-(3) and back to (1)).
Practice using your thumb as a pick. Practice on one string always alternating between a downward and upward stroke. Work on evening out the sound (which in this case means making sure your upward stroke is as loud as the downward stroke). This is good practice for alzapua but it is also a technique in itself used widely in the Jerez style of flamenco.
Don't play too fast! If your sound isn't clear playing triplets at 70 bpm. Bring it back down to 60 bpm. The key to a clean sound is slow practice. There's no jumping the gun here. If it doesn't sound right at 40 bpm, it will sound even worse at 180 bpm. I regularly use alzapua at buleria speed (160bpm and above) but I sometimes still practice at the lowest setting on the metronome.
Answer: Some Tips:

Hire time with an actual Flamenco guitarist if you are interested in true flamenco technique. This will answer most of your questions.
Make sure that you thumb nail is properly trimmed.
It's ok in the beginning steps if you hear some nail with this technique. If you are doing this to play the lightning fast scales that Flamenco guys like to do, it's going to be more about aggression and physicality than utter perfection and cleanliness.

As a master of the technique says in his youtube comments:
"as far as I do not see you actually playing it, I can't advise nor say even one word about it, "
Comment: I would advise some caution as to the teachings of Mr. Diaz. 80% of what he teaches is on point, but some of is not. He presents himself as a disciple of Paco de Lucia but Paco de Lucia's inner circle, when asked about him, described him as a stalker. That he is a shrewed businessman who has managed to fare well on the internet is one thing, to call him a master is another. This video seems legit, but others have been altered to give the impression that he is playing faster than he is. For beginners, it may be difficult to sort out which teachings are good, and which aren't.

What is the best way to learn Alzapua?


Create a view of all nodes that have the same value for a specified field as the current node

Question: So I have an event, which has a field called 'field_location'. I want to create a view on the event page where all other events are listed with the same location. In this case location is a node reference to a node (with content type 'location').
How can I dynamically filter all my event nodes on 'location value of the current event'?
I tried this with contextual filters but here it only checks the field you use, in this case 'field_location', with the content id of the url.
I already tried this but without success.

I get zero results.
Answer: Use Page manager and panels and add the view as a content pane. Then, pass the node's field's value as an argument to the pane(s) on the panel and you should be good to go.
Answer: Try this for you php code instead:
<code>$node = menu_get_object();
return $node->field_location['und'][0]['target_id'];
</code>
Does that work?
There's a similar question with a few answers here too: views and contextual filters with entity reference field.  There are also comments in that discussion about approaches that avoid poking around the node object and avoiding the ['und'][0] business.  Check that out too!
Comment: Alright tried that. I can't find a working solution. Is there also a way to output the value that you want to return to get an idea what's getting returned in the PHP Code?


Intercept Http call to SSL certificate

Question: Is there a way to intercept a call made by WebBrowser to SSL (within in an asp.net application)? I need to pass parameters to http-headers at runtime before the request is made.
Example: if I type "http://test.com", the browser communicates with the server and returns "https://test1.com" as the secured url. I should be be able to intercept the call and pass in headder information (key, value that determines the original host) to http://test.com. Or is there a better solution to achieve this?
Thanks in advance
Comment: Not sure what you mean... Is the interception to take place within the ASP.NET application. Or do you want to put a proxy in the middle?
Comment: in the asp.net application itself.
Answer: I do the following to force users to use HTTPS:
<code>protected override void OnPreInit(EventArgs e)
{
    if (string.Compare(Request.ServerVariables["HTTPS"], "OFF", true) == 0)
    {
        StringBuilder builder = new StringBuilder("https://");
        builder.Append(Request.ServerVariables["SERVER_NAME"]);
        builder.Append(Request.ServerVariables["URL"]);
        Response.Redirect(builder.ToString());
        return;
    }

    base.OnPreInit(e);
}
</code>
You should be able to modify it to do what you need.

Intercept Http call to SSL certificate


Why are tennis balls not airtight?

Question: I know tennis balls go flat (even if all they do is sit there) because the interior of the ball is actually pressurized above normal atmospheric pressure, and over time some of the air leaks out.
The question is, why aren't the balls manufactured with some material lining the interior that's properly airtight (creating balls that should never go flat)?  Do the rules of the game prohibit that sort of thing?  Or is it more that manufacturers would rather keep selling you new balls?  Or something else?
Comment: Aren't most balls( tennis balls, footballs, volleyballs, basketballs,... )not airtight? So I'm guessing there's a simple explanation for it, and not being a rule.

BTW: most tennis balls are apparently filled with nitrogen rather than air.

Only balls that are airtight (and not solid) that I can think of are pingpongballs. And they break rather quickly.
Answer: Tennis balls are mostly airtight.  They're made of rubber covered with felt; the rubber is quite good at keeping air in, but not perfect.  Some of the answer as to why they are not more airtight is due to cost (it would cost more), some is tradition (tennis balls are largely built the same way they always have been, at least in a long time), and some is physics (many of the things you might do to make them completely airtight would alter the rigidity of the ball).  Realistically a rubber ball is so good at keeping air in and is so cheap that it's not really worth the extra cost to make it last longer.
This is a difference in quality of ball, though: the much nicer, and more expensive, balls are less leaky than the cheaper balls you find at Wal-Mart.  I've also seen that some are filled with Sulphur Hexaflouride, which is a very heavy, inert gas; being heavy means it doesn't leak out nearly as fast as Nitrogen would (the other major option).

Why are tennis balls not airtight?


html global attributes React.js

Question: I apologize if this is a silly question, but maybe legitimate for the web developer newbie.
So I understand that a backend server serves HTML where the code is in the clients browser to render. With global HTML attributes I am learning that I can set an attribute contentEditable="true" in react and then in the browser I can edit the text.
import "./styles.css";

export default function App() {
  return (

Hello CodeSandbox

Start editing to see some magic happen!

  );
}

I am learning in code sand box with React. Is it possible on the client side browser to be able to change/edit the text in the html file and then for the server to save that data? So when the client closes the browser and then opens another session, that the changed edited text is present in the HTML file that was served by the server?
If it is possible to do something like this what would all go into this process explained a a high level for the newb to understand? Anything React related also greatly appreciated.
Answer: No question is silly!!!
Yes, you can do it all you need is an API to update and save at the server.
You have maintain a backend where you can store/update all the user data and serve when user comes at your website.
Comment: Would you know of any links to look at or tutorials? I am using React and Python backend servers. SO my react code would need to like POST to my backend Python server which would update the HTML file somehow? How does that work?
Comment: Are you maintaining Backend by yourself?
Comment: Yes my backend skills are much more developed that front end. I am learning front end so setting up an API for the backend is something I definitely understand.

html global attributes React.js


SAS and R survival package have different confidence interval estimates. Why?

Question: Hello I am learning about Survival Analysis and I noticed that SAS and R survival package produce different confidence interval estimates for the median Survival times and I was curious why?
Generating my simulated data in R
set.seed(123)
library(survival)
size <-  100

deathtime <- rexp(size, rate = 1)
censor <- abs(rbinom(size, 1, .1) -1)

df <- data.frame(deathtime, censor)
#write.csv(df, "TestData.csv") #For uses in SAS

Using the Survival package
surv.obj <- Surv(df$deathtime, df$censor)

survfit(surv.obj ~ 1)

Using SAS
proc import datafile="P:\SAS\Interval\TestData.csv" out = test;
run;

PROC LIFETEST PLOTS=(S) METHOD=PL;
     TIME   deathtime *censor(0) ;
 RUN;

Question
The point estimate is the same though the confidence intervals differs why?
Comment: Have you tried other transform? According to the `LIFETEST` procedure you can choose the transform using the `CONFTYPE` option https://documentation.sas.com/doc/en/statug/15.2/statug_lifetest_syntax01.htm#statug.lifetest.lftmethod. More details regarding computation of the confidence interval are given on page 33 here https://support.sas.com/documentation/onlinedoc/stat/141/lifetest.pdf
Comment: Yes @periwinkle as mentioned by EdM R has the `conf.type` argument to change the transform whose default is Log and SAS has the `CONFTYPE` to change the transform which default is log log. We figured it out
Answer: There are several ways to compute confidence intervals (CI) for survival curves. The SAS output suggests that it uses a log-log method based on $\log(-\log(\text{survival}))$.
Check the R documentation for survfit.formula to see its options for CI estimation. There is a default method for that function in R that isn't log-log. See what happens when you specify "log-log" as the method in R. Then, as suggested in a comment on your question, see what happens when you use SAS with different CI options.
Comment: Yes `survfit(surv.obj ~ 1, conf.type = "log-log")` Produced the same results as SAS
Comment: And adding a to SAS `CONFTYPE= LOG` leads to the same result in R.


Apache htaccess reliability

Question: I am denying access to certain files in the public_html folder with
<Files ~ "\.inc$">
    Order allow,deny
    Deny from all
</Files>

place in a .htaccess file.
I know it is best to put important files outside the public dir but I was wondering how reliable it is to refuse access with this (if it is possible to measure reliability)? Are there any tricks to get to those files?
Answer: To my knowledge it is reliable.
This of course can change fast, new bugs get discovered everyday.
However, one real concern is, if you make wrong change to your apache config and mistakenly disable parsing of .htaccess files without knowing/noticing it.
Then of course you are exposing these files.
While placing them outside of web reachable folders you avoid this possibility.
Answer: .htaccess is as reliable as any other Apache configuration directive, subject to the following caveats:

As faker pointed out above if you disable .htaccess parsing or protection in your main apache   configuration they stop working.
If you disable specific .htaccess directives (e.g. removing AuthConfig from the AllowOverride line) those features stop working.
If the .htaccess file is writable by the Apache user (or any user that a CGI runs as) they can be modified by a sufficiently determined hacker.
(This is actually a thing - Some Content Management Systems demand that they be able to modify the .htaccess file.  It can become a serious thing if you have a brain-damaged Apache configuration with AllowOverride All)

Apache htaccess reliability


Find $\lim\limits_{n\rightarrow\infty}\int\limits_0^1f(x^n)dx$

Question:
Let $f:[0,1]\rightarrow\mathbb{R}$ be  a continuous function.

Show that for each $\epsilon\in(0,1)$, $\lim\limits_{n\rightarrow\infty}\int\limits_0^{1-\epsilon}f(x^n)dx=(1-\epsilon)f(0)$
Find $\lim\limits_{n\rightarrow\infty}\int\limits_{0}^{1}f(x^n)dx$.
  Hint: Start by explaining why $f$ is bounded.

For my Answer:,
I have done the part one by using the fact that
\begin{align*}
\left|\int\limits_{0}^{1-\epsilon}f(x^n)dx-(1-\epsilon)f(0)\right|\leq \int\limits_0^{1-\epsilon}|f(x^n)-f(0)|dx
\end{align*}
And with the continuity of $f$ at zero along with $x^n\leq(1-\epsilon)^n\rightarrow0$
But for the part two what I can see is that:
\begin{align*}
\lim\limits_{n\rightarrow\infty}\int\limits_{0}^{1}f(x^n)dx &=\lim\limits_{n\rightarrow\infty}\lim\limits_{\epsilon\rightarrow0}\int\limits_{0}^{1-\epsilon}f(x^n)dx
\end{align*}
But there after if I need to make use of part (1) then I have to interchange the limits. So is it possible. If so, I would like to know what are the conditions we need to have for such an interchange.
Moreover I would like a feedback on the hint given. (Why is it given?)
Answer: Okay, so please let me state an analysis principle that will be very useful in numerous problems.
Interversion is painful.
Either there is a straightforward (« logically tautological », that is, that does not require any analysis) argument for doing it, or it requires thinking the whole reasoning through with more elaborate arguments (such as some form of uniform convergence).
So now, let $M$ be a bound for $f$. Let $\epsilon >0$. I suggest that you prove that
$$\left|\int_0^1{f(x^n)}-f(0)\right| \leq \left|\int_0^{1-\epsilon}{f(x^n)}-(1-\epsilon)f(0)\right| + M\epsilon + \epsilon |f(0)|. $$
Thus for every $n$ large enough $$\left|\int_0^1{f(x^n)}-f(0)\right| \leq 3M\epsilon$$.
Comment: Yes, unless you can use some more advanced machinery (double-limit theorems, uniform convergence and stuff), you have to prove the limit using $\epsilon$. On another note: if you wanted to have some $\epsilon$ in the final estimate, you would have to take the integral to $1-\frac{\epsilon}{3M+1}$.
Comment: Thank you @Mindlack.So this means we are proving the limit definition for this one as well. ?
Also I think if we choose the interval as  $(0,\frac{\epsilon}{3})$ we would end up in epsilon alone in the RHS
Answer: Another approach uses the mean value theorem for integrals. Indeed, set $g_n(x)=f(x^n).$ Then, there is a sequence $(c_n)\subseteq (0,1-\epsilon)$ such that $\int\limits_0^{1-\epsilon}g_n(x)dx=g_n(c_n)(1-\epsilon)=f(c^n_n)(1-\epsilon).$ Then, $c_n^n\to 0$ as $n\to \infty$ and so $f(c_n^n)\to f(0).$
For the second part, note that $\int_0^1f(x^n)\,dx=\int_0^{1-\epsilon}f(x^n)\,dx+\int_{1-\epsilon}^1f(x^n)\,dx,$ so we just need to consider the second integral. But as $g_n$ is bounded, we can apply the dominated convergence theorem to write $\lim \int_{1-\epsilon}^1f(x^n)\,dx=\int_{1-\epsilon}^1f(0)dx=\epsilon f(0)$.
Therefore, $\lim \int_0^1f(x^n)\,dx= f(0).$
Comment: why the downvote? since $(c_n)\subseteq (0,1-\epsilon),\ \limsup c_n^n\to 0$ and since $f$ is continuous, $f(c_n^n)\to 0$.
Answer: As $f$ is continuous at $0$, given $c>0$, there exists $\delta>0$ such that $|f(x)-f(0)|<c$ whenever $|x|<\delta$. So choose $n_0$ such that $(1-\epsilon)^{n_0}<\delta$. Then, for any $x<1-\epsilon$ and $n\geq n_0$, we have $x^n<\delta$; then $|f(x^n)-f(0)|<c$. Then
\begin{align}
(1-\epsilon)(f(0)-c)&=\int_0^{(1-\epsilon)}(f(0)-c)\,dx\leq\int_0^{1-\epsilon}f(x^n)\,dx\leq \int_0^{(1-\epsilon)}(f(0)+c)\,dx\\ \ \\ &=(1-\epsilon)(f(0)+c).
\end{align}
As we can do this for all $c>0$, we get
$$
\lim_{n\to\infty} \int_0^{1-\epsilon}f(x^n)\,dx=(1-\epsilon)f(0)
$$
For the second part, because $f$ is continuous and $[0,1]$ is compact, $f$ is bounded, say $a\leq f(x)\leq b$ for all $x$. Then, for any $\epsilon>0$,
$$
\int_0^1f(x^n)\,dx=\int_0^{(1-\epsilon)}f(x^n)\,dx+\int_{(1-\epsilon)}^1f(x^n)\,dx.
$$
For the second integral,
$$
\epsilon\, a\leq \int_{(1-\epsilon)}^1f(x^n)\,dx\leq \epsilon\, b.
$$
Then
$$
\limsup_n\int_0^1f(x^n)\,dx= (1-\epsilon)f(0)+\int_{(1-\epsilon)}^1f(x^n)\,dx\leq(1-\epsilon)f(0)+\epsilon\,b.
$$
As this works for all $\epsilon>0$,
$$\tag1
\limsup_n\int_0^1f(x^n)\,dx\leq f(0).
$$
Similarly,
$$
\liminf_n\int_0^1f(x^n)\,dx= (1-\epsilon)f(0)+\int_{(1-\epsilon)}^1f(x^n)\,dx\geq(1-\epsilon)f(0)+\epsilon\,a.
$$
As this works for all $\epsilon>0$,
$$\tag2
\liminf_n\int_0^1f(x^n)\,dx\geq f(0).
$$
Now $(1)$ and $(2)$ together imply that that $\lim_n\int_0^1f(x^n)\,dx$ exists and that
$$
\lim_n\int_0^1f(x^n)\,dx=f(0).
$$
Answer: So you managed to show that for each $\varepsilon\in(0,1)$ you get:
$$ \lim\limits_{n\to\infty}\int\limits_0^{1-\varepsilon}f(x^n)\,{\rm d}x=(1-\varepsilon)f(0) $$
So for each $\varepsilon\in(0,1)$ you can now look at the following:
$$ \int\limits_0^1f(x^n)\,{\rm d}x=\int\limits_0^{1-\varepsilon}f(x^n)\,{\rm d}x+\int\limits_{1-\varepsilon}^1f(x^n)\,{\rm d}x$$
Since you know that $f$ is bounded (a continuous function on a closed interval) you know there exists some $M>0$ such that:
$$ \forall x\in(0,1),-M\leq f(x)\leq M $$
So you can show that for second interval you get:
$$ -M\varepsilon\leq\int\limits_{1-\varepsilon}^1f(x^n){\rm d}x\leq M\varepsilon $$
Or in other words:
$$ \int\limits_0^{1-\varepsilon}f(x^n)\,{\rm d}x-M\varepsilon\leq \int\limits_0^1f(x^n)\,{\rm d}x\leq \int\limits_0^{1-\varepsilon}f(x^n){\rm d}x+M\varepsilon $$
Taking the limits on all sides as $n\to\infty$ you get using the first part:
$$(1-\varepsilon)f(0)-M\varepsilon\leq\lim\limits_{n\to\infty}\int\limits_0^1f(x^n)\,{\rm d}x\leq(1-\varepsilon)f(0)+M\varepsilon $$
Lastly, taking the limit $\varepsilon\to 0$ gives you the result:
$$ \lim\limits_{n\to\infty}\int\limits_0^1f(x^n)\,{\rm d}x=f(0) $$
Answer: Another approach would be to use some measure theory:
Clearly for all $x \in [0,1-\epsilon)$ we have that $x^n \to 0$ as $n \to \infty$, and hence $f(x^n) \to f(0)$ by continuity for all such $n$. Now since the Riemann integral exists, it is equal to the Lebesgue integral;
$lim_{n \to \infty}\int_{0}^{1-\epsilon}f(x^n)dx = lim_{n \to \infty}\int_{[0,1-\epsilon]}f(x^n)d\lambda(x) =_{(1)} \int_{[0,1-\epsilon]}f(0)d\lambda(x) = (1-\epsilon)f(0)$, since $f$ is dominated by the constant $sup_{x \in [0,1]}\{|f(x)|\}<\infty$ and thus the dominated convergence Theorem implies (1). The same argument works for the second part of your question, since $f(x^n) \to f(0)$ for all $x \in [0,1)$ and $\{1\}$ is a Lebesgue null set, thus does not change the value of our integral; that yields $lim_{n \to \infty}\int_{0}^{1}f(x^n)dx = f(0)$


Apache serves garbage content

Question: I've set up an apache2 (Apache/2.2.16) on a VirtualBox (4.2.6) driven Debian (6.0.6) running on a Mac OS 10.7 host system. I mount a shared folder by fstab with the following configuration:
htdocsshare /home/dev/htdocsshare vboxsf defaults,uid=1000,gid=1000 0 0

The mount works fine, the default user (dev, 1000) has read and write permissions. I run the apache as this user (dev, 1000 – and yes, I know, that has a bad taste, but I don't really think thats the problem here).
I've set up a catchall vhost, with DocumentRoot set to /home/dev/htdocsshare (no further settings changed). Apache displays the files and folders in there correct, but when trying to open a file, it serves garbage content. Sometimes it looks like shell script or something like that, as I can recognize messages with variable placeholders.
Opening the files on the mount with vi/vim also works fine. But even if i touch and modify a file within the guest system, apache reads garbage characters. Does anyone have a hint or know what the problem is? Google didn't tell me much, but I don't really know what to search for. Thanks.
Edit: I recognized, the content changes from time to time and not reproducible. Here is something it delivers me for an apache error-log (from another server).
Answer: Two features the vboxsf may not support: mmap and sendfile. Try adding these to your apache config:
EnableMMAP off
EnableSendfile off

Apache serves garbage content


Can't force 'https' and reverse proxy with Apache at the same time

Question: Really racking my brain over this one. I need to always force 'https' whenever a user requests 'http' on my site, but at the same time I need to proxy pass from Apache to Tomcat (over http). I can't get these two pieces to work in tandem.
I have the https redirect defined here in httpd.conf:
<VirtualHost *:80> ServerName myserver.foo.com
    Redirect / https://myserver.foo.com/
</VirtualHost>

Then for the proxy:
RewriteEngine on
RewriteLog /opt/HTTPServer/logs/rewrite_log
RewriteLogLevel 9
RewriteRule ^/testnew/MyApp(.*)$  http://localhost:8080/test/MyApp$1?product=new  [NC,P,QSA]
RewriteRule ^/testold/MyApp(.*)$  http://localhost:8080/test/MyApp$1?product=old  [NC,P,QSA]

Note: This does actually work if I use ProxyPass instead, but I need to be able to add additional GET parameters to the request, hence the use of the [P] flag approach here.
So when I hit the following URL, I get the Apache HTTP Server page which reads "Not Found".
http://myserver.foo.com/testnew/MyApp/RunReport
In the access log, there's a 404
[10/Nov/2014:01:45:21 -0600] "GET /testnew/MyApp/RunReport HTTP/1.1" 404 321

Also, nothing gets written to the rewrite log.
As I understand it, RewriteRules will execute BEFORE Redirect, so even if the above URL did work (and I don't understand why it doesn't), it wouldn't get redirected from http to https.  So how can I accomplish this?
I also tried this using only RewriteRules:
RewriteEngine on
RewriteCond %{HTTPS} !on
RewriteRule ^(.*)$  https://%{HTTP_HOST}$1  [R=301]

RewriteRule ^/testnew/MyApp(.*)$  http://localhost:8080/test/MyApp$1?product=new  [NC,P,QSA]
RewriteRule ^/testold/MyApp(.*)$  http://localhost:8080/test/MyApp$1?product=old  [NC,P,QSA]

However with this, the URL gets translated to include the https scheme and hostname after the 1st redirect, so the subsequent RewriteRules fail to match.  If I add the full 'https://myserver.foo.com' to the RewriteRule, it matches, but then the full URL gets translated back to http via the proxy.
I can't win!  This seems to me like it would be a fairly common configuration. Did I completely miss something?  I've been looking at this too long.
Answer: I was able to get this to work by moving the proxy RewriteRules under the *:443 VirtualHost and leaving the http -> https ones at the global level, i.e.
Listen 443
<VirtualHost *:443>
    SSLEnable
    SSLClientAuth None
    RewriteEngine On
    RewriteLog /opt/HTTPServer/logs/rewrite_log-443
    RewriteLogLevel 9

    RewriteRule ^/testnew/MyApp(.*)$  http://localhost:8080/test/MyApp$1?product=new [NC,P,QSA]

</VirtualHost>

...
...

RewriteEngine on
RewriteCond %{HTTPS} !on
RewriteRule ^(.*)$  https://%{HTTP_HOST}$1  [R=301]

Works beautifully now. :)


real memory increase when remove a custom view which contains few subviews IOS(ARC)

Question: I have an iPad app which is crashing on iPad (First model) as it is running out of memory.
I create a custom view called RoadSectionView which means one road, and another custom view called CrossRoadView which contains four RoadSectionViews.
RoadSectionView.h:
#import "GestureView.h"

@interface RoadSectionView : GestureView <NSCopying,NSCoding>

@property (nonatomic, assign) CGPoint startPoint;       //手指触摸起始点
@property (nonatomic, assign) CGPoint endPoint;         //手指触摸终止点

@property (nonatomic, strong) UIImageView *startPointView;     //起始控制点
@property (nonatomic, strong) UIImageView *endPointView;       //终止控制点

@property (nonatomic)NSString *type;               //路段的类型
@property (nonatomic)NSString *roadName;           //路段名称

@property (nonatomic, assign)NSInteger roadWidth;            //路道宽,默认为350
@property (nonatomic, assign)NSInteger roadIslandWidth;      //中间路岛宽,默认为40
@property (nonatomic, assign)NSInteger upOrLeftLaneNum;      //上或左路段的路道数,默认为2
@property (nonatomic, assign)NSInteger downOrRightLaneNum;   //下或右路段的路道数,默认为2

@property (nonatomic) NSArray *startUpOrLeft;              //上或左起始点数组
@property (nonatomic) NSArray *startDownOrRight;           //下或右起始点数组
@property (nonatomic) NSArray *endUpOrLeft;                //上或左终止点数组
@property (nonatomic) NSArray *endDownOrRight;             //下或右终止点数组

- (void)drawView:(CGPoint)point1 :(CGPoint)point2;
- (void)addControlPoint:(CGPoint) start : (CGPoint) end;
- (id)initWithFrame:(CGRect)frame : (NSString *)name;

@end

here is the CrossRoadView.h
#import "GestureView.h"
#import "RoadSectionView.h"

@interface CrossRoadView : GestureView<NSCopying,NSCoding>

@property (nonatomic) NSString *type;

@property (nonatomic, assign) CGPoint centerPoint;

@property (nonatomic, strong)RoadSectionView *leftRoad;
@property (nonatomic, strong)RoadSectionView *rightRoad;
@property (nonatomic, strong)RoadSectionView *upRoad;
@property (nonatomic, strong)RoadSectionView *downRoad;

- (void)drawView:(CGPoint)start;
- (id)initWithFrame:(CGRect)frame : (NSString *)name;
- (void)addControlPoint;
- (void)addDistanceLine;
- (void)drawConnectLines;

@end

the GestureView.h file:
#import <UIKit/UIKit.h>

@interface GestureView : UIImageView <UIGestureRecognizerDelegate,  UIPopoverControllerDelegate,NSCoding,NSCopying>

@property (nonatomic, retain) UIView *parentView;

@property  BOOL isPanEnable;
@property  BOOL isRotateEnable;
@property  BOOL isPinchEnable;

@property BOOL doesHaveTreelawn;

@property (nonatomic) CGPoint imagePoint;       //记录添加的view的在父视图中的起点
@property (nonatomic) CGFloat imageSize;        //记录放缩的倍数
@property (nonatomic) CGFloat imageRotation;    //记录旋转的角度
@property (nonatomic) CGPoint imageTranslate;   //记录平移的大小

@property (nonatomic, assign) CGPoint upContrlPoint;
@property (nonatomic, assign) CGPoint downContrlPoint;

@property (nonatomic, retain) UIPopoverController *popoverController;

- (void)handlePan:(UIPanGestureRecognizer *)recognizer;
- (void)handlePinch:(UIPinchGestureRecognizer *)recognizer;
- (void)handleRotate:(UIRotationGestureRecognizer *)recognizer;
- (void)handleLongPress:(UILongPressGestureRecognizer *)recognizer;

- (void)setGesture:(UIView *)parent : (BOOL)isPan : (BOOL)isPinch : (BOOL)isRotate;

@end
when I add few of RoadSectionView in rootView, and than remove them, it works fine, the real memory didn't increased.
the remove code is
[self.canvasView.subviews makeObjectsPerformSelector: @selector(removeFromSuperview)];

but when I add few of CrossRoadView in rootView, than I remove them, the real memory increased, as I save them to disk, the canvasView will first remove all subViews when open the file, than I open the file several times, the app crashed
can you help me!! Thanks very much
Comment: Could you please share your CrossRoadView.h file. Thank you
Comment: What is parentView for in GestureView?
Comment: self.superView, it do nothing
Comment: thanks, here is the problem! I shouldn't set it to `strong`, it comes into being a retain cycle
Answer: You probably don't need to use strong property for the RoadSectionView since they will be retained by the superview (CrossRoadView) when you will add them as subview.
Then, they will be release when the superview is destroyed.
Try to use
@property (nonatomic, weak) RoadSectionView *leftRoad
...

Comment: I change it to `weak` property, but when I create the leftRoad,`_leftRoad = [[RoadSectionView alloc] initWithFrame:self.frame :@"直绘路段"];`, it sad assigned retained object to weak variable, and it the leftRoad can't draw
Comment: Could you explain how work your view hierarchy please ?
Comment: the four RoadSectionRoad first draw respectively, then add to CrossRoadView, in CrossRoadView draw their connection, the GestureView is a UIImageView which add several gesture
Comment: Could you please add the GestureView.h file ?
Comment: And `RoadSectionView.h`
 :p ?
Comment: Ok Then, maybe my answer should be applicated to both of the `UIImageView` properties in `RoadSectionView` or is there another reason to have them strong ?
Comment: I set the properties to `weak`, then how can I create it? it don't work when use `[[object alloc] init...]`


Recovering a mdadm+lvm+ext4 partition with read error

Question: One of disks in my NAS has failed.
The NAS is running Linux, and it uses mdadm + LVM technology for its filesystems.
I do have backup for most of the contents, but not for the very last changes, and if possible, I'd like to recover that from this failing disk.
The disk (a 'green drive' WD10EARS 1TB in size) throws this kind of errors:
Oct  3 12:00:41 kernel: [ 3625.620000] ata5.00: read unc at 9453282
Oct  3 12:00:41 kernel: [ 3625.620000] lba 9453282 start 9453280 end 1953511007
Oct  3 12:00:41 kernel: [ 3625.620000] sde5 auto_remap 0
Oct  3 12:00:41 kernel: [ 3625.630000] ata5.00: exception Emask 0x0 SAct 0x1 SErr 0x0 action 0x6
Oct  3 12:00:41 kernel: [ 3625.630000] ata5.00: edma_err_cause=00000084 pp_flags=00000003, dev error, EDMA self-disable
Oct  3 12:00:41 kernel: [ 3625.640000] ata5.00: failed command: READ FPDMA QUEUED
Oct  3 12:00:41 kernel: [ 3625.650000] ata5.00: cmd 60/40:00:e0:3e:90/00:00:00:00:00/40 tag 0 ncq 32768 in
Oct  3 12:00:41 kernel: [ 3625.650000]          res 41/40:00:e2:3e:90/12:00:00:00:00/40 Emask 0x409 (media error) <F>
Oct  3 12:00:41 kernel: [ 3625.660000] ata5.00: status: { DRDY ERR }

However, while testing with 'dd', I noticed that if I skip the first 4kB, the read seems to be ok,
i.e. a command like.
    dd if=/dev/sde5 of=dev/null bs=4k count=1000 skip=1
doesn't return any read error.
Supposing that there is no other read failure in the rest of the disk, would I be able to recover this 900 GB partition (as I mentioned before, it's a 'linux raid autodetect' partition, that contains a a LVM2 volume that contains a ext4 filesystem) if I copy-clone the partition somewhere else, but the first 4kB?
Comment: If the RAID is not degraded already, than you really don't need to recover anything. Just replace the drive with the new one and do resync.
Comment: (Obviously?) I would have not posted the question if there would have been another mirror to use for resyncing.
Answer: ...Otherwise (i.e. if you already have degraded array) you still should be able to do it.
If your mdadm which created the array is < v.3.0, than the payload starts in offset 0x22000 (and further up if it is v.3.0 or later), which as well before the deleted first 4KB.
So only the linux-raid superblock got corrupted, but that is not that difficult to restore (especially if you have other devices in that array intact).
Comment: Thanks, so there is some hope. The disk in question is (or rather was) the last one of the array, although I have another disk belonging to a different array that has a similar structure.  In that case how do you suggest to repair the superblock?
Comment: Well, this is a good question on its own. Try the answer on [this question](http://serverfault.com/questions/427683/what-parameters-to-mdadm-to-re-create-md-device-with-payload-starting-at-0x2200). In short: if you know the array parameters (including the relative position of the device in the array) **and** you use mdadm with the version that puts the superblock in the same offset as the mdadm used to create it originally, (and of course you `--assume-clean`), than I believe you are safe.
Answer: Considering that it was a relatively simple case, an md device working as single physical device for a LVM volume linearly allocated, and that wraps a single ext4 fs, my solution was to go directly after the ext4 fs and mount it as a loop filesystem for the time necessary to the recovery.
My steps:

As mentioned above, with dd I copied the whole damaged partition to a similar-sized partition on a healthy disk (here below named /dev/sdd5)
I copied the first MB of /dev/sdd5 to a file and imported to my Ubuntu desktop computer, where I opened it with hex editor ghex
I saw from ext wiki https://ext4.wiki.kernel.org/index.php/Ext4_Disk_Layout#The_Super_Block that EXT4 superblock has at offset 0x38 the magic number 0xEF53 and from my hex dump I could find that signature.
Redoing the same with a different, healthy ext4 filesystem, I found that the beginning of superblock is 1024 bytes after beginning of partition, so I calculated what would be the offset from begin of partition sdd5 to beginning of the ext4 partition I was looking for.
I created the loop partition with losetup -o <offset> /dev/loop0 /dev/sdd5
Verified with fsck -n /dev/loop0 that offset was right as I indeed got a valid ext fs and that the filesystem was at least in a consistent state.
I mounted the loop fs in read-only mode to a temporary directory: mount -o ro /dev/loop0 /tmp/recovery

At this point I could begin to access the content I wanted to recover from /tmp/recovery/.


Format of adding hidden layers in Keras.

Question: I wrote a neural network code and I want to add hidden layers to it. I have access to this small part of code:
trainX, trainY = create_dataset(train, look_back)
testX, testY = create_dataset(test, look_back)

trainX = numpy.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))
testX = numpy.reshape(testX, (testX.shape[0], 1, testX.shape[1]))

model = Sequential()
model.add(LSTM(4, input_shape=(1, look_back)))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(trainX, trainY, epochs=100, batch_size=1, verbose=2)

trainPredict = model.predict(trainX)
testPredict = model.predict(testX)

Is there any way to add hidden layers to it with this much information available? Also, this code works fine in Python3.
It would be a great help. Thanks.
Comment: I think this link should help. [Create your own NN](https://becominghuman.ai/creating-your-own-neural-network-using-tensorflow-fa8ca7cc4d0e)
Answer: The mentioned code is the entire implementation of core ML part.
Here you created model,
model = Sequential()
This is input layer,
model.add(LSTM(4, input_shape=(1, look_back)))
This is output layer
model.add(Dense(1))
Model compilation
model.compile(loss='mean_squared_error', optimizer='adam')
Model training
model.fit(trainX, trainY, epochs=100, batch_size=1, verbose=2)
Any layer added between input and output layer is called Hidden layer, you can easily add and your final code will look like below,
trainX, trainY = create_dataset(train, look_back)
testX, testY = create_dataset(test, look_back)

trainX = numpy.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))
testX = numpy.reshape(testX, (testX.shape[0], 1, testX.shape[1]))

model = Sequential()
model.add(LSTM(4, input_shape=(1, look_back)))
model.add(Dense(4)) # New hidden layer with 4 params
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(trainX, trainY, epochs=100, batch_size=1, verbose=2)

trainPredict = model.predict(trainX)
testPredict = model.predict(testX)

Answer: You can try adding hidden layers using the following format structure. The example is not applied to your problem, though:
from tensorflow.keras.layers import Dense
from tensorflow.keras import Model, Input

input_layer = Input(shape=(3,), name='input') # 3 dimensional input
hidden_layer1 = Dense(units=20, activation="sigmoid", name="hidden_layer1")(input_layer)
hidden_layer2 = Dense(units=20, activation="sigmoid", name="hidden_layer2")(hidden_layer1)
output_layer = Dense(units=1, activation="sigmoid", name="output_layer")(hidden_layer2)

# Create the model
model = Model(input_layer, output_layer)


Bonjour networking (sending messages) to more than two iOS devices

Question: I'm using example code from the answer on this Stack Overflow question (http://stackoverflow.com/questions/3240617/cfnetwork-and-bonjour-integration-for-iphone-to-mac-integration) which you can download here
I have the code running and I am able to send a message to the other device. Is there any way to link more than two devices to this network so that messages can be sent to specific devices in the device list at the same time?
Here's the plan for an app;
I want one admin version of the app which the admin user can send a message out to all the connected iPads (up to 12) in a list. Once they receive the message, they can reply to it and the admin user can see which iPad has sent the reply. How can this be done?
Answer: You should advertise two bonjour services, a server-service and a client-service.
Servers should connect only to clients and clients should connect only to servers.
Bonjour is a service discovery protocol that makes the process of "knowing" peers in a network. This means, once you know the peer (server/client), you (and not Bonjour) have to establish the connection and from then on, it's up to your app to do what it wants to do.
Do note that, you have to remember the IP address of the clients you connect to (you get this information from the Bonjour service) and reconnect when the app awakes from sleep (iOS closes socket connections when the app enters the background.
Comment: I have no idea how to implement this sort of development into my project - are there any sample projects out there which provide multiple connection support?
Answer: Not sure if I'm too late on this one, but check out Chatty. It's really really cool. I ported the iPhone app to Mac rather easily and set it as the server and the iPhone apps as clients.
I was using the code in the example app you posted at first, and was struggling to find out why it only allowed one connection. Thankfully, I was able to convert Chatty to my needs.


Understanding a theorem of Saint-Donat

Question: In his thesis on K3 surfaces Saint-Donat proves the following fact (thm 6.1)

Let $L$ be a line bundle on a K3 surface $X$ such that the linear system $|L|$ has no fixed components and the morphism $\varphi_L$ is birational. Then the natural map
  $$S^\ast H^0(X,L)\rightarrow\oplus_{n\geq0} H^0(X,L^{\otimes n}) $$
  is surjective.

Denote by $I$ the kernel of this map. Later in the paper (thm 7.2) Saint-Donat shows that $I$ is generated by elements of degree $2$ and $3$.
Now, my problem is that I do not understand the notation $S^\ast H^0(X,L)$, and as a consequence what is the map and why $I$ is the homogeneous ideal of the image surface $S=\varphi_L(X)$.
Any elaboration on these concepts would be very useful :)
Comment: I believe $S^*(V)$ is the symmetric algebra on a vector space $V$. This is the homogeneous coordinate ring of $\mathbb{P}(H^0(X, L)^*)$, the target of $\varphi_L$. The map here fits together the ,ultiplication maps like $H^0(X, L) \times H^0(X, L) \to H^0(X, L \otimes L)$, which are symmetric because everything is $1$-dimensional.
Answer: As Hoot points out $S^\ast H^0(X,L)$ is the symmetric algebra of the finite-dimensional vector space $H^0(X,L)$. Elements of $S^\ast H^0(X,L)$ are polynomials with variables $s_0,...,s_n$ a base of sections from $H^0(X,L)$.
The graded component of $S^\ast H^0(X,L)$ of degree $d \in N$ are all homogeneous polynomials of degree d. Furthermore, the canonical map
$$f: S^\ast H^0(X,L)\rightarrow\oplus_{n\geq0} H^0(X,L^{\otimes n})$$
is defined by taking the product of sections. Its image are those sections in $L^{\otimes n}$ which are - globally - the product of sections in $L$. If $L$ has no base-points, then its complete linear system defines the holomorphic map
$$\phi_L: X \longrightarrow \check{\mathbb P}(H^0(X, L)), x \mapsto [s \mapsto s(x)].$$
Here $\phi_L(x)$ is considered a linear functional on $H^0(X, L)$. The image $\phi_L(X) \subset \check {\mathbb P} (H^0(X, L))$ is the projective variety $Var(I)$ with
$$I := ker \ f \subset S^\ast H^0(X,L)$$
the ideal generated by all homogeneous polynomials which vanish on all points $x \in X$.
Probably it helps imagining $H^0(X,L)$ as $\mathbb C^{n+1}$. Then it could be easier to connect to the classical context of projective space and its subvarieties defined by homogeneous polynomials.
Note. There is a companion to Saint-Donat's paper by Francois C. Cossec: Projective Models of Enriques Surfaces. Math. Ann. 265, 283-334 (1983)
Comment: thank you Jo, for your very clear and detailed answer. It helps!

Understanding a theorem of Saint-Donat


Custom module 'managed_file' variable info keeps disappearing

Question: I have a custom module which allows a 'managed_file' upload in the settings/config page. This works fine and displays as expected after uploading (with the filename linked, and a "Remove" submit button) but the value of the field keeps disappearing after some time. What am I missing?
Here's the code from the custom module:
  $form['custom_managed_jpg'] = array(
    '#type' => 'managed_file',
    '#name' => 'custom_managed_jpg',
    '#title' => 'Custom Image (JPG)',
    '#default_value' => variable_get('custom_managed_jpg', ''),
    '#upload_location' => 'public://custom_directory/',
    '#upload_validators' => array(
      'file_validate_extensions' => array('jpg'),
    ),
    '#description' => t('This is a custom image (jpg format).'),
  );

It appears to be a problem with the file_load function. The variable is indeed saved, as I get a file ID when I dpm() the variable_get('custom_managed_jpg') (a number -- the fid). However, when I dpm() the result of file_load($fid) it is empty.
The strangest part is that this works as expected to start with, and the file will even remain between page loads and cache clears, but then after a few hours it just disappears as described above without any warning.
UPDATE:
It seems that the reason file_load doesn't return anything is that the directory (public://custom_directory/) is empty. At some point these files are being deleted from the directory but I have no idea why.
UPDATE2:
When I watch the file_managed table, I can see a new file added after uploading. The one difference between files uploaded here and those already in the table is that the status field is set to 0 instead of 1. I am guessing that could be part of the problem? How/where do I set the status to 1 programmatically?
Answer: Scott's code is right (and is nearly identical to what I had) but the final step I was missing is in the form's submit handler, where I needed to grab the file that was uploaded and mark it as permanent, and add a file usage to tell Drupal the file was in use. By default Drupal treats uploaded files as temporary and they are deleted from the database and filesystem after 6 hours (when cron runs).
Here's the submit handler code.
function MODULE_admin_settings_submit($form, &$form_state) {
  global $user;
  if (isset($form_state['values']['custom_managed_jpg']) && $form_state['values']['custom_managed_jpg']!="") {
    // Load the file via file.fid.
    $file = file_load($form_state['values']['custom_managed_jpg']);
    // Change status to permanent.
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);
    // Record that the module (in this example, "custom module") is using the file.
    file_usage_add($file, 'custom_module', 'custom_managed_jpg', $user->uid);
  }
}

Answer: If you're using Drupal 4.7 this will not work for you (hook_settings is from Drupal 4.7).
Set up the menu item:
function MODULE_menu() {
  $items = array();

  $items['admin/config/PATH'] = array(
    'title'             => 'TITLE',
    'description'       => 'DESCRIPTION',
    'page callback'     => 'drupal_get_form',
    'page arguments'    => array('MODULE_admin_settings'),
    'access callback'   => 'user_access',
    'access arguments'  => array('administer site configuration'),
  );

  return $items;
}

Page Callback Function must return system_settings_form($form):
function MODULE_admin_settings() {
  $form['fieldset_homepage']['custom_managed_jpg'] = array(
    '#type' => 'managed_file',
    '#name' => 'custom_managed_jpg',
    '#title' => 'Custom Image (JPG)',
    '#default_value' => variable_get('custom_managed_jpg', ''),
    '#upload_location' => 'public://custom_directory/',
    '#upload_validators' => array(
      'file_validate_extensions' => array('jpg'),
    ),
    '#description' => t('This is a custom image (jpg format).'),
  );

  return system_settings_form($form);
}

system_settings_form will save all form fields to the variable table and I think is the part you are missing.
Comment: Thanks, I misspoke RE: hook_settings! Actually the full code I have looks a lot like this but it just seems like the file disappears from the settings after a while. I guess I need to do further troubleshooting. Will post back with any other relevant info.
Comment: I've updated my question.


What are the marathons with the largest number of participants?

Question: In my opinion, this is a great topic but it does not fit on this website.
So I think that an objective criteria to compare marathons could be the number of participants.

So what are the city marathons with the largest number of participants by continent?

I would like to consider only the marathons available for amateurs (no requirements of qualifying times, only something like a bill of health).
Answer: The largest marathons by continent, as of 2016, are:

North America: New York City
Europe: Paris
Asia: Tokyo International
Africa: Soweto
South America: Buenos Aires
Australia: Melbourne

(Source: ARRS.)
South Africa's Comrades Marathon would be considered, but it is actually an ultramarathon.
South America has a very big Sao Silvestre race in Brazil (New Year's Eve traditionally has multiple Saint Silvester races worldwide) but it's 15km, not a marathon, despite being listed as one in several places.
Comment: In the "interesting side note" department, the largest Japanese marathon used to be in Hawaii. Marathon running is a huge sport in Japan, but until fairly recently the major Japanese marathons (Fukuoka, Osaka, Beppu-Oita, et al) were invitation only and did not have mass-participation entry. Therefore, Japan Air Lines became a sponsor of the Honolulu Marathon, and for a long time the majority of the entrants in Honolulu were Japanese. I don't know if this is still true now that there are some mass-participation marathons in Japan, though.


What is the variance of a binomial distribution with -1 and 1?

Question: I am struggling to see how to solve the following problem:

I have n i.i.d bernoulli trials. The result can be -1 or 1. I can figure out the expected value of this = n(p-(1-p) but how do I know what the variance is if p is known?

I know that:
$$
{\rm Var}(X) = E[X^2] - E[X]^2
$$
I don't know where to go from here.
Comment: In general, for a Bernoulli Random Variable E(X) is $P(X=x_1)*x_1+P(X=x_2)*x_2$. In the "default" case $x_1 = 1, x_2 = 0$, which reduces this to E(X) = p. In your case, $x_1 = 1 $  and $x_2 = -1$. You can then plug in what you get for E(X) into the formula $Var(X) = E(X^2) - E(X)^2$. The variance of the default case is $p*(1-p)$
Comment: If B is a 0-1 Bernoulli variable with probability of a 1 at $p$, then you're describing a variable, ($Z$ say) where $Z=2B-1$. Just apply basic [properties of variance](https://en.wikipedia.org/wiki/Variance#Basic_properties) to that linear transformation.
Answer: When you work with variances, know these facts (in addition to the definition of variance):

The variance of a sum of independent (or just uncorrelated) variables is the sum of their variances.
The expectation of a sum of variables (independent or not) is the sum of their expectations.
The expectation (of any discrete variable) is the sum of each possible value multiplied by its probability.

As an example, let's apply them to your case.  You may model the sum of your Bernoulli trials with a variable $X$ expressed as the sum of $n$ independent variables $X_i$.  Each $X_i$ takes on the value $1$ with probability $p$ and the value $-1$ with the probability $1-p$.
Fact $(3)$ asserts $$\mathbb{E}(X_i) = p(1) + (1-p)(-1) = 2p-1$$ and $$\mathbb{E}(X_i^2) = p(1)^2 + (1-p)(-1)^2 = p + (1-p) = 1.$$
Fact $(2)$ asserts $$\eqalign{\mathbb{E}(X) &= \mathbb{E}(X_1+\cdots+X_n) = \mathbb{E}(X_1) + \cdots + \mathbb{E}(X_n) = n\mathbb{E}(X_1) \\&=n(2p-1).}$$
The definition of variance now tells you$$\operatorname{Var}(X_i) = \mathbb{E}(X_i^2) - \mathbb{E}(X_i)^2 = 1 - (2p-1)^2 = 4p(1-p).$$
Consequently, fact $(1)$ yields $$\eqalign{\operatorname{Var}(X) &= \operatorname{Var}(X_1+\cdots+X_n) = \operatorname{Var}(X_1) + \cdots + \operatorname{Var}(X_n)=n \operatorname{Var}(X_1) \\&= n(4p(1-p)).}$$

The appearance of the factor of $4$ might seem somewhat mysterious.  There's another extremely useful fact you might consider using to shortcut these considerations and identify the origin of that factor:
(4) The variance of a shifted, rescaled variable is the square of the scale factor times the variance. In mathematical symbols, $$\operatorname{Var}(\sigma X + \mu) = \sigma^2 \operatorname{Var}(X)$$ no matter what values the numbers $\sigma$ and $\mu$ might have.
This applies by noting that your $X_i$ can all be expressed as $2Y_i-1$ where $Y_i$ is a true Bernoulli (that is, $0-1$) variable.  It's simple to show this: since $2\times 1-1=1$ and $2\times 0 - 1=-1$, the values of $1$ and $0$ taken on by $Y_i$ become $1$ and $-1$, respectively, for $X_i$.  The probabilities are unchanged.
You might already know that $Y=Y_1+\cdots + Y_n$, the sum of $n$ independent Bernoulli variables with common probability $p$, is called a Binomial variable.  It has a Binomial distribution.  You can remember or look up its variance, which is $np(1-p)$.  Since $$X = X_1+\cdots+X_n = (2Y_1-1) + \cdots + (2Y_n-1) = 2(Y_1 + \cdots + Y_n) - n=2Y-n,$$ you can take $\sigma=2$ in applying fact $(4)$, which immediately tells you $$\operatorname{Var}(X) = 2^2 \operatorname{Var}(Y) = 4np(1-p).$$
Comment: I personally find the observation that $4=\frac{1}{0.5(1-0.5)}$ soothing as it shows that the variance is the ratio of $pq(X_i)$ to $pq(0.5)$ (forgive the abuse of notation).
Comment: In what sense is the second part of the answer $X_i=2Y_i-1$ ... different from my answer ?
Comment: @fcop It's exactly the same approach--but the explanation is more extensive and thorough. If you take a look over the entirety of my answer, I hope you will see the pattern: it focuses on stating and illustrating useful principles. These are often overlooked or unknown to people who come to our site with questions. My purpose is to collect, unify, and illustrate some (obvious, well-known) techniques that can be found by future visitors and referenced in future answers. In that sense, my answer differs from yours, which focuses on solving the immediate problem.
Comment: Well you could have referenced it no?
Comment: @fcop One ordinarily does not reference obvious or well-known things. (If that were the practice, then most posts would be 90% references.)  The point of this answer is to explain the *reasoning*--not just the results--at the same level of understanding as the question.  Its contribution is not to make the observation that $X_i=2Y_i-1$ (you're welcome to take credit for that), but rather to show *as clearly and explicitly as possible,* with all reasons supplied, how that produces the *same* answer derived earlier in the question.
Comment: @whuber: reference a comment to a question in an answer to that same question when you almost copy the comment is not realy the same as reference whatever post on this site I would assume?
Answer: if you take $x=2b-1$ where $b$ is bernoulli, then then $x$ is either 1 or -1, and mean and variance follow from Bernoulli $\mu_b=p$ and $\sigma^2_b=p(1-p)$, the extension to 'Binomial' is then just a sum (assuming independence),
The mean of $x$ is then $\mu_x=2\mu_b-1=2p-1$, variance $\sigma_x^2=4\sigma_b^2=4p(1-p)$,
The sum of $n$ independent such $x$'s has mean $n\cdot(2p-1)$ (your result) and the variance is $4\cdot n \cdot p(1-p)$
EDIT after your question in the comment
It is as @Pegah says:  $b$ is the ''usual'' Bernoulli with a success probability $p$ and outcomes 0 and 1.  It's expected value is $1 \times p + 0 \times (1-p)=p$ and the variance $p(1-p)$ (also from the definition.
So $b$ is the known Bernoulli with outcome 0 and 1 and $x$ is just a linear function of it. The linear function is such that $x$ has outcomes -1 and 1, and the mean and variance can be obtained from the mean and variance of $b$.
Comment: In fcop's derivation, $\mu_b$ is the expected value of the random variable b, which is, as I understand a "default" binomial random variable (i.e. it can take on values 1 or 0, see also my comment above). Here the expected value is just p.


Java more efficient array searching

Question: I am coding a game using LibGdx and I have an array with all of my wall objects that the player can collide with. For those who don't use LibGdx, I am talking about LibGdx's Array class which provides the same functionality as an ArrayList but it's built with memory efficiency in mind.  When I check for collision, I am having to go through every wall in the array and check for collision like this:
for(Wall  w : walls) {
    if(w.bounds().contains(player.bounds()) {
    // handle collision
    }
}

I realized this was inefficient because I am going through every wall even if that wall is off the current view of the map. Obviously, if I am checking for collision with walls currently in the camera's viewport (this means they are currently visible by the player) then there is no point in going through the whole array because the player can't collide with them until they come into view. I was thinking of making my game a bit more efficient by only checking for collision with walls close to the player. In my game, I have all of the walls snapped onto a grid with cells 32x32 px. I really don't know how I could create more efficient searching for collision. Could I use like a map of some sort which uses a vector2 position for its key and then look up the player's position and look through walls within a certain range from the player's position in the map? I am just really lost on how to have code that won't go through all 100+ walls in my game when there are only 10 current possible walls that the player could touch because of where it currently is. Does this make any sense? Could someone explain a good way to do something like this? Thanks so much.
Answer: There are lots of collision alghoritms out there, you will need to find one that suits your need.
One solution I can think of on the top of my head is:
Keep your wall list sorted on their coordinates. If you create a new wall, use insertion sort to resort your array. When you want to check for collisions, take the objects coordinates (in this case probably the player that is running) and do a binary search to find the closest wall to the player. Then calculate if the player and this wall collides. If the closest wall isn't causing a collision, you can be pretty confident that no other wall is as well.
Comment: I'll give this a shot. The other answer looks practical so I will try them both out and then depending on which works best, mark that answer as solved.
Comment: It might be interesting to look into quad/octrees as well. It might not be 100% what you are looking for, but i can give you an idea of a better approach. http://www.kyleschouviller.com/wsuxna/quadtree-source-included/
Comment: I looked into those. Interesting. Thanks.
Answer: Each wall is on one or more of these 32x32px grids. Let the coordinates of a grid be x and y. If a grid contains a wall, enter this into a
HashMap<CoordPair,Set<Wall>> xy2wall

To investigate where a location is in contact with a nearby wall, use the coordinates of the location to determine a small set of grid coordinates, fetch the set or sets of Walls mapped by these CoordPairs. I guess the Player.bounds() can provide a suitable set of coordinates.
If the 32x32 grid results in too many entries, you can always use a coarser grid.
Comment: I'll give this a shot. The other answer looks practical so I will try them both out and then depending on which works best, mark that answer as solved.
Comment: I'd be interested in a feedback in any case. I used this algo for a similar task, and it worked very well with ~1000 hot spots in the arena.
Comment: I thought a lot and ended up using physics and box2d in my game so I no longer needed to do this. For sure, next time I will try this. Thanks so much.
Answer: I once came into the same realization that you have while developing a top down rpg.
There are more walls than you can imagine in a top down rpg.
Here is how I solved it:
First: Segment the map into zones ie.) draw your map on paper or something and cut it up into parts.
Second: Record the pixel boundaries for each segmented section of the map.
Third: Check where your players location is with respect to the boundaries.
Finally: Only check the walls within those boundaries.
In a realm of infinite walls this is not any more efficient (speaking about Big O) but for all practical purposes this is effective in cutting down on lookup times

if (boundary1.contains(player1)) {

    for(Wall  w : Boundary1Walls) {
        if(w.bounds().contains(player.bounds()) {
            // handle collision
        }
    }
}
else if (boundary2.contains(player1)) {

    for (Wall  w : Boundary2Walls) {
        if(w.bounds().contains(player.bounds()) {
            // handle collision
        }
    }
}

....
Continue in this fashion
Take note... I did it like this before going to college for software development, so I did not make use of data structures such as BST which could be used to store walls with respect to their coordinates. Making your lookup time extremely fast.
Comment: That seems like a good approach but i think I'd rather use some sort of data structure. Thanks.

Java more efficient array searching


Simple question about linear regression

Question: I am dealing with the following exercise:
Exercise. In a linear regression model of the form $y = w_1x + w_0$, if we increase the value of $x$ by one unit, what can we expect from the value of of $y$?
$(a)$ An increase of value equal to $1$;
$(b)$ An increase of value equal to $w_0$;
$(c)$ An increase of value equal to $w_1;$
$(d)$ It is impossible to tell anything about the increase on $y$.
My attempt. As an aspirant to be a mathematician, this question leads to one simple line of thinking: if $x$ is increased by one unit, one might think of this as a simple variable change of the form $x \to x+1.$ If this is case, we obviously expect $y$ to suffer an increase of value equal to the parameter $w_1,$ hence I would select option $(c).$
My concerns. After some further thought, what exactly is "one unit" of the variable $x$? As far as I am concerned, this might not be a concept as objeticve as I thought. This makes me think that probably option $(d)$ makes some sense aswell.
All the information I have about the question is posted in the Exercise. section. Thanks for any help in advance.
Comment: Thank you @Dave . As I tried to explain in the **My attempt.** section, if we change the $x$-value to $x+1$, our $y$ becomes $$ y = w_1(x+1) + w_0 = w_1x + w_0 + w_1.$$ In others words, this means that there is an increase of $y$ in the value equal to $w_1.$ I was really just wondering, increasing one unit in $x$ means simply having $x+1$ instead of $x?$
Comment: What else would it mean to increase a quantity by one unit?
Comment: @Dave That's exactly my question (sorry if it's dumb)! Is it possible that there's another meaning than simply increasing $+1?$
Answer: The answer to the question is certainly $(c)$. With a one unit increase in $x$, you simply multiply this value by the slope value, and this will yield an increase in $y$. So if the equation is:
$$
y = .54x + 45
$$
This would simplify to an increase of value equal to the slope (the $w_1$ in your question):
$$
y = .54 + 45
$$
Resulting in this $y$, a simple $.54$ addition to the intercept:
$$
y = 45.54
$$
To your question about what a one-unit increase in $x$ actually means, I suppose that depends on the measurement of the $x$ (centimeters, pounds, etc.). However, that doesn't seem to matter here. The units counted are not the same as the type of unit involved. Therefore the answer would still be $(c)$.

Simple question about linear regression


Solving a double integral with infinite bounds with a set of rules on a function with two variables

Question: Here's the problem description:
Let the function $f(x,y)$ be defined by
$
f(x)=
\begin{cases}
 g(x)/x,&\text{if}\, 0 < y < x\\
 0, &\text{otherwise}
\end{cases}
$
where $g(x)$ is a non-negative function defined on $(0, \infty)$ and $\int_{0}^{\infty}$ $g(x) dx = 1$.
Compute
  $\int_{-\infty}^{\infty}$ $\int_{-\infty}^{\infty}$ $f(x,y)dx dy$
I swear this should be pretty easy but for some reason I'm just stumped. I tried integration first with respect to $dx$ and splitting up the improper integral on the inside from $-\infty$ to $0$ and $0$ to $\infty$... but I just ended up with something that I couldn't really compute.
I'm also not really sure how I'm supposed to use the fact that $\int_{0}^{\infty}$ $g(x) dx = 1$ when I have to integrate $g(x)/x$. I'm guessing I'm pretty rusty on my calc.
I would appreciate it if anyone could help me out here.
Answer: HINT: Observe that
$$
\int_0^x (g(x)/x)\,dy=(g(x)/x)\cdot1\Bigr|_0^x=g(x).
$$
Let $D=\{(x,y):0\leq x\leq y\}$. Then
$$
\int\int_{D}f(x,y)\,dx\,dy=\int_0^\infty g(x)\,dx=1.
$$
Comment: Ahh, that makes a lot of sense! But I'm having some trouble actually getting to that step. How would I end up with the bounds $0$ to $x$? Because I'm splitting up the integral on the inside from $-\infty$ to $0$ and $0$ to $\infty$. The $-\infty$ to $0$ part is just equal to $0$, but then I have an integral from $0$ to $\infty$. The good thing now is that I'm integrating with respect to dy, though.
Comment: @Kawaiiii The actual domain of integration is `an infinite triangle` $\{(x,y):0<y<x,0<x<\infty$ and every integral with respect to $y$ gives $g(x)$.
Comment: Hmm, I'm really sorry but I'm having a bit of a hard time understanding how every integral with respect to $y$ gives $g(x)$... I get that the domain is an infinite triangle in the first quadrant, but how does that lead to the first statement?
Comment: @Kawaiiii Is the extended hint enough?
Comment: So we're integrating over the region D, with D being an infinite triangle in the first quadrant, but how do we get from that double integral to $\int_0^\infty g(x)\,dx$?... I'm so sorry if I'm being dumb, something just isn't clicking for me for some reason...
Comment: @Kawaiiii The inner integral is $\int_0^x (g(x)/x)\,dy$ and was computed as a first version of the hint.
Comment: Ohhhh, wow I see it now! That helps a lot. So, from the original post, could I just say that because $f(x,y)$ is only non-zero from $0$ to $\infty$, and because $0 < y < x$, then I could let $D=\{(x,y):0\leq x\leq y\}$ (as you said), and just "convert" the integral from $\int_{-\infty}^{\infty}$ $\int_{-\infty}^{\infty}$ $f(x,y)\,dx\,dy$ to $\int\int_{D}f(x,y)\,dx\,dy$ ?
Comment: @Kawaiiii Yes. :-)


MedialEment.js module not seeing the installed library

Question: I've just installed the MediaElement.js module and downloaded the corresponding library but in the modules page it won't turn on because it's not finding the library.
i have other libraries running so i know it's in the right place.
the Media Module version is 7x-1.2 and the on the webpage the version is
2.15.1
i've cleared the cache, run Cron and renamed the folder to mediaelement
how the freak do you trouble shoot something like this? this should take like 10 mins to do and now it's going on 40mins trying to troubleshoot.
Answer: The easiest way to debug something like this is to look at the MediaElement module itself.
Its implement of hook_library() contains the following:
$libraries['mediaelement'] = array(
    'title' => 'Media Element',
    'website' => 'http://mediaelementjs.com/',
    'version' => '2.1.6',
    'js' => array(
      // The mediaelement script detects the path to itself to call other files
      // in the same location. With preprocessing this is problematic as the
      // script is no longer in the same directory as its other assets. There
      // is an option that can be passed into the script with its location.
      // @todo Update all calls to mediaelement to pass in the assets location.
      $path . '/build/mediaelement-and-player.min.js' => array('group' => JS_LIBRARY, 'preprocess' => FALSE),
    ),
    'css' => array(
      $path . '/build/mediaelementplayer.min.css' => array('group' => CSS_SYSTEM),
    ),
  );

So it would appear the module is looking for

sites/all/libraries/mediaelement/build/mediaelement-and-player.js
sites/all/libraries/mediaelement/build/mediaelementplayer.min.css

If you make sure those files are in the right place, you should have no more issues.
Comment: thanks that is helpful. i looked up that code in the module just to learn. but those files are all there. and i set permission to all read, write, execute.
Comment: my other libs are there, working. really stumped.
Answer:
check folder permissions of your sites/all/libraries/mediaelement folder
use Firebug or Chrome Developer tools, or equivalent, and check the Console for any javascript errors.


Generated $\sigma(X)$ where $\Omega \neq \mathbb{R}$

Question: Simple question here. I am trying to enumerate the sigma field generated by the random variable: $$X(\omega)=2+1_{\left\{a,b\right\}}(\omega)$$ where $\Omega=\left\{a,b,c,d\right\}$.
I think what is confusing me is that I am used to looking for the pre-images under a function in $\mathbb{R}$ or similar. I know the simple discrete space should make this exercise easier, but it just isn't clicking in my head.
Answer: First note that $$X(\omega) = \begin{cases} 2 & \omega \in \{c,d\}\\ 3 & \omega \in \{a,b\}\end{cases}$$
Now consider $$\{\omega \in \Omega : X(\omega) \leq \alpha\}.$$

For $\alpha <2$, you get $\emptyset$.
For $\alpha \in [2,3)$, you get $\{c,d\}$.
For $\alpha \geq 3$, you get $\{a,b,c,d\} = \Omega$.

You want these set to be in your $\sigma$-algebra. Hence, $$\sigma(X(\omega)) = \sigma(\emptyset, \{c,d\}, \Omega) = \{\emptyset, \{a,b\}, \{c,d\}, \Omega\}$$
Comment: am I missing something, or are the values for X(w) switched in your answer. Shouldnt the RV take the value 3 when $\omega\in\left\{a,b\right\}$?
Comment: @Justin Yes. It was a typo. Fixed it.
Comment: Thanks. I thought that was the case, but sometimes when I'm really looking at these concepts and dont fully understand them, I hesitate to think something is a typo. Thank you for the comment and help!
Comment: If I were to extend this to determine the sigma-field for (X,Y) with Y defined similarly (but not exactly the same), would it simply be a list of all the events in $\sigma(X), \sigma(Y)$ listed as ordered pairs, such as $\sigma(X,Y)=$ {{a,b},{c,d}} etc?
Answer: I will include another pretty easy approach since I think the reply of Marvis had a typo in the function (not that it would make any major difference in this particular case, but I think this detail made you question the final result).
Note that $X$ takes only two values in $\mathbb{R}$: $2$ and $3$. For this reason, the preimage of any Borel set $B\subset \mathbb{R}$ is equals the preimage of either the singleton $\{2\}$ or $\{3\}$. The function $X$ in fact is $X(w)=3$ if $w\in\{a,b\}$ and $X(w)=2$ if $w\in\{c,d\}$. So
\begin{align*}
\sigma(X)=\sigma(X^{-1}\{2\},X^{-1}\{3\})=\sigma(\{a,b\},\{c,d\})=\{\emptyset,\{a,b\},\{c,d\},\Omega\}.
\end{align*}


Problema com setInterval()

Question: Então pessoal..
Tenho um código que trás um setInterval das mensagens passadas entre os usuários de e para na função abaixo..
    function openWidChat(de,para) {
        var url_s = $("#url_s").val();
        $("label#boxC input").val('');
        $("label#boxC input").removeAttr('disabled');
        $("label#boxC input").attr('user-de',de);
        $("label#boxC input").attr('user-para',para);

        $("#mensChat div._5chat").fadeIn(400).html('

');
        para = setInterval(function() {
            $.ajax({
                url: url_s +"/demo/chat/chat.php",
                data:'d='+de+'&p='+para+'&url_s='+url_s,
                type: "POST",
                cache: false,
                success : function(html){
                    $("#mensChat div._5chat").html(html);
                }
            });
        }, 1000);
    }

até então ele funciona de boa, mas quando clico em um nome de outro usuário para iniciar na mesma box uma nova conversa o setInterval fica indo e voltando em todos os usuários que eu cliquei para conversar... Fica um vai e vem do caramba..
Alguém tem uma solução pra isso?
Comment: Um problema, tens o parâmetro `para` e uma variável `para`. Isso dá problemas porque estás a fazer uso do `para` na chamada de Ajax. Além disso, convinha iniciar a variável `para` com `var para ...`. Sugiro que facultes nomes diferentes entre o parâmetro e a variável.
Answer: Fala meu,
Olha só, você precisa colocar no seu programa uma estrutura que utilize o comando "clearInterval". O setInterval é um loop infinito, e só vai parar quando você pedir para ele parar, por exemplo:
var looper = setInterval(function(){},1000); //Loop de 1s

clearInterval( looper ); //Para o loop.

Você precisa associar a função à uma variável para manter o controle dela, que no seu caso é a variável "para". Em algum ponto do seu programa (como quando você muda de usuário) você vai precisar colocar o clearInterval dessa forma:
clearInteval( para );

Depois vai ser necessário reiniciar o loop.
Tenho uma resposta aqui que pode te ajudar a criar uma estrutura de código.
Olhando seu código, te aconselho também a estudar um cara chamado "websockets". É algo mais complexo, mas vai te ajudar a entender mais conceitos importantes como "pooling request", por exemplo, mas se encaixa nesse tipo de programa que você tem aí.
Espero ter ajudado! Abraços!

Problema com setInterval()