I need a way get rid of using && operator so much

Question: I need to compare two objects of the same type but with a lot of prop
return string.Equals(x.Name, y.Name) &&
x.Price == y.Price &&
string.Equals(x.Species, y.Species) &&
x.AgeEnforced == y.AgeEnforced &&
x.MinimumAge == y.MinimumAge &&
string.Equals(x.WeightRange, y.WeightRange) &&
x.MinimumWeight == y.MinimumWeight

The list goes on up to 14 props
A hint on how can I lose && operator?
Comment: What's wrong with what you have? It's perfectly readable, though the formatting could be improved :)
Comment: Put a `#region`/`#endregion` around it so you don't have to look at it.
Comment: You could overload the `Equals` (and `GetHashCode`) method of whatever `x` and `y` are and put this code there.
Comment: @Chump Because memory management is a known problem that I don't want to solve over and over again.
Comment: @Chump Because they don't want to waste many hours writing tedious memory management code and chasing wild pointer write bugs?
Comment: @Chump Because when we switched to C#, we found we were getting actual releasable features out the door in half the time. And I've wasted enough of my life tracking down other people's memory leaks, thanks.
Comment: @Chump You sound like one of those emacs guys who think Picard could beat up Kirk.
Comment: If you are willing to use a library, you could use [`DeepEqual`](https://github.com/jamesfoster/DeepEqual)
Comment: Look at [IEquatable](https://msdn.microsoft.com/pl-pl/library/ms131187%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396) interface
Comment: We have std::unique_ptr now. What memory leaks? ;-)
Comment: You're going to be pretty hard pressed to replace a two character operator with anything sorter than that.  Even if you found a one character operator that did the same thing, you're saving all of one character, not exactly a significant improvement.
Comment: Sometimes there is no better way to write your code. If the business logic demands that these checks be made, then that is what you have to do.
Comment: DeepEqual is the perfect solution for me :)
Thanks BWA!
Comment: && is no better or worse than || or + or - or * - they all have their purpose. It's not like && is time consuming or anything.
Answer: If your class has 14 properties and all of them have to be compared to ensure equality, all of these checks have to be made somewhere. No matter if you put them into a (maybe static) helper method, the Equals-method, a class that implements IEqualityComparer (IMHO the best choice), an extension method or whatever else comes to your mind, you have to write down all of these checks once.
Instead of writing these checks on yourself you can use some reflection stuff (or a library that makes use of it) by iterating over all properties, but that's normally not the best choice, cause it is slower and equality checks are tend to be called very often (sort, hashset, etc.). So take the pain and write the checks down.
If you think these are too many checks, then maybe your object is to fat and has to much properties. Maybe it needs a deeper hierarchy by using classes which are representing a part of the whole thing and you have a top class that has as property a child class and then you write the compare method for each child class individually and the top class just calls these comparers for its child classes.
Answer: Answer to A hint on how can i lose && operator?
if (string.Equals(x.Name, y.Name) == false) return false;
if (x.Price != y.Price) return false

// ... others

return true;

Comment: This has the nice property of being easier to debug! When single-steeping though a misbehaving return value, this lets us known which comparison broken the chain quite easily. Good luck with that with the &&. Other than that, I don't find any differences really.
Comment: you've replace two characters of code with 17 characters of code.  You've made the code 8x *more verbose* than the OP's code, with no improvement to the semantics.
Comment: I think the idea was less about removing the operator from the code and more about not having to methodically do each check, but this does answer the question as stated.
Comment: anyways, that's about cosmetics and comfort. functionality is the same, so there's not much to argue further about. Just use what you like :)
Comment: @Servy, I am from `vb.net` background - I "like" verbose code :)
Comment: Also it's more instructions to do, so that answer not really convinces me.
Comment: Write `if (!string.Equals(x.Name, y.Name)) return false` !
Comment: @Fabio I have a feeling your answer is sarcastic (by _litrally_ replaceing the `&&` operator with something _worse_), but the `&&` effectively does exactly what you are doing since it short-circuits and will return `false` the first time it finds a `false` operand
Comment: @Alejandro You can accomplish the same thing, if you truly find it necessary, just using `&&` and a boolean variable that you update as you go, while still avoiding the massive increase in boilerplate.
Comment: as Alejandro said, the debugging convenience is actually very high. Diagnosing why a multiple chained && returned 'false' is a real pain if there are more than 3-4 terms in the chain. Moreover, you cannot place a breakpoint in a middle of the expression to quickly catch a specific case. Sure, you can place a conditional breakpoint, but then, with long expression, it's really irritating in the long run. **ANY** way of writing the multiple-chained-&& is a plus, be it if() or &&= or whatever.
Comment: @quetzalcoatl Well if you have something like `if (a && b && c && d)` and you stop on that in the debugger, if you hover over the first  `&&` a tooltip will tell you if `a && b` is true or false. If you hover over the second `&&`, a tooltip tells you if `a && b && c` is true or false. If you hover over the third `&&` a tooltip tells you if `a && b && c && d` is true or false. This tells you all you need to know without all that tedious and uneccessary splitting up of the expression... (Also you can hover over `a`, `b`, `c` or `d` to see their individual values.)
Comment: @MatthewWatson: have you tried doing a hover 30 times in a row? Several times because you were in a loop and didn't know which element false'd on which term? I did. Some legacy code had such expression chains. Sure, you can try bisecting. But even so, doing that for N elements because you're in a loop is not what I would want to do every day. Why not just place a breakpoint and go? I mean, 3, 4, okay,  maybe even 6 chained &&/|| are fine. But 14? 30? no, not for me. By the way, it's also a problem for diff/merge utils, because often &&/|| chains are "compacted" for "brevity" into fewer lines.
Comment: this answer
1. is just longer
2. does not answers the question
Comment: @Dexion. it is perfectly answer a question  _how can i lose && operator?_ - question was even added to the answer.  :) but I understand the reason of your comment ...
Comment: Question was how to avoid 14 manual if or &&, etc, not how to rewrite the syntax, especially not to a longer form. This is the reason.
Answer: This code must be somewhere. If this is only place where this code exist this is ok in my opinion. Bu if it exists in many places then you can move it to some helper fuction or override Equals() method in your object. MSDN info.
Example how to oveeride and use Equals():
public class MyObject
{
    public string Name { get; set; }
    public decimal Price { get; set; }

    public override bool Equals(object obj)
    {
        MyObject o = obj as MyObject;

        if (o == null)
            return false;

        if (this.Name != o.Name)
            return false;

        return true;
    }

    ///
    /// Serves as the default hash function.
    ///
    /// <returns>
    /// A hash code for the current object.
    /// </returns>
    public override int GetHashCode()
    {
        return base.GetHashCode();
    }
}

public class Program
{
    static public void Main()
    {
        MyObject o1 = new MyObject()
        {
            Name = "a",
            Price = 1
        };

        MyObject o2 = new MyObject()
        {
            Name = "b",
            Price = 1
        };

        MyObject o3 = new MyObject()
        {
            Name = "a",
            Price = 1
        };

        Console.WriteLine("o1 == o2: {0}", o1.Equals(o2));
        Console.WriteLine("o1 == o3: {0}", o1.Equals(o3));

        Console.ReadKey();
    }
}

Result is:

o1 == o2: False
o1 == o3: True
Answer: This seems as a correct way how to do the compare.
If your aim is to be able to easily check if two different instances are equal you can override Equals() and GetHashCode().
You will be able to do:
x.Equals(y)

You can also override operator ==. In which case you can do:
x == y

Check MSDN for details and example.

Also there is no reason for you (unless you want to use any extra parameters) to use
string.Equals(x.Name, y.Name)

use simply
x.Name == y.Name

Answer: For me, && or || are pretty short already. Your problem lies not in the operator itself, but in the way you are doing the comparison of 14+ properties.
Instead of writing all the property-comparisons by hand, you can try automating it.
var props_string = new List<Func<MyObject, string>>();
props_string.Add(foo => foo.Name);
props_string.Add(foo => foo.Species);
//..

var props_double = new List<Func<MyObject, double>>();
props_double.Add(foo => foo.Price);
//..

Now, having them listed, you can ran a loop over it
MyObject first = ...;
MyObject second = ...;

bool areEqual = true;

foreach(var prop in props_string)
    if(!string.Equals(prop(first), prop(second)))
        areEqual = false;

foreach(var prop in props_double)
    if(prop(first) != prop(second))
        areEqual = false;

return areEqual;

The positive side is that even if there were 100 properties, one or two (or more) loops would fly over it.
Please note that this code is not optimized and pretty naive.
More natural would be a fast-exit on first difference:
foreach(var prop in props_double)
    if(prop(first) != prop(second))
        return false;

