Blazor: How to conditionally redirect user to another page at startup?

Question: I have the _Host.cshtml.cs file. The code is executed before any page is loaded.
Blazor by default will load the page with a matching @page header.
But I detected something in HttpContext and I want take the user who requested the "/" URL to another default location. A redirection, but in code.

Redirection should occur before any page is loaded (should load my special page).
Should not affect normal site operation (header criteria not met - default page loaded, default routing)

I need it for a mobile version of my application. I detect mobile browsers. Done. I even create different menu in my MainLayout. Done. Now I just want the other page to be default for mobile users.
I have following code:
if (_httpContextAccssor.HttpContext.Request.Path == "/")
                _httpContextAccssor.HttpContext.Request.Path = "/m_index";

It works, but the page is displayed for like a half of a second, then I'm redirected again to "/".
The app uses Identity to log in users and redirect to the login page. I have a hunch it's somehow related to it, but I'm not sure how. When a user is not logged in he or she is redirected to the login page. Then "/" page is loaded. The problem is the user is already logged in (cookie), the login page doesn't show, but still I'm redirected from the page I set in the Request.Path.
Answer: OK, got it. I could delete the question, but maybe someone would stumble upon the similar problem.
First things first:
How to use the HttpContext object in server-side Blazor to retrieve information about the user, user agent
Here's what I've started from. I needed to detect a mobile device, it worked as charm (with a few modifications, irrelevant now).
The important part is that _Host.cshtml.cs example. In the link I pasted there is description how to access the HttpContext of the request. And one more important thing - how to pass parameters from the host to the main App.razor component.
So I just wondered - what if I made a redirection there, in the App?
So, my App:
using Microsoft.AspNetCore.Components;
using System;

namespace Example {

    public partial class App : IDisposable {

        [Inject] NavigationManager NavMan { get; set; }

        [Parameter] public bool IsMobile { get; set; }

        void LocationChangeEventHandler(object sender, EventArgs eventArgs) => ScriptableComponentBase.ResetInstanceCounter();

        protected override void OnInitialized() {
            base.OnInitialized();
            NavMan.LocationChanged += LocationChangeEventHandler;
            var localPath = new Uri(NavMan.Uri).LocalPath;
            if (IsMobile && localPath == "/") NavMan.NavigateTo("/m_index");
        }

        public void Dispose() => NavMan.LocationChanged -= LocationChangeEventHandler;

    }

}

Holup... How do I get IsMobile parameter?
Here, my relevant _Host.cshtml fragment:
<app>
    <component type="typeof(App)" render-mode="ServerPrerendered" param-IsMobile="@Model.IsMobile" />
</app>

Wait, but where does the Model come from? From the linked example. Here's mine _Host.cshtml.cs:
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Components;

namespace Example.Pages {

    ///
    /// Allows access HttpContext to detect mobile requests.
    /// <see href="https://stackoverflow.com/questions/59538318/how-to-use-the-httpcontext-object-in-server-side-blazor-to-retrieve-information" />
    ///
    public class HostModel : PageModel {

        private readonly IHttpContextAccessor _httpContextAccssor;
        private readonly Regex RxMobileUATest = new Regex(@"(iPhone|Android|Mini|Mobile|Puffin)", RegexOptions.Compiled);

        public HostModel(IHttpContextAccessor httpContextAccssor, NavigationManager navigationManager) => _httpContextAccssor = httpContextAccssor;

        public string UserAgent { get; private set; }

        public string IPAddress { get; private set; }

        public bool IsMobile { get; private set; }

        public void OnGet() {
            UserAgent = _httpContextAccssor.HttpContext.Request.Headers["User-Agent"];
            IPAddress = _httpContextAccssor.HttpContext.Connection.RemoteIpAddress.ToString();
            IsMobile = RxMobileUATest.IsMatch(UserAgent);
        }

    }

}

It all looks a little bit chaotic, but it shows the direction of my investigation. First I've checked if I can redirect the main page ("/" request) to a random other page in the App component. To my greatest surprise I could. The rest seemed to be easy having the knowledge from the link. So - I needed my app to know, if the request comes from a mobile browser. I've seen in linked example, that a parameter can be passed to the App component. I just needed to get the value. So I needed to access HttpContext of the request to get the headers from the browser, that can be done like in linked example: basically you create a model for the _Host.cshtml page. You have also to add services.AddHttpContextAccessor(); to your Startup.ConfigureServices() method. Having the context - detecting the mobile browsers by UserAgent header is a piece of cake. You can totally ignore all weird cases. If a mobile browser doesn't want mobile content - fine, we serve desktop. If the mobile browser doesn't want to announce it's a mobile browser like most mobile browsers do - we serve desktop.
Look mum, no JavaScript! ;)


LoL player needs help configuring DotA 2 quick cast controls