..and/or observing that string.equals and double!=double can all be packed as the same object.Equals method (so you don't need separate props_string, props_double etc)
..and/or observing that you don't really need to list all properties, you can get them from Reflection, so you don't need to 'define' the 100 properties in these lists. (But then, you often have some special properties that you don't want to include.. so your reflection-way would need a way to detect and skip them..)
..and/or observing that if you used struct instead of class you would get full memberwise object.Equals comparison for free. (But then, structs differ from classes in many other things..)
..and/or(...)
All these 'optimizations' are highly dependent on what you have in the rest of the 14+ comparisons. It looks fun and smart at first, but the more the types of properties vary and the more types of comparisons you need to do (string.equals with case-insensitive maybe?) the worse it will get. Sometimes 14 times &&, or 14 times if(x==y)return false isn't really that bad.
Please don't get me wrong: I do not advise you to use the way I show here. I just show you that it is possible. Don't use it unless absolutely relevant and necessary. Doing it this way may cost you much more time than you would want to.


CSS Is Not Working for Firefox

Question: I have a site that is not displaying correctly for Firefox. Works perfectly for IE Edge, Chrome and Safari.  It's like Firefox is not rendering any of the css.
I even disabled all the plugins and changed the theme to WP's default TwentySeventeen.  Still same problem.
Can anyone tell me why and how to fix it.
css not working for Firefox
Comment: Right click anywhere on the page, then click Inspect Element. You will see a list of JS warning, saying that your ressources have been blocked, so they are not loading using FF. *EDIT*: If you try to open one of your ressources from the console, Firefox doesn't let you access it
Comment: Is this only certain elements that aren't displaying correctly? Or do you mean the entire CSS styling isn't working?
Comment: In a nutshell, the site was hosted on Godaddy. Then the blacklist happened. So I set up a site at Siteground using the default Wordpress install and them. In saying none of the files have been migrated over yet.  I then changed the dns at Godaddy to point to Site Ground and the page breaks just like it does now.  I am not sure why or if the SSL Certificate is the issue or what but I am baffled.  To answer your question, it seems that Javascript and css are not rendering.
Answer: It is due to the fact your website is analysed having a dangerous and deceptive content by firefox. I disabled the option 'block dangerous and deceptive content' in 'Privacy & security' within my Firefox options. Work well afterwards.
Have a look to your SSL certificate for your https url. It may be the cause.
Comment: So do you think the SSL certificate might be bad?  How can I check to know it's bad?
Comment: I have checked your ssl certificate. It seems good. I have checked your website with google yur website through transparency report and I get this issue: Current status
warning
Some pages on this site are unsafe

The site https://sweetsfest.com/ contains harmful content, including pages that:

    Try to trick visitors into sharing personal info or downloading software

Unsafe content might only appear on some pages of a website. Check the URL of the specific directory or webpage you want to visit for more detailed safety info.
Comment: you do not seem to have virus tho https://www.virustotal.com/#/home/upload
Comment: you can try this https://safebrowsing.google.com/safebrowsing/report_error/?hl=en
Comment: with this last link you can say to google that your site is clean and does not try to fish
Comment: And last thing, I do not know if your are from this agency (the agency that develops the website)? https://levitateagency.com/ but I have the same issue with their website.
Comment: I am not the owner of levitateagency.com but it too was one of the sites that was blacklisted but after moving that site over to Site Ground it does not breaks visually as sweetsfest.com did and that's what's confusing me.

As for the google links, I did submit to google those two domains as being clean (including a 3rd one).  I do not know how long it will take them but the scan for sweetsfest.com was done August 13th but the clean site was done earlier this week.
Comment: Update: levitateagency.com  last scan was August 22nd but it gave me a clean report.  So I don't know why  you are getting the same issue.
Comment: ok please let us know when google has replied to you. Good luck

CSS Is Not Working for Firefox


Restore TFS Website in IIS Manager

Question: I've accidently deleted the Tfs site in IIS Manager. I've tried reinstalling TFS but it didn't come back. How can I restore it?
Answer: Uninstall, install, then run the add an AT wizard to restore TFS. Point the wizard to the SQL Server that hosts the data from the original instance.
Here is the MSDN topic for using the add an AT wizard for disaster recovery.
http://msdn.microsoft.com/en-us/library/ee259689.aspx
Comment: umm... what's AT?
Comment: Sorry, AT is application tier, essentially all the guts of TFS (IIS sites, windows services, etc) except for the data. Read the section in the linked topic on disaster recovery. Good luck!

Restore TFS Website in IIS Manager


Asp.Net Absolute Path of a URL

Question: To make it simpler for a webapp to share files with another app on a different server, I'm using a base href tag in my master page.  As many people have discovered, this breaks webform paths.  I have a working Form Adaptor class but am not sure how to get the absolute path of the url.  Currently, my program is hardcoded to use something akin to :
HttpContext Context = HttpContext.Current;
value = "http://localhost" + Context.Request.RawUrl;

It is worth noting that I'm currently testing on my local IIS server, so there's a strange tendency for a lot of things I've tried using in order what the absolute path do not include the domain name (my local IIS is not visible externally).  Which means it isn't an absolute path and thus the base href will wreck it.
Is there a good way to handle this such that it will work locally without hardcoding but will also work properly when uploaded to a server?  I'd prefer to avoid anything that involves doing something different on the server-side copy.
Yes, I realize I could use separate web.config files locally and on the server to get this information but this is ugly and violates DRY.
Comment: I am not sure but, did you try Request.Url.Host ?
Answer: I have used this in the past:
// Gets the base url in the following format:
// "http(s)://domain(:port)/AppPath"
HttpContext.Current.Request.Url.Scheme
    + "://"
    + HttpContext.Current.Request.Url.Authority
    + HttpContext.Current.Request.ApplicationPath;

Answer: Old post but here is another slightly less verbose method
var baseUri = new Uri(HttpContext.Current.Request.Url, "/");

Answer: Using string interpolation:
string redirectUri = $"{this.Request.Url.Scheme}://{this.Request.Url.Authority}{this.Request.ApplicationPath}account/signedout";

Substitute 'this' for 'HttpContext' or 'HttpContext.Current' based on context.
Answer: I have used following and it worked for me both client and the server.
string surl = string.Format("{0}://{1}",
    HttpContext.Current.Request.Url.Scheme,
    HttpContext.Current.Request.Url.Authority);

Answer: Code :
string loginUrl = Request.Url.GetLeftPart(UriPartial.Authority) + VirtualPathUtility.ToAbsolute("~/") + "Login/Login.aspx?UserName=" + LoggedinUser["UserName"] + "&Password=" + LoggedinUser["Password"];

Comment: Very bad thing to put the password into the URL. Don't do that.

Asp.Net Absolute Path of a URL


verify solution to first order quasi linear pde

Question: question is, $u^2u_x+u_y = u$ and Initial value is $u(x,0)=x$ where $y \gt 0$
my solution is $x=u^2(y+(u/e^y))$
Answer: $$u^2u_x+u_y = u \quad\text{ and Initial value is }\quad u(x,0)=x$$
My answer as terse as the question is :
$$x-e^{-y}u-(1-e^{-2y})\frac{u^2}{2}=0$$
Solving this quadratic equation for $u$ leads to $u(x,y)$.


Internet explorer CSS FIX. Having trouble with floats in internet explorer

Question: I have a simple problem but have not figured out what might be solution just yet. I used a css reset to fix the issue with internet explorer, but no dice. I also do not want to use relative - absolute positioning. If you go to http://securitycamerasflorida.net via firefox, chrome, or safari it looks the way I wanted which content and sidebar is next to each other. They are both positioned with float but if you click on one of the cities you can see in IE that sidebar is pushed at the bottom of the page.
Comment: What's with the wacky URL?  Are you worried about spam bots finding your public web site or are you trying to hide it from this sites filters?
Comment: Actually non of the above. I just don't want the site's issues visible to people when its googled.
Comment: I realized that it also works on IE8 but not in IE7. Also it is not tested on IE6
Comment: @hightouch - but you do realize that people with sufficient reputation can edit your post any time and change that URL...
Comment: @hightech - and these kind of "problems" are common an are no security threat for your site. So I don't really see a need for this obscurity.
Answer: Maybe this can help you: About Conditional Comments
Comment: Just tried it also. Please see http://www.securitycamerasflorida.net/cctv-miami.php ie css has a float right property for some reason it is not taking affect
Comment: got it now just had to put the conditional after the original statement thanks
Answer: Try putting a right margin on your
 and remove the left margin from your

You can a wacky double margin in IE6 when you put a margin in the same direction you're floating.


Positional association cannot follow named association

Question: I have implemnted Carry Select Adder using D-lATCh. But I am Getting the following error.

HDLCompiler:720 - "/home/aabhinav/Downloads/Example/CSA_4bits/CSA_BEC1.vhd" Line 76: Positional association cannot follow named association
ERROR:HDLCompiler:854 - "/home/aabhinav/Downloads/Example/CSA_4bits/CSA_BEC1.vhd" Line 41: Unit  ignored due to previous errors.

Below is my attached code. If anyone could help me as I am new to VHDL and doing my school project.
----------------------------------------------------------------------------------
-- Company:
-- Engineer:
--
-- Create Date:    17:08:00 11/16/2016
-- Design Name:
-- Module Name:    CSA_BEC1 - Behavioral
-- Project Name:
-- Target Devices:
-- Tool versions:
-- Description:
--
-- Dependencies:
--
-- Revision:
-- Revision 0.01 - File Created
-- Additional Comments:
--
----------------------------------------------------------------------------------
library IEEE;
USE ieee.std_logic_1164.ALL;
use IEEE.STD_LOGIC_ARITH.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;

-- Uncomment the following library declaration if using
-- arithmetic functions with Signed or Unsigned values
--use IEEE.NUMERIC_STD.ALL;

-- Uncomment the following library declaration if instantiating
-- any Xilinx primitives in this code.
--library UNISIM;
--use UNISIM.VComponents.all;

entity CSA_BEC1 is
port( A,B : in std_logic_vector(3 downto 0);
        cin : in std_logic;
        Scsa : out std_logic_vector(4 downto 0));

end CSA_BEC1;

architecture Behavioral of CSA_BEC1 is

COMPONENT d_latch_top is
   port( A : in std_logic_vector(4 downto 0);
            EN : IN STD_LOGIC;
         B : out std_logic_vector(4 downto 0));
end COMPONENT;

COMPONENT MUX10_5 is
    PORT(X, Y: in std_logic_vector(4 downto 0);
            sel: in std_logic;
          m: out std_logic_vector(4 downto 0));
end COMPONENT;

component rc_adder
    Port ( X : in  STD_LOGIC_VECTOR (3 downto 0);
           Y : in  STD_LOGIC_VECTOR (3 downto 0);
--            Cin: in STD_LOGIC ;
           sum : out  STD_LOGIC_VECTOR (3 downto 0);
           Carry : out  STD_LOGIC);
end component;

signal RCSum: STD_LOGIC_VECTOR( 3 DOWNTO 0);
signal BECSum, M: STD_LOGIC_VECTOR( 4 DOWNTO 0);
signal RCCarry,BECCarry: STD_LOGIC;
signal RC_S_C: STD_LOGIC_VECTOR( 4 DOWNTO 0);

begin

RC: rc_adder PORT MAP(X => A, Y => B, SUM => RCSum, Carry => RCCarry);
RC_S_C <= RCCarry&RCSum;
dlatch: d_latch_top PORT MAP(A => RC_S_C,B => BECSum, EN = '1');
MUX: MUX10_5 PORT MAP(X => BECSum, y => RC_S_C , sel => cin, m => Scsa);

end Behavioral;

----------------------------------------------------------------------------------
-- Company:
-- Engineer:
--
-- Create Date:    17:19:36 11/16/2016
-- Design Name:
-- Module Name:    rc_adder - Behavioral
-- Project Name:
-- Target Devices:
-- Tool versions:
-- Description:
--
-- Dependencies:
--
-- Revision:
-- Revision 0.01 - File Created
-- Additional Comments:
--
----------------------------------------------------------------------------------
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;

-- Uncomment the following library declaration if using
-- arithmetic functions with Signed or Unsigned values
--use IEEE.NUMERIC_STD.ALL;

-- Uncomment the following library declaration if instantiating
-- any Xilinx primitives in this code.
--library UNISIM;
--use UNISIM.VComponents.all;

entity rc_adder is
port(   X : in std_logic_vector(3 downto 0);  --4 bit input 1
            Y :  in std_logic_vector(3 downto 0);  -- 4 bit input 2
--              Cin : in STD_LOGIC;
            sum : out std_logic_vector(3 downto 0);   -- 4 bit sum
           carry :  out std_logic   -- carry out.
);
end rc_adder;

architecture logic of rc_adder is

COMPONENT full_adder is
    port (a : in std_logic;
            b : in std_logic;
           cin : in std_logic;
           sum : out std_logic;
           carry : out std_logic
         );
end COMPONENT;

signal C0: STD_LOGIC_VECTOR( 2 DOWNTO 0);

begin
FA1: full_adder PORT MAP(X(0),Y(0),'0',sum(0),C0(0));
FA2: full_adder PORT MAP(X(1),Y(1),C0(0),sum(1),C0(1));
FA3: full_adder PORT MAP(X(2),Y(2),C0(1),sum(2),C0(2));
FA4: full_adder PORT MAP(X(3),Y(3),C0(2),sum(3),Carry);

end logic;

library IEEE;
use IEEE.STD_LOGIC_1164.ALL;

entity d_latch_top is
    Port ( A  : in  std_logic_vector(4 downto 0);
           EN : in  STD_LOGIC;
           B  : out std_logic_vector(4 downto 0));
end d_latch_top;

architecture Behavioral of d_latch_top is
    signal DATA : std_logic_vector(4 downto 0);
begin

    DATA <= A when (EN = '1') else DATA;
    B <= DATA;

end Behavioral;

----------------------------------------------------------------------------------
-- Company:
-- Engineer:
--
-- Create Date:    17:54:06 11/12/2016
-- Design Name:
-- Module Name:    MUX10_5 - Behavioral
-- Project Name:
-- Target Devices:
-- Tool versions:
-- Description:
--
-- Dependencies:
--
-- Revision:
-- Revision 0.01 - File Created
-- Additional Comments:
--
----------------------------------------------------------------------------------
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;

-- Uncomment the following library declaration if using
-- arithmetic functions with Signed or Unsigned values
--use IEEE.NUMERIC_STD.ALL;

-- Uncomment the following library declaration if instantiating
-- any Xilinx primitives in this code.
--library UNISIM;
--use UNISIM.VComponents.all;
entity MUX10_5 is
    PORT( X, Y: in std_logic_vector(4 downto 0);
            sel: in std_logic;
          m: out std_logic_vector(4 downto 0));
end MUX10_5;

architecture logic of MUX10_5 is

    component MUX6_3 is
        PORT( sel: in std_logic;
              X, Y: in std_logic_vector(2 downto 0);
              m: out std_logic_vector(2 downto 0));
    end component;

    component MUX4_2 is
        PORT( sel, X0, X1, Y0, Y1: in std_logic;
              m0, m1: out std_logic);
    end component;

begin

    mux6_3_inst0 : MUX6_3
    PORT MAP( sel => sel, X => X(2 downto 0), Y => Y(2 downto 0),
              m => m(2 downto 0));

    mux4_2_inst0 : MUX4_2
    PORT MAP( sel => sel, X0 => X(3), X1 => X(4), Y0 => Y(3), Y1 => Y(4),
              m0 => m(3), m1 => m(4));

end logic;

Comment: We're not your personal debugging service.
Comment: This is not an [MCVE] - you could usefully have trimmed a few pages of unnecessary commented out stuff and brought it down to a few lines. I'm not going to count through this mess to find line 76.
Answer: See IEEE Std 1076-2008 6.5.7 Association lists, 220.127.116.11 General, para 5:

Named associations can be given in any order, but if both positional and named associations appear in the same association list, then all positional associations shall occur first at their normal position. Hence once a named association is used, the rest of the association list shall use only named associations.

In the architecture for CSA_BEC1, the component instantiation labeled dlatch, pretty much where the first error message said. The named association malformed: EN = '1' should be EN => '1'.
A VHDL parser can be implemented LALR(1), meaning it doesn't need to look ahead beyond the next token.  You might imagine someone was using the compound delimiter "=>" to determine whether or not an association item is named or positional. It seems it's not smart enough to give a separate error message when the following delimiter ("="), wasn't a ',' or a ')' for the last item in an association list.
Such 'luxuries' usually show up with tool implementation maturity. Fee free to allow the vendor to know the error message is not particularly enlightening.


Arpeggios on chords. Alternate or economy picking?

Question: As I'm tired from being able to make some arppegios on chords just with fingerstyle, I started praticing it with the pick (take musics GnR's Don't Cry or Civil War for example).
I ever did it with economy picking because it was easier. Make fingerstyle patterns with economy picking seems a lot easier than alternate.
But then I found a video on YouTube saying that it's better to train alternate picking with arppegios. Reference:

Is that right?
I mean, learning only with economy picking will stuck me in other situation?
Answer: Use what works for you.
The way I was taught and the way I prefer is to start with alternate picking and use that as sort of your baseline. But once you learn alternate picking to the point of it being second nature there's no reason that can't move on to also using economy picking when appropriate.
As for when it's appropriate, that's up to you. Personally, I like the built-in rhythm to alternate picking. I play quite a bit of jazz and alternate picking gels better with that steady swinging rhythm. But I'll also use economy picking for selective passages (ex. sweeps across 3 or more strings).
There's no right way other than what works for you. But I would definitely learn both so that you can see the value of each before you decide.


Image of the composition of a kernel with a cokernel.

Question: Let $ h:H\to G $ and $ k:K\to G $ be two normal monomorphisms and let $ f:H\ast K\to G $ theire coproduct.
It is always true that $ h\text {coker} k $ and $ f\text {coker} k $ has the same image?
Comment: Do you work in an arbitrary category with zero morphisms, or in the category of groups?
Comment: I'm interested in an arbitrary cathegory with zero morphisms, finite limits and colimits.
Answer: Yes. Note that $\def\coker{\rm{coker}\,} \def\im{\rm{im}\,} \coker k=G\to G/(\im k)$ where $(\im k)$ is the normal subgroup generated by the image of $k$. Then, for a word $w=x_1y_1..x_ny_n$ with $x_i\in H,\ y_i\in K$, we have
$$w \overset{f\,\coker k}\mapsto [h(x_1)k(y_1)h(x_2)k(y_2)\dots]_{(\im k)}=[h(x_1)h(x_2)\dots]_{(\im k)} $$
because $k(y_i)\in (\im k)$ and these can be grouped on one side, using conjugations: if $z\in N$ for a normal subgroup $N$ and $x,y\in G$, then
$$xzy=xzx^{-1}xy\in Nxy\,.$$
Comment: You showed that the statement is true in groups category. This is true in any category with kernels and cokernels?


How can I migrate the Domain publishing settings for nodes via SQL?

Question: I am using Drupal 7 and Domain Access (latest stable versions).
In my source site, there are nodes with "Domain access options", "publish to.." then a number of selected domains.
I migrate the data in the node_access table, mapping the old nid to the new nid using the migrate_map_xxx table.
However when I view a Node which has rows in the node_access table, publishing the node to certain domain id, the relevant box is not ticked on the node edit page.
When I rebuild permissions, the rows of data I migrated into node_access disappear and the node is still published to just the default domain (three other rows were inserted into the node_access table, now there is just one).
How can I migrate the publishing options for nodes from one DB to another?
Comment: To clarify, I was migrating the node data using the migrate module, and the migrate_d2d UI. Using the latest Domain Access dev version, the source domains are migrated, but the publishing options are not.
Answer: OK, I figured it out... The domain_access table is the one I need to migrate the data from and to.
Key is to rebuild permissions after updating the domain_access table, so the node_access table is updated with the latest domain publishing options.
So I executed the following SQL to migrate the old domain_access records in to the new DB, then update with the new nid values from the migrate_d2d mapping table:-
delete from destinationdatabase.domain_access
    where nid in (select destid1 from destinationdatabase.migrate_map_blognodearticle);

CREATE TABLE IF NOT EXISTS destinationdatabase.domain_access_tmp LIKE destinationdatabase.domain_access;

INSERT INTO destinationdb.domain_access_tmp (nid, gid, realm)
SELECT nid, gid, realm
FROM sourcedatabase.domain_access
where sourcedatabase.domain_access.nid in (select sourceid1 from destinationdatabase.migrate_map_blognodearticle);

UPDATE destinationdatabase.domain_access_tmp AS ds, destinationdatabase.migrate_map_blognodearticle AS new
SET ds.nid=new.destid1
WHERE ds.nid=new.sourceid1
and ds.nid in (select sourceid1 from destinationdatabase.migrate_map_blognodearticle);

INSERT INTO destinationdatabase.domain_access (nid, gid, realm)
SELECT nid, gid, realm
FROM destinationdatabase.domain_access_tmp;

Then ran drush eval 'node_access_rebuild();


Introductory text before a view

Question: I've created an about us page on a Drupal 8 site that is a view displaying people on my site (in alphabetical order) that were generated from a custom member content type.
The page is basically a "Card" type look for each person in a 3 column grid.
What is the correct way to add an introductory block of text above this view listing? Is adding a custom block of text to the header portion the best way of doing this still? I can't seem to find any recent answers to this question. Is this easy for content editors to alter afterwords?
Answer: Under "Header" select "Add" and choose "Text area" or "Unfiltered text". Then fill in your text in the text area and click "Apply".

You will need to provide content editors access to your view in order to alter it.
Another option would be to create a custom block and to place it above the Main page content block. Then again, you will need to provide access to the content editors to administer blocks.
Comment: Alternative approach that will require a bunch of contrib modules and result in a pretty different Content creation workflow is using Paragraphs and https://www.drupal.org/project/viewsreference, then you can have a View paragraph type and mix text and views in whatever way you want, without giving your editors special permissions.
Answer: You could also try to do this the other way around. The view is 'fixed', and you want to have the node remain editable.
It appeared this did not work the way I had in mind. You want to show the view on that specific page only and because in views there is no relation between the users and the specific node, so there is no possibility to show the content only on the given node id (the view will be attached to all nodes). EVA is a great module for situations where there is such a connection though.

For example, you might make a View that displays posts with an 'Author
  ID' argument, then use Eva to attach the view to the User entity type.
  When a user profile is displayed, the User's ID will be passed in as
  the argument to the view magically.

Original answer
By creating a basic page with your introduction text and using Entity Views Attachment (I have not tried the 8 version, but for Drupal 7 it worked nice). You configure it from within views, and then choose to attach it to the node. The node remains editable as every other node.
New answer
Since EVA is not a good solution. Let's make a block. If you create a view block that lists your users. Place the block below your content block in the blocks configuration and then change the visibility preferences. Just enter the path to your content (/node/1 or something similar. It is favorable to use the node id, because the URL alias can change more easily.).

A lightweight alternative could be to use the Global: Rendered entity - Content display in the views header area. This will allow you to embed the complete node in the view. But in this case you will have access to the node via its regular path and the path of the view, which might be undesirable.

Introductory text before a view


How can I create a new page template for the user registration page?

Question: I am a beginner in Drupal. I need to create a new page template for the registration page. Because in my website almost all pages have different layout.
Currently all pages are rendering through page.tpl.php.
Any suggestions?
Answer: There are so many ways to theming your registration page.
You can create user-register.tpl.php
To know about how to create user-register.tpl.php refer below links.
https://www.drupal.org/node/1211520
https://api.drupal.org/api/drupal/modules!user!user-profile.tpl.php/7
https://www.drupal.org/node/1195754
If you want to know how to create tpl files.
Page template suggestions are not working


Record network data By Ip address

Question: Im getting some unexplainable happenings on my home network. Like lots of data being chewed. Ive got mac address filtering and WPA on, but it hasn't helped.
So I was wondering does anybody know of a program that will tell me how much each IP on the network has transferred? Maybe it needs to go through a proxy, which im fine about. I'll just route all data through my server. Basically i just want to find out if somebody else is getting onto my network somehow. So i need a network monitor.
Any help would be great!
Answer: A dual homed machine capable of acting as your gateway router would be perfect for this. Here's a howto that might help: http://www.stanford.edu/~fenn/linux/
Using that would permit you to watch the streams, packet counts, etc etc so you could examine every packet transmitting across your network.
Answer: I've been using a package called Argus, written by Carter Bullard at Qosient.  You feed it either a promiscuous network card, or a tcpdump file, and it outputs file containing the flow data for all the network traffic seen.  It comes with a number of client programs for doing various and sundry types of analysis on the traffic.  There is a switch to record MAC addresses, if seen.
Answer: If you can put your card into promiscuous mode and the router sends all the packets, you can use wireshark to watch/analyse traffic.
Answer: install netmon 3.3 from here:
Network Monitor 3.3 is available here
Use the top users expert in network monitor 3.3 See Top Users Expert for Network Monitor 3.3

Once you've installed the expert by
  running the MSI, "Top Users by
  Endpoint" and/or "Top Users by
  Conversation" will appear in the
  experts menu. Once you run the expert
  a new window will show up and display
  a data grid. The data will depend on
  any display filters applied or
  conversation tree nodes you might have
  selected. The data grid contains a
  list of nodes or conversations and
  then statics on the frames and bytes
  that have been sent and/or received.

By using the expert you don't need to worry about how to analyze the data yourself, the tool will do it for you.  If you know nothing about netmon (or network analyzers) watch this video intro:
Network Monitor (Netmon) 3.3 Overview
Answer: I've been using NTOP for a few years now; haven't had any reason to try/use anything else.  Will give you traffic for each IP and where the traffic has gone/come from for each IP
www.ntop.org/
Comment: The problem with NTOP is that unless your switch is configured (or can be configured) to send all traffic to the machine running ntop, you only see local traffic plus broadcasts.

Record network data By Ip address


DataFrame To Excel in C#

Question: I am new to .NetFramWork, I have some Python experience
I have seen that Microsoft is providing DataFrame functionality in  Microsoft.Data.Analysis Nugget Package
I am happy with that, I can see that we can read data from the excel like below
DataFrame csvDataFrame = DataFrame.LoadCsv("path/to/file.csv");

Any one know how to write DataFrame to the excel, I could not see any method for that
and could you also point me out to documentation on this
Comment: By "write to the Excel" do you mean write a CSV file?
Comment: Yes, to either CSV or Xlsx, or if possible to both
Answer: I'd like to suggest to use another library for that. For example, ClosedXML (Documentation is here) which can be installed as NuGet package. And you may do something like this:
var csvDataFrame = DataFrame.LoadCsv("path/to/file.csv");

var workbook = new XLWorkbook();
workbook.Worksheets.Add("Test");
var ws = workbook.Worksheets.FirstOrDefault();

var rowNumber = 1;
for (int i = 0; i < csvDataFrame.Rows.Count(); i++)
{
    var row = csvDataFrame.Rows[i];
    var colNumber = 1;
    for (int j = 0; j < row.Count(); j++)
    {
        var cell = ws.Cell(rowNumber, colNumber);
        cell.Value = row[j];
        colNumber++;
    }
    rowNumber++;
}

There are also some useful packages for CSV, but approach is the same as for Excel.

DataFrame To Excel in C#


Lua / Love2d physics setCallback - how to correctly create a callback to a method of an object

Question: I'm still struggling with the basics of Lua and Love2d while adding some physics to my first game prototype:
Creating a local or global (non method) collision callback function, that is called when two objects collide works like a charm.
Now - As all my game elements are objects (even the game area) I tried to create the callback function as a method of the area-object with no success:
It seems that Area:beginContact assumes that the first parameter is the instance of the object. As  self.world:setCallbacks is not aware of that, this will to all parameter of the call being shiftes to the left: fixture_a within the callback function becomes filled with fixture_b, fixture_b with contact and contact is becoming nil.
I tried to solve this problem by defining the callback as self.world:setCallbacks(self:beginContact). I thought this would force the first parameter to be set as the instance of the object, but this just leads to an error.
Any ideas how to solve this issue?
function Area:new(room)
    self.room = room
    self.game_objects = {}
    self.physics_objects = {}
    love.physics.setMeter(64)
    self.world = love.physics.newWorld(0, 0, true)
    self.world:setCallbacks(self.beginContact) <---- here's the problem
end

function Area:beginContact(fixture_a, fixture_b, contact)
    print(self)
    local name_a = fixture_a:getUserData()
    local name_b = fixture_b:getUserData()

    print(name_a, name_b, contact, '!!beginning contact')
end

Answer: Here's the documentation: https://love2d.org/wiki/World:setCallbacks
I'm just a beginner, but perhaps rename Area:beginContact to AreaBeginContact and use setCallbacks(AreaBeginContact,...). On collision that is called can get the Area from the fixtures
function AreaBeginContact(fixture_a, fixture_b, contact)
    (...)
    local fixture_area = fixture_a:getArea()

(you would need to implement getArea function), and do Area-specific stuff.
Comment: Thank you for your insights. I feared that a non-global callback-function would require a modification of love (that's a path I don't want to go), but I hoped that I just missed an easy different solution due to my missing experience.
Comment: Yes, that would work (it's my currenty work around) but is not using a method but a function for the callback (AreaBeginContact in that Case is not part of an area object)
Comment: @Paraglider0815 I don't think it is possible the way you want, because the collision callback given by setCallbacks is global. It detects collisions between all objects. If you wanted for it to detect collision only within an Area, you would need to rewrite love2d collision routine (as far as I can tell).
Comment: @Paraglider0815 It may be possible however to do this rewrite of love, but may not be worthwhile.


React Native auth error handle with  component

Question: i'm handling firebase auth errors and i cant show error message on screen
here is my code;
if (error.code === "auth/user-not-found") {
            return (
                <View>
                    <Text>user not found</Text>
                    <Text>try create a account or check ur mail and passwrd</Text>
                </View>
            )
        }

but i use alert it works perfectly.
how can i solve it ?
Answer: Try to add some styles in your components so you can see something.
if (error.code === "auth/user-not-found") {
            return (
                <View style={{flex: 1, width: "100%", height: "100%", backgroundColor: "#f00"}}>
                    <Text>user not found</Text>
                    <Text>try create a account or check ur mail and passwrd</Text>
                </View>
            )
        }

I like to try first with full width and height, and with a very basic color (in this case red) so I can watch whats happening in my views. Remember that you can save and metro gonna refresh your app in your emulator/phone.
Comment: @n00b do you have another return after this one?
Maybe thats your problem, if your conditional is always false you would never gonna return your view with texts.
If you can provide more context we can help you more.
Comment: here is my code;
https://i.ibb.co/HBN8y84/err.png


Are there different type of lacquer problems?

Question: Hello fellow musicians!
Directly related to my previous question.
I checked my new trombone again for lacquer problems. I saw three different types of missing lacquer.

At the slide handle, the lacquer is either just missing or has greenish dots.
The bell section has red-ish "holes", some of those red parts have the bare metal revealed in their centre.
Inside the main tuning slide (the inner tube) I can see a lot of blue-ish dots, a whole area of it. Next to it there are some greenish dots.

What did I just find? Rust? Some kind of verdigris? Or merely Oxidation? Do I need immediate restoration (e.g. new lacquer), or is the trombone still fine?
It's a 1980sth Bach Stradivarius LT42. As @mkingsbu pointed out here, missing lacquer doesn't necessarily seem to be a problem. But I'm not so sure about those parts:

Main slide Handle

Bell "middle" section

Bell inner rim
Actual Questions

What can actually be seen on the photographs?
What do I really need to do about it?

Background of my questions
Dealers and techs usually won't tell, nor be specific.
I'm very much interested in what actually is going on. Perhaps even a bit scientifically.
Thanks a lot in advance!!
PS: there is no restoration tag, nor a lacquer tag, nor any recommended tags. ;-)
Comment: I wonder if the chemistry stack would have some interesting answers about the corrosion itself.
Answer: Aha! Pictures definitely help. So let's talk about this one component at a time
Slide
Your slide is all nickel slide. (Bach slides that are lightweight (LT42) are also made of a nickel-brass alloy, without oversleeves).  The problem with nickel is that many people are allergic to it. Your cork barrel is pitted as is the part of the slide that you would normally hold.  However, the pitting is not very bad and if you are not allergic to nickel then you'd have no problems. If you wanted, you could have a tech relacquer it. It would be expensive, but at least your hand would not be touching metal.
Another common technique that is used - but one that you have to be careful about - is using fingernail polish. Yes, fingernail polish! They make an assortment of colors, including clear that can be applied.  The reason you have to use caution is you want to make sure you don't seal in the stuff that is causing it to be pitted! Since the horn is older, it probably needs a chem clean before you do this. This really should be done professionally unless you really know what you are doing with chemicals.  More on this a little later.
Note: This is a lot thicker than lacquer, but your hand is already gripping the area so it isn't likely that you'll notice this sonically. And, worst case scenario if you do, you can remove it easily.
** Bell **
I'm really not in a position to identify red rot, but clearly there is some corrosion going on here. Brass does not rust, but it does dezincify.  As with the slide, the horn is probably long overdue for a chem clean.  I'd get that done before anything else.  You can figure out what to do from there.  Nothing stops the process of red rot (if this is indeed red rot) once it is started. Even lacquering. You just have to replace the part eventually.
Once you get a chem clean on the bell, you can possibly choose to leave it as-is or buff it out.  Its hard to say prior to doing the chem clean. I would personally go the route of having the lacquer removed and the bell buffed.  A slight deviation from this would be to have a satin finish applied.  I have done this to several of my own trombones with a bench grinder and a steel wool wheel.  You will still want to get the chem clean prior to this, but you can save on labor cost if you do the finishing yourself. The advantage of having the lacquer removed is that you may maintain the bell yourself with brass polish.  It also won't get anything trapped under the lacquer so it may actually require less maintenance.
There is also a contingent of players who find that lacquer has a detrimental influence on the sound, especially on the bell.  You may find that if the lacquer is removed, that the horn plays much better than it did with the lacquer.
Finally, you can get the horn re-lacquered.  This is purely optional though and largely for aesthetics.  There is a marginal amount of protection it affords the brass under it, but it needs to be wiped down frequently just as raw brass would or else you will end up with a horn that looks like the one you currently have!
Summary
What I would do is have it chemically cleaned in addition to what I recommended in your other question and remove the lacquer from the bell. But what you choose to do may be different depending on your preferences.
Sources:
http://tromboneforum.org/index.php?topic=63792.0
http://tromboneforum.org/index.php?topic=88611.0
Comment: Thank you so much. Haven't had the time to answer. I now play this instrument for a while and it didn't seem like bad red rot. Also, I am thinking of removing the lacquer completely. Had a chemical bath which made the parts go less reddish. The only thing I miss: the slide of my Conn 88H-CL goes much easier. Other than that… great instrument so far! Thanks for you help! :)
Answer: I personally do not play trombone myself, nor do I own one or know much about the handling of the instrument, but I do know that it probably isn't too harmful to the instrument's sound.
I know someone who has a trombone that looks like it was dipped in acid, then left outside in a rainstorm, and it still sounds amazing. (Believe it or not, it was technically dipped in acid then left in a rainstorm. He had the the lacquer removed from it, which uses nasty, caustic chemicals, and accidentally left it outside through a rainstorm. It survived, and it has a cool, almost synthetic sound to it. I don't recommend this route if you are trying to restore your trombone, though.)
You are experiencing "pitting" in the lacquer, which usually happens when it is exposed to water with a relatively low pH, or low oxygen levels. (tl;dr: Because science!)
You could re-apply the lacquer, but it is dangerous (for both you and, to a much lesser extent, the instrument), and potentially expensive.
Your best option is probably to use some form of light metal polisher.


eBay API - List an item with 'Local Pick up' shipping method

Question: I am a .NET developer. I am working on listing an item whose shipping method I want to set it as "Local Pick up". I referred to the API doc which says "LocalDelivery" should be used to define shippingmethod for Local Pick up. I did that and tried listing it on US sandbox. But then it gave me an exception:

Shipping Service Local Delivery/Pickup(15) is deprecated and mapped to Local Pickup(150).

Here is my code example:
ShippingServiceOptionsType shippingOptions = new ShippingServiceOptionsType();
shippingOptions.ShippingService = "LocalDelivery";
shippingOptions.ShippingServicePriority = 1;
shippingOptions.LocalPickup = true;
shippingOptions.FreeShippingSpecified = false;

Any ideas? Any help would be appreciated.
Answer: I think the problem is that you defined ShippingService as "LocalDelivery" it should be "LocalPickup". i.e.
shippingOptions.ShippingService = "LocalPickup";


What's the best way to download file using urllib3

Question: I would like to download file over HTTP protocol using urllib3.
I have managed to do this using following code:
 url = 'http://url_to_a_file'
 connection_pool = urllib3.PoolManager()
 resp = connection_pool.request('GET',url )
 f = open(filename, 'wb')
 f.write(resp.data)
 f.close()
 resp.release_conn()

But I was wondering what is the proper way of doing this.
For example will it work well for big files and If no what to do to make this code more bug tolerant and scalable.
Note. It is important to me to use urllib3 library not urllib2 for example, because I want my code to be thread safe.
Answer: Your code snippet is close. Two things worth noting:

If you're using resp.data, it will consume the entire response and return the connection (you don't need to resp.release_conn() manually). This is fine if you're cool with holding the data in-memory.
You could use resp.read(amt) which will stream the response, but the connection will need to be returned via resp.release_conn().

This would look something like...
import urllib3
http = urllib3.PoolManager()
r = http.request('GET', url, preload_content=False)

with open(path, 'wb') as out:
    while True:
        data = r.read(chunk_size)
        if not data:
            break
        out.write(data)

r.release_conn()

The documentation might be a bit lacking on this scenario. If anyone is interested in making a pull-request to improve the urllib3 documentation, that would be greatly appreciated. :)
Comment: Is there a reason for `while` looping when `for data in request.read(chunk_size)\n\tout.write(data)` *seems* to achieve the same results?
Comment: Good question. 64kb is probably a safe choice (2**16 or 65536).
Comment: And one more question. Will it work with POST method if I add `r = http.request('POST', url)`?
Comment: @running.t Err, that was a mistake in my code. You're right, the method should go first, and your snippet will work. (Updated my answer.)
Comment: I tried the above code today using urllib3 1.15.1. It needs two modifications to be 100% correct. First, you need `preload_content=False` in `http.request('GET', url, ...)`. Second, `if data is None` should be `if not data` to take into account that `data` being an empty string, not `None`. Otherwise, it works perfectly. Thank you. I also want to thank @Alecz below for providing more clues.
Comment: Works well! What's a reasonable chunk size?
Answer: The most correct way to do this is probably to get a file-like object that represents the HTTP response and copy it to a real file using shutil.copyfileobj as below:
url = 'http://url_to_a_file'
c = urllib3.PoolManager()