Question: I have my keys in LoL like this:
<code>Shift does not queue commands.
Shift-key = quick cast
Control-key = quick self cast
</code>
Since I can configure my keys like this in both LoL and HotS, I'm sure that if I don't play DotA with these, it will start confusing me in the other two games.
Last time I checked (a while ago, admittedly) I could not bind the control key in this way since it was reserved. Is there some way I can get around this? I can play on either OSX or Windows 10, so third-party keyboard modifiers on either platform are a possibility.
I tried asking on the Steam forum, but they just threw a bunch of insults at me.
Comment: Hmm I dont have dota 2 installed right now, so i can't check. But you could remap your control key with the help of an autohotkey script. Very easy to write and you can toggle it on/off with a hotkey aswell.
Comment: Doing that kind of stuff for a long time since many games don't allow you to change all or certain hotkeys. Yeah the writing gets messed up. Therefore I recommend to have a on/off toggle button aswell.
Comment: So this hotkey thing would intercept control, and send it as something else, fooling dota?
Comment: Yes, you could set quickcasting in dota on a unused key like "U" for example. In your autohotkey script your could map Control => U, so everytime you press control, U gets pressed and your quickcast.
Comment: @PaulErlenmeyer thanks a lot, I have come up with something that works based on this comment. Makes a mess of normal typing though. ;)
Answer: So the answer I came up with was to use Karabiner, a keyboard remapping app.
The config looks like this:
<code>{
  "title": "DotA 2 quick cast modifiers",
  "rules": [
    {
      "description": "Map <shift-key> combinations to quick-cast keys.",
      "manipulators": [
        {
          "type": "basic",
          "from": {
            "key_code": "q",
            "modifiers": {
              "mandatory": [
                "left_shift"
              ]
            }
          },
          "to": [
            {
              "key_code": "t"
            }
          ]
        },
        {
          "type": "basic",
          "from": {
            "key_code": "w",
            "modifiers": {
              "mandatory": [
                "left_shift"
              ]
            }
          },
          "to": [
            {
              "key_code": "y"
            }
          ]
        },
</code>
This remaps Shift+q to t, and Shift+w to y. In DotA 2, I have t set to quick-cast the normal q spell, and y to quick-cast the normal w spell, etc. Add more in that comma-seperated list.


Is it possible to compute the minimum of a set of numbers modulo a given number in amortized sublinear time?

Question: Is there a data structure representing a large set S of (64-bit) integers, that starts out empty and supports the following two operations:

insert(s) inserts the number s into S;
minmod(m) returns the number s in S such that s mod m is minimal.

An example:

    insert(11)
    insert(15)
    minmod(7) -> the answer is 15 (which mod 7 = 1)
    insert(14)
    minmod(7) -> the answer is 14 (which mod 7 = 0)
    minmod(10) -> the answer is 11 (which mod 10 = 1)

I am interested in minimizing the maximal total time spent on a sequence of n such operations. It is obviously possible to just maintain a list of elements for S and iterate through them for every minmod operation; then insert is O(1) and minmod is O(|S|), which would take O(n^2) time for n operations (e.g., n/2 insert operations followed by n/2 minmod operations would take roughly n^2/4 operations).
So: is it possible to do better than O(n^2) for a sequence of n operations? Maybe O(n sqrt(n)) or O(n log(n))? If this is possible, then I would also be interested to know if there are data structures that additionally admit removing single elements from S, or removing all numbers within an interval.
Comment: Is there a bound on the modulo?
Comment: @MatthewStrawbridge I don't think they can both be O(1) you may be misunderstanding the question
Comment: If `n` is the number of elements in the array, then this is O(n), surely?  For each element, calculate `x % m`, and keep track of the current minimum.
Comment: sorry,but it needs to insert and query dynamically and answer the queries online,and there are a huge number of operations of inserting and queries.
Comment: I have edited the problem to make it clear.
Comment: Please clarify what `n` is.
Comment: Well I have explained it:"which time complexity is lower than O(nsqrt(n)),in which n is the times of operations".An operation means an inserting or query.I'm sorry for my confusing expression because I'm not a native speaker.
Comment: I have tried to rewrite the question substantially for language and clarity; feel free to roll back if you feel that I missed something. (Edit should show up once it's been reviewed.)
Comment: @Keith Suppose it's also a 64-bit integer
Comment: @aaronman Sorry, for some reason I thought it was always the same modulus
Comment: I'm wondering if a (hypothetical) efficient implementation could lead to a faster-than-currently-best-known algorithm for factorisation.
Comment: If cuda is option, you might want to look into that
Answer: Another idea based on balanced binary search tree, as in Keith's answer.
Suppose all inserted elements so far are stored in balanced BST, and we need to compute minmod(m). Consider our set S as a union of subsets of numbers, lying in intervals [0,m-1], [m, 2m-1], [2m, 3m-1] .. etc. The answer will obviously be among the minimal numbers we have in each of that intervals. So, we can consequently lookup the tree to find the minimal numbers of that intervals. It's easy to do, for example if we need to find the minimal number in [a,b], we'll move left if current value is greater than a, and right otherwise, keeping track of the minimal value in [a,b] we've met so far.
Now if we suppose that m is uniformly distributed in [1, 2^64], let's calculate the mathematical expectation of number of queries we'll need.
For all m in [2^63, 2^64-1] we'll need 2 queries. The probability of this is 1/2.
For all m in [2^62, 2^63-1] we'll need 4 queries. The probability of this is 1/4.
...
The mathematical expectation will be sum[ 1/(2^k) * 2^k ], for k in [1,64], which is 64 queries.
So, to sum up, the average minmod(m) query complexity will be O(64*logn). In general, if we m has unknown upper bound, this will be O(logmlogn). The BST update is, as known, O(logn), so the overall complexity in case of n queries will be O(nlogm*logn).
Comment: Well I haven't understood it but it seems to be a great solution.I'd like to confirm if you have made a typing mistake,which is "lying in intervals [0,m-1], [m, 2m-1], [2m, 2m-1]",located at the third line.
Comment: Sorry if I was unclear, please tell me which part you didn't understand well, and I'll clarify.
Comment: Thank you very much.I have understand it.But it seems that the algorithm only fit random m,and it may run really slow when the special input is given.
Comment: Yes, I especially mentioned uniform distribution. Of course it's possible to give such m which will maximize queries number. However I don't think there's better algo than just checking all the numbers if, let's say, someone who wants to slow you down is choosing bad m on each step.
Comment: Very nice answer. I'd also like to note that you can keep track of the size of the tree and fall back to linear search if the number of intervals you need to check is larger than `1/log(n)`. This will take care of the potential issue @algodynamic is concerned about.
Answer: Partial answer too big for a comment.
Suppose you implement S as a balanced binary search tree.
When you seek S.minmod(m), naively you walk the tree and the cost is O(n^2).
However, at a given time during the walk, you have the best (lowest) result so far. You can use this to avoid checking whole sub-trees when:
bestSoFar < leftChild mod m

and
rightChild - leftChild < m - leftChild mod m

This will only help much if a common spacing b/w the numbers in the set is smaller than common values of m.
Update the next morning...
Grigor has better and more fully articulated my idea and shown how it works well for "large" m. He also shows how a "random" m is typically "large", so works well.
Grigor's algorithm is so efficient for large m that one needs to think about the risk for much smaller m.
So it is clear that you need to think about the distribution of m and optimise for different cases if need be.
For example, it might be worth simply keeping track of the minimal modulus for very small m.
But suppose m ~ 2^32? Then the search algorithm (certainly as given but also otherwise) needs to check 2^32 intervals, which may amount to searching the whole set anyway.


How to use Task Queue API in Google App Engine?

Question: I enabled Task Queue API in my_project of Google Cloud Platform.
And I generated OAuth client-id for web-application and set redirect URL to https://my_project.appspot.com/oauth2callback.
And I add (decorator.callback_path, decorator.callback_handler()) to webapp2.WSGIApplication.
<code>from oauth2client.contrib.appengine import OAuth2DecoratorFromClientSecrets
from googleapiclient.discovery import build

decorator = OAuth2DecoratorFromClientSecrets(
'my.json', scope='https://www.googleapis.com/auth/tasks.readonly')

@decorator.oauth_aware
def get_google_client_credential_tasks(self):
    http = decorator.http()

    service_tasks = build('tasks', 'v1', http=http)

    temp_str = ''
    tasklists = service_tasks.tasklists().list().execute(http=http)
    for tasklist in tasklists[0]['items']:
        temp_str += tasklist['title']

    self.response.write(temp_str)
</code>
When I execute the above code, I got the following error message.
https://www.googleapis.com/tasks/v1/users/@me/lists?alt=json returned "Insufficient Permission">
How do I fix the error?
Answer: <code>@decorator.oauth_aware
def get_google_client_credential_tasks(self):
    if decorator_google_client.has_credentials():
        http = decorator.http()

        service_tasks = build('tasks', 'v1', http=http)

        temp_str = ''
        tasklists = service_tasks.tasklists().list().execute(http=http)
        for tasklist in tasklists[0]['items']:
            temp_str += tasklist['title']

        self.response.write(temp_str)
    else:
        url = decorator_google_client.authorize_url()
        self.redirect(url)
</code>


How do I group a h1 and list together?

Question: I'm trying to make a header menu that has horizontal list (a navigation area or menu) on the right and the h1 (name of the website) on the left (both using float tags to do so).
I tried grouping the two together with header, nav, and div tag but nothing works. the h1 and ul tag act as if separate, not grouped. when i give the grouping tag (Div, header, nav) background color nothing happens, but when i give it a color: .... all the text inside does change color, so at least that works.
Please help me group h1 and ul together.

.header {
  width: 100%;
  background-color: aquamarine;
  color: red;
}

h1 {
  float: left;
}

ul {
  float: right;
  list-style: none;
  display: block;
}

ul li {
  display: inline-block;
}

website name

Home

contact

Answer: Since you are using floats, you need to use something called clearfix hack. If not you can make them as display: inline-block

.header {
  width: 100%;
  background-color: aquamarine;
  color: red;
}

h1 {
  float: left;
}

ul {
  float: right;
  list-style: none;
  display: block;
}

ul li {
  display: inline-block;
}

.clearfix::after {
  display: block;
  content: "";
  clear: both;
}

website name

Home

contact

Answer: As stated by MDN - CSS Float

As mentioned above, when an element is floated, it is taken out of the normal flow of the document (though still remaining part of it). It is shifted to the left, or right, until it touches the edge of its containing box, or another floated element.
  Floats are removed from a parent context

Implies use of old-school CSS hacks like clearfixes in order to make a parent element "aware" of the containing floated elements.
Therefore to prevent the Float caveats, simply recur to a better yet simpler approach:
CSS Flex
display: flex;

.header {
  background-color: aquamarine;
  color: red;
  display: flex;
}

ul {
  list-style: none;
  display: flex;
  margin-left: auto;
}

li{
  padding: 1em;
}

website name

Home

Contact

Related: What is a clearfix?
Answer: Using float is quite tidious job, Use Flexbox for making navbar.

.nav-wrapper
{
  width:100%;
  display:flex;
  justify-content:space-between;
  align-items:center;
}
.list-wrapper
{
  width:50%;
  display:flex;
  justify-content: space-evenly;
  align-items:center;
}

Header

Home

Contact

About us

How do I group a h1 and list together?


'IronSource/IronSource.h' file not found error Unity XCode in iOSBridge.h file

Question: I should mention that I'm not experienced in XCode debugging, that being said, I have been using XCode to build my unity project to TestFlight for some time now and I haven't experienced this until now.

What I'm confused about is that all of this is straight exported from Unity so surely it should just work? If anyone has any experience with this error, I would much appreciate some insight, thank you for any contribution!
Comment: Hi, i assume you are having this after adding new Unity Levelplay sdk right? i'm having same issue once i use the new sdk.
Comment: @BrutalJazzy Hi, mine turned out to be me opening the wrong xcode file from the builds folder. Sorry I can't help more than that
Answer: In my case I simply hadn't realised that after adding ironsource sdk my Unity build has to create a xcworkspace that contains my proj and the pods proj.
Open the workspace, dont open the xcproj on its own file or else you get this error.
Good luck
Answer: I was able to fix this by:

manually downloading the corresponding iOS SDK
unzipping it
adding the IronSource.framework directory in Assets/IronSource/Plugins/iOS.


Change dns values with chrome plugin?

Question: I want to be able to achieve the same thing as you do with hosts but using a chrome plugin. I'm not sure if theres one available.
Essentially, I want to point a url to a specific IP address that's not listed on the web.  I don't want to use the hosts file because I want to make this as easy as possible for my clients.
Is there a plugin out there or a solution that is contained within a web browser?
Answer: This is DNS:
I want to point a url to a specific IP address

However, this:
that's not listed on the web.

causes questions. You could generate random names in DNS to obfuscate what you're doing, but anything you present as a client based solution where the client doesn't have to do this work will need to be translated, whether you reinvent the wheel from scratch or use a solution that's already available.

Change dns values with chrome plugin?


Convert ut8 to string

Question: I would like to convert a Utf String  to Characters.
I have "%CE%98%CF%89%CE%BC%CE%B1%CF%82+%CE%BA%CE%BF%CF%85%CF%81%CE%B7%CF%82" which i know it must be translated to Θωμας Κουρης.
I have tried anything.
Help Please!
Comment: Is it an UTF-8 string? Maybe but for your _problem_ I think you're searching for the wrong term, try with **URL** encoded...
Comment: Without showing us the code that you tried we cannot help. Please see https://stackoverflow.com/help/how-to-ask
Comment: `System.Web.HttpUtility.UrlDecode("your+string")` could do it, but I think there might be better ways
Answer: I think you are trying to do URL encode decode. In that case url decode for your value is : Θωμας κουρης
This tool below helps you to encode decode urls: Url Encode Decode
<code>Decode: System.Web.HttpUtility.UrlDecode("value");
Encode: System.Web.HttpUtility.UrlEncode("value");
</code>

Convert ut8 to string


Data validation in mvc not work

Question: I am now on a mvc project, I have trouble on the validation of user input. Below are the steps I used to perform the validation:

My entity looks like below:
public class Sysuser
{
public Guid User_id { get; set; }  //pk
public Guid? Permission_id { get; set; }
public Guid? Sex_id { get; set; }

[Required(ErrorMessage="Pls input the user name")]
[StringLength(50,ErrorMessage="UserName must less than 50 chars")]
public string User_name { get; set; }

[Required(ErrorMessage = "Pls input the pwd")]
public string Password { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
public string Userdesc { get; set; }
public bool Isfamer { get; set; }

public string Ctrlpwd { get; set; }
public Guid Parent_id { get; set; }

public Syspermission Permission { get; set; }
public Bassex Sex { get; set; }
}

in the SysUser.aspx page, I included the js file that required:

in the SysUser.aspx page, I put the html elements in the BeginForm like below:
用户姓名:
<%=Html.TextBox("User_name", (b == null) ? string.Empty : b.User_name, new { @class = "textbox" })%>
<%=Html.ValidationMessage("User_name")%>

in the web.config, I included below attributes :
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>

In order to test the functionality, I leave the User_name textbox blank, When I hit the submit button, but it throw me an exception like below:
  public global::System.String user_name
    {
        get
        {
            return _user_name;
        }
        set
        {
            Onuser_nameChanging(value);
            ReportPropertyChanging("user_name");
            _user_name = StructuralObject.SetValidValue(value, false);
            ReportPropertyChanged("user_name");
            Onuser_nameChanged();
        }
    }
    Exception Thrown at : _user_name = StructuralObject.SetValidValue(value, false); This property can't be set to null.

why I get this error? anyone can help me to work it out? thx.
Answer: You need to create a stronly-typed view (of SysUser.aspx), and then use instead of:
<%=Html.TextBox(...)

this function:
<%=Html.TextBoxFor(m => m.User_Name, ...)

The TextBoxFor function will automatically create unobtrusive validation properties in the <input> element. So can find some more information here: http://weblogs.asp.net/scottgu/archive/2010/01/10/asp-net-mvc-2-strongly-typed-html-helpers.aspx
And by the way, you should always validate the model server-side as well:
[HttpPost]
public ActionResult MySaveFunction(MyModel model)
{
  if (ModelState.IsValid)
  {
    // save entity in db and redirect to for example success page
  }
  return View(model); // show the form page again
}

Comment: Thx for your answer, But I have thousands of textbox in <%=Html.TextBox(...) style. I can't modify it one by one.
Comment: I'm afraid it's the only way to go. A strongly-typed view makes validation both client and server side a lot easier. And Visual Studio can generate a form including all elements for you (select the Edit template when creating a new view).
Comment: that's sad to me. Do you have other methods to do client side validation?
Comment: Yes there is, you need to implement all the client-side validation rules manually, see: http://jqueryvalidation.org/documentation/ But when you make changes in your model, don't forget to apply these changes for the validation rules as well.

Data validation in mvc not work


Basic factorisation of matrix Eigenvalue

Question: I need to diagonalise a matrix (or at least attempt to) but I am stuck on the factorisation of the eigenvalues.
The matrix goes as follow :
$
\textbf{A} = \matrix{ 5-\Lambda & -1 & 2  \cr
             -1 & 5-\Lambda & 2 \cr
              2 & 2 & 2-\Lambda \cr }
$
To calculate the determinant, we have to do
$5-\Lambda * |\matrix{ 5-\Lambda & 2  \cr
              2 & 2-\Lambda \cr } | + 1* |\matrix{-1 & 2  \cr
              2 & 2-\Lambda \cr } | + 2*|\matrix{-1 & 2  \cr
              5-\Lambda & 2 \cr }|
$
Which gives me
$5-\Lambda [ (  5-\Lambda)(2-\Lambda)-4)+[-(2-\lambda)-4]+2[-2-2( 5-\Lambda)]$
Now I did a few steps and got to this point :
$ (5-\Lambda)^2 (2- \lambda) - ( 5-\Lambda)*4 - (2-\lambda)-8-4( 5-\Lambda)$
Seeing that nothing good came out, I developped the second half of the equation to get
$ (5-\Lambda)^2 (2- \lambda) - 20 + 4\lambda-2+\lambda-8-20+4\lambda)$
$ (5-\Lambda)^2 (2- \lambda) - 50+9\lambda$
Now i'm stuck..if I try to develop the left side I get
$(25-10\lambda + \lambda^2)(2-\lambda)- 50+9\lambda$
$50-20\lambda+2\lambda^2-25\lambda+10\lambda^2-\lambda^3-50+9\lambda$
$-100-36\lambda+12\lambda^2-\lambda^3$
Now I can see that something is up with the multiples of 6, but I am not too familiar with factorizing $^3$ Note that this is an old exam's question and it seems to me that this takes way too much time to do. Also, my teacher warned us to not develop the parenthesises when looking for $\lambda$, so i'm confused about what else I could of done.
Comment: The characteristic polynomial for $A = \left(
\begin{array}{ccc}
 5 & -1 & 2 \\
 -1 & 5 & 2 \\
 2 & 2 & 2 \\
\end{array}
\right)$ is $-\lambda ^3+12 \lambda ^2-36 \lambda = 0$. Did I use the correct $A$? Notice that that cubic factors very easily to give eigenvalues $6, 6, 0$.
Comment: Yes that is the correct A, how did you do it?!
Comment: Your last expression is wrong. For the constant term, $50-50=0$, not $-100$.
Comment: @Maude: Same as you - you have a slight algebra error. Fix that and we match.
Comment: Oh god it was only that, I feel dumb.. thank you so much guys!
Comment: You also had some inaccuracies in notation, which didn't hurt your solution here because you fortunately remembered what you meant. But if you keep writing like this, it will inevitably creates problems sooner or later. In your first expression for the determinant, "$5-\Lambda[\cdots]$" must actually be "$(5-\Lambda)[\cdots]$" -- according to the rules for order of operations and using parentheses for grouping.
Comment: Thanks for the advice zip i'll try to be more careful with the notation!
Answer: As has been noted in the comments, you've made an algebraic error in calculating the characteristic polynomial. However, the eigenvalues of this matrix can be found without doing that.
First, observe that the sum of the columns is $(6,6,6)^T$, so $(1,1,1)^T$ is an eigenvector of $6$. Similarly, the sum of the first two columns minus twice the last is zero, so $(1,1,-2)^T$ is an eigenvector of $0$. The trace of the matrix is $12$, so the last eigenvalue is also $6$. It should be a simple matter to finish diagonalizing the matrix from here.


Are heal on hit also applied on dot effects?

Question: In Diablo 3, I wonder if my life on hit also heals me on DOT effects. More specifically, I have a Barbarian with a certain amount of heal per hit. If I were to use the Rend spell (AOE DOT around me), would every damage tick, heal me for the full amount which is displayed in character details screen?
Answer: DOTs return the life per hit amount ONLY on the initial hit, if we take rend here as an example, you gain your Life per Hit x the Proc coefficient(I'll come later to that) per enemy hit with the initial use of Rend.
If you use a rune which makes a DOT spread, like Bloodbath in the Rend example, you again gain the Life per Hit x Proc Coefficient per enemy spreaded to.
You don't gain the Life if you Hit enemies who are immune to damage (shielding).
Proc coefficients for all abilities are listed HERE
Sources: Own Experience, SOURCE 1 SOURCE 2


Can too much ridge ventilation be detrimental?

Question: At my house in central Texas, where temperatures can persist at 86 - 110 degrees Fahrenheit, one side is always hot, no matter how long the A/C runs. That attic space is considerably hotter than other locations.
Attic ventilation includes:

twenty-two 16x8 soffit vents
two 10' runs of plastic ridge vent
three stack vents

For better or worse, the ridge vents do not have a filter underneath and are covered with shingles.
According to the web, such as this website, 20' is the minimum requirement and the 22 soffit vents balance appropriately.
Will it help to install additional ridge and soffit vent? or will that disrupt current circulation?

UPDATE:
The ridge vents are actually 8 ft. long (not 10') and only 5 ft. of that are actually exposed. 1.5 ft. on either side of the ridge vents are covered over by shingles.
Comment: Excellent diagram.  It would help to have it labeled with North, prevailing summertime winds, indicate which side is always hot, and add any shade trees.  You might also want to add an elevation diagram with windows for the hot side, and add info on the attic insulation and specs of your AC system.
Comment: Given the height of the arched window, it looks like the 'hot room' might have vaulted ceilings, yes/no?  If so, insulation in the ceiling might be filling the entire space between the ceiling sheet rock and the roof plywood, blocking passive circulation, rendering the soffit and ridge vents non-functional.  In such situations, the insulation needs to be held away from the plywood by using baffles like the pink ones here:  http://nyrampage.files.wordpress.com/2007/05/12-07-ceiling-insulation-007.jpg
Comment: Unless there are soffit and ridge vents for each bay, cathedral ceilings also require  circulation between adjacent bays.
Comment: Do you know the specifications of your vents? In particular, what's the "net free area" of each vent you have?
Comment: Prevailing winds are from the south in summer. No trees large enough for shade yet. Updated diagram with new info. Turns out the length of the ridge vents is only 8 ft. and only 5 ft of that is actually exposed. Assuming the roofer installed incorrectly..
Comment: Another possibility is that the prevailing winds from the south are being diverted by south wing, such that they pass well above the north wing's ridge line. This would reduce the venturi effect, which acts to suck air out of the attic through the ridge vent.
Comment: The hot room is not vaulted. The entire attic has ventilation baffles. None of the sofits are blocked with insulation.
Comment: It's good to have those eliminated. I assume that the roof sheathing was cut back for the ridge vent. Another factor at play is that compared to the main house, the hot wing has a much larger surface area (walls+roof) per square foot of floor.  The wing needs to be cooled based on it's thermal envelope  rather than the room's square footage.
Comment: How much window area is there on the sides of the hot room? Are you in a dry climate or humid climate? Here in FL panhandle (similar latitude to yours) it's like a tropical rainforest so many houses also have large gable louvers, some with fans, to move the 50-90% humidity (year-round!) air.
Answer: With the solar-powered vent and two static vents being so close together, I wouldn't be surprised if the the solar-powered vent (because it's powered) is pulling most of it's air from the two static vents. You might be able to check this by using toilet tissue, feather, incense smoke or something to determine air-flow direction through the static vents while the solar-powered vent is running.
If the net effect is that air is being pulled in, then none of those vents are doing as much as they should to cool the attic. Some of the air through the soffit vents is being exhausted through the solar-power vent, to be sure, but the static vents aren't helping.
If I were going to make changes, I would consider the following, in order of preference...

Remove and seal up the two static vents. This alone would cause the solar-powered vent intake to come completely from the soffits and thus pull hot air out of the entire attic area underneath.
Remove the solar-powered vent and install a ridge vent the entire length of the ridge next to it. As this makes venting totally passive, it might not be enough for your climate. Depending on size and efficiency, the solar-powered vent without the static vents may move more air. If still not enough, I would think more CFMs of air could be vented using a line-powered unit, but haven't researched it.
Comment: All of the static vents are venting hot air per a smoke test. It does not appear the solar vent is pulling air from the others. All the vents are a good 7 feet away from each other.
Comment: Then you're golden on that aspect.

Mike may be onto something if the hot room has vaulted ceilings without baffles or its attic space is filled. In either case, the vents wouldn't do any good at all as no air can circulate. What's the ceiling construction in the hot room?
Answer: The point of attic ventilation is to keep the air from getting trapped in what's called the "cold zone" (an ironic term when you're in Texas but there you go...).  If an attic cannot breathe well, moisture will get trapped, and lead to term structural deterioration.
Temperature isn't a concern - the attic isn't an insulated area - so as long as your insulation itself is adequate, it doesn't matter how hot/cold the attic gets.
So basically - it's not really possible to over-ventilate your attic.  More airflow = better.  There's a minimum amount because less than that much ventilation is a bad thing, but there's not a max because more ventilation can't do any harm.
Comment: I agree about moisture, and about more=better in summertime.  But for an attic<=>room situation, heat exchange is proportional to the temperature difference regardless of the amount of insulation. For a 75 degree home, dropping the attic from 105 to 90 will cut the A/C load in half for that exchange.  Whether or not that is significant depends on the design of the rest of the thermal envelope.
Comment: You control that by insulating the warm zone from the cold zone, not by reducing ventilation to the cold zone.
Comment: Insulation is an important factor, but so is the temperature difference.  In the winter, unlike the summer, the most energy efficient amount of ventilation is the minimum required to control condensation.
Comment: You lost me.  The point of insulation is to remove the temperature difference factor.  In the winter a well ventilated attic will have the same temperature and moisture level as the outside unless you have improper vapor seal between house and attic.
Comment: Even in theory, the temperature difference factor cannot be removed.  It will always be there.  Regardless of the amount of installed insulation, reducing the temperature difference will always reduce the heat exchange in direct proportion.
Answer: Agree with @DocSalvage and his thinking - you definitely should remove/seal the static vents.
You could also have a problem in that the solar powered fan is so powerful that it draws in air from your ridge vents, which like with the static vents during a summer day would be very hot air. You should get up in the attic and see if you can tell how/where airflow is occurring.
Here in Texas, as with most places, you want to maximize your ventilation. You could install as much ridge vent as you have space for and adjust the number of soffits to match (and definitely don't consider the entire size of the soffit vents as the clear airspace - account for mesh or openings on the soffit vents). But it would seem from your diagram that your roof is not ideal for passive/convective venting.
Assuming your solar fan is powerful enough, it's going to be doing a lot more exhausting, and at a better location in your attic, than the ridge vents. Most likely your biggest issue is not enough soffit venting.
Answer: Too much ventilation is only when the extra vents introduce the chance for extra moisture.  Living in Texas you want your attic to be as close to the outside temperature as you can get.  If your attic temp is at 100 F then your temperature variance will be low and may be completely negated with decent insulation.
I would take the temperature of my attic during a hot day.  I lived in Fort Worth when I was younger and did a lot of roofs while working through college.  The attics can get to 130-140 F.  In warmer climates we have had a lot of luck with large gable vents.  They do a great job letting the warm air escape (not so great at overall circulation unless they have a fan).
Also a lot of people complain about a hot attic and their ridge venting is blocked by insulation or the vents are dirty.  With blown-in insulation you really need to clean the vents after and then about a year later.
I would also look at the color and materials for your roof if your attic is hot.  Changing from black shingles to off-white can reduce temperatures by as much as 15-20 degrees in an attic.  There are more expensive options that can have a greater impact.
As far as ventilation, the only time I have read about over circulating is in colder climates where there are measures to use sunlight to warm the attic during winter months.  Your house in Texas would by all means function better (temp-wise) with no roof and 3 feet of insulation if it weren't for rain, wind, animals...
Comment: A roof shades the insulated surface and substantially reduces convective heat exchange.
Comment: A large tree would do a much better job.
Comment: better? in terms of?
Answer: Yes, it is possible to install too much ridge vent.
Passive attic venting systems are now designed so that they intake air from the soffits and expel air near the ridge. This is normally done without power by using the fact that hot air rises.
If there is too much venting near the ridge, a lower pressure will develop in the attic, and air can be sucked into the attic from the conditioned living space.
Vents are normally rated by the amount of "net free area" they have. One aims for equal net free areas at the soffits and the ridge. If there is a large difference, it's better to have the "extra" area at the soffits.
Your powered fan will be specified with some minimum intake area.
As long as things are balance between intake and exhaust, it's a good system. The more ventilation, the better.
Comment: I agree with the low pressure increasing exfiltration in principle, but in practice the pressure difference between passively balanced and unbalanced is negligible in terms of exfiltration through an energy sealed envelope. The temperature differential discussed elsewhere is a far bigger factor.
Comment: You can't both say that convective airflow will happen and that there can be too much ridge vent. Convective airflow will draw cooler air in from the eave vents and not draw it from the conditioned living space (or at least not much depending on how much airflow there is through the drywall). Similarly a pressure differential will just draw air in through the eaves faster.


ScriptManager.RegisterClientScriptBlock not working anymore when adding MasterPage

Question: I call a javascript function from C# like this :
        ScriptManager.RegisterClientScriptBlock(this, GetType(), "script", "$(function () {initializeMap(); });", true);

It worked perfectly until I add a master Page :
MasterPageFile="~/Header.master

<%@ Register Assembly="myassembly" Namespace="mynamesapce" TagPrefix="mytag" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>

And put my code in an asp Content :
<asp:Content ID="Content1" ContentPlaceHolderID="Body" runat="Server">
After I added all of this the javascript function call wasn't working anymore, and I got this error :

Uncaught ReferenceError: $ is not defined

and when I click on the error it gets me too
$(function () {initializeMap(); });

Do you have an idea of the problem ?
Comment: This "$ not defined" error, mostly comes up when jQuery lib is not loaded.
Comment: That's what I was thinking first but all the other scripts I include (bootstrap for example) are working well..
Comment: or referenced multiple times, check for duplicate reference in master as well in child page
Comment: Have a look at your rendered HTML. See where your `$(function(){})` is positioned and where the jQuery lib is being loaded.
Comment: I added an other MasterPage and it seems to work now... On the first masterPage there wasn't any scripts includes so don't really know what happend
Comment: I had the same problem ,I used the ScriptManager in the MasterPage and removed it from the rest of the pages works fine now :)
Answer: I bet that your jQuery declaration, if it is still being declared, is in a different position in the HTML.
I tend to use RegisterStartupScript, though not bulletproof, but is less likely to cause these issues because the script will be rendered at the bottom of the page.
ScriptManager.RegisterStartupScript(this, GetType(), "script", "$(function () {initializeMap(); });", true);

Answer:  <asp:ScriptManager ID="ScriptManager1" runat="server" AsyncPostBackTimeout="400"></asp:ScriptManager>
 <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">

 </asp:ContentPlaceHolder>

add the ScriptManager only in MasterPage and remove it From every other Pages and then give it a try..


Every surjective homomorphism is integral.

Question: I want to show that every surjective ring homomorphism is integral, i.e., $f: R \longrightarrow S$ is integral, where $f$ is onto
We define $s$ is integral over $R$ if there exists a poly $p(x) \in R[x]$ such that $p(s) = 0$. Besides, $f$ is integral if every $s \in S$ is integral over $R$.
It seems to me that I need to find a proper polynomial, which should be trivial, but I just cannot get one.
Any hint would be great! Thanks in advance.
Answer: We need a monic polynomial.
But now that's easy: the $R$-module structure on $S$ is given by $f$ by
$$r\cdot s:=f(r)s$$
Now, for any $s\in S$, there is an $r\in R$ such that $s=f(r)$, so just take
$$p(x) = x-r$$
(meant as $1\cdot x-r\cdot 1$), that gives $p(s)=s-r\cdot 1=s-f(r)=0$.
Comment: I guess I missed the part that $S$ is an $R$-module. It is also an $R$-algebra, right? @Berci
Comment: Yes. But the notion 'integral' can be defined on modules.
Comment: You get the same if you interpret the polynomials in the $R$-algebra structure.
Comment: Thank you very much! @Berci


Restcomm variable for the date

Question: I'm creating a new App in RVD and creating a request to an external service. Everything works as expected, I'm using different variables as core_From, core_To and so on. The problem is, I would like also send the date when the call is done but I don't find any variable for that and I wasn't able to find any documentation defining those variables.
I guess I could invoke an external service to know the date, but it seems to costly to do something so trivial... so I think I'm missing something obvious here. Any help on that would be welcomed.
Comment: Anton, unfortunately RVD does not support this feature yet but you could work your way around it using ES as you suggested. There is a pending issue for adding date support though, so stay tuned.
Comment: here is the issue:
https://github.com/RestComm/Restcomm-Connect/issues/1034
Comment: Thanks @otsakir, if I have the opportunity, I will add the feature
Answer: After this PR, the variable core_callTimestamp is available to provide this functionality.

Restcomm variable for the date


LLVM version on iOS and Android

Question: How to find out which LLVM version is used in Android NDK and Apple Xcode?
Checking clang --version from Android NDK r15c I got:
Android clang version 5.0.300080  (based on LLVM 5.0.300080)

but NDK r15c was released in July 2017, before actual release of LLVM 5.0 (what happened in September 2017). Does it really use LLVM 5.0?
Checking clang --version from Xcode only shows Apple's own LLVM version:
Apple LLVM version 9.0.0 (clang-900.0.38)

is there any way to find out to which "unpatched" LLVM version it relates?
Comment: This might help: https://stackoverflow.com/a/39076986/598057.
Comment: Thanks, but the info there is a bit outdated (Apple LLVM 7.0.x => LLVM 3.x)
Comment: True, the latest is [800.0.42.1](https://opensource.apple.com/source/clang/clang-800.0.42.1/src/) which is 3.9.0 if judging on CMakeLists.
Comment: You can ask on [llvm-dev](http://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-dev) forum to get the best answer.
Comment: "the latest is 800.0.42.1 which is 3.9.0", and the actual version reported from clang binary is 900.0.38, hope we have 4.0 update at least :) and thank you I will try to use the forum as well
Comment: Yes, I meant latest available on opensource.apple. Please post back the answer here if you get it on llvm-dev - your question is very good :)
Comment: Another duplicate: https://stackoverflow.com/questions/46955807/whats-is-proper-version-of-llvm-clang-xcode?rq=1.
Comment: Yes, sure :) I will post the answer if find the info!
Comment: And this one: https://stackoverflow.com/questions/26421690/what-is-my-version-of-llvm-clang-osx?rq=1. Find your answer and then we can mark all other answers as duplicates of yours (they are mostly outdated, do not have a good answer).
Comment: Not exactly duplicate, because I'm asking about Android as well :)
Answer: 1) Android. Accordingly to the LLVM source code for Android NDK: http://llvm.org/svn/llvm-project/llvm/tags/google/stable/, it seems that NDK r15c really uses LLVM 5.0 (as contained in CMakeLists.txt).
And right after that release they switched to unreleased yet LLVM 6.0. So it seems that Google tries to use in NDK the latest LLVM version available.
2) iOS. For the Xcode, guys from llvm-dev maillist suggested to look at the branches of swift-llvm repository: https://github.com/apple/swift-llvm
- accordingly to that, Swift 4.0 (as well as the current Xcode 9.1 version) uses LLVM 4.0 and the upcoming release of Swift 4.1 (in 2018) will use at least LLVM 5.0.
Answer: but it was created by llvm5.0.1,can not be read by LLVM of NDK r15c。

error: Invalid value (Producer: 'LLVM5.0.1' Reader: 'LLVM 5.0.300080')

LLVM version on iOS and Android


Can I use existing 40 AMP breakers when the item calls for 30 AMP

Question: My tankless water heater stopped working and I purchased a new but slightly smaller one.  The description on the website said that it used the same wiring as my last one (3 40 AMP breakers and 8/2 AWG wires).
The instruction coming with the new unit now say it requires 3 30 AMP breakers and 10/2 wires.
Can I keep my existing 40 breakers if I am also using the 8/2 wiring?  I have read other comments that say that the person couldn't use the 30amp since the wiring was probably 10/2, but I know mine is 8/2 so I am hoping I can still use the newer and smaller heater.
Thanks
Comment: What make and model is the new water heater?
Answer: It may be possible if the new water heater doesn't state the maximum breaker size.
If the manufacturer only states the minimum, since you are not at 150% I would hook a triple 40a to the new triple 30 water heater.
It is not Code compliant to go the other way from 3 30 with #10 to a 40 this is correct.
Comment: I was going to say something similar, but wasn't sure, so I shut up! Hoped and glad you chimed in!  I thought that was the correct answer, but wasn't sure enough to respond.
Comment: Well as long as the MFG doesn't state a maximum value that is lower, I haven't checked 2020 code but 150% is stated some place.
Answer: I would change the breakers. The instructions are part of the NRTL Listing. And the NEC says:

NEC 110.3(B) Installation and Use Listed and Labelled equipment shall be installed and used in accordance with any instructions
included in the listing or labelling.

Breakers are cheap.


Read data from excel to table in MATLAB App Designer

Question: Good evening
I am trying to develop a MATLAB GUI where the user can either input the data manually in a table or attach an excel folder, which will copy the data in the excel sheet in the table.
My lines of code are
function AttachExcelFolderButtonPushed(app, event)
            [filename pathname]=uigetfile({'*.xlsx'},'File Selector');
            text = readtable(filename, "Sheet",1);
            app.UITable.Data = text;
        end

I get the following error:
Error using readtable (line 223)
Unable to open file 'Book1.xlsx' as a workbook. Check that the file exists, read access is available, and the file is a valid spreadsheet file.
Please help
Note: I am a newbie
Thank you
Comment: There is a variable `fullpathname` in your code which is never used.
Comment: I don't think that will produce an error, but thank you for replying, I will remove the line
Answer: My guess is that you don't have the file you want on the path. Try this line:
text = readtable([pathnaem filename], "Sheet",1);

This will use the entire path of the file to find it. Otherwise MATLAB will only look for files currently on the path.
Comment: Thank you very much for replying
It worked! but it doesn't show the first row and the application window disappears and when I open it again from the desktop bar it shows the values starting the second row
Comment: That has to do with that other attributes in `readtable`. change the line to `text = readtable([pathnaem filename], "Sheet",1, ReadVariableNames',false)` to get the first row. I have no idea what you mean by the other problem.
Comment: It works. thank you so much - I wish I could reply with a small video - When I press "attach excel file," then browse to my documents folder, choose "sheet 1", and double left-click on the file, the screen closes and I have to reopen it from the bottom bar in windows 10, where the table shows and the app runs.
Comment: Sounds strange. Could be a bug. Only thing I can think of to try is:
`waitfor([filename pathname]=uigetfile({'*.xlsx'},'File Selector'));`
Comment: The program tells me:
Error using app1
Error: File: app1.mlapp Line: 21 Column: 40
Incorrect use of '=' operator. To assign a value to a variable, use '='. To compare values for equality, use '=='.
Comment: I fixed it by putting == instead of = but nothing happens when I press on the "attach excel file" button
Comment: no that wont work, forget the `waitfor`. There is something strange going on. Im not even sure i know what you mean the problem is.
Comment: NVM Thank you so much


My power button doesn't work under LXDE. How can I fix this?

Question: Ever since I switched to LXDE my power button won't work anymore. I would love to be able to display a fancy logout menu like the one in Unity and similar DEs. How can I achieve this?
Answer: The ACPID way

Overview
There are numerous ways of fixing this issue. If you look through the web you will find suggestions on installing power managers used in other desktop environments (DEs) like xfce4-power-manager or gnome-settings-daemon. However, as an LXDE user you are probably striving for a lightweight solution. One lightweight way to display a logout menu on power button press is to utilize an ACPID script.
What is ACPID?
From the ArchWiki:

acpid is a flexible and extensible daemon for delivering ACPI events.
  It listens on /proc/acpi/event and when an event occurs, executes
  programs to handle the event. These events are triggered by certain
  actions, such as:

Pressing special keys, including the Power/Sleep/Suspend button
Closing a notebook lid (Un)Plugging an AC power adapter from a    notebook
(Un)Plugging phone jack etc.

Installation
sudo apt-get install acpi acpid

Configuration
Open /etc/acpi/powerbtn.sh in a text editor of your choice, e.g. leafpad:
gksudo leafpad /etc/acpi/powerbtn.sh

At the end of the file you will find the following passage:
# If all else failed, just initiate a plain shutdown.
/sbin/shutdown -h now "Power button pressed"

Just before this passage add the following snippet:
# If LXDE is running execute lxsession-logout
if [ -n $(pidof lxsession) ]; then
    for x in /tmp/.X11-unix/*; do
       displaynum=`echo $x | sed s#/tmp/.X11-unix/X##`
       getXuser;
       if [ x"$XAUTHORITY" != x"" ]; then
           export DISPLAY=":$displaynum"
           export _LXSESSION_PID=`pidof lxsession`
           lxsession-logout
           exit
       fi
    done
fi

Most of the snippet consists of functions and commands that make sure that a graphical application like the logout menu can be run by ACPID (setting environment variables like XUSER and DISPLAY).
Note: If you have GNOME components running in your LXDE session (e.g. nautilus, various daemons) the session detection might go wrong. In these cases I would advise you to insert the code in the following way:
  if pidof x $PMS > /dev/null; then
     if [ -n $(pidof lxsession) ]; then
        for x in /tmp/.X11-unix/*; do
           displaynum=`echo $x | sed s#/tmp/.X11-unix/X##`
           getXuser;
           if [ x"$XAUTHORITY" != x"" ]; then
           export DISPLAY=":$displaynum"
           export _LXSESSION_PID=`pidof lxsession`
           killall lxsession-logout
           lxsession-logout
           fi
        done
        echo "if correct"
        exit
             else
                 exit
     fi
<...>

Troubleshooting
For some unknown reason these functions don't always work. In that case you will have to replace the snippet above with the following one:
if [ -n $(pidof lxsession) ]; then
   export DISPLAY=:0
   export _LXSESSION_PID=$(pidof lxsession)
   export XUSER=user
   export XAUTHORITY=/home/user/.Xauthority
   lxsession-logout
   exit
fi

The environment variables are hard-coded in this one. Make sure to substitute user for your own user name. It should work for most single-user system configurations.
Here's another workaround, just in case none of the variants above work. Replace the getXuser function with the following passage:
getXuser() {
        user=`pinky -fw | awk '{ if ($2 == ":'$displaynum'" || $(NF) == ":'$displaynum'" ) { print $1; exit; } }'`
        if [ x"$user" = x"" ]; then
                startx=`pgrep -n startx`
                if [ x"$startx" != x"" ]; then
                        user=`ps -o user --no-headers $startx`
                fi
        fi
        if [ x"$user" = x"" ]; then                           # lines added
               user=$(pinky -fw | awk '{ print $1; exit; }')  # lines added
        fi                                                    # lines added
        if [ x"$user" != x"" ]; then
                userhome=`getent passwd $user | cut -d: -f6`
                export XAUTHORITY=$userhome/.Xauthority
        else
                export XAUTHORITY=""
        fi
        export XUSER=$user
}

What does it do?
The powerbtn.sh script is triggered by ACPID each time the power button is pressed. As you can see it already includes a number of checks for common DEs like Unity, GNOME and KDE. These checks are there to make sure that the shutdown event is handled by the respective power manager. Alas, LXDE doesn't have one of those built in.
That's why we added a snippet of our own that does the checking for ACPID. If it detects an LXDE session it makes sure that your PC isn't just shut down right away and instead launches the logout menu you should be familiar with.
With these changes you should now be able to launch your logout menu with your hardware power button - without needing to install a bulky power manager. And even better, this does not interfere with other DEs in any way.
Sources
http://www.ollie-reardon.co.uk/lxde-tip-power-button-not-working/
https://wiki.archlinux.org/index.php/Acpid
http://forum.lxde.org/viewtopic.php?f=8&t=205

Further reading
Lubuntu - power button doesn't turn off computer,
Laptop power button not working
https://bugs.launchpad.net/xfce4-power-manager/+bug/1008650
https://unix.stackexchange.com/questions/87259/why-wont-this-shutdown-script-work-when-executed-by-acpid
Answer: It seems that LXDE does not include the lxsession-logout package.
Install the package by typing this in terminal:
sudo apt install lxsession-logout

I know this is an old thread, but I just experienced this problem and could not find a direct answer anywhere.
Comment: Zanna - Yes, it did make the GUI power button work on my laptop.
Comment: I have `lxsession-logout` installed on my system but same facing same problem: power button does not do anything!
Answer: Using systemd. Simply edit /etc/systemd/logind.conf, uncomment the relevant line for HandlePowerKey and set to poweroff, suspend, or hibernate as desired. There are other preferences in there for the lid switch, etc.
More info, options

Without systemd. This might get useless style points for using w, pidof, read and ps instead of piping through sed.
In /etc/acpi/powerbtn.sh, before the final check and shutdown section.
# If LXDE is running execute lxsession-logout
IFS=" "
read -r user pid foo <<<$(ps u --no-headers -C lxsession)
if [ x"$user" != x"" ]; then
   read -r foo display foo <<<$(w -sh $user)
   if [ x"$XAUTHORITY" != x"" ]; then
       export DISPLAY="$display"
       export _LXSESSION_PID=$pid
       lxsession-logout
       exit
    fi
fi

Troubleshooting.
To troubleshoot, save this snippet as a script and (provided that you understand the commands and don't just blindly execute code off the internet) invoke it as root.


xfce keyboard setup

Question: I am accessing Ubuntu Desktop version 16.04.1 LTS from Windows 10 with RDP but can't get a UK keyboard layout working which means that office applications are very difficult to use.
I have downloaded and installed http://archive.xfce.org/src/panel-plugins/xfce4-xkb-plugin/0.5/xfce4-xkb-plugin-0.5.4.3.tar.bz2 but when I try to change the keyboard layout I can only see the US KB option as you can see from the screenshot. Is there something else I should be doing other than installing to make this work please?
Answer: I got an answer to this problem from a friend so adding it here to help others that may find the same problem. The problem is that xrdp always uses km-0409.ini (US keyboard) & is apparently not configurable to use anything else. The best solution is to download a copy of km-0809.ini with UK keyboard definitions in it. I found one that works at c-nergy.be/downloads/km-0809.ini. I first saved a copy of the existing km-0409.ini in /etc/xrdp then replaced the contents of the file with the downloaded version. Restart of the xrdp session it all works as required with a UK keyboard mapping. Presumably the same could be applied to any other keyboard layout variant if you can get hold of a suitable keyboard definition file.

xfce keyboard setup


If repositories are for aggregate roots, where should data access logic for other entities go?

Question: I have a few objects that represent a web application.  Currently I have a cluster object to represent a specific deployment of the app.  Within a cluster object I have the following objects:  Server, Customer, User.  None of these objects can exist without being part of a cluster, so I created a ClusterRepository to retrieve the clusters from the database.  Now, from the cluster I need to get a list of Customers, presumably by using a method in the Cluster object like GetCustomers().  Now, my initial thought was to then offload the work of this operation to a CustomerRepository, but since repositories are only for aggregate roots, where should the data access logic go?  Does this belong in a service class?
Answer: Essentially,  an Aggregate root is any object that you might need to fetch as the root of an object graph.  Just because a specific entity is an aggregate root, and has a repository, does not mean that another entity which is one of it's properties can't also be an aggregate root - with it's own repository.
A good example is a customer billing system.  Customer would certainly be an aggregate root,  and would contain a collection of invoices... But for another application function, the invoice itself might be an aggregate root with constituent LineItem objects in it's object graph.
So in your example, there is nothing wrong with creating another repository for customers, if you need to fetch them independantly of clusters in some situations.
NOTE:  See thread in comments as well.  Although root entities can, (and often will) have references to other root entities, it is frowned upon (and that may be too mild a turn of phrase) to allow the repository for any root entity to contain functionality that manages (creates, updates, or deletes) any root entity within its object graph that it has a reference to.  Any such referenced root entities should have their own individual repositories, and the functionality to manage them (Create, Update and/or delete operations) should be in their repository, so that it is only in one place.
Comment: You are confusing a reference with aggregate "membership".  Study the car example.  Car is an aggregate root and has entities within it's aggregate.  Engine is also an aggregate root.  Car holds a reference to Engine but Engine is never part of the Car aggregate. By your same argument, if roots overlapped one root could modify another root.  If the mod was a delete, the second root could leave the entities it was responsible for orphaned. An even worse inconsistency.  You will find NO examples in Evans where an object which is an aggregate root is also a member of another aggregate.
Comment: An aggregate root is an object which is responsible for the life cycle of all of it's contained entities.  Aggregate roots exist to maintain valid relationships invariants, fetch access is a consequence of that not the reason for creating an aggregate root. This answer almost seems to suggest an aggregate root arises depending on perspective of the caller.  Invoice is either an aggregate root or it is not.  Period.  To the original question if Customer is treated as an aggregate root, Cluster can still have a reference but Customer is now no longer part of the Cluster aggregate root.
Comment: If I understand your objection correctly, it is equivilent to requiring that there be no overlap within the set of defined aggregates, which which would be unusual and unnecessary. To your other point about basing aggregates on the access requirements of the application domain, I quote from Evans, "...Provide repositories only for AGGREGATE roots that actually need direct access.."  It is of course often the case that entities which are part of one aggregate may need to be directly accessed, with their constituents, in another part of the application.
Comment: Evans p124 "An aggregate is a cluster of associated objects that we treat as a unit for the purpose of data changes."  The root is the object responsible for controlling change/access to all others in the aggregate.  What I object to is an entity which is at times a non root part of one aggregate and at other times the root of it's own aggregate.  The entity could be deleted as a member of first aggregate, after which it could not be in control of it's own aggregate.  A root cannot be part of another aggregate because it is responsible for maintaining it's own aggregate in a valid state.
Comment: I suspect you do not understand the concept.  From Pg 129 of DDD, Evans clearly says "Objects within the AGGREGATE can hold references to other AGGREGATE roots".  The point of separation is at the root.  Aggregate roots CAN be part of other Aggregates, indeed, there is no reasonable way to design a system without allowing this.  What the paradigm frowns on is when the overlap includes non-root objects in more than one aggregate boundary.  That is considered bad because multiple aggregates might inconsistently modify those objects. But the paradigm HAS to allow overlap of root objects.
Comment: He said the customer can't exist without being part of a cluster..


Solving for Line Intersecting Two Cones

Question: I am looking for a closed form and recursive form (an approximate form would be okay) solution to evaluate a fixed vector when I know the angle between it and two other known vectors. Any suggestions on how to go about solving this would be helpful.
Given vectors $\vec{M}$, $\vec{V}_{1}$, and $\vec{V}_{2}$ (all in  $\mathbb{R ^{3} } $), I know the angle between $M$ and $\vec{V}_{1}$ is $\theta_{1}$ and the angle between $\vec{M}$ and $\vec{V}_{2}$ is $\theta_{2}$.
I can take the dot product between the vectors to get
$$\vec{M}\cdot\vec{V}_{1}=|\vec{M}||\vec{V}_{1}|\cos(\theta_{1})$$
$$\vec{M}\cdot\vec{V}_{2}=|\vec{M}||\vec{V}_{2}|\cos(\theta_{2})$$
I'll simplify the right side and assume the magnitude of all of these vectors is 1.
Using subscripts to break each vector down into its x, y, and z components, I have these simultaneous equations:
$$M_{x}V_{1x}+M_{y}V_{1y}+M_{z}V_{1z}=\cos(\theta_{1})$$
$$M_{x}V_{2x}+M_{y}V_{2y}+M_{z}V_{2z}=\cos(\theta_{2})$$
The only unknown here is vector $\vec{M}$, which is assumed to have unit length.
For what it's worth, each of these describes a cone with a half angle of $\theta$. I'm looking for the vector(s) $\vec{M}$ where the cones intersect.
Is this how I should start? Where do I go from here?
I want to be able to solve this recursively in a Kalman filter (or extended Kalman filter). I'll have a continuous set of vectors $\vec{V}$, and I'd like to update my estimate of $\vec{M}$ recursively. I'm interested in any suggestions on how to approach that.
Comment: I am going to take the word "tangent" out. After looking at it, I see there is an ambiguity where there can be two lines of intersection and two corresponding solutions pointing in the opposite direction (anti-parallel). So I see there can be 1, 2 or 4 solutions. I'll have to determine some way to resolve that ambiguity.
Answer: I think that you're not going to find a closed form unless you're willing to narrow the problem. As you observe, two cones can intersect in 0, 1, or 2 lines, and each line contributes two (opposing) unit vectors to your answer set. But there's another possibility, which is that the two cones can intersect in a plane.
Suppose $V_1$ and $V_2$ point towards the north and south poles, and $\theta_1 = \theta_2 = \frac{\pi}{2}$. Then every unit vector in the equatorial plane is a solution to your problem. You have infinitely many solutions. And "closed form equations" don't tend to produce that kind of thing.
If you're willing to say "the $V$ vectors are not collinear," then perhaps we can take their average, start working with a plane orthogonal to that average, etc., and eventually get to a quadratic. But as it stands: it seems hopeless.

Solving for Line Intersecting Two Cones


How can I wire switch to convert a regular outlet to half switch?

Question: I have a junction box with 2 switches:
- Right switch controls the ceiling fan.
- Left switch does nothing, but the black(hot) wire is labeled "Fan". The white neutral wire is not attached.

I'm trying to wire one of the outlets to be a half-switch controlled by the extra switch.
- all the outlets have 2 black wires attached to them and 2 white wires.

Is this possible without running additional wiring?
I had the house fully renovated last year but the GC did not ask me how I wanted to rooms wired despite me clearly stating this was to be the case.
Answer: No. Definitely NO way to make that receptacle switched in any way without running new wire.
Sorry.
Looks like those two switches were intended to control a fan and light separately. Notice how the black and red are in the same cable? That cable goes up to the fan/light.


Installing an electrical outlet in my attic?

Question: So before it snows and gets colder outside I would like to install an electrical outlet in my attic. I'm gonna hook up a light to it. In my attic there is some wire running along the beams, could I splice it and add a junction box and then hook up a the electrical outlet to it? Thanks in advance.
Comment: "Some wiring", eh?
Comment: Step two: investigate where it goes and what devices it supplies. Chances are you can do as you describe, but we can't answer with what little you've provided. Edit your question to add details.
Comment: I think it's 12/2 electrical wire.
Answer: If the cable is feeding a typical residential circuit, and if it's not already at legal capacity (which is fairly flexible in many cases), and if there's no other weirdness at play, yes.
If you're not lucky enough to have two feet of slack you may need to use two junction boxes. Cut the wire between two boxes and pull it into each of them. Run a new length of wire between, and splice in your new outlet leg from one box. It's more or less blacks to blacks and whites to whites. Junction boxes must remain accessible. Secure all cables appropriately (and within a foot of each box).
Comment: Ok thanks. I figured I would have to add 2 because I don't think there is any slack.
Comment: Be careful which cable, it might be a switched, instead of always hot.
Comment: Does "the circuit supplies bathroom, laundry room or kitchen receptacles" count as a weirdness?
Comment: @MikeD then you might as well add 2 in respectable locations for lights.  Consider non-incandescent lights, nothing is more annoying than nailing an incandescent bulb with stuff or your head, and breaking the bulb and plunging into darkness.  Or the kid stacks right up to the bulb and the bulb burns a hole in your stuff.   My preference is fluorescent fixtures at the apes, run off flexible cords, which are legal when supplying luminaires.
Comment: I checked I believe it's connected to a ceiling light and some outlets.


Interface to merge suggested updates with existing information

Question: I'm building an application that will let a record administrator merge updates submitted by the general public with an internal record.  Records include contact information, qualifications, etc.  Information is captured from the general public using text fields, drop lists, check boxes, and radio buttons.
The updates are placed in a pending area.  All changes to the internal record must then be approved by the administrator.  Often times, the administrator will approve all the suggested changes, however there are cases when the administrator must consider the change, and possibly override the suggestion.

I started building two copies of the form side-by-side.  All user submitted fields were open for editing.  Changes could be applied by section (i.e. Address, Qualifications, etc.), or by field.  The result was a very intimidating form with far too much going on.
What is the best way to compare the information from two forms, and merge the two forms together?
Comment: I updated my question to include a screenshot of how the form was shaping up.  Imagine those sample rows with all their buttons in a big long list.  It's messy.
Comment: If there's any amount of non-trivial editing done on user-submitted data, please consider adding unlimited undo functionality (for the admin to get from inadvertent typos to the original users' version).
Answer: It would be great to see your form to provide more relevant results. Anyway, there are several ways to provide merge capability to the form, I will try to provide several conceptual idea in order to provide some starting point for you.
So ideas are the following:

Do not change the form, but balloons in order to show changed value. Optionally you can let user apply all or cancel all changes.
Modify form components (edit fields, etc) to let user switch values. This solution is not flexible enough and highly component dependent.
Use common approach, put old values on the left, new on the right and let user do the rest. Optionally you can hide empty or not-changed fields
Comment: Thanks for the great suggestions.  I like the first and third option mockups best for what I'm trying to accomplish.  A whole lot cleaner and more intuitive compared to what I was putting together.
Answer: This is how PyCharm lets you merge two Git repositories. The left side is the local version, the right is the version you're merging, and the middle is the version you have accepted. This arrangement is intuitive to me. If you can make your form wide enough, you might consider three columns of forms, with one version on the left, the other on the right, and the user's accepted choices in the middle. That way you can always see the original and the new values, so depending on whether that's important you might consider this approach.


Color does not change for different chart datasets

Question: XYSeriesCollection dataset = new XYSeriesCollection();

XYSeries validKoordinates = new XYSeries("Not dangerous");
for (SimulationResult sr : validSR.values()) {
     validKoordinates.add(sr.getMinTTC(), sr.getMinTHW());  //x,y
}

dataset.addSeries(validKoordinates);
JFreeChart chart = chart = ChartFactory.createScatterPlot(
            "Distribution of THW and TTC Values",
            "TTC", "THW", dataset);

//Changes background color
XYPlot plot = (XYPlot) chart.getPlot();
plot.setBackgroundPaint(new Color(255, 228, 196));
plot.getRendererForDataset(plot.getDataset(0)).setSeriesPaint(0, Color.GRAY);

XYSeriesCollection dataset2 = new XYSeriesCollection();
XYSeries warningKoordinates = new XYSeries("Very critical");
for (SimulationResult sr : criticalSR.values()) {
    warningKoordinates.add(sr.getMinTTC(), sr.getMinTHW());  //x,y
}
dataset2.addSeries(warningKoordinates);

plot.setDataset(1, dataset2);
plot.getRendererForDataset(plot.getDataset(1)).setSeriesPaint(0, Color.RED);

So I have two different datasets (dataset 1 and dataset 2). Each dataset contains different values. My aim is to change the color of the dataset 1 to gray and the color of the second one to red. (BUT the shape should same the SAME). At the beginning I only had one dataset with 2 XYSeries. The problem at that time was that the shape was different for each XYSeries. Now I have the opposite problem. The shape stays but the color does not change.
This is what my table looks right now:

As you can see right now I cant seperate which one is very critical and whitch not.
Answer: It is found that only one dataSet is required, all series should be added to the dataSet. And using the first parameter of setSeriesPaint to configure color of the series. Since the version of jfreeChart is not provide, I used 1.0.12. The code is edited for testing.
public static void main(String[] args) throws IOException {
    XYSeriesCollection dataset = new XYSeriesCollection();

    int[][] sr = new int[3][2];
    for (int i = 0; i < sr.length; i++) {
        sr[i][0] = i + 3;
        sr[i][1] = 2 * (i + 1) + 1;
    }
    XYSeries validKoordinates = new XYSeries("Not dangerous");
    XYSeries warningKoordinates = new XYSeries("Very critical");
    System.out.println(sr.length);
    for (int i = 0; i < sr.length; i++) {
        validKoordinates.add(sr[i][0], sr[i][1]);
    }
    for (int i = 0; i < sr.length; i++) {
        warningKoordinates.add(sr[i][0]+1, sr[i][1]+1);
    }
    // Add dataset for all series
    dataset.addSeries(validKoordinates);
    dataset.addSeries(warningKoordinates);
    // Only reference one dataset
    JFreeChart chart = ChartFactory.createScatterPlot("Distribution of THW and TTC Values", "TTC", "THW", dataset,
            PlotOrientation.HORIZONTAL, true, true, true);
    XYPlot plot = (XYPlot) chart.getPlot();

    plot.setBackgroundPaint(new Color(255, 228, 196));
    // Change the index of setSeriesPaint to set color
    plot.getRendererForDataset(dataset).setSeriesPaint(0, Color.GRAY);
    plot.getRendererForDataset(dataset).setSeriesPaint(1, Color.RED);

    BufferedImage objBufferedImage = chart.createBufferedImage(600, 800);
    ByteArrayOutputStream bas = new ByteArrayOutputStream();
    try {
        ImageIO.write(objBufferedImage, "png", bas);
    } catch (IOException e) {
        e.printStackTrace();
    }

    byte[] byteArray = bas.toByteArray();
    InputStream in = new ByteArrayInputStream(byteArray);
    BufferedImage image = ImageIO.read(in);
    File outputfile = new File("testimage.png");
    ImageIO.write(image, "png", outputfile);
}

The image generated by the above method


Need to change the resolution options

Question: I've been trying to add my external monitor's native resolution (1680x1050). It does not show up on the GUI "Monitors"
I followed the "Adding Undetected Resolutions" section of
https://wiki.ubuntu.com/X/Config/Resolution
Here is what I got:
chris@chris-laptop:~$ cvt 1680 1050
# 1680x1050 59.95 Hz (CVT 1.76MA) hsync: 65.29 kHz; pclk: 146.25 MHz
Modeline "1680x1050_60.00"  146.25  1680 1784 1960 2240  1050 1053 1059 1089 -hsync     +vsync
chris@chris-laptop:~$ xrandr --newmode "1680x1050_60.00"  146.25  1680 1784 1960 2240      1050 1053 1059 1089 -hsync +vsync
chris@chris-laptop:~$ xrandr --addmode VGA-0 1680x1050
xrandr: cannot find mode "1680x1050"
chris@chris-laptop:~$ xrandr --addmode VGA-0 1680x1050
xrandr: cannot find mode "1680x1050"
chris@chris-laptop:~$ xrandr --addmode VGA-0 1680x1050_60.00
chris@chris-laptop:~$ xrandr
Screen 0: minimum 320 x 200, current 1024 x 768, maximum 4096 x 4096
VGA-0 connected 1024x768+0+0 (normal left inverted right x axis y axis) 0mm x 0mm
   1024x768       60.0*
   800x600        60.3     56.2
   848x480        60.0
   640x480        59.9
   1680x1050_60.00   60.0
LVDS connected (normal left inverted right x axis y axis)
   1280x800       60.0 +
   1280x720       59.9
   1152x768       59.8
   1024x768       59.9
   800x600        59.9

The example was as follows:
$ cvt 800 600
# 800x600 59.86 Hz (CVT 0.48M3) hsync: 37.35 kHz; pclk: 38.25 MHz
Modeline "800x600_60.00"   38.25  800 832 912 1024  600 603 607 624 -hsync +vsync
$ xrandr --newmode "800x600_60.00"   38.25  800 832 912 1024  600 603 607 624 -hsync +vsync
$ xrandr --addmode S-video 800x600

I tried to use exactly what they had (replacing 800x600 with 1680x1050), but it didn't recognize 1680x1050 as a mode. So I tried 1680x1050_60.00 which didn't give me an error message, but also didn't add it to xranr.
Comment: Have you looked for the monitors edid online? you need correct sync data as well as the resolution. These used to be available in the ini files which would come with monitor install 'driver' programs. Now I'm not sure where you'd find them. I wonder why the edid isn't detected properly anyway. If you can, report your Xorg log file in your question so we can see what's detected.
Comment: Actually, the new mode was added, it's the las one for VGA-0.
Answer: The following worked for me trying to get my Acer AL2223W to work with kubuntu 12.04 LTS dual monitor
In trying to execute:
xrandr --newmode "1680x1050_60.00"  146.25  1680 1784 1960 2240  1050 1053 1059 1089 -hsync +vsync

I got the following error:
X Error of failed request:  BadName (named color or font does not exist)
Major opcode of failed request:  150 (RANDR)
Minor opcode of failed request:  16 (RRCreateMode)
Serial number of failed request:  39
Current serial number in output stream:  39

So, I tried it after removing "_60.00" and received no error:
xrandr --newmode "1680x1050"  146.25  1680 1784 1960 2240  1050 1053 1059 1089 -hsync +vsync

Then adding with no error:
xrandr --addmode VGA1 1680x1050

And then was able to set my VGA1 output to 1680x1050 with no problem.
I hope this helps someone.
Answer: I had a similar problem -  Ubuntu not recognizing my second monitor higher resolutions. I solved it with a new VGA cable. I think there are two types 14 and 15 pins... Worth trying...

Need to change the resolution options


How can I find a replacement screw/bolt?

Question: I have a cast iron Christmas tree stand and I need to replace the screws/bolts. Where can I get them and/or how can I determine the thread so that I can check at a hardware store?
Comment: Your question is way to general to answer. Why not just take the stand to the hardware store and ask a clerk to help you find the right replacement?
Answer: Most hardware stores have thread to test if there the right thread.
So your better of taking the stand or bolts  to the hardware and test it on the threads
When you find the right thread the packets are marked with the size an thread of tho bolt.
If you can't find the right thread ask a worker there to help you.
Answer: You will also need the flat end pieces that go against the tree for the stand to be safe.  I have bolts but they wouldn't work just screwing the bolts against or even into the tree.  They need more surface area.
Comment: Hello, and welcome to Home Improvement. Thanks for the answer; keep 'em coming. And, you should probably [take our tour](//diy.stackexchange.com/tour) so you'll know how best to contribute here.


Hybris Spartacus after login via OpenID IAS cant reach from backend side current user

Question: We are using Hybris spartacus (3.0). We added app.module.ts following configuration for loggin sso via ias. When we open login page it redirects auto sso page we loggin and redirect to website. We can see Local Storage information idtoken userid. But we need backend side (occ side)current user information. When we call getCurrentUser method we cannot reach user which authenticate with openid. Do you have any comments for this ?
authentication: {
    client_id: environment.clientId, // this should be the client_id used in IAS
    client_secret: 'fakeClient', // The client secret is needed to fulfill the API contract for certain flows.
    //Never put here a real value as this is publicly available in the internet.
    baseUrl: environment.iasURL + '/oauth2', // The base URL defines, where to redirect.
    tokenEndpoint: '/token',
    loginUrl: '/authorize',
    logoutUrl: '/logout',
    OAuthLibConfig: {
      issuer: environment.iasURL,
      responseType: 'token',
      scope: 'openid',
      redirectUri: environment.baseUrl,
      customTokenParameters: ['token_type'],
      oidc: true,
    },
  },

image from local storage
Comment: I found some cdc code i try use this codes like this.authStorageService.setItem('access_token', token.access_token);  But when i send token which i get from ias side access token backend system send this error. INFO  [hybrisHTTP3] [HybrisOAuthTokenStore] Failed to find access token for token eyJzdWIiOiJFWF9LT0VHQ0VTIiwibWFpbCI6InNpbmFuLmtvZWdjZUBkb2VobGVyLmNvbSIsImlzcyI6Imh0dHBzOlwvXC9heDF2a2J3YTEuYWNjb3VudHMub25kZW1hbmQuY29tIiwibGFzdF9uYW1lIjoiS29lZ2NlIiwidHlwZSI6ImVtcGxveWVlIiwibm9uY2UiOiJjVE5rTFMxTFJWQTJWRmhCV21WQmJFaFBVVFpwZEhnMlZ6QlpXVlJMZEcxTlZ
Answer: When you get the redirect from the SSO you get the token (and maybe additional parameters) which you then should use for the auth/token call against Commerce. Here a implementation of org.springframework.security.oauth2.provider.token.AbstractTokenGranter (which you maybe need to implement?) should then take care of verifying this token etc. Make sure the grant_type maps to your TokenGranter.


What is the proper method to creating butcher block for a computer workstation?

Question: I've been looking into creating my own custom computer workstation and for the top I wanted to create butcher block but I am needing it pretty thick to be able to hold the weight of servers, monitors, and laptops I am working on.  I am using pipe underneath to support the top  so that will effect how thick the wood will be, such as this:

After several weeks of research I have seen a variety of methods used from:

Just glue
Pin Nailing and gluing
Pocket Jig

With all the weight of the hardware I dont want the wood to bow and I will be running supports in the center as such:

Image from this tutorial
So my questions are:

What wood should I use and how thick for a 36" x 84" table?
What is the best method to build the tops?

I did see some butcher block at IKEA but sadly I dont have an IKEA near me.
Answer: I honestly have to recommend that you buy the work bench top pre-built. You can buy these for about the same cost of the raw material itself. The ready built ones are beautiful, nicely sanded and sealed with rounded edges. Look for work bench tops at certain online business supply places. Tops can be found that are about 1.75 inches thick which are very sturdy. A typical top is 60x30 inches in size.

As I recall the IKEA ones are way thinner. Maybe 1.00 or at most 1.25 inches thick.
A web search will turn up many sources. One name to keep an eye out for would be ULINE.
Answer: If you're set on building your own butcher block top, first you're going to need some tools.  You most likely won't have most of these, but you might find a shop in your community that rents time, or try a local college, high school, etc.
You may or may not need all of these depending on the wood you're using.

Jointer
Thickness planer
Table saw
Radial arm saw (maybe, if you need to cross-cut raw lumber)
Clamps, lots and lots of clamps....
More clamps.  Did I mention you need a lot of clamps?
Sander - lots of options here.  Belt, palm, wooden block, etc.
Router (maybe, if you want to round or shape the edges of the wood)

As well, you'll need some wood, glue and lots of working space. You could build this out of many different types of wood but Maple and Cherry are common. As for thickness, somewhere between 1.5" and 2" thick.  1.75" is common.
Using each of the above tools is outside the scope of this question, but essentially you need to get your raw lumber cut down to rough size, jointed and thickness planed down to rough dimensions.  Then you'd rip strips on a table saw that will make up the blocks.
Once you have all the wood cut to dimensions, you'd arrange the wood and test fit it together.  After that, glue everything and clamp it together.  It might be easier to glue smaller sections first, and then glue all the smaller sections together to create the final top.  Once the glue sets, sand the top, route the edges and apply a finish.
Don't underestimate how long this will likely take!
Answer: You might be over-thinking the weight and strength issues.  You are going to be setting servers and monitors on this, not pounding them with sledge hammers.  One inch is thick enough to hold that without bowing, especially if you are adding extra supports.
Are you doing butcher block because of the perceived strength, or because you want to create a beautiful piece of furniture?  If it is for the beauty, go for it.  If it is just for the utilitarian strength of holding PC machines, don't bother.
If all you are concerned with is strength, just glue two pieces of plywood together. Any thickness from 1/2-inch to 3/4-inch will work; perhaps a nicer piece of 1/2-inch hardwood plywood on top of a 3/4-inch piece of anything.  That's going to be massive and strong; you could stand on it and jump up and down on it all day long and not hurt it or make it sag.
If you want to do the butcher block to create an awesome looking piece of furniture that could last for decades of pounding a meat cleaver into and still remain water-tight, then by all means do it.
The strength in butcher block comes from glueing the strips together.  Cut and plane your boards, glue them up, and clamp them to dry.  Glueing and clamping is the key.  Pin nailing is a convenient way of holding the pieces aligned while you assemble everything.  If you have a pin/brad nailer and want to avoid everything shifting around in assembly, use it.  Don't bother buying one just for this if you don't already have it (unless you've been looking for an excuse to buy one; they are fun).  The pins/brads certainly don't add any strength; that's all in the glue.
Butcher block is traditionally tall, narrow strips of wood.  I've seen the pocket screw approach to create large tables from wide flat boards, but I don't know if I'd call that butcher block.  I certainly would still always glue the edges of the boards together.
Whichever way you do it, you will still end up needing to plane it after all the glue dries, if you are looking for a smooth flat table-top.  Doesn't need to be a power planer; a hand plane works as well.
So, ask yourself about what your goal is.  You can certainly make a strong, fine-looking piece of furniture with the butcher block approach, if that's what you want.  If you just want the strength, look into plywood.
Answer: Personally, I would set the computers under the desk and only set monitors, keyboard(s), mice, printer, and other input devices (tablet, scanner) on the desk.
For a high quality and strong desktop easily obtained, check your local building supply stores for doors.


MS Access Query Syntax Error in FROM

Question: For an assignement I have to write SQL out to display Customer's Last name, order date, product ID, fabric of the product, quantity ordered, and unit price. This must be a 4-table join and must user INNERJOIN even if where can be used.
These are the tables involved.
Cus (CID, Last, First, Phone)
Orders (OrdID, OrdDate, ShipDate, CID)
Manu (ManuID, Name, Phone, City)
Prods (PrID, ManuID, Category)
ProdFabric (PrID, Fabric, Price)
Orderline (OrdId, PrID, Fabric, Qty)
Bold means it is a primary key or part of a composite key.
Here is the query I entered, but I keep getting a syntax error on FROM and it
keeps highlighting Orders (after Cus INNERJOIN) for some reason.
SELECT Last, OrdDate, Prods.PrID, Fabric, Qty, Price
FROM Cus INNERJOIN Orders INNERJOIN Orderline INNERJOIN ProdFabric
ON OrderLine.PrID=ProdFabric.PrID
AND ON Orderline.Fabric=ProdFrabric.Fabric
AND ON Cus.CID=Orders.CID
AND ON Orders.OrdID=Orderline.OrdID;

What causes this and how do I solve it?
Answer: AFAIK MS Access requires a Lisp-like proliferation of parentheses to support multiple joins.

Edit your MS Access queries in another editor that supports paren-matching and syntax-highlighting, e.g. Notepad++.
Use table aliases to keep your queries shorter and more manageable.

With the parentheses, your query will look something like this:
SELECT c.Last
       , o.OrdDate
       , pf.PrID
       , pf.Fabric
       , ol.Qty
       , pf.Price
FROM   ((Cus c
       INNER JOIN Orders o ON c.CID = o.CID)
       INNER JOIN Orderline ol ON o.OrdID = ol.OrdID)
       INNER JOIN ProdFabric pf ON ol.PrID = pf.PrID;

Comment: Thanks Adam. Got it working with the parenthesis. Although, when I add the table names before the field, it asks me to enter a parameter, so I left it out. Here's what I have finally, hope it's right.

SELECT Last, OrdDate, Orderline.PrID,Orderline.Fabric, Qty, Price
FROM ((Cus INNER JOIN Orders  ON Cus.CID=Orders.CID)
INNER JOIN Orderline  ON Orders.OrdID=Orderline.OrdID) INNER JOIN ProdFabric ON Orderline.Fabric=ProdFabric.Fabric AND OrderLine.Fabric=ProdFabric.Fabric;
Comment: Looks good, except I'm not sure why you join to ProdFabric on Fabric twice. Can you join to ProdFabric on PrID? If you really need to join on Fabric, join on PrID *and* Fabric like this: INNER JOIN ProdFabric ON Orderline.PrID = ProdFabric.PrID AND Orderline.Fabric = ProdFabric.Fabric;  Other than that you're good to go!
Answer: I don't think "AND ON" exists like you use it in your query.
You have to specify each join on its own.
SELECT ...
FROM cus INNER JOIN orders ON cus.cid = orders.cid
         INNER JOIN orderline ON orders.orderid = orderline.orderid
...

or you can also specify the join in your WHERE clause:
SELECT ...
FROM cus INNER JOIN orders
         INNER JOIN orderline
...
WHERE cus.cid = orders.cid
  AND orders.orderid = orderline.orderid
...

Also: INNER JOIN are 2 words ;-)
Comment: Of course... didn't see the more obvious error... INNER JOIN is not in one word... I updated the answer.
Comment: Now I am getting this error message:

Syntax error (missing operator) in query expression 'Cus.CID=Orders.CID INNER JOIN Orderline ON Orders.OrdID=Orderline.OrdID INNER JOIN ProdFabric ON Orderline.Fabric=ProdFabric.Fabric'.
Comment: Try to add the parentheses like Adam suggested, and otherwise try specifying the join in the where clause like my second example.

MS Access Query Syntax Error in FROM


Error: Index out of bounds - Python

Question: I am still fairly new to Python and I am attempting to run a for loop. However, I receive an error indicating that my index is out of bounds. I'm not sure what exactly the problem is, any help is appreciated!
My code and error are both below:
croot = 1
ctip = 1
span = 1
thetaroot = 0
thetatip = 0
a0root = 0.11
a0tip = 0.11
alpha = 0
alpha0root = -2.5
alpha0tip = -2.5
thetaroot = thetaroot * atan(1.) / 45.
thetatip = thetatip * atan(1.) / 45.
alpha = alpha * atan(1.) / 45.
alpha0root = alpha0root * atan(1.) / 45.
alpha0tip = alpha0tip * atan(1.) / 45.
n = 10
theta = zeros((1,n))
y = zeros((1,n))
c = zeros((1,n))
cl = zeros((1,n))
alp = zeros((1,n))
a = zeros((1,n))
rhs = zeros((n,1))
b = zeros((n,1))
a = zeros((n,1))
#
# Define properties at n span stations
#
pi = 4. * atan(1.)
for i in range(1,n):
    theta[i] = i * pi / (2. * n)
    y[i] = span * 0.5 * cos(theta[i])
    c[i] = croot + (ctip - croot) * y[i] * 2. / span
    alp[i] = alpha + thetaroot - (alpha0root + (alpha0tip - alpha0root + thetaroot - thetatip) * y[i] * 2. / span)
    a[i] = a0root + (a0tip - a0root) * y[i] * 2. / span

pi = 4. * atan(1)

I then receive the error
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-8-8710173d8f43> in <module>()
     29 pi = 4. * atan(1.)
     30 for i in range(1,n):
---> 31     theta[i] = i * pi / (2. * n)
     32     y[i] = span * 0.5 * cos(theta[i])
     33     c[i] = croot + (ctip - croot) * y[i] * 2. / span

IndexError: index 1 is out of bounds for axis 0 with size 1

Comment: As pointed out below - you should use range(0, n) (or just range(n), it's the same thing) because python is 0-indexed, not 1-indexed (like, say Octave). Looking at what you're doing though, it looks as though you could do this in a 'vectorized' way without using the loop at all.
Comment: I assume that you're using numpy?
Comment: Yes, numpy was imported.
Answer: As you have mentioned in the comments that you are using numpy.zeros here, the value of theta in your code will be
theta = array([0,0,0]) # If size of n is 3

If you wish to add elements to theta like
theta = array([0, 1, 2]), you have to do it like this:
theta[0][i] = i * pi / (2. * n)
And this goes with your variables y, c, alp, a as well. This will be the code:
croot = 1
ctip = 1
span = 1
thetaroot = 0
thetatip = 0
a0root = 0.11
a0tip = 0.11
alpha = 0
alpha0root = -2.5
alpha0tip = -2.5
thetaroot = thetaroot * atan(1.) / 45.
thetatip = thetatip * atan(1.) / 45.
alpha = alpha * atan(1.) / 45.
alpha0root = alpha0root * atan(1.) / 45.
alpha0tip = alpha0tip * atan(1.) / 45.
n = 10
theta = zeros((1,n))
y = zeros((1,n))
c = zeros((1,n))
cl = zeros((1,n))
alp = zeros((1,n))
a = zeros((1,n))
rhs = zeros((n,1))
b = zeros((n,1))
a = zeros((n,1)) # There are 2 definitions of a here which is not good
#
# Define properties at n span stations
#
pi = 4. * atan(1.)
for i in range(1,n):
    theta[0][i] = i * pi / (2. * n)
    y[0][i] = span * 0.5 * cos(theta[0][i])
    c[0][i] = croot + (ctip - croot) * y[i] * 2. / span
    alp[0][i] = alpha + thetaroot - (alpha0root + (alpha0tip - alpha0root + thetaroot - thetatip) * y[0][i] * 2. / span)
    a[i][0] = a0root + (a0tip - a0root) * y[0][i] * 2. / span
    #Or use a[0][i] if a is defined as a = zeros((1, n)), the first definition

pi = 4. * atan(1)

In case you wish to add elements like
theta = array([0,0,0], [1,1,1], [2,2,2])

Then modify the for loop as follows:
for i in range(1,n):
    theta += i * pi / (2. * n)
    y += span * 0.5 * cos(theta[i])
    c += croot + (ctip - croot) * y[i] * 2. / span
    alp += alpha + thetaroot - (alpha0root + (alpha0tip - alpha0root + thetaroot - thetatip) * y[i] * 2. / span)
    a += a0root + (a0tip - a0root) * y[i] * 2. / span

Comment: Your code fixes most of the lines, but I still get an error for line 35 where a[0][i] is called. Same error as before.
Comment: That's because I missed the later a which makes a to build zeros((n,1)). I will fix my answer. Thanks :-)
Answer: The problem is that zeros function of numpy generate a structure like [[0. 0. 0. 0. ...]]
So to access the first element you need to do theta[0][0].
Your loop need to be like :
for i in range(n):
    theta[0][i] = #your code

same thing for all your array generate by zeros().
zeros function return a multidimensional array.
Answer: When executing theta = zeros((1,n)) with n = 10 will return
array([[ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]])

Which is one list contains one list inside. The outter list contains only one element at index 0 and you cannot access it at index 1....n
To fix this, try this:
theta[0][i] = i * pi / (2. * n)

Error: Index out of bounds - Python