with c.request('GET',url, preload_content=False) as resp, open(filename, 'wb') as out_file:
    shutil.copyfileobj(resp, out_file)

resp.release_conn()     # not 100% sure this is required though

Comment: Doing `resp.release_conn()` with `preload_content=False` is required so that the connection can be reused by the pool manager. See [Streaming and IO](https://urllib3.readthedocs.io/en/latest/advanced-usage.html#streaming-and-io).
Comment: According to documentation `resp.release_conn()` seems not required. This is the description of the release_conn parameter: _If False, then the urlopen call will not release the connection back into the pool once a response is received (**but will release if you read the entire contents of the response** such as when preload_content=True)._
Answer: Most easy way with urllib3, you can use shutil do auto-manage packages.
import urllib3
import shutil

http = urllib3.PoolManager()
with open(filename, 'wb') as out:
    r = http.request('GET', url, preload_content=False)
    shutil.copyfileobj(r, out)


C# - How to get the area of a System.Drawing.Region?

Question: I'm computing the area of a rectagle after exclude the area of some circles.
this is my current solution:
<code>    var region = new Region( new Rectangle(0, 0, 10, 10) );
    var circle = new System.Drawing.Drawing2D.GraphicsPath();
    circle.AddEllipse(50, 50, 25, 25);
    // Exclude the circle from the region.
    region.Exclude(circle);
</code>
However I need something like region.getArea() to get the area after excluding the circle.
Do you know how to compute a System.Drawing.Region area?
-Or-
Do you know another way to compute a rectangle area after excluding some circles?
Comment: Why do you need the area? Maybe there's a better way to do whatever you're trying to do.
Comment: @MerickOWA's answer is the best solution for a general case. However, if you know that the circles don't overlap and are all within the rectangle, you can do some simple maths to compute the area by yourself.
Answer: <code>        float diam = 25;
        var region = new Region(new RectangleF(0, 0, diam, diam));
        var circle = new System.Drawing.Drawing2D.GraphicsPath();
        circle.AddEllipse(0, 0, diam, diam);
        region.Exclude(circle);

        var rects = region.GetRegionScans(new System.Drawing.Drawing2D.Matrix());
        float area = 0;
        foreach (var rc in rects) area += rc.Width * rc.Height;
        double realArea = diam * diam - Math.PI * diam * diam / 4;
        Console.WriteLine("Approx area = {0}, real area = {1}", area, realArea);
</code>
Output: Approx area = 141, real area = 134.126147876595
Keep this result in mind, the Region class was designed to be used in graphic code.  It is only accurate to a pixel with a knack for rounding errors to accumulate.  The larger you make diam, the smaller the relative error.
Answer: Theres no method to do so, but my best guess is that the GetRegionData function will give you back a RegionData who's Data member is a byte[] which matches the RGNDATA stucture from C++.  In there you have a header with a list of rectangles which don't overlap.  Calculating the area would be a simple for-loop at that point.
If the area is all your interested in and you don't plan to use the Region for drawing then this is probably an overkill.  The code my be simple but you'll be using up more memory and computer resources for a value calculation.
Solving it the 'mathy' way might involve alot of special cases, but once you solve the line-circle intersection code it shouldn't be too bad and would probably be faster than all the memory allocation of a RegionData and DC context.
Comment: yes, altough making multiple intersections become a pain. + 1
Comment: Geometry classes looks more appropiate for this case: http://msdn.microsoft.com/en-us/library/system.windows.media.geometry.aspx#inheritanceContinued what do you think?
Comment: @SDReyes Geometry classes are like regions, they're made for displaying not for area calculations.  For speed and correctness, code to handle the box/circle intersection would be best.  Perhaps looking for an existing geometry library if you need something more generic.


Como reorganizar de forma aleatória uma lista de Strings e selecionar um elemento por vez sem que se repita o valor contido na lista?

Question: Estou desenvolvendo um aplicativo em Android studio em linguagem Java e preciso saber como resolver meu problema.
Eu tenho uma lista de String:
List<String> valores = new ArrayList<>();

Dai então eu crio um loop for para adicionar Strings a essa Lista.
Exemplo:
int i;
for (i = 0; i < n; i++){
    valores.add(disp[i]);
}

Continuando o raciocínio, digamos que ao final desse loop for a minha lista ficou assim e nessa ordem:

"Pera" (na posição 0),
  "Maça" (na posição 1) ,
  "Uva" (na posição 2),
  "Banana" (na posição 3) e
  "Abacaxi" (na posição 4)

O que eu preciso é reorganizar de forma aleatória as posições dos itens da minha Lista e criar um método que pegue cada item de uma vez sem que o mesmo valor se repita.
Por exemplo: eu reorganizei as posições e a minha Lista ficou dessa forma:

"Uva" (na posição 0),
  "Banana" (na posição 1),
  "Abacaxi" (na posição 2),
  "Maça" (na posição 3) e
  "Pera" (na posição 4)

Agora, como exemplo, imagine que eu tenho um botão e que quando eu clico nesse botão, ele me mostre a primeira posição que é no caso "Uva" e  que quando eu clico no botão de novo ele me mostre a segunda opção que é banana.
A minha real intenção era usar Collections.shuffle(valores)
para embaralhar a lista e depois usar algum método que indique quais itens da minha lista já foram mostrados.
Isso tudo porque eu quero usar o realtime database do firebase para fazer a seguinte situação:
Eu tenho 3 usuários conectados. Daí então eu mando uma mensagem para o primeiro usuário com uma pergunta. Se o primeiro usuário responder "sim" o loop vai se interromper e meu aplicativo indicará para mim que ele aceitou e se ele disser não, então esse usuário é descartado e a mensagem é enviada ao segundo e assim por diante. Até que alguém responda sim ou então que todos digam não.
Answer: Boa noite, para embaralhar a lista você pode criar uma extensão para List<> como:
private static Random rng = new Random();

public static void Shuffle<T>(this IList<T> list)
{
    int n = list.Count;
    while (n > 1) {
        n--;
        int k = rng.Next(n + 1);
        T value = list[k];
        list[k] = list[n];
        list[n] = value;
    }
}
// USAR
List<Product> products = GetProducts();
products.Shuffle();

Para saber quais itens você já mostrou crie outra lista e adicione os elementos a ela quando você clicar no botão, depois você pode verificar se esse elemento já foi mostrado com método visualizados.conteins(KEY).
Comment: Obrigado meu amigo.... vou fazer dessa forma!


Check if Sequence is Graphic: 8, 8, 7, 7, 6, 6, 4, 3, 2, 1, 1, 1

Question: This is part of my Discrete Math homework and I have no idea how to solve this.
I am given this sequence: $8, 8, 7, 7, 6, 6, 4, 3, 2, 1, 1, 1 $
I have to check whether it is graphic or not.
How do I go on about doing that? Haven't done anything like this before so I'm a bit puzzled. I'm not sure how to solve this, do I have to plot this sequence or what?
Comment: have you tried applying the [handshaking lemma](http://en.wikipedia.org/wiki/Handshaking_lemma) yet?
Comment: Start with the defintion: a sequence is "[graphic](http://mathworld.wolfram.com/GraphicSequence.html)" *iff* it is attained as the [degree sequence of a graph](http://en.wikipedia.org/wiki/Degree_%28graph_theory%29#Degree_sequence).  This condition can be checked algorithmically.
Answer: A sequence is graphic if and only if the sequence obtained by deleting the largest degree $k$ and subtracting one to the $k$ largest degrees remaining is graphic.Try to prove this by induction.
hence you get $8,8,7,7,6,6,4,3,2,1,1,1$ is graphic $\iff$
$7,6,6,5,5,3,2,1,1,1,1$ is graphic $\iff$
$5,5,4,4,2,1,0,1,1,1$ is graphic $\iff$
$4,3,3,0,0,1,1,1,1$ is graphic $\iff$
$2,2,0,0,0,0,1,1,$ is graphic $\iff$
$1,0,0,0,0,0,1$ is graphic. So the graph is in fact graphic.
Here is a graph with that degree sequence
Comment: I mean, you should count the degrees in the graph to make sure, but I can't find more conclusive evidence it is graphic
Comment: This is part of my homework ~ therefore I can check online if the solution is correct, unfortunately your solution was incorrect, it said that the sequence isn't graphic. What's going on here? Maybe a mistake on their part?
Comment: Well, I counted the degrees in the graph in the solution and it is correct, are you sure you copied the sequence correctly?


Unable to access the updated global variable's value

Question: Suppose I have two Python files:

abc.py:

from .config import *
update_a()
print_a() # prints 5
print(a)  # prints 2 rather than 5 even after calling update_a() and using global in update_a()

config.py:

a = 2

def update_a():
    global a
    a = 5

def print_a():
    global a
    print(a) # prints 5

The global variable in config.py does not seem to have the updated value when accessed from abc.py.
Comment: use `globals()` to achieve what you are trying to achieve!
Answer: When you do an import say from .config import *, the variable a is imported as a local scope. Any modification to a will happen within the scope in abc.py NOT in config.py whereas the call to update_a() and print_a() is modifying the variable a within config.py
Answer: Adding to Joe's answer, you can achieve what you want with the following piece of code:
import config as config

config.update_a()
config.print_a() # prints 5

# This will print the global variable in 'config.py'
print(config.a)  # prints 5


Does a paired t-test compare means?

Question: The reason I ask is that I keep reading it compares means, yet everywhere people keep  using box-plots for visualization, which seems fishy to me.
In more detail I would like to know whether information of the 2 sample means is enough to unambiguously know the "direction"* of a paired t-test p-value?
Are there any theoretical scenarios where looking just at the 2 means would be misleading?
(Like many close pairs and a pair with infinite difference..)
*direction: I am lacking the jargon but for example the "direction" of a sign-test points to the group which has more "+". A U-test points to the direction of higher intra-sample mean of inter-sample-ranks and a 'normal' t-test_ind points to the direction of higher mean.
EDIT:
Here is the first google-picture result to "paired t-test visualization":
But obviously I know that a boxplot of the differences would be ok!
Comment: That's not right: a one-sample t-test evaluates whether the data are consistent with the true mean being equal to a hypothesized value.  It does not compare two distributions. The purpose of showing boxplots is to provide information beyond that presented by the t-test: there's nothing "fishy" about this.
Comment: A paired t-test in a one-sample test. Do you mean a two-sample t-test?
Comment: I'm sorry that you interpret comments intended to be helpful and informative as condescending.  I will disagree that my comments "add absolutely nothing"--that's clearly untrue, as several voters have indicated.
Comment: Yea, I basically mean a 1 sample t-test comparing the differences of 2 distribution before and after treatment to 0. Thereby it reduces variance caused by individual samples.
Comment: Could you please post an example of where you've seen the paired test visualized with box plots?
Comment: I just added an example as an edit.
Comment: But thanks anyways! You already passively answered my question by making me aware it's actually a 1 sample t-test. It DOES compare means of the 2 distributions, because the 1 sample t-test does. I know that now! So thanks!
Comment: So are you saying a paired t-test cannot be compared to a 1 sample t-test against 0? Otherwise what exactly is "wrong"? And you are saying that a box-plot is capable of visualizing which of the 2 distribution is higher in whatever measure the paired t-test compares the two, without any theoretical exceptions? Otherwise, I don't see how claiming it's not fishy provides useful information to any reader, given the context of the question.
Answer: The boxplot gives you a flavour of the two distributions. Often wrong statistical modelling (mistakes in the estimated significance, for instance) can be identified by looking at the plotted distributions.
It's easier to understand something visually than by abstract concepts like numbers.
One case where a plot (typically a violin plot) may be informative is when the distributions are complex (bimodal for instance). The plot gives an immediate sense of what's going on with the data. That would tell you if the statistical test assumptions are violated or not. For this reason, many journals require not only the boxplots (or violin plots) but also the individual points (when the number is not too large).
A paired t-test is equivalent to a t-test for the difference with null of 0:
You can easily check if with the following code:
x = rnorm(100, mean=0, sd=1)
y = rnorm(100, mean=5, sd=1)

Paired t-test:
t.test(x,y, paired = T)

gives:
Paired t-test

data:  x and y
t = -34.659, df = 99, p-value < 2.2e-16
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -5.297422 -4.723708
sample estimates:
mean of the differences
          -5.010565

T-test against 0:
t.test(x-y)

gives:
    One Sample t-test

data:  x - y
t = -34.659, df = 99, p-value < 2.2e-16
alternative hypothesis: true mean is not equal to 0
95 percent confidence interval:
 -5.297422 -4.723708
sample estimates:
mean of x
-5.010565

Does a paired t-test compare means?


What is the expected value of the chi square statistic when the null is true?

Question: And how does it depend on degrees of freedom? And why isn't the answer 0?
Comment: Re "why isn't the answer zero" - why do you expect it to be? It is difficult to explain the flaw in your reasoning unless you say why you thought it would be zero. By chi squared test, do you mean the chi squared test for variance or the co squared test for goodness of fit? (Not that this changes the expected value but it might change the intuition for why it isn't zero.)
Comment: This question seems clear enough to me, & has a good answer to boot.
Comment: i'm talking about a chi squared test for the variance. sorry if missing many obvious details, as just briefly exposed to this, but by the null, wouldn't there be no explained or observed variance in the numerator?
Answer: If all the other assumptions hold (and, depending on which particular chi-square test you're doing), also assuming that the chi-square approximation to the distribution of the test statistic holds*, then under the null hypothesis, the statistic has the same distribution as the sum of squares of $\nu$ independent standard normal random variables.
* chi-squared tests of counts have a discrete distribution that is approximated by a chi-square.
This has expectation $\nu$ and variance $2\nu$.

why isn't the answer 0?

Assuming you're doing some kind of "observed minus expected" calculation -- because under the null hypothesis the observed values are random quantities whose mean happens to be the expected values, but they vary around that mean. Hence their squared-standardized-differences from those expected values won't be 0;  $\mathbb{E}(O_i-E_i)= 0$ (under the null) but $\mathbb{E}[(O_i-E_i)^2]$ - essentially a variance - is not.
Comment: sorry, hastily written and mistitled. What is the expected chi square stat assuming the null is true? Using chi-square to test multiple regression parameters
Comment: How are you using the chi-square to do that? Are you doing an asymptotic Wald chi-square? If so, why not just do an F test? (and if that's what you are doing then the small sample distribution doesn't have an expectation of $\nu$ under the null; under iid normal errors the expectation would be $\nu\cdot\frac{\nu_e}{\nu_e-2}$)


Loop through a list using a while statement

Question: I want to loop through a list and terminate when I reach a certain value.
Something like:
ls = ['yes','yes','stop','yes']

while a in ls <> 'stop':
    print a

Would print:
yes
yes

I know I can do:
for a in ls:
    if a == 'stop':
        break
    print a

but it seems messy.
Comment: It might be "messy", but it is perfectly clear & does the job
Comment: Also, you should not be using `<>`.  That operator was deprecated in Python 2.5 and removed entirely from Python 3.x.  You should be using `!=` instead.
Answer: You could use list indexing and slicing:
print ls[:ls.index('stop')]
# => ['yes', 'yes']

In a loop:
for a in ls[:ls.index('stop')]:
    print a

Answer: You could use itertools.takewhile:
>>> from itertools import takewhile
>>> ls = ['yes','yes','stop','yes']
>>> for i in takewhile(lambda x: x != 'stop', ls):
...     i
...
'yes'
'yes'
>>>


Problems with custom renderer and validation triggered in custom elements

Question: I'm using firstname.lastname@example.com.
My scenario is:

I've got a form which has a validation controller and validation rules
There is a containerless custom element in the form which wraps a password input, and exposes the current password as a bindable property
The validate binding behavior is used on the form's binding to this custom element property
The custom element also raises the blur event, so that the validation binding is triggered when the wrapped password input loses focus

The validation lifecycle is working as expected.
The problem I'm running into is with the custom renderer I'm using, which currently assumes the element it receives is the actual DOM input element so that a class can be applied to the input, and a sibling error element can be injected next to it, but here it's receiving the custom element that wraps the input, which can't be handled in the same manner because it's just a comment node in the DOM.
Is there a strategy or API in aurelia-validation that could solve this sort of problem? I'm stumped, and can't find much out there on working with custom elements within validation.
EDIT:
Here is the custom element template:
<template>

        <input
            id="password"
            type="${isPasswordVisible ? 'text' : 'password'}"
            value.bind="password"
            t="[placeholder]fields_Password"
            maxlength="20"
            focus.trigger="onInputFocus()"
            blur.trigger="onInputBlur()" />

</template>

I made it containerless because I don't want <password-box> emitted into the DOM as an outer element, as that breaks the current CSS rules for layout (and I don't want to change the CSS).
However if the custom element is containerless then I don't know how to access the first div inside the template using DOM navigation from the comment node that represents the custom element in the DOM.
Comment: Could you share your custom-element's code? Any specific reason for `@containerless`? Perhaps you will have to check whether the element is a real HTMLInputElement or a comment, and then choose the right strategy
Comment: I added the template code.
Answer: Unfortunately, Aurelia team has identified this issue and (at least as of now) said they won't fix it. https://github.com/aurelia/templating/issues/140
There is a hacky workaround for the issue as follows:
if(element.nodeType === 8) {
  element = this.getPreviusElementSibling(element)
}

If you add that within your render method for your renderer, it should work. Again, hacky, but it gets the job done in lieu of an official fix from the AU team.
Comment: We ended up creating a solution that allows custom elements to interact with validation in the parent context via implementing a custom interface - when the validation renderer inspects elements for attaching messages, it can see if the element is a custom element, and pass the validation instruction to it by interacting with the custom element as an interface (called IHasCustomValidation), so the custom element can return the inner element instead, this works pretty well in practice.


Calculate simple trajectory

Question: I'm working with OpenGL developing a simple (very simple) game. I came across a problem with calculating a missile trajectory (unfortunately don't have many math skills).
I'm working with $x$, $y$ and $z$ coordinates. My target is set at coordinates $(40,40,0)$ and my missile launcher is at $(40,0,50)$ with a zero angle.
I'm discarding gravitational forces and other forces.
If my missile position was perpendicular to my target and with a zero angle, and an constant velocity, if I fire the missile, it would go at a given rate, decreasing is $z$ coordinate and stop at $z=0$.
My problem is if the missile is not perpendicular to the target and if it as an angle.
So my simple question is how can I calculate the trajectory, my target is set at some coordinates and my missile launcher at another coordinates and with some angle?
Comment: To calculate the trajectory, we need to know the direction of firing. This will be a 3D vector, $(x,y,z)$. You say the launcher has "zero angle". Does that mean you're firing horizontally? If so, we know that $z=0$. We need $x$ and $y$, too.
Comment: Sorry. I just noticed that we are supposed to ignore gravity. So I suppose the direction of firing is directly towards the target.
Comment: @bubba Thanks. Yes. To make it more simple lets ignore  gravity. Imagine the missile launcher is at an 25 degree angle ($y$ coordinate) at the position ($40,0,50$) with a 15 degree angle at the $z$ coordinate (it's not facing front to the "wall"). The direction of firing is where the "wall" is, at $z=0$. I need to know with that position of the missile where is he going to hit the wall. Since i'm ignoring gravity, it will be a straight line.
Comment: This seems like a completely different question. What's this "wall" thing? How (from where) are the angles measured? If the angles specify the direction of firing, then what's the relevance of the target? A picture would probably help.
Comment: Sorry. Missed this comment. The "wall" thing is the plane were the target is placed. The angles are measured from the position of the missile. If the missile is at (40,0,50) the angle is measured between $z$ and $y$ for the vertical position and from the $z$ and $x$ for the horizontal position
Answer: I assume we fire directly at the target. Suppose the speed of the bullet is $v$. Then, at time $t$, the position of the bullet will be
\begin{align*}
x &= 40     \\
y &= 40vt/d        \\
z &= 50 - 50vt/d
\end{align*}
where $d = \sqrt{4100}$ is the distance between the launch site and the target. You can check that the bullet reaches the target when $t = d/v$.
Comment: Thanks bubba. Where does the value 4100 comes from? And if we do not fire directly at the target?
Comment: I explained the 4100. If you don't fire directly at ther target, you need to specify the direction vector. See comments above.
Comment: Thanks. Lets say the missile is at (40,0,50) ant the direction target is (20,10,0) it would be $x = 20; y= 10vt/d;z = 50-50vt/d$??

Calculate simple trajectory


entropy of the sum of binomial distributions

Question: Suppose that one has $X_1 \sim Bin(n,p)$ and $X_2 \sim Bin(n,1-p)$ and that $Z$ is distributed s.t:
$$
P(Z = k) = .5 P(X_1=k) + .5P(X_2=k)
$$
How do we compute the entropy? For a binomial distributed variable i have seen this proof:
Entropy of a binomial distribution
let $A = p^k (1-p)^{n-k} + (1-p)^k (1-p)^{n-k}$ then we see that:
\begin{align}
H(Z) &= -.5 \sum {n \choose k} \Big[A\Big] \log \Big[.5{n \choose k}A\Big] \\&= 1 - .5\sum {n \choose k} \Big[A\Big] \log \Big[{n \choose k}\Big] -  .5\sum {n \choose k} \Big[A\Big] \log \Big[A\Big]
\end{align}
Using de-Moivre-Laplace theorem, i get:
\begin{align*}
1+\log_2(\sqrt{2\pi}\sigma) + \int_{-\infty}^{\infty} \Big[e^{{\frac{(x-\mu_1)^2}{2\sigma^2})}}+e^{{\frac{(x-\mu_2)^2}{2\sigma^2})}}\Big] \log_2(e^{{\frac{(x-\mu_1)^2}{2\sigma^2})}}+e^{{\frac{(x-\mu_2)^2}{2\sigma^2})}})
\end{align*}
where $\mu_1 = np, \mu2 = n(1-p)$ and $\sigma^2 = np(1-p)$
I tried to get the integral on the right hand side using Mathematica but that failed. Any suggestions on how to get the exact or approximation of this integral? What i tried is this:
\begin{align*}
R &= \int_{-\infty}^{\infty}\frac{1}{2\sigma\sqrt{2 \pi}}\Big[e^{-\frac{(x-\mu_1)^2}{2\sigma^2}}+e^{-\frac{(x-\mu_2)^2}{2\sigma^2}}\Big]\log_2\left(e^{-\frac{(x-\mu_1)^2}{2\sigma^2}}+e^{-\frac{(x-\mu_2)^2}{2\sigma^2}}\right) \\ &= \int_{-\infty}^{\infty}\frac{1}{2\sigma\sqrt{2 \pi}}\Big[e^{-\frac{(x-\mu_1)^2}{2\sigma^2}}+e^{-\frac{(x-\mu_2)^2}{2\sigma^2}}\Big]\Big[\log_2\left(e^{\frac{(x-\mu_{1})^2}{2\sigma^2}}\right)+\log_2\left(1+e^{\frac{-(2p-1)(n-2x)}{2(p-1)p}}\right)\Big]
\\& \approx \frac{1}{2\sigma\sqrt{2 \pi}}\int_{-\infty}^{\infty}\Big[e^{-\frac{(x-\mu_1)^2}{2\sigma^2}}+e^{-\frac{(x-\mu_2)^2}{2\sigma^2}}\Big]\log_2\left(\left(e^{\frac{(x-\mu_1)^2}{2\sigma^2}}\right)\right) + \frac{1}{\sigma\sqrt{2 \pi}} \int_\frac{n}{2}^{\infty}\left(e^{-\frac{(x-\mu_1)^2}{2\sigma^2}}+e^{-\frac{(x-\mu_2)^2}{2\sigma^2}}\right) e^{\frac{-(2p-1)(n-2x)}{2(p-1)p}} \\&= \frac{1}{4}\log_2(e)\left(1 + (\sigma^2 + (n-2\mu_1)^2)\right) + \frac{1}{\sigma\sqrt{2 \pi}} \int_\frac{n}{2}^{\infty}\left(e^{-\frac{(x-\mu_1)^2}{2\sigma^2}}+e^{-\frac{(x-\mu_2)^2}{2\sigma^2}}\right) e^{\frac{-(2p-1)(n-2x)}{2(p-1)p}}
\end{align*}
The approximation
$\log_2(1+e^{\frac{-(2p-1)(n-2x)}{2(p-1)p}}) \approx e^{\frac{-(2p-1)(n-2x)}{2(p-1)p}} \text{if } x \in [\frac{n}{2},\infty)$ and since the function is symetrical around $\frac{n}{2}$ i can just multiply the integration by 2. The right hand side gives me an ugly term so i was wondering if an approximation there could work?
Are there more theorems that i should consider looking at?
Comment: I didn't write an answer; it's by leonbloy.
Comment: The entropy will vary between $H_0$ and $H_0+1$, where $H_0$ is the entropy of a single binomial. (For $p=0.5$ you're just reproducing the binomial, and for $p\to0$ you have one extra bit of information for which branch was used.) So you could try to subtract out the $H_0$ part and approximate the rest as a function between $0$ and $1$.
Comment: How did you come up with these bounds? I do understand it has an upper bound of 1 and lower bound of 0, is that what you mean?
Comment: What are you referring to by "it"?
Comment: the entropy but you clarified everything in your answer thanks :D
Answer: For small $n$, you just compute it numerically.
If you need an approximation for large $n$, (and $p$ not too close to $0$ or $1$) you can rely on the approximation for a single Binomial distribution from the linked question:
$$H(B;n,p)=\frac1 2 \log_2 \big( 2\pi e\, np(1-p) \big) + O \left( \frac{1}{n} \right) \tag{1}$$
You can combine this with the known expression for the entropy of a mixture: Let $Z$ be a rv chosen from one of two rvs $X,Y$ with probabilities $\alpha,1-\alpha$; then, applying the entropy chain rule to $H(Z,A)$ (where $A$ is a variable that indicates which of the two rvs was chose) we get
$$H(Z)=H(A)+H(Z\mid A) - H(A\mid Z)=h(\alpha)+\alpha H(X) + (1-\alpha)H(Y)- H(A\mid Z) \tag{2}$$
where $h(\cdot)$ is the binary entropy function. In our case, $\alpha=\frac12$ and $H(X)=H(Y)=H(B;n,p)$, hence
$$H(Z)=1 + H(B;n,p) - H(A \mid Z) \tag{3}$$
Because $0\le H(A \mid Z)\le1$,
$$H(B;n,p)\le H(Z)\le 1 + H(B;n,p) $$
Assuming $0<p<1$ and $n\to \infty$, then $$ H(Z) =
 \frac1 2 \log_2 \big( 2\pi e\, np(1-p) \big) + O(1)\\
\approx \frac1 2 \log_2 \big( 2\pi e\, np(1-p) \big)$$
Comment: I really like the way of thinking in this proof, do you think for small $n$ only numerical approximations are possible?
Comment: For small $n$, one can hardly think of something better than just computing it numerically  - even the entropy of a single Binomial


Linear regression when you only know $X^t Y$, not $Y$ directly

Question: Suppose $X\beta =Y$.
We don't know $Y$ exactly, only its correlation with each predictor, $X^\mathrm{t}Y$.
The ordinary least-squares (OLS) solution is $\beta=(X^\mathrm{t} X)^{-1} X^\mathrm{t}Y$ and there isn't a problem.
But suppose $X^\mathrm{t}X$ is near singular (multicollinearity), and you need to estimate the optimal ridge parameter. All the methods seems to need the exact values of $Y$.
Is there an alternative method when only $X^\mathrm{t}Y$ is known?
Comment: @JohnSmith: You are alluding to the point I was driving at. There is no indication of how to measure "optimality". What you are effectively doing is introducing a different metric (distance function) to measure "quality" of prediction or fit. We need more details from the OP in order to get very far, I suspect.
Comment: @Pardis: Finding the estimates is not the problem, as you note. :) However, if you decide to do crossvalidation, how are you going to estimate the out-of-sample MSE, i.e., on the left-out fold for each iteration? :)
Comment: interesting question.  Perhaps some sort of EM algorithm would work...
Comment: I don't understand, can't you use cross-validation for estimating the optimal ridge parameter?
Comment: @Pardis: No loss function is given in the question so we don't know what *optimal* means. Can you see the trouble we run into if the loss function is the MSE?
Comment: Actually, cannot we still use cross-validation? Let's say we are looking for $\lambda$ that minimizes the error like this: $||(X_{cv}^t X_{cv})\beta(\lambda) - X_{cv}^t Y_{cv}||$, where $\beta(\lambda) = (X_{train}^t X_{train} + \lambda I)^{-1} X_{train}^t Y_{train}$. That is not exactly correct, but can work.
Comment: @Pardis: If you don't know $Y$, how do you find $\|Y - \hat Y\|_2^2$? :)
Comment: @cardinal I see, but isn't the loss function for OLS the square loss? We see that the solution can be expressed in terms of $X^tY$, just like the solution of ridge regression.
Comment: @cardinal: The loss function is the MSE, as in the OLS.
Comment: @JohnSmith: cv isn't possible, we don't know individual $Y_i$
Answer: This is an interesting question. Surprisingly, it is possible to do something under certain assumptions, but there is a potential loss of information about the residual variance. It depends upon $X$ how much is lost.
Let's consider the following singular value decomposition $\newcommand{\t}{^\mathrm{t}}X = UDV\t$ of $X$ with $U$ an $n \times p$ matrix with orthonormal columns, $D$ a diagonal matrix with positive singular values $d_1 \geq d_2 \geq ... \geq d_p > 0$ in the diagonal and $V$ a $p \times p$ orthogonal matrix. Then the columns of $U$ form an orthonormal basis for the column space of $X$ and
$$Z = U\t Y = D^{-1} V\t V D U\t Y = D^{-1} V\t X\t Y$$
is the vector of coefficients for the projection of $Y$ onto this column space when expanded in the $U$-column basis. From the formula we see that $Z$ is computable from knowledge of $X$ and $X\t Y$ only.
Since the ridge regression predictor for a given $\lambda$ can be computed as
$$\hat{Y} = X(X\t X + \lambda I)^{-1} X\t Y = U D(D^2 + \lambda I)^{-1} D U\t Y = U D(D^2 + \lambda I)^{-1} D Z$$
we see that the coefficients for the ridge regression predictor in the $U$-column basis are
$$\hat{Z} = D (D^2 + \lambda I)^{-1} D Z.$$
Now we make the distributional assumption that $Y$ has $n$-dimensional mean $\xi$ and covariance matrix $\sigma^2 I_n$. Then $Z$ has $p$-dimensional mean $U\t \xi$ and covariance matrix $\sigma^2 I_p$. If we imagine an independent $Y^{\text{New}}$ with the same distribution as $Y$ (everything conditionally on $X$ from hereon) the corresponding $Z^{\text{New}} = U\t Y^{\text{New}}$ has the same distribution as $Z$ and is independent and
\begin{eqnarray*}
E ||Y^{\text{New}} - \hat{Y}||^2 &= & E || Y^{\text{New}} - U Z^{\text{New}} + U Z^{\text{New}}  - U \hat{Z} ||^2 \\
& = & E || Y^{\text{New}} - U Z^{\text{New}}||^2 + E||U Z^{\text{New}}  - U \hat{Z} ||^2 \\
& = & \text{Err}_0 + E||Z^{\text{New}}  - \hat{Z} ||^2.
\end{eqnarray*}
Here the third equality follows by orthogonality of $Y^{\text{New}} - U Z^{\text{New}}$ and $U Z^{\text{New}}  - U \hat{Z}$ and the fourth by the fact that $U$ has orthonormal columns.
The quantity $\text{Err}_0$ is an error that we cannot get any information about, but it does not depend upon $\lambda$ either. To minimize the prediction error on the left hand side we have to minimize the second term on the right hand side.
By a standard computation
\begin{eqnarray*}
E||Z^{\text{New}}  - \hat{Z} ||^2 &= & E||Z - \hat{Z}||^2 + 2 \sum_{i=1}^p \text{cov}(Z_i, \hat{Z}_i) \\ & = &
E||Z - \hat{Z}||^2 + 2 \sigma^2 \underbrace{\sum_{i=1}^p \frac{d_i^2}{d_i^2 + \lambda}}_{\text{df}(\lambda)}.
\end{eqnarray*}
Here $\text{df}(\lambda)$ is known as the effective degrees of freedom for ridge regression with parameter $\lambda$. An unbiased estimator of $E||Z - \hat{Z}||^2$ is
$$\text{err}(\lambda) = ||Z - \hat{Z}||^2 = \sum_{i=1}^p \left(1 - \frac{d_i^2}{d_i^2 + \lambda}\right)^2 Z_i^2.$$
We combine this with the (unbiased) estimator
$$\text{err}(\lambda) + 2 \sigma^2 \text{df}(\lambda)$$
of $E||Z^{\text{New}}  - \hat{Z} ||^2$ given that we know $\sigma^2$, which we then need to minimize. Obviously, this can only be done if we know $\sigma^2$ or have a reasonable guess at or estimator of $\sigma^2$.
Estimating $\sigma^2$ can be more problematic. It is possible to show that
$$E||Z - \hat{Z}||^2 = \sigma^2\left(p - \underbrace{\sum_{i=1}^p \frac{d_i^2}{d_i^2 + \lambda}\left(2 - \frac{d_i^2}{d_i^2 + \lambda}\right)}_{\text{d}(\lambda)}\right) + \text{bias}(\lambda)^2.$$
Thus if it is possible to choose $\lambda$ so small that the squared bias can be ignored we can try to estimate $\sigma^2$ as
$$\hat{\sigma}^2 = \frac{1}{p-\text{d}(\lambda)} ||Z - \hat{Z}||^2.$$
If this will work depends a lot on $X$.
For some details see Section 3.4.1 and Chapter 7 in ESL or perhaps even better Chapter 2 in GAM.
Answer: Define $β$ as in the question and $β(λ,K)=[(X^TX)_{KK}+λI]^{−1}(X^TY)_K$ for various parameters $\lambda$ and sets $K$ of sample labels.
Then $e(λ,K):=\|Xβ(λ,K)-Y\|^2-\|Xβ-Y\|^2$ is computable since the unknown $\|Y\|^2$ drops out when expanding both norms.
This leads to the following algorithm:

Compute the $e(λ,K)$ for some choices of the training set $K$.
Plot the results as a function of $\lambda$.
Accept a value of $\lambda$ where the plot is flattest.
Use $β^*=[X^TX+λI]^{−1}X^TY$ as the final estimate.
Comment: @ArnoldNeumaier: $(X^TY)_K$ isn't computable. We only know the correlation with each predictor. $(X^TY)$ is in the "predictor domain", not in the "Y domain" (If N is the sample size and p the number of predictors, we only have p values, one for each predictor).
Comment: I'm guessing "where the plot is flattest" will be at $\lambda$ very small, like roughly 0 :)
Comment: @jbowman: This will happen only if the problem is well-conditioned and needs no regularization, then $\lambda=0$ is indeed adequate. In the ill-conditioned case, the prediction of the items outside $K$ will be poor because of overfitting, and $e(\lambda,K)$ will therefore be large.
Comment: @Jag: Then there is not enough information for selecting $\lambda$. But $X^TY$ must have been collected somehow. If during its collection you partition the sample into $k$ batches and assemble the $X^TY$ separately for each batch then one can reserve one batch each for cross validation.
Comment: @ArnoldNeumaier: $X^TY$ are externally given, don't collected.


Problem mapping classes with different attributes with MapStruct

Question: I'm trying to make a mapping using MapStruct but I don't know how to deal with the fields from one to the other.
I have the classes below:
class DataDomain {

    private List<Domain> data;
}

class Domain {

    private String codDist;

    private String numFun;

    private String txtJust;

    private Boolean valPar;

    private LocalDateTime dateHr;

    private Integer numPn;
}

class DataEntity {

    private String codDist;

    private String numFun;

    private List<ParEntity> pares;
 }

class ParEntity {

    private String numFun;

    private String txtJus;

    private String indValPar;

    private String dateHr;

    private String numPn;
    }

interface ParOutMapper{

    ParOutMapper INSTANCE = Mappers.getMapper(ParOutMapper.class);

    @Mapping(target = "data", source = "entity")
    DataDomain map(DataEntity entity);

    Domain toDomain(DataEntity entity);

    default List<Domain> toList(DataEntity entity) {
        return entity != null ? singletonList(toDomain(entity)) : new ArrayList<>();
    }

    default DataEntity map(DataDomain domain) {
        return domain != null
                && domain.getData() != null
                && !domain.getData().isEmpty() ? toEntity(domain.getData().get(0)) : null;
    }

    DataEntity toEntity(Domain domains);

    List<Domain> toDomainList(List<DataEntity> domainList);
}

That's what I've done so far, but it's giving divergence in the mapping because both have different structures and I ended up getting lost in how to apply their origin and destination field to field.
If possible and someone knows how to do it in an interesting correct way I would be very grateful.
Answer: I would suggest the following solution
@Mapper(unmappedTargetPolicy = ReportingPolicy.ERROR,
    componentModel = "spring",
    collectionMappingStrategy = CollectionMappingStrategy.ADDER_PREFERRED,
    builder = @Builder(disableBuilder = true))
public interface ParOutMapper {

@Mapping(target = "data", source = "entity")
DataDomain map(DataEntity entity);

@Mapping(target = "txtJust", source = "pares", qualifiedByName = "txtJust")
@Mapping(target = "valPar", source = "pares", qualifiedByName = "valPar")
@Mapping(target = "dateHr", source = "pares", qualifiedByName = "dateHr")
@Mapping(target = "numPn", source = "pares", qualifiedByName = "numPn")
Domain toDomain(DataEntity entity);

default List<Domain> toList(DataEntity entity) {
    return entity != null ? singletonList(toDomain(entity)) : new ArrayList<>();
}

default DataEntity map(DataDomain domain) {
    return domain != null
            && domain.getData() != null
            && !domain.getData().isEmpty() ? toEntity(domain.getData().get(0)) : null;
}

@Mapping(target = "pares", ignore = true)
DataEntity toEntity(Domain domains);

List<Domain> toDomainList(List<DataEntity> domainList);

@AfterMapping
default DataEntity valuesToList(Domain domains, @MappingTarget DataEntity dataEntity){
    ParEntity parEntity = new ParEntity();
    parEntity.setDateHr(domains.getDateHr().toString()); // alternative call custom entity to list mapping here !
    parEntity.setTxtJus(domains.getTxtJust());
    parEntity.setNumPn(domains.getNumPn().toString());
    parEntity.setNumFun(domains.getNumFun());
    parEntity.setIndValPar(domains.getValPar().toString());
    dataEntity.setPares(List.of(parEntity));
    return dataEntity;
}

@Named("txtJust")
default String mapTxtJust(List<ParEntity> pares) {
    return pares.get(0).getTxtJus(); // or custom mapping logic here
}

@Named("valPar")
default Boolean mapValPar(List<ParEntity> pares) {
    return Boolean.valueOf(pares.get(0).getIndValPar()); // or custom mapping logic here
}

@Named("dateHr")
default LocalDateTime mapDateHr(List<ParEntity> pares) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
    return LocalDateTime.parse(pares.get(0).getDateHr(),formatter); // or custom mapping logic here
}

@Named("numPn")
default Integer mapNumPn(List<ParEntity> pares) {
    return Integer.valueOf(pares.get(0).getNumPn()); // or custom mapping logic here
}
}

Since you tagged your question with spring-boot i assume you are using it. Therefore i would suggest to use the provided component model by mapstruct in its configuration
I am unsure how you want to do your mapping of list to entitiy or entity to list. With my approach you can do it value by value or with the entire list. Both workes either way.
The solution compiles and workes for DataEntity toEntity(Domain domains); and Domain toDomain(DataEntity entity); i did not recognize any other problems since mapstruct is able to generate the required mappings.
Comment: Thanks! Your approach worked